code stringlengths 3 10M | language stringclasses 31 values |
|---|---|
// Written in the D programming language.
/**
* Interface to C++ <exception>
*
* Copyright: Copyright (c) 2016 D Language Foundation
* License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: $(HTTP digitalmars.com, Walter Bright)
* Manu Evans
* Source: $(DRUNTIMESRC core/stdcpp/_exception.d)
*/
module core.stdcpp.exception;
import core.stdcpp.xutility : __cplusplus, CppStdRevision;
import core.attribute : weak;
version (CppRuntime_Gcc)
version = GenericBaseException;
version (CppRuntime_Clang)
version = GenericBaseException;
version (CppRuntime_Sun)
version = GenericBaseException;
extern (C++, "std"):
@nogc:
///
alias terminate_handler = void function() nothrow;
///
terminate_handler set_terminate(terminate_handler f) nothrow;
///
terminate_handler get_terminate() nothrow;
///
void terminate() nothrow;
static if (__cplusplus < CppStdRevision.cpp17)
{
///
alias unexpected_handler = void function();
///
deprecated unexpected_handler set_unexpected(unexpected_handler f) nothrow;
///
deprecated unexpected_handler get_unexpected() nothrow;
///
deprecated void unexpected();
}
static if (__cplusplus < CppStdRevision.cpp17)
{
///
bool uncaught_exception() nothrow;
}
else static if (__cplusplus == CppStdRevision.cpp17)
{
///
deprecated bool uncaught_exception() nothrow;
}
static if (__cplusplus >= CppStdRevision.cpp17)
{
///
int uncaught_exceptions() nothrow;
}
version (GenericBaseException)
{
///
class exception
{
@nogc:
///
extern(D) this() nothrow {}
///
@weak ~this() nothrow {} // HACK: this should extern, but then we have link errors!
///
@weak const(char)* what() const nothrow { return "unknown"; } // HACK: this should extern, but then we have link errors!
protected:
extern(D) this(const(char)*, int = 1) nothrow { this(); } // compat with MS derived classes
}
}
else version (CppRuntime_DigitalMars)
{
///
class exception
{
@nogc:
///
extern(D) this() nothrow {}
//virtual ~this();
void dtor() { } // reserve slot in vtbl[]
///
const(char)* what() const nothrow;
protected:
this(const(char)*, int = 1) nothrow { this(); } // compat with MS derived classes
}
}
else version (CppRuntime_Microsoft)
{
///
class exception
{
@nogc:
///
extern(D) this(const(char)* message = "unknown", int = 1) nothrow { msg = message; }
///
@weak ~this() nothrow {}
///
@weak const(char)* what() const nothrow { return msg != null ? msg : "unknown exception"; }
// TODO: do we want this? exceptions are classes... ref types.
// final ref exception opAssign(ref const(exception) e) nothrow { msg = e.msg; return this; }
protected:
@weak void _Doraise() const { assert(0); }
protected:
const(char)* msg;
}
}
else
static assert(0, "Missing std::exception binding for this platform");
///
class bad_exception : exception
{
@nogc:
///
extern(D) this(const(char)* message = "bad exception") nothrow { super(message); }
version (GenericBaseException)
{
///
@weak override const(char)* what() const nothrow { return "bad exception"; }
}
}
| D |
/Users/luoguochun/privt/proj/coding-blog/.demo/rust-lib/mini-redis/target/debug/deps/mio-7d2ff21466adf85d.rmeta: /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/lib.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/macros.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/interest.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/poll.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/token.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/waker.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/event.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/events.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/source.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/selector/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/selector/kqueue.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/sourcefd.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/waker.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/net.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/tcp.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/udp.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/socketaddr.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/datagram.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/listener.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/stream.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/pipe.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/io_source.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/listener.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/socket.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/stream.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/udp.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/datagram.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/listener.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/stream.rs
/Users/luoguochun/privt/proj/coding-blog/.demo/rust-lib/mini-redis/target/debug/deps/mio-7d2ff21466adf85d.d: /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/lib.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/macros.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/interest.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/poll.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/token.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/waker.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/event.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/events.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/source.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/selector/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/selector/kqueue.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/sourcefd.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/waker.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/net.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/tcp.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/udp.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/socketaddr.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/datagram.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/listener.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/stream.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/pipe.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/io_source.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/listener.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/socket.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/stream.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/udp.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/mod.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/datagram.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/listener.rs /Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/stream.rs
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/lib.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/macros.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/interest.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/poll.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/mod.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/token.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/waker.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/mod.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/event.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/events.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/event/source.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/mod.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/selector/mod.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/selector/kqueue.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/sourcefd.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/waker.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/net.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/tcp.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/udp.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/mod.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/socketaddr.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/datagram.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/listener.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/uds/stream.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/sys/unix/pipe.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/io_source.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/mod.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/mod.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/listener.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/socket.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/tcp/stream.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/udp.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/mod.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/datagram.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/listener.rs:
/Users/luoguochun/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/mio-0.7.6/src/net/uds/stream.rs:
| D |
module collie.codec.http.parser;
public import collie.codec.http.parsertype;
import collie.codec.http.config;
/** ubyte[] 为传过去字段里的位置引用,没有数据拷贝,自己使用的时候注意拷贝数据,
bool 此段数据是否完结,可能只是数据的一部分。
*/
alias CallBackData = void delegate(HTTPParser, ubyte[], bool);
alias CallBackNotify = void delegate(HTTPParser);
final class HTTPParser
{
this(HTTPParserType ty = HTTPParserType.HTTP_BOTH, uint maxHeaderSize = 1024)
{
rest(ty);
_maxHeaderSize = maxHeaderSize;
}
@property type()
{
return _type;
}
@property isUpgrade()
{
return upgrade;
}
@property contentLength()
{
return content_length;
}
@property isChunked()
{
return (flags & HTTPParserFlags.F_CHUNKED) == 0 ? false : true;
}
//@property status() {return status_code;}
@property error()
{
return http_errno;
}
@property errorString()
{
return error_string[http_errno];
}
@property methodCode()
{
return method;
}
@property methodString()
{
return method_strings[method];
}
@property major()
{
return http_major;
} //版本号首位
@property minor()
{
return http_minor;
} //版本号末尾
@property handleIng()
{
return _isHandle;
}
@property handleIng(bool handle)
{
_isHandle = handle;
}
@property skipBody()
{
return _skipBody;
}
@property skipBody(bool skip)
{
return _skipBody = skip;
}
/** 回调函数指定 */
@property onMessageBegin(CallBackNotify cback)
{
_on_message_begin = cback;
}
@property onMessageComplete(CallBackNotify cback)
{
_on_message_complete = cback;
}
@property onHeaderComplete(CallBackNotify cback)
{
_on_headers_complete = cback;
}
@property onChunkHeader(CallBackNotify cback)
{
_on_chunk_header = cback;
}
@property onChunkComplete(CallBackNotify cback)
{
_on_chunk_complete = cback;
}
@property onUrl(CallBackData cback)
{
_on_url = cback;
}
@property onStatus(CallBackData cback)
{
_on_status = cback;
}
@property onHeaderField(CallBackData cback)
{
_on_header_field = cback;
}
@property onHeaderValue(CallBackData cback)
{
_on_header_value = cback;
}
@property onBody(CallBackData cback)
{
_on_body = cback;
}
void rest(HTTPParserType ty)
{
type = ty;
state = (
type == HTTPParserType.HTTP_REQUEST ? HTTPParserState.s_start_req : (
type == HTTPParserType.HTTP_RESPONSE ? HTTPParserState.s_start_res
: HTTPParserState.s_start_req_or_res));
http_errno = HTTPParserErrno.HPE_OK;
flags = HTTPParserFlags.F_ZERO;
}
protected:
CallBackNotify _on_message_begin;
CallBackNotify _on_headers_complete;
CallBackNotify _on_message_complete;
CallBackNotify _on_chunk_header;
CallBackNotify _on_chunk_complete;
CallBackData _on_url;
CallBackData _on_status;
CallBackData _on_header_field;
CallBackData _on_header_value;
CallBackData _on_body;
public:
bool bodyIsFinal() {return state == HTTPParserState.s_message_done;}
ulong httpParserExecute(ubyte[] data)
{
handleIng = true;
scope(exit) handleIng = false;
ubyte c,ch;
byte unhex_val;
size_t header_field_mark = uint.max;
size_t header_value_mark = uint.max;
size_t url_mark = uint.max;
size_t body_mark = uint.max;
size_t status_mark = uint.max;
size_t maxP = cast(long)data.length ;
size_t p = 0;
if(http_errno != HTTPParserErrno.HPE_OK){
return 0;
}
if(data.length == 0){
switch (state) {
case HTTPParserState.s_body_identity_eof:
/* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if
* we got paused.
*/
mixin(
CALLBACK_NOTIFY_NOADVANCE("message_complete"));
return 0;
case HTTPParserState.s_dead:
case HTTPParserState.s_start_req_or_res:
case HTTPParserState.s_start_res:
case HTTPParserState.s_start_req:
return 0;
default:
//http_errno = HTTPParserErrno.HPE_INVALID_EOF_STATE);
http_errno = HTTPParserErrno.HPE_INVALID_EOF_STATE;
return 1;
}
}
if (state == HTTPParserState.s_header_field)
header_field_mark = 0;
if (state == HTTPParserState.s_header_value)
header_value_mark = 0;
switch (state)
{
case HTTPParserState.s_req_path:
case HTTPParserState.s_req_schema:
case HTTPParserState.s_req_schema_slash:
case HTTPParserState.s_req_schema_slash_slash:
case HTTPParserState.s_req_server_start:
case HTTPParserState.s_req_server:
case HTTPParserState.s_req_server_with_at:
case HTTPParserState.s_req_query_string_start:
case HTTPParserState.s_req_query_string:
case HTTPParserState.s_req_fragment_start:
case HTTPParserState.s_req_fragment:
url_mark = 0;
break;
case HTTPParserState.s_res_status:
status_mark = 0;
break;
default:
break;
}
for (; p < maxP; ++p)
{
ch = data[p];
if (state <= HTTPParserState.s_headers_done)
{
nread += 1;
if (nread > _maxHeaderSize)
{
http_errno = HTTPParserErrno.HPE_HEADER_OVERFLOW;
goto error;
}
}
reexecute:
switch (state)
{
case HTTPParserState.s_dead:
/* this state is used after a 'Connection: close' message
* the parser will error out if it reads another message
*/
if (ch == CR || ch == LF)
break;
http_errno = HTTPParserErrno.HPE_CLOSED_CONNECTION;
goto error;
case HTTPParserState.s_start_req_or_res:
{
if (ch == CR || ch == LF)
break;
flags = HTTPParserFlags.F_ZERO;
content_length = ulong.max;
if (ch == 'H')
{
state = HTTPParserState.s_res_or_resp_H;
mixin(CALLBACK_NOTIFY("message_begin")); // 开始处理
}
else
{
type = HTTPParserType.HTTP_REQUEST;
state = HTTPParserState.s_start_req;
goto reexecute;
}
break;
}
case HTTPParserState.s_res_or_resp_H:
if (ch == 'T')
{
type = HTTPParserType.HTTP_RESPONSE;
state = HTTPParserState.s_res_HT;
}
else
{
if (ch != 'E')
{
http_errno = HTTPParserErrno.HPE_INVALID_CONSTANT;
goto error;
}
type = HTTPParserType.HTTP_REQUEST;
method = HTTPMethod.HTTP_HEAD;
index = 2;
state = HTTPParserState.s_req_method;
}
break;
case HTTPParserState.s_start_res:
{
flags = HTTPParserFlags.F_ZERO;
content_length = ulong.max;
switch (ch)
{
case 'H':
state = HTTPParserState.s_res_H;
break;
case CR:
case LF:
break;
default:
http_errno = HTTPParserErrno.HPE_INVALID_CONSTANT;
goto error;
}
mixin(CALLBACK_NOTIFY("message_begin"));
break;
}
case HTTPParserState.s_res_H:
mixin(STRICT_CHECK("ch != 'T'"));
state = HTTPParserState.s_res_HT;
break;
case HTTPParserState.s_res_HT:
//STRICT_CHECK(ch != 'T');
mixin(STRICT_CHECK("ch != 'T'"));
state = HTTPParserState.s_res_HTT;
break;
case HTTPParserState.s_res_HTT:
//STRICT_CHECK(ch != 'P');
mixin(STRICT_CHECK("ch != 'P'"));
state = HTTPParserState.s_res_HTTP;
break;
case HTTPParserState.s_res_HTTP:
//STRICT_CHECK(ch != '/');
mixin(STRICT_CHECK("ch != '/'"));
state = HTTPParserState.s_res_first_http_major;
break;
case HTTPParserState.s_res_first_http_major:
if (ch < '0' || ch > '9')
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
http_major = cast(ushort)(ch - '0');
state = HTTPParserState.s_res_http_major;
break;
/* major HTTP version or dot */
case HTTPParserState.s_res_http_major:
{
if (ch == '.')
{
state = HTTPParserState.s_res_first_http_minor;
break;
}
if (!mixin(IS_NUM("ch")))
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
http_major *= 10;
http_major += ch - '0';
if (http_major > 999)
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
break;
}
/* first digit of minor HTTP version */
case HTTPParserState.s_res_first_http_minor:
if (!mixin(IS_NUM("ch")))
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
http_minor = cast(ushort)(ch - '0');
state = HTTPParserState.s_res_http_minor;
break;
/* minor HTTP version or end of request line */
case HTTPParserState.s_res_http_minor:
{
if (ch == ' ')
{
state = HTTPParserState.s_res_first_status_code;
break;
}
if (!mixin(IS_NUM("ch")))
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
http_minor *= 10;
http_minor += ch - '0';
if (http_minor > 999)
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
break;
}
case HTTPParserState.s_res_first_status_code:
{
if (!mixin(IS_NUM("ch")))
{
if (ch == ' ')
{
break;
}
http_errno = HTTPParserErrno.HPE_INVALID_STATUS;
goto error;
}
status_code = ch - '0';
state = HTTPParserState.s_res_status_code;
break;
}
case HTTPParserState.s_res_status_code:
{
if (!mixin(IS_NUM("ch")))
{
switch (ch)
{
case ' ':
state = HTTPParserState.s_res_status_start;
break;
case CR:
state = HTTPParserState.s_res_line_almost_done;
break;
case LF:
state = HTTPParserState.s_header_field_start;
break;
default:
http_errno = HTTPParserErrno.HPE_INVALID_STATUS;
goto error;
}
break;
}
status_code *= 10;
status_code += ch - '0';
if (status_code > 999)
{
http_errno = HTTPParserErrno.HPE_INVALID_STATUS;
goto error;
}
break;
}
case HTTPParserState.s_res_status_start:
{
if (ch == CR)
{
state = HTTPParserState.s_res_line_almost_done;
break;
}
if (ch == LF)
{
state = HTTPParserState.s_header_field_start;
break;
}
//MARK(status);
if (status_mark == uint.max)
{
status_mark = p;
}
state = HTTPParserState.s_res_status;
index = 0;
break;
}
case HTTPParserState.s_res_status:
if (ch == CR)
{
state = HTTPParserState.s_res_line_almost_done;
mixin(CALLBACK_DATA("status"));
break;
}
if (ch == LF)
{
state = HTTPParserState.s_header_field_start;
//statusCall();
mixin(CALLBACK_DATA("status"));
break;
}
break;
case HTTPParserState.s_res_line_almost_done:
mixin(STRICT_CHECK("ch != LF"));
state = HTTPParserState.s_header_field_start;
break;
case HTTPParserState.s_start_req:
{
if (ch == CR || ch == LF)
break;
flags = HTTPParserFlags.F_ZERO;
content_length = ulong.max;
if (!mixin(IS_ALPHA("ch")))
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
index = 1;
switch (ch)
{
case 'A':
method = HTTPMethod.HTTP_ACL;
break;
case 'B':
method = HTTPMethod.HTTP_BIND;
break;
case 'C':
method = HTTPMethod.HTTP_CONNECT; /* or COPY, CHECKOUT */ break;
case 'D':
method = HTTPMethod.HTTP_DELETE;
break;
case 'G':
method = HTTPMethod.HTTP_GET;
break;
case 'H':
method = HTTPMethod.HTTP_HEAD;
break;
case 'L':
method = HTTPMethod.HTTP_LOCK; /* or LINK */ break;
case 'M':
method = HTTPMethod.HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break;
case 'N':
method = HTTPMethod.HTTP_NOTIFY;
break;
case 'O':
method = HTTPMethod.HTTP_OPTIONS;
break;
case 'P':
method = HTTPMethod.HTTP_POST;
/* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */
break;
case 'R':
method = HTTPMethod.HTTP_REPORT; /* or REBIND */ break;
case 'S':
method = HTTPMethod.HTTP_SUBSCRIBE; /* or SEARCH */ break;
case 'T':
method = HTTPMethod.HTTP_TRACE;
break;
case 'U':
method = HTTPMethod.HTTP_UNLOCK; /* or UNSUBSCRIBE, UNBIND, UNLINK */ break;
default:
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
state = HTTPParserState.s_req_method;
mixin(CALLBACK_NOTIFY("message_begin"));
break;
}
case HTTPParserState.s_req_method:
{
if (ch == '\0')
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
string matcher = method_strings[method];
if (ch == ' ' && matcher.length == index)
{
state = HTTPParserState.s_req_spaces_before_url;
}
else if (ch == matcher[index])
{
//; /* nada */
}
else if (method == HTTPMethod.HTTP_CONNECT)
{
if (index == 1 && ch == 'H')
{
method = HTTPMethod.HTTP_CHECKOUT;
}
else if (index == 2 && ch == 'P')
{
method = HTTPMethod.HTTP_COPY;
}
else
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
}
else if (method == HTTPMethod.HTTP_MKCOL)
{
if (index == 1 && ch == 'O')
{
method = HTTPMethod.HTTP_MOVE;
}
else if (index == 1 && ch == 'E')
{
method = HTTPMethod.HTTP_MERGE;
}
else if (index == 1 && ch == '-')
{
method = HTTPMethod.HTTP_MSEARCH;
}
else if (index == 2 && ch == 'A')
{
method = HTTPMethod.HTTP_MKACTIVITY;
}
else if (index == 3 && ch == 'A')
{
method = HTTPMethod.HTTP_MKCALENDAR;
}
else
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
}
else if (method == HTTPMethod.HTTP_SUBSCRIBE)
{
if (index == 1 && ch == 'E')
{
method = HTTPMethod.HTTP_SEARCH;
}
else
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
}
else if (method == HTTPMethod.HTTP_REPORT)
{
if (index == 2 && ch == 'B')
{
//error("err0");
method = HTTPMethod.HTTP_REBIND;
}
else
{
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
}
else if (index == 1)
{
if (method == HTTPMethod.HTTP_POST)
{
if (ch == 'R')
{
method = HTTPMethod.HTTP_PROPFIND; /* or HTTP_PROPPATCH */
}
else if (ch == 'U')
{
method = HTTPMethod.HTTP_PUT; /* or HTTP_PURGE */
}
else if (ch == 'A')
{
method = HTTPMethod.HTTP_PATCH;
}
else
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
}
else if (method == HTTPMethod.HTTP_LOCK)
{
if (ch == 'I')
{
method = HTTPMethod.HTTP_LINK;
}
else
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
}
}
else if (index == 2)
{
if (method == HTTPMethod.HTTP_PUT)
{
if (ch == 'R')
{
method = HTTPMethod.HTTP_PURGE;
}
else
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
}
else if (method == HTTPMethod.HTTP_UNLOCK)
{
if (ch == 'S')
{
method = HTTPMethod.HTTP_UNSUBSCRIBE;
}
else if (ch == 'B')
{
method = HTTPMethod.HTTP_UNBIND;
}
else
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
}
else
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
}
else if (index == 4 && method == HTTPMethod.HTTP_PROPFIND && ch == 'P')
{
method = HTTPMethod.HTTP_PROPPATCH;
}
else if (index == 3 && method == HTTPMethod.HTTP_UNLOCK && ch == 'I')
{
method = HTTPMethod.HTTP_UNLINK;
}
else
{
//error("err0");
http_errno = HTTPParserErrno.HPE_INVALID_METHOD;
goto error;
}
++index;
break;
}
case HTTPParserState.s_req_spaces_before_url:
{
if (ch == ' ')
break;
//MARK(url);
if (url_mark == uint.max)
{
url_mark = p;
}
if (method == HTTPMethod.HTTP_CONNECT)
{
state = HTTPParserState.s_req_server_start;
}
state = parse_url_char(state, ch);
if (state == HTTPParserState.s_dead)
{
http_errno = HTTPParserErrno.HPE_INVALID_URL;
goto error;
}
break;
}
case HTTPParserState.s_req_schema:
case HTTPParserState.s_req_schema_slash:
case HTTPParserState.s_req_schema_slash_slash:
case HTTPParserState.s_req_server_start:
{
switch (ch)
{
/* No whitespace allowed here */
case ' ':
case CR:
case LF:
http_errno = HTTPParserErrno.HPE_INVALID_URL;
goto error;
default:
state = parse_url_char(state, ch);
if (state == HTTPParserState.s_dead)
{
http_errno = HTTPParserErrno.HPE_INVALID_URL;
goto error;
}
}
break;
}
case HTTPParserState.s_req_server:
case HTTPParserState.s_req_server_with_at:
case HTTPParserState.s_req_path:
case HTTPParserState.s_req_query_string_start:
case HTTPParserState.s_req_query_string:
case HTTPParserState.s_req_fragment_start:
case HTTPParserState.s_req_fragment:
{
switch (ch)
{
case ' ':
state = HTTPParserState.s_req_http_start;
mixin(CALLBACK_DATA("url"));
break;
case CR:
case LF:
http_major = 0;
http_minor = 9;
state = (ch == CR) ? HTTPParserState.s_req_line_almost_done
: HTTPParserState.s_header_field_start;
mixin(CALLBACK_DATA("url"));
break;
default:
state = parse_url_char(state, ch);
if (state == HTTPParserState.s_dead)
{
http_errno = HTTPParserErrno.HPE_INVALID_URL;
goto error;
}
}
break;
}
case HTTPParserState.s_req_http_start:
switch (ch)
{
case 'H':
state = HTTPParserState.s_req_http_H;
break;
case ' ':
break;
default:
http_errno = HTTPParserErrno.HPE_INVALID_CONSTANT;
goto error;
}
break;
case HTTPParserState.s_req_http_H:
mixin(STRICT_CHECK("ch != 'T'"));
state = HTTPParserState.s_req_http_HT;
break;
case HTTPParserState.s_req_http_HT:
//STRICT_CHECK(ch != 'T');
mixin(STRICT_CHECK("ch != 'T'"));
state = HTTPParserState.s_req_http_HTT;
break;
case HTTPParserState.s_req_http_HTT:
//STRICT_CHECK(ch != 'P');
mixin(STRICT_CHECK("ch != 'P'"));
state = HTTPParserState.s_req_http_HTTP;
break;
case HTTPParserState.s_req_http_HTTP:
//STRICT_CHECK(ch != '/');
mixin(STRICT_CHECK("ch != '/'"));
state = HTTPParserState.s_req_first_http_major;
break;
/* first digit of major HTTP version */
case HTTPParserState.s_req_first_http_major:
if (ch < '1' || ch > '9')
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
http_major = cast(ushort)(ch - '0');
state = HTTPParserState.s_req_http_major;
break;
/* major HTTP version or dot */
case HTTPParserState.s_req_http_major:
{
if (ch == '.')
{
state = HTTPParserState.s_req_first_http_minor;
break;
}
if (!mixin(IS_NUM("ch")))
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
http_major *= 10;
http_major += ch - '0';
if (http_major > 999)
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
break;
}
/* first digit of minor HTTP version */
case HTTPParserState.s_req_first_http_minor:
if (!mixin(IS_NUM("ch")))
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
http_minor = cast(ushort)(ch - '0');
state = HTTPParserState.s_req_http_minor;
break;
/* minor HTTP version or end of request line */
case HTTPParserState.s_req_http_minor:
{
if (ch == CR)
{
state = HTTPParserState.s_req_line_almost_done;
break;
}
if (ch == LF)
{
state = HTTPParserState.s_header_field_start;
break;
}
/* XXX allow spaces after digit? */
if (!mixin(IS_NUM("ch")))
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
http_minor *= 10;
http_minor += ch - '0';
if (http_minor > 999)
{
http_errno = HTTPParserErrno.HPE_INVALID_VERSION;
goto error;
}
break;
}
/* end of request line */
case HTTPParserState.s_req_line_almost_done:
{
if (ch != LF)
{
http_errno = HTTPParserErrno.HPE_LF_EXPECTED;
goto error;
}
state = HTTPParserState.s_header_field_start;
break;
}
case HTTPParserState.s_header_field_start:
{
if (ch == CR)
{
state = HTTPParserState.s_headers_almost_done;
break;
}
if (ch == LF)
{
/* they might be just sending \n instead of \r\n so this would be
* the second \n to denote the end of headers*/
state = HTTPParserState.s_headers_almost_done;
//goto reexecute;
goto reexecute;
}
c = tokens[ch];
if (!c)
{
http_errno = HTTPParserErrno.HPE_INVALID_HEADER_TOKEN;
goto error;
}
if (header_field_mark == uint.max)
{
header_field_mark = p;
}
index = 0;
state = HTTPParserState.s_header_field;
switch (c)
{
case 'c':
header_state = HTTPParserHeaderstates.h_C;
break;
case 'p':
header_state = HTTPParserHeaderstates.h_matching_proxy_connection;
break;
case 't':
header_state = HTTPParserHeaderstates.h_matching_transfer_encoding;
break;
case 'u':
header_state = HTTPParserHeaderstates.h_matching_upgrade;
break;
default:
header_state = HTTPParserHeaderstates.h_general;
break;
}
break;
}
case HTTPParserState.s_header_field:
{
const long start = p;
for (; p < maxP; p++)
{
ch = data[p];
c = tokens[ch];
if (!c)
break;
switch (header_state)
{
case HTTPParserHeaderstates.h_general:
break;
case HTTPParserHeaderstates.h_C:
index++;
header_state = (
c == 'o' ? HTTPParserHeaderstates.h_CO
: HTTPParserHeaderstates.h_general);
break;
case HTTPParserHeaderstates.h_CO:
index++;
header_state = (
c == 'n' ? HTTPParserHeaderstates.h_CON
: HTTPParserHeaderstates.h_general);
break;
case HTTPParserHeaderstates.h_CON:
index++;
switch (c)
{
case 'n':
header_state = HTTPParserHeaderstates.h_matching_connection;
break;
case 't':
header_state = HTTPParserHeaderstates.h_matching_content_length;
break;
default:
header_state = HTTPParserHeaderstates.h_general;
break;
}
break;
/* connection */
case HTTPParserHeaderstates.h_matching_connection:
index++;
if (index > CONNECTION.length || c != CONNECTION[index])
{
header_state = HTTPParserHeaderstates.h_general;
}
else if (index == CONNECTION.length - 1)
{
header_state = HTTPParserHeaderstates.h_connection;
}
break;
/* proxy-connection */
case HTTPParserHeaderstates.h_matching_proxy_connection:
index++;
if (index > PROXY_CONNECTION.length || c != PROXY_CONNECTION[index])
{
header_state = HTTPParserHeaderstates.h_general;
}
else if (index == PROXY_CONNECTION.length)
{
header_state = HTTPParserHeaderstates.h_connection;
}
break;
/* content-length */
case HTTPParserHeaderstates.h_matching_content_length:
index++;
if (index > CONTENT_LENGTH.length || c != CONTENT_LENGTH[index])
{
header_state = HTTPParserHeaderstates.h_general;
}
else if (index == CONTENT_LENGTH.length - 1)
{
if (flags & HTTPParserFlags.F_CONTENTLENGTH)
{
http_errno = HTTPParserErrno.HPE_UNEXPECTED_CONTENT_LENGTH;
goto error;
}
header_state = HTTPParserHeaderstates.h_content_length;
flags |= HTTPParserFlags.F_CONTENTLENGTH;
}
break;
/* transfer-encoding */
case HTTPParserHeaderstates.h_matching_transfer_encoding:
index++;
if (index > TRANSFER_ENCODING.length || c != TRANSFER_ENCODING[index])
{
header_state = HTTPParserHeaderstates.h_general;
}
else if (index == TRANSFER_ENCODING.length - 1)
{
header_state = HTTPParserHeaderstates.h_transfer_encoding;
}
break;
/* upgrade */
case HTTPParserHeaderstates.h_matching_upgrade:
index++;
if (index > UPGRADE.length || c != UPGRADE[index])
{
header_state = HTTPParserHeaderstates.h_general;
}
else if (index == UPGRADE.length - 1)
{
header_state = HTTPParserHeaderstates.h_upgrade;
}
break;
case HTTPParserHeaderstates.h_connection:
case HTTPParserHeaderstates.h_content_length:
case HTTPParserHeaderstates.h_transfer_encoding:
case HTTPParserHeaderstates.h_upgrade:
if (
ch != ' ')
header_state = HTTPParserHeaderstates.h_general;
break;
default:
assert(false, "Unknown header_state");
// break;
}
}
//COUNT_HEADER_SIZE(p - start);
nread += (p - start);
if (nread > _maxHeaderSize)
{
http_errno = HTTPParserErrno.HPE_HEADER_OVERFLOW;
goto error;
}
if (p == maxP)
{
--p;
break;
}
if (ch == ':')
{
state = HTTPParserState.s_header_value_discard_ws;
mixin(CALLBACK_DATA("header_field"));
break;
}
http_errno = HTTPParserErrno.HPE_INVALID_HEADER_TOKEN;
goto error;
}
case HTTPParserState.s_header_value_discard_ws:
if (ch == ' ' || ch == '\t')
break;
if (ch == CR)
{
state = HTTPParserState.s_header_value_discard_ws_almost_done;
break;
}
if (ch == LF)
{
state = HTTPParserState.s_header_value_discard_lws;
break;
}
goto case;
/* FALLTHROUGH */
case HTTPParserState.s_header_value_start:
{
//MARK(header_value);
if (header_value_mark == uint.max)
{
header_value_mark = p;
}
state = HTTPParserState.s_header_value;
index = 0;
c = ch | 0x20; //LOWER(ch);
switch (header_state)
{
case HTTPParserHeaderstates.h_upgrade:
flags |= HTTPParserFlags.F_UPGRADE;
header_state = HTTPParserHeaderstates.h_general;
break;
case HTTPParserHeaderstates.h_transfer_encoding:
/* looking for 'Transfer-Encoding: chunked' */
if ('c' == c)
{
header_state = HTTPParserHeaderstates
.h_matching_transfer_encoding_chunked;
}
else
{
header_state = HTTPParserHeaderstates.h_general;
}
break;
case HTTPParserHeaderstates.h_content_length:
if (!mixin(IS_NUM("ch")))
{
http_errno = HTTPParserErrno.HPE_INVALID_CONTENT_LENGTH;
goto error;
}
content_length = ch - '0';
break;
case HTTPParserHeaderstates.h_connection:
/* looking for 'Connection: keep-alive' */
if (c == 'k')
{
header_state = HTTPParserHeaderstates.h_matching_connection_keep_alive;
/* looking for 'Connection: close' */
}
else if (c == 'c')
{
header_state = HTTPParserHeaderstates.h_matching_connection_close;
}
else if (c == 'u')
{
header_state = HTTPParserHeaderstates.h_matching_connection_upgrade;
}
else
{
header_state = HTTPParserHeaderstates.h_matching_connection_token;
}
break;
/* Multi-value `Connection` header */
case HTTPParserHeaderstates.h_matching_connection_token_start:
break;
default:
header_state = HTTPParserHeaderstates.h_general;
break;
}
break;
}
case HTTPParserState.s_header_value: //BUG,找不到结束
{
const long start = p;
auto h_state = header_state;
for (; p < maxP; p++)
{
ch = data[p];
if (ch == CR)
{
state = HTTPParserState.s_header_almost_done;
header_state = h_state;
mixin(CALLBACK_DATA("header_value"));
break;
}
if (ch == LF)
{
state = HTTPParserState.s_header_almost_done;
//COUNT_HEADER_SIZE(p - start);
nread += (p - start);
if (nread > _maxHeaderSize)
{
http_errno = HTTPParserErrno.HPE_HEADER_OVERFLOW;
goto error;
}
header_state = h_state;
mixin(CALLBACK_DATA_NOADVANCE("header_value"));
goto reexecute;
}
if (!lenient_http_headers && !(ch == CR || ch == LF
|| ch == 9 || (ch > 31 && ch != 127)))
{
http_errno = HTTPParserErrno.HPE_INVALID_HEADER_TOKEN;
goto error;
}
c = ch | 0x20; //LOWER(ch);
switch (h_state)
{
case HTTPParserHeaderstates.h_general:
{
import std.string;
import core.stdc.string;
size_t limit = maxP - p;
limit = (
limit < _maxHeaderSize ? limit
: _maxHeaderSize); //MIN(limit, TTPConfig.instance.MaxHeaderSize);
string str = cast(string) data[p .. maxP];
auto p_cr = str.indexOf(CR); // memchr(p, CR, limit);
auto p_lf = str.indexOf(LF); // memchr(p, LF, limit);
++p_cr;
++p_lf;
if (p_cr > 0)
{
if (p_lf > 0 && p_cr >= p_lf)
p += p_lf;
else
p += p_cr;
}
else if (p_lf > 0)
{
p += p_lf;
}
else
{
p = maxP;
}
p -= 2;
break;
}
case HTTPParserHeaderstates.h_connection:
case HTTPParserHeaderstates.h_transfer_encoding:
assert(0,
"Shouldn't get here.");
//break;
case HTTPParserHeaderstates.h_content_length:
{
ulong t;
if (ch == ' ')
break;
if (!mixin(IS_NUM("ch")))
{
http_errno = HTTPParserErrno.HPE_INVALID_CONTENT_LENGTH;
header_state = h_state;
goto error;
}
t = content_length;
t *= 10;
t += ch - '0';
/* Overflow? Test against a conservative limit for simplicity. */
if ((ulong.max - 10) / 10 < content_length)
{
http_errno = HTTPParserErrno.HPE_INVALID_CONTENT_LENGTH;
header_state = h_state;
goto error;
}
content_length = t;
break;
}
/* Transfer-Encoding: chunked */
case HTTPParserHeaderstates.h_matching_transfer_encoding_chunked:
index++;
if (index > CHUNKED.length || c != CHUNKED[index])
{
h_state = HTTPParserHeaderstates.h_general;
}
else if (index == CHUNKED.length - 1)
{
h_state = HTTPParserHeaderstates.h_transfer_encoding_chunked;
}
break;
case HTTPParserHeaderstates.h_matching_connection_token_start:
/* looking for 'Connection: keep-alive' */
if (c == 'k')
{
h_state = HTTPParserHeaderstates.h_matching_connection_keep_alive;
/* looking for 'Connection: close' */
}
else if (c == 'c')
{
h_state = HTTPParserHeaderstates.h_matching_connection_close;
}
else if (c == 'u')
{
h_state = HTTPParserHeaderstates.h_matching_connection_upgrade;
}
else if (tokens[c])
{
h_state = HTTPParserHeaderstates.h_matching_connection_token;
}
else if (c == ' ' || c == '\t')
{
/* Skip lws */
}
else
{
h_state = HTTPParserHeaderstates.h_general;
}
break;
/* looking for 'Connection: keep-alive' */
case HTTPParserHeaderstates.h_matching_connection_keep_alive:
index++;
if (index > KEEP_ALIVE.length || c != KEEP_ALIVE[index])
{
h_state = HTTPParserHeaderstates.h_matching_connection_token;
}
else if (index == KEEP_ALIVE.length - 1)
{
h_state = HTTPParserHeaderstates.h_connection_keep_alive;
}
break;
/* looking for 'Connection: close' */
case HTTPParserHeaderstates.h_matching_connection_close:
index++;
if (index > CLOSE.length || c != CLOSE[index])
{
h_state = HTTPParserHeaderstates.h_matching_connection_token;
}
else if (index == CLOSE.length - 1)
{
h_state = HTTPParserHeaderstates.h_connection_close;
}
break;
/* looking for 'Connection: upgrade' */
case HTTPParserHeaderstates.h_matching_connection_upgrade:
index++;
if (index > UPGRADE.length || c != UPGRADE[index])
{
h_state = HTTPParserHeaderstates.h_matching_connection_token;
}
else if (index == UPGRADE.length - 1)
{
h_state = HTTPParserHeaderstates.h_connection_upgrade;
}
break;
case HTTPParserHeaderstates.h_matching_connection_token:
if (ch == ',')
{
h_state = HTTPParserHeaderstates.h_matching_connection_token_start;
index = 0;
}
break;
case HTTPParserHeaderstates.h_transfer_encoding_chunked:
if (
ch != ' ')
h_state = HTTPParserHeaderstates.h_general;
break;
case HTTPParserHeaderstates.h_connection_keep_alive:
case HTTPParserHeaderstates.h_connection_close:
case HTTPParserHeaderstates.h_connection_upgrade:
if (ch == ',')
{
if (h_state == HTTPParserHeaderstates.h_connection_keep_alive)
{
flags |= HTTPParserFlags.F_CONNECTION_KEEP_ALIVE;
}
else if (h_state == HTTPParserHeaderstates.h_connection_close)
{
flags |= HTTPParserFlags.F_CONNECTION_CLOSE;
}
else if (h_state == HTTPParserHeaderstates.h_connection_upgrade)
{
flags |= HTTPParserFlags.F_CONNECTION_UPGRADE;
}
h_state = HTTPParserHeaderstates.h_matching_connection_token_start;
index = 0;
}
else if (ch != ' ')
{
h_state = HTTPParserHeaderstates.h_matching_connection_token;
}
break;
default:
state = HTTPParserState.s_header_value;
h_state = HTTPParserHeaderstates.h_general;
break;
}
}
header_state = h_state;
//COUNT_HEADER_SIZE(p - start);
nread += (p - start);
if (nread > _maxHeaderSize)
{
http_errno = HTTPParserErrno.HPE_HEADER_OVERFLOW;
goto error;
}
if (p == maxP)
--p;
break;
}
case HTTPParserState.s_header_almost_done:
{
if (ch != LF)
{
http_errno = HTTPParserErrno.HPE_LF_EXPECTED;
goto error;
}
state = HTTPParserState.s_header_value_lws;
break;
}
case HTTPParserState.s_header_value_lws:
{
if (ch == ' ' || ch == '\t')
{
state = HTTPParserState.s_header_value_start;
goto reexecute;
}
/* finished the header */
switch (header_state)
{
case HTTPParserHeaderstates.h_connection_keep_alive:
flags |= HTTPParserFlags.F_CONNECTION_KEEP_ALIVE;
break;
case HTTPParserHeaderstates.h_connection_close:
flags
|= HTTPParserFlags.F_CONNECTION_CLOSE;
break;
case HTTPParserHeaderstates.h_transfer_encoding_chunked:
flags |= HTTPParserFlags.F_CHUNKED;
break;
case HTTPParserHeaderstates.h_connection_upgrade:
flags
|= HTTPParserFlags.F_CONNECTION_UPGRADE;
break;
default:
break;
}
state = HTTPParserState.s_header_field_start;
goto reexecute;
}
case HTTPParserState.s_header_value_discard_ws_almost_done:
{
mixin(STRICT_CHECK("ch != LF"));
state = HTTPParserState.s_header_value_discard_lws;
break;
}
case HTTPParserState.s_header_value_discard_lws:
{
if (ch == ' ' || ch == '\t')
{
state = HTTPParserState.s_header_value_discard_ws;
break;
}
else
{
switch (header_state)
{
case HTTPParserHeaderstates.h_connection_keep_alive:
flags |= HTTPParserFlags.F_CONNECTION_KEEP_ALIVE;
break;
case HTTPParserHeaderstates.h_connection_close:
flags
|= HTTPParserFlags.F_CONNECTION_CLOSE;
break;
case HTTPParserHeaderstates.h_connection_upgrade:
flags |= HTTPParserFlags.F_CONNECTION_UPGRADE;
break;
case HTTPParserHeaderstates.h_transfer_encoding_chunked:
flags |= HTTPParserFlags.F_CHUNKED;
break;
default:
break;
}
/* header value was empty */
//MARK(header_value);
if (header_value_mark == uint.max)
{
header_value_mark = p;
}
state = HTTPParserState.s_header_field_start;
mixin(CALLBACK_DATA_NOADVANCE("header_value"));
goto reexecute;
}
}
//TODO
case HTTPParserState.s_headers_almost_done:
{
mixin(STRICT_CHECK("ch != LF"));
if (flags & HTTPParserFlags.F_TRAILING)
{
/* End of a chunked request */
state = HTTPParserState.s_message_done;
mixin(CALLBACK_NOTIFY_NOADVANCE("chunk_complete"));
goto reexecute;
}
/* Cannot use chunked encoding and a content-length header together
per the HTTP specification. */
if ((flags & HTTPParserFlags.F_CHUNKED)
&& (flags & HTTPParserFlags.F_CONTENTLENGTH))
{
http_errno = HTTPParserErrno.HPE_UNEXPECTED_CONTENT_LENGTH;
goto error;
}
state = HTTPParserState.s_headers_done;
/* Set this here so that on_headers_complete() callbacks can see it */
upgrade = (
(flags & (HTTPParserFlags.F_UPGRADE | HTTPParserFlags.F_CONNECTION_UPGRADE)) == (
HTTPParserFlags.F_UPGRADE | HTTPParserFlags.F_CONNECTION_UPGRADE)
|| method == HTTPMethod.HTTP_CONNECT);
{
if (_on_headers_complete != null)
{
_on_headers_complete(this);
//error("_on_headers_complete " , errorString);
//error("handleIng " , handleIng);
//error("handleIng " , skipBody);
//error("state " , state);
if (!handleIng)
{
http_errno = HTTPParserErrno.HPE_CB_headers_complete;
return p; /* Error */
}
if (skipBody)
flags |= HTTPParserFlags.F_SKIPBODY;
}
}
goto reexecute;
}
case HTTPParserState.s_headers_done:
{
int hasBody;
mixin(STRICT_CHECK("ch != LF"));
nread = 0;
//int chunked = flags & HTTPParserFlags.F_CHUNKED ;
//error("s_headers_done is chunked : ", chunked);
hasBody = flags & HTTPParserFlags.F_CHUNKED
|| (content_length > 0 && content_length != ULLONG_MAX);
if (upgrade && (method == HTTPMethod.HTTP_CONNECT
|| (flags & HTTPParserFlags.F_SKIPBODY) || !hasBody))
{
/* Exit, the rest of the message is in a different protocol. */
state = mixin(NEW_MESSAGE);
mixin(CALLBACK_NOTIFY("message_complete"));
return (p + 1);
}
if (flags & HTTPParserFlags.F_SKIPBODY)
{
state = mixin(NEW_MESSAGE);
mixin(CALLBACK_NOTIFY("message_complete"));
}
else if (flags & HTTPParserFlags.F_CHUNKED)
{
/* chunked encoding - ignore Content-Length header */
state = HTTPParserState.s_chunk_size_start;
}
else
{
if (content_length == 0)
{
/* Content-Length header given but zero: Content-Length: 0\r\n */
state = mixin(NEW_MESSAGE);
mixin(CALLBACK_NOTIFY("message_complete"));
}
else if (content_length != ULLONG_MAX)
{
/* Content-Length header given and non-zero */
state = HTTPParserState.s_body_identity;
}
else
{
if (!http_message_needs_eof())
{
/* Assume content-length 0 - read the next */
state = mixin(NEW_MESSAGE);
mixin(CALLBACK_NOTIFY("message_complete"));
}
else
{
/* Read body until EOF */
state = HTTPParserState.s_body_identity_eof;
}
}
}
break;
}
case HTTPParserState.s_body_identity:
{
ulong to_read = content_length < cast(ulong)(maxP - p) ? content_length : cast(
ulong)(maxP - p);
assert(content_length != 0 && content_length != ULLONG_MAX);
/* The difference between advancing content_length and p is because
* the latter will automaticaly advance on the next loop iteration.
* Further, if content_length ends up at 0, we want to see the last
* byte again for our message complete callback.
*/
//MARK(body);
if (body_mark == uint.max)
{
body_mark = p;
}
content_length -= to_read;
p += to_read - 1;
if (content_length == 0)
{
state = HTTPParserState.s_message_done;
/* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte.
*
* The alternative to doing this is to wait for the next byte to
* trigger the data callback, just as in every other case. The
* problem with this is that this makes it difficult for the test
* harness to distinguish between complete-on-EOF and
* complete-on-length. It's not clear that this distinction is
* important for applications, but let's keep it for now.
*/
if (body_mark != uint.max && _on_body != null)
{
ubyte[] _data = data[body_mark .. p + 1];
_on_body(this, _data, true);
if (!handleIng)
{
http_errno = HTTPParserErrno.HPE_CB_body;
return p + 1;
}
}
body_mark = uint.max;
goto reexecute;
}
break;
}
/* read until EOF */
case HTTPParserState.s_body_identity_eof:
//MARK(body);
if (body_mark == uint.max)
{
body_mark = p;
}
p = maxP - 1;
break;
case HTTPParserState.s_message_done:
state = mixin(NEW_MESSAGE);
mixin(CALLBACK_NOTIFY("message_complete"));
if (upgrade)
{
/* Exit, the rest of the message is in a different protocol. */
return (p + 1);
}
break;
case HTTPParserState.s_chunk_size_start:
{
assert(nread == 1);
assert(flags & HTTPParserFlags.F_CHUNKED);
unhex_val = unhex[ch];
if (unhex_val == -1)
{
http_errno = HTTPParserErrno.HPE_INVALID_CHUNK_SIZE;
goto error;
}
content_length = unhex_val;
state = HTTPParserState.s_chunk_size;
break;
}
case HTTPParserState.s_chunk_size:
{
ulong t;
assert(flags & HTTPParserFlags.F_CHUNKED);
if (ch == CR)
{
state = HTTPParserState.s_chunk_size_almost_done;
break;
}
unhex_val = unhex[ch];
if (unhex_val == -1)
{
if (ch == ';' || ch == ' ')
{
state = HTTPParserState.s_chunk_parameters;
break;
}
http_errno = HTTPParserErrno.HPE_INVALID_CHUNK_SIZE;
goto error;
}
t = content_length;
t *= 16;
t += unhex_val;
/* Overflow? Test against a conservative limit for simplicity. */
if ((ULLONG_MAX - 16) / 16 < content_length)
{
http_errno = HTTPParserErrno.HPE_INVALID_CONTENT_LENGTH;
goto error;
}
content_length = t;
break;
}
case HTTPParserState.s_chunk_parameters:
{
assert(flags & HTTPParserFlags.F_CHUNKED);
/* just ignore this shit. TODO check for overflow */
if (ch == CR)
{
state = HTTPParserState.s_chunk_size_almost_done;
break;
}
break;
}
case HTTPParserState.s_chunk_size_almost_done:
{
assert(flags & HTTPParserFlags.F_CHUNKED);
mixin(STRICT_CHECK("ch != LF"));
nread = 0;
if (content_length == 0)
{
flags |= HTTPParserFlags.F_TRAILING;
state = HTTPParserState.s_header_field_start;
}
else
{
state = HTTPParserState.s_chunk_data;
}
mixin(CALLBACK_NOTIFY("chunk_header"));
break;
}
case HTTPParserState.s_chunk_data:
{
ulong to_read = content_length < cast(ulong)(maxP - p) ? content_length : cast(
ulong)(maxP - p);
assert(flags & HTTPParserFlags.F_CHUNKED);
assert(content_length != 0 && content_length != ULLONG_MAX);
/* See the explanation in s_body_identity for why the content
* length and data pointers are managed this way.
*/
//MARK(body);
if (body_mark == uint.max)
{
body_mark = p;
}
content_length -= to_read;
p += to_read - 1;
if (content_length == 0)
{
state = HTTPParserState.s_chunk_data_almost_done;
}
break;
}
case HTTPParserState.s_chunk_data_almost_done:
assert(flags & HTTPParserFlags.F_CHUNKED);
assert(content_length == 0);
mixin(STRICT_CHECK("ch != CR"));
state = HTTPParserState.s_chunk_data_done;
mixin(CALLBACK_DATA("body"));
break;
case HTTPParserState.s_chunk_data_done:
assert(flags & HTTPParserFlags.F_CHUNKED);
mixin(STRICT_CHECK("ch != LF"));
nread = 0;
state = HTTPParserState.s_chunk_size_start;
mixin(CALLBACK_NOTIFY("chunk_complete"));
break;
default:
//assert(0 && "unhandled state");
http_errno = HTTPParserErrno.HPE_INVALID_INTERNAL_STATE;
goto error;
}
}
assert(
(
(header_field_mark != uint.max ? 1 : 0) + (header_value_mark != uint.max ? 1 : 0) + (
url_mark != uint.max ? 1 : 0) + (body_mark != uint.max ? 1 : 0) + (
status_mark != uint.max ? 1 : 0)) <= 1);
mixin(CALLBACK_DATA_NOADVANCE("header_field")); //最后没找到
mixin(CALLBACK_DATA_NOADVANCE("header_value"));
mixin(CALLBACK_DATA_NOADVANCE("url"));
mixin(CALLBACK_DATA_NOADVANCE("body"));
mixin(CALLBACK_DATA_NOADVANCE("status"));
return data.length;
error:
if (http_errno == HTTPParserErrno.HPE_OK)
{
http_errno = HTTPParserErrno.HPE_UNKNOWN;
}
return p;
}
private:
HTTPParserType _type = HTTPParserType.HTTP_BOTH;
HTTPParserFlags flags = HTTPParserFlags.F_ZERO;
HTTPParserState state;
HTTPParserHeaderstates header_state;
uint index;
uint lenient_http_headers;
uint nread;
ulong content_length;
ushort http_major;
ushort http_minor;
uint status_code; /* responses only */
HTTPMethod method; /* requests only */
HTTPParserErrno http_errno = HTTPParserErrno.HPE_OK;
/* 1 = Upgrade header was present and the parser has exited because of that.
* 0 = No upgrade header present.
* Should be checked when http_parser_execute() returns in addition to
* error checking.
*/
bool upgrade;
bool _isHandle = false;
bool _skipBody = false;
uint _maxHeaderSize = 1024;
protected:
@property type(HTTPParserType ty)
{
_type = ty;
}
bool http_message_needs_eof()
{
if (type == HTTPParserType.HTTP_REQUEST)
{
return false;
}
/* See RFC 2616 section 4.4 */
if (status_code / 100 == 1 || /* 1xx e.g. Continue */
status_code == 204 || /* No Content */
status_code == 304
|| /* Not Modified */
flags & HTTPParserFlags.F_SKIPBODY)
{ /* response to a HEAD request */
return false;
}
if ((flags & HTTPParserFlags.F_CHUNKED) || content_length != ULLONG_MAX)
{
return false;
}
return true;
}
bool http_should_keep_alive()
{
if (http_major > 0 && http_minor > 0)
{
/* HTTP/1.1 */
if (flags & HTTPParserFlags.F_CONNECTION_CLOSE)
{
return false;
}
}
else
{
/* HTTP/1.0 or earlier */
if (!(flags & HTTPParserFlags.F_CONNECTION_KEEP_ALIVE))
{
return false;
}
}
return !http_message_needs_eof();
}
HTTPParserState parse_url_char(HTTPParserState s, ubyte ch)
{
if (ch == ' ' || ch == '\r' || ch == '\n')
{
return HTTPParserState.s_dead;
}
version (HTTP_PARSER_STRICT)
{
if (ch == '\t' || ch == '\f')
{
return s_dead;
}
}
switch (s)
{
case HTTPParserState.s_req_spaces_before_url:
/* Proxied requests are followed by scheme of an absolute URI (alpha).
* All methods except CONNECT are followed by '/' or '*'.
*/
if (ch == '/' || ch == '*')
{
return HTTPParserState.s_req_path;
}
if (mixin(IS_ALPHA("ch")))
{
return HTTPParserState.s_req_schema;
}
break;
case HTTPParserState.s_req_schema:
if (mixin(IS_ALPHA("ch")))
{
return s;
}
if (ch == ':')
{
return HTTPParserState.s_req_schema_slash;
}
break;
case HTTPParserState.s_req_schema_slash:
if (ch == '/')
{
return HTTPParserState.s_req_schema_slash_slash;
}
break;
case HTTPParserState.s_req_schema_slash_slash:
if (ch == '/')
{
return HTTPParserState.s_req_server_start;
}
break;
case HTTPParserState.s_req_server_with_at:
if (ch == '@')
{
return HTTPParserState.s_dead;
}
goto case;
/* FALLTHROUGH */
case HTTPParserState.s_req_server_start:
case HTTPParserState.s_req_server:
{
if (ch == '/')
{
return HTTPParserState.s_req_path;
}
if (ch == '?')
{
return HTTPParserState.s_req_query_string_start;
}
if (ch == '@')
{
return HTTPParserState.s_req_server_with_at;
}
if ( /*mixin(IS_USERINFO_CHAR("ch"))*/ IS_USERINFO_CHAR2(ch) || ch == '['
|| ch == ']')
{
return HTTPParserState.s_req_server;
}
}
break;
case HTTPParserState.s_req_path:
{
if (mixin(IS_URL_CHAR("ch")))
{
return s;
}
switch (ch)
{
case '?':
return HTTPParserState.s_req_query_string_start;
case '#':
return HTTPParserState.s_req_fragment_start;
default:
break;
}
break;
}
case HTTPParserState.s_req_query_string_start:
case HTTPParserState.s_req_query_string:
{
if (mixin(IS_URL_CHAR("ch")))
{
return HTTPParserState.s_req_query_string;
}
switch (ch)
{
case '?':
/* allow extra '?' in query string */
return HTTPParserState.s_req_query_string;
case '#':
return HTTPParserState.s_req_fragment_start;
default:
break;
}
break;
}
case HTTPParserState.s_req_fragment_start:
{
if (mixin(IS_URL_CHAR("ch")))
{
return HTTPParserState.s_req_fragment;
}
switch (ch)
{
case '?':
return HTTPParserState.s_req_fragment;
case '#':
return s;
default:
break;
}
break;
}
case HTTPParserState.s_req_fragment:
{
if (mixin(IS_URL_CHAR("ch")))
{
return s;
}
switch (ch)
{
case '?':
case '#':
return s;
default:
break;
}
break;
}
default:
break;
}
/* We should never fall out of the switch above unless there's an error */
return HTTPParserState.s_dead;
}
}
private:
string IS_USERINFO_CHAR(string c)
{
return "( " ~ IS_ALPHA(c) ~ " || " ~ IS_NUM(c) ~ " || " ~ c ~ " == '%' || " ~ c ~ " == ';' || " ~ c ~ " == ':' || " ~ c ~ " == '&' || " ~ c ~ " == '=' || " ~ c ~ " == '+' || " ~ c ~ " == '$' || " ~ c ~ " == ','" ~ c ~ " == '-' || '_' == " ~ c ~ "|| '.' == " ~ c ~ "|| '!' == " ~ c ~ "|| '~' == " ~ c ~ "|| '*' == " ~ c ~ "|| '\'' == " ~ c ~ "|| '(' == " ~ c ~ "|| ')' == " ~ c ~ ")";
}
bool IS_USERINFO_CHAR2(ubyte c)
{
bool alpha = mixin(IS_ALPHA("c"));
bool sum = mixin(IS_NUM("c"));
bool b1 = (c == '%' || c == ';' || c == ':' || c == '&' || c == '='
|| c == '+' || c == '$' || c == ',');
bool b2 = (c == '-' || '_' == c || '.' == c || '!' == c || '~' == c || '*' == c
|| '\'' == c || '(' == c || ')' == c);
return (b2 || b1 || sum || alpha);
}
string STRICT_CHECK(string cond)
{
string code = "if (";
code = code ~ cond ~ ") {
http_errno = HTTPParserErrno.HPE_STRICT;
goto error;
} ";
return code;
}
// string IS_MARK(string c) { return "(" ~ c ~ " == '-' || " ~ c ~ " == '_' || "~ c ~ " == '.' || " ~ c ~ " == '!' || " ~ c ~ " == '~' || " ~ c ~ " == '*' || " ~ c ~ " == '\'' || " ~ c ~ " == '(' || " ~ c ~ " == ')')";}
string IS_NUM(string c)
{
return "(" ~ c ~ " >= '0' && " ~ c ~ " <= '9')";
}
string IS_ALPHA(string c)
{
return "((" ~ c ~ "| 0x20) >= 'a' && (" ~ c ~ " | 0x20) <= 'z')";
}
/* bool BIT_AT(ubyte[32] a, ubyte i) {
return (!!(cast(uint) (a[cast(uint) (i) >> 3] )&
(1 << (cast(uint)i & 7))));}
bool IS_URL_CHAR(ubyte c) {return (BIT_AT(normal_url_char, c));} */
string IS_URL_CHAR(string c)
{
return "(!!(cast(uint) (normal_url_char[cast(uint) (" ~ c ~ ") >> 3] ) &
(1 << (cast(uint)" ~ c ~ " & 7))))";
}
enum NEW_MESSAGE = "http_should_keep_alive() ? (type == HTTPParserType.HTTP_REQUEST ? HTTPParserState.s_start_req : HTTPParserState.s_start_res) : HTTPParserState.s_dead";
string CALLBACK_NOTIFY(string code)
{
string _s = " {if (_on_" ~ code ~ " != null){
_on_" ~ code ~ "(this); if(!handleIng){
http_errno = HTTPParserErrno.HPE_CB_" ~ code ~ ";
return p + 1;}} }";
return _s;
}
string CALLBACK_NOTIFY_NOADVANCE(string code)
{
string _s = " {if (_on_" ~ code ~ " != null){
_on_" ~ code ~ "(this); if(!handleIng){
http_errno = HTTPParserErrno.HPE_CB_" ~ code ~ ";
return p;} }}";
return _s;
}
string CALLBACK_DATA(string code)
{
string _s = "{ if(" ~ code ~ "_mark != uint.max && _on_" ~ code ~ " != null){
ulong len = (p - " ~ code ~ "_mark) ;
if(len > 0) {
/* writeln(\"CALLBACK_DATA at \",__LINE__, \" " ~ code ~ "\");*/
ubyte[] _data = data[" ~ code ~ "_mark..p];
_on_" ~ code ~ "(this,_data,true);
if (!handleIng){
http_errno = HTTPParserErrno.HPE_CB_" ~ code ~ ";
return p + 1;}} }" ~ code ~ "_mark = uint.max;}";
return _s;
}
string CALLBACK_DATA_NOADVANCE(string code)
{
string _s = "{ if(" ~ code ~ "_mark != uint.max && _on_" ~ code ~ " != null){
ulong len = (p - " ~ code ~ "_mark) ;
if(len > 0) {
/*writeln(\"CALLBACK_DATA_NOADVANCE at \",__LINE__, \" " ~ code ~ "\");*/
ubyte[] _data = data[" ~ code ~ "_mark..p];
_on_" ~ code ~ "(this,_data,false);
if (!handleIng){
http_errno = HTTPParserErrno.HPE_CB_" ~ code ~ ";
return p;} }}" ~ code ~ "_mark = uint.max;}";
return _s;
}
unittest
{
import std.stdio;
import std.functional;
writeln("\n\n\n");
void on_message_begin(HTTPParser)
{
writeln("_on_message_begin");
writeln(" ");
}
void on_url(HTTPParser par, ubyte[] data, bool adv)
{
writeln("_on_url, is NOADVANCE = ", adv);
writeln("\" ", cast(string) data, " \"");
writeln("HTTPMethod is = ", par.methodString);
writeln(" ");
}
void on_status(HTTPParser par, ubyte[] data, bool adv)
{
writeln("_on_status, is NOADVANCE = ", adv);
writeln("\" ", cast(string) data, " \"");
writeln(" ");
}
void on_header_field(HTTPParser par, ubyte[] data, bool adv)
{
static bool frist = true;
writeln("_on_header_field, is NOADVANCE = ", adv);
writeln("len = ", data.length);
writeln("\" ", cast(string) data, " \"");
if (frist)
{
writeln("\t http_major", par.major);
writeln("\t http_minor", par.minor);
frist = false;
}
writeln(" ");
}
void on_header_value(HTTPParser par, ubyte[] data, bool adv)
{
writeln("_on_header_value, is NOADVANCE = ", adv);
writeln("\" ", cast(string) data, " \"");
writeln(" ");
}
void on_headers_complete(HTTPParser par)
{
writeln("_on_headers_complete");
writeln(" ");
}
void on_body(HTTPParser par, ubyte[] data, bool adv)
{
writeln("_on_body, is NOADVANCE = ", adv);
writeln("\" ", cast(string) data, " \"");
writeln(" ");
}
void on_message_complete(HTTPParser par)
{
writeln("_on_message_complete");
writeln(" ");
}
void on_chunk_header(HTTPParser par)
{
writeln("_on_chunk_header");
writeln(" ");
}
void on_chunk_complete(HTTPParser par)
{
writeln("_on_chunk_complete");
writeln(" ");
}
string data = "GET /test HTTP/1.1\r\nUser-Agent: curl/7.18.0 (i486-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1\r\nHost:0.0.0.0=5000\r\nAccept: */*\r\n\r\n";
HTTPParser par = new HTTPParser();
par.onMessageBegin = toDelegate(&on_message_begin);
par.onMessageComplete = toDelegate(&on_message_complete);
par.onUrl = toDelegate(&on_url);
par.onStatus = toDelegate(&on_status);
par.onHeaderField = toDelegate(&on_header_field);
par.onHeaderValue = toDelegate(&on_header_value);
par.onChunkHeader = toDelegate(&on_chunk_header);
par.onChunkComplete = toDelegate(&on_chunk_complete);
par.onBody = toDelegate(&on_body);
ulong len = par.httpParserExecute(cast(ubyte[]) data);
if (data.length != len)
{
writeln("\t error ! ", par.error);
}
par.rest(HTTPParserType.HTTP_BOTH);
data = "POST /post_chunked_all_your_base HTTP/1.1\r\nHost:0.0.0.0=5000\r\nTransfer-Encoding:chunked\r\n\r\n5\r\nhello\r\n";
auto data2 = "0\r\n\r\n";
len = par.httpParserExecute(cast(ubyte[]) data);
if (data.length != len)
{
writeln("error1 ! ", par.error);
writeln("\t error1 ! ", par.errorString);
return;
}
writeln("data 1 is over!");
len = par.httpParserExecute(cast(ubyte[]) data2);
writeln("last len = ", len);
if (data2.length != len)
{
writeln("\t error ! ", par.errorString);
writeln("HTTPMethod is = ", par.methodString);
writeln("erro!!!!!");
}
}
| D |
in a humorous manner
| D |
.tr @@
.BG
.FN xgobi
.TL
XGobi: Dynamic Graphics for Data Analysis
.DN
Dynamic graphics, including brushing, rotation, grand tour, projection
pursuit, slicing. Most effectively used when called more than once on same
data, which then allows linked plots. Brushing with several glyphs and
colors is supported. (On monochrome displays, only glyphs can be used.)
.CS
xgobi(matrx,
collab=NULL, rowlab=NULL,
colors=NULL, glyphs=NULL, erase=NULL,
lines=NULL, linecolors=NULL,
resources=NULL, title=NULL,
vgroups=NULL, std="mmx",
nlinkable=0, subset=NULL,
display=NULL)
.RA
.AG matrx
Any numeric matrix or data.frame.
.OA
.AG collab
Optional character vector of column labels; the default is
`dimnames(matrx)[[2]]'. If no default exists, xgobi constructs its own
defaults.
.AG rowlab
Optional character vector of row labels; the default is
`dimnames(matrx)[[1]]'. If no default exists, xgobi constructs its own
defaults.
.AG colors
Optional character vector, used to supply initial point colors to be used;
the default is that all points are the same color.
.AG glyphs
Optional integer vector, used to supply glyphs to be used on
startup; the default is that all points are drawn with the same glyph.
.AG erase
Optional integer vector of length equal to the number of rows in the
data and composed of 1s and 0s. A 1 in position i specifies that
point i should be erased. The default is a vector of 0s.
.AG lines
Optional integer matrix, n by 2, which specifies by row number
pairs of points to be connected by line segments. The default
connecting line matrix connects each point to the one that follows
it in the data; that is, (1 2), (2 3), (3 4), ..., (n-1, n).
.AG linecolors
Optional integer vector, of length n where n is the number of
lines specified by the 'lines' argument. It is used to supply
line colors to be used on startup; the default is for all the
lines to be drawn in the standard foreground color.
.AG resources
Optional character vector created by clicking on the "Save
Resources" button in XGobi (if this XGobi was initiated during
an S session).
.AG title
Optional character string which defines the `-title' argument used by
X. The default is the name of the current matrix matrx. See documentation
for xgobi, or for X.
.AG vgroups
Optional integer vector, used to assign columns to groups for
transformation and axis scaling. This vector must contain one integer
for each variable. Columns to be grouped together should share the
same integer. Default is the vector 1:(ncol(matrx)).
.AG std
Optional string; which standardization of view to use. Default is
`"mmx"', minimum-maximum scaling, in which the view is centered at the
midpoint of the data, and all the data fits inside the plotting
window. Alternatives are `"msd"', in which the plot is centered at the
mean of the data, or `"mmd"' in which the plot is centered at the median.
In those two cases, the view is standardized using the largest distance.
.AG dev
Optional numeric scalar; the number of standard deviations (if `"msd"'
is chosen) or median absolute deviations (if `"mmd"' is chosen) that will
be plotted inside the plotting window. Default is 2.
.AG nlinkable
Optional integer scalar, the number of rows to be used in linking
of brushing and identification;
the default is for all rows to be used. This feature can be used
to link ordinary scatterplots with plots that have some decorations
requiring additional points, such as clustering trees.
.AG subset
Optional integer scalar, the number of rows to be included in the
initial display. That is, all data will be read in, but an
initial random sample will be drawn for display. Use the Subset
panel on the Tools Menu to select a new subset during the session.
.AG display
Optional character string, identifying the monitor on which to display
the xgobi window. The default is `"machine:0.0"' where `machine' is the
name of the user's workstation. See documentation for xgobi or for X.
.RT
The UNIX `status' upon completion, i.e. `0' if ok.
.SE
The xgobi S function executes a call to the C program of the same name,
an interactive statistical graphics program which runs under the X
Window System, and returns control of the S shell to the user.
.PP
XGobi can be used to create vectors of brushing information and rotation
coefficients; see the documentation for XGobi for details.
.SH REFERENCE
http://www.research.att.com/areas/stat/xgobi/
http://www.public.iastate.edu/~dicook/
.SH CONTACT
D. F. Swayne dfs@research.att.com
.EX
xgobi(x)
xgobi(cbind(x,y,z), name="laser")
xgobi(x, collabels, rowlabels, subset=5000)
.KW dynamic, interactive, graphics, plotting, rotation, grand tour, identify
.WR
| D |
#include "../hdr/GLcommand.h"
#include "lcode_tst.h"
#define WIND0 0
#define WIND1 1
int nObjects = 1;
int objList[1] = { 1 };
float targXlist[1] = { 50.0 };
float targYlist[1] = { 0.0 };
int orientations[1] = { 0 };
float spatialFrequencies[1] = { 1.0 };
float temporalFrequencies[1] = { 1.0 };
int counterPhases[1] = { 0 };
float redContrasts[1] = { 50.0 };
float greenContrasts[1] = { 50.0 };
float blueContrasts[1] = { 50.0 };
int patchSizes[1] = { 100 };
int fixon = OBJ_ON;
int offList[1] = { OBJ_OFF };
int onList[1] = { OBJ_ON };
int fixoff = OBJ_OFF;
int cntrPhase = 0;
int ptchDiameter = 100;
int nCycles = 0;
int orntn;
int stim_X = 50;
int stim_Y = 0;
int spatFreq = 10;
int tempFreq = 10;
int redCntrst = 50;
int greenCntrst = 50;
int blueCntrst = 50.0;
int setStimuli(){
int code = 0;
targXlist[0] = (float)stim_X;
targYlist[0] = (float)stim_Y;
orientations[0] = orntn;
spatialFrequencies[0] = (float)spatFreq / 10.0;
temporalFrequencies[0] = (float)tempFreq/ 10.0;
counterPhases[0] = cntrPhase;
redContrasts[0] = (float)redCntrst;
greenContrasts[0] = (float)greenCntrst;
blueContrasts[0] = (float)blueCntrst;
patchSizes[0] = ptchDiameter;
return(code);
}
void rinitf()
{
char *vexHost = "lsr-jwmvex";
pcsConnectVex(vexHost);
wd_src_pos(WIND0, WD_DIRPOS, 0, WD_DIRPOS, 0);
wd_src_pos(WIND1, WD_DIRPOS, 0, WD_DIRPOS, 0);
wd_src_check(WIND0, WD_SIGNAL, 0, WD_SIGNAL, 1);
wd_src_check(WIND1, WD_SIGNAL, 2, WD_SIGNAL, 3);
wd_cntrl(WIND0, WD_ON);
wd_cntrl(WIND1, WD_ON);
}
int wndxctr = 0;
int wndyctr = 0;
int wndsiz = 5;
int cnt_wnd()
{
int code = 0;
wd_pos(WIND0, wndxctr, wndyctr);
wd_disp(D_W_EYE_X);
wd_siz(WIND0, wndsiz, wndsiz);
wd_cntrl(WIND0, WD_ON);
return(code);
}
VLIST state_vars_vl[] = {
{"stimLoc_X", &stim_X, NP, NP, 0, ME_DEC}, // 0 0
{"stimLoc_Y", &stim_Y, NP, NP, 0, ME_DEC}, // 0 35
{"grating_orientation", &orntn, NP, NP, 0, ME_DEC}, // 0 70
{"spatial_frequency", &spatFreq, NP, NP, 0, ME_DEC}, // 0 105
{"temporal_frequency", &tempFreq, NP, NP, 0, ME_DEC}, // 0 140
{"counterphase", &cntrPhase, NP, NP, 0, ME_DEC}, // 0 175
{"red_contrast", &redCntrst, NP, NP, 0, ME_DEC}, // 0 210
{"green_contrast", &greenCntrst, NP, NP, 0, ME_DEC}, // 0 245
{"blue_contrast", &blueCntrst, NP, NP, 0, ME_DEC}, // 0 280
{"patch_diameter", &ptchDiameter, NP, NP, 0, ME_DEC}, // 0 315
{"drift_cycles", &nCycles, NP, NP, 0, ME_DEC}, // 0 350
NS
};
MENU umenus[] = {
{"state_vars", &state_vars_vl, NP, NP, 0, NP, hm_null}, // 457, 3, 150, 398, 1
NS,
};
USER_FUNC ufuncs[] = { // EMPTY
{""},
};
RTVAR rtvars[] = { // EMPTY
{""},
};
%%
id 100
restart rinitf
main_set {
status ON
begin first:
to disable
disable:
to enable on -PSTOP & softswitch
enable:
code 1001
to setStim
setStim:
do setStimuli()
to targLoc
targLoc:
do PvexStimLocation(&nObjects, objList, targXlist, targYlist)
to setGrating on 0 % tst_rx_new
setGrating:
do PvexDrawSineGrating(&nObjects, objList, orientations, spatialFrequencies, temporalFrequencies, counterPhases, redContrasts, greenContrasts, blueContrasts, patchSizes)
to winset on 0 % tst_rx_new
winset:
do cnt_wnd()
to openwin
fponcmd:
do PvexSwitchFix(&fixon)
to fpon on 0 % tst_rx_new
fpon:
code FPONCD
time 1000
to stmoncmd
stmoncmd:
do PvexSwitchStim(&nObjects, objList, onList)
to stimon on 0 % tst_rx_new
stimon:
code STIMCD
time 1000
to chooseDrift
chooseDrift:
to startDrift on 0 = nCycles
to timeDrift on 0 < nCycles
startDrift:
do PvexStartSine(&nObjects, objList)
to driftRunning on 0 % tst_rx_new
driftRunning:
code 2000
time 1000
to stopDrift
stopDrift:
do PvexStopSine()
to driftOff on 0 % tst_rx_new
driftOff:
time 1000
to stmoffcmd
stmoffcmd:
do PvexSwitchStim(&nObjects, objList, offList)
to stimoff on 0 % tst_rx_new
openwin:
do awind(OPEN_W)
to fponcmd
stimoff:
code 1101
time 1000
to fpoffcmd
fpoffcmd:
do PvexSwitchFix(&fixoff)
to closeWin on 0 % tst_rx_new
closeWin:
code FPOFFCD
do awind(CLOSE_W)
time 500
to first
timeDrift:
do PvexTimeGrating(&nObjects, objList, &nCycles)
to timingDrift on 0 % tst_rx_new
timingDrift:
code 3000
to driftOff on 0 % tst_rx_new
}
| D |
/*******************************************************************************
copyright: Copyright (c) 2005 Kris Bell. все rights reserved
license: BSD стиль: $(LICENSE)
version: Nov 2005: Initial release
author: Kris
*******************************************************************************/
module text.convert.Sprint;
private import text.convert.Layout;
/******************************************************************************
Конструирует вывод в стиле sprintf. Является заменой
семейству функций vsprintf(),вывод записывается в отдельный буфер:
---
// создать экземпляр Sprint
auto sprint = new Sprint!(сим);
// записать форматированный вывод в логгер
лог.инфо (sprint ("{} green bottles, sitting on a wall\n", 10));
---
Sprint удобен, когда требуется форматировать вывод для Логгера
или в подобной ситуации, т.к. при преобразовании используется
не куча, а буфер преобразования фиксированного размера.
Это важно при отладке, так как из-за использования кучи могут
изменяться поведенческие моменты. Экземпляр Sprint можно создать
заблаговременно, и использовать его в связке с пакетом логгинга.
Please note that the class itself is stateful, и therefore a
single экземпляр is not shareable across multИПle threads. The
returned контент is not .dup'd either, so do that yourself if
you require a persistent копируй.
Note also that Sprint is templated, и can be instantiated for
wide симвы through a Sprint!(дим) or Sprint!(шим). The wide
versions differ in that Всё the вывод и the форматируй-ткст
are of the мишень тип. Variadic текст аргументы are transcoded
appropriately.
See also: text.convert.Layout
******************************************************************************/
class Sprint(T)
{
protected T[] буфер;
Выкладка!(T) выкладка;
alias форматируй opCall;
/**********************************************************************
Созд new Sprint экземпляры with a буфер of the specified
размер
Deprecated - use Стдвыв.выкладка.sprint() instead
**********************************************************************/
deprecated this (цел размер = 256)
{
this (размер, Выкладка!(T).экземпляр);
}
/**********************************************************************
Созд new Sprint экземпляры with a буфер of the specified
размер, и the provопрed форматёр. The секунда аргумент can be
использован в_ apply cultural specifics (I18N) в_ Sprint
**********************************************************************/
this (цел размер, Выкладка!(T) форматёр)
{
буфер = new T[размер];
this.выкладка = форматёр;
}
/**********************************************************************
Выкладка a установи of аргументы
**********************************************************************/
T[] форматируй (T[] фмт, ...)
{
return выкладка.vprint (буфер, фмт, _arguments, _argptr);
}
/**********************************************************************
Выкладка a установи of аргументы
**********************************************************************/
T[] форматируй (T[] фмт, ИнфОТипе[] аргументы, АргСписок argptr)
{
return выкладка.vprint (буфер, фмт, аргументы, argptr);
}
}
| D |
module android.java.android.security.KeyPairGeneratorSpec;
public import android.java.android.security.KeyPairGeneratorSpec_d_interface;
import arsd.jni : ImportExportImpl;
mixin ImportExportImpl!KeyPairGeneratorSpec;
import import4 = android.java.java.util.Date;
import import2 = android.java.javax.security.auth.x500.X500Principal;
import import5 = android.java.java.lang.Class;
import import1 = android.java.java.security.spec.AlgorithmParameterSpec;
import import3 = android.java.java.math.BigInteger;
import import0 = android.java.android.content.Context;
| D |
/*
* This file is part of gtkD.
*
* gtkD is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* gtkD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with gtkD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
module utils.HTODConvert;
private import utils.DefReader;
private import utils.GtkWrapper;
private import std.io;
private import std.file;
import std.path;
private import std.string;
private import std.process;
static char[] htod_location = "wrap/utils/htod.exe";
static char[] wine_command = "wine";
//debug = flow;
//debug = processLine;
//debug = getDType;
//debug = functions;
public class Ranges
{
private struct Range
{
int vStart;
int vEnd;
bool exclude = true;
public bool contains(int pos)
{
return (pos>= vStart) && (pos<=vEnd);
}
public bool includes(int pos)
{
return contains(pos)
? !exclude
: exclude
;
}
public bool matches(int start, int end)
{
return vStart == start
&& vEnd == end;
}
}
private Range*[] ranges;
public void addRange(int start, int end, bool exclude)
{
Range* range = new Range;
range.vStart = start;
range.vEnd = end;
range.exclude = exclude;
ranges ~= range;
}
/**
* Finds the last range that contains the position and returns it's include value
* Params:
* pos =
*/
public void include(int pos)
{
bool incl = true;
Range* range;
int i=ranges.length;
while ( i > 0 )
{
range = ranges[--i];
if ( range.contains(pos) )
{
i=0;
incl = !range.exclude;
}
}
//return incl;
}
}
/**
* This is used to post-process dm htod .d file for gtkD
* to create the htod .d file:
* - copy the original .h file to a working directory
* - remove all unecessary definitions
* - run `wine ~/dm/bin/htod.exe <file.h>`
* - run this on the generated .d file
*/
public class HTODConvert
{
char[] dText;
DefReader defReader;
/** the library id on the system (for instance GL for libGL.so) */
char[] lib;
/** the .h (or .h pos-processed) to convert to .d */
char[] preFile;
/** the package */
char[] pack;
char[] bindDir;
char[] outputRoot;
char[] inputRoot;
/** convert to dynamic loading */
bool dynLoad;
/** mark when the header was already added to the text */
bool dynLoadAlreadyOpen;
/** mar when the module and license where already added to the text */
bool headerAlreadyAdded;
char[][] functions;
char[][] comment;
this(char[] htodFilename)
{
defReader = new DefReader(htodFilename);
clearValues();
process();
}
this(char[] htodFilename, char[] _outputRoot, char[] _inputRoot)
{
inputRoot = _inputRoot;
outputRoot = _outputRoot;
this(htodFilename);
}
void process()
{
debug(flow)(writefln("HTODConvert.process 1"));
while ( defReader.next().length > 0 )
{
switch ( defReader.getKey() )
{
case "prefile":
debug(flow)(writefln("HTODConvert.process case prefile"));
preFile = defReader.getValue();
break;
case "bindDir":
bindDir = defReader.getValue();
break;
case "pack":
debug(flow)(writefln("HTODConvert.process case pack"));
pack = defReader.getValue();
break;
case "lib":
debug(flow)(writefln("HTODConvert.process case libe"));
lib = defReader.getValue();
break;
case "file":
debug(flow)(writefln("HTODConvert.process case file 1"));
if ( preFile.length > 0 )
{
debug(flow)(writefln("HTODConvert.process case file 2"));
processPreFile(preFile, defReader.getValue());
debug(flow)(writefln("HTODConvert.process case file 3"));
}
debug(flow)(writefln("HTODConvert.process case file 4"));
preFile.length = 0;
debug(flow)(writefln("HTODConvert.process case file 5"));
processFile(defReader.getValue());
debug(flow)(writefln("HTODConvert.process case file 6 "));
break;
case "dynload":
debug(flow)(writefln("HTODConvert.process case dynload"));
dynLoadAlreadyOpen = false;
headerAlreadyAdded = false;
dynLoad = true;
break;
case "outfile":
debug(flow)(writefln("HTODConvert.process case outfile"));
writeFile(defReader.getValue());
clearValues();
break;
default:
debug(flow)(writefln("HTODConvert.process case default"));
writefln("Unknown key/value = %s/%s", defReader.getKey(), defReader.getValue());
break;
}
}
}
void processPreFile(char[] preFileName, char[] fileName)
{
//debug(flow)
writefln("HTODConvert.processPreFile files: %s > %s", preFileName, fileName);
char[][] args;
args ~= htod_location;
args ~= htod_location;
args ~= preFileName;
args ~= std.path.join(inputRoot,fileName);
try
{
std.process.execvp(wine_command, args);
}
catch ( Object e)
{
// ignore - it always fail - most of the time produces the file
}
}
void processFile(char[] fileName)
{
debug(flow)(writefln("HTODConvert.processFile"));
char[] hText = cast(char[])std.file.read(fileName);
char[][] hLines = std.string.splitlines(hText);
char[] line;
int i = 0;
while ( i < hLines.length )
{
line = hLines[i++];
if ( std.string.find(line,'(')>=0 )
{
int openBrace = 1;
if ( std.string.find(line,')')>=0 ) --openBrace;
while ( openBrace > 0
&& i<hLines.length
)
{
char[] l = hLines[i++];
if ( std.string.find(l,')') >=0) --openBrace;
line ~= " " ~ std.string.strip(l);
}
}
addLine(dText, line);
}
if ( dynLoad )
{
closeDynLoad(dText);
}
}
void addLine(inout char[] dText, char[] line)
{
if ( !startsWith(line, "//C")
&& line !="alias extern GLAPI;"
&& line !="alias GLAPIENTRY APIENTRY;"
)
{
if ( line == "alias sbyte GLbyte;" )
{
line = "alias byte GLbyte;";
}
if ( line == "module wrap/cHeaders/GL/gl;" )
{
line = "module "~bindDir~".gl;";
}
if ( line == "module wrap/cHeaders/GL/glu;" )
{
line = "module "~bindDir~".glu;";
}
if ( line == "import std.c.gl;" )
{
line = "import "~bindDir~".gl;";
}
if ( startsWith(line, "/* Converted to D from" ) )
{
line = GtkWrapper.license;
}
if ( dynLoad )
{
addLineDynLoad(dText, line);
}
else
{
dText ~= line~"\n";
}
}
}
/**
* If the line is a function definition stores the line to include on the extern(C)
* and the symbols.
* for now a function is a line that ends with ");"
* Params:
* dText =
* line =
*/
void addLineDynLoad(inout char[] dText, char[] line)
{
//debug(flow)(writefln("HTODConvert.addLineDynLoad"));
if ( headerAlreadyAdded
&& !dynLoadAlreadyOpen
)
{
openDynLoad(dText);
}
if ( endsWith(line, ");") )
{
int i=0;
while ( i<comment.length )
{
functions ~= comment[i++];
}
comment.length = 0;
functions ~= line;
debug(functions)writefln("HTODConvert.addLineDynLoad function[%s] = %s",
functions.length, line);
}
else if ( startsWith(line, "/*")
|| startsWith(line, " *")
|| startsWith(line, " */")
|| line.length == 0
)
{
comment ~= line;
}
else
{
if ( startsWith(line, "module") )
{
headerAlreadyAdded = true;
}
int i=0;
while ( i<comment.length )
{
dText ~= comment[i++]~"\n";
}
comment.length = 0;
dText ~= line~"\n";
}
}
void openDynLoad(inout char[] dText)
{
debug(flow)(writefln("HTODConvert.openDynLoad"));
dynLoadAlreadyOpen = true;
dText ~=
"\n"
"\n"
"private import std.io;\n"
"private import "~bindDir~"."~pack~"types;\n"
"private import gtkD.gtkc.Loader;\n"
"private import gtkD.gtkc.paths;\n"
"\n"
;
if ( lib == "GL"
|| lib == "GLU" )
{
return;
}
dText ~=
"private Linker "~lib~"_Linker;\n"
"\n"
"static this()\n"
"{\n"
" "~lib~"_Linker = new Linker(libPath ~ importLibs[LIBRARY."~std.string.toupper(lib)~"] );\n"
" "~lib~"_Linker.link("~lib~"Links);\n"
" debug writefln(\"* Finished static this(): "~lib~"\");\n"
"}\n"
"\n"
"static ~this()\n"
"{\n"
" delete "~lib~"_Linker;\n"
" debug writefln(\"* Finished static ~this(): "~lib~"\");\n"
"}\n\n"
;
}
void closeDynLoad(inout char[] dText)
{
debug(flow)(writefln("HTODConvert.closeDynLoad"));
dText ~= "\n\nextern(C)\n{\n";
foreach ( char[] line ; functions )
{
dText ~= "\t" ~ line ~"\n";
}
dText ~= "} // extern(C)\n";
dText ~= "\n\nSymbol[] "~lib~"Links = \n";
dText ~= "[\n";
foreach ( char[] line ; functions )
{
if ( startsWith(line, "/*")
|| startsWith(line, " *")
|| startsWith(line, " */")
|| line.length == 0
)
{
dText ~= "\t"~line~"\n";
}
else
{
int end = std.string.find(line,'(');
if ( end > 0 )
{
int start = end;
while ( start > 0 && line[start] > ' ' )
{
--start;
}
char[] functionName = line[start+1..end];
if ( functionName.length>1)
{
dText ~= "\t{ \""
~functionName
~"\", cast(void**)& "
~functionName
~"},\n"
;
}
}
}
}
dText ~= "];\n\n";
}
void clearValues()
{
debug(flow)(writefln("HTODConvert.clearValues"));
dText.length = 0;
dynLoad = false;
lib.length = 0;
preFile.length = 0;
pack.length = 0;
bool dynLoadAlreadyOpen = false;
bool headerAlreadyAdded = false;
functions.length = 0;
comment.length = 0;
}
void writeFile(char[] fileName)
{
debug(flow)(writefln("HTODConvert.writeFile"));
debug(flow)(writefln("HTODConvert.writeFile fileName = %s", fileName));
std.file.write(std.path.join(outputRoot,fileName), dText);
}
public static bit startsWith(char[] str, char[] prefix)
{
return str.length >= prefix.length
&& str[0..prefix.length] == prefix;
}
public static bit startsWith(char[] str, char prefix)
{
return str.length > 0
&& str[0] == prefix;
}
public static bit endsWith(char[] str, char[] prefix)
{
return str.length >= prefix.length
&& str[str.length-prefix.length..str.length] == prefix;
}
public static bit endsWith(char[] str, char suffix)
{
return str.length >= 1
&& str[str.length-1] == suffix;
}
}
| D |
import pyd.pyd, pyd.embedded, pyd.extra;
import deimos.python.Python;
import std.complex;
import std.datetime;
import std.bigint;
import std.string;
static this() {
py_init();
}
/*
unittest {
alias cfloat_ = Complex!float;
cfloat_[] data = [
cfloat_(1,2),
cfloat_(1,3),
cfloat_(1,4),
cfloat_(1,6),
];
auto npa = d_to_python_numpy_ndarray(data);
auto npop = new PydObject(npa);
assert(npop[0].imag.to_d!float() == 2);
assert(npop[0].getattr("real").to_d!float() == 1);
foreach(i, datum; data) {
assert(npop[i].imag.to_d!float() == datum.im);
assert(npop[i].getattr("real").to_d!float() == datum.re);
}
}
*/
// should convert numpy number types to primitives
unittest {
auto context = new InterpContext();
context.py_stmts("
import numpy
b = numpy.bool_()
i8 = numpy.int8()
i16 = numpy.int16()
i32 = numpy.int32()
i64 = numpy.int64()
u8 = numpy.uint8()
u16 = numpy.uint16()
u32 = numpy.uint32()
u64 = numpy.uint64()
f32 = numpy.float32()
f64 = numpy.float64()
c64 = numpy.complex64()
");
context.b.to_d!bool();
foreach(var; ["b", "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64"]) {
context.locals[var].to_d!byte();
context.locals[var].to_d!ubyte();
context.locals[var].to_d!short();
context.locals[var].to_d!ushort();
context.locals[var].to_d!int();
context.locals[var].to_d!uint();
context.locals[var].to_d!long();
context.locals[var].to_d!ulong();
context.locals[var].to_d!BigInt();
}
foreach(var; ["f32", "f64"]) {
context.locals[var].to_d!float();
context.locals[var].to_d!double();
context.locals[var].to_d!real();
}
context.c64.to_d!(Complex!float)();
context.py_stmts("
b = numpy.bool_(True)
i8 = numpy.int8(5)
i16 = numpy.int16(17)
i64 = numpy.int64(-11)
u32 = numpy.uint32(20)
f32 = numpy.float32(7.5)
");
assert(context.b.to_d!bool() == true);
assert(context.b.to_d!int() == 1);
assert(context.i8.to_d!byte() == 5);
assert(context.i8.to_d!ushort() == 5);
assert(context.i8.to_d!long() == 5);
assert(context.i8.to_d!float() == 5);
assert(context.i8.to_d!BigInt() == 5);
assert(context.i16.to_d!byte() == 17);
assert(context.i16.to_d!ushort() == 17);
assert(context.i16.to_d!long() == 17);
assert(context.i16.to_d!float() == 17);
assert(context.i16.to_d!BigInt() == 17);
assert(context.i64.to_d!byte() == -11);
assert(context.i64.to_d!long() == -11);
assert(context.i64.to_d!BigInt() == -11);
assert(context.u32.to_d!int() == 20);
assert(context.f32.to_d!int() == 7);
assert(context.f32.to_d!float() == 7.5);
assert(context.f32.to_d!double() == 7.5);
assert(context.f32.to_d!BigInt() == 7);
}
unittest {
alias cfloat_ = const(Complex!float);
cfloat_[] data = [
cfloat_(1,2),
cfloat_(1,3),
cfloat_(1,4),
cfloat_(1,6),
];
auto npa = d_to_python_numpy_ndarray(data);
auto npop = new PydObject(npa);
assert(npop[0].imag.to_d!float() == 2);
assert(npop[0].getattr("real").to_d!float() == 1);
foreach(i, datum; data) {
assert(npop[i].imag.to_d!float() == datum.im);
assert(npop[i].getattr("real").to_d!float() == datum.re);
}
}
unittest {
auto context = new InterpContext();
context.py_stmts("
from datetime import datetime
import numpy as np;
dt1 = np.datetime64(datetime(2014, 2, 3, 5, 1, 4))
");
auto result = context.dt1.to_d!DateTime();
assert (result.year == 2014);
assert (result.month == 2);
assert (result.day == 3);
assert (result.hour == 5);
assert (result.minute == 1);
assert (result.second == 4);
auto result2 = context.dt1.to_d!SysTime();
assert (result2.year == 2014);
assert (result2.month == 2);
assert (result2.day == 3);
assert (result2.hour == 5);
assert (result2.minute == 1);
assert (result2.second == 4);
auto result3 = context.dt1.to_d!Date();
assert (result3.year == 2014);
assert (result3.month == 2);
assert (result3.day == 3);
auto result4 = context.dt1.to_d!TimeOfDay();
assert (result4.hour == 5);
assert (result4.minute == 1);
assert (result4.second == 4);
}
unittest {
auto context = new InterpContext();
auto dt = DateTime(2014, 8, 22, 13, 7, 54);
context.dt = d_to_numpy_datetime64(dt);
context.py_stmts("
from datetime import datetime
from numpy import datetime64
assert isinstance(dt, datetime64)
dt_ = dt.astype(datetime)
assert dt_.year == 2014
assert dt_.month == 8
assert dt_.day == 22
assert dt_.hour == 13
assert dt_.minute == 7
assert dt_.second == 54
");
}
unittest {
bool[] data = [true, false, true, true, false];
auto npa = new PydObject(d_to_python_numpy_ndarray(data));
foreach(i, datum; data) {
assert(npa[i].to_d!bool() == datum);
}
}
unittest {
InterpContext context = new InterpContext();
context.py_stmts(outdent("
import numpy
a = numpy.eye(2, dtype='complex64')
"));
context.a.to_d!(Complex!float[][] )();
}
unittest {
InterpContext context = new InterpContext();
context.py_stmts(outdent("
import numpy
a = numpy.eye(2, dtype='complex128')
"));
context.a.to_d!(Complex!double[][] )();
}
void main() {}
| D |
import std.stdio;
void main()
{
double x = 50.0 / 3.0 * 520.0;
writeln(x);
//8666.67
x = 50.0 * 520.0 / 3.0;
writeln(x);
//8666.67
} | D |
/**
* Implementation of the gamma and beta functions, and their integrals.
*
* License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Copyright: Based on the CEPHES math library, which is
* Copyright (C) 1994 Stephen L. Moshier (moshier@world.std.com).
* Authors: Stephen L. Moshier (original C code). Conversion to D by Don Clugston
*
*
Macros:
* TABLE_SV = <table border=1 cellpadding=4 cellspacing=0>
* <caption>Special Values</caption>
* $0</table>
* SVH = $(TR $(TH $1) $(TH $2))
* SV = $(TR $(TD $1) $(TD $2))
* GAMMA = Γ
* INTEGRATE = $(BIG ∫<sub>$(SMALL $1)</sub><sup>$2</sup>)
* POWER = $1<sup>$2</sup>
* NAN = $(RED NAN)
*/
module std.internal.math.gammafunction;
import std.internal.math.errorfunction;
import std.math;
private {
enum real SQRT2PI = 2.50662827463100050242E0L; // sqrt(2pi)
immutable real EULERGAMMA = 0.57721_56649_01532_86060_65120_90082_40243_10421_59335_93992L; /** Euler-Mascheroni constant 0.57721566.. */
// Polynomial approximations for gamma and loggamma.
immutable real[8] GammaNumeratorCoeffs = [ 1.0,
0x1.acf42d903366539ep-1, 0x1.73a991c8475f1aeap-2, 0x1.c7e918751d6b2a92p-4,
0x1.86d162cca32cfe86p-6, 0x1.0c378e2e6eaf7cd8p-8, 0x1.dc5c66b7d05feb54p-12,
0x1.616457b47e448694p-15
];
immutable real[9] GammaDenominatorCoeffs = [ 1.0,
0x1.a8f9faae5d8fc8bp-2, -0x1.cb7895a6756eebdep-3, -0x1.7b9bab006d30652ap-5,
0x1.c671af78f312082ep-6, -0x1.a11ebbfaf96252dcp-11, -0x1.447b4d2230a77ddap-10,
0x1.ec1d45bb85e06696p-13,-0x1.d4ce24d05bd0a8e6p-17
];
immutable real[9] GammaSmallCoeffs = [ 1.0,
0x1.2788cfc6fb618f52p-1, -0x1.4fcf4026afa2f7ecp-1, -0x1.5815e8fa24d7e306p-5,
0x1.5512320aea2ad71ap-3, -0x1.59af0fb9d82e216p-5, -0x1.3b4b61d3bfdf244ap-7,
0x1.d9358e9d9d69fd34p-8, -0x1.38fc4bcbada775d6p-10
];
immutable real[9] GammaSmallNegCoeffs = [ -1.0,
0x1.2788cfc6fb618f54p-1, 0x1.4fcf4026afa2bc4cp-1, -0x1.5815e8fa2468fec8p-5,
-0x1.5512320baedaf4b6p-3, -0x1.59af0fa283baf07ep-5, 0x1.3b4a70de31e05942p-7,
0x1.d9398be3bad13136p-8, 0x1.291b73ee05bcbba2p-10
];
immutable real[7] logGammaStirlingCoeffs = [
0x1.5555555555553f98p-4, -0x1.6c16c16c07509b1p-9, 0x1.a01a012461cbf1e4p-11,
-0x1.3813089d3f9d164p-11, 0x1.b911a92555a277b8p-11, -0x1.ed0a7b4206087b22p-10,
0x1.402523859811b308p-8
];
immutable real[7] logGammaNumerator = [
-0x1.0edd25913aaa40a2p+23, -0x1.31c6ce2e58842d1ep+24, -0x1.f015814039477c3p+23,
-0x1.74ffe40c4b184b34p+22, -0x1.0d9c6d08f9eab55p+20, -0x1.54c6b71935f1fc88p+16,
-0x1.0e761b42932b2aaep+11
];
immutable real[8] logGammaDenominator = [
-0x1.4055572d75d08c56p+24, -0x1.deeb6013998e4d76p+24, -0x1.106f7cded5dcc79ep+24,
-0x1.25e17184848c66d2p+22, -0x1.301303b99a614a0ap+19, -0x1.09e76ab41ae965p+15,
-0x1.00f95ced9e5f54eep+9, 1.0
];
/*
* Helper function: Gamma function computed by Stirling's formula.
*
* Stirling's formula for the gamma function is:
*
* $(GAMMA)(x) = sqrt(2 π) x<sup>x-0.5</sup> exp(-x) (1 + 1/x P(1/x))
*
*/
real gammaStirling(real x)
{
// CEPHES code Copyright 1994 by Stephen L. Moshier
static immutable real[9] SmallStirlingCoeffs = [
0x1.55555555555543aap-4, 0x1.c71c71c720dd8792p-9, -0x1.5f7268f0b5907438p-9,
-0x1.e13cd410e0477de6p-13, 0x1.9b0f31643442616ep-11, 0x1.2527623a3472ae08p-14,
-0x1.37f6bc8ef8b374dep-11,-0x1.8c968886052b872ap-16, 0x1.76baa9c6d3eeddbcp-11
];
static immutable real[7] LargeStirlingCoeffs = [ 1.0L,
8.33333333333333333333E-2L, 3.47222222222222222222E-3L,
-2.68132716049382716049E-3L, -2.29472093621399176955E-4L,
7.84039221720066627474E-4L, 6.97281375836585777429E-5L
];
real w = 1.0L/x;
real y = exp(x);
if ( x > 1024.0L ) {
// For large x, use rational coefficients from the analytical expansion.
w = poly(w, LargeStirlingCoeffs);
// Avoid overflow in pow()
real v = pow( x, 0.5L * x - 0.25L );
y = v * (v / y);
}
else {
w = 1.0L + w * poly( w, SmallStirlingCoeffs);
y = pow( x, x - 0.5L ) / y;
}
y = SQRT2PI * y * w;
return y;
}
} // private
public:
/// The maximum value of x for which gamma(x) < real.infinity.
enum real MAXGAMMA = 1755.5483429L;
/*****************************************************
* The Gamma function, $(GAMMA)(x)
*
* $(GAMMA)(x) is a generalisation of the factorial function
* to real and complex numbers.
* Like x!, $(GAMMA)(x+1) = x*$(GAMMA)(x).
*
* Mathematically, if z.re > 0 then
* $(GAMMA)(z) = $(INTEGRATE 0, ∞) $(POWER t, z-1)$(POWER e, -t) dt
*
* $(TABLE_SV
* $(SVH x, $(GAMMA)(x) )
* $(SV $(NAN), $(NAN) )
* $(SV ±0.0, ±∞)
* $(SV integer > 0, (x-1)! )
* $(SV integer < 0, $(NAN) )
* $(SV +∞, +∞ )
* $(SV -∞, $(NAN) )
* )
*/
real gamma(real x)
{
/* Based on code from the CEPHES library.
* CEPHES code Copyright 1994 by Stephen L. Moshier
*
* Arguments |x| <= 13 are reduced by recurrence and the function
* approximated by a rational function of degree 7/8 in the
* interval (2,3). Large arguments are handled by Stirling's
* formula. Large negative arguments are made positive using
* a reflection formula.
*/
real q, z;
if (isNaN(x)) return x;
if (x == -x.infinity) return real.nan;
if ( fabs(x) > MAXGAMMA ) return real.infinity;
if (x==0) return 1.0 / x; // +- infinity depending on sign of x, create an exception.
q = fabs(x);
if ( q > 13.0L ) {
// Large arguments are handled by Stirling's
// formula. Large negative arguments are made positive using
// the reflection formula.
if ( x < 0.0L ) {
if (x < -1/real.epsilon)
{
// Large negatives lose all precision
return real.nan;
}
int sgngam = 1; // sign of gamma.
long intpart = cast(long)(q);
if (q == intpart)
return real.nan; // poles for all integers <0.
real p = intpart;
if ( (intpart & 1) == 0 )
sgngam = -1;
z = q - p;
if ( z > 0.5L ) {
p += 1.0L;
z = q - p;
}
z = q * sin( PI * z );
z = fabs(z) * gammaStirling(q);
if ( z <= PI/real.max ) return sgngam * real.infinity;
return sgngam * PI/z;
} else {
return gammaStirling(x);
}
}
// Arguments |x| <= 13 are reduced by recurrence and the function
// approximated by a rational function of degree 7/8 in the
// interval (2,3).
z = 1.0L;
while ( x >= 3.0L ) {
x -= 1.0L;
z *= x;
}
while ( x < -0.03125L ) {
z /= x;
x += 1.0L;
}
if ( x <= 0.03125L ) {
if ( x == 0.0L )
return real.nan;
else {
if ( x < 0.0L ) {
x = -x;
return z / (x * poly( x, GammaSmallNegCoeffs ));
} else {
return z / (x * poly( x, GammaSmallCoeffs ));
}
}
}
while ( x < 2.0L ) {
z /= x;
x += 1.0L;
}
if ( x == 2.0L ) return z;
x -= 2.0L;
return z * poly( x, GammaNumeratorCoeffs ) / poly( x, GammaDenominatorCoeffs );
}
unittest {
// gamma(n) = factorial(n-1) if n is an integer.
real fact = 1.0L;
for (int i=1; fact<real.max; ++i) {
// Require exact equality for small factorials
if (i<14) assert(gamma(i*1.0L) == fact);
assert(feqrel(gamma(i*1.0L), fact) > real.mant_dig-15);
fact *= (i*1.0L);
}
assert(gamma(0.0) == real.infinity);
assert(gamma(-0.0) == -real.infinity);
assert(isNaN(gamma(-1.0)));
assert(isNaN(gamma(-15.0)));
assert(isIdentical(gamma(NaN(0xABC)), NaN(0xABC)));
assert(gamma(real.infinity) == real.infinity);
assert(gamma(real.max) == real.infinity);
assert(isNaN(gamma(-real.infinity)));
assert(gamma(real.min_normal*real.epsilon) == real.infinity);
assert(gamma(MAXGAMMA)< real.infinity);
assert(gamma(MAXGAMMA*2) == real.infinity);
// Test some high-precision values (50 decimal digits)
real SQRT_PI = 1.77245385090551602729816748334114518279754945612238L;
assert(feqrel(gamma(0.5L), SQRT_PI) == real.mant_dig);
assert(feqrel(gamma(17.25L), 4.224986665692703551570937158682064589938e13L) >= real.mant_dig-4);
assert(feqrel(gamma(1.0 / 3.0L), 2.67893853470774763365569294097467764412868937795730L) >= real.mant_dig-2);
assert(feqrel(gamma(0.25L),
3.62560990822190831193068515586767200299516768288006L) >= real.mant_dig-1);
assert(feqrel(gamma(1.0 / 5.0L),
4.59084371199880305320475827592915200343410999829340L) >= real.mant_dig-1);
}
/*****************************************************
* Natural logarithm of gamma function.
*
* Returns the base e (2.718...) logarithm of the absolute
* value of the gamma function of the argument.
*
* For reals, logGamma is equivalent to log(fabs(gamma(x))).
*
* $(TABLE_SV
* $(SVH x, logGamma(x) )
* $(SV $(NAN), $(NAN) )
* $(SV integer <= 0, +∞ )
* $(SV ±∞, +∞ )
* )
*/
real logGamma(real x)
{
/* Based on code from the CEPHES library.
* CEPHES code Copyright 1994 by Stephen L. Moshier
*
* For arguments greater than 33, the logarithm of the gamma
* function is approximated by the logarithmic version of
* Stirling's formula using a polynomial approximation of
* degree 4. Arguments between -33 and +33 are reduced by
* recurrence to the interval [2,3] of a rational approximation.
* The cosecant reflection formula is employed for arguments
* less than -33.
*/
real q, w, z, f, nx;
if (isNaN(x)) return x;
if (fabs(x) == x.infinity) return x.infinity;
if( x < -34.0L )
{
q = -x;
w = logGamma(q);
real p = floor(q);
if ( p == q )
return real.infinity;
int intpart = cast(int)(p);
real sgngam = 1;
if ( (intpart & 1) == 0 )
sgngam = -1;
z = q - p;
if ( z > 0.5L ) {
p += 1.0L;
z = p - q;
}
z = q * sin( PI * z );
if ( z == 0.0L )
return sgngam * real.infinity;
/* z = LOGPI - logl( z ) - w; */
z = log( PI/z ) - w;
return z;
}
if( x < 13.0L )
{
z = 1.0L;
nx = floor( x + 0.5L );
f = x - nx;
while ( x >= 3.0L ) {
nx -= 1.0L;
x = nx + f;
z *= x;
}
while ( x < 2.0L ) {
if( fabs(x) <= 0.03125 )
{
if ( x == 0.0L )
return real.infinity;
if ( x < 0.0L )
{
x = -x;
q = z / (x * poly( x, GammaSmallNegCoeffs));
} else
q = z / (x * poly( x, GammaSmallCoeffs));
return log( fabs(q) );
}
z /= nx + f;
nx += 1.0L;
x = nx + f;
}
z = fabs(z);
if ( x == 2.0L )
return log(z);
x = (nx - 2.0L) + f;
real p = x * rationalPoly( x, logGammaNumerator, logGammaDenominator);
return log(z) + p;
}
// const real MAXLGM = 1.04848146839019521116e+4928L;
// if( x > MAXLGM ) return sgngaml * real.infinity;
const real LOGSQRT2PI = 0.91893853320467274178L; // log( sqrt( 2*pi ) )
q = ( x - 0.5L ) * log(x) - x + LOGSQRT2PI;
if (x > 1.0e10L) return q;
real p = 1.0L / (x*x);
q += poly( p, logGammaStirlingCoeffs ) / x;
return q ;
}
unittest {
assert(isIdentical(logGamma(NaN(0xDEF)), NaN(0xDEF)));
assert(logGamma(real.infinity) == real.infinity);
assert(logGamma(-1.0) == real.infinity);
assert(logGamma(0.0) == real.infinity);
assert(logGamma(-50.0) == real.infinity);
assert(isIdentical(0.0L, logGamma(1.0L)));
assert(isIdentical(0.0L, logGamma(2.0L)));
assert(logGamma(real.min_normal*real.epsilon) == real.infinity);
assert(logGamma(-real.min_normal*real.epsilon) == real.infinity);
// x, correct loggamma(x), correct d/dx loggamma(x).
static real[] testpoints = [
8.0L, 8.525146484375L + 1.48766904143001655310E-5, 2.01564147795560999654E0L,
8.99993896484375e-1L, 6.6375732421875e-2L + 5.11505711292524166220E-6L, -7.54938684259372234258E-1,
7.31597900390625e-1L, 2.2369384765625e-1 + 5.21506341809849792422E-6L, -1.13355566660398608343E0L,
2.31639862060546875e-1L, 1.3686676025390625L + 1.12609441752996145670E-5L, -4.56670961813812679012E0,
1.73162841796875L, -8.88214111328125e-2L + 3.36207740803753034508E-6L, 2.33339034686200586920E-1L,
1.23162841796875L, -9.3902587890625e-2L + 1.28765089229009648104E-5L, -2.49677345775751390414E-1L,
7.3786976294838206464e19L, 3.301798506038663053312e21L - 1.656137564136932662487046269677E5L,
4.57477139169563904215E1L,
1.08420217248550443401E-19L, 4.36682586669921875e1L + 1.37082843669932230418E-5L,
-9.22337203685477580858E18L,
1.0L, 0.0L, -5.77215664901532860607E-1L,
2.0L, 0.0L, 4.22784335098467139393E-1L,
-0.5L, 1.2655029296875L + 9.19379714539648894580E-6L, 3.64899739785765205590E-2L,
-1.5L, 8.6004638671875e-1L + 6.28657731014510932682E-7L, 7.03156640645243187226E-1L,
-2.5L, -5.6243896484375E-2L + 1.79986700949327405470E-7, 1.10315664064524318723E0L,
-3.5L, -1.30902099609375L + 1.43111007079536392848E-5L, 1.38887092635952890151E0L
];
// TODO: test derivatives as well.
for (int i=0; i<testpoints.length; i+=3) {
assert( feqrel(logGamma(testpoints[i]), testpoints[i+1]) > real.mant_dig-5);
if (testpoints[i]<MAXGAMMA) {
assert( feqrel(log(fabs(gamma(testpoints[i]))), testpoints[i+1]) > real.mant_dig-5);
}
}
assert(logGamma(-50.2) == log(fabs(gamma(-50.2))));
assert(logGamma(-0.008) == log(fabs(gamma(-0.008))));
assert(feqrel(logGamma(-38.8),log(fabs(gamma(-38.8)))) > real.mant_dig-4);
assert(feqrel(logGamma(1500.0L),log(gamma(1500.0L))) > real.mant_dig-2);
}
private {
enum real MAXLOG = 0x1.62e42fefa39ef358p+13L; // log(real.max)
enum real MINLOG = -0x1.6436716d5406e6d8p+13L; // log(real.min*real.epsilon) = log(smallest denormal)
enum real BETA_BIG = 9.223372036854775808e18L;
enum real BETA_BIGINV = 1.084202172485504434007e-19L;
}
/** Incomplete beta integral
*
* Returns incomplete beta integral of the arguments, evaluated
* from zero to x. The regularized incomplete beta function is defined as
*
* betaIncomplete(a, b, x) = Γ(a+b)/(Γ(a) Γ(b)) *
* $(INTEGRATE 0, x) $(POWER t, a-1)$(POWER (1-t),b-1) dt
*
* and is the same as the the cumulative distribution function.
*
* The domain of definition is 0 <= x <= 1. In this
* implementation a and b are restricted to positive values.
* The integral from x to 1 may be obtained by the symmetry
* relation
*
* betaIncompleteCompl(a, b, x ) = betaIncomplete( b, a, 1-x )
*
* The integral is evaluated by a continued fraction expansion
* or, when b*x is small, by a power series.
*/
real betaIncomplete(real aa, real bb, real xx )
{
if ( !(aa>0 && bb>0) )
{
if ( isNaN(aa) ) return aa;
if ( isNaN(bb) ) return bb;
return real.nan; // domain error
}
if (!(xx>0 && xx<1.0)) {
if (isNaN(xx)) return xx;
if ( xx == 0.0L ) return 0.0;
if ( xx == 1.0L ) return 1.0;
return real.nan; // domain error
}
if ( (bb * xx) <= 1.0L && xx <= 0.95L) {
return betaDistPowerSeries(aa, bb, xx);
}
real x;
real xc; // = 1 - x
real a, b;
int flag = 0;
/* Reverse a and b if x is greater than the mean. */
if( xx > (aa/(aa+bb)) ) {
// here x > aa/(aa+bb) and (bb*x>1 or x>0.95)
flag = 1;
a = bb;
b = aa;
xc = xx;
x = 1.0L - xx;
} else {
a = aa;
b = bb;
xc = 1.0L - xx;
x = xx;
}
if( flag == 1 && (b * x) <= 1.0L && x <= 0.95L) {
// here xx > aa/(aa+bb) and ((bb*xx>1) or xx>0.95) and (aa*(1-xx)<=1) and xx > 0.05
return 1.0 - betaDistPowerSeries(a, b, x); // note loss of precision
}
real w;
// Choose expansion for optimal convergence
// One is for x * (a+b+2) < (a+1),
// the other is for x * (a+b+2) > (a+1).
real y = x * (a+b-2.0L) - (a-1.0L);
if( y < 0.0L ) {
w = betaDistExpansion1( a, b, x );
} else {
w = betaDistExpansion2( a, b, x ) / xc;
}
/* Multiply w by the factor
a b
x (1-x) Gamma(a+b) / ( a Gamma(a) Gamma(b) ) . */
y = a * log(x);
real t = b * log(xc);
if ( (a+b) < MAXGAMMA && fabs(y) < MAXLOG && fabs(t) < MAXLOG ) {
t = pow(xc,b);
t *= pow(x,a);
t /= a;
t *= w;
t *= gamma(a+b) / (gamma(a) * gamma(b));
} else {
/* Resort to logarithms. */
y += t + logGamma(a+b) - logGamma(a) - logGamma(b);
y += log(w/a);
t = exp(y);
/+
// There seems to be a bug in Cephes at this point.
// Problems occur for y > MAXLOG, not y < MINLOG.
if( y < MINLOG ) {
t = 0.0L;
} else {
t = exp(y);
}
+/
}
if( flag == 1 ) {
/+ // CEPHES includes this code, but I think it is erroneous.
if( t <= real.epsilon ) {
t = 1.0L - real.epsilon;
} else
+/
t = 1.0L - t;
}
return t;
}
/** Inverse of incomplete beta integral
*
* Given y, the function finds x such that
*
* betaIncomplete(a, b, x) == y
*
* Newton iterations or interval halving is used.
*/
real betaIncompleteInv(real aa, real bb, real yy0 )
{
real a, b, y0, d, y, x, x0, x1, lgm, yp, di, dithresh, yl, yh, xt;
int i, rflg, dir, nflg;
if (isNaN(yy0)) return yy0;
if (isNaN(aa)) return aa;
if (isNaN(bb)) return bb;
if( yy0 <= 0.0L )
return 0.0L;
if( yy0 >= 1.0L )
return 1.0L;
x0 = 0.0L;
yl = 0.0L;
x1 = 1.0L;
yh = 1.0L;
if( aa <= 1.0L || bb <= 1.0L ) {
dithresh = 1.0e-7L;
rflg = 0;
a = aa;
b = bb;
y0 = yy0;
x = a/(a+b);
y = betaIncomplete( a, b, x );
nflg = 0;
goto ihalve;
} else {
nflg = 0;
dithresh = 1.0e-4L;
}
// approximation to inverse function
yp = -normalDistributionInvImpl( yy0 );
if( yy0 > 0.5L ) {
rflg = 1;
a = bb;
b = aa;
y0 = 1.0L - yy0;
yp = -yp;
} else {
rflg = 0;
a = aa;
b = bb;
y0 = yy0;
}
lgm = (yp * yp - 3.0L)/6.0L;
x = 2.0L/( 1.0L/(2.0L * a-1.0L) + 1.0L/(2.0L * b - 1.0L) );
d = yp * sqrt( x + lgm ) / x
- ( 1.0L/(2.0L * b - 1.0L) - 1.0L/(2.0L * a - 1.0L) )
* (lgm + (5.0L/6.0L) - 2.0L/(3.0L * x));
d = 2.0L * d;
if( d < MINLOG ) {
x = 1.0L;
goto under;
}
x = a/( a + b * exp(d) );
y = betaIncomplete( a, b, x );
yp = (y - y0)/y0;
if( fabs(yp) < 0.2 )
goto newt;
/* Resort to interval halving if not close enough. */
ihalve:
dir = 0;
di = 0.5L;
for( i=0; i<400; i++ ) {
if( i != 0 ) {
x = x0 + di * (x1 - x0);
if( x == 1.0L ) {
x = 1.0L - real.epsilon;
}
if( x == 0.0L ) {
di = 0.5;
x = x0 + di * (x1 - x0);
if( x == 0.0 )
goto under;
}
y = betaIncomplete( a, b, x );
yp = (x1 - x0)/(x1 + x0);
if( fabs(yp) < dithresh )
goto newt;
yp = (y-y0)/y0;
if( fabs(yp) < dithresh )
goto newt;
}
if( y < y0 ) {
x0 = x;
yl = y;
if( dir < 0 ) {
dir = 0;
di = 0.5L;
} else if( dir > 3 )
di = 1.0L - (1.0L - di) * (1.0L - di);
else if( dir > 1 )
di = 0.5L * di + 0.5L;
else
di = (y0 - y)/(yh - yl);
dir += 1;
if( x0 > 0.95L ) {
if( rflg == 1 ) {
rflg = 0;
a = aa;
b = bb;
y0 = yy0;
} else {
rflg = 1;
a = bb;
b = aa;
y0 = 1.0 - yy0;
}
x = 1.0L - x;
y = betaIncomplete( a, b, x );
x0 = 0.0;
yl = 0.0;
x1 = 1.0;
yh = 1.0;
goto ihalve;
}
} else {
x1 = x;
if( rflg == 1 && x1 < real.epsilon ) {
x = 0.0L;
goto done;
}
yh = y;
if( dir > 0 ) {
dir = 0;
di = 0.5L;
}
else if( dir < -3 )
di = di * di;
else if( dir < -1 )
di = 0.5L * di;
else
di = (y - y0)/(yh - yl);
dir -= 1;
}
}
if( x0 >= 1.0L ) {
// partial loss of precision
x = 1.0L - real.epsilon;
goto done;
}
if( x <= 0.0L ) {
under:
// underflow has occurred
x = real.min_normal * real.min_normal;
goto done;
}
newt:
if ( nflg ) {
goto done;
}
nflg = 1;
lgm = logGamma(a+b) - logGamma(a) - logGamma(b);
for( i=0; i<15; i++ ) {
/* Compute the function at this point. */
if ( i != 0 )
y = betaIncomplete(a,b,x);
if ( y < yl ) {
x = x0;
y = yl;
} else if( y > yh ) {
x = x1;
y = yh;
} else if( y < y0 ) {
x0 = x;
yl = y;
} else {
x1 = x;
yh = y;
}
if( x == 1.0L || x == 0.0L )
break;
/* Compute the derivative of the function at this point. */
d = (a - 1.0L) * log(x) + (b - 1.0L) * log(1.0L - x) + lgm;
if ( d < MINLOG ) {
goto done;
}
if ( d > MAXLOG ) {
break;
}
d = exp(d);
/* Compute the step to the next approximation of x. */
d = (y - y0)/d;
xt = x - d;
if ( xt <= x0 ) {
y = (x - x0) / (x1 - x0);
xt = x0 + 0.5L * y * (x - x0);
if( xt <= 0.0L )
break;
}
if ( xt >= x1 ) {
y = (x1 - x) / (x1 - x0);
xt = x1 - 0.5L * y * (x1 - x);
if ( xt >= 1.0L )
break;
}
x = xt;
if ( fabs(d/x) < (128.0L * real.epsilon) )
goto done;
}
/* Did not converge. */
dithresh = 256.0L * real.epsilon;
goto ihalve;
done:
if ( rflg ) {
if( x <= real.epsilon )
x = 1.0L - real.epsilon;
else
x = 1.0L - x;
}
return x;
}
unittest { // also tested by the normal distribution
// check NaN propagation
assert(isIdentical(betaIncomplete(NaN(0xABC),2,3), NaN(0xABC)));
assert(isIdentical(betaIncomplete(7,NaN(0xABC),3), NaN(0xABC)));
assert(isIdentical(betaIncomplete(7,15,NaN(0xABC)), NaN(0xABC)));
assert(isIdentical(betaIncompleteInv(NaN(0xABC),1,17), NaN(0xABC)));
assert(isIdentical(betaIncompleteInv(2,NaN(0xABC),8), NaN(0xABC)));
assert(isIdentical(betaIncompleteInv(2,3, NaN(0xABC)), NaN(0xABC)));
assert(isNaN(betaIncomplete(-1, 2, 3)));
assert(betaIncomplete(1, 2, 0)==0);
assert(betaIncomplete(1, 2, 1)==1);
assert(isNaN(betaIncomplete(1, 2, 3)));
assert(betaIncompleteInv(1, 1, 0)==0);
assert(betaIncompleteInv(1, 1, 1)==1);
// Test against Mathematica betaRegularized[z,a,b]
// These arbitrary points are chosen to give good code coverage.
assert(feqrel(betaIncomplete(8, 10, 0.2), 0.010_934_315_234_099_2L) >= real.mant_dig - 4);
assert(feqrel(betaIncomplete(2, 2.5, 0.9),0.989_722_597_604_452_767_171_003_59L) >= real.mant_dig - 1 );
assert(feqrel(betaIncomplete(1000, 800, 0.5), 1.179140859734704555102808541457164E-06L) >= real.mant_dig - 12 );
assert(feqrel(betaIncomplete(0.0001, 10000, 0.0001),0.999978059362107134278786L) >= real.mant_dig - 18 );
assert(betaIncomplete(0.01, 327726.7, 0.545113) == 1.0);
assert(feqrel(betaIncompleteInv(8, 10, 0.010_934_315_234_099_2L), 0.2L) >= real.mant_dig - 1);
assert(feqrel(betaIncomplete(0.01, 498.437, 0.0121433),0.99999664562033077636065L) >= real.mant_dig - 1);
assert(feqrel(betaIncompleteInv(5, 10, 0.2000002972865658842), 0.229121208190918L) >= real.mant_dig - 3);
assert(feqrel(betaIncompleteInv(4, 7, 0.8000002209179505L), 0.483657360076904L) >= real.mant_dig - 3);
// Coverage tests. I don't have correct values for these tests, but
// these values cover most of the code, so they are useful for
// regression testing.
// Extensive testing failed to increase the coverage. It seems likely that about
// half the code in this function is unnecessary; there is potential for
// significant improvement over the original CEPHES code.
assert(betaIncompleteInv(0.01, 8e-48, 5.45464e-20)==1-real.epsilon);
assert(betaIncompleteInv(0.01, 8e-48, 9e-26)==1-real.epsilon);
// Beware: a one-bit change in pow() changes almost all digits in the result!
assert(feqrel(betaIncompleteInv(0x1.b3d151fbba0eb18p+1, 1.2265e-19, 2.44859e-18),0x1.c0110c8531d0952cp-1L) > 10);
// This next case uncovered a one-bit difference in the FYL2X instruction
// between Intel and AMD processors. This difference gets magnified by 2^^38.
// WolframAlpha crashes attempting to calculate this.
assert(feqrel(betaIncompleteInv(0x1.ff1275ae5b939bcap-41, 4.6713e18, 0.0813601),
0x1.f97749d90c7adba8p-63L) >= real.mant_dig - 39);
real a1 = 3.40483;
assert(betaIncompleteInv(a1, 4.0640301659679627772e19L, 0.545113)== 0x1.ba8c08108aaf5d14p-109);
real b1 = 2.82847e-25;
assert(feqrel(betaIncompleteInv(0.01, b1, 9e-26), 0x1.549696104490aa9p-830L) >= real.mant_dig-10);
// --- Problematic cases ---
// This is a situation where the series expansion fails to converge
assert( isNaN(betaIncompleteInv(0.12167, 4.0640301659679627772e19L, 0.0813601)));
// This next result is almost certainly erroneous.
// Mathematica states: "(cannot be determined by current methods)"
assert(betaIncomplete(1.16251e20, 2.18e39, 5.45e-20)==-real.infinity);
// WolframAlpha gives no result for this, though indicates that it approximately 1.0 - 1.3e-9
assert(1- betaIncomplete(0.01, 328222, 4.0375e-5) == 0x1.5f62926b4p-30);
}
private {
// Implementation functions
// Continued fraction expansion #1 for incomplete beta integral
// Use when x < (a+1)/(a+b+2)
real betaDistExpansion1(real a, real b, real x )
{
real xk, pk, pkm1, pkm2, qk, qkm1, qkm2;
real k1, k2, k3, k4, k5, k6, k7, k8;
real r, t, ans;
int n;
k1 = a;
k2 = a + b;
k3 = a;
k4 = a + 1.0L;
k5 = 1.0L;
k6 = b - 1.0L;
k7 = k4;
k8 = a + 2.0L;
pkm2 = 0.0L;
qkm2 = 1.0L;
pkm1 = 1.0L;
qkm1 = 1.0L;
ans = 1.0L;
r = 1.0L;
n = 0;
const real thresh = 3.0L * real.epsilon;
do {
xk = -( x * k1 * k2 )/( k3 * k4 );
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
xk = ( x * k5 * k6 )/( k7 * k8 );
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if( qk != 0.0L )
r = pk/qk;
if( r != 0.0L ) {
t = fabs( (ans - r)/r );
ans = r;
} else {
t = 1.0L;
}
if( t < thresh )
return ans;
k1 += 1.0L;
k2 += 1.0L;
k3 += 2.0L;
k4 += 2.0L;
k5 += 1.0L;
k6 -= 1.0L;
k7 += 2.0L;
k8 += 2.0L;
if( (fabs(qk) + fabs(pk)) > BETA_BIG ) {
pkm2 *= BETA_BIGINV;
pkm1 *= BETA_BIGINV;
qkm2 *= BETA_BIGINV;
qkm1 *= BETA_BIGINV;
}
if( (fabs(qk) < BETA_BIGINV) || (fabs(pk) < BETA_BIGINV) ) {
pkm2 *= BETA_BIG;
pkm1 *= BETA_BIG;
qkm2 *= BETA_BIG;
qkm1 *= BETA_BIG;
}
}
while( ++n < 400 );
// loss of precision has occurred
// mtherr( "incbetl", PLOSS );
return ans;
}
// Continued fraction expansion #2 for incomplete beta integral
// Use when x > (a+1)/(a+b+2)
real betaDistExpansion2(real a, real b, real x )
{
real xk, pk, pkm1, pkm2, qk, qkm1, qkm2;
real k1, k2, k3, k4, k5, k6, k7, k8;
real r, t, ans, z;
k1 = a;
k2 = b - 1.0L;
k3 = a;
k4 = a + 1.0L;
k5 = 1.0L;
k6 = a + b;
k7 = a + 1.0L;
k8 = a + 2.0L;
pkm2 = 0.0L;
qkm2 = 1.0L;
pkm1 = 1.0L;
qkm1 = 1.0L;
z = x / (1.0L-x);
ans = 1.0L;
r = 1.0L;
int n = 0;
const real thresh = 3.0L * real.epsilon;
do {
xk = -( z * k1 * k2 )/( k3 * k4 );
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
xk = ( z * k5 * k6 )/( k7 * k8 );
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if( qk != 0.0L )
r = pk/qk;
if( r != 0.0L ) {
t = fabs( (ans - r)/r );
ans = r;
} else
t = 1.0L;
if( t < thresh )
return ans;
k1 += 1.0L;
k2 -= 1.0L;
k3 += 2.0L;
k4 += 2.0L;
k5 += 1.0L;
k6 += 1.0L;
k7 += 2.0L;
k8 += 2.0L;
if( (fabs(qk) + fabs(pk)) > BETA_BIG ) {
pkm2 *= BETA_BIGINV;
pkm1 *= BETA_BIGINV;
qkm2 *= BETA_BIGINV;
qkm1 *= BETA_BIGINV;
}
if( (fabs(qk) < BETA_BIGINV) || (fabs(pk) < BETA_BIGINV) ) {
pkm2 *= BETA_BIG;
pkm1 *= BETA_BIG;
qkm2 *= BETA_BIG;
qkm1 *= BETA_BIG;
}
} while( ++n < 400 );
// loss of precision has occurred
//mtherr( "incbetl", PLOSS );
return ans;
}
/* Power series for incomplete gamma integral.
Use when b*x is small. */
real betaDistPowerSeries(real a, real b, real x )
{
real ai = 1.0L / a;
real u = (1.0L - b) * x;
real v = u / (a + 1.0L);
real t1 = v;
real t = u;
real n = 2.0L;
real s = 0.0L;
real z = real.epsilon * ai;
while( fabs(v) > z ) {
u = (n - b) * x / n;
t *= u;
v = t / (a + n);
s += v;
n += 1.0L;
}
s += t1;
s += ai;
u = a * log(x);
if ( (a+b) < MAXGAMMA && fabs(u) < MAXLOG ) {
t = gamma(a+b)/(gamma(a)*gamma(b));
s = s * t * pow(x,a);
} else {
t = logGamma(a+b) - logGamma(a) - logGamma(b) + u + log(s);
if( t < MINLOG ) {
s = 0.0L;
} else
s = exp(t);
}
return s;
}
}
/***************************************
* Incomplete gamma integral and its complement
*
* These functions are defined by
*
* gammaIncomplete = ( $(INTEGRATE 0, x) $(POWER e, -t) $(POWER t, a-1) dt )/ $(GAMMA)(a)
*
* gammaIncompleteCompl(a,x) = 1 - gammaIncomplete(a,x)
* = ($(INTEGRATE x, ∞) $(POWER e, -t) $(POWER t, a-1) dt )/ $(GAMMA)(a)
*
* In this implementation both arguments must be positive.
* The integral is evaluated by either a power series or
* continued fraction expansion, depending on the relative
* values of a and x.
*/
real gammaIncomplete(real a, real x )
in {
assert(x >= 0);
assert(a > 0);
}
body {
/* left tail of incomplete gamma function:
*
* inf. k
* a -x - x
* x e > ----------
* - -
* k=0 | (a+k+1)
*
*/
if (x==0)
return 0.0L;
if ( (x > 1.0L) && (x > a ) )
return 1.0L - gammaIncompleteCompl(a,x);
real ax = a * log(x) - x - logGamma(a);
/+
if( ax < MINLOGL ) return 0; // underflow
// { mtherr( "igaml", UNDERFLOW ); return( 0.0L ); }
+/
ax = exp(ax);
/* power series */
real r = a;
real c = 1.0L;
real ans = 1.0L;
do {
r += 1.0L;
c *= x/r;
ans += c;
} while( c/ans > real.epsilon );
return ans * ax/a;
}
/** ditto */
real gammaIncompleteCompl(real a, real x )
in {
assert(x >= 0);
assert(a > 0);
}
body {
if (x==0)
return 1.0L;
if ( (x < 1.0L) || (x < a) )
return 1.0L - gammaIncomplete(a,x);
// DAC (Cephes bug fix): This is necessary to avoid
// spurious nans, eg
// log(x)-x = NaN when x = real.infinity
const real MAXLOGL = 1.1356523406294143949492E4L;
if (x > MAXLOGL) return 0; // underflow
real ax = a * log(x) - x - logGamma(a);
//const real MINLOGL = -1.1355137111933024058873E4L;
// if ( ax < MINLOGL ) return 0; // underflow;
ax = exp(ax);
/* continued fraction */
real y = 1.0L - a;
real z = x + y + 1.0L;
real c = 0.0L;
real pk, qk, t;
real pkm2 = 1.0L;
real qkm2 = x;
real pkm1 = x + 1.0L;
real qkm1 = z * x;
real ans = pkm1/qkm1;
do {
c += 1.0L;
y += 1.0L;
z += 2.0L;
real yc = y * c;
pk = pkm1 * z - pkm2 * yc;
qk = qkm1 * z - qkm2 * yc;
if( qk != 0.0L ) {
real r = pk/qk;
t = fabs( (ans - r)/r );
ans = r;
} else {
t = 1.0L;
}
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
const real BIG = 9.223372036854775808e18L;
if ( fabs(pk) > BIG ) {
pkm2 /= BIG;
pkm1 /= BIG;
qkm2 /= BIG;
qkm1 /= BIG;
}
} while ( t > real.epsilon );
return ans * ax;
}
/** Inverse of complemented incomplete gamma integral
*
* Given a and p, the function finds x such that
*
* gammaIncompleteCompl( a, x ) = p.
*
* Starting with the approximate value x = a $(POWER t, 3), where
* t = 1 - d - normalDistributionInv(p) sqrt(d),
* and d = 1/9a,
* the routine performs up to 10 Newton iterations to find the
* root of incompleteGammaCompl(a,x) - p = 0.
*/
real gammaIncompleteComplInv(real a, real p)
in {
assert(p>=0 && p<= 1);
assert(a>0);
}
body {
if (p==0) return real.infinity;
real y0 = p;
const real MAXLOGL = 1.1356523406294143949492E4L;
real x0, x1, x, yl, yh, y, d, lgm, dithresh;
int i, dir;
/* bound the solution */
x0 = real.max;
yl = 0.0L;
x1 = 0.0L;
yh = 1.0L;
dithresh = 4.0 * real.epsilon;
/* approximation to inverse function */
d = 1.0L/(9.0L*a);
y = 1.0L - d - normalDistributionInvImpl(y0) * sqrt(d);
x = a * y * y * y;
lgm = logGamma(a);
for( i=0; i<10; i++ ) {
if( x > x0 || x < x1 )
goto ihalve;
y = gammaIncompleteCompl(a,x);
if ( y < yl || y > yh )
goto ihalve;
if ( y < y0 ) {
x0 = x;
yl = y;
} else {
x1 = x;
yh = y;
}
/* compute the derivative of the function at this point */
d = (a - 1.0L) * log(x0) - x0 - lgm;
if ( d < -MAXLOGL )
goto ihalve;
d = -exp(d);
/* compute the step to the next approximation of x */
d = (y - y0)/d;
x = x - d;
if ( i < 3 ) continue;
if ( fabs(d/x) < dithresh ) return x;
}
/* Resort to interval halving if Newton iteration did not converge. */
ihalve:
d = 0.0625L;
if ( x0 == real.max ) {
if( x <= 0.0L )
x = 1.0L;
while( x0 == real.max ) {
x = (1.0L + d) * x;
y = gammaIncompleteCompl( a, x );
if ( y < y0 ) {
x0 = x;
yl = y;
break;
}
d = d + d;
}
}
d = 0.5L;
dir = 0;
for( i=0; i<400; i++ ) {
x = x1 + d * (x0 - x1);
y = gammaIncompleteCompl( a, x );
lgm = (x0 - x1)/(x1 + x0);
if ( fabs(lgm) < dithresh )
break;
lgm = (y - y0)/y0;
if ( fabs(lgm) < dithresh )
break;
if ( x <= 0.0L )
break;
if ( y > y0 ) {
x1 = x;
yh = y;
if ( dir < 0 ) {
dir = 0;
d = 0.5L;
} else if ( dir > 1 )
d = 0.5L * d + 0.5L;
else
d = (y0 - yl)/(yh - yl);
dir += 1;
} else {
x0 = x;
yl = y;
if ( dir > 0 ) {
dir = 0;
d = 0.5L;
} else if ( dir < -1 )
d = 0.5L * d;
else
d = (y0 - yl)/(yh - yl);
dir -= 1;
}
}
/+
if( x == 0.0L )
mtherr( "igamil", UNDERFLOW );
+/
return x;
}
unittest {
//Values from Excel's GammaInv(1-p, x, 1)
assert(fabs(gammaIncompleteComplInv(1, 0.5) - 0.693147188044814) < 0.00000005);
assert(fabs(gammaIncompleteComplInv(12, 0.99) - 5.42818075054289) < 0.00000005);
assert(fabs(gammaIncompleteComplInv(100, 0.8) - 91.5013985848288L) < 0.000005);
assert(gammaIncomplete(1, 0)==0);
assert(gammaIncompleteCompl(1, 0)==1);
assert(gammaIncomplete(4545, real.infinity)==1);
// Values from Excel's (1-GammaDist(x, alpha, 1, TRUE))
assert(fabs(1.0L-gammaIncompleteCompl(0.5, 2) - 0.954499729507309L) < 0.00000005);
assert(fabs(gammaIncomplete(0.5, 2) - 0.954499729507309L) < 0.00000005);
// Fixed Cephes bug:
assert(gammaIncompleteCompl(384, real.infinity)==0);
assert(gammaIncompleteComplInv(3, 0)==real.infinity);
}
/** Digamma function
*
* The digamma function is the logarithmic derivative of the gamma function.
*
* digamma(x) = d/dx logGamma(x)
*
*/
real digamma(real x)
{
// Based on CEPHES, Stephen L. Moshier.
// DAC: These values are Bn / n for n=2,4,6,8,10,12,14.
static immutable real [7] Bn_n = [
1.0L/(6*2), -1.0L/(30*4), 1.0L/(42*6), -1.0L/(30*8),
5.0L/(66*10), -691.0L/(2730*12), 7.0L/(6*14) ];
real p, q, nz, s, w, y, z;
long i, n;
int negative;
negative = 0;
nz = 0.0;
if ( x <= 0.0 ) {
negative = 1;
q = x;
p = floor(q);
if( p == q ) {
return real.nan; // singularity.
}
/* Remove the zeros of tan(PI x)
* by subtracting the nearest integer from x
*/
nz = q - p;
if ( nz != 0.5 ) {
if ( nz > 0.5 ) {
p += 1.0;
nz = q - p;
}
nz = PI/tan(PI*nz);
} else {
nz = 0.0;
}
x = 1.0 - x;
}
// check for small positive integer
if ((x <= 13.0) && (x == floor(x)) ) {
y = 0.0;
n = lrint(x);
// DAC: CEPHES bugfix. Cephes did this in reverse order, which
// created a larger roundoff error.
for (i=n-1; i>0; --i) {
y+=1.0L/i;
}
y -= EULERGAMMA;
goto done;
}
s = x;
w = 0.0;
while ( s < 10.0 ) {
w += 1.0/s;
s += 1.0;
}
if ( s < 1.0e17 ) {
z = 1.0/(s * s);
y = z * poly(z, Bn_n);
} else
y = 0.0;
y = log(s) - 0.5L/s - y - w;
done:
if ( negative ) {
y -= nz;
}
return y;
}
version(unittest) import core.stdc.stdio;
unittest {
// Exact values
assert(digamma(1)== -EULERGAMMA);
assert(feqrel(digamma(0.25), -PI/2 - 3* LN2 - EULERGAMMA) >= real.mant_dig-7);
assert(feqrel(digamma(1.0L/6), -PI/2 *sqrt(3.0L) - 2* LN2 -1.5*log(3.0L) - EULERGAMMA) >= real.mant_dig-7);
assert(digamma(-5)!<>0);
assert(feqrel(digamma(2.5), -EULERGAMMA - 2*LN2 + 2.0 + 2.0L/3) >= real.mant_dig-9);
assert(isIdentical(digamma(NaN(0xABC)), NaN(0xABC)));
for (int k=1; k<40; ++k) {
real y=0;
for (int u=k; u>=1; --u) {
y += 1.0L/u;
}
assert(feqrel(digamma(k+1), -EULERGAMMA + y) >= real.mant_dig-2);
}
}
| D |
/*
TEST_OUTPUT:
---
fail_compilation/fail312.d(13): Error: incompatible types for ((a[]) == (b)): 'int[]' and 'short'
fail_compilation/fail312.d(14): Error: incompatible types for ((a[]) <= (b)): 'int[]' and 'short'
---
*/
void main()
{
int[1] a = 1;
short b = 1;
assert(a[] == b);
assert(a[] <= b);
}
| D |
// This file is part of Visual D
//
// Visual D integrates the D programming language into Visual Studio
// Copyright (c) 2010 by Rainer Schuetze, All Rights Reserved
//
// License for redistribution is given by the Artistic License 2.0
// see file LICENSE for further details
module visuald.viewfilter;
import visuald.windows;
import visuald.comutil;
import visuald.logutil;
import visuald.hierutil;
import visuald.fileutil;
import visuald.stringutil;
import visuald.pkgutil;
import visuald.dpackage;
import visuald.dproject;
import visuald.hierarchy;
import visuald.chiernode;
import visuald.dimagelist;
import visuald.completion;
import visuald.simpleparser;
import visuald.intellisense;
import visuald.searchsymbol;
import visuald.expansionprovider;
import visuald.dlangsvc;
import visuald.winctrl;
import visuald.tokenreplace;
import visuald.cppwizard;
import visuald.config;
import visuald.build;
import visuald.help;
import vdc.lexer;
import sdk.port.vsi;
import sdk.vsi.textmgr;
import sdk.vsi.textmgr2;
import sdk.vsi.stdidcmd;
import sdk.vsi.vsshell;
import sdk.vsi.vsdbgcmd;
import sdk.vsi.vsdebugguids;
import sdk.vsi.msdbg;
import stdext.array;
import stdext.path;
import stdext.string;
import std.string;
import std.ascii;
import std.utf;
import std.conv;
import std.algorithm;
import std.array;
///////////////////////////////////////////////////////////////////////////////
interface IVsCustomDataTip : IUnknown
{
static const GUID iid = uuid("80DD0557-F6FE-48e3-9651-398C5E7D8D78");
HRESULT DisplayDataTip();
}
// version = tip;
class ViewFilter : DisposingComObject, IVsTextViewFilter, IOleCommandTarget,
IVsTextViewEvents, IVsExpansionEvents
{
CodeWindowManager mCodeWinMgr;
IVsTextView mView;
uint mCookieTextViewEvents;
IOleCommandTarget mNextTarget;
int mLastHighlightBracesLine;
ViewCol mLastHighlightBracesCol;
version(tip)
TextTipData mTextTipData;
this(CodeWindowManager mgr, IVsTextView view)
{
mCodeWinMgr = mgr;
mView = addref(view);
mCookieTextViewEvents = Advise!(IVsTextViewEvents)(mView, this);
mView.AddCommandFilter(this, &mNextTarget);
version(tip)
mTextTipData = addref(new TextTipData);
}
~this()
{
}
override void Dispose()
{
if(mView)
{
mView.RemoveCommandFilter(this);
if(mCookieTextViewEvents)
Unadvise!(IVsTextViewEvents)(mView, mCookieTextViewEvents);
mView = release(mView);
}
version(tip)
if(mTextTipData)
{
// we need to break the circular reference TextTipData<->IVsMethodTipWindow
mTextTipData.Dispose();
mTextTipData = release(mTextTipData);
}
mCodeWinMgr = null;
}
override HRESULT QueryInterface(in IID* riid, void** pvObject)
{
if(queryInterface!(IVsTextViewFilter) (this, riid, pvObject))
return S_OK;
if(queryInterface!(IVsTextViewEvents) (this, riid, pvObject))
return S_OK;
if(queryInterface!(IOleCommandTarget) (this, riid, pvObject))
return S_OK;
if(queryInterface!(IVsExpansionEvents) (this, riid, pvObject))
return S_OK;
return super.QueryInterface(riid, pvObject);
}
// IOleCommandTarget //////////////////////////////////////
override int QueryStatus( /* [unique][in] */ in GUID *pguidCmdGroup,
/* [in] */ in uint cCmds,
/* [out][in][size_is] */ OLECMD *prgCmds,
/* [unique][out][in] */ OLECMDTEXT *pCmdText)
{
// mixin(LogCallMix);
for (uint i = 0; i < cCmds; i++)
{
int rc = QueryCommandStatus(pguidCmdGroup, prgCmds[i].cmdID);
if(rc == E_FAIL)
{
if(mNextTarget)
return mNextTarget.QueryStatus(pguidCmdGroup, cCmds, prgCmds, pCmdText);
return rc;
}
prgCmds[i].cmdf = cast(uint)rc;
}
return S_OK;
}
override int Exec( /* [unique][in] */ in GUID *pguidCmdGroup,
/* [in] */ in uint nCmdID,
/* [in] */ in uint nCmdexecopt,
/* [unique][in] */ in VARIANT *pvaIn,
/* [unique][out][in] */ VARIANT *pvaOut)
{
if(*pguidCmdGroup == CMDSETID_StandardCommandSet2K && nCmdID == 1627 /*OutputPaneCombo*/)
return OLECMDERR_E_NOTSUPPORTED; // do not litter output
debug
{
bool logit = true;
if(*pguidCmdGroup == CMDSETID_StandardCommandSet2K)
{
switch(nCmdID)
{
case ECMD_HANDLEIMEMESSAGE:
logit = false;
break;
default:
break;
}
}
else if(*pguidCmdGroup == guidVSDebugCommand)
{
switch(nCmdID)
{
case cmdidOutputPaneCombo:
case cmdidProcessList:
case cmdidThreadList:
case cmdidStackFrameList:
logit = false;
break;
default:
break;
}
}
if(logit)
logCall("%s.Exec(this=%s, pguidCmdGroup=%s, nCmdId=%d: %s)",
this, cast(void*) this, _toLog(pguidCmdGroup), nCmdID, cmd2string(*pguidCmdGroup, nCmdID));
}
Package.GetLanguageService().OnExec();
ushort lo = (nCmdexecopt & 0xffff);
ushort hi = (nCmdexecopt >> 16);
bool wasCompletorActive = mCodeWinMgr.mSource.IsCompletorActive();
bool gotEnterKey = false;
ExpansionProvider ep = GetExpansionProvider();
if(ep) //if (ep.InTemplateEditingMode)
if (ep.HandlePreExec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut))
return S_OK;
if(*pguidCmdGroup == CMDSETID_StandardCommandSet97)
{
switch (nCmdID)
{
case cmdidPasteNextTBXCBItem:
if(PasteFromRing() == S_OK)
return S_OK;
break;
case cmdidGotoDefn:
return HandleGotoDef();
case cmdidF1Help:
return HandleHelp();
default:
break;
}
}
if(*pguidCmdGroup == CMDSETID_StandardCommandSet2K)
{
switch (nCmdID)
{
case ECMD_RETURN:
gotEnterKey = true;
break;
case ECMD_INVOKESNIPPETFROMSHORTCUT:
return HandleSnippet();
case ECMD_PARAMINFO:
return HandleMethodTip();
case ECMD_FORMATSELECTION:
return ReindentLines();
case ECMD_COMMENTBLOCK:
case ECMD_COMMENT_BLOCK:
return CommentLines(Source.ForceComment);
case ECMD_UNCOMMENTBLOCK:
case ECMD_UNCOMMENT_BLOCK:
return CommentLines(Source.ForceUncomment);
case ECMD_COMPLETEWORD:
case ECMD_AUTOCOMPLETE:
if(mCodeWinMgr.mSource.IsCompletorActive())
moreCompletions();
else
initCompletion(true);
return S_OK;
case ECMD_SURROUNDWITH:
if (mView && ep)
//ep.DisplayExpansionBrowser(mView, "Insert Snippet", ["type1", "type2"], true, ["kind1", "kind2"], true);
ep.DisplayExpansionBrowser(mView, "Surround with", [], true, [], true);
break;
case ECMD_INSERTSNIPPET:
if (mView && ep)
//ep.DisplayExpansionBrowser(mView, "Insert Snippet", ["type1", "type2"], true, ["kind1", "kind2"], true);
ep.DisplayExpansionBrowser(mView, "Insert Snippet", [], false, [], false);
break;
case ECMD_COMPILE:
return CompileDoc();
case ECMD_GOTOBRACE:
return GotoMatchingPair(false);
case ECMD_GOTOBRACE_EXT:
return GotoMatchingPair(true);
case ECMD_OUTLN_STOP_HIDING_ALL:
return mCodeWinMgr.mSource.StopOutlining();
case ECMD_OUTLN_TOGGLE_ALL:
return mCodeWinMgr.mSource.ToggleOutlining();
default:
break;
}
}
if(g_commandSetCLSID == *pguidCmdGroup)
{
switch (nCmdID)
{
case CmdShowScope:
return showCurrentScope();
case CmdShowMethodTip:
return HandleMethodTip();
case CmdToggleComment:
return CommentLines(Source.AutoComment);
case CmdConvSelection:
return ConvertSelection();
default:
break;
}
}
/+
switch (lo)
{
case OLECMDEXECOPT.OLECMDEXECOPT_SHOWHELP:
if((nCmdexecopt >> 16) == VsMenus.VSCmdOptQueryParameterList) {
return QueryParameterList(ref guidCmdGroup, nCmdId, nCmdexecopt, pvaIn, pvaOut);
}
break;
default:
// On every command, update the tip window if it's active.
if(this.textTipData != null && this.textTipData.IsActive())
textTipData.CheckCaretPosition(this.textView);
int rc = 0;
try {
rc = ExecCommand(ref guidCmdGroup, nCmdId, nCmdexecopt, pvaIn, pvaOut);
} catch (COMException e) {
int hr = e.ErrorCode;
// We silently fail on the following errors because the user has
// most likely already been prompted with things like source control checkout
// dialogs and so forth.
if(hr != (int)TextBufferErrors.BUFFER_E_LOCKED &&
hr != (int)TextBufferErrors.BUFFER_E_READONLY &&
hr != (int)TextBufferErrors.BUFFER_E_READONLY_REGION &&
hr != (int)TextBufferErrors.BUFFER_E_SCC_READONLY) {
throw;
}
}
return rc;
}
return OLECMDERR_E_NOTSUPPORTED;
+/
int rc = mNextTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
if (ep)
if (ep.HandlePostExec(pguidCmdGroup, nCmdID, nCmdexecopt, gotEnterKey, pvaIn, pvaOut))
return rc;
if(*pguidCmdGroup == CMDSETID_StandardCommandSet97)
{
switch (nCmdID)
{
case cmdidPasteNextTBXCBItem:
case cmdidPaste:
ReindentPastedLines();
break;
default:
break;
}
}
if(*pguidCmdGroup == CMDSETID_StandardCommandSet2K)
{
switch (nCmdID)
{
case ECMD_RETURN:
if(!wasCompletorActive)
HandleSmartIndent('\n');
break;
case ECMD_LEFT:
case ECMD_RIGHT:
case ECMD_BACKSPACE:
if(mCodeWinMgr.mSource.IsCompletorActive())
initCompletion(false);
goto case;
case ECMD_UP:
case ECMD_DOWN:
if(mCodeWinMgr.mSource.IsMethodTipActive())
HandleMethodTip();
break;
case ECMD_TYPECHAR:
dchar ch = pvaIn.uiVal;
if(ch == '.' && Package.GetGlobalOptions().expandTrigger >= 1
&& Package.GetGlobalOptions().projectSemantics)
initCompletion(false);
else if(mCodeWinMgr.mSource.IsCompletorActive() || Package.GetGlobalOptions().expandTrigger >= 2)
{
if(isAlphaNum(ch) || ch == '_')
initCompletion(false);
else
mCodeWinMgr.mSource.DismissCompletor();
}
if(ch == '{' || ch == '}' || ch == '[' || ch == ']' ||
ch == 'n' || ch == 't' || ch == 'y') // last characters of "in", "out" and "body"
HandleSmartIndent(ch);
if(mCodeWinMgr.mSource.IsMethodTipActive())
{
if(ch == ',' || ch == ')')
HandleMethodTip();
}
else if(ch == '(')
{
LANGPREFERENCES langPrefs;
if(GetUserPreferences(&langPrefs) == S_OK && langPrefs.fAutoListParams)
_HandleMethodTip(false);
}
break;
default:
break;
}
}
// delayed into idle: HighlightMatchingPairs();
return rc;
}
//////////////////////////////
HRESULT CompileDoc()
{
IVsUIShellOpenDocument pIVsUIShellOpenDocument = queryService!(IVsUIShellOpenDocument);
if(!pIVsUIShellOpenDocument)
return returnError(E_FAIL);
scope(exit) release(pIVsUIShellOpenDocument);
string fname = mCodeWinMgr.mSource.GetFileName();
wchar* wfname = _toUTF16z(fname);
IVsUIHierarchy pUIH;
uint itemid;
IServiceProvider pSP;
VSDOCINPROJECT docInProj;
if(pIVsUIShellOpenDocument.IsDocumentInAProject(wfname, &pUIH, &itemid, &pSP, &docInProj) != S_OK)
return S_OK;
scope(exit) release(pSP);
scope(exit) release(pUIH);
if(!pUIH)
return returnError(E_FAIL);
Project proj = qi_cast!Project(pUIH);
if(!proj)
return S_OK;
CHierNode pNode = proj.VSITEMID2Node(itemid);
if(!pNode)
return returnError(E_INVALIDARG);
CFileNode pFile = cast(CFileNode) pNode;
if(!pFile)
string S_OK;
if(pFile.SaveDoc(SLNSAVEOPT_SaveIfDirty) != S_OK)
return returnError(E_FAIL);
auto solutionBuildManager = queryService!(IVsSolutionBuildManager)();
scope(exit) release(solutionBuildManager);
IVsProjectCfg activeCfg;
scope(exit) release(activeCfg);
if(solutionBuildManager)
if(solutionBuildManager.FindActiveProjectCfg(null, null, proj, &activeCfg) == S_OK)
{
if(Config cfg = qi_cast!Config(activeCfg))
{
scope(exit) release(cfg);
string tool = pFile.GetTool();
string stool = cfg.GetStaticCompileTool(pFile);
if(stool == "DMD")
pFile.SetTool("DMDsingle");
scope(exit) pFile.SetTool(tool);
string cmd = cfg.GetCompileCommand(pFile, true);
if(cmd.length)
{
string workdir = cfg.GetProjectDir();
string outfile = cfg.GetOutputFile(pFile);
string cmdfile = makeFilenameAbsolute(outfile ~ ".syntax", workdir);
removeCachedFileTime(makeFilenameAbsolute(outfile, workdir));
auto pane = getBuildOutputPane();
clearBuildOutputPane();
if(pane)
pane.Activate();
HRESULT hr = RunCustomBuildBatchFile(outfile, cmdfile, cmd, pane, cfg.getBuilder());
}
}
}
return S_OK;
}
//////////////////////////////
void initCompletion(bool autoInsert)
{
CompletionSet cs = mCodeWinMgr.mSource.GetCompletionSet();
Declarations decl = new Declarations;
decl.StartExpansions(mView, mCodeWinMgr.mSource, autoInsert);
}
void moreCompletions()
{
CompletionSet cs = mCodeWinMgr.mSource.GetCompletionSet();
Declarations decl = cs.mDecls;
decl.MoreExpansions(mView, mCodeWinMgr.mSource);
}
int QueryCommandStatus(in GUID *guidCmdGroup, uint cmdID)
{
if(*guidCmdGroup == CMDSETID_StandardCommandSet97)
{
switch (cmdID)
{
case cmdidPasteNextTBXCBItem:
return OLECMDF_SUPPORTED | OLECMDF_ENABLED;
case cmdidGotoDefn:
//case VsCommands.GotoDecl:
//case VsCommands.GotoRef:
return OLECMDF_SUPPORTED | OLECMDF_ENABLED;
default:
break;
}
}
if(*guidCmdGroup == CMDSETID_StandardCommandSet2K)
{
switch (cmdID)
{
case ECMD_PARAMINFO:
case ECMD_FORMATSELECTION:
case ECMD_COMMENTBLOCK:
case ECMD_COMMENT_BLOCK:
case ECMD_UNCOMMENTBLOCK:
case ECMD_UNCOMMENT_BLOCK:
case ECMD_COMPLETEWORD:
case ECMD_INSERTSNIPPET:
case ECMD_INVOKESNIPPETFROMSHORTCUT:
case ECMD_SURROUNDWITH:
case ECMD_AUTOCOMPLETE:
case ECMD_GOTOBRACE:
case ECMD_GOTOBRACE_EXT:
case ECMD_OUTLN_STOP_HIDING_ALL:
case ECMD_OUTLN_TOGGLE_ALL:
case ECMD_COMPILE:
return OLECMDF_SUPPORTED | OLECMDF_ENABLED;
default:
break;
}
}
if(g_commandSetCLSID == *guidCmdGroup)
{
switch (cmdID)
{
case CmdShowScope:
case CmdShowMethodTip:
case CmdToggleComment:
case CmdConvSelection:
return OLECMDF_SUPPORTED | OLECMDF_ENABLED;
default:
break;
}
}
return E_FAIL;
}
int HighlightComment(wstring txt, int line, ref ViewCol idx, out int otherLine, out int otherIndex)
{
int iState, tokidx;
uint pos;
size_t idxpos = idx;
if(Lexer.isStartingComment(txt, idxpos))
{
idx = cast(ViewCol) idxpos;
tokidx = mCodeWinMgr.mSource.FindLineToken(line, idx, iState, pos);
if(pos == idx)
{
int startState = iState;
if(dLex.scan(iState, txt, pos) == TokenCat.Comment)
{
//if(iState == Lexer.toState(Lexer.State.kNestedComment, 1, 0) ||
if(iState == Lexer.State.kWhite)
{
// terminated on same line
otherLine = line;
otherIndex = pos - 2; //assume 2 character comment extro
return S_OK;
}
if(Lexer.isCommentState(Lexer.scanState(iState)))
{
if(mCodeWinMgr.mSource.FindEndOfComment(startState, iState, line, pos))
{
otherLine = line;
otherIndex = pos - 2; //assume 2 character comment extro
return S_OK;
}
}
}
}
}
if(Lexer.isEndingComment(txt, idxpos))
{
idx = cast(ViewCol) idxpos;
tokidx = mCodeWinMgr.mSource.FindLineToken(line, idx, iState, pos);
if(tokidx >= 0)
{
int startState = iState;
uint startpos = pos;
if(dLex.scan(iState, txt, pos) == TokenCat.Comment)
{
if(startState == iState ||
mCodeWinMgr.mSource.FindStartOfComment(startState, line, startpos))
{
otherLine = line;
otherIndex = startpos;
return S_OK;
}
}
/+
int prevpos = pos;
int prevline = line;
Lexer.scan(iState, txt, pos);
if(pos == idx + 2 && iState == Lexer.State.kWhite)
{
while(line > 0)
{
TokenInfo[] lineInfo = mCodeWinMgr.mSource.GetLineInfo(line);
if(tokidx < 0)
tokidx = lineInfo.length - 1;
while(tokidx >= 0)
{
if(lineInfo[tokidx].type != TokenCat.Comment)
{
otherLine = prevline;
otherIndex = prevpos;
return S_OK;
}
prevpos = lineInfo[tokidx].StartIndex;
prevline = line;
tokidx--;
}
line--;
}
}
+/
}
}
return S_FALSE;
}
int HighlightString(wstring txt, int line, ref ViewCol idx, out int otherLine, out int otherIndex)
{
int iState;
uint pos;
auto src = mCodeWinMgr.mSource;
int tokidx = src.FindLineToken(line, idx, iState, pos);
if(tokidx < 0)
return S_FALSE;
uint startPos = pos;
int startState = iState;
int type = dLex.scan(iState, txt, pos);
if(type == TokenCat.String)
{
Lexer.State sstate;
sstate = Lexer.scanState(startState);
if(idx == startPos && !Lexer.isStringState(sstate))
{
if(src.FindEndOfString(startState, iState, line, pos))
{
otherLine = line;
otherIndex = pos - 1;
return S_OK;
}
return S_FALSE;
}
sstate = Lexer.scanState(iState);
if(idx == pos - 1 && !Lexer.isStringState(sstate))
{
if(src.FindStartOfString(startState, line, startPos))
{
otherLine = line;
otherIndex = startPos;
return S_OK;
}
}
}
return S_FALSE;
}
int HighlightMatchingPairs()
{
int line, otherLine;
ViewCol idx, otherIndex;
int highlightLen;
bool checkMismatch;
if(int rc = mView.GetCaretPos(&line, &idx))
return rc;
if(FindMatchingPairs(line, idx, otherLine, otherIndex, highlightLen, checkMismatch) != S_OK)
return S_OK;
TextSpan[2] spans;
spans[0].iStartLine = line;
spans[0].iStartIndex = idx;
spans[0].iEndLine = line;
spans[0].iEndIndex = idx + highlightLen;
spans[1].iStartLine = otherLine;
spans[1].iStartIndex = otherIndex;
spans[1].iEndLine = otherLine;
spans[1].iEndIndex = otherIndex + highlightLen;
// HIGHLIGHTMATCHINGBRACEFLAGS.USERECTANGLEBRACES
HRESULT hr = mView.HighlightMatchingBrace(0, 2, spans.ptr);
if(highlightLen == 1 && checkMismatch)
{
wstring txt = mCodeWinMgr.mSource.GetText(line, idx, line, idx + 1);
wstring otxt = mCodeWinMgr.mSource.GetText(otherLine, otherIndex, otherLine, otherIndex + 1);
if(!otxt.length || !Lexer.isBracketPair(txt[0], otxt[0]))
showStatusBarText("mismatched bracket " ~ otxt);
}
return hr;
}
int FindMatchingPairs(int line, ref ViewCol idx, out int otherLine, out ViewCol otherIndex,
out int highlightLen, out bool checkMismatch)
{
wstring txt = mCodeWinMgr.mSource.GetText(line, 0, line, -1);
if(txt.length <= idx)
return S_FALSE;
highlightLen = 1;
checkMismatch = true;
if(HighlightComment(txt, line, idx, otherLine, otherIndex) == S_OK)
highlightLen = 2;
else if(HighlightString(txt, line, idx, otherLine, otherIndex) == S_OK)
checkMismatch = false;
else if(!Lexer.isOpeningBracket(txt[idx]) &&
!Lexer.isClosingBracket(txt[idx]))
return S_FALSE;
else if(!FindMatchingBrace(line, idx, otherLine, otherIndex))
{
// showStatusBarText("no matching bracket found"w);
return S_FALSE;
}
return S_OK;
}
bool FindMatchingBrace(int line, int idx, out int otherLine, out int otherIndex)
{
int iState;
uint pos;
int tok = mCodeWinMgr.mSource.FindLineToken(line, idx, iState, pos);
if(tok < 0)
return false;
wstring text = mCodeWinMgr.mSource.GetText(line, 0, line, -1);
uint ppos = pos;
int toktype = dLex.scan(iState, text, pos);
if(toktype != TokenCat.Operator)
return false;
if(Lexer.isOpeningBracket(text[ppos]))
return mCodeWinMgr.mSource.FindClosingBracketForward(line, iState, pos, otherLine, otherIndex);
else if(Lexer.isClosingBracket(text[ppos]))
return mCodeWinMgr.mSource.FindOpeningBracketBackward(line, tok, otherLine, otherIndex);
return false;
}
int FindClosingMatchingPairs(out int line, out ViewCol idx, out int otherLine, out ViewCol otherIndex,
out int highlightLen, out bool checkMismatch)
{
if(int rc = mView.GetCaretPos(&line, &idx))
return rc;
int caretLine = line;
int caretIndex = idx;
while(line >= 0)
{
wstring text = mCodeWinMgr.mSource.GetText(line, 0, line, -1);
if(idx < 0)
idx = text.length;
while(--idx >= 0)
{
if(Lexer.isOpeningBracket(text[idx]) ||
text[idx] == '\"' || text[idx] == '`' || text[idx] == '/')
{
if(FindMatchingPairs(line, idx, otherLine, otherIndex, highlightLen, checkMismatch) == S_OK)
if(otherLine > caretLine ||
(otherLine == caretLine && otherIndex > caretIndex))
return S_OK;
}
}
line--;
}
return S_FALSE;
}
int GotoMatchingPair(bool select)
{
int line, otherLine;
ViewCol idx, otherIndex;
int highlightLen;
bool checkMismatch;
if(mView.GetCaretPos(&line, &idx) != S_OK)
return S_FALSE;
if(FindMatchingPairs(line, idx, otherLine, otherIndex, highlightLen, checkMismatch) != S_OK)
if(FindClosingMatchingPairs(line, idx, otherLine, otherIndex, highlightLen, checkMismatch) != S_OK)
return S_OK;
mView.SetCaretPos(otherLine, otherIndex);
TextSpan span;
span.iStartLine = otherLine;
span.iStartIndex = otherIndex;
span.iEndLine = otherLine;
span.iEndIndex = otherIndex + highlightLen;
mView.EnsureSpanVisible(span);
if(select)
mView.SetSelection (line, idx, otherLine, otherIndex + highlightLen);
return S_OK;
}
//////////////////////////////
wstring GetWordAtCaret()
{
int line, idx;
if(mView.GetCaretPos(&line, &idx) != S_OK)
return "";
int startIdx, endIdx;
if(!mCodeWinMgr.mSource.GetWordExtent(line, idx, WORDEXT_CURRENT, startIdx, endIdx))
return "";
return mCodeWinMgr.mSource.GetText(line, startIdx, line, endIdx);
}
ExpansionProvider GetExpansionProvider()
{
return mCodeWinMgr.mSource.GetExpansionProvider();
}
int HandleSnippet()
{
int line, idx;
if(mView.GetCaretPos(&line, &idx) != S_OK)
return S_FALSE;
int startIdx, endIdx;
if(!mCodeWinMgr.mSource.GetWordExtent(line, idx, WORDEXT_CURRENT, startIdx, endIdx))
return S_FALSE;
wstring shortcut = mCodeWinMgr.mSource.GetText(line, startIdx, line, endIdx);
TextSpan ts = TextSpan(startIdx, line, endIdx, line);
string title, path;
ExpansionProvider ep = GetExpansionProvider();
return ep.InvokeExpansionByShortcut(mView, shortcut, ts, true, title, path);
}
//////////////////////////////////////////////////////////////
int showCurrentScope()
{
TextSpan span;
if(mView.GetCaretPos(&span.iStartLine, &span.iStartIndex) != S_OK)
return S_FALSE;
int line = span.iStartLine;
int idx = span.iStartIndex;
int iState;
uint pos;
int tok = mCodeWinMgr.mSource.FindLineToken(line, idx, iState, pos);
wstring curScope;
int otherLine, otherIndex;
Source src = mCodeWinMgr.mSource;
while(src.FindOpeningBracketBackward(line, tok, otherLine, otherIndex))
{
tok = mCodeWinMgr.mSource.FindLineToken(line, otherIndex, iState, pos);
wstring bracket = src.GetText(otherLine, otherIndex, otherLine, otherIndex + 1);
if(bracket == "{"w)
{
wstring fn;
src.findStatementStart(otherLine, otherIndex, fn);
wstring name = src.getScopeIdentifer(otherLine, otherIndex, fn);
if(name.length && name != "{")
{
if(curScope.length)
curScope = "." ~ curScope;
curScope = name ~ curScope;
}
}
line = otherLine;
}
if(curScope.length)
showStatusBarText("Scope: " ~ curScope);
else
showStatusBarText("Scope: at module scope"w);
return S_OK;
}
//////////////////////////////////////////////////////////////
int ConvertSelection()
{
if(convertSelection(mView))
return S_OK;
return S_FALSE;
}
//////////////////////////////////////////////////////////////
int HandleSmartIndent(dchar ch)
{
LANGPREFERENCES langPrefs;
if(int rc = GetUserPreferences(&langPrefs))
return rc;
if(langPrefs.IndentStyle != vsIndentStyleSmart)
return S_FALSE;
int line, idx, len;
if(int rc = mView.GetCaretPos(&line, &idx))
return rc;
if(ch != '\n')
idx--;
else if(mCodeWinMgr.mSource.mBuffer.GetLengthOfLine(line, &len) == S_OK && len > 0)
return ReindentLines();
wstring linetxt = mCodeWinMgr.mSource.GetText(line, 0, line, -1);
int p, orgn = countVisualSpaces(linetxt, langPrefs.uTabSize, &p);
wstring trimmed;
if(std.ascii.isAlpha(ch) && ((trimmed = strip(linetxt)) == "in" || trimmed == "out" || trimmed == "body"))
return ReindentLines();
if(idx > p || (ch != '\n' && linetxt[p] != ch))
return S_FALSE; // do nothing if not at beginning of line
Source.CacheLineIndentInfo cacheInfo;
int n = mCodeWinMgr.mSource.CalcLineIndent(line, ch, &langPrefs, cacheInfo);
if(n < 0 || n == orgn)
return S_OK;
if(ch == '\n')
return mView.SetCaretPos(line, n);
else
return mCodeWinMgr.mSource.doReplaceLineIndent(line, p, n, &langPrefs);
}
int ReindentLines()
{
int iStartLine, iStartIndex, iEndLine, iEndIndex;
int hr = GetSelectionForward(mView, &iStartLine, &iStartIndex, &iEndLine, &iEndIndex);
if(FAILED(hr)) // S_FALSE if no selection, but caret-coordinates returned
return hr;
return ReindentLines(iStartLine, iEndLine);
}
int ReindentLines(int iStartLine, int iEndLine)
{
if(iEndLine < iStartLine)
std.algorithm.swap(iStartLine, iEndLine);
IVsCompoundAction compAct = qi_cast!IVsCompoundAction(mView);
if(compAct)
compAct.OpenCompoundAction("ReindentLines"w.ptr);
int hr = mCodeWinMgr.mSource.ReindentLines(iStartLine, iEndLine);
if(compAct)
{
compAct.CloseCompoundAction();
compAct.Release();
}
return hr;
}
int ReindentPastedLines()
{
if(Package.GetGlobalOptions().pasteIndent)
with(mCodeWinMgr.mSource.mLastTextLineChange)
if(iStartLine != iNewEndLine)
return ReindentLines(iStartLine, iNewEndLine);
return S_OK;
}
//////////////////////////////////////////////////////////////
int CommentLines(int commentMode)
{
int iStartLine, iStartIndex, iEndLine, iEndIndex;
int hr = GetSelectionForward(mView, &iStartLine, &iStartIndex, &iEndLine, &iEndIndex);
if(FAILED(hr)) // S_FALSE if no selection, but caret-coordinates returned
return hr;
if(iEndIndex == 0 && iEndLine > iStartLine)
iEndLine--;
IVsCompoundAction compAct = qi_cast!IVsCompoundAction(mView);
if(compAct)
compAct.OpenCompoundAction("CommentLines"w.ptr);
hr = mCodeWinMgr.mSource.CommentLines(iStartLine, iEndLine, commentMode);
if(compAct)
{
compAct.CloseCompoundAction();
compAct.Release();
}
return hr;
}
//////////////////////////////////////////////////////////////
int PasteFromRing()
{
if(auto svc = queryService!(IVsToolbox, IVsToolboxClipboardCycler))
{
scope(exit) release(svc);
wstring[] entries;
int[] entryIndex;
int cntEntries = 0;
svc.BeginCycle();
IVsToolboxUser tbuser = qi_cast!IVsToolboxUser(mView);
scope(exit) release(tbuser);
BOOL itemsAvailable;
if(svc.AreDataObjectsAvailable(tbuser, &itemsAvailable) == S_OK && itemsAvailable)
{
IDataObject firstDataObject;
IDataObject pDataObject;
while(entries.length < 30 &&
svc.GetAndSelectNextDataObject(tbuser, &pDataObject) == S_OK)
{
scope(exit) release(pDataObject);
if(pDataObject is firstDataObject)
break;
if(!firstDataObject)
firstDataObject = addref(pDataObject);
FORMATETC fmt;
fmt.cfFormat = CF_UNICODETEXT;
fmt.ptd = null;
fmt.dwAspect = DVASPECT_CONTENT;
fmt.lindex = -1;
fmt.tymed = TYMED_HGLOBAL;
STGMEDIUM medium;
if(pDataObject.GetData(&fmt, &medium) == S_OK)
{
if(medium.tymed == TYMED_HGLOBAL)
{
wstring s = UtilGetStringFromHGLOBAL(medium.hGlobal);
.GlobalFree(medium.hGlobal);
s = createPasteString(s);
if(!contains(entries, s))
{
entries ~= s;
entryIndex ~= cntEntries;
}
}
}
cntEntries++;
}
release(firstDataObject);
if(entries.length > 0)
{
TextSpan span;
if(mView.GetCaretPos (&span.iStartLine, &span.iStartIndex) == S_OK)
{
span.iEndLine = span.iStartLine;
span.iEndIndex = span.iStartIndex;
mView.EnsureSpanVisible(span);
POINT pt;
if(mView.GetPointOfLineColumn (span.iStartLine, span.iStartIndex, &pt) == S_OK)
{
int height;
mView.GetLineHeight (&height);
pt.y += height;
HWND hwnd = cast(HWND) mView.GetWindowHandle();
ClientToScreen(hwnd, &pt);
for(int k = 0; k < 10 && k < entries.length; k++)
entries[k] = entries[k] ~ "\t(&" ~ cast(wchar)('0' + ((k + 1) % 10)) ~ ")";
int sel = PopupContextMenu(hwnd, pt, entries);
if(sel >= 0 && sel < entryIndex.length)
{
int cnt = entryIndex[sel];
svc.BeginCycle();
for(int i = 0; i <= cnt; i++)
{
if(svc.GetAndSelectNextDataObject(tbuser, &pDataObject) == S_OK)
release(pDataObject);
}
return E_NOTIMPL; // forward to VS for insert
}
}
}
}
return S_OK; // do not pass to VS, insert cancelled
}
}
return E_NOTIMPL; // forward to VS for insert
}
//////////////////////////////////////////////////////////////
int RemoveUnittests()
{
int endLine, endCol;
mCodeWinMgr.mSource.GetLastLineIndex(endLine, endCol);
wstring wtxt = mCodeWinMgr.mSource.GetText(0, 0, endLine, endCol);
ReplaceOptions opt;
version(none)
{
string txt = to!string(wtxt);
string rtxt = replaceTokenSequence(txt, "unittest { $any }", "", opt, null);
if(txt == rtxt)
return S_OK;
wstring wrtxt = to!wstring(rtxt);
}
else
wstring wrtxt = replaceTokenSequence(wtxt, 1, 0, "unittest { $any }", "", opt, null);
TextSpan changedSpan;
return mCodeWinMgr.mSource.mBuffer.ReplaceLines(0, 0, endLine, endCol, wrtxt.ptr, wrtxt.length, &changedSpan);
}
//////////////////////////////////////////////////////////////
int HandleGotoDef()
{
int line, idx;
if(mView.GetCaretPos(&line, &idx) != S_OK)
return S_FALSE;
string file = mCodeWinMgr.mSource.GetFileName();
wstring impw = mCodeWinMgr.mSource.GetImportModule(line, idx, false);
if(impw.length)
{
string imp = to!string(impw);
imp = replace(imp, ".", "\\") ~ ".d";
HRESULT hr = OpenFileInSolution(imp, -1, file, false);
if(hr != S_OK)
{
imp ~= "i";
hr = OpenFileInSolution(imp, -1, file, false);
}
return hr;
}
string word = toUTF8(GetWordAtCaret());
if(word.length <= 0)
return S_FALSE;
Definition[] defs = Package.GetLibInfos().findDefinition(word);
if(defs.length == 0)
{
showStatusBarText("No definition found for '" ~ word ~ "'");
return S_FALSE;
}
if(defs.length > 1)
{
showStatusBarText("Multiple definitions found for '" ~ word ~ "'");
showSearchWindow(false, word);
return S_FALSE;
}
HRESULT hr = OpenFileInSolution(defs[0].filename, defs[0].line, file, true);
if(hr != S_OK)
showStatusBarText(format("Cannot open %s(%d) for definition of '%s'", defs[0].filename, defs[0].line, word));
return hr;
}
int HandleHelp()
{
string word = toUTF8(GetWordAtCaret());
if(word.length <= 0)
return S_FALSE;
if(!openHelp(word))
showStatusBarText(text("No documentation found for '", word, "'."));
return S_OK;
}
//////////////////////////////////////////////////////////////
int HandleMethodTip()
{
int rc = _HandleMethodTip();
if(rc != S_OK)
mCodeWinMgr.mSource.DismissMethodTip();
return rc;
}
int _HandleMethodTip(bool tryUpper = true)
{
TextSpan span;
if(mView.GetCaretPos(&span.iStartLine, &span.iStartIndex) != S_OK)
return S_FALSE;
int line = span.iStartLine;
int idx = span.iStartIndex;
int iState;
uint pos;
int tok = mCodeWinMgr.mSource.FindLineToken(line, idx, iState, pos);
stepUp:
int otherLine, otherIndex, cntComma;
Source src = mCodeWinMgr.mSource;
if(!src.FindOpeningBracketBackward(line, tok, otherLine, otherIndex, &cntComma))
return S_FALSE;
wstring bracket = src.GetText(otherLine, otherIndex, otherLine, otherIndex + 1);
if(bracket != "("w)
return S_FALSE;
tok = mCodeWinMgr.mSource.FindLineToken(otherLine, otherIndex, iState, pos);
string word = toUTF8(src.FindIdentifierBackward(otherLine, tok));
if(word.length <= 0)
{
line = otherLine;
idx = otherIndex;
if(!tryUpper)
return S_FALSE;
goto stepUp;
}
Definition[] defs = Package.GetLibInfos().findDefinition(word);
if(defs.length == 0)
return S_FALSE;
MethodData md = src.GetMethodData();
span.iEndLine = span.iStartLine;
span.iEndIndex = span.iStartIndex + 1;
md.Refresh(mView, defs, cntComma, span);
return S_OK;
}
// IVsTextViewFilter //////////////////////////////////////
override int GetWordExtent(in int iLine, in CharIndex iIndex, in uint dwFlags, /* [out] */ TextSpan *pSpan)
{
mixin(LogCallMix);
int startIdx, endIdx;
if(!mCodeWinMgr.mSource.GetWordExtent(iLine, iIndex, dwFlags, startIdx, endIdx))
return S_FALSE;
pSpan.iStartLine = iLine;
pSpan.iStartIndex = startIdx;
pSpan.iEndLine = iLine;
pSpan.iEndIndex = endIdx;
return S_OK;
}
override int GetDataTipText( /* [out][in] */ TextSpan *pSpan, /* [out] */ BSTR *pbstrText)
{
mixin(LogCallMix);
HRESULT resFwd = TIP_S_ONLYIFNOMARKER; // enable and prefer TextMarker tooltips
TextSpan span = *pSpan;
if(pSpan.iStartLine == pSpan.iEndLine && pSpan.iStartIndex == pSpan.iEndIndex)
{
if(HRESULT hr = GetWordExtent(pSpan.iStartLine, pSpan.iStartIndex, WORDEXT_CURRENT, pSpan))
return resFwd;
wstring txt = mCodeWinMgr.mSource.GetText(pSpan.iStartLine, 0, pSpan.iStartLine, -1);
L_again:
int idx = pSpan.iStartIndex - 1;
while(idx >= 0 && isWhite(txt[idx]))
idx--;
if(idx >= 0 && txt[idx] == '.')
{
while(idx > 0 && isWhite(txt[idx - 1]))
idx--;
while(idx > 0 && dLex.isIdentifierCharOrDigit(txt[idx - 1]))
idx--;
pSpan.iStartIndex = idx;
goto L_again;
}
}
// when implementing IVsTextViewFilter, VS2010 will no longer ask the debugger
// for tooltips, so we have to do it ourselves
if(IVsDebugger srpVsDebugger = queryService!(IVsDebugger))
{
scope(exit) release(srpVsDebugger);
HRESULT hr = srpVsDebugger.GetDataTipValue(mCodeWinMgr.mSource.mBuffer, pSpan, null, pbstrText);
if(hr == 0x45001) // always returned when debugger active, so no other tooltips then
{
if(IVsCustomDataTip tip = qi_cast!IVsCustomDataTip(srpVsDebugger))
{
scope(exit) release(tip);
if(SUCCEEDED (tip.DisplayDataTip()))
return S_OK;
}
else
return hr;
} // return hr; // this triggers HandoffNoDefaultTipToDebugger
}
version(none) // quick info tooltips not good enough yet
{
string word = toUTF8(mCodeWinMgr.mSource.GetText(pSpan.iStartLine, pSpan.iStartIndex, pSpan.iEndLine, pSpan.iEndIndex));
if(word.length <= 0)
return resFwd;
Definition[] defs = Package.GetLibInfos().findDefinition(word);
if(defs.length == 0)
return resFwd;
string msg = word;
foreach(def; defs)
{
string m = "\n" ~ def.kind ~ "\t" ~ def.filename;
if(def.line > 0)
m ~= ":" ~ to!(string)(def.line);
msg ~= m;
}
*pbstrText = allocBSTR(msg);
}
if(Package.GetGlobalOptions().showTypeInTooltip)
{
if(mPendingSpan == span && mTipRequest == mPendingRequest)
{
*pbstrText = allocBSTR(mTipText);
*pSpan = mTipSpan;
}
else
{
if(mPendingSpan != span)
{
mPendingSpan = span;
mPendingRequest = Package.GetLanguageService().GetTip(mCodeWinMgr.mSource, &span, &OnGetTipText);
}
return E_PENDING;
}
}
return resFwd;
}
override int GetPairExtents(in int iLine, in CharIndex iIndex, /* [out] */ TextSpan *pSpan)
{
mixin(LogCallMix);
return E_NOTIMPL;
}
// IVsTextViewEvents //////////////////////////////////////
override int OnSetFocus(IVsTextView pView)
{
mixin(LogCallMix);
mCodeWinMgr.mLangSvc.mLastActiveView = this;
return S_OK;
}
override int OnKillFocus(IVsTextView pView)
{
mixin(LogCallMix);
if(mCodeWinMgr.mLangSvc.mLastActiveView is this)
mCodeWinMgr.mLangSvc.mLastActiveView = null;
return S_OK;
}
override int OnSetBuffer(IVsTextView pView, IVsTextLines pBuffer)
{
mixin(LogCallMix);
return S_OK;
}
override int OnChangeScrollInfo(IVsTextView pView, in int iBar,
in int iMinUnit, in int iMaxUnits,
in int iVisibleUnits, in int iFirstVisibleUnit)
{
// mixin(LogCallMix);
return S_OK;
}
override int OnChangeCaretLine(IVsTextView pView, in int iNewLine, in int iOldLine)
{
// mixin(LogCallMix);
return S_OK;
}
// IVsExpansionEvents //////////////////////////////////////
override int OnAfterSnippetsUpdate()
{
mixin(LogCallMix);
return S_OK;
}
override int OnAfterSnippetsKeyBindingChange(in uint dwCmdGuid, in uint dwCmdId, in BOOL fBound)
{
mixin(LogCallMix);
return S_OK;
}
//////////////////////////////
TextSpan mPendingSpan;
uint mPendingRequest;
TextSpan mTipSpan;
string mTipText;
uint mTipRequest;
extern(D) void OnGetTipText(uint request, string filename, string text, TextSpan span)
{
mTipText = text;
mTipSpan = span;
mTipRequest = request;
version(none)
{
if(type.length)
{
mTextTipData.Init(mView, type);
mTextTipData.UpdateView();
}
else
mTextTipData.Dismiss();
}
}
bool OnIdle()
{
int line;
ViewCol idx;
if(int rc = mView.GetCaretPos(&line, &idx))
return false;
if(mLastHighlightBracesLine == line && mLastHighlightBracesCol == idx)
return false;
mLastHighlightBracesLine = line;
mLastHighlightBracesCol = idx;
HighlightMatchingPairs();
version(tip)
{
string msg = mCodeWinMgr.mSource.getParseError(line, idx);
if(msg.length)
{
mTextTipData.Init(mView, msg);
mTextTipData.UpdateView();
}
else
mTextTipData.Dismiss();
}
return true;
}
}
class TextTipData : DisposingComObject, IVsTextTipData
{
IVsTextTipWindow mTipWindow;
IVsTextView mTextView;
string mTipText;
bool mDisplayed;
this()
{
mTipText = "Tipp";
auto uuid = uuid_coclass_VsTextTipWindow;
mTipWindow = VsLocalCreateInstance!IVsTextTipWindow (&uuid, sdk.win32.wtypes.CLSCTX_INPROC_SERVER);
if (mTipWindow)
mTipWindow.SetTextTipData(this);
}
override HRESULT QueryInterface(in IID* riid, void** pvObject)
{
if(queryInterface!(IVsTextTipData) (this, riid, pvObject))
return S_OK;
return super.QueryInterface(riid, pvObject);
}
void Init(IVsTextView textView, string tip)
{
Close();
mTextView = textView;
mTipText = tip;
mDisplayed = false;
}
void Close()
{
Dismiss();
}
void Dismiss()
{
if (mDisplayed && mTextView)
mTextView.UpdateTipWindow(mTipWindow, UTW_DISMISS);
OnDismiss();
}
override void Dispose()
{
Close();
if (mTipWindow)
mTipWindow.SetTextTipData(null);
mTipWindow = release(mTipWindow);
}
HRESULT GetTipText (/+[out, custom(uuid_IVsTextTipData, "optional")]+/ BSTR *pbstrText,
/+[out]+/ BOOL *pfGetFontInfo)
{
if(pbstrText)
*pbstrText = allocBSTR(mTipText);
if(pfGetFontInfo)
*pfGetFontInfo = FALSE;
return S_OK;
}
// NOTE: *pdwFontAttr will already have been memset-ed to zeroes, so you can set only the indices that are not normal
HRESULT GetTipFontInfo (in int cChars, /+[out, size_is(cChars)]+/ ULONG *pdwFontAttr)
{
return E_NOTIMPL;
}
HRESULT GetContextStream(/+[out]+/ int *piPos, /+[out]+/ int *piLength)
{
int line, idx, vspace, endpos;
if(HRESULT rc = mTextView.GetCaretPos(&line, &idx))
return rc;
if(HRESULT rc = mTextView.GetNearestPosition(line, idx, piPos, &vspace))
return rc;
*piLength = 1;
return S_OK;
}
HRESULT OnDismiss ()
{
mTextView = null;
mDisplayed = false;
return S_OK;
}
HRESULT UpdateView ()
{
if (mTextView && mTipWindow)
{
mTextView.UpdateTipWindow(mTipWindow, UTW_CONTENTCHANGED);
mDisplayed = true;
}
return S_OK;
}
}
| D |
#!/usr/bin/env rdmd
/*
@author: Wai Yi Leung
@copyright: 2013-2014 Wai Yi Leung
@contact: w.y.leung@e-sensei.nl
@license: MIT Licence
*/
/*
Region definition: a genomic region with at least 2 bases
We summarize the genome regions which have genomic DNA reads aligned,
but they are reported discordant (abnormal insert-size, mate on other chromosome)
*/
import core.atomic;
import core.memory;
import std.array;
import std.algorithm;
import std.datetime;
import std.file;
import std.getopt;
import std.math;
import std.parallelism;
import std.path;
import std.stdio;
import std.string;
import bio.bam.pileup;
import bio.bam.read;
import bio.bam.reader;
import bio.bam.region;
import bio.bam.writer;
import sambamba.utils.common.filtering;
import bam.SortedBamReader;
import yamsvc.datatypes;
import yamsvc.utils;
struct DiscordantCall {
int ref1;
uint s1; // cluster 1 start
uint e1; // cluster 1 end
int ref2;
uint s2; // ditto
uint e2; // ditto
// translation table for orientation:
// 0: FF
// 1: FR
// 2: RF
// 3: RR
ubyte orientation;
ushort pairs_supporting;
static const ushort SEARCH_WINDOW = 500;
string repr() {
auto ret = appender!string();
ret.put( to!string(ref1) ); ret.put(" ");
ret.put( to!string(this.s1) ); ret.put(" ");
ret.put( to!string(this.e1) ); ret.put(" ");
ret.put( to!string(ref2) ); ret.put(" ");
ret.put( to!string(this.s2) ); ret.put(" ");
ret.put( to!string(this.e2) ); ret.put(" ");
ret.put("- orientation: ");
ret.put( to!string(orientation) ); ret.put(" ");
ret.put("- insertsize: ");
ret.put( to!string(this.insertsize) ); ret.put(" ");
ret.put("- DP: ");
ret.put( to!string( this.pairs_supporting ) ); ret.put(" ");
return cast(string) ret.data;
}
@property string toBED( const(ReferenceSequenceInfo)[] refseq ) const {
return format("%s\t%d\t%d\tDP=%d;SVLEN=%d\n%s\t%d\t%d\tDP=%d;SVLEN=%d",
refseq[ref1].name, s1, e1, pairs_supporting, insertsize,
refseq[ref2].name, s2, e2, pairs_supporting, insertsize);
}
this( AlnPair_t pair ) {
this.ref1 = pair.read1.ref_id;
this.s1 = pair.read1.position;
this.e1 = pair.read1.position + pair.read1.basesCovered;
this.ref2 = pair.read2.ref_id;
this.s2 = pair.read2.position;
this.e2 = pair.read2.position + pair.read2.basesCovered;
this.orientation = pair.orientation;
this.pairs_supporting = 1;
}
@property uint scan_till_pos() {
return this.e2 + this.SEARCH_WINDOW;
}
bool overlapping( BamRead other, uint reference_id, uint start, uint end ) const {
if ( other.ref_id != reference_id ) return false;
// compute the start and end of the 'other' first
uint os = other.position;
uint oe = other.position + other.basesCovered;
/** /overlapping by start/
* sccccccccccccccceWWWWWWW <- cluster
* srrrrrrrrrrrrrre <- read
*/
bool overlapping_by_start = start <= os && os <= (end + this.SEARCH_WINDOW);
/** /overlapping by end/
* sccccccccccccccceWWWWWWW <- cluster
* srrrrrrrrrrrrrrre
****/
bool overlapping_by_end = oe >= start && oe <= end + this.SEARCH_WINDOW;
bool enclosed = start <= os && oe <= (end + this.SEARCH_WINDOW);
return overlapping_by_start || overlapping_by_end || enclosed;
}
bool overlaps( AlnPair_t pair ) const {
if ( pair.orientation != this.orientation ) return false;
// writeln(pair.repr());
double size_ratio;
if ( this.insertsize == 0 ) {
size_ratio = cast(double)(pair.insertsize / (this.insertsize+1));
} else {
size_ratio = cast(double)(pair.insertsize / this.insertsize);
}
return ( size_ratio <= 1.1 && size_ratio >= 0.9 ) &&
overlapping( pair.read1, ref1, s1, e1 ) &&
overlapping( pair.read2, ref2, s2, e2 );
}
void merge( AlnPair_t pair ) {
if ( pair.read1.position < s1 ) this.s1 = pair.read1.position;
if ( pair.read2.position < s2 ) this.s2 = pair.read2.position;
uint newE1 = pair.read1.position + pair.read1.basesCovered;
uint newE2 = pair.read2.position + pair.read2.basesCovered;
if ( newE1 > e1 ) this.e1 = newE1;
if ( newE2 > e2 ) this.e2 = newE2;
this.pairs_supporting += 1;
}
bool opEquals()(auto const ref DiscordantCall other) const {
return ( other.ref1 == this.ref1 ) &&
( other.s1 == this.s1 ) &&
( other.e1 == this.e1 ) &&
( other.ref2 == this.ref2 ) &&
( other.s2 == this.s2 ) &&
( other.e2 == this.e2 ) &&
( other.orientation == this.orientation );
}
int opCmp( ref const DiscordantCall other ) const {
if ( this == other ) {
return 0;
} else if ( this.ref1 < other.ref1 ) {
return -1;
} else if ( this.ref2 < other.ref2 ) {
return -1;
} else if ( this.s1 < other.s1 ) {
return -1;
// } else if ( this.e1 < other.e1 ) {
// return -1;
// } else if ( this.s2 < other.s2 ) {
// return -1;
// } else if ( this.e2 < other.e2 ) {
// return -1;
} else {
return 1;
}
}
@property bool is_interchromosomal() const {
return ref1 != ref2;
}
@property int insertsize() const {
// the insert size definition the following pair configurations:
// no insertsize on interchromosomal matings
if( this.is_interchromosomal ) {
return 0;
}
switch( orientation ) {
default:
return 0;
case 0: // FF
return s2 - s1;
case 1: // FR
return e2 - s1;
case 2: // RF
return s2 - e1;
case 3: // RR
return e2 - e1;
}
}
}
unittest {
// testing the DiscordantCall
// first create 3 AlnPair_t to use
}
struct ReadStorage {
private:
BamRead[] _reads;
public:
@property bool empty() const {
return this._reads.length == 0;
}
@property ref BamRead front() {
return this._reads[0];
}
void popFront() {
this._reads = this._reads[1 .. $];
}
void opOpAssign(string op)(BamRead r)
{
mixin("_reads" ~ op ~ "=r;");
}
void add( BamRead r ) {
try {
this._reads ~= r.dup;
}
catch (Exception e) {
stderr.writefln("[Error] %s", e.msg);
}
}
}
ReadInfo fromBamRead( BamRead r ) {
ReadInfo ri = ReadInfo( r );
return ri;
}
void extractReadInfo( string bamfile,
string discordant_bam, // target bam
string calls_file, // target calls file
string bed_file, // target bed file
BamRegion bamregion,
ushort cutoff_min,
ushort cutoff_max,
ushort window_width,
uint estimated_insertsize,
uint estimated_insertsize_stdev,
uint max_sd_degree) {
// stderr.writefln("Entering extract read info %s", bamregion);
BamReader bam;
auto tp = new TaskPool(4);
scope(exit) tp.finish();
try {
bam = new BamReader(bamfile, tp);
} catch (Exception e) {
writefln("[Error] %s", e.msg);
}
auto input_buf_size = 16_000_000;
bam.setBufferSize(input_buf_size);
auto reads = bam.getReadsOverlapping([bamregion]);
BamRead[] contigreads_trans;
BamRead[] contigreads_first;
BamRead[] contigreads_second;
BamRead read;
AlnPair_t pair;
DiscordantCall[] clusters;
DiscordantCall[] clusters_for_reporting;
// resource allocation in memory
static const ushort CAPACITY_SIZE = 10240;
contigreads_trans.reserve(CAPACITY_SIZE * 4);
contigreads_first.reserve(CAPACITY_SIZE);
contigreads_second.reserve(CAPACITY_SIZE);
clusters.reserve(10240);
clusters_for_reporting.reserve(10240);
uint reads_seen = 0;
// defaultPoolThreads(1);
std.datetime.StopWatch sw;
sw.start(); // total time spent on reading all the reads in the region
auto _minireads = tp.map!fromBamRead(
reads
).array();
auto trans_reads = filter!( a => a.transchromosomal == true )(_minireads).array();
auto minireads = filter!( a => a.transchromosomal == false )(_minireads).array();
sw.stop();
std.datetime.StopWatch swsorting;
swsorting.start(); // total time spent on reading all the reads in the region
auto readsFirst = filter!( a => a.first_of_pair == true )(minireads).array();
sort!("a.pos < b.pos")(readsFirst);
auto readsSecond = filter!( a => a.first_of_pair == false )(minireads).array();
sort!("a.mate_pos < b.mate_pos")(readsSecond);
stderr.writefln("Sorting:\t%s\treads in total %d [hns],\t%g [hns]/read",
bamregion,
swsorting.peek().hnsecs,
cast(double) swsorting.peek().hnsecs / minireads.length);
stderr.writefln("Mapped:\t%s\t:%d reads in total %d [hns],\t%g [hns]/read\nFirst:\t%d\tSecond\t%d",
bamregion,
minireads.length,
sw.peek().hnsecs,
cast(double) sw.peek().hnsecs / minireads.length,
readsFirst.length,
readsSecond.length );
ReadInfo[] report_storage;
report_storage.reserve(10240*2);
ReadInfo[] tmp_storage;
tmp_storage.reserve(10240*2);
ReadInfo last_read;
ReadInfo r1;
ReadInfo r2;
AlnPair_t[] cluster_pairs;
cluster_pairs.reserve(10240);
uint cluster_count;
std.datetime.StopWatch sw_matching;
sw_matching.start(); // total time spent on reading all the reads in the region
stderr.writefln("1: %d, 2: %d", readsFirst.length, readsSecond.length );
while ( !readsFirst.empty && !readsSecond.empty ) {
r1 = readsFirst.front;
readsFirst.popFront();
if ( r1.pos != last_read.pos ) {
// dump the tmp_storage to
report_storage ~= tmp_storage;
writefln("cur: %d\tlast: %d", r1.pos, last_read.pos);
foreach( r; tmp_storage) {
writeln(r);
}
tmp_storage.length = 0;
tmp_storage.reserve(1024);
writeln("Restarting tmp storage");
// fill the tmp_storage will all reads second in pair on the particular position of the r1.
// a one time operation
// assume the readsSecond is sorted by mate_pos
while ( readsSecond.front.mate_pos == r1.pos ) {
tmp_storage ~= readsSecond.front;
readsSecond.popFront();
}
}
last_read = r1;
if ( tmp_storage.length == 0 ) {
// no mating reads for this position, move on to next?
report_storage ~= r1;
continue;
}
auto hits = filter!( a => a.name == r1.name )( tmp_storage ).array();
if( hits.length ) {
r2 = hits.front;
writefln("%s\t%s", r1.name, r2.name);
// cluster_pairs ~= AlnPair_t(r1, r2);
cluster_count++;
tmp_storage = filter!( a => a.name != r1.name )( tmp_storage ).array();
} else {
writefln("%d\t%d", tmp_storage.length, hits.length);
// tmp_storage ~= r1;
}
}
stderr.writefln("Matching:\t%s\t%d pairs in total %d [hns],\t%g [hns]/pair",
bamregion,
cluster_count,
sw_matching.peek().hnsecs,
cast(double) sw_matching.peek().hnsecs / cluster_count);
return; // quick hack to not run the code below.
while (!reads.empty) {
reads_seen++;
reads.popFront();
read = reads.front.dup; // duplicate only for low memory usage ?, dereferencing the read, optimize for the popFront
bool found_read = false;
if ( read.ref_id != read.mate_ref_id ) {
if ( contigreads_trans.length == contigreads_trans.capacity ) {
contigreads_trans.reserve( contigreads_trans.length + CAPACITY_SIZE );
}
contigreads_trans ~= read;
continue;
}
// std.datetime.StopWatch sw_matching;
// sw_matching.start(); // total time spent on reading all the reads in the region
BamRead[] workset;
if( read.is_first_of_pair ) {
workset = contigreads_second;
} else {
workset = contigreads_first;
}
uint readposition = read.position;
string readname = read.name;
auto matching = filter!( a =>
a.mate_position == readposition &&
a.name == readname )(workset);
foreach ( BamRead match; matching ) {
found_read = true;
pair = AlnPair_t(match, read);
break;
}
// sw_matching.stop();
// stderr.writefln("%s : %d reads in total %d [hns], %g [hns]/read",
// bamregion,
// workset.length,
// sw_matching.peek().hnsecs,
// cast(double) sw_matching.peek().hnsecs / workset.length );
// if (matching.length > 0) {
// found_read = true;
// pair = AlnPair_t(matching.front, read);
// }
// foreach(int j, BamRead cread; contigreads) {
// if( cread.mate_position != position || cread.name != readname ) continue;
// found_read = true;
// pair = AlnPair_t(cread, read);
// contigreads = std.algorithm.remove( contigreads, j );
// break;
// }
if (!found_read) {
if( read.is_first_of_pair ) {
if ( contigreads_first.length == contigreads_first.capacity ) {
stderr.writefln("1: Capacity old: %d", contigreads_first.capacity);
contigreads_first.reserve( contigreads_first.length + CAPACITY_SIZE );
stderr.writefln("1: Capacity new: %d", contigreads_first.capacity);
}
contigreads_first ~= read;
} else {
if (contigreads_second.length == contigreads_second.capacity ) {
stderr.writefln("2: Capacity old: %d", contigreads_second.capacity);
contigreads_second.reserve( contigreads_second.length + CAPACITY_SIZE );
stderr.writefln("2: Capacity new: %d", contigreads_second.capacity);
}
contigreads_second ~= read;
}
} else { // the read was found
}
if ( reads_seen % CAPACITY_SIZE == 0 ) {
// cleanup the read storage every 10k reads processed.
// using the position of the current read to determine which ones to keep
// ulong now = sw.peek().hnsecs;
// ulong f_seq = contigreads_first.length;
// ulong s_seq = contigreads_second.length;
// stderr.writefln("%d\tReads: \t%d \t1: \t%d \t%d \t2: \t%d \t%d",
// read.position,
// reads_seen,
// contigreads_first.length, contigreads_first.capacity,
// contigreads_second.length, contigreads_second.capacity
// );
contigreads_first = sort!("a.mate_position < b.mate_position")(
filter!( a => a.mate_position >= read.position )(contigreads_first).array()
).array();
contigreads_first.reserve( contigreads_first.length + CAPACITY_SIZE );
contigreads_second = sort!("a.mate_position < b.mate_position")(
filter!( a => a.mate_position >= read.position )(contigreads_second).array()
).array();
contigreads_second.reserve( contigreads_second.length + CAPACITY_SIZE );
// ulong time_lapsed = (sw.peek().hnsecs - now);
// stderr.writefln("%d\tReads: \t%d \t1: \t%d \t%d \t2: \t%d \t%d\t\t%d\t%d\t%d",
// read.position,
// reads_seen,
// contigreads_first.length, contigreads_first.capacity,
// contigreads_second.length, contigreads_second.capacity,
// time_lapsed,
// f_seq - contigreads_first.length,
// s_seq - contigreads_second.length
// );
}
// else {
// bool report = false;
// if( pair.is_unmapped || pair.is_duplicate || pair.is_secondary_alignment ) continue;
//
// // don't use translocational mates for insertsize histogram
// if( pair.is_interchromosomal ) report=true;
//
// uint isize_low = estimated_insertsize - (max_sd_degree * estimated_insertsize_stdev );
// uint isize_high = estimated_insertsize + (max_sd_degree * estimated_insertsize_stdev );
// if( report || pair.insertsize <= isize_low || pair.insertsize >= isize_high ) {
// bool found_pair = false;
// int[] to_remove;
// version(Debug) {
// writefln("Scanning cluster (%d) matching the pair %s", clusters.length, pair.name);
// }
// // remove anything that is not in the scanning window, only if the number of elements is exceeding n=5000
// if ( clusters.length >= 5000 ) {
// clusters_for_reporting ~= clusters.filter!( a => a.scan_till_pos < pair.read1.position ).array();
// clusters = clusters.filter!( a => a.scan_till_pos >= pair.read1.position ).array();
// sort!("a < b")(clusters);
// }
// std.datetime.StopWatch sw_clustering;
// sw_clustering.start(); // measure time spent on seeking matching pair
//
// foreach( int callno, ref DiscordantCall call; clusters ) {
// if( !call.overlaps( pair ) ) continue;
//
// found_pair = true;
// call.merge( pair );
// break;
// }
// sw_clustering.stop();
// writefln("Time iterating over clusters: %d [hns] and %s", sw_clustering.peek().hnsecs, found_pair);
//
// if ( !found_pair ) {
// clusters ~= DiscordantCall( pair );
// } // if not found pair
// } //if in insertsize range or reporting
// } // found read, else ...
} // end while
sw.stop();
stderr.writefln("%s : %d reads in total %d [hns], %g [hns]/read",
bamregion,
reads_seen,
sw.peek().hnsecs,
cast(double) sw.peek().hnsecs / reads_seen );
stdout.writefln("%s : %d reads in total %d [hns], %g [hns]/read",
bamregion,
reads_seen,
sw.peek().hnsecs,
cast(double) sw.peek().hnsecs / reads_seen );
clusters ~= clusters_for_reporting;
auto f = File(calls_file, "w"); // open for writing
auto b = File(bed_file, "w"); // open for writing
sort!("a < b")(clusters);
auto filtered_clusters = filter!(x => x.pairs_supporting >= 4)(clusters);
foreach( DiscordantCall call; filtered_clusters) {
f.writefln("%s", call.repr());
b.writefln("%s", call.toBED( bam.reference_sequences ));
}
auto dst = new BamWriter(discordant_bam, 9); // maximal compression
scope (exit) dst.finish(); // close the stream at exit
dst.writeSamHeader(bam.header); // copy header and reference sequence info
dst.writeReferenceSequenceInfo(bam.reference_sequences);
// writefln( "Unmatched reads: %d in %s, size in mem: %d", contigreads.length, reference_sequence.name(), contigreads.sizeof*contigreads.length );
stderr.writefln("%d transchromosomal reads", contigreads_trans.length);
stdout.writefln("%d transchromosomal reads", contigreads_trans.length);
foreach( BamRead _r; contigreads_trans ) {
dst.writeRecord( _r );
}
foreach( BamRead _r; contigreads_first ) {
dst.writeRecord( _r );
}
foreach( BamRead _r; contigreads_second ) {
dst.writeRecord( _r );
}
}
void scanContig(string bamfile,
string workdir,
ReferenceSequenceInfo reference_sequence,
uint refno,
ushort cutoff_min,
ushort cutoff_max,
ushort window_width,
uint binsize,
uint estimated_insertsize,
uint estimated_insertsize_stdev,
uint max_sd_degree,
uint threads) {
// stderr.writefln("Starting analysis of %s", reference_sequence.name);
// stderr.writefln("Read bam %s for %s", bamfile, reference_sequence.name);
// we create 2 files in the workdir:
// new bam with only the discordant reads (for debugging)
// CallRegion file with the plain calls without normalisation and filtering
// just compose the filename over here and pass them to the analysis module.
string cleaned_ref_name = replace(reference_sequence.name,"|","_");
string wd = absolutePath(workdir ~ "/" ~ cleaned_ref_name ~ "/");
// first make the workdir
if ( !std.file.exists(wd) ) {
try {
mkdirRecurse( wd );
}
catch (Exception e) {
// fail silently, since the directory could be created by other scanContig threads
// stderr.writefln("[Error] %s", e.msg);
}
}
uint searchbins = reference_sequence.length / binsize;
// auto tp = new TaskPool(1);
// scope(exit) tp.finish();
// stderr.writefln("[Debug] Chromosome %s len: %d, bins: %d, maxsize: %d", reference_sequence.name, reference_sequence.length, searchbins, (searchbins+1)*binsize);
foreach( uint bin; 0 .. searchbins+1 ) {
uint start = 0 + (bin*binsize);
uint end = start + binsize;
if (end > reference_sequence.length) {
end = reference_sequence.length;
}
// stderr.writefln("%s %d %d %d", reference_sequence.name, reference_sequence.length, start, end);
BamRegion bamregion = BamRegion( refno, start, end );
// stderr.writefln("Bam region: %s", bamregion);
string discordant_bam = absolutePath( wd ~ "/" ~ cleaned_ref_name ~ "." ~ to!string(bin) ~ ".bam" );
string calls = absolutePath( wd ~ "/" ~ cleaned_ref_name ~ "." ~ to!string(bin) ~ ".calls" );
string bedfile = absolutePath( wd ~ "/" ~ cleaned_ref_name ~ "." ~ to!string(bin) ~ ".bed" );
// auto t = task!
extractReadInfo(bamfile,
discordant_bam,
calls,
bedfile,
bamregion,
cutoff_min,
cutoff_max,
window_width,
estimated_insertsize,
estimated_insertsize_stdev,
max_sd_degree);
// tp.put(t);
}
// writefln("Writing new bam to %s", discordant_bam);
}
void printUsage() {
int n_threads = std.parallelism.totalCPUs;
stderr.writeln("Usage: yamsvp-bedregion [options] <input.bam | input.sam>");
stderr.writeln();
stderr.writeln("Options: -T, --threads=NTHREADS");
stderr.writefln(" maximum number of threads to use [%d]", n_threads);
stderr.writeln(" -w, --window=WINDOWWIDTH");
stderr.writeln(" width of window (bp) determing overlap [200]");
stderr.writeln(" -b, --binsize=BINSIZE");
stderr.writeln(" width of bin (bp) to scan [10_000_000]");
stderr.writeln(" -l, --cutoff_min");
stderr.writeln(" low threshold for reads covering a breakpoint [2]");
stderr.writeln(" -h, --cutoff_max");
stderr.writeln(" high threshold for reads covering a breakpoint [90]");
// stderr.writeln(" -o, --bam_output=BAMOUTPUT");
// stderr.writeln(" Write the resulting bam to ...");
stderr.writeln(" -l, --compression_level");
stderr.writeln(" compression level 1-9 (low-high) of bam file [9]");
stderr.writeln(" -r, --reads_for_histogram");
stderr.writeln(" reads used to determine insert-size, a minimum of 10_000 is recomended [10_000]");
stderr.writeln(" -d, --max_sd_degree");
stderr.writeln(" set degree of sd allowed to mark as concordant read in the insertsize [2]");
stderr.writeln(" -v, --verbose");
stderr.writeln(" Turn on verbose mode");
}
int main(string[] args) {
int n_threads = std.parallelism.totalCPUs;
uint binsize = 10_000_000;
ushort window_width = 200;
ushort cutoff_max = 90;
ushort cutoff_min = 2;
uint estimated_insertsize = 450;
uint estimated_insertsize_stdev = 15;
uint max_sd_degree = 4;
ubyte compression_level = 9;
uint reads_for_histogram = 10_000;
string bam_outputfilename;
string bed_filename;
bool verbose;
string workdir = "./work/";
getopt(
args,
std.getopt.config.caseSensitive,
"threads|T", &n_threads, // numeric
"window|w", &window_width, // numeric
"binsize|b", &binsize, // numeric
"cutoff_max|h", &cutoff_max, // numeric
"cutoff_min|l", &cutoff_min, // numeric
"bamoutput|o", &bam_outputfilename,
"compression_level|l", &compression_level, // numeric
"insertsize|i", &estimated_insertsize, // numeric
"insertsd|s", &estimated_insertsize_stdev, // numeric
"reads_for_histogram|r", &reads_for_histogram, // numeric
"max_sd_degree|d", &max_sd_degree, // numeric
"workdir|W", &workdir, // flag
"verbose|v", &verbose, // flag
);
if (args.length < 2) {
printUsage();
return 0;
}
// std.parallelism.defaultPoolThreads = n_threads;
// int working_threads = n_threads;
int working_threads = n_threads;
// if ( n_threads > 1 ) {
// working_threads = cast(int)std.math.ceil( cast(float)(n_threads/2.0) );
// }
auto task_pool = new TaskPool( working_threads );
scope(exit) task_pool.finish();
string _bamfilename = args[1];
auto bam = new BamReader(_bamfilename );
auto src = new SortedBamReader( bam );
// Fix index, we need this for random access
if( !src.has_index ) {
stderr.writeln("No bai index found, creating one now....");
src.createIndex();
}
Histogram h = Histogram();
auto _reads = src.reads;
auto limit = reads_for_histogram;
int counter = 0;
foreach( AlnPair_t pair; _reads) {
++counter;
if( pair.is_duplicate ) continue;
if( pair.is_secondary_alignment) continue;
if( pair.is_unmapped ) continue;
// don't use translocational mates for insertsize histogram
if( pair.is_interchromosomal ) continue;
limit--;
h.add( std.math.abs( pair.insertsize ) );
// h.add( std.math.abs(read.template_length) );
if (limit == 0){
break;
}
}
auto stat = h._recompute();
stderr.writefln("Histogram range: %d .. %d", h.min , h.max);
stderr.writefln("Histogram width: %d", h.width);
stderr.writefln("Histogram records: %d", h.size);
stderr.writefln("Histogram median: %s", h.median);
stderr.writefln("Histogram q25: %s", h.q25);
stderr.writefln("Histogram q50: %s", h.q50);
stderr.writefln("Histogram q75: %s", h.q75);
stderr.writefln("Histogram mean: %s", h.mean);
stderr.writefln("Histogram sd: %s", h.sd);
ReferenceSequenceInfo[] ref_seqs;
ref_seqs = src.reference_sequences.dup;
// sort!("a.length > b.length")(ref_seqs);
// writefln("Refseqs: %s", ref_seqs);
foreach (int refno, ReferenceSequenceInfo refseq; ref_seqs) {
if ( canFind( refseq.name, "_" ) ) {
continue;
}
// stderr.writefln("Queuing task for contig %s", refseq.name);
auto t = task!scanContig(_bamfilename,
buildNormalizedPath(absolutePath(workdir)),
refseq,
refno,
cutoff_min,
cutoff_max,
window_width,
binsize,
h.q50,
cast(uint) h.sd,
max_sd_degree,
n_threads);
task_pool.put(t);
}
return 0;
}
| D |
//Written in the D programming language
/++
Module containing Date/Time functionality.
This module provides:
$(UL
$(LI Types to represent points in time: $(D SysTime), $(D Date),
$(D TimeOfDay), and $(D DateTime).)
$(LI Types to represent intervals of time.)
$(LI Types to represent ranges over intervals of time.)
$(LI Types to represent time zones (used by $(D SysTime)).)
$(LI A platform-independent, high precision stopwatch type:
$(D StopWatch))
$(LI Benchmarking functions.)
$(LI Various helper functions.)
)
Closely related to std.datetime is <a href="core_time.html">$(D core.time)</a>,
and some of the time types used in std.datetime come from there - such as
$(CXREF time, Duration), $(CXREF time, TickDuration), and
$(CXREF time, FracSec). So, you may want to look at its documentation as
well. However, core.time is publically imported into std.datetime, so you
don't have to import it separately.
Three of the main concepts used in this module are time points, time
durations, and time intervals.
A time point is a specific point in time. e.g. January 5th, 2010
or 5:00.
A time duration is a length of time with units. e.g. 5 days or 231 seconds.
A time interval indicates a period of time associated with a fixed point in
time. So, it is either two time points associated with each other,
indicating the time starting at the first point up to, but not including,
the second point - e.g. [January 5th, 2010 - March 10th, 2010$(RPAREN) - or
it is a time point and a time duration associated with one another. e.g.
January 5th, 2010 and 5 days, indicating [January 5th, 2010 -
January 10th, 2010$(RPAREN).
Various arithmetic operations are supported between time points and
durations (e.g. the difference between two time points is a time duration),
and ranges can be gotten from time intervals, so range-based operations may
be done on a series of time points.
The types that the typical user is most likely to be interested in are
$(D Date) (if they want dates but don't care about time), $(D DateTime)
(if they want dates and times but don't care about time zones), $(D SysTime)
(if they want the date and time from the OS and/or do care about time
zones), and StopWatch (a platform-independent, high precision stop watch).
$(D Date) and $(D DateTime) are optimized for calendar-based operations,
while $(D SysTime) is designed for dealing with time from the OS. Check out
their specific documentation for more details.
To get the current time, use $(D Clock.currTime). It will return the current
time as a $(D SysTime). If you want to print it, $(D toString) is
sufficient, but if you use $(D toISOString), $(D toISOExtString), or
$(D toSimpleString), you can use the corresponding $(D fromISOString),
$(D fromISOExtString), or $(D fromISOExtString) to create a
$(D SysTime) from the string.
--------------------
auto currentTime = Clock.currTime();
auto timeString = currentTime.toISOExtString();
auto restoredTime = SysTime.fromISOExtString(timeString);
--------------------
Various functions take a string (or strings) to represent a unit of time
(e.g. $(D convert!("days", "hours")(numDays))). The valid strings to use
with such functions are $(D "years"), $(D "months"), $(D "weeks"),
$(D "days"), $(D "hours"), $(D "minutes"), $(D "seconds"),
$(D "msecs") (milliseconds), $(D "usecs") (microseconds),
$(D "hnsecs") (hecto-nanoseconds - i.e. 100 ns), or some subset thereof.
There are a few functions in core.time which take $(D "nsecs"), but because
nothing in std.datetime has precision greater than hnsecs, and very little
in core.time does, no functions in std.datetime accept $(D "nsecs"). If
you need help remembering which units are abbreviated and which aren't,
notice that all units seconds and greater use their full names, and all
sub-second units are abbreviated (since they'd be rather long if they
weren't).
If you're looking for the definitions of $(D Duration), $(D TickDuration),
or $(D FracSec), they're in core.time.
Note:
$(D DateTimeException) is an alias for core.time's $(D TimeException),
so you don't need to worry about core.time functions and std.datetime
functions throwing different exception types (except in the rare case
that they throw something other than $(D TimeException) or
$(D DateTimeException)).
See_Also:
$(WEB en.wikipedia.org/wiki/ISO_8601, ISO 8601)
$(WEB en.wikipedia.org/wiki/Tz_database, Wikipedia entry on TZ Database)
$(WEB en.wikipedia.org/wiki/List_of_tz_database_time_zones,
List of Time Zones)
Copyright: Copyright 2010 - 2011
License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Jonathan M Davis and Kato Shoichi
Source: $(PHOBOSSRC std/_datetime.d)
+/
module std.datetime;
public import core.time;
import core.exception;
import core.stdc.time;
import std.array;
import std.algorithm;
import std.ascii;
import std.conv;
import std.exception;
import std.file;
import std.functional;
import std.math;
import std.metastrings;
import std.path;
import std.range;
import std.stdio;
import std.string;
import std.system;
import std.traits;
version(Windows)
{
import core.sys.windows.windows;
import std.c.windows.winsock;
//For system call to access the registry.
pragma(lib, "advapi32.lib");
}
else version(Posix)
{
import core.sys.posix.arpa.inet;
import core.sys.posix.stdlib;
import core.sys.posix.time;
import core.sys.posix.sys.time;
//We need to disable many tests because building all of Phobos
//with all of std.datetime's unit tests enables currently causes
//dmd to run out of memory.
//Regardless of that, however, it's also useful to be able to
//easily turn the tests on and off.
version = testStdDateTime;
}
version(unittest)
{
import std.c.string;
import std.stdio;
}
//I'd just alias it to indexOf, but
//http://d.puremagic.com/issues/show_bug.cgi?id=6013 would mean that that would
//pollute the global namespace. So, for now, I've created an alias which is
//highly unlikely to conflict with anything that anyone else is doing.
private alias std.string.indexOf stds_indexOf;
//Verify module example.
version(testStdDateTime) unittest
{
auto currentTime = Clock.currTime();
auto timeString = currentTime.toISOExtString();
auto restoredTime = SysTime.fromISOExtString(timeString);
}
//Verify Examples for core.time.Duration which couldn't be in core.time.
unittest
{
assert(std.datetime.Date(2010, 9, 7) + dur!"days"(5) ==
std.datetime.Date(2010, 9, 12));
assert(std.datetime.Date(2010, 9, 7) - std.datetime.Date(2010, 10, 3) ==
dur!"days"(-26));
}
//Note: There various functions which void as their return type and ref of the
// struct type which they're in as a commented out return type. Ideally,
// they would return the ref, but there are several dmd bugs which prevent
// that, relating to both ref and invariants. So, I've left the ref return
// types commented out with the idea that those functions can be made to
// return a ref to this once those bugs have been fixed.
//==============================================================================
// Section with public enums and constants.
//==============================================================================
/++
Represents the 12 months of the Gregorian year (January is 1).
+/
enum Month : ubyte { jan = 1, ///
feb, ///
mar, ///
apr, ///
may, ///
jun, ///
jul, ///
aug, ///
sep, ///
oct, ///
nov, ///
dec ///
}
/++
Represents the 7 days of the Gregorian week (Sunday is 0).
+/
enum DayOfWeek : ubyte { sun = 0, ///
mon, ///
tue, ///
wed, ///
thu, ///
fri, ///
sat ///
}
/++
In some date calculations, adding months or years can cause the date to fall
on a day of the month which is not valid (e.g. February 29th 2001 or
June 31st 2000). If overflow is allowed (as is the default), then the month
will be incremented accordingly (so, February 29th 2001 would become
March 1st 2001, and June 31st 2000 would become July 1st 2000). If overflow
is not allowed, then the day will be adjusted to the last valid day in that
month (so, February 29th 2001 would become February 28th 2001 and
June 31st 2000 would become June 30th 2000).
AllowDayOverflow only applies to calculations involving months or years.
+/
enum AllowDayOverflow
{
/// No, don't allow day overflow.
no,
/// Yes, allow day overflow.
yes
}
/++
Indicates a direction in time. One example of its use is $(D Interval)'s
$(D expand) function which uses it to indicate whether the interval should
be expanded backwards (into the past), forwards (into the future), or both.
+/
enum Direction
{
/// Backward.
bwd,
/// Forward.
fwd,
/// Both backward and forward.
both
}
/++
Used to indicate whether $(D popFront) should be called immediately upon
creating a range. The idea is that for some functions used to generate a
range for an interval, $(D front) is not necessarily a time point which
would ever be generated by the range, and if you want the first time point
in the range to match what the function generates, then you use
$(D PopFirst.yes) to indicate that the range should have $(D popFront)
called on it before the range is returned so that $(D front) is a time point
which the function would generate.
For instance, if the function used to generate a range of time points
generated successive Easters (i.e. you're iterating over all of the Easters
within the interval), the initial date probably isn't an Easter. By using
$(D PopFirst.yes), you would be telling the function which returned the
range that you wanted $(D popFront) to be called so that front would then be
an Easter - the next one generated by the function (which if you were
iterating forward, would be the Easter following the original $(D front),
while if you were iterating backward, it would be the Easter prior to the
original $(D front)). If $(D PopFirst.no) were used, then $(D front) would
remain the original time point and it would not necessarily be a time point
which would be generated by the range-generating function (which in many
cases is exactly what you
want - e.g. if you were iterating over every day starting at the beginning
of the interval).
+/
enum PopFirst
{
/// No, don't call popFront() before returning the range.
no,
/// Yes, call popFront() before returning the range.
yes
}
/++
Used by StopWatch to indicate whether it should start immediately upon
construction.
+/
enum AutoStart
{
/// No, don't start the StopWatch when it is constructed.
no,
/// Yes, do start the StopWatch when it is constructed.
yes
}
/++
Array of the strings representing time units, starting with the smallest
unit and going to the largest. It does not include $(D "nsecs").
Includes $(D "hnsecs") (hecto-nanoseconds (100 ns)),
$(D "usecs") (microseconds), $(D "msecs") (milliseconds), $(D "seconds"),
$(D "minutes"), $(D "hours"), $(D "days"), $(D "weeks"), $(D "months"), and
$(D "years")
+/
immutable string[] timeStrings = ["hnsecs", "usecs", "msecs", "seconds", "minutes",
"hours", "days", "weeks", "months", "years"];
//==============================================================================
// Section with other types.
//==============================================================================
/++
Exception type used by std.datetime. It's an alias to TimeException, which
is what core.time uses. So, you can catch either and not worry about which
module it came from.
+/
alias TimeException DateTimeException;
/++
Effectively a namespace to make it clear that the methods it contains are
getting the time from the system clock. It cannot be instantiated.
+/
final class Clock
{
public:
/++
Returns the current time in the given time zone.
Throws:
$(D ErrnoException) (on Posix) or $(D Exception) (on Windows)
if it fails to get the time of day.
+/
static SysTime currTime(immutable TimeZone tz = LocalTime())
{
return SysTime(currStdTime, tz);
}
version(testStdDateTime) unittest
{
assert(currTime(UTC()).timezone is UTC());
//I have no idea why, but for some reason, Windows/Wine likes to get
//time_t wrong when getting it with core.stdc.time.time. On one box
//I have (which has its local time set to UTC), it always gives time_t
//in the real local time (America/Los_Angeles), and after the most recent
//DST switch, every Windows box that I've tried it in is reporting
//time_t as being 1 hour off of where it's supposed to be. So, I really
//don't know what the deal is, but given what I'm seeing, I don't trust
//core.stdc.time.time on Windows, so I'm just going to disable this test
//on Windows.
version(Posix)
{
immutable unixTimeD = currTime().toUnixTime();
immutable unixTimeC = core.stdc.time.time(null);
immutable diff = unixTimeC - unixTimeD;
_assertPred!">="(diff, -2);
_assertPred!"<="(diff, 2);
}
}
/++
Returns the number of hnsecs since midnight, January 1st, 1 A.D. for the
current time.
Throws:
$(D DateTimeException) if it fails to get the time.
+/
@trusted
static @property long currStdTime()
{
version(Windows)
{
//FILETIME represents hnsecs from midnight, January 1st, 1601.
enum hnsecsFrom1601 = 504_911_232_000_000_000L;
FILETIME fileTime;
GetSystemTimeAsFileTime(&fileTime);
ulong tempHNSecs = fileTime.dwHighDateTime;
tempHNSecs <<= 32;
tempHNSecs |= fileTime.dwLowDateTime;
return cast(long)tempHNSecs + hnsecsFrom1601;
}
else version(Posix)
{
enum hnsecsToUnixEpoch = 621_355_968_000_000_000L;
static if(is(typeof(clock_gettime)))
{
timespec ts;
if(clock_gettime(CLOCK_REALTIME, &ts) != 0)
throw new TimeException("Failed in clock_gettime().");
return convert!("seconds", "hnsecs")(ts.tv_sec) +
ts.tv_nsec / 100 +
hnsecsToUnixEpoch;
}
else
{
timeval tv;
if(gettimeofday(&tv, null) != 0)
throw new TimeException("Failed in gettimeofday().");
return convert!("seconds", "hnsecs")(tv.tv_sec) +
convert!("usecs", "hnsecs")(tv.tv_usec) +
hnsecsToUnixEpoch;
}
}
}
/++
The current system tick. The number of ticks per second varies from
system to system. currSystemTick uses a monotonic clock, so it's
intended for precision timing by comparing relative time values, not
for getting the current system time.
Warning:
On some systems, the monotonic clock may stop counting when
the computer goes to sleep or hibernates. So, the monotonic
clock could be off if that occurs. This is known to happen
on Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
Throws:
$(D DateTimeException) if it fails to get the time.
+/
@safe
static @property TickDuration currSystemTick()
{
return TickDuration.currSystemTick();
}
version(testStdDateTime) unittest
{
assert(Clock.currSystemTick.length > 0);
}
/++
The current number of system ticks since the application started.
The number of ticks per second varies from system to system.
This uses a monotonic clock.
Warning:
On some systems, the monotonic clock may stop counting when
the computer goes to sleep or hibernates. So, the monotonic
clock could be off if that occurs. This is known to happen
on Mac OS X. It has not been tested whether it occurs on
either Windows or on Linux.
Throws:
$(D DateTimeException) if it fails to get the time.
+/
@safe
static @property TickDuration currAppTick()
{
return currSystemTick - TickDuration.appOrigin;
}
version(testStdDateTime) unittest
{
auto a = Clock.currSystemTick;
auto b = Clock.currAppTick;
assert(a.length);
assert(b.length);
assert(a > b);
}
private:
@disable this() {}
}
//==============================================================================
// Section with time points.
//==============================================================================
/++
$(D SysTime) is the type used when you want to get the current time from the
system or if you're doing anything that involves time zones. Unlike
$(D DateTime), the time zone is an integral part of $(D SysTime) (though if
all you care about is local time, you can pretty much ignore time zones, and
it will work, since it defaults to using the local time zone). It holds its
internal time in std time (hnsecs since midnight, January 1st, 1 A.D. UTC),
so it interfaces well with the system time. However, that means that, unlike
$(D DateTime), it is not optimized for calendar-based operations, and
getting individual units from it such as years or days is going to involve
conversions and be less efficient.
Basically, if you care about calendar-based operations and don't
necessarily care about time zones, then $(D DateTime) would be the type to
use. However, if what you care about is the system time, then $(D SysTime)
would be the type to use.
$(D Clock.currTime) will return the current time as a $(D SysTime). If you
want to convert a $(D SysTime) to a $(D Date) or $(D DateTime), simply cast
it. And if you ever want to convert a $(D Date) or $(D DateTime) to a
$(D SysTime), use $(D SysTime)'s constructor, and you can pass in the
intended time zone with it (or don't pass in a $(D TimeZone), and the local
time zone will be used). Be aware, however, that converting from a
$(D DateTime) to a $(D SysTime) will not necessarily be 100% accurate due to
DST (one hour of the year doesn't exist and another occurs twice). So, if
you don't want to risk any conversion errors, keep your times as
$(D SysTime)s. Aside from DST though, there shouldn't be any conversion
problems.
If you care about using time zones other than local time or UTC, you can use
$(D PosixTimeZone) on Posix systems (or on Windows, if you provide the TZ
Database files), and you can use $(D WindowsTimeZone) on Windows systems.
The time in $(D SysTime) is kept internally in hnsecs from midnight,
January 1st, 1 A.D. UTC. So, you never get conversion errors when changing
the time zone of a $(D SysTime). $(D LocalTime) is the $(D TimeZone) class
which represents the local time, and $(D UTC) is the $(D TimeZone) class
which represents UTC. $(D SysTime) uses $(D LocalTime) if no $(D TimeZone)
is provided. For more details on time zones, look at the documentation for
$(D TimeZone), $(D PosixTimeZone), and $(D WindowsTimeZone).
$(D SysTime)'s range is from approximately 29,000 B.C. to approximately
29,000 A.D.
+/
struct SysTime
{
public:
/++
Params:
dateTime = The $(D DateTime) to use to set this $(D SysTime)'s
internal std time. As $(D DateTime) has no concept of
time zone, tz is used as its time zone.
tz = The $(D TimeZone) to use for this $(D SysTime). If null,
$(D LocalTime) will be used. The given $(D DateTime) is
assumed to be in the given time zone.
+/
this(in DateTime dateTime, immutable TimeZone tz = null) nothrow
{
try
this(dateTime, FracSec.from!"hnsecs"(0), tz);
catch(Exception e)
assert(0, "FracSec's constructor threw when it shouldn't have.");
}
version(testStdDateTime) unittest
{
static void test(DateTime dt, immutable TimeZone tz, long expected)
{
auto sysTime = SysTime(dt, tz);
_assertPred!"=="(sysTime._stdTime, expected);
assert(sysTime._timezone is (tz is null ? LocalTime() : tz),
format("Given DateTime: %s", dt));
}
test(DateTime.init, UTC(), 0);
test(DateTime(1, 1, 1, 12, 30, 33), UTC(), 450_330_000_000L);
test(DateTime(0, 12, 31, 12, 30, 33), UTC(), -413_670_000_000L);
test(DateTime(1, 1, 1, 0, 0, 0), UTC(), 0);
test(DateTime(1, 1, 1, 0, 0, 1), UTC(), 10_000_000L);
test(DateTime(0, 12, 31, 23, 59, 59), UTC(), -10_000_000L);
test(DateTime(1, 1, 1, 0, 0, 0), new SimpleTimeZone(-60),
36_000_000_000L);
test(DateTime(1, 1, 1, 0, 0, 0), new SimpleTimeZone(0), 0);
test(DateTime(1, 1, 1, 0, 0, 0), new SimpleTimeZone(60),
-36_000_000_000L);
}
/++
Params:
dateTime = The $(D DateTime) to use to set this $(D SysTime)'s
internal std time. As $(D DateTime) has no concept of
time zone, tz is used as its time zone.
fracSec = The fractional seconds portion of the time.
tz = The $(D TimeZone) to use for this $(D SysTime). If null,
$(D LocalTime) will be used. The given $(D DateTime) is
assumed to be in the given time zone.
Throws:
$(D DateTimeException) if $(D fracSec) is negative.
+/
this(in DateTime dateTime, in FracSec fracSec, immutable TimeZone tz = null)
{
immutable fracHNSecs = fracSec.hnsecs;
enforce(fracHNSecs >= 0, new DateTimeException("A SysTime cannot have negative fractional seconds."));
_timezone = tz is null ? LocalTime() : tz;
try
{
immutable dateDiff = (dateTime.date - Date(1, 1, 1)).total!"hnsecs";
immutable todDiff = (dateTime.timeOfDay - TimeOfDay(0, 0, 0)).total!"hnsecs";
immutable adjustedTime = dateDiff + todDiff + fracHNSecs;
immutable standardTime = _timezone.tzToUTC(adjustedTime);
this(standardTime, _timezone.get);
}
catch(Exception e)
{
assert(0, "Date, TimeOfDay, or DateTime's constructor threw when " ~
"it shouldn't have.");
}
}
version(testStdDateTime) unittest
{
static void test(DateTime dt,
FracSec fracSec,
immutable TimeZone tz,
long expected)
{
auto sysTime = SysTime(dt, fracSec, tz);
_assertPred!"=="(sysTime._stdTime, expected);
assert(sysTime._timezone is (tz is null ? LocalTime() : tz),
format("Given DateTime: %s, Given FracSec: %s", dt, fracSec));
}
test(DateTime.init, FracSec.init, UTC(), 0);
test(DateTime(1, 1, 1, 12, 30, 33), FracSec.init, UTC(), 450_330_000_000L);
test(DateTime(0, 12, 31, 12, 30, 33), FracSec.init, UTC(), -413_670_000_000L);
test(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(1), UTC(), 10_000L);
test(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"msecs"(999), UTC(), -10_000L);
test(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999), UTC(), -1);
test(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(1), UTC(), -9_999_999);
test(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0), UTC(), -10_000_000);
assertThrown!DateTimeException(SysTime(DateTime.init, FracSec.from!"hnsecs"(-1), UTC()));
}
/++
Params:
date = The $(D Date) to use to set this $(D SysTime)'s internal std
time. As $(D Date) has no concept of time zone, tz is used as
its time zone.
tz = The $(D TimeZone) to use for this $(D SysTime). If null,
$(D LocalTime) will be used. The given $(D Date) is assumed
to be in the given time zone.
+/
this(in Date date, immutable TimeZone tz = null) nothrow
{
_timezone = tz is null ? LocalTime() : tz;
try
{
immutable adjustedTime = (date - Date(1, 1, 1)).total!"hnsecs";
immutable standardTime = _timezone.tzToUTC(adjustedTime);
this(standardTime, _timezone.get);
}
catch(Exception e)
assert(0, "Date's constructor through when it shouldn't have.");
}
version(testStdDateTime) unittest
{
static void test(Date d, immutable TimeZone tz, long expected)
{
auto sysTime = SysTime(d, tz);
_assertPred!"=="(sysTime._stdTime, expected);
assert(sysTime._timezone is (tz is null ? LocalTime() : tz),
format("Given Date: %s", d));
}
test(Date.init, UTC(), 0);
test(Date(1, 1, 1), UTC(), 0);
test(Date(1, 1, 2), UTC(), 864000000000);
test(Date(0, 12, 31), UTC(), -864000000000);
}
/++
Note:
Whereas the other constructors take in the given date/time, assume
that it's in the given time zone, and convert it to hnsecs in UTC
since midnight, January 1st, 1 A.D. UTC - i.e. std time - this
constructor takes a std time, which is specifically already in UTC,
so no conversion takes place. Of course, the various getter
properties and functions will use the given time zone's conversion
function to convert the results to that time zone, but no conversion
of the arguments to this constructor takes place.
Params:
stdTime = The number of hnsecs since midnight, January 1st, 1 A.D. UTC.
tz = The $(D TimeZone) to use for this $(D SysTime). If null,
$(D LocalTime) will be used.
+/
this(long stdTime, immutable TimeZone tz = null) pure nothrow
{
_stdTime = stdTime;
_timezone = tz is null ? LocalTime() : tz;
}
version(testStdDateTime) unittest
{
static void test(long stdTime, immutable TimeZone tz)
{
auto sysTime = SysTime(stdTime, tz);
_assertPred!"=="(sysTime._stdTime, stdTime);
assert(sysTime._timezone is (tz is null ? LocalTime() : tz),
format("Given stdTime: %s", stdTime));
}
foreach(stdTime; [-1234567890L, -250, 0, 250, 1235657390L])
{
foreach(tz; testTZs)
test(stdTime, tz);
}
}
/++
Params:
rhs = The $(D SysTime) to assign to this one.
+/
ref SysTime opAssign(const ref SysTime rhs) pure nothrow
{
_stdTime = rhs._stdTime;
_timezone = rhs._timezone.get;
return this;
}
/++
Params:
rhs = The $(D SysTime) to assign to this one.
+/
ref SysTime opAssign(SysTime rhs) pure nothrow
{
_stdTime = rhs._stdTime;
_timezone = rhs._timezone.get;
return this;
}
/++
Checks for equality between this $(D SysTime) and the given
$(D SysTime).
Note that the time zone is ignored. Only the internal
std times (which are in UTC) are compared.
+/
bool opEquals(const ref SysTime rhs) const pure nothrow
{
return _stdTime == rhs._stdTime;
}
version(testStdDateTime) unittest
{
_assertPred!"=="(SysTime(DateTime.init, UTC()), SysTime(0, UTC()));
_assertPred!"=="(SysTime(DateTime.init, UTC()), SysTime(0));
_assertPred!"=="(SysTime(Date.init, UTC()), SysTime(0));
_assertPred!"=="(SysTime(0), SysTime(0));
static void test(DateTime dt,
immutable TimeZone tz1,
immutable TimeZone tz2)
{
auto st1 = SysTime(dt);
st1.timezone = tz1;
auto st2 = SysTime(dt);
st2.timezone = tz2;
_assertPred!"=="(st1, st2);
}
foreach(tz1; testTZs)
{
foreach(tz2; testTZs)
{
foreach(dt; chain(testDateTimesBC, testDateTimesAD))
test(dt, tz1, tz2);
}
}
auto st = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
const cst = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
static assert(__traits(compiles, st == st));
static assert(__traits(compiles, st == cst));
//static assert(__traits(compiles, st == ist));
static assert(__traits(compiles, cst == st));
static assert(__traits(compiles, cst == cst));
//static assert(__traits(compiles, cst == ist));
//static assert(__traits(compiles, ist == st));
//static assert(__traits(compiles, ist == cst));
//static assert(__traits(compiles, ist == ist));
}
/++
Compares this $(D SysTime) with the given $(D SysTime).
Time zone is irrelevant when comparing $(D SysTime)s.
Returns:
$(BOOKTABLE,
$(TR $(TD this < rhs) $(TD < 0))
$(TR $(TD this == rhs) $(TD 0))
$(TR $(TD this > rhs) $(TD > 0))
)
+/
int opCmp(in SysTime rhs) const pure nothrow
{
if(_stdTime < rhs._stdTime)
return -1;
if(_stdTime > rhs._stdTime)
return 1;
return 0;
}
version(testStdDateTime) unittest
{
_assertPred!("opCmp", "==")(SysTime(DateTime.init, UTC()),
SysTime(0, UTC()));
_assertPred!("opCmp", "==")(SysTime(DateTime.init, UTC()), SysTime(0));
_assertPred!("opCmp", "==")(SysTime(Date.init, UTC()), SysTime(0));
_assertPred!("opCmp", "==")(SysTime(0), SysTime(0));
static void testEqual(DateTime dt,
immutable TimeZone tz1,
immutable TimeZone tz2)
{
auto st1 = SysTime(dt);
st1.timezone = tz1;
auto st2 = SysTime(dt);
st2.timezone = tz2;
_assertPred!("opCmp", "==")(st1, st2);
}
foreach(dt; chain(testDateTimesBC, testDateTimesAD))
{
foreach(tz1; testTZs)
{
foreach(tz2; testTZs)
testEqual(dt, tz1, tz2);
}
}
static void testCmp(DateTime dt1,
immutable TimeZone tz1,
DateTime dt2,
immutable TimeZone tz2)
{
auto st1 = SysTime(dt1);
st1.timezone = tz1;
auto st2 = SysTime(dt2);
st2.timezone = tz2;
_assertPred!("opCmp", "<")(st1, st2);
_assertPred!("opCmp", ">")(st2, st1);
}
auto dts = testDateTimesBC ~ testDateTimesAD;
foreach(tz1; testTZs)
{
foreach(tz2; testTZs)
{
for(size_t i = 0; i < dts.length; ++i)
{
for(size_t j = i + 1; j < dts.length; ++j)
testCmp(dts[i], tz1, dts[j], tz2);
}
}
}
auto st = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
const cst = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
static assert(__traits(compiles, st.opCmp(st)));
static assert(__traits(compiles, st.opCmp(cst)));
//static assert(__traits(compiles, st.opCmp(ist)));
static assert(__traits(compiles, cst.opCmp(st)));
static assert(__traits(compiles, cst.opCmp(cst)));
//static assert(__traits(compiles, cst.opCmp(ist)));
//static assert(__traits(compiles, ist.opCmp(st)));
//static assert(__traits(compiles, ist.opCmp(cst)));
//static assert(__traits(compiles, ist.opCmp(ist)));
}
/++
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive
are B.C.
+/
@property short year() const nothrow
{
return (cast(Date)this).year;
}
version(testStdDateTime) unittest
{
static void test(SysTime sysTime, long expected, size_t line = __LINE__)
{
_assertPred!"=="(sysTime.year, expected,
format("Value given: %s", sysTime), __FILE__, line);
}
test(SysTime(0, UTC()), 1);
test(SysTime(1, UTC()), 1);
test(SysTime(-1, UTC()), 0);
foreach(year; chain(testYearsBC, testYearsAD))
{
foreach(md; testMonthDays)
{
foreach(tod; testTODs)
{
auto dt = DateTime(Date(year, md.month, md.day), tod);
foreach(tz; testTZs)
{
foreach(fs; testFracSecs)
test(SysTime(dt, fs, tz), year);
}
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.year));
//static assert(__traits(compiles, ist.year));
}
/++
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive
are B.C.
Params:
year = The year to set this $(D SysTime)'s year to.
Throws:
$(D DateTimeException) if the new year is not a leap year and the
resulting date would be on February 29th.
Examples:
--------------------
assert(SysTime(DateTime(1999, 7, 6, 9, 7, 5)).year == 1999);
assert(SysTime(DateTime(2010, 10, 4, 0, 0, 30)).year == 2010);
assert(SysTime(DateTime(-7, 4, 5, 7, 45, 2)).year == -7);
--------------------
+/
@property void year(int year)
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
auto date = Date(cast(int)days);
date.year = year;
immutable newDaysHNSecs = convert!("days", "hnsecs")(date.dayOfGregorianCal - 1);
adjTime = newDaysHNSecs + hnsecs;
}
//Verify Examples.
version(testStdDateTime) unittest
{
assert(SysTime(DateTime(1999, 7, 6, 9, 7, 5)).year == 1999);
assert(SysTime(DateTime(2010, 10, 4, 0, 0, 30)).year == 2010);
assert(SysTime(DateTime(-7, 4, 5, 7, 45, 2)).year == -7);
}
version(testStdDateTime) unittest
{
static void test(SysTime st, int year, in SysTime expected, size_t line = __LINE__)
{
st.year = year;
_assertPred!"=="(st, expected, "", __FILE__, line);
}
foreach(st; chain(testSysTimesBC, testSysTimesAD))
{
auto dt = cast(DateTime)st;
foreach(year; chain(testYearsBC, testYearsAD))
{
auto e = SysTime(DateTime(year, dt.month, dt.day, dt.hour, dt.minute, dt.second),
st.fracSec,
st.timezone);
test(st, year, e);
}
}
foreach(fs; testFracSecs)
{
foreach(tz; testTZs)
{
foreach(tod; testTODs)
{
test(SysTime(DateTime(Date(1999, 2, 28), tod), fs, tz), 2000,
SysTime(DateTime(Date(2000, 2, 28), tod), fs, tz));
test(SysTime(DateTime(Date(2000, 2, 28), tod), fs, tz), 1999,
SysTime(DateTime(Date(1999, 2, 28), tod), fs, tz));
}
foreach(tod; testTODsThrown)
{
auto st = SysTime(DateTime(Date(2000, 2, 29), tod), fs, tz);
assertThrown!DateTimeException(st.year = 1999);
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.year = 7));
//static assert(!__traits(compiles, ist.year = 7));
}
/++
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C.
Throws:
$(D DateTimeException) if $(D isAD) is true.
Examples:
--------------------
assert(SysTime(DateTime(0, 1, 1, 12, 30, 33)).yearBC == 1);
assert(SysTime(DateTime(-1, 1, 1, 10, 7, 2)).yearBC == 2);
assert(SysTime(DateTime(-100, 1, 1, 4, 59, 0)).yearBC == 101);
--------------------
+/
@property ushort yearBC() const
{
return (cast(Date)this).yearBC;
}
//Verify Examples.
version(testStdDateTime) unittest
{
assert(SysTime(DateTime(0, 1, 1, 12, 30, 33)).yearBC == 1);
assert(SysTime(DateTime(-1, 1, 1, 10, 7, 2)).yearBC == 2);
assert(SysTime(DateTime(-100, 1, 1, 4, 59, 0)).yearBC == 101);
}
version(testStdDateTime) unittest
{
foreach(st; testSysTimesBC)
{
auto msg = format("SysTime: %s", st);
assertNotThrown!DateTimeException(st.yearBC, msg);
_assertPred!"=="(st.yearBC, (st.year * -1) + 1, msg);
}
foreach(st; [testSysTimesAD[0], testSysTimesAD[$/2], testSysTimesAD[$-1]])
assertThrown!DateTimeException(st.yearBC, format("SysTime: %s", st));
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st.year = 12));
static assert(!__traits(compiles, cst.year = 12));
//static assert(!__traits(compiles, ist.year = 12));
}
/++
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C.
Params:
year = The year B.C. to set this $(D SysTime)'s year to.
Throws:
$(D DateTimeException) if a non-positive value is given.
Examples:
--------------------
auto st = SysTime(DateTime(2010, 1, 1, 7, 30, 0));
st.yearBC = 1;
assert(st == SysTime(DateTime(0, 1, 1, 7, 30, 0)));
st.yearBC = 10;
assert(st == SysTime(DateTime(-9, 1, 1, 7, 30, 0)));
--------------------
+/
@property void yearBC(int year)
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
auto date = Date(cast(int)days);
date.yearBC = year;
immutable newDaysHNSecs = convert!("days", "hnsecs")(date.dayOfGregorianCal - 1);
adjTime = newDaysHNSecs + hnsecs;
}
//Verify Examples
version(testStdDateTime) unittest
{
auto st = SysTime(DateTime(2010, 1, 1, 7, 30, 0));
st.yearBC = 1;
assert(st == SysTime(DateTime(0, 1, 1, 7, 30, 0)));
st.yearBC = 10;
assert(st == SysTime(DateTime(-9, 1, 1, 7, 30, 0)));
}
version(testStdDateTime) unittest
{
static void test(SysTime st, int year, in SysTime expected, size_t line = __LINE__)
{
st.yearBC = year;
_assertPred!"=="(st, expected, format("SysTime: %s", st), __FILE__, line);
}
foreach(st; chain(testSysTimesBC, testSysTimesAD))
{
auto dt = cast(DateTime)st;
foreach(year; testYearsBC)
{
auto e = SysTime(DateTime(year, dt.month, dt.day, dt.hour, dt.minute, dt.second),
st.fracSec,
st.timezone);
test(st, (year * -1) + 1, e);
}
}
foreach(st; [testSysTimesBC[0], testSysTimesBC[$ - 1],
testSysTimesAD[0], testSysTimesAD[$ - 1]])
{
foreach(year; testYearsBC)
assertThrown!DateTimeException(st.yearBC = year);
}
foreach(fs; testFracSecs)
{
foreach(tz; testTZs)
{
foreach(tod; testTODs)
{
test(SysTime(DateTime(Date(-1999, 2, 28), tod), fs, tz), 2001,
SysTime(DateTime(Date(-2000, 2, 28), tod), fs, tz));
test(SysTime(DateTime(Date(-2000, 2, 28), tod), fs, tz), 2000,
SysTime(DateTime(Date(-1999, 2, 28), tod), fs, tz));
}
foreach(tod; testTODsThrown)
{
auto st = SysTime(DateTime(Date(-2000, 2, 29), tod), fs, tz);
assertThrown!DateTimeException(st.year = -1999);
}
}
}
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st.yearBC = 12));
static assert(!__traits(compiles, cst.yearBC = 12));
//static assert(!__traits(compiles, ist.yearBC = 12));
}
/++
Month of a Gregorian Year.
Examples:
--------------------
assert(SysTime(DateTime(1999, 7, 6, 9, 7, 5)).month == 7);
assert(SysTime(DateTime(2010, 10, 4, 0, 0, 30)).month == 10);
assert(SysTime(DateTime(-7, 4, 5, 7, 45, 2)).month == 4);
--------------------
+/
@property Month month() const nothrow
{
return (cast(Date)this).month;
}
//Verify Examples.
version(testStdDateTime) unittest
{
assert(SysTime(DateTime(1999, 7, 6, 9, 7, 5)).month == 7);
assert(SysTime(DateTime(2010, 10, 4, 0, 0, 30)).month == 10);
assert(SysTime(DateTime(-7, 4, 5, 7, 45, 2)).month == 4);
}
version(testStdDateTime) unittest
{
static void test(SysTime sysTime, Month expected, size_t line = __LINE__)
{
_assertPred!"=="(sysTime.month, expected,
format("Value given: %s", sysTime), __FILE__, line);
}
test(SysTime(0, UTC()), Month.jan);
test(SysTime(1, UTC()), Month.jan);
test(SysTime(-1, UTC()), Month.dec);
foreach(year; chain(testYearsBC, testYearsAD))
{
foreach(md; testMonthDays)
{
foreach(tod; testTODs)
{
auto dt = DateTime(Date(year, md.month, md.day), tod);
foreach(fs; testFracSecs)
{
foreach(tz; testTZs)
test(SysTime(dt, fs, tz), md.month);
}
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.month));
//static assert(__traits(compiles, ist.month));
}
/++
Month of a Gregorian Year.
Params:
month = The month to set this $(D SysTime)'s month to.
Throws:
$(D DateTimeException) if the given month is not a valid month.
+/
@property void month(Month month)
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
auto date = Date(cast(int)days);
date.month = month;
immutable newDaysHNSecs = convert!("days", "hnsecs")(date.dayOfGregorianCal - 1);
adjTime = newDaysHNSecs + hnsecs;
}
version(testStdDateTime) unittest
{
static void test(SysTime st, Month month, in SysTime expected, size_t line = __LINE__)
{
st.month = cast(Month)month;
_assertPred!"=="(st, expected, "", __FILE__, line);
}
foreach(st; chain(testSysTimesBC, testSysTimesAD))
{
auto dt = cast(DateTime)st;
foreach(md; testMonthDays)
{
if(st.day > maxDay(dt.year, md.month))
continue;
auto e = SysTime(DateTime(dt.year, md.month, dt.day, dt.hour, dt.minute, dt.second),
st.fracSec,
st.timezone);
test(st, md.month, e);
}
}
foreach(fs; testFracSecs)
{
foreach(tz; testTZs)
{
foreach(tod; testTODs)
{
foreach(year; filter!((a){return yearIsLeapYear(a);})
(chain(testYearsBC, testYearsAD)))
{
test(SysTime(DateTime(Date(year, 1, 29), tod), fs, tz),
Month.feb,
SysTime(DateTime(Date(year, 2, 29), tod), fs, tz));
}
foreach(year; chain(testYearsBC, testYearsAD))
{
test(SysTime(DateTime(Date(year, 1, 28), tod), fs, tz),
Month.feb,
SysTime(DateTime(Date(year, 2, 28), tod), fs, tz));
test(SysTime(DateTime(Date(year, 7, 30), tod), fs, tz),
Month.jun,
SysTime(DateTime(Date(year, 6, 30), tod), fs, tz));
}
}
}
}
foreach(fs; [testFracSecs[0], testFracSecs[$-1]])
{
foreach(tz; testTZs)
{
foreach(tod; testTODsThrown)
{
foreach(year; [testYearsBC[$-3], testYearsBC[$-2],
testYearsBC[$-2], testYearsAD[0],
testYearsAD[$-2], testYearsAD[$-1]])
{
auto day = yearIsLeapYear(year) ? 30 : 29;
auto st1 = SysTime(DateTime(Date(year, 1, day), tod), fs, tz);
assertThrown!DateTimeException(st1.month = Month.feb);
auto st2 = SysTime(DateTime(Date(year, 7, 31), tod), fs, tz);
assertThrown!DateTimeException(st2.month = Month.jun);
}
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.month = 12));
//static assert(!__traits(compiles, ist.month = 12));
}
/++
Day of a Gregorian Month.
Examples:
--------------------
assert(SysTime(DateTime(1999, 7, 6, 9, 7, 5)).day == 6);
assert(SysTime(DateTime(2010, 10, 4, 0, 0, 30)).day == 4);
assert(SysTime(DateTime(-7, 4, 5, 7, 45, 2)).day == 5);
--------------------
+/
@property ubyte day() const nothrow
{
return (cast(Date)this).day;
}
//Verify Examples.
version(testStdDateTime) unittest
{
assert(SysTime(DateTime(1999, 7, 6, 9, 7, 5)).day == 6);
assert(SysTime(DateTime(2010, 10, 4, 0, 0, 30)).day == 4);
assert(SysTime(DateTime(-7, 4, 5, 7, 45, 2)).day == 5);
}
version(testStdDateTime) unittest
{
static void test(SysTime sysTime, int expected, size_t line = __LINE__)
{
_assertPred!"=="(sysTime.day, expected,
format("Value given: %s", sysTime), __FILE__, line);
}
test(SysTime(0, UTC()), 1);
test(SysTime(1, UTC()), 1);
test(SysTime(-1, UTC()), 31);
foreach(year; chain(testYearsBC, testYearsAD))
{
foreach(md; testMonthDays)
{
foreach(tod; testTODs)
{
auto dt = DateTime(Date(year, md.month, md.day), tod);
foreach(tz; testTZs)
{
foreach(fs; testFracSecs)
test(SysTime(dt, fs, tz), md.day);
}
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.day));
//static assert(__traits(compiles, ist.day));
}
/++
Day of a Gregorian Month.
Params:
day = The day of the month to set this $(D SysTime)'s day to.
Throws:
$(D DateTimeException) if the given day is not a valid day of the
current month.
+/
@property void day(int day)
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
auto date = Date(cast(int)days);
date.day = day;
immutable newDaysHNSecs = convert!("days", "hnsecs")(date.dayOfGregorianCal - 1);
adjTime = newDaysHNSecs + hnsecs;
}
version(testStdDateTime) unittest
{
static void test(SysTime st, int day, in SysTime expected, size_t line = __LINE__)
{
st.day = day;
_assertPred!"=="(st, expected, "", __FILE__, line);
}
foreach(day; chain(testDays))
{
foreach(st; chain(testSysTimesBC, testSysTimesAD))
{
auto dt = cast(DateTime)st;
if(day > maxDay(dt.year, dt.month))
continue;
auto e = SysTime(DateTime(dt.year, dt.month, day, dt.hour, dt.minute, dt.second),
st.fracSec,
st.timezone);
test(st, day, e);
}
}
foreach(tz; testTZs)
{
foreach(tod; testTODs)
{
foreach(fs; testFracSecs)
{
foreach(year; chain(testYearsBC, testYearsAD))
{
foreach(month; EnumMembers!Month)
{
auto st = SysTime(DateTime(Date(year, month, 1), tod), fs, tz);
immutable max = maxDay(year, month);
test(st, max, SysTime(DateTime(Date(year, month, max), tod), fs, tz));
}
}
}
}
}
foreach(tz; testTZs)
{
foreach(tod; testTODsThrown)
{
foreach(fs; [testFracSecs[0], testFracSecs[$-1]])
{
foreach(year; [testYearsBC[$-3], testYearsBC[$-2],
testYearsBC[$-2], testYearsAD[0],
testYearsAD[$-2], testYearsAD[$-1]])
{
foreach(month; EnumMembers!Month)
{
auto st = SysTime(DateTime(Date(year, month, 1), tod), fs, tz);
immutable max = maxDay(year, month);
assertThrown!DateTimeException(st.day = max + 1);
}
}
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.day = 27));
//static assert(!__traits(compiles, ist.day = 27));
}
/++
Hours past midnight.
+/
@property ubyte hour() const nothrow
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
return cast(ubyte)getUnitsFromHNSecs!"hours"(hnsecs);
}
version(testStdDateTime) unittest
{
static void test(SysTime sysTime, int expected, size_t line = __LINE__)
{
_assertPred!"=="(sysTime.hour, expected,
format("Value given: %s", sysTime), __FILE__, line);
}
test(SysTime(0, UTC()), 0);
test(SysTime(1, UTC()), 0);
test(SysTime(-1, UTC()), 23);
foreach(tz; testTZs)
{
foreach(year; chain(testYearsBC, testYearsAD))
{
foreach(md; testMonthDays)
{
foreach(hour; testHours)
{
foreach(minute; testMinSecs)
{
foreach(second; testMinSecs)
{
auto dt = DateTime(Date(year, md.month, md.day),
TimeOfDay(hour, minute, second));
foreach(fs; testFracSecs)
test(SysTime(dt, fs, tz), hour);
}
}
}
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.hour));
//static assert(__traits(compiles, ist.hour));
}
/++
Hours past midnight.
Params:
hour = The hours to set this $(D SysTime)'s hour to.
Throws:
$(D DateTimeException) if the given hour are not a valid hour of
the day.
+/
@property void hour(int hour)
{
enforceValid!"hours"(hour);
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs);
immutable daysHNSecs = convert!("days", "hnsecs")(days);
immutable negative = hnsecs < 0;
if(negative)
hnsecs += convert!("hours", "hnsecs")(24);
hnsecs = removeUnitsFromHNSecs!"hours"(hnsecs);
hnsecs += convert!("hours", "hnsecs")(hour);
if(negative)
hnsecs -= convert!("hours", "hnsecs")(24);
adjTime = daysHNSecs + hnsecs;
}
version(testStdDateTime) unittest
{
static void test(SysTime st, int hour, in SysTime expected,
size_t line = __LINE__)
{
st.hour = hour;
_assertPred!"=="(st, expected, "", __FILE__, line);
}
foreach(hour; chain(testHours))
{
foreach(st; chain(testSysTimesBC, testSysTimesAD))
{
auto dt = cast(DateTime)st;
auto e = SysTime(DateTime(dt.year, dt.month, dt.day, hour, dt.minute, dt.second),
st.fracSec,
st.timezone);
test(st, hour, e);
}
}
auto st = testSysTimesAD[0];
assertThrown!DateTimeException(st.hour = -1);
assertThrown!DateTimeException(st.hour = 60);
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.hour = 27));
//static assert(!__traits(compiles, ist.hour = 27));
}
/++
Minutes past the current hour.
+/
@property ubyte minute() const nothrow
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
hnsecs = removeUnitsFromHNSecs!"hours"(hnsecs);
return cast(ubyte)getUnitsFromHNSecs!"minutes"(hnsecs);
}
version(testStdDateTime) unittest
{
static void test(SysTime sysTime, int expected, size_t line = __LINE__)
{
_assertPred!"=="(sysTime.minute, expected,
format("Value given: %s", sysTime), __FILE__, line);
}
test(SysTime(0, UTC()), 0);
test(SysTime(1, UTC()), 0);
test(SysTime(-1, UTC()), 59);
foreach(tz; testTZs)
{
foreach(year; chain(testYearsBC, testYearsAD))
{
foreach(md; testMonthDays)
{
foreach(hour; testHours)
{
foreach(minute; testMinSecs)
{
foreach(second; testMinSecs)
{
auto dt = DateTime(Date(year, md.month, md.day),
TimeOfDay(hour, minute, second));
foreach(fs; testFracSecs)
test(SysTime(dt, fs, tz), minute);
}
}
}
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.minute));
//static assert(__traits(compiles, ist.minute));
}
/++
Minutes past the current hour.
Params:
minutes = The minute to set this $(D SysTime)'s minute to.
Throws:
$(D DateTimeException) if the given minute are not a valid minute
of an hour.
+/
@property void minute(int minute)
{
enforceValid!"minutes"(minute);
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs);
immutable daysHNSecs = convert!("days", "hnsecs")(days);
immutable negative = hnsecs < 0;
if(negative)
hnsecs += convert!("hours", "hnsecs")(24);
immutable hour = splitUnitsFromHNSecs!"hours"(hnsecs);
hnsecs = removeUnitsFromHNSecs!"minutes"(hnsecs);
hnsecs += convert!("hours", "hnsecs")(hour);
hnsecs += convert!("minutes", "hnsecs")(minute);
if(negative)
hnsecs -= convert!("hours", "hnsecs")(24);
adjTime = daysHNSecs + hnsecs;
}
version(testStdDateTime) unittest
{
static void test(SysTime st, int minute, in SysTime expected, size_t line = __LINE__)
{
st.minute = minute;
_assertPred!"=="(st, expected, "", __FILE__, line);
}
foreach(minute; testMinSecs)
{
foreach(st; chain(testSysTimesBC, testSysTimesAD))
{
auto dt = cast(DateTime)st;
auto e = SysTime(DateTime(dt.year, dt.month, dt.day, dt.hour, minute, dt.second),
st.fracSec,
st.timezone);
test(st, minute, e);
}
}
auto st = testSysTimesAD[0];
assertThrown!DateTimeException(st.minute = -1);
assertThrown!DateTimeException(st.minute = 60);
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.minute = 27));
//static assert(!__traits(compiles, ist.minute = 27));
}
/++
Seconds past the current minute.
+/
@property ubyte second() const nothrow
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
hnsecs = removeUnitsFromHNSecs!"hours"(hnsecs);
hnsecs = removeUnitsFromHNSecs!"minutes"(hnsecs);
return cast(ubyte)getUnitsFromHNSecs!"seconds"(hnsecs);
}
version(testStdDateTime) unittest
{
static void test(SysTime sysTime, int expected, size_t line = __LINE__)
{
_assertPred!"=="(sysTime.second, expected,
format("Value given: %s", sysTime), __FILE__, line);
}
test(SysTime(0, UTC()), 0);
test(SysTime(1, UTC()), 0);
test(SysTime(-1, UTC()), 59);
foreach(tz; testTZs)
{
foreach(year; chain(testYearsBC, testYearsAD))
{
foreach(md; testMonthDays)
{
foreach(hour; testHours)
{
foreach(minute; testMinSecs)
{
foreach(second; testMinSecs)
{
auto dt = DateTime(Date(year, md.month, md.day),
TimeOfDay(hour, minute, second));
foreach(fs; testFracSecs)
test(SysTime(dt, fs, tz), second);
}
}
}
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.second));
//static assert(__traits(compiles, ist.second));
}
/++
Seconds past the current minute.
Params:
second = The second to set this $(D SysTime)'s second to.
Throws:
$(D DateTimeException) if the given second are not a valid second
of a minute.
+/
@property void second(int second)
{
enforceValid!"seconds"(second);
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs);
immutable daysHNSecs = convert!("days", "hnsecs")(days);
immutable negative = hnsecs < 0;
if(negative)
hnsecs += convert!("hours", "hnsecs")(24);
immutable hour = splitUnitsFromHNSecs!"hours"(hnsecs);
immutable minute = splitUnitsFromHNSecs!"minutes"(hnsecs);
hnsecs = removeUnitsFromHNSecs!"seconds"(hnsecs);
hnsecs += convert!("hours", "hnsecs")(hour);
hnsecs += convert!("minutes", "hnsecs")(minute);
hnsecs += convert!("seconds", "hnsecs")(second);
if(negative)
hnsecs -= convert!("hours", "hnsecs")(24);
adjTime = daysHNSecs + hnsecs;
}
version(testStdDateTime) unittest
{
static void test(SysTime st, int second, in SysTime expected,
size_t line = __LINE__)
{
st.second = second;
_assertPred!"=="(st, expected, "", __FILE__, line);
}
foreach(second; testMinSecs)
{
foreach(st; chain(testSysTimesBC, testSysTimesAD))
{
auto dt = cast(DateTime)st;
auto e = SysTime(DateTime(dt.year, dt.month, dt.day, dt.hour, dt.minute, second),
st.fracSec,
st.timezone);
test(st, second, e);
}
}
auto st = testSysTimesAD[0];
assertThrown!DateTimeException(st.second = -1);
assertThrown!DateTimeException(st.second = 60);
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.seconds = 27));
//static assert(!__traits(compiles, ist.seconds = 27));
}
/++
Fractional seconds passed the second.
+/
@property FracSec fracSec() const nothrow
{
try
{
auto hnsecs = removeUnitsFromHNSecs!"days"(adjTime);
if(hnsecs < 0)
hnsecs += convert!("hours", "hnsecs")(24);
hnsecs = removeUnitsFromHNSecs!"seconds"(hnsecs);
return FracSec.from!"hnsecs"(cast(int)hnsecs);
}
catch(Exception e)
assert(0, "FracSec.from!\"hnsecs\"() threw.");
}
version(testStdDateTime) unittest
{
static void test(SysTime sysTime, FracSec expected, size_t line = __LINE__)
{
_assertPred!"=="(sysTime.fracSec, expected,
format("Value given: %s", sysTime), __FILE__, line);
}
test(SysTime(0, UTC()), FracSec.from!"hnsecs"(0));
test(SysTime(1, UTC()), FracSec.from!"hnsecs"(1));
test(SysTime(-1, UTC()), FracSec.from!"hnsecs"(9_999_999));
foreach(tz; testTZs)
{
foreach(year; chain(testYearsBC, testYearsAD))
{
foreach(md; testMonthDays)
{
foreach(hour; testHours)
{
foreach(minute; testMinSecs)
{
foreach(second; testMinSecs)
{
auto dt = DateTime(Date(year, md.month, md.day),
TimeOfDay(hour, minute, second));
foreach(fs; testFracSecs)
test(SysTime(dt, fs, tz), fs);
}
}
}
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.fracSec));
//static assert(__traits(compiles, ist.fracSec));
}
/++
Fractional seconds passed the second.
Params:
fracSec = The fractional seconds to set this $(D SysTimes)'s
fractional seconds to.
Throws:
$(D DateTimeException) if $(D fracSec) is negative.
+/
@property void fracSec(FracSec fracSec)
{
immutable fracHNSecs = fracSec.hnsecs;
enforce(fracHNSecs >= 0, new DateTimeException("A SysTime cannot have negative fractional seconds."));
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs);
immutable daysHNSecs = convert!("days", "hnsecs")(days);
immutable negative = hnsecs < 0;
if(negative)
hnsecs += convert!("hours", "hnsecs")(24);
immutable hour = splitUnitsFromHNSecs!"hours"(hnsecs);
immutable minute = splitUnitsFromHNSecs!"minutes"(hnsecs);
immutable second = getUnitsFromHNSecs!"seconds"(hnsecs);
hnsecs = fracHNSecs;
hnsecs += convert!("hours", "hnsecs")(hour);
hnsecs += convert!("minutes", "hnsecs")(minute);
hnsecs += convert!("seconds", "hnsecs")(second);
if(negative)
hnsecs -= convert!("hours", "hnsecs")(24);
adjTime = daysHNSecs + hnsecs;
}
version(testStdDateTime) unittest
{
static void test(SysTime st, FracSec fracSec, in SysTime expected, size_t line = __LINE__)
{
st.fracSec = fracSec;
_assertPred!"=="(st, expected, "", __FILE__, line);
}
foreach(fracSec; testFracSecs)
{
foreach(st; chain(testSysTimesBC, testSysTimesAD))
{
auto dt = cast(DateTime)st;
auto e = SysTime(DateTime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second),
fracSec,
st.timezone);
test(st, fracSec, e);
}
}
SysTime st = SysTime(DateTime(2011, 7, 11, 2, 51, 27));
assertThrown!DateTimeException(st.fracSec = FracSec.from!"hnsecs"(-1));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.fracSec = FracSec.from!"msecs"(7)));
//static assert(!__traits(compiles, ist.fracSec = FracSec.from!"msecs"(7)));
}
/++
The total hnsecs from midnight, January 1st, 1 A.D. UTC. This is the
internal representation of $(D SysTime).
+/
@property long stdTime() const pure nothrow
{
return _stdTime;
}
version(testStdDateTime) unittest
{
_assertPred!"=="(SysTime(0).stdTime, 0);
_assertPred!"=="(SysTime(1).stdTime, 1);
_assertPred!"=="(SysTime(-1).stdTime, -1);
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 0, 0, 33), FracSec.from!"hnsecs"(502), UTC()).stdTime,
330000502L);
_assertPred!"=="(SysTime(DateTime(1970, 1, 1, 0, 0, 0), UTC()).stdTime,
621355968000000000L);
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.stdTime));
//static assert(__traits(compiles, ist.stdTime));
}
/++
The total hnsecs from midnight, January 1st, 1 A.D. UTC. This is the
internal representation of $(D SysTime).
Params:
stdTime = The number of hnsecs since January 1st, 1 A.D. UTC.
+/
@property void stdTime(long stdTime) pure nothrow
{
_stdTime = stdTime;
}
version(testStdDateTime) unittest
{
static void test(long stdTime, in SysTime expected, size_t line = __LINE__)
{
auto st = SysTime(0, UTC());
st.stdTime = stdTime;
_assertPred!"=="(st, expected);
}
test(0, SysTime(Date(1, 1, 1), UTC()));
test(1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1), UTC()));
test(-1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999), UTC()));
test(330_000_502L, SysTime(DateTime(1, 1, 1, 0, 0, 33), FracSec.from!"hnsecs"(502), UTC()));
test(621_355_968_000_000_000L, SysTime(DateTime(1970, 1, 1, 0, 0, 0), UTC()));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.stdTime = 27));
//static assert(!__traits(compiles, ist.stdTime = 27));
}
/++
The current time zone of this $(D SysTime). Its internal time is always
kept in UTC, so there are no conversion issues between time zones due to
DST. Functions which return all or part of the time - such as hours -
adjust the time to this $(D SysTime)'s time zone before returning.
+/
@property immutable(TimeZone) timezone() const pure nothrow
{
return _timezone.get;
}
/++
The current time zone of this $(D SysTime). It's internal time is always
kept in UTC, so there are no conversion issues between time zones due to
DST. Functions which return all or part of the time - such as hours -
adjust the time to this $(D SysTime)'s time zone before returning.
Params:
tz = The $(D TimeZone) to set this $(D SysTime)'s time zone to.
+/
@property void timezone(immutable TimeZone timezone) pure nothrow
{
if(timezone is null)
_timezone = LocalTime();
else
_timezone = timezone;
}
/++
Returns whether DST is in effect for this $(D SysTime).
+/
@property bool dstInEffect() const nothrow
{
return _timezone.dstInEffect(_stdTime);
//This function's unit testing is done in the time zone classes.
}
/++
Returns a $(D SysTime) with the same std time as this one, but with
$(D LocalTime) as its time zone.
+/
SysTime toLocalTime() const nothrow
{
return SysTime(_stdTime, LocalTime());
}
unittest
{
version(testStdDateTime)
{
{
auto sysTime = SysTime(DateTime(1982, 1, 4, 8, 59, 7), FracSec.from!"hnsecs"(27));
_assertPred!"=="(sysTime, sysTime.toLocalTime());
_assertPred!"=="(sysTime._stdTime, sysTime.toLocalTime()._stdTime);
assert(sysTime.toLocalTime().timezone is LocalTime());
assert(sysTime.toLocalTime().timezone is sysTime.timezone);
assert(sysTime.toLocalTime().timezone !is UTC());
}
{
immutable stz = new SimpleTimeZone(-3 * 60);
auto sysTime = SysTime(DateTime(1982, 1, 4, 8, 59, 7), FracSec.from!"hnsecs"(27), stz);
_assertPred!"=="(sysTime, sysTime.toLocalTime());
_assertPred!"=="(sysTime._stdTime, sysTime.toLocalTime()._stdTime);
assert(sysTime.toLocalTime().timezone is LocalTime());
assert(sysTime.toLocalTime().timezone !is UTC());
assert(sysTime.toLocalTime().timezone !is stz);
}
}
}
/++
Returns a $(D SysTime) with the same std time as this one, but with
$(D UTC) as its time zone.
+/
SysTime toUTC() const pure nothrow
{
return SysTime(_stdTime, UTC());
}
unittest
{
version(testStdDateTime)
{
auto sysTime = SysTime(DateTime(1982, 1, 4, 8, 59, 7), FracSec.from!"hnsecs"(27));
_assertPred!"=="(sysTime, sysTime.toUTC());
_assertPred!"=="(sysTime._stdTime, sysTime.toUTC()._stdTime);
assert(sysTime.toUTC().timezone is UTC());
assert(sysTime.toUTC().timezone !is LocalTime());
assert(sysTime.toUTC().timezone !is sysTime.timezone);
}
}
/++
Returns a $(D SysTime) with the same std time as this one, but with
given time zone as its time zone.
+/
SysTime toOtherTZ(immutable TimeZone tz) const pure nothrow
{
if(tz is null)
return SysTime(_stdTime, LocalTime());
else
return SysTime(_stdTime, tz);
}
unittest
{
version(testStdDateTime)
{
immutable stz = new SimpleTimeZone(11 * 60);
auto sysTime = SysTime(DateTime(1982, 1, 4, 8, 59, 7), FracSec.from!"hnsecs"(27));
_assertPred!"=="(sysTime, sysTime.toOtherTZ(stz));
_assertPred!"=="(sysTime._stdTime, sysTime.toOtherTZ(stz)._stdTime);
assert(sysTime.toOtherTZ(stz).timezone is stz);
assert(sysTime.toOtherTZ(stz).timezone !is LocalTime());
assert(sysTime.toOtherTZ(stz).timezone !is UTC());
}
}
/++
Returns a $(D time_t) which represents the same time as this
$(D SysTime).
Note that like all conversions in std.datetime, this is a truncating
conversion.
If $(D time_t) is 32 bits, rather than 64, and the result can't fit in a
32-bit value, then the closest value that can be held in 32 bits will be
used (so $(D time_t.max) if it goes over and $(D time_t.min) if it goes
under).
+/
time_t toUnixTime() const pure nothrow
{
return stdTimeToUnixTime(_stdTime);
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(SysTime(DateTime(1970, 1, 1), UTC()).toUnixTime, 0);
_assertPred!"=="(SysTime(DateTime(1970, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1), UTC()).toUnixTime, 0);
_assertPred!"=="(SysTime(DateTime(1970, 1, 1, 0, 0, 0), FracSec.from!"usecs"(1), UTC()).toUnixTime, 0);
_assertPred!"=="(SysTime(DateTime(1970, 1, 1, 0, 0, 0), FracSec.from!"msecs"(1), UTC()).toUnixTime, 0);
_assertPred!"=="(SysTime(DateTime(1970, 1, 1, 0, 0, 1), UTC()).toUnixTime, 1);
_assertPred!"=="(SysTime(DateTime(1969, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999), UTC()).toUnixTime, 0);
_assertPred!"=="(SysTime(DateTime(1969, 12, 31, 23, 59, 59), FracSec.from!"usecs"(999_999), UTC()).toUnixTime, 0);
_assertPred!"=="(SysTime(DateTime(1969, 12, 31, 23, 59, 59), FracSec.from!"msecs"(999), UTC()).toUnixTime, 0);
_assertPred!"=="(SysTime(DateTime(1969, 12, 31, 23, 59, 59), UTC()).toUnixTime, -1);
}
}
/++
Returns a $(D timeval) which represents this $(D SysTime).
Note that like all conversions in std.datetime, this is a truncating
conversion.
If $(D time_t) is 32 bits, rather than 64, and the result can't fit in a
32-bit value, then the closest value that can be held in 32 bits will be
used for $(D tv_sec). (so $(D time_t.max) if it goes over and
$(D time_t.min) if it goes under).
+/
timeval toTimeVal() const pure nothrow
{
immutable tv_sec = toUnixTime();
immutable fracHNSecs = removeUnitsFromHNSecs!"seconds"(_stdTime - 621355968000000000L);
immutable tv_usec = cast(int)convert!("hnsecs", "usecs")(fracHNSecs);
return timeval(tv_sec, tv_usec);
}
unittest
{
version(testStdDateTime)
{
assert(SysTime(DateTime(1970, 1, 1), UTC()).toTimeVal() == timeval(0, 0));
assert(SysTime(DateTime(1970, 1, 1), FracSec.from!"hnsecs"(9), UTC()).toTimeVal() == timeval(0, 0));
assert(SysTime(DateTime(1970, 1, 1), FracSec.from!"hnsecs"(10), UTC()).toTimeVal() == timeval(0, 1));
assert(SysTime(DateTime(1970, 1, 1), FracSec.from!"usecs"(7), UTC()).toTimeVal() == timeval(0, 7));
assert(SysTime(DateTime(1970, 1, 1, 0, 0, 1), UTC()).toTimeVal() == timeval(1, 0));
assert(SysTime(DateTime(1970, 1, 1, 0, 0, 1), FracSec.from!"hnsecs"(9), UTC()).toTimeVal() == timeval(1, 0));
assert(SysTime(DateTime(1970, 1, 1, 0, 0, 1), FracSec.from!"hnsecs"(10), UTC()).toTimeVal() == timeval(1, 1));
assert(SysTime(DateTime(1970, 1, 1, 0, 0, 1), FracSec.from!"usecs"(7), UTC()).toTimeVal() == timeval(1, 7));
assert(SysTime(DateTime(1969, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999), UTC()).toTimeVal() ==
timeval(0, 0));
assert(SysTime(DateTime(1969, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_990), UTC()).toTimeVal() ==
timeval(0, -1));
assert(SysTime(DateTime(1969, 12, 31, 23, 59, 59), FracSec.from!"usecs"(999_999), UTC()).toTimeVal() ==
timeval(0, -1));
assert(SysTime(DateTime(1969, 12, 31, 23, 59, 59), FracSec.from!"usecs"(999), UTC()).toTimeVal() ==
timeval(0, -999_001));
assert(SysTime(DateTime(1969, 12, 31, 23, 59, 59), FracSec.from!"msecs"(999), UTC()).toTimeVal() ==
timeval(0, -1000));
assert(SysTime(DateTime(1969, 12, 31, 23, 59, 59), UTC()).toTimeVal() == timeval(-1, 0));
assert(SysTime(DateTime(1969, 12, 31, 23, 59, 58), FracSec.from!"usecs"(17), UTC()).toTimeVal() ==
timeval(-1, -999_983));
}
}
/++
Returns a $(D tm) which represents this $(D SysTime).
+/
tm toTM() const nothrow
{
try
{
auto dateTime = cast(DateTime)this;
tm timeInfo;
timeInfo.tm_sec = dateTime.second;
timeInfo.tm_min = dateTime.minute;
timeInfo.tm_hour = dateTime.hour;
timeInfo.tm_mday = dateTime.day;
timeInfo.tm_mon = dateTime.month - 1;
timeInfo.tm_year = dateTime.year - 1900;
timeInfo.tm_wday = dateTime.dayOfWeek;
timeInfo.tm_yday = dateTime.dayOfYear - 1;
timeInfo.tm_isdst = _timezone.dstInEffect(_stdTime);
version(Posix)
{
char[] zone = (timeInfo.tm_isdst ? _timezone.dstName : _timezone.stdName).dup;
zone ~= "\0";
timeInfo.tm_gmtoff = cast(int)convert!("hnsecs", "seconds")(adjTime - _stdTime);
timeInfo.tm_zone = zone.ptr;
}
return timeInfo;
}
catch(Exception e)
assert(0, "Either DateTime's constructor threw.");
}
unittest
{
version(testStdDateTime)
{
version(Posix)
{
scope(exit) clearTZEnvVar();
setTZEnvVar("America/Los_Angeles");
}
{
auto timeInfo = SysTime(DateTime(1970, 1, 1)).toTM();
_assertPred!"=="(timeInfo.tm_sec, 0);
_assertPred!"=="(timeInfo.tm_min, 0);
_assertPred!"=="(timeInfo.tm_hour, 0);
_assertPred!"=="(timeInfo.tm_mday, 1);
_assertPred!"=="(timeInfo.tm_mon, 0);
_assertPred!"=="(timeInfo.tm_year, 70);
_assertPred!"=="(timeInfo.tm_wday, 4);
_assertPred!"=="(timeInfo.tm_yday, 0);
version(Posix)
_assertPred!"=="(timeInfo.tm_isdst, 0);
else version(Windows)
assert(timeInfo.tm_isdst == 0 || timeInfo.tm_isdst == 1);
version(Posix)
{
_assertPred!"=="(timeInfo.tm_gmtoff, -8 * 60 * 60);
_assertPred!"=="(to!string(timeInfo.tm_zone), "PST");
}
}
{
auto timeInfo = SysTime(DateTime(2010, 7, 4, 12, 15, 7), FracSec.from!"hnsecs"(15)).toTM();
_assertPred!"=="(timeInfo.tm_sec, 7);
_assertPred!"=="(timeInfo.tm_min, 15);
_assertPred!"=="(timeInfo.tm_hour, 12);
_assertPred!"=="(timeInfo.tm_mday, 4);
_assertPred!"=="(timeInfo.tm_mon, 6);
_assertPred!"=="(timeInfo.tm_year, 110);
_assertPred!"=="(timeInfo.tm_wday, 0);
_assertPred!"=="(timeInfo.tm_yday, 184);
version(Posix)
_assertPred!"=="(timeInfo.tm_isdst, 1);
else version(Windows)
assert(timeInfo.tm_isdst == 0 || timeInfo.tm_isdst == 1);
version(Posix)
{
_assertPred!"=="(timeInfo.tm_gmtoff, -7 * 60 * 60);
_assertPred!"=="(to!string(timeInfo.tm_zone), "PDT");
}
}
}
}
/++
Adds the given number of years or months to this $(D SysTime). A
negative number will subtract.
Note that if day overflow is allowed, and the date with the adjusted
year/month overflows the number of days in the new month, then the month
will be incremented by one, and the day set to the number of days
overflowed. (e.g. if the day were 31 and the new month were June, then
the month would be incremented to July, and the new day would be 1). If
day overflow is not allowed, then the day will be set to the last valid
day in the month (e.g. June 31st would become June 30th).
Params:
units = The type of units to add ("years" or "months").
value = The number of months or years to add to this
$(D SysTime).
allowOverflow = Whether the days should be allowed to overflow,
causing the month to increment.
Examples:
--------------------
auto st1 = SysTime(DateTime(2010, 1, 1, 12, 30, 33));
st1.add!"months"(11);
assert(st1 == SysTime(DateTime(2010, 12, 1, 12, 30, 33)));
auto st2 = SysTime(DateTime(2010, 1, 1, 12, 30, 33));
st2.add!"months"(-11);
assert(st2 == SysTime(DateTime(2009, 2, 1, 12, 30, 33)));
auto st3 = SysTime(DateTime(2000, 2, 29, 12, 30, 33));
st3.add!"years"(1);
assert(st3 == SysTime(DateTime(2001, 3, 1, 12, 30, 33)));
auto st4 = SysTime(DateTime(2000, 2, 29, 12, 30, 33));
st4.add!"years"(1, AllowDayOverflow.no);
assert(st4 == SysTime(DateTime(2001, 2, 28, 12, 30, 33)));
--------------------
+/
ref SysTime add(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes) nothrow
if(units == "years" ||
units == "months")
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
auto date = Date(cast(int)days);
date.add!units(value, allowOverflow);
days = date.dayOfGregorianCal - 1;
if(days < 0)
{
hnsecs -= convert!("hours", "hnsecs")(24);
++days;
}
immutable newDaysHNSecs = convert!("days", "hnsecs")(days);
adjTime = newDaysHNSecs + hnsecs;
return this;
}
//Verify Examples.
unittest
{
version (testStdDateTime)
{
auto st1 = SysTime(DateTime(2010, 1, 1, 12, 30, 33));
st1.add!"months"(11);
assert(st1 == SysTime(DateTime(2010, 12, 1, 12, 30, 33)));
auto st2 = SysTime(DateTime(2010, 1, 1, 12, 30, 33));
st2.add!"months"(-11);
assert(st2 == SysTime(DateTime(2009, 2, 1, 12, 30, 33)));
auto st3 = SysTime(DateTime(2000, 2, 29, 12, 30, 33));
st3.add!"years"(1);
assert(st3 == SysTime(DateTime(2001, 3, 1, 12, 30, 33)));
auto st4 = SysTime(DateTime(2000, 2, 29, 12, 30, 33));
st4.add!"years"(1, AllowDayOverflow.no);
assert(st4 == SysTime(DateTime(2001, 2, 28, 12, 30, 33)));
}
}
//Test add!"years"() with AllowDayOverlow.yes
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.add!"years"(7);
_assertPred!"=="(sysTime, SysTime(Date(2006, 7, 6)));
sysTime.add!"years"(-9);
_assertPred!"=="(sysTime, SysTime(Date(1997, 7, 6)));
}
{
auto sysTime = SysTime(Date(1999, 2, 28));
sysTime.add!"years"(1);
_assertPred!"=="(sysTime, SysTime(Date(2000, 2, 28)));
}
{
auto sysTime = SysTime(Date(2000, 2, 29));
sysTime.add!"years"(-1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 3, 1)));
}
{
auto sysTime = SysTime(DateTime(1999, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234));
sysTime.add!"years"(7);
_assertPred!"=="(sysTime, SysTime(DateTime(2006, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234)));
sysTime.add!"years"(-9);
_assertPred!"=="(sysTime, SysTime(DateTime(1997, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234)));
}
{
auto sysTime = SysTime(DateTime(1999, 2, 28, 0, 7, 2), FracSec.from!"usecs"(1207));
sysTime.add!"years"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(2000, 2, 28, 0, 7, 2), FracSec.from!"usecs"(1207)));
}
{
auto sysTime = SysTime(DateTime(2000, 2, 29, 0, 7, 2), FracSec.from!"usecs"(1207));
sysTime.add!"years"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 3, 1, 0, 7, 2), FracSec.from!"usecs"(1207)));
}
//Test B.C.
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.add!"years"(-7);
_assertPred!"=="(sysTime, SysTime(Date(-2006, 7, 6)));
sysTime.add!"years"(9);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 7, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 2, 28));
sysTime.add!"years"(-1);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 2, 28)));
}
{
auto sysTime = SysTime(Date(-2000, 2, 29));
sysTime.add!"years"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 3, 1)));
}
{
auto sysTime = SysTime(DateTime(-1999, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234));
sysTime.add!"years"(-7);
_assertPred!"=="(sysTime, SysTime(DateTime(-2006, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234)));
sysTime.add!"years"(9);
_assertPred!"=="(sysTime, SysTime(DateTime(-1997, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234)));
}
{
auto sysTime = SysTime(DateTime(-1999, 2, 28, 3, 3, 3), FracSec.from!"hnsecs"(3));
sysTime.add!"years"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(-2000, 2, 28, 3, 3, 3), FracSec.from!"hnsecs"(3)));
}
{
auto sysTime = SysTime(DateTime(-2000, 2, 29, 3, 3, 3), FracSec.from!"hnsecs"(3));
sysTime.add!"years"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 3, 1, 3, 3, 3), FracSec.from!"hnsecs"(3)));
}
//Test Both
{
auto sysTime = SysTime(Date(4, 7, 6));
sysTime.add!"years"(-5);
_assertPred!"=="(sysTime, SysTime(Date(-1, 7, 6)));
sysTime.add!"years"(5);
_assertPred!"=="(sysTime, SysTime(Date(4, 7, 6)));
}
{
auto sysTime = SysTime(Date(-4, 7, 6));
sysTime.add!"years"(5);
_assertPred!"=="(sysTime, SysTime(Date(1, 7, 6)));
sysTime.add!"years"(-5);
_assertPred!"=="(sysTime, SysTime(Date(-4, 7, 6)));
}
{
auto sysTime = SysTime(Date(4, 7, 6));
sysTime.add!"years"(-8);
_assertPred!"=="(sysTime, SysTime(Date(-4, 7, 6)));
sysTime.add!"years"(8);
_assertPred!"=="(sysTime, SysTime(Date(4, 7, 6)));
}
{
auto sysTime = SysTime(Date(-4, 7, 6));
sysTime.add!"years"(8);
_assertPred!"=="(sysTime, SysTime(Date(4, 7, 6)));
sysTime.add!"years"(-8);
_assertPred!"=="(sysTime, SysTime(Date(-4, 7, 6)));
}
{
auto sysTime = SysTime(Date(-4, 2, 29));
sysTime.add!"years"(5);
_assertPred!"=="(sysTime, SysTime(Date(1, 3, 1)));
}
{
auto sysTime = SysTime(Date(4, 2, 29));
sysTime.add!"years"(-5);
_assertPred!"=="(sysTime, SysTime(Date(-1, 3, 1)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.add!"years"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.add!"years"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.add!"years"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.add!"years"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(0, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.add!"years"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.add!"years"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.add!"years"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.add!"years"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(4, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329));
sysTime.add!"years"(-5);
_assertPred!"=="(sysTime, SysTime(DateTime(-1, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329)));
sysTime.add!"years"(5);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329)));
}
{
auto sysTime = SysTime(DateTime(-4, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329));
sysTime.add!"years"(5);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329)));
sysTime.add!"years"(-5);
_assertPred!"=="(sysTime, SysTime(DateTime(-4, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329)));
}
{
auto sysTime = SysTime(DateTime(-4, 2, 29, 5, 5, 5), FracSec.from!"msecs"(555));
sysTime.add!"years"(5);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 3, 1, 5, 5, 5), FracSec.from!"msecs"(555)));
}
{
auto sysTime = SysTime(DateTime(4, 2, 29, 5, 5, 5), FracSec.from!"msecs"(555));
sysTime.add!"years"(-5);
_assertPred!"=="(sysTime, SysTime(DateTime(-1, 3, 1, 5, 5, 5), FracSec.from!"msecs"(555)));
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.add!"years"(4)));
//static assert(!__traits(compiles, ist.add!"years"(4)));
}
}
//Test add!"years"() with AllowDayOverlow.no
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.add!"years"(7, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(2006, 7, 6)));
sysTime.add!"years"(-9, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1997, 7, 6)));
}
{
auto sysTime = SysTime(Date(1999, 2, 28));
sysTime.add!"years"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(2000, 2, 28)));
}
{
auto sysTime = SysTime(Date(2000, 2, 29));
sysTime.add!"years"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 28)));
}
{
auto sysTime = SysTime(DateTime(1999, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234));
sysTime.add!"years"(7, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(2006, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234)));
sysTime.add!"years"(-9, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1997, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234)));
}
{
auto sysTime = SysTime(DateTime(1999, 2, 28, 0, 7, 2), FracSec.from!"usecs"(1207));
sysTime.add!"years"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(2000, 2, 28, 0, 7, 2), FracSec.from!"usecs"(1207)));
}
{
auto sysTime = SysTime(DateTime(2000, 2, 29, 0, 7, 2), FracSec.from!"usecs"(1207));
sysTime.add!"years"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 2, 28, 0, 7, 2), FracSec.from!"usecs"(1207)));
}
//Test B.C.
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.add!"years"(-7, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2006, 7, 6)));
sysTime.add!"years"(9, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 7, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 2, 28));
sysTime.add!"years"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 2, 28)));
}
{
auto sysTime = SysTime(Date(-2000, 2, 29));
sysTime.add!"years"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 2, 28)));
}
{
auto sysTime = SysTime(DateTime(-1999, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234));
sysTime.add!"years"(-7, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-2006, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234)));
sysTime.add!"years"(9, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-1997, 7, 6, 12, 7, 3), FracSec.from!"msecs"(234)));
}
{
auto sysTime = SysTime(DateTime(-1999, 2, 28, 3, 3, 3), FracSec.from!"hnsecs"(3));
sysTime.add!"years"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-2000, 2, 28, 3, 3, 3), FracSec.from!"hnsecs"(3)));
}
{
auto sysTime = SysTime(DateTime(-2000, 2, 29, 3, 3, 3), FracSec.from!"hnsecs"(3));
sysTime.add!"years"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 2, 28, 3, 3, 3), FracSec.from!"hnsecs"(3)));
}
//Test Both
{
auto sysTime = SysTime(Date(4, 7, 6));
sysTime.add!"years"(-5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1, 7, 6)));
sysTime.add!"years"(5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 7, 6)));
}
{
auto sysTime = SysTime(Date(-4, 7, 6));
sysTime.add!"years"(5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1, 7, 6)));
sysTime.add!"years"(-5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-4, 7, 6)));
}
{
auto sysTime = SysTime(Date(4, 7, 6));
sysTime.add!"years"(-8, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-4, 7, 6)));
sysTime.add!"years"(8, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 7, 6)));
}
{
auto sysTime = SysTime(Date(-4, 7, 6));
sysTime.add!"years"(8, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 7, 6)));
sysTime.add!"years"(-8, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-4, 7, 6)));
}
{
auto sysTime = SysTime(Date(-4, 2, 29));
sysTime.add!"years"(5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1, 2, 28)));
}
{
auto sysTime = SysTime(Date(4, 2, 29));
sysTime.add!"years"(-5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1, 2, 28)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.add!"years"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.add!"years"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.add!"years"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.add!"years"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(0, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.add!"years"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.add!"years"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.add!"years"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.add!"years"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(4, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329));
sysTime.add!"years"(-5);
_assertPred!"=="(sysTime, SysTime(DateTime(-1, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329)));
sysTime.add!"years"(5);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329)));
}
{
auto sysTime = SysTime(DateTime(4, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329));
sysTime.add!"years"(-5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-1, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329)));
sysTime.add!"years"(5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329)));
}
{
auto sysTime = SysTime(DateTime(-4, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329));
sysTime.add!"years"(5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329)));
sysTime.add!"years"(-5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-4, 7, 6, 14, 7, 1), FracSec.from!"usecs"(54329)));
}
{
auto sysTime = SysTime(DateTime(-4, 2, 29, 5, 5, 5), FracSec.from!"msecs"(555));
sysTime.add!"years"(5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 2, 28, 5, 5, 5), FracSec.from!"msecs"(555)));
}
{
auto sysTime = SysTime(DateTime(4, 2, 29, 5, 5, 5), FracSec.from!"msecs"(555));
sysTime.add!"years"(-5, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-1, 2, 28, 5, 5, 5), FracSec.from!"msecs"(555)));
}
}
}
//Test add!"months"() with AllowDayOverlow.yes
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.add!"months"(3);
_assertPred!"=="(sysTime, SysTime(Date(1999, 10, 6)));
sysTime.add!"months"(-4);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.add!"months"(6);
_assertPred!"=="(sysTime, SysTime(Date(2000, 1, 6)));
sysTime.add!"months"(-6);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 6)));
}
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.add!"months"(27);
_assertPred!"=="(sysTime, SysTime(Date(2001, 10, 6)));
sysTime.add!"months"(-28);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(1999, 5, 31));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 1)));
}
{
auto sysTime = SysTime(Date(1999, 5, 31));
sysTime.add!"months"(-1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 5, 1)));
}
{
auto sysTime = SysTime(Date(1999, 2, 28));
sysTime.add!"months"(12);
_assertPred!"=="(sysTime, SysTime(Date(2000, 2, 28)));
}
{
auto sysTime = SysTime(Date(2000, 2, 29));
sysTime.add!"months"(12);
_assertPred!"=="(sysTime, SysTime(Date(2001, 3, 1)));
}
{
auto sysTime = SysTime(Date(1999, 7, 31));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 8, 31)));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 10, 1)));
}
{
auto sysTime = SysTime(Date(1998, 8, 31));
sysTime.add!"months"(13);
_assertPred!"=="(sysTime, SysTime(Date(1999, 10, 1)));
sysTime.add!"months"(-13);
_assertPred!"=="(sysTime, SysTime(Date(1998, 9, 1)));
}
{
auto sysTime = SysTime(Date(1997, 12, 31));
sysTime.add!"months"(13);
_assertPred!"=="(sysTime, SysTime(Date(1999, 1, 31)));
sysTime.add!"months"(-13);
_assertPred!"=="(sysTime, SysTime(Date(1997, 12, 31)));
}
{
auto sysTime = SysTime(Date(1997, 12, 31));
sysTime.add!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(1999, 3, 3)));
sysTime.add!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(1998, 1, 3)));
}
{
auto sysTime = SysTime(Date(1998, 12, 31));
sysTime.add!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(2000, 3, 2)));
sysTime.add!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(1999, 1, 2)));
}
{
auto sysTime = SysTime(Date(1999, 12, 31));
sysTime.add!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(2001, 3, 3)));
sysTime.add!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(2000, 1, 3)));
}
{
auto sysTime = SysTime(DateTime(1999, 7, 6, 12, 2, 7), FracSec.from!"usecs"(5007));
sysTime.add!"months"(3);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 10, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
sysTime.add!"months"(-4);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 6, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
}
{
auto sysTime = SysTime(DateTime(1998, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.add!"months"(14);
_assertPred!"=="(sysTime, SysTime(DateTime(2000, 3, 2, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.add!"months"(-14);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 1, 2, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
{
auto sysTime = SysTime(DateTime(1999, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.add!"months"(14);
_assertPred!"=="(sysTime, SysTime(DateTime(2001, 3, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.add!"months"(-14);
_assertPred!"=="(sysTime, SysTime(DateTime(2000, 1, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
//Test B.C.
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.add!"months"(3);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 10, 6)));
sysTime.add!"months"(-4);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.add!"months"(6);
_assertPred!"=="(sysTime, SysTime(Date(-1998, 1, 6)));
sysTime.add!"months"(-6);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.add!"months"(-27);
_assertPred!"=="(sysTime, SysTime(Date(-2001, 4, 6)));
sysTime.add!"months"(28);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 8, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 5, 31));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 1)));
}
{
auto sysTime = SysTime(Date(-1999, 5, 31));
sysTime.add!"months"(-1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 5, 1)));
}
{
auto sysTime = SysTime(Date(-1999, 2, 28));
sysTime.add!"months"(-12);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 2, 28)));
}
{
auto sysTime = SysTime(Date(-2000, 2, 29));
sysTime.add!"months"(-12);
_assertPred!"=="(sysTime, SysTime(Date(-2001, 3, 1)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 31));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 8, 31)));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 10, 1)));
}
{
auto sysTime = SysTime(Date(-1998, 8, 31));
sysTime.add!"months"(13);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 10, 1)));
sysTime.add!"months"(-13);
_assertPred!"=="(sysTime, SysTime(Date(-1998, 9, 1)));
}
{
auto sysTime = SysTime(Date(-1997, 12, 31));
sysTime.add!"months"(13);
_assertPred!"=="(sysTime, SysTime(Date(-1995, 1, 31)));
sysTime.add!"months"(-13);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 12, 31)));
}
{
auto sysTime = SysTime(Date(-1997, 12, 31));
sysTime.add!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(-1995, 3, 3)));
sysTime.add!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(-1996, 1, 3)));
}
{
auto sysTime = SysTime(Date(-2002, 12, 31));
sysTime.add!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 3, 2)));
sysTime.add!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(-2001, 1, 2)));
}
{
auto sysTime = SysTime(Date(-2001, 12, 31));
sysTime.add!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 3, 3)));
sysTime.add!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 1, 3)));
}
{
auto sysTime = SysTime(DateTime(-1999, 7, 6, 12, 2, 7), FracSec.from!"usecs"(5007));
sysTime.add!"months"(3);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 10, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
sysTime.add!"months"(-4);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 6, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
}
{
auto sysTime = SysTime(DateTime(-2002, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.add!"months"(14);
_assertPred!"=="(sysTime, SysTime(DateTime(-2000, 3, 2, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.add!"months"(-14);
_assertPred!"=="(sysTime, SysTime(DateTime(-2001, 1, 2, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
{
auto sysTime = SysTime(DateTime(-2001, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.add!"months"(14);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 3, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.add!"months"(-14);
_assertPred!"=="(sysTime, SysTime(DateTime(-2000, 1, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
//Test Both
{
auto sysTime = SysTime(Date(1, 1, 1));
sysTime.add!"months"(-1);
_assertPred!"=="(sysTime, SysTime(Date(0, 12, 1)));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(1, 1, 1)));
}
{
auto sysTime = SysTime(Date(4, 1, 1));
sysTime.add!"months"(-48);
_assertPred!"=="(sysTime, SysTime(Date(0, 1, 1)));
sysTime.add!"months"(48);
_assertPred!"=="(sysTime, SysTime(Date(4, 1, 1)));
}
{
auto sysTime = SysTime(Date(4, 3, 31));
sysTime.add!"months"(-49);
_assertPred!"=="(sysTime, SysTime(Date(0, 3, 2)));
sysTime.add!"months"(49);
_assertPred!"=="(sysTime, SysTime(Date(4, 4, 2)));
}
{
auto sysTime = SysTime(Date(4, 3, 31));
sysTime.add!"months"(-85);
_assertPred!"=="(sysTime, SysTime(Date(-3, 3, 3)));
sysTime.add!"months"(85);
_assertPred!"=="(sysTime, SysTime(Date(4, 4, 3)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.add!"months"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.add!"months"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.add!"months"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.add!"months"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 7, 9), FracSec.from!"hnsecs"(17));
sysTime.add!"months"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 0, 7, 9), FracSec.from!"hnsecs"(17)));
sysTime.add!"months"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 7, 9), FracSec.from!"hnsecs"(17)));
}
{
auto sysTime = SysTime(DateTime(4, 3, 31, 12, 11, 10), FracSec.from!"msecs"(9));
sysTime.add!"months"(-85);
_assertPred!"=="(sysTime, SysTime(DateTime(-3, 3, 3, 12, 11, 10), FracSec.from!"msecs"(9)));
sysTime.add!"months"(85);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 4, 3, 12, 11, 10), FracSec.from!"msecs"(9)));
}
{
auto sysTime = SysTime(DateTime(-3, 3, 31, 12, 11, 10), FracSec.from!"msecs"(9));
sysTime.add!"months"(85);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 5, 1, 12, 11, 10), FracSec.from!"msecs"(9)));
sysTime.add!"months"(-85);
_assertPred!"=="(sysTime, SysTime(DateTime(-3, 4, 1, 12, 11, 10), FracSec.from!"msecs"(9)));
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.add!"months"(4)));
//static assert(!__traits(compiles, ist.add!"months"(4)));
}
}
//Test add!"months"() with AllowDayOverlow.no
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.add!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 10, 6)));
sysTime.add!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.add!"months"(6, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(2000, 1, 6)));
sysTime.add!"months"(-6, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 6)));
}
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.add!"months"(27, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(2001, 10, 6)));
sysTime.add!"months"(-28, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(1999, 5, 31));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 30)));
}
{
auto sysTime = SysTime(Date(1999, 5, 31));
sysTime.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 4, 30)));
}
{
auto sysTime = SysTime(Date(1999, 2, 28));
sysTime.add!"months"(12, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(2000, 2, 28)));
}
{
auto sysTime = SysTime(Date(2000, 2, 29));
sysTime.add!"months"(12, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(2001, 2, 28)));
}
{
auto sysTime = SysTime(Date(1999, 7, 31));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 8, 31)));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 9, 30)));
}
{
auto sysTime = SysTime(Date(1998, 8, 31));
sysTime.add!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 9, 30)));
sysTime.add!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1998, 8, 30)));
}
{
auto sysTime = SysTime(Date(1997, 12, 31));
sysTime.add!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 1, 31)));
sysTime.add!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1997, 12, 31)));
}
{
auto sysTime = SysTime(Date(1997, 12, 31));
sysTime.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 28)));
sysTime.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1997, 12, 28)));
}
{
auto sysTime = SysTime(Date(1998, 12, 31));
sysTime.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(2000, 2, 29)));
sysTime.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1998, 12, 29)));
}
{
auto sysTime = SysTime(Date(1999, 12, 31));
sysTime.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(2001, 2, 28)));
sysTime.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 12, 28)));
}
{
auto sysTime = SysTime(DateTime(1999, 7, 6, 12, 2, 7), FracSec.from!"usecs"(5007));
sysTime.add!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 10, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
sysTime.add!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 6, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
}
{
auto sysTime = SysTime(DateTime(1998, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(2000, 2, 29, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1998, 12, 29, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
{
auto sysTime = SysTime(DateTime(1999, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(2001, 2, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 12, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
//Test B.C.
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.add!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 10, 6)));
sysTime.add!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.add!"months"(6, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1998, 1, 6)));
sysTime.add!"months"(-6, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.add!"months"(-27, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2001, 4, 6)));
sysTime.add!"months"(28, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 8, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 5, 31));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 6, 30)));
}
{
auto sysTime = SysTime(Date(-1999, 5, 31));
sysTime.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 4, 30)));
}
{
auto sysTime = SysTime(Date(-1999, 2, 28));
sysTime.add!"months"(-12, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 2, 28)));
}
{
auto sysTime = SysTime(Date(-2000, 2, 29));
sysTime.add!"months"(-12, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2001, 2, 28)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 31));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 8, 31)));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 9, 30)));
}
{
auto sysTime = SysTime(Date(-1998, 8, 31));
sysTime.add!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 9, 30)));
sysTime.add!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1998, 8, 30)));
}
{
auto sysTime = SysTime(Date(-1997, 12, 31));
sysTime.add!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1995, 1, 31)));
sysTime.add!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 12, 31)));
}
{
auto sysTime = SysTime(Date(-1997, 12, 31));
sysTime.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1995, 2, 28)));
sysTime.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 12, 28)));
}
{
auto sysTime = SysTime(Date(-2002, 12, 31));
sysTime.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 2, 29)));
sysTime.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2002, 12, 29)));
}
{
auto sysTime = SysTime(Date(-2001, 12, 31));
sysTime.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 2, 28)));
sysTime.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2001, 12, 28)));
}
{
auto sysTime = SysTime(DateTime(-1999, 7, 6, 12, 2, 7), FracSec.from!"usecs"(5007));
sysTime.add!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 10, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
sysTime.add!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 6, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
}
{
auto sysTime = SysTime(DateTime(-2002, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-2000, 2, 29, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-2002, 12, 29, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
{
auto sysTime = SysTime(DateTime(-2001, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 2, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-2001, 12, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
//Test Both
{
auto sysTime = SysTime(Date(1, 1, 1));
sysTime.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(0, 12, 1)));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1, 1, 1)));
}
{
auto sysTime = SysTime(Date(4, 1, 1));
sysTime.add!"months"(-48, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(0, 1, 1)));
sysTime.add!"months"(48, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 1, 1)));
}
{
auto sysTime = SysTime(Date(4, 3, 31));
sysTime.add!"months"(-49, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(0, 2, 29)));
sysTime.add!"months"(49, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 3, 29)));
}
{
auto sysTime = SysTime(Date(4, 3, 31));
sysTime.add!"months"(-85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-3, 2, 28)));
sysTime.add!"months"(85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 3, 28)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 7, 9), FracSec.from!"hnsecs"(17));
sysTime.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 0, 7, 9), FracSec.from!"hnsecs"(17)));
sysTime.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 7, 9), FracSec.from!"hnsecs"(17)));
}
{
auto sysTime = SysTime(DateTime(4, 3, 31, 12, 11, 10), FracSec.from!"msecs"(9));
sysTime.add!"months"(-85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-3, 2, 28, 12, 11, 10), FracSec.from!"msecs"(9)));
sysTime.add!"months"(85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 3, 28, 12, 11, 10), FracSec.from!"msecs"(9)));
}
{
auto sysTime = SysTime(DateTime(-3, 3, 31, 12, 11, 10), FracSec.from!"msecs"(9));
sysTime.add!"months"(85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 4, 30, 12, 11, 10), FracSec.from!"msecs"(9)));
sysTime.add!"months"(-85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-3, 3, 30, 12, 11, 10), FracSec.from!"msecs"(9)));
}
}
}
/++
Adds the given number of years or months to this $(D SysTime). A
negative number will subtract.
The difference between rolling and adding is that rolling does not
affect larger units. So, if you roll a $(D SysTime) 12 months, you
get the exact same $(D SysTime). However, the days can still be affected
due to the differing number of days in each month.
Because there are no units larger than years, there is no difference
between adding and rolling years.
Params:
units = The type of units to add ("years" or "months").
value = The number of months or years to add to this
$(D SysTime).
allowOverflow = Whether the days should be allowed to overflow,
causing the month to increment.
Examples:
--------------------
auto st1 = SysTime(DateTime(2010, 1, 1, 12, 33, 33));
st1.roll!"months"(1);
assert(st1 == SysTime(DateTime(2010, 2, 1, 12, 33, 33)));
auto st2 = SysTime(DateTime(2010, 1, 1, 12, 33, 33));
st2.roll!"months"(-1);
assert(st2 == SysTime(DateTime(2010, 12, 1, 12, 33, 33)));
auto st3 = SysTime(DateTime(1999, 1, 29, 12, 33, 33));
st3.roll!"months"(1);
assert(st3 == SysTime(DateTime(1999, 3, 1, 12, 33, 33)));
auto st4 = SysTime(DateTime(1999, 1, 29, 12, 33, 33));
st4.roll!"months"(1, AllowDayOverflow.no);
assert(st4 == SysTime(DateTime(1999, 2, 28, 12, 33, 33)));
auto st5 = SysTime(DateTime(2000, 2, 29, 12, 30, 33));
st5.roll!"years"(1);
assert(st5 == SysTime(DateTime(2001, 3, 1, 12, 30, 33)));
auto st6 = SysTime(DateTime(2000, 2, 29, 12, 30, 33));
st6.roll!"years"(1, AllowDayOverflow.no);
assert(st6 == SysTime(DateTime(2001, 2, 28, 12, 30, 33)));
--------------------
+/
/+ref SysTime+/ void roll(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes) nothrow
if(units == "years")
{
add!"years"(value, allowOverflow);
}
unittest
{
version(testStdDateTime)
{
//Verify Examples.
auto st1 = SysTime(DateTime(2010, 1, 1, 12, 33, 33));
st1.roll!"months"(1);
assert(st1 == SysTime(DateTime(2010, 2, 1, 12, 33, 33)));
auto st2 = SysTime(DateTime(2010, 1, 1, 12, 33, 33));
st2.roll!"months"(-1);
assert(st2 == SysTime(DateTime(2010, 12, 1, 12, 33, 33)));
auto st3 = SysTime(DateTime(1999, 1, 29, 12, 33, 33));
st3.roll!"months"(1);
assert(st3 == SysTime(DateTime(1999, 3, 1, 12, 33, 33)));
auto st4 = SysTime(DateTime(1999, 1, 29, 12, 33, 33));
st4.roll!"months"(1, AllowDayOverflow.no);
assert(st4 == SysTime(DateTime(1999, 2, 28, 12, 33, 33)));
auto st5 = SysTime(DateTime(2000, 2, 29, 12, 30, 33));
st5.roll!"years"(1);
assert(st5 == SysTime(DateTime(2001, 3, 1, 12, 30, 33)));
auto st6 = SysTime(DateTime(2000, 2, 29, 12, 30, 33));
st6.roll!"years"(1, AllowDayOverflow.no);
assert(st6 == SysTime(DateTime(2001, 2, 28, 12, 30, 33)));
}
}
unittest
{
version(testStdDateTime)
{
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st.roll!"years"(4)));
static assert(!__traits(compiles, cst.roll!"years"(4)));
//static assert(!__traits(compiles, ist.roll!"years"(4)));
}
}
//Shares documentation with "years" version.
/+ref SysTime+/ void roll(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes) nothrow
if(units == "months")
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
auto date = Date(cast(int)days);
date.roll!"months"(value, allowOverflow);
days = date.dayOfGregorianCal - 1;
if(days < 0)
{
hnsecs -= convert!("hours", "hnsecs")(24);
++days;
}
immutable newDaysHNSecs = convert!("days", "hnsecs")(days);
adjTime = newDaysHNSecs + hnsecs;
}
//Test roll!"months"() with AllowDayOverlow.yes
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.roll!"months"(3);
_assertPred!"=="(sysTime, SysTime(Date(1999, 10, 6)));
sysTime.roll!"months"(-4);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.roll!"months"(6);
_assertPred!"=="(sysTime, SysTime(Date(1999, 1, 6)));
sysTime.roll!"months"(-6);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 6)));
}
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.roll!"months"(27);
_assertPred!"=="(sysTime, SysTime(Date(1999, 10, 6)));
sysTime.roll!"months"(-28);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(1999, 5, 31));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 1)));
}
{
auto sysTime = SysTime(Date(1999, 5, 31));
sysTime.roll!"months"(-1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 5, 1)));
}
{
auto sysTime = SysTime(Date(1999, 2, 28));
sysTime.roll!"months"(12);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 28)));
}
{
auto sysTime = SysTime(Date(2000, 2, 29));
sysTime.roll!"months"(12);
_assertPred!"=="(sysTime, SysTime(Date(2000, 2, 29)));
}
{
auto sysTime = SysTime(Date(1999, 7, 31));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 8, 31)));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 10, 1)));
}
{
auto sysTime = SysTime(Date(1998, 8, 31));
sysTime.roll!"months"(13);
_assertPred!"=="(sysTime, SysTime(Date(1998, 10, 1)));
sysTime.roll!"months"(-13);
_assertPred!"=="(sysTime, SysTime(Date(1998, 9, 1)));
}
{
auto sysTime = SysTime(Date(1997, 12, 31));
sysTime.roll!"months"(13);
_assertPred!"=="(sysTime, SysTime(Date(1997, 1, 31)));
sysTime.roll!"months"(-13);
_assertPred!"=="(sysTime, SysTime(Date(1997, 12, 31)));
}
{
auto sysTime = SysTime(Date(1997, 12, 31));
sysTime.roll!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(1997, 3, 3)));
sysTime.roll!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(1997, 1, 3)));
}
{
auto sysTime = SysTime(Date(1998, 12, 31));
sysTime.roll!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(1998, 3, 3)));
sysTime.roll!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(1998, 1, 3)));
}
{
auto sysTime = SysTime(Date(1999, 12, 31));
sysTime.roll!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(1999, 3, 3)));
sysTime.roll!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(1999, 1, 3)));
}
{
auto sysTime = SysTime(DateTime(1999, 7, 6, 12, 2, 7), FracSec.from!"usecs"(5007));
sysTime.roll!"months"(3);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 10, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
sysTime.roll!"months"(-4);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 6, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
}
{
auto sysTime = SysTime(DateTime(1998, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.roll!"months"(14);
_assertPred!"=="(sysTime, SysTime(DateTime(1998, 3, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.roll!"months"(-14);
_assertPred!"=="(sysTime, SysTime(DateTime(1998, 1, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
{
auto sysTime = SysTime(DateTime(1999, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.roll!"months"(14);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 3, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.roll!"months"(-14);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 1, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
//Test B.C.
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.roll!"months"(3);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 10, 6)));
sysTime.roll!"months"(-4);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.roll!"months"(6);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 1, 6)));
sysTime.roll!"months"(-6);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.roll!"months"(-27);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 4, 6)));
sysTime.roll!"months"(28);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 8, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 5, 31));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 1)));
}
{
auto sysTime = SysTime(Date(-1999, 5, 31));
sysTime.roll!"months"(-1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 5, 1)));
}
{
auto sysTime = SysTime(Date(-1999, 2, 28));
sysTime.roll!"months"(-12);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 2, 28)));
}
{
auto sysTime = SysTime(Date(-2000, 2, 29));
sysTime.roll!"months"(-12);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 2, 29)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 31));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 8, 31)));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 10, 1)));
}
{
auto sysTime = SysTime(Date(-1998, 8, 31));
sysTime.roll!"months"(13);
_assertPred!"=="(sysTime, SysTime(Date(-1998, 10, 1)));
sysTime.roll!"months"(-13);
_assertPred!"=="(sysTime, SysTime(Date(-1998, 9, 1)));
}
{
auto sysTime = SysTime(Date(-1997, 12, 31));
sysTime.roll!"months"(13);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 1, 31)));
sysTime.roll!"months"(-13);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 12, 31)));
}
{
auto sysTime = SysTime(Date(-1997, 12, 31));
sysTime.roll!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 3, 3)));
sysTime.roll!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 1, 3)));
}
{
auto sysTime = SysTime(Date(-2002, 12, 31));
sysTime.roll!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(-2002, 3, 3)));
sysTime.roll!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(-2002, 1, 3)));
}
{
auto sysTime = SysTime(Date(-2001, 12, 31));
sysTime.roll!"months"(14);
_assertPred!"=="(sysTime, SysTime(Date(-2001, 3, 3)));
sysTime.roll!"months"(-14);
_assertPred!"=="(sysTime, SysTime(Date(-2001, 1, 3)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"months"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"months"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"months"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"months"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(-1999, 7, 6, 12, 2, 7), FracSec.from!"hnsecs"(5007));
sysTime.roll!"months"(3);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 10, 6, 12, 2, 7), FracSec.from!"hnsecs"(5007)));
sysTime.roll!"months"(-4);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 6, 6, 12, 2, 7), FracSec.from!"hnsecs"(5007)));
}
{
auto sysTime = SysTime(DateTime(-2002, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.roll!"months"(14);
_assertPred!"=="(sysTime, SysTime(DateTime(-2002, 3, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.roll!"months"(-14);
_assertPred!"=="(sysTime, SysTime(DateTime(-2002, 1, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
{
auto sysTime = SysTime(DateTime(-2001, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.roll!"months"(14);
_assertPred!"=="(sysTime, SysTime(DateTime(-2001, 3, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.roll!"months"(-14);
_assertPred!"=="(sysTime, SysTime(DateTime(-2001, 1, 3, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
//Test Both
{
auto sysTime = SysTime(Date(1, 1, 1));
sysTime.roll!"months"(-1);
_assertPred!"=="(sysTime, SysTime(Date(1, 12, 1)));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(1, 1, 1)));
}
{
auto sysTime = SysTime(Date(4, 1, 1));
sysTime.roll!"months"(-48);
_assertPred!"=="(sysTime, SysTime(Date(4, 1, 1)));
sysTime.roll!"months"(48);
_assertPred!"=="(sysTime, SysTime(Date(4, 1, 1)));
}
{
auto sysTime = SysTime(Date(4, 3, 31));
sysTime.roll!"months"(-49);
_assertPred!"=="(sysTime, SysTime(Date(4, 3, 2)));
sysTime.roll!"months"(49);
_assertPred!"=="(sysTime, SysTime(Date(4, 4, 2)));
}
{
auto sysTime = SysTime(Date(4, 3, 31));
sysTime.roll!"months"(-85);
_assertPred!"=="(sysTime, SysTime(Date(4, 3, 2)));
sysTime.roll!"months"(85);
_assertPred!"=="(sysTime, SysTime(Date(4, 4, 2)));
}
{
auto sysTime = SysTime(Date(-1, 1, 1));
sysTime.roll!"months"(-1);
_assertPred!"=="(sysTime, SysTime(Date(-1, 12, 1)));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1, 1, 1)));
}
{
auto sysTime = SysTime(Date(-4, 1, 1));
sysTime.roll!"months"(-48);
_assertPred!"=="(sysTime, SysTime(Date(-4, 1, 1)));
sysTime.roll!"months"(48);
_assertPred!"=="(sysTime, SysTime(Date(-4, 1, 1)));
}
{
auto sysTime = SysTime(Date(-4, 3, 31));
sysTime.roll!"months"(-49);
_assertPred!"=="(sysTime, SysTime(Date(-4, 3, 2)));
sysTime.roll!"months"(49);
_assertPred!"=="(sysTime, SysTime(Date(-4, 4, 2)));
}
{
auto sysTime = SysTime(Date(-4, 3, 31));
sysTime.roll!"months"(-85);
_assertPred!"=="(sysTime, SysTime(Date(-4, 3, 2)));
sysTime.roll!"months"(85);
_assertPred!"=="(sysTime, SysTime(Date(-4, 4, 2)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 7, 9), FracSec.from!"hnsecs"(17));
sysTime.roll!"months"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 12, 1, 0, 7, 9), FracSec.from!"hnsecs"(17)));
sysTime.roll!"months"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 7, 9), FracSec.from!"hnsecs"(17)));
}
{
auto sysTime = SysTime(DateTime(4, 3, 31, 12, 11, 10), FracSec.from!"msecs"(9));
sysTime.roll!"months"(-85);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 3, 2, 12, 11, 10), FracSec.from!"msecs"(9)));
sysTime.roll!"months"(85);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 4, 2, 12, 11, 10), FracSec.from!"msecs"(9)));
}
{
auto sysTime = SysTime(DateTime(-3, 3, 31, 12, 11, 10), FracSec.from!"msecs"(9));
sysTime.roll!"months"(85);
_assertPred!"=="(sysTime, SysTime(DateTime(-3, 5, 1, 12, 11, 10), FracSec.from!"msecs"(9)));
sysTime.roll!"months"(-85);
_assertPred!"=="(sysTime, SysTime(DateTime(-3, 4, 1, 12, 11, 10), FracSec.from!"msecs"(9)));
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.roll!"months"(4)));
//static assert(!__traits(compiles, ist.roll!"months"(4)));
//Verify Examples.
auto st1 = SysTime(DateTime(2010, 1, 1, 12, 33, 33));
st1.roll!"months"(1);
assert(st1 == SysTime(DateTime(2010, 2, 1, 12, 33, 33)));
auto st2 = SysTime(DateTime(2010, 1, 1, 12, 33, 33));
st2.roll!"months"(-1);
assert(st2 == SysTime(DateTime(2010, 12, 1, 12, 33, 33)));
auto st3 = SysTime(DateTime(1999, 1, 29, 12, 33, 33));
st3.roll!"months"(1);
assert(st3 == SysTime(DateTime(1999, 3, 1, 12, 33, 33)));
auto st4 = SysTime(DateTime(1999, 1, 29, 12, 33, 33));
st4.roll!"months"(1, AllowDayOverflow.no);
assert(st4 == SysTime(DateTime(1999, 2, 28, 12, 33, 33)));
}
}
//Test roll!"months"() with AllowDayOverlow.no
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.roll!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 10, 6)));
sysTime.roll!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.roll!"months"(6, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 1, 6)));
sysTime.roll!"months"(-6, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 6)));
}
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.roll!"months"(27, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 10, 6)));
sysTime.roll!"months"(-28, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(1999, 5, 31));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 30)));
}
{
auto sysTime = SysTime(Date(1999, 5, 31));
sysTime.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 4, 30)));
}
{
auto sysTime = SysTime(Date(1999, 2, 28));
sysTime.roll!"months"(12, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 28)));
}
{
auto sysTime = SysTime(Date(2000, 2, 29));
sysTime.roll!"months"(12, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(2000, 2, 29)));
}
{
auto sysTime = SysTime(Date(1999, 7, 31));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 8, 31)));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 9, 30)));
}
{
auto sysTime = SysTime(Date(1998, 8, 31));
sysTime.roll!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1998, 9, 30)));
sysTime.roll!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1998, 8, 30)));
}
{
auto sysTime = SysTime(Date(1997, 12, 31));
sysTime.roll!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1997, 1, 31)));
sysTime.roll!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1997, 12, 31)));
}
{
auto sysTime = SysTime(Date(1997, 12, 31));
sysTime.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1997, 2, 28)));
sysTime.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1997, 12, 28)));
}
{
auto sysTime = SysTime(Date(1998, 12, 31));
sysTime.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1998, 2, 28)));
sysTime.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1998, 12, 28)));
}
{
auto sysTime = SysTime(Date(1999, 12, 31));
sysTime.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 28)));
sysTime.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1999, 12, 28)));
}
{
auto sysTime = SysTime(DateTime(1999, 7, 6, 12, 2, 7), FracSec.from!"usecs"(5007));
sysTime.roll!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 10, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
sysTime.roll!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 6, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
}
{
auto sysTime = SysTime(DateTime(1998, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1998, 2, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1998, 12, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
{
auto sysTime = SysTime(DateTime(1999, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 2, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 12, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
//Test B.C.
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.roll!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 10, 6)));
sysTime.roll!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 6, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.roll!"months"(6, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 1, 6)));
sysTime.roll!"months"(-6, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.roll!"months"(-27, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 4, 6)));
sysTime.roll!"months"(28, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 8, 6)));
}
{
auto sysTime = SysTime(Date(-1999, 5, 31));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 6, 30)));
}
{
auto sysTime = SysTime(Date(-1999, 5, 31));
sysTime.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 4, 30)));
}
{
auto sysTime = SysTime(Date(-1999, 2, 28));
sysTime.roll!"months"(-12, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 2, 28)));
}
{
auto sysTime = SysTime(Date(-2000, 2, 29));
sysTime.roll!"months"(-12, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 2, 29)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 31));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 8, 31)));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 9, 30)));
}
{
auto sysTime = SysTime(Date(-1998, 8, 31));
sysTime.roll!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1998, 9, 30)));
sysTime.roll!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1998, 8, 30)));
}
{
auto sysTime = SysTime(Date(-1997, 12, 31));
sysTime.roll!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 1, 31)));
sysTime.roll!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 12, 31)));
}
{
auto sysTime = SysTime(Date(-1997, 12, 31));
sysTime.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 2, 28)));
sysTime.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1997, 12, 28)));
}
{
auto sysTime = SysTime(Date(-2002, 12, 31));
sysTime.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2002, 2, 28)));
sysTime.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2002, 12, 28)));
}
{
auto sysTime = SysTime(Date(-2001, 12, 31));
sysTime.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2001, 2, 28)));
sysTime.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-2001, 12, 28)));
}
{
auto sysTime = SysTime(DateTime(-1999, 7, 6, 12, 2, 7), FracSec.from!"usecs"(5007));
sysTime.roll!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 10, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
sysTime.roll!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 6, 6, 12, 2, 7), FracSec.from!"usecs"(5007)));
}
{
auto sysTime = SysTime(DateTime(-2002, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-2002, 2, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-2002, 12, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
{
auto sysTime = SysTime(DateTime(-2001, 12, 31, 7, 7, 7), FracSec.from!"hnsecs"(422202));
sysTime.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-2001, 2, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
sysTime.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-2001, 12, 28, 7, 7, 7), FracSec.from!"hnsecs"(422202)));
}
//Test Both
{
auto sysTime = SysTime(Date(1, 1, 1));
sysTime.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1, 12, 1)));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(1, 1, 1)));
}
{
auto sysTime = SysTime(Date(4, 1, 1));
sysTime.roll!"months"(-48, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 1, 1)));
sysTime.roll!"months"(48, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 1, 1)));
}
{
auto sysTime = SysTime(Date(4, 3, 31));
sysTime.roll!"months"(-49, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 2, 29)));
sysTime.roll!"months"(49, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 3, 29)));
}
{
auto sysTime = SysTime(Date(4, 3, 31));
sysTime.roll!"months"(-85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 2, 29)));
sysTime.roll!"months"(85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(4, 3, 29)));
}
{
auto sysTime = SysTime(Date(-1, 1, 1));
sysTime.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1, 12, 1)));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-1, 1, 1)));
}
{
auto sysTime = SysTime(Date(-4, 1, 1));
sysTime.roll!"months"(-48, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-4, 1, 1)));
sysTime.roll!"months"(48, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-4, 1, 1)));
}
{
auto sysTime = SysTime(Date(-4, 3, 31));
sysTime.roll!"months"(-49, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-4, 2, 29)));
sysTime.roll!"months"(49, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-4, 3, 29)));
}
{
auto sysTime = SysTime(Date(-4, 3, 31));
sysTime.roll!"months"(-85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-4, 2, 29)));
sysTime.roll!"months"(85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(Date(-4, 3, 29)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 7, 9), FracSec.from!"hnsecs"(17));
sysTime.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 12, 1, 0, 7, 9), FracSec.from!"hnsecs"(17)));
sysTime.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 7, 9), FracSec.from!"hnsecs"(17)));
}
{
auto sysTime = SysTime(DateTime(4, 3, 31, 12, 11, 10), FracSec.from!"msecs"(9));
sysTime.roll!"months"(-85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 2, 29, 12, 11, 10), FracSec.from!"msecs"(9)));
sysTime.roll!"months"(85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(4, 3, 29, 12, 11, 10), FracSec.from!"msecs"(9)));
}
{
auto sysTime = SysTime(DateTime(-3, 3, 31, 12, 11, 10), FracSec.from!"msecs"(9));
sysTime.roll!"months"(85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-3, 4, 30, 12, 11, 10), FracSec.from!"msecs"(9)));
sysTime.roll!"months"(-85, AllowDayOverflow.no);
_assertPred!"=="(sysTime, SysTime(DateTime(-3, 3, 30, 12, 11, 10), FracSec.from!"msecs"(9)));
}
}
}
/++
Adds the given number of units to this $(D SysTime). A negative number
will subtract.
The difference between rolling and adding is that rolling does not
affect larger units. So, for instance, if you roll a $(D SysTime) one
year's worth of days, then you get the exact same $(D SysTime).
Accepted units are $(D "days"), $(D "minutes"), $(D "hours"),
$(D "minutes"), $(D "seconds"), $(D "msecs"), $(D "usecs"), and
$(D "hnsecs").
Note that when rolling msecs, usecs or hnsecs, they all add up to a
second. So, for example, rolling 1000 msecs is exactly the same as
rolling 100,000 usecs.
Params:
units = The units to add.
value = The number of $(D_PARAM units) to add to this $(D SysTime).
Examples:
--------------------
auto st1 = SysTime(DateTime(2010, 1, 1, 11, 23, 12));
st1.roll!"days"(1);
assert(st1 == SysTime(DateTime(2010, 1, 2, 11, 23, 12)));
st1.roll!"days"(365);
assert(st1 == SysTime(DateTime(2010, 1, 26, 11, 23, 12)));
st1.roll!"days"(-32);
assert(st1 == SysTime(DateTime(2010, 1, 25, 11, 23, 12)));
auto st2 = SysTime(DateTime(2010, 7, 4, 12, 0, 0));
st2.roll!"hours"(1);
assert(st2 == SysTime(DateTime(2010, 7, 4, 13, 0, 0)));
auto st3 = SysTime(DateTime(2010, 1, 1, 0, 0, 0));
st3.roll!"seconds"(-1);
assert(st3 == SysTime(DateTime(2010, 1, 1, 0, 0, 59)));
auto st4 = SysTime(DateTime(2010, 1, 1, 0, 0, 0),
FracSec.from!"usecs"(2_400));
st4.roll!"usecs"(-1_200_000);
assert(st4 == SysTime(DateTime(2010, 1, 1, 0, 0, 0),
FracSec.from!"usecs"(802_400)));
--------------------
+/
/+ref SysTime+/ void roll(string units)(long value) nothrow
if(units == "days")
{
auto hnsecs = adjTime;
auto gdays = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--gdays;
}
auto date = Date(cast(int)gdays);
date.roll!"days"(value);
gdays = date.dayOfGregorianCal - 1;
if(gdays < 0)
{
hnsecs -= convert!("hours", "hnsecs")(24);
++gdays;
}
immutable newDaysHNSecs = convert!("days", "hnsecs")(gdays);
adjTime = newDaysHNSecs + hnsecs;
}
//Verify Examples.
unittest
{
version(testStdDateTime)
{
auto st1 = SysTime(DateTime(2010, 1, 1, 11, 23, 12));
st1.roll!"days"(1);
assert(st1 == SysTime(DateTime(2010, 1, 2, 11, 23, 12)));
st1.roll!"days"(365);
assert(st1 == SysTime(DateTime(2010, 1, 26, 11, 23, 12)));
st1.roll!"days"(-32);
assert(st1 == SysTime(DateTime(2010, 1, 25, 11, 23, 12)));
auto st2 = SysTime(DateTime(2010, 7, 4, 12, 0, 0));
st2.roll!"hours"(1);
assert(st2 == SysTime(DateTime(2010, 7, 4, 13, 0, 0)));
auto st3 = SysTime(DateTime(2010, 1, 1, 0, 0, 0));
st3.roll!"seconds"(-1);
assert(st3 == SysTime(DateTime(2010, 1, 1, 0, 0, 59)));
auto st4 = SysTime(DateTime(2010, 1, 1, 0, 0, 0),
FracSec.from!"usecs"(2_400));
st4.roll!"usecs"(-1_200_000);
assert(st4 == SysTime(DateTime(2010, 1, 1, 0, 0, 0),
FracSec.from!"usecs"(802_400)));
}
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto sysTime = SysTime(Date(1999, 2, 28));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 1)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 28)));
}
{
auto sysTime = SysTime(Date(2000, 2, 28));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(2000, 2, 29)));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(2000, 2, 1)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(Date(2000, 2, 29)));
}
{
auto sysTime = SysTime(Date(1999, 6, 30));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 1)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 6, 30)));
}
{
auto sysTime = SysTime(Date(1999, 7, 31));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 1)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 31)));
}
{
auto sysTime = SysTime(Date(1999, 1, 1));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 1, 31)));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(1999, 1, 1)));
}
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.roll!"days"(9);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 15)));
sysTime.roll!"days"(-11);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 4)));
sysTime.roll!"days"(30);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 3)));
sysTime.roll!"days"(-3);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 31)));
}
{
auto sysTime = SysTime(Date(1999, 7, 6));
sysTime.roll!"days"(365);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 30)));
sysTime.roll!"days"(-365);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 6)));
sysTime.roll!"days"(366);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 31)));
sysTime.roll!"days"(730);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 17)));
sysTime.roll!"days"(-1096);
_assertPred!"=="(sysTime, SysTime(Date(1999, 7, 6)));
}
{
auto sysTime = SysTime(Date(1999, 2, 6));
sysTime.roll!"days"(365);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 7)));
sysTime.roll!"days"(-365);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 6)));
sysTime.roll!"days"(366);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 8)));
sysTime.roll!"days"(730);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 10)));
sysTime.roll!"days"(-1096);
_assertPred!"=="(sysTime, SysTime(Date(1999, 2, 6)));
}
{
auto sysTime = SysTime(DateTime(1999, 2, 28, 7, 9, 2), FracSec.from!"usecs"(234578));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 2, 1, 7, 9, 2), FracSec.from!"usecs"(234578)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 2, 28, 7, 9, 2), FracSec.from!"usecs"(234578)));
}
{
auto sysTime = SysTime(DateTime(1999, 7, 6, 7, 9, 2), FracSec.from!"usecs"(234578));
sysTime.roll!"days"(9);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 7, 15, 7, 9, 2), FracSec.from!"usecs"(234578)));
sysTime.roll!"days"(-11);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 7, 4, 7, 9, 2), FracSec.from!"usecs"(234578)));
sysTime.roll!"days"(30);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 7, 3, 7, 9, 2), FracSec.from!"usecs"(234578)));
sysTime.roll!"days"(-3);
_assertPred!"=="(sysTime, SysTime(DateTime(1999, 7, 31, 7, 9, 2), FracSec.from!"usecs"(234578)));
}
//Test B.C.
{
auto sysTime = SysTime(Date(-1999, 2, 28));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 2, 1)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 2, 28)));
}
{
auto sysTime = SysTime(Date(-2000, 2, 28));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 2, 29)));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 2, 1)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(Date(-2000, 2, 29)));
}
{
auto sysTime = SysTime(Date(-1999, 6, 30));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 6, 1)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 6, 30)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 31));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 1)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 31)));
}
{
auto sysTime = SysTime(Date(-1999, 1, 1));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 1, 31)));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 1, 1)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.roll!"days"(9);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 15)));
sysTime.roll!"days"(-11);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 4)));
sysTime.roll!"days"(30);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 3)));
sysTime.roll!"days"(-3);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 31)));
}
{
auto sysTime = SysTime(Date(-1999, 7, 6));
sysTime.roll!"days"(365);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 30)));
sysTime.roll!"days"(-365);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 6)));
sysTime.roll!"days"(366);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 31)));
sysTime.roll!"days"(730);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 17)));
sysTime.roll!"days"(-1096);
_assertPred!"=="(sysTime, SysTime(Date(-1999, 7, 6)));
}
{
auto sysTime = SysTime(DateTime(-1999, 2, 28, 7, 9, 2), FracSec.from!"usecs"(234578));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 2, 1, 7, 9, 2), FracSec.from!"usecs"(234578)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 2, 28, 7, 9, 2), FracSec.from!"usecs"(234578)));
}
{
auto sysTime = SysTime(DateTime(-1999, 7, 6, 7, 9, 2), FracSec.from!"usecs"(234578));
sysTime.roll!"days"(9);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 7, 15, 7, 9, 2), FracSec.from!"usecs"(234578)));
sysTime.roll!"days"(-11);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 7, 4, 7, 9, 2), FracSec.from!"usecs"(234578)));
sysTime.roll!"days"(30);
_assertPred!"=="(sysTime, SysTime(DateTime(-1999, 7, 3, 7, 9, 2), FracSec.from!"usecs"(234578)));
sysTime.roll!"days"(-3);
}
//Test Both
{
auto sysTime = SysTime(Date(1, 7, 6));
sysTime.roll!"days"(-365);
_assertPred!"=="(sysTime, SysTime(Date(1, 7, 13)));
sysTime.roll!"days"(365);
_assertPred!"=="(sysTime, SysTime(Date(1, 7, 6)));
sysTime.roll!"days"(-731);
_assertPred!"=="(sysTime, SysTime(Date(1, 7, 19)));
sysTime.roll!"days"(730);
_assertPred!"=="(sysTime, SysTime(Date(1, 7, 5)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"days"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"days"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(1, 7, 6, 13, 13, 9), FracSec.from!"msecs"(22));
sysTime.roll!"days"(-365);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 7, 13, 13, 13, 9), FracSec.from!"msecs"(22)));
sysTime.roll!"days"(365);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 7, 6, 13, 13, 9), FracSec.from!"msecs"(22)));
sysTime.roll!"days"(-731);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 7, 19, 13, 13, 9), FracSec.from!"msecs"(22)));
sysTime.roll!"days"(730);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 7, 5, 13, 13, 9), FracSec.from!"msecs"(22)));
}
{
auto sysTime = SysTime(DateTime(0, 7, 6, 13, 13, 9), FracSec.from!"msecs"(22));
sysTime.roll!"days"(-365);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 7, 13, 13, 13, 9), FracSec.from!"msecs"(22)));
sysTime.roll!"days"(365);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 7, 6, 13, 13, 9), FracSec.from!"msecs"(22)));
sysTime.roll!"days"(-731);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 7, 19, 13, 13, 9), FracSec.from!"msecs"(22)));
sysTime.roll!"days"(730);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 7, 5, 13, 13, 9), FracSec.from!"msecs"(22)));
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.roll!"days"(4)));
//static assert(!__traits(compiles, ist.roll!"days"(4)));
//Verify Examples.
auto st = SysTime(DateTime(2010, 1, 1, 11, 23, 12));
st.roll!"days"(1);
assert(st == SysTime(DateTime(2010, 1, 2, 11, 23, 12)));
st.roll!"days"(365);
assert(st == SysTime(DateTime(2010, 1, 26, 11, 23, 12)));
st.roll!"days"(-32);
assert(st == SysTime(DateTime(2010, 1, 25, 11, 23, 12)));
}
}
//Shares documentation with "days" version.
/+ref SysTime+/ void roll(string units)(long value) nothrow
if(units == "hours" ||
units == "minutes" ||
units == "seconds")
{
try
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
immutable hour = splitUnitsFromHNSecs!"hours"(hnsecs);
immutable minute = splitUnitsFromHNSecs!"minutes"(hnsecs);
immutable second = splitUnitsFromHNSecs!"seconds"(hnsecs);
auto dateTime = DateTime(Date(cast(int)days), TimeOfDay(cast(int)hour, cast(int)minute, cast(int)second));
dateTime.roll!units(value);
--days;
hnsecs += convert!("hours", "hnsecs")(dateTime.hour);
hnsecs += convert!("minutes", "hnsecs")(dateTime.minute);
hnsecs += convert!("seconds", "hnsecs")(dateTime.second);
if(days < 0)
{
hnsecs -= convert!("hours", "hnsecs")(24);
++days;
}
immutable newDaysHNSecs = convert!("days", "hnsecs")(days);
adjTime = newDaysHNSecs + hnsecs;
}
catch(Exception e)
assert(0, "Either DateTime's constructor or TimeOfDay's constructor threw.");
}
//Test roll!"hours"().
unittest
{
version(testStdDateTime)
{
static void TestST(SysTime orig, int hours, in SysTime expected, size_t line = __LINE__)
{
orig.roll!"hours"(hours);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 0, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 1, SysTime(DateTime(1999, 7, 6, 13, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 2, SysTime(DateTime(1999, 7, 6, 14, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 3, SysTime(DateTime(1999, 7, 6, 15, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 4, SysTime(DateTime(1999, 7, 6, 16, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 5, SysTime(DateTime(1999, 7, 6, 17, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 6, SysTime(DateTime(1999, 7, 6, 18, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 7, SysTime(DateTime(1999, 7, 6, 19, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 8, SysTime(DateTime(1999, 7, 6, 20, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 9, SysTime(DateTime(1999, 7, 6, 21, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 10, SysTime(DateTime(1999, 7, 6, 22, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 11, SysTime(DateTime(1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 12, SysTime(DateTime(1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 13, SysTime(DateTime(1999, 7, 6, 1, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 14, SysTime(DateTime(1999, 7, 6, 2, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 15, SysTime(DateTime(1999, 7, 6, 3, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 16, SysTime(DateTime(1999, 7, 6, 4, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 17, SysTime(DateTime(1999, 7, 6, 5, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 18, SysTime(DateTime(1999, 7, 6, 6, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 19, SysTime(DateTime(1999, 7, 6, 7, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 20, SysTime(DateTime(1999, 7, 6, 8, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 21, SysTime(DateTime(1999, 7, 6, 9, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 22, SysTime(DateTime(1999, 7, 6, 10, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 23, SysTime(DateTime(1999, 7, 6, 11, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 24, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 25, SysTime(DateTime(1999, 7, 6, 13, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 50, SysTime(DateTime(1999, 7, 6, 14, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 10_000, SysTime(DateTime(1999, 7, 6, 4, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -1, SysTime(DateTime(1999, 7, 6, 11, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -2, SysTime(DateTime(1999, 7, 6, 10, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -3, SysTime(DateTime(1999, 7, 6, 9, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -4, SysTime(DateTime(1999, 7, 6, 8, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -5, SysTime(DateTime(1999, 7, 6, 7, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -6, SysTime(DateTime(1999, 7, 6, 6, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -7, SysTime(DateTime(1999, 7, 6, 5, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -8, SysTime(DateTime(1999, 7, 6, 4, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -9, SysTime(DateTime(1999, 7, 6, 3, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -10, SysTime(DateTime(1999, 7, 6, 2, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -11, SysTime(DateTime(1999, 7, 6, 1, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -12, SysTime(DateTime(1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -13, SysTime(DateTime(1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -14, SysTime(DateTime(1999, 7, 6, 22, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -15, SysTime(DateTime(1999, 7, 6, 21, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -16, SysTime(DateTime(1999, 7, 6, 20, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -17, SysTime(DateTime(1999, 7, 6, 19, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -18, SysTime(DateTime(1999, 7, 6, 18, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -19, SysTime(DateTime(1999, 7, 6, 17, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -20, SysTime(DateTime(1999, 7, 6, 16, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -21, SysTime(DateTime(1999, 7, 6, 15, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -22, SysTime(DateTime(1999, 7, 6, 14, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -23, SysTime(DateTime(1999, 7, 6, 13, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -24, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -25, SysTime(DateTime(1999, 7, 6, 11, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -50, SysTime(DateTime(1999, 7, 6, 10, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -10_000, SysTime(DateTime(1999, 7, 6, 20, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)), 1, SysTime(DateTime(1999, 7, 6, 1, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)), 0, SysTime(DateTime(1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)), -1, SysTime(DateTime(1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)), 1, SysTime(DateTime(1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)), 0, SysTime(DateTime(1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)), -1, SysTime(DateTime(1999, 7, 6, 22, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 7, 31, 23, 30, 33), FracSec.from!"msecs"(45)), 1, SysTime(DateTime(1999, 7, 31, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 8, 1, 0, 30, 33), FracSec.from!"msecs"(45)), -1, SysTime(DateTime(1999, 8, 1, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 12, 31, 23, 30, 33), FracSec.from!"msecs"(45)), 1, SysTime(DateTime(1999, 12, 31, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(2000, 1, 1, 0, 30, 33), FracSec.from!"msecs"(45)), -1, SysTime(DateTime(2000, 1, 1, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 2, 28, 23, 30, 33), FracSec.from!"msecs"(45)), 25, SysTime(DateTime(1999, 2, 28, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1999, 3, 2, 0, 30, 33), FracSec.from!"msecs"(45)), -25, SysTime(DateTime(1999, 3, 2, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(2000, 2, 28, 23, 30, 33), FracSec.from!"msecs"(45)), 25, SysTime(DateTime(2000, 2, 28, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(2000, 3, 1, 0, 30, 33), FracSec.from!"msecs"(45)), -25, SysTime(DateTime(2000, 3, 1, 23, 30, 33), FracSec.from!"msecs"(45)));
//Test B.C.
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 0, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 1, SysTime(DateTime(-1999, 7, 6, 13, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 2, SysTime(DateTime(-1999, 7, 6, 14, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 3, SysTime(DateTime(-1999, 7, 6, 15, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 4, SysTime(DateTime(-1999, 7, 6, 16, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 5, SysTime(DateTime(-1999, 7, 6, 17, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 6, SysTime(DateTime(-1999, 7, 6, 18, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 7, SysTime(DateTime(-1999, 7, 6, 19, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 8, SysTime(DateTime(-1999, 7, 6, 20, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 9, SysTime(DateTime(-1999, 7, 6, 21, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 10, SysTime(DateTime(-1999, 7, 6, 22, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 11, SysTime(DateTime(-1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 12, SysTime(DateTime(-1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 13, SysTime(DateTime(-1999, 7, 6, 1, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 14, SysTime(DateTime(-1999, 7, 6, 2, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 15, SysTime(DateTime(-1999, 7, 6, 3, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 16, SysTime(DateTime(-1999, 7, 6, 4, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 17, SysTime(DateTime(-1999, 7, 6, 5, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 18, SysTime(DateTime(-1999, 7, 6, 6, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 19, SysTime(DateTime(-1999, 7, 6, 7, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 20, SysTime(DateTime(-1999, 7, 6, 8, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 21, SysTime(DateTime(-1999, 7, 6, 9, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 22, SysTime(DateTime(-1999, 7, 6, 10, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 23, SysTime(DateTime(-1999, 7, 6, 11, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 24, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 25, SysTime(DateTime(-1999, 7, 6, 13, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 50, SysTime(DateTime(-1999, 7, 6, 14, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), 10_000, SysTime(DateTime(-1999, 7, 6, 4, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -1, SysTime(DateTime(-1999, 7, 6, 11, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -2, SysTime(DateTime(-1999, 7, 6, 10, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -3, SysTime(DateTime(-1999, 7, 6, 9, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -4, SysTime(DateTime(-1999, 7, 6, 8, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -5, SysTime(DateTime(-1999, 7, 6, 7, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -6, SysTime(DateTime(-1999, 7, 6, 6, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -7, SysTime(DateTime(-1999, 7, 6, 5, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -8, SysTime(DateTime(-1999, 7, 6, 4, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -9, SysTime(DateTime(-1999, 7, 6, 3, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -10, SysTime(DateTime(-1999, 7, 6, 2, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -11, SysTime(DateTime(-1999, 7, 6, 1, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -12, SysTime(DateTime(-1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -13, SysTime(DateTime(-1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -14, SysTime(DateTime(-1999, 7, 6, 22, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -15, SysTime(DateTime(-1999, 7, 6, 21, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -16, SysTime(DateTime(-1999, 7, 6, 20, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -17, SysTime(DateTime(-1999, 7, 6, 19, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -18, SysTime(DateTime(-1999, 7, 6, 18, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -19, SysTime(DateTime(-1999, 7, 6, 17, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -20, SysTime(DateTime(-1999, 7, 6, 16, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -21, SysTime(DateTime(-1999, 7, 6, 15, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -22, SysTime(DateTime(-1999, 7, 6, 14, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -23, SysTime(DateTime(-1999, 7, 6, 13, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -24, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -25, SysTime(DateTime(-1999, 7, 6, 11, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -50, SysTime(DateTime(-1999, 7, 6, 10, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(45)), -10_000, SysTime(DateTime(-1999, 7, 6, 20, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)), 1, SysTime(DateTime(-1999, 7, 6, 1, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)), 0, SysTime(DateTime(-1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)), -1, SysTime(DateTime(-1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)), 1, SysTime(DateTime(-1999, 7, 6, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)), 0, SysTime(DateTime(-1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 6, 23, 30, 33), FracSec.from!"msecs"(45)), -1, SysTime(DateTime(-1999, 7, 6, 22, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 7, 31, 23, 30, 33), FracSec.from!"msecs"(45)), 1, SysTime(DateTime(-1999, 7, 31, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-1999, 8, 1, 0, 30, 33), FracSec.from!"msecs"(45)), -1, SysTime(DateTime(-1999, 8, 1, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-2001, 12, 31, 23, 30, 33), FracSec.from!"msecs"(45)), 1, SysTime(DateTime(-2001, 12, 31, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-2000, 1, 1, 0, 30, 33), FracSec.from!"msecs"(45)), -1, SysTime(DateTime(-2000, 1, 1, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-2001, 2, 28, 23, 30, 33), FracSec.from!"msecs"(45)), 25, SysTime(DateTime(-2001, 2, 28, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-2001, 3, 2, 0, 30, 33), FracSec.from!"msecs"(45)), -25, SysTime(DateTime(-2001, 3, 2, 23, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-2000, 2, 28, 23, 30, 33), FracSec.from!"msecs"(45)), 25, SysTime(DateTime(-2000, 2, 28, 0, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(-2000, 3, 1, 0, 30, 33), FracSec.from!"msecs"(45)), -25, SysTime(DateTime(-2000, 3, 1, 23, 30, 33), FracSec.from!"msecs"(45)));
//Test Both
TestST(SysTime(DateTime(-1, 1, 1, 11, 30, 33), FracSec.from!"msecs"(45)), 17_546, SysTime(DateTime(-1, 1, 1, 13, 30, 33), FracSec.from!"msecs"(45)));
TestST(SysTime(DateTime(1, 1, 1, 13, 30, 33), FracSec.from!"msecs"(45)), -17_546, SysTime(DateTime(1, 1, 1, 11, 30, 33), FracSec.from!"msecs"(45)));
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"hours"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"hours"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"hours"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"hours"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 31, 23, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"hours"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"hours"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"hours"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 0, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"hours"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.roll!"hours"(4)));
//static assert(!__traits(compiles, ist.roll!"hours"(4)));
//Verify Examples.
auto st1 = SysTime(DateTime(2010, 7, 4, 12, 0, 0));
st1.roll!"hours"(1);
assert(st1 == SysTime(DateTime(2010, 7, 4, 13, 0, 0)));
auto st2 = SysTime(DateTime(2010, 2, 12, 12, 0, 0));
st2.roll!"hours"(-1);
assert(st2 == SysTime(DateTime(2010, 2, 12, 11, 0, 0)));
auto st3 = SysTime(DateTime(2009, 12, 31, 0, 0, 0));
st3.roll!"minutes"(1);
assert(st3 == SysTime(DateTime(2009, 12, 31, 0, 1, 0)));
auto st4 = SysTime(DateTime(2010, 1, 1, 0, 0, 0));
st4.roll!"minutes"(-1);
assert(st4 == SysTime(DateTime(2010, 1, 1, 0, 59, 0)));
auto st5 = SysTime(DateTime(2009, 12, 31, 0, 0, 0));
st5.roll!"seconds"(1);
assert(st5 == SysTime(DateTime(2009, 12, 31, 0, 0, 1)));
auto st6 = SysTime(DateTime(2010, 1, 1, 0, 0, 0));
st6.roll!"seconds"(-1);
assert(st6 == SysTime(DateTime(2010, 1, 1, 0, 0, 59)));
}
}
//Test roll!"minutes"().
unittest
{
version(testStdDateTime)
{
static void TestST(SysTime orig, int minutes, in SysTime expected, size_t line = __LINE__)
{
orig.roll!"minutes"(minutes);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(1999, 7, 6, 12, 31, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 2, SysTime(DateTime(1999, 7, 6, 12, 32, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 3, SysTime(DateTime(1999, 7, 6, 12, 33, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 4, SysTime(DateTime(1999, 7, 6, 12, 34, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 5, SysTime(DateTime(1999, 7, 6, 12, 35, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 10, SysTime(DateTime(1999, 7, 6, 12, 40, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 15, SysTime(DateTime(1999, 7, 6, 12, 45, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 29, SysTime(DateTime(1999, 7, 6, 12, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 30, SysTime(DateTime(1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 45, SysTime(DateTime(1999, 7, 6, 12, 15, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 60, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 75, SysTime(DateTime(1999, 7, 6, 12, 45, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 90, SysTime(DateTime(1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 100, SysTime(DateTime(1999, 7, 6, 12, 10, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 689, SysTime(DateTime(1999, 7, 6, 12, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 690, SysTime(DateTime(1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 691, SysTime(DateTime(1999, 7, 6, 12, 1, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 960, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 1439, SysTime(DateTime(1999, 7, 6, 12, 29, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 1440, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 1441, SysTime(DateTime(1999, 7, 6, 12, 31, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 2880, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(1999, 7, 6, 12, 29, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -2, SysTime(DateTime(1999, 7, 6, 12, 28, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -3, SysTime(DateTime(1999, 7, 6, 12, 27, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -4, SysTime(DateTime(1999, 7, 6, 12, 26, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -5, SysTime(DateTime(1999, 7, 6, 12, 25, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -10, SysTime(DateTime(1999, 7, 6, 12, 20, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -15, SysTime(DateTime(1999, 7, 6, 12, 15, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -29, SysTime(DateTime(1999, 7, 6, 12, 1, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -30, SysTime(DateTime(1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -45, SysTime(DateTime(1999, 7, 6, 12, 45, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -60, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -75, SysTime(DateTime(1999, 7, 6, 12, 15, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -90, SysTime(DateTime(1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -100, SysTime(DateTime(1999, 7, 6, 12, 50, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -749, SysTime(DateTime(1999, 7, 6, 12, 1, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -750, SysTime(DateTime(1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -751, SysTime(DateTime(1999, 7, 6, 12, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -960, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -1439, SysTime(DateTime(1999, 7, 6, 12, 31, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -1440, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -1441, SysTime(DateTime(1999, 7, 6, 12, 29, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -2880, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(1999, 7, 6, 12, 1, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(1999, 7, 6, 12, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 11, 59, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(1999, 7, 6, 11, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 11, 59, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(1999, 7, 6, 11, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 11, 59, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(1999, 7, 6, 11, 58, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 0, 0, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(1999, 7, 6, 0, 1, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 0, 0, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(1999, 7, 6, 0, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 6, 0, 0, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(1999, 7, 6, 0, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 5, 23, 59, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(1999, 7, 5, 23, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 5, 23, 59, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(1999, 7, 5, 23, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1999, 7, 5, 23, 59, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(1999, 7, 5, 23, 58, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1998, 12, 31, 23, 59, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(1998, 12, 31, 23, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1998, 12, 31, 23, 59, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(1998, 12, 31, 23, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1998, 12, 31, 23, 59, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(1998, 12, 31, 23, 58, 33), FracSec.from!"usecs"(7203)));
//Test B.C.
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(-1999, 7, 6, 12, 31, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 2, SysTime(DateTime(-1999, 7, 6, 12, 32, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 3, SysTime(DateTime(-1999, 7, 6, 12, 33, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 4, SysTime(DateTime(-1999, 7, 6, 12, 34, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 5, SysTime(DateTime(-1999, 7, 6, 12, 35, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 10, SysTime(DateTime(-1999, 7, 6, 12, 40, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 15, SysTime(DateTime(-1999, 7, 6, 12, 45, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 29, SysTime(DateTime(-1999, 7, 6, 12, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 30, SysTime(DateTime(-1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 45, SysTime(DateTime(-1999, 7, 6, 12, 15, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 60, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 75, SysTime(DateTime(-1999, 7, 6, 12, 45, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 90, SysTime(DateTime(-1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 100, SysTime(DateTime(-1999, 7, 6, 12, 10, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 689, SysTime(DateTime(-1999, 7, 6, 12, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 690, SysTime(DateTime(-1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 691, SysTime(DateTime(-1999, 7, 6, 12, 1, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 960, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 1439, SysTime(DateTime(-1999, 7, 6, 12, 29, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 1440, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 1441, SysTime(DateTime(-1999, 7, 6, 12, 31, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), 2880, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(-1999, 7, 6, 12, 29, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -2, SysTime(DateTime(-1999, 7, 6, 12, 28, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -3, SysTime(DateTime(-1999, 7, 6, 12, 27, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -4, SysTime(DateTime(-1999, 7, 6, 12, 26, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -5, SysTime(DateTime(-1999, 7, 6, 12, 25, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -10, SysTime(DateTime(-1999, 7, 6, 12, 20, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -15, SysTime(DateTime(-1999, 7, 6, 12, 15, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -29, SysTime(DateTime(-1999, 7, 6, 12, 1, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -30, SysTime(DateTime(-1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -45, SysTime(DateTime(-1999, 7, 6, 12, 45, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -60, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -75, SysTime(DateTime(-1999, 7, 6, 12, 15, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -90, SysTime(DateTime(-1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -100, SysTime(DateTime(-1999, 7, 6, 12, 50, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -749, SysTime(DateTime(-1999, 7, 6, 12, 1, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -750, SysTime(DateTime(-1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -751, SysTime(DateTime(-1999, 7, 6, 12, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -960, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -1439, SysTime(DateTime(-1999, 7, 6, 12, 31, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -1440, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -1441, SysTime(DateTime(-1999, 7, 6, 12, 29, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)), -2880, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(-1999, 7, 6, 12, 1, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(-1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 0, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(-1999, 7, 6, 12, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 11, 59, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(-1999, 7, 6, 11, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 11, 59, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(-1999, 7, 6, 11, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 11, 59, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(-1999, 7, 6, 11, 58, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 0, 0, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(-1999, 7, 6, 0, 1, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 0, 0, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(-1999, 7, 6, 0, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 6, 0, 0, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(-1999, 7, 6, 0, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 5, 23, 59, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(-1999, 7, 5, 23, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 5, 23, 59, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(-1999, 7, 5, 23, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1999, 7, 5, 23, 59, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(-1999, 7, 5, 23, 58, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-2000, 12, 31, 23, 59, 33), FracSec.from!"usecs"(7203)), 1, SysTime(DateTime(-2000, 12, 31, 23, 0, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-2000, 12, 31, 23, 59, 33), FracSec.from!"usecs"(7203)), 0, SysTime(DateTime(-2000, 12, 31, 23, 59, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-2000, 12, 31, 23, 59, 33), FracSec.from!"usecs"(7203)), -1, SysTime(DateTime(-2000, 12, 31, 23, 58, 33), FracSec.from!"usecs"(7203)));
//Test Both
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0)), -1, SysTime(DateTime(1, 1, 1, 0, 59, 0)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 0)), 1, SysTime(DateTime(0, 12, 31, 23, 0, 0)));
TestST(SysTime(DateTime(0, 1, 1, 0, 0, 0)), -1, SysTime(DateTime(0, 1, 1, 0, 59, 0)));
TestST(SysTime(DateTime(-1, 12, 31, 23, 59, 0)), 1, SysTime(DateTime(-1, 12, 31, 23, 0, 0)));
TestST(SysTime(DateTime(-1, 1, 1, 11, 30, 33), FracSec.from!"usecs"(7203)), 1_052_760, SysTime(DateTime(-1, 1, 1, 11, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1, 1, 1, 13, 30, 33), FracSec.from!"usecs"(7203)), -1_052_760, SysTime(DateTime(1, 1, 1, 13, 30, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(-1, 1, 1, 11, 30, 33), FracSec.from!"usecs"(7203)), 1_052_782, SysTime(DateTime(-1, 1, 1, 11, 52, 33), FracSec.from!"usecs"(7203)));
TestST(SysTime(DateTime(1, 1, 1, 13, 52, 33), FracSec.from!"usecs"(7203)), -1_052_782, SysTime(DateTime(1, 1, 1, 13, 30, 33), FracSec.from!"usecs"(7203)));
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"minutes"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 59, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"minutes"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"minutes"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"minutes"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 59), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 31, 23, 59, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"minutes"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 0, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"minutes"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 59, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"minutes"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 0, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"minutes"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.roll!"minutes"(4)));
//static assert(!__traits(compiles, ist.roll!"minutes"(4)));
}
}
//Test roll!"seconds"().
unittest
{
version(testStdDateTime)
{
static void TestST(SysTime orig, int seconds, in SysTime expected, size_t line = __LINE__)
{
orig.roll!"seconds"(seconds);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(1999, 7, 6, 12, 30, 34), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 2, SysTime(DateTime(1999, 7, 6, 12, 30, 35), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 3, SysTime(DateTime(1999, 7, 6, 12, 30, 36), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 4, SysTime(DateTime(1999, 7, 6, 12, 30, 37), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 5, SysTime(DateTime(1999, 7, 6, 12, 30, 38), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 10, SysTime(DateTime(1999, 7, 6, 12, 30, 43), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 15, SysTime(DateTime(1999, 7, 6, 12, 30, 48), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 26, SysTime(DateTime(1999, 7, 6, 12, 30, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 27, SysTime(DateTime(1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 30, SysTime(DateTime(1999, 7, 6, 12, 30, 3), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 59, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 60, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 61, SysTime(DateTime(1999, 7, 6, 12, 30, 34), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1766, SysTime(DateTime(1999, 7, 6, 12, 30, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1767, SysTime(DateTime(1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1768, SysTime(DateTime(1999, 7, 6, 12, 30, 1), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 2007, SysTime(DateTime(1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 3599, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 3600, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 3601, SysTime(DateTime(1999, 7, 6, 12, 30, 34), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 7200, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -2, SysTime(DateTime(1999, 7, 6, 12, 30, 31), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -3, SysTime(DateTime(1999, 7, 6, 12, 30, 30), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -4, SysTime(DateTime(1999, 7, 6, 12, 30, 29), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -5, SysTime(DateTime(1999, 7, 6, 12, 30, 28), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -10, SysTime(DateTime(1999, 7, 6, 12, 30, 23), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -15, SysTime(DateTime(1999, 7, 6, 12, 30, 18), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -33, SysTime(DateTime(1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -34, SysTime(DateTime(1999, 7, 6, 12, 30, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -35, SysTime(DateTime(1999, 7, 6, 12, 30, 58), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -59, SysTime(DateTime(1999, 7, 6, 12, 30, 34), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -60, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -61, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(1999, 7, 6, 12, 30, 1), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(1999, 7, 6, 12, 30, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 0, 0), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(1999, 7, 6, 12, 0, 1), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 0, 0), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(1999, 7, 6, 12, 0, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 0, 0), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(1999, 7, 6, 12, 0, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 0, 0, 0), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(1999, 7, 6, 0, 0, 1), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 0, 0, 0), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(1999, 7, 6, 0, 0, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 0, 0, 0), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(1999, 7, 6, 0, 0, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 5, 23, 59, 59), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(1999, 7, 5, 23, 59, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 5, 23, 59, 59), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(1999, 7, 5, 23, 59, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 5, 23, 59, 59), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(1999, 7, 5, 23, 59, 58), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1998, 12, 31, 23, 59, 59), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(1998, 12, 31, 23, 59, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1998, 12, 31, 23, 59, 59), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(1998, 12, 31, 23, 59, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1998, 12, 31, 23, 59, 59), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(1998, 12, 31, 23, 59, 58), FracSec.from!"msecs"(274)));
//Test B.C.
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(-1999, 7, 6, 12, 30, 34), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 2, SysTime(DateTime(-1999, 7, 6, 12, 30, 35), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 3, SysTime(DateTime(-1999, 7, 6, 12, 30, 36), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 4, SysTime(DateTime(-1999, 7, 6, 12, 30, 37), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 5, SysTime(DateTime(-1999, 7, 6, 12, 30, 38), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 10, SysTime(DateTime(-1999, 7, 6, 12, 30, 43), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 15, SysTime(DateTime(-1999, 7, 6, 12, 30, 48), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 26, SysTime(DateTime(-1999, 7, 6, 12, 30, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 27, SysTime(DateTime(-1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 30, SysTime(DateTime(-1999, 7, 6, 12, 30, 3), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 59, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 60, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 61, SysTime(DateTime(-1999, 7, 6, 12, 30, 34), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1766, SysTime(DateTime(-1999, 7, 6, 12, 30, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1767, SysTime(DateTime(-1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1768, SysTime(DateTime(-1999, 7, 6, 12, 30, 1), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 2007, SysTime(DateTime(-1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 3599, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 3600, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 3601, SysTime(DateTime(-1999, 7, 6, 12, 30, 34), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 7200, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -2, SysTime(DateTime(-1999, 7, 6, 12, 30, 31), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -3, SysTime(DateTime(-1999, 7, 6, 12, 30, 30), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -4, SysTime(DateTime(-1999, 7, 6, 12, 30, 29), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -5, SysTime(DateTime(-1999, 7, 6, 12, 30, 28), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -10, SysTime(DateTime(-1999, 7, 6, 12, 30, 23), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -15, SysTime(DateTime(-1999, 7, 6, 12, 30, 18), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -33, SysTime(DateTime(-1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -34, SysTime(DateTime(-1999, 7, 6, 12, 30, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -35, SysTime(DateTime(-1999, 7, 6, 12, 30, 58), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -59, SysTime(DateTime(-1999, 7, 6, 12, 30, 34), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -60, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -61, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(-1999, 7, 6, 12, 30, 1), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(-1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 0), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(-1999, 7, 6, 12, 30, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 0, 0), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(-1999, 7, 6, 12, 0, 1), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 0, 0), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(-1999, 7, 6, 12, 0, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 0, 0), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(-1999, 7, 6, 12, 0, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 0, 0, 0), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(-1999, 7, 6, 0, 0, 1), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 0, 0, 0), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(-1999, 7, 6, 0, 0, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 0, 0, 0), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(-1999, 7, 6, 0, 0, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 5, 23, 59, 59), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(-1999, 7, 5, 23, 59, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 5, 23, 59, 59), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(-1999, 7, 5, 23, 59, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 5, 23, 59, 59), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(-1999, 7, 5, 23, 59, 58), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-2000, 12, 31, 23, 59, 59), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(-2000, 12, 31, 23, 59, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-2000, 12, 31, 23, 59, 59), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(-2000, 12, 31, 23, 59, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-2000, 12, 31, 23, 59, 59), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(-2000, 12, 31, 23, 59, 58), FracSec.from!"msecs"(274)));
//Test Both
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(1, 1, 1, 0, 0, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(0, 12, 31, 23, 59, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(0, 1, 1, 0, 0, 0), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(0, 1, 1, 0, 0, 59), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1, 12, 31, 23, 59, 59), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(-1, 12, 31, 23, 59, 0), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1, 1, 1, 11, 30, 33), FracSec.from!"msecs"(274)), 63_165_600L, SysTime(DateTime(-1, 1, 1, 11, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1, 1, 1, 13, 30, 33), FracSec.from!"msecs"(274)), -63_165_600L, SysTime(DateTime(1, 1, 1, 13, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1, 1, 1, 11, 30, 33), FracSec.from!"msecs"(274)), 63_165_617L, SysTime(DateTime(-1, 1, 1, 11, 30, 50), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1, 1, 1, 13, 30, 50), FracSec.from!"msecs"(274)), -63_165_617L, SysTime(DateTime(1, 1, 1, 13, 30, 33), FracSec.from!"msecs"(274)));
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0));
sysTime.roll!"seconds"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 59), FracSec.from!"hnsecs"(0)));
sysTime.roll!"seconds"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"seconds"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 59), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"seconds"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0));
sysTime.roll!"seconds"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 59, 0), FracSec.from!"hnsecs"(0)));
sysTime.roll!"seconds"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)));
}
{
auto sysTime = SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999));
sysTime.roll!"seconds"(1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 59, 0), FracSec.from!"hnsecs"(9_999_999)));
sysTime.roll!"seconds"(-1);
_assertPred!"=="(sysTime, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.roll!"seconds"(4)));
//static assert(!__traits(compiles, ist.roll!"seconds"(4)));
}
}
//Shares documentation with "days" version.
/+ref SysTime+/ void roll(string units)(long value) nothrow
if(units == "msecs" ||
units == "usecs" ||
units == "hnsecs")
{
auto hnsecs = adjTime;
immutable days = splitUnitsFromHNSecs!"days"(hnsecs);
immutable negative = hnsecs < 0;
if(negative)
hnsecs += convert!("hours", "hnsecs")(24);
immutable seconds = splitUnitsFromHNSecs!"seconds"(hnsecs);
hnsecs += convert!(units, "hnsecs")(value);
hnsecs %= convert!("seconds", "hnsecs")(1);
if(hnsecs < 0)
hnsecs += convert!("seconds", "hnsecs")(1);
hnsecs += convert!("seconds", "hnsecs")(seconds);
if(negative)
hnsecs -= convert!("hours", "hnsecs")(24);
immutable newDaysHNSecs = convert!("days", "hnsecs")(days);
adjTime = newDaysHNSecs + hnsecs;
}
//Test roll!"msecs"().
unittest
{
version(testStdDateTime)
{
static void TestST(SysTime orig, int milliseconds, in SysTime expected, size_t line = __LINE__)
{
orig.roll!"msecs"(milliseconds);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(275)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 2, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(276)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 10, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(284)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 100, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(374)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1001, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(275)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 2000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 26_725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 26_726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 26_727, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(1)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1_766_725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1_766_726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(273)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -2, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(272)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -10, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(264)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -100, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(174)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -275, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1001, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(273)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -2000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -33_274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -33_275, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1_833_274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1_833_275, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
//Test B.C.
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 0, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(275)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 2, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(276)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 10, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(284)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 100, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(374)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1001, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(275)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 2000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 26_725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 26_726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 26_727, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(1)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1_766_725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), 1_766_726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(273)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -2, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(272)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -10, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(264)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -100, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(174)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -275, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1001, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(273)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -2000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -33_274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -33_275, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1_833_274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(274)), -1_833_275, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(999)));
//Test Both
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(0)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(1)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(0)), 0, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(0)), -1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(999)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(0)), -2, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(998)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(0)), -1000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(0)), -2000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(0)), -2555, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"msecs"(445)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), -1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_989_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(19_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2555, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(5_549_999)));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.addMSecs(4)));
//static assert(!__traits(compiles, ist.addMSecs(4)));
}
}
//Test roll!"usecs"().
unittest
{
version(testStdDateTime)
{
static void TestST(SysTime orig, long microseconds, in SysTime expected, size_t line = __LINE__)
{
orig.roll!"usecs"(microseconds);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 0, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(275)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 2, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(276)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 10, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(284)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 100, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(374)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(1000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(1274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1001, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(1275)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 2000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(2274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 26_725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(26_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 26_726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(27_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 26_727, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(27_001)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1_766_725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(766_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1_766_726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(767_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1_000_000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 60_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 3_600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(273)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -2, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(272)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -10, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(264)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -100, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(174)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(0)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -275, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(999_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(999_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1001, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(999_273)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -2000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(998_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -33_274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(967_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -33_275, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(966_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1_833_274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(167_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1_833_275, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(166_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1_000_000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -60_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -3_600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
//Test B.C.
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 0, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(275)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 2, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(276)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 10, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(284)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 100, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(374)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(1000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(1274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1001, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(1275)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 2000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(2274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 26_725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(26_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 26_726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(27_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 26_727, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(27_001)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1_766_725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(766_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1_766_726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(767_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 1_000_000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 60_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), 3_600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(273)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -2, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(272)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -10, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(264)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -100, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(174)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(0)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -275, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(999_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(999_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1001, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(999_273)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -2000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(998_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -33_274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(967_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -33_275, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(966_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1_833_274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(167_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1_833_275, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(166_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -1_000_000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -60_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)), -3_600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(274)));
//Test Both
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(1)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)), 0, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)), -1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(999_999)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)), -2, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(999_998)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)), -1000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(999_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)), -2000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(998_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)), -2555, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(997_445)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)), -1_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)), -2_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(0)), -2_333_333, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"usecs"(666_667)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), -1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_989)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(19)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(19_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2555, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(25_549)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2_333_333, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(3_333_329)));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.roll!"usecs"(4)));
//static assert(!__traits(compiles, ist.roll!"usecs"(4)));
}
}
//Test roll!"hnsecs"().
unittest
{
version(testStdDateTime)
{
static void TestST(SysTime orig, long hnsecs, in SysTime expected, size_t line = __LINE__)
{
orig.roll!"hnsecs"(hnsecs);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 0, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(275)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(276)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 10, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(284)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 100, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(374)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1001, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1275)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(26_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_727, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_001)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_766_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_767_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_000_000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_000_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 60_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 3_600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 36_000_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(273)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(272)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -10, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(264)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -100, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(174)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -275, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_999_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1001, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_999_273)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_998_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_967_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_275, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_966_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(8_167_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_275, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(8_166_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_000_000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_000_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -60_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -3_600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -36_000_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
//Test B.C.
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 0, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(275)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(276)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 10, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(284)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 100, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(374)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1001, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1275)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(26_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_727, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_001)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_766_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_767_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_000_000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_000_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 60_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 3_600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 36_000_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(273)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(272)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -10, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(264)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -100, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(174)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -275, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_999_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1001, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_999_273)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_998_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_967_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_275, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_966_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(8_167_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_275, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(8_166_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_000_000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(9_000_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -60_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -3_600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -36_000_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
//Test Both
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), 0, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_998)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -1000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_998_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2555, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_997_445)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -1_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_000_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(8_000_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2_333_333, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(7_666_667)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -10_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -20_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -20_888_888, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_111_112)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), -1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_998)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(1)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(1999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2555, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(2554)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(1_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2_333_333, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(2_333_332)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 10_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 20_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 20_888_888, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(888_887)));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.roll!"hnsecs"(4)));
//static assert(!__traits(compiles, ist.roll!"hnsecs"(4)));
}
}
/++
Gives the result of adding or subtracting a duration from this
$(D SysTime).
The legal types of arithmetic for $(D SysTime) using this operator are
$(BOOKTABLE,
$(TR $(TD SysTime) $(TD +) $(TD duration) $(TD -->) $(TD SysTime))
$(TR $(TD SysTime) $(TD -) $(TD duration) $(TD -->) $(TD SysTime))
)
Params:
duration = The duration to add to or subtract from this
$(D SysTime).
+/
SysTime opBinary(string op, D)(in D duration) const pure nothrow
if((op == "+" || op == "-") &&
(is(Unqual!D == Duration) ||
is(Unqual!D == TickDuration)))
{
SysTime retval = SysTime(this._stdTime, this._timezone.get);
static if(is(Unqual!D == Duration))
immutable hnsecs = duration.total!"hnsecs";
else static if(is(Unqual!D == TickDuration))
immutable hnsecs = duration.hnsecs;
//Ideally, this would just be
//retval._stdTime += unaryFun!(op ~ "a")(hnsecs);
//But there isn't currently a pure version of unaryFun!().
static if(op == "+")
immutable signedHNSecs = hnsecs;
else static if(op == "-")
immutable signedHNSecs = -hnsecs;
else
static assert(0);
retval._stdTime += signedHNSecs;
return retval;
}
unittest
{
version(testStdDateTime)
{
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_678));
_assertPred!"=="(st + dur!"weeks"(7), SysTime(DateTime(1999, 8, 24, 12, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st + dur!"weeks"(-7), SysTime(DateTime(1999, 5, 18, 12, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st + dur!"days"(7), SysTime(DateTime(1999, 7, 13, 12, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st + dur!"days"(-7), SysTime(DateTime(1999, 6, 29, 12, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st + dur!"hours"(7), SysTime(DateTime(1999, 7, 6, 19, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st + dur!"hours"(-7), SysTime(DateTime(1999, 7, 6, 5, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st + dur!"minutes"(7), SysTime(DateTime(1999, 7, 6, 12, 37, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st + dur!"minutes"(-7), SysTime(DateTime(1999, 7, 6, 12, 23, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st + dur!"seconds"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 40), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st + dur!"seconds"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 26), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st + dur!"msecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_415_678)));
_assertPred!"=="(st + dur!"msecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_275_678)));
_assertPred!"=="(st + dur!"usecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_748)));
_assertPred!"=="(st + dur!"usecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_608)));
_assertPred!"=="(st + dur!"hnsecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_685)));
_assertPred!"=="(st + dur!"hnsecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_671)));
//This probably only runs in cases where gettimeofday() is used, but it's
//hard to do this test correctly with variable ticksPerSec.
if(TickDuration.ticksPerSec == 1_000_000)
{
_assertPred!"=="(st + TickDuration.from!"usecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_748)));
_assertPred!"=="(st + TickDuration.from!"usecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_608)));
}
_assertPred!"=="(st - dur!"weeks"(-7), SysTime(DateTime(1999, 8, 24, 12, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st - dur!"weeks"(7), SysTime(DateTime(1999, 5, 18, 12, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st - dur!"days"(-7), SysTime(DateTime(1999, 7, 13, 12, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st - dur!"days"(7), SysTime(DateTime(1999, 6, 29, 12, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st - dur!"hours"(-7), SysTime(DateTime(1999, 7, 6, 19, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st - dur!"hours"(7), SysTime(DateTime(1999, 7, 6, 5, 30, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st - dur!"minutes"(-7), SysTime(DateTime(1999, 7, 6, 12, 37, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st - dur!"minutes"(7), SysTime(DateTime(1999, 7, 6, 12, 23, 33), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st - dur!"seconds"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 40), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st - dur!"seconds"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 26), FracSec.from!"hnsecs"(2_345_678)));
_assertPred!"=="(st - dur!"msecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_415_678)));
_assertPred!"=="(st - dur!"msecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_275_678)));
_assertPred!"=="(st - dur!"usecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_748)));
_assertPred!"=="(st - dur!"usecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_608)));
_assertPred!"=="(st - dur!"hnsecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_685)));
_assertPred!"=="(st - dur!"hnsecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_671)));
//This probably only runs in cases where gettimeofday() is used, but it's
//hard to do this test correctly with variable ticksPerSec.
if(TickDuration.ticksPerSec == 1_000_000)
{
_assertPred!"=="(st - TickDuration.from!"usecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_748)));
_assertPred!"=="(st - TickDuration.from!"usecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2_345_608)));
}
static void TestST(in SysTime orig, long hnsecs, in SysTime expected, size_t line = __LINE__)
{
_assertPred!"=="(orig + dur!"hnsecs"(hnsecs), expected, "", __FILE__, line);
}
//Test A.D.
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 0, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(275)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(276)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 10, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(284)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 100, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(374)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1001, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1275)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(26_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_727, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_001)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_766_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_767_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_000_000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_000_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 60_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 39), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 3_600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 36, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 31, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 36_000_000_000L, SysTime(DateTime(1999, 7, 6, 13, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(273)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(272)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -10, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(264)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -100, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(174)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -275, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1000, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1001, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_273)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2000, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_998_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_274, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_967_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_275, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_966_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_274, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(8_167_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_275, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(8_166_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_000_000, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_000_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -60_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 27), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -3_600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 24, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 29, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -36_000_000_000L, SysTime(DateTime(1999, 7, 6, 11, 30, 33), FracSec.from!"hnsecs"(274)));
//Test B.C.
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 0, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(275)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(276)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 10, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(284)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 100, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(374)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1001, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1275)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(26_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_727, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_001)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_766_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_767_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_000_000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_000_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 60_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 39), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 3_600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 36, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 31, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 36_000_000_000L, SysTime(DateTime(-1999, 7, 6, 13, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(273)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(272)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -10, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(264)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -100, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(174)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -275, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1000, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1001, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_273)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2000, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_998_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_274, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_967_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_275, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_966_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_274, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(8_167_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_275, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(8_166_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_000_000, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_000_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -60_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 27), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -3_600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 24, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 29, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -36_000_000_000L, SysTime(DateTime(-1999, 7, 6, 11, 30, 33), FracSec.from!"hnsecs"(274)));
//Test Both
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), 0, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_998)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -1000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_998_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2555, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_997_445)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -1_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_000_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(8_000_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2_333_333, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(7_666_667)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -10_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -20_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 58), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -20_888_888, SysTime(DateTime(0, 12, 31, 23, 59, 57), FracSec.from!"hnsecs"(9_111_112)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), -1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_998)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2555, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(2554)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2_333_333, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(2_333_332)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 10_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 20_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 1), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 20_888_888, SysTime(DateTime(1, 1, 1, 0, 0, 2), FracSec.from!"hnsecs"(888_887)));
auto duration = dur!"seconds"(12);
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst + duration));
//static assert(__traits(compiles, ist + duration));
static assert(__traits(compiles, cst - duration));
//static assert(__traits(compiles, ist - duration));
}
}
/++
Gives the result of adding or subtracting a duration from this
$(D SysTime), as well as assigning the result to this $(D SysTime).
The legal types of arithmetic for $(D SysTime) using this operator are
$(BOOKTABLE,
$(TR $(TD SysTime) $(TD +) $(TD duration) $(TD -->) $(TD SysTime))
$(TR $(TD SysTime) $(TD -) $(TD duration) $(TD -->) $(TD SysTime))
)
Params:
duration = The duration to add to or subtract from this
$(D SysTime).
+/
/+ref+/ SysTime opOpAssign(string op, D)(in D duration) pure nothrow
if((op == "+" || op == "-") &&
(is(Unqual!D == Duration) ||
is(Unqual!D == TickDuration)))
{
static if(is(Unqual!D == Duration))
auto hnsecs = duration.total!"hnsecs";
else static if(is(Unqual!D == TickDuration))
auto hnsecs = duration.hnsecs;
//Ideally, this would just be
//_stdTime += unaryFun!(op ~ "a")(hnsecs);
//But there isn't currently a pure version of unaryFun!().
static if(op == "+")
immutable signedHNSecs = hnsecs;
else static if(op == "-")
immutable signedHNSecs = -hnsecs;
else
static assert(0);
_stdTime += signedHNSecs;
return this;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"weeks"(7), SysTime(DateTime(1999, 8, 24, 12, 30, 33)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"weeks"(-7), SysTime(DateTime(1999, 5, 18, 12, 30, 33)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"days"(7), SysTime(DateTime(1999, 7, 13, 12, 30, 33)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"days"(-7), SysTime(DateTime(1999, 6, 29, 12, 30, 33)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"hours"(7), SysTime(DateTime(1999, 7, 6, 19, 30, 33)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"hours"(-7), SysTime(DateTime(1999, 7, 6, 5, 30, 33)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"minutes"(7), SysTime(DateTime(1999, 7, 6, 12, 37, 33)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"minutes"(-7), SysTime(DateTime(1999, 7, 6, 12, 23, 33)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"seconds"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 40)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"seconds"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 26)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"msecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(7)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"msecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"msecs"(993)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"usecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"usecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"usecs"(999_993)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"hnsecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(7)));
_assertPred!"+="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"hnsecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_993)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"weeks"(-7), SysTime(DateTime(1999, 8, 24, 12, 30, 33)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"weeks"(7), SysTime(DateTime(1999, 5, 18, 12, 30, 33)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"days"(-7), SysTime(DateTime(1999, 7, 13, 12, 30, 33)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"days"(7), SysTime(DateTime(1999, 6, 29, 12, 30, 33)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"hours"(-7), SysTime(DateTime(1999, 7, 6, 19, 30, 33)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"hours"(7), SysTime(DateTime(1999, 7, 6, 5, 30, 33)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"minutes"(-7), SysTime(DateTime(1999, 7, 6, 12, 37, 33)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"minutes"(7), SysTime(DateTime(1999, 7, 6, 12, 23, 33)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"seconds"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 40)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"seconds"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 26)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"msecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(7)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"msecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"msecs"(993)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"usecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(7)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"usecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"usecs"(999_993)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"hnsecs"(-7), SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(7)));
_assertPred!"-="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)), dur!"hnsecs"(7), SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_993)));
static void TestST(SysTime orig, long hnsecs, in SysTime expected, size_t line = __LINE__)
{
orig += dur!"hnsecs"(hnsecs);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 0, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(275)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(276)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 10, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(284)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 100, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(374)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1001, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1275)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(26_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_727, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_001)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_725, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_766_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_726, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_767_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_000_000, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_000_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 60_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 39), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 3_600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 36, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 31, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 36_000_000_000L, SysTime(DateTime(1999, 7, 6, 13, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(273)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(272)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -10, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(264)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -100, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(174)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -274, SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -275, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1000, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1001, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_273)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2000, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_998_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_274, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_967_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_275, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_966_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_274, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(8_167_000)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_275, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(8_166_999)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_000_000, SysTime(DateTime(1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_000_274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -60_000_000L, SysTime(DateTime(1999, 7, 6, 12, 30, 27), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -3_600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 24, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -600_000_000L, SysTime(DateTime(1999, 7, 6, 12, 29, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -36_000_000_000L, SysTime(DateTime(1999, 7, 6, 11, 30, 33), FracSec.from!"hnsecs"(274)));
//Test B.C.
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 0, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(275)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(276)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 10, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(284)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 100, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(374)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1001, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1275)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 2000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(2274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(26_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 26_727, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(27_001)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_725, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_766_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_766_726, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_767_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 1_000_000, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_000_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 60_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 39), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 3_600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 36, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 31, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), 36_000_000_000L, SysTime(DateTime(-1999, 7, 6, 13, 30, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(273)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(272)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -10, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(264)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -100, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(174)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -274, SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -275, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1000, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1001, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_999_273)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -2000, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_998_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_274, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_967_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -33_275, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_966_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_274, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(8_167_000)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_833_275, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(8_166_999)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -1_000_000, SysTime(DateTime(-1999, 7, 6, 12, 30, 32), FracSec.from!"hnsecs"(9_000_274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -60_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 30, 27), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -3_600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 24, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -600_000_000L, SysTime(DateTime(-1999, 7, 6, 12, 29, 33), FracSec.from!"hnsecs"(274)));
TestST(SysTime(DateTime(-1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(274)), -36_000_000_000L, SysTime(DateTime(-1999, 7, 6, 11, 30, 33), FracSec.from!"hnsecs"(274)));
//Test Both
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), 0, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_998)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -1000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_998_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2555, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_997_445)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -1_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_000_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(8_000_000)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -2_333_333, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(7_666_667)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -10_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -20_000_000, SysTime(DateTime(0, 12, 31, 23, 59, 58), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), -20_888_888, SysTime(DateTime(0, 12, 31, 23, 59, 57), FracSec.from!"hnsecs"(9_111_112)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), -1, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_998)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2555, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(2554)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 2_333_333, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(2_333_332)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 10_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 20_000_000, SysTime(DateTime(1, 1, 1, 0, 0, 1), FracSec.from!"hnsecs"(9_999_999)));
TestST(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 20_888_888, SysTime(DateTime(1, 1, 1, 0, 0, 2), FracSec.from!"hnsecs"(888_887)));
auto duration = dur!"seconds"(12);
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst += duration));
//static assert(!__traits(compiles, ist += duration));
static assert(!__traits(compiles, cst -= duration));
//static assert(!__traits(compiles, ist -= duration));
}
}
/++
Gives the difference between two $(D SysTime)s.
The legal types of arithmetic for $(D SysTime) using this operator are
$(BOOKTABLE,
$(TR $(TD SysTime) $(TD -) $(TD SysTime) $(TD -->) $(TD duration))
)
+/
Duration opBinary(string op)(in SysTime rhs) const pure nothrow
if(op == "-")
{
return dur!"hnsecs"(_stdTime - rhs._stdTime);
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)) - SysTime(DateTime(1998, 7, 6, 12, 30, 33)),
dur!"seconds"(31_536_000));
_assertPred!"=="(SysTime(DateTime(1998, 7, 6, 12, 30, 33)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33)),
dur!"seconds"(-31_536_000));
_assertPred!"=="(SysTime(DateTime(1999, 8, 6, 12, 30, 33)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33)),
dur!"seconds"(26_78_400));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)) - SysTime(DateTime(1999, 8, 6, 12, 30, 33)),
dur!"seconds"(-26_78_400));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)) - SysTime(DateTime(1999, 7, 5, 12, 30, 33)),
dur!"seconds"(86_400));
_assertPred!"=="(SysTime(DateTime(1999, 7, 5, 12, 30, 33)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33)),
dur!"seconds"(-86_400));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)) - SysTime(DateTime(1999, 7, 6, 11, 30, 33)),
dur!"seconds"(3600));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 11, 30, 33)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33)),
dur!"seconds"(-3600));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 31, 33)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33)),
dur!"seconds"(60));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)) - SysTime(DateTime(1999, 7, 6, 12, 31, 33)),
dur!"seconds"(-60));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 34)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33)),
dur!"seconds"(1));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)) - SysTime(DateTime(1999, 7, 6, 12, 30, 34)),
dur!"seconds"(-1));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(532)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33)),
dur!"msecs"(532));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"msecs"(532)),
dur!"msecs"(-532));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(333_347)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33)),
dur!"usecs"(333_347));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"usecs"(333_347)),
dur!"usecs"(-333_347));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_234_567)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33)),
dur!"hnsecs"(1_234_567));
_assertPred!"=="(SysTime(DateTime(1999, 7, 6, 12, 30, 33)) - SysTime(DateTime(1999, 7, 6, 12, 30, 33), FracSec.from!"hnsecs"(1_234_567)),
dur!"hnsecs"(-1_234_567));
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 12, 30, 33)) - SysTime(DateTime(1, 1, 1, 0, 0, 0)), dur!"seconds"(45033));
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 0, 0, 0)) - SysTime(DateTime(1, 1, 1, 12, 30, 33)), dur!"seconds"(-45033));
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 12, 30, 33)) - SysTime(DateTime(1, 1, 1, 0, 0, 0)), dur!"seconds"(-41367));
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 0, 0, 0)) - SysTime(DateTime(0, 12, 31, 12, 30, 33)), dur!"seconds"(41367));
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 0, 0, 0)) - SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)),
dur!"hnsecs"(1));
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)) - SysTime(DateTime(1, 1, 1, 0, 0, 0)),
dur!"hnsecs"(-1));
auto tz = TimeZone.getTimeZone("America/Los_Angeles");
_assertPred!"=="(SysTime(DateTime(2011, 1, 13, 8, 17, 2), FracSec.from!"msecs"(296), tz) -
SysTime(DateTime(2011, 1, 13, 8, 17, 2), FracSec.from!"msecs"(296), tz),
dur!"hnsecs"(0));
_assertPred!"=="(SysTime(DateTime(2011, 1, 13, 8, 17, 2), FracSec.from!"msecs"(296), tz) -
SysTime(DateTime(2011, 1, 13, 8, 17, 2), FracSec.from!"msecs"(296), UTC()),
dur!"hours"(8));
_assertPred!"=="(SysTime(DateTime(2011, 1, 13, 8, 17, 2), FracSec.from!"msecs"(296), UTC()) -
SysTime(DateTime(2011, 1, 13, 8, 17, 2), FracSec.from!"msecs"(296), tz),
dur!"hours"(-8));
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st - st));
static assert(__traits(compiles, cst - st));
//static assert(__traits(compiles, ist - st));
static assert(__traits(compiles, st - cst));
static assert(__traits(compiles, cst - cst));
//static assert(__traits(compiles, ist - cst));
//static assert(__traits(compiles, st - ist));
//static assert(__traits(compiles, cst - ist));
//static assert(__traits(compiles, ist - ist));
}
}
/++
Returns the difference between the two $(D SysTime)s in months.
You can get the difference in years by subtracting the year property
of two $(D SysTime)s, and you can get the difference in days or weeks by
subtracting the $(D SysTime)s themselves and using the $(D Duration)
that results, but because you cannot convert between months and smaller
units without a specific date (which $(D Duration)s don't have), you
cannot get the difference in months without doing some math using both
the year and month properties, so this is a convenience function for
getting the difference in months.
Note that the number of days in the months or how far into the month
either date is is irrelevant. It is the difference in the month property
combined with the difference in years * 12. So, for instance,
December 31st and January 1st are one month apart just as December 1st
and January 31st are one month apart.
Params:
rhs = The $(D SysTime) to subtract from this one.
Examples:
--------------------
assert(SysTime(Date(1999, 2, 1)).diffMonths(SysTime(Date(1999, 1, 31))) == 1);
assert(SysTime(Date(1999, 1, 31)).diffMonths(SysTime(Date(1999, 2, 1))) == -1);
assert(SysTime(Date(1999, 3, 1)).diffMonths(SysTime(Date(1999, 1, 1))) == 2);
assert(SysTime(Date(1999, 1, 1)).diffMonths(SysTime(Date(1999, 3, 31))) == -2);
--------------------
+/
int diffMonths(in SysTime rhs) const nothrow
{
return (cast(Date)this).diffMonths(cast(Date)rhs);
}
unittest
{
version(testStdDateTime)
{
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st.diffMonths(st)));
static assert(__traits(compiles, cst.diffMonths(st)));
//static assert(__traits(compiles, ist.diffMonths(st)));
static assert(__traits(compiles, st.diffMonths(cst)));
static assert(__traits(compiles, cst.diffMonths(cst)));
//static assert(__traits(compiles, ist.diffMonths(cst)));
//static assert(__traits(compiles, st.diffMonths(ist)));
//static assert(__traits(compiles, cst.diffMonths(ist)));
//static assert(__traits(compiles, ist.diffMonths(ist)));
//Verify Examples.
assert(SysTime(Date(1999, 2, 1)).diffMonths(SysTime(Date(1999, 1, 31))) == 1);
assert(SysTime(Date(1999, 1, 31)).diffMonths(SysTime(Date(1999, 2, 1))) == -1);
assert(SysTime(Date(1999, 3, 1)).diffMonths(SysTime(Date(1999, 1, 1))) == 2);
assert(SysTime(Date(1999, 1, 1)).diffMonths(SysTime(Date(1999, 3, 31))) == -2);
}
}
/++
Whether this $(D SysTime) is in a leap year.
+/
@property bool isLeapYear() const nothrow
{
return (cast(Date)this).isLeapYear;
}
unittest
{
version(testStdDateTime)
{
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st.isLeapYear));
static assert(__traits(compiles, cst.isLeapYear));
//static assert(__traits(compiles, ist.isLeapYear));
}
}
/++
Day of the week this $(D SysTime) is on.
+/
@property DayOfWeek dayOfWeek() const nothrow
{
return getDayOfWeek(dayOfGregorianCal);
}
unittest
{
version(testStdDateTime)
{
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st.dayOfWeek));
static assert(__traits(compiles, cst.dayOfWeek));
//static assert(__traits(compiles, ist.dayOfWeek));
}
}
/++
Day of the year this $(D SysTime) is on.
Examples:
--------------------
assert(SysTime(DateTime(1999, 1, 1, 12, 22, 7)).dayOfYear == 1);
assert(SysTime(DateTime(1999, 12, 31, 7, 2, 59)).dayOfYear == 365);
assert(SysTime(DateTime(2000, 12, 31, 21, 20, 0)).dayOfYear == 366);
--------------------
+/
@property ushort dayOfYear() const nothrow
{
return (cast(Date)this).dayOfYear;
}
unittest
{
version(testStdDateTime)
{
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st.dayOfYear));
static assert(__traits(compiles, cst.dayOfYear));
//static assert(__traits(compiles, ist.dayOfYear));
//Verify Examples.
assert(SysTime(DateTime(1999, 1, 1, 12, 22, 7)).dayOfYear == 1);
assert(SysTime(DateTime(1999, 12, 31, 7, 2, 59)).dayOfYear == 365);
assert(SysTime(DateTime(2000, 12, 31, 21, 20, 0)).dayOfYear == 366);
}
}
/++
Day of the year.
Params:
day = The day of the year to set which day of the year this
$(D SysTime) is on.
+/
@property void dayOfYear(int day)
{
immutable hnsecs = adjTime;
immutable days = convert!("hnsecs", "days")(hnsecs);
immutable theRest = hnsecs - convert!("days", "hnsecs")(days);
auto date = Date(cast(int)days);
date.dayOfYear = day;
immutable newDaysHNSecs = convert!("days", "hnsecs")(date.dayOfGregorianCal - 1);
adjTime = newDaysHNSecs + theRest;
}
unittest
{
version(testStdDateTime)
{
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st.dayOfYear = 12));
static assert(!__traits(compiles, cst.dayOfYear = 12));
//static assert(!__traits(compiles, ist.dayOfYear = 12));
}
}
/++
The Xth day of the Gregorian Calendar that this $(D SysTime) is on.
Examples:
--------------------
assert(SysTime(DateTime(1, 1, 1, 0, 0, 0)).dayOfGregorianCal == 1);
assert(SysTime(DateTime(1, 12, 31, 23, 59, 59)).dayOfGregorianCal == 365);
assert(SysTime(DateTime(2, 1, 1, 2, 2, 2)).dayOfGregorianCal == 366);
assert(SysTime(DateTime(0, 12, 31, 7, 7, 7)).dayOfGregorianCal == 0);
assert(SysTime(DateTime(0, 1, 1, 19, 30, 0)).dayOfGregorianCal == -365);
assert(SysTime(DateTime(-1, 12, 31, 4, 7, 0)).dayOfGregorianCal == -366);
assert(SysTime(DateTime(2000, 1, 1, 9, 30, 20)).dayOfGregorianCal == 730_120);
assert(SysTime(DateTime(2010, 12, 31, 15, 45, 50)).dayOfGregorianCal == 734_137);
--------------------
+/
@property int dayOfGregorianCal() const nothrow
{
immutable adjustedTime = adjTime;
//We have to add one because 0 would be midnight, January 1st, 1 A.D.,
//which would be the 1st day of the Gregorian Calendar, not the 0th. So,
//simply casting to days is one day off.
if(adjustedTime > 0)
return cast(int)getUnitsFromHNSecs!"days"(adjustedTime) + 1;
auto hnsecs = adjustedTime;
immutable days = cast(int)splitUnitsFromHNSecs!"days"(hnsecs);
return hnsecs == 0 ? days + 1 : days;
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal, 1);
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1)).dayOfGregorianCal, 1);
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal, 1);
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 1);
_assertPred!"=="(SysTime(DateTime(1, 1, 2, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 2);
_assertPred!"=="(SysTime(DateTime(1, 2, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 32);
_assertPred!"=="(SysTime(DateTime(2, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 366);
_assertPred!"=="(SysTime(DateTime(3, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 731);
_assertPred!"=="(SysTime(DateTime(4, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 1096);
_assertPred!"=="(SysTime(DateTime(5, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 1462);
_assertPred!"=="(SysTime(DateTime(50, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 17_898);
_assertPred!"=="(SysTime(DateTime(97, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 35_065);
_assertPred!"=="(SysTime(DateTime(100, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 36_160);
_assertPred!"=="(SysTime(DateTime(101, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 36_525);
_assertPred!"=="(SysTime(DateTime(105, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 37_986);
_assertPred!"=="(SysTime(DateTime(200, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 72_684);
_assertPred!"=="(SysTime(DateTime(201, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 73_049);
_assertPred!"=="(SysTime(DateTime(300, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 109_208);
_assertPred!"=="(SysTime(DateTime(301, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 109_573);
_assertPred!"=="(SysTime(DateTime(400, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 145_732);
_assertPred!"=="(SysTime(DateTime(401, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 146_098);
_assertPred!"=="(SysTime(DateTime(500, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 182_257);
_assertPred!"=="(SysTime(DateTime(501, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 182_622);
_assertPred!"=="(SysTime(DateTime(1000, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 364_878);
_assertPred!"=="(SysTime(DateTime(1001, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 365_243);
_assertPred!"=="(SysTime(DateTime(1600, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 584_023);
_assertPred!"=="(SysTime(DateTime(1601, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 584_389);
_assertPred!"=="(SysTime(DateTime(1900, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 693_596);
_assertPred!"=="(SysTime(DateTime(1901, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 693_961);
_assertPred!"=="(SysTime(DateTime(1945, 11, 12, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 710_347);
_assertPred!"=="(SysTime(DateTime(1999, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 729_755);
_assertPred!"=="(SysTime(DateTime(2000, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 730_120);
_assertPred!"=="(SysTime(DateTime(2001, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 730_486);
_assertPred!"=="(SysTime(DateTime(2010, 1, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_773);
_assertPred!"=="(SysTime(DateTime(2010, 1, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_803);
_assertPred!"=="(SysTime(DateTime(2010, 2, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_804);
_assertPred!"=="(SysTime(DateTime(2010, 2, 28, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_831);
_assertPred!"=="(SysTime(DateTime(2010, 3, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_832);
_assertPred!"=="(SysTime(DateTime(2010, 3, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_862);
_assertPred!"=="(SysTime(DateTime(2010, 4, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_863);
_assertPred!"=="(SysTime(DateTime(2010, 4, 30, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_892);
_assertPred!"=="(SysTime(DateTime(2010, 5, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_893);
_assertPred!"=="(SysTime(DateTime(2010, 5, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_923);
_assertPred!"=="(SysTime(DateTime(2010, 6, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_924);
_assertPred!"=="(SysTime(DateTime(2010, 6, 30, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_953);
_assertPred!"=="(SysTime(DateTime(2010, 7, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_954);
_assertPred!"=="(SysTime(DateTime(2010, 7, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_984);
_assertPred!"=="(SysTime(DateTime(2010, 8, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 733_985);
_assertPred!"=="(SysTime(DateTime(2010, 8, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 734_015);
_assertPred!"=="(SysTime(DateTime(2010, 9, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 734_016);
_assertPred!"=="(SysTime(DateTime(2010, 9, 30, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 734_045);
_assertPred!"=="(SysTime(DateTime(2010, 10, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 734_046);
_assertPred!"=="(SysTime(DateTime(2010, 10, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 734_076);
_assertPred!"=="(SysTime(DateTime(2010, 11, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 734_077);
_assertPred!"=="(SysTime(DateTime(2010, 11, 30, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 734_106);
_assertPred!"=="(SysTime(DateTime(2010, 12, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 734_107);
_assertPred!"=="(SysTime(DateTime(2010, 12, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, 734_137);
_assertPred!"=="(SysTime(DateTime(2012, 2, 1, 0, 0, 0), FracSec.from!"msecs"(0)).dayOfGregorianCal, 734_534);
_assertPred!"=="(SysTime(DateTime(2012, 2, 28, 0, 0, 0), FracSec.from!"msecs"(0)).dayOfGregorianCal, 734_561);
_assertPred!"=="(SysTime(DateTime(2012, 2, 29, 0, 0, 0), FracSec.from!"msecs"(0)).dayOfGregorianCal, 734_562);
_assertPred!"=="(SysTime(DateTime(2012, 3, 1, 0, 0, 0), FracSec.from!"msecs"(0)).dayOfGregorianCal, 734_563);
//Test B.C.
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal, 0);
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_998)).dayOfGregorianCal, 0);
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)).dayOfGregorianCal, 0);
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(1)).dayOfGregorianCal, 0);
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal, 0);
_assertPred!"=="(SysTime(DateTime(-1, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal, -366);
_assertPred!"=="(SysTime(DateTime(-1, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_998)).dayOfGregorianCal, -366);
_assertPred!"=="(SysTime(DateTime(-1, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)).dayOfGregorianCal, -366);
_assertPred!"=="(SysTime(DateTime(-1, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal, -366);
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, 0);
_assertPred!"=="(SysTime(DateTime(0, 12, 30, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -1);
_assertPred!"=="(SysTime(DateTime(0, 12, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -30);
_assertPred!"=="(SysTime(DateTime(0, 11, 30, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -31);
_assertPred!"=="(SysTime(DateTime(-1, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -366);
_assertPred!"=="(SysTime(DateTime(-1, 12, 30, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -367);
_assertPred!"=="(SysTime(DateTime(-1, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -730);
_assertPred!"=="(SysTime(DateTime(-2, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -731);
_assertPred!"=="(SysTime(DateTime(-2, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -1095);
_assertPred!"=="(SysTime(DateTime(-3, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -1096);
_assertPred!"=="(SysTime(DateTime(-3, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -1460);
_assertPred!"=="(SysTime(DateTime(-4, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -1461);
_assertPred!"=="(SysTime(DateTime(-4, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -1826);
_assertPred!"=="(SysTime(DateTime(-5, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -1827);
_assertPred!"=="(SysTime(DateTime(-5, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -2191);
_assertPred!"=="(SysTime(DateTime(-9, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -3652);
_assertPred!"=="(SysTime(DateTime(-49, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -18_262);
_assertPred!"=="(SysTime(DateTime(-50, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -18_627);
_assertPred!"=="(SysTime(DateTime(-97, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -35_794);
_assertPred!"=="(SysTime(DateTime(-99, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -36_160);
_assertPred!"=="(SysTime(DateTime(-99, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -36_524);
_assertPred!"=="(SysTime(DateTime(-100, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -36_889);
_assertPred!"=="(SysTime(DateTime(-101, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -37_254);
_assertPred!"=="(SysTime(DateTime(-105, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -38_715);
_assertPred!"=="(SysTime(DateTime(-200, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -73_413);
_assertPred!"=="(SysTime(DateTime(-201, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -73_778);
_assertPred!"=="(SysTime(DateTime(-300, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -109_937);
_assertPred!"=="(SysTime(DateTime(-301, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -110_302);
_assertPred!"=="(SysTime(DateTime(-400, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -146_097);
_assertPred!"=="(SysTime(DateTime(-400, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -146_462);
_assertPred!"=="(SysTime(DateTime(-401, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -146_827);
_assertPred!"=="(SysTime(DateTime(-499, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -182_621);
_assertPred!"=="(SysTime(DateTime(-500, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -182_986);
_assertPred!"=="(SysTime(DateTime(-501, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -183_351);
_assertPred!"=="(SysTime(DateTime(-1000, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -365_607);
_assertPred!"=="(SysTime(DateTime(-1001, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -365_972);
_assertPred!"=="(SysTime(DateTime(-1599, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -584_387);
_assertPred!"=="(SysTime(DateTime(-1600, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -584_388);
_assertPred!"=="(SysTime(DateTime(-1600, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -584_753);
_assertPred!"=="(SysTime(DateTime(-1601, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -585_118);
_assertPred!"=="(SysTime(DateTime(-1900, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -694_325);
_assertPred!"=="(SysTime(DateTime(-1901, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -694_690);
_assertPred!"=="(SysTime(DateTime(-1999, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -730_484);
_assertPred!"=="(SysTime(DateTime(-2000, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -730_485);
_assertPred!"=="(SysTime(DateTime(-2000, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -730_850);
_assertPred!"=="(SysTime(DateTime(-2001, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)).dayOfGregorianCal, -731_215);
_assertPred!"=="(SysTime(DateTime(-2010, 1, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_502);
_assertPred!"=="(SysTime(DateTime(-2010, 1, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_472);
_assertPred!"=="(SysTime(DateTime(-2010, 2, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_471);
_assertPred!"=="(SysTime(DateTime(-2010, 2, 28, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_444);
_assertPred!"=="(SysTime(DateTime(-2010, 3, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_443);
_assertPred!"=="(SysTime(DateTime(-2010, 3, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_413);
_assertPred!"=="(SysTime(DateTime(-2010, 4, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_412);
_assertPred!"=="(SysTime(DateTime(-2010, 4, 30, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_383);
_assertPred!"=="(SysTime(DateTime(-2010, 5, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_382);
_assertPred!"=="(SysTime(DateTime(-2010, 5, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_352);
_assertPred!"=="(SysTime(DateTime(-2010, 6, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_351);
_assertPred!"=="(SysTime(DateTime(-2010, 6, 30, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_322);
_assertPred!"=="(SysTime(DateTime(-2010, 7, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_321);
_assertPred!"=="(SysTime(DateTime(-2010, 7, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_291);
_assertPred!"=="(SysTime(DateTime(-2010, 8, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_290);
_assertPred!"=="(SysTime(DateTime(-2010, 8, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_260);
_assertPred!"=="(SysTime(DateTime(-2010, 9, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_259);
_assertPred!"=="(SysTime(DateTime(-2010, 9, 30, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_230);
_assertPred!"=="(SysTime(DateTime(-2010, 10, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_229);
_assertPred!"=="(SysTime(DateTime(-2010, 10, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_199);
_assertPred!"=="(SysTime(DateTime(-2010, 11, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_198);
_assertPred!"=="(SysTime(DateTime(-2010, 11, 30, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_169);
_assertPred!"=="(SysTime(DateTime(-2010, 12, 1, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_168);
_assertPred!"=="(SysTime(DateTime(-2010, 12, 31, 23, 59, 59), FracSec.from!"msecs"(999)).dayOfGregorianCal, -734_138);
_assertPred!"=="(SysTime(DateTime(-2012, 2, 1, 0, 0, 0), FracSec.from!"msecs"(0)).dayOfGregorianCal, -735_202);
_assertPred!"=="(SysTime(DateTime(-2012, 2, 28, 0, 0, 0), FracSec.from!"msecs"(0)).dayOfGregorianCal, -735_175);
_assertPred!"=="(SysTime(DateTime(-2012, 2, 29, 0, 0, 0), FracSec.from!"msecs"(0)).dayOfGregorianCal, -735_174);
_assertPred!"=="(SysTime(DateTime(-2012, 3, 1, 0, 0, 0), FracSec.from!"msecs"(0)).dayOfGregorianCal, -735_173);
_assertPred!"=="(SysTime(DateTime(-3760, 9, 7, 0, 0, 0), FracSec.from!"msecs"(0)).dayOfGregorianCal, -1_373_427); //Start of Hebrew Calendar
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.dayOfGregorianCal));
//static assert(__traits(compiles, ist.dayOfGregorianCal));
//Verify Examples.
assert(SysTime(DateTime(1, 1, 1, 0, 0, 0)).dayOfGregorianCal == 1);
assert(SysTime(DateTime(1, 12, 31, 23, 59, 59)).dayOfGregorianCal == 365);
assert(SysTime(DateTime(2, 1, 1, 2, 2, 2)).dayOfGregorianCal == 366);
assert(SysTime(DateTime(0, 12, 31, 7, 7, 7)).dayOfGregorianCal == 0);
assert(SysTime(DateTime(0, 1, 1, 19, 30, 0)).dayOfGregorianCal == -365);
assert(SysTime(DateTime(-1, 12, 31, 4, 7, 0)).dayOfGregorianCal == -366);
assert(SysTime(DateTime(2000, 1, 1, 9, 30, 20)).dayOfGregorianCal == 730_120);
assert(SysTime(DateTime(2010, 12, 31, 15, 45, 50)).dayOfGregorianCal == 734_137);
}
}
//Test that the logic for the day of the Gregorian Calendar is consistent
//between Date and SysTime.
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(Date(1, 1, 1).dayOfGregorianCal, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(1, 1, 2).dayOfGregorianCal, SysTime(DateTime(1, 1, 2, 0, 0, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(1, 2, 1).dayOfGregorianCal, SysTime(DateTime(1, 2, 1, 0, 0, 0), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(2, 1, 1).dayOfGregorianCal, SysTime(DateTime(2, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(3, 1, 1).dayOfGregorianCal, SysTime(DateTime(3, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(4, 1, 1).dayOfGregorianCal, SysTime(DateTime(4, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(5, 1, 1).dayOfGregorianCal, SysTime(DateTime(5, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(50, 1, 1).dayOfGregorianCal, SysTime(DateTime(50, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(97, 1, 1).dayOfGregorianCal, SysTime(DateTime(97, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(100, 1, 1).dayOfGregorianCal, SysTime(DateTime(100, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(101, 1, 1).dayOfGregorianCal, SysTime(DateTime(101, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(105, 1, 1).dayOfGregorianCal, SysTime(DateTime(105, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(200, 1, 1).dayOfGregorianCal, SysTime(DateTime(200, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(201, 1, 1).dayOfGregorianCal, SysTime(DateTime(201, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(300, 1, 1).dayOfGregorianCal, SysTime(DateTime(300, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(301, 1, 1).dayOfGregorianCal, SysTime(DateTime(301, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(400, 1, 1).dayOfGregorianCal, SysTime(DateTime(400, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(401, 1, 1).dayOfGregorianCal, SysTime(DateTime(401, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(500, 1, 1).dayOfGregorianCal, SysTime(DateTime(500, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(501, 1, 1).dayOfGregorianCal, SysTime(DateTime(501, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(1000, 1, 1).dayOfGregorianCal, SysTime(DateTime(1000, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(1001, 1, 1).dayOfGregorianCal, SysTime(DateTime(1001, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(1600, 1, 1).dayOfGregorianCal, SysTime(DateTime(1600, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(1601, 1, 1).dayOfGregorianCal, SysTime(DateTime(1601, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(1900, 1, 1).dayOfGregorianCal, SysTime(DateTime(1900, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(1901, 1, 1).dayOfGregorianCal, SysTime(DateTime(1901, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(1945, 11, 12).dayOfGregorianCal, SysTime(DateTime(1945, 11, 12, 0, 0, 0), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(1999, 1, 1).dayOfGregorianCal, SysTime(DateTime(1999, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(1999, 7, 6).dayOfGregorianCal, SysTime(DateTime(1999, 7, 6, 12, 13, 14), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(2000, 1, 1).dayOfGregorianCal, SysTime(DateTime(2000, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(2001, 1, 1).dayOfGregorianCal, SysTime(DateTime(2001, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 1, 1).dayOfGregorianCal, SysTime(DateTime(2010, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 1, 31).dayOfGregorianCal, SysTime(DateTime(2010, 1, 31, 23, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 2, 1).dayOfGregorianCal, SysTime(DateTime(2010, 2, 1, 23, 59, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 2, 28).dayOfGregorianCal, SysTime(DateTime(2010, 2, 28, 23, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 3, 1).dayOfGregorianCal, SysTime(DateTime(2010, 3, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 3, 31).dayOfGregorianCal, SysTime(DateTime(2010, 3, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 4, 1).dayOfGregorianCal, SysTime(DateTime(2010, 4, 1, 0, 0, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 4, 30).dayOfGregorianCal, SysTime(DateTime(2010, 4, 30, 0, 0, 0), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 5, 1).dayOfGregorianCal, SysTime(DateTime(2010, 5, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 5, 31).dayOfGregorianCal, SysTime(DateTime(2010, 5, 31, 12, 13, 14), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 6, 1).dayOfGregorianCal, SysTime(DateTime(2010, 6, 1, 12, 13, 14), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 6, 30).dayOfGregorianCal, SysTime(DateTime(2010, 6, 30, 12, 13, 14), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 7, 1).dayOfGregorianCal, SysTime(DateTime(2010, 7, 1, 12, 13, 14), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 7, 31).dayOfGregorianCal, SysTime(DateTime(2010, 7, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 8, 1).dayOfGregorianCal, SysTime(DateTime(2010, 8, 1, 23, 59, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 8, 31).dayOfGregorianCal, SysTime(DateTime(2010, 8, 31, 23, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 9, 1).dayOfGregorianCal, SysTime(DateTime(2010, 9, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 9, 30).dayOfGregorianCal, SysTime(DateTime(2010, 9, 30, 12, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 10, 1).dayOfGregorianCal, SysTime(DateTime(2010, 10, 1, 0, 12, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 10, 31).dayOfGregorianCal, SysTime(DateTime(2010, 10, 31, 0, 0, 12), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 11, 1).dayOfGregorianCal, SysTime(DateTime(2010, 11, 1, 23, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 11, 30).dayOfGregorianCal, SysTime(DateTime(2010, 11, 30, 0, 59, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 12, 1).dayOfGregorianCal, SysTime(DateTime(2010, 12, 1, 0, 0, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(2010, 12, 31).dayOfGregorianCal, SysTime(DateTime(2010, 12, 31, 0, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(2012, 2, 1).dayOfGregorianCal, SysTime(DateTime(2012, 2, 1, 23, 0, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(2012, 2, 28).dayOfGregorianCal, SysTime(DateTime(2012, 2, 28, 23, 59, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(2012, 2, 29).dayOfGregorianCal, SysTime(DateTime(2012, 2, 29, 7, 7, 7), FracSec.from!"hnsecs"(7)).dayOfGregorianCal);
_assertPred!"=="(Date(2012, 3, 1).dayOfGregorianCal, SysTime(DateTime(2012, 3, 1, 7, 7, 7), FracSec.from!"hnsecs"(7)).dayOfGregorianCal);
//Test B.C.
_assertPred!"=="(Date(0, 12, 31).dayOfGregorianCal, SysTime(DateTime(0, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(0, 12, 30).dayOfGregorianCal, SysTime(DateTime(0, 12, 30, 0, 0, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(0, 12, 1).dayOfGregorianCal, SysTime(DateTime(0, 12, 1, 0, 0, 0), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(0, 11, 30).dayOfGregorianCal, SysTime(DateTime(0, 11, 30, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-1, 12, 31).dayOfGregorianCal, SysTime(DateTime(-1, 12, 31, 12, 13, 14), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-1, 12, 30).dayOfGregorianCal, SysTime(DateTime(-1, 12, 30, 12, 13, 14), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-1, 1, 1).dayOfGregorianCal, SysTime(DateTime(-1, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-2, 12, 31).dayOfGregorianCal, SysTime(DateTime(-2, 12, 31, 12, 13, 14), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-2, 1, 1).dayOfGregorianCal, SysTime(DateTime(-2, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-3, 12, 31).dayOfGregorianCal, SysTime(DateTime(-3, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-3, 1, 1).dayOfGregorianCal, SysTime(DateTime(-3, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-4, 12, 31).dayOfGregorianCal, SysTime(DateTime(-4, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-4, 1, 1).dayOfGregorianCal, SysTime(DateTime(-4, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-5, 12, 31).dayOfGregorianCal, SysTime(DateTime(-5, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-5, 1, 1).dayOfGregorianCal, SysTime(DateTime(-5, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-9, 1, 1).dayOfGregorianCal, SysTime(DateTime(-9, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-49, 1, 1).dayOfGregorianCal, SysTime(DateTime(-49, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-50, 1, 1).dayOfGregorianCal, SysTime(DateTime(-50, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-97, 1, 1).dayOfGregorianCal, SysTime(DateTime(-97, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-99, 12, 31).dayOfGregorianCal, SysTime(DateTime(-99, 12, 31, 12, 13, 14), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-99, 1, 1).dayOfGregorianCal, SysTime(DateTime(-99, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-100, 1, 1).dayOfGregorianCal, SysTime(DateTime(-100, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-101, 1, 1).dayOfGregorianCal, SysTime(DateTime(-101, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-105, 1, 1).dayOfGregorianCal, SysTime(DateTime(-105, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-200, 1, 1).dayOfGregorianCal, SysTime(DateTime(-200, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-201, 1, 1).dayOfGregorianCal, SysTime(DateTime(-201, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-300, 1, 1).dayOfGregorianCal, SysTime(DateTime(-300, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-301, 1, 1).dayOfGregorianCal, SysTime(DateTime(-301, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-400, 12, 31).dayOfGregorianCal, SysTime(DateTime(-400, 12, 31, 12, 13, 14), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-400, 1, 1).dayOfGregorianCal, SysTime(DateTime(-400, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-401, 1, 1).dayOfGregorianCal, SysTime(DateTime(-401, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-499, 1, 1).dayOfGregorianCal, SysTime(DateTime(-499, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-500, 1, 1).dayOfGregorianCal, SysTime(DateTime(-500, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-501, 1, 1).dayOfGregorianCal, SysTime(DateTime(-501, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-1000, 1, 1).dayOfGregorianCal, SysTime(DateTime(-1000, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-1001, 1, 1).dayOfGregorianCal, SysTime(DateTime(-1001, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-1599, 1, 1).dayOfGregorianCal, SysTime(DateTime(-1599, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-1600, 12, 31).dayOfGregorianCal, SysTime(DateTime(-1600, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-1600, 1, 1).dayOfGregorianCal, SysTime(DateTime(-1600, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-1601, 1, 1).dayOfGregorianCal, SysTime(DateTime(-1601, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-1900, 1, 1).dayOfGregorianCal, SysTime(DateTime(-1900, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-1901, 1, 1).dayOfGregorianCal, SysTime(DateTime(-1901, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-1999, 1, 1).dayOfGregorianCal, SysTime(DateTime(-1999, 1, 1, 12, 13, 14), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-1999, 7, 6).dayOfGregorianCal, SysTime(DateTime(-1999, 7, 6, 12, 13, 14), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-2000, 12, 31).dayOfGregorianCal, SysTime(DateTime(-2000, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-2000, 1, 1).dayOfGregorianCal, SysTime(DateTime(-2000, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-2001, 1, 1).dayOfGregorianCal, SysTime(DateTime(-2001, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 1, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 1, 31).dayOfGregorianCal, SysTime(DateTime(-2010, 1, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 2, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 2, 1, 0, 0, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 2, 28).dayOfGregorianCal, SysTime(DateTime(-2010, 2, 28, 0, 0, 0), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 3, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 3, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 3, 31).dayOfGregorianCal, SysTime(DateTime(-2010, 3, 31, 12, 13, 14), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 4, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 4, 1, 12, 13, 14), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 4, 30).dayOfGregorianCal, SysTime(DateTime(-2010, 4, 30, 12, 13, 14), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 5, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 5, 1, 12, 13, 14), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 5, 31).dayOfGregorianCal, SysTime(DateTime(-2010, 5, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 6, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 6, 1, 23, 59, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 6, 30).dayOfGregorianCal, SysTime(DateTime(-2010, 6, 30, 23, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 7, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 7, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 7, 31).dayOfGregorianCal, SysTime(DateTime(-2010, 7, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 8, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 8, 1, 0, 0, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 8, 31).dayOfGregorianCal, SysTime(DateTime(-2010, 8, 31, 0, 0, 0), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 9, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 9, 1, 0, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 9, 30).dayOfGregorianCal, SysTime(DateTime(-2010, 9, 30, 12, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 10, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 10, 1, 0, 12, 0), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 10, 31).dayOfGregorianCal, SysTime(DateTime(-2010, 10, 31, 0, 0, 12), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 11, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 11, 1, 23, 0, 0), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 11, 30).dayOfGregorianCal, SysTime(DateTime(-2010, 11, 30, 0, 59, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 12, 1).dayOfGregorianCal, SysTime(DateTime(-2010, 12, 1, 0, 0, 59), FracSec.from!"hnsecs"(500)).dayOfGregorianCal);
_assertPred!"=="(Date(-2010, 12, 31).dayOfGregorianCal, SysTime(DateTime(-2010, 12, 31, 0, 59, 59), FracSec.from!"hnsecs"(50_000)).dayOfGregorianCal);
_assertPred!"=="(Date(-2012, 2, 1).dayOfGregorianCal, SysTime(DateTime(-2012, 2, 1, 23, 0, 59), FracSec.from!"hnsecs"(9_999_999)).dayOfGregorianCal);
_assertPred!"=="(Date(-2012, 2, 28).dayOfGregorianCal, SysTime(DateTime(-2012, 2, 28, 23, 59, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
_assertPred!"=="(Date(-2012, 2, 29).dayOfGregorianCal, SysTime(DateTime(-2012, 2, 29, 7, 7, 7), FracSec.from!"hnsecs"(7)).dayOfGregorianCal);
_assertPred!"=="(Date(-2012, 3, 1).dayOfGregorianCal, SysTime(DateTime(-2012, 3, 1, 7, 7, 7), FracSec.from!"hnsecs"(7)).dayOfGregorianCal);
_assertPred!"=="(Date(-3760, 9, 7).dayOfGregorianCal, SysTime(DateTime(-3760, 9, 7, 0, 0, 0), FracSec.from!"hnsecs"(0)).dayOfGregorianCal);
}
}
/++
The Xth day of the Gregorian Calendar that this $(D SysTime) is on.
Setting this property does not affect the time portion of $(D SysTime).
Params:
days = The day of the Gregorian Calendar to set this $(D SysTime)
to.
Examples:
--------------------
auto st = SysTime(DateTime(0, 0, 0, 12, 0, 0));
st.dayOfGregorianCal = 1;
assert(st == SysTime(DateTime(1, 1, 1, 12, 0, 0)));
st.dayOfGregorianCal = 365;
assert(st == SysTime(DateTime(1, 12, 31, 12, 0, 0)));
st.dayOfGregorianCal = 366;
assert(st == SysTime(DateTime(2, 1, 1, 12, 0, 0)));
st.dayOfGregorianCal = 0;
assert(st == SysTime(DateTime(0, 12, 31, 12, 0, 0)));
st.dayOfGregorianCal = -365;
assert(st == SysTime(DateTime(-0, 1, 1, 12, 0, 0)));
st.dayOfGregorianCal = -366;
assert(st == SysTime(DateTime(-1, 12, 31, 12, 0, 0)));
st.dayOfGregorianCal = 730_120;
assert(st == SysTime(DateTime(2000, 1, 1, 12, 0, 0)));
st.dayOfGregorianCal = 734_137;
assert(st == SysTime(DateTime(2010, 12, 31, 12, 0, 0)));
--------------------
+/
@property void dayOfGregorianCal(int days) nothrow
{
auto hnsecs = adjTime;
hnsecs = removeUnitsFromHNSecs!"days"(hnsecs);
if(hnsecs < 0)
hnsecs += convert!("hours", "hnsecs")(24);
if(--days < 0)
{
hnsecs -= convert!("hours", "hnsecs")(24);
++days;
}
immutable newDaysHNSecs = convert!("days", "hnsecs")(days);
adjTime = newDaysHNSecs + hnsecs;
}
unittest
{
version(testStdDateTime)
{
void testST(SysTime orig, int day, in SysTime expected, size_t line = __LINE__)
{
orig.dayOfGregorianCal = day;
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
testST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
testST(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1)));
testST(SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
//Test B.C.
testST(SysTime(DateTime(0, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)), 0, SysTime(DateTime(0, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)));
testST(SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
testST(SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(1)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(1)));
testST(SysTime(DateTime(0, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(0)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)));
//Test Both.
testST(SysTime(DateTime(-512, 7, 20, 0, 0, 0), FracSec.from!"hnsecs"(0)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(0)));
testST(SysTime(DateTime(-513, 6, 6, 0, 0, 0), FracSec.from!"hnsecs"(1)), 1, SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1)));
testST(SysTime(DateTime(-511, 5, 7, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 1, SysTime(DateTime(1, 1, 1, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
testST(SysTime(DateTime(1607, 4, 8, 0, 0, 0), FracSec.from!"hnsecs"(0)), 0, SysTime(DateTime(0, 12, 31, 0, 0, 0), FracSec.from!"hnsecs"(0)));
testST(SysTime(DateTime(1500, 3, 9, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
testST(SysTime(DateTime(999, 2, 10, 23, 59, 59), FracSec.from!"hnsecs"(1)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(1)));
testST(SysTime(DateTime(2007, 12, 11, 23, 59, 59), FracSec.from!"hnsecs"(0)), 0, SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(0)));
auto sysTime = SysTime(DateTime(1, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212));
void testST2(int day, in SysTime expected, size_t line = __LINE__)
{
sysTime.dayOfGregorianCal = day;
_assertPred!"=="(sysTime, expected, "", __FILE__, line);
}
//Test A.D.
testST2(1, SysTime(DateTime(1, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(2, SysTime(DateTime(1, 1, 2, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(32, SysTime(DateTime(1, 2, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(366, SysTime(DateTime(2, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(731, SysTime(DateTime(3, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(1096, SysTime(DateTime(4, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(1462, SysTime(DateTime(5, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(17_898, SysTime(DateTime(50, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(35_065, SysTime(DateTime(97, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(36_160, SysTime(DateTime(100, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(36_525, SysTime(DateTime(101, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(37_986, SysTime(DateTime(105, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(72_684, SysTime(DateTime(200, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(73_049, SysTime(DateTime(201, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(109_208, SysTime(DateTime(300, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(109_573, SysTime(DateTime(301, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(145_732, SysTime(DateTime(400, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(146_098, SysTime(DateTime(401, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(182_257, SysTime(DateTime(500, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(182_622, SysTime(DateTime(501, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(364_878, SysTime(DateTime(1000, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(365_243, SysTime(DateTime(1001, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(584_023, SysTime(DateTime(1600, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(584_389, SysTime(DateTime(1601, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(693_596, SysTime(DateTime(1900, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(693_961, SysTime(DateTime(1901, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(729_755, SysTime(DateTime(1999, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(730_120, SysTime(DateTime(2000, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(730_486, SysTime(DateTime(2001, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_773, SysTime(DateTime(2010, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_803, SysTime(DateTime(2010, 1, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_804, SysTime(DateTime(2010, 2, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_831, SysTime(DateTime(2010, 2, 28, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_832, SysTime(DateTime(2010, 3, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_862, SysTime(DateTime(2010, 3, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_863, SysTime(DateTime(2010, 4, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_892, SysTime(DateTime(2010, 4, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_893, SysTime(DateTime(2010, 5, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_923, SysTime(DateTime(2010, 5, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_924, SysTime(DateTime(2010, 6, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_953, SysTime(DateTime(2010, 6, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_954, SysTime(DateTime(2010, 7, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_984, SysTime(DateTime(2010, 7, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(733_985, SysTime(DateTime(2010, 8, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_015, SysTime(DateTime(2010, 8, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_016, SysTime(DateTime(2010, 9, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_045, SysTime(DateTime(2010, 9, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_046, SysTime(DateTime(2010, 10, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_076, SysTime(DateTime(2010, 10, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_077, SysTime(DateTime(2010, 11, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_106, SysTime(DateTime(2010, 11, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_107, SysTime(DateTime(2010, 12, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_137, SysTime(DateTime(2010, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_534, SysTime(DateTime(2012, 2, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_561, SysTime(DateTime(2012, 2, 28, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_562, SysTime(DateTime(2012, 2, 29, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_563, SysTime(DateTime(2012, 3, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_534, SysTime(DateTime(2012, 2, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_561, SysTime(DateTime(2012, 2, 28, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_562, SysTime(DateTime(2012, 2, 29, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(734_563, SysTime(DateTime(2012, 3, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
//Test B.C.
testST2(0, SysTime(DateTime(0, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-1, SysTime(DateTime(0, 12, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-30, SysTime(DateTime(0, 12, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-31, SysTime(DateTime(0, 11, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-366, SysTime(DateTime(-1, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-367, SysTime(DateTime(-1, 12, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-730, SysTime(DateTime(-1, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-731, SysTime(DateTime(-2, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-1095, SysTime(DateTime(-2, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-1096, SysTime(DateTime(-3, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-1460, SysTime(DateTime(-3, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-1461, SysTime(DateTime(-4, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-1826, SysTime(DateTime(-4, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-1827, SysTime(DateTime(-5, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-2191, SysTime(DateTime(-5, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-3652, SysTime(DateTime(-9, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-18_262, SysTime(DateTime(-49, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-18_627, SysTime(DateTime(-50, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-35_794, SysTime(DateTime(-97, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-36_160, SysTime(DateTime(-99, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-36_524, SysTime(DateTime(-99, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-36_889, SysTime(DateTime(-100, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-37_254, SysTime(DateTime(-101, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-38_715, SysTime(DateTime(-105, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-73_413, SysTime(DateTime(-200, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-73_778, SysTime(DateTime(-201, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-109_937, SysTime(DateTime(-300, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-110_302, SysTime(DateTime(-301, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-146_097, SysTime(DateTime(-400, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-146_462, SysTime(DateTime(-400, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-146_827, SysTime(DateTime(-401, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-182_621, SysTime(DateTime(-499, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-182_986, SysTime(DateTime(-500, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-183_351, SysTime(DateTime(-501, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-365_607, SysTime(DateTime(-1000, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-365_972, SysTime(DateTime(-1001, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-584_387, SysTime(DateTime(-1599, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-584_388, SysTime(DateTime(-1600, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-584_753, SysTime(DateTime(-1600, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-585_118, SysTime(DateTime(-1601, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-694_325, SysTime(DateTime(-1900, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-694_690, SysTime(DateTime(-1901, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-730_484, SysTime(DateTime(-1999, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-730_485, SysTime(DateTime(-2000, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-730_850, SysTime(DateTime(-2000, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-731_215, SysTime(DateTime(-2001, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_502, SysTime(DateTime(-2010, 1, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_472, SysTime(DateTime(-2010, 1, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_471, SysTime(DateTime(-2010, 2, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_444, SysTime(DateTime(-2010, 2, 28, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_443, SysTime(DateTime(-2010, 3, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_413, SysTime(DateTime(-2010, 3, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_412, SysTime(DateTime(-2010, 4, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_383, SysTime(DateTime(-2010, 4, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_382, SysTime(DateTime(-2010, 5, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_352, SysTime(DateTime(-2010, 5, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_351, SysTime(DateTime(-2010, 6, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_322, SysTime(DateTime(-2010, 6, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_321, SysTime(DateTime(-2010, 7, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_291, SysTime(DateTime(-2010, 7, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_290, SysTime(DateTime(-2010, 8, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_260, SysTime(DateTime(-2010, 8, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_259, SysTime(DateTime(-2010, 9, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_230, SysTime(DateTime(-2010, 9, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_229, SysTime(DateTime(-2010, 10, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_199, SysTime(DateTime(-2010, 10, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_198, SysTime(DateTime(-2010, 11, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_169, SysTime(DateTime(-2010, 11, 30, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_168, SysTime(DateTime(-2010, 12, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-734_138, SysTime(DateTime(-2010, 12, 31, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-735_202, SysTime(DateTime(-2012, 2, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-735_175, SysTime(DateTime(-2012, 2, 28, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-735_174, SysTime(DateTime(-2012, 2, 29, 12, 2, 9), FracSec.from!"msecs"(212)));
testST2(-735_173, SysTime(DateTime(-2012, 3, 1, 12, 2, 9), FracSec.from!"msecs"(212)));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(!__traits(compiles, cst.dayOfGregorianCal = 7));
//static assert(!__traits(compiles, ist.dayOfGregorianCal = 7));
//Verify Examples.
auto st = SysTime(DateTime(0, 1, 1, 12, 0, 0));
st.dayOfGregorianCal = 1;
assert(st == SysTime(DateTime(1, 1, 1, 12, 0, 0)));
st.dayOfGregorianCal = 365;
assert(st == SysTime(DateTime(1, 12, 31, 12, 0, 0)));
st.dayOfGregorianCal = 366;
assert(st == SysTime(DateTime(2, 1, 1, 12, 0, 0)));
st.dayOfGregorianCal = 0;
assert(st == SysTime(DateTime(0, 12, 31, 12, 0, 0)));
st.dayOfGregorianCal = -365;
assert(st == SysTime(DateTime(-0, 1, 1, 12, 0, 0)));
st.dayOfGregorianCal = -366;
assert(st == SysTime(DateTime(-1, 12, 31, 12, 0, 0)));
st.dayOfGregorianCal = 730_120;
assert(st == SysTime(DateTime(2000, 1, 1, 12, 0, 0)));
st.dayOfGregorianCal = 734_137;
assert(st == SysTime(DateTime(2010, 12, 31, 12, 0, 0)));
}
}
/++
The ISO 8601 week of the year that this $(D SysTime) is in.
See_Also:
$(WEB en.wikipedia.org/wiki/ISO_week_date, ISO Week Date).
+/
@property ubyte isoWeek() const nothrow
{
return (cast(Date)this).isoWeek;
}
unittest
{
version(testStdDateTime)
{
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st.isoWeek));
static assert(__traits(compiles, cst.isoWeek));
//static assert(__traits(compiles, ist.isoWeek));
}
}
/++
$(D SysTime) for the last day in the month that this Date is in.
The time portion of endOfMonth is always 23:59:59.9999999.
Examples:
--------------------
assert(SysTime(DateTime(1999, 1, 6, 0, 0, 0)).endOfMonth ==
SysTime(DateTime(1999, 1, 31, 23, 59, 59),
FracSec.from!"hnsecs"(9_999_999)));
assert(SysTime(DateTime(1999, 2, 7, 19, 30, 0),
FracSec.from!"msecs"(24)).endOfMonth ==
SysTime(DateTime(1999, 2, 28, 23, 59, 59),
FracSec.from!"hnsecs"(9_999_999)));
assert(SysTime(DateTime(2000, 2, 7, 5, 12, 27),
FracSec.from!"usecs"(5203)).endOfMonth ==
SysTime(DateTime(2000, 2, 29, 23, 59, 59),
FracSec.from!"hnsecs"(9_999_999)));
assert(SysTime(DateTime(2000, 6, 4, 12, 22, 9),
FracSec.from!"hnsecs"(12345)).endOfMonth ==
SysTime(DateTime(2000, 6, 30, 23, 59, 59),
FracSec.from!"hnsecs"(9_999_999)));
--------------------
+/
@property SysTime endOfMonth() const nothrow
{
immutable hnsecs = adjTime;
immutable days = getUnitsFromHNSecs!"days"(hnsecs);
auto date = Date(cast(int)days + 1).endOfMonth;
auto newDays = date.dayOfGregorianCal - 1;
long theTimeHNSecs;
if(newDays < 0)
{
theTimeHNSecs = -1;
++newDays;
}
else
theTimeHNSecs = convert!("days", "hnsecs")(1) - 1;
immutable newDaysHNSecs = convert!("days", "hnsecs")(newDays);
auto retval = SysTime(this._stdTime, this._timezone.get);
retval.adjTime = newDaysHNSecs + theTimeHNSecs;
return retval;
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(SysTime(Date(1999, 1, 1)).endOfMonth, SysTime(DateTime(1999, 1, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 2, 1)).endOfMonth, SysTime(DateTime(1999, 2, 28, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(2000, 2, 1)).endOfMonth, SysTime(DateTime(2000, 2, 29, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 3, 1)).endOfMonth, SysTime(DateTime(1999, 3, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 4, 1)).endOfMonth, SysTime(DateTime(1999, 4, 30, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 5, 1)).endOfMonth, SysTime(DateTime(1999, 5, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 6, 1)).endOfMonth, SysTime(DateTime(1999, 6, 30, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 7, 1)).endOfMonth, SysTime(DateTime(1999, 7, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 8, 1)).endOfMonth, SysTime(DateTime(1999, 8, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 9, 1)).endOfMonth, SysTime(DateTime(1999, 9, 30, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 10, 1)).endOfMonth, SysTime(DateTime(1999, 10, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 11, 1)).endOfMonth, SysTime(DateTime(1999, 11, 30, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(1999, 12, 1)).endOfMonth, SysTime(DateTime(1999, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
//Test B.C.
_assertPred!"=="(SysTime(Date(-1999, 1, 1)).endOfMonth, SysTime(DateTime(-1999, 1, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 2, 1)).endOfMonth, SysTime(DateTime(-1999, 2, 28, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-2000, 2, 1)).endOfMonth, SysTime(DateTime(-2000, 2, 29, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 3, 1)).endOfMonth, SysTime(DateTime(-1999, 3, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 4, 1)).endOfMonth, SysTime(DateTime(-1999, 4, 30, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 5, 1)).endOfMonth, SysTime(DateTime(-1999, 5, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 6, 1)).endOfMonth, SysTime(DateTime(-1999, 6, 30, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 7, 1)).endOfMonth, SysTime(DateTime(-1999, 7, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 8, 1)).endOfMonth, SysTime(DateTime(-1999, 8, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 9, 1)).endOfMonth, SysTime(DateTime(-1999, 9, 30, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 10, 1)).endOfMonth, SysTime(DateTime(-1999, 10, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 11, 1)).endOfMonth, SysTime(DateTime(-1999, 11, 30, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
_assertPred!"=="(SysTime(Date(-1999, 12, 1)).endOfMonth, SysTime(DateTime(-1999, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.endOfMonth));
//static assert(__traits(compiles, ist.endOfMonth));
//Verify Examples.
assert(SysTime(DateTime(1999, 1, 6, 0, 0, 0)).endOfMonth == SysTime(DateTime(1999, 1, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
assert(SysTime(DateTime(1999, 2, 7, 19, 30, 0), FracSec.from!"msecs"(24)).endOfMonth == SysTime(DateTime(1999, 2, 28, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
assert(SysTime(DateTime(2000, 2, 7, 5, 12, 27), FracSec.from!"usecs"(5203)).endOfMonth == SysTime(DateTime(2000, 2, 29, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
assert(SysTime(DateTime(2000, 6, 4, 12, 22, 9), FracSec.from!"hnsecs"(12345)).endOfMonth == SysTime(DateTime(2000, 6, 30, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999)));
}
}
/++
The last day in the month that this $(D SysTime) is in.
Examples:
--------------------
assert(SysTime(DateTime(1999, 1, 6, 0, 0, 0)).daysInMonth == 31);
assert(SysTime(DateTime(1999, 2, 7, 19, 30, 0)).daysInMonth == 28);
assert(SysTime(DateTime(2000, 2, 7, 5, 12, 27)).daysInMonth == 29);
assert(SysTime(DateTime(2000, 6, 4, 12, 22, 9)).daysInMonth == 30);
--------------------
+/
@property ubyte daysInMonth() const nothrow
{
return Date(dayOfGregorianCal).daysInMonth;
}
/++
$(RED Scheduled for deprecation in January 2012.
Please use daysInMonth instead.)
+/
alias daysInMonth endofMonthDay;
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(SysTime(DateTime(1999, 1, 1, 12, 1, 13)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(1999, 2, 1, 17, 13, 12)).daysInMonth, 28);
_assertPred!"=="(SysTime(DateTime(2000, 2, 1, 13, 2, 12)).daysInMonth, 29);
_assertPred!"=="(SysTime(DateTime(1999, 3, 1, 12, 13, 12)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(1999, 4, 1, 12, 6, 13)).daysInMonth, 30);
_assertPred!"=="(SysTime(DateTime(1999, 5, 1, 15, 13, 12)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(1999, 6, 1, 13, 7, 12)).daysInMonth, 30);
_assertPred!"=="(SysTime(DateTime(1999, 7, 1, 12, 13, 17)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(1999, 8, 1, 12, 3, 13)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(1999, 9, 1, 12, 13, 12)).daysInMonth, 30);
_assertPred!"=="(SysTime(DateTime(1999, 10, 1, 13, 19, 12)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(1999, 11, 1, 12, 13, 17)).daysInMonth, 30);
_assertPred!"=="(SysTime(DateTime(1999, 12, 1, 12, 52, 13)).daysInMonth, 31);
//Test B.C.
_assertPred!"=="(SysTime(DateTime(-1999, 1, 1, 12, 1, 13)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(-1999, 2, 1, 7, 13, 12)).daysInMonth, 28);
_assertPred!"=="(SysTime(DateTime(-2000, 2, 1, 13, 2, 12)).daysInMonth, 29);
_assertPred!"=="(SysTime(DateTime(-1999, 3, 1, 12, 13, 12)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(-1999, 4, 1, 12, 6, 13)).daysInMonth, 30);
_assertPred!"=="(SysTime(DateTime(-1999, 5, 1, 5, 13, 12)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(-1999, 6, 1, 13, 7, 12)).daysInMonth, 30);
_assertPred!"=="(SysTime(DateTime(-1999, 7, 1, 12, 13, 17)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(-1999, 8, 1, 12, 3, 13)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(-1999, 9, 1, 12, 13, 12)).daysInMonth, 30);
_assertPred!"=="(SysTime(DateTime(-1999, 10, 1, 13, 19, 12)).daysInMonth, 31);
_assertPred!"=="(SysTime(DateTime(-1999, 11, 1, 12, 13, 17)).daysInMonth, 30);
_assertPred!"=="(SysTime(DateTime(-1999, 12, 1, 12, 52, 13)).daysInMonth, 31);
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.daysInMonth));
//static assert(__traits(compiles, ist.daysInMonth));
//Verify Examples.
assert(SysTime(DateTime(1999, 1, 6, 0, 0, 0)).daysInMonth == 31);
assert(SysTime(DateTime(1999, 2, 7, 19, 30, 0)).daysInMonth == 28);
assert(SysTime(DateTime(2000, 2, 7, 5, 12, 27)).daysInMonth == 29);
assert(SysTime(DateTime(2000, 6, 4, 12, 22, 9)).daysInMonth == 30);
}
}
/++
Whether the current year is a date in A.D.
Examples:
--------------------
assert(SysTime(DateTime(1, 1, 1, 12, 7, 0)).isAD);
assert(SysTime(DateTime(2010, 12, 31, 0, 0, 0)).isAD);
assert(!SysTime(DateTime(0, 12, 31, 23, 59, 59)).isAD);
assert(!SysTime(DateTime(-2010, 1, 1, 2, 2, 2)).isAD);
--------------------
+/
@property bool isAD() const nothrow
{
return adjTime >= 0;
}
unittest
{
version(testStdDateTime)
{
assert(SysTime(DateTime(2010, 7, 4, 12, 0, 9)).isAD);
assert(SysTime(DateTime(1, 1, 1, 0, 0, 0)).isAD);
assert(!SysTime(DateTime(0, 12, 31, 23, 59, 59)).isAD);
assert(!SysTime(DateTime(0, 1, 1, 23, 59, 59)).isAD);
assert(!SysTime(DateTime(-1, 1, 1, 23 ,59 ,59)).isAD);
assert(!SysTime(DateTime(-2010, 7, 4, 12, 2, 2)).isAD);
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.isAD));
//static assert(__traits(compiles, ist.isAD));
//Verify Examples.
assert(SysTime(DateTime(1, 1, 1, 12, 7, 0)).isAD);
assert(SysTime(DateTime(2010, 12, 31, 0, 0, 0)).isAD);
assert(!SysTime(DateTime(0, 12, 31, 23, 59, 59)).isAD);
assert(!SysTime(DateTime(-2010, 1, 1, 2, 2, 2)).isAD);
}
}
/++
The julian day for this $(D SysTime) at the given time. For example,
prior to noon, 1996-03-31 would be the julian day number 2_450_173, so
this function returns 2_450_173, while from noon onward, the julian
day number would be 2_450_174, so this function returns 2_450_174.
+/
@property long julianDay() const nothrow
{
immutable jd = dayOfGregorianCal + 1_721_425;
return hour < 12 ? jd - 1 : jd;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(SysTime(DateTime(-4713, 11, 24, 0, 0, 0)).julianDay, -1);
_assertPred!"=="(SysTime(DateTime(-4713, 11, 24, 12, 0, 0)).julianDay, 0);
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 0, 0, 0)).julianDay, 1_721_424);
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 12, 0, 0)).julianDay, 1_721_425);
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 0, 0, 0)).julianDay, 1_721_425);
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 12, 0, 0)).julianDay, 1_721_426);
_assertPred!"=="(SysTime(DateTime(1582, 10, 15, 0, 0, 0)).julianDay, 2_299_160);
_assertPred!"=="(SysTime(DateTime(1582, 10, 15, 12, 0, 0)).julianDay, 2_299_161);
_assertPred!"=="(SysTime(DateTime(1858, 11, 17, 0, 0, 0)).julianDay, 2_400_000);
_assertPred!"=="(SysTime(DateTime(1858, 11, 17, 12, 0, 0)).julianDay, 2_400_001);
_assertPred!"=="(SysTime(DateTime(1982, 1, 4, 0, 0, 0)).julianDay, 2_444_973);
_assertPred!"=="(SysTime(DateTime(1982, 1, 4, 12, 0, 0)).julianDay, 2_444_974);
_assertPred!"=="(SysTime(DateTime(1996, 3, 31, 0, 0, 0)).julianDay, 2_450_173);
_assertPred!"=="(SysTime(DateTime(1996, 3, 31, 12, 0, 0)).julianDay, 2_450_174);
_assertPred!"=="(SysTime(DateTime(2010, 8, 24, 0, 0, 0)).julianDay, 2_455_432);
_assertPred!"=="(SysTime(DateTime(2010, 8, 24, 12, 0, 0)).julianDay, 2_455_433);
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.julianDay));
//static assert(__traits(compiles, ist.julianDay));
}
}
/++
The modified julian day for any time on this date (since, the modified
julian day changes at midnight).
+/
@property long modJulianDay() const nothrow
{
return (dayOfGregorianCal + 1_721_425) - 2_400_001;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(SysTime(DateTime(1858, 11, 17, 0, 0, 0)).modJulianDay, 0);
_assertPred!"=="(SysTime(DateTime(1858, 11, 17, 12, 0, 0)).modJulianDay, 0);
_assertPred!"=="(SysTime(DateTime(2010, 8, 24, 0, 0, 0)).modJulianDay, 55_432);
_assertPred!"=="(SysTime(DateTime(2010, 8, 24, 12, 0, 0)).modJulianDay, 55_432);
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cst.modJulianDay));
//static assert(__traits(compiles, ist.modJulianDay));
}
}
/++
Returns a $(D Date) equivalent to this $(D SysTime).
+/
Date opCast(T)() const nothrow
if(is(Unqual!T == Date))
{
return Date(dayOfGregorianCal);
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(cast(Date)SysTime(Date(1999, 7, 6)), Date(1999, 7, 6));
_assertPred!"=="(cast(Date)SysTime(Date(2000, 12, 31)), Date(2000, 12, 31));
_assertPred!"=="(cast(Date)SysTime(Date(2001, 1, 1)), Date(2001, 1, 1));
_assertPred!"=="(cast(Date)SysTime(DateTime(1999, 7, 6, 12, 10, 9)), Date(1999, 7, 6));
_assertPred!"=="(cast(Date)SysTime(DateTime(2000, 12, 31, 13, 11, 10)), Date(2000, 12, 31));
_assertPred!"=="(cast(Date)SysTime(DateTime(2001, 1, 1, 14, 12, 11)), Date(2001, 1, 1));
_assertPred!"=="(cast(Date)SysTime(Date(-1999, 7, 6)), Date(-1999, 7, 6));
_assertPred!"=="(cast(Date)SysTime(Date(-2000, 12, 31)), Date(-2000, 12, 31));
_assertPred!"=="(cast(Date)SysTime(Date(-2001, 1, 1)), Date(-2001, 1, 1));
_assertPred!"=="(cast(Date)SysTime(DateTime(-1999, 7, 6, 12, 10, 9)), Date(-1999, 7, 6));
_assertPred!"=="(cast(Date)SysTime(DateTime(-2000, 12, 31, 13, 11, 10)), Date(-2000, 12, 31));
_assertPred!"=="(cast(Date)SysTime(DateTime(-2001, 1, 1, 14, 12, 11)), Date(-2001, 1, 1));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cast(Date)cst));
//static assert(__traits(compiles, cast(Date)ist));
}
}
/++
Returns a $(D DateTime) equivalent to this $(D SysTime).
+/
DateTime opCast(T)() const nothrow
if(is(Unqual!T == DateTime))
{
try
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
immutable hour = splitUnitsFromHNSecs!"hours"(hnsecs);
immutable minute = splitUnitsFromHNSecs!"minutes"(hnsecs);
immutable second = getUnitsFromHNSecs!"seconds"(hnsecs);
return DateTime(Date(cast(int)days), TimeOfDay(cast(int)hour, cast(int)minute, cast(int)second));
}
catch(Exception e)
assert(0, "Either DateTime's constructor or TimeOfDay's constructor threw.");
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(cast(DateTime)SysTime(DateTime(1, 1, 6, 7, 12, 22)), DateTime(1, 1, 6, 7, 12, 22));
_assertPred!"=="(cast(DateTime)SysTime(DateTime(1, 1, 6, 7, 12, 22), FracSec.from!"msecs"(22)), DateTime(1, 1, 6, 7, 12, 22));
_assertPred!"=="(cast(DateTime)SysTime(Date(1999, 7, 6)), DateTime(1999, 7, 6, 0, 0, 0));
_assertPred!"=="(cast(DateTime)SysTime(Date(2000, 12, 31)), DateTime(2000, 12, 31, 0, 0, 0));
_assertPred!"=="(cast(DateTime)SysTime(Date(2001, 1, 1)), DateTime(2001, 1, 1, 0, 0, 0));
_assertPred!"=="(cast(DateTime)SysTime(DateTime(1999, 7, 6, 12, 10, 9)), DateTime(1999, 7, 6, 12, 10, 9));
_assertPred!"=="(cast(DateTime)SysTime(DateTime(2000, 12, 31, 13, 11, 10)), DateTime(2000, 12, 31, 13, 11, 10));
_assertPred!"=="(cast(DateTime)SysTime(DateTime(2001, 1, 1, 14, 12, 11)), DateTime(2001, 1, 1, 14, 12, 11));
_assertPred!"=="(cast(DateTime)SysTime(DateTime(-1, 1, 6, 7, 12, 22)), DateTime(-1, 1, 6, 7, 12, 22));
_assertPred!"=="(cast(DateTime)SysTime(DateTime(-1, 1, 6, 7, 12, 22), FracSec.from!"msecs"(22)), DateTime(-1, 1, 6, 7, 12, 22));
_assertPred!"=="(cast(DateTime)SysTime(Date(-1999, 7, 6)), DateTime(-1999, 7, 6, 0, 0, 0));
_assertPred!"=="(cast(DateTime)SysTime(Date(-2000, 12, 31)), DateTime(-2000, 12, 31, 0, 0, 0));
_assertPred!"=="(cast(DateTime)SysTime(Date(-2001, 1, 1)), DateTime(-2001, 1, 1, 0, 0, 0));
_assertPred!"=="(cast(DateTime)SysTime(DateTime(-1999, 7, 6, 12, 10, 9)), DateTime(-1999, 7, 6, 12, 10, 9));
_assertPred!"=="(cast(DateTime)SysTime(DateTime(-2000, 12, 31, 13, 11, 10)), DateTime(-2000, 12, 31, 13, 11, 10));
_assertPred!"=="(cast(DateTime)SysTime(DateTime(-2001, 1, 1, 14, 12, 11)), DateTime(-2001, 1, 1, 14, 12, 11));
_assertPred!"=="(cast(DateTime)SysTime(DateTime(2011, 1, 13, 8, 17, 2), FracSec.from!"msecs"(296), LocalTime()),
DateTime(2011, 1, 13, 8, 17, 2));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cast(DateTime)cst));
//static assert(__traits(compiles, cast(DateTime)ist));
}
}
/++
Returns a $(D TimeOfDay) equivalent to this $(D SysTime).
+/
TimeOfDay opCast(T)() const nothrow
if(is(Unqual!T == TimeOfDay))
{
try
{
auto hnsecs = adjTime;
hnsecs = removeUnitsFromHNSecs!"days"(hnsecs);
if(hnsecs < 0)
hnsecs += convert!("hours", "hnsecs")(24);
immutable hour = splitUnitsFromHNSecs!"hours"(hnsecs);
immutable minute = splitUnitsFromHNSecs!"minutes"(hnsecs);
immutable second = getUnitsFromHNSecs!"seconds"(hnsecs);
return TimeOfDay(cast(int)hour, cast(int)minute, cast(int)second);
}
catch(Exception e)
assert(0, "TimeOfDay's constructor threw.");
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(cast(TimeOfDay)SysTime(Date(1999, 7, 6)), TimeOfDay(0, 0, 0));
_assertPred!"=="(cast(TimeOfDay)SysTime(Date(2000, 12, 31)), TimeOfDay(0, 0, 0));
_assertPred!"=="(cast(TimeOfDay)SysTime(Date(2001, 1, 1)), TimeOfDay(0, 0, 0));
_assertPred!"=="(cast(TimeOfDay)SysTime(DateTime(1999, 7, 6, 12, 10, 9)), TimeOfDay(12, 10, 9));
_assertPred!"=="(cast(TimeOfDay)SysTime(DateTime(2000, 12, 31, 13, 11, 10)), TimeOfDay(13, 11, 10));
_assertPred!"=="(cast(TimeOfDay)SysTime(DateTime(2001, 1, 1, 14, 12, 11)), TimeOfDay(14, 12, 11));
_assertPred!"=="(cast(TimeOfDay)SysTime(Date(-1999, 7, 6)), TimeOfDay(0, 0, 0));
_assertPred!"=="(cast(TimeOfDay)SysTime(Date(-2000, 12, 31)), TimeOfDay(0, 0, 0));
_assertPred!"=="(cast(TimeOfDay)SysTime(Date(-2001, 1, 1)), TimeOfDay(0, 0, 0));
_assertPred!"=="(cast(TimeOfDay)SysTime(DateTime(-1999, 7, 6, 12, 10, 9)), TimeOfDay(12, 10, 9));
_assertPred!"=="(cast(TimeOfDay)SysTime(DateTime(-2000, 12, 31, 13, 11, 10)), TimeOfDay(13, 11, 10));
_assertPred!"=="(cast(TimeOfDay)SysTime(DateTime(-2001, 1, 1, 14, 12, 11)), TimeOfDay(14, 12, 11));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cast(TimeOfDay)cst));
//static assert(__traits(compiles, cast(TimeOfDay)ist));
}
}
//Temporary hack until bug http://d.puremagic.com/issues/show_bug.cgi?id=4867 is fixed.
//This allows assignment from const(SysTime) to SysTime.
//It may be a good idea to keep it though, since casting from a type to itself
//should be allowed, and it doesn't work without this opCast() since opCast()
//has already been defined for other types.
SysTime opCast(T)() const pure nothrow
if(is(Unqual!T == SysTime))
{
return SysTime(_stdTime, _timezone.get);
}
/++
Converts this $(D SysTime) to a string with the format
YYYYMMDDTHHMMSS.FFFFFFFTZ (where F is fractional seconds and TZ is time
zone).
Note that the number of digits in the fractional seconds varies with the
number of fractional seconds. It's a maximum of 7 (which would be
hnsecs), but only has as many as are necessary to hold the correct value
(so no trailing zeroes), and if there are no fractional seconds, then
there is no decimal point.
If this $(D SysTime)'s time zone is $(D LocalTime), then TZ is empty.
If its time zone is $(D UTC), then it is "Z". Otherwise, it is the
offset from UTC (e.g. +1:00 or -7:00). Note that the offset from UTC
is $(I not) enough to uniquely identify the time zone.
Time zone offsets will be in the form +HH:MM or -HH:MM.
Examples:
--------------------
assert(SysTime(DateTime(2010, 7, 4, 7, 6, 12)).toISOString() ==
"20100704T070612");
assert(SysTime(DateTime(1998, 12, 25, 2, 15, 0),
FracSec.from!"msecs"(24)).toISOString() ==
"19981225T021500.024");
assert(SysTime(DateTime(0, 1, 5, 23, 9, 59)).toISOString() ==
"00000105T230959");
assert(SysTime(DateTime(-4, 1, 5, 0, 0, 2),
FracSec.from!"hnsecs"(520_920)).toISOString() ==
"-00040105T000002.052092");
--------------------
+/
string toISOString() const nothrow
{
try
{
immutable adjustedTime = adjTime;
long hnsecs = adjustedTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
auto hour = splitUnitsFromHNSecs!"hours"(hnsecs);
auto minute = splitUnitsFromHNSecs!"minutes"(hnsecs);
auto second = splitUnitsFromHNSecs!"seconds"(hnsecs);
auto dateTime = DateTime(Date(cast(int)days), TimeOfDay(cast(int)hour, cast(int)minute, cast(int)second));
auto fracSecStr = fracSecToISOString(cast(int)hnsecs);
if(_timezone.get is LocalTime())
return dateTime.toISOString() ~ fracSecToISOString(cast(int)hnsecs);
if(_timezone.get is UTC())
return dateTime.toISOString() ~ fracSecToISOString(cast(int)hnsecs) ~ "Z";
immutable utcOffset = cast(int)convert!("hnsecs", "minutes")(adjustedTime - stdTime);
return dateTime.toISOString() ~ fracSecToISOString(cast(int)hnsecs) ~ SimpleTimeZone.toISOString(utcOffset);
}
catch(Exception e)
assert(0, "format() threw.");
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(SysTime(DateTime.init, UTC()).toISOString(), "00010101T000000Z");
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1), UTC()).toISOString(), "00010101T000000.0000001Z");
_assertPred!"=="(SysTime(DateTime(9, 12, 4, 0, 0, 0)).toISOString(), "00091204T000000");
_assertPred!"=="(SysTime(DateTime(99, 12, 4, 5, 6, 12)).toISOString(), "00991204T050612");
_assertPred!"=="(SysTime(DateTime(999, 12, 4, 13, 44, 59)).toISOString(), "09991204T134459");
_assertPred!"=="(SysTime(DateTime(9999, 7, 4, 23, 59, 59)).toISOString(), "99990704T235959");
_assertPred!"=="(SysTime(DateTime(10000, 10, 20, 1, 1, 1)).toISOString(), "+100001020T010101");
_assertPred!"=="(SysTime(DateTime(9, 12, 4, 0, 0, 0), FracSec.from!"msecs"(42)).toISOString(), "00091204T000000.042");
_assertPred!"=="(SysTime(DateTime(99, 12, 4, 5, 6, 12), FracSec.from!"msecs"(100)).toISOString(), "00991204T050612.1");
_assertPred!"=="(SysTime(DateTime(999, 12, 4, 13, 44, 59), FracSec.from!"usecs"(45020)).toISOString(), "09991204T134459.04502");
_assertPred!"=="(SysTime(DateTime(9999, 7, 4, 23, 59, 59), FracSec.from!"hnsecs"(12)).toISOString(), "99990704T235959.0000012");
_assertPred!"=="(SysTime(DateTime(10000, 10, 20, 1, 1, 1), FracSec.from!"hnsecs"(507890)).toISOString(), "+100001020T010101.050789");
_assertPred!"=="(SysTime(DateTime(2012, 12, 21, 12, 12, 12),
new SimpleTimeZone(-360)).toISOString(),
"20121221T121212-06:00");
_assertPred!"=="(SysTime(DateTime(2012, 12, 21, 12, 12, 12),
new SimpleTimeZone(420)).toISOString(),
"20121221T121212+07:00");
//Test B.C.
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999), UTC()).toISOString(), "00001231T235959.9999999Z");
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(1), UTC()).toISOString(), "00001231T235959.0000001Z");
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), UTC()).toISOString(), "00001231T235959Z");
_assertPred!"=="(SysTime(DateTime(0, 12, 4, 0, 12, 4)).toISOString(), "00001204T001204");
_assertPred!"=="(SysTime(DateTime(-9, 12, 4, 0, 0, 0)).toISOString(), "-00091204T000000");
_assertPred!"=="(SysTime(DateTime(-99, 12, 4, 5, 6, 12)).toISOString(), "-00991204T050612");
_assertPred!"=="(SysTime(DateTime(-999, 12, 4, 13, 44, 59)).toISOString(), "-09991204T134459");
_assertPred!"=="(SysTime(DateTime(-9999, 7, 4, 23, 59, 59)).toISOString(), "-99990704T235959");
_assertPred!"=="(SysTime(DateTime(-10000, 10, 20, 1, 1, 1)).toISOString(), "-100001020T010101");
_assertPred!"=="(SysTime(DateTime(0, 12, 4, 0, 0, 0), FracSec.from!"msecs"(7)).toISOString(), "00001204T000000.007");
_assertPred!"=="(SysTime(DateTime(-9, 12, 4, 0, 0, 0), FracSec.from!"msecs"(42)).toISOString(), "-00091204T000000.042");
_assertPred!"=="(SysTime(DateTime(-99, 12, 4, 5, 6, 12), FracSec.from!"msecs"(100)).toISOString(), "-00991204T050612.1");
_assertPred!"=="(SysTime(DateTime(-999, 12, 4, 13, 44, 59), FracSec.from!"usecs"(45020)).toISOString(), "-09991204T134459.04502");
_assertPred!"=="(SysTime(DateTime(-9999, 7, 4, 23, 59, 59), FracSec.from!"hnsecs"(12)).toISOString(), "-99990704T235959.0000012");
_assertPred!"=="(SysTime(DateTime(-10000, 10, 20, 1, 1, 1), FracSec.from!"hnsecs"(507890)).toISOString(), "-100001020T010101.050789");
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cast(TimeOfDay)cst));
//static assert(__traits(compiles, cast(TimeOfDay)ist));
//Verify Examples.
assert(SysTime(DateTime(2010, 7, 4, 7, 6, 12)).toISOString() ==
"20100704T070612");
assert(SysTime(DateTime(1998, 12, 25, 2, 15, 0),
FracSec.from!"msecs"(24)).toISOString() ==
"19981225T021500.024");
assert(SysTime(DateTime(0, 1, 5, 23, 9, 59)).toISOString() ==
"00000105T230959");
assert(SysTime(DateTime(-4, 1, 5, 0, 0, 2),
FracSec.from!"hnsecs"(520_920)).toISOString() ==
"-00040105T000002.052092");
}
}
/++
Converts this $(D SysTime) to a string with the format
YYYY-MM-DDTHH:MM:SS.FFFFFFFTZ (where F is fractional seconds and TZ
is the time zone).
Note that the number of digits in the fractional seconds varies with the
number of fractional seconds. It's a maximum of 7 (which would be
hnsecs), but only has as many as are necessary to hold the correct value
(so no trailing zeroes), and if there are no fractional seconds, then
there is no decimal point.
If this $(D SysTime)'s time zone is $(D LocalTime), then TZ is empty. If
its time zone is $(D UTC), then it is "Z". Otherwise, it is the offset
from UTC (e.g. +1:00 or -7:00). Note that the offset from UTC is
$(I not) enough to uniquely identify the time zone.
Time zone offsets will be in the form +HH:MM or -HH:MM.
Examples:
--------------------
assert(SysTime(DateTime(2010, 7, 4, 7, 6, 12)).toISOExtString() ==
"2010-07-04T07:06:12");
assert(SysTime(DateTime(1998, 12, 25, 2, 15, 0),
FracSec.from!"msecs"(24)).toISOExtString() ==
"1998-12-25T02:15:00.024");
assert(SysTime(DateTime(0, 1, 5, 23, 9, 59)).toISOExtString() ==
"0000-01-05T23:09:59");
assert(SysTime(DateTime(-4, 1, 5, 0, 0, 2),
FracSec.from!"hnsecs"(520_920)).toISOExtString() ==
"-0004-01-05T00:00:02.052092");
--------------------
+/
string toISOExtString() const nothrow
{
try
{
immutable adjustedTime = adjTime;
long hnsecs = adjustedTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
auto hour = splitUnitsFromHNSecs!"hours"(hnsecs);
auto minute = splitUnitsFromHNSecs!"minutes"(hnsecs);
auto second = splitUnitsFromHNSecs!"seconds"(hnsecs);
auto dateTime = DateTime(Date(cast(int)days), TimeOfDay(cast(int)hour, cast(int)minute, cast(int)second));
auto fracSecStr = fracSecToISOString(cast(int)hnsecs);
if(_timezone.get is LocalTime())
return dateTime.toISOExtString() ~ fracSecToISOString(cast(int)hnsecs);
if(_timezone.get is UTC())
return dateTime.toISOExtString() ~ fracSecToISOString(cast(int)hnsecs) ~ "Z";
immutable utcOffset = cast(int)convert!("hnsecs", "minutes")(adjustedTime - stdTime);
return dateTime.toISOExtString() ~ fracSecToISOString(cast(int)hnsecs) ~ SimpleTimeZone.toISOString(utcOffset);
}
catch(Exception e)
assert(0, "format() threw.");
}
/++
$(RED Scheduled for deprecation in November 2011.
Please use toISOExtString instead.)
+/
alias toISOExtString toISOExtendedString;
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(SysTime(DateTime.init, UTC()).toISOExtString(), "0001-01-01T00:00:00Z");
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1), UTC()).toISOExtString(), "0001-01-01T00:00:00.0000001Z");
_assertPred!"=="(SysTime(DateTime(9, 12, 4, 0, 0, 0)).toISOExtString(), "0009-12-04T00:00:00");
_assertPred!"=="(SysTime(DateTime(99, 12, 4, 5, 6, 12)).toISOExtString(), "0099-12-04T05:06:12");
_assertPred!"=="(SysTime(DateTime(999, 12, 4, 13, 44, 59)).toISOExtString(), "0999-12-04T13:44:59");
_assertPred!"=="(SysTime(DateTime(9999, 7, 4, 23, 59, 59)).toISOExtString(), "9999-07-04T23:59:59");
_assertPred!"=="(SysTime(DateTime(10000, 10, 20, 1, 1, 1)).toISOExtString(), "+10000-10-20T01:01:01");
_assertPred!"=="(SysTime(DateTime(9, 12, 4, 0, 0, 0), FracSec.from!"msecs"(42)).toISOExtString(), "0009-12-04T00:00:00.042");
_assertPred!"=="(SysTime(DateTime(99, 12, 4, 5, 6, 12), FracSec.from!"msecs"(100)).toISOExtString(), "0099-12-04T05:06:12.1");
_assertPred!"=="(SysTime(DateTime(999, 12, 4, 13, 44, 59), FracSec.from!"usecs"(45020)).toISOExtString(), "0999-12-04T13:44:59.04502");
_assertPred!"=="(SysTime(DateTime(9999, 7, 4, 23, 59, 59), FracSec.from!"hnsecs"(12)).toISOExtString(), "9999-07-04T23:59:59.0000012");
_assertPred!"=="(SysTime(DateTime(10000, 10, 20, 1, 1, 1), FracSec.from!"hnsecs"(507890)).toISOExtString(), "+10000-10-20T01:01:01.050789");
_assertPred!"=="(SysTime(DateTime(2012, 12, 21, 12, 12, 12),
new SimpleTimeZone(-360)).toISOExtString(),
"2012-12-21T12:12:12-06:00");
_assertPred!"=="(SysTime(DateTime(2012, 12, 21, 12, 12, 12),
new SimpleTimeZone(420)).toISOExtString(),
"2012-12-21T12:12:12+07:00");
//Test B.C.
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999), UTC()).toISOExtString(), "0000-12-31T23:59:59.9999999Z");
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(1), UTC()).toISOExtString(), "0000-12-31T23:59:59.0000001Z");
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), UTC()).toISOExtString(), "0000-12-31T23:59:59Z");
_assertPred!"=="(SysTime(DateTime(0, 12, 4, 0, 12, 4)).toISOExtString(), "0000-12-04T00:12:04");
_assertPred!"=="(SysTime(DateTime(-9, 12, 4, 0, 0, 0)).toISOExtString(), "-0009-12-04T00:00:00");
_assertPred!"=="(SysTime(DateTime(-99, 12, 4, 5, 6, 12)).toISOExtString(), "-0099-12-04T05:06:12");
_assertPred!"=="(SysTime(DateTime(-999, 12, 4, 13, 44, 59)).toISOExtString(), "-0999-12-04T13:44:59");
_assertPred!"=="(SysTime(DateTime(-9999, 7, 4, 23, 59, 59)).toISOExtString(), "-9999-07-04T23:59:59");
_assertPred!"=="(SysTime(DateTime(-10000, 10, 20, 1, 1, 1)).toISOExtString(), "-10000-10-20T01:01:01");
_assertPred!"=="(SysTime(DateTime(0, 12, 4, 0, 0, 0), FracSec.from!"msecs"(7)).toISOExtString(), "0000-12-04T00:00:00.007");
_assertPred!"=="(SysTime(DateTime(-9, 12, 4, 0, 0, 0), FracSec.from!"msecs"(42)).toISOExtString(), "-0009-12-04T00:00:00.042");
_assertPred!"=="(SysTime(DateTime(-99, 12, 4, 5, 6, 12), FracSec.from!"msecs"(100)).toISOExtString(), "-0099-12-04T05:06:12.1");
_assertPred!"=="(SysTime(DateTime(-999, 12, 4, 13, 44, 59), FracSec.from!"usecs"(45020)).toISOExtString(), "-0999-12-04T13:44:59.04502");
_assertPred!"=="(SysTime(DateTime(-9999, 7, 4, 23, 59, 59), FracSec.from!"hnsecs"(12)).toISOExtString(), "-9999-07-04T23:59:59.0000012");
_assertPred!"=="(SysTime(DateTime(-10000, 10, 20, 1, 1, 1), FracSec.from!"hnsecs"(507890)).toISOExtString(), "-10000-10-20T01:01:01.050789");
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cast(TimeOfDay)cst));
//static assert(__traits(compiles, cast(TimeOfDay)ist));
//Verify Examples.
assert(SysTime(DateTime(2010, 7, 4, 7, 6, 12)).toISOExtString() ==
"2010-07-04T07:06:12");
assert(SysTime(DateTime(1998, 12, 25, 2, 15, 0),
FracSec.from!"msecs"(24)).toISOExtString() ==
"1998-12-25T02:15:00.024");
assert(SysTime(DateTime(0, 1, 5, 23, 9, 59)).toISOExtString() ==
"0000-01-05T23:09:59");
assert(SysTime(DateTime(-4, 1, 5, 0, 0, 2),
FracSec.from!"hnsecs"(520_920)).toISOExtString() ==
"-0004-01-05T00:00:02.052092");
}
}
/++
Converts this $(D SysTime) to a string with the format
YYYY-Mon-DD HH:MM:SS.FFFFFFFTZ (where F is fractional seconds and TZ
is the time zone).
Note that the number of digits in the fractional seconds varies with the
number of fractional seconds. It's a maximum of 7 (which would be
hnsecs), but only has as many as are necessary to hold the correct value
(so no trailing zeroes), and if there are no fractional seconds, then
there is no decimal point.
If this $(D SysTime)'s time zone is $(D LocalTime), then TZ is empty. If
its time zone is $(D UTC), then it is "Z". Otherwise, it is the offset
from UTC (e.g. +1:00 or -7:00). Note that the offset from UTC is
$(I not) enough to uniquely identify the time zone.
Time zone offsets will be in the form +HH:MM or -HH:MM.
Examples:
--------------------
assert(SysTime(DateTime(2010, 7, 4, 7, 6, 12)).toSimpleString() ==
"2010-Jul-04 07:06:12");
assert(SysTime(DateTime(1998, 12, 25, 2, 15, 0),
FracSec.from!"msecs"(24)).toSimpleString() ==
"1998-Dec-25 02:15:00.024");
assert(SysTime(DateTime(0, 1, 5, 23, 9, 59)).toSimpleString() ==
"0000-Jan-05 23:09:59");
assert(SysTime(DateTime(-4, 1, 5, 0, 0, 2),
FracSec.from!"hnsecs"(520_920)).toSimpleString() ==
"-0004-Jan-05 00:00:02.052092");
--------------------
+/
string toSimpleString() const nothrow
{
try
{
immutable adjustedTime = adjTime;
long hnsecs = adjustedTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if(hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
auto hour = splitUnitsFromHNSecs!"hours"(hnsecs);
auto minute = splitUnitsFromHNSecs!"minutes"(hnsecs);
auto second = splitUnitsFromHNSecs!"seconds"(hnsecs);
auto dateTime = DateTime(Date(cast(int)days), TimeOfDay(cast(int)hour, cast(int)minute, cast(int)second));
auto fracSecStr = fracSecToISOString(cast(int)hnsecs);
if(_timezone.get is LocalTime())
return dateTime.toSimpleString() ~ fracSecToISOString(cast(int)hnsecs);
if(_timezone.get is UTC())
return dateTime.toSimpleString() ~ fracSecToISOString(cast(int)hnsecs) ~ "Z";
immutable utcOffset = cast(int)convert!("hnsecs", "minutes")(adjustedTime - stdTime);
return dateTime.toSimpleString() ~ fracSecToISOString(cast(int)hnsecs) ~ SimpleTimeZone.toISOString(utcOffset);
}
catch(Exception e)
assert(0, "format() threw.");
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(SysTime(DateTime.init, UTC()).toString(), "0001-Jan-01 00:00:00Z");
_assertPred!"=="(SysTime(DateTime(1, 1, 1, 0, 0, 0), FracSec.from!"hnsecs"(1), UTC()).toString(), "0001-Jan-01 00:00:00.0000001Z");
_assertPred!"=="(SysTime(DateTime(9, 12, 4, 0, 0, 0)).toSimpleString(), "0009-Dec-04 00:00:00");
_assertPred!"=="(SysTime(DateTime(99, 12, 4, 5, 6, 12)).toSimpleString(), "0099-Dec-04 05:06:12");
_assertPred!"=="(SysTime(DateTime(999, 12, 4, 13, 44, 59)).toSimpleString(), "0999-Dec-04 13:44:59");
_assertPred!"=="(SysTime(DateTime(9999, 7, 4, 23, 59, 59)).toSimpleString(), "9999-Jul-04 23:59:59");
_assertPred!"=="(SysTime(DateTime(10000, 10, 20, 1, 1, 1)).toSimpleString(), "+10000-Oct-20 01:01:01");
_assertPred!"=="(SysTime(DateTime(9, 12, 4, 0, 0, 0), FracSec.from!"msecs"(42)).toSimpleString(), "0009-Dec-04 00:00:00.042");
_assertPred!"=="(SysTime(DateTime(99, 12, 4, 5, 6, 12), FracSec.from!"msecs"(100)).toSimpleString(), "0099-Dec-04 05:06:12.1");
_assertPred!"=="(SysTime(DateTime(999, 12, 4, 13, 44, 59), FracSec.from!"usecs"(45020)).toSimpleString(), "0999-Dec-04 13:44:59.04502");
_assertPred!"=="(SysTime(DateTime(9999, 7, 4, 23, 59, 59), FracSec.from!"hnsecs"(12)).toSimpleString(), "9999-Jul-04 23:59:59.0000012");
_assertPred!"=="(SysTime(DateTime(10000, 10, 20, 1, 1, 1), FracSec.from!"hnsecs"(507890)).toSimpleString(), "+10000-Oct-20 01:01:01.050789");
_assertPred!"=="(SysTime(DateTime(2012, 12, 21, 12, 12, 12),
new SimpleTimeZone(-360)).toSimpleString(),
"2012-Dec-21 12:12:12-06:00");
_assertPred!"=="(SysTime(DateTime(2012, 12, 21, 12, 12, 12),
new SimpleTimeZone(420)).toSimpleString(),
"2012-Dec-21 12:12:12+07:00");
//Test B.C.
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(9_999_999), UTC()).toSimpleString(), "0000-Dec-31 23:59:59.9999999Z");
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), FracSec.from!"hnsecs"(1), UTC()).toSimpleString(), "0000-Dec-31 23:59:59.0000001Z");
_assertPred!"=="(SysTime(DateTime(0, 12, 31, 23, 59, 59), UTC()).toSimpleString(), "0000-Dec-31 23:59:59Z");
_assertPred!"=="(SysTime(DateTime(0, 12, 4, 0, 12, 4)).toSimpleString(), "0000-Dec-04 00:12:04");
_assertPred!"=="(SysTime(DateTime(-9, 12, 4, 0, 0, 0)).toSimpleString(), "-0009-Dec-04 00:00:00");
_assertPred!"=="(SysTime(DateTime(-99, 12, 4, 5, 6, 12)).toSimpleString(), "-0099-Dec-04 05:06:12");
_assertPred!"=="(SysTime(DateTime(-999, 12, 4, 13, 44, 59)).toSimpleString(), "-0999-Dec-04 13:44:59");
_assertPred!"=="(SysTime(DateTime(-9999, 7, 4, 23, 59, 59)).toSimpleString(), "-9999-Jul-04 23:59:59");
_assertPred!"=="(SysTime(DateTime(-10000, 10, 20, 1, 1, 1)).toSimpleString(), "-10000-Oct-20 01:01:01");
_assertPred!"=="(SysTime(DateTime(0, 12, 4, 0, 0, 0), FracSec.from!"msecs"(7)).toSimpleString(), "0000-Dec-04 00:00:00.007");
_assertPred!"=="(SysTime(DateTime(-9, 12, 4, 0, 0, 0), FracSec.from!"msecs"(42)).toSimpleString(), "-0009-Dec-04 00:00:00.042");
_assertPred!"=="(SysTime(DateTime(-99, 12, 4, 5, 6, 12), FracSec.from!"msecs"(100)).toSimpleString(), "-0099-Dec-04 05:06:12.1");
_assertPred!"=="(SysTime(DateTime(-999, 12, 4, 13, 44, 59), FracSec.from!"usecs"(45020)).toSimpleString(), "-0999-Dec-04 13:44:59.04502");
_assertPred!"=="(SysTime(DateTime(-9999, 7, 4, 23, 59, 59), FracSec.from!"hnsecs"(12)).toSimpleString(), "-9999-Jul-04 23:59:59.0000012");
_assertPred!"=="(SysTime(DateTime(-10000, 10, 20, 1, 1, 1), FracSec.from!"hnsecs"(507890)).toSimpleString(), "-10000-Oct-20 01:01:01.050789");
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, cast(TimeOfDay)cst));
//static assert(__traits(compiles, cast(TimeOfDay)ist));
//Verify Examples.
assert(SysTime(DateTime(2010, 7, 4, 7, 6, 12)).toSimpleString() ==
"2010-Jul-04 07:06:12");
assert(SysTime(DateTime(1998, 12, 25, 2, 15, 0),
FracSec.from!"msecs"(24)).toSimpleString() ==
"1998-Dec-25 02:15:00.024");
assert(SysTime(DateTime(0, 1, 5, 23, 9, 59)).toSimpleString() ==
"0000-Jan-05 23:09:59");
assert(SysTime(DateTime(-4, 1, 5, 0, 0, 2),
FracSec.from!"hnsecs"(520_920)).toSimpleString() ==
"-0004-Jan-05 00:00:02.052092");
}
}
/+
Converts this $(D SysTime) to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString()
{
return toSimpleString();
}
/++
Converts this $(D SysTime) to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString() const nothrow
{
return toSimpleString();
}
unittest
{
version(testStdDateTime)
{
auto st = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
//immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
static assert(__traits(compiles, st.toString()));
static assert(__traits(compiles, cst.toString()));
//static assert(__traits(compiles, ist.toString()));
}
}
/++
Creates a $(D SysTime) from a string with the format
YYYYMMDDTHHMMSS.FFFFFFFTZ (where F is fractional seconds is the time
zone). Whitespace is stripped from the given string.
The exact format is exactly as described in $(D toISOString) except that
trailing zeroes are permitted - including having fractional seconds with
all zeroes. However, a decimal point with nothing following it is
invalid.
If there is no time zone in the string, then $(D LocalTime) is used. If
the time zone is "Z", then $(D UTC) is used. Otherwise, a
$(D SimpleTimeZone) which corresponds to the given offset from UTC is
used. If you wish the returned $(D SysTime) to be a particular time
zone, then pass in that time zone and the $(D SysTime) to be returned
will be converted to that time zone (though it will still be read in as
whatever time zone is in its string).
The accepted formats for time zone offsets
are +H, -H, +HH, -HH, +H:MM, -H:MM, +HH:MM, and -HH:MM.
Params:
isoString = A string formatted in the ISO format for dates and times.
tz = The time zone to convert the given time to (no
conversion occurs if null).
Throws:
$(D DateTimeException) if the given string is not in the ISO format
or if the resulting $(D SysTime) would not be valid.
Examples:
--------------------
assert(SysTime.fromISOString("20100704T070612") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromISOString("19981225T021500.007") ==
SysTime(DateTime(1998, 12, 25, 2, 15, 0), FracSec.from!"msecs"(7)));
assert(SysTime.fromISOString("00000105T230959.00002") ==
SysTime(DateTime(0, 1, 5, 23, 9, 59), FracSec.from!"usecs"(20)));
assert(SysTime.fromISOString("-00040105T000002") ==
SysTime(DateTime(-4, 1, 5, 0, 0, 2)));
assert(SysTime.fromISOString(" 20100704T070612 ") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromISOString("20100704T070612Z") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12), UTC()));
assert(SysTime.fromISOString("20100704T070612-8:00") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(-480)));
assert(SysTime.fromISOString("20100704T070612+8:00") ==
SysTime(DateTime(2010, 7, 3, 7, 6, 12), new SimpleTimeZone(480)));
--------------------
+/
static SysTime fromISOString(S)(in S isoString, immutable TimeZone tz = null)
if(isSomeString!S)
{
auto dstr = to!dstring(strip(isoString));
immutable skipFirst = dstr.startsWith("+", "-") != 0;
auto found = (skipFirst ? dstr[1..$] : dstr).find(".", "Z", "+", "-");
auto dateTimeStr = dstr[0 .. $ - found[0].length];
dstring fracSecStr;
dstring zoneStr;
if(found[1] != 0)
{
if(found[1] == 1)
{
auto foundTZ = found[0].find("Z", "+", "-");
if(foundTZ[1] != 0)
{
fracSecStr = found[0][0 .. $ - foundTZ[0].length];
zoneStr = foundTZ[0];
}
else
fracSecStr = found[0];
}
else
zoneStr = found[0];
}
try
{
auto dateTime = DateTime.fromISOString(dateTimeStr);
auto fracSec = fracSecFromISOString(fracSecStr);
DTRebindable!(immutable TimeZone) parsedZone;
if(zoneStr.empty)
parsedZone = LocalTime();
else if(zoneStr == "Z")
parsedZone = UTC();
else
parsedZone = SimpleTimeZone.fromISOString(zoneStr);
auto retval = SysTime(dateTime, fracSec, parsedZone.get);
if(tz !is null)
retval.timezone = tz;
return retval;
}
catch(DateTimeException dte)
throw new DateTimeException(format("Invalid ISO String: %s", isoString));
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(SysTime.fromISOString(""));
assertThrown!DateTimeException(SysTime.fromISOString("20100704000000"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704 000000"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704t000000"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000."));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000.A"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000.Z"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000.00000000"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000.00000000"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000+"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000-"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000:"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000-:"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000+:"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000-1:"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000+1:"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000+1:0"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000-24.00"));
assertThrown!DateTimeException(SysTime.fromISOString("20100704T000000+24.00"));
assertThrown!DateTimeException(SysTime.fromISOString("2010-07-0400:00:00"));
assertThrown!DateTimeException(SysTime.fromISOString("2010-07-04 00:00:00"));
assertThrown!DateTimeException(SysTime.fromISOString("2010-07-04t00:00:00"));
assertThrown!DateTimeException(SysTime.fromISOString("2010-07-04T00:00:00."));
assertThrown!DateTimeException(SysTime.fromISOString("2010-Jul-0400:00:00"));
assertThrown!DateTimeException(SysTime.fromISOString("2010-Jul-04 00:00:00"));
assertThrown!DateTimeException(SysTime.fromISOString("2010-Jul-04t00:00:00"));
assertThrown!DateTimeException(SysTime.fromISOString("2010-Jul-04T00:00:00"));
assertThrown!DateTimeException(SysTime.fromISOString("2010-Jul-04 00:00:00."));
assertThrown!DateTimeException(SysTime.fromISOString("2010-12-22T172201"));
assertThrown!DateTimeException(SysTime.fromISOString("2010-Dec-22 17:22:01"));
_assertPred!"=="(SysTime.fromISOString("20101222T172201"), SysTime(DateTime(2010, 12, 22, 17, 22, 01)));
_assertPred!"=="(SysTime.fromISOString("19990706T123033"), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOString("-19990706T123033"), SysTime(DateTime(-1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOString("+019990706T123033"), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOString("19990706T123033 "), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOString(" 19990706T123033"), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOString(" 19990706T123033 "), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOString("19070707T121212.0"), SysTime(DateTime(1907, 07, 07, 12, 12, 12)));
_assertPred!"=="(SysTime.fromISOString("19070707T121212.0000000"), SysTime(DateTime(1907, 07, 07, 12, 12, 12)));
_assertPred!"=="(SysTime.fromISOString("19070707T121212.0000001"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"hnsecs"(1)));
_assertPred!"=="(SysTime.fromISOString("19070707T121212.000001"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"usecs"(1)));
_assertPred!"=="(SysTime.fromISOString("19070707T121212.0000010"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"usecs"(1)));
_assertPred!"=="(SysTime.fromISOString("19070707T121212.001"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"msecs"(1)));
_assertPred!"=="(SysTime.fromISOString("19070707T121212.0010000"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"msecs"(1)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201Z"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), UTC()));
_assertPred!"=="(SysTime.fromISOString("20101222T172201-1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201-1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201-1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-90)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201-8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-480)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201+1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201+1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201+1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(90)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201+8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(480)));
_assertPred!"=="(SysTime.fromISOString("20101103T065106.57159Z"), SysTime(DateTime(2010, 11, 3, 6, 51, 6), FracSec.from!"hnsecs"(5715900), UTC()));
_assertPred!"=="(SysTime.fromISOString("20101222T172201.23412Z"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(2_341_200), UTC()));
_assertPred!"=="(SysTime.fromISOString("20101222T172201.23112-1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(2_311_200), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201.45-1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(4_500_000), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201.1-1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(1_000_000), new SimpleTimeZone(-90)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201.55-8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(5_500_000), new SimpleTimeZone(-480)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201.1234567+1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(1_234_567), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201.0+1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(0), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201.0000000+1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(0), new SimpleTimeZone(90)));
_assertPred!"=="(SysTime.fromISOString("20101222T172201.45+8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(4_500_000), new SimpleTimeZone(480)));
//Verify Examples.
assert(SysTime.fromISOString("20100704T070612") == SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromISOString("19981225T021500.007") == SysTime(DateTime(1998, 12, 25, 2, 15, 0), FracSec.from!"msecs"(7)));
assert(SysTime.fromISOString("00000105T230959.00002") == SysTime(DateTime(0, 1, 5, 23, 9, 59), FracSec.from!"usecs"(20)));
assert(SysTime.fromISOString("-00040105T000002") == SysTime(DateTime(-4, 1, 5, 0, 0, 2)));
assert(SysTime.fromISOString(" 20100704T070612 ") == SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromISOString("20100704T070612Z") == SysTime(DateTime(2010, 7, 4, 7, 6, 12), UTC()));
assert(SysTime.fromISOString("20100704T070612-8:00") == SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(-480)));
assert(SysTime.fromISOString("20100704T070612+8:00") == SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(480)));
}
}
/++
Creates a $(D SysTime) from a string with the format
YYYY-MM-DDTHH:MM:SS.FFFFFFFTZ (where F is fractional seconds is the
time zone). Whitespace is stripped from the given string.
The exact format is exactly as described in $(D toISOExtString)
except that trailing zeroes are permitted - including having fractional
seconds with all zeroes. However, a decimal point with nothing following
it is invalid.
If there is no time zone in the string, then $(D LocalTime) is used. If
the time zone is "Z", then $(D UTC) is used. Otherwise, a
$(D SimpleTimeZone) which corresponds to the given offset from UTC is
used. If you wish the returned $(D SysTime) to be a particular time
zone, then pass in that time zone and the $(D SysTime) to be returned
will be converted to that time zone (though it will still be read in as
whatever time zone is in its string).
The accepted formats for time zone offsets
are +H, -H, +HH, -HH, +H:MM, -H:MM, +HH:MM, and -HH:MM.
Params:
isoString = A string formatted in the ISO Extended format for dates
and times.
tz = The time zone to convert the given time to (no
conversion occurs if null).
Throws:
$(D DateTimeException) if the given string is not in the ISO format
or if the resulting $(D SysTime) would not be valid.
Examples:
--------------------
assert(SysTime.fromISOExtString("2010-07-04T07:06:12") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromISOExtString("1998-12-25T02:15:00.007") ==
SysTime(DateTime(1998, 12, 25, 2, 15, 0), FracSec.from!"msecs"(7)));
assert(SysTime.fromISOExtString("0000-01-05T23:09:59.00002") ==
SysTime(DateTime(0, 1, 5, 23, 9, 59), FracSec.from!"usecs"(20)));
assert(SysTime.fromISOExtString("-0004-01-05T00:00:02") ==
SysTime(DateTime(-4, 1, 5, 0, 0, 2)));
assert(SysTime.fromISOExtString(" 2010-07-04T07:06:12 ") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromISOExtString("2010-07-04T07:06:12Z") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12), UTC()));
assert(SysTime.fromISOExtString("2010-07-04T07:06:12-8:00") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(-480)));
assert(SysTime.fromISOExtString("2010-07-04T07:06:12+8:00") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(480)));
--------------------
+/
static SysTime fromISOExtString(S)(in S isoExtString, immutable TimeZone tz = null)
if(isSomeString!(S))
{
auto dstr = to!dstring(strip(isoExtString));
auto tIndex = dstr.stds_indexOf("T");
enforce(tIndex != -1, new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
auto found = dstr[tIndex + 1 .. $].find(".", "Z", "+", "-");
auto dateTimeStr = dstr[0 .. $ - found[0].length];
dstring fracSecStr;
dstring zoneStr;
if(found[1] != 0)
{
if(found[1] == 1)
{
auto foundTZ = found[0].find("Z", "+", "-");
if(foundTZ[1] != 0)
{
fracSecStr = found[0][0 .. $ - foundTZ[0].length];
zoneStr = foundTZ[0];
}
else
fracSecStr = found[0];
}
else
zoneStr = found[0];
}
try
{
auto dateTime = DateTime.fromISOExtString(dateTimeStr);
auto fracSec = fracSecFromISOString(fracSecStr);
DTRebindable!(immutable TimeZone) parsedZone;
if(zoneStr.empty)
parsedZone = LocalTime();
else if(zoneStr == "Z")
parsedZone = UTC();
else
parsedZone = SimpleTimeZone.fromISOString(zoneStr);
auto retval = SysTime(dateTime, fracSec, parsedZone.get);
if(tz !is null)
retval.timezone = tz;
return retval;
}
catch(DateTimeException dte)
throw new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString));
}
/++
$(RED Scheduled for deprecation in November 2011.
Please use fromISOExtString instead.)
+/
static SysTime fromISOExtendedString(S)(in S isoExtString, immutable TimeZone tz = null)
if(isSomeString!(S))
{
pragma(msg, softDeprec!("2.053", "November 2011", "fromISOExtendedString", "fromISOExtString"));
return fromISOExtString!string(isoExtString, tz);
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(SysTime.fromISOExtString(""));
assertThrown!DateTimeException(SysTime.fromISOExtString("20100704000000"));
assertThrown!DateTimeException(SysTime.fromISOExtString("20100704 000000"));
assertThrown!DateTimeException(SysTime.fromISOExtString("20100704t000000"));
assertThrown!DateTimeException(SysTime.fromISOExtString("20100704T000000."));
assertThrown!DateTimeException(SysTime.fromISOExtString("20100704T000000.0"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07:0400:00:00"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04 00:00:00"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04 00:00:00"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04t00:00:00"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00."));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00.A"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00.Z"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00.00000000"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00.00000000"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00+"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00-"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00:"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00-:"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00+:"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00-1:"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00+1:"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00+1:0"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00-24.00"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-07-04T00:00:00+24.00"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-Jul-0400:00:00"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-Jul-04t00:00:00"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-Jul-04 00:00:00."));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-Jul-04 00:00:00.0"));
assertThrown!DateTimeException(SysTime.fromISOExtString("20101222T172201"));
assertThrown!DateTimeException(SysTime.fromISOExtString("2010-Dec-22 17:22:01"));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01"), SysTime(DateTime(2010, 12, 22, 17, 22, 01)));
_assertPred!"=="(SysTime.fromISOExtString("1999-07-06T12:30:33"), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOExtString("-1999-07-06T12:30:33"), SysTime(DateTime(-1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOExtString("+01999-07-06T12:30:33"), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOExtString("1999-07-06T12:30:33 "), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOExtString(" 1999-07-06T12:30:33"), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOExtString(" 1999-07-06T12:30:33 "), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromISOExtString("1907-07-07T12:12:12.0"), SysTime(DateTime(1907, 07, 07, 12, 12, 12)));
_assertPred!"=="(SysTime.fromISOExtString("1907-07-07T12:12:12.0000000"), SysTime(DateTime(1907, 07, 07, 12, 12, 12)));
_assertPred!"=="(SysTime.fromISOExtString("1907-07-07T12:12:12.0000001"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"hnsecs"(1)));
_assertPred!"=="(SysTime.fromISOExtString("1907-07-07T12:12:12.000001"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"usecs"(1)));
_assertPred!"=="(SysTime.fromISOExtString("1907-07-07T12:12:12.0000010"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"usecs"(1)));
_assertPred!"=="(SysTime.fromISOExtString("1907-07-07T12:12:12.001"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"msecs"(1)));
_assertPred!"=="(SysTime.fromISOExtString("1907-07-07T12:12:12.0010000"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"msecs"(1)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01Z"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), UTC()));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01-1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01-1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01-1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-90)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01-8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-480)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01+1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01+1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01+1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(90)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01+8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(480)));
_assertPred!"=="(SysTime.fromISOExtString("2010-11-03T06:51:06.57159Z"), SysTime(DateTime(2010, 11, 3, 6, 51, 6), FracSec.from!"hnsecs"(5715900), UTC()));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01.23412Z"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(2_341_200), UTC()));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01.23112-1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(2_311_200), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01.45-1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(4_500_000), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01.1-1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(1_000_000), new SimpleTimeZone(-90)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01.55-8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(5_500_000), new SimpleTimeZone(-480)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01.1234567+1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(1_234_567), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01.0+1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(0), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01.0000000+1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(0), new SimpleTimeZone(90)));
_assertPred!"=="(SysTime.fromISOExtString("2010-12-22T17:22:01.45+8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(4_500_000), new SimpleTimeZone(480)));
//Verify Examples.
assert(SysTime.fromISOExtString("2010-07-04T07:06:12") == SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromISOExtString("1998-12-25T02:15:00.007") == SysTime(DateTime(1998, 12, 25, 2, 15, 0), FracSec.from!"msecs"(7)));
assert(SysTime.fromISOExtString("0000-01-05T23:09:59.00002") == SysTime(DateTime(0, 1, 5, 23, 9, 59), FracSec.from!"usecs"(20)));
assert(SysTime.fromISOExtString("-0004-01-05T00:00:02") == SysTime(DateTime(-4, 1, 5, 0, 0, 2)));
assert(SysTime.fromISOExtString(" 2010-07-04T07:06:12 ") == SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromISOExtString("2010-07-04T07:06:12Z") == SysTime(DateTime(2010, 7, 4, 7, 6, 12), UTC()));
assert(SysTime.fromISOExtString("2010-07-04T07:06:12-8:00") == SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(-480)));
assert(SysTime.fromISOExtString("2010-07-04T07:06:12+8:00") == SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(480)));
}
}
/++
Creates a $(D SysTime) from a string with the format
YYYY-MM-DD HH:MM:SS.FFFFFFFTZ (where F is fractional seconds is the
time zone). Whitespace is stripped from the given string.
The exact format is exactly as described in $(D toSimpleString) except
that trailing zeroes are permitted - including having fractional seconds
with all zeroes. However, a decimal point with nothing following it is
invalid.
If there is no time zone in the string, then $(D LocalTime) is used. If
the time zone is "Z", then $(D UTC) is used. Otherwise, a
$(D SimpleTimeZone) which corresponds to the given offset from UTC is
used. If you wish the returned $(D SysTime) to be a particular time
zone, then pass in that time zone and the $(D SysTime) to be returned
will be converted to that time zone (though it will still be read in as
whatever time zone is in its string).
The accepted formats for time zone offsets
are +H, -H, +HH, -HH, +H:MM, -H:MM, +HH:MM, and -HH:MM.
Params:
simpleString = A string formatted in the way that
$(D toSimpleString) formats dates and times.
tz = The time zone to convert the given time to (no
conversion occurs if null).
Throws:
$(D DateTimeException) if the given string is not in the ISO format
or if the resulting $(D SysTime) would not be valid.
Examples:
--------------------
assert(SysTime.fromSimpleString("2010-Jul-04 07:06:12") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromSimpleString("1998-Dec-25 02:15:00.007") ==
SysTime(DateTime(1998, 12, 25, 2, 15, 0), FracSec.from!"msecs"(7)));
assert(SysTime.fromSimpleString("0000-Jan-05 23:09:59.00002") ==
SysTime(DateTime(0, 1, 5, 23, 9, 59), FracSec.from!"usecs"(20)));
assert(SysTime.fromSimpleString("-0004-Jan-05 00:00:02") ==
SysTime(DateTime(-4, 1, 5, 0, 0, 2)));
assert(SysTime.fromSimpleString(" 2010-Jul-04 07:06:12 ") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromSimpleString("2010-Jul-04 07:06:12Z") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12), UTC()));
assert(SysTime.fromSimpleString("2010-Jul-04 07:06:12-8:00") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(-480)));
assert(SysTime.fromSimpleString("2010-Jul-04 07:06:12+8:00") ==
SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(480)));
--------------------
+/
static SysTime fromSimpleString(S)(in S simpleString, immutable TimeZone tz = null)
if(isSomeString!(S))
{
auto dstr = to!dstring(strip(simpleString));
auto spaceIndex = dstr.stds_indexOf(" ");
enforce(spaceIndex != -1, new DateTimeException(format("Invalid Simple String: %s", simpleString)));
auto found = dstr[spaceIndex + 1 .. $].find(".", "Z", "+", "-");
auto dateTimeStr = dstr[0 .. $ - found[0].length];
dstring fracSecStr;
dstring zoneStr;
if(found[1] != 0)
{
if(found[1] == 1)
{
auto foundTZ = found[0].find("Z", "+", "-");
if(foundTZ[1] != 0)
{
fracSecStr = found[0][0 .. $ - foundTZ[0].length];
zoneStr = foundTZ[0];
}
else
fracSecStr = found[0];
}
else
zoneStr = found[0];
}
try
{
auto dateTime = DateTime.fromSimpleString(dateTimeStr);
auto fracSec = fracSecFromISOString(fracSecStr);
DTRebindable!(immutable TimeZone) parsedZone;
if(zoneStr.empty)
parsedZone = LocalTime();
else if(zoneStr == "Z")
parsedZone = UTC();
else
parsedZone = SimpleTimeZone.fromISOString(zoneStr);
auto retval = SysTime(dateTime, fracSec, parsedZone.get);
if(tz !is null)
retval.timezone = tz;
return retval;
}
catch(DateTimeException dte)
throw new DateTimeException(format("Invalid Simple String: %s", simpleString));
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(SysTime.fromSimpleString(""));
assertThrown!DateTimeException(SysTime.fromSimpleString("20100704000000"));
assertThrown!DateTimeException(SysTime.fromSimpleString("20100704 000000"));
assertThrown!DateTimeException(SysTime.fromSimpleString("20100704t000000"));
assertThrown!DateTimeException(SysTime.fromSimpleString("20100704T000000."));
assertThrown!DateTimeException(SysTime.fromSimpleString("20100704T000000.0"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-07-0400:00:00"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-07-04 00:00:00"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-07-04t00:00:00"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-07-04T00:00:00."));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-07-04T00:00:00.0"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-0400:00:00"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04t00:00:00"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04T00:00:00"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00."));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00.A"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00.Z"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00.00000000"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00.00000000"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00+"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00-"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00:"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00-:"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00+:"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00-1:"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00+1:"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00+1:0"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00-24.00"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-Jul-04 00:00:00+24.00"));
assertThrown!DateTimeException(SysTime.fromSimpleString("20101222T172201"));
assertThrown!DateTimeException(SysTime.fromSimpleString("2010-12-22T172201"));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01"), SysTime(DateTime(2010, 12, 22, 17, 22, 01)));
_assertPred!"=="(SysTime.fromSimpleString("1999-Jul-06 12:30:33"), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromSimpleString("-1999-Jul-06 12:30:33"), SysTime(DateTime(-1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromSimpleString("+01999-Jul-06 12:30:33"), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromSimpleString("1999-Jul-06 12:30:33 "), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromSimpleString(" 1999-Jul-06 12:30:33"), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromSimpleString(" 1999-Jul-06 12:30:33 "), SysTime(DateTime(1999, 7, 6, 12, 30, 33)));
_assertPred!"=="(SysTime.fromSimpleString("1907-Jul-07 12:12:12.0"), SysTime(DateTime(1907, 07, 07, 12, 12, 12)));
_assertPred!"=="(SysTime.fromSimpleString("1907-Jul-07 12:12:12.0000000"), SysTime(DateTime(1907, 07, 07, 12, 12, 12)));
_assertPred!"=="(SysTime.fromSimpleString("1907-Jul-07 12:12:12.0000001"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"hnsecs"(1)));
_assertPred!"=="(SysTime.fromSimpleString("1907-Jul-07 12:12:12.000001"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"usecs"(1)));
_assertPred!"=="(SysTime.fromSimpleString("1907-Jul-07 12:12:12.0000010"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"usecs"(1)));
_assertPred!"=="(SysTime.fromSimpleString("1907-Jul-07 12:12:12.001"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"msecs"(1)));
_assertPred!"=="(SysTime.fromSimpleString("1907-Jul-07 12:12:12.0010000"), SysTime(DateTime(1907, 07, 07, 12, 12, 12), FracSec.from!"msecs"(1)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01Z"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), UTC()));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01-1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01-1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01-1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-90)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01-8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(-480)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01+1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01+1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01+1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(90)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01+8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), new SimpleTimeZone(480)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Nov-03 06:51:06.57159Z"), SysTime(DateTime(2010, 11, 3, 6, 51, 6), FracSec.from!"hnsecs"(5715900), UTC()));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01.23412Z"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(2_341_200), UTC()));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01.23112-1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(2_311_200), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01.45-1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(4_500_000), new SimpleTimeZone(-60)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01.1-1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(1_000_000), new SimpleTimeZone(-90)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01.55-8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(5_500_000), new SimpleTimeZone(-480)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01.1234567+1:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(1_234_567), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01.0+1"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(0), new SimpleTimeZone(60)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01.0000000+1:30"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(0), new SimpleTimeZone(90)));
_assertPred!"=="(SysTime.fromSimpleString("2010-Dec-22 17:22:01.45+8:00"), SysTime(DateTime(2010, 12, 22, 17, 22, 01), FracSec.from!"hnsecs"(4_500_000), new SimpleTimeZone(480)));
//Verify Examples.
assert(SysTime.fromSimpleString("2010-Jul-04 07:06:12") == SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromSimpleString("1998-Dec-25 02:15:00.007") == SysTime(DateTime(1998, 12, 25, 2, 15, 0), FracSec.from!"msecs"(7)));
assert(SysTime.fromSimpleString("0000-Jan-05 23:09:59.00002") == SysTime(DateTime(0, 1, 5, 23, 9, 59), FracSec.from!"usecs"(20)));
assert(SysTime.fromSimpleString("-0004-Jan-05 00:00:02") == SysTime(DateTime(-4, 1, 5, 0, 0, 2)));
assert(SysTime.fromSimpleString(" 2010-Jul-04 07:06:12 ") == SysTime(DateTime(2010, 7, 4, 7, 6, 12)));
assert(SysTime.fromSimpleString("2010-Jul-04 07:06:12Z") == SysTime(DateTime(2010, 7, 4, 7, 6, 12), UTC()));
assert(SysTime.fromSimpleString("2010-Jul-04 07:06:12-8:00") == SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(-480)));
assert(SysTime.fromSimpleString("2010-Jul-04 07:06:12+8:00") == SysTime(DateTime(2010, 7, 4, 7, 6, 12), new SimpleTimeZone(480)));
}
}
//TODO Add function which takes a user-specified time format and produces a SysTime
//TODO Add function which takes pretty much any time-string and produces a SysTime.
// Obviously, it will be less efficient, and it probably won't manage _every_
// possible date format, but a smart conversion function would be nice.
/++
Returns the $(D SysTime) farthest in the past which is representable
by $(D SysTime).
The $(D SysTime) which is returned is in UTC.
+/
@property static SysTime min() pure nothrow
{
return SysTime(long.min, UTC());
}
unittest
{
version(testStdDateTime)
{
assert(SysTime.min.year < 0);
assert(SysTime.min < SysTime.max);
}
}
/++
Returns the $(D SysTime) farthest in the future which is representable
by $(D SysTime).
The $(D SysTime) which is returned is in UTC.
+/
@property static SysTime max() pure nothrow
{
return SysTime(long.max, UTC());
}
unittest
{
version(testStdDateTime)
{
assert(SysTime.max.year > 0);
assert(SysTime.max > SysTime.min);
}
}
private:
/+
Returns $(D stdTime) converted to $(D SysTime)'s time zone.
+/
@property long adjTime() const nothrow
{
return _timezone.utcToTZ(_stdTime);
}
/+
Converts the given hnsecs from $(D SysTime)'s time zone to std time.
+/
@property void adjTime(long adjTime) nothrow
{
_stdTime = _timezone.tzToUTC(adjTime);
}
//Commented out due to bug http://d.puremagic.com/issues/show_bug.cgi?id=5058
/+
invariant()
{
assert(_timezone.get !is null, "Invariant Failure: timezone is null. Were you foolish enough to use SysTime.init? (since timezone for SysTime.init can't be set at compile time).");
}
+/
long _stdTime;
DTRebindable!(immutable TimeZone) _timezone;
}
/++
Represents a date in the Proleptic Gregorian Calendar ranging from
32,768 B.C. to 32,767 A.D. Positive years are A.D. Non-positive years are
B.C.
Year, month, and day are kept separately internally so that $(D Date) is
optimized for calendar-based operations.
$(D Date) uses the Proleptic Gregorian Calendar, so it assumes the Gregorian
leap year calculations for its entire length. And, as per
$(WEB en.wikipedia.org/wiki/ISO_8601, ISO 8601), it also treats 1 B.C. as
year 0. So, 1 B.C. is 0, 2 B.C. is -1, etc. Use $(D yearBC) if want B.C. as
a positive integer with 1 B.C. being the year prior to 1 A.D.
Year 0 is a leap year.
+/
struct Date
{
public:
/++
Throws:
$(D DateTimeException) if the resulting $(D Date) would not be valid.
Params:
year = Year of the Gregorian Calendar. Positive values are A.D.
Non-positive values are B.C. with year 0 being the year
prior to 1 A.D.
month = Month of the year.
day = Day of the month.
+/
this(int year, int month, int day) pure
{
enforceValid!"months"(cast(Month)month);
enforceValid!"days"(year, cast(Month)month, day);
_year = cast(short)year;
_month = cast(Month)month;
_day = cast(ubyte)day;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(Date(1, 1, 1), Date.init);
static void testDate(in Date date, int year, int month, int day, size_t line = __LINE__)
{
_assertPred!"=="(date._year, year, "", __FILE__, line);
_assertPred!"=="(date._month, month, "", __FILE__, line);
_assertPred!"=="(date._day, day, "", __FILE__, line);
}
testDate(Date(1999, 1 , 1), 1999, Month.jan, 1);
testDate(Date(1999, 7 , 1), 1999, Month.jul, 1);
testDate(Date(1999, 7 , 6), 1999, Month.jul, 6);
//Test A.D.
assertThrown!DateTimeException(Date(1, 0, 1));
assertThrown!DateTimeException(Date(1, 1, 0));
assertThrown!DateTimeException(Date(1999, 13, 1));
assertThrown!DateTimeException(Date(1999, 1, 32));
assertThrown!DateTimeException(Date(1999, 2, 29));
assertThrown!DateTimeException(Date(2000, 2, 30));
assertThrown!DateTimeException(Date(1999, 3, 32));
assertThrown!DateTimeException(Date(1999, 4, 31));
assertThrown!DateTimeException(Date(1999, 5, 32));
assertThrown!DateTimeException(Date(1999, 6, 31));
assertThrown!DateTimeException(Date(1999, 7, 32));
assertThrown!DateTimeException(Date(1999, 8, 32));
assertThrown!DateTimeException(Date(1999, 9, 31));
assertThrown!DateTimeException(Date(1999, 10, 32));
assertThrown!DateTimeException(Date(1999, 11, 31));
assertThrown!DateTimeException(Date(1999, 12, 32));
assertNotThrown!DateTimeException(Date(1999, 1, 31));
assertNotThrown!DateTimeException(Date(1999, 2, 28));
assertNotThrown!DateTimeException(Date(2000, 2, 29));
assertNotThrown!DateTimeException(Date(1999, 3, 31));
assertNotThrown!DateTimeException(Date(1999, 4, 30));
assertNotThrown!DateTimeException(Date(1999, 5, 31));
assertNotThrown!DateTimeException(Date(1999, 6, 30));
assertNotThrown!DateTimeException(Date(1999, 7, 31));
assertNotThrown!DateTimeException(Date(1999, 8, 31));
assertNotThrown!DateTimeException(Date(1999, 9, 30));
assertNotThrown!DateTimeException(Date(1999, 10, 31));
assertNotThrown!DateTimeException(Date(1999, 11, 30));
assertNotThrown!DateTimeException(Date(1999, 12, 31));
//Test B.C.
assertNotThrown!DateTimeException(Date(0, 1, 1));
assertNotThrown!DateTimeException(Date(-1, 1, 1));
assertNotThrown!DateTimeException(Date(-1, 12, 31));
assertNotThrown!DateTimeException(Date(-1, 2, 28));
assertNotThrown!DateTimeException(Date(-4, 2, 29));
assertThrown!DateTimeException(Date(-1, 2, 29));
assertThrown!DateTimeException(Date(-2, 2, 29));
assertThrown!DateTimeException(Date(-3, 2, 29));
}
}
/++
Params:
day = The Xth day of the Gregorian Calendar that the constructed
$(D Date) will be for.
+/
this(int day) pure nothrow
{
if(day > 0)
{
int years = (day / daysIn400Years) * 400 + 1;
day %= daysIn400Years;
{
immutable tempYears = day / daysIn100Years;
if(tempYears == 4)
{
years += 300;
day -= daysIn100Years * 3;
}
else
{
years += tempYears * 100;
day %= daysIn100Years;
}
}
years += (day / daysIn4Years) * 4;
day %= daysIn4Years;
{
immutable tempYears = day / daysInYear;
if(tempYears == 4)
{
years += 3;
day -= daysInYear * 3;
}
else
{
years += tempYears;
day %= daysInYear;
}
}
if(day == 0)
{
_year = cast(short)(years - 1);
_month = Month.dec;
_day = 31;
}
else
{
_year = cast(short)years;
try
dayOfYear = day;
catch(Exception e)
assert(0, "dayOfYear assignment threw.");
}
}
else if(day <= 0 && -day < daysInLeapYear)
{
_year = 0;
try
dayOfYear = (daysInLeapYear + day);
catch(Exception e)
assert(0, "dayOfYear assignment threw.");
}
else
{
day += daysInLeapYear - 1;
int years = (day / daysIn400Years) * 400 - 1;
day %= daysIn400Years;
{
immutable tempYears = day / daysIn100Years;
if(tempYears == -4)
{
years -= 300;
day += daysIn100Years * 3;
}
else
{
years += tempYears * 100;
day %= daysIn100Years;
}
}
years += (day / daysIn4Years) * 4;
day %= daysIn4Years;
{
immutable tempYears = day / daysInYear;
if(tempYears == -4)
{
years -= 3;
day += daysInYear * 3;
}
else
{
years += tempYears;
day %= daysInYear;
}
}
if(day == 0)
{
_year = cast(short)(years + 1);
_month = Month.jan;
_day = 1;
}
else
{
_year = cast(short)years;
immutable newDoY = (yearIsLeapYear(_year) ? daysInLeapYear : daysInYear) + day + 1;
try
dayOfYear = newDoY;
catch(Exception e)
assert(0, "dayOfYear assignment threw.");
}
}
}
version(testStdDateTime) unittest
{
//Test A.D.
foreach(gd; chain(testGregDaysBC, testGregDaysAD))
_assertPred!"=="(Date(gd.day), gd.date);
}
/++
Compares this $(D Date) with the given $(D Date).
Returns:
$(BOOKTABLE,
$(TR $(TD this < rhs) $(TD < 0))
$(TR $(TD this == rhs) $(TD 0))
$(TR $(TD this > rhs) $(TD > 0))
)
+/
int opCmp(in Date rhs) const pure nothrow
{
if(_year < rhs._year)
return -1;
if(_year > rhs._year)
return 1;
if(_month < rhs._month)
return -1;
if(_month > rhs._month)
return 1;
if(_day < rhs._day)
return -1;
if(_day > rhs._day)
return 1;
return 0;
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!("opCmp", "==")(Date(1, 1, 1), Date.init);
_assertPred!("opCmp", "==")(Date(1999, 1, 1), Date(1999, 1, 1));
_assertPred!("opCmp", "==")(Date(1, 7, 1), Date(1, 7, 1));
_assertPred!("opCmp", "==")(Date(1, 1, 6), Date(1, 1, 6));
_assertPred!("opCmp", "==")(Date(1999, 7, 1), Date(1999, 7, 1));
_assertPred!("opCmp", "==")(Date(1999, 7, 6), Date(1999, 7, 6));
_assertPred!("opCmp", "==")(Date(1, 7, 6), Date(1, 7, 6));
_assertPred!("opCmp", "<")(Date(1999, 7, 6), Date(2000, 7, 6));
_assertPred!("opCmp", ">")(Date(2000, 7, 6), Date(1999, 7, 6));
_assertPred!("opCmp", "<")(Date(1999, 7, 6), Date(1999, 8, 6));
_assertPred!("opCmp", ">")(Date(1999, 8, 6), Date(1999, 7, 6));
_assertPred!("opCmp", "<")(Date(1999, 7, 6), Date(1999, 7, 7));
_assertPred!("opCmp", ">")(Date(1999, 7, 7), Date(1999, 7, 6));
_assertPred!("opCmp", "<")(Date(1999, 8, 7), Date(2000, 7, 6));
_assertPred!("opCmp", ">")(Date(2000, 8, 6), Date(1999, 7, 7));
_assertPred!("opCmp", "<")(Date(1999, 7, 7), Date(2000, 7, 6));
_assertPred!("opCmp", ">")(Date(2000, 7, 6), Date(1999, 7, 7));
_assertPred!("opCmp", "<")(Date(1999, 7, 7), Date(1999, 8, 6));
_assertPred!("opCmp", ">")(Date(1999, 8, 6), Date(1999, 7, 7));
//Test B.C.
_assertPred!("opCmp", "==")(Date(0, 1, 1), Date(0, 1, 1));
_assertPred!("opCmp", "==")(Date(-1, 1, 1), Date(-1, 1, 1));
_assertPred!("opCmp", "==")(Date(-1, 7, 1), Date(-1, 7, 1));
_assertPred!("opCmp", "==")(Date(-1, 1, 6), Date(-1, 1, 6));
_assertPred!("opCmp", "==")(Date(-1999, 7, 1), Date(-1999, 7, 1));
_assertPred!("opCmp", "==")(Date(-1999, 7, 6), Date(-1999, 7, 6));
_assertPred!("opCmp", "==")(Date(-1, 7, 6), Date(-1, 7, 6));
_assertPred!("opCmp", "<")(Date(-2000, 7, 6), Date(-1999, 7, 6));
_assertPred!("opCmp", ">")(Date(-1999, 7, 6), Date(-2000, 7, 6));
_assertPred!("opCmp", "<")(Date(-1999, 7, 6), Date(-1999, 8, 6));
_assertPred!("opCmp", ">")(Date(-1999, 8, 6), Date(-1999, 7, 6));
_assertPred!("opCmp", "<")(Date(-1999, 7, 6), Date(-1999, 7, 7));
_assertPred!("opCmp", ">")(Date(-1999, 7, 7), Date(-1999, 7, 6));
_assertPred!("opCmp", "<")(Date(-2000, 8, 6), Date(-1999, 7, 7));
_assertPred!("opCmp", ">")(Date(-1999, 8, 7), Date(-2000, 7, 6));
_assertPred!("opCmp", "<")(Date(-2000, 7, 6), Date(-1999, 7, 7));
_assertPred!("opCmp", ">")(Date(-1999, 7, 7), Date(-2000, 7, 6));
_assertPred!("opCmp", "<")(Date(-1999, 7, 7), Date(-1999, 8, 6));
_assertPred!("opCmp", ">")(Date(-1999, 8, 6), Date(-1999, 7, 7));
//Test Both
_assertPred!("opCmp", "<")(Date(-1999, 7, 6), Date(1999, 7, 6));
_assertPred!("opCmp", ">")(Date(1999, 7, 6), Date(-1999, 7, 6));
_assertPred!("opCmp", "<")(Date(-1999, 8, 6), Date(1999, 7, 6));
_assertPred!("opCmp", ">")(Date(1999, 7, 6), Date(-1999, 8, 6));
_assertPred!("opCmp", "<")(Date(-1999, 7, 7), Date(1999, 7, 6));
_assertPred!("opCmp", ">")(Date(1999, 7, 6), Date(-1999, 7, 7));
_assertPred!("opCmp", "<")(Date(-1999, 8, 7), Date(1999, 7, 6));
_assertPred!("opCmp", ">")(Date(1999, 7, 6), Date(-1999, 8, 7));
_assertPred!("opCmp", "<")(Date(-1999, 8, 6), Date(1999, 6, 6));
_assertPred!("opCmp", ">")(Date(1999, 6, 8), Date(-1999, 7, 6));
auto date = Date(1999, 7, 6);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, date.opCmp(date)));
static assert(__traits(compiles, date.opCmp(cdate)));
static assert(__traits(compiles, date.opCmp(idate)));
static assert(__traits(compiles, cdate.opCmp(date)));
static assert(__traits(compiles, cdate.opCmp(cdate)));
static assert(__traits(compiles, cdate.opCmp(idate)));
static assert(__traits(compiles, idate.opCmp(date)));
static assert(__traits(compiles, idate.opCmp(cdate)));
static assert(__traits(compiles, idate.opCmp(idate)));
}
}
/++
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive
are B.C.
Examples:
--------------------
assert(Date(1999, 7, 6).year == 1999);
assert(Date(2010, 10, 4).year == 2010);
assert(Date(-7, 4, 5).year == -7);
--------------------
+/
@property short year() const pure nothrow
{
return _year;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(Date.init.year, 1);
_assertPred!"=="(Date(1999, 7, 6).year, 1999);
_assertPred!"=="(Date(-1999, 7, 6).year, -1999);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.year == 1999));
static assert(__traits(compiles, idate.year == 1999));
//Verify Examples.
assert(Date(1999, 7, 6).year == 1999);
assert(Date(2010, 10, 4).year == 2010);
assert(Date(-7, 4, 5).year == -7);
}
}
/++
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive
are B.C.
Params:
year = The year to set this Date's year to.
Throws:
$(D DateTimeException) if the new year is not a leap year and the
resulting date would be on February 29th.
+/
@property void year(int year) pure
{
enforceValid!"days"(year, _month, _day);
_year = cast(short)year;
}
unittest
{
version(testStdDateTime)
{
static void testDateInvalid(Date date, int year)
{
date.year = year;
}
static void testDate(Date date, int year, in Date expected, size_t line = __LINE__)
{
date.year = year;
_assertPred!"=="(date, expected, "", __FILE__, line);
}
assertThrown!DateTimeException(testDateInvalid(Date(4, 2, 29), 1));
testDate(Date(1, 1, 1), 1999, Date(1999, 1, 1));
testDate(Date(1, 1, 1), 0, Date(0, 1, 1));
testDate(Date(1, 1, 1), -1999, Date(-1999, 1, 1));
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.year = 1999));
static assert(!__traits(compiles, idate.year = 1999));
//Verify Examples.
assert(Date(1999, 7, 6).year == 1999);
assert(Date(2010, 10, 4).year == 2010);
assert(Date(-7, 4, 5).year == -7);
}
}
/++
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C.
Throws:
$(D DateTimeException) if $(D isAD) is true.
Examples:
--------------------
assert(Date(0, 1, 1).yearBC == 1);
assert(Date(-1, 1, 1).yearBC == 2);
assert(Date(-100, 1, 1).yearBC == 101);
--------------------
+/
@property ushort yearBC() const pure
{
if(isAD)
throw new DateTimeException("Year " ~ numToString(_year) ~ " is A.D.");
//Once format is pure, this would be a better error message.
//throw new DateTimeException(format("%s is A.D.", this));
return cast(ushort)((_year * -1) + 1);
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException((in Date date){date.yearBC;}(Date(1, 1, 1)));
auto date = Date(0, 7, 6);
const cdate = Date(0, 7, 6);
immutable idate = Date(0, 7, 6);
static assert(__traits(compiles, date.yearBC));
static assert(__traits(compiles, cdate.yearBC));
static assert(__traits(compiles, idate.yearBC));
//Verify Examples.
assert(Date(0, 1, 1).yearBC == 1);
assert(Date(-1, 1, 1).yearBC == 2);
assert(Date(-100, 1, 1).yearBC == 101);
}
}
/++
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C.
Params:
year = The year B.C. to set this $(D Date)'s year to.
Throws:
$(D DateTimeException) if a non-positive value is given.
Examples:
--------------------
auto date = Date(2010, 1, 1);
date.yearBC = 1;
assert(date == Date(0, 1, 1));
date.yearBC = 10;
assert(date == Date(-9, 1, 1));
--------------------
+/
@property void yearBC(int year) pure
{
if(year <= 0)
throw new DateTimeException("The given year is not a year B.C.");
_year = cast(short)((year - 1) * -1);
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException((Date date){date.yearBC = -1;}(Date(1, 1, 1)));
{
auto date = Date(0, 7, 6);
const cdate = Date(0, 7, 6);
immutable idate = Date(0, 7, 6);
static assert(__traits(compiles, date.yearBC = 7));
static assert(!__traits(compiles, cdate.yearBC = 7));
static assert(!__traits(compiles, idate.yearBC = 7));
}
//Verify Examples.
{
auto date = Date(2010, 1, 1);
date.yearBC = 1;
assert(date == Date(0, 1, 1));
date.yearBC = 10;
assert(date == Date(-9, 1, 1));
}
}
}
/++
Month of a Gregorian Year.
Examples:
--------------------
assert(Date(1999, 7, 6).month == 7);
assert(Date(2010, 10, 4).month == 10);
assert(Date(-7, 4, 5).month == 4);
--------------------
+/
@property Month month() const pure nothrow
{
return _month;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(Date.init.month, 1);
_assertPred!"=="(Date(1999, 7, 6).month, 7);
_assertPred!"=="(Date(-1999, 7, 6).month, 7);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.month == 7));
static assert(__traits(compiles, idate.month == 7));
//Verify Examples.
assert(Date(1999, 7, 6).month == 7);
assert(Date(2010, 10, 4).month == 10);
assert(Date(-7, 4, 5).month == 4);
}
}
/++
Month of a Gregorian Year.
Params:
month = The month to set this $(D Date)'s month to.
Throws:
$(D DateTimeException) if the given month is not a valid month or if
the current day would not be valid in the given month.
+/
@property void month(Month month) pure
{
enforceValid!"months"(month);
enforceValid!"days"(_year, month, _day);
_month = cast(Month)month;
}
unittest
{
version(testStdDateTime)
{
static void testDate(Date date, Month month, in Date expected = Date.init, size_t line = __LINE__)
{
date.month = month;
assert(expected != Date.init);
_assertPred!"=="(date, expected, "", __FILE__, line);
}
assertThrown!DateTimeException(testDate(Date(1, 1, 1), cast(Month)0));
assertThrown!DateTimeException(testDate(Date(1, 1, 1), cast(Month)13));
assertThrown!DateTimeException(testDate(Date(1, 1, 29), cast(Month)2));
assertThrown!DateTimeException(testDate(Date(0, 1, 30), cast(Month)2));
testDate(Date(1, 1, 1), cast(Month)7, Date(1, 7, 1));
testDate(Date(-1, 1, 1), cast(Month)7, Date(-1, 7, 1));
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.month = 7));
static assert(!__traits(compiles, idate.month = 7));
}
}
/++
Day of a Gregorian Month.
Examples:
--------------------
assert(Date(1999, 7, 6).day == 6);
assert(Date(2010, 10, 4).day == 4);
assert(Date(-7, 4, 5).day == 5);
--------------------
+/
@property ubyte day() const pure nothrow
{
return _day;
}
//Verify Examples.
version(testStdDateTime) unittest
{
assert(Date(1999, 7, 6).day == 6);
assert(Date(2010, 10, 4).day == 4);
assert(Date(-7, 4, 5).day == 5);
}
version(testStdDateTime) unittest
{
static void test(Date date, int expected, size_t line = __LINE__)
{
_assertPred!"=="(date.day, expected,
format("Value given: %s", date), __FILE__, line);
}
foreach(year; chain(testYearsBC, testYearsAD))
{
foreach(md; testMonthDays)
test(Date(year, md.month, md.day), md.day);
}
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.day == 6));
static assert(__traits(compiles, idate.day == 6));
}
/++
Day of a Gregorian Month.
Params:
day = The day of the month to set this $(D Date)'s day to.
Throws:
$(D DateTimeException) if the given day is not a valid day of the
current month.
+/
@property void day(int day) pure
{
enforceValid!"days"(_year, _month, day);
_day = cast(ubyte)day;
}
unittest
{
version(testStdDateTime)
{
static void testDate(Date date, int day)
{
date.day = day;
}
//Test A.D.
assertThrown!DateTimeException(testDate(Date(1, 1, 1), 0));
assertThrown!DateTimeException(testDate(Date(1, 1, 1), 32));
assertThrown!DateTimeException(testDate(Date(1, 2, 1), 29));
assertThrown!DateTimeException(testDate(Date(4, 2, 1), 30));
assertThrown!DateTimeException(testDate(Date(1, 3, 1), 32));
assertThrown!DateTimeException(testDate(Date(1, 4, 1), 31));
assertThrown!DateTimeException(testDate(Date(1, 5, 1), 32));
assertThrown!DateTimeException(testDate(Date(1, 6, 1), 31));
assertThrown!DateTimeException(testDate(Date(1, 7, 1), 32));
assertThrown!DateTimeException(testDate(Date(1, 8, 1), 32));
assertThrown!DateTimeException(testDate(Date(1, 9, 1), 31));
assertThrown!DateTimeException(testDate(Date(1, 10, 1), 32));
assertThrown!DateTimeException(testDate(Date(1, 11, 1), 31));
assertThrown!DateTimeException(testDate(Date(1, 12, 1), 32));
assertNotThrown!DateTimeException(testDate(Date(1, 1, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(1, 2, 1), 28));
assertNotThrown!DateTimeException(testDate(Date(4, 2, 1), 29));
assertNotThrown!DateTimeException(testDate(Date(1, 3, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(1, 4, 1), 30));
assertNotThrown!DateTimeException(testDate(Date(1, 5, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(1, 6, 1), 30));
assertNotThrown!DateTimeException(testDate(Date(1, 7, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(1, 8, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(1, 9, 1), 30));
assertNotThrown!DateTimeException(testDate(Date(1, 10, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(1, 11, 1), 30));
assertNotThrown!DateTimeException(testDate(Date(1, 12, 1), 31));
{
auto date = Date(1, 1, 1);
date.day = 6;
_assertPred!"=="(date, Date(1, 1, 6));
}
//Test B.C.
assertThrown!DateTimeException(testDate(Date(-1, 1, 1), 0));
assertThrown!DateTimeException(testDate(Date(-1, 1, 1), 32));
assertThrown!DateTimeException(testDate(Date(-1, 2, 1), 29));
assertThrown!DateTimeException(testDate(Date(0, 2, 1), 30));
assertThrown!DateTimeException(testDate(Date(-1, 3, 1), 32));
assertThrown!DateTimeException(testDate(Date(-1, 4, 1), 31));
assertThrown!DateTimeException(testDate(Date(-1, 5, 1), 32));
assertThrown!DateTimeException(testDate(Date(-1, 6, 1), 31));
assertThrown!DateTimeException(testDate(Date(-1, 7, 1), 32));
assertThrown!DateTimeException(testDate(Date(-1, 8, 1), 32));
assertThrown!DateTimeException(testDate(Date(-1, 9, 1), 31));
assertThrown!DateTimeException(testDate(Date(-1, 10, 1), 32));
assertThrown!DateTimeException(testDate(Date(-1, 11, 1), 31));
assertThrown!DateTimeException(testDate(Date(-1, 12, 1), 32));
assertNotThrown!DateTimeException(testDate(Date(-1, 1, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(-1, 2, 1), 28));
assertNotThrown!DateTimeException(testDate(Date(0, 2, 1), 29));
assertNotThrown!DateTimeException(testDate(Date(-1, 3, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(-1, 4, 1), 30));
assertNotThrown!DateTimeException(testDate(Date(-1, 5, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(-1, 6, 1), 30));
assertNotThrown!DateTimeException(testDate(Date(-1, 7, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(-1, 8, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(-1, 9, 1), 30));
assertNotThrown!DateTimeException(testDate(Date(-1, 10, 1), 31));
assertNotThrown!DateTimeException(testDate(Date(-1, 11, 1), 30));
assertNotThrown!DateTimeException(testDate(Date(-1, 12, 1), 31));
{
auto date = Date(-1, 1, 1);
date.day = 6;
_assertPred!"=="(date, Date(-1, 1, 6));
}
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.day = 6));
static assert(!__traits(compiles, idate.day = 6));
}
}
/++
Adds the given number of years or months to this $(D Date). A negative
number will subtract.
Note that if day overflow is allowed, and the date with the adjusted
year/month overflows the number of days in the new month, then the month
will be incremented by one, and the day set to the number of days
overflowed. (e.g. if the day were 31 and the new month were June, then
the month would be incremented to July, and the new day would be 1). If
day overflow is not allowed, then the day will be set to the last valid
day in the month (e.g. June 31st would become June 30th).
Params:
units = The type of units to add ("years" or "months").
value = The number of months or years to add to this
$(D Date).
allowOverflow = Whether the day should be allowed to overflow,
causing the month to increment.
Examples:
--------------------
auto d1 = Date(2010, 1, 1);
d1.add!"months"(11);
assert(d1 == Date(2010, 12, 1));
auto d2 = Date(2010, 1, 1);
d2.add!"months"(-11);
assert(d2 == Date(2009, 2, 1));
auto d3 = Date(2000, 2, 29);
d3.add!"years"(1);
assert(d3 == Date(2001, 3, 1));
auto d4 = Date(2000, 2, 29);
d4.add!"years"(1, AllowDayOverflow.no);
assert(d4 == Date(2001, 2, 28));
--------------------
+/
/+ref Date+/ void add(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes) pure nothrow
if(units == "years")
{
immutable newYear = _year + value;
_year += value;
if(_month == Month.feb && _day == 29 && !yearIsLeapYear(_year))
{
if(allowOverflow == AllowDayOverflow.yes)
{
_month = Month.mar;
_day = 1;
}
else
_day = 28;
}
}
//Verify Examples.
unittest
{
version(stdStdDateTime)
{
auto d1 = Date(2010, 1, 1);
d1.add!"months"(11);
assert(d1 == Date(2010, 12, 1));
auto d2 = Date(2010, 1, 1);
d2.add!"months"(-11);
assert(d2 == Date(2009, 2, 1));
auto d3 = Date(2000, 2, 29);
d3.add!"years"(1);
assert(d3 == Date(2001, 3, 1));
auto d4 = Date(2000, 2, 29);
d4.add!"years"(1, AllowDayOverflow.no);
assert(d4 == Date(2001, 2, 28));
}
}
//Test add!"years"() with AllowDayOverlow.yes
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto date = Date(1999, 7, 6);
date.add!"years"(7);
_assertPred!"=="(date, Date(2006, 7, 6));
date.add!"years"(-9);
_assertPred!"=="(date, Date(1997, 7, 6));
}
{
auto date = Date(1999, 2, 28);
date.add!"years"(1);
_assertPred!"=="(date, Date(2000, 2, 28));
}
{
auto date = Date(2000, 2, 29);
date.add!"years"(-1);
_assertPred!"=="(date, Date(1999, 3, 1));
}
//Test B.C.
{
auto date = Date(-1999, 7, 6);
date.add!"years"(-7);
_assertPred!"=="(date, Date(-2006, 7, 6));
date.add!"years"(9);
_assertPred!"=="(date, Date(-1997, 7, 6));
}
{
auto date = Date(-1999, 2, 28);
date.add!"years"(-1);
_assertPred!"=="(date, Date(-2000, 2, 28));
}
{
auto date = Date(-2000, 2, 29);
date.add!"years"(1);
_assertPred!"=="(date, Date(-1999, 3, 1));
}
//Test Both
{
auto date = Date(4, 7, 6);
date.add!"years"(-5);
_assertPred!"=="(date, Date(-1, 7, 6));
date.add!"years"(5);
_assertPred!"=="(date, Date(4, 7, 6));
}
{
auto date = Date(-4, 7, 6);
date.add!"years"(5);
_assertPred!"=="(date, Date(1, 7, 6));
date.add!"years"(-5);
_assertPred!"=="(date, Date(-4, 7, 6));
}
{
auto date = Date(4, 7, 6);
date.add!"years"(-8);
_assertPred!"=="(date, Date(-4, 7, 6));
date.add!"years"(8);
_assertPred!"=="(date, Date(4, 7, 6));
}
{
auto date = Date(-4, 7, 6);
date.add!"years"(8);
_assertPred!"=="(date, Date(4, 7, 6));
date.add!"years"(-8);
_assertPred!"=="(date, Date(-4, 7, 6));
}
{
auto date = Date(-4, 2, 29);
date.add!"years"(5);
_assertPred!"=="(date, Date(1, 3, 1));
}
{
auto date = Date(4, 2, 29);
date.add!"years"(-5);
_assertPred!"=="(date, Date(-1, 3, 1));
}
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.add!"years"(7)));
static assert(!__traits(compiles, idate.add!"years"(7)));
}
}
//Test add!"years"() with AllowDayOverlow.no
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto date = Date(1999, 7, 6);
date.add!"years"(7, AllowDayOverflow.no);
_assertPred!"=="(date, Date(2006, 7, 6));
date.add!"years"(-9, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1997, 7, 6));
}
{
auto date = Date(1999, 2, 28);
date.add!"years"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(2000, 2, 28));
}
{
auto date = Date(2000, 2, 29);
date.add!"years"(-1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 2, 28));
}
//Test B.C.
{
auto date = Date(-1999, 7, 6);
date.add!"years"(-7, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2006, 7, 6));
date.add!"years"(9, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1997, 7, 6));
}
{
auto date = Date(-1999, 2, 28);
date.add!"years"(-1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2000, 2, 28));
}
{
auto date = Date(-2000, 2, 29);
date.add!"years"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 2, 28));
}
//Test Both
{
auto date = Date(4, 7, 6);
date.add!"years"(-5, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1, 7, 6));
date.add!"years"(5, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 7, 6));
}
{
auto date = Date(-4, 7, 6);
date.add!"years"(5, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1, 7, 6));
date.add!"years"(-5, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-4, 7, 6));
}
{
auto date = Date(4, 7, 6);
date.add!"years"(-8, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-4, 7, 6));
date.add!"years"(8, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 7, 6));
}
{
auto date = Date(-4, 7, 6);
date.add!"years"(8, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 7, 6));
date.add!"years"(-8, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-4, 7, 6));
}
{
auto date = Date(-4, 2, 29);
date.add!"years"(5, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1, 2, 28));
}
{
auto date = Date(4, 2, 29);
date.add!"years"(-5, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1, 2, 28));
}
}
}
//Shares documentation with "years" version.
/+ref Date+/ void add(string units)(long months, AllowDayOverflow allowOverflow = AllowDayOverflow.yes) pure nothrow
if(units == "months")
{
auto years = months / 12;
months %= 12;
auto newMonth = _month + months;
if(months < 0)
{
if(newMonth < 1)
{
newMonth += 12;
--years;
}
}
else if(newMonth > 12)
{
newMonth -= 12;
++years;
}
_year += years;
_month = cast(Month)newMonth;
immutable currMaxDay = maxDay(_year, _month);
immutable overflow = _day - currMaxDay;
if(overflow > 0)
{
if(allowOverflow == AllowDayOverflow.yes)
{
++_month;
_day = cast(ubyte)overflow;
}
else
_day = cast(ubyte)currMaxDay;
}
}
//Test add!"months"() with AllowDayOverlow.yes
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto date = Date(1999, 7, 6);
date.add!"months"(3);
_assertPred!"=="(date, Date(1999, 10, 6));
date.add!"months"(-4);
_assertPred!"=="(date, Date(1999, 6, 6));
}
{
auto date = Date(1999, 7, 6);
date.add!"months"(6);
_assertPred!"=="(date, Date(2000, 1, 6));
date.add!"months"(-6);
_assertPred!"=="(date, Date(1999, 7, 6));
}
{
auto date = Date(1999, 7, 6);
date.add!"months"(27);
_assertPred!"=="(date, Date(2001, 10, 6));
date.add!"months"(-28);
_assertPred!"=="(date, Date(1999, 6, 6));
}
{
auto date = Date(1999, 5, 31);
date.add!"months"(1);
_assertPred!"=="(date, Date(1999, 7, 1));
}
{
auto date = Date(1999, 5, 31);
date.add!"months"(-1);
_assertPred!"=="(date, Date(1999, 5, 1));
}
{
auto date = Date(1999, 2, 28);
date.add!"months"(12);
_assertPred!"=="(date, Date(2000, 2, 28));
}
{
auto date = Date(2000, 2, 29);
date.add!"months"(12);
_assertPred!"=="(date, Date(2001, 3, 1));
}
{
auto date = Date(1999, 7, 31);
date.add!"months"(1);
_assertPred!"=="(date, Date(1999, 8, 31));
date.add!"months"(1);
_assertPred!"=="(date, Date(1999, 10, 1));
}
{
auto date = Date(1998, 8, 31);
date.add!"months"(13);
_assertPred!"=="(date, Date(1999, 10, 1));
date.add!"months"(-13);
_assertPred!"=="(date, Date(1998, 9, 1));
}
{
auto date = Date(1997, 12, 31);
date.add!"months"(13);
_assertPred!"=="(date, Date(1999, 1, 31));
date.add!"months"(-13);
_assertPred!"=="(date, Date(1997, 12, 31));
}
{
auto date = Date(1997, 12, 31);
date.add!"months"(14);
_assertPred!"=="(date, Date(1999, 3, 3));
date.add!"months"(-14);
_assertPred!"=="(date, Date(1998, 1, 3));
}
{
auto date = Date(1998, 12, 31);
date.add!"months"(14);
_assertPred!"=="(date, Date(2000, 3, 2));
date.add!"months"(-14);
_assertPred!"=="(date, Date(1999, 1, 2));
}
{
auto date = Date(1999, 12, 31);
date.add!"months"(14);
_assertPred!"=="(date, Date(2001, 3, 3));
date.add!"months"(-14);
_assertPred!"=="(date, Date(2000, 1, 3));
}
//Test B.C.
{
auto date = Date(-1999, 7, 6);
date.add!"months"(3);
_assertPred!"=="(date, Date(-1999, 10, 6));
date.add!"months"(-4);
_assertPred!"=="(date, Date(-1999, 6, 6));
}
{
auto date = Date(-1999, 7, 6);
date.add!"months"(6);
_assertPred!"=="(date, Date(-1998, 1, 6));
date.add!"months"(-6);
_assertPred!"=="(date, Date(-1999, 7, 6));
}
{
auto date = Date(-1999, 7, 6);
date.add!"months"(-27);
_assertPred!"=="(date, Date(-2001, 4, 6));
date.add!"months"(28);
_assertPred!"=="(date, Date(-1999, 8, 6));
}
{
auto date = Date(-1999, 5, 31);
date.add!"months"(1);
_assertPred!"=="(date, Date(-1999, 7, 1));
}
{
auto date = Date(-1999, 5, 31);
date.add!"months"(-1);
_assertPred!"=="(date, Date(-1999, 5, 1));
}
{
auto date = Date(-1999, 2, 28);
date.add!"months"(-12);
_assertPred!"=="(date, Date(-2000, 2, 28));
}
{
auto date = Date(-2000, 2, 29);
date.add!"months"(-12);
_assertPred!"=="(date, Date(-2001, 3, 1));
}
{
auto date = Date(-1999, 7, 31);
date.add!"months"(1);
_assertPred!"=="(date, Date(-1999, 8, 31));
date.add!"months"(1);
_assertPred!"=="(date, Date(-1999, 10, 1));
}
{
auto date = Date(-1998, 8, 31);
date.add!"months"(13);
_assertPred!"=="(date, Date(-1997, 10, 1));
date.add!"months"(-13);
_assertPred!"=="(date, Date(-1998, 9, 1));
}
{
auto date = Date(-1997, 12, 31);
date.add!"months"(13);
_assertPred!"=="(date, Date(-1995, 1, 31));
date.add!"months"(-13);
_assertPred!"=="(date, Date(-1997, 12, 31));
}
{
auto date = Date(-1997, 12, 31);
date.add!"months"(14);
_assertPred!"=="(date, Date(-1995, 3, 3));
date.add!"months"(-14);
_assertPred!"=="(date, Date(-1996, 1, 3));
}
{
auto date = Date(-2002, 12, 31);
date.add!"months"(14);
_assertPred!"=="(date, Date(-2000, 3, 2));
date.add!"months"(-14);
_assertPred!"=="(date, Date(-2001, 1, 2));
}
{
auto date = Date(-2001, 12, 31);
date.add!"months"(14);
_assertPred!"=="(date, Date(-1999, 3, 3));
date.add!"months"(-14);
_assertPred!"=="(date, Date(-2000, 1, 3));
}
//Test Both
{
auto date = Date(1, 1, 1);
date.add!"months"(-1);
_assertPred!"=="(date, Date(0, 12, 1));
date.add!"months"(1);
_assertPred!"=="(date, Date(1, 1, 1));
}
{
auto date = Date(4, 1, 1);
date.add!"months"(-48);
_assertPred!"=="(date, Date(0, 1, 1));
date.add!"months"(48);
_assertPred!"=="(date, Date(4, 1, 1));
}
{
auto date = Date(4, 3, 31);
date.add!"months"(-49);
_assertPred!"=="(date, Date(0, 3, 2));
date.add!"months"(49);
_assertPred!"=="(date, Date(4, 4, 2));
}
{
auto date = Date(4, 3, 31);
date.add!"months"(-85);
_assertPred!"=="(date, Date(-3, 3, 3));
date.add!"months"(85);
_assertPred!"=="(date, Date(4, 4, 3));
}
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.add!"months"(3)));
static assert(!__traits(compiles, idate.add!"months"(3)));
}
}
//Test add!"months"() with AllowDayOverlow.no
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto date = Date(1999, 7, 6);
date.add!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 10, 6));
date.add!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 6, 6));
}
{
auto date = Date(1999, 7, 6);
date.add!"months"(6, AllowDayOverflow.no);
_assertPred!"=="(date, Date(2000, 1, 6));
date.add!"months"(-6, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 7, 6));
}
{
auto date = Date(1999, 7, 6);
date.add!"months"(27, AllowDayOverflow.no);
_assertPred!"=="(date, Date(2001, 10, 6));
date.add!"months"(-28, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 6, 6));
}
{
auto date = Date(1999, 5, 31);
date.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 6, 30));
}
{
auto date = Date(1999, 5, 31);
date.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 4, 30));
}
{
auto date = Date(1999, 2, 28);
date.add!"months"(12, AllowDayOverflow.no);
_assertPred!"=="(date, Date(2000, 2, 28));
}
{
auto date = Date(2000, 2, 29);
date.add!"months"(12, AllowDayOverflow.no);
_assertPred!"=="(date, Date(2001, 2, 28));
}
{
auto date = Date(1999, 7, 31);
date.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 8, 31));
date.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 9, 30));
}
{
auto date = Date(1998, 8, 31);
date.add!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 9, 30));
date.add!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1998, 8, 30));
}
{
auto date = Date(1997, 12, 31);
date.add!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 1, 31));
date.add!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1997, 12, 31));
}
{
auto date = Date(1997, 12, 31);
date.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 2, 28));
date.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1997, 12, 28));
}
{
auto date = Date(1998, 12, 31);
date.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(2000, 2, 29));
date.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1998, 12, 29));
}
{
auto date = Date(1999, 12, 31);
date.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(2001, 2, 28));
date.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 12, 28));
}
//Test B.C.
{
auto date = Date(-1999, 7, 6);
date.add!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 10, 6));
date.add!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 6, 6));
}
{
auto date = Date(-1999, 7, 6);
date.add!"months"(6, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1998, 1, 6));
date.add!"months"(-6, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 7, 6));
}
{
auto date = Date(-1999, 7, 6);
date.add!"months"(-27, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2001, 4, 6));
date.add!"months"(28, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 8, 6));
}
{
auto date = Date(-1999, 5, 31);
date.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 6, 30));
}
{
auto date = Date(-1999, 5, 31);
date.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 4, 30));
}
{
auto date = Date(-1999, 2, 28);
date.add!"months"(-12, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2000, 2, 28));
}
{
auto date = Date(-2000, 2, 29);
date.add!"months"(-12, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2001, 2, 28));
}
{
auto date = Date(-1999, 7, 31);
date.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 8, 31));
date.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 9, 30));
}
{
auto date = Date(-1998, 8, 31);
date.add!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1997, 9, 30));
date.add!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1998, 8, 30));
}
{
auto date = Date(-1997, 12, 31);
date.add!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1995, 1, 31));
date.add!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1997, 12, 31));
}
{
auto date = Date(-1997, 12, 31);
date.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1995, 2, 28));
date.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1997, 12, 28));
}
{
auto date = Date(-2002, 12, 31);
date.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2000, 2, 29));
date.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2002, 12, 29));
}
{
auto date = Date(-2001, 12, 31);
date.add!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 2, 28));
date.add!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2001, 12, 28));
}
//Test Both
{
auto date = Date(1, 1, 1);
date.add!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(0, 12, 1));
date.add!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1, 1, 1));
}
{
auto date = Date(4, 1, 1);
date.add!"months"(-48, AllowDayOverflow.no);
_assertPred!"=="(date, Date(0, 1, 1));
date.add!"months"(48, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 1, 1));
}
{
auto date = Date(4, 3, 31);
date.add!"months"(-49, AllowDayOverflow.no);
_assertPred!"=="(date, Date(0, 2, 29));
date.add!"months"(49, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 3, 29));
}
{
auto date = Date(4, 3, 31);
date.add!"months"(-85, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-3, 2, 28));
date.add!"months"(85, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 3, 28));
}
}
}
/++
Adds the given number of years or months to this $(D Date). A negative
number will subtract.
The difference between rolling and adding is that rolling does not
affect larger units. So, if you roll a $(D Date) 12 months, you get
the exact same $(D Date). However, the days can still be affected due to
the differing number of days in each month.
Because there are no units larger than years, there is no difference
between adding and rolling years.
Params:
units = The type of units to add ("years" or "months").
value = The number of months or years to add to this
$(D Date).
Examples:
--------------------
auto d1 = Date(2010, 1, 1);
d1.roll!"months"(1);
assert(d1 == Date(2010, 2, 1));
auto d2 = Date(2010, 1, 1);
d2.roll!"months"(-1);
assert(d2 == Date(2010, 12, 1));
auto d3 = Date(1999, 1, 29);
d3.roll!"months"(1);
assert(d3 == Date(1999, 3, 1));
auto d4 = Date(1999, 1, 29);
d4.roll!"months"(1, AllowDayOverflow.no);
assert(d4 == Date(1999, 2, 28));
auto d5 = Date(2000, 2, 29);
d5.roll!"years"(1);
assert(d5 == Date(2001, 3, 1));
auto d6 = Date(2000, 2, 29);
d6.roll!"years"(1, AllowDayOverflow.no);
assert(d6 == Date(2001, 2, 28));
--------------------
+/
/+ref Date+/ void roll(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes) pure nothrow
if(units == "years")
{
add!"years"(value, allowOverflow);
}
//Verify Examples.
unittest
{
version(testStdDateTime)
{
auto d1 = Date(2010, 1, 1);
d1.roll!"months"(1);
assert(d1 == Date(2010, 2, 1));
auto d2 = Date(2010, 1, 1);
d2.roll!"months"(-1);
assert(d2 == Date(2010, 12, 1));
auto d3 = Date(1999, 1, 29);
d3.roll!"months"(1);
assert(d3 == Date(1999, 3, 1));
auto d4 = Date(1999, 1, 29);
d4.roll!"months"(1, AllowDayOverflow.no);
assert(d4 == Date(1999, 2, 28));
auto d5 = Date(2000, 2, 29);
d5.roll!"years"(1);
assert(d5 == Date(2001, 3, 1));
auto d6 = Date(2000, 2, 29);
d6.roll!"years"(1, AllowDayOverflow.no);
assert(d6 == Date(2001, 2, 28));
}
}
unittest
{
version(testStdDateTime)
{
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.roll!"years"(3)));
static assert(!__traits(compiles, idate.rolYears(3)));
}
}
//Shares documentation with "years" version.
/+ref Date+/ void roll(string units)(long months, AllowDayOverflow allowOverflow = AllowDayOverflow.yes) pure nothrow
if(units == "months")
{
months %= 12;
auto newMonth = _month + months;
if(months < 0)
{
if(newMonth < 1)
newMonth += 12;
}
else
{
if(newMonth > 12)
newMonth -= 12;
}
_month = cast(Month)newMonth;
immutable currMaxDay = maxDay(_year, _month);
immutable overflow = _day - currMaxDay;
if(overflow > 0)
{
if(allowOverflow == AllowDayOverflow.yes)
{
++_month;
_day = cast(ubyte)overflow;
}
else
_day = cast(ubyte)currMaxDay;
}
}
//Test roll!"months"() with AllowDayOverlow.yes
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto date = Date(1999, 7, 6);
date.roll!"months"(3);
_assertPred!"=="(date, Date(1999, 10, 6));
date.roll!"months"(-4);
_assertPred!"=="(date, Date(1999, 6, 6));
}
{
auto date = Date(1999, 7, 6);
date.roll!"months"(6);
_assertPred!"=="(date, Date(1999, 1, 6));
date.roll!"months"(-6);
_assertPred!"=="(date, Date(1999, 7, 6));
}
{
auto date = Date(1999, 7, 6);
date.roll!"months"(27);
_assertPred!"=="(date, Date(1999, 10, 6));
date.roll!"months"(-28);
_assertPred!"=="(date, Date(1999, 6, 6));
}
{
auto date = Date(1999, 5, 31);
date.roll!"months"(1);
_assertPred!"=="(date, Date(1999, 7, 1));
}
{
auto date = Date(1999, 5, 31);
date.roll!"months"(-1);
_assertPred!"=="(date, Date(1999, 5, 1));
}
{
auto date = Date(1999, 2, 28);
date.roll!"months"(12);
_assertPred!"=="(date, Date(1999, 2, 28));
}
{
auto date = Date(2000, 2, 29);
date.roll!"months"(12);
_assertPred!"=="(date, Date(2000, 2, 29));
}
{
auto date = Date(1999, 7, 31);
date.roll!"months"(1);
_assertPred!"=="(date, Date(1999, 8, 31));
date.roll!"months"(1);
_assertPred!"=="(date, Date(1999, 10, 1));
}
{
auto date = Date(1998, 8, 31);
date.roll!"months"(13);
_assertPred!"=="(date, Date(1998, 10, 1));
date.roll!"months"(-13);
_assertPred!"=="(date, Date(1998, 9, 1));
}
{
auto date = Date(1997, 12, 31);
date.roll!"months"(13);
_assertPred!"=="(date, Date(1997, 1, 31));
date.roll!"months"(-13);
_assertPred!"=="(date, Date(1997, 12, 31));
}
{
auto date = Date(1997, 12, 31);
date.roll!"months"(14);
_assertPred!"=="(date, Date(1997, 3, 3));
date.roll!"months"(-14);
_assertPred!"=="(date, Date(1997, 1, 3));
}
{
auto date = Date(1998, 12, 31);
date.roll!"months"(14);
_assertPred!"=="(date, Date(1998, 3, 3));
date.roll!"months"(-14);
_assertPred!"=="(date, Date(1998, 1, 3));
}
{
auto date = Date(1999, 12, 31);
date.roll!"months"(14);
_assertPred!"=="(date, Date(1999, 3, 3));
date.roll!"months"(-14);
_assertPred!"=="(date, Date(1999, 1, 3));
}
//Test B.C.
{
auto date = Date(-1999, 7, 6);
date.roll!"months"(3);
_assertPred!"=="(date, Date(-1999, 10, 6));
date.roll!"months"(-4);
_assertPred!"=="(date, Date(-1999, 6, 6));
}
{
auto date = Date(-1999, 7, 6);
date.roll!"months"(6);
_assertPred!"=="(date, Date(-1999, 1, 6));
date.roll!"months"(-6);
_assertPred!"=="(date, Date(-1999, 7, 6));
}
{
auto date = Date(-1999, 7, 6);
date.roll!"months"(-27);
_assertPred!"=="(date, Date(-1999, 4, 6));
date.roll!"months"(28);
_assertPred!"=="(date, Date(-1999, 8, 6));
}
{
auto date = Date(-1999, 5, 31);
date.roll!"months"(1);
_assertPred!"=="(date, Date(-1999, 7, 1));
}
{
auto date = Date(-1999, 5, 31);
date.roll!"months"(-1);
_assertPred!"=="(date, Date(-1999, 5, 1));
}
{
auto date = Date(-1999, 2, 28);
date.roll!"months"(-12);
_assertPred!"=="(date, Date(-1999, 2, 28));
}
{
auto date = Date(-2000, 2, 29);
date.roll!"months"(-12);
_assertPred!"=="(date, Date(-2000, 2, 29));
}
{
auto date = Date(-1999, 7, 31);
date.roll!"months"(1);
_assertPred!"=="(date, Date(-1999, 8, 31));
date.roll!"months"(1);
_assertPred!"=="(date, Date(-1999, 10, 1));
}
{
auto date = Date(-1998, 8, 31);
date.roll!"months"(13);
_assertPred!"=="(date, Date(-1998, 10, 1));
date.roll!"months"(-13);
_assertPred!"=="(date, Date(-1998, 9, 1));
}
{
auto date = Date(-1997, 12, 31);
date.roll!"months"(13);
_assertPred!"=="(date, Date(-1997, 1, 31));
date.roll!"months"(-13);
_assertPred!"=="(date, Date(-1997, 12, 31));
}
{
auto date = Date(-1997, 12, 31);
date.roll!"months"(14);
_assertPred!"=="(date, Date(-1997, 3, 3));
date.roll!"months"(-14);
_assertPred!"=="(date, Date(-1997, 1, 3));
}
{
auto date = Date(-2002, 12, 31);
date.roll!"months"(14);
_assertPred!"=="(date, Date(-2002, 3, 3));
date.roll!"months"(-14);
_assertPred!"=="(date, Date(-2002, 1, 3));
}
{
auto date = Date(-2001, 12, 31);
date.roll!"months"(14);
_assertPred!"=="(date, Date(-2001, 3, 3));
date.roll!"months"(-14);
_assertPred!"=="(date, Date(-2001, 1, 3));
}
//Test Both
{
auto date = Date(1, 1, 1);
date.roll!"months"(-1);
_assertPred!"=="(date, Date(1, 12, 1));
date.roll!"months"(1);
_assertPred!"=="(date, Date(1, 1, 1));
}
{
auto date = Date(4, 1, 1);
date.roll!"months"(-48);
_assertPred!"=="(date, Date(4, 1, 1));
date.roll!"months"(48);
_assertPred!"=="(date, Date(4, 1, 1));
}
{
auto date = Date(4, 3, 31);
date.roll!"months"(-49);
_assertPred!"=="(date, Date(4, 3, 2));
date.roll!"months"(49);
_assertPred!"=="(date, Date(4, 4, 2));
}
{
auto date = Date(4, 3, 31);
date.roll!"months"(-85);
_assertPred!"=="(date, Date(4, 3, 2));
date.roll!"months"(85);
_assertPred!"=="(date, Date(4, 4, 2));
}
{
auto date = Date(-1, 1, 1);
date.roll!"months"(-1);
_assertPred!"=="(date, Date(-1, 12, 1));
date.roll!"months"(1);
_assertPred!"=="(date, Date(-1, 1, 1));
}
{
auto date = Date(-4, 1, 1);
date.roll!"months"(-48);
_assertPred!"=="(date, Date(-4, 1, 1));
date.roll!"months"(48);
_assertPred!"=="(date, Date(-4, 1, 1));
}
{
auto date = Date(-4, 3, 31);
date.roll!"months"(-49);
_assertPred!"=="(date, Date(-4, 3, 2));
date.roll!"months"(49);
_assertPred!"=="(date, Date(-4, 4, 2));
}
{
auto date = Date(-4, 3, 31);
date.roll!"months"(-85);
_assertPred!"=="(date, Date(-4, 3, 2));
date.roll!"months"(85);
_assertPred!"=="(date, Date(-4, 4, 2));
}
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.roll!"months"(3)));
static assert(!__traits(compiles, idate.roll!"months"(3)));
//Verify Examples.
auto date1 = Date(2010, 1, 1);
date1.roll!"months"(1);
assert(date1 == Date(2010, 2, 1));
auto date2 = Date(2010, 1, 1);
date2.roll!"months"(-1);
assert(date2 == Date(2010, 12, 1));
auto date3 = Date(1999, 1, 29);
date3.roll!"months"(1);
assert(date3 == Date(1999, 3, 1));
auto date4 = Date(1999, 1, 29);
date4.roll!"months"(1, AllowDayOverflow.no);
assert(date4 == Date(1999, 2, 28));
}
}
//Test roll!"months"() with AllowDayOverlow.no
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto date = Date(1999, 7, 6);
date.roll!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 10, 6));
date.roll!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 6, 6));
}
{
auto date = Date(1999, 7, 6);
date.roll!"months"(6, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 1, 6));
date.roll!"months"(-6, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 7, 6));
}
{
auto date = Date(1999, 7, 6);
date.roll!"months"(27, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 10, 6));
date.roll!"months"(-28, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 6, 6));
}
{
auto date = Date(1999, 5, 31);
date.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 6, 30));
}
{
auto date = Date(1999, 5, 31);
date.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 4, 30));
}
{
auto date = Date(1999, 2, 28);
date.roll!"months"(12, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 2, 28));
}
{
auto date = Date(2000, 2, 29);
date.roll!"months"(12, AllowDayOverflow.no);
_assertPred!"=="(date, Date(2000, 2, 29));
}
{
auto date = Date(1999, 7, 31);
date.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 8, 31));
date.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 9, 30));
}
{
auto date = Date(1998, 8, 31);
date.roll!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1998, 9, 30));
date.roll!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1998, 8, 30));
}
{
auto date = Date(1997, 12, 31);
date.roll!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1997, 1, 31));
date.roll!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1997, 12, 31));
}
{
auto date = Date(1997, 12, 31);
date.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1997, 2, 28));
date.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1997, 12, 28));
}
{
auto date = Date(1998, 12, 31);
date.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1998, 2, 28));
date.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1998, 12, 28));
}
{
auto date = Date(1999, 12, 31);
date.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 2, 28));
date.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1999, 12, 28));
}
//Test B.C.
{
auto date = Date(-1999, 7, 6);
date.roll!"months"(3, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 10, 6));
date.roll!"months"(-4, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 6, 6));
}
{
auto date = Date(-1999, 7, 6);
date.roll!"months"(6, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 1, 6));
date.roll!"months"(-6, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 7, 6));
}
{
auto date = Date(-1999, 7, 6);
date.roll!"months"(-27, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 4, 6));
date.roll!"months"(28, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 8, 6));
}
{
auto date = Date(-1999, 5, 31);
date.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 6, 30));
}
{
auto date = Date(-1999, 5, 31);
date.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 4, 30));
}
{
auto date = Date(-1999, 2, 28);
date.roll!"months"(-12, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 2, 28));
}
{
auto date = Date(-2000, 2, 29);
date.roll!"months"(-12, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2000, 2, 29));
}
{
auto date = Date(-1999, 7, 31);
date.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 8, 31));
date.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1999, 9, 30));
}
{
auto date = Date(-1998, 8, 31);
date.roll!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1998, 9, 30));
date.roll!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1998, 8, 30));
}
{
auto date = Date(-1997, 12, 31);
date.roll!"months"(13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1997, 1, 31));
date.roll!"months"(-13, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1997, 12, 31));
}
{
auto date = Date(-1997, 12, 31);
date.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1997, 2, 28));
date.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1997, 12, 28));
}
{
auto date = Date(-2002, 12, 31);
date.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2002, 2, 28));
date.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2002, 12, 28));
}
{
auto date = Date(-2001, 12, 31);
date.roll!"months"(14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2001, 2, 28));
date.roll!"months"(-14, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-2001, 12, 28));
}
//Test Both
{
auto date = Date(1, 1, 1);
date.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1, 12, 1));
date.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(1, 1, 1));
}
{
auto date = Date(4, 1, 1);
date.roll!"months"(-48, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 1, 1));
date.roll!"months"(48, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 1, 1));
}
{
auto date = Date(4, 3, 31);
date.roll!"months"(-49, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 2, 29));
date.roll!"months"(49, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 3, 29));
}
{
auto date = Date(4, 3, 31);
date.roll!"months"(-85, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 2, 29));
date.roll!"months"(85, AllowDayOverflow.no);
_assertPred!"=="(date, Date(4, 3, 29));
}
{
auto date = Date(-1, 1, 1);
date.roll!"months"(-1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1, 12, 1));
date.roll!"months"(1, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-1, 1, 1));
}
{
auto date = Date(-4, 1, 1);
date.roll!"months"(-48, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-4, 1, 1));
date.roll!"months"(48, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-4, 1, 1));
}
{
auto date = Date(-4, 3, 31);
date.roll!"months"(-49, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-4, 2, 29));
date.roll!"months"(49, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-4, 3, 29));
}
{
auto date = Date(-4, 3, 31);
date.roll!"months"(-85, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-4, 2, 29));
date.roll!"months"(85, AllowDayOverflow.no);
_assertPred!"=="(date, Date(-4, 3, 29));
}
}
}
/++
Adds the given number of units to this $(D Date). A negative number will
subtract.
The difference between rolling and adding is that rolling does not
affect larger units. So, for instance, if you roll a $(D Date) one
year's worth of days, then you get the exact same $(D Date).
The only accepted units are $(D "days").
Params:
units = The units to add. Must be $(D "days").
value = The number of days to add to this $(D Date).
Examples:
--------------------
auto d = Date(2010, 1, 1);
d.roll!"days"(1);
assert(d == Date(2010, 1, 2));
d.roll!"days"(365);
assert(d == Date(2010, 1, 26));
d.roll!"days"(-32);
assert(d == Date(2010, 1, 25));
--------------------
+/
/+ref Date+/ void roll(string units)(long days) pure nothrow
if(units == "days")
{
immutable limit = maxDay(_year, _month);
days %= limit;
auto newDay = _day + days;
if(days < 0)
{
if(newDay < 1)
newDay += limit;
}
else if(newDay > limit)
newDay -= limit;
_day = cast(ubyte)newDay;
}
//Verify Examples.
unittest
{
version(testStdDateTime)
{
auto d = Date(2010, 1, 1);
d.roll!"days"(1);
assert(d == Date(2010, 1, 2));
d.roll!"days"(365);
assert(d == Date(2010, 1, 26));
d.roll!"days"(-32);
assert(d == Date(2010, 1, 25));
}
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto date = Date(1999, 2, 28);
date.roll!"days"(1);
_assertPred!"=="(date, Date(1999, 2, 1));
date.roll!"days"(-1);
_assertPred!"=="(date, Date(1999, 2, 28));
}
{
auto date = Date(2000, 2, 28);
date.roll!"days"(1);
_assertPred!"=="(date, Date(2000, 2, 29));
date.roll!"days"(1);
_assertPred!"=="(date, Date(2000, 2, 1));
date.roll!"days"(-1);
_assertPred!"=="(date, Date(2000, 2, 29));
}
{
auto date = Date(1999, 6, 30);
date.roll!"days"(1);
_assertPred!"=="(date, Date(1999, 6, 1));
date.roll!"days"(-1);
_assertPred!"=="(date, Date(1999, 6, 30));
}
{
auto date = Date(1999, 7, 31);
date.roll!"days"(1);
_assertPred!"=="(date, Date(1999, 7, 1));
date.roll!"days"(-1);
_assertPred!"=="(date, Date(1999, 7, 31));
}
{
auto date = Date(1999, 1, 1);
date.roll!"days"(-1);
_assertPred!"=="(date, Date(1999, 1, 31));
date.roll!"days"(1);
_assertPred!"=="(date, Date(1999, 1, 1));
}
{
auto date = Date(1999, 7, 6);
date.roll!"days"(9);
_assertPred!"=="(date, Date(1999, 7, 15));
date.roll!"days"(-11);
_assertPred!"=="(date, Date(1999, 7, 4));
date.roll!"days"(30);
_assertPred!"=="(date, Date(1999, 7, 3));
date.roll!"days"(-3);
_assertPred!"=="(date, Date(1999, 7, 31));
}
{
auto date = Date(1999, 7, 6);
date.roll!"days"(365);
_assertPred!"=="(date, Date(1999, 7, 30));
date.roll!"days"(-365);
_assertPred!"=="(date, Date(1999, 7, 6));
date.roll!"days"(366);
_assertPred!"=="(date, Date(1999, 7, 31));
date.roll!"days"(730);
_assertPred!"=="(date, Date(1999, 7, 17));
date.roll!"days"(-1096);
_assertPred!"=="(date, Date(1999, 7, 6));
}
{
auto date = Date(1999, 2, 6);
date.roll!"days"(365);
_assertPred!"=="(date, Date(1999, 2, 7));
date.roll!"days"(-365);
_assertPred!"=="(date, Date(1999, 2, 6));
date.roll!"days"(366);
_assertPred!"=="(date, Date(1999, 2, 8));
date.roll!"days"(730);
_assertPred!"=="(date, Date(1999, 2, 10));
date.roll!"days"(-1096);
_assertPred!"=="(date, Date(1999, 2, 6));
}
//Test B.C.
{
auto date = Date(-1999, 2, 28);
date.roll!"days"(1);
_assertPred!"=="(date, Date(-1999, 2, 1));
date.roll!"days"(-1);
_assertPred!"=="(date, Date(-1999, 2, 28));
}
{
auto date = Date(-2000, 2, 28);
date.roll!"days"(1);
_assertPred!"=="(date, Date(-2000, 2, 29));
date.roll!"days"(1);
_assertPred!"=="(date, Date(-2000, 2, 1));
date.roll!"days"(-1);
_assertPred!"=="(date, Date(-2000, 2, 29));
}
{
auto date = Date(-1999, 6, 30);
date.roll!"days"(1);
_assertPred!"=="(date, Date(-1999, 6, 1));
date.roll!"days"(-1);
_assertPred!"=="(date, Date(-1999, 6, 30));
}
{
auto date = Date(-1999, 7, 31);
date.roll!"days"(1);
_assertPred!"=="(date, Date(-1999, 7, 1));
date.roll!"days"(-1);
_assertPred!"=="(date, Date(-1999, 7, 31));
}
{
auto date = Date(-1999, 1, 1);
date.roll!"days"(-1);
_assertPred!"=="(date, Date(-1999, 1, 31));
date.roll!"days"(1);
_assertPred!"=="(date, Date(-1999, 1, 1));
}
{
auto date = Date(-1999, 7, 6);
date.roll!"days"(9);
_assertPred!"=="(date, Date(-1999, 7, 15));
date.roll!"days"(-11);
_assertPred!"=="(date, Date(-1999, 7, 4));
date.roll!"days"(30);
_assertPred!"=="(date, Date(-1999, 7, 3));
date.roll!"days"(-3);
_assertPred!"=="(date, Date(-1999, 7, 31));
}
{
auto date = Date(-1999, 7, 6);
date.roll!"days"(365);
_assertPred!"=="(date, Date(-1999, 7, 30));
date.roll!"days"(-365);
_assertPred!"=="(date, Date(-1999, 7, 6));
date.roll!"days"(366);
_assertPred!"=="(date, Date(-1999, 7, 31));
date.roll!"days"(730);
_assertPred!"=="(date, Date(-1999, 7, 17));
date.roll!"days"(-1096);
_assertPred!"=="(date, Date(-1999, 7, 6));
}
//Test Both
{
auto date = Date(1, 7, 6);
date.roll!"days"(-365);
_assertPred!"=="(date, Date(1, 7, 13));
date.roll!"days"(365);
_assertPred!"=="(date, Date(1, 7, 6));
date.roll!"days"(-731);
_assertPred!"=="(date, Date(1, 7, 19));
date.roll!"days"(730);
_assertPred!"=="(date, Date(1, 7, 5));
}
{
auto date = Date(0, 7, 6);
date.roll!"days"(-365);
_assertPred!"=="(date, Date(0, 7, 13));
date.roll!"days"(365);
_assertPred!"=="(date, Date(0, 7, 6));
date.roll!"days"(-731);
_assertPred!"=="(date, Date(0, 7, 19));
date.roll!"days"(730);
_assertPred!"=="(date, Date(0, 7, 5));
}
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.roll!"days"(12)));
static assert(!__traits(compiles, idate.roll!"days"(12)));
//Verify Examples.
auto date = Date(2010, 1, 1);
date.roll!"days"(1);
assert(date == Date(2010, 1, 2));
date.roll!"days"(365);
assert(date == Date(2010, 1, 26));
date.roll!"days"(-32);
assert(date == Date(2010, 1, 25));
}
}
/++
Gives the result of adding or subtracting a duration from this
$(D Date).
The legal types of arithmetic for Date using this operator are
$(BOOKTABLE,
$(TR $(TD Date) $(TD +) $(TD duration) $(TD -->) $(TD Date))
$(TR $(TD Date) $(TD -) $(TD duration) $(TD -->) $(TD Date))
)
Params:
duration = The duration to add to or subtract from this $(D Date).
+/
Date opBinary(string op, D)(in D duration) const pure nothrow
if((op == "+" || op == "-") &&
(is(Unqual!D == Duration) ||
is(Unqual!D == TickDuration)))
{
Date retval = this;
static if(is(Unqual!D == Duration))
immutable days = duration.total!"days";
else static if(is(Unqual!D == TickDuration))
immutable days = convert!("hnsecs", "days")(duration.hnsecs);
//Ideally, this would just be
//return retval.addDays(unaryFun!(op ~ "a")(days));
//But there isn't currently a pure version of unaryFun!().
static if(op == "+")
immutable signedDays = days;
else static if(op == "-")
immutable signedDays = -days;
else
static assert(0);
return retval.addDays(signedDays);
}
unittest
{
version(testStdDateTime)
{
auto date = Date(1999, 7, 6);
_assertPred!"=="(date + dur!"weeks"(7), Date(1999, 8, 24));
_assertPred!"=="(date + dur!"weeks"(-7), Date(1999, 5, 18));
_assertPred!"=="(date + dur!"days"(7), Date(1999, 7, 13));
_assertPred!"=="(date + dur!"days"(-7), Date(1999, 6, 29));
_assertPred!"=="(date + dur!"hours"(24), Date(1999, 7, 7));
_assertPred!"=="(date + dur!"hours"(-24), Date(1999, 7, 5));
_assertPred!"=="(date + dur!"minutes"(1440), Date(1999, 7, 7));
_assertPred!"=="(date + dur!"minutes"(-1440), Date(1999, 7, 5));
_assertPred!"=="(date + dur!"seconds"(86_400), Date(1999, 7, 7));
_assertPred!"=="(date + dur!"seconds"(-86_400), Date(1999, 7, 5));
_assertPred!"=="(date + dur!"msecs"(86_400_000), Date(1999, 7, 7));
_assertPred!"=="(date + dur!"msecs"(-86_400_000), Date(1999, 7, 5));
_assertPred!"=="(date + dur!"usecs"(86_400_000_000), Date(1999, 7, 7));
_assertPred!"=="(date + dur!"usecs"(-86_400_000_000), Date(1999, 7, 5));
_assertPred!"=="(date + dur!"hnsecs"(864_000_000_000), Date(1999, 7, 7));
_assertPred!"=="(date + dur!"hnsecs"(-864_000_000_000), Date(1999, 7, 5));
//This probably only runs in cases where gettimeofday() is used, but it's
//hard to do this test correctly with variable ticksPerSec.
if(TickDuration.ticksPerSec == 1_000_000)
{
_assertPred!"=="(date + TickDuration.from!"usecs"(86_400_000_000), Date(1999, 7, 7));
_assertPred!"=="(date + TickDuration.from!"usecs"(-86_400_000_000), Date(1999, 7, 5));
}
_assertPred!"=="(date - dur!"weeks"(-7), Date(1999, 8, 24));
_assertPred!"=="(date - dur!"weeks"(7), Date(1999, 5, 18));
_assertPred!"=="(date - dur!"days"(-7), Date(1999, 7, 13));
_assertPred!"=="(date - dur!"days"(7), Date(1999, 6, 29));
_assertPred!"=="(date - dur!"hours"(-24), Date(1999, 7, 7));
_assertPred!"=="(date - dur!"hours"(24), Date(1999, 7, 5));
_assertPred!"=="(date - dur!"minutes"(-1440), Date(1999, 7, 7));
_assertPred!"=="(date - dur!"minutes"(1440), Date(1999, 7, 5));
_assertPred!"=="(date - dur!"seconds"(-86_400), Date(1999, 7, 7));
_assertPred!"=="(date - dur!"seconds"(86_400), Date(1999, 7, 5));
_assertPred!"=="(date - dur!"msecs"(-86_400_000), Date(1999, 7, 7));
_assertPred!"=="(date - dur!"msecs"(86_400_000), Date(1999, 7, 5));
_assertPred!"=="(date - dur!"usecs"(-86_400_000_000), Date(1999, 7, 7));
_assertPred!"=="(date - dur!"usecs"(86_400_000_000), Date(1999, 7, 5));
_assertPred!"=="(date - dur!"hnsecs"(-864_000_000_000), Date(1999, 7, 7));
_assertPred!"=="(date - dur!"hnsecs"(864_000_000_000), Date(1999, 7, 5));
//This probably only runs in cases where gettimeofday() is used, but it's
//hard to do this test correctly with variable ticksPerSec.
if(TickDuration.ticksPerSec == 1_000_000)
{
_assertPred!"=="(date - TickDuration.from!"usecs"(-86_400_000_000), Date(1999, 7, 7));
_assertPred!"=="(date - TickDuration.from!"usecs"(86_400_000_000), Date(1999, 7, 5));
}
auto duration = dur!"days"(12);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, date + duration));
static assert(__traits(compiles, cdate + duration));
static assert(__traits(compiles, idate + duration));
static assert(__traits(compiles, date - duration));
static assert(__traits(compiles, cdate - duration));
static assert(__traits(compiles, idate - duration));
}
}
/++
Gives the result of adding or subtracting a duration from this
$(D Date), as well as assigning the result to this $(D Date).
The legal types of arithmetic for $(D Date) using this operator are
$(BOOKTABLE,
$(TR $(TD Date) $(TD +) $(TD duration) $(TD -->) $(TD Date))
$(TR $(TD Date) $(TD -) $(TD duration) $(TD -->) $(TD Date))
)
Params:
duration = The duration to add to or subtract from this $(D Date).
+/
/+ref+/ Date opOpAssign(string op, D)(in D duration) pure nothrow
if((op == "+" || op == "-") &&
(is(Unqual!D == Duration) ||
is(Unqual!D == TickDuration)))
{
static if(is(Unqual!D == Duration))
immutable days = duration.total!"days";
else static if(is(Unqual!D == TickDuration))
immutable days = convert!("hnsecs", "days")(duration.hnsecs);
//Ideally, this would just be
//return addDays(unaryFun!(op ~ "a")(days));
//But there isn't currently a pure version of unaryFun!().
static if(op == "+")
immutable signedDays = days;
else static if(op == "-")
immutable signedDays = -days;
else
static assert(0);
return addDays(signedDays);
}
unittest
{
version(testStdDateTime)
{
_assertPred!"+="(Date(1999, 7, 6), dur!"weeks"(7), Date(1999, 8, 24));
_assertPred!"+="(Date(1999, 7, 6), dur!"weeks"(-7), Date(1999, 5, 18));
_assertPred!"+="(Date(1999, 7, 6), dur!"days"(7), Date(1999, 7, 13));
_assertPred!"+="(Date(1999, 7, 6), dur!"days"(-7), Date(1999, 6, 29));
_assertPred!"+="(Date(1999, 7, 6), dur!"hours"(24), Date(1999, 7, 7));
_assertPred!"+="(Date(1999, 7, 6), dur!"hours"(-24), Date(1999, 7, 5));
_assertPred!"+="(Date(1999, 7, 6), dur!"minutes"(1440), Date(1999, 7, 7));
_assertPred!"+="(Date(1999, 7, 6), dur!"minutes"(-1440), Date(1999, 7, 5));
_assertPred!"+="(Date(1999, 7, 6), dur!"seconds"(86_400), Date(1999, 7, 7));
_assertPred!"+="(Date(1999, 7, 6), dur!"seconds"(-86_400), Date(1999, 7, 5));
_assertPred!"+="(Date(1999, 7, 6), dur!"msecs"(86_400_000), Date(1999, 7, 7));
_assertPred!"+="(Date(1999, 7, 6), dur!"msecs"(-86_400_000), Date(1999, 7, 5));
_assertPred!"+="(Date(1999, 7, 6), dur!"usecs"(86_400_000_000), Date(1999, 7, 7));
_assertPred!"+="(Date(1999, 7, 6), dur!"usecs"(-86_400_000_000), Date(1999, 7, 5));
_assertPred!"+="(Date(1999, 7, 6), dur!"hnsecs"(864_000_000_000), Date(1999, 7, 7));
_assertPred!"+="(Date(1999, 7, 6), dur!"hnsecs"(-864_000_000_000), Date(1999, 7, 5));
_assertPred!"-="(Date(1999, 7, 6), dur!"weeks"(-7), Date(1999, 8, 24));
_assertPred!"-="(Date(1999, 7, 6), dur!"weeks"(7), Date(1999, 5, 18));
_assertPred!"-="(Date(1999, 7, 6), dur!"days"(-7), Date(1999, 7, 13));
_assertPred!"-="(Date(1999, 7, 6), dur!"days"(7), Date(1999, 6, 29));
_assertPred!"-="(Date(1999, 7, 6), dur!"hours"(-24), Date(1999, 7, 7));
_assertPred!"-="(Date(1999, 7, 6), dur!"hours"(24), Date(1999, 7, 5));
_assertPred!"-="(Date(1999, 7, 6), dur!"minutes"(-1440), Date(1999, 7, 7));
_assertPred!"-="(Date(1999, 7, 6), dur!"minutes"(1440), Date(1999, 7, 5));
_assertPred!"-="(Date(1999, 7, 6), dur!"seconds"(-86_400), Date(1999, 7, 7));
_assertPred!"-="(Date(1999, 7, 6), dur!"seconds"(86_400), Date(1999, 7, 5));
_assertPred!"-="(Date(1999, 7, 6), dur!"msecs"(-86_400_000), Date(1999, 7, 7));
_assertPred!"-="(Date(1999, 7, 6), dur!"msecs"(86_400_000), Date(1999, 7, 5));
_assertPred!"-="(Date(1999, 7, 6), dur!"usecs"(-86_400_000_000), Date(1999, 7, 7));
_assertPred!"-="(Date(1999, 7, 6), dur!"usecs"(86_400_000_000), Date(1999, 7, 5));
_assertPred!"-="(Date(1999, 7, 6), dur!"hnsecs"(-864_000_000_000), Date(1999, 7, 7));
_assertPred!"-="(Date(1999, 7, 6), dur!"hnsecs"(864_000_000_000), Date(1999, 7, 5));
auto duration = dur!"days"(12);
auto date = Date(1999, 7, 6);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, date += duration));
static assert(!__traits(compiles, cdate += duration));
static assert(!__traits(compiles, idate += duration));
static assert(__traits(compiles, date -= duration));
static assert(!__traits(compiles, cdate -= duration));
static assert(!__traits(compiles, idate -= duration));
}
}
/++
Gives the difference between two $(D Date)s.
The legal types of arithmetic for Date using this operator are
$(BOOKTABLE,
$(TR $(TD Date) $(TD -) $(TD Date) $(TD -->) $(TD duration))
)
+/
Duration opBinary(string op)(in Date rhs) const pure nothrow
if(op == "-")
{
return dur!"days"(this.dayOfGregorianCal - rhs.dayOfGregorianCal);
}
unittest
{
version(testStdDateTime)
{
auto date = Date(1999, 7, 6);
_assertPred!"=="(Date(1999, 7, 6) - Date(1998, 7, 6), dur!"days"(365));
_assertPred!"=="(Date(1998, 7, 6) - Date(1999, 7, 6), dur!"days"(-365));
_assertPred!"=="(Date(1999, 6, 6) - Date(1999, 5, 6), dur!"days"(31));
_assertPred!"=="(Date(1999, 5, 6) - Date(1999, 6, 6), dur!"days"(-31));
_assertPred!"=="(Date(1999, 1, 1) - Date(1998, 12, 31), dur!"days"(1));
_assertPred!"=="(Date(1998, 12, 31) - Date(1999, 1, 1), dur!"days"(-1));
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, date - date));
static assert(__traits(compiles, cdate - date));
static assert(__traits(compiles, idate - date));
static assert(__traits(compiles, date - cdate));
static assert(__traits(compiles, cdate - cdate));
static assert(__traits(compiles, idate - cdate));
static assert(__traits(compiles, date - idate));
static assert(__traits(compiles, cdate - idate));
static assert(__traits(compiles, idate - idate));
}
}
/++
Returns the difference between the two $(D Date)s in months.
You can get the difference in years by subtracting the year property
of two $(D Date)s, and you can get the difference in days or weeks by
subtracting the $(D Date)s themselves and using the $(D Duration) that
results, but because you cannot convert between months and smaller units
without a specific date (which $(D Duration)s don't have), you cannot
get the difference in months without doing some math using both the year
and month properties, so this is a convenience function for getting the
difference in months.
Note that the number of days in the months or how far into the month
either $(D Date) is is irrelevant. It is the difference in the month
property combined with the difference in years * 12. So, for instance,
December 31st and January 1st are one month apart just as December 1st
and January 31st are one month apart.
Params:
rhs = The $(D Date) to subtract from this one.
Examples:
--------------------
assert(Date(1999, 2, 1).diffMonths(Date(1999, 1, 31)) == 1);
assert(Date(1999, 1, 31).diffMonths(Date(1999, 2, 1)) == -1);
assert(Date(1999, 3, 1).diffMonths(Date(1999, 1, 1)) == 2);
assert(Date(1999, 1, 1).diffMonths(Date(1999, 3, 31)) == -2);
--------------------
+/
int diffMonths(in Date rhs) const pure nothrow
{
immutable yearDiff = _year - rhs._year;
immutable monthDiff = _month - rhs._month;
return yearDiff * 12 + monthDiff;
}
unittest
{
version(testStdDateTime)
{
auto date = Date(1999, 7, 6);
//Test A.D.
_assertPred!"=="(date.diffMonths(Date(1998, 6, 5)), 13);
_assertPred!"=="(date.diffMonths(Date(1998, 7, 5)), 12);
_assertPred!"=="(date.diffMonths(Date(1998, 8, 5)), 11);
_assertPred!"=="(date.diffMonths(Date(1998, 9, 5)), 10);
_assertPred!"=="(date.diffMonths(Date(1998, 10, 5)), 9);
_assertPred!"=="(date.diffMonths(Date(1998, 11, 5)), 8);
_assertPred!"=="(date.diffMonths(Date(1998, 12, 5)), 7);
_assertPred!"=="(date.diffMonths(Date(1999, 1, 5)), 6);
_assertPred!"=="(date.diffMonths(Date(1999, 2, 6)), 5);
_assertPred!"=="(date.diffMonths(Date(1999, 3, 6)), 4);
_assertPred!"=="(date.diffMonths(Date(1999, 4, 6)), 3);
_assertPred!"=="(date.diffMonths(Date(1999, 5, 6)), 2);
_assertPred!"=="(date.diffMonths(Date(1999, 6, 6)), 1);
_assertPred!"=="(date.diffMonths(date), 0);
_assertPred!"=="(date.diffMonths(Date(1999, 8, 6)), -1);
_assertPred!"=="(date.diffMonths(Date(1999, 9, 6)), -2);
_assertPred!"=="(date.diffMonths(Date(1999, 10, 6)), -3);
_assertPred!"=="(date.diffMonths(Date(1999, 11, 6)), -4);
_assertPred!"=="(date.diffMonths(Date(1999, 12, 6)), -5);
_assertPred!"=="(date.diffMonths(Date(2000, 1, 6)), -6);
_assertPred!"=="(date.diffMonths(Date(2000, 2, 6)), -7);
_assertPred!"=="(date.diffMonths(Date(2000, 3, 6)), -8);
_assertPred!"=="(date.diffMonths(Date(2000, 4, 6)), -9);
_assertPred!"=="(date.diffMonths(Date(2000, 5, 6)), -10);
_assertPred!"=="(date.diffMonths(Date(2000, 6, 6)), -11);
_assertPred!"=="(date.diffMonths(Date(2000, 7, 6)), -12);
_assertPred!"=="(date.diffMonths(Date(2000, 8, 6)), -13);
_assertPred!"=="(Date(1998, 6, 5).diffMonths(date), -13);
_assertPred!"=="(Date(1998, 7, 5).diffMonths(date), -12);
_assertPred!"=="(Date(1998, 8, 5).diffMonths(date), -11);
_assertPred!"=="(Date(1998, 9, 5).diffMonths(date), -10);
_assertPred!"=="(Date(1998, 10, 5).diffMonths(date), -9);
_assertPred!"=="(Date(1998, 11, 5).diffMonths(date), -8);
_assertPred!"=="(Date(1998, 12, 5).diffMonths(date), -7);
_assertPred!"=="(Date(1999, 1, 5).diffMonths(date), -6);
_assertPred!"=="(Date(1999, 2, 6).diffMonths(date), -5);
_assertPred!"=="(Date(1999, 3, 6).diffMonths(date), -4);
_assertPred!"=="(Date(1999, 4, 6).diffMonths(date), -3);
_assertPred!"=="(Date(1999, 5, 6).diffMonths(date), -2);
_assertPred!"=="(Date(1999, 6, 6).diffMonths(date), -1);
_assertPred!"=="(Date(1999, 8, 6).diffMonths(date), 1);
_assertPred!"=="(Date(1999, 9, 6).diffMonths(date), 2);
_assertPred!"=="(Date(1999, 10, 6).diffMonths(date), 3);
_assertPred!"=="(Date(1999, 11, 6).diffMonths(date), 4);
_assertPred!"=="(Date(1999, 12, 6).diffMonths(date), 5);
_assertPred!"=="(Date(2000, 1, 6).diffMonths(date), 6);
_assertPred!"=="(Date(2000, 2, 6).diffMonths(date), 7);
_assertPred!"=="(Date(2000, 3, 6).diffMonths(date), 8);
_assertPred!"=="(Date(2000, 4, 6).diffMonths(date), 9);
_assertPred!"=="(Date(2000, 5, 6).diffMonths(date), 10);
_assertPred!"=="(Date(2000, 6, 6).diffMonths(date), 11);
_assertPred!"=="(Date(2000, 7, 6).diffMonths(date), 12);
_assertPred!"=="(Date(2000, 8, 6).diffMonths(date), 13);
_assertPred!"=="(date.diffMonths(Date(1999, 6, 30)), 1);
_assertPred!"=="(date.diffMonths(Date(1999, 7, 1)), 0);
_assertPred!"=="(date.diffMonths(Date(1999, 7, 6)), 0);
_assertPred!"=="(date.diffMonths(Date(1999, 7, 11)), 0);
_assertPred!"=="(date.diffMonths(Date(1999, 7, 16)), 0);
_assertPred!"=="(date.diffMonths(Date(1999, 7, 21)), 0);
_assertPred!"=="(date.diffMonths(Date(1999, 7, 26)), 0);
_assertPred!"=="(date.diffMonths(Date(1999, 7, 31)), 0);
_assertPred!"=="(date.diffMonths(Date(1999, 8, 1)), -1);
_assertPred!"=="(date.diffMonths(Date(1990, 6, 30)), 109);
_assertPred!"=="(date.diffMonths(Date(1990, 7, 1)), 108);
_assertPred!"=="(date.diffMonths(Date(1990, 7, 6)), 108);
_assertPred!"=="(date.diffMonths(Date(1990, 7, 11)), 108);
_assertPred!"=="(date.diffMonths(Date(1990, 7, 16)), 108);
_assertPred!"=="(date.diffMonths(Date(1990, 7, 21)), 108);
_assertPred!"=="(date.diffMonths(Date(1990, 7, 26)), 108);
_assertPred!"=="(date.diffMonths(Date(1990, 7, 31)), 108);
_assertPred!"=="(date.diffMonths(Date(1990, 8, 1)), 107);
_assertPred!"=="(Date(1999, 6, 30).diffMonths(date), -1);
_assertPred!"=="(Date(1999, 7, 1).diffMonths(date), 0);
_assertPred!"=="(Date(1999, 7, 6).diffMonths(date), 0);
_assertPred!"=="(Date(1999, 7, 11).diffMonths(date), 0);
_assertPred!"=="(Date(1999, 7, 16).diffMonths(date), 0);
_assertPred!"=="(Date(1999, 7, 21).diffMonths(date), 0);
_assertPred!"=="(Date(1999, 7, 26).diffMonths(date), 0);
_assertPred!"=="(Date(1999, 7, 31).diffMonths(date), 0);
_assertPred!"=="(Date(1999, 8, 1).diffMonths(date), 1);
_assertPred!"=="(Date(1990, 6, 30).diffMonths(date), -109);
_assertPred!"=="(Date(1990, 7, 1).diffMonths(date), -108);
_assertPred!"=="(Date(1990, 7, 6).diffMonths(date), -108);
_assertPred!"=="(Date(1990, 7, 11).diffMonths(date), -108);
_assertPred!"=="(Date(1990, 7, 16).diffMonths(date), -108);
_assertPred!"=="(Date(1990, 7, 21).diffMonths(date), -108);
_assertPred!"=="(Date(1990, 7, 26).diffMonths(date), -108);
_assertPred!"=="(Date(1990, 7, 31).diffMonths(date), -108);
_assertPred!"=="(Date(1990, 8, 1).diffMonths(date), -107);
//Test B.C.
auto dateBC = Date(-1999, 7, 6);
_assertPred!"=="(dateBC.diffMonths(Date(-2000, 6, 5)), 13);
_assertPred!"=="(dateBC.diffMonths(Date(-2000, 7, 5)), 12);
_assertPred!"=="(dateBC.diffMonths(Date(-2000, 8, 5)), 11);
_assertPred!"=="(dateBC.diffMonths(Date(-2000, 9, 5)), 10);
_assertPred!"=="(dateBC.diffMonths(Date(-2000, 10, 5)), 9);
_assertPred!"=="(dateBC.diffMonths(Date(-2000, 11, 5)), 8);
_assertPred!"=="(dateBC.diffMonths(Date(-2000, 12, 5)), 7);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 1, 5)), 6);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 2, 6)), 5);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 3, 6)), 4);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 4, 6)), 3);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 5, 6)), 2);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 6, 6)), 1);
_assertPred!"=="(dateBC.diffMonths(dateBC), 0);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 8, 6)), -1);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 9, 6)), -2);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 10, 6)), -3);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 11, 6)), -4);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 12, 6)), -5);
_assertPred!"=="(dateBC.diffMonths(Date(-1998, 1, 6)), -6);
_assertPred!"=="(dateBC.diffMonths(Date(-1998, 2, 6)), -7);
_assertPred!"=="(dateBC.diffMonths(Date(-1998, 3, 6)), -8);
_assertPred!"=="(dateBC.diffMonths(Date(-1998, 4, 6)), -9);
_assertPred!"=="(dateBC.diffMonths(Date(-1998, 5, 6)), -10);
_assertPred!"=="(dateBC.diffMonths(Date(-1998, 6, 6)), -11);
_assertPred!"=="(dateBC.diffMonths(Date(-1998, 7, 6)), -12);
_assertPred!"=="(dateBC.diffMonths(Date(-1998, 8, 6)), -13);
_assertPred!"=="(Date(-2000, 6, 5).diffMonths(dateBC), -13);
_assertPred!"=="(Date(-2000, 7, 5).diffMonths(dateBC), -12);
_assertPred!"=="(Date(-2000, 8, 5).diffMonths(dateBC), -11);
_assertPred!"=="(Date(-2000, 9, 5).diffMonths(dateBC), -10);
_assertPred!"=="(Date(-2000, 10, 5).diffMonths(dateBC), -9);
_assertPred!"=="(Date(-2000, 11, 5).diffMonths(dateBC), -8);
_assertPred!"=="(Date(-2000, 12, 5).diffMonths(dateBC), -7);
_assertPred!"=="(Date(-1999, 1, 5).diffMonths(dateBC), -6);
_assertPred!"=="(Date(-1999, 2, 6).diffMonths(dateBC), -5);
_assertPred!"=="(Date(-1999, 3, 6).diffMonths(dateBC), -4);
_assertPred!"=="(Date(-1999, 4, 6).diffMonths(dateBC), -3);
_assertPred!"=="(Date(-1999, 5, 6).diffMonths(dateBC), -2);
_assertPred!"=="(Date(-1999, 6, 6).diffMonths(dateBC), -1);
_assertPred!"=="(Date(-1999, 8, 6).diffMonths(dateBC), 1);
_assertPred!"=="(Date(-1999, 9, 6).diffMonths(dateBC), 2);
_assertPred!"=="(Date(-1999, 10, 6).diffMonths(dateBC), 3);
_assertPred!"=="(Date(-1999, 11, 6).diffMonths(dateBC), 4);
_assertPred!"=="(Date(-1999, 12, 6).diffMonths(dateBC), 5);
_assertPred!"=="(Date(-1998, 1, 6).diffMonths(dateBC), 6);
_assertPred!"=="(Date(-1998, 2, 6).diffMonths(dateBC), 7);
_assertPred!"=="(Date(-1998, 3, 6).diffMonths(dateBC), 8);
_assertPred!"=="(Date(-1998, 4, 6).diffMonths(dateBC), 9);
_assertPred!"=="(Date(-1998, 5, 6).diffMonths(dateBC), 10);
_assertPred!"=="(Date(-1998, 6, 6).diffMonths(dateBC), 11);
_assertPred!"=="(Date(-1998, 7, 6).diffMonths(dateBC), 12);
_assertPred!"=="(Date(-1998, 8, 6).diffMonths(dateBC), 13);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 6, 30)), 1);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 7, 1)), 0);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 7, 6)), 0);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 7, 11)), 0);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 7, 16)), 0);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 7, 21)), 0);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 7, 26)), 0);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 7, 31)), 0);
_assertPred!"=="(dateBC.diffMonths(Date(-1999, 8, 1)), -1);
_assertPred!"=="(dateBC.diffMonths(Date(-2008, 6, 30)), 109);
_assertPred!"=="(dateBC.diffMonths(Date(-2008, 7, 1)), 108);
_assertPred!"=="(dateBC.diffMonths(Date(-2008, 7, 6)), 108);
_assertPred!"=="(dateBC.diffMonths(Date(-2008, 7, 11)), 108);
_assertPred!"=="(dateBC.diffMonths(Date(-2008, 7, 16)), 108);
_assertPred!"=="(dateBC.diffMonths(Date(-2008, 7, 21)), 108);
_assertPred!"=="(dateBC.diffMonths(Date(-2008, 7, 26)), 108);
_assertPred!"=="(dateBC.diffMonths(Date(-2008, 7, 31)), 108);
_assertPred!"=="(dateBC.diffMonths(Date(-2008, 8, 1)), 107);
_assertPred!"=="(Date(-1999, 6, 30).diffMonths(dateBC), -1);
_assertPred!"=="(Date(-1999, 7, 1).diffMonths(dateBC), 0);
_assertPred!"=="(Date(-1999, 7, 6).diffMonths(dateBC), 0);
_assertPred!"=="(Date(-1999, 7, 11).diffMonths(dateBC), 0);
_assertPred!"=="(Date(-1999, 7, 16).diffMonths(dateBC), 0);
_assertPred!"=="(Date(-1999, 7, 21).diffMonths(dateBC), 0);
_assertPred!"=="(Date(-1999, 7, 26).diffMonths(dateBC), 0);
_assertPred!"=="(Date(-1999, 7, 31).diffMonths(dateBC), 0);
_assertPred!"=="(Date(-1999, 8, 1).diffMonths(dateBC), 1);
_assertPred!"=="(Date(-2008, 6, 30).diffMonths(dateBC), -109);
_assertPred!"=="(Date(-2008, 7, 1).diffMonths(dateBC), -108);
_assertPred!"=="(Date(-2008, 7, 6).diffMonths(dateBC), -108);
_assertPred!"=="(Date(-2008, 7, 11).diffMonths(dateBC), -108);
_assertPred!"=="(Date(-2008, 7, 16).diffMonths(dateBC), -108);
_assertPred!"=="(Date(-2008, 7, 21).diffMonths(dateBC), -108);
_assertPred!"=="(Date(-2008, 7, 26).diffMonths(dateBC), -108);
_assertPred!"=="(Date(-2008, 7, 31).diffMonths(dateBC), -108);
_assertPred!"=="(Date(-2008, 8, 1).diffMonths(dateBC), -107);
//Test Both
_assertPred!"=="(Date(3, 3, 3).diffMonths(Date(-5, 5, 5)), 94);
_assertPred!"=="(Date(-5, 5, 5).diffMonths(Date(3, 3, 3)), -94);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, date.diffMonths(date)));
static assert(__traits(compiles, cdate.diffMonths(date)));
static assert(__traits(compiles, idate.diffMonths(date)));
static assert(__traits(compiles, date.diffMonths(cdate)));
static assert(__traits(compiles, cdate.diffMonths(cdate)));
static assert(__traits(compiles, idate.diffMonths(cdate)));
static assert(__traits(compiles, date.diffMonths(idate)));
static assert(__traits(compiles, cdate.diffMonths(idate)));
static assert(__traits(compiles, idate.diffMonths(idate)));
//Verify Examples.
assert(Date(1999, 2, 1).diffMonths(Date(1999, 1, 31)) == 1);
assert(Date(1999, 1, 31).diffMonths(Date(1999, 2, 1)) == -1);
assert(Date(1999, 3, 1).diffMonths(Date(1999, 1, 1)) == 2);
assert(Date(1999, 1, 1).diffMonths(Date(1999, 3, 31)) == -2);
}
}
/++
Whether this $(D Date) is in a leap year.
+/
@property bool isLeapYear() const pure nothrow
{
return yearIsLeapYear(_year);
}
unittest
{
version(testStdDateTime)
{
auto date = Date(1999, 7, 6);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, date.isLeapYear = true));
static assert(!__traits(compiles, cdate.isLeapYear = true));
static assert(!__traits(compiles, idate.isLeapYear = true));
}
}
/++
Day of the week this $(D Date) is on.
+/
@property DayOfWeek dayOfWeek() const pure nothrow
{
return getDayOfWeek(dayOfGregorianCal);
}
unittest
{
version(testStdDateTime)
{
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.dayOfWeek == DayOfWeek.sun));
static assert(!__traits(compiles, cdate.dayOfWeek = DayOfWeek.sun));
static assert(__traits(compiles, idate.dayOfWeek == DayOfWeek.sun));
static assert(!__traits(compiles, idate.dayOfWeek = DayOfWeek.sun));
}
}
/++
Day of the year this $(D Date) is on.
Examples:
--------------------
assert(Date(1999, 1, 1).dayOfYear == 1);
assert(Date(1999, 12, 31).dayOfYear == 365);
assert(Date(2000, 12, 31).dayOfYear == 366);
--------------------
+/
@property ushort dayOfYear() const pure nothrow
{
switch(_month)
{
case Month.jan:
return _day;
case Month.feb:
return cast(ushort)(31 + _day);
case Month.mar:
return cast(ushort)((isLeapYear ? 60 : 59) + _day);
case Month.apr:
return cast(ushort)((isLeapYear ? 91 : 90) + _day);
case Month.may:
return cast(ushort)((isLeapYear ? 121 : 120) + _day);
case Month.jun:
return cast(ushort)((isLeapYear ? 152 : 151) + _day);
case Month.jul:
return cast(ushort)((isLeapYear ? 182 : 181) + _day);
case Month.aug:
return cast(ushort)((isLeapYear ? 213 : 212) + _day);
case Month.sep:
return cast(ushort)((isLeapYear ? 244 : 243) + _day);
case Month.oct:
return cast(ushort)((isLeapYear ? 274 : 273) + _day);
case Month.nov:
return cast(ushort)((isLeapYear ? 305 : 304) + _day);
case Month.dec:
return cast(ushort)((isLeapYear ? 335 : 334) + _day);
default:
assert(0, "Invalid month.");
}
}
//Verify Examples.
version(testStdDateTime) unittest
{
assert(Date(1999, 1, 1).dayOfYear == 1);
assert(Date(1999, 12, 31).dayOfYear == 365);
assert(Date(2000, 12, 31).dayOfYear == 366);
}
version(testStdDateTime) unittest
{
foreach(year; filter!((a){return !yearIsLeapYear(a);})
(chain(testYearsBC, testYearsAD)))
{
foreach(doy; testDaysOfYear)
{
_assertPred!"=="(Date(year, doy.md.month, doy.md.day).dayOfYear,
doy.day);
}
}
foreach(year; filter!((a){return yearIsLeapYear(a);})
(chain(testYearsBC, testYearsAD)))
{
foreach(doy; testDaysOfLeapYear)
{
_assertPred!"=="(Date(year, doy.md.month, doy.md.day).dayOfYear,
doy.day);
}
}
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.dayOfYear == 187));
static assert(__traits(compiles, idate.dayOfYear == 187));
}
/++
Day of the year.
Params:
day = The day of the year to set which day of the year this
$(D Date) is on.
Throws:
$(D DateTimeException) if the given day is an invalid day of the
year.
+/
@property void dayOfYear(int day) pure
{
if(isLeapYear)
{
if(day <= 0 || day > daysInLeapYear)
throw new DateTimeException("Invalid day of the year.");
switch(day)
{
case 1: .. case 31:
{
_month = Month.jan;
_day = cast(ubyte)day;
break;
}
case 32: .. case 60:
{
_month = Month.feb;
_day = cast(ubyte)(day - 31);
break;
}
case 61: .. case 91:
{
_month = Month.mar;
_day = cast(ubyte)(day - 60);
break;
}
case 92: .. case 121:
{
_month = Month.apr;
_day = cast(ubyte)(day - 91);
break;
}
case 122: .. case 152:
{
_month = Month.may;
_day = cast(ubyte)(day - 121);
break;
}
case 153: .. case 182:
{
_month = Month.jun;
_day = cast(ubyte)(day - 152);
break;
}
case 183: .. case 213:
{
_month = Month.jul;
_day = cast(ubyte)(day - 182);
break;
}
case 214: .. case 244:
{
_month = Month.aug;
_day = cast(ubyte)(day - 213);
break;
}
case 245: .. case 274:
{
_month = Month.sep;
_day = cast(ubyte)(day - 244);
break;
}
case 275: .. case 305:
{
_month = Month.oct;
_day = cast(ubyte)(day - 274);
break;
}
case 306: .. case 335:
{
_month = Month.nov;
_day = cast(ubyte)(day - 305);
break;
}
case 336: .. case 366:
{
_month = Month.dec;
_day = cast(ubyte)(day - 335);
break;
}
default:
assert(0, "Invalid day of the year.");
}
}
else
{
if(day <= 0 || day > daysInYear)
throw new DateTimeException("Invalid day of the year.");
switch(day)
{
case 1: .. case 31:
{
_month = Month.jan;
_day = cast(ubyte)day;
break;
}
case 32: .. case 59:
{
_month = Month.feb;
_day = cast(ubyte)(day - 31);
break;
}
case 60: .. case 90:
{
_month = Month.mar;
_day = cast(ubyte)(day - 59);
break;
}
case 91: .. case 120:
{
_month = Month.apr;
_day = cast(ubyte)(day - 90);
break;
}
case 121: .. case 151:
{
_month = Month.may;
_day = cast(ubyte)(day - 120);
break;
}
case 152: .. case 181:
{
_month = Month.jun;
_day = cast(ubyte)(day - 151);
break;
}
case 182: .. case 212:
{
_month = Month.jul;
_day = cast(ubyte)(day - 181);
break;
}
case 213: .. case 243:
{
_month = Month.aug;
_day = cast(ubyte)(day - 212);
break;
}
case 244: .. case 273:
{
_month = Month.sep;
_day = cast(ubyte)(day - 243);
break;
}
case 274: .. case 304:
{
_month = Month.oct;
_day = cast(ubyte)(day - 273);
break;
}
case 305: .. case 334:
{
_month = Month.nov;
_day = cast(ubyte)(day - 304);
break;
}
case 335: .. case 365:
{
_month = Month.dec;
_day = cast(ubyte)(day - 334);
break;
}
default:
assert(0, "Invalid day of the year.");
}
}
}
version(testStdDateTime) unittest
{
static void test(Date date, int day, MonthDay expected, size_t line = __LINE__)
{
date.dayOfYear = day;
_assertPred!"=="(date.month, expected.month, "", __FILE__, line);
_assertPred!"=="(date.day, expected.day, "", __FILE__, line);
}
foreach(doy; testDaysOfYear)
{
test(Date(1999, 1, 1), doy.day, doy.md);
test(Date(-1, 1, 1), doy.day, doy.md);
}
foreach(doy; testDaysOfLeapYear)
{
test(Date(2000, 1, 1), doy.day, doy.md);
test(Date(-4, 1, 1), doy.day, doy.md);
}
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.dayOfYear = 187));
static assert(!__traits(compiles, idate.dayOfYear = 187));
}
/++
The Xth day of the Gregorian Calendar that this $(D Date) is on.
Examples:
--------------------
assert(Date(1, 1, 1).dayOfGregorianCal == 1);
assert(Date(1, 12, 31).dayOfGregorianCal == 365);
assert(Date(2, 1, 1).dayOfGregorianCal == 366);
assert(Date(0, 12, 31).dayOfGregorianCal == 0);
assert(Date(0, 1, 1).dayOfGregorianCal == -365);
assert(Date(-1, 12, 31).dayOfGregorianCal == -366);
assert(Date(2000, 1, 1).dayOfGregorianCal == 730_120);
assert(Date(2010, 12, 31).dayOfGregorianCal == 734_137);
--------------------
+/
@property int dayOfGregorianCal() const pure nothrow
{
if(isAD)
{
if(_year == 1)
return dayOfYear;
int years = _year - 1;
auto days = (years / 400) * daysIn400Years;
years %= 400;
days += (years / 100) * daysIn100Years;
years %= 100;
days += (years / 4) * daysIn4Years;
years %= 4;
days += years * daysInYear;
days += dayOfYear;
return days;
}
else if(_year == 0)
return dayOfYear - daysInLeapYear;
else
{
int years = _year;
auto days = (years / 400) * daysIn400Years;
years %= 400;
days += (years / 100) * daysIn100Years;
years %= 100;
days += (years / 4) * daysIn4Years;
years %= 4;
if(years < 0)
{
days -= daysInLeapYear;
++years;
days += years * daysInYear;
days -= daysInYear - dayOfYear;
}
else
days -= daysInLeapYear - dayOfYear;
return days;
}
}
//Verify Examples.
version(testStdDateTime) unittest
{
assert(Date(1, 1, 1).dayOfGregorianCal == 1);
assert(Date(1, 12, 31).dayOfGregorianCal == 365);
assert(Date(2, 1, 1).dayOfGregorianCal == 366);
assert(Date(0, 12, 31).dayOfGregorianCal == 0);
assert(Date(0, 1, 1).dayOfGregorianCal == -365);
assert(Date(-1, 12, 31).dayOfGregorianCal == -366);
assert(Date(2000, 1, 1).dayOfGregorianCal == 730_120);
assert(Date(2010, 12, 31).dayOfGregorianCal == 734_137);
}
version(testStdDateTime) unittest
{
foreach(gd; chain(testGregDaysBC, testGregDaysAD))
_assertPred!"=="(gd.date.dayOfGregorianCal, gd.day);
auto date = Date(1999, 7, 6);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, date.dayOfGregorianCal));
static assert(__traits(compiles, cdate.dayOfGregorianCal));
static assert(__traits(compiles, idate.dayOfGregorianCal));
}
/++
The Xth day of the Gregorian Calendar that this $(D Date) is on.
Params:
day = The day of the Gregorian Calendar to set this $(D Date) to.
Examples:
--------------------
auto date = Date.init;
date.dayOfGregorianCal = 1;
assert(date == Date(1, 1, 1));
date.dayOfGregorianCal = 365;
assert(date == Date(1, 12, 31));
date.dayOfGregorianCal = 366;
assert(date == Date(2, 1, 1));
date.dayOfGregorianCal = 0;
assert(date == Date(0, 12, 31));
date.dayOfGregorianCal = -365;
assert(date == Date(-0, 1, 1));
date.dayOfGregorianCal = -366;
assert(date == Date(-1, 12, 31));
date.dayOfGregorianCal = 730_120;
assert(date == Date(2000, 1, 1));
date.dayOfGregorianCal = 734_137;
assert(date == Date(2010, 12, 31));
--------------------
+/
@property void dayOfGregorianCal(int day) pure nothrow
{
this = Date(day);
}
unittest
{
version(testStdDateTime)
{
{
auto date = Date(1999, 7, 6);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, date.dayOfGregorianCal = 187));
static assert(!__traits(compiles, cdate.dayOfGregorianCal = 187));
static assert(!__traits(compiles, idate.dayOfGregorianCal = 187));
}
//Verify Examples.
{
auto date = Date.init;
date.dayOfGregorianCal = 1;
assert(date == Date(1, 1, 1));
date.dayOfGregorianCal = 365;
assert(date == Date(1, 12, 31));
date.dayOfGregorianCal = 366;
assert(date == Date(2, 1, 1));
date.dayOfGregorianCal = 0;
assert(date == Date(0, 12, 31));
date.dayOfGregorianCal = -365;
assert(date == Date(-0, 1, 1));
date.dayOfGregorianCal = -366;
assert(date == Date(-1, 12, 31));
date.dayOfGregorianCal = 730_120;
assert(date == Date(2000, 1, 1));
date.dayOfGregorianCal = 734_137;
assert(date == Date(2010, 12, 31));
}
}
}
/++
The ISO 8601 week of the year that this $(D Date) is in.
See_Also:
$(WEB en.wikipedia.org/wiki/ISO_week_date, ISO Week Date)
+/
@property ubyte isoWeek() const pure nothrow
{
immutable weekday = dayOfWeek;
immutable adjustedWeekday = weekday == DayOfWeek.sun ? 7 : weekday;
immutable week = (dayOfYear - adjustedWeekday + 10) / 7;
try
{
if(week == 53)
{
switch(Date(_year + 1, 1, 1).dayOfWeek)
{
case DayOfWeek.mon:
case DayOfWeek.tue:
case DayOfWeek.wed:
case DayOfWeek.thu:
return 1;
case DayOfWeek.fri:
case DayOfWeek.sat:
case DayOfWeek.sun:
return 53;
default:
assert(0, "Invalid ISO Week");
}
}
else if(week > 0)
return cast(ubyte)week;
else
return Date(_year - 1, 12, 31).isoWeek;
}
catch(Exception e)
assert(0, "Date's constructor threw.");
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(Date(2009, 12, 28).isoWeek, 53);
_assertPred!"=="(Date(2009, 12, 29).isoWeek, 53);
_assertPred!"=="(Date(2009, 12, 30).isoWeek, 53);
_assertPred!"=="(Date(2009, 12, 31).isoWeek, 53);
_assertPred!"=="(Date(2010, 1, 1).isoWeek, 53);
_assertPred!"=="(Date(2010, 1, 2).isoWeek, 53);
_assertPred!"=="(Date(2010, 1, 3).isoWeek, 53);
_assertPred!"=="(Date(2010, 1, 4).isoWeek, 1);
_assertPred!"=="(Date(2010, 1, 5).isoWeek, 1);
_assertPred!"=="(Date(2010, 1, 6).isoWeek, 1);
_assertPred!"=="(Date(2010, 1, 7).isoWeek, 1);
_assertPred!"=="(Date(2010, 1, 8).isoWeek, 1);
_assertPred!"=="(Date(2010, 1, 9).isoWeek, 1);
_assertPred!"=="(Date(2010, 1, 10).isoWeek, 1);
_assertPred!"=="(Date(2010, 1, 11).isoWeek, 2);
_assertPred!"=="(Date(2010, 12, 31).isoWeek, 52);
_assertPred!"=="(Date(2004, 12, 26).isoWeek, 52);
_assertPred!"=="(Date(2004, 12, 27).isoWeek, 53);
_assertPred!"=="(Date(2004, 12, 28).isoWeek, 53);
_assertPred!"=="(Date(2004, 12, 29).isoWeek, 53);
_assertPred!"=="(Date(2004, 12, 30).isoWeek, 53);
_assertPred!"=="(Date(2004, 12, 31).isoWeek, 53);
_assertPred!"=="(Date(2005, 1, 1).isoWeek, 53);
_assertPred!"=="(Date(2005, 1, 2).isoWeek, 53);
_assertPred!"=="(Date(2005, 12, 31).isoWeek, 52);
_assertPred!"=="(Date(2007, 1, 1).isoWeek, 1);
_assertPred!"=="(Date(2007, 12, 30).isoWeek, 52);
_assertPred!"=="(Date(2007, 12, 31).isoWeek, 1);
_assertPred!"=="(Date(2008, 1, 1).isoWeek, 1);
_assertPred!"=="(Date(2008, 12, 28).isoWeek, 52);
_assertPred!"=="(Date(2008, 12, 29).isoWeek, 1);
_assertPred!"=="(Date(2008, 12, 30).isoWeek, 1);
_assertPred!"=="(Date(2008, 12, 31).isoWeek, 1);
_assertPred!"=="(Date(2009, 1, 1).isoWeek, 1);
_assertPred!"=="(Date(2009, 1, 2).isoWeek, 1);
_assertPred!"=="(Date(2009, 1, 3).isoWeek, 1);
_assertPred!"=="(Date(2009, 1, 4).isoWeek, 1);
//Test B.C.
//The algorithm should work identically for both A.D. and B.C. since
//it doesn't really take the year into account, so B.C. testing
//probably isn't really needed.
_assertPred!"=="(Date(0, 12, 31).isoWeek, 52);
_assertPred!"=="(Date(0, 1, 4).isoWeek, 1);
_assertPred!"=="(Date(0, 1, 1).isoWeek, 52);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.isoWeek == 3));
static assert(!__traits(compiles, cdate.isoWeek = 3));
static assert(__traits(compiles, idate.isoWeek == 3));
static assert(!__traits(compiles, idate.isoWeek = 3));
}
}
/++
$(D Date) for the last day in the month that this $(D Date) is in.
Examples:
--------------------
assert(Date(1999, 1, 6).endOfMonth == Date(1999, 1, 31));
assert(Date(1999, 2, 7).endOfMonth == Date(1999, 2, 28));
assert(Date(2000, 2, 7).endOfMonth == Date(1999, 2, 29));
assert(Date(2000, 6, 4).endOfMonth == Date(1999, 6, 30));
--------------------
+/
@property Date endOfMonth() const pure nothrow
{
try
return Date(_year, _month, maxDay(_year, _month));
catch(Exception e)
assert(0, "Date's constructor threw.");
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(Date(1999, 1, 1).endOfMonth, Date(1999, 1, 31));
_assertPred!"=="(Date(1999, 2, 1).endOfMonth, Date(1999, 2, 28));
_assertPred!"=="(Date(2000, 2, 1).endOfMonth, Date(2000, 2, 29));
_assertPred!"=="(Date(1999, 3, 1).endOfMonth, Date(1999, 3, 31));
_assertPred!"=="(Date(1999, 4, 1).endOfMonth, Date(1999, 4, 30));
_assertPred!"=="(Date(1999, 5, 1).endOfMonth, Date(1999, 5, 31));
_assertPred!"=="(Date(1999, 6, 1).endOfMonth, Date(1999, 6, 30));
_assertPred!"=="(Date(1999, 7, 1).endOfMonth, Date(1999, 7, 31));
_assertPred!"=="(Date(1999, 8, 1).endOfMonth, Date(1999, 8, 31));
_assertPred!"=="(Date(1999, 9, 1).endOfMonth, Date(1999, 9, 30));
_assertPred!"=="(Date(1999, 10, 1).endOfMonth, Date(1999, 10, 31));
_assertPred!"=="(Date(1999, 11, 1).endOfMonth, Date(1999, 11, 30));
_assertPred!"=="(Date(1999, 12, 1).endOfMonth, Date(1999, 12, 31));
//Test B.C.
_assertPred!"=="(Date(-1999, 1, 1).endOfMonth, Date(-1999, 1, 31));
_assertPred!"=="(Date(-1999, 2, 1).endOfMonth, Date(-1999, 2, 28));
_assertPred!"=="(Date(-2000, 2, 1).endOfMonth, Date(-2000, 2, 29));
_assertPred!"=="(Date(-1999, 3, 1).endOfMonth, Date(-1999, 3, 31));
_assertPred!"=="(Date(-1999, 4, 1).endOfMonth, Date(-1999, 4, 30));
_assertPred!"=="(Date(-1999, 5, 1).endOfMonth, Date(-1999, 5, 31));
_assertPred!"=="(Date(-1999, 6, 1).endOfMonth, Date(-1999, 6, 30));
_assertPred!"=="(Date(-1999, 7, 1).endOfMonth, Date(-1999, 7, 31));
_assertPred!"=="(Date(-1999, 8, 1).endOfMonth, Date(-1999, 8, 31));
_assertPred!"=="(Date(-1999, 9, 1).endOfMonth, Date(-1999, 9, 30));
_assertPred!"=="(Date(-1999, 10, 1).endOfMonth, Date(-1999, 10, 31));
_assertPred!"=="(Date(-1999, 11, 1).endOfMonth, Date(-1999, 11, 30));
_assertPred!"=="(Date(-1999, 12, 1).endOfMonth, Date(-1999, 12, 31));
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.endOfMonth = Date(1999, 7, 30)));
static assert(!__traits(compiles, idate.endOfMonth = Date(1999, 7, 30)));
//Verify Examples.
assert(Date(1999, 1, 6).endOfMonth == Date(1999, 1, 31));
assert(Date(1999, 2, 7).endOfMonth == Date(1999, 2, 28));
assert(Date(2000, 2, 7).endOfMonth == Date(2000, 2, 29));
assert(Date(2000, 6, 4).endOfMonth == Date(2000, 6, 30));
}
}
/++
The last day in the month that this $(D Date) is in.
Examples:
--------------------
assert(Date(1999, 1, 6).daysInMonth == 31);
assert(Date(1999, 2, 7).daysInMonth == 28);
assert(Date(2000, 2, 7).daysInMonth == 29);
assert(Date(2000, 6, 4).daysInMonth == 30);
--------------------
+/
@property ubyte daysInMonth() const pure nothrow
{
return maxDay(_year, _month);
}
/++
$(RED Scheduled for deprecation in January 2012.
Please use daysInMonth instead.)
+/
alias daysInMonth endofMonthDay;
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(Date(1999, 1, 1).daysInMonth, 31);
_assertPred!"=="(Date(1999, 2, 1).daysInMonth, 28);
_assertPred!"=="(Date(2000, 2, 1).daysInMonth, 29);
_assertPred!"=="(Date(1999, 3, 1).daysInMonth, 31);
_assertPred!"=="(Date(1999, 4, 1).daysInMonth, 30);
_assertPred!"=="(Date(1999, 5, 1).daysInMonth, 31);
_assertPred!"=="(Date(1999, 6, 1).daysInMonth, 30);
_assertPred!"=="(Date(1999, 7, 1).daysInMonth, 31);
_assertPred!"=="(Date(1999, 8, 1).daysInMonth, 31);
_assertPred!"=="(Date(1999, 9, 1).daysInMonth, 30);
_assertPred!"=="(Date(1999, 10, 1).daysInMonth, 31);
_assertPred!"=="(Date(1999, 11, 1).daysInMonth, 30);
_assertPred!"=="(Date(1999, 12, 1).daysInMonth, 31);
//Test B.C.
_assertPred!"=="(Date(-1999, 1, 1).daysInMonth, 31);
_assertPred!"=="(Date(-1999, 2, 1).daysInMonth, 28);
_assertPred!"=="(Date(-2000, 2, 1).daysInMonth, 29);
_assertPred!"=="(Date(-1999, 3, 1).daysInMonth, 31);
_assertPred!"=="(Date(-1999, 4, 1).daysInMonth, 30);
_assertPred!"=="(Date(-1999, 5, 1).daysInMonth, 31);
_assertPred!"=="(Date(-1999, 6, 1).daysInMonth, 30);
_assertPred!"=="(Date(-1999, 7, 1).daysInMonth, 31);
_assertPred!"=="(Date(-1999, 8, 1).daysInMonth, 31);
_assertPred!"=="(Date(-1999, 9, 1).daysInMonth, 30);
_assertPred!"=="(Date(-1999, 10, 1).daysInMonth, 31);
_assertPred!"=="(Date(-1999, 11, 1).daysInMonth, 30);
_assertPred!"=="(Date(-1999, 12, 1).daysInMonth, 31);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.daysInMonth = 30));
static assert(!__traits(compiles, idate.daysInMonth = 30));
//Verify Examples.
assert(Date(1999, 1, 6).daysInMonth == 31);
assert(Date(1999, 2, 7).daysInMonth == 28);
assert(Date(2000, 2, 7).daysInMonth == 29);
assert(Date(2000, 6, 4).daysInMonth == 30);
}
}
/++
Whether the current year is a date in A.D.
Examples:
--------------------
assert(Date(1, 1, 1).isAD);
assert(Date(2010, 12, 31).isAD);
assert(!Date(0, 12, 31).isAD);
assert(!Date(-2010, 1, 1).isAD);
--------------------
+/
@property bool isAD() const pure nothrow
{
return _year > 0;
}
unittest
{
version(testStdDateTime)
{
assert(Date(2010, 7, 4).isAD);
assert(Date(1, 1, 1).isAD);
assert(!Date(0, 1, 1).isAD);
assert(!Date(-1, 1, 1).isAD);
assert(!Date(-2010, 7, 4).isAD);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.isAD));
static assert(__traits(compiles, idate.isAD));
//Verify Examples.
assert(Date(1, 1, 1).isAD);
assert(Date(2010, 12, 31).isAD);
assert(!Date(0, 12, 31).isAD);
assert(!Date(-2010, 1, 1).isAD);
}
}
/++
The julian day for this $(D Date) at noon (since the julian day changes
at noon).
+/
@property long julianDay() const pure nothrow
{
return dayOfGregorianCal + 1_721_425;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(Date(-4713, 11, 24).julianDay, 0);
_assertPred!"=="(Date(0, 12, 31).julianDay, 1_721_425);
_assertPred!"=="(Date(1, 1, 1).julianDay, 1_721_426);
_assertPred!"=="(Date(1582, 10, 15).julianDay, 2_299_161);
_assertPred!"=="(Date(1858, 11, 17).julianDay, 2_400_001);
_assertPred!"=="(Date(1982, 1, 4).julianDay, 2_444_974);
_assertPred!"=="(Date(1996, 3, 31).julianDay, 2_450_174);
_assertPred!"=="(Date(2010, 8, 24).julianDay, 2_455_433);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.julianDay));
static assert(__traits(compiles, idate.julianDay));
}
}
/++
The modified julian day for any time on this date (since, the modified
julian day changes at midnight).
+/
@property long modJulianDay() const pure nothrow
{
return julianDay - 2_400_001;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(Date(1858, 11, 17).modJulianDay, 0);
_assertPred!"=="(Date(2010, 8, 24).modJulianDay, 55_432);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.modJulianDay));
static assert(__traits(compiles, idate.modJulianDay));
}
}
/++
Converts this $(D Date) to a string with the format YYYYMMDD.
Examples:
--------------------
assert(Date(2010, 7, 4).toISOString() == "20100704");
assert(Date(1998, 12, 25).toISOString() == "19981225");
assert(Date(0, 1, 5).toISOString() == "00000105");
assert(Date(-4, 1, 5).toISOString() == "-00040105");
--------------------
+/
string toISOString() const nothrow
{
try
{
if(_year >= 0)
{
if(_year < 10_000)
return format("%04d%02d%02d", _year, _month, _day);
else
return format("+%05d%02d%02d", _year, _month, _day);
}
else if(_year > -10_000)
return format("%05d%02d%02d", _year, _month, _day);
else
return format("%06d%02d%02d", _year, _month, _day);
}
catch(Exception e)
assert(0, "format() threw.");
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(Date(9, 12, 4).toISOString(), "00091204");
_assertPred!"=="(Date(99, 12, 4).toISOString(), "00991204");
_assertPred!"=="(Date(999, 12, 4).toISOString(), "09991204");
_assertPred!"=="(Date(9999, 7, 4).toISOString(), "99990704");
_assertPred!"=="(Date(10000, 10, 20).toISOString(), "+100001020");
//Test B.C.
_assertPred!"=="(Date(0, 12, 4).toISOString(), "00001204");
_assertPred!"=="(Date(-9, 12, 4).toISOString(), "-00091204");
_assertPred!"=="(Date(-99, 12, 4).toISOString(), "-00991204");
_assertPred!"=="(Date(-999, 12, 4).toISOString(), "-09991204");
_assertPred!"=="(Date(-9999, 7, 4).toISOString(), "-99990704");
_assertPred!"=="(Date(-10000, 10, 20).toISOString(), "-100001020");
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.toISOString()));
static assert(__traits(compiles, idate.toISOString()));
//Verify Examples.
assert(Date(2010, 7, 4).toISOString() == "20100704");
assert(Date(1998, 12, 25).toISOString() == "19981225");
assert(Date(0, 1, 5).toISOString() == "00000105");
assert(Date(-4, 1, 5).toISOString() == "-00040105");
}
}
/++
Converts this $(D Date) to a string with the format YYYY-MM-DD.
Examples:
--------------------
assert(Date(2010, 7, 4).toISOExtString() == "2010-07-04");
assert(Date(1998, 12, 25).toISOExtString() == "1998-12-25");
assert(Date(0, 1, 5).toISOExtString() == "0000-01-05");
assert(Date(-4, 1, 5).toISOExtString() == "-0004-01-05");
--------------------
+/
string toISOExtString() const nothrow
{
try
{
if(_year >= 0)
{
if(_year < 10_000)
return format("%04d-%02d-%02d", _year, _month, _day);
else
return format("+%05d-%02d-%02d", _year, _month, _day);
}
else if(_year > -10_000)
return format("%05d-%02d-%02d", _year, _month, _day);
else
return format("%06d-%02d-%02d", _year, _month, _day);
}
catch(Exception e)
assert(0, "format() threw.");
}
/++
$(RED Scheduled for deprecation in November 2011.
Please use toISOExtString instead.)
+/
alias toISOExtString toISOExtendedString;
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(Date(9, 12, 4).toISOExtString(), "0009-12-04");
_assertPred!"=="(Date(99, 12, 4).toISOExtString(), "0099-12-04");
_assertPred!"=="(Date(999, 12, 4).toISOExtString(), "0999-12-04");
_assertPred!"=="(Date(9999, 7, 4).toISOExtString(), "9999-07-04");
_assertPred!"=="(Date(10000, 10, 20).toISOExtString(), "+10000-10-20");
//Test B.C.
_assertPred!"=="(Date(0, 12, 4).toISOExtString(), "0000-12-04");
_assertPred!"=="(Date(-9, 12, 4).toISOExtString(), "-0009-12-04");
_assertPred!"=="(Date(-99, 12, 4).toISOExtString(), "-0099-12-04");
_assertPred!"=="(Date(-999, 12, 4).toISOExtString(), "-0999-12-04");
_assertPred!"=="(Date(-9999, 7, 4).toISOExtString(), "-9999-07-04");
_assertPred!"=="(Date(-10000, 10, 20).toISOExtString(), "-10000-10-20");
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.toISOExtString()));
static assert(__traits(compiles, idate.toISOExtString()));
//Verify Examples.
assert(Date(2010, 7, 4).toISOExtString() == "2010-07-04");
assert(Date(1998, 12, 25).toISOExtString() == "1998-12-25");
assert(Date(0, 1, 5).toISOExtString() == "0000-01-05");
assert(Date(-4, 1, 5).toISOExtString() == "-0004-01-05");
}
}
/++
Converts this $(D Date) to a string with the format YYYY-Mon-DD.
Examples:
--------------------
assert(Date(2010, 7, 4).toSimpleString() == "2010-Jul-04");
assert(Date(1998, 12, 25).toSimpleString() == "1998-Dec-25");
assert(Date(0, 1, 5).toSimpleString() == "0000-Jan-05");
assert(Date(-4, 1, 5).toSimpleString() == "-0004-Jan-05");
--------------------
+/
string toSimpleString() const nothrow
{
try
{
if(_year >= 0)
{
if(_year < 10_000)
return format("%04d-%s-%02d", _year, monthToString(_month, false), _day);
else
return format("+%05d-%s-%02d", _year, monthToString(_month, false), _day);
}
else if(_year > -10_000)
return format("%05d-%s-%02d", _year, monthToString(_month, false), _day);
else
return format("%06d-%s-%02d", _year, monthToString(_month, false), _day);
}
catch(Exception e)
assert(0, "format() threw.");
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(Date(9, 12, 4).toSimpleString(), "0009-Dec-04");
_assertPred!"=="(Date(99, 12, 4).toSimpleString(), "0099-Dec-04");
_assertPred!"=="(Date(999, 12, 4).toSimpleString(), "0999-Dec-04");
_assertPred!"=="(Date(9999, 7, 4).toSimpleString(), "9999-Jul-04");
_assertPred!"=="(Date(10000, 10, 20).toSimpleString(), "+10000-Oct-20");
//Test B.C.
_assertPred!"=="(Date(0, 12, 4).toSimpleString(), "0000-Dec-04");
_assertPred!"=="(Date(-9, 12, 4).toSimpleString(), "-0009-Dec-04");
_assertPred!"=="(Date(-99, 12, 4).toSimpleString(), "-0099-Dec-04");
_assertPred!"=="(Date(-999, 12, 4).toSimpleString(), "-0999-Dec-04");
_assertPred!"=="(Date(-9999, 7, 4).toSimpleString(), "-9999-Jul-04");
_assertPred!"=="(Date(-10000, 10, 20).toSimpleString(), "-10000-Oct-20");
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, cdate.toSimpleString()));
static assert(__traits(compiles, idate.toSimpleString()));
//Verify Examples.
assert(Date(2010, 7, 4).toSimpleString() == "2010-Jul-04");
assert(Date(1998, 12, 25).toSimpleString() == "1998-Dec-25");
assert(Date(0, 1, 5).toSimpleString() == "0000-Jan-05");
assert(Date(-4, 1, 5).toSimpleString() == "-0004-Jan-05");
}
}
//TODO Add a function which returns a string in a user-specified format.
/+
Converts this $(D Date) to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString()
{
return toSimpleString();
}
/++
Converts this $(D Date) to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString() const nothrow
{
return toSimpleString();
}
unittest
{
version(testStdDateTime)
{
auto date = Date(1999, 7, 6);
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(__traits(compiles, date.toString()));
static assert(__traits(compiles, cdate.toString()));
static assert(__traits(compiles, idate.toString()));
}
}
/++
Creates a $(D Date) from a string with the format YYYYMMDD. Whitespace
is stripped from the given string.
Params:
isoString = A string formatted in the ISO format for dates.
Throws:
$(D DateTimeException) if the given string is not in the ISO format
or if the resulting $(D Date) would not be valid.
Examples:
--------------------
assert(Date.fromISOString("20100704") == Date(2010, 7, 4));
assert(Date.fromISOString("19981225") == Date(1998, 12, 25));
assert(Date.fromISOString("00000105") == Date(0, 1, 5));
assert(Date.fromISOString("-00040105") == Date(-4, 1, 5));
assert(Date.fromISOString(" 20100704 ") == Date(2010, 7, 4));
--------------------
+/
static Date fromISOString(S)(in S isoString)
if(isSomeString!S)
{
auto dstr = to!dstring(strip(isoString));
enforce(dstr.length >= 8, new DateTimeException(format("Invalid ISO String: %s", isoString)));
auto day = dstr[$-2 .. $];
auto month = dstr[$-4 .. $-2];
auto year = dstr[0 .. $-4];
enforce(!canFind!(not!isDigit)(day), new DateTimeException(format("Invalid ISO String: %s", isoString)));
enforce(!canFind!(not!isDigit)(month), new DateTimeException(format("Invalid ISO String: %s", isoString)));
if(year.length > 4)
{
enforce(year.startsWith("-") || year.startsWith("+"),
new DateTimeException(format("Invalid ISO String: %s", isoString)));
enforce(!canFind!(not!isDigit)(year[1..$]),
new DateTimeException(format("Invalid ISO String: %s", isoString)));
}
else
enforce(!canFind!(not!isDigit)(year), new DateTimeException(format("Invalid ISO String: %s", isoString)));
return Date(to!short(year), to!ubyte(month), to!ubyte(day));
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(Date.fromISOString(""));
assertThrown!DateTimeException(Date.fromISOString("990704"));
assertThrown!DateTimeException(Date.fromISOString("0100704"));
assertThrown!DateTimeException(Date.fromISOString("2010070"));
assertThrown!DateTimeException(Date.fromISOString("2010070 "));
assertThrown!DateTimeException(Date.fromISOString("120100704"));
assertThrown!DateTimeException(Date.fromISOString("-0100704"));
assertThrown!DateTimeException(Date.fromISOString("+0100704"));
assertThrown!DateTimeException(Date.fromISOString("2010070a"));
assertThrown!DateTimeException(Date.fromISOString("20100a04"));
assertThrown!DateTimeException(Date.fromISOString("2010a704"));
assertThrown!DateTimeException(Date.fromISOString("99-07-04"));
assertThrown!DateTimeException(Date.fromISOString("010-07-04"));
assertThrown!DateTimeException(Date.fromISOString("2010-07-0"));
assertThrown!DateTimeException(Date.fromISOString("2010-07-0 "));
assertThrown!DateTimeException(Date.fromISOString("12010-07-04"));
assertThrown!DateTimeException(Date.fromISOString("-010-07-04"));
assertThrown!DateTimeException(Date.fromISOString("+010-07-04"));
assertThrown!DateTimeException(Date.fromISOString("2010-07-0a"));
assertThrown!DateTimeException(Date.fromISOString("2010-0a-04"));
assertThrown!DateTimeException(Date.fromISOString("2010-a7-04"));
assertThrown!DateTimeException(Date.fromISOString("2010/07/04"));
assertThrown!DateTimeException(Date.fromISOString("2010/7/04"));
assertThrown!DateTimeException(Date.fromISOString("2010/7/4"));
assertThrown!DateTimeException(Date.fromISOString("2010/07/4"));
assertThrown!DateTimeException(Date.fromISOString("2010-7-04"));
assertThrown!DateTimeException(Date.fromISOString("2010-7-4"));
assertThrown!DateTimeException(Date.fromISOString("2010-07-4"));
assertThrown!DateTimeException(Date.fromISOString("99Jul04"));
assertThrown!DateTimeException(Date.fromISOString("010Jul04"));
assertThrown!DateTimeException(Date.fromISOString("2010Jul0"));
assertThrown!DateTimeException(Date.fromISOString("2010Jul0 "));
assertThrown!DateTimeException(Date.fromISOString("12010Jul04"));
assertThrown!DateTimeException(Date.fromISOString("-010Jul04"));
assertThrown!DateTimeException(Date.fromISOString("+010Jul04"));
assertThrown!DateTimeException(Date.fromISOString("2010Jul0a"));
assertThrown!DateTimeException(Date.fromISOString("2010Jua04"));
assertThrown!DateTimeException(Date.fromISOString("2010aul04"));
assertThrown!DateTimeException(Date.fromISOString("99-Jul-04"));
assertThrown!DateTimeException(Date.fromISOString("010-Jul-04"));
assertThrown!DateTimeException(Date.fromISOString("2010-Jul-0"));
assertThrown!DateTimeException(Date.fromISOString("2010-Jul-0 "));
assertThrown!DateTimeException(Date.fromISOString("12010-Jul-04"));
assertThrown!DateTimeException(Date.fromISOString("-010-Jul-04"));
assertThrown!DateTimeException(Date.fromISOString("+010-Jul-04"));
assertThrown!DateTimeException(Date.fromISOString("2010-Jul-0a"));
assertThrown!DateTimeException(Date.fromISOString("2010-Jua-04"));
assertThrown!DateTimeException(Date.fromISOString("2010-Jal-04"));
assertThrown!DateTimeException(Date.fromISOString("2010-aul-04"));
assertThrown!DateTimeException(Date.fromISOString("2010-07-04"));
assertThrown!DateTimeException(Date.fromISOString("2010-Jul-04"));
_assertPred!"=="(Date.fromISOString("19990706"), Date(1999, 7, 6));
_assertPred!"=="(Date.fromISOString("-19990706"), Date(-1999, 7, 6));
_assertPred!"=="(Date.fromISOString("+019990706"), Date(1999, 7, 6));
_assertPred!"=="(Date.fromISOString("19990706 "), Date(1999, 7, 6));
_assertPred!"=="(Date.fromISOString(" 19990706"), Date(1999, 7, 6));
_assertPred!"=="(Date.fromISOString(" 19990706 "), Date(1999, 7, 6));
//Verify Examples.
assert(Date.fromISOString("20100704") == Date(2010, 7, 4));
assert(Date.fromISOString("19981225") == Date(1998, 12, 25));
assert(Date.fromISOString("00000105") == Date(0, 1, 5));
assert(Date.fromISOString("-00040105") == Date(-4, 1, 5));
assert(Date.fromISOString(" 20100704 ") == Date(2010, 7, 4));
}
}
/++
Creates a $(D Date) from a string with the format YYYY-MM-DD. Whitespace
is stripped from the given string.
Params:
isoExtString = A string formatted in the ISO Extended format for
dates.
Throws:
$(D DateTimeException) if the given string is not in the ISO
Extended format or if the resulting $(D Date) would not be valid.
Examples:
--------------------
assert(Date.fromISOExtString("2010-07-04") == Date(2010, 7, 4));
assert(Date.fromISOExtString("1998-12-25") == Date(1998, 12, 25));
assert(Date.fromISOExtString("0000-01-05") == Date(0, 1, 5));
assert(Date.fromISOExtString("-0004-01-05") == Date(-4, 1, 5));
assert(Date.fromISOExtString(" 2010-07-04 ") == Date(2010, 7, 4));
--------------------
+/
static Date fromISOExtString(S)(in S isoExtString)
if(isSomeString!(S))
{
auto dstr = to!dstring(strip(isoExtString));
enforce(dstr.length >= 10, new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
auto day = dstr[$-2 .. $];
auto month = dstr[$-5 .. $-3];
auto year = dstr[0 .. $-6];
enforce(dstr[$-3] == '-', new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
enforce(dstr[$-6] == '-', new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
enforce(!canFind!(not!isDigit)(day),
new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
enforce(!canFind!(not!isDigit)(month),
new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
if(year.length > 4)
{
enforce(year.startsWith("-") || year.startsWith("+"),
new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
enforce(!canFind!(not!isDigit)(year[1..$]),
new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
}
else
enforce(!canFind!(not!isDigit)(year),
new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
return Date(to!short(year), to!ubyte(month), to!ubyte(day));
}
/++
$(RED Scheduled for deprecation in November 2011.
Please use fromISOExtString instead.)
+/
static Date fromISOExtendedString(S)(in S isoExtString)
if(isSomeString!(S))
{
pragma(msg, softDeprec!("2.053", "November 2011", "fromISOExtendedString", "fromISOExtString"));
return fromISOExtString!string(isoExtString);
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(Date.fromISOExtString(""));
assertThrown!DateTimeException(Date.fromISOExtString("990704"));
assertThrown!DateTimeException(Date.fromISOExtString("0100704"));
assertThrown!DateTimeException(Date.fromISOExtString("2010070"));
assertThrown!DateTimeException(Date.fromISOExtString("2010070 "));
assertThrown!DateTimeException(Date.fromISOExtString("120100704"));
assertThrown!DateTimeException(Date.fromISOExtString("-0100704"));
assertThrown!DateTimeException(Date.fromISOExtString("+0100704"));
assertThrown!DateTimeException(Date.fromISOExtString("2010070a"));
assertThrown!DateTimeException(Date.fromISOExtString("20100a04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010a704"));
assertThrown!DateTimeException(Date.fromISOExtString("99-07-04"));
assertThrown!DateTimeException(Date.fromISOExtString("010-07-04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-07-0"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-07-0 "));
assertThrown!DateTimeException(Date.fromISOExtString("12010-07-04"));
assertThrown!DateTimeException(Date.fromISOExtString("-010-07-04"));
assertThrown!DateTimeException(Date.fromISOExtString("+010-07-04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-07-0a"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-0a-04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-a7-04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010/07/04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010/7/04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010/7/4"));
assertThrown!DateTimeException(Date.fromISOExtString("2010/07/4"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-7-04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-7-4"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-07-4"));
assertThrown!DateTimeException(Date.fromISOExtString("99Jul04"));
assertThrown!DateTimeException(Date.fromISOExtString("010Jul04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010Jul0"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-Jul-0 "));
assertThrown!DateTimeException(Date.fromISOExtString("12010Jul04"));
assertThrown!DateTimeException(Date.fromISOExtString("-010Jul04"));
assertThrown!DateTimeException(Date.fromISOExtString("+010Jul04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010Jul0a"));
assertThrown!DateTimeException(Date.fromISOExtString("2010Jua04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010aul04"));
assertThrown!DateTimeException(Date.fromISOExtString("99-Jul-04"));
assertThrown!DateTimeException(Date.fromISOExtString("010-Jul-04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-Jul-0"));
assertThrown!DateTimeException(Date.fromISOExtString("2010Jul0 "));
assertThrown!DateTimeException(Date.fromISOExtString("12010-Jul-04"));
assertThrown!DateTimeException(Date.fromISOExtString("-010-Jul-04"));
assertThrown!DateTimeException(Date.fromISOExtString("+010-Jul-04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-Jul-0a"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-Jua-04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-Jal-04"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-aul-04"));
assertThrown!DateTimeException(Date.fromISOExtString("20100704"));
assertThrown!DateTimeException(Date.fromISOExtString("2010-Jul-04"));
_assertPred!"=="(Date.fromISOExtString("1999-07-06"), Date(1999, 7, 6));
_assertPred!"=="(Date.fromISOExtString("-1999-07-06"), Date(-1999, 7, 6));
_assertPred!"=="(Date.fromISOExtString("+01999-07-06"), Date(1999, 7, 6));
_assertPred!"=="(Date.fromISOExtString("1999-07-06 "), Date(1999, 7, 6));
_assertPred!"=="(Date.fromISOExtString(" 1999-07-06"), Date(1999, 7, 6));
_assertPred!"=="(Date.fromISOExtString(" 1999-07-06 "), Date(1999, 7, 6));
//Verify Examples.
assert(Date.fromISOExtString("2010-07-04") == Date(2010, 7, 4));
assert(Date.fromISOExtString("1998-12-25") == Date(1998, 12, 25));
assert(Date.fromISOExtString("0000-01-05") == Date(0, 1, 5));
assert(Date.fromISOExtString("-0004-01-05") == Date(-4, 1, 5));
assert(Date.fromISOExtString(" 2010-07-04 ") == Date(2010, 7, 4));
}
}
/++
Creates a $(D Date) from a string with the format YYYY-Mon-DD.
Whitespace is stripped from the given string.
Params:
simpleString = A string formatted in the way that toSimpleString
formats dates.
Throws:
$(D DateTimeException) if the given string is not in the correct
format or if the resulting $(D Date) would not be valid.
Examples:
--------------------
assert(Date.fromSimpleString("2010-Jul-04") == Date(2010, 7, 4));
assert(Date.fromSimpleString("1998-Dec-25") == Date(1998, 12, 25));
assert(Date.fromSimpleString("0000-Jan-05") == Date(0, 1, 5));
assert(Date.fromSimpleString("-0004-Jan-05") == Date(-4, 1, 5));
assert(Date.fromSimpleString(" 2010-Jul-04 ") == Date(2010, 7, 4));
--------------------
+/
static Date fromSimpleString(S)(in S simpleString)
if(isSomeString!(S))
{
auto dstr = to!dstring(strip(simpleString));
enforce(dstr.length >= 11, new DateTimeException(format("Invalid string format: %s", simpleString)));
auto day = dstr[$-2 .. $];
auto month = monthFromString(to!string(dstr[$-6 .. $-3]));
auto year = dstr[0 .. $-7];
enforce(dstr[$-3] == '-', new DateTimeException(format("Invalid string format: %s", simpleString)));
enforce(dstr[$-7] == '-', new DateTimeException(format("Invalid string format: %s", simpleString)));
enforce(!canFind!(not!isDigit)(day), new DateTimeException(format("Invalid string format: %s", simpleString)));
if(year.length > 4)
{
enforce(year.startsWith("-") || year.startsWith("+"),
new DateTimeException(format("Invalid string format: %s", simpleString)));
enforce(!canFind!(not!isDigit)(year[1..$]),
new DateTimeException(format("Invalid string format: %s", simpleString)));
}
else
enforce(!canFind!(not!isDigit)(year),
new DateTimeException(format("Invalid string format: %s", simpleString)));
return Date(to!short(year), month, to!ubyte(day));
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(Date.fromSimpleString(""));
assertThrown!DateTimeException(Date.fromSimpleString("990704"));
assertThrown!DateTimeException(Date.fromSimpleString("0100704"));
assertThrown!DateTimeException(Date.fromSimpleString("2010070"));
assertThrown!DateTimeException(Date.fromSimpleString("2010070 "));
assertThrown!DateTimeException(Date.fromSimpleString("120100704"));
assertThrown!DateTimeException(Date.fromSimpleString("-0100704"));
assertThrown!DateTimeException(Date.fromSimpleString("+0100704"));
assertThrown!DateTimeException(Date.fromSimpleString("2010070a"));
assertThrown!DateTimeException(Date.fromSimpleString("20100a04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010a704"));
assertThrown!DateTimeException(Date.fromSimpleString("99-07-04"));
assertThrown!DateTimeException(Date.fromSimpleString("010-07-04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-07-0"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-07-0 "));
assertThrown!DateTimeException(Date.fromSimpleString("12010-07-04"));
assertThrown!DateTimeException(Date.fromSimpleString("-010-07-04"));
assertThrown!DateTimeException(Date.fromSimpleString("+010-07-04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-07-0a"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-0a-04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-a7-04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010/07/04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010/7/04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010/7/4"));
assertThrown!DateTimeException(Date.fromSimpleString("2010/07/4"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-7-04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-7-4"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-07-4"));
assertThrown!DateTimeException(Date.fromSimpleString("99Jul04"));
assertThrown!DateTimeException(Date.fromSimpleString("010Jul04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010Jul0"));
assertThrown!DateTimeException(Date.fromSimpleString("2010Jul0 "));
assertThrown!DateTimeException(Date.fromSimpleString("12010Jul04"));
assertThrown!DateTimeException(Date.fromSimpleString("-010Jul04"));
assertThrown!DateTimeException(Date.fromSimpleString("+010Jul04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010Jul0a"));
assertThrown!DateTimeException(Date.fromSimpleString("2010Jua04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010aul04"));
assertThrown!DateTimeException(Date.fromSimpleString("99-Jul-04"));
assertThrown!DateTimeException(Date.fromSimpleString("010-Jul-04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-Jul-0"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-Jul-0 "));
assertThrown!DateTimeException(Date.fromSimpleString("12010-Jul-04"));
assertThrown!DateTimeException(Date.fromSimpleString("-010-Jul-04"));
assertThrown!DateTimeException(Date.fromSimpleString("+010-Jul-04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-Jul-0a"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-Jua-04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-Jal-04"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-aul-04"));
assertThrown!DateTimeException(Date.fromSimpleString("20100704"));
assertThrown!DateTimeException(Date.fromSimpleString("2010-07-04"));
_assertPred!"=="(Date.fromSimpleString("1999-Jul-06"), Date(1999, 7, 6));
_assertPred!"=="(Date.fromSimpleString("-1999-Jul-06"), Date(-1999, 7, 6));
_assertPred!"=="(Date.fromSimpleString("+01999-Jul-06"), Date(1999, 7, 6));
_assertPred!"=="(Date.fromSimpleString("1999-Jul-06 "), Date(1999, 7, 6));
_assertPred!"=="(Date.fromSimpleString(" 1999-Jul-06"), Date(1999, 7, 6));
_assertPred!"=="(Date.fromSimpleString(" 1999-Jul-06 "), Date(1999, 7, 6));
//Verify Examples.
assert(Date.fromSimpleString("2010-Jul-04") == Date(2010, 7, 4));
assert(Date.fromSimpleString("1998-Dec-25") == Date(1998, 12, 25));
assert(Date.fromSimpleString("0000-Jan-05") == Date(0, 1, 5));
assert(Date.fromSimpleString("-0004-Jan-05") == Date(-4, 1, 5));
assert(Date.fromSimpleString(" 2010-Jul-04 ") == Date(2010, 7, 4));
}
}
//TODO Add function which takes a user-specified time format and produces a Date
//TODO Add function which takes pretty much any time-string and produces a Date
// Obviously, it will be less efficient, and it probably won't manage _every_
// possible date format, but a smart conversion function would be nice.
/++
Returns the $(D Date) farthest in the past which is representable by
$(D Date).
+/
@property static Date min() pure nothrow
{
auto date = Date.init;
date._year = short.min;
date._month = Month.jan;
date._day = 1;
return date;
}
unittest
{
version(testStdDateTime)
{
assert(Date.min.year < 0);
assert(Date.min < Date.max);
}
}
/++
Returns the $(D Date) farthest in the future which is representable by
$(D Date).
+/
@property static Date max() pure nothrow
{
auto date = Date.init;
date._year = short.max;
date._month = Month.dec;
date._day = 31;
return date;
}
unittest
{
version(testStdDateTime)
{
assert(Date.max.year > 0);
assert(Date.max > Date.min);
}
}
private:
/+
Whether the given values form a valid date.
Params:
year = The year to test.
month = The month of the Gregorian Calendar to test.
day = The day of the month to test.
+/
static bool _valid(int year, int month, int day) pure nothrow
{
if(!valid!"months"(month))
return false;
return valid!"days"(year, month, day);
}
/+
Adds the given number of days to this $(D Date). A negative number will
subtract.
The month will be adjusted along with the day if the number of days
added (or subtracted) would overflow (or underflow) the current month.
The year will be adjusted along with the month if the increase (or
decrease) to the month would cause it to overflow (or underflow) the
current year.
$(D addDays(numDays)) is effectively equivalent to
$(D date.dayOfGregorianCal = date.dayOfGregorianCal + days).
Params:
days = The number of days to add to this Date.
+/
ref Date addDays(long days) pure nothrow
{
dayOfGregorianCal = cast(int)(dayOfGregorianCal + days);
return this;
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
{
auto date = Date(1999, 2, 28);
date.addDays(1);
_assertPred!"=="(date, Date(1999, 3, 1));
date.addDays(-1);
_assertPred!"=="(date, Date(1999, 2, 28));
}
{
auto date = Date(2000, 2, 28);
date.addDays(1);
_assertPred!"=="(date, Date(2000, 2, 29));
date.addDays(1);
_assertPred!"=="(date, Date(2000, 3, 1));
date.addDays(-1);
_assertPred!"=="(date, Date(2000, 2, 29));
}
{
auto date = Date(1999, 6, 30);
date.addDays(1);
_assertPred!"=="(date, Date(1999, 7, 1));
date.addDays(-1);
_assertPred!"=="(date, Date(1999, 6, 30));
}
{
auto date = Date(1999, 7, 31);
date.addDays(1);
_assertPred!"=="(date, Date(1999, 8, 1));
date.addDays(-1);
_assertPred!"=="(date, Date(1999, 7, 31));
}
{
auto date = Date(1999, 1, 1);
date.addDays(-1);
_assertPred!"=="(date, Date(1998, 12, 31));
date.addDays(1);
_assertPred!"=="(date, Date(1999, 1, 1));
}
{
auto date = Date(1999, 7, 6);
date.addDays(9);
_assertPred!"=="(date, Date(1999, 7, 15));
date.addDays(-11);
_assertPred!"=="(date, Date(1999, 7, 4));
date.addDays(30);
_assertPred!"=="(date, Date(1999, 8, 3));
date.addDays(-3);
_assertPred!"=="(date, Date(1999, 7, 31));
}
{
auto date = Date(1999, 7, 6);
date.addDays(365);
_assertPred!"=="(date, Date(2000, 7, 5));
date.addDays(-365);
_assertPred!"=="(date, Date(1999, 7, 6));
date.addDays(366);
_assertPred!"=="(date, Date(2000, 7, 6));
date.addDays(730);
_assertPred!"=="(date, Date(2002, 7, 6));
date.addDays(-1096);
_assertPred!"=="(date, Date(1999, 7, 6));
}
//Test B.C.
{
auto date = Date(-1999, 2, 28);
date.addDays(1);
_assertPred!"=="(date, Date(-1999, 3, 1));
date.addDays(-1);
_assertPred!"=="(date, Date(-1999, 2, 28));
}
{
auto date = Date(-2000, 2, 28);
date.addDays(1);
_assertPred!"=="(date, Date(-2000, 2, 29));
date.addDays(1);
_assertPred!"=="(date, Date(-2000, 3, 1));
date.addDays(-1);
_assertPred!"=="(date, Date(-2000, 2, 29));
}
{
auto date = Date(-1999, 6, 30);
date.addDays(1);
_assertPred!"=="(date, Date(-1999, 7, 1));
date.addDays(-1);
_assertPred!"=="(date, Date(-1999, 6, 30));
}
{
auto date = Date(-1999, 7, 31);
date.addDays(1);
_assertPred!"=="(date, Date(-1999, 8, 1));
date.addDays(-1);
_assertPred!"=="(date, Date(-1999, 7, 31));
}
{
auto date = Date(-1999, 1, 1);
date.addDays(-1);
_assertPred!"=="(date, Date(-2000, 12, 31));
date.addDays(1);
_assertPred!"=="(date, Date(-1999, 1, 1));
}
{
auto date = Date(-1999, 7, 6);
date.addDays(9);
_assertPred!"=="(date, Date(-1999, 7, 15));
date.addDays(-11);
_assertPred!"=="(date, Date(-1999, 7, 4));
date.addDays(30);
_assertPred!"=="(date, Date(-1999, 8, 3));
date.addDays(-3);
}
{
auto date = Date(-1999, 7, 6);
date.addDays(365);
_assertPred!"=="(date, Date(-1998, 7, 6));
date.addDays(-365);
_assertPred!"=="(date, Date(-1999, 7, 6));
date.addDays(366);
_assertPred!"=="(date, Date(-1998, 7, 7));
date.addDays(730);
_assertPred!"=="(date, Date(-1996, 7, 6));
date.addDays(-1096);
_assertPred!"=="(date, Date(-1999, 7, 6));
}
//Test Both
{
auto date = Date(1, 7, 6);
date.addDays(-365);
_assertPred!"=="(date, Date(0, 7, 6));
date.addDays(365);
_assertPred!"=="(date, Date(1, 7, 6));
date.addDays(-731);
_assertPred!"=="(date, Date(-1, 7, 6));
date.addDays(730);
_assertPred!"=="(date, Date(1, 7, 5));
}
const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.addDays(12)));
static assert(!__traits(compiles, idate.addDays(12)));
}
}
pure invariant()
{
assert(valid!"months"(_month), "Invariant Failure: year [" ~
numToString(_year) ~
"] month [" ~
numToString(_month) ~
"] day [" ~
numToString(_day) ~
"]");
assert(valid!"days"(_year, _month, _day), "Invariant Failure: year [" ~
numToString(_year) ~
"] month [" ~
numToString(_month) ~
"] day [" ~
numToString(_day) ~
"]");
}
short _year = 1;
Month _month = Month.jan;
ubyte _day = 1;
}
/++
Represents a time of day with hours, minutes, and seconds. It uses 24 hour
time.
+/
struct TimeOfDay
{
public:
/++
Params:
hour = Hour of the day [0 - 24$(RPAREN).
minute = Minute of the hour [0 - 60$(RPAREN).
second = Second of the minute [0 - 60$(RPAREN).
Throws:
$(D DateTimeException) if the resulting $(D TimeOfDay) would be not
be valid.
+/
this(int hour, int minute, int second = 0) pure
{
enforceValid!"hours"(hour);
enforceValid!"minutes"(minute);
enforceValid!"seconds"(second);
_hour = cast(ubyte)hour;
_minute = cast(ubyte)minute;
_second = cast(ubyte)second;
}
unittest
{
version(testStdDateTime)
{
assert(TimeOfDay(0, 0) == TimeOfDay.init);
{
auto tod = TimeOfDay(0, 0);
_assertPred!"=="(tod._hour, 0);
_assertPred!"=="(tod._minute, 0);
_assertPred!"=="(tod._second, 0);
}
{
auto tod = TimeOfDay(12, 30, 33);
_assertPred!"=="(tod._hour, 12);
_assertPred!"=="(tod._minute, 30);
_assertPred!"=="(tod._second, 33);
}
{
auto tod = TimeOfDay(23, 59, 59);
_assertPred!"=="(tod._hour, 23);
_assertPred!"=="(tod._minute, 59);
_assertPred!"=="(tod._second, 59);
}
assertThrown!DateTimeException(TimeOfDay(24, 0, 0));
assertThrown!DateTimeException(TimeOfDay(0, 60, 0));
assertThrown!DateTimeException(TimeOfDay(0, 0, 60));
}
}
/++
Compares this $(D TimeOfDay) with the given $(D TimeOfDay).
Returns:
$(BOOKTABLE,
$(TR $(TD this < rhs) $(TD < 0))
$(TR $(TD this == rhs) $(TD 0))
$(TR $(TD this > rhs) $(TD > 0))
)
+/
int opCmp(in TimeOfDay rhs) const pure nothrow
{
if(_hour < rhs._hour)
return -1;
if(_hour > rhs._hour)
return 1;
if(_minute < rhs._minute)
return -1;
if(_minute > rhs._minute)
return 1;
if(_second < rhs._second)
return -1;
if(_second > rhs._second)
return 1;
return 0;
}
unittest
{
version(testStdDateTime)
{
_assertPred!("opCmp", "==")(TimeOfDay(0, 0, 0), TimeOfDay.init);
_assertPred!("opCmp", "==")(TimeOfDay(0, 0, 0), TimeOfDay(0, 0, 0));
_assertPred!("opCmp", "==")(TimeOfDay(12, 0, 0), TimeOfDay(12, 0, 0));
_assertPred!("opCmp", "==")(TimeOfDay(0, 30, 0), TimeOfDay(0, 30, 0));
_assertPred!("opCmp", "==")(TimeOfDay(0, 0, 33), TimeOfDay(0, 0, 33));
_assertPred!("opCmp", "==")(TimeOfDay(12, 30, 0), TimeOfDay(12, 30, 0));
_assertPred!("opCmp", "==")(TimeOfDay(12, 30, 33), TimeOfDay(12, 30, 33));
_assertPred!("opCmp", "==")(TimeOfDay(0, 30, 33), TimeOfDay(0, 30, 33));
_assertPred!("opCmp", "==")(TimeOfDay(0, 0, 33), TimeOfDay(0, 0, 33));
_assertPred!("opCmp", "<")(TimeOfDay(12, 30, 33), TimeOfDay(13, 30, 33));
_assertPred!("opCmp", ">")(TimeOfDay(13, 30, 33), TimeOfDay(12, 30, 33));
_assertPred!("opCmp", "<")(TimeOfDay(12, 30, 33), TimeOfDay(12, 31, 33));
_assertPred!("opCmp", ">")(TimeOfDay(12, 31, 33), TimeOfDay(12, 30, 33));
_assertPred!("opCmp", "<")(TimeOfDay(12, 30, 33), TimeOfDay(12, 30, 34));
_assertPred!("opCmp", ">")(TimeOfDay(12, 30, 34), TimeOfDay(12, 30, 33));
_assertPred!("opCmp", ">")(TimeOfDay(13, 30, 33), TimeOfDay(12, 30, 34));
_assertPred!("opCmp", "<")(TimeOfDay(12, 30, 34), TimeOfDay(13, 30, 33));
_assertPred!("opCmp", ">")(TimeOfDay(13, 30, 33), TimeOfDay(12, 31, 33));
_assertPred!("opCmp", "<")(TimeOfDay(12, 31, 33), TimeOfDay(13, 30, 33));
_assertPred!("opCmp", ">")(TimeOfDay(12, 31, 33), TimeOfDay(12, 30, 34));
_assertPred!("opCmp", "<")(TimeOfDay(12, 30, 34), TimeOfDay(12, 31, 33));
const ctod = TimeOfDay(12, 30, 33);
immutable itod = TimeOfDay(12, 30, 33);
static assert(__traits(compiles, ctod.opCmp(itod)));
static assert(__traits(compiles, itod.opCmp(ctod)));
}
}
/++
Hours passed midnight.
+/
@property ubyte hour() const pure nothrow
{
return _hour;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(TimeOfDay.init.hour, 0);
_assertPred!"=="(TimeOfDay(12, 0, 0).hour, 12);
const ctod = TimeOfDay(12, 0, 0);
immutable itod = TimeOfDay(12, 0, 0);
static assert(__traits(compiles, ctod.hour == 12));
static assert(__traits(compiles, itod.hour == 12));
}
}
/++
Hours passed midnight.
Params:
hour = The hour of the day to set this $(D TimeOfDay)'s hour to.
Throws:
$(D DateTimeException) if the given hour would result in an invalid
$(D TimeOfDay).
+/
@property void hour(int hour) pure
{
enforceValid!"hours"(hour);
_hour = cast(ubyte)hour;
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException((){TimeOfDay(0, 0, 0).hour = 24;}());
auto tod = TimeOfDay(0, 0, 0);
tod.hour = 12;
_assertPred!"=="(tod, TimeOfDay(12, 0, 0));
const ctod = TimeOfDay(0, 0, 0);
immutable itod = TimeOfDay(0, 0, 0);
static assert(!__traits(compiles, ctod.hour = 12));
static assert(!__traits(compiles, itod.hour = 12));
}
}
/++
Minutes passed the hour.
+/
@property ubyte minute() const pure nothrow
{
return _minute;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(TimeOfDay.init.minute, 0);
_assertPred!"=="(TimeOfDay(0, 30, 0).minute, 30);
const ctod = TimeOfDay(0, 30, 0);
immutable itod = TimeOfDay(0, 30, 0);
static assert(__traits(compiles, ctod.minute == 30));
static assert(__traits(compiles, itod.minute == 30));
}
}
/++
Minutes passed the hour.
Params:
minute = The minute to set this $(D TimeOfDay)'s minute to.
Throws:
$(D DateTimeException) if the given minute would result in an
invalid $(D TimeOfDay).
+/
@property void minute(int minute) pure
{
enforceValid!"minutes"(minute);
_minute = cast(ubyte)minute;
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException((){TimeOfDay(0, 0, 0).minute = 60;}());
auto tod = TimeOfDay(0, 0, 0);
tod.minute = 30;
_assertPred!"=="(tod, TimeOfDay(0, 30, 0));
const ctod = TimeOfDay(0, 0, 0);
immutable itod = TimeOfDay(0, 0, 0);
static assert(!__traits(compiles, ctod.minute = 30));
static assert(!__traits(compiles, itod.minute = 30));
}
}
/++
Seconds passed the minute.
+/
@property ubyte second() const pure nothrow
{
return _second;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(TimeOfDay.init.second, 0);
_assertPred!"=="(TimeOfDay(0, 0, 33).second, 33);
const ctod = TimeOfDay(0, 0, 33);
immutable itod = TimeOfDay(0, 0, 33);
static assert(__traits(compiles, ctod.second == 33));
static assert(__traits(compiles, itod.second == 33));
}
}
/++
Seconds passed the minute.
Params:
second = The second to set this $(D TimeOfDay)'s second to.
Throws:
$(D DateTimeException) if the given second would result in an
invalid $(D TimeOfDay).
+/
@property void second(int second) pure
{
enforceValid!"seconds"(second);
_second = cast(ubyte)second;
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException((){TimeOfDay(0, 0, 0).second = 60;}());
auto tod = TimeOfDay(0, 0, 0);
tod.second = 33;
_assertPred!"=="(tod, TimeOfDay(0, 0, 33));
const ctod = TimeOfDay(0, 0, 0);
immutable itod = TimeOfDay(0, 0, 0);
static assert(!__traits(compiles, ctod.second = 33));
static assert(!__traits(compiles, itod.second = 33));
}
}
/++
Adds the given number of units to this $(D TimeOfDay). A negative number
will subtract.
The difference between rolling and adding is that rolling does not
affect larger units. So, for instance, if you roll a $(D TimeOfDay)
one hours's worth of minutes, then you get the exact same
$(D TimeOfDay).
Accepted units are $(D "hours"), $(D "minutes"), and $(D "seconds").
Params:
units = The units to add.
value = The number of $(D_PARAM units) to add to this
$(D TimeOfDay).
Examples:
--------------------
auto tod1 = TimeOfDay(7, 12, 0);
tod1.roll!"hours"(1);
assert(tod1 == TimeOfDay(8, 12, 0));
auto tod2 = TimeOfDay(7, 12, 0);
tod2.roll!"hours"(-1);
assert(tod2 == TimeOfDay(6, 12, 0));
auto tod3 = TimeOfDay(23, 59, 0);
tod3.roll!"minutes"(1);
assert(tod3 == TimeOfDay(23, 0, 0));
auto tod4 = TimeOfDay(0, 0, 0);
tod4.roll!"minutes"(-1);
assert(tod4 == TimeOfDay(0, 59, 0));
auto tod5 = TimeOfDay(23, 59, 59);
tod5.roll!"seconds"(1);
assert(tod5 == TimeOfDay(23, 59, 0));
auto tod6 = TimeOfDay(0, 0, 0);
tod6.roll!"seconds"(-1);
assert(tod6 == TimeOfDay(0, 0, 59));
--------------------
+/
/+ref TimeOfDay+/ void roll(string units)(long value) pure nothrow
if(units == "hours")
{
this += dur!"hours"(value);
}
//Verify Examples.
unittest
{
version(testStdDateTime)
{
auto tod1 = TimeOfDay(7, 12, 0);
tod1.roll!"hours"(1);
assert(tod1 == TimeOfDay(8, 12, 0));
auto tod2 = TimeOfDay(7, 12, 0);
tod2.roll!"hours"(-1);
assert(tod2 == TimeOfDay(6, 12, 0));
auto tod3 = TimeOfDay(23, 59, 0);
tod3.roll!"minutes"(1);
assert(tod3 == TimeOfDay(23, 0, 0));
auto tod4 = TimeOfDay(0, 0, 0);
tod4.roll!"minutes"(-1);
assert(tod4 == TimeOfDay(0, 59, 0));
auto tod5 = TimeOfDay(23, 59, 59);
tod5.roll!"seconds"(1);
assert(tod5 == TimeOfDay(23, 59, 0));
auto tod6 = TimeOfDay(0, 0, 0);
tod6.roll!"seconds"(-1);
assert(tod6 == TimeOfDay(0, 0, 59));
}
}
unittest
{
version(testStdDateTime)
{
const ctod = TimeOfDay(0, 0, 0);
immutable itod = TimeOfDay(0, 0, 0);
static assert(!__traits(compiles, ctod.roll!"hours"(53)));
static assert(!__traits(compiles, itod.roll!"hours"(53)));
}
}
//Shares documentation with "hours" version.
/+ref TimeOfDay+/ void roll(string units)(long value) pure nothrow
if(units == "minutes" ||
units == "seconds")
{
static if(units == "minutes")
enum memberVarStr = "minute";
else static if(units == "seconds")
enum memberVarStr = "second";
else
static assert(0);
value %= 60;
mixin("auto newVal = cast(ubyte)(_" ~ memberVarStr ~ ") + value;");
if(value < 0)
{
if(newVal < 0)
newVal += 60;
}
else if(newVal >= 60)
newVal -= 60;
mixin("_" ~ memberVarStr ~ " = cast(ubyte)newVal;");
}
//Test roll!"minutes"().
unittest
{
version(testStdDateTime)
{
static void testTOD(TimeOfDay orig, int minutes, in TimeOfDay expected, size_t line = __LINE__)
{
orig.roll!"minutes"(minutes);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
testTOD(TimeOfDay(12, 30, 33), 0, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), 1, TimeOfDay(12, 31, 33));
testTOD(TimeOfDay(12, 30, 33), 2, TimeOfDay(12, 32, 33));
testTOD(TimeOfDay(12, 30, 33), 3, TimeOfDay(12, 33, 33));
testTOD(TimeOfDay(12, 30, 33), 4, TimeOfDay(12, 34, 33));
testTOD(TimeOfDay(12, 30, 33), 5, TimeOfDay(12, 35, 33));
testTOD(TimeOfDay(12, 30, 33), 10, TimeOfDay(12, 40, 33));
testTOD(TimeOfDay(12, 30, 33), 15, TimeOfDay(12, 45, 33));
testTOD(TimeOfDay(12, 30, 33), 29, TimeOfDay(12, 59, 33));
testTOD(TimeOfDay(12, 30, 33), 30, TimeOfDay(12, 0, 33));
testTOD(TimeOfDay(12, 30, 33), 45, TimeOfDay(12, 15, 33));
testTOD(TimeOfDay(12, 30, 33), 60, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), 75, TimeOfDay(12, 45, 33));
testTOD(TimeOfDay(12, 30, 33), 90, TimeOfDay(12, 0, 33));
testTOD(TimeOfDay(12, 30, 33), 100, TimeOfDay(12, 10, 33));
testTOD(TimeOfDay(12, 30, 33), 689, TimeOfDay(12, 59, 33));
testTOD(TimeOfDay(12, 30, 33), 690, TimeOfDay(12, 0, 33));
testTOD(TimeOfDay(12, 30, 33), 691, TimeOfDay(12, 1, 33));
testTOD(TimeOfDay(12, 30, 33), 960, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), 1439, TimeOfDay(12, 29, 33));
testTOD(TimeOfDay(12, 30, 33), 1440, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), 1441, TimeOfDay(12, 31, 33));
testTOD(TimeOfDay(12, 30, 33), 2880, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), -1, TimeOfDay(12, 29, 33));
testTOD(TimeOfDay(12, 30, 33), -2, TimeOfDay(12, 28, 33));
testTOD(TimeOfDay(12, 30, 33), -3, TimeOfDay(12, 27, 33));
testTOD(TimeOfDay(12, 30, 33), -4, TimeOfDay(12, 26, 33));
testTOD(TimeOfDay(12, 30, 33), -5, TimeOfDay(12, 25, 33));
testTOD(TimeOfDay(12, 30, 33), -10, TimeOfDay(12, 20, 33));
testTOD(TimeOfDay(12, 30, 33), -15, TimeOfDay(12, 15, 33));
testTOD(TimeOfDay(12, 30, 33), -29, TimeOfDay(12, 1, 33));
testTOD(TimeOfDay(12, 30, 33), -30, TimeOfDay(12, 0, 33));
testTOD(TimeOfDay(12, 30, 33), -45, TimeOfDay(12, 45, 33));
testTOD(TimeOfDay(12, 30, 33), -60, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), -75, TimeOfDay(12, 15, 33));
testTOD(TimeOfDay(12, 30, 33), -90, TimeOfDay(12, 0, 33));
testTOD(TimeOfDay(12, 30, 33), -100, TimeOfDay(12, 50, 33));
testTOD(TimeOfDay(12, 30, 33), -749, TimeOfDay(12, 1, 33));
testTOD(TimeOfDay(12, 30, 33), -750, TimeOfDay(12, 0, 33));
testTOD(TimeOfDay(12, 30, 33), -751, TimeOfDay(12, 59, 33));
testTOD(TimeOfDay(12, 30, 33), -960, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), -1439, TimeOfDay(12, 31, 33));
testTOD(TimeOfDay(12, 30, 33), -1440, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), -1441, TimeOfDay(12, 29, 33));
testTOD(TimeOfDay(12, 30, 33), -2880, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 0, 33), 1, TimeOfDay(12, 1, 33));
testTOD(TimeOfDay(12, 0, 33), 0, TimeOfDay(12, 0, 33));
testTOD(TimeOfDay(12, 0, 33), -1, TimeOfDay(12, 59, 33));
testTOD(TimeOfDay(11, 59, 33), 1, TimeOfDay(11, 0, 33));
testTOD(TimeOfDay(11, 59, 33), 0, TimeOfDay(11, 59, 33));
testTOD(TimeOfDay(11, 59, 33), -1, TimeOfDay(11, 58, 33));
testTOD(TimeOfDay(0, 0, 33), 1, TimeOfDay(0, 1, 33));
testTOD(TimeOfDay(0, 0, 33), 0, TimeOfDay(0, 0, 33));
testTOD(TimeOfDay(0, 0, 33), -1, TimeOfDay(0, 59, 33));
testTOD(TimeOfDay(23, 59, 33), 1, TimeOfDay(23, 0, 33));
testTOD(TimeOfDay(23, 59, 33), 0, TimeOfDay(23, 59, 33));
testTOD(TimeOfDay(23, 59, 33), -1, TimeOfDay(23, 58, 33));
const ctod = TimeOfDay(0, 0, 0);
immutable itod = TimeOfDay(0, 0, 0);
static assert(!__traits(compiles, ctod.roll!"minutes"(7)));
static assert(!__traits(compiles, itod.roll!"minutes"(7)));
//Verify Examples.
auto tod1 = TimeOfDay(7, 12, 0);
tod1.roll!"minutes"(1);
assert(tod1 == TimeOfDay(7, 13, 0));
auto tod2 = TimeOfDay(7, 12, 0);
tod2.roll!"minutes"(-1);
assert(tod2 == TimeOfDay(7, 11, 0));
auto tod3 = TimeOfDay(23, 59, 0);
tod3.roll!"minutes"(1);
assert(tod3 == TimeOfDay(23, 0, 0));
auto tod4 = TimeOfDay(0, 0, 0);
tod4.roll!"minutes"(-1);
assert(tod4 == TimeOfDay(0, 59, 0));
auto tod5 = TimeOfDay(7, 32, 12);
tod5.roll!"seconds"(1);
assert(tod5 == TimeOfDay(7, 32, 13));
auto tod6 = TimeOfDay(7, 32, 12);
tod6.roll!"seconds"(-1);
assert(tod6 == TimeOfDay(7, 32, 11));
auto tod7 = TimeOfDay(23, 59, 59);
tod7.roll!"seconds"(1);
assert(tod7 == TimeOfDay(23, 59, 0));
auto tod8 = TimeOfDay(0, 0, 0);
tod8.roll!"seconds"(-1);
assert(tod8 == TimeOfDay(0, 0, 59));
}
}
//Test roll!"seconds"().
unittest
{
version(testStdDateTime)
{
static void testTOD(TimeOfDay orig, int seconds, in TimeOfDay expected, size_t line = __LINE__)
{
orig.roll!"seconds"(seconds);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
testTOD(TimeOfDay(12, 30, 33), 0, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), 1, TimeOfDay(12, 30, 34));
testTOD(TimeOfDay(12, 30, 33), 2, TimeOfDay(12, 30, 35));
testTOD(TimeOfDay(12, 30, 33), 3, TimeOfDay(12, 30, 36));
testTOD(TimeOfDay(12, 30, 33), 4, TimeOfDay(12, 30, 37));
testTOD(TimeOfDay(12, 30, 33), 5, TimeOfDay(12, 30, 38));
testTOD(TimeOfDay(12, 30, 33), 10, TimeOfDay(12, 30, 43));
testTOD(TimeOfDay(12, 30, 33), 15, TimeOfDay(12, 30, 48));
testTOD(TimeOfDay(12, 30, 33), 26, TimeOfDay(12, 30, 59));
testTOD(TimeOfDay(12, 30, 33), 27, TimeOfDay(12, 30, 0));
testTOD(TimeOfDay(12, 30, 33), 30, TimeOfDay(12, 30, 3));
testTOD(TimeOfDay(12, 30, 33), 59, TimeOfDay(12, 30, 32));
testTOD(TimeOfDay(12, 30, 33), 60, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), 61, TimeOfDay(12, 30, 34));
testTOD(TimeOfDay(12, 30, 33), 1766, TimeOfDay(12, 30, 59));
testTOD(TimeOfDay(12, 30, 33), 1767, TimeOfDay(12, 30, 0));
testTOD(TimeOfDay(12, 30, 33), 1768, TimeOfDay(12, 30, 1));
testTOD(TimeOfDay(12, 30, 33), 2007, TimeOfDay(12, 30, 0));
testTOD(TimeOfDay(12, 30, 33), 3599, TimeOfDay(12, 30, 32));
testTOD(TimeOfDay(12, 30, 33), 3600, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), 3601, TimeOfDay(12, 30, 34));
testTOD(TimeOfDay(12, 30, 33), 7200, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), -1, TimeOfDay(12, 30, 32));
testTOD(TimeOfDay(12, 30, 33), -2, TimeOfDay(12, 30, 31));
testTOD(TimeOfDay(12, 30, 33), -3, TimeOfDay(12, 30, 30));
testTOD(TimeOfDay(12, 30, 33), -4, TimeOfDay(12, 30, 29));
testTOD(TimeOfDay(12, 30, 33), -5, TimeOfDay(12, 30, 28));
testTOD(TimeOfDay(12, 30, 33), -10, TimeOfDay(12, 30, 23));
testTOD(TimeOfDay(12, 30, 33), -15, TimeOfDay(12, 30, 18));
testTOD(TimeOfDay(12, 30, 33), -33, TimeOfDay(12, 30, 0));
testTOD(TimeOfDay(12, 30, 33), -34, TimeOfDay(12, 30, 59));
testTOD(TimeOfDay(12, 30, 33), -35, TimeOfDay(12, 30, 58));
testTOD(TimeOfDay(12, 30, 33), -59, TimeOfDay(12, 30, 34));
testTOD(TimeOfDay(12, 30, 33), -60, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), -61, TimeOfDay(12, 30, 32));
testTOD(TimeOfDay(12, 30, 0), 1, TimeOfDay(12, 30, 1));
testTOD(TimeOfDay(12, 30, 0), 0, TimeOfDay(12, 30, 0));
testTOD(TimeOfDay(12, 30, 0), -1, TimeOfDay(12, 30, 59));
testTOD(TimeOfDay(12, 0, 0), 1, TimeOfDay(12, 0, 1));
testTOD(TimeOfDay(12, 0, 0), 0, TimeOfDay(12, 0, 0));
testTOD(TimeOfDay(12, 0, 0), -1, TimeOfDay(12, 0, 59));
testTOD(TimeOfDay(0, 0, 0), 1, TimeOfDay(0, 0, 1));
testTOD(TimeOfDay(0, 0, 0), 0, TimeOfDay(0, 0, 0));
testTOD(TimeOfDay(0, 0, 0), -1, TimeOfDay(0, 0, 59));
testTOD(TimeOfDay(23, 59, 59), 1, TimeOfDay(23, 59, 0));
testTOD(TimeOfDay(23, 59, 59), 0, TimeOfDay(23, 59, 59));
testTOD(TimeOfDay(23, 59, 59), -1, TimeOfDay(23, 59, 58));
const ctod = TimeOfDay(0, 0, 0);
immutable itod = TimeOfDay(0, 0, 0);
static assert(!__traits(compiles, ctod.roll!"seconds"(7)));
static assert(!__traits(compiles, itod.roll!"seconds"(7)));
}
}
/++
Gives the result of adding or subtracting a duration from this
$(D TimeOfDay).
The legal types of arithmetic for $(D TimeOfDay) using this operator are
$(BOOKTABLE,
$(TR $(TD TimeOfDay) $(TD +) $(TD duration) $(TD -->) $(TD TimeOfDay))
$(TR $(TD TimeOfDay) $(TD -) $(TD duration) $(TD -->) $(TD TimeOfDay))
)
Params:
duration = The duration to add to or subtract from this
$(D TimeOfDay).
+/
TimeOfDay opBinary(string op, D)(in D duration) const pure nothrow
if((op == "+" || op == "-") &&
(is(Unqual!D == Duration) ||
is(Unqual!D == TickDuration)))
{
TimeOfDay retval = this;
static if(is(Unqual!D == Duration))
immutable hnsecs = duration.total!"hnsecs";
else static if(is(Unqual!D == TickDuration))
immutable hnsecs = duration.hnsecs;
//Ideally, this would just be
//return retval.addSeconds(convert!("hnsecs", "seconds")(unaryFun!(op ~ "a")(hnsecs)));
//But there isn't currently a pure version of unaryFun!().
static if(op == "+")
immutable signedHNSecs = hnsecs;
else static if(op == "-")
immutable signedHNSecs = -hnsecs;
else
static assert(0);
return retval.addSeconds(convert!("hnsecs", "seconds")(signedHNSecs));
}
unittest
{
version(testStdDateTime)
{
auto tod = TimeOfDay(12, 30, 33);
_assertPred!"=="(tod + dur!"hours"(7), TimeOfDay(19, 30, 33));
_assertPred!"=="(tod + dur!"hours"(-7), TimeOfDay(5, 30, 33));
_assertPred!"=="(tod + dur!"minutes"(7), TimeOfDay(12, 37, 33));
_assertPred!"=="(tod + dur!"minutes"(-7), TimeOfDay(12, 23, 33));
_assertPred!"=="(tod + dur!"seconds"(7), TimeOfDay(12, 30, 40));
_assertPred!"=="(tod + dur!"seconds"(-7), TimeOfDay(12, 30, 26));
_assertPred!"=="(tod + dur!"msecs"(7000), TimeOfDay(12, 30, 40));
_assertPred!"=="(tod + dur!"msecs"(-7000), TimeOfDay(12, 30, 26));
_assertPred!"=="(tod + dur!"usecs"(7_000_000), TimeOfDay(12, 30, 40));
_assertPred!"=="(tod + dur!"usecs"(-7_000_000), TimeOfDay(12, 30, 26));
_assertPred!"=="(tod + dur!"hnsecs"(70_000_000), TimeOfDay(12, 30, 40));
_assertPred!"=="(tod + dur!"hnsecs"(-70_000_000), TimeOfDay(12, 30, 26));
//This probably only runs in cases where gettimeofday() is used, but it's
//hard to do this test correctly with variable ticksPerSec.
if(TickDuration.ticksPerSec == 1_000_000)
{
_assertPred!"=="(tod + TickDuration.from!"usecs"(7_000_000), TimeOfDay(12, 30, 40));
_assertPred!"=="(tod + TickDuration.from!"usecs"(-7_000_000), TimeOfDay(12, 30, 26));
}
_assertPred!"=="(tod - dur!"hours"(-7), TimeOfDay(19, 30, 33));
_assertPred!"=="(tod - dur!"hours"(7), TimeOfDay(5, 30, 33));
_assertPred!"=="(tod - dur!"minutes"(-7), TimeOfDay(12, 37, 33));
_assertPred!"=="(tod - dur!"minutes"(7), TimeOfDay(12, 23, 33));
_assertPred!"=="(tod - dur!"seconds"(-7), TimeOfDay(12, 30, 40));
_assertPred!"=="(tod - dur!"seconds"(7), TimeOfDay(12, 30, 26));
_assertPred!"=="(tod - dur!"msecs"(-7000), TimeOfDay(12, 30, 40));
_assertPred!"=="(tod - dur!"msecs"(7000), TimeOfDay(12, 30, 26));
_assertPred!"=="(tod - dur!"usecs"(-7_000_000), TimeOfDay(12, 30, 40));
_assertPred!"=="(tod - dur!"usecs"(7_000_000), TimeOfDay(12, 30, 26));
_assertPred!"=="(tod - dur!"hnsecs"(-70_000_000), TimeOfDay(12, 30, 40));
_assertPred!"=="(tod - dur!"hnsecs"(70_000_000), TimeOfDay(12, 30, 26));
//This probably only runs in cases where gettimeofday() is used, but it's
//hard to do this test correctly with variable ticksPerSec.
if(TickDuration.ticksPerSec == 1_000_000)
{
_assertPred!"=="(tod - TickDuration.from!"usecs"(-7_000_000), TimeOfDay(12, 30, 40));
_assertPred!"=="(tod - TickDuration.from!"usecs"(7_000_000), TimeOfDay(12, 30, 26));
}
auto duration = dur!"hours"(11);
const ctod = TimeOfDay(12, 33, 30);
immutable itod = TimeOfDay(12, 33, 30);
static assert(__traits(compiles, tod + duration));
static assert(__traits(compiles, ctod + duration));
static assert(__traits(compiles, itod + duration));
static assert(__traits(compiles, tod - duration));
static assert(__traits(compiles, ctod - duration));
static assert(__traits(compiles, itod - duration));
}
}
/++
Gives the result of adding or subtracting a duration from this
$(D TimeOfDay), as well as assigning the result to this
$(D TimeOfDay).
The legal types of arithmetic for $(D TimeOfDay) using this operator are
$(BOOKTABLE,
$(TR $(TD TimeOfDay) $(TD +) $(TD duration) $(TD -->) $(TD TimeOfDay))
$(TR $(TD TimeOfDay) $(TD -) $(TD duration) $(TD -->) $(TD TimeOfDay))
)
Params:
duration = The duration to add to or subtract from this
$(D TimeOfDay).
+/
/+ref+/ TimeOfDay opOpAssign(string op, D)(in D duration) pure nothrow
if((op == "+" || op == "-") &&
(is(Unqual!D == Duration) ||
is(Unqual!D == TickDuration)))
{
static if(is(Unqual!D == Duration))
immutable hnsecs = duration.total!"hnsecs";
else static if(is(Unqual!D == TickDuration))
immutable hnsecs = duration.hnsecs;
//Ideally, this would just be
//return addSeconds(convert!("hnsecs", "seconds")(unaryFun!(op ~ "a")(hnsecs)));
//But there isn't currently a pure version of unaryFun!().
static if(op == "+")
immutable signedHNSecs = hnsecs;
else static if(op == "-")
immutable signedHNSecs = -hnsecs;
else
static assert(0);
return addSeconds(convert!("hnsecs", "seconds")(signedHNSecs));
}
unittest
{
version(testStdDateTime)
{
auto duration = dur!"hours"(12);
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"hours"(7), TimeOfDay(19, 30, 33));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"hours"(-7), TimeOfDay(5, 30, 33));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"minutes"(7), TimeOfDay(12, 37, 33));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"minutes"(-7), TimeOfDay(12, 23, 33));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"seconds"(7), TimeOfDay(12, 30, 40));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"seconds"(-7), TimeOfDay(12, 30, 26));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"msecs"(7000), TimeOfDay(12, 30, 40));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"msecs"(-7000), TimeOfDay(12, 30, 26));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"usecs"(7_000_000), TimeOfDay(12, 30, 40));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"usecs"(-7_000_000), TimeOfDay(12, 30, 26));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"hnsecs"(70_000_000), TimeOfDay(12, 30, 40));
_assertPred!"+="(TimeOfDay(12, 30, 33), dur!"hnsecs"(-70_000_000), TimeOfDay(12, 30, 26));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"hours"(-7), TimeOfDay(19, 30, 33));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"hours"(7), TimeOfDay(5, 30, 33));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"minutes"(-7), TimeOfDay(12, 37, 33));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"minutes"(7), TimeOfDay(12, 23, 33));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"seconds"(-7), TimeOfDay(12, 30, 40));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"seconds"(7), TimeOfDay(12, 30, 26));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"msecs"(-7000), TimeOfDay(12, 30, 40));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"msecs"(7000), TimeOfDay(12, 30, 26));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"usecs"(-7_000_000), TimeOfDay(12, 30, 40));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"usecs"(7_000_000), TimeOfDay(12, 30, 26));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"hnsecs"(-70_000_000), TimeOfDay(12, 30, 40));
_assertPred!"-="(TimeOfDay(12, 30, 33), dur!"hnsecs"(70_000_000), TimeOfDay(12, 30, 26));
const ctod = TimeOfDay(12, 33, 30);
immutable itod = TimeOfDay(12, 33, 30);
static assert(!__traits(compiles, ctod += duration));
static assert(!__traits(compiles, itod += duration));
static assert(!__traits(compiles, ctod -= duration));
static assert(!__traits(compiles, itod -= duration));
}
}
/++
Gives the difference between two $(D TimeOfDay)s.
The legal types of arithmetic for $(D TimeOfDay) using this operator are
$(BOOKTABLE,
$(TR $(TD TimeOfDay) $(TD -) $(TD TimeOfDay) $(TD -->) $(TD duration))
)
Params:
rhs = The $(D TimeOfDay) to subtract from this one.
+/
Duration opBinary(string op)(in TimeOfDay rhs) const pure nothrow
if(op == "-")
{
immutable lhsSec = _hour * 3600 + _minute * 60 + _second;
immutable rhsSec = rhs._hour * 3600 + rhs._minute * 60 + rhs._second;
return dur!"seconds"(lhsSec - rhsSec);
}
unittest
{
version(testStdDateTime)
{
auto tod = TimeOfDay(12, 30, 33);
_assertPred!"=="(TimeOfDay(7, 12, 52) - TimeOfDay(12, 30, 33), dur!"seconds"(-19_061));
_assertPred!"=="(TimeOfDay(12, 30, 33) - TimeOfDay(7, 12, 52), dur!"seconds"(19_061));
_assertPred!"=="(TimeOfDay(12, 30, 33) - TimeOfDay(14, 30, 33), dur!"seconds"(-7200));
_assertPred!"=="(TimeOfDay(14, 30, 33) - TimeOfDay(12, 30, 33), dur!"seconds"(7200));
_assertPred!"=="(TimeOfDay(12, 30, 33) - TimeOfDay(12, 34, 33), dur!"seconds"(-240));
_assertPred!"=="(TimeOfDay(12, 34, 33) - TimeOfDay(12, 30, 33), dur!"seconds"(240));
_assertPred!"=="(TimeOfDay(12, 30, 33) - TimeOfDay(12, 30, 34), dur!"seconds"(-1));
_assertPred!"=="(TimeOfDay(12, 30, 34) - TimeOfDay(12, 30, 33), dur!"seconds"(1));
const ctod = TimeOfDay(12, 30, 33);
immutable itod = TimeOfDay(12, 30, 33);
static assert(__traits(compiles, tod - tod));
static assert(__traits(compiles, ctod - tod));
static assert(__traits(compiles, itod - tod));
static assert(__traits(compiles, tod - ctod));
static assert(__traits(compiles, ctod - ctod));
static assert(__traits(compiles, itod - ctod));
static assert(__traits(compiles, tod - itod));
static assert(__traits(compiles, ctod - itod));
static assert(__traits(compiles, itod - itod));
}
}
/++
Converts this $(D TimeOfDay) to a string with the format HHMMSS.
Examples:
--------------------
assert(TimeOfDay(0, 0, 0).toISOString() == "000000");
assert(TimeOfDay(12, 30, 33).toISOString() == "123033");
--------------------
+/
string toISOString() const nothrow
{
try
return format("%02d%02d%02d", _hour, _minute, _second);
catch(Exception e)
assert(0, "format() threw.");
}
unittest
{
version(testStdDateTime)
{
auto tod = TimeOfDay(12, 30, 33);
const ctod = TimeOfDay(12, 30, 33);
immutable itod = TimeOfDay(12, 30, 33);
static assert(__traits(compiles, tod.toISOString()));
static assert(__traits(compiles, ctod.toISOString()));
static assert(__traits(compiles, itod.toISOString()));
//Verify Examples.
assert(TimeOfDay(0, 0, 0).toISOString() == "000000");
assert(TimeOfDay(12, 30, 33).toISOString() == "123033");
}
}
/++
Converts this $(D TimeOfDay) to a string with the format HH:MM:SS.
Examples:
--------------------
assert(TimeOfDay(0, 0, 0).toISOExtString() == "000000");
assert(TimeOfDay(12, 30, 33).toISOExtString() == "123033");
--------------------
+/
string toISOExtString() const nothrow
{
try
return format("%02d:%02d:%02d", _hour, _minute, _second);
catch(Exception e)
assert(0, "format() threw.");
}
/++
$(RED Scheduled for deprecation in November 2011.
Please use toISOExtString instead.)
+/
alias toISOExtString toISOExtendedString;
unittest
{
version(testStdDateTime)
{
auto tod = TimeOfDay(12, 30, 33);
const ctod = TimeOfDay(12, 30, 33);
immutable itod = TimeOfDay(12, 30, 33);
static assert(__traits(compiles, tod.toISOExtString()));
static assert(__traits(compiles, ctod.toISOExtString()));
static assert(__traits(compiles, itod.toISOExtString()));
//Verify Examples.
assert(TimeOfDay(0, 0, 0).toISOExtString() == "00:00:00");
assert(TimeOfDay(12, 30, 33).toISOExtString() == "12:30:33");
}
}
/+
Converts this $(D TimeOfDay) to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString()
{
return toISOExtString();
}
/++
Converts this TimeOfDay to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString() const nothrow
{
return toISOExtString();
}
unittest
{
version(testStdDateTime)
{
auto tod = TimeOfDay(12, 30, 33);
const ctod = TimeOfDay(12, 30, 33);
immutable itod = TimeOfDay(12, 30, 33);
static assert(__traits(compiles, tod.toString()));
static assert(__traits(compiles, ctod.toString()));
static assert(__traits(compiles, itod.toString()));
}
}
//TODO Add a function which returns a string in a user-specified format.
/++
Creates a $(D TimeOfDay) from a string with the format HHMMSS.
Whitespace is stripped from the given string.
Params:
isoString = A string formatted in the ISO format for times.
Throws:
$(D DateTimeException) if the given string is not in the ISO format
or if the resulting $(D TimeOfDay) would not be valid.
Examples:
--------------------
assert(TimeOfDay.fromISOString("000000") == TimeOfDay(0, 0, 0));
assert(TimeOfDay.fromISOString("123033") == TimeOfDay(12, 30, 33));
assert(TimeOfDay.fromISOString(" 123033 ") == TimeOfDay(12, 30, 33));
--------------------
+/
static TimeOfDay fromISOString(S)(in S isoString)
if(isSomeString!S)
{
auto dstr = to!dstring(strip(isoString));
enforce(dstr.length == 6, new DateTimeException(format("Invalid ISO String: %s", isoString)));
auto hours = dstr[0 .. 2];
auto minutes = dstr[2 .. 4];
auto seconds = dstr[4 .. $];
enforce(!canFind!(not!isDigit)(hours), new DateTimeException(format("Invalid ISO String: %s", isoString)));
enforce(!canFind!(not!isDigit)(minutes), new DateTimeException(format("Invalid ISO String: %s", isoString)));
enforce(!canFind!(not!isDigit)(seconds), new DateTimeException(format("Invalid ISO String: %s", isoString)));
return TimeOfDay(to!int(hours), to!int(minutes), to!int(seconds));
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(TimeOfDay.fromISOString(""));
assertThrown!DateTimeException(TimeOfDay.fromISOString("0"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("00"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("000"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("0000"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("00000"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("13033"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("1277"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12707"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12070"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12303a"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("1230a3"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("123a33"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12a033"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("1a0033"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("a20033"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("1200330"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("0120033"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("-120033"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("+120033"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("120033am"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("120033pm"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("0::"));
assertThrown!DateTimeException(TimeOfDay.fromISOString(":0:"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("::0"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("0:0:0"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("0:0:00"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("0:00:0"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("00:0:0"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("00:00:0"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("00:0:00"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("13:0:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:7:7"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:7:07"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:07:0"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:30:3a"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:30:a3"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:3a:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:a0:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("1a:00:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("a2:00:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:003:30"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("120:03:30"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("012:00:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("01:200:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("-12:00:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("+12:00:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:00:33am"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:00:33pm"));
assertThrown!DateTimeException(TimeOfDay.fromISOString("12:00:33"));
_assertPred!"=="(TimeOfDay.fromISOString("011217"), TimeOfDay(1, 12, 17));
_assertPred!"=="(TimeOfDay.fromISOString("001412"), TimeOfDay(0, 14, 12));
_assertPred!"=="(TimeOfDay.fromISOString("000007"), TimeOfDay(0, 0, 7));
_assertPred!"=="(TimeOfDay.fromISOString("011217 "), TimeOfDay(1, 12, 17));
_assertPred!"=="(TimeOfDay.fromISOString(" 011217"), TimeOfDay(1, 12, 17));
_assertPred!"=="(TimeOfDay.fromISOString(" 011217 "), TimeOfDay(1, 12, 17));
//Verify Examples.
assert(TimeOfDay.fromISOString("000000") == TimeOfDay(0, 0, 0));
assert(TimeOfDay.fromISOString("123033") == TimeOfDay(12, 30, 33));
assert(TimeOfDay.fromISOString(" 123033 ") == TimeOfDay(12, 30, 33));
}
}
/++
Creates a $(D TimeOfDay) from a string with the format HH:MM:SS.
Whitespace is stripped from the given string.
Params:
isoString = A string formatted in the ISO Extended format for times.
Throws:
$(D DateTimeException) if the given string is not in the ISO
Extended format or if the resulting $(D TimeOfDay) would not be
valid.
Examples:
--------------------
assert(TimeOfDay.fromISOExtString("00:00:00") == TimeOfDay(0, 0, 0));
assert(TimeOfDay.fromISOExtString("12:30:33") == TimeOfDay(12, 30, 33));
assert(TimeOfDay.fromISOExtString(" 12:30:33 ") == TimeOfDay(12, 30, 33));
--------------------
+/
static TimeOfDay fromISOExtString(S)(in S isoExtString)
if(isSomeString!S)
{
auto dstr = to!dstring(strip(isoExtString));
enforce(dstr.length == 8, new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
auto hours = dstr[0 .. 2];
auto minutes = dstr[3 .. 5];
auto seconds = dstr[6 .. $];
enforce(dstr[2] == ':', new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
enforce(dstr[5] == ':', new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
enforce(!canFind!(not!isDigit)(hours),
new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
enforce(!canFind!(not!isDigit)(minutes),
new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
enforce(!canFind!(not!isDigit)(seconds),
new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
return TimeOfDay(to!int(hours), to!int(minutes), to!int(seconds));
}
/++
$(RED Scheduled for deprecation in November 2011.
Please use fromISOExtString instead.)
+/
static TimeOfDay fromISOExtendedString(S)(in S isoExtString)
if(isSomeString!(S))
{
pragma(msg, softDeprec!("2.053", "November 2011", "fromISOExtendedString", "fromISOExtString"));
return fromISOExtString!string(isoExtString);
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(TimeOfDay.fromISOExtString(""));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("0"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("00"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("000"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("0000"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("00000"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("13033"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("1277"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12707"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12070"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12303a"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("1230a3"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("123a33"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12a033"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("1a0033"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("a20033"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("1200330"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("0120033"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("-120033"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("+120033"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("120033am"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("120033pm"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("0::"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString(":0:"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("::0"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("0:0:0"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("0:0:00"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("0:00:0"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("00:0:0"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("00:00:0"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("00:0:00"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("13:0:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12:7:7"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12:7:07"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12:07:0"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12:30:3a"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12:30:a3"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12:3a:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12:a0:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("1a:00:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("a2:00:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12:003:30"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("120:03:30"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("012:00:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("01:200:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("-12:00:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("+12:00:33"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12:00:33am"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("12:00:33pm"));
assertThrown!DateTimeException(TimeOfDay.fromISOExtString("120033"));
_assertPred!"=="(TimeOfDay.fromISOExtString("01:12:17"), TimeOfDay(1, 12, 17));
_assertPred!"=="(TimeOfDay.fromISOExtString("00:14:12"), TimeOfDay(0, 14, 12));
_assertPred!"=="(TimeOfDay.fromISOExtString("00:00:07"), TimeOfDay(0, 0, 7));
_assertPred!"=="(TimeOfDay.fromISOExtString("01:12:17 "), TimeOfDay(1, 12, 17));
_assertPred!"=="(TimeOfDay.fromISOExtString(" 01:12:17"), TimeOfDay(1, 12, 17));
_assertPred!"=="(TimeOfDay.fromISOExtString(" 01:12:17 "), TimeOfDay(1, 12, 17));
//Verify Examples.
assert(TimeOfDay.fromISOExtString("00:00:00") == TimeOfDay(0, 0, 0));
assert(TimeOfDay.fromISOExtString("12:30:33") == TimeOfDay(12, 30, 33));
assert(TimeOfDay.fromISOExtString(" 12:30:33 ") == TimeOfDay(12, 30, 33));
}
}
//TODO Add function which takes a user-specified time format and produces a TimeOfDay
//TODO Add function which takes pretty much any time-string and produces a TimeOfDay
// Obviously, it will be less efficient, and it probably won't manage _every_
// possible date format, but a smart conversion function would be nice.
/++
Returns midnight.
+/
@property static TimeOfDay min() pure nothrow
{
return TimeOfDay.init;
}
unittest
{
version(testStdDateTime)
{
assert(TimeOfDay.min.hour == 0);
assert(TimeOfDay.min.minute == 0);
assert(TimeOfDay.min.second == 0);
assert(TimeOfDay.min < TimeOfDay.max);
}
}
/++
Returns one second short of midnight.
+/
@property static TimeOfDay max() pure nothrow
{
auto tod = TimeOfDay.init;
tod._hour = maxHour;
tod._minute = maxMinute;
tod._second = maxSecond;
return tod;
}
unittest
{
version(testStdDateTime)
{
assert(TimeOfDay.max.hour == 23);
assert(TimeOfDay.max.minute == 59);
assert(TimeOfDay.max.second == 59);
assert(TimeOfDay.max > TimeOfDay.min);
}
}
private:
/+
Add seconds to the time of day. Negative values will subtract. If the
number of seconds overflows (or underflows), then the seconds will wrap,
increasing (or decreasing) the number of minutes accordingly. If the
number of minutes overflows (or underflows), then the minutes will wrap.
If the number of minutes overflows(or underflows), then the hour will
wrap. (e.g. adding 90 seconds to 23:59:00 would result in 00:00:30).
Params:
seconds = The number of seconds to add to this TimeOfDay.
+/
ref TimeOfDay addSeconds(long seconds) pure nothrow
{
long hnsecs = convert!("seconds", "hnsecs")(seconds);
hnsecs += convert!("hours", "hnsecs")(_hour);
hnsecs += convert!("minutes", "hnsecs")(_minute);
hnsecs += convert!("seconds", "hnsecs")(_second);
hnsecs %= convert!("days", "hnsecs")(1);
if(hnsecs < 0)
hnsecs += convert!("days", "hnsecs")(1);
immutable newHours = splitUnitsFromHNSecs!"hours"(hnsecs);
immutable newMinutes = splitUnitsFromHNSecs!"minutes"(hnsecs);
immutable newSeconds = splitUnitsFromHNSecs!"seconds"(hnsecs);
_hour = cast(ubyte)newHours;
_minute = cast(ubyte)newMinutes;
_second = cast(ubyte)newSeconds;
return this;
}
unittest
{
version(testStdDateTime)
{
static void testTOD(TimeOfDay orig, int seconds, in TimeOfDay expected, size_t line = __LINE__)
{
orig.addSeconds(seconds);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
testTOD(TimeOfDay(12, 30, 33), 0, TimeOfDay(12, 30, 33));
testTOD(TimeOfDay(12, 30, 33), 1, TimeOfDay(12, 30, 34));
testTOD(TimeOfDay(12, 30, 33), 2, TimeOfDay(12, 30, 35));
testTOD(TimeOfDay(12, 30, 33), 3, TimeOfDay(12, 30, 36));
testTOD(TimeOfDay(12, 30, 33), 4, TimeOfDay(12, 30, 37));
testTOD(TimeOfDay(12, 30, 33), 5, TimeOfDay(12, 30, 38));
testTOD(TimeOfDay(12, 30, 33), 10, TimeOfDay(12, 30, 43));
testTOD(TimeOfDay(12, 30, 33), 15, TimeOfDay(12, 30, 48));
testTOD(TimeOfDay(12, 30, 33), 26, TimeOfDay(12, 30, 59));
testTOD(TimeOfDay(12, 30, 33), 27, TimeOfDay(12, 31, 0));
testTOD(TimeOfDay(12, 30, 33), 30, TimeOfDay(12, 31, 3));
testTOD(TimeOfDay(12, 30, 33), 59, TimeOfDay(12, 31, 32));
testTOD(TimeOfDay(12, 30, 33), 60, TimeOfDay(12, 31, 33));
testTOD(TimeOfDay(12, 30, 33), 61, TimeOfDay(12, 31, 34));
testTOD(TimeOfDay(12, 30, 33), 1766, TimeOfDay(12, 59, 59));
testTOD(TimeOfDay(12, 30, 33), 1767, TimeOfDay(13, 0, 0));
testTOD(TimeOfDay(12, 30, 33), 1768, TimeOfDay(13, 0, 1));
testTOD(TimeOfDay(12, 30, 33), 2007, TimeOfDay(13, 4, 0));
testTOD(TimeOfDay(12, 30, 33), 3599, TimeOfDay(13, 30, 32));
testTOD(TimeOfDay(12, 30, 33), 3600, TimeOfDay(13, 30, 33));
testTOD(TimeOfDay(12, 30, 33), 3601, TimeOfDay(13, 30, 34));
testTOD(TimeOfDay(12, 30, 33), 7200, TimeOfDay(14, 30, 33));
testTOD(TimeOfDay(12, 30, 33), -1, TimeOfDay(12, 30, 32));
testTOD(TimeOfDay(12, 30, 33), -2, TimeOfDay(12, 30, 31));
testTOD(TimeOfDay(12, 30, 33), -3, TimeOfDay(12, 30, 30));
testTOD(TimeOfDay(12, 30, 33), -4, TimeOfDay(12, 30, 29));
testTOD(TimeOfDay(12, 30, 33), -5, TimeOfDay(12, 30, 28));
testTOD(TimeOfDay(12, 30, 33), -10, TimeOfDay(12, 30, 23));
testTOD(TimeOfDay(12, 30, 33), -15, TimeOfDay(12, 30, 18));
testTOD(TimeOfDay(12, 30, 33), -33, TimeOfDay(12, 30, 0));
testTOD(TimeOfDay(12, 30, 33), -34, TimeOfDay(12, 29, 59));
testTOD(TimeOfDay(12, 30, 33), -35, TimeOfDay(12, 29, 58));
testTOD(TimeOfDay(12, 30, 33), -59, TimeOfDay(12, 29, 34));
testTOD(TimeOfDay(12, 30, 33), -60, TimeOfDay(12, 29, 33));
testTOD(TimeOfDay(12, 30, 33), -61, TimeOfDay(12, 29, 32));
testTOD(TimeOfDay(12, 30, 33), -1833, TimeOfDay(12, 0, 0));
testTOD(TimeOfDay(12, 30, 33), -1834, TimeOfDay(11, 59, 59));
testTOD(TimeOfDay(12, 30, 33), -3600, TimeOfDay(11, 30, 33));
testTOD(TimeOfDay(12, 30, 33), -3601, TimeOfDay(11, 30, 32));
testTOD(TimeOfDay(12, 30, 33), -5134, TimeOfDay(11, 4, 59));
testTOD(TimeOfDay(12, 30, 33), -7200, TimeOfDay(10, 30, 33));
testTOD(TimeOfDay(12, 30, 0), 1, TimeOfDay(12, 30, 1));
testTOD(TimeOfDay(12, 30, 0), 0, TimeOfDay(12, 30, 0));
testTOD(TimeOfDay(12, 30, 0), -1, TimeOfDay(12, 29, 59));
testTOD(TimeOfDay(12, 0, 0), 1, TimeOfDay(12, 0, 1));
testTOD(TimeOfDay(12, 0, 0), 0, TimeOfDay(12, 0, 0));
testTOD(TimeOfDay(12, 0, 0), -1, TimeOfDay(11, 59, 59));
testTOD(TimeOfDay(0, 0, 0), 1, TimeOfDay(0, 0, 1));
testTOD(TimeOfDay(0, 0, 0), 0, TimeOfDay(0, 0, 0));
testTOD(TimeOfDay(0, 0, 0), -1, TimeOfDay(23, 59, 59));
testTOD(TimeOfDay(23, 59, 59), 1, TimeOfDay(0, 0, 0));
testTOD(TimeOfDay(23, 59, 59), 0, TimeOfDay(23, 59, 59));
testTOD(TimeOfDay(23, 59, 59), -1, TimeOfDay(23, 59, 58));
const ctod = TimeOfDay(0, 0, 0);
immutable itod = TimeOfDay(0, 0, 0);
static assert(!__traits(compiles, ctod.addSeconds(7)));
static assert(!__traits(compiles, itod.addSeconds(7)));
}
}
/+
Whether the given values form a valid $(D TimeOfDay).
+/
static bool _valid(int hour, int minute, int second) pure nothrow
{
return valid!"hours"(hour) && valid!"minutes"(minute) && valid!"seconds"(second);
}
pure invariant()
{
assert(_valid(_hour, _minute, _second),
"Invariant Failure: hour [" ~
numToString(_hour) ~
"] minute [" ~
numToString(_minute) ~
"] second [" ~
numToString(_second) ~
"]");
}
ubyte _hour;
ubyte _minute;
ubyte _second;
enum ubyte maxHour = 24 - 1;
enum ubyte maxMinute = 60 - 1;
enum ubyte maxSecond = 60 - 1;
}
/++
Combines the $(D Date) and $(D TimeOfDay) structs to give you an object
which holds both the date and the time. It is optimized for calendar-based
operations and has no concept of time zone. If you want an object which is
optimized for time operations based on the system time, then use
$(D SysTime). $(D SysTime) has a concept of time zone and has much higher
precision (hnsecs). $(D DateTime) is intended primarily for calendar-based
uses rather than precise time operations.
+/
struct DateTime
{
public:
/++
Params:
date = The date portion of $(D DateTime).
tod = The time portion of $(D DateTime).
+/
this(in Date date, in TimeOfDay tod = TimeOfDay.init) pure nothrow
{
_date = date;
_tod = tod;
}
unittest
{
version(testStdDateTime)
{
{
auto dt = DateTime.init;
_assertPred!"=="(dt._date, Date.init);
_assertPred!"=="(dt._tod, TimeOfDay.init);
}
{
auto dt = DateTime(Date(1999, 7 ,6));
_assertPred!"=="(dt._date, Date(1999, 7, 6));
_assertPred!"=="(dt._tod, TimeOfDay.init);
}
{
auto dt = DateTime(Date(1999, 7 ,6), TimeOfDay(12, 30, 33));
_assertPred!"=="(dt._date, Date(1999, 7, 6));
_assertPred!"=="(dt._tod, TimeOfDay(12, 30, 33));
}
}
}
/++
Params:
year = The year portion of the date.
month = The month portion of the date.
day = The day portion of the date.
hour = The hour portion of the time;
minute = The minute portion of the time;
second = The second portion of the time;
+/
this(int year, int month, int day,
int hour = 0, int minute = 0, int second = 0) pure
{
_date = Date(year, month, day);
_tod = TimeOfDay(hour, minute, second);
}
unittest
{
version(testStdDateTime)
{
{
auto dt = DateTime(1999, 7 ,6);
_assertPred!"=="(dt._date, Date(1999, 7, 6));
_assertPred!"=="(dt._tod, TimeOfDay.init);
}
{
auto dt = DateTime(1999, 7 ,6, 12, 30, 33);
_assertPred!"=="(dt._date, Date(1999, 7, 6));
_assertPred!"=="(dt._tod, TimeOfDay(12, 30, 33));
}
}
}
/++
Compares this $(D DateTime) with the given $(D DateTime.).
Returns:
$(BOOKTABLE,
$(TR $(TD this < rhs) $(TD < 0))
$(TR $(TD this == rhs) $(TD 0))
$(TR $(TD this > rhs) $(TD > 0))
)
+/
int opCmp(in DateTime rhs) const pure nothrow
{
immutable dateResult = _date.opCmp(rhs._date);
if(dateResult != 0)
return dateResult;
return _tod.opCmp(rhs._tod);
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!("opCmp", "==")(DateTime(Date.init, TimeOfDay.init), DateTime.init);
_assertPred!("opCmp", "==")(DateTime(Date(1999, 1, 1)), DateTime(Date(1999, 1, 1)));
_assertPred!("opCmp", "==")(DateTime(Date(1, 7, 1)), DateTime(Date(1, 7, 1)));
_assertPred!("opCmp", "==")(DateTime(Date(1, 1, 6)), DateTime(Date(1, 1, 6)));
_assertPred!("opCmp", "==")(DateTime(Date(1999, 7, 1)), DateTime(Date(1999, 7, 1)));
_assertPred!("opCmp", "==")(DateTime(Date(1999, 7, 6)), DateTime(Date(1999, 7, 6)));
_assertPred!("opCmp", "==")(DateTime(Date(1, 7, 6)), DateTime(Date(1, 7, 6)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6)), DateTime(Date(2000, 7, 6)));
_assertPred!("opCmp", ">")(DateTime(Date(2000, 7, 6)), DateTime(Date(1999, 7, 6)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6)), DateTime(Date(1999, 8, 6)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 8, 6)), DateTime(Date(1999, 7, 6)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6)), DateTime(Date(1999, 7, 7)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 7)), DateTime(Date(1999, 7, 6)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 8, 7)), DateTime(Date(2000, 7, 6)));
_assertPred!("opCmp", ">")(DateTime(Date(2000, 8, 6)), DateTime(Date(1999, 7, 7)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 7)), DateTime(Date(2000, 7, 6)));
_assertPred!("opCmp", ">")(DateTime(Date(2000, 7, 6)), DateTime(Date(1999, 7, 7)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 7)), DateTime(Date(1999, 8, 6)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 8, 6)), DateTime(Date(1999, 7, 7)));
_assertPred!("opCmp", "==")(DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 0)),
DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 0)));
_assertPred!("opCmp", "==")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 0)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 0)));
_assertPred!("opCmp", "==")(DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 0)),
DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 0)));
_assertPred!("opCmp", "==")(DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 33)));
_assertPred!("opCmp", "==")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 0)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 0)));
_assertPred!("opCmp", "==")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "==")(DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 33)));
_assertPred!("opCmp", "==")(DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)),
DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)),
DateTime(Date(2000, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(2000, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)),
DateTime(Date(2000, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(2000, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)),
DateTime(Date(2000, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(2000, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)),
DateTime(Date(1999, 8, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 8, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)),
DateTime(Date(1999, 8, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 8, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)),
DateTime(Date(1999, 8, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 8, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)),
DateTime(Date(1999, 7, 7), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 7), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)),
DateTime(Date(1999, 7, 7), TimeOfDay(12, 31, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 7), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)),
DateTime(Date(1999, 7, 7), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 7), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)));
//Test B.C.
_assertPred!("opCmp", "==")(DateTime(Date(-1, 1, 1), TimeOfDay(12, 30, 33)),
DateTime(Date(-1, 1, 1), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "==")(DateTime(Date(-1, 7, 1), TimeOfDay(12, 30, 33)),
DateTime(Date(-1, 7, 1), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "==")(DateTime(Date(-1, 1, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1, 1, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "==")(DateTime(Date(-1999, 7, 1), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 1), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "==")(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "==")(DateTime(Date(-1, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(-2000, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-2000, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 8, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(-1999, 8, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 7), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(-1999, 7, 7), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(-2000, 8, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 7), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(-1999, 8, 7), TimeOfDay(12, 30, 33)),
DateTime(Date(-2000, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(-2000, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 7), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(-1999, 7, 7), TimeOfDay(12, 30, 33)),
DateTime(Date(-2000, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(-1999, 7, 7), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 8, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(-1999, 8, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 7), TimeOfDay(12, 30, 33)));
//Test Both
_assertPred!("opCmp", "<")(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(-1999, 8, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 8, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(-1999, 7, 7), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 7), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(-1999, 8, 7), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 8, 7), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", "<")(DateTime(Date(-1999, 8, 6), TimeOfDay(12, 30, 33)),
DateTime(Date(1999, 6, 6), TimeOfDay(12, 30, 33)));
_assertPred!("opCmp", ">")(DateTime(Date(1999, 6, 8), TimeOfDay(12, 30, 33)),
DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
auto dt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 33, 30));
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 33, 30));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 33, 30));
static assert(__traits(compiles, dt.opCmp(dt)));
static assert(__traits(compiles, dt.opCmp(cdt)));
static assert(__traits(compiles, dt.opCmp(idt)));
static assert(__traits(compiles, cdt.opCmp(dt)));
static assert(__traits(compiles, cdt.opCmp(cdt)));
static assert(__traits(compiles, cdt.opCmp(idt)));
static assert(__traits(compiles, idt.opCmp(dt)));
static assert(__traits(compiles, idt.opCmp(cdt)));
static assert(__traits(compiles, idt.opCmp(idt)));
}
}
/++
The date portion of $(D DateTime).
+/
@property Date date() const pure nothrow
{
return _date;
}
unittest
{
version(testStdDateTime)
{
{
auto dt = DateTime.init;
_assertPred!"=="(dt.date, Date.init);
}
{
auto dt = DateTime(Date(1999, 7, 6));
_assertPred!"=="(dt.date, Date(1999, 7, 6));
}
const cdt = DateTime(1999, 7, 6);
immutable idt = DateTime(1999, 7, 6);
static assert(__traits(compiles, cdt.date == Date(2010, 1, 1)));
static assert(__traits(compiles, idt.date == Date(2010, 1, 1)));
}
}
/++
The date portion of $(D DateTime).
Params:
date = The Date to set this $(D DateTime)'s date portion to.
+/
@property void date(in Date date) pure nothrow
{
_date = date;
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime.init;
dt.date = Date(1999, 7, 6);
_assertPred!"=="(dt._date, Date(1999, 7, 6));
_assertPred!"=="(dt._tod, TimeOfDay.init);
const cdt = DateTime(1999, 7, 6);
immutable idt = DateTime(1999, 7, 6);
static assert(!__traits(compiles, cdt.date = Date(2010, 1, 1)));
static assert(!__traits(compiles, idt.date = Date(2010, 1, 1)));
}
}
/++
The time portion of $(D DateTime).
+/
@property TimeOfDay timeOfDay() const pure nothrow
{
return _tod;
}
unittest
{
version(testStdDateTime)
{
{
auto dt = DateTime.init;
_assertPred!"=="(dt.timeOfDay, TimeOfDay.init);
}
{
auto dt = DateTime(Date.init, TimeOfDay(12, 30, 33));
_assertPred!"=="(dt.timeOfDay, TimeOfDay(12, 30, 33));
}
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, cdt.timeOfDay == TimeOfDay(12, 30, 33)));
static assert(__traits(compiles, idt.timeOfDay == TimeOfDay(12, 30, 33)));
}
}
/++
The time portion of $(D DateTime).
Params:
tod = The $(D TimeOfDay) to set this $(D DateTime)'s time portion
to.
+/
@property void timeOfDay(in TimeOfDay tod) pure nothrow
{
_tod = tod;
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime.init;
dt.timeOfDay = TimeOfDay(12, 30, 33);
_assertPred!"=="(dt._date, date.init);
_assertPred!"=="(dt._tod, TimeOfDay(12, 30, 33));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.timeOfDay = TimeOfDay(12, 30, 33)));
static assert(!__traits(compiles, idt.timeOfDay = TimeOfDay(12, 30, 33)));
}
}
/++
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive
are B.C.
+/
@property short year() const pure nothrow
{
return _date.year;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(Date.init.year, 1);
_assertPred!"=="(Date(1999, 7, 6).year, 1999);
_assertPred!"=="(Date(-1999, 7, 6).year, -1999);
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, idt.year));
static assert(__traits(compiles, idt.year));
}
}
/++
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive
are B.C.
Params:
year = The year to set this $(D DateTime)'s year to.
Throws:
$(D DateTimeException) if the new year is not a leap year and if the
resulting date would be on February 29th.
Examples:
--------------------
assert(DateTime(Date(1999, 7, 6), TimeOfDay(9, 7, 5)).year == 1999);
assert(DateTime(Date(2010, 10, 4), TimeOfDay(0, 0, 30)).year == 2010);
assert(DateTime(Date(-7, 4, 5), TimeOfDay(7, 45, 2)).year == -7);
--------------------
+/
@property void year(int year) pure
{
_date.year = year;
}
unittest
{
version(testStdDateTime)
{
static void testDT(DateTime dt, int year, in DateTime expected, size_t line = __LINE__)
{
dt.year = year;
_assertPred!"=="(dt, expected, "", __FILE__, line);
}
testDT(DateTime(Date(1, 1, 1), TimeOfDay(12, 30, 33)), 1999, DateTime(Date(1999, 1, 1), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1, 1, 1), TimeOfDay(12, 30, 33)), 0, DateTime(Date(0, 1, 1), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1, 1, 1), TimeOfDay(12, 30, 33)), -1999, DateTime(Date(-1999, 1, 1), TimeOfDay(12, 30, 33)));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.year = 7));
static assert(!__traits(compiles, idt.year = 7));
//Verify Examples.
assert(DateTime(Date(1999, 7, 6), TimeOfDay(9, 7, 5)).year == 1999);
assert(DateTime(Date(2010, 10, 4), TimeOfDay(0, 0, 30)).year == 2010);
assert(DateTime(Date(-7, 4, 5), TimeOfDay(7, 45, 2)).year == -7);
}
}
/++
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C.
Throws:
$(D DateTimeException) if $(D isAD) is true.
Examples:
--------------------
assert(DateTime(Date(0, 1, 1), TimeOfDay(12, 30, 33)).yearBC == 1);
assert(DateTime(Date(-1, 1, 1), TimeOfDay(10, 7, 2)).yearBC == 2);
assert(DateTime(Date(-100, 1, 1), TimeOfDay(4, 59, 0)).yearBC == 101);
--------------------
+/
@property short yearBC() const pure
{
return _date.yearBC;
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException((in DateTime dt){dt.yearBC;}(DateTime(Date(1, 1, 1))));
auto dt = DateTime(1999, 7, 6, 12, 30, 33);
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, dt.yearBC = 12));
static assert(!__traits(compiles, cdt.yearBC = 12));
static assert(!__traits(compiles, idt.yearBC = 12));
//Verify Examples.
assert(DateTime(Date(0, 1, 1), TimeOfDay(12, 30, 33)).yearBC == 1);
assert(DateTime(Date(-1, 1, 1), TimeOfDay(10, 7, 2)).yearBC == 2);
assert(DateTime(Date(-100, 1, 1), TimeOfDay(4, 59, 0)).yearBC == 101);
}
}
/++
Year B.C. of the Gregorian Calendar counting year 0 as 1 B.C.
Params:
year = The year B.C. to set this $(D DateTime)'s year to.
Throws:
$(D DateTimeException) if a non-positive value is given.
Examples:
--------------------
auto dt = DateTime(Date(2010, 1, 1), TimeOfDay(7, 30, 0));
dt.yearBC = 1;
assert(dt == DateTime(Date(0, 1, 1), TimeOfDay(7, 30, 0)));
dt.yearBC = 10;
assert(dt == DateTime(Date(-9, 1, 1), TimeOfDay(7, 30, 0)));
--------------------
+/
@property void yearBC(int year) pure
{
_date.yearBC = year;
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException((DateTime dt){dt.yearBC = -1;}(DateTime(Date(1, 1, 1))));
{
auto dt = DateTime(1999, 7, 6, 12, 30, 33);
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, dt.yearBC = 12));
static assert(!__traits(compiles, cdt.yearBC = 12));
static assert(!__traits(compiles, idt.yearBC = 12));
}
//Verify Examples.
{
auto dt = DateTime(Date(2010, 1, 1), TimeOfDay(7, 30, 0));
dt.yearBC = 1;
assert(dt == DateTime(Date(0, 1, 1), TimeOfDay(7, 30, 0)));
dt.yearBC = 10;
assert(dt == DateTime(Date(-9, 1, 1), TimeOfDay(7, 30, 0)));
}
}
}
/++
Month of a Gregorian Year.
Examples:
--------------------
assert(DateTime(Date(1999, 7, 6), TimeOfDay(9, 7, 5)).month == 7);
assert(DateTime(Date(2010, 10, 4), TimeOfDay(0, 0, 30)).month == 10);
assert(DateTime(Date(-7, 4, 5), TimeOfDay(7, 45, 2)).month == 4);
--------------------
+/
@property Month month() const pure nothrow
{
return _date.month;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(DateTime.init.month, 1);
_assertPred!"=="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)).month, 7);
_assertPred!"=="(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)).month, 7);
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, cdt.month));
static assert(__traits(compiles, idt.month));
//Verify Examples.
assert(DateTime(Date(1999, 7, 6), TimeOfDay(9, 7, 5)).month == 7);
assert(DateTime(Date(2010, 10, 4), TimeOfDay(0, 0, 30)).month == 10);
assert(DateTime(Date(-7, 4, 5), TimeOfDay(7, 45, 2)).month == 4);
}
}
/++
Month of a Gregorian Year.
Params:
month = The month to set this $(D DateTime)'s month to.
Throws:
$(D DateTimeException) if the given month is not a valid month.
+/
@property void month(Month month) pure
{
_date.month = month;
}
unittest
{
version(testStdDateTime)
{
static void testDT(DateTime dt, Month month, in DateTime expected = DateTime.init, size_t line = __LINE__)
{
dt.month = month;
assert(expected != DateTime.init);
_assertPred!"=="(dt, expected, "", __FILE__, line);
}
assertThrown!DateTimeException(testDT(DateTime(Date(1, 1, 1), TimeOfDay(12, 30, 33)), cast(Month)0));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 1, 1), TimeOfDay(12, 30, 33)), cast(Month)13));
testDT(DateTime(Date(1, 1, 1), TimeOfDay(12, 30, 33)), cast(Month)7, DateTime(Date(1, 7, 1), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1, 1, 1), TimeOfDay(12, 30, 33)), cast(Month)7, DateTime(Date(-1, 7, 1), TimeOfDay(12, 30, 33)));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.month = 12));
static assert(!__traits(compiles, idt.month = 12));
}
}
/++
Day of a Gregorian Month.
Examples:
--------------------
assert(DateTime(Date(1999, 7, 6), TimeOfDay(9, 7, 5)).day == 6);
assert(DateTime(Date(2010, 10, 4), TimeOfDay(0, 0, 30)).day == 4);
assert(DateTime(Date(-7, 4, 5), TimeOfDay(7, 45, 2)).day == 5);
--------------------
+/
@property ubyte day() const pure nothrow
{
return _date.day;
}
//Verify Examples.
version(testStdDateTime) unittest
{
assert(DateTime(Date(1999, 7, 6), TimeOfDay(9, 7, 5)).day == 6);
assert(DateTime(Date(2010, 10, 4), TimeOfDay(0, 0, 30)).day == 4);
assert(DateTime(Date(-7, 4, 5), TimeOfDay(7, 45, 2)).day == 5);
}
version(testStdDateTime) unittest
{
static void test(DateTime dateTime, int expected, size_t line = __LINE__)
{
_assertPred!"=="(dateTime.day, expected,
format("Value given: %s", dateTime), __FILE__, line);
}
foreach(year; chain(testYearsBC, testYearsAD))
{
foreach(md; testMonthDays)
{
foreach(tod; testTODs)
test(DateTime(Date(year, md.month, md.day), tod), md.day);
}
}
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, cdt.day));
static assert(__traits(compiles, idt.day));
}
/++
Day of a Gregorian Month.
Params:
day = The day of the month to set this $(D DateTime)'s day to.
Throws:
$(D DateTimeException) if the given day is not a valid day of the
current month.
+/
@property void day(int day) pure
{
_date.day = day;
}
unittest
{
version(testStdDateTime)
{
static void testDT(DateTime dt, int day)
{
dt.day = day;
}
//Test A.D.
assertThrown!DateTimeException(testDT(DateTime(Date(1, 1, 1)), 0));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 1, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 2, 1)), 29));
assertThrown!DateTimeException(testDT(DateTime(Date(4, 2, 1)), 30));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 3, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 4, 1)), 31));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 5, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 6, 1)), 31));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 7, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 8, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 9, 1)), 31));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 10, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 11, 1)), 31));
assertThrown!DateTimeException(testDT(DateTime(Date(1, 12, 1)), 32));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 1, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 2, 1)), 28));
assertNotThrown!DateTimeException(testDT(DateTime(Date(4, 2, 1)), 29));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 3, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 4, 1)), 30));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 5, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 6, 1)), 30));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 7, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 8, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 9, 1)), 30));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 10, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 11, 1)), 30));
assertNotThrown!DateTimeException(testDT(DateTime(Date(1, 12, 1)), 31));
{
auto dt = DateTime(Date(1, 1, 1), TimeOfDay(7, 12, 22));
dt.day = 6;
_assertPred!"=="(dt, DateTime(Date(1, 1, 6), TimeOfDay(7, 12, 22)));
}
//Test B.C.
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 1, 1)), 0));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 1, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 2, 1)), 29));
assertThrown!DateTimeException(testDT(DateTime(Date(0, 2, 1)), 30));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 3, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 4, 1)), 31));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 5, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 6, 1)), 31));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 7, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 8, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 9, 1)), 31));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 10, 1)), 32));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 11, 1)), 31));
assertThrown!DateTimeException(testDT(DateTime(Date(-1, 12, 1)), 32));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 1, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 2, 1)), 28));
assertNotThrown!DateTimeException(testDT(DateTime(Date(0, 2, 1)), 29));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 3, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 4, 1)), 30));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 5, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 6, 1)), 30));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 7, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 8, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 9, 1)), 30));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 10, 1)), 31));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 11, 1)), 30));
assertNotThrown!DateTimeException(testDT(DateTime(Date(-1, 12, 1)), 31));
auto dt = DateTime(Date(-1, 1, 1), TimeOfDay(7, 12, 22));
dt.day = 6;
_assertPred!"=="(dt, DateTime(Date(-1, 1, 6), TimeOfDay(7, 12, 22)));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.day = 27));
static assert(!__traits(compiles, idt.day = 27));
}
}
/++
Hours passed midnight.
+/
@property ubyte hour() const pure nothrow
{
return _tod.hour;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(DateTime.init.hour, 0);
_assertPred!"=="(DateTime(Date.init, TimeOfDay(12, 0, 0)).hour, 12);
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, cdt.hour));
static assert(__traits(compiles, idt.hour));
}
}
/++
Hours passed midnight.
Params:
hour = The hour of the day to set this $(D DateTime)'s hour to.
Throws:
$(D DateTimeException) if the given hour would result in an invalid
$(D DateTime).
+/
@property void hour(int hour) pure
{
_tod.hour = hour;
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException((){DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 0)).hour = 24;}());
auto dt = DateTime.init;
dt.hour = 12;
_assertPred!"=="(dt, DateTime(1, 1, 1, 12, 0, 0));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.hour = 27));
static assert(!__traits(compiles, idt.hour = 27));
}
}
/++
Minutes passed the hour.
+/
@property ubyte minute() const pure nothrow
{
return _tod.minute;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(DateTime.init.minute, 0);
_assertPred!"=="(DateTime(1, 1, 1, 0, 30, 0).minute, 30);
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, cdt.minute));
static assert(__traits(compiles, idt.minute));
}
}
/++
Minutes passed the hour.
Params:
minute = The minute to set this $(D DateTime)'s minute to.
Throws:
$(D DateTimeException) if the given minute would result in an
invalid $(D DateTime).
+/
@property void minute(int minute) pure
{
_tod.minute = minute;
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException((){DateTime.init.minute = 60;}());
auto dt = DateTime.init;
dt.minute = 30;
_assertPred!"=="(dt, DateTime(1, 1, 1, 0, 30, 0));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.minute = 27));
static assert(!__traits(compiles, idt.minute = 27));
}
}
/++
Seconds passed the minute.
+/
@property ubyte second() const pure nothrow
{
return _tod.second;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(DateTime.init.second, 0);
_assertPred!"=="(DateTime(1, 1, 1, 0, 0, 33).second, 33);
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, cdt.second));
static assert(__traits(compiles, idt.second));
}
}
/++
Seconds passed the minute.
Params:
second = The second to set this $(D DateTime)'s second to.
Throws:
$(D DateTimeException) if the given seconds would result in an
invalid $(D DateTime).
+/
@property void second(int second) pure
{
_tod.second = second;
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException((){DateTime.init.second = 60;}());
auto dt = DateTime.init;
dt.second = 33;
_assertPred!"=="(dt, DateTime(1, 1, 1, 0, 0, 33));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.second = 27));
static assert(!__traits(compiles, idt.second = 27));
}
}
/++
Adds the given number of years or months to this $(D DateTime). A
negative number will subtract.
Note that if day overflow is allowed, and the date with the adjusted
year/month overflows the number of days in the new month, then the month
will be incremented by one, and the day set to the number of days
overflowed. (e.g. if the day were 31 and the new month were June, then
the month would be incremented to July, and the new day would be 1). If
day overflow is not allowed, then the day will be set to the last valid
day in the month (e.g. June 31st would become June 30th).
Params:
units = The type of units to add ("years" or "months").
value = The number of months or years to add to this
$(D DateTime).
allowOverflow = Whether the days should be allowed to overflow,
causing the month to increment.
Examples:
--------------------
auto dt1 = DateTime(2010, 1, 1, 12, 30, 33);
dt1.add!"months"(11);
assert(dt1 == DateTime(2010, 12, 1, 12, 30, 33));
auto dt2 = DateTime(2010, 1, 1, 12, 30, 33);
dt2.add!"months"(-11);
assert(dt2 == DateTime(2009, 2, 1, 12, 30, 33));
auto dt3 = DateTime(2000, 2, 29, 12, 30, 33);
dt3.add!"years"(1);
assert(dt3 == DateTime(2001, 3, 1, 12, 30, 33));
auto dt4 = DateTime(2000, 2, 29, 12, 30, 33);
dt4.add!"years"(1, AllowDayOverflow.no);
assert(dt4 == DateTime(2001, 2, 28, 12, 30, 33));
--------------------
+/
/+ref DateTime+/ void add(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes) pure nothrow
if(units == "years" ||
units == "months")
{
_date.add!units(value, allowOverflow);
}
//Verify Examples.
unittest
{
version(testStdDateTime)
{
auto dt1 = DateTime(2010, 1, 1, 12, 30, 33);
dt1.add!"months"(11);
assert(dt1 == DateTime(2010, 12, 1, 12, 30, 33));
auto dt2 = DateTime(2010, 1, 1, 12, 30, 33);
dt2.add!"months"(-11);
assert(dt2 == DateTime(2009, 2, 1, 12, 30, 33));
auto dt3 = DateTime(2000, 2, 29, 12, 30, 33);
dt3.add!"years"(1);
assert(dt3 == DateTime(2001, 3, 1, 12, 30, 33));
auto dt4 = DateTime(2000, 2, 29, 12, 30, 33);
dt4.add!"years"(1, AllowDayOverflow.no);
assert(dt4 == DateTime(2001, 2, 28, 12, 30, 33));
}
}
unittest
{
version(testStdDateTime)
{
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.add!"years"(4)));
static assert(!__traits(compiles, idt.add!"years"(4)));
static assert(!__traits(compiles, cdt.add!"months"(4)));
static assert(!__traits(compiles, idt.add!"months"(4)));
}
}
/++
Adds the given number of years or months to this $(D DateTime). A
negative number will subtract.
The difference between rolling and adding is that rolling does not
affect larger units. So, if you roll a $(D DateTime) 12 months, you
get the exact same $(D DateTime). However, the days can still be
affected due to the differing number of days in each month.
Because there are no units larger than years, there is no difference
between adding and rolling years.
Params:
units = The type of units to add ("years" or "months").
value = The number of months or years to add to this
$(D DateTime).
allowOverflow = Whether the days should be allowed to overflow,
causing the month to increment.
Examples:
--------------------
auto dt1 = DateTime(2010, 1, 1, 12, 33, 33);
dt1.roll!"months"(1);
assert(dt1 == DateTime(2010, 2, 1, 12, 33, 33));
auto dt2 = DateTime(2010, 1, 1, 12, 33, 33);
dt2.roll!"months"(-1);
assert(dt2 == DateTime(2010, 12, 1, 12, 33, 33));
auto dt3 = DateTime(1999, 1, 29, 12, 33, 33);
dt3.roll!"months"(1);
assert(dt3 == DateTime(1999, 3, 1, 12, 33, 33));
auto dt4 = DateTime(1999, 1, 29, 12, 33, 33);
dt4.roll!"months"(1, AllowDayOverflow.no);
assert(dt4 == DateTime(1999, 2, 28, 12, 33, 33));
auto dt5 = DateTime(2000, 2, 29, 12, 30, 33);
dt5.roll!"years"(1);
assert(dt5 == DateTime(2001, 3, 1, 12, 30, 33));
auto dt6 = DateTime(2000, 2, 29, 12, 30, 33);
dt6.roll!"years"(1, AllowDayOverflow.no);
assert(dt6 == DateTime(2001, 2, 28, 12, 30, 33));
--------------------
+/
/+ref DateTime+/ void roll(string units)(long value, AllowDayOverflow allowOverflow = AllowDayOverflow.yes) pure nothrow
if(units == "years" ||
units == "months")
{
_date.roll!units(value, allowOverflow);
}
//Verify Examples.
unittest
{
version(testdStdDateTime)
{
auto dt1 = DateTime(2010, 1, 1, 12, 33, 33);
dt1.roll!"months"(1);
assert(dt1 == DateTime(2010, 2, 1, 12, 33, 33));
auto dt2 = DateTime(2010, 1, 1, 12, 33, 33);
dt2.roll!"months"(-1);
assert(dt2 == DateTime(2010, 12, 1, 12, 33, 33));
auto dt3 = DateTime(1999, 1, 29, 12, 33, 33);
dt3.roll!"months"(1);
assert(dt3 == DateTime(1999, 3, 1, 12, 33, 33));
auto dt4 = DateTime(1999, 1, 29, 12, 33, 33);
dt4.roll!"months"(1, AllowDayOverflow.no);
assert(dt4 == DateTime(1999, 2, 28, 12, 33, 33));
auto dt5 = DateTime(2000, 2, 29, 12, 30, 33);
dt5.roll!"years"(1);
assert(dt5 == DateTime(2001, 3, 1, 12, 30, 33));
auto dt6 = DateTime(2000, 2, 29, 12, 30, 33);
dt6.roll!"years"(1, AllowDayOverflow.no);
assert(dt6 == DateTime(2001, 2, 28, 12, 30, 33));
}
}
unittest
{
version(testStdDateTime)
{
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.roll!"years"(4)));
static assert(!__traits(compiles, idt.roll!"years"(4)));
static assert(!__traits(compiles, cdt.roll!"months"(4)));
static assert(!__traits(compiles, idt.roll!"months"(4)));
static assert(!__traits(compiles, cdt.roll!"days"(4)));
static assert(!__traits(compiles, idt.roll!"days"(4)));
}
}
/++
Adds the given number of units to this $(D DateTime). A negative number
will subtract.
The difference between rolling and adding is that rolling does not
affect larger units. So, for instance, if you roll a $(D DateTime) one
year's worth of days, then you get the exact same $(D DateTime).
Accepted units are $(D "days"), $(D "minutes"), $(D "hours"),
$(D "minutes"), and $(D "seconds").
Params:
units = The units to add.
value = The number of $(D_PARAM units) to add to this $(D DateTime).
Examples:
--------------------
auto dt1 = DateTime(2010, 1, 1, 11, 23, 12);
dt1.roll!"days"(1);
assert(dt1 == DateTime(2010, 1, 2, 11, 23, 12));
dt1.roll!"days"(365);
assert(dt1 == DateTime(2010, 1, 26, 11, 23, 12));
dt1.roll!"days"(-32);
assert(dt1 == DateTime(2010, 1, 25, 11, 23, 12));
auto dt2 = DateTime(2010, 7, 4, 12, 0, 0);
dt2.roll!"hours"(1);
assert(dt2 == DateTime(2010, 7, 4, 13, 0, 0));
auto dt3 = DateTime(2010, 1, 1, 0, 0, 0);
dt3.roll!"seconds"(-1);
assert(dt3 == DateTime(2010, 1, 1, 0, 0, 59));
--------------------
+/
/+ref DateTime+/ void roll(string units)(long days) pure nothrow
if(units == "days")
{
_date.roll!"days"(days);
}
//Verify Examples.
unittest
{
version(testStdDateTime)
{
auto dt1 = DateTime(2010, 1, 1, 11, 23, 12);
dt1.roll!"days"(1);
assert(dt1 == DateTime(2010, 1, 2, 11, 23, 12));
dt1.roll!"days"(365);
assert(dt1 == DateTime(2010, 1, 26, 11, 23, 12));
dt1.roll!"days"(-32);
assert(dt1 == DateTime(2010, 1, 25, 11, 23, 12));
auto dt2 = DateTime(2010, 7, 4, 12, 0, 0);
dt2.roll!"hours"(1);
assert(dt2 == DateTime(2010, 7, 4, 13, 0, 0));
auto dt3 = DateTime(2010, 1, 1, 0, 0, 0);
dt3.roll!"seconds"(-1);
assert(dt3 == DateTime(2010, 1, 1, 0, 0, 59));
}
}
unittest
{
version(testStdDateTime)
{
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.roll!"days"(4)));
static assert(!__traits(compiles, idt.roll!"days"(4)));
}
}
//Shares documentation with "days" version.
/+ref DateTime+/ void roll(string units)(long value) pure nothrow
if(units == "hours" ||
units == "minutes" ||
units == "seconds")
{
_tod.roll!units(value);
}
//Test roll!"hours"().
unittest
{
version(testStdDateTime)
{
static void testDT(DateTime orig, int hours, in DateTime expected, size_t line = __LINE__)
{
orig.roll!"hours"(hours);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 2, DateTime(Date(1999, 7, 6), TimeOfDay(14, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 3, DateTime(Date(1999, 7, 6), TimeOfDay(15, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 4, DateTime(Date(1999, 7, 6), TimeOfDay(16, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 5, DateTime(Date(1999, 7, 6), TimeOfDay(17, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 6, DateTime(Date(1999, 7, 6), TimeOfDay(18, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 7, DateTime(Date(1999, 7, 6), TimeOfDay(19, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 8, DateTime(Date(1999, 7, 6), TimeOfDay(20, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 9, DateTime(Date(1999, 7, 6), TimeOfDay(21, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 10, DateTime(Date(1999, 7, 6), TimeOfDay(22, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 11, DateTime(Date(1999, 7, 6), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 12, DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 13, DateTime(Date(1999, 7, 6), TimeOfDay(1, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 14, DateTime(Date(1999, 7, 6), TimeOfDay(2, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 15, DateTime(Date(1999, 7, 6), TimeOfDay(3, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 16, DateTime(Date(1999, 7, 6), TimeOfDay(4, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 17, DateTime(Date(1999, 7, 6), TimeOfDay(5, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 18, DateTime(Date(1999, 7, 6), TimeOfDay(6, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 19, DateTime(Date(1999, 7, 6), TimeOfDay(7, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 20, DateTime(Date(1999, 7, 6), TimeOfDay(8, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 21, DateTime(Date(1999, 7, 6), TimeOfDay(9, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 22, DateTime(Date(1999, 7, 6), TimeOfDay(10, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 23, DateTime(Date(1999, 7, 6), TimeOfDay(11, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 24, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 25, DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(11, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -2, DateTime(Date(1999, 7, 6), TimeOfDay(10, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -3, DateTime(Date(1999, 7, 6), TimeOfDay(9, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -4, DateTime(Date(1999, 7, 6), TimeOfDay(8, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -5, DateTime(Date(1999, 7, 6), TimeOfDay(7, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -6, DateTime(Date(1999, 7, 6), TimeOfDay(6, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -7, DateTime(Date(1999, 7, 6), TimeOfDay(5, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -8, DateTime(Date(1999, 7, 6), TimeOfDay(4, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -9, DateTime(Date(1999, 7, 6), TimeOfDay(3, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -10, DateTime(Date(1999, 7, 6), TimeOfDay(2, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -11, DateTime(Date(1999, 7, 6), TimeOfDay(1, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -12, DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -13, DateTime(Date(1999, 7, 6), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -14, DateTime(Date(1999, 7, 6), TimeOfDay(22, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -15, DateTime(Date(1999, 7, 6), TimeOfDay(21, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -16, DateTime(Date(1999, 7, 6), TimeOfDay(20, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -17, DateTime(Date(1999, 7, 6), TimeOfDay(19, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -18, DateTime(Date(1999, 7, 6), TimeOfDay(18, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -19, DateTime(Date(1999, 7, 6), TimeOfDay(17, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -20, DateTime(Date(1999, 7, 6), TimeOfDay(16, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -21, DateTime(Date(1999, 7, 6), TimeOfDay(15, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -22, DateTime(Date(1999, 7, 6), TimeOfDay(14, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -23, DateTime(Date(1999, 7, 6), TimeOfDay(13, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -24, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -25, DateTime(Date(1999, 7, 6), TimeOfDay(11, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 33)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(1, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 33)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 33)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(23, 30, 33)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(23, 30, 33)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(23, 30, 33)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(22, 30, 33)));
testDT(DateTime(Date(1999, 7, 31), TimeOfDay(23, 30, 33)), 1, DateTime(Date(1999, 7, 31), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(1999, 8, 1), TimeOfDay(0, 30, 33)), -1, DateTime(Date(1999, 8, 1), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(1999, 12, 31), TimeOfDay(23, 30, 33)), 1, DateTime(Date(1999, 12, 31), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(2000, 1, 1), TimeOfDay(0, 30, 33)), -1, DateTime(Date(2000, 1, 1), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(1999, 2, 28), TimeOfDay(23, 30, 33)), 25, DateTime(Date(1999, 2, 28), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(1999, 3, 2), TimeOfDay(0, 30, 33)), -25, DateTime(Date(1999, 3, 2), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(2000, 2, 28), TimeOfDay(23, 30, 33)), 25, DateTime(Date(2000, 2, 28), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(2000, 3, 1), TimeOfDay(0, 30, 33)), -25, DateTime(Date(2000, 3, 1), TimeOfDay(23, 30, 33)));
//Test B.C.
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(13, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 2, DateTime(Date(-1999, 7, 6), TimeOfDay(14, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 3, DateTime(Date(-1999, 7, 6), TimeOfDay(15, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 4, DateTime(Date(-1999, 7, 6), TimeOfDay(16, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 5, DateTime(Date(-1999, 7, 6), TimeOfDay(17, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 6, DateTime(Date(-1999, 7, 6), TimeOfDay(18, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 7, DateTime(Date(-1999, 7, 6), TimeOfDay(19, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 8, DateTime(Date(-1999, 7, 6), TimeOfDay(20, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 9, DateTime(Date(-1999, 7, 6), TimeOfDay(21, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 10, DateTime(Date(-1999, 7, 6), TimeOfDay(22, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 11, DateTime(Date(-1999, 7, 6), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 12, DateTime(Date(-1999, 7, 6), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 13, DateTime(Date(-1999, 7, 6), TimeOfDay(1, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 14, DateTime(Date(-1999, 7, 6), TimeOfDay(2, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 15, DateTime(Date(-1999, 7, 6), TimeOfDay(3, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 16, DateTime(Date(-1999, 7, 6), TimeOfDay(4, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 17, DateTime(Date(-1999, 7, 6), TimeOfDay(5, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 18, DateTime(Date(-1999, 7, 6), TimeOfDay(6, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 19, DateTime(Date(-1999, 7, 6), TimeOfDay(7, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 20, DateTime(Date(-1999, 7, 6), TimeOfDay(8, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 21, DateTime(Date(-1999, 7, 6), TimeOfDay(9, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 22, DateTime(Date(-1999, 7, 6), TimeOfDay(10, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 23, DateTime(Date(-1999, 7, 6), TimeOfDay(11, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 24, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 25, DateTime(Date(-1999, 7, 6), TimeOfDay(13, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(11, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -2, DateTime(Date(-1999, 7, 6), TimeOfDay(10, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -3, DateTime(Date(-1999, 7, 6), TimeOfDay(9, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -4, DateTime(Date(-1999, 7, 6), TimeOfDay(8, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -5, DateTime(Date(-1999, 7, 6), TimeOfDay(7, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -6, DateTime(Date(-1999, 7, 6), TimeOfDay(6, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -7, DateTime(Date(-1999, 7, 6), TimeOfDay(5, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -8, DateTime(Date(-1999, 7, 6), TimeOfDay(4, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -9, DateTime(Date(-1999, 7, 6), TimeOfDay(3, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -10, DateTime(Date(-1999, 7, 6), TimeOfDay(2, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -11, DateTime(Date(-1999, 7, 6), TimeOfDay(1, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -12, DateTime(Date(-1999, 7, 6), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -13, DateTime(Date(-1999, 7, 6), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -14, DateTime(Date(-1999, 7, 6), TimeOfDay(22, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -15, DateTime(Date(-1999, 7, 6), TimeOfDay(21, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -16, DateTime(Date(-1999, 7, 6), TimeOfDay(20, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -17, DateTime(Date(-1999, 7, 6), TimeOfDay(19, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -18, DateTime(Date(-1999, 7, 6), TimeOfDay(18, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -19, DateTime(Date(-1999, 7, 6), TimeOfDay(17, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -20, DateTime(Date(-1999, 7, 6), TimeOfDay(16, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -21, DateTime(Date(-1999, 7, 6), TimeOfDay(15, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -22, DateTime(Date(-1999, 7, 6), TimeOfDay(14, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -23, DateTime(Date(-1999, 7, 6), TimeOfDay(13, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -24, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -25, DateTime(Date(-1999, 7, 6), TimeOfDay(11, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(0, 30, 33)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(1, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(0, 30, 33)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(0, 30, 33)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(23, 30, 33)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(23, 30, 33)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(23, 30, 33)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(22, 30, 33)));
testDT(DateTime(Date(-1999, 7, 31), TimeOfDay(23, 30, 33)), 1, DateTime(Date(-1999, 7, 31), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(-1999, 8, 1), TimeOfDay(0, 30, 33)), -1, DateTime(Date(-1999, 8, 1), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(-2001, 12, 31), TimeOfDay(23, 30, 33)), 1, DateTime(Date(-2001, 12, 31), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(-2000, 1, 1), TimeOfDay(0, 30, 33)), -1, DateTime(Date(-2000, 1, 1), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(-2001, 2, 28), TimeOfDay(23, 30, 33)), 25, DateTime(Date(-2001, 2, 28), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(-2001, 3, 2), TimeOfDay(0, 30, 33)), -25, DateTime(Date(-2001, 3, 2), TimeOfDay(23, 30, 33)));
testDT(DateTime(Date(-2000, 2, 28), TimeOfDay(23, 30, 33)), 25, DateTime(Date(-2000, 2, 28), TimeOfDay(0, 30, 33)));
testDT(DateTime(Date(-2000, 3, 1), TimeOfDay(0, 30, 33)), -25, DateTime(Date(-2000, 3, 1), TimeOfDay(23, 30, 33)));
//Test Both
testDT(DateTime(Date(-1, 1, 1), TimeOfDay(11, 30, 33)), 17_546, DateTime(Date(-1, 1, 1), TimeOfDay(13, 30, 33)));
testDT(DateTime(Date(1, 1, 1), TimeOfDay(13, 30, 33)), -17_546, DateTime(Date(1, 1, 1), TimeOfDay(11, 30, 33)));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.roll!"hours"(4)));
static assert(!__traits(compiles, idt.roll!"hours"(4)));
//Verify Examples.
auto dt1 = DateTime(Date(2010, 7, 4), TimeOfDay(12, 0, 0));
dt1.roll!"hours"(1);
assert(dt1 == DateTime(Date(2010, 7, 4), TimeOfDay(13, 0, 0)));
auto dt2 = DateTime(Date(2010, 2, 12), TimeOfDay(12, 0, 0));
dt2.roll!"hours"(-1);
assert(dt2 == DateTime(Date(2010, 2, 12), TimeOfDay(11, 0, 0)));
auto dt3 = DateTime(Date(2009, 12, 31), TimeOfDay(23, 0, 0));
dt3.roll!"hours"(1);
assert(dt3 == DateTime(Date(2009, 12, 31), TimeOfDay(0, 0, 0)));
auto dt4 = DateTime(Date(2010, 1, 1), TimeOfDay(0, 0, 0));
dt4.roll!"hours"(-1);
assert(dt4 == DateTime(Date(2010, 1, 1), TimeOfDay(23, 0, 0)));
}
}
//Test roll!"minutes"().
unittest
{
version(testStdDateTime)
{
static void testDT(DateTime orig, int minutes, in DateTime expected, size_t line = __LINE__)
{
orig.roll!"minutes"(minutes);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 2, DateTime(Date(1999, 7, 6), TimeOfDay(12, 32, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 3, DateTime(Date(1999, 7, 6), TimeOfDay(12, 33, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 4, DateTime(Date(1999, 7, 6), TimeOfDay(12, 34, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 5, DateTime(Date(1999, 7, 6), TimeOfDay(12, 35, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 10, DateTime(Date(1999, 7, 6), TimeOfDay(12, 40, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 15, DateTime(Date(1999, 7, 6), TimeOfDay(12, 45, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 29, DateTime(Date(1999, 7, 6), TimeOfDay(12, 59, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 30, DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 45, DateTime(Date(1999, 7, 6), TimeOfDay(12, 15, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 60, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 75, DateTime(Date(1999, 7, 6), TimeOfDay(12, 45, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 90, DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 100, DateTime(Date(1999, 7, 6), TimeOfDay(12, 10, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 689, DateTime(Date(1999, 7, 6), TimeOfDay(12, 59, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 690, DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 691, DateTime(Date(1999, 7, 6), TimeOfDay(12, 1, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 960, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 1439, DateTime(Date(1999, 7, 6), TimeOfDay(12, 29, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 1440, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 1441, DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 2880, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(12, 29, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -2, DateTime(Date(1999, 7, 6), TimeOfDay(12, 28, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -3, DateTime(Date(1999, 7, 6), TimeOfDay(12, 27, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -4, DateTime(Date(1999, 7, 6), TimeOfDay(12, 26, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -5, DateTime(Date(1999, 7, 6), TimeOfDay(12, 25, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -10, DateTime(Date(1999, 7, 6), TimeOfDay(12, 20, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -15, DateTime(Date(1999, 7, 6), TimeOfDay(12, 15, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -29, DateTime(Date(1999, 7, 6), TimeOfDay(12, 1, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -30, DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -45, DateTime(Date(1999, 7, 6), TimeOfDay(12, 45, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -60, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -75, DateTime(Date(1999, 7, 6), TimeOfDay(12, 15, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -90, DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -100, DateTime(Date(1999, 7, 6), TimeOfDay(12, 50, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -749, DateTime(Date(1999, 7, 6), TimeOfDay(12, 1, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -750, DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -751, DateTime(Date(1999, 7, 6), TimeOfDay(12, 59, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -960, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -1439, DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -1440, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -1441, DateTime(Date(1999, 7, 6), TimeOfDay(12, 29, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -2880, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 33)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(12, 1, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 33)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 33)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(12, 59, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(11, 59, 33)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(11, 0, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(11, 59, 33)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(11, 59, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(11, 59, 33)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(11, 58, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 33)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(0, 1, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 33)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 33)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(0, 59, 33)));
testDT(DateTime(Date(1999, 7, 5), TimeOfDay(23, 59, 33)), 1, DateTime(Date(1999, 7, 5), TimeOfDay(23, 0, 33)));
testDT(DateTime(Date(1999, 7, 5), TimeOfDay(23, 59, 33)), 0, DateTime(Date(1999, 7, 5), TimeOfDay(23, 59, 33)));
testDT(DateTime(Date(1999, 7, 5), TimeOfDay(23, 59, 33)), -1, DateTime(Date(1999, 7, 5), TimeOfDay(23, 58, 33)));
testDT(DateTime(Date(1998, 12, 31), TimeOfDay(23, 59, 33)), 1, DateTime(Date(1998, 12, 31), TimeOfDay(23, 0, 33)));
testDT(DateTime(Date(1998, 12, 31), TimeOfDay(23, 59, 33)), 0, DateTime(Date(1998, 12, 31), TimeOfDay(23, 59, 33)));
testDT(DateTime(Date(1998, 12, 31), TimeOfDay(23, 59, 33)), -1, DateTime(Date(1998, 12, 31), TimeOfDay(23, 58, 33)));
//Test B.C.
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 31, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 2, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 32, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 3, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 33, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 4, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 34, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 5, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 35, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 10, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 40, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 15, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 45, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 29, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 59, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 30, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 45, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 15, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 60, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 75, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 45, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 90, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 100, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 10, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 689, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 59, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 690, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 691, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 1, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 960, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 1439, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 29, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 1440, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 1441, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 31, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 2880, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 29, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -2, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 28, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -3, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 27, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -4, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 26, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -5, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 25, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -10, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 20, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -15, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 15, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -29, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 1, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -30, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -45, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 45, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -60, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -75, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 15, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -90, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -100, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 50, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -749, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 1, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -750, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -751, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 59, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -960, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -1439, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 31, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -1440, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -1441, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 29, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -2880, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 33)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 1, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 33)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 33)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 59, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(11, 59, 33)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(11, 0, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(11, 59, 33)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(11, 59, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(11, 59, 33)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(11, 58, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(0, 0, 33)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(0, 1, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(0, 0, 33)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(0, 0, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(0, 0, 33)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(0, 59, 33)));
testDT(DateTime(Date(-1999, 7, 5), TimeOfDay(23, 59, 33)), 1, DateTime(Date(-1999, 7, 5), TimeOfDay(23, 0, 33)));
testDT(DateTime(Date(-1999, 7, 5), TimeOfDay(23, 59, 33)), 0, DateTime(Date(-1999, 7, 5), TimeOfDay(23, 59, 33)));
testDT(DateTime(Date(-1999, 7, 5), TimeOfDay(23, 59, 33)), -1, DateTime(Date(-1999, 7, 5), TimeOfDay(23, 58, 33)));
testDT(DateTime(Date(-2000, 12, 31), TimeOfDay(23, 59, 33)), 1, DateTime(Date(-2000, 12, 31), TimeOfDay(23, 0, 33)));
testDT(DateTime(Date(-2000, 12, 31), TimeOfDay(23, 59, 33)), 0, DateTime(Date(-2000, 12, 31), TimeOfDay(23, 59, 33)));
testDT(DateTime(Date(-2000, 12, 31), TimeOfDay(23, 59, 33)), -1, DateTime(Date(-2000, 12, 31), TimeOfDay(23, 58, 33)));
//Test Both
testDT(DateTime(Date(1, 1, 1), TimeOfDay(0, 0, 0)), -1, DateTime(Date(1, 1, 1), TimeOfDay(0, 59, 0)));
testDT(DateTime(Date(0, 12, 31), TimeOfDay(23, 59, 0)), 1, DateTime(Date(0, 12, 31), TimeOfDay(23, 0, 0)));
testDT(DateTime(Date(0, 1, 1), TimeOfDay(0, 0, 0)), -1, DateTime(Date(0, 1, 1), TimeOfDay(0, 59, 0)));
testDT(DateTime(Date(-1, 12, 31), TimeOfDay(23, 59, 0)), 1, DateTime(Date(-1, 12, 31), TimeOfDay(23, 0, 0)));
testDT(DateTime(Date(-1, 1, 1), TimeOfDay(11, 30, 33)), 1_052_760, DateTime(Date(-1, 1, 1), TimeOfDay(11, 30, 33)));
testDT(DateTime(Date(1, 1, 1), TimeOfDay(13, 30, 33)), -1_052_760, DateTime(Date(1, 1, 1), TimeOfDay(13, 30, 33)));
testDT(DateTime(Date(-1, 1, 1), TimeOfDay(11, 30, 33)), 1_052_782, DateTime(Date(-1, 1, 1), TimeOfDay(11, 52, 33)));
testDT(DateTime(Date(1, 1, 1), TimeOfDay(13, 52, 33)), -1_052_782, DateTime(Date(1, 1, 1), TimeOfDay(13, 30, 33)));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.roll!"minutes"(4)));
static assert(!__traits(compiles, idt.roll!"minutes"(4)));
}
}
//Test roll!"seconds"().
unittest
{
version(testStdDateTime)
{
static void testDT(DateTime orig, int seconds, in DateTime expected, size_t line = __LINE__)
{
orig.roll!"seconds"(seconds);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 2, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 35)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 3, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 36)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 4, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 37)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 5, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 38)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 10, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 43)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 15, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 48)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 26, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 59)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 27, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 0)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 30, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 3)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 59, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 32)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 60, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 61, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 1766, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 59)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 1767, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 0)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 1768, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 1)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 2007, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 0)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 3599, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 32)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 3600, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 3601, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), 7200, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 32)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -2, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 31)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -3, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 30)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -4, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 29)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -5, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 28)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -10, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 23)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -15, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 18)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -33, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 0)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -34, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 59)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -35, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 58)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -59, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -60, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), -61, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 32)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 0)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 1)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 0)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 0)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 0)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 59)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 0)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 1)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 0)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 0)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 0)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(12, 0, 59)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 0)), 1, DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 1)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 0)), 0, DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 0)));
testDT(DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 0)), -1, DateTime(Date(1999, 7, 6), TimeOfDay(0, 0, 59)));
testDT(DateTime(Date(1999, 7, 5), TimeOfDay(23, 59, 59)), 1, DateTime(Date(1999, 7, 5), TimeOfDay(23, 59, 0)));
testDT(DateTime(Date(1999, 7, 5), TimeOfDay(23, 59, 59)), 0, DateTime(Date(1999, 7, 5), TimeOfDay(23, 59, 59)));
testDT(DateTime(Date(1999, 7, 5), TimeOfDay(23, 59, 59)), -1, DateTime(Date(1999, 7, 5), TimeOfDay(23, 59, 58)));
testDT(DateTime(Date(1998, 12, 31), TimeOfDay(23, 59, 59)), 1, DateTime(Date(1998, 12, 31), TimeOfDay(23, 59, 0)));
testDT(DateTime(Date(1998, 12, 31), TimeOfDay(23, 59, 59)), 0, DateTime(Date(1998, 12, 31), TimeOfDay(23, 59, 59)));
testDT(DateTime(Date(1998, 12, 31), TimeOfDay(23, 59, 59)), -1, DateTime(Date(1998, 12, 31), TimeOfDay(23, 59, 58)));
//Test B.C.
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 34)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 2, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 35)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 3, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 36)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 4, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 37)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 5, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 38)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 10, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 43)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 15, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 48)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 26, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 59)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 27, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 0)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 30, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 3)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 59, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 32)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 60, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 61, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 34)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 1766, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 59)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 1767, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 0)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 1768, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 1)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 2007, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 0)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 3599, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 32)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 3600, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 3601, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 34)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), 7200, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 32)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -2, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 31)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -3, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 30)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -4, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 29)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -5, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 28)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -10, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 23)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -15, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 18)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -33, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 0)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -34, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 59)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -35, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 58)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -59, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 34)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -60, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)), -61, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 32)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 0)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 1)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 0)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 0)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 0)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 59)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 0)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 1)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 0)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 0)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 0)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(12, 0, 59)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(0, 0, 0)), 1, DateTime(Date(-1999, 7, 6), TimeOfDay(0, 0, 1)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(0, 0, 0)), 0, DateTime(Date(-1999, 7, 6), TimeOfDay(0, 0, 0)));
testDT(DateTime(Date(-1999, 7, 6), TimeOfDay(0, 0, 0)), -1, DateTime(Date(-1999, 7, 6), TimeOfDay(0, 0, 59)));
testDT(DateTime(Date(-1999, 7, 5), TimeOfDay(23, 59, 59)), 1, DateTime(Date(-1999, 7, 5), TimeOfDay(23, 59, 0)));
testDT(DateTime(Date(-1999, 7, 5), TimeOfDay(23, 59, 59)), 0, DateTime(Date(-1999, 7, 5), TimeOfDay(23, 59, 59)));
testDT(DateTime(Date(-1999, 7, 5), TimeOfDay(23, 59, 59)), -1, DateTime(Date(-1999, 7, 5), TimeOfDay(23, 59, 58)));
testDT(DateTime(Date(-2000, 12, 31), TimeOfDay(23, 59, 59)), 1, DateTime(Date(-2000, 12, 31), TimeOfDay(23, 59, 0)));
testDT(DateTime(Date(-2000, 12, 31), TimeOfDay(23, 59, 59)), 0, DateTime(Date(-2000, 12, 31), TimeOfDay(23, 59, 59)));
testDT(DateTime(Date(-2000, 12, 31), TimeOfDay(23, 59, 59)), -1, DateTime(Date(-2000, 12, 31), TimeOfDay(23, 59, 58)));
//Test Both
testDT(DateTime(Date(1, 1, 1), TimeOfDay(0, 0, 0)), -1, DateTime(Date(1, 1, 1), TimeOfDay(0, 0, 59)));
testDT(DateTime(Date(0, 12, 31), TimeOfDay(23, 59, 59)), 1, DateTime(Date(0, 12, 31), TimeOfDay(23, 59, 0)));
testDT(DateTime(Date(0, 1, 1), TimeOfDay(0, 0, 0)), -1, DateTime(Date(0, 1, 1), TimeOfDay(0, 0, 59)));
testDT(DateTime(Date(-1, 12, 31), TimeOfDay(23, 59, 59)), 1, DateTime(Date(-1, 12, 31), TimeOfDay(23, 59, 0)));
testDT(DateTime(Date(-1, 1, 1), TimeOfDay(11, 30, 33)), 63_165_600L, DateTime(Date(-1, 1, 1), TimeOfDay(11, 30, 33)));
testDT(DateTime(Date(1, 1, 1), TimeOfDay(13, 30, 33)), -63_165_600L, DateTime(Date(1, 1, 1), TimeOfDay(13, 30, 33)));
testDT(DateTime(Date(-1, 1, 1), TimeOfDay(11, 30, 33)), 63_165_617L, DateTime(Date(-1, 1, 1), TimeOfDay(11, 30, 50)));
testDT(DateTime(Date(1, 1, 1), TimeOfDay(13, 30, 50)), -63_165_617L, DateTime(Date(1, 1, 1), TimeOfDay(13, 30, 33)));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.roll!"seconds"(4)));
static assert(!__traits(compiles, idt.roll!"seconds"(4)));
}
}
/++
Gives the result of adding or subtracting a duration from this
$(D DateTime).
The legal types of arithmetic for $(D DateTime) using this operator are
$(BOOKTABLE,
$(TR $(TD DateTime) $(TD +) $(TD duration) $(TD -->) $(TD DateTime))
$(TR $(TD DateTime) $(TD -) $(TD duration) $(TD -->) $(TD DateTime))
)
Params:
duration = The duration to add to or subtract from this
$(D DateTime).
+/
DateTime opBinary(string op, D)(in D duration) const pure nothrow
if((op == "+" || op == "-") &&
(is(Unqual!D == Duration) ||
is(Unqual!D == TickDuration)))
{
DateTime retval = this;
static if(is(Unqual!D == Duration))
immutable hnsecs = duration.total!"hnsecs";
else static if(is(Unqual!D == TickDuration))
immutable hnsecs = duration.hnsecs;
//Ideally, this would just be
//return retval.addSeconds(convert!("hnsecs", "seconds")(unaryFun!(op ~ "a")(hnsecs)));
//But there isn't currently a pure version of unaryFun!().
static if(op == "+")
immutable signedHNSecs = hnsecs;
else static if(op == "-")
immutable signedHNSecs = -hnsecs;
else
static assert(0);
return retval.addSeconds(convert!("hnsecs", "seconds")(signedHNSecs));
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
_assertPred!"=="(dt + dur!"weeks"(7), DateTime(Date(1999, 8, 24), TimeOfDay(12, 30, 33)));
_assertPred!"=="(dt + dur!"weeks"(-7), DateTime(Date(1999, 5, 18), TimeOfDay(12, 30, 33)));
_assertPred!"=="(dt + dur!"days"(7), DateTime(Date(1999, 7, 13), TimeOfDay(12, 30, 33)));
_assertPred!"=="(dt + dur!"days"(-7), DateTime(Date(1999, 6, 29), TimeOfDay(12, 30, 33)));
_assertPred!"=="(dt + dur!"hours"(7), DateTime(Date(1999, 7, 6), TimeOfDay(19, 30, 33)));
_assertPred!"=="(dt + dur!"hours"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(5, 30, 33)));
_assertPred!"=="(dt + dur!"minutes"(7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 37, 33)));
_assertPred!"=="(dt + dur!"minutes"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 23, 33)));
_assertPred!"=="(dt + dur!"seconds"(7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"=="(dt + dur!"seconds"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"=="(dt + dur!"msecs"(7_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"=="(dt + dur!"msecs"(-7_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"=="(dt + dur!"usecs"(7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"=="(dt + dur!"usecs"(-7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"=="(dt + dur!"hnsecs"(70_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"=="(dt + dur!"hnsecs"(-70_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
//This probably only runs in cases where gettimeofday() is used, but it's
//hard to do this test correctly with variable ticksPerSec.
if(TickDuration.ticksPerSec == 1_000_000)
{
_assertPred!"=="(dt + TickDuration.from!"usecs"(7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"=="(dt + TickDuration.from!"usecs"(-7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
}
_assertPred!"=="(dt - dur!"weeks"(-7), DateTime(Date(1999, 8, 24), TimeOfDay(12, 30, 33)));
_assertPred!"=="(dt - dur!"weeks"(7), DateTime(Date(1999, 5, 18), TimeOfDay(12, 30, 33)));
_assertPred!"=="(dt - dur!"days"(-7), DateTime(Date(1999, 7, 13), TimeOfDay(12, 30, 33)));
_assertPred!"=="(dt - dur!"days"(7), DateTime(Date(1999, 6, 29), TimeOfDay(12, 30, 33)));
_assertPred!"=="(dt - dur!"hours"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(19, 30, 33)));
_assertPred!"=="(dt - dur!"hours"(7), DateTime(Date(1999, 7, 6), TimeOfDay(5, 30, 33)));
_assertPred!"=="(dt - dur!"minutes"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 37, 33)));
_assertPred!"=="(dt - dur!"minutes"(7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 23, 33)));
_assertPred!"=="(dt - dur!"seconds"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"=="(dt - dur!"seconds"(7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"=="(dt - dur!"msecs"(-7_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"=="(dt - dur!"msecs"(7_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"=="(dt - dur!"usecs"(-7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"=="(dt - dur!"usecs"(7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"=="(dt - dur!"hnsecs"(-70_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"=="(dt - dur!"hnsecs"(70_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
//This probably only runs in cases where gettimeofday() is used, but it's
//hard to do this test correctly with variable ticksPerSec.
if(TickDuration.ticksPerSec == 1_000_000)
{
_assertPred!"=="(dt - TickDuration.from!"usecs"(-7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"=="(dt - TickDuration.from!"usecs"(7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
}
auto duration = dur!"seconds"(12);
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, cdt + duration));
static assert(__traits(compiles, idt + duration));
static assert(__traits(compiles, cdt - duration));
static assert(__traits(compiles, idt - duration));
}
}
/++
Gives the result of adding or subtracting a duration from this
$(D DateTime), as well as assigning the result to this $(D DateTime).
The legal types of arithmetic for $(D DateTime) using this operator are
$(BOOKTABLE,
$(TR $(TD DateTime) $(TD +) $(TD duration) $(TD -->) $(TD DateTime))
$(TR $(TD DateTime) $(TD -) $(TD duration) $(TD -->) $(TD DateTime))
)
Params:
duration = The duration to add to or subtract from this
$(D DateTime).
+/
/+ref+/ DateTime opOpAssign(string op, D)(in D duration) pure nothrow
if((op == "+" || op == "-") &&
(is(Unqual!D == Duration) ||
is(Unqual!D == TickDuration)))
{
DateTime retval = this;
static if(is(Unqual!D == Duration))
immutable hnsecs = duration.total!"hnsecs";
else static if(is(Unqual!D == TickDuration))
immutable hnsecs = duration.hnsecs;
//Ideally, this would just be
//return addSeconds(convert!("hnsecs", "seconds")(unaryFun!(op ~ "a")(hnsecs)));
//But there isn't currently a pure version of unaryFun!().
static if(op == "+")
immutable signedHNSecs = hnsecs;
else static if(op == "-")
immutable signedHNSecs = -hnsecs;
else
static assert(0);
return addSeconds(convert!("hnsecs", "seconds")(signedHNSecs));
}
unittest
{
version(testStdDateTime)
{
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"weeks"(7), DateTime(Date(1999, 8, 24), TimeOfDay(12, 30, 33)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"weeks"(-7), DateTime(Date(1999, 5, 18), TimeOfDay(12, 30, 33)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"days"(7), DateTime(Date(1999, 7, 13), TimeOfDay(12, 30, 33)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"days"(-7), DateTime(Date(1999, 6, 29), TimeOfDay(12, 30, 33)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"hours"(7), DateTime(Date(1999, 7, 6), TimeOfDay(19, 30, 33)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"hours"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(5, 30, 33)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"minutes"(7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 37, 33)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"minutes"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 23, 33)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"seconds"(7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"seconds"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"msecs"(7_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"msecs"(-7_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"usecs"(7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"usecs"(-7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"hnsecs"(70_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"+="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"hnsecs"(-70_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"weeks"(-7), DateTime(Date(1999, 8, 24), TimeOfDay(12, 30, 33)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"weeks"(7), DateTime(Date(1999, 5, 18), TimeOfDay(12, 30, 33)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"days"(-7), DateTime(Date(1999, 7, 13), TimeOfDay(12, 30, 33)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"days"(7), DateTime(Date(1999, 6, 29), TimeOfDay(12, 30, 33)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"hours"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(19, 30, 33)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"hours"(7), DateTime(Date(1999, 7, 6), TimeOfDay(5, 30, 33)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"minutes"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 37, 33)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"minutes"(7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 23, 33)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"seconds"(-7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"seconds"(7), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"msecs"(-7_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"msecs"(7_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"usecs"(-7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"usecs"(7_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"hnsecs"(-70_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 40)));
_assertPred!"-="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)), dur!"hnsecs"(70_000_000), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 26)));
auto duration = dur!"seconds"(12);
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(!__traits(compiles, cdt += duration));
static assert(!__traits(compiles, idt += duration));
static assert(!__traits(compiles, cdt -= duration));
static assert(!__traits(compiles, idt -= duration));
}
}
/++
Gives the difference between two $(D DateTime)s.
The legal types of arithmetic for $(D DateTime) using this operator are
$(BOOKTABLE,
$(TR $(TD DateTime) $(TD -) $(TD DateTime) $(TD -->) $(TD duration))
)
+/
Duration opBinary(string op)(in DateTime rhs) const pure nothrow
if(op == "-")
{
immutable dateResult = _date - rhs.date;
immutable todResult = _tod - rhs._tod;
return dur!"hnsecs"(dateResult.total!"hnsecs" + todResult.total!"hnsecs");
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime(1999, 7, 6, 12, 30, 33);
_assertPred!"=="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)) -
DateTime(Date(1998, 7, 6), TimeOfDay(12, 30, 33)),
dur!"seconds"(31_536_000));
_assertPred!"=="(DateTime(Date(1998, 7, 6), TimeOfDay(12, 30, 33)) -
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
dur!"seconds"(-31_536_000));
_assertPred!"=="(DateTime(Date(1999, 8, 6), TimeOfDay(12, 30, 33)) -
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
dur!"seconds"(26_78_400));
_assertPred!"=="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)) -
DateTime(Date(1999, 8, 6), TimeOfDay(12, 30, 33)),
dur!"seconds"(-26_78_400));
_assertPred!"=="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)) -
DateTime(Date(1999, 7, 5), TimeOfDay(12, 30, 33)),
dur!"seconds"(86_400));
_assertPred!"=="(DateTime(Date(1999, 7, 5), TimeOfDay(12, 30, 33)) -
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
dur!"seconds"(-86_400));
_assertPred!"=="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)) -
DateTime(Date(1999, 7, 6), TimeOfDay(11, 30, 33)),
dur!"seconds"(3600));
_assertPred!"=="(DateTime(Date(1999, 7, 6), TimeOfDay(11, 30, 33)) -
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
dur!"seconds"(-3600));
_assertPred!"=="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)) -
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
dur!"seconds"(60));
_assertPred!"=="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)) -
DateTime(Date(1999, 7, 6), TimeOfDay(12, 31, 33)),
dur!"seconds"(-60));
_assertPred!"=="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)) -
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)),
dur!"seconds"(1));
_assertPred!"=="(DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)) -
DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 34)),
dur!"seconds"(-1));
_assertPred!"=="(DateTime(1, 1, 1, 12, 30, 33) - DateTime(1, 1, 1, 0, 0, 0), dur!"seconds"(45033));
_assertPred!"=="(DateTime(1, 1, 1, 0, 0, 0) - DateTime(1, 1, 1, 12, 30, 33), dur!"seconds"(-45033));
_assertPred!"=="(DateTime(0, 12, 31, 12, 30, 33) - DateTime(1, 1, 1, 0, 0, 0), dur!"seconds"(-41367));
_assertPred!"=="(DateTime(1, 1, 1, 0, 0, 0) - DateTime(0, 12, 31, 12, 30, 33), dur!"seconds"(41367));
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, dt - dt));
static assert(__traits(compiles, cdt - dt));
static assert(__traits(compiles, idt - dt));
static assert(__traits(compiles, dt - cdt));
static assert(__traits(compiles, cdt - cdt));
static assert(__traits(compiles, idt - cdt));
static assert(__traits(compiles, dt - idt));
static assert(__traits(compiles, cdt - idt));
static assert(__traits(compiles, idt - idt));
}
}
/++
Returns the difference between the two $(D DateTime)s in months.
You can get the difference in years by subtracting the year property
of two $(D DateTime)s, and you can get the difference in days or weeks
by subtracting the $(D DateTime)s themselves and using the Duration that
results, but because you cannot convert between months and smaller units
without a specific date (which $(D Duration)s don't have), you cannot
get the difference in months without doing some math using both the year
and month properties, so this is a convenience function for getting the
difference in months.
Note that the number of days in the months or how far into the month
either date is is irrelevant. It is the difference in the month property
combined with the difference in years * 12. So, for instance,
December 31st and January 1st are one month apart just as December 1st
and January 31st are one month apart.
Params:
rhs = The $(D DateTime) to subtract from this one.
Examples:
--------------------
assert(DateTime(1999, 2, 1, 12, 2, 3).diffMonths(
DateTime(1999, 1, 31, 23, 59, 59)) == 1);
assert(DateTime(1999, 1, 31, 0, 0, 0).diffMonths(
DateTime(1999, 2, 1, 12, 3, 42)) == -1);
assert(DateTime(1999, 3, 1, 5, 30, 0).diffMonths(
DateTime(1999, 1, 1, 2, 4, 7)) == 2);
assert(DateTime(1999, 1, 1, 7, 2, 4).diffMonths(
DateTime(1999, 3, 31, 0, 30, 58)) == -2);
--------------------
+/
int diffMonths(in DateTime rhs) const pure nothrow
{
return _date.diffMonths(rhs._date);
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, dt.diffMonths(dt)));
static assert(__traits(compiles, cdt.diffMonths(dt)));
static assert(__traits(compiles, idt.diffMonths(dt)));
static assert(__traits(compiles, dt.diffMonths(cdt)));
static assert(__traits(compiles, cdt.diffMonths(cdt)));
static assert(__traits(compiles, idt.diffMonths(cdt)));
static assert(__traits(compiles, dt.diffMonths(idt)));
static assert(__traits(compiles, cdt.diffMonths(idt)));
static assert(__traits(compiles, idt.diffMonths(idt)));
//Verify Examples.
assert(DateTime(1999, 2, 1, 12, 2, 3).diffMonths(DateTime(1999, 1, 31, 23, 59, 59)) == 1);
assert(DateTime(1999, 1, 31, 0, 0, 0).diffMonths(DateTime(1999, 2, 1, 12, 3, 42)) == -1);
assert(DateTime(1999, 3, 1, 5, 30, 0).diffMonths(DateTime(1999, 1, 1, 2, 4, 7)) == 2);
assert(DateTime(1999, 1, 1, 7, 2, 4).diffMonths(DateTime(1999, 3, 31, 0, 30, 58)) == -2);
}
}
/++
Whether this $(D DateTime) is in a leap year.
+/
@property bool isLeapYear() const pure nothrow
{
return _date.isLeapYear;
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, dt.isLeapYear));
static assert(__traits(compiles, cdt.isLeapYear));
static assert(__traits(compiles, idt.isLeapYear));
}
}
/++
Day of the week this $(D DateTime) is on.
+/
@property DayOfWeek dayOfWeek() const pure nothrow
{
return _date.dayOfWeek;
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, dt.dayOfWeek));
static assert(__traits(compiles, cdt.dayOfWeek));
static assert(__traits(compiles, idt.dayOfWeek));
}
}
/++
Day of the year this $(D DateTime) is on.
Examples:
--------------------
assert(DateTime(Date(1999, 1, 1), TimeOfDay(12, 22, 7)).dayOfYear == 1);
assert(DateTime(Date(1999, 12, 31), TimeOfDay(7, 2, 59)).dayOfYear == 365);
assert(DateTime(Date(2000, 12, 31), TimeOfDay(21, 20, 0)).dayOfYear == 366);
--------------------
+/
@property ushort dayOfYear() const pure nothrow
{
return _date.dayOfYear;
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, dt.dayOfYear));
static assert(__traits(compiles, cdt.dayOfYear));
static assert(__traits(compiles, idt.dayOfYear));
//Verify Examples.
assert(DateTime(Date(1999, 1, 1), TimeOfDay(12, 22, 7)).dayOfYear == 1);
assert(DateTime(Date(1999, 12, 31), TimeOfDay(7, 2, 59)).dayOfYear == 365);
assert(DateTime(Date(2000, 12, 31), TimeOfDay(21, 20, 0)).dayOfYear == 366);
}
}
/++
Day of the year.
Params:
day = The day of the year to set which day of the year this
$(D DateTime) is on.
+/
@property void dayOfYear(int day) pure
{
_date.dayOfYear = day;
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, dt.dayOfYear = 12));
static assert(!__traits(compiles, cdt.dayOfYear = 12));
static assert(!__traits(compiles, idt.dayOfYear = 12));
}
}
/++
The Xth day of the Gregorian Calendar that this $(D DateTime) is on.
Examples:
--------------------
assert(DateTime(Date(1, 1, 1), TimeOfDay(0, 0, 0)).dayOfGregorianCal ==
1);
assert(DateTime(Date(1, 12, 31), TimeOfDay(23, 59, 59)).dayOfGregorianCal ==
365);
assert(DateTime(Date(2, 1, 1), TimeOfDay(2, 2, 2)).dayOfGregorianCal ==
366);
assert(DateTime(Date(0, 12, 31), TimeOfDay(7, 7, 7)).dayOfGregorianCal ==
0);
assert(DateTime(Date(0, 1, 1), TimeOfDay(19, 30, 0)).dayOfGregorianCal ==
-365);
assert(DateTime(Date(-1, 12, 31), TimeOfDay(4, 7, 0)).dayOfGregorianCal ==
-366);
assert(DateTime(Date(2000, 1, 1), TimeOfDay(9, 30, 20)).dayOfGregorianCal ==
730_120);
assert(DateTime(Date(2010, 12, 31), TimeOfDay(15, 45, 50)).dayOfGregorianCal ==
734_137);
--------------------
+/
@property int dayOfGregorianCal() const pure nothrow
{
return _date.dayOfGregorianCal;
}
unittest
{
version(testStdDateTime)
{
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, cdt.dayOfGregorianCal));
static assert(__traits(compiles, idt.dayOfGregorianCal));
//Verify Examples.
assert(DateTime(Date(1, 1, 1), TimeOfDay(0, 0, 0)).dayOfGregorianCal == 1);
assert(DateTime(Date(1, 12, 31), TimeOfDay(23, 59, 59)).dayOfGregorianCal == 365);
assert(DateTime(Date(2, 1, 1), TimeOfDay(2, 2, 2)).dayOfGregorianCal == 366);
assert(DateTime(Date(0, 12, 31), TimeOfDay(7, 7, 7)).dayOfGregorianCal == 0);
assert(DateTime(Date(0, 1, 1), TimeOfDay(19, 30, 0)).dayOfGregorianCal == -365);
assert(DateTime(Date(-1, 12, 31), TimeOfDay(4, 7, 0)).dayOfGregorianCal == -366);
assert(DateTime(Date(2000, 1, 1), TimeOfDay(9, 30, 20)).dayOfGregorianCal == 730_120);
assert(DateTime(Date(2010, 12, 31), TimeOfDay(15, 45, 50)).dayOfGregorianCal == 734_137);
}
}
/++
The Xth day of the Gregorian Calendar that this $(D DateTime) is on.
Setting this property does not affect the time portion of
$(D DateTime).
Params:
days = The day of the Gregorian Calendar to set this $(D DateTime)
to.
Examples:
--------------------
auto dt = DateTime(Date.init, TimeOfDay(12, 0, 0));
dt.dayOfGregorianCal = 1;
assert(dt == DateTime(Date(1, 1, 1), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = 365;
assert(dt == DateTime(Date(1, 12, 31), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = 366;
assert(dt == DateTime(Date(2, 1, 1), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = 0;
assert(dt == DateTime(Date(0, 12, 31), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = -365;
assert(dt == DateTime(Date(-0, 1, 1), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = -366;
assert(dt == DateTime(Date(-1, 12, 31), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = 730_120;
assert(dt == DateTime(Date(2000, 1, 1), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = 734_137;
assert(dt == DateTime(Date(2010, 12, 31), TimeOfDay(12, 0, 0)));
--------------------
+/
@property void dayOfGregorianCal(int days) pure nothrow
{
_date.dayOfGregorianCal = days;
}
unittest
{
version(testStdDateTime)
{
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(!__traits(compiles, cdt.dayOfGregorianCal = 7));
static assert(!__traits(compiles, idt.dayOfGregorianCal = 7));
//Verify Examples.
auto dt = DateTime(Date.init, TimeOfDay(12, 0, 0));
dt.dayOfGregorianCal = 1;
assert(dt == DateTime(Date(1, 1, 1), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = 365;
assert(dt == DateTime(Date(1, 12, 31), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = 366;
assert(dt == DateTime(Date(2, 1, 1), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = 0;
assert(dt == DateTime(Date(0, 12, 31), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = -365;
assert(dt == DateTime(Date(-0, 1, 1), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = -366;
assert(dt == DateTime(Date(-1, 12, 31), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = 730_120;
assert(dt == DateTime(Date(2000, 1, 1), TimeOfDay(12, 0, 0)));
dt.dayOfGregorianCal = 734_137;
assert(dt == DateTime(Date(2010, 12, 31), TimeOfDay(12, 0, 0)));
}
}
/++
The ISO 8601 week of the year that this $(D DateTime) is in.
See_Also:
$(WEB en.wikipedia.org/wiki/ISO_week_date, ISO Week Date)
+/
@property ubyte isoWeek() const pure nothrow
{
return _date.isoWeek;
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, dt.isoWeek));
static assert(__traits(compiles, cdt.isoWeek));
static assert(__traits(compiles, idt.isoWeek));
}
}
/++
$(D DateTime) for the last day in the month that this $(D DateTime) is
in. The time portion of endOfMonth is always 23:59:59.
Examples:
--------------------
assert(DateTime(Date(1999, 1, 6), TimeOfDay(0, 0, 0)).endOfMonth ==
DateTime(Date(1999, 1, 31), TimeOfDay(23, 59, 59)));
assert(DateTime(Date(1999, 2, 7), TimeOfDay(19, 30, 0)).endOfMonth ==
DateTime(Date(1999, 2, 28), TimeOfDay(23, 59, 59)));
assert(DateTime(Date(2000, 2, 7), TimeOfDay(5, 12, 27)).endOfMonth ==
DateTime(Date(2000, 2, 29), TimeOfDay(23, 59, 59)));
assert(DateTime(Date(2000, 6, 4), TimeOfDay(12, 22, 9)).endOfMonth ==
DateTime(Date(2000, 6, 30), TimeOfDay(23, 59, 59)));
--------------------
+/
@property DateTime endOfMonth() const pure nothrow
{
try
return DateTime(_date.endOfMonth, TimeOfDay(23, 59, 59));
catch(Exception e)
assert(0, "DateTime constructor threw.");
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(DateTime(1999, 1, 1, 0, 13, 26).endOfMonth, DateTime(1999, 1, 31, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 2, 1, 1, 14, 27).endOfMonth, DateTime(1999, 2, 28, 23, 59, 59));
_assertPred!"=="(DateTime(2000, 2, 1, 2, 15, 28).endOfMonth, DateTime(2000, 2, 29, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 3, 1, 3, 16, 29).endOfMonth, DateTime(1999, 3, 31, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 4, 1, 4, 17, 30).endOfMonth, DateTime(1999, 4, 30, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 5, 1, 5, 18, 31).endOfMonth, DateTime(1999, 5, 31, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 6, 1, 6, 19, 32).endOfMonth, DateTime(1999, 6, 30, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 7, 1, 7, 20, 33).endOfMonth, DateTime(1999, 7, 31, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 8, 1, 8, 21, 34).endOfMonth, DateTime(1999, 8, 31, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 9, 1, 9, 22, 35).endOfMonth, DateTime(1999, 9, 30, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 10, 1, 10, 23, 36).endOfMonth, DateTime(1999, 10, 31, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 11, 1, 11, 24, 37).endOfMonth, DateTime(1999, 11, 30, 23, 59, 59));
_assertPred!"=="(DateTime(1999, 12, 1, 12, 25, 38).endOfMonth, DateTime(1999, 12, 31, 23, 59, 59));
//Test B.C.
_assertPred!"=="(DateTime(-1999, 1, 1, 0, 13, 26).endOfMonth, DateTime(-1999, 1, 31, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 2, 1, 1, 14, 27).endOfMonth, DateTime(-1999, 2, 28, 23, 59, 59));
_assertPred!"=="(DateTime(-2000, 2, 1, 2, 15, 28).endOfMonth, DateTime(-2000, 2, 29, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 3, 1, 3, 16, 29).endOfMonth, DateTime(-1999, 3, 31, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 4, 1, 4, 17, 30).endOfMonth, DateTime(-1999, 4, 30, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 5, 1, 5, 18, 31).endOfMonth, DateTime(-1999, 5, 31, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 6, 1, 6, 19, 32).endOfMonth, DateTime(-1999, 6, 30, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 7, 1, 7, 20, 33).endOfMonth, DateTime(-1999, 7, 31, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 8, 1, 8, 21, 34).endOfMonth, DateTime(-1999, 8, 31, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 9, 1, 9, 22, 35).endOfMonth, DateTime(-1999, 9, 30, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 10, 1, 10, 23, 36).endOfMonth, DateTime(-1999, 10, 31, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 11, 1, 11, 24, 37).endOfMonth, DateTime(-1999, 11, 30, 23, 59, 59));
_assertPred!"=="(DateTime(-1999, 12, 1, 12, 25, 38).endOfMonth, DateTime(-1999, 12, 31, 23, 59, 59));
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, cdt.endOfMonth));
static assert(__traits(compiles, idt.endOfMonth));
//Verify Examples.
assert(DateTime(Date(1999, 1, 6), TimeOfDay(0, 0, 0)).endOfMonth == DateTime(Date(1999, 1, 31), TimeOfDay(23, 59, 59)));
assert(DateTime(Date(1999, 2, 7), TimeOfDay(19, 30, 0)).endOfMonth == DateTime(Date(1999, 2, 28), TimeOfDay(23, 59, 59)));
assert(DateTime(Date(2000, 2, 7), TimeOfDay(5, 12, 27)).endOfMonth == DateTime(Date(2000, 2, 29), TimeOfDay(23, 59, 59)));
assert(DateTime(Date(2000, 6, 4), TimeOfDay(12, 22, 9)).endOfMonth == DateTime(Date(2000, 6, 30), TimeOfDay(23, 59, 59)));
}
}
/++
The last day in the month that this $(D DateTime) is in.
Examples:
--------------------
assert(DateTime(Date(1999, 1, 6), TimeOfDay(0, 0, 0)).daysInMonth == 31);
assert(DateTime(Date(1999, 2, 7), TimeOfDay(19, 30, 0)).daysInMonth == 28);
assert(DateTime(Date(2000, 2, 7), TimeOfDay(5, 12, 27)).daysInMonth == 29);
assert(DateTime(Date(2000, 6, 4), TimeOfDay(12, 22, 9)).daysInMonth == 30);
--------------------
+/
@property ubyte daysInMonth() const pure nothrow
{
return _date.daysInMonth;
}
/++
$(RED Scheduled for deprecation in January 2012.
Please use daysInMonth instead.)
+/
alias daysInMonth endofMonthDay;
unittest
{
version(testStdDateTime)
{
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, cdt.daysInMonth));
static assert(__traits(compiles, idt.daysInMonth));
//Verify Examples.
assert(DateTime(Date(1999, 1, 6), TimeOfDay(0, 0, 0)).daysInMonth == 31);
assert(DateTime(Date(1999, 2, 7), TimeOfDay(19, 30, 0)).daysInMonth == 28);
assert(DateTime(Date(2000, 2, 7), TimeOfDay(5, 12, 27)).daysInMonth == 29);
assert(DateTime(Date(2000, 6, 4), TimeOfDay(12, 22, 9)).daysInMonth == 30);
}
}
/++
Whether the current year is a date in A.D.
Examples:
--------------------
assert(DateTime(Date(1, 1, 1), TimeOfDay(12, 7, 0)).isAD);
assert(DateTime(Date(2010, 12, 31), TimeOfDay(0, 0, 0)).isAD);
assert(!DateTime(Date(0, 12, 31), TimeOfDay(23, 59, 59)).isAD);
assert(!DateTime(Date(-2010, 1, 1), TimeOfDay(2, 2, 2)).isAD);
--------------------
+/
@property bool isAD() const pure nothrow
{
return _date.isAD;
}
unittest
{
version(testStdDateTime)
{
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, cdt.isAD));
static assert(__traits(compiles, idt.isAD));
//Verify Examples.
assert(DateTime(Date(1, 1, 1), TimeOfDay(12, 7, 0)).isAD);
assert(DateTime(Date(2010, 12, 31), TimeOfDay(0, 0, 0)).isAD);
assert(!DateTime(Date(0, 12, 31), TimeOfDay(23, 59, 59)).isAD);
assert(!DateTime(Date(-2010, 1, 1), TimeOfDay(2, 2, 2)).isAD);
}
}
/++
The julian day for this $(D DateTime) at the given time. For example,
prior to noon, 1996-03-31 would be the julian day number 2_450_173, so
this function returns 2_450_173, while from noon onward, the julian
day number would be 2_450_174, so this function returns 2_450_174.
+/
@property long julianDay() const pure nothrow
{
if(_tod._hour < 12)
return _date.julianDay - 1;
else
return _date.julianDay;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(DateTime(Date(-4713, 11, 24), TimeOfDay(0, 0, 0)).julianDay, -1);
_assertPred!"=="(DateTime(Date(-4713, 11, 24), TimeOfDay(12, 0, 0)).julianDay, 0);
_assertPred!"=="(DateTime(Date(0, 12, 31), TimeOfDay(0, 0, 0)).julianDay, 1_721_424);
_assertPred!"=="(DateTime(Date(0, 12, 31), TimeOfDay(12, 0, 0)).julianDay, 1_721_425);
_assertPred!"=="(DateTime(Date(1, 1, 1), TimeOfDay(0, 0, 0)).julianDay, 1_721_425);
_assertPred!"=="(DateTime(Date(1, 1, 1), TimeOfDay(12, 0, 0)).julianDay, 1_721_426);
_assertPred!"=="(DateTime(Date(1582, 10, 15), TimeOfDay(0, 0, 0)).julianDay, 2_299_160);
_assertPred!"=="(DateTime(Date(1582, 10, 15), TimeOfDay(12, 0, 0)).julianDay, 2_299_161);
_assertPred!"=="(DateTime(Date(1858, 11, 17), TimeOfDay(0, 0, 0)).julianDay, 2_400_000);
_assertPred!"=="(DateTime(Date(1858, 11, 17), TimeOfDay(12, 0, 0)).julianDay, 2_400_001);
_assertPred!"=="(DateTime(Date(1982, 1, 4), TimeOfDay(0, 0, 0)).julianDay, 2_444_973);
_assertPred!"=="(DateTime(Date(1982, 1, 4), TimeOfDay(12, 0, 0)).julianDay, 2_444_974);
_assertPred!"=="(DateTime(Date(1996, 3, 31), TimeOfDay(0, 0, 0)).julianDay, 2_450_173);
_assertPred!"=="(DateTime(Date(1996, 3, 31), TimeOfDay(12, 0, 0)).julianDay, 2_450_174);
_assertPred!"=="(DateTime(Date(2010, 8, 24), TimeOfDay(0, 0, 0)).julianDay, 2_455_432);
_assertPred!"=="(DateTime(Date(2010, 8, 24), TimeOfDay(12, 0, 0)).julianDay, 2_455_433);
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, cdt.julianDay));
static assert(__traits(compiles, idt.julianDay));
}
}
/++
The modified julian day for any time on this date (since, the modified
julian day changes at midnight).
+/
@property long modJulianDay() const pure nothrow
{
return _date.modJulianDay;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(DateTime(Date(1858, 11, 17), TimeOfDay(0, 0, 0)).modJulianDay, 0);
_assertPred!"=="(DateTime(Date(1858, 11, 17), TimeOfDay(12, 0, 0)).modJulianDay, 0);
_assertPred!"=="(DateTime(Date(2010, 8, 24), TimeOfDay(0, 0, 0)).modJulianDay, 55_432);
_assertPred!"=="(DateTime(Date(2010, 8, 24), TimeOfDay(12, 0, 0)).modJulianDay, 55_432);
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, cdt.modJulianDay));
static assert(__traits(compiles, idt.modJulianDay));
}
}
/++
Converts this $(D DateTime) to a string with the format YYYYMMDDTHHMMSS.
Examples:
--------------------
assert(DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)).toISOString() ==
"20100704T070612");
assert(DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)).toISOString() ==
"19981225T021500");
assert(DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)).toISOString() ==
"00000105T230959");
assert(DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)).toISOString() ==
"-00040105T000002");
--------------------
+/
string toISOString() const nothrow
{
try
return format("%sT%s", _date.toISOString(), _tod.toISOString());
catch(Exception e)
assert(0, "format() threw.");
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(DateTime(Date(9, 12, 4), TimeOfDay(0, 0, 0)).toISOString(), "00091204T000000");
_assertPred!"=="(DateTime(Date(99, 12, 4), TimeOfDay(5, 6, 12)).toISOString(), "00991204T050612");
_assertPred!"=="(DateTime(Date(999, 12, 4), TimeOfDay(13, 44, 59)).toISOString(), "09991204T134459");
_assertPred!"=="(DateTime(Date(9999, 7, 4), TimeOfDay(23, 59, 59)).toISOString(), "99990704T235959");
_assertPred!"=="(DateTime(Date(10000, 10, 20), TimeOfDay(1, 1, 1)).toISOString(), "+100001020T010101");
//Test B.C.
_assertPred!"=="(DateTime(Date(0, 12, 4), TimeOfDay(0, 12, 4)).toISOString(), "00001204T001204");
_assertPred!"=="(DateTime(Date(-9, 12, 4), TimeOfDay(0, 0, 0)).toISOString(), "-00091204T000000");
_assertPred!"=="(DateTime(Date(-99, 12, 4), TimeOfDay(5, 6, 12)).toISOString(), "-00991204T050612");
_assertPred!"=="(DateTime(Date(-999, 12, 4), TimeOfDay(13, 44, 59)).toISOString(), "-09991204T134459");
_assertPred!"=="(DateTime(Date(-9999, 7, 4), TimeOfDay(23, 59, 59)).toISOString(), "-99990704T235959");
_assertPred!"=="(DateTime(Date(-10000, 10, 20), TimeOfDay(1, 1, 1)).toISOString(), "-100001020T010101");
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, cdt.toISOString()));
static assert(__traits(compiles, idt.toISOString()));
//Verify Examples.
assert(DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)).toISOString() == "20100704T070612");
assert(DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)).toISOString() == "19981225T021500");
assert(DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)).toISOString() == "00000105T230959");
assert(DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)).toISOString() == "-00040105T000002");
}
}
/++
Converts this $(D DateTime) to a string with the format
YYYY-MM-DDTHH:MM:SS.
Examples:
--------------------
assert(DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)).toISOExtString() ==
"2010-07-04T07:06:12");
assert(DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)).toISOExtString() ==
"1998-12-25T02:15:00");
assert(DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)).toISOExtString() ==
"0000-01-05T23:09:59");
assert(DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)).toISOExtString() ==
"-0004-01-05T00:00:02");
--------------------
+/
string toISOExtString() const nothrow
{
try
return format("%sT%s", _date.toISOExtString(), _tod.toISOExtString());
catch(Exception e)
assert(0, "format() threw.");
}
/++
$(RED Scheduled for deprecation in November 2011.
Please use toISOExtString instead.)
+/
alias toISOExtString toISOExtendedString;
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(DateTime(Date(9, 12, 4), TimeOfDay(0, 0, 0)).toISOExtString(), "0009-12-04T00:00:00");
_assertPred!"=="(DateTime(Date(99, 12, 4), TimeOfDay(5, 6, 12)).toISOExtString(), "0099-12-04T05:06:12");
_assertPred!"=="(DateTime(Date(999, 12, 4), TimeOfDay(13, 44, 59)).toISOExtString(), "0999-12-04T13:44:59");
_assertPred!"=="(DateTime(Date(9999, 7, 4), TimeOfDay(23, 59, 59)).toISOExtString(), "9999-07-04T23:59:59");
_assertPred!"=="(DateTime(Date(10000, 10, 20), TimeOfDay(1, 1, 1)).toISOExtString(), "+10000-10-20T01:01:01");
//Test B.C.
_assertPred!"=="(DateTime(Date(0, 12, 4), TimeOfDay(0, 12, 4)).toISOExtString(), "0000-12-04T00:12:04");
_assertPred!"=="(DateTime(Date(-9, 12, 4), TimeOfDay(0, 0, 0)).toISOExtString(), "-0009-12-04T00:00:00");
_assertPred!"=="(DateTime(Date(-99, 12, 4), TimeOfDay(5, 6, 12)).toISOExtString(), "-0099-12-04T05:06:12");
_assertPred!"=="(DateTime(Date(-999, 12, 4), TimeOfDay(13, 44, 59)).toISOExtString(), "-0999-12-04T13:44:59");
_assertPred!"=="(DateTime(Date(-9999, 7, 4), TimeOfDay(23, 59, 59)).toISOExtString(), "-9999-07-04T23:59:59");
_assertPred!"=="(DateTime(Date(-10000, 10, 20), TimeOfDay(1, 1, 1)).toISOExtString(), "-10000-10-20T01:01:01");
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, cdt.toISOExtString()));
static assert(__traits(compiles, idt.toISOExtString()));
//Verify Examples.
assert(DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)).toISOExtString() == "2010-07-04T07:06:12");
assert(DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)).toISOExtString() == "1998-12-25T02:15:00");
assert(DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)).toISOExtString() == "0000-01-05T23:09:59");
assert(DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)).toISOExtString() == "-0004-01-05T00:00:02");
}
}
/++
Converts this $(D DateTime) to a string with the format
YYYY-Mon-DD HH:MM:SS.
Examples:
--------------------
assert(DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)).toSimpleString() ==
"2010-Jul-04 07:06:12");
assert(DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)).toSimpleString() ==
"1998-Dec-25 02:15:00");
assert(DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)).toSimpleString() ==
"0000-Jan-05 23:09:59");
assert(DateTime(Dte(-4, 1, 5), TimeOfDay(0, 0, 2)).toSimpleString() ==
"-0004-Jan-05 00:00:02");
--------------------
+/
string toSimpleString() const nothrow
{
try
return format("%s %s", _date.toSimpleString(), _tod.toString());
catch(Exception e)
assert(0, "format() threw.");
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(DateTime(Date(9, 12, 4), TimeOfDay(0, 0, 0)).toSimpleString(), "0009-Dec-04 00:00:00");
_assertPred!"=="(DateTime(Date(99, 12, 4), TimeOfDay(5, 6, 12)).toSimpleString(), "0099-Dec-04 05:06:12");
_assertPred!"=="(DateTime(Date(999, 12, 4), TimeOfDay(13, 44, 59)).toSimpleString(), "0999-Dec-04 13:44:59");
_assertPred!"=="(DateTime(Date(9999, 7, 4), TimeOfDay(23, 59, 59)).toSimpleString(), "9999-Jul-04 23:59:59");
_assertPred!"=="(DateTime(Date(10000, 10, 20), TimeOfDay(1, 1, 1)).toSimpleString(), "+10000-Oct-20 01:01:01");
//Test B.C.
_assertPred!"=="(DateTime(Date(0, 12, 4), TimeOfDay(0, 12, 4)).toSimpleString(), "0000-Dec-04 00:12:04");
_assertPred!"=="(DateTime(Date(-9, 12, 4), TimeOfDay(0, 0, 0)).toSimpleString(), "-0009-Dec-04 00:00:00");
_assertPred!"=="(DateTime(Date(-99, 12, 4), TimeOfDay(5, 6, 12)).toSimpleString(), "-0099-Dec-04 05:06:12");
_assertPred!"=="(DateTime(Date(-999, 12, 4), TimeOfDay(13, 44, 59)).toSimpleString(), "-0999-Dec-04 13:44:59");
_assertPred!"=="(DateTime(Date(-9999, 7, 4), TimeOfDay(23, 59, 59)).toSimpleString(), "-9999-Jul-04 23:59:59");
_assertPred!"=="(DateTime(Date(-10000, 10, 20), TimeOfDay(1, 1, 1)).toSimpleString(), "-10000-Oct-20 01:01:01");
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(__traits(compiles, cdt.toSimpleString()));
static assert(__traits(compiles, idt.toSimpleString()));
//Verify Examples.
assert(DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)).toSimpleString() == "2010-Jul-04 07:06:12");
assert(DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)).toSimpleString() == "1998-Dec-25 02:15:00");
assert(DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)).toSimpleString() == "0000-Jan-05 23:09:59");
assert(DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)).toSimpleString() == "-0004-Jan-05 00:00:02");
}
}
/+
Converts this $(D DateTime) to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString()
{
return toSimpleString();
}
/++
Converts this $(D DateTime) to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString() const nothrow
{
return toSimpleString();
}
unittest
{
version(testStdDateTime)
{
auto dt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
const cdt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
immutable idt = DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33));
static assert(__traits(compiles, dt.toString()));
static assert(__traits(compiles, cdt.toString()));
static assert(__traits(compiles, idt.toString()));
}
}
/++
Creates a $(D DateTime) from a string with the format YYYYMMDDTHHMMSS.
Whitespace is stripped from the given string.
Params:
isoString = A string formatted in the ISO format for dates and times.
Throws:
$(D DateTimeException) if the given string is not in the ISO format
or if the resulting $(D DateTime) would not be valid.
Examples:
--------------------
assert(DateTime.fromISOString("20100704T070612") ==
DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
assert(DateTime.fromISOString("19981225T021500") ==
DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)));
assert(DateTime.fromISOString("00000105T230959") ==
DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)));
assert(DateTime.fromISOString("-00040105T000002") ==
DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)));
assert(DateTime.fromISOString(" 20100704T070612 ") ==
DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
--------------------
+/
static DateTime fromISOString(S)(in S isoString)
if(isSomeString!S)
{
immutable dstr = to!dstring(strip(isoString));
enforce(dstr.length >= 15, new DateTimeException(format("Invalid ISO String: %s", isoString)));
auto t = dstr.stds_indexOf('T');
enforce(t != -1, new DateTimeException(format("Invalid ISO String: %s", isoString)));
immutable date = Date.fromISOString(dstr[0..t]);
immutable tod = TimeOfDay.fromISOString(dstr[t+1 .. $]);
return DateTime(date, tod);
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(DateTime.fromISOString(""));
assertThrown!DateTimeException(DateTime.fromISOString("20100704000000"));
assertThrown!DateTimeException(DateTime.fromISOString("20100704 000000"));
assertThrown!DateTimeException(DateTime.fromISOString("20100704t000000"));
assertThrown!DateTimeException(DateTime.fromISOString("20100704T000000."));
assertThrown!DateTimeException(DateTime.fromISOString("20100704T000000.0"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-07-0400:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-07-04 00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-07-04t00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-07-04T00:00:00."));
assertThrown!DateTimeException(DateTime.fromISOString("2010-07-04T00:00:00.0"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-0400:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-04 00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-04t00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-04T00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-04 00:00:00."));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-04 00:00:00.0"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-12-22T172201"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Dec-22 17:22:01"));
_assertPred!"=="(DateTime.fromISOString("20101222T172201"), DateTime(Date(2010, 12, 22), TimeOfDay(17, 22, 01)));
_assertPred!"=="(DateTime.fromISOString("19990706T123033"), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromISOString("-19990706T123033"), DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromISOString("+019990706T123033"), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromISOString("19990706T123033 "), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromISOString(" 19990706T123033"), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromISOString(" 19990706T123033 "), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
//Verify Examples.
assert(DateTime.fromISOString("20100704T070612") == DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
assert(DateTime.fromISOString("19981225T021500") == DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)));
assert(DateTime.fromISOString("00000105T230959") == DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)));
assert(DateTime.fromISOString("-00040105T000002") == DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)));
assert(DateTime.fromISOString(" 20100704T070612 ") == DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
}
}
/++
Creates a $(D DateTime) from a string with the format
YYYY-MM-DDTHH:MM:SS. Whitespace is stripped from the given string.
Params:
isoString = A string formatted in the ISO Extended format for dates
and times.
Throws:
$(D DateTimeException) if the given string is not in the ISO
Extended format or if the resulting $(D DateTime) would not be
valid.
Examples:
--------------------
assert(DateTime.fromISOExtString("2010-07-04T07:06:12") ==
DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
assert(DateTime.fromISOExtString("1998-12-25T02:15:00") ==
DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)));
assert(DateTime.fromISOExtString("0000-01-05T23:09:59") ==
DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)));
assert(DateTime.fromISOExtString("-0004-01-05T00:00:02") ==
DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)));
assert(DateTime.fromISOExtString(" 2010-07-04T07:06:12 ") ==
DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
--------------------
+/
static DateTime fromISOExtString(S)(in S isoExtString)
if(isSomeString!(S))
{
immutable dstr = to!dstring(strip(isoExtString));
enforce(dstr.length >= 15, new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
auto t = dstr.stds_indexOf('T');
enforce(t != -1, new DateTimeException(format("Invalid ISO Extended String: %s", isoExtString)));
immutable date = Date.fromISOExtString(dstr[0..t]);
immutable tod = TimeOfDay.fromISOExtString(dstr[t+1 .. $]);
return DateTime(date, tod);
}
/++
$(RED Scheduled for deprecation in November 2011.
Please use fromISOExtString instead.)
+/
static DateTime fromISOExtendedString(S)(in S isoExtString)
if(isSomeString!(S))
{
pragma(msg, softDeprec!("2.053", "November 2011", "fromISOExtendedString", "fromISOExtString"));
return fromISOExtString!string(isoExtString);
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(DateTime.fromISOExtString(""));
assertThrown!DateTimeException(DateTime.fromISOExtString("20100704000000"));
assertThrown!DateTimeException(DateTime.fromISOExtString("20100704 000000"));
assertThrown!DateTimeException(DateTime.fromISOExtString("20100704t000000"));
assertThrown!DateTimeException(DateTime.fromISOExtString("20100704T000000."));
assertThrown!DateTimeException(DateTime.fromISOExtString("20100704T000000.0"));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-07:0400:00:00"));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-07-04 00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-07-04 00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-07-04t00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-07-04T00:00:00."));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-07-04T00:00:00.0"));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-Jul-0400:00:00"));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-Jul-04t00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-Jul-04 00:00:00."));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-Jul-04 00:00:00.0"));
assertThrown!DateTimeException(DateTime.fromISOExtString("20101222T172201"));
assertThrown!DateTimeException(DateTime.fromISOExtString("2010-Dec-22 17:22:01"));
_assertPred!"=="(DateTime.fromISOExtString("2010-12-22T17:22:01"), DateTime(Date(2010, 12, 22), TimeOfDay(17, 22, 01)));
_assertPred!"=="(DateTime.fromISOExtString("1999-07-06T12:30:33"), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromISOExtString("-1999-07-06T12:30:33"), DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromISOExtString("+01999-07-06T12:30:33"), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromISOExtString("1999-07-06T12:30:33 "), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromISOExtString(" 1999-07-06T12:30:33"), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromISOExtString(" 1999-07-06T12:30:33 "), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
//Verify Examples.
assert(DateTime.fromISOExtString("2010-07-04T07:06:12") == DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
assert(DateTime.fromISOExtString("1998-12-25T02:15:00") == DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)));
assert(DateTime.fromISOExtString("0000-01-05T23:09:59") == DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)));
assert(DateTime.fromISOExtString("-0004-01-05T00:00:02") == DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)));
assert(DateTime.fromISOExtString(" 2010-07-04T07:06:12 ") == DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
}
}
/++
Creates a $(D DateTime) from a string with the format
YYYY-Mon-DD HH:MM:SS. Whitespace is stripped from the given string.
Params:
simpleString = A string formatted in the way that toSimpleString
formats dates and times.
Throws:
$(D DateTimeException) if the given string is not in the correct
format or if the resulting $(D DateTime) would not be valid.
Examples:
--------------------
assert(DateTime.fromSimpleString("2010-Jul-04 07:06:12") ==
DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
assert(DateTime.fromSimpleString("1998-Dec-25 02:15:00") ==
DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)));
assert(DateTime.fromSimpleString("0000-Jan-05 23:09:59") ==
DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)));
assert(DateTime.fromSimpleString("-0004-Jan-05 00:00:02") ==
DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)));
assert(DateTime.fromSimpleString(" 2010-Jul-04 07:06:12 ") ==
DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
--------------------
+/
static DateTime fromSimpleString(S)(in S simpleString)
if(isSomeString!(S))
{
immutable dstr = to!dstring(strip(simpleString));
enforce(dstr.length >= 15, new DateTimeException(format("Invalid string format: %s", simpleString)));
auto t = dstr.stds_indexOf(' ');
enforce(t != -1, new DateTimeException(format("Invalid string format: %s", simpleString)));
immutable date = Date.fromSimpleString(dstr[0..t]);
immutable tod = TimeOfDay.fromISOExtString(dstr[t+1 .. $]);
return DateTime(date, tod);
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(DateTime.fromISOString(""));
assertThrown!DateTimeException(DateTime.fromISOString("20100704000000"));
assertThrown!DateTimeException(DateTime.fromISOString("20100704 000000"));
assertThrown!DateTimeException(DateTime.fromISOString("20100704t000000"));
assertThrown!DateTimeException(DateTime.fromISOString("20100704T000000."));
assertThrown!DateTimeException(DateTime.fromISOString("20100704T000000.0"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-07-0400:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-07-04 00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-07-04t00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-07-04T00:00:00."));
assertThrown!DateTimeException(DateTime.fromISOString("2010-07-04T00:00:00.0"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-0400:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-04 00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-04t00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-04T00:00:00"));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-04 00:00:00."));
assertThrown!DateTimeException(DateTime.fromISOString("2010-Jul-04 00:00:00.0"));
assertThrown!DateTimeException(DateTime.fromSimpleString("20101222T172201"));
assertThrown!DateTimeException(DateTime.fromSimpleString("2010-12-22T172201"));
_assertPred!"=="(DateTime.fromSimpleString("2010-Dec-22 17:22:01"), DateTime(Date(2010, 12, 22), TimeOfDay(17, 22, 01)));
_assertPred!"=="(DateTime.fromSimpleString("1999-Jul-06 12:30:33"), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromSimpleString("-1999-Jul-06 12:30:33"), DateTime(Date(-1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromSimpleString("+01999-Jul-06 12:30:33"), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromSimpleString("1999-Jul-06 12:30:33 "), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromSimpleString(" 1999-Jul-06 12:30:33"), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
_assertPred!"=="(DateTime.fromSimpleString(" 1999-Jul-06 12:30:33 "), DateTime(Date(1999, 7, 6), TimeOfDay(12, 30, 33)));
//Verify Examples.
assert(DateTime.fromSimpleString("2010-Jul-04 07:06:12") == DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
assert(DateTime.fromSimpleString("1998-Dec-25 02:15:00") == DateTime(Date(1998, 12, 25), TimeOfDay(2, 15, 0)));
assert(DateTime.fromSimpleString("0000-Jan-05 23:09:59") == DateTime(Date(0, 1, 5), TimeOfDay(23, 9, 59)));
assert(DateTime.fromSimpleString("-0004-Jan-05 00:00:02") == DateTime(Date(-4, 1, 5), TimeOfDay(0, 0, 2)));
assert(DateTime.fromSimpleString(" 2010-Jul-04 07:06:12 ") == DateTime(Date(2010, 7, 4), TimeOfDay(7, 6, 12)));
}
}
//TODO Add function which takes a user-specified time format and produces a DateTime
//TODO Add function which takes pretty much any time-string and produces a DateTime
// Obviously, it will be less efficient, and it probably won't manage _every_
// possible date format, but a smart conversion function would be nice.
/++
Returns the $(D DateTime) farthest in the past which is representable by
$(D DateTime).
+/
@property static DateTime min() pure nothrow
out(result)
{
assert(result._date == Date.min);
assert(result._tod == TimeOfDay.min);
}
body
{
auto dt = DateTime.init;
dt._date._year = short.min;
dt._date._month = Month.jan;
dt._date._day = 1;
return dt;
}
unittest
{
version(testStdDateTime)
{
assert(DateTime.min.year < 0);
assert(DateTime.min < DateTime.max);
}
}
/++
Returns the $(D DateTime) farthest in the future which is representable
by $(D DateTime).
+/
@property static DateTime max() pure nothrow
out(result)
{
assert(result._date == Date.max);
assert(result._tod == TimeOfDay.max);
}
body
{
auto dt = DateTime.init;
dt._date._year = short.max;
dt._date._month = Month.dec;
dt._date._day = 31;
dt._tod._hour = TimeOfDay.maxHour;
dt._tod._minute = TimeOfDay.maxMinute;
dt._tod._second = TimeOfDay.maxSecond;
return dt;
}
unittest
{
version(testStdDateTime)
{
assert(DateTime.max.year > 0);
assert(DateTime.max > DateTime.min);
}
}
private:
/+
Add seconds to the time of day. Negative values will subtract. If the
number of seconds overflows (or underflows), then the seconds will wrap,
increasing (or decreasing) the number of minutes accordingly. The
same goes for any larger units.
Params:
seconds = The number of seconds to add to this $(D DateTime).
+/
ref DateTime addSeconds(long seconds) pure nothrow
{
long hnsecs = convert!("seconds", "hnsecs")(seconds);
hnsecs += convert!("hours", "hnsecs")(_tod._hour);
hnsecs += convert!("minutes", "hnsecs")(_tod._minute);
hnsecs += convert!("seconds", "hnsecs")(_tod._second);
auto days = splitUnitsFromHNSecs!"days"(hnsecs);
if(hnsecs < 0)
{
hnsecs += convert!("days", "hnsecs")(1);
--days;
}
_date.addDays(days);
immutable newHours = splitUnitsFromHNSecs!"hours"(hnsecs);
immutable newMinutes = splitUnitsFromHNSecs!"minutes"(hnsecs);
immutable newSeconds = splitUnitsFromHNSecs!"seconds"(hnsecs);
_tod._hour = cast(ubyte)newHours;
_tod._minute = cast(ubyte)newMinutes;
_tod._second = cast(ubyte)newSeconds;
return this;
}
unittest
{
version(testStdDateTime)
{
static void testDT(DateTime orig, int seconds, in DateTime expected, size_t line = __LINE__)
{
orig.addSeconds(seconds);
_assertPred!"=="(orig, expected, "", __FILE__, line);
}
//Test A.D.
testDT(DateTime(1999, 7, 6, 12, 30, 33), 0, DateTime(1999, 7, 6, 12, 30, 33));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 1, DateTime(1999, 7, 6, 12, 30, 34));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 2, DateTime(1999, 7, 6, 12, 30, 35));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 3, DateTime(1999, 7, 6, 12, 30, 36));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 4, DateTime(1999, 7, 6, 12, 30, 37));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 5, DateTime(1999, 7, 6, 12, 30, 38));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 10, DateTime(1999, 7, 6, 12, 30, 43));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 15, DateTime(1999, 7, 6, 12, 30, 48));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 26, DateTime(1999, 7, 6, 12, 30, 59));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 27, DateTime(1999, 7, 6, 12, 31, 0));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 30, DateTime(1999, 7, 6, 12, 31, 3));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 59, DateTime(1999, 7, 6, 12, 31, 32));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 60, DateTime(1999, 7, 6, 12, 31, 33));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 61, DateTime(1999, 7, 6, 12, 31, 34));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 1766, DateTime(1999, 7, 6, 12, 59, 59));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 1767, DateTime(1999, 7, 6, 13, 0, 0));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 1768, DateTime(1999, 7, 6, 13, 0, 1));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 2007, DateTime(1999, 7, 6, 13, 4, 0));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 3599, DateTime(1999, 7, 6, 13, 30, 32));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 3600, DateTime(1999, 7, 6, 13, 30, 33));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 3601, DateTime(1999, 7, 6, 13, 30, 34));
testDT(DateTime(1999, 7, 6, 12, 30, 33), 7200, DateTime(1999, 7, 6, 14, 30, 33));
testDT(DateTime(1999, 7, 6, 23, 0, 0), 432_123, DateTime(1999, 7, 11, 23, 2, 3));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -1, DateTime(1999, 7, 6, 12, 30, 32));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -2, DateTime(1999, 7, 6, 12, 30, 31));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -3, DateTime(1999, 7, 6, 12, 30, 30));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -4, DateTime(1999, 7, 6, 12, 30, 29));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -5, DateTime(1999, 7, 6, 12, 30, 28));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -10, DateTime(1999, 7, 6, 12, 30, 23));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -15, DateTime(1999, 7, 6, 12, 30, 18));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -33, DateTime(1999, 7, 6, 12, 30, 0));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -34, DateTime(1999, 7, 6, 12, 29, 59));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -35, DateTime(1999, 7, 6, 12, 29, 58));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -59, DateTime(1999, 7, 6, 12, 29, 34));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -60, DateTime(1999, 7, 6, 12, 29, 33));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -61, DateTime(1999, 7, 6, 12, 29, 32));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -1833, DateTime(1999, 7, 6, 12, 0, 0));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -1834, DateTime(1999, 7, 6, 11, 59, 59));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -3600, DateTime(1999, 7, 6, 11, 30, 33));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -3601, DateTime(1999, 7, 6, 11, 30, 32));
testDT(DateTime(1999, 7, 6, 12, 30, 33), -5134, DateTime(1999, 7, 6, 11, 4, 59));
testDT(DateTime(1999, 7, 6, 23, 0, 0), -432_123, DateTime(1999, 7, 1, 22, 57, 57));
testDT(DateTime(1999, 7, 6, 12, 30, 0), 1, DateTime(1999, 7, 6, 12, 30, 1));
testDT(DateTime(1999, 7, 6, 12, 30, 0), 0, DateTime(1999, 7, 6, 12, 30, 0));
testDT(DateTime(1999, 7, 6, 12, 30, 0), -1, DateTime(1999, 7, 6, 12, 29, 59));
testDT(DateTime(1999, 7, 6, 12, 0, 0), 1, DateTime(1999, 7, 6, 12, 0, 1));
testDT(DateTime(1999, 7, 6, 12, 0, 0), 0, DateTime(1999, 7, 6, 12, 0, 0));
testDT(DateTime(1999, 7, 6, 12, 0, 0), -1, DateTime(1999, 7, 6, 11, 59, 59));
testDT(DateTime(1999, 7, 6, 0, 0, 0), 1, DateTime(1999, 7, 6, 0, 0, 1));
testDT(DateTime(1999, 7, 6, 0, 0, 0), 0, DateTime(1999, 7, 6, 0, 0, 0));
testDT(DateTime(1999, 7, 6, 0, 0, 0), -1, DateTime(1999, 7, 5, 23, 59, 59));
testDT(DateTime(1999, 7, 5, 23, 59, 59), 1, DateTime(1999, 7, 6, 0, 0, 0));
testDT(DateTime(1999, 7, 5, 23, 59, 59), 0, DateTime(1999, 7, 5, 23, 59, 59));
testDT(DateTime(1999, 7, 5, 23, 59, 59), -1, DateTime(1999, 7, 5, 23, 59, 58));
testDT(DateTime(1998, 12, 31, 23, 59, 59), 1, DateTime(1999, 1, 1, 0, 0, 0));
testDT(DateTime(1998, 12, 31, 23, 59, 59), 0, DateTime(1998, 12, 31, 23, 59, 59));
testDT(DateTime(1998, 12, 31, 23, 59, 59), -1, DateTime(1998, 12, 31, 23, 59, 58));
testDT(DateTime(1998, 1, 1, 0, 0, 0), 1, DateTime(1998, 1, 1, 0, 0, 1));
testDT(DateTime(1998, 1, 1, 0, 0, 0), 0, DateTime(1998, 1, 1, 0, 0, 0));
testDT(DateTime(1998, 1, 1, 0, 0, 0), -1, DateTime(1997, 12, 31, 23, 59, 59));
//Test B.C.
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 0, DateTime(-1999, 7, 6, 12, 30, 33));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 1, DateTime(-1999, 7, 6, 12, 30, 34));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 2, DateTime(-1999, 7, 6, 12, 30, 35));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 3, DateTime(-1999, 7, 6, 12, 30, 36));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 4, DateTime(-1999, 7, 6, 12, 30, 37));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 5, DateTime(-1999, 7, 6, 12, 30, 38));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 10, DateTime(-1999, 7, 6, 12, 30, 43));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 15, DateTime(-1999, 7, 6, 12, 30, 48));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 26, DateTime(-1999, 7, 6, 12, 30, 59));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 27, DateTime(-1999, 7, 6, 12, 31, 0));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 30, DateTime(-1999, 7, 6, 12, 31, 3));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 59, DateTime(-1999, 7, 6, 12, 31, 32));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 60, DateTime(-1999, 7, 6, 12, 31, 33));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 61, DateTime(-1999, 7, 6, 12, 31, 34));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 1766, DateTime(-1999, 7, 6, 12, 59, 59));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 1767, DateTime(-1999, 7, 6, 13, 0, 0));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 1768, DateTime(-1999, 7, 6, 13, 0, 1));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 2007, DateTime(-1999, 7, 6, 13, 4, 0));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 3599, DateTime(-1999, 7, 6, 13, 30, 32));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 3600, DateTime(-1999, 7, 6, 13, 30, 33));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 3601, DateTime(-1999, 7, 6, 13, 30, 34));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), 7200, DateTime(-1999, 7, 6, 14, 30, 33));
testDT(DateTime(-1999, 7, 6, 23, 0, 0), 432_123, DateTime(-1999, 7, 11, 23, 2, 3));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -1, DateTime(-1999, 7, 6, 12, 30, 32));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -2, DateTime(-1999, 7, 6, 12, 30, 31));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -3, DateTime(-1999, 7, 6, 12, 30, 30));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -4, DateTime(-1999, 7, 6, 12, 30, 29));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -5, DateTime(-1999, 7, 6, 12, 30, 28));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -10, DateTime(-1999, 7, 6, 12, 30, 23));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -15, DateTime(-1999, 7, 6, 12, 30, 18));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -33, DateTime(-1999, 7, 6, 12, 30, 0));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -34, DateTime(-1999, 7, 6, 12, 29, 59));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -35, DateTime(-1999, 7, 6, 12, 29, 58));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -59, DateTime(-1999, 7, 6, 12, 29, 34));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -60, DateTime(-1999, 7, 6, 12, 29, 33));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -61, DateTime(-1999, 7, 6, 12, 29, 32));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -1833, DateTime(-1999, 7, 6, 12, 0, 0));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -1834, DateTime(-1999, 7, 6, 11, 59, 59));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -3600, DateTime(-1999, 7, 6, 11, 30, 33));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -3601, DateTime(-1999, 7, 6, 11, 30, 32));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -5134, DateTime(-1999, 7, 6, 11, 4, 59));
testDT(DateTime(-1999, 7, 6, 12, 30, 33), -7200, DateTime(-1999, 7, 6, 10, 30, 33));
testDT(DateTime(-1999, 7, 6, 23, 0, 0), -432_123, DateTime(-1999, 7, 1, 22, 57, 57));
testDT(DateTime(-1999, 7, 6, 12, 30, 0), 1, DateTime(-1999, 7, 6, 12, 30, 1));
testDT(DateTime(-1999, 7, 6, 12, 30, 0), 0, DateTime(-1999, 7, 6, 12, 30, 0));
testDT(DateTime(-1999, 7, 6, 12, 30, 0), -1, DateTime(-1999, 7, 6, 12, 29, 59));
testDT(DateTime(-1999, 7, 6, 12, 0, 0), 1, DateTime(-1999, 7, 6, 12, 0, 1));
testDT(DateTime(-1999, 7, 6, 12, 0, 0), 0, DateTime(-1999, 7, 6, 12, 0, 0));
testDT(DateTime(-1999, 7, 6, 12, 0, 0), -1, DateTime(-1999, 7, 6, 11, 59, 59));
testDT(DateTime(-1999, 7, 6, 0, 0, 0), 1, DateTime(-1999, 7, 6, 0, 0, 1));
testDT(DateTime(-1999, 7, 6, 0, 0, 0), 0, DateTime(-1999, 7, 6, 0, 0, 0));
testDT(DateTime(-1999, 7, 6, 0, 0, 0), -1, DateTime(-1999, 7, 5, 23, 59, 59));
testDT(DateTime(-1999, 7, 5, 23, 59, 59), 1, DateTime(-1999, 7, 6, 0, 0, 0));
testDT(DateTime(-1999, 7, 5, 23, 59, 59), 0, DateTime(-1999, 7, 5, 23, 59, 59));
testDT(DateTime(-1999, 7, 5, 23, 59, 59), -1, DateTime(-1999, 7, 5, 23, 59, 58));
testDT(DateTime(-2000, 12, 31, 23, 59, 59), 1, DateTime(-1999, 1, 1, 0, 0, 0));
testDT(DateTime(-2000, 12, 31, 23, 59, 59), 0, DateTime(-2000, 12, 31, 23, 59, 59));
testDT(DateTime(-2000, 12, 31, 23, 59, 59), -1, DateTime(-2000, 12, 31, 23, 59, 58));
testDT(DateTime(-2000, 1, 1, 0, 0, 0), 1, DateTime(-2000, 1, 1, 0, 0, 1));
testDT(DateTime(-2000, 1, 1, 0, 0, 0), 0, DateTime(-2000, 1, 1, 0, 0, 0));
testDT(DateTime(-2000, 1, 1, 0, 0, 0), -1, DateTime(-2001, 12, 31, 23, 59, 59));
//Test Both
testDT(DateTime(1, 1, 1, 0, 0, 0), -1, DateTime(0, 12, 31, 23, 59, 59));
testDT(DateTime(0, 12, 31, 23, 59, 59), 1, DateTime(1, 1, 1, 0, 0, 0));
testDT(DateTime(0, 1, 1, 0, 0, 0), -1, DateTime(-1, 12, 31, 23, 59, 59));
testDT(DateTime(-1, 12, 31, 23, 59, 59), 1, DateTime(0, 1, 1, 0, 0, 0));
testDT(DateTime(-1, 1, 1, 11, 30, 33), 63_165_600L, DateTime(1, 1, 1, 13, 30, 33));
testDT(DateTime(1, 1, 1, 13, 30, 33), -63_165_600L, DateTime(-1, 1, 1, 11, 30, 33));
testDT(DateTime(-1, 1, 1, 11, 30, 33), 63_165_617L, DateTime(1, 1, 1, 13, 30, 50));
testDT(DateTime(1, 1, 1, 13, 30, 50), -63_165_617L, DateTime(-1, 1, 1, 11, 30, 33));
const cdt = DateTime(1999, 7, 6, 12, 30, 33);
immutable idt = DateTime(1999, 7, 6, 12, 30, 33);
static assert(!__traits(compiles, cdt.addSeconds(4)));
static assert(!__traits(compiles, idt.addSeconds(4)));
}
}
Date _date;
TimeOfDay _tod;
}
//==============================================================================
// Section with intervals.
//==============================================================================
/++
Represents an interval of time.
An $(D Interval) has a starting point and an end point. The interval of time
is therefore the time starting at the starting point up to, but not
including, the end point. e.g.
$(BOOKTABLE,
$(TR $(TD [January 5th, 2010 - March 10th, 2010$(RPAREN)))
$(TR $(TD [05:00:30 - 12:00:00$(RPAREN)))
$(TR $(TD [1982-01-04T08:59:00 - 2010-07-04T12:00:00$(RPAREN)))
)
A range can be obtained from an $(D Interval), allowing you to iterate over
that interval, with the exact time points which are iterated over depending
on the function which generates the range.
+/
struct Interval(TP)
{
public:
/++
Params:
begin = The time point which begins the interval.
end = The time point which ends (but is not included in) the
interval.
Throws:
$(D DateTimeException) if $(D_PARAM end) is before $(D_PARAM begin).
Examples:
--------------------
Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
--------------------
+/
this(U)(in TP begin, in U end) pure
if(is(Unqual!TP == Unqual!U))
{
if(!_valid(begin, end))
throw new DateTimeException("Arguments would result in an invalid Interval.");
_begin = cast(TP)begin;
_end = cast(TP)end;
}
/++
Params:
begin = The time point which begins the interval.
duration = The duration from the starting point to the end point.
Throws:
$(D DateTimeException) if the resulting $(D end) is before
$(D begin).
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Dur.years(3)) ==
Interval!Date(Date(1996, 1, 2), Date(1999, 1, 2)));
--------------------
+/
this(D)(in TP begin, in D duration) pure
if(__traits(compiles, begin + duration))
{
_begin = cast(TP)begin;
_end = begin + duration;
if(!_valid(_begin, _end))
throw new DateTimeException("Arguments would result in an invalid Interval.");
}
/++
Params:
rhs = The $(D Interval) to assign to this one.
+/
/+ref+/ Interval opAssign(const ref Interval rhs) pure nothrow
{
_begin = cast(TP)rhs._begin;
_end = cast(TP)rhs._end;
return this;
}
/++
Params:
rhs = The $(D Interval) to assign to this one.
+/
/+ref+/ Interval opAssign(Interval rhs) pure nothrow
{
_begin = cast(TP)rhs._begin;
_end = cast(TP)rhs._end;
return this;
}
/++
The starting point of the interval. It is included in the interval.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).begin ==
Date(1996, 1, 2));
--------------------
+/
@property TP begin() const pure nothrow
{
return cast(TP)_begin;
}
/++
The starting point of the interval. It is included in the interval.
Params:
timePoint = The time point to set $(D begin) to.
Throws:
$(D DateTimeException) if the resulting interval would be invalid.
+/
@property void begin(TP timePoint) pure
{
if(!_valid(timePoint, _end))
throw new DateTimeException("Arguments would result in an invalid Interval.");
_begin = timePoint;
}
/++
The end point of the interval. It is excluded from the interval.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).end ==
Date(2012, 3, 1));
--------------------
+/
@property TP end() const pure nothrow
{
return cast(TP)_end;
}
/++
The end point of the interval. It is excluded from the interval.
Params:
timePoint = The time point to set end to.
Throws:
$(D DateTimeException) if the resulting interval would be invalid.
+/
@property void end(TP timePoint) pure
{
if(!_valid(_begin, timePoint))
throw new DateTimeException("Arguments would result in an invalid Interval.");
_end = timePoint;
}
/++
Returns the duration between $(D begin) and $(D end).
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).length ==
dur!"days"(5903));
--------------------
+/
@property typeof(end - begin) length() const pure nothrow
{
return _end - _begin;
}
/++
Whether the interval's length is 0, that is, whether $(D begin == end).
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(1996, 1, 2)).empty);
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).empty);
--------------------
+/
@property bool empty() const pure nothrow
{
return _begin == _end;
}
/++
Whether the given time point is within this interval.
Params:
timePoint = The time point to check for inclusion in this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
Date(1994, 12, 24)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
Date(2000, 1, 5)));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
Date(2012, 3, 1)));
--------------------
+/
bool contains(in TP timePoint) const pure
{
_enforceNotEmpty();
return timePoint >= _begin && timePoint < _end;
}
/++
Whether the given interval is completely within this interval.
Params:
interval = The interval to check for inclusion in this interval.
Throws:
$(D DateTimeException) if either interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
Interval!Date(Date(1998, 2, 28), Date(2013, 5, 1))));
--------------------
+/
bool contains(in Interval interval) const pure
{
_enforceNotEmpty();
interval._enforceNotEmpty();
return interval._begin >= _begin &&
interval._begin < _end &&
interval._end <= _end;
}
/++
Whether the given interval is completely within this interval.
Always returns false (unless this interval is empty), because an
interval going to positive infinity can never be contained in a finite
interval.
Params:
interval = The interval to check for inclusion in this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
PosInfInterval!Date(Date(1999, 5, 4))));
--------------------
+/
bool contains(in PosInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return false;
}
/++
Whether the given interval is completely within this interval.
Always returns false (unless this interval is empty), because an
interval beginning at negative infinity can never be contained in a
finite interval.
Params:
interval = The interval to check for inclusion in this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(
NegInfInterval!Date(Date(1996, 5, 4))));
--------------------
+/
bool contains(in NegInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return false;
}
/++
Whether this interval is before the given time point.
Params:
timePoint = The time point to check whether this interval is before
it.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
Date(1994, 12, 24)));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
Date(2000, 1, 5)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
Date(2012, 3, 1)));
--------------------
+/
bool isBefore(in TP timePoint) const pure
{
_enforceNotEmpty();
return _end <= timePoint;
}
/++
Whether this interval is before the given interval and does not
intersect with it.
Params:
interval = The interval to check for against this interval.
Throws:
$(D DateTimeException) if either interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
Interval!Date(Date(2012, 3, 1), Date(2013, 5, 1))));
--------------------
+/
bool isBefore(in Interval interval) const pure
{
_enforceNotEmpty();
interval._enforceNotEmpty();
return _end <= interval._begin;
}
/++
Whether this interval is before the given interval and does not
intersect with it.
Params:
interval = The interval to check for against this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
PosInfInterval!Date(Date(1999, 5, 4))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
PosInfInterval!Date(Date(2013, 3, 7))));
--------------------
+/
bool isBefore(in PosInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return _end <= interval._begin;
}
/++
Whether this interval is before the given interval and does not
intersect with it.
Always returns false (unless this interval is empty) because a finite
interval can never be before an interval beginning at negative infinity.
Params:
interval = The interval to check for against this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(
NegInfInterval!Date(Date(1996, 5, 4))));
--------------------
+/
bool isBefore(in NegInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return false;
}
/++
Whether this interval is after the given time point.
Params:
timePoint = The time point to check whether this interval is after
it.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
Date(1994, 12, 24)));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
Date(2000, 1, 5)));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
Date(2012, 3, 1)));
--------------------
+/
bool isAfter(in TP timePoint) const pure
{
_enforceNotEmpty();
return timePoint < _begin;
}
/++
Whether this interval is after the given interval and does not intersect
it.
Params:
interval = The interval to check against this interval.
Throws:
$(D DateTimeException) if either interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));
--------------------
+/
bool isAfter(in Interval interval) const pure
{
_enforceNotEmpty();
interval._enforceNotEmpty();
return _begin >= interval._end;
}
/++
Whether this interval is after the given interval and does not intersect
it.
Always returns false (unless this interval is empty) because a finite
interval can never be after an interval going to positive infinity.
Params:
interval = The interval to check against this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
PosInfInterval!Date(Date(1999, 5, 4))));
--------------------
+/
bool isAfter(in PosInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return false;
}
/++
Whether this interval is after the given interval and does not intersect
it.
Params:
interval = The interval to check against this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(
NegInfInterval!Date(Date(1996, 1, 2))));
--------------------
+/
bool isAfter(in NegInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return _begin >= interval._end;
}
/++
Whether the given interval overlaps this interval.
Params:
interval = The interval to check for intersection with this interval.
Throws:
$(D DateTimeException) if either interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));
--------------------
+/
bool intersects(in Interval interval) const pure
{
_enforceNotEmpty();
interval._enforceNotEmpty();
return interval._begin < _end && interval._end > _begin;
}
/++
Whether the given interval overlaps this interval.
Params:
interval = The interval to check for intersection with this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
PosInfInterval!Date(Date(1999, 5, 4))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
PosInfInterval!Date(Date(2012, 3, 1))));
--------------------
+/
bool intersects(in PosInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return _end > interval._begin;
}
/++
Whether the given interval overlaps this interval.
Params:
interval = The interval to check for intersection with this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
NegInfInterval!Date(Date(1996, 1, 2))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(
NegInfInterval!Date(Date(2000, 1, 2))));
--------------------
+/
bool intersects(in NegInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return _begin < interval._end;
}
/++
Returns the intersection of two intervals
Params:
interval = The interval to intersect with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect or if
either interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
Interval!Date(Date(1996, 1 , 2), Date(2000, 8, 2)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) ==
Interval!Date(Date(1999, 1 , 12), Date(2011, 9, 17)));
--------------------
+/
Interval intersection(in Interval interval) const
{
enforce(this.intersects(interval), new DateTimeException(format("%s and %s do not intersect.", this, interval)));
auto begin = _begin > interval._begin ? _begin : interval._begin;
auto end = _end < interval._end ? _end : interval._end;
return Interval(begin, end);
}
/++
Returns the intersection of two intervals
Params:
interval = The interval to intersect with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect or if
this interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
PosInfInterval!Date(Date(1990, 7, 6))) ==
Interval!Date(Date(1996, 1 , 2), Date(2012, 3, 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
PosInfInterval!Date(Date(1999, 1, 12))) ==
Interval!Date(Date(1999, 1 , 12), Date(2012, 3, 1)));
--------------------
+/
Interval intersection(in PosInfInterval!TP interval) const
{
enforce(this.intersects(interval), new DateTimeException(format("%s and %s do not intersect.", this, interval)));
return Interval(_begin > interval._begin ? _begin : interval._begin, _end);
}
/++
Returns the intersection of two intervals
Params:
interval = The interval to intersect with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect or if
this interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
NegInfInterval!Date(Date(1999, 7, 6))) ==
Interval!Date(Date(1996, 1 , 2), Date(1999, 7, 6)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(
NegInfInterval!Date(Date(2013, 1, 12))) ==
Interval!Date(Date(1996, 1 , 2), Date(2012, 3, 1)));
--------------------
+/
Interval intersection(in NegInfInterval!TP interval) const
{
enforce(this.intersects(interval), new DateTimeException(format("%s and %s do not intersect.", this, interval)));
return Interval(_begin, _end < interval._end ? _end : interval._end);
}
/++
Whether the given interval is adjacent to this interval.
Params:
interval = The interval to check whether its adjecent to this
interval.
Throws:
$(D DateTimeException) if either interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
Interval!Date(Date(1990, 7, 6), Date(1996, 1, 2))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
Interval!Date(Date(2012, 3, 1), Date(2013, 9, 17))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
Interval!Date(Date(1989, 3, 1), Date(2012, 3, 1))));
--------------------
+/
bool isAdjacent(in Interval interval) const pure
{
_enforceNotEmpty();
interval._enforceNotEmpty();
return _begin == interval._end || _end == interval._begin;
}
/++
Whether the given interval is adjacent to this interval.
Params:
interval = The interval to check whether its adjecent to this
interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
PosInfInterval!Date(Date(1999, 5, 4))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
PosInfInterval!Date(Date(2012, 3, 1))));
--------------------
+/
bool isAdjacent(in PosInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return _end == interval._begin;
}
/++
Whether the given interval is adjacent to this interval.
Params:
interval = The interval to check whether its adjecent to this
interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
NegInfInterval!Date(Date(1996, 1, 2))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(
NegInfInterval!Date(Date(2000, 1, 2))));
--------------------
+/
bool isAdjacent(in NegInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return _begin == interval._end;
}
/++
Returns the union of two intervals
Params:
interval = The interval to merge with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect and are
not adjacent or if either interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
Interval!Date(Date(1990, 7 , 6), Date(2012, 3, 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
Interval!Date(Date(2012, 3, 1), Date(2013, 5, 7))) ==
Interval!Date(Date(1996, 1 , 2), Date(2013, 5, 7)));
--------------------
+/
Interval merge(in Interval interval) const
{
enforce(this.isAdjacent(interval) || this.intersects(interval),
new DateTimeException(format("%s and %s are not adjacent and do not intersect.", this, interval)));
auto begin = _begin < interval._begin ? _begin : interval._begin;
auto end = _end > interval._end ? _end : interval._end;
return Interval(begin, end);
}
/++
Returns the union of two intervals
Params:
interval = The interval to merge with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect and are
not adjacent or if this interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
PosInfInterval!Date(Date(1990, 7, 6))) ==
PosInfInterval!Date(Date(1990, 7 , 6)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
PosInfInterval!Date(Date(2012, 3, 1))) ==
PosInfInterval!Date(Date(1996, 1 , 2)));
--------------------
+/
PosInfInterval!TP merge(in PosInfInterval!TP interval) const
{
enforce(this.isAdjacent(interval) || this.intersects(interval),
new DateTimeException(format("%s and %s are not adjacent and do not intersect.", this, interval)));
return PosInfInterval!TP(_begin < interval._begin ? _begin : interval._begin);
}
/++
Returns the union of two intervals
Params:
interval = The interval to merge with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect and are not
adjacent or if this interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
NegInfInterval!Date(Date(1996, 1, 2))) ==
NegInfInterval!Date(Date(2012, 3 , 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(
NegInfInterval!Date(Date(2013, 1, 12))) ==
NegInfInterval!Date(Date(2013, 1 , 12)));
--------------------
+/
NegInfInterval!TP merge(in NegInfInterval!TP interval) const
{
enforce(this.isAdjacent(interval) || this.intersects(interval),
new DateTimeException(format("%s and %s are not adjacent and do not intersect.", this, interval)));
return NegInfInterval!TP(_end > interval._end ? _end : interval._end);
}
/++
Returns an interval that covers from the earliest time point of two
intervals up to (but not including) the latest time point of two
intervals.
Params:
interval = The interval to create a span together with this interval.
Throws:
$(D DateTimeException) if either interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
Interval!Date(Date(1990, 7, 6), Date(1991, 1, 8))) ==
Interval!Date(Date(1990, 7 , 6), Date(2012, 3, 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
Interval!Date(Date(2012, 3, 1), Date(2013, 5, 7))) ==
Interval!Date(Date(1996, 1 , 2), Date(2013, 5, 7)));
--------------------
+/
Interval span(in Interval interval) const pure
{
_enforceNotEmpty();
interval._enforceNotEmpty();
auto begin = _begin < interval._begin ? _begin : interval._begin;
auto end = _end > interval._end ? _end : interval._end;
return Interval(begin, end);
}
/++
Returns an interval that covers from the earliest time point of two
intervals up to (but not including) the latest time point of two
intervals.
Params:
interval = The interval to create a span together with this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
PosInfInterval!Date(Date(1990, 7, 6))) ==
PosInfInterval!Date(Date(1990, 7 , 6)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
PosInfInterval!Date(Date(2050, 1, 1))) ==
PosInfInterval!Date(Date(1996, 1 , 2)));
--------------------
+/
PosInfInterval!TP span(in PosInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return PosInfInterval!TP(_begin < interval._begin ? _begin : interval._begin);
}
/++
Returns an interval that covers from the earliest time point of two
intervals up to (but not including) the latest time point of two
intervals.
Params:
interval = The interval to create a span together with this interval.
Throws:
$(D DateTimeException) if this interval is empty.
Examples:
--------------------
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
NegInfInterval!Date(Date(1602, 5, 21))) ==
NegInfInterval!Date(Date(2012, 3 , 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(
NegInfInterval!Date(Date(2013, 1, 12))) ==
NegInfInterval!Date(Date(2013, 1 , 12)));
--------------------
+/
NegInfInterval!TP span(in NegInfInterval!TP interval) const pure
{
_enforceNotEmpty();
return NegInfInterval!TP(_end > interval._end ? _end : interval._end);
}
/++
Shifts the interval forward or backwards in time by the given duration
(a positive duration shifts the interval forward; a negative duration
shifts it backward). Effectively, it does $(D begin += duration) and
$(D end += duration).
Params:
duration = The duration to shift the interval by.
Throws:
$(D DateTimeException) this interval is empty or if the resulting
interval would be invalid.
Examples:
--------------------
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 4, 5));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 4, 5));
interval1.shift(dur!"days"(50));
assert(interval1 == Interval!Date(Date(1996, 2, 21), Date(2012, 5, 25)));
interval2.shift(dur!"days"(-50));
assert(interval2 == Interval!Date(Date(1995, 11, 13), Date(2012, 2, 15)));
--------------------
+/
void shift(D)(D duration) pure
if(__traits(compiles, begin + duration))
{
_enforceNotEmpty();
auto begin = _begin + duration;
auto end = _end + duration;
if(!_valid(begin, end))
throw new DateTimeException("Argument would result in an invalid Interval.");
_begin = begin;
_end = end;
}
static if(__traits(compiles, begin.add!"months"(1)) &&
__traits(compiles, begin.add!"years"(1)))
{
/++
Shifts the interval forward or backwards in time by the given number
of years and/or months (a positive number of years and months shifts
the interval forward; a negative number shifts it backward).
It adds the years the given years and months to both begin and end.
It effectively calls $(D add!"years"()) and then $(D add!"months"())
on begin and end with the given number of years and months.
Params:
years = The number of years to shift the interval by.
months = The number of months to shift the interval by.
allowOverflow = Whether the days should be allowed to overflow
on $(D begin) and $(D end), causing their month
to increment.
Throws:
$(D DateTimeException) if this interval is empty or if the
resulting interval would be invalid.
Examples:
--------------------
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
interval1.shift(2);
assert(interval1 == Interval!Date(Date(1998, 1, 2), Date(2014, 3, 1)));
interval2.shift(-2);
assert(interval2 == Interval!Date(Date(1994, 1, 2), Date(2010, 3, 1)));
--------------------
+/
void shift(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)
if(isIntegral!T)
{
_enforceNotEmpty();
auto begin = _begin;
auto end = _end;
begin.add!"years"(years, allowOverflow);
begin.add!"months"(months, allowOverflow);
end.add!"years"(years, allowOverflow);
end.add!"months"(months, allowOverflow);
enforce(_valid(begin, end), new DateTimeException("Argument would result in an invalid Interval."));
_begin = begin;
_end = end;
}
}
/++
Expands the interval forwards and/or backwards in time. Effectively,
it does $(D begin -= duration) and/or $(D end += duration). Whether
it expands forwards and/or backwards in time is determined by
$(D_PARAM dir).
Params:
duration = The duration to expand the interval by.
dir = The direction in time to expand the interval.
Throws:
$(D DateTimeException) this interval is empty or if the resulting
interval would be invalid.
Examples:
--------------------
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
interval1.expand(2);
assert(interval1 == Interval!Date(Date(1994, 1, 2), Date(2014, 3, 1)));
interval2.expand(-2);
assert(interval2 == Interval!Date(Date(1998, 1, 2), Date(2010, 3, 1)));
--------------------
+/
void expand(D)(D duration, Direction dir = Direction.both) pure
if(__traits(compiles, begin + duration))
{
_enforceNotEmpty();
switch(dir)
{
case Direction.both:
{
auto begin = _begin - duration;
auto end = _end + duration;
if(!_valid(begin, end))
throw new DateTimeException("Argument would result in an invalid Interval.");
_begin = begin;
_end = end;
return;
}
case Direction.fwd:
{
auto end = _end + duration;
if(!_valid(_begin, end))
throw new DateTimeException("Argument would result in an invalid Interval.");
_end = end;
return;
}
case Direction.bwd:
{
auto begin = _begin - duration;
if(!_valid(begin, _end))
throw new DateTimeException("Argument would result in an invalid Interval.");
_begin = begin;
return;
}
default:
assert(0, "Invalid Direction.");
}
}
static if(__traits(compiles, begin.add!"months"(1)) &&
__traits(compiles, begin.add!"years"(1)))
{
/++
Expands the interval forwards and/or backwards in time. Effectively,
it subtracts the given number of months/years from $(D begin) and
adds them to $(D end). Whether it expands forwards and/or backwards
in time is determined by $(D_PARAM dir).
Params:
years = The number of years to expand the interval by.
months = The number of months to expand the interval by.
allowOverflow = Whether the days should be allowed to overflow
on $(D begin) and $(D end), causing their month
to increment.
Throws:
$(D DateTimeException) if this interval is empty or if the
resulting interval would be invalid.
Examples:
--------------------
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
interval1.expand(2);
assert(interval1 == Interval!Date(Date(1994, 1, 2), Date(2014, 3, 1)));
interval2.expand(-2);
assert(interval2 == Interval!Date(Date(1998, 1, 2), Date(2010, 3, 1)));
--------------------
+/
void expand(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes, Direction dir = Direction.both)
if(isIntegral!T)
{
_enforceNotEmpty();
switch(dir)
{
case Direction.both:
{
auto begin = _begin;
auto end = _end;
begin.add!"years"(-years, allowOverflow);
begin.add!"months"(-months, allowOverflow);
end.add!"years"(years, allowOverflow);
end.add!"months"(months, allowOverflow);
enforce(_valid(begin, end), new DateTimeException("Argument would result in an invalid Interval."));
_begin = begin;
_end = end;
return;
}
case Direction.fwd:
{
auto end = _end;
end.add!"years"(years, allowOverflow);
end.add!"months"(months, allowOverflow);
enforce(_valid(_begin, end), new DateTimeException("Argument would result in an invalid Interval."));
_end = end;
return;
}
case Direction.bwd:
{
auto begin = _begin;
begin.add!"years"(-years, allowOverflow);
begin.add!"months"(-months, allowOverflow);
enforce(_valid(begin, _end), new DateTimeException("Argument would result in an invalid Interval."));
_begin = begin;
return;
}
default:
assert(0, "Invalid Direction.");
}
}
}
/++
Returns a range which iterates forward over the interval, starting
at $(D begin), using $(D_PARAM func) to generate each successive time
point.
The range's $(D front) is the interval's $(D begin). $(D_PARAM func) is
used to generate the next $(D front) when $(D popFront) is called. If
$(D_PARAM popFirst) is $(D PopFirst.yes), then $(D popFront) is called
before the range is returned (so that $(D front) is a time point which
$(D_PARAM func) would generate).
If $(D_PARAM func) ever generates a time point less than or equal to the
current $(D front) of the range, then a $(D DateTimeException) will be
thrown. The range will be empty and iteration complete when
$(D_PARAM func) generates a time point equal to or beyond the $(D end)
of the interval.
There are helper functions in this module which generate common
delegates to pass to $(D fwdRange). Their documentation starts with
"Range-generating function," so you can easily search for them.
Params:
func = The function used to generate the time points of the
range over the interval.
popFirst = Whether $(D popFront) should be called on the range
before returning it.
Throws:
$(D DateTimeException) if this interval is empty.
Warning:
$(D_PARAM func) must be logically pure. Ideally, $(D_PARAM func)
would be a function pointer to a pure function, but forcing
$(D_PARAM func) to be pure is far too restrictive to be useful, and
in order to have the ease of use of having functions which generate
functions to pass to $(D fwdRange), $(D_PARAM func) must be a
delegate.
If $(D_PARAM func) retains state which changes as it is called, then
some algorithms will not work correctly, because the range's
$(D save) will have failed to have really saved the range's state.
So, if you want to avoid such bugs, don't pass a delegate which is
not logically pure to $(D fwdRange). If $(D_PARAM func) is given the
same time point with two different calls, it must return the same
result both times.
Of course, none of the functions in this module have this problem,
so it's only relevant if you're creating your own delegate.
Examples:
--------------------
auto interval = Interval!Date(Date(2010, 9, 1), Date(2010, 9, 9));
auto func = (in Date date) //For iterating over even-numbered days.
{
if((date.day & 1) == 0)
return date + dur!"days"(2);
return date + dur!"days"(1);
};
auto range = interval.fwdRange(func);
//An odd day. Using PopFirst.yes would have made this Date(2010, 9, 2).
assert(range.front == Date(2010, 9, 1));
range.popFront();
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.front == Date(2010, 9, 4));
range.popFront();
assert(range.front == Date(2010, 9, 6));
range.popFront();
assert(range.front == Date(2010, 9, 8));
range.popFront();
assert(range.empty);
--------------------
+/
IntervalRange!(TP, Direction.fwd) fwdRange(TP delegate(in TP) func, PopFirst popFirst = PopFirst.no) const
{
_enforceNotEmpty();
auto range = IntervalRange!(TP, Direction.fwd)(this, func);
if(popFirst == PopFirst.yes)
range.popFront();
return range;
}
/++
Returns a range which iterates backwards over the interval, starting
at $(D end), using $(D_PARAM func) to generate each successive time
point.
The range's $(D front) is the interval's $(D end). $(D_PARAM func) is
used to generate the next $(D front) when $(D popFront) is called. If
$(D_PARAM popFirst) is $(D PopFirst.yes), then $(D popFront) is called
before the range is returned (so that $(D front) is a time point which
$(D_PARAM func) would generate).
If $(D_PARAM func) ever generates a time point greater than or equal to
the current $(D front) of the range, then a $(D DateTimeException) will
be thrown. The range will be empty and iteration complete when
$(D_PARAM func) generates a time point equal to or less than the
$(D begin) of the interval.
There are helper functions in this module which generate common
delegates to pass to $(D bwdRange). Their documentation starts with
"Range-generating function," so you can easily search for them.
Params:
func = The function used to generate the time points of the
range over the interval.
popFirst = Whether $(D popFront) should be called on the range
before returning it.
Throws:
$(D DateTimeException) if this interval is empty.
Warning:
$(D_PARAM func) must be logically pure. Ideally, $(D_PARAM func)
would be a function pointer to a pure function, but forcing
$(D_PARAM func) to be pure is far too restrictive to be useful, and
in order to have the ease of use of having functions which generate
functions to pass to $(D fwdRange), $(D_PARAM func) must be a
delegate.
If $(D_PARAM func) retains state which changes as it is called, then
some algorithms will not work correctly, because the range's
$(D save) will have failed to have really saved the range's state.
So, if you want to avoid such bugs, don't pass a delegate which is
not logically pure to $(D fwdRange). If $(D_PARAM func) is given the
same time point with two different calls, it must return the same
result both times.
Of course, none of the functions in this module have this problem,
so it's only relevant if you're creating your own delegate.
Examples:
--------------------
auto interval = Interval!Date(Date(2010, 9, 1), Date(2010, 9, 9));
auto func = (in Date date) //For iterating over even-numbered days.
{
if((date.day & 1) == 0)
return date - dur!"days"(2);
return date - dur!"days"(1);
};
auto range = interval.bwdRange(func);
//An odd day. Using PopFirst.yes would have made this Date(2010, 9, 8).
assert(range.front == Date(2010, 9, 9));
range.popFront();
assert(range.front == Date(2010, 9, 8));
range.popFront();
assert(range.front == Date(2010, 9, 6));
range.popFront();
assert(range.front == Date(2010, 9, 4));
range.popFront();
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.empty);
--------------------
+/
IntervalRange!(TP, Direction.bwd) bwdRange(TP delegate(in TP) func, PopFirst popFirst = PopFirst.no) const
{
_enforceNotEmpty();
auto range = IntervalRange!(TP, Direction.bwd)(this, func);
if(popFirst == PopFirst.yes)
range.popFront();
return range;
}
/+
Converts this interval to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString()
{
return _toStringImpl();
}
/++
Converts this interval to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString() const nothrow
{
return _toStringImpl();
}
private:
/+
Since we have two versions of toString, we have _toStringImpl
so that they can share implementations.
+/
string _toStringImpl() const nothrow
{
try
return format("[%s - %s)", _begin, _end);
catch(Exception e)
assert(0, "format() threw.");
}
/+
Throws:
$(D DateTimeException) if this interval is empty.
+/
void _enforceNotEmpty(size_t line = __LINE__) const pure
{
if(empty)
throw new DateTimeException("Invalid operation for an empty Interval.", __FILE__, line);
}
/+
Whether the given values form a valid time interval.
Params:
begin = The starting point of the interval.
end = The end point of the interval.
+/
static bool _valid(in TP begin, in TP end) pure nothrow
{
return begin <= end;
}
pure invariant()
{
assert(_valid(_begin, _end), "Invariant Failure: begin is not before or equal to end.");
}
TP _begin;
TP _end;
}
//Test Interval's constructors.
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(Interval!Date(Date(2010, 1, 1), Date(1, 1, 1)));
Interval!Date(Date.init, Date.init);
Interval!TimeOfDay(TimeOfDay.init, TimeOfDay.init);
Interval!DateTime(DateTime.init, DateTime.init);
Interval!SysTime(SysTime(0), SysTime(0));
Interval!DateTime(DateTime.init, dur!"days"(7));
//Verify Examples.
Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
assert(Interval!Date(Date(1996, 1, 2), dur!"weeks"(3)) == Interval!Date(Date(1996, 1, 2), Date(1996, 1, 23)));
assert(Interval!Date(Date(1996, 1, 2), dur!"days"(3)) == Interval!Date(Date(1996, 1, 2), Date(1996, 1, 5)));
assert(Interval!DateTime(DateTime(1996, 1, 2, 12, 0, 0), dur!"hours"(3)) == Interval!DateTime(DateTime(1996, 1, 2, 12, 0, 0), DateTime(1996, 1, 2, 15, 0, 0)));
assert(Interval!DateTime(DateTime(1996, 1, 2, 12, 0, 0), dur!"minutes"(3)) == Interval!DateTime(DateTime(1996, 1, 2, 12, 0, 0), DateTime(1996, 1, 2, 12, 3, 0)));
assert(Interval!DateTime(DateTime(1996, 1, 2, 12, 0, 0), dur!"seconds"(3)) == Interval!DateTime(DateTime(1996, 1, 2, 12, 0, 0), DateTime(1996, 1, 2, 12, 0, 3)));
assert(Interval!DateTime(DateTime(1996, 1, 2, 12, 0, 0), dur!"msecs"(3000)) == Interval!DateTime(DateTime(1996, 1, 2, 12, 0, 0), DateTime(1996, 1, 2, 12, 0, 3)));
}
}
//Test Interval's begin.
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(Interval!Date(Date(1, 1, 1), Date(2010, 1, 1)).begin, Date(1, 1, 1));
_assertPred!"=="(Interval!Date(Date(2010, 1, 1), Date(2010, 1, 1)).begin, Date(2010, 1, 1));
_assertPred!"=="(Interval!Date(Date(1997, 12, 31), Date(1998, 1, 1)).begin, Date(1997, 12, 31));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, cInterval.begin));
static assert(__traits(compiles, iInterval.begin));
//Verify Examples.
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).begin == Date(1996, 1, 2));
}
}
//Test Interval's end.
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(Interval!Date(Date(1, 1, 1), Date(2010, 1, 1)).end, Date(2010, 1, 1));
_assertPred!"=="(Interval!Date(Date(2010, 1, 1), Date(2010, 1, 1)).end, Date(2010, 1, 1));
_assertPred!"=="(Interval!Date(Date(1997, 12, 31), Date(1998, 1, 1)).end, Date(1998, 1, 1));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, cInterval.end));
static assert(__traits(compiles, iInterval.end));
//Verify Examples.
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).end == Date(2012, 3, 1));
}
}
//Test Interval's length.
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(Interval!Date(Date(2010, 1, 1), Date(2010, 1, 1)).length, dur!"days"(0));
_assertPred!"=="(Interval!Date(Date(2010, 1, 1), Date(2010, 4, 1)).length, dur!"days"(90));
_assertPred!"=="(Interval!TimeOfDay(TimeOfDay(0, 30, 0), TimeOfDay(12, 22, 7)).length, dur!"seconds"(42_727));
_assertPred!"=="(Interval!DateTime(DateTime(2010, 1, 1, 0, 30, 0), DateTime(2010, 1, 2, 12, 22, 7)).length, dur!"seconds"(129_127));
_assertPred!"=="(Interval!SysTime(SysTime(DateTime(2010, 1, 1, 0, 30, 0)), SysTime(DateTime(2010, 1, 2, 12, 22, 7))).length, dur!"seconds"(129_127));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, cInterval.length));
static assert(__traits(compiles, iInterval.length));
//Verify Examples.
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).length == dur!"days"(5903));
}
}
//Test Interval's empty.
unittest
{
version(testStdDateTime)
{
assert(Interval!Date(Date(2010, 1, 1), Date(2010, 1, 1)).empty);
assert(!Interval!Date(Date(2010, 1, 1), Date(2010, 4, 1)).empty);
assert(!Interval!TimeOfDay(TimeOfDay(0, 30, 0), TimeOfDay(12, 22, 7)).empty);
assert(!Interval!DateTime(DateTime(2010, 1, 1, 0, 30, 0), DateTime(2010, 1, 2, 12, 22, 7)).empty);
assert(!Interval!SysTime(SysTime(DateTime(2010, 1, 1, 0, 30, 0)), SysTime(DateTime(2010, 1, 2, 12, 22, 7))).empty);
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, cInterval.empty));
static assert(__traits(compiles, iInterval.empty));
//Verify Examples.
assert(Interval!Date(Date(1996, 1, 2), Date(1996, 1, 2)).empty);
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).empty);
}
}
//Test Interval's contains(time point).
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).contains(Date(2010, 7, 4)));
assert(!interval.contains(Date(2009, 7, 4)));
assert(!interval.contains(Date(2010, 7, 3)));
assert(interval.contains(Date(2010, 7, 4)));
assert(interval.contains(Date(2010, 7, 5)));
assert(interval.contains(Date(2011, 7, 1)));
assert(interval.contains(Date(2012, 1, 6)));
assert(!interval.contains(Date(2012, 1, 7)));
assert(!interval.contains(Date(2012, 1, 8)));
assert(!interval.contains(Date(2013, 1, 7)));
const cdate = Date(2010, 7, 6);
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, interval.contains(cdate)));
static assert(__traits(compiles, cInterval.contains(cdate)));
static assert(__traits(compiles, iInterval.contains(cdate)));
//Verify Examples.
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(Date(1994, 12, 24)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(Date(2000, 1, 5)));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(Date(2012, 3, 1)));
}
}
//Test Interval's contains(Interval).
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
assertThrown!DateTimeException(interval.contains(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).contains(interval));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).contains(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(interval.contains(interval));
assert(!interval.contains(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!interval.contains(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(!interval.contains(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!interval.contains(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!interval.contains(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!interval.contains(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(interval.contains(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(interval.contains(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(interval.contains(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!interval.contains(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(!interval.contains(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!interval.contains(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3)).contains(interval));
assert(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)).contains(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4)).contains(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5)).contains(interval));
assert(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)).contains(interval));
assert(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)).contains(interval));
assert(!Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)).contains(interval));
assert(!Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)).contains(interval));
assert(!Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)).contains(interval));
assert(!Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8)).contains(interval));
assert(!Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8)).contains(interval));
assert(!Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9)).contains(interval));
assert(!interval.contains(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!interval.contains(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!interval.contains(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!interval.contains(PosInfInterval!Date(Date(2012, 1, 6))));
assert(!interval.contains(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!interval.contains(PosInfInterval!Date(Date(2012, 1, 8))));
assert(!interval.contains(NegInfInterval!Date(Date(2010, 7, 3))));
assert(!interval.contains(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!interval.contains(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!interval.contains(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!interval.contains(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!interval.contains(NegInfInterval!Date(Date(2012, 1, 8))));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, interval.contains(interval)));
static assert(__traits(compiles, interval.contains(cInterval)));
static assert(__traits(compiles, interval.contains(iInterval)));
static assert(__traits(compiles, interval.contains(posInfInterval)));
static assert(__traits(compiles, interval.contains(cPosInfInterval)));
static assert(__traits(compiles, interval.contains(iPosInfInterval)));
static assert(__traits(compiles, interval.contains(negInfInterval)));
static assert(__traits(compiles, interval.contains(cNegInfInterval)));
static assert(__traits(compiles, interval.contains(iNegInfInterval)));
static assert(__traits(compiles, cInterval.contains(interval)));
static assert(__traits(compiles, cInterval.contains(cInterval)));
static assert(__traits(compiles, cInterval.contains(iInterval)));
static assert(__traits(compiles, cInterval.contains(posInfInterval)));
static assert(__traits(compiles, cInterval.contains(cPosInfInterval)));
static assert(__traits(compiles, cInterval.contains(iPosInfInterval)));
static assert(__traits(compiles, cInterval.contains(negInfInterval)));
static assert(__traits(compiles, cInterval.contains(cNegInfInterval)));
static assert(__traits(compiles, cInterval.contains(iNegInfInterval)));
static assert(__traits(compiles, iInterval.contains(interval)));
static assert(__traits(compiles, iInterval.contains(cInterval)));
static assert(__traits(compiles, iInterval.contains(iInterval)));
static assert(__traits(compiles, iInterval.contains(posInfInterval)));
static assert(__traits(compiles, iInterval.contains(cPosInfInterval)));
static assert(__traits(compiles, iInterval.contains(iPosInfInterval)));
static assert(__traits(compiles, iInterval.contains(negInfInterval)));
static assert(__traits(compiles, iInterval.contains(cNegInfInterval)));
static assert(__traits(compiles, iInterval.contains(iNegInfInterval)));
//Verify Examples.
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(Interval!Date(Date(1998, 2, 28), Date(2013, 5, 1))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(PosInfInterval!Date(Date(1999, 5, 4))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).contains(NegInfInterval!Date(Date(1996, 5, 4))));
}
}
//Test Interval's isBefore(time point).
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).isBefore(Date(2010, 7, 4)));
assert(!interval.isBefore(Date(2009, 7, 3)));
assert(!interval.isBefore(Date(2010, 7, 3)));
assert(!interval.isBefore(Date(2010, 7, 4)));
assert(!interval.isBefore(Date(2010, 7, 5)));
assert(!interval.isBefore(Date(2011, 7, 1)));
assert(!interval.isBefore(Date(2012, 1, 6)));
assert(interval.isBefore(Date(2012, 1, 7)));
assert(interval.isBefore(Date(2012, 1, 8)));
assert(interval.isBefore(Date(2013, 1, 7)));
const cdate = Date(2010, 7, 6);
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, interval.isBefore(cdate)));
static assert(__traits(compiles, cInterval.isBefore(cdate)));
static assert(__traits(compiles, iInterval.isBefore(cdate)));
//Verify Examples.
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(Date(1994, 12, 24)));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(Date(2000, 1, 5)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(Date(2012, 3, 1)));
}
}
//Test Interval's isBefore(Interval).
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
assertThrown!DateTimeException(interval.isBefore(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).isBefore(interval));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).isBefore(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(!interval.isBefore(interval));
assert(!interval.isBefore(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!interval.isBefore(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(!interval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!interval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!interval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!interval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(!interval.isBefore(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(!interval.isBefore(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(!interval.isBefore(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!interval.isBefore(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(interval.isBefore(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(interval.isBefore(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3)).isBefore(interval));
assert(!Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)).isBefore(interval));
assert(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4)).isBefore(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5)).isBefore(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)).isBefore(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)).isBefore(interval));
assert(!Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)).isBefore(interval));
assert(!Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)).isBefore(interval));
assert(!Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)).isBefore(interval));
assert(!Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8)).isBefore(interval));
assert(!Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8)).isBefore(interval));
assert(!Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9)).isBefore(interval));
assert(!interval.isBefore(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!interval.isBefore(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!interval.isBefore(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!interval.isBefore(PosInfInterval!Date(Date(2012, 1, 6))));
assert(interval.isBefore(PosInfInterval!Date(Date(2012, 1, 7))));
assert(interval.isBefore(PosInfInterval!Date(Date(2012, 1, 8))));
assert(!interval.isBefore(NegInfInterval!Date(Date(2010, 7, 3))));
assert(!interval.isBefore(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!interval.isBefore(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!interval.isBefore(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!interval.isBefore(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!interval.isBefore(NegInfInterval!Date(Date(2012, 1, 8))));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, interval.isBefore(interval)));
static assert(__traits(compiles, interval.isBefore(cInterval)));
static assert(__traits(compiles, interval.isBefore(iInterval)));
static assert(__traits(compiles, interval.isBefore(posInfInterval)));
static assert(__traits(compiles, interval.isBefore(cPosInfInterval)));
static assert(__traits(compiles, interval.isBefore(iPosInfInterval)));
static assert(__traits(compiles, interval.isBefore(negInfInterval)));
static assert(__traits(compiles, interval.isBefore(cNegInfInterval)));
static assert(__traits(compiles, interval.isBefore(iNegInfInterval)));
static assert(__traits(compiles, cInterval.isBefore(interval)));
static assert(__traits(compiles, cInterval.isBefore(cInterval)));
static assert(__traits(compiles, cInterval.isBefore(iInterval)));
static assert(__traits(compiles, cInterval.isBefore(posInfInterval)));
static assert(__traits(compiles, cInterval.isBefore(cPosInfInterval)));
static assert(__traits(compiles, cInterval.isBefore(iPosInfInterval)));
static assert(__traits(compiles, cInterval.isBefore(negInfInterval)));
static assert(__traits(compiles, cInterval.isBefore(cNegInfInterval)));
static assert(__traits(compiles, cInterval.isBefore(iNegInfInterval)));
static assert(__traits(compiles, iInterval.isBefore(interval)));
static assert(__traits(compiles, iInterval.isBefore(cInterval)));
static assert(__traits(compiles, iInterval.isBefore(iInterval)));
static assert(__traits(compiles, iInterval.isBefore(posInfInterval)));
static assert(__traits(compiles, iInterval.isBefore(cPosInfInterval)));
static assert(__traits(compiles, iInterval.isBefore(iPosInfInterval)));
static assert(__traits(compiles, iInterval.isBefore(negInfInterval)));
static assert(__traits(compiles, iInterval.isBefore(cNegInfInterval)));
static assert(__traits(compiles, iInterval.isBefore(iNegInfInterval)));
//Verify Examples.
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(Interval!Date(Date(2012, 3, 1), Date(2013, 5, 1))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(PosInfInterval!Date(Date(1999, 5, 4))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(PosInfInterval!Date(Date(2013, 3, 7))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isBefore(NegInfInterval!Date(Date(1996, 5, 4))));
}
}
//Test Interval's isAfter(time point).
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).isAfter(Date(2010, 7, 4)));
assert(interval.isAfter(Date(2009, 7, 4)));
assert(interval.isAfter(Date(2010, 7, 3)));
assert(!interval.isAfter(Date(2010, 7, 4)));
assert(!interval.isAfter(Date(2010, 7, 5)));
assert(!interval.isAfter(Date(2011, 7, 1)));
assert(!interval.isAfter(Date(2012, 1, 6)));
assert(!interval.isAfter(Date(2012, 1, 7)));
assert(!interval.isAfter(Date(2012, 1, 8)));
assert(!interval.isAfter(Date(2013, 1, 7)));
const cdate = Date(2010, 7, 6);
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, interval.isAfter(cdate)));
static assert(__traits(compiles, cInterval.isAfter(cdate)));
static assert(__traits(compiles, iInterval.isAfter(cdate)));
//Verify Examples.
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(Date(1994, 12, 24)));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(Date(2000, 1, 5)));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(Date(2012, 3, 1)));
}
}
//Test Interval's isAfter(Interval).
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
assertThrown!DateTimeException(interval.isAfter(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).isAfter(interval));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).isAfter(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(!interval.isAfter(interval));
assert(interval.isAfter(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!interval.isAfter(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(interval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!interval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!interval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!interval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(!interval.isAfter(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(!interval.isAfter(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(!interval.isAfter(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!interval.isAfter(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(!interval.isAfter(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!interval.isAfter(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3)).isAfter(interval));
assert(!Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)).isAfter(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4)).isAfter(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5)).isAfter(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)).isAfter(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)).isAfter(interval));
assert(!Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)).isAfter(interval));
assert(!Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)).isAfter(interval));
assert(!Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)).isAfter(interval));
assert(!Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8)).isAfter(interval));
assert(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8)).isAfter(interval));
assert(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9)).isAfter(interval));
assert(!interval.isAfter(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!interval.isAfter(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!interval.isAfter(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!interval.isAfter(PosInfInterval!Date(Date(2012, 1, 6))));
assert(!interval.isAfter(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!interval.isAfter(PosInfInterval!Date(Date(2012, 1, 8))));
assert(interval.isAfter(NegInfInterval!Date(Date(2010, 7, 3))));
assert(interval.isAfter(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!interval.isAfter(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!interval.isAfter(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!interval.isAfter(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!interval.isAfter(NegInfInterval!Date(Date(2012, 1, 8))));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, interval.isAfter(interval)));
static assert(__traits(compiles, interval.isAfter(cInterval)));
static assert(__traits(compiles, interval.isAfter(iInterval)));
static assert(__traits(compiles, interval.isAfter(posInfInterval)));
static assert(__traits(compiles, interval.isAfter(cPosInfInterval)));
static assert(__traits(compiles, interval.isAfter(iPosInfInterval)));
static assert(__traits(compiles, interval.isAfter(negInfInterval)));
static assert(__traits(compiles, interval.isAfter(cNegInfInterval)));
static assert(__traits(compiles, interval.isAfter(iNegInfInterval)));
static assert(__traits(compiles, cInterval.isAfter(interval)));
static assert(__traits(compiles, cInterval.isAfter(cInterval)));
static assert(__traits(compiles, cInterval.isAfter(iInterval)));
static assert(__traits(compiles, cInterval.isAfter(posInfInterval)));
static assert(__traits(compiles, cInterval.isAfter(cPosInfInterval)));
static assert(__traits(compiles, cInterval.isAfter(iPosInfInterval)));
static assert(__traits(compiles, cInterval.isAfter(negInfInterval)));
static assert(__traits(compiles, cInterval.isAfter(cNegInfInterval)));
static assert(__traits(compiles, cInterval.isAfter(iNegInfInterval)));
static assert(__traits(compiles, iInterval.isAfter(interval)));
static assert(__traits(compiles, iInterval.isAfter(cInterval)));
static assert(__traits(compiles, iInterval.isAfter(iInterval)));
static assert(__traits(compiles, iInterval.isAfter(posInfInterval)));
static assert(__traits(compiles, iInterval.isAfter(cPosInfInterval)));
static assert(__traits(compiles, iInterval.isAfter(iPosInfInterval)));
static assert(__traits(compiles, iInterval.isAfter(negInfInterval)));
static assert(__traits(compiles, iInterval.isAfter(cNegInfInterval)));
static assert(__traits(compiles, iInterval.isAfter(iNegInfInterval)));
//Verify Examples.
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(PosInfInterval!Date(Date(1999, 5, 4))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAfter(NegInfInterval!Date(Date(1996, 1, 2))));
}
}
//Test Interval's intersects().
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
assertThrown!DateTimeException(interval.intersects(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).intersects(interval));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).intersects(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(interval.intersects(interval));
assert(!interval.intersects(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(interval.intersects(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(!interval.intersects(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(interval.intersects(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(interval.intersects(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(interval.intersects(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(interval.intersects(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(interval.intersects(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(interval.intersects(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(interval.intersects(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(!interval.intersects(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!interval.intersects(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3)).intersects(interval));
assert(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)).intersects(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4)).intersects(interval));
assert(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5)).intersects(interval));
assert(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)).intersects(interval));
assert(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)).intersects(interval));
assert(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)).intersects(interval));
assert(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)).intersects(interval));
assert(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)).intersects(interval));
assert(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8)).intersects(interval));
assert(!Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8)).intersects(interval));
assert(!Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9)).intersects(interval));
assert(interval.intersects(PosInfInterval!Date(Date(2010, 7, 3))));
assert(interval.intersects(PosInfInterval!Date(Date(2010, 7, 4))));
assert(interval.intersects(PosInfInterval!Date(Date(2010, 7, 5))));
assert(interval.intersects(PosInfInterval!Date(Date(2012, 1, 6))));
assert(!interval.intersects(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!interval.intersects(PosInfInterval!Date(Date(2012, 1, 8))));
assert(!interval.intersects(NegInfInterval!Date(Date(2010, 7, 3))));
assert(!interval.intersects(NegInfInterval!Date(Date(2010, 7, 4))));
assert(interval.intersects(NegInfInterval!Date(Date(2010, 7, 5))));
assert(interval.intersects(NegInfInterval!Date(Date(2012, 1, 6))));
assert(interval.intersects(NegInfInterval!Date(Date(2012, 1, 7))));
assert(interval.intersects(NegInfInterval!Date(Date(2012, 1, 8))));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, interval.intersects(interval)));
static assert(__traits(compiles, interval.intersects(cInterval)));
static assert(__traits(compiles, interval.intersects(iInterval)));
static assert(__traits(compiles, interval.intersects(posInfInterval)));
static assert(__traits(compiles, interval.intersects(cPosInfInterval)));
static assert(__traits(compiles, interval.intersects(iPosInfInterval)));
static assert(__traits(compiles, interval.intersects(negInfInterval)));
static assert(__traits(compiles, interval.intersects(cNegInfInterval)));
static assert(__traits(compiles, interval.intersects(iNegInfInterval)));
static assert(__traits(compiles, cInterval.intersects(interval)));
static assert(__traits(compiles, cInterval.intersects(cInterval)));
static assert(__traits(compiles, cInterval.intersects(iInterval)));
static assert(__traits(compiles, cInterval.intersects(posInfInterval)));
static assert(__traits(compiles, cInterval.intersects(cPosInfInterval)));
static assert(__traits(compiles, cInterval.intersects(iPosInfInterval)));
static assert(__traits(compiles, cInterval.intersects(negInfInterval)));
static assert(__traits(compiles, cInterval.intersects(cNegInfInterval)));
static assert(__traits(compiles, cInterval.intersects(iNegInfInterval)));
static assert(__traits(compiles, iInterval.intersects(interval)));
static assert(__traits(compiles, iInterval.intersects(cInterval)));
static assert(__traits(compiles, iInterval.intersects(iInterval)));
static assert(__traits(compiles, iInterval.intersects(posInfInterval)));
static assert(__traits(compiles, iInterval.intersects(cPosInfInterval)));
static assert(__traits(compiles, iInterval.intersects(iPosInfInterval)));
static assert(__traits(compiles, iInterval.intersects(negInfInterval)));
static assert(__traits(compiles, iInterval.intersects(cNegInfInterval)));
static assert(__traits(compiles, iInterval.intersects(iNegInfInterval)));
//Verify Examples.
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(PosInfInterval!Date(Date(1999, 5, 4))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(PosInfInterval!Date(Date(2012, 3, 1))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(NegInfInterval!Date(Date(1996, 1, 2))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersects(NegInfInterval!Date(Date(2000, 1, 2))));
}
}
//Test Interval's intersection().
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
assertThrown!DateTimeException(interval.intersection(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).intersection(interval));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 4), dur!"days"(0)).intersection(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(interval.intersection(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assertThrown!DateTimeException(interval.intersection(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assertThrown!DateTimeException(interval.intersection(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assertThrown!DateTimeException(interval.intersection(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3)).intersection(interval));
assertThrown!DateTimeException(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4)).intersection(interval));
assertThrown!DateTimeException(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8)).intersection(interval));
assertThrown!DateTimeException(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9)).intersection(interval));
assertThrown!DateTimeException(interval.intersection(PosInfInterval!Date(Date(2012, 1, 7))));
assertThrown!DateTimeException(interval.intersection(PosInfInterval!Date(Date(2012, 1, 8))));
assertThrown!DateTimeException(interval.intersection(NegInfInterval!Date(Date(2010, 7, 3))));
assertThrown!DateTimeException(interval.intersection(NegInfInterval!Date(Date(2010, 7, 4))));
_assertPred!"=="(interval.intersection(interval), interval);
_assertPred!"=="(interval.intersection(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))),
Interval!Date(Date(2010, 7, 4), Date(2010, 7, 5)));
_assertPred!"=="(interval.intersection(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))),
Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)));
_assertPred!"=="(interval.intersection(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))),
Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))),
Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)).intersection(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5)).intersection(interval),
Interval!Date(Date(2010, 7, 4), Date(2010, 7, 5)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)).intersection(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)).intersection(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)).intersection(interval),
Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)).intersection(interval),
Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)).intersection(interval),
Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8)).intersection(interval),
Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(PosInfInterval!Date(Date(2010, 7, 3))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(PosInfInterval!Date(Date(2010, 7, 4))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(PosInfInterval!Date(Date(2010, 7, 5))),
Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(PosInfInterval!Date(Date(2012, 1, 6))),
Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(NegInfInterval!Date(Date(2010, 7, 5))),
Interval!Date(Date(2010, 7, 4), Date(2010, 7, 5)));
_assertPred!"=="(interval.intersection(NegInfInterval!Date(Date(2012, 1, 6))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 6)));
_assertPred!"=="(interval.intersection(NegInfInterval!Date(Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.intersection(NegInfInterval!Date(Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, interval.intersection(interval)));
static assert(__traits(compiles, interval.intersection(cInterval)));
static assert(__traits(compiles, interval.intersection(iInterval)));
static assert(__traits(compiles, interval.intersection(posInfInterval)));
static assert(__traits(compiles, interval.intersection(cPosInfInterval)));
static assert(__traits(compiles, interval.intersection(iPosInfInterval)));
static assert(__traits(compiles, interval.intersection(negInfInterval)));
static assert(__traits(compiles, interval.intersection(cNegInfInterval)));
static assert(__traits(compiles, interval.intersection(iNegInfInterval)));
static assert(__traits(compiles, cInterval.intersection(interval)));
static assert(__traits(compiles, cInterval.intersection(cInterval)));
static assert(__traits(compiles, cInterval.intersection(iInterval)));
static assert(__traits(compiles, cInterval.intersection(posInfInterval)));
static assert(__traits(compiles, cInterval.intersection(cPosInfInterval)));
static assert(__traits(compiles, cInterval.intersection(iPosInfInterval)));
static assert(__traits(compiles, cInterval.intersection(negInfInterval)));
static assert(__traits(compiles, cInterval.intersection(cNegInfInterval)));
static assert(__traits(compiles, cInterval.intersection(iNegInfInterval)));
static assert(__traits(compiles, iInterval.intersection(interval)));
static assert(__traits(compiles, iInterval.intersection(cInterval)));
static assert(__traits(compiles, iInterval.intersection(iInterval)));
static assert(__traits(compiles, iInterval.intersection(posInfInterval)));
static assert(__traits(compiles, iInterval.intersection(cPosInfInterval)));
static assert(__traits(compiles, iInterval.intersection(iPosInfInterval)));
static assert(__traits(compiles, iInterval.intersection(negInfInterval)));
static assert(__traits(compiles, iInterval.intersection(cNegInfInterval)));
static assert(__traits(compiles, iInterval.intersection(iNegInfInterval)));
//Verify Examples.
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) == Interval!Date(Date(1996, 1 , 2), Date(2000, 8, 2)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) == Interval!Date(Date(1999, 1 , 12), Date(2011, 9, 17)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(PosInfInterval!Date(Date(1990, 7, 6))) == Interval!Date(Date(1996, 1 , 2), Date(2012, 3, 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(PosInfInterval!Date(Date(1999, 1, 12))) == Interval!Date(Date(1999, 1 , 12), Date(2012, 3, 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(NegInfInterval!Date(Date(1999, 7, 6))) == Interval!Date(Date(1996, 1 , 2), Date(1999, 7, 6)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).intersection(NegInfInterval!Date(Date(2013, 1, 12))) == Interval!Date(Date(1996, 1 , 2), Date(2012, 3, 1)));
}
}
//Test Interval's isAdjacent().
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static void testInterval(in Interval!Date interval1, in Interval!Date interval2)
{
interval1.isAdjacent(interval2);
}
assertThrown!DateTimeException(testInterval(interval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(testInterval(Interval!Date(Date(2010, 7, 4), dur!"days"(0)), interval));
assertThrown!DateTimeException(testInterval(Interval!Date(Date(2010, 7, 4), dur!"days"(0)), Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(!interval.isAdjacent(interval));
assert(!interval.isAdjacent(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!interval.isAdjacent(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(interval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!interval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!interval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!interval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(!interval.isAdjacent(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(!interval.isAdjacent(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(!interval.isAdjacent(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!interval.isAdjacent(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(interval.isAdjacent(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!interval.isAdjacent(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3)).isAdjacent(interval));
assert(!Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)).isAdjacent(interval));
assert(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4)).isAdjacent(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5)).isAdjacent(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)).isAdjacent(interval));
assert(!Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)).isAdjacent(interval));
assert(!Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)).isAdjacent(interval));
assert(!Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)).isAdjacent(interval));
assert(!Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)).isAdjacent(interval));
assert(!Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8)).isAdjacent(interval));
assert(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8)).isAdjacent(interval));
assert(!Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9)).isAdjacent(interval));
assert(!interval.isAdjacent(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!interval.isAdjacent(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!interval.isAdjacent(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!interval.isAdjacent(PosInfInterval!Date(Date(2012, 1, 6))));
assert(interval.isAdjacent(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!interval.isAdjacent(PosInfInterval!Date(Date(2012, 1, 8))));
assert(!interval.isAdjacent(NegInfInterval!Date(Date(2010, 7, 3))));
assert(interval.isAdjacent(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!interval.isAdjacent(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!interval.isAdjacent(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!interval.isAdjacent(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!interval.isAdjacent(NegInfInterval!Date(Date(2012, 1, 8))));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, interval.isAdjacent(interval)));
static assert(__traits(compiles, interval.isAdjacent(cInterval)));
static assert(__traits(compiles, interval.isAdjacent(iInterval)));
static assert(__traits(compiles, interval.isAdjacent(posInfInterval)));
static assert(__traits(compiles, interval.isAdjacent(cPosInfInterval)));
static assert(__traits(compiles, interval.isAdjacent(iPosInfInterval)));
static assert(__traits(compiles, interval.isAdjacent(negInfInterval)));
static assert(__traits(compiles, interval.isAdjacent(cNegInfInterval)));
static assert(__traits(compiles, interval.isAdjacent(iNegInfInterval)));
static assert(__traits(compiles, cInterval.isAdjacent(interval)));
static assert(__traits(compiles, cInterval.isAdjacent(cInterval)));
static assert(__traits(compiles, cInterval.isAdjacent(iInterval)));
static assert(__traits(compiles, cInterval.isAdjacent(posInfInterval)));
static assert(__traits(compiles, cInterval.isAdjacent(cPosInfInterval)));
static assert(__traits(compiles, cInterval.isAdjacent(iPosInfInterval)));
static assert(__traits(compiles, cInterval.isAdjacent(negInfInterval)));
static assert(__traits(compiles, cInterval.isAdjacent(cNegInfInterval)));
static assert(__traits(compiles, cInterval.isAdjacent(iNegInfInterval)));
static assert(__traits(compiles, iInterval.isAdjacent(interval)));
static assert(__traits(compiles, iInterval.isAdjacent(cInterval)));
static assert(__traits(compiles, iInterval.isAdjacent(iInterval)));
static assert(__traits(compiles, iInterval.isAdjacent(posInfInterval)));
static assert(__traits(compiles, iInterval.isAdjacent(cPosInfInterval)));
static assert(__traits(compiles, iInterval.isAdjacent(iPosInfInterval)));
static assert(__traits(compiles, iInterval.isAdjacent(negInfInterval)));
static assert(__traits(compiles, iInterval.isAdjacent(cNegInfInterval)));
static assert(__traits(compiles, iInterval.isAdjacent(iNegInfInterval)));
//Verify Examples.
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(Interval!Date(Date(1990, 7, 6), Date(1996, 1, 2))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(Interval!Date(Date(2012, 3, 1), Date(2013, 9, 17))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(Interval!Date(Date(1989, 3, 1), Date(2012, 3, 1))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(PosInfInterval!Date(Date(1999, 5, 4))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(PosInfInterval!Date(Date(2012, 3, 1))));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(NegInfInterval!Date(Date(1996, 1, 2))));
assert(!Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).isAdjacent(NegInfInterval!Date(Date(2000, 1, 2))));
}
}
//Test Interval's merge().
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static void testInterval(I)(in Interval!Date interval1, in I interval2)
{
interval1.merge(interval2);
}
assertThrown!DateTimeException(testInterval(interval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(testInterval(Interval!Date(Date(2010, 7, 4), dur!"days"(0)), interval));
assertThrown!DateTimeException(testInterval(Interval!Date(Date(2010, 7, 4), dur!"days"(0)), Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(testInterval(interval, Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assertThrown!DateTimeException(testInterval(interval, Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assertThrown!DateTimeException(testInterval(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3)), interval));
assertThrown!DateTimeException(testInterval(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9)), interval));
assertThrown!DateTimeException(testInterval(interval, PosInfInterval!Date(Date(2012, 1, 8))));
assertThrown!DateTimeException(testInterval(interval, NegInfInterval!Date(Date(2010, 7, 3))));
_assertPred!"=="(interval.merge(interval), interval);
_assertPred!"=="(interval.merge(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))),
Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)));
_assertPred!"=="(interval.merge(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(interval.merge(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(interval.merge(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(interval.merge(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)));
_assertPred!"=="(interval.merge(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.merge(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.merge(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.merge(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 8)));
_assertPred!"=="(interval.merge(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 8)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)).merge(interval),
Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4)).merge(interval),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5)).merge(interval),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)).merge(interval),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)).merge(interval),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)).merge(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)).merge(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)).merge(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8)).merge(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 8)));
_assertPred!"=="(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8)).merge(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 8)));
_assertPred!"=="(interval.merge(PosInfInterval!Date(Date(2010, 7, 3))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(interval.merge(PosInfInterval!Date(Date(2010, 7, 4))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(interval.merge(PosInfInterval!Date(Date(2010, 7, 5))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(interval.merge(PosInfInterval!Date(Date(2012, 1, 6))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(interval.merge(PosInfInterval!Date(Date(2012, 1, 7))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(interval.merge(NegInfInterval!Date(Date(2010, 7, 4))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(interval.merge(NegInfInterval!Date(Date(2010, 7, 5))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(interval.merge(NegInfInterval!Date(Date(2012, 1, 6))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(interval.merge(NegInfInterval!Date(Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(interval.merge(NegInfInterval!Date(Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 8)));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, interval.merge(interval)));
static assert(__traits(compiles, interval.merge(cInterval)));
static assert(__traits(compiles, interval.merge(iInterval)));
static assert(__traits(compiles, interval.merge(posInfInterval)));
static assert(__traits(compiles, interval.merge(cPosInfInterval)));
static assert(__traits(compiles, interval.merge(iPosInfInterval)));
static assert(__traits(compiles, interval.merge(negInfInterval)));
static assert(__traits(compiles, interval.merge(cNegInfInterval)));
static assert(__traits(compiles, interval.merge(iNegInfInterval)));
static assert(__traits(compiles, cInterval.merge(interval)));
static assert(__traits(compiles, cInterval.merge(cInterval)));
static assert(__traits(compiles, cInterval.merge(iInterval)));
static assert(__traits(compiles, cInterval.merge(posInfInterval)));
static assert(__traits(compiles, cInterval.merge(cPosInfInterval)));
static assert(__traits(compiles, cInterval.merge(iPosInfInterval)));
static assert(__traits(compiles, cInterval.merge(negInfInterval)));
static assert(__traits(compiles, cInterval.merge(cNegInfInterval)));
static assert(__traits(compiles, cInterval.merge(iNegInfInterval)));
static assert(__traits(compiles, iInterval.merge(interval)));
static assert(__traits(compiles, iInterval.merge(cInterval)));
static assert(__traits(compiles, iInterval.merge(iInterval)));
static assert(__traits(compiles, iInterval.merge(posInfInterval)));
static assert(__traits(compiles, iInterval.merge(cPosInfInterval)));
static assert(__traits(compiles, iInterval.merge(iPosInfInterval)));
static assert(__traits(compiles, iInterval.merge(negInfInterval)));
static assert(__traits(compiles, iInterval.merge(cNegInfInterval)));
static assert(__traits(compiles, iInterval.merge(iNegInfInterval)));
//Verify Examples.
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) == Interval!Date(Date(1990, 7 , 6), Date(2012, 3, 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(Interval!Date(Date(2012, 3, 1), Date(2013, 5, 7))) == Interval!Date(Date(1996, 1 , 2), Date(2013, 5, 7)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(PosInfInterval!Date(Date(1990, 7, 6))) == PosInfInterval!Date(Date(1990, 7 , 6)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(PosInfInterval!Date(Date(2012, 3, 1))) == PosInfInterval!Date(Date(1996, 1 , 2)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(NegInfInterval!Date(Date(1996, 1, 2))) == NegInfInterval!Date(Date(2012, 3 , 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).merge(NegInfInterval!Date(Date(2013, 1, 12))) == NegInfInterval!Date(Date(2013, 1 , 12)));
}
}
//Test Interval's span().
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static void testInterval(in Interval!Date interval1, in Interval!Date interval2)
{
interval1.span(interval2);
}
assertThrown!DateTimeException(testInterval(interval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(testInterval(Interval!Date(Date(2010, 7, 4), dur!"days"(0)), interval));
assertThrown!DateTimeException(testInterval(Interval!Date(Date(2010, 7, 4), dur!"days"(0)), Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
_assertPred!"=="(interval.span(interval), interval);
_assertPred!"=="(interval.span(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))),
Interval!Date(Date(2010, 7, 1), Date(2012, 1, 7)));
_assertPred!"=="(interval.span(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))),
Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)));
_assertPred!"=="(interval.span(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(interval.span(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(interval.span(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(interval.span(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)));
_assertPred!"=="(interval.span(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.span(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.span(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(interval.span(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 8)));
_assertPred!"=="(interval.span(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 8)));
_assertPred!"=="(interval.span(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 9)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3)).span(interval),
Interval!Date(Date(2010, 7, 1), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)).span(interval),
Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4)).span(interval),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5)).span(interval),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)).span(interval),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)).span(interval),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)).span(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)).span(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)).span(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8)).span(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 8)));
_assertPred!"=="(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8)).span(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 8)));
_assertPred!"=="(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9)).span(interval),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 9)));
_assertPred!"=="(interval.span(PosInfInterval!Date(Date(2010, 7, 3))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(interval.span(PosInfInterval!Date(Date(2010, 7, 4))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(interval.span(PosInfInterval!Date(Date(2010, 7, 5))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(interval.span(PosInfInterval!Date(Date(2012, 1, 6))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(interval.span(PosInfInterval!Date(Date(2012, 1, 7))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(interval.span(PosInfInterval!Date(Date(2012, 1, 8))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(interval.span(NegInfInterval!Date(Date(2010, 7, 3))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(interval.span(NegInfInterval!Date(Date(2010, 7, 4))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(interval.span(NegInfInterval!Date(Date(2010, 7, 5))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(interval.span(NegInfInterval!Date(Date(2012, 1, 6))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(interval.span(NegInfInterval!Date(Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(interval.span(NegInfInterval!Date(Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 8)));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, interval.span(interval)));
static assert(__traits(compiles, interval.span(cInterval)));
static assert(__traits(compiles, interval.span(iInterval)));
static assert(__traits(compiles, interval.span(posInfInterval)));
static assert(__traits(compiles, interval.span(cPosInfInterval)));
static assert(__traits(compiles, interval.span(iPosInfInterval)));
static assert(__traits(compiles, interval.span(negInfInterval)));
static assert(__traits(compiles, interval.span(cNegInfInterval)));
static assert(__traits(compiles, interval.span(iNegInfInterval)));
static assert(__traits(compiles, cInterval.span(interval)));
static assert(__traits(compiles, cInterval.span(cInterval)));
static assert(__traits(compiles, cInterval.span(iInterval)));
static assert(__traits(compiles, cInterval.span(posInfInterval)));
static assert(__traits(compiles, cInterval.span(cPosInfInterval)));
static assert(__traits(compiles, cInterval.span(iPosInfInterval)));
static assert(__traits(compiles, cInterval.span(negInfInterval)));
static assert(__traits(compiles, cInterval.span(cNegInfInterval)));
static assert(__traits(compiles, cInterval.span(iNegInfInterval)));
static assert(__traits(compiles, iInterval.span(interval)));
static assert(__traits(compiles, iInterval.span(cInterval)));
static assert(__traits(compiles, iInterval.span(iInterval)));
static assert(__traits(compiles, iInterval.span(posInfInterval)));
static assert(__traits(compiles, iInterval.span(cPosInfInterval)));
static assert(__traits(compiles, iInterval.span(iPosInfInterval)));
static assert(__traits(compiles, iInterval.span(negInfInterval)));
static assert(__traits(compiles, iInterval.span(cNegInfInterval)));
static assert(__traits(compiles, iInterval.span(iNegInfInterval)));
//Verify Examples.
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(Interval!Date(Date(1990, 7, 6), Date(1991, 1, 8))) == Interval!Date(Date(1990, 7 , 6), Date(2012, 3, 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(Interval!Date(Date(2012, 3, 1), Date(2013, 5, 7))) == Interval!Date(Date(1996, 1 , 2), Date(2013, 5, 7)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(PosInfInterval!Date(Date(1990, 7, 6))) == PosInfInterval!Date(Date(1990, 7 , 6)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(PosInfInterval!Date(Date(2050, 1, 1))) == PosInfInterval!Date(Date(1996, 1 , 2)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(NegInfInterval!Date(Date(1602, 5, 21))) == NegInfInterval!Date(Date(2012, 3 , 1)));
assert(Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1)).span(NegInfInterval!Date(Date(2013, 1, 12))) == NegInfInterval!Date(Date(2013, 1 , 12)));
}
}
//Test Interval's shift(duration).
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static void testIntervalFail(Interval!Date interval, in Duration duration)
{
interval.shift(duration);
}
assertThrown!DateTimeException(testIntervalFail(Interval!Date(Date(2010, 7, 4), dur!"days"(0)), dur!"days"(1)));
static void testInterval(I)(I interval, in Duration duration, in I expected, size_t line = __LINE__)
{
interval.shift(duration);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, dur!"days"(22), Interval!Date(Date(2010, 7, 26), Date(2012, 1, 29)));
testInterval(interval, dur!"days"(-22), Interval!Date(Date(2010, 6, 12), Date(2011, 12, 16)));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(!__traits(compiles, cInterval.shift(dur!"days"(5))));
static assert(!__traits(compiles, iInterval.shift(dur!"days"(5))));
//Verify Examples.
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 4, 5));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 4, 5));
interval1.shift(dur!"days"(50));
assert(interval1 == Interval!Date(Date(1996, 2, 21), Date(2012, 5, 25)));
interval2.shift(dur!"days"(-50));
assert(interval2 == Interval!Date(Date(1995, 11, 13), Date(2012, 2, 15)));
}
}
//Test Interval's shift(int, int, AllowDayOverflow).
unittest
{
version(testStdDateTime)
{
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static void testIntervalFail(Interval!Date interval, int years, int months)
{
interval.shift(years, months);
}
assertThrown!DateTimeException(testIntervalFail(Interval!Date(Date(2010, 7, 4), dur!"days"(0)), 1, 0));
static void testInterval(I)(I interval, int years, int months, AllowDayOverflow allow, in I expected, size_t line = __LINE__)
{
interval.shift(years, months, allow);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, 5, 0, AllowDayOverflow.yes, Interval!Date(Date(2015, 7, 4), Date(2017, 1, 7)));
testInterval(interval, -5, 0, AllowDayOverflow.yes, Interval!Date(Date(2005, 7, 4), Date(2007, 1, 7)));
auto interval2 = Interval!Date(Date(2000, 1, 29), Date(2010, 5, 31));
testInterval(interval2, 1, 1, AllowDayOverflow.yes, Interval!Date(Date(2001, 3, 1), Date(2011, 7, 1)));
testInterval(interval2, 1, -1, AllowDayOverflow.yes, Interval!Date(Date(2000, 12, 29), Date(2011, 5, 1)));
testInterval(interval2, -1, -1, AllowDayOverflow.yes, Interval!Date(Date(1998, 12, 29), Date(2009, 5, 1)));
testInterval(interval2, -1, 1, AllowDayOverflow.yes, Interval!Date(Date(1999, 3, 1), Date(2009, 7, 1)));
testInterval(interval2, 1, 1, AllowDayOverflow.no, Interval!Date(Date(2001, 2, 28), Date(2011, 6, 30)));
testInterval(interval2, 1, -1, AllowDayOverflow.no, Interval!Date(Date(2000, 12, 29), Date(2011, 4, 30)));
testInterval(interval2, -1, -1, AllowDayOverflow.no, Interval!Date(Date(1998, 12, 29), Date(2009, 4, 30)));
testInterval(interval2, -1, 1, AllowDayOverflow.no, Interval!Date(Date(1999, 2, 28), Date(2009, 6, 30)));
}
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(!__traits(compiles, cInterval.shift(5)));
static assert(!__traits(compiles, iInterval.shift(5)));
//Verify Examples.
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
interval1.shift(2);
assert(interval1 == Interval!Date(Date(1998, 1, 2), Date(2014, 3, 1)));
interval2.shift(-2);
assert(interval2 == Interval!Date(Date(1994, 1, 2), Date(2010, 3, 1)));
}
}
//Test Interval's expand(Duration).
unittest
{
version(testStdDateTime)
{
auto interval = Interval!Date(Date(2000, 7, 4), Date(2012, 1, 7));
static void testIntervalFail(I)(I interval, in Duration duration)
{
interval.expand(duration);
}
assertThrown!DateTimeException(testIntervalFail(Interval!Date(Date(2010, 7, 4), dur!"days"(0)), dur!"days"(1)));
assertThrown!DateTimeException(testIntervalFail(Interval!Date(Date(2010, 7, 4), Date(2010, 7, 5)), dur!"days"(-5)));
static void testInterval(I)(I interval, in Duration duration, in I expected, size_t line = __LINE__)
{
interval.expand(duration);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, dur!"days"(22), Interval!Date(Date(2000, 6, 12), Date(2012, 1, 29)));
testInterval(interval, dur!"days"(-22), Interval!Date(Date(2000, 7, 26), Date(2011, 12, 16)));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(!__traits(compiles, cInterval.expand(dur!"days"(5))));
static assert(!__traits(compiles, iInterval.expand(dur!"days"(5))));
//Verify Examples.
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
interval1.expand(dur!"days"(2));
assert(interval1 == Interval!Date(Date(1995, 12, 31), Date(2012, 3, 3)));
interval2.expand(dur!"days"(-2));
assert(interval2 == Interval!Date(Date(1996, 1, 4), Date(2012, 2, 28)));
}
}
//Test Interval's expand(int, int, AllowDayOverflow, Direction)
unittest
{
version(testStdDateTime)
{
{
auto interval = Interval!Date(Date(2000, 7, 4), Date(2012, 1, 7));
static void testIntervalFail(Interval!Date interval, int years, int months)
{
interval.expand(years, months);
}
assertThrown!DateTimeException(testIntervalFail(Interval!Date(Date(2010, 7, 4), dur!"days"(0)), 1, 0));
assertThrown!DateTimeException(testIntervalFail(Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)), -5, 0));
static void testInterval(I)(I interval, int years, int months, AllowDayOverflow allow, Direction dir, in I expected, size_t line = __LINE__)
{
interval.expand(years, months, allow, dir);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, 5, 0, AllowDayOverflow.yes, Direction.both, Interval!Date(Date(1995, 7, 4), Date(2017, 1, 7)));
testInterval(interval, -5, 0, AllowDayOverflow.yes, Direction.both, Interval!Date(Date(2005, 7, 4), Date(2007, 1, 7)));
testInterval(interval, 5, 0, AllowDayOverflow.yes, Direction.fwd, Interval!Date(Date(2000, 7, 4), Date(2017, 1, 7)));
testInterval(interval, -5, 0, AllowDayOverflow.yes, Direction.fwd, Interval!Date(Date(2000, 7, 4), Date(2007, 1, 7)));
testInterval(interval, 5, 0, AllowDayOverflow.yes, Direction.bwd, Interval!Date(Date(1995, 7, 4), Date(2012, 1, 7)));
testInterval(interval, -5, 0, AllowDayOverflow.yes, Direction.bwd, Interval!Date(Date(2005, 7, 4), Date(2012, 1, 7)));
auto interval2 = Interval!Date(Date(2000, 1, 29), Date(2010, 5, 31));
testInterval(interval2, 1, 1, AllowDayOverflow.yes, Direction.both, Interval!Date(Date(1998, 12, 29), Date(2011, 7, 1)));
testInterval(interval2, 1, -1, AllowDayOverflow.yes, Direction.both, Interval!Date(Date(1999, 3, 1), Date(2011, 5, 1)));
testInterval(interval2, -1, -1, AllowDayOverflow.yes, Direction.both, Interval!Date(Date(2001, 3, 1), Date(2009, 5, 1)));
testInterval(interval2, -1, 1, AllowDayOverflow.yes, Direction.both, Interval!Date(Date(2000, 12, 29), Date(2009, 7, 1)));
testInterval(interval2, 1, 1, AllowDayOverflow.no, Direction.both, Interval!Date(Date(1998, 12, 29), Date(2011, 6, 30)));
testInterval(interval2, 1, -1, AllowDayOverflow.no, Direction.both, Interval!Date(Date(1999, 2, 28), Date(2011, 4, 30)));
testInterval(interval2, -1, -1, AllowDayOverflow.no, Direction.both, Interval!Date(Date(2001, 2, 28), Date(2009, 4, 30)));
testInterval(interval2, -1, 1, AllowDayOverflow.no, Direction.both, Interval!Date(Date(2000, 12, 29), Date(2009, 6, 30)));
testInterval(interval2, 1, 1, AllowDayOverflow.yes, Direction.fwd, Interval!Date(Date(2000, 1, 29), Date(2011, 7, 1)));
testInterval(interval2, 1, -1, AllowDayOverflow.yes, Direction.fwd, Interval!Date(Date(2000, 1, 29), Date(2011, 5, 1)));
testInterval(interval2, -1, -1, AllowDayOverflow.yes, Direction.fwd, Interval!Date(Date(2000, 1, 29), Date(2009, 5, 1)));
testInterval(interval2, -1, 1, AllowDayOverflow.yes, Direction.fwd, Interval!Date(Date(2000, 1, 29), Date(2009, 7, 1)));
testInterval(interval2, 1, 1, AllowDayOverflow.no, Direction.fwd, Interval!Date(Date(2000, 1, 29), Date(2011, 6, 30)));
testInterval(interval2, 1, -1, AllowDayOverflow.no, Direction.fwd, Interval!Date(Date(2000, 1, 29), Date(2011, 4, 30)));
testInterval(interval2, -1, -1, AllowDayOverflow.no, Direction.fwd, Interval!Date(Date(2000, 1, 29), Date(2009, 4, 30)));
testInterval(interval2, -1, 1, AllowDayOverflow.no, Direction.fwd, Interval!Date(Date(2000, 1, 29), Date(2009, 6, 30)));
testInterval(interval2, 1, 1, AllowDayOverflow.yes, Direction.bwd, Interval!Date(Date(1998, 12, 29), Date(2010, 5, 31)));
testInterval(interval2, 1, -1, AllowDayOverflow.yes, Direction.bwd, Interval!Date(Date(1999, 3, 1), Date(2010, 5, 31)));
testInterval(interval2, -1, -1, AllowDayOverflow.yes, Direction.bwd, Interval!Date(Date(2001, 3, 1), Date(2010, 5, 31)));
testInterval(interval2, -1, 1, AllowDayOverflow.yes, Direction.bwd, Interval!Date(Date(2000, 12, 29), Date(2010, 5, 31)));
testInterval(interval2, 1, 1, AllowDayOverflow.no, Direction.bwd, Interval!Date(Date(1998, 12, 29), Date(2010, 5, 31)));
testInterval(interval2, 1, -1, AllowDayOverflow.no, Direction.bwd, Interval!Date(Date(1999, 2, 28), Date(2010, 5, 31)));
testInterval(interval2, -1, -1, AllowDayOverflow.no, Direction.bwd, Interval!Date(Date(2001, 2, 28), Date(2010, 5, 31)));
testInterval(interval2, -1, 1, AllowDayOverflow.no, Direction.bwd, Interval!Date(Date(2000, 12, 29), Date(2010, 5, 31)));
}
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(!__traits(compiles, cInterval.expand(5)));
static assert(!__traits(compiles, iInterval.expand(5)));
//Verify Examples.
auto interval1 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
auto interval2 = Interval!Date(Date(1996, 1, 2), Date(2012, 3, 1));
interval1.expand(2);
assert(interval1 == Interval!Date(Date(1994, 1, 2), Date(2014, 3, 1)));
interval2.expand(-2);
assert(interval2 == Interval!Date(Date(1998, 1, 2), Date(2010, 3, 1)));
}
}
//Test Interval's fwdRange.
unittest
{
version(testStdDateTime)
{
{
auto interval = Interval!Date(Date(2010, 9, 19), Date(2010, 9, 21));
static void testInterval1(Interval!Date interval)
{
interval.fwdRange(everyDayOfWeek!Date(DayOfWeek.fri));
}
assertThrown!DateTimeException(testInterval1(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
static void testInterval2(Interval!Date interval)
{
interval.fwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri)).popFront();
}
assertThrown!DateTimeException(testInterval2(interval));
assert(!interval.fwdRange(everyDayOfWeek!Date(DayOfWeek.fri)).empty);
assert(interval.fwdRange(everyDayOfWeek!Date(DayOfWeek.fri), PopFirst.yes).empty);
_assertPred!"=="(Interval!Date(Date(2010, 9, 12), Date(2010, 10, 1)).fwdRange(everyDayOfWeek!Date(DayOfWeek.fri)).front,
Date(2010, 9, 12));
_assertPred!"=="(Interval!Date(Date(2010, 9, 12), Date(2010, 10, 1)).fwdRange(everyDayOfWeek!Date(DayOfWeek.fri), PopFirst.yes).front,
Date(2010, 9, 17));
}
//Verify Examples.
{
auto interval = Interval!Date(Date(2010, 9, 1), Date(2010, 9, 9));
auto func = (in Date date)
{
if((date.day & 1) == 0)
return date + dur!"days"(2);
return date + dur!"days"(1);
};
auto range = interval.fwdRange(func);
assert(range.front == Date(2010, 9, 1)); //An odd day. Using PopFirst.yes would have made this Date(2010, 9, 2).
range.popFront();
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.front == Date(2010, 9, 4));
range.popFront();
assert(range.front == Date(2010, 9, 6));
range.popFront();
assert(range.front == Date(2010, 9, 8));
range.popFront();
assert(range.empty);
}
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, cInterval.fwdRange(everyDayOfWeek!Date(DayOfWeek.fri))));
static assert(__traits(compiles, iInterval.fwdRange(everyDayOfWeek!Date(DayOfWeek.fri))));
}
}
//Test Interval's bwdRange.
unittest
{
version(testStdDateTime)
{
{
auto interval = Interval!Date(Date(2010, 9, 19), Date(2010, 9, 21));
static void testInterval1(Interval!Date interval)
{
interval.bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri));
}
assertThrown!DateTimeException(testInterval1(Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
static void testInterval2(Interval!Date interval)
{
interval.bwdRange(everyDayOfWeek!(Date, Direction.fwd)(DayOfWeek.fri)).popFront();
}
assertThrown!DateTimeException(testInterval2(interval));
assert(!interval.bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri)).empty);
assert(interval.bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri), PopFirst.yes).empty);
_assertPred!"=="(Interval!Date(Date(2010, 9, 19), Date(2010, 10, 1)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri)).front,
Date(2010, 10, 1));
_assertPred!"=="(Interval!Date(Date(2010, 9, 19), Date(2010, 10, 1)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri), PopFirst.yes).front,
Date(2010, 9, 24));
}
//Verify Examples.
{
auto interval = Interval!Date(Date(2010, 9, 1), Date(2010, 9, 9));
auto func = (in Date date)
{
if((date.day & 1) == 0)
return date - dur!"days"(2);
return date - dur!"days"(1);
};
auto range = interval.bwdRange(func);
assert(range.front == Date(2010, 9, 9)); //An odd day. Using PopFirst.yes would have made this Date(2010, 9, 8).
range.popFront();
assert(range.front == Date(2010, 9, 8));
range.popFront();
assert(range.front == Date(2010, 9, 6));
range.popFront();
assert(range.front == Date(2010, 9, 4));
range.popFront();
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.empty);
}
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, cInterval.bwdRange(everyDayOfWeek!Date(DayOfWeek.fri))));
static assert(__traits(compiles, iInterval.bwdRange(everyDayOfWeek!Date(DayOfWeek.fri))));
}
}
//Test Interval's toString().
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).toString(), "[2010-Jul-04 - 2012-Jan-07)");
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, cInterval.toString()));
static assert(__traits(compiles, iInterval.toString()));
}
}
/++
Represents an interval of time which has positive infinity as its end point.
Any ranges which iterate over a $(D PosInfInterval) are infinite. So, the
main purpose of using $(D PosInfInterval) is to create an infinite range
which starts at a fixed point in time and goes to positive infinity.
+/
struct PosInfInterval(TP)
{
public:
/++
Params:
begin = The time point which begins the interval.
Examples:
--------------------
auto interval = PosInfInterval!Date(Date(1996, 1, 2));
--------------------
+/
this(in TP begin) pure nothrow
{
_begin = cast(TP)begin;
}
/++
Params:
rhs = The $(D PosInfInterval) to assign to this one.
+/
/+ref+/ PosInfInterval opAssign(const ref PosInfInterval rhs) pure nothrow
{
_begin = cast(TP)rhs._begin;
return this;
}
/++
Params:
rhs = The $(D PosInfInterval) to assign to this one.
+/
/+ref+/ PosInfInterval opAssign(PosInfInterval rhs) pure nothrow
{
_begin = cast(TP)rhs._begin;
return this;
}
/++
The starting point of the interval. It is included in the interval.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).begin == Date(1996, 1, 2));
--------------------
+/
@property TP begin() const pure nothrow
{
return cast(TP)_begin;
}
/++
The starting point of the interval. It is included in the interval.
Params:
timePoint = The time point to set $(D begin) to.
+/
@property void begin(TP timePoint) pure nothrow
{
_begin = timePoint;
}
/++
Whether the interval's length is 0. Always returns false.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).empty);
--------------------
+/
@property bool empty() const pure nothrow
{
return false;
}
/++
Whether the given time point is within this interval.
Params:
timePoint = The time point to check for inclusion in this interval.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(Date(1994, 12, 24)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(Date(2000, 1, 5)));
--------------------
+/
bool contains(TP timePoint) const pure nothrow
{
return timePoint >= _begin;
}
/++
Whether the given interval is completely within this interval.
Params:
interval = The interval to check for inclusion in this interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(
Interval!Date(Date(1998, 2, 28), Date(2013, 5, 1))));
--------------------
+/
bool contains(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return interval._begin >= _begin;
}
/++
Whether the given interval is completely within this interval.
Params:
interval = The interval to check for inclusion in this interval.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(
PosInfInterval!Date(Date(1999, 5, 4))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(
PosInfInterval!Date(Date(1995, 7, 2))));
--------------------
+/
bool contains(in PosInfInterval interval) const pure nothrow
{
return interval._begin >= _begin;
}
/++
Whether the given interval is completely within this interval.
Always returns false because an interval going to positive infinity
can never contain an interval beginning at negative infinity.
Params:
interval = The interval to check for inclusion in this interval.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(
NegInfInterval!Date(Date(1996, 5, 4))));
--------------------
+/
bool contains(in NegInfInterval!TP interval) const pure nothrow
{
return false;
}
/++
Whether this interval is before the given time point.
Always returns false because an interval going to positive infinity
can never be before any time point.
Params:
timePoint = The time point to check whether this interval is before
it.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(Date(1994, 12, 24)));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(Date(2000, 1, 5)));
--------------------
+/
bool isBefore(in TP timePoint) const pure nothrow
{
return false;
}
/++
Whether this interval is before the given interval and does not
intersect it.
Always returns false (unless the given interval is empty) because an
interval going to positive infinity can never be before any other
interval.
Params:
interval = The interval to check for against this interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
--------------------
+/
bool isBefore(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return false;
}
/++
Whether this interval is before the given interval and does not
intersect it.
Always returns false because an interval going to positive infinity can
never be before any other interval.
Params:
interval = The interval to check for against this interval.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(
PosInfInterval!Date(Date(1992, 5, 4))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(
PosInfInterval!Date(Date(2013, 3, 7))));
--------------------
+/
bool isBefore(in PosInfInterval interval) const pure nothrow
{
return false;
}
/++
Whether this interval is before the given interval and does not
intersect it.
Always returns false because an interval going to positive infinity can
never be before any other interval.
Params:
interval = The interval to check for against this interval.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(
NegInfInterval!Date(Date(1996, 5, 4))));
--------------------
+/
bool isBefore(in NegInfInterval!TP interval) const pure nothrow
{
return false;
}
/++
Whether this interval is after the given time point.
Params:
timePoint = The time point to check whether this interval is after
it.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAfter(Date(1994, 12, 24)));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(Date(2000, 1, 5)));
--------------------
+/
bool isAfter(in TP timePoint) const pure nothrow
{
return timePoint < _begin;
}
/++
Whether this interval is after the given interval and does not intersect
it.
Params:
interval = The interval to check against this interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));
--------------------
+/
bool isAfter(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return _begin >= interval._end;
}
/++
Whether this interval is after the given interval and does not intersect
it.
Always returns false because an interval going to positive infinity can
never be after another interval going to positive infinity.
Params:
interval = The interval to check against this interval.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
PosInfInterval!Date(Date(1990, 1, 7))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
PosInfInterval!Date(Date(1999, 5, 4))));
--------------------
+/
bool isAfter(in PosInfInterval interval) const pure nothrow
{
return false;
}
/++
Whether this interval is after the given interval and does not intersect
it.
Params:
interval = The interval to check against this interval.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
NegInfInterval!Date(Date(1996, 1, 2))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(
NegInfInterval!Date(Date(2000, 7, 1))));
--------------------
+/
bool isAfter(in NegInfInterval!TP interval) const pure nothrow
{
return _begin >= interval._end;
}
/++
Whether the given interval overlaps this interval.
Params:
interval = The interval to check for intersection with this interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).intersects(
Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));
--------------------
+/
bool intersects(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return interval._end > _begin;
}
/++
Whether the given interval overlaps this interval.
Always returns true because two intervals going to positive infinity
always overlap.
Params:
interval = The interval to check for intersection with this
interval.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(
PosInfInterval!Date(Date(1990, 1, 7))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(
PosInfInterval!Date(Date(1999, 5, 4))));
--------------------
+/
bool intersects(in PosInfInterval interval) const pure nothrow
{
return true;
}
/++
Whether the given interval overlaps this interval.
Params:
interval = The interval to check for intersection with this
interval.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).intersects(
NegInfInterval!Date(Date(1996, 1, 2))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(
NegInfInterval!Date(Date(2000, 7, 1))));
--------------------
+/
bool intersects(in NegInfInterval!TP interval) const pure nothrow
{
return _begin < interval._end;
}
/++
Returns the intersection of two intervals
Params:
interval = The interval to intersect with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect or if
the given interval is empty.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
Interval!Date(Date(1996, 1 , 2), Date(2000, 8, 2)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) ==
Interval!Date(Date(1999, 1 , 12), Date(2011, 9, 17)));
--------------------
+/
Interval!TP intersection(in Interval!TP interval) const
{
enforce(this.intersects(interval), new DateTimeException(format("%s and %s do not intersect.", this, interval)));
auto begin = _begin > interval._begin ? _begin : interval._begin;
return Interval!TP(begin, interval._end);
}
/++
Returns the intersection of two intervals
Params:
interval = The interval to intersect with this interval.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
PosInfInterval!Date(Date(1990, 7, 6))) ==
PosInfInterval!Date(Date(1996, 1 , 2)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
PosInfInterval!Date(Date(1999, 1, 12))) ==
PosInfInterval!Date(Date(1999, 1 , 12)));
--------------------
+/
PosInfInterval intersection(in PosInfInterval interval) const pure nothrow
{
return PosInfInterval(_begin < interval._begin ? interval._begin : _begin);
}
/++
Returns the intersection of two intervals
Params:
interval = The interval to intersect with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
NegInfInterval!Date(Date(1999, 7, 6))) ==
Interval!Date(Date(1996, 1 , 2), Date(1999, 7, 6)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(
NegInfInterval!Date(Date(2013, 1, 12))) ==
Interval!Date(Date(1996, 1 , 2), Date(2013, 1, 12)));
--------------------
+/
Interval!TP intersection(in NegInfInterval!TP interval) const
{
enforce(this.intersects(interval), new DateTimeException(format("%s and %s do not intersect.", this, interval)));
return Interval!TP(_begin, interval._end);
}
/++
Whether the given interval is adjacent to this interval.
Params:
interval = The interval to check whether its adjecent to this
interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(
Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));
assert(!PosInfInterval!Date(Date(1999, 1, 12)).isAdjacent(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
--------------------
+/
bool isAdjacent(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return _begin == interval._end;
}
/++
Whether the given interval is adjacent to this interval.
Always returns false because two intervals going to positive infinity
can never be adjacent to one another.
Params:
interval = The interval to check whether its adjecent to this
interval.
Examples:
--------------------
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(
PosInfInterval!Date(Date(1990, 1, 7))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(
PosInfInterval!Date(Date(1996, 1, 2))));
--------------------
+/
bool isAdjacent(in PosInfInterval interval) const pure nothrow
{
return false;
}
/++
Whether the given interval is adjacent to this interval.
Params:
interval = The interval to check whether its adjecent to this
interval.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(
NegInfInterval!Date(Date(1996, 1, 2))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(
NegInfInterval!Date(Date(2000, 7, 1))));
--------------------
+/
bool isAdjacent(in NegInfInterval!TP interval) const pure nothrow
{
return _begin == interval._end;
}
/++
Returns the union of two intervals
Params:
interval = The interval to merge with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect and are
not adjacent or if the given interval is empty.
Note:
There is no overload for $(D merge) which takes a
$(D NegInfInterval). This is because you can't have an interval
which goes from negative infinity to positive infinity.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
PosInfInterval!Date(Date(1990, 7 , 6)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) ==
PosInfInterval!Date(Date(1996, 1 , 2)));
--------------------
+/
PosInfInterval merge(in Interval!TP interval) const
{
enforce(this.isAdjacent(interval) || this.intersects(interval),
new DateTimeException(format("%s and %s are not adjacent and do not intersect.", this, interval)));
return PosInfInterval(_begin < interval._begin ? _begin : interval._begin);
}
/++
Returns the union of two intervals
Params:
interval = The interval to merge with this interval.
Note:
There is no overload for $(D merge) which takes a
$(D NegInfInterval). This is because you can't have an interval
which goes from negative infinity to positive infinity.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(
PosInfInterval!Date(Date(1990, 7, 6))) ==
PosInfInterval!Date(Date(1990, 7 , 6)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(
PosInfInterval!Date(Date(1999, 1, 12))) ==
PosInfInterval!Date(Date(1996, 1 , 2)));
--------------------
+/
PosInfInterval merge(in PosInfInterval interval) const pure nothrow
{
return PosInfInterval(_begin < interval._begin ? _begin : interval._begin);
}
/++
Returns an interval that covers from the earliest time point of two
intervals up to (but not including) the latest time point of two
intervals.
Params:
interval = The interval to create a span together with this
interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Note:
There is no overload for $(D span) which takes a
$(D NegInfInterval). This is because you can't have an interval
which goes from negative infinity to positive infinity.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(
Interval!Date(Date(500, 8, 9), Date(1602, 1, 31))) ==
PosInfInterval!Date(Date(500, 8, 9)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
PosInfInterval!Date(Date(1990, 7 , 6)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) ==
PosInfInterval!Date(Date(1996, 1 , 2)));
--------------------
+/
PosInfInterval span(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return PosInfInterval(_begin < interval._begin ? _begin : interval._begin);
}
/++
Returns an interval that covers from the earliest time point of two
intervals up to (but not including) the latest time point of two
intervals.
Params:
interval = The interval to create a span together with this
interval.
Note:
There is no overload for $(D span) which takes a
$(D NegInfInterval). This is because you can't have an interval
which goes from negative infinity to positive infinity.
Examples:
--------------------
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(
PosInfInterval!Date(Date(1990, 7, 6))) ==
PosInfInterval!Date(Date(1990, 7 , 6)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(
PosInfInterval!Date(Date(1999, 1, 12))) ==
PosInfInterval!Date(Date(1996, 1 , 2)));
--------------------
+/
PosInfInterval span(in PosInfInterval interval) const pure nothrow
{
return PosInfInterval(_begin < interval._begin ? _begin : interval._begin);
}
/++
Shifts the $(D begin) of this interval forward or backwards in time by
the given duration (a positive duration shifts the interval forward; a
negative duration shifts it backward). Effectively, it does
$(D begin += duration).
Params:
duration = The duration to shift the interval by.
Examples:
--------------------
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));
interval1.shift(dur!"days"(50));
assert(interval1 == PosInfInterval!Date(Date(1996, 2, 21)));
interval2.shift(dur!"days"(-50));
assert(interval2 == PosInfInterval!Date(Date(1995, 11, 13)));
--------------------
+/
void shift(D)(D duration) pure nothrow
if(__traits(compiles, begin + duration))
{
_begin += duration;
}
static if(__traits(compiles, begin.add!"months"(1)) &&
__traits(compiles, begin.add!"years"(1)))
{
/++
Shifts the $(D begin) of this interval forward or backwards in time
by the given number of years and/or months (a positive number of years
and months shifts the interval forward; a negative number shifts it
backward). It adds the years the given years and months to
$(D begin). It effectively calls $(D add!"years"()) and then
$(D add!"months"()) on $(D begin) with the given number of years and
months.
Params:
years = The number of years to shift the interval by.
months = The number of months to shift the interval by.
allowOverflow = Whether the days should be allowed to overflow
on $(D begin), causing its month to increment.
Throws:
$(D DateTimeException) if this interval is empty or if the
resulting interval would be invalid.
Examples:
--------------------
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));
interval1.shift(dur!"days"(50));
assert(interval1 == PosInfInterval!Date(Date(1996, 2, 21)));
interval2.shift(dur!"days"(-50));
assert(interval2 == PosInfInterval!Date(Date(1995, 11, 13)));
--------------------
+/
void shift(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)
if(isIntegral!T)
{
auto begin = _begin;
begin.add!"years"(years, allowOverflow);
begin.add!"months"(months, allowOverflow);
_begin = begin;
}
}
/++
Expands the interval backwards in time. Effectively, it does
$(D begin -= duration).
Params:
duration = The duration to expand the interval by.
dir = The direction in time to expand the interval.
Examples:
--------------------
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));
interval1.expand(dur!"days"(2));
assert(interval1 == PosInfInterval!Date(Date(1995, 12, 31)));
interval2.expand(dur!"days"(-2));
assert(interval2 == PosInfInterval!Date(Date(1996, 1, 4)));
--------------------
+/
void expand(D)(D duration) pure nothrow
if(__traits(compiles, begin + duration))
{
_begin -= duration;
}
static if(__traits(compiles, begin.add!"months"(1)) &&
__traits(compiles, begin.add!"years"(1)))
{
/++
Expands the interval forwards and/or backwards in time. Effectively,
it subtracts the given number of months/years from $(D begin).
Params:
years = The number of years to expand the interval by.
months = The number of months to expand the interval by.
allowOverflow = Whether the days should be allowed to overflow
on $(D begin), causing its month to increment.
Throws:
$(D DateTimeException) if this interval is empty or if the
resulting interval would be invalid.
Examples:
--------------------
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));
interval1.expand(2);
assert(interval1 == PosInfInterval!Date(Date(1994, 1, 2)));
interval2.expand(-2);
assert(interval2 == PosInfInterval!Date(Date(1998, 1, 2)));
--------------------
+/
void expand(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)
if(isIntegral!T)
{
auto begin = _begin;
begin.add!"years"(-years, allowOverflow);
begin.add!"months"(-months, allowOverflow);
_begin = begin;
return;
}
}
/++
Returns a range which iterates forward over the interval, starting
at $(D begin), using $(D_PARAM func) to generate each successive time
point.
The range's $(D front) is the interval's $(D begin). $(D_PARAM func) is
used to generate the next $(D front) when $(D popFront) is called. If
$(D_PARAM popFirst) is $(D PopFirst.yes), then $(D popFront) is called
before the range is returned (so that $(D front) is a time point which
$(D_PARAM func) would generate).
If $(D_PARAM func) ever generates a time point less than or equal to the
current $(D front) of the range, then a $(D DateTimeException) will be
thrown.
There are helper functions in this module which generate common
delegates to pass to $(D fwdRange). Their documentation starts with
"Range-generating function," so you can easily search for them.
Params:
func = The function used to generate the time points of the
range over the interval.
popFirst = Whether $(D popFront) should be called on the range
before returning it.
Throws:
$(D DateTimeException) if this interval is empty.
Warning:
$(D_PARAM func) must be logically pure. Ideally, $(D_PARAM func)
would be a function pointer to a pure function, but forcing
$(D_PARAM func) to be pure is far too restrictive to be useful, and
in order to have the ease of use of having functions which generate
functions to pass to $(D fwdRange), $(D_PARAM func) must be a
delegate.
If $(D_PARAM func) retains state which changes as it is called, then
some algorithms will not work correctly, because the range's
$(D save) will have failed to have really saved the range's state.
So, if you want to avoid such bugs, don't pass a delegate which is
not logically pure to $(D fwdRange). If $(D_PARAM func) is given the
same time point with two different calls, it must return the same
result both times.
Of course, none of the functions in this module have this problem,
so it's only relevant if you're creating your own delegate.
Examples:
--------------------
auto interval = PosInfInterval!Date(Date(2010, 9, 1));
auto func = (in Date date) //For iterating over even-numbered days.
{
if((date.day & 1) == 0)
return date + dur!"days"(2);
return date + dur!"days"(1);
};
auto range = interval.fwdRange(func);
//An odd day. Using PopFirst.yes would have made this Date(2010, 9, 2).
assert(range.front == Date(2010, 9, 1));
range.popFront();
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.front == Date(2010, 9, 4));
range.popFront();
assert(range.front == Date(2010, 9, 6));
range.popFront();
assert(range.front == Date(2010, 9, 8));
range.popFront();
assert(!range.empty);
--------------------
+/
PosInfIntervalRange!(TP) fwdRange(TP delegate(in TP) func, PopFirst popFirst = PopFirst.no) const
{
auto range = PosInfIntervalRange!(TP)(this, func);
if(popFirst == PopFirst.yes)
range.popFront();
return range;
}
/+
Converts this interval to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString()
{
return _toStringImpl();
}
/++
Converts this interval to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString() const nothrow
{
return _toStringImpl();
}
private:
/+
Since we have two versions of toString(), we have _toStringImpl()
so that they can share implementations.
+/
string _toStringImpl() const nothrow
{
try
return format("[%s - ∞)", _begin);
catch(Exception e)
assert(0, "format() threw.");
}
TP _begin;
}
//Test PosInfInterval's constructor.
unittest
{
version(testStdDateTime)
{
PosInfInterval!Date(Date.init);
PosInfInterval!TimeOfDay(TimeOfDay.init);
PosInfInterval!DateTime(DateTime.init);
PosInfInterval!SysTime(SysTime(0));
//Verify Examples.
auto interval = PosInfInterval!Date(Date(1996, 1, 2));
}
}
//Test PosInfInterval's begin.
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(PosInfInterval!Date(Date(1, 1, 1)).begin, Date(1, 1, 1));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 1, 1)).begin, Date(2010, 1, 1));
_assertPred!"=="(PosInfInterval!Date(Date(1997, 12, 31)).begin, Date(1997, 12, 31));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static assert(__traits(compiles, cPosInfInterval.begin));
static assert(__traits(compiles, iPosInfInterval.begin));
//Verify Examples.
assert(PosInfInterval!Date(Date(1996, 1, 2)).begin == Date(1996, 1, 2));
}
}
//Test PosInfInterval's empty.
unittest
{
version(testStdDateTime)
{
assert(!PosInfInterval!Date(Date(2010, 1, 1)).empty);
assert(!PosInfInterval!TimeOfDay(TimeOfDay(0, 30, 0)).empty);
assert(!PosInfInterval!DateTime(DateTime(2010, 1, 1, 0, 30, 0)).empty);
assert(!PosInfInterval!SysTime(SysTime(DateTime(2010, 1, 1, 0, 30, 0))).empty);
const cPosInfInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iPosInfInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
static assert(__traits(compiles, cPosInfInterval.empty));
static assert(__traits(compiles, iPosInfInterval.empty));
//Verify Examples.
assert(!PosInfInterval!Date(Date(1996, 1, 2)).empty);
}
}
//Test PosInfInterval's contains(time point).
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
assert(!posInfInterval.contains(Date(2009, 7, 4)));
assert(!posInfInterval.contains(Date(2010, 7, 3)));
assert(posInfInterval.contains(Date(2010, 7, 4)));
assert(posInfInterval.contains(Date(2010, 7, 5)));
assert(posInfInterval.contains(Date(2011, 7, 1)));
assert(posInfInterval.contains(Date(2012, 1, 6)));
assert(posInfInterval.contains(Date(2012, 1, 7)));
assert(posInfInterval.contains(Date(2012, 1, 8)));
assert(posInfInterval.contains(Date(2013, 1, 7)));
const cdate = Date(2010, 7, 6);
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static assert(__traits(compiles, posInfInterval.contains(cdate)));
static assert(__traits(compiles, cPosInfInterval.contains(cdate)));
static assert(__traits(compiles, iPosInfInterval.contains(cdate)));
//Verify Examples.
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(Date(1994, 12, 24)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(Date(2000, 1, 5)));
}
}
//Test PosInfInterval's contains(Interval).
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static void testInterval(in PosInfInterval!Date posInfInterval, in Interval!Date interval)
{
posInfInterval.contains(interval);
}
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(posInfInterval.contains(posInfInterval));
assert(!posInfInterval.contains(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!posInfInterval.contains(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(!posInfInterval.contains(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!posInfInterval.contains(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!posInfInterval.contains(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!posInfInterval.contains(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(posInfInterval.contains(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(posInfInterval.contains(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(posInfInterval.contains(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(posInfInterval.contains(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(posInfInterval.contains(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(posInfInterval.contains(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!posInfInterval.contains(PosInfInterval!Date(Date(2010, 7, 3))));
assert(posInfInterval.contains(PosInfInterval!Date(Date(2010, 7, 4))));
assert(posInfInterval.contains(PosInfInterval!Date(Date(2010, 7, 5))));
assert(posInfInterval.contains(PosInfInterval!Date(Date(2012, 1, 6))));
assert(posInfInterval.contains(PosInfInterval!Date(Date(2012, 1, 7))));
assert(posInfInterval.contains(PosInfInterval!Date(Date(2012, 1, 8))));
assert(PosInfInterval!Date(Date(2010, 7, 3)).contains(posInfInterval));
assert(PosInfInterval!Date(Date(2010, 7, 4)).contains(posInfInterval));
assert(!PosInfInterval!Date(Date(2010, 7, 5)).contains(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 6)).contains(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 7)).contains(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 8)).contains(posInfInterval));
assert(!posInfInterval.contains(NegInfInterval!Date(Date(2010, 7, 3))));
assert(!posInfInterval.contains(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!posInfInterval.contains(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!posInfInterval.contains(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!posInfInterval.contains(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!posInfInterval.contains(NegInfInterval!Date(Date(2012, 1, 8))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, posInfInterval.contains(interval)));
static assert(__traits(compiles, posInfInterval.contains(cInterval)));
static assert(__traits(compiles, posInfInterval.contains(iInterval)));
static assert(__traits(compiles, posInfInterval.contains(posInfInterval)));
static assert(__traits(compiles, posInfInterval.contains(cPosInfInterval)));
static assert(__traits(compiles, posInfInterval.contains(iPosInfInterval)));
static assert(__traits(compiles, posInfInterval.contains(negInfInterval)));
static assert(__traits(compiles, posInfInterval.contains(cNegInfInterval)));
static assert(__traits(compiles, posInfInterval.contains(iNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.contains(interval)));
static assert(__traits(compiles, cPosInfInterval.contains(cInterval)));
static assert(__traits(compiles, cPosInfInterval.contains(iInterval)));
static assert(__traits(compiles, cPosInfInterval.contains(posInfInterval)));
static assert(__traits(compiles, cPosInfInterval.contains(cPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.contains(iPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.contains(negInfInterval)));
static assert(__traits(compiles, cPosInfInterval.contains(cNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.contains(iNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.contains(interval)));
static assert(__traits(compiles, iPosInfInterval.contains(cInterval)));
static assert(__traits(compiles, iPosInfInterval.contains(iInterval)));
static assert(__traits(compiles, iPosInfInterval.contains(posInfInterval)));
static assert(__traits(compiles, iPosInfInterval.contains(cPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.contains(iPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.contains(negInfInterval)));
static assert(__traits(compiles, iPosInfInterval.contains(cNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.contains(iNegInfInterval)));
//Verify Examples.
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(Interval!Date(Date(1998, 2, 28), Date(2013, 5, 1))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).contains(PosInfInterval!Date(Date(1999, 5, 4))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(PosInfInterval!Date(Date(1995, 7, 2))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).contains(NegInfInterval!Date(Date(1996, 5, 4))));
}
}
//Test PosInfInterval's isBefore(time point).
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
assert(!posInfInterval.isBefore(Date(2009, 7, 3)));
assert(!posInfInterval.isBefore(Date(2010, 7, 3)));
assert(!posInfInterval.isBefore(Date(2010, 7, 4)));
assert(!posInfInterval.isBefore(Date(2010, 7, 5)));
assert(!posInfInterval.isBefore(Date(2011, 7, 1)));
assert(!posInfInterval.isBefore(Date(2012, 1, 6)));
assert(!posInfInterval.isBefore(Date(2012, 1, 7)));
assert(!posInfInterval.isBefore(Date(2012, 1, 8)));
assert(!posInfInterval.isBefore(Date(2013, 1, 7)));
const cdate = Date(2010, 7, 6);
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static assert(__traits(compiles, posInfInterval.isBefore(cdate)));
static assert(__traits(compiles, cPosInfInterval.isBefore(cdate)));
static assert(__traits(compiles, iPosInfInterval.isBefore(cdate)));
//Verify Examples.
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(Date(1994, 12, 24)));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(Date(2000, 1, 5)));
}
}
//Test PosInfInterval's isBefore(Interval).
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static void testInterval(in PosInfInterval!Date posInfInterval, in Interval!Date interval)
{
posInfInterval.isBefore(interval);
}
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(!posInfInterval.isBefore(posInfInterval));
assert(!posInfInterval.isBefore(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!posInfInterval.isBefore(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!posInfInterval.isBefore(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!posInfInterval.isBefore(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!posInfInterval.isBefore(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!posInfInterval.isBefore(PosInfInterval!Date(Date(2012, 1, 6))));
assert(!posInfInterval.isBefore(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!posInfInterval.isBefore(PosInfInterval!Date(Date(2012, 1, 8))));
assert(!PosInfInterval!Date(Date(2010, 7, 3)).isBefore(posInfInterval));
assert(!PosInfInterval!Date(Date(2010, 7, 4)).isBefore(posInfInterval));
assert(!PosInfInterval!Date(Date(2010, 7, 5)).isBefore(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 6)).isBefore(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 7)).isBefore(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 8)).isBefore(posInfInterval));
assert(!posInfInterval.isBefore(NegInfInterval!Date(Date(2010, 7, 3))));
assert(!posInfInterval.isBefore(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!posInfInterval.isBefore(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!posInfInterval.isBefore(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!posInfInterval.isBefore(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!posInfInterval.isBefore(NegInfInterval!Date(Date(2012, 1, 8))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, posInfInterval.isBefore(interval)));
static assert(__traits(compiles, posInfInterval.isBefore(cInterval)));
static assert(__traits(compiles, posInfInterval.isBefore(iInterval)));
static assert(__traits(compiles, posInfInterval.isBefore(posInfInterval)));
static assert(__traits(compiles, posInfInterval.isBefore(cPosInfInterval)));
static assert(__traits(compiles, posInfInterval.isBefore(iPosInfInterval)));
static assert(__traits(compiles, posInfInterval.isBefore(negInfInterval)));
static assert(__traits(compiles, posInfInterval.isBefore(cNegInfInterval)));
static assert(__traits(compiles, posInfInterval.isBefore(iNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isBefore(interval)));
static assert(__traits(compiles, cPosInfInterval.isBefore(cInterval)));
static assert(__traits(compiles, cPosInfInterval.isBefore(iInterval)));
static assert(__traits(compiles, cPosInfInterval.isBefore(posInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isBefore(cPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isBefore(iPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isBefore(negInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isBefore(cNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isBefore(iNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isBefore(interval)));
static assert(__traits(compiles, iPosInfInterval.isBefore(cInterval)));
static assert(__traits(compiles, iPosInfInterval.isBefore(iInterval)));
static assert(__traits(compiles, iPosInfInterval.isBefore(posInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isBefore(cPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isBefore(iPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isBefore(negInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isBefore(cNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isBefore(iNegInfInterval)));
//Verify Examples.
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(PosInfInterval!Date(Date(1992, 5, 4))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(PosInfInterval!Date(Date(2013, 3, 7))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isBefore(NegInfInterval!Date(Date(1996, 5, 4))));
}
}
//Test PosInfInterval's isAfter(time point).
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
assert(posInfInterval.isAfter(Date(2009, 7, 3)));
assert(posInfInterval.isAfter(Date(2010, 7, 3)));
assert(!posInfInterval.isAfter(Date(2010, 7, 4)));
assert(!posInfInterval.isAfter(Date(2010, 7, 5)));
assert(!posInfInterval.isAfter(Date(2011, 7, 1)));
assert(!posInfInterval.isAfter(Date(2012, 1, 6)));
assert(!posInfInterval.isAfter(Date(2012, 1, 7)));
assert(!posInfInterval.isAfter(Date(2012, 1, 8)));
assert(!posInfInterval.isAfter(Date(2013, 1, 7)));
const cdate = Date(2010, 7, 6);
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static assert(__traits(compiles, posInfInterval.isAfter(cdate)));
static assert(__traits(compiles, cPosInfInterval.isAfter(cdate)));
static assert(__traits(compiles, iPosInfInterval.isAfter(cdate)));
//Verify Examples.
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAfter(Date(1994, 12, 24)));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(Date(2000, 1, 5)));
}
}
//Test PosInfInterval's isAfter(Interval).
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static void testInterval(in PosInfInterval!Date posInfInterval, in Interval!Date interval)
{
posInfInterval.isAfter(interval);
}
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(!posInfInterval.isAfter(posInfInterval));
assert(posInfInterval.isAfter(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!posInfInterval.isAfter(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(posInfInterval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!posInfInterval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!posInfInterval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!posInfInterval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(!posInfInterval.isAfter(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(!posInfInterval.isAfter(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(!posInfInterval.isAfter(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!posInfInterval.isAfter(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(!posInfInterval.isAfter(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!posInfInterval.isAfter(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!posInfInterval.isAfter(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!posInfInterval.isAfter(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!posInfInterval.isAfter(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!posInfInterval.isAfter(PosInfInterval!Date(Date(2012, 1, 6))));
assert(!posInfInterval.isAfter(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!posInfInterval.isAfter(PosInfInterval!Date(Date(2012, 1, 8))));
assert(!PosInfInterval!Date(Date(2010, 7, 3)).isAfter(posInfInterval));
assert(!PosInfInterval!Date(Date(2010, 7, 4)).isAfter(posInfInterval));
assert(!PosInfInterval!Date(Date(2010, 7, 5)).isAfter(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 6)).isAfter(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 7)).isAfter(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 8)).isAfter(posInfInterval));
assert(posInfInterval.isAfter(NegInfInterval!Date(Date(2010, 7, 3))));
assert(posInfInterval.isAfter(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!posInfInterval.isAfter(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!posInfInterval.isAfter(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!posInfInterval.isAfter(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!posInfInterval.isAfter(NegInfInterval!Date(Date(2012, 1, 8))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, posInfInterval.isAfter(interval)));
static assert(__traits(compiles, posInfInterval.isAfter(cInterval)));
static assert(__traits(compiles, posInfInterval.isAfter(iInterval)));
static assert(__traits(compiles, posInfInterval.isAfter(posInfInterval)));
static assert(__traits(compiles, posInfInterval.isAfter(cPosInfInterval)));
static assert(__traits(compiles, posInfInterval.isAfter(iPosInfInterval)));
static assert(__traits(compiles, posInfInterval.isAfter(negInfInterval)));
static assert(__traits(compiles, posInfInterval.isAfter(cNegInfInterval)));
static assert(__traits(compiles, posInfInterval.isAfter(iNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAfter(interval)));
static assert(__traits(compiles, cPosInfInterval.isAfter(cInterval)));
static assert(__traits(compiles, cPosInfInterval.isAfter(iInterval)));
static assert(__traits(compiles, cPosInfInterval.isAfter(posInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAfter(cPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAfter(iPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAfter(negInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAfter(cNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAfter(iNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAfter(interval)));
static assert(__traits(compiles, iPosInfInterval.isAfter(cInterval)));
static assert(__traits(compiles, iPosInfInterval.isAfter(iInterval)));
static assert(__traits(compiles, iPosInfInterval.isAfter(posInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAfter(cPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAfter(iPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAfter(negInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAfter(cNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAfter(iNegInfInterval)));
//Verify Examples.
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAfter(Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(PosInfInterval!Date(Date(1990, 1, 7))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(PosInfInterval!Date(Date(1999, 5, 4))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAfter(NegInfInterval!Date(Date(1996, 1, 2))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAfter(NegInfInterval!Date(Date(2000, 7, 1))));
}
}
//Test PosInfInterval's intersects().
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static void testInterval(in PosInfInterval!Date posInfInterval, in Interval!Date interval)
{
posInfInterval.intersects(interval);
}
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(posInfInterval.intersects(posInfInterval));
assert(!posInfInterval.intersects(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(posInfInterval.intersects(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(!posInfInterval.intersects(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(posInfInterval.intersects(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(posInfInterval.intersects(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(posInfInterval.intersects(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(posInfInterval.intersects(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(posInfInterval.intersects(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(posInfInterval.intersects(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(posInfInterval.intersects(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(posInfInterval.intersects(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(posInfInterval.intersects(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(posInfInterval.intersects(PosInfInterval!Date(Date(2010, 7, 3))));
assert(posInfInterval.intersects(PosInfInterval!Date(Date(2010, 7, 4))));
assert(posInfInterval.intersects(PosInfInterval!Date(Date(2010, 7, 5))));
assert(posInfInterval.intersects(PosInfInterval!Date(Date(2012, 1, 6))));
assert(posInfInterval.intersects(PosInfInterval!Date(Date(2012, 1, 7))));
assert(posInfInterval.intersects(PosInfInterval!Date(Date(2012, 1, 8))));
assert(PosInfInterval!Date(Date(2010, 7, 3)).intersects(posInfInterval));
assert(PosInfInterval!Date(Date(2010, 7, 4)).intersects(posInfInterval));
assert(PosInfInterval!Date(Date(2010, 7, 5)).intersects(posInfInterval));
assert(PosInfInterval!Date(Date(2012, 1, 6)).intersects(posInfInterval));
assert(PosInfInterval!Date(Date(2012, 1, 7)).intersects(posInfInterval));
assert(PosInfInterval!Date(Date(2012, 1, 8)).intersects(posInfInterval));
assert(!posInfInterval.intersects(NegInfInterval!Date(Date(2010, 7, 3))));
assert(!posInfInterval.intersects(NegInfInterval!Date(Date(2010, 7, 4))));
assert(posInfInterval.intersects(NegInfInterval!Date(Date(2010, 7, 5))));
assert(posInfInterval.intersects(NegInfInterval!Date(Date(2012, 1, 6))));
assert(posInfInterval.intersects(NegInfInterval!Date(Date(2012, 1, 7))));
assert(posInfInterval.intersects(NegInfInterval!Date(Date(2012, 1, 8))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, posInfInterval.intersects(interval)));
static assert(__traits(compiles, posInfInterval.intersects(cInterval)));
static assert(__traits(compiles, posInfInterval.intersects(iInterval)));
static assert(__traits(compiles, posInfInterval.intersects(posInfInterval)));
static assert(__traits(compiles, posInfInterval.intersects(cPosInfInterval)));
static assert(__traits(compiles, posInfInterval.intersects(iPosInfInterval)));
static assert(__traits(compiles, posInfInterval.intersects(negInfInterval)));
static assert(__traits(compiles, posInfInterval.intersects(cNegInfInterval)));
static assert(__traits(compiles, posInfInterval.intersects(iNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersects(interval)));
static assert(__traits(compiles, cPosInfInterval.intersects(cInterval)));
static assert(__traits(compiles, cPosInfInterval.intersects(iInterval)));
static assert(__traits(compiles, cPosInfInterval.intersects(posInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersects(cPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersects(iPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersects(negInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersects(cNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersects(iNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersects(interval)));
static assert(__traits(compiles, iPosInfInterval.intersects(cInterval)));
static assert(__traits(compiles, iPosInfInterval.intersects(iInterval)));
static assert(__traits(compiles, iPosInfInterval.intersects(posInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersects(cPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersects(iPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersects(negInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersects(cNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersects(iNegInfInterval)));
//Verify Examples.
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).intersects(Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(PosInfInterval!Date(Date(1990, 1, 7))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(PosInfInterval!Date(Date(1999, 5, 4))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).intersects(NegInfInterval!Date(Date(1996, 1, 2))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersects(NegInfInterval!Date(Date(2000, 7, 1))));
}
}
//Test PosInfInterval's intersection().
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static void testInterval(I, J)(in I interval1, in J interval2)
{
interval1.intersection(interval2);
}
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assertThrown!DateTimeException(testInterval(posInfInterval, NegInfInterval!Date(Date(2010, 7, 3))));
assertThrown!DateTimeException(testInterval(posInfInterval, NegInfInterval!Date(Date(2010, 7, 4))));
_assertPred!"=="(posInfInterval.intersection(posInfInterval),
posInfInterval);
_assertPred!"=="(posInfInterval.intersection(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))),
Interval!Date(Date(2010, 7, 4), Date(2013, 7, 3)));
_assertPred!"=="(posInfInterval.intersection(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))),
Interval!Date(Date(2010, 7, 4), Date(2010, 7, 5)));
_assertPred!"=="(posInfInterval.intersection(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(posInfInterval.intersection(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 8)));
_assertPred!"=="(posInfInterval.intersection(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))),
Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)));
_assertPred!"=="(posInfInterval.intersection(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)));
_assertPred!"=="(posInfInterval.intersection(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))),
Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)));
_assertPred!"=="(posInfInterval.intersection(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))),
Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8)));
_assertPred!"=="(posInfInterval.intersection(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))),
Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8)));
_assertPred!"=="(posInfInterval.intersection(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))),
Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9)));
_assertPred!"=="(posInfInterval.intersection(PosInfInterval!Date(Date(2010, 7, 3))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.intersection(PosInfInterval!Date(Date(2010, 7, 4))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.intersection(PosInfInterval!Date(Date(2010, 7, 5))),
PosInfInterval!Date(Date(2010, 7, 5)));
_assertPred!"=="(posInfInterval.intersection(PosInfInterval!Date(Date(2012, 1, 6))),
PosInfInterval!Date(Date(2012, 1, 6)));
_assertPred!"=="(posInfInterval.intersection(PosInfInterval!Date(Date(2012, 1, 7))),
PosInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(posInfInterval.intersection(PosInfInterval!Date(Date(2012, 1, 8))),
PosInfInterval!Date(Date(2012, 1, 8)));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 7, 3)).intersection(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 7, 4)).intersection(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 7, 5)).intersection(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 5)));
_assertPred!"=="(PosInfInterval!Date(Date(2012, 1, 6)).intersection(posInfInterval),
PosInfInterval!Date(Date(2012, 1, 6)));
_assertPred!"=="(PosInfInterval!Date(Date(2012, 1, 7)).intersection(posInfInterval),
PosInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(PosInfInterval!Date(Date(2012, 1, 8)).intersection(posInfInterval),
PosInfInterval!Date(Date(2012, 1, 8)));
_assertPred!"=="(posInfInterval.intersection(NegInfInterval!Date(Date(2010, 7, 5))),
Interval!Date(Date(2010, 7, 4), Date(2010, 7, 5)));
_assertPred!"=="(posInfInterval.intersection(NegInfInterval!Date(Date(2012, 1, 6))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 6)));
_assertPred!"=="(posInfInterval.intersection(NegInfInterval!Date(Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)));
_assertPred!"=="(posInfInterval.intersection(NegInfInterval!Date(Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1, 8)));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, posInfInterval.intersection(interval)));
static assert(__traits(compiles, posInfInterval.intersection(cInterval)));
static assert(__traits(compiles, posInfInterval.intersection(iInterval)));
static assert(__traits(compiles, posInfInterval.intersection(posInfInterval)));
static assert(__traits(compiles, posInfInterval.intersection(cPosInfInterval)));
static assert(__traits(compiles, posInfInterval.intersection(iPosInfInterval)));
static assert(__traits(compiles, posInfInterval.intersection(negInfInterval)));
static assert(__traits(compiles, posInfInterval.intersection(cNegInfInterval)));
static assert(__traits(compiles, posInfInterval.intersection(iNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersection(interval)));
static assert(__traits(compiles, cPosInfInterval.intersection(cInterval)));
static assert(__traits(compiles, cPosInfInterval.intersection(iInterval)));
static assert(__traits(compiles, cPosInfInterval.intersection(posInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersection(cPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersection(iPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersection(negInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersection(cNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.intersection(iNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersection(interval)));
static assert(__traits(compiles, iPosInfInterval.intersection(cInterval)));
static assert(__traits(compiles, iPosInfInterval.intersection(iInterval)));
static assert(__traits(compiles, iPosInfInterval.intersection(posInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersection(cPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersection(iPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersection(negInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersection(cNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.intersection(iNegInfInterval)));
//Verify Examples.
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) == Interval!Date(Date(1996, 1 , 2), Date(2000, 8, 2)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) == Interval!Date(Date(1999, 1 , 12), Date(2011, 9, 17)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(PosInfInterval!Date(Date(1990, 7, 6))) == PosInfInterval!Date(Date(1996, 1 , 2)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(PosInfInterval!Date(Date(1999, 1, 12))) == PosInfInterval!Date(Date(1999, 1 , 12)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(NegInfInterval!Date(Date(1999, 7, 6))) == Interval!Date(Date(1996, 1 , 2), Date(1999, 7, 6)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).intersection(NegInfInterval!Date(Date(2013, 1, 12))) == Interval!Date(Date(1996, 1 , 2), Date(2013, 1, 12)));
}
}
//Test PosInfInterval's isAdjacent().
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static void testInterval(in PosInfInterval!Date posInfInterval, in Interval!Date interval)
{
posInfInterval.isAdjacent(interval);
}
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(!posInfInterval.isAdjacent(posInfInterval));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(posInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!posInfInterval.isAdjacent(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!posInfInterval.isAdjacent(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!posInfInterval.isAdjacent(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!posInfInterval.isAdjacent(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!posInfInterval.isAdjacent(PosInfInterval!Date(Date(2012, 1, 6))));
assert(!posInfInterval.isAdjacent(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!posInfInterval.isAdjacent(PosInfInterval!Date(Date(2012, 1, 8))));
assert(!PosInfInterval!Date(Date(2010, 7, 3)).isAdjacent(posInfInterval));
assert(!PosInfInterval!Date(Date(2010, 7, 4)).isAdjacent(posInfInterval));
assert(!PosInfInterval!Date(Date(2010, 7, 5)).isAdjacent(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 6)).isAdjacent(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 7)).isAdjacent(posInfInterval));
assert(!PosInfInterval!Date(Date(2012, 1, 8)).isAdjacent(posInfInterval));
assert(!posInfInterval.isAdjacent(NegInfInterval!Date(Date(2010, 7, 3))));
assert(posInfInterval.isAdjacent(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!posInfInterval.isAdjacent(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!posInfInterval.isAdjacent(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!posInfInterval.isAdjacent(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!posInfInterval.isAdjacent(NegInfInterval!Date(Date(2012, 1, 8))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, posInfInterval.isAdjacent(interval)));
static assert(__traits(compiles, posInfInterval.isAdjacent(cInterval)));
static assert(__traits(compiles, posInfInterval.isAdjacent(iInterval)));
static assert(__traits(compiles, posInfInterval.isAdjacent(posInfInterval)));
static assert(__traits(compiles, posInfInterval.isAdjacent(cPosInfInterval)));
static assert(__traits(compiles, posInfInterval.isAdjacent(iPosInfInterval)));
static assert(__traits(compiles, posInfInterval.isAdjacent(negInfInterval)));
static assert(__traits(compiles, posInfInterval.isAdjacent(cNegInfInterval)));
static assert(__traits(compiles, posInfInterval.isAdjacent(iNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAdjacent(interval)));
static assert(__traits(compiles, cPosInfInterval.isAdjacent(cInterval)));
static assert(__traits(compiles, cPosInfInterval.isAdjacent(iInterval)));
static assert(__traits(compiles, cPosInfInterval.isAdjacent(posInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAdjacent(cPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAdjacent(iPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAdjacent(negInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAdjacent(cNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.isAdjacent(iNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAdjacent(interval)));
static assert(__traits(compiles, iPosInfInterval.isAdjacent(cInterval)));
static assert(__traits(compiles, iPosInfInterval.isAdjacent(iInterval)));
static assert(__traits(compiles, iPosInfInterval.isAdjacent(posInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAdjacent(cPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAdjacent(iPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAdjacent(negInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAdjacent(cNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.isAdjacent(iNegInfInterval)));
//Verify Examples.
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(Interval!Date(Date(1989, 3, 1), Date(1996, 1, 2))));
assert(!PosInfInterval!Date(Date(1999, 1, 12)).isAdjacent(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(PosInfInterval!Date(Date(1990, 1, 7))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(PosInfInterval!Date(Date(1996, 1, 2))));
assert(PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(NegInfInterval!Date(Date(1996, 1, 2))));
assert(!PosInfInterval!Date(Date(1996, 1, 2)).isAdjacent(NegInfInterval!Date(Date(2000, 7, 1))));
}
}
//Test PosInfInterval's merge().
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static void testInterval(in PosInfInterval!Date posInfInterval, in Interval!Date interval)
{
posInfInterval.merge(interval);
}
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
_assertPred!"=="(posInfInterval.merge(posInfInterval),
posInfInterval);
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))),
PosInfInterval!Date(Date(2010, 7, 1)));
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.merge(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.merge(PosInfInterval!Date(Date(2010, 7, 3))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(posInfInterval.merge(PosInfInterval!Date(Date(2010, 7, 4))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.merge(PosInfInterval!Date(Date(2010, 7, 5))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.merge(PosInfInterval!Date(Date(2012, 1, 6))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.merge(PosInfInterval!Date(Date(2012, 1, 7))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.merge(PosInfInterval!Date(Date(2012, 1, 8))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 7, 3)).merge(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 7, 4)).merge(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 7, 5)).merge(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2012, 1, 6)).merge(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2012, 1, 7)).merge(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2012, 1, 8)).merge(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
static assert(!__traits(compiles, posInfInterval.merge(NegInfInterval!Date(Date(2010, 7, 3)))));
static assert(!__traits(compiles, posInfInterval.merge(NegInfInterval!Date(Date(2010, 7, 4)))));
static assert(!__traits(compiles, posInfInterval.merge(NegInfInterval!Date(Date(2010, 7, 5)))));
static assert(!__traits(compiles, posInfInterval.merge(NegInfInterval!Date(Date(2012, 1, 6)))));
static assert(!__traits(compiles, posInfInterval.merge(NegInfInterval!Date(Date(2012, 1, 7)))));
static assert(!__traits(compiles, posInfInterval.merge(NegInfInterval!Date(Date(2012, 1, 8)))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, posInfInterval.merge(interval)));
static assert(__traits(compiles, posInfInterval.merge(cInterval)));
static assert(__traits(compiles, posInfInterval.merge(iInterval)));
static assert(__traits(compiles, posInfInterval.merge(posInfInterval)));
static assert(__traits(compiles, posInfInterval.merge(cPosInfInterval)));
static assert(__traits(compiles, posInfInterval.merge(iPosInfInterval)));
static assert(!__traits(compiles, posInfInterval.merge(negInfInterval)));
static assert(!__traits(compiles, posInfInterval.merge(cNegInfInterval)));
static assert(!__traits(compiles, posInfInterval.merge(iNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.merge(interval)));
static assert(__traits(compiles, cPosInfInterval.merge(cInterval)));
static assert(__traits(compiles, cPosInfInterval.merge(iInterval)));
static assert(__traits(compiles, cPosInfInterval.merge(posInfInterval)));
static assert(__traits(compiles, cPosInfInterval.merge(cPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.merge(iPosInfInterval)));
static assert(!__traits(compiles, cPosInfInterval.merge(negInfInterval)));
static assert(!__traits(compiles, cPosInfInterval.merge(cNegInfInterval)));
static assert(!__traits(compiles, cPosInfInterval.merge(iNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.merge(interval)));
static assert(__traits(compiles, iPosInfInterval.merge(cInterval)));
static assert(__traits(compiles, iPosInfInterval.merge(iInterval)));
static assert(__traits(compiles, iPosInfInterval.merge(posInfInterval)));
static assert(__traits(compiles, iPosInfInterval.merge(cPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.merge(iPosInfInterval)));
static assert(!__traits(compiles, iPosInfInterval.merge(negInfInterval)));
static assert(!__traits(compiles, iPosInfInterval.merge(cNegInfInterval)));
static assert(!__traits(compiles, iPosInfInterval.merge(iNegInfInterval)));
//Verify Examples.
assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) == PosInfInterval!Date(Date(1990, 7 , 6)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) == PosInfInterval!Date(Date(1996, 1 , 2)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(PosInfInterval!Date(Date(1990, 7, 6))) == PosInfInterval!Date(Date(1990, 7 , 6)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).merge(PosInfInterval!Date(Date(1999, 1, 12))) == PosInfInterval!Date(Date(1996, 1 , 2)));
}
}
//Test PosInfInterval's span().
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static void testInterval(in PosInfInterval!Date posInfInterval, in Interval!Date interval)
{
posInfInterval.span(interval);
}
assertThrown!DateTimeException(testInterval(posInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
_assertPred!"=="(posInfInterval.span(posInfInterval),
posInfInterval);
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))),
PosInfInterval!Date(Date(2010, 7, 1)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))),
PosInfInterval!Date(Date(2010, 7, 1)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.span(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.span(PosInfInterval!Date(Date(2010, 7, 3))),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(posInfInterval.span(PosInfInterval!Date(Date(2010, 7, 4))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.span(PosInfInterval!Date(Date(2010, 7, 5))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.span(PosInfInterval!Date(Date(2012, 1, 6))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.span(PosInfInterval!Date(Date(2012, 1, 7))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(posInfInterval.span(PosInfInterval!Date(Date(2012, 1, 8))),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 7, 3)).span(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 7, 4)).span(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 7, 5)).span(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2012, 1, 6)).span(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2012, 1, 7)).span(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(PosInfInterval!Date(Date(2012, 1, 8)).span(posInfInterval),
PosInfInterval!Date(Date(2010, 7, 4)));
static assert(!__traits(compiles, posInfInterval.span(NegInfInterval!Date(Date(2010, 7, 3)))));
static assert(!__traits(compiles, posInfInterval.span(NegInfInterval!Date(Date(2010, 7, 4)))));
static assert(!__traits(compiles, posInfInterval.span(NegInfInterval!Date(Date(2010, 7, 5)))));
static assert(!__traits(compiles, posInfInterval.span(NegInfInterval!Date(Date(2012, 1, 6)))));
static assert(!__traits(compiles, posInfInterval.span(NegInfInterval!Date(Date(2012, 1, 7)))));
static assert(!__traits(compiles, posInfInterval.span(NegInfInterval!Date(Date(2012, 1, 8)))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, posInfInterval.span(interval)));
static assert(__traits(compiles, posInfInterval.span(cInterval)));
static assert(__traits(compiles, posInfInterval.span(iInterval)));
static assert(__traits(compiles, posInfInterval.span(posInfInterval)));
static assert(__traits(compiles, posInfInterval.span(cPosInfInterval)));
static assert(__traits(compiles, posInfInterval.span(iPosInfInterval)));
static assert(!__traits(compiles, posInfInterval.span(negInfInterval)));
static assert(!__traits(compiles, posInfInterval.span(cNegInfInterval)));
static assert(!__traits(compiles, posInfInterval.span(iNegInfInterval)));
static assert(__traits(compiles, cPosInfInterval.span(interval)));
static assert(__traits(compiles, cPosInfInterval.span(cInterval)));
static assert(__traits(compiles, cPosInfInterval.span(iInterval)));
static assert(__traits(compiles, cPosInfInterval.span(posInfInterval)));
static assert(__traits(compiles, cPosInfInterval.span(cPosInfInterval)));
static assert(__traits(compiles, cPosInfInterval.span(iPosInfInterval)));
static assert(!__traits(compiles, cPosInfInterval.span(negInfInterval)));
static assert(!__traits(compiles, cPosInfInterval.span(cNegInfInterval)));
static assert(!__traits(compiles, cPosInfInterval.span(iNegInfInterval)));
static assert(__traits(compiles, iPosInfInterval.span(interval)));
static assert(__traits(compiles, iPosInfInterval.span(cInterval)));
static assert(__traits(compiles, iPosInfInterval.span(iInterval)));
static assert(__traits(compiles, iPosInfInterval.span(posInfInterval)));
static assert(__traits(compiles, iPosInfInterval.span(cPosInfInterval)));
static assert(__traits(compiles, iPosInfInterval.span(iPosInfInterval)));
static assert(!__traits(compiles, iPosInfInterval.span(negInfInterval)));
static assert(!__traits(compiles, iPosInfInterval.span(cNegInfInterval)));
static assert(!__traits(compiles, iPosInfInterval.span(iNegInfInterval)));
//Verify Examples.
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(Interval!Date(Date(500, 8, 9), Date(1602, 1, 31))) == PosInfInterval!Date(Date(500, 8, 9)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) == PosInfInterval!Date(Date(1990, 7 , 6)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))) == PosInfInterval!Date(Date(1996, 1 , 2)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(PosInfInterval!Date(Date(1990, 7, 6))) == PosInfInterval!Date(Date(1990, 7 , 6)));
assert(PosInfInterval!Date(Date(1996, 1, 2)).span(PosInfInterval!Date(Date(1999, 1, 12))) == PosInfInterval!Date(Date(1996, 1 , 2)));
}
}
//Test PosInfInterval's shift().
unittest
{
version(testStdDateTime)
{
auto interval = PosInfInterval!Date(Date(2010, 7, 4));
static void testInterval(I)(I interval, in Duration duration, in I expected, size_t line = __LINE__)
{
interval.shift(duration);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, dur!"days"(22), PosInfInterval!Date(Date(2010, 7, 26)));
testInterval(interval, dur!"days"(-22), PosInfInterval!Date(Date(2010, 6, 12)));
const cInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iInterval = PosInfInterval!Date(Date(2010, 7, 4));
static assert(!__traits(compiles, cInterval.shift(dur!"days"(5))));
static assert(!__traits(compiles, iInterval.shift(dur!"days"(5))));
//Verify Examples.
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));
interval1.shift(dur!"days"(50));
assert(interval1 == PosInfInterval!Date(Date(1996, 2, 21)));
interval2.shift(dur!"days"(-50));
assert(interval2 == PosInfInterval!Date(Date(1995, 11, 13)));
}
}
//Test PosInfInterval's shift(int, int, AllowDayOverflow).
unittest
{
version(testStdDateTime)
{
{
auto interval = PosInfInterval!Date(Date(2010, 7, 4));
static void testInterval(I)(I interval, int years, int months, AllowDayOverflow allow, in I expected, size_t line = __LINE__)
{
interval.shift(years, months, allow);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, 5, 0, AllowDayOverflow.yes, PosInfInterval!Date(Date(2015, 7, 4)));
testInterval(interval, -5, 0, AllowDayOverflow.yes, PosInfInterval!Date(Date(2005, 7, 4)));
auto interval2 = PosInfInterval!Date(Date(2000, 1, 29));
testInterval(interval2, 1, 1, AllowDayOverflow.yes, PosInfInterval!Date(Date(2001, 3, 1)));
testInterval(interval2, 1, -1, AllowDayOverflow.yes, PosInfInterval!Date(Date(2000, 12, 29)));
testInterval(interval2, -1, -1, AllowDayOverflow.yes, PosInfInterval!Date(Date(1998, 12, 29)));
testInterval(interval2, -1, 1, AllowDayOverflow.yes, PosInfInterval!Date(Date(1999, 3, 1)));
testInterval(interval2, 1, 1, AllowDayOverflow.no, PosInfInterval!Date(Date(2001, 2, 28)));
testInterval(interval2, 1, -1, AllowDayOverflow.no, PosInfInterval!Date(Date(2000, 12, 29)));
testInterval(interval2, -1, -1, AllowDayOverflow.no, PosInfInterval!Date(Date(1998, 12, 29)));
testInterval(interval2, -1, 1, AllowDayOverflow.no, PosInfInterval!Date(Date(1999, 2, 28)));
}
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static assert(!__traits(compiles, cPosInfInterval.shift(1)));
static assert(!__traits(compiles, iPosInfInterval.shift(1)));
//Verify Examples.
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));
interval1.shift(2);
assert(interval1 == PosInfInterval!Date(Date(1998, 1, 2)));
interval2.shift(-2);
assert(interval2 == PosInfInterval!Date(Date(1994, 1, 2)));
}
}
//Test PosInfInterval's expand().
unittest
{
version(testStdDateTime)
{
auto interval = PosInfInterval!Date(Date(2000, 7, 4));
static void testInterval(I)(I interval, in Duration duration, in I expected, size_t line = __LINE__)
{
interval.expand(duration);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, dur!"days"(22), PosInfInterval!Date(Date(2000, 6, 12)));
testInterval(interval, dur!"days"(-22), PosInfInterval!Date(Date(2000, 7, 26)));
const cInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iInterval = PosInfInterval!Date(Date(2010, 7, 4));
static assert(!__traits(compiles, cInterval.expand(dur!"days"(5))));
static assert(!__traits(compiles, iInterval.expand(dur!"days"(5))));
//Verify Examples.
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));
interval1.expand(dur!"days"(2));
assert(interval1 == PosInfInterval!Date(Date(1995, 12, 31)));
interval2.expand(dur!"days"(-2));
assert(interval2 == PosInfInterval!Date(Date(1996, 1, 4)));
}
}
//Test PosInfInterval's expand(int, int, AllowDayOverflow).
unittest
{
version(testStdDateTime)
{
{
auto interval = PosInfInterval!Date(Date(2000, 7, 4));
static void testInterval(I)(I interval, int years, int months, AllowDayOverflow allow, in I expected, size_t line = __LINE__)
{
interval.expand(years, months, allow);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, 5, 0, AllowDayOverflow.yes, PosInfInterval!Date(Date(1995, 7, 4)));
testInterval(interval, -5, 0, AllowDayOverflow.yes, PosInfInterval!Date(Date(2005, 7, 4)));
auto interval2 = PosInfInterval!Date(Date(2000, 1, 29));
testInterval(interval2, 1, 1, AllowDayOverflow.yes, PosInfInterval!Date(Date(1998, 12, 29)));
testInterval(interval2, 1, -1, AllowDayOverflow.yes, PosInfInterval!Date(Date(1999, 3, 1)));
testInterval(interval2, -1, -1, AllowDayOverflow.yes, PosInfInterval!Date(Date(2001, 3, 1)));
testInterval(interval2, -1, 1, AllowDayOverflow.yes, PosInfInterval!Date(Date(2000, 12, 29)));
testInterval(interval2, 1, 1, AllowDayOverflow.no, PosInfInterval!Date(Date(1998, 12, 29)));
testInterval(interval2, 1, -1, AllowDayOverflow.no, PosInfInterval!Date(Date(1999, 2, 28)));
testInterval(interval2, -1, -1, AllowDayOverflow.no, PosInfInterval!Date(Date(2001, 2, 28)));
testInterval(interval2, -1, 1, AllowDayOverflow.no, PosInfInterval!Date(Date(2000, 12, 29)));
}
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static assert(!__traits(compiles, cPosInfInterval.expand(1)));
static assert(!__traits(compiles, iPosInfInterval.expand(1)));
//Verify Examples.
auto interval1 = PosInfInterval!Date(Date(1996, 1, 2));
auto interval2 = PosInfInterval!Date(Date(1996, 1, 2));
interval1.expand(2);
assert(interval1 == PosInfInterval!Date(Date(1994, 1, 2)));
interval2.expand(-2);
assert(interval2 == PosInfInterval!Date(Date(1998, 1, 2)));
}
}
//Test PosInfInterval's fwdRange().
unittest
{
version(testStdDateTime)
{
auto posInfInterval = PosInfInterval!Date(Date(2010, 9, 19));
static void testInterval(PosInfInterval!Date posInfInterval)
{
posInfInterval.fwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri)).popFront();
}
assertThrown!DateTimeException(testInterval(posInfInterval));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 9, 12)).fwdRange(everyDayOfWeek!Date(DayOfWeek.fri)).front,
Date(2010, 9, 12));
_assertPred!"=="(PosInfInterval!Date(Date(2010, 9, 12)).fwdRange(everyDayOfWeek!Date(DayOfWeek.fri), PopFirst.yes).front,
Date(2010, 9, 17));
//Verify Examples.
auto interval = PosInfInterval!Date(Date(2010, 9, 1));
auto func = (in Date date)
{
if((date.day & 1) == 0)
return date + dur!"days"(2);
return date + dur!"days"(1);
};
auto range = interval.fwdRange(func);
assert(range.front == Date(2010, 9, 1)); //An odd day. Using PopFirst.yes would have made this Date(2010, 9, 2).
range.popFront();
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.front == Date(2010, 9, 4));
range.popFront();
assert(range.front == Date(2010, 9, 6));
range.popFront();
assert(range.front == Date(2010, 9, 8));
range.popFront();
assert(!range.empty);
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static assert(__traits(compiles, cPosInfInterval.fwdRange(everyDayOfWeek!Date(DayOfWeek.fri))));
static assert(__traits(compiles, iPosInfInterval.fwdRange(everyDayOfWeek!Date(DayOfWeek.fri))));
}
}
//Test PosInfInterval's toString().
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(PosInfInterval!Date(Date(2010, 7, 4)).toString(), "[2010-Jul-04 - ∞)");
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
static assert(__traits(compiles, cPosInfInterval.toString()));
static assert(__traits(compiles, iPosInfInterval.toString()));
}
}
/++
Represents an interval of time which has negative infinity as its starting
point.
Any ranges which iterate over a $(D NegInfInterval) are infinite. So, the
main purpose of using $(D NegInfInterval) is to create an infinite range
which starts at negative infinity and goes to a fixed end point. You would
then iterate over it in reverse.
+/
struct NegInfInterval(TP)
{
public:
/++
Params:
begin = The time point which begins the interval.
Examples:
--------------------
auto interval = PosInfInterval!Date(Date(1996, 1, 2));
--------------------
+/
this(in TP end) pure nothrow
{
_end = cast(TP)end;
}
/++
Params:
rhs = The $(D NegInfInterval) to assign to this one.
+/
/+ref+/ NegInfInterval opAssign(const ref NegInfInterval rhs) pure nothrow
{
_end = cast(TP)rhs._end;
return this;
}
/++
Params:
rhs = The $(D NegInfInterval) to assign to this one.
+/
/+ref+/ NegInfInterval opAssign(NegInfInterval rhs) pure nothrow
{
_end = cast(TP)rhs._end;
return this;
}
/++
The end point of the interval. It is excluded from the interval.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).end == Date(2012, 3, 1));
--------------------
+/
@property TP end() const pure nothrow
{
return cast(TP)_end;
}
/++
The end point of the interval. It is excluded from the interval.
Params:
timePoint = The time point to set end to.
+/
@property void end(TP timePoint) pure nothrow
{
_end = timePoint;
}
/++
Whether the interval's length is 0. Always returns false.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(1996, 1, 2)).empty);
--------------------
+/
@property bool empty() const pure nothrow
{
return false;
}
/++
Whether the given time point is within this interval.
Params:
timePoint = The time point to check for inclusion in this interval.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(Date(1994, 12, 24)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(Date(2000, 1, 5)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(Date(2012, 3, 1)));
--------------------
+/
bool contains(TP timePoint) const pure nothrow
{
return timePoint < _end;
}
/++
Whether the given interval is completely within this interval.
Params:
interval = The interval to check for inclusion in this interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(
Interval!Date(Date(1998, 2, 28), Date(2013, 5, 1))));
--------------------
+/
bool contains(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return interval._end <= _end;
}
/++
Whether the given interval is completely within this interval.
Always returns false because an interval beginning at negative
infinity can never contain an interval going to positive infinity.
Params:
interval = The interval to check for inclusion in this interval.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(
PosInfInterval!Date(Date(1999, 5, 4))));
--------------------
+/
bool contains(in PosInfInterval!TP interval) const pure nothrow
{
return false;
}
/++
Whether the given interval is completely within this interval.
Params:
interval = The interval to check for inclusion in this interval.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(
NegInfInterval!Date(Date(1996, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(
NegInfInterval!Date(Date(2013, 7, 9))));
--------------------
+/
bool contains(in NegInfInterval interval) const pure nothrow
{
return interval._end <= _end;
}
/++
Whether this interval is before the given time point.
Params:
timePoint = The time point to check whether this interval is
before it.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Date(1994, 12, 24)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Date(2000, 1, 5)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Date(2012, 3, 1)));
--------------------
+/
bool isBefore(in TP timePoint) const pure nothrow
{
return timePoint >= _end;
}
/++
Whether this interval is before the given interval and does not
intersect it.
Params:
interval = The interval to check for against this interval.
Throws:
$(D DateTimeException) if the given interval is empty
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));
--------------------
+/
bool isBefore(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return _end <= interval._begin;
}
/++
Whether this interval is before the given interval and does not
intersect it.
Params:
interval = The interval to check for against this interval.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
PosInfInterval!Date(Date(1999, 5, 4))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
PosInfInterval!Date(Date(2012, 3, 1))));
--------------------
+/
bool isBefore(in PosInfInterval!TP interval) const pure nothrow
{
return _end <= interval._begin;
}
/++
Whether this interval is before the given interval and does not
intersect it.
Always returns false because an interval beginning at negative
infinity can never be before another interval beginning at negative
infinity.
Params:
interval = The interval to check for against this interval.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
NegInfInterval!Date(Date(1996, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(
NegInfInterval!Date(Date(2013, 7, 9))));
--------------------
+/
bool isBefore(in NegInfInterval interval) const pure nothrow
{
return false;
}
/++
Whether this interval is after the given time point.
Always returns false because an interval beginning at negative infinity
can never be after any time point.
Params:
timePoint = The time point to check whether this interval is after
it.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Date(1994, 12, 24)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Date(2000, 1, 5)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Date(2012, 3, 1)));
--------------------
+/
bool isAfter(in TP timePoint) const pure nothrow
{
return false;
}
/++
Whether this interval is after the given interval and does not
intersect it.
Always returns false (unless the given interval is empty) because an
interval beginning at negative infinity can never be after any other
interval.
Params:
interval = The interval to check against this interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));
--------------------
+/
bool isAfter(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return false;
}
/++
Whether this interval is after the given interval and does not intersect
it.
Always returns false because an interval beginning at negative infinity
can never be after any other interval.
Params:
interval = The interval to check against this interval.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
PosInfInterval!Date(Date(1999, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
PosInfInterval!Date(Date(2012, 3, 1))));
--------------------
+/
bool isAfter(in PosInfInterval!TP interval) const pure nothrow
{
return false;
}
/++
Whether this interval is after the given interval and does not intersect
it.
Always returns false because an interval beginning at negative infinity
can never be after any other interval.
Params:
interval = The interval to check against this interval.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
NegInfInterval!Date(Date(1996, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(
NegInfInterval!Date(Date(2013, 7, 9))));
--------------------
+/
bool isAfter(in NegInfInterval interval) const pure nothrow
{
return false;
}
/++
Whether the given interval overlaps this interval.
Params:
interval = The interval to check for intersection with this interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(
Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).intersects(
Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));
--------------------
+/
bool intersects(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return interval._begin < _end;
}
/++
Whether the given interval overlaps this interval.
Params:
interval = The interval to check for intersection with this
interval.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(
PosInfInterval!Date(Date(1999, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).intersects(
PosInfInterval!Date(Date(2012, 3, 1))));
--------------------
+/
bool intersects(in PosInfInterval!TP interval) const pure nothrow
{
return interval._begin < _end;
}
/++
Whether the given interval overlaps this interval.
Always returns true because two intervals beginning at negative infinity
always overlap.
Params:
interval = The interval to check for intersection with this interval.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(
NegInfInterval!Date(Date(1996, 5, 4))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(
NegInfInterval!Date(Date(2013, 7, 9))));
--------------------
+/
bool intersects(in NegInfInterval!TP interval) const pure nothrow
{
return true;
}
/++
Returns the intersection of two intervals
Params:
interval = The interval to intersect with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect or if
the given interval is empty.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
Interval!Date(Date(1990, 7 , 6), Date(2000, 8, 2)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
Interval!Date(Date(1999, 1, 12), Date(2015, 9, 2))) ==
Interval!Date(Date(1999, 1 , 12), Date(2012, 3, 1)));
--------------------
+/
Interval!TP intersection(in Interval!TP interval) const
{
enforce(this.intersects(interval), new DateTimeException(format("%s and %s do not intersect.", this, interval)));
auto end = _end < interval._end ? _end : interval._end;
return Interval!TP(interval._begin, end);
}
/++
Returns the intersection of two intervals
Params:
interval = The interval to intersect with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
PosInfInterval!Date(Date(1990, 7, 6))) ==
Interval!Date(Date(1990, 7 , 6), Date(2012, 3, 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
PosInfInterval!Date(Date(1999, 1, 12))) ==
Interval!Date(Date(1999, 1 , 12), Date(2012, 3, 1)));
--------------------
+/
Interval!TP intersection(in PosInfInterval!TP interval) const
{
enforce(this.intersects(interval), new DateTimeException(format("%s and %s do not intersect.", this, interval)));
return Interval!TP(interval._begin, _end);
}
/++
Returns the intersection of two intervals
Params:
interval = The interval to intersect with this interval.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
NegInfInterval!Date(Date(1999, 7, 6))) ==
NegInfInterval!Date(Date(1999, 7 , 6)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(
NegInfInterval!Date(Date(2013, 1, 12))) ==
NegInfInterval!Date(Date(2012, 3 , 1)));
--------------------
+/
NegInfInterval intersection(in NegInfInterval interval) const nothrow
{
return NegInfInterval(_end < interval._end ? _end : interval._end);
}
/++
Whether the given interval is adjacent to this interval.
Params:
interval = The interval to check whether its adjecent to this
interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
Interval!Date(Date(1999, 1, 12), Date(2012, 3, 1))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
Interval!Date(Date(2012, 3, 1), Date(2019, 2, 2))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));
--------------------
+/
bool isAdjacent(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return interval._begin == _end;
}
/++
Whether the given interval is adjacent to this interval.
Params:
interval = The interval to check whether its adjecent to this
interval.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
PosInfInterval!Date(Date(1999, 5, 4))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
PosInfInterval!Date(Date(2012, 3, 1))));
--------------------
+/
bool isAdjacent(in PosInfInterval!TP interval) const pure nothrow
{
return interval._begin == _end;
}
/++
Whether the given interval is adjacent to this interval.
Always returns false because two intervals beginning at negative
infinity can never be adjacent to one another.
Params:
interval = The interval to check whether its adjecent to this
interval.
Examples:
--------------------
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
NegInfInterval!Date(Date(1996, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(
NegInfInterval!Date(Date(2012, 3, 1))));
--------------------
+/
bool isAdjacent(in NegInfInterval interval) const pure nothrow
{
return false;
}
/++
Returns the union of two intervals
Params:
interval = The interval to merge with this interval.
Throws:
$(D DateTimeException) if the two intervals do not intersect and are
not adjacent or if the given interval is empty.
Note:
There is no overload for $(D merge) which takes a
$(D PosInfInterval). This is because you can't have an interval
which goes from negative infinity to positive infinity.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
NegInfInterval!Date(Date(2012, 3 , 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(
Interval!Date(Date(1999, 1, 12), Date(2015, 9, 2))) ==
NegInfInterval!Date(Date(2015, 9 , 2)));
--------------------
+/
NegInfInterval merge(in Interval!TP interval) const
{
enforce(this.isAdjacent(interval) || this.intersects(interval),
new DateTimeException(format("%s and %s are not adjacent and do not intersect.", this, interval)));
return NegInfInterval(_end > interval._end ? _end : interval._end);
}
/++
Returns the union of two intervals
Params:
interval = The interval to merge with this interval.
Note:
There is no overload for $(D merge) which takes a
$(D PosInfInterval). This is because you can't have an interval
which goes from negative infinity to positive infinity.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(
NegInfInterval!Date(Date(1999, 7, 6))) ==
NegInfInterval!Date(Date(2012, 3 , 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(
NegInfInterval!Date(Date(2013, 1, 12))) ==
NegInfInterval!Date(Date(2013, 1 , 12)));
--------------------
+/
NegInfInterval merge(in NegInfInterval interval) const pure nothrow
{
return NegInfInterval(_end > interval._end ? _end : interval._end);
}
/++
Returns an interval that covers from the earliest time point of two
intervals up to (but not including) the latest time point of two
intervals.
Params:
interval = The interval to create a span together with this
interval.
Throws:
$(D DateTimeException) if the given interval is empty.
Note:
There is no overload for $(D span) which takes a
$(D PosInfInterval). This is because you can't have an interval
which goes from negative infinity to positive infinity.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).span(
Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) ==
NegInfInterval!Date(Date(2012, 3 , 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).span(
Interval!Date(Date(1999, 1, 12), Date(2015, 9, 2))) ==
NegInfInterval!Date(Date(2015, 9 , 2)));
assert(NegInfInterval!Date(Date(1600, 1, 7)).span(
Interval!Date(Date(2012, 3, 11), Date(2017, 7, 1))) ==
NegInfInterval!Date(Date(2017, 7 , 1)));
--------------------
+/
NegInfInterval span(in Interval!TP interval) const pure
{
interval._enforceNotEmpty();
return NegInfInterval(_end > interval._end ? _end : interval._end);
}
/++
Returns an interval that covers from the earliest time point of two
intervals up to (but not including) the latest time point of two
intervals.
Params:
interval = The interval to create a span together with this
interval.
Note:
There is no overload for $(D span) which takes a
$(D PosInfInterval). This is because you can't have an interval
which goes from negative infinity to positive infinity.
Examples:
--------------------
assert(NegInfInterval!Date(Date(2012, 3, 1)).span(
NegInfInterval!Date(Date(1999, 7, 6))) ==
NegInfInterval!Date(Date(2012, 3 , 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).span(
NegInfInterval!Date(Date(2013, 1, 12))) ==
NegInfInterval!Date(Date(2013, 1 , 12)));
--------------------
+/
NegInfInterval span(in NegInfInterval interval) const pure nothrow
{
return NegInfInterval(_end > interval._end ? _end : interval._end);
}
/++
Shifts the $(D end) of this interval forward or backwards in time by the
given duration (a positive duration shifts the interval forward; a
negative duration shifts it backward). Effectively, it does
$(D end += duration).
Params:
duration = The duration to shift the interval by.
Examples:
--------------------
auto interval1 = NegInfInterval!Date(Date(2012, 4, 5));
auto interval2 = NegInfInterval!Date(Date(2012, 4, 5));
interval1.shift(dur!"days"(50));
assert(interval1 == NegInfInterval!Date(Date(2012, 5, 25)));
interval2.shift(dur!"days"(-50));
assert(interval2 == NegInfInterval!Date( Date(2012, 2, 15)));
--------------------
+/
void shift(D)(D duration) pure nothrow
if(__traits(compiles, end + duration))
{
_end += duration;
}
static if(__traits(compiles, end.add!"months"(1)) &&
__traits(compiles, end.add!"years"(1)))
{
/++
Shifts the $(D end) of this interval forward or backwards in time by
the given number of years and/or months (a positive number of years
and months shifts the interval forward; a negative number shifts it
backward). It adds the years the given years and months to end. It
effectively calls $(D add!"years"()) and then $(D add!"months"())
on end with the given number of years and months.
Params:
years = The number of years to shift the interval by.
months = The number of months to shift the interval by.
allowOverflow = Whether the days should be allowed to overflow
on $(D end), causing its month to increment.
Throws:
$(D DateTimeException) if empty is true or if the resulting
interval would be invalid.
Examples:
--------------------
auto interval1 = NegInfInterval!Date(Date(2012, 3, 1));
auto interval2 = NegInfInterval!Date(Date(2012, 3, 1));
interval1.shift(2);
assert(interval1 == NegInfInterval!Date(Date(2014, 3, 1)));
interval2.shift(-2);
assert(interval2 == NegInfInterval!Date(Date(2010, 3, 1)));
--------------------
+/
void shift(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)
if(isIntegral!T)
{
auto end = _end;
end.add!"years"(years, allowOverflow);
end.add!"months"(months, allowOverflow);
_end = end;
}
}
/++
Expands the interval forwards in time. Effectively, it does
$(D end += duration).
Params:
duration = The duration to expand the interval by.
dir = The direction in time to expand the interval.
Examples:
--------------------
auto interval1 = NegInfInterval!Date(Date(2012, 3, 1));
auto interval2 = NegInfInterval!Date(Date(2012, 3, 1));
interval1.expand(dur!"days"(2));
assert(interval1 == NegInfInterval!Date(Date(2012, 3, 3)));
interval2.expand(dur!"days"(-2));
assert(interval2 == NegInfInterval!Date(Date(2012, 2, 28)));
--------------------
+/
void expand(D)(D duration) pure nothrow
if(__traits(compiles, end + duration))
{
_end += duration;
}
static if(__traits(compiles, end.add!"months"(1)) &&
__traits(compiles, end.add!"years"(1)))
{
/++
Expands the interval forwards and/or backwards in time. Effectively,
it adds the given number of months/years to end.
Params:
years = The number of years to expand the interval by.
months = The number of months to expand the interval by.
allowOverflow = Whether the days should be allowed to overflow
on $(D end), causing their month to increment.
Throws:
$(D DateTimeException) if empty is true or if the resulting
interval would be invalid.
Examples:
--------------------
auto interval1 = NegInfInterval!Date(Date(2012, 3, 1));
auto interval2 = NegInfInterval!Date(Date(2012, 3, 1));
interval1.expand(2);
assert(interval1 == NegInfInterval!Date(Date(2014, 3, 1)));
interval2.expand(-2);
assert(interval2 == NegInfInterval!Date(Date(2010, 3, 1)));
--------------------
+/
void expand(T)(T years, T months = 0, AllowDayOverflow allowOverflow = AllowDayOverflow.yes)
if(isIntegral!T)
{
auto end = _end;
end.add!"years"(years, allowOverflow);
end.add!"months"(months, allowOverflow);
_end = end;
return;
}
}
/++
Returns a range which iterates backwards over the interval, starting
at $(D end), using $(D_PARAM func) to generate each successive time
point.
The range's $(D front) is the interval's $(D end). $(D_PARAM func) is
used to generate the next $(D front) when $(D popFront) is called. If
$(D_PARAM popFirst) is $(D PopFirst.yes), then $(D popFront) is called
before the range is returned (so that $(D front) is a time point which
$(D_PARAM func) would generate).
If $(D_PARAM func) ever generates a time point greater than or equal to
the current $(D front) of the range, then a $(D DateTimeException) will
be thrown.
There are helper functions in this module which generate common
delegates to pass to $(D bwdRange). Their documentation starts with
"Range-generating function," so you can easily search for them.
Params:
func = The function used to generate the time points of the
range over the interval.
popFirst = Whether $(D popFront) should be called on the range
before returning it.
Throws:
$(D DateTimeException) if this interval is empty.
Warning:
$(D_PARAM func) must be logically pure. Ideally, $(D_PARAM func)
would be a function pointer to a pure function, but forcing
$(D_PARAM func) to be pure is far too restrictive to be useful, and
in order to have the ease of use of having functions which generate
functions to pass to $(D fwdRange), $(D_PARAM func) must be a
delegate.
If $(D_PARAM func) retains state which changes as it is called, then
some algorithms will not work correctly, because the range's
$(D save) will have failed to have really saved the range's state.
So, if you want to avoid such bugs, don't pass a delegate which is
not logically pure to $(D fwdRange). If $(D_PARAM func) is given the
same time point with two different calls, it must return the same
result both times.
Of course, none of the functions in this module have this problem,
so it's only relevant if you're creating your own delegate.
Examples:
--------------------
auto interval = NegInfInterval!Date(Date(2010, 9, 9));
auto func = (in Date date) //For iterating over even-numbered days.
{
if((date.day & 1) == 0)
return date - dur!"days"(2);
return date - dur!"days"(1);
};
auto range = interval.bwdRange(func);
assert(range.front == Date(2010, 9, 9)); //An odd day. Using PopFirst.yes would have made this Date(2010, 9, 8).
range.popFront();
assert(range.front == Date(2010, 9, 8));
range.popFront();
assert(range.front == Date(2010, 9, 6));
range.popFront();
assert(range.front == Date(2010, 9, 4));
range.popFront();
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(!range.empty);
--------------------
+/
NegInfIntervalRange!(TP) bwdRange(TP delegate(in TP) func, PopFirst popFirst = PopFirst.no) const
{
auto range = NegInfIntervalRange!(TP)(this, func);
if(popFirst == PopFirst.yes)
range.popFront();
return range;
}
/+
Converts this interval to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString()
{
return _toStringImpl();
}
/++
Converts this interval to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString() const nothrow
{
return _toStringImpl();
}
private:
/+
Since we have two versions of toString(), we have _toStringImpl()
so that they can share implementations.
+/
string _toStringImpl() const nothrow
{
try
return format("[-∞ - %s)", _end);
catch(Exception e)
assert(0, "format() threw.");
}
TP _end;
}
//Test NegInfInterval's constructor.
unittest
{
version(testStdDateTime)
{
NegInfInterval!Date(Date.init);
NegInfInterval!TimeOfDay(TimeOfDay.init);
NegInfInterval!DateTime(DateTime.init);
NegInfInterval!SysTime(SysTime(0));
}
}
//Test NegInfInterval's end.
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(NegInfInterval!Date(Date(2010, 1, 1)).end, Date(2010, 1, 1));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 1, 1)).end, Date(2010, 1, 1));
_assertPred!"=="(NegInfInterval!Date(Date(1998, 1, 1)).end, Date(1998, 1, 1));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, cNegInfInterval.end));
static assert(__traits(compiles, iNegInfInterval.end));
//Verify Examples.
assert(NegInfInterval!Date(Date(2012, 3, 1)).end == Date(2012, 3, 1));
}
}
//Test NegInfInterval's empty.
unittest
{
version(testStdDateTime)
{
assert(!NegInfInterval!Date(Date(2010, 1, 1)).empty);
assert(!NegInfInterval!TimeOfDay(TimeOfDay(0, 30, 0)).empty);
assert(!NegInfInterval!DateTime(DateTime(2010, 1, 1, 0, 30, 0)).empty);
assert(!NegInfInterval!SysTime(SysTime(DateTime(2010, 1, 1, 0, 30, 0))).empty);
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, cNegInfInterval.empty));
static assert(__traits(compiles, iNegInfInterval.empty));
//Verify Examples.
assert(!NegInfInterval!Date(Date(1996, 1, 2)).empty);
}
}
//Test NegInfInterval's contains(time point).
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
assert(negInfInterval.contains(Date(2009, 7, 4)));
assert(negInfInterval.contains(Date(2010, 7, 3)));
assert(negInfInterval.contains(Date(2010, 7, 4)));
assert(negInfInterval.contains(Date(2010, 7, 5)));
assert(negInfInterval.contains(Date(2011, 7, 1)));
assert(negInfInterval.contains(Date(2012, 1, 6)));
assert(!negInfInterval.contains(Date(2012, 1, 7)));
assert(!negInfInterval.contains(Date(2012, 1, 8)));
assert(!negInfInterval.contains(Date(2013, 1, 7)));
const cdate = Date(2010, 7, 6);
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.contains(cdate)));
static assert(__traits(compiles, cNegInfInterval.contains(cdate)));
static assert(__traits(compiles, iNegInfInterval.contains(cdate)));
//Verify Examples.
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(Date(1994, 12, 24)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(Date(2000, 1, 5)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(Date(2012, 3, 1)));
}
}
//Test NegInfInterval's contains(Interval).
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(in NegInfInterval!Date negInfInterval, in Interval!Date interval)
{
negInfInterval.contains(interval);
}
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(negInfInterval.contains(negInfInterval));
assert(negInfInterval.contains(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!negInfInterval.contains(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(negInfInterval.contains(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(negInfInterval.contains(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(negInfInterval.contains(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!negInfInterval.contains(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(negInfInterval.contains(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(negInfInterval.contains(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(negInfInterval.contains(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!negInfInterval.contains(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(!negInfInterval.contains(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!negInfInterval.contains(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(negInfInterval.contains(NegInfInterval!Date(Date(2010, 7, 3))));
assert(negInfInterval.contains(NegInfInterval!Date(Date(2010, 7, 4))));
assert(negInfInterval.contains(NegInfInterval!Date(Date(2010, 7, 5))));
assert(negInfInterval.contains(NegInfInterval!Date(Date(2012, 1, 6))));
assert(negInfInterval.contains(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!negInfInterval.contains(NegInfInterval!Date(Date(2012, 1, 8))));
assert(!NegInfInterval!Date(Date(2010, 7, 3)).contains(negInfInterval));
assert(!NegInfInterval!Date(Date(2010, 7, 4)).contains(negInfInterval));
assert(!NegInfInterval!Date(Date(2010, 7, 5)).contains(negInfInterval));
assert(!NegInfInterval!Date(Date(2012, 1, 6)).contains(negInfInterval));
assert(NegInfInterval!Date(Date(2012, 1, 7)).contains(negInfInterval));
assert(NegInfInterval!Date(Date(2012, 1, 8)).contains(negInfInterval));
assert(!negInfInterval.contains(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!negInfInterval.contains(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!negInfInterval.contains(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!negInfInterval.contains(PosInfInterval!Date(Date(2012, 1, 6))));
assert(!negInfInterval.contains(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!negInfInterval.contains(PosInfInterval!Date(Date(2012, 1, 8))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.contains(interval)));
static assert(__traits(compiles, negInfInterval.contains(cInterval)));
static assert(__traits(compiles, negInfInterval.contains(iInterval)));
static assert(__traits(compiles, negInfInterval.contains(posInfInterval)));
static assert(__traits(compiles, negInfInterval.contains(cPosInfInterval)));
static assert(__traits(compiles, negInfInterval.contains(iPosInfInterval)));
static assert(__traits(compiles, negInfInterval.contains(negInfInterval)));
static assert(__traits(compiles, negInfInterval.contains(cNegInfInterval)));
static assert(__traits(compiles, negInfInterval.contains(iNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.contains(interval)));
static assert(__traits(compiles, cNegInfInterval.contains(cInterval)));
static assert(__traits(compiles, cNegInfInterval.contains(iInterval)));
static assert(__traits(compiles, cNegInfInterval.contains(posInfInterval)));
static assert(__traits(compiles, cNegInfInterval.contains(cPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.contains(iPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.contains(negInfInterval)));
static assert(__traits(compiles, cNegInfInterval.contains(cNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.contains(iNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.contains(interval)));
static assert(__traits(compiles, iNegInfInterval.contains(cInterval)));
static assert(__traits(compiles, iNegInfInterval.contains(iInterval)));
static assert(__traits(compiles, iNegInfInterval.contains(posInfInterval)));
static assert(__traits(compiles, iNegInfInterval.contains(cPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.contains(iPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.contains(negInfInterval)));
static assert(__traits(compiles, iNegInfInterval.contains(cNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.contains(iNegInfInterval)));
//Verify Examples.
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(Interval!Date(Date(1998, 2, 28), Date(2013, 5, 1))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(PosInfInterval!Date(Date(1999, 5, 4))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).contains(NegInfInterval!Date(Date(1996, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).contains(NegInfInterval!Date(Date(2013, 7, 9))));
}
}
//Test NegInfInterval's isBefore(time point).
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
assert(!negInfInterval.isBefore(Date(2009, 7, 4)));
assert(!negInfInterval.isBefore(Date(2010, 7, 3)));
assert(!negInfInterval.isBefore(Date(2010, 7, 4)));
assert(!negInfInterval.isBefore(Date(2010, 7, 5)));
assert(!negInfInterval.isBefore(Date(2011, 7, 1)));
assert(!negInfInterval.isBefore(Date(2012, 1, 6)));
assert(negInfInterval.isBefore(Date(2012, 1, 7)));
assert(negInfInterval.isBefore(Date(2012, 1, 8)));
assert(negInfInterval.isBefore(Date(2013, 1, 7)));
const cdate = Date(2010, 7, 6);
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.isBefore(cdate)));
static assert(__traits(compiles, cNegInfInterval.isBefore(cdate)));
static assert(__traits(compiles, iNegInfInterval.isBefore(cdate)));
//Verify Examples.
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Date(1994, 12, 24)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Date(2000, 1, 5)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Date(2012, 3, 1)));
}
}
//Test NegInfInterval's isBefore(Interval).
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(in NegInfInterval!Date negInfInterval, in Interval!Date interval)
{
negInfInterval.isBefore(interval);
}
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(!negInfInterval.isBefore(negInfInterval));
assert(!negInfInterval.isBefore(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!negInfInterval.isBefore(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(!negInfInterval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!negInfInterval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!negInfInterval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!negInfInterval.isBefore(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(!negInfInterval.isBefore(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(!negInfInterval.isBefore(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(!negInfInterval.isBefore(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!negInfInterval.isBefore(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(negInfInterval.isBefore(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(negInfInterval.isBefore(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!negInfInterval.isBefore(NegInfInterval!Date(Date(2010, 7, 3))));
assert(!negInfInterval.isBefore(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!negInfInterval.isBefore(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!negInfInterval.isBefore(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!negInfInterval.isBefore(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!negInfInterval.isBefore(NegInfInterval!Date(Date(2012, 1, 8))));
assert(!NegInfInterval!Date(Date(2010, 7, 3)).isBefore(negInfInterval));
assert(!NegInfInterval!Date(Date(2010, 7, 4)).isBefore(negInfInterval));
assert(!NegInfInterval!Date(Date(2010, 7, 5)).isBefore(negInfInterval));
assert(!NegInfInterval!Date(Date(2012, 1, 6)).isBefore(negInfInterval));
assert(!NegInfInterval!Date(Date(2012, 1, 7)).isBefore(negInfInterval));
assert(!NegInfInterval!Date(Date(2012, 1, 8)).isBefore(negInfInterval));
assert(!negInfInterval.isBefore(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!negInfInterval.isBefore(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!negInfInterval.isBefore(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!negInfInterval.isBefore(PosInfInterval!Date(Date(2012, 1, 6))));
assert(negInfInterval.isBefore(PosInfInterval!Date(Date(2012, 1, 7))));
assert(negInfInterval.isBefore(PosInfInterval!Date(Date(2012, 1, 8))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.isBefore(interval)));
static assert(__traits(compiles, negInfInterval.isBefore(cInterval)));
static assert(__traits(compiles, negInfInterval.isBefore(iInterval)));
static assert(__traits(compiles, negInfInterval.isBefore(posInfInterval)));
static assert(__traits(compiles, negInfInterval.isBefore(cPosInfInterval)));
static assert(__traits(compiles, negInfInterval.isBefore(iPosInfInterval)));
static assert(__traits(compiles, negInfInterval.isBefore(negInfInterval)));
static assert(__traits(compiles, negInfInterval.isBefore(cNegInfInterval)));
static assert(__traits(compiles, negInfInterval.isBefore(iNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isBefore(interval)));
static assert(__traits(compiles, cNegInfInterval.isBefore(cInterval)));
static assert(__traits(compiles, cNegInfInterval.isBefore(iInterval)));
static assert(__traits(compiles, cNegInfInterval.isBefore(posInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isBefore(cPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isBefore(iPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isBefore(negInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isBefore(cNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isBefore(iNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isBefore(interval)));
static assert(__traits(compiles, iNegInfInterval.isBefore(cInterval)));
static assert(__traits(compiles, iNegInfInterval.isBefore(iInterval)));
static assert(__traits(compiles, iNegInfInterval.isBefore(posInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isBefore(cPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isBefore(iPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isBefore(negInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isBefore(cNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isBefore(iNegInfInterval)));
//Verify Examples.
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isBefore(Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(PosInfInterval!Date(Date(1999, 5, 4))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isBefore(PosInfInterval!Date(Date(2012, 3, 1))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(NegInfInterval!Date(Date(1996, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isBefore(NegInfInterval!Date(Date(2013, 7, 9))));
}
}
//Test NegInfInterval's isAfter(time point).
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
assert(!negInfInterval.isAfter(Date(2009, 7, 4)));
assert(!negInfInterval.isAfter(Date(2010, 7, 3)));
assert(!negInfInterval.isAfter(Date(2010, 7, 4)));
assert(!negInfInterval.isAfter(Date(2010, 7, 5)));
assert(!negInfInterval.isAfter(Date(2011, 7, 1)));
assert(!negInfInterval.isAfter(Date(2012, 1, 6)));
assert(!negInfInterval.isAfter(Date(2012, 1, 7)));
assert(!negInfInterval.isAfter(Date(2012, 1, 8)));
assert(!negInfInterval.isAfter(Date(2013, 1, 7)));
const cdate = Date(2010, 7, 6);
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.isAfter(cdate)));
static assert(__traits(compiles, cNegInfInterval.isAfter(cdate)));
static assert(__traits(compiles, iNegInfInterval.isAfter(cdate)));
}
}
//Test NegInfInterval's isAfter(Interval).
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(in NegInfInterval!Date negInfInterval, in Interval!Date interval)
{
negInfInterval.isAfter(interval);
}
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(!negInfInterval.isAfter(negInfInterval));
assert(!negInfInterval.isAfter(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!negInfInterval.isAfter(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!negInfInterval.isAfter(NegInfInterval!Date(Date(2010, 7, 3))));
assert(!negInfInterval.isAfter(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!negInfInterval.isAfter(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!negInfInterval.isAfter(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!negInfInterval.isAfter(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!negInfInterval.isAfter(NegInfInterval!Date(Date(2012, 1, 8))));
assert(!NegInfInterval!Date(Date(2010, 7, 3)).isAfter(negInfInterval));
assert(!NegInfInterval!Date(Date(2010, 7, 4)).isAfter(negInfInterval));
assert(!NegInfInterval!Date(Date(2010, 7, 5)).isAfter(negInfInterval));
assert(!NegInfInterval!Date(Date(2012, 1, 6)).isAfter(negInfInterval));
assert(!NegInfInterval!Date(Date(2012, 1, 7)).isAfter(negInfInterval));
assert(!NegInfInterval!Date(Date(2012, 1, 8)).isAfter(negInfInterval));
assert(!negInfInterval.isAfter(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!negInfInterval.isAfter(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!negInfInterval.isAfter(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!negInfInterval.isAfter(PosInfInterval!Date(Date(2012, 1, 6))));
assert(!negInfInterval.isAfter(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!negInfInterval.isAfter(PosInfInterval!Date(Date(2012, 1, 8))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.isAfter(interval)));
static assert(__traits(compiles, negInfInterval.isAfter(cInterval)));
static assert(__traits(compiles, negInfInterval.isAfter(iInterval)));
static assert(__traits(compiles, negInfInterval.isAfter(posInfInterval)));
static assert(__traits(compiles, negInfInterval.isAfter(cPosInfInterval)));
static assert(__traits(compiles, negInfInterval.isAfter(iPosInfInterval)));
static assert(__traits(compiles, negInfInterval.isAfter(negInfInterval)));
static assert(__traits(compiles, negInfInterval.isAfter(cNegInfInterval)));
static assert(__traits(compiles, negInfInterval.isAfter(iNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAfter(interval)));
static assert(__traits(compiles, cNegInfInterval.isAfter(cInterval)));
static assert(__traits(compiles, cNegInfInterval.isAfter(iInterval)));
static assert(__traits(compiles, cNegInfInterval.isAfter(posInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAfter(cPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAfter(iPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAfter(negInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAfter(cNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAfter(iNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAfter(interval)));
static assert(__traits(compiles, iNegInfInterval.isAfter(cInterval)));
static assert(__traits(compiles, iNegInfInterval.isAfter(iInterval)));
static assert(__traits(compiles, iNegInfInterval.isAfter(posInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAfter(cPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAfter(iPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAfter(negInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAfter(cNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAfter(iNegInfInterval)));
//Verify Examples.
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Date(1994, 12, 24)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Date(2000, 1, 5)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Date(2012, 3, 1)));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(PosInfInterval!Date(Date(1999, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(PosInfInterval!Date(Date(2012, 3, 1))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(NegInfInterval!Date(Date(1996, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAfter(NegInfInterval!Date(Date(2013, 7, 9))));
}
}
//Test NegInfInterval's intersects().
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(in NegInfInterval!Date negInfInterval, in Interval!Date interval)
{
negInfInterval.intersects(interval);
}
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(negInfInterval.intersects(negInfInterval));
assert(negInfInterval.intersects(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(negInfInterval.intersects(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(negInfInterval.intersects(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(negInfInterval.intersects(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(negInfInterval.intersects(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(negInfInterval.intersects(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(negInfInterval.intersects(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(negInfInterval.intersects(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(negInfInterval.intersects(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(negInfInterval.intersects(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(!negInfInterval.intersects(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!negInfInterval.intersects(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(negInfInterval.intersects(NegInfInterval!Date(Date(2010, 7, 3))));
assert(negInfInterval.intersects(NegInfInterval!Date(Date(2010, 7, 4))));
assert(negInfInterval.intersects(NegInfInterval!Date(Date(2010, 7, 5))));
assert(negInfInterval.intersects(NegInfInterval!Date(Date(2012, 1, 6))));
assert(negInfInterval.intersects(NegInfInterval!Date(Date(2012, 1, 7))));
assert(negInfInterval.intersects(NegInfInterval!Date(Date(2012, 1, 8))));
assert(NegInfInterval!Date(Date(2010, 7, 3)).intersects(negInfInterval));
assert(NegInfInterval!Date(Date(2010, 7, 4)).intersects(negInfInterval));
assert(NegInfInterval!Date(Date(2010, 7, 5)).intersects(negInfInterval));
assert(NegInfInterval!Date(Date(2012, 1, 6)).intersects(negInfInterval));
assert(NegInfInterval!Date(Date(2012, 1, 7)).intersects(negInfInterval));
assert(NegInfInterval!Date(Date(2012, 1, 8)).intersects(negInfInterval));
assert(negInfInterval.intersects(PosInfInterval!Date(Date(2010, 7, 3))));
assert(negInfInterval.intersects(PosInfInterval!Date(Date(2010, 7, 4))));
assert(negInfInterval.intersects(PosInfInterval!Date(Date(2010, 7, 5))));
assert(negInfInterval.intersects(PosInfInterval!Date(Date(2012, 1, 6))));
assert(!negInfInterval.intersects(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!negInfInterval.intersects(PosInfInterval!Date(Date(2012, 1, 8))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.intersects(interval)));
static assert(__traits(compiles, negInfInterval.intersects(cInterval)));
static assert(__traits(compiles, negInfInterval.intersects(iInterval)));
static assert(__traits(compiles, negInfInterval.intersects(posInfInterval)));
static assert(__traits(compiles, negInfInterval.intersects(cPosInfInterval)));
static assert(__traits(compiles, negInfInterval.intersects(iPosInfInterval)));
static assert(__traits(compiles, negInfInterval.intersects(negInfInterval)));
static assert(__traits(compiles, negInfInterval.intersects(cNegInfInterval)));
static assert(__traits(compiles, negInfInterval.intersects(iNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersects(interval)));
static assert(__traits(compiles, cNegInfInterval.intersects(cInterval)));
static assert(__traits(compiles, cNegInfInterval.intersects(iInterval)));
static assert(__traits(compiles, cNegInfInterval.intersects(posInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersects(cPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersects(iPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersects(negInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersects(cNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersects(iNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersects(interval)));
static assert(__traits(compiles, iNegInfInterval.intersects(cInterval)));
static assert(__traits(compiles, iNegInfInterval.intersects(iInterval)));
static assert(__traits(compiles, iNegInfInterval.intersects(posInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersects(cPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersects(iPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersects(negInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersects(cNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersects(iNegInfInterval)));
//Verify Examples.
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(Interval!Date(Date(1999, 1, 12), Date(2011, 9, 17))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).intersects(Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(PosInfInterval!Date(Date(1999, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).intersects(PosInfInterval!Date(Date(2012, 3, 1))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(NegInfInterval!Date(Date(1996, 5, 4))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersects(NegInfInterval!Date(Date(2013, 7, 9))));
}
}
//Test NegInfInterval's intersection().
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(I, J)(in I interval1, in J interval2)
{
interval1.intersection(interval2);
}
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assertThrown!DateTimeException(testInterval(negInfInterval, PosInfInterval!Date(Date(2012, 1, 7))));
assertThrown!DateTimeException(testInterval(negInfInterval, PosInfInterval!Date(Date(2012, 1, 8))));
_assertPred!"=="(negInfInterval.intersection(negInfInterval),
negInfInterval);
_assertPred!"=="(negInfInterval.intersection(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))),
Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3)));
_assertPred!"=="(negInfInterval.intersection(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))),
Interval!Date(Date(2010, 7, 1), Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.intersection(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))),
Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4)));
_assertPred!"=="(negInfInterval.intersection(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))),
Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5)));
_assertPred!"=="(negInfInterval.intersection(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.intersection(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.intersection(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))),
Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6)));
_assertPred!"=="(negInfInterval.intersection(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))),
Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.intersection(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))),
Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.intersection(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))),
Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.intersection(NegInfInterval!Date(Date(2010, 7, 3))),
NegInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(negInfInterval.intersection(NegInfInterval!Date(Date(2010, 7, 4))),
NegInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(negInfInterval.intersection(NegInfInterval!Date(Date(2010, 7, 5))),
NegInfInterval!Date(Date(2010, 7, 5)));
_assertPred!"=="(negInfInterval.intersection(NegInfInterval!Date(Date(2012, 1, 6))),
NegInfInterval!Date(Date(2012, 1, 6)));
_assertPred!"=="(negInfInterval.intersection(NegInfInterval!Date(Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.intersection(NegInfInterval!Date(Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 7, 3)).intersection(negInfInterval),
NegInfInterval!Date(Date(2010, 7, 3)));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 7, 4)).intersection(negInfInterval),
NegInfInterval!Date(Date(2010, 7, 4)));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 7, 5)).intersection(negInfInterval),
NegInfInterval!Date(Date(2010, 7, 5)));
_assertPred!"=="(NegInfInterval!Date(Date(2012, 1, 6)).intersection(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 6)));
_assertPred!"=="(NegInfInterval!Date(Date(2012, 1, 7)).intersection(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2012, 1, 8)).intersection(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.intersection(PosInfInterval!Date(Date(2010, 7, 3))),
Interval!Date(Date(2010, 7, 3), Date(2012, 1 ,7)));
_assertPred!"=="(negInfInterval.intersection(PosInfInterval!Date(Date(2010, 7, 4))),
Interval!Date(Date(2010, 7, 4), Date(2012, 1 ,7)));
_assertPred!"=="(negInfInterval.intersection(PosInfInterval!Date(Date(2010, 7, 5))),
Interval!Date(Date(2010, 7, 5), Date(2012, 1 ,7)));
_assertPred!"=="(negInfInterval.intersection(PosInfInterval!Date(Date(2012, 1, 6))),
Interval!Date(Date(2012, 1, 6), Date(2012, 1 ,7)));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.intersection(interval)));
static assert(__traits(compiles, negInfInterval.intersection(cInterval)));
static assert(__traits(compiles, negInfInterval.intersection(iInterval)));
static assert(__traits(compiles, negInfInterval.intersection(posInfInterval)));
static assert(__traits(compiles, negInfInterval.intersection(cPosInfInterval)));
static assert(__traits(compiles, negInfInterval.intersection(iPosInfInterval)));
static assert(__traits(compiles, negInfInterval.intersection(negInfInterval)));
static assert(__traits(compiles, negInfInterval.intersection(cNegInfInterval)));
static assert(__traits(compiles, negInfInterval.intersection(iNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersection(interval)));
static assert(__traits(compiles, cNegInfInterval.intersection(cInterval)));
static assert(__traits(compiles, cNegInfInterval.intersection(iInterval)));
static assert(__traits(compiles, cNegInfInterval.intersection(posInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersection(cPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersection(iPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersection(negInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersection(cNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.intersection(iNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersection(interval)));
static assert(__traits(compiles, iNegInfInterval.intersection(cInterval)));
static assert(__traits(compiles, iNegInfInterval.intersection(iInterval)));
static assert(__traits(compiles, iNegInfInterval.intersection(posInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersection(cPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersection(iPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersection(negInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersection(cNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.intersection(iNegInfInterval)));
//Verify Examples.
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) == Interval!Date(Date(1990, 7 , 6), Date(2000, 8, 2)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(Interval!Date(Date(1999, 1, 12), Date(2015, 9, 2))) == Interval!Date(Date(1999, 1 , 12), Date(2012, 3, 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(PosInfInterval!Date(Date(1990, 7, 6))) == Interval!Date(Date(1990, 7 , 6), Date(2012, 3, 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(PosInfInterval!Date(Date(1999, 1, 12))) == Interval!Date(Date(1999, 1 , 12), Date(2012, 3, 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(NegInfInterval!Date(Date(1999, 7, 6))) == NegInfInterval!Date(Date(1999, 7 , 6)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).intersection(NegInfInterval!Date(Date(2013, 1, 12))) == NegInfInterval!Date(Date(2012, 3 , 1)));
}
}
//Test NegInfInterval's isAdjacent().
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(in NegInfInterval!Date negInfInterval, in Interval!Date interval)
{
negInfInterval.isAdjacent(interval);
}
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assert(!negInfInterval.isAdjacent(negInfInterval));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))));
assert(negInfInterval.isAdjacent(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))));
assert(!negInfInterval.isAdjacent(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
assert(!negInfInterval.isAdjacent(NegInfInterval!Date(Date(2010, 7, 3))));
assert(!negInfInterval.isAdjacent(NegInfInterval!Date(Date(2010, 7, 4))));
assert(!negInfInterval.isAdjacent(NegInfInterval!Date(Date(2010, 7, 5))));
assert(!negInfInterval.isAdjacent(NegInfInterval!Date(Date(2012, 1, 6))));
assert(!negInfInterval.isAdjacent(NegInfInterval!Date(Date(2012, 1, 7))));
assert(!negInfInterval.isAdjacent(NegInfInterval!Date(Date(2012, 1, 8))));
assert(!NegInfInterval!Date(Date(2010, 7, 3)).isAdjacent(negInfInterval));
assert(!NegInfInterval!Date(Date(2010, 7, 4)).isAdjacent(negInfInterval));
assert(!NegInfInterval!Date(Date(2010, 7, 5)).isAdjacent(negInfInterval));
assert(!NegInfInterval!Date(Date(2012, 1, 6)).isAdjacent(negInfInterval));
assert(!NegInfInterval!Date(Date(2012, 1, 7)).isAdjacent(negInfInterval));
assert(!NegInfInterval!Date(Date(2012, 1, 8)).isAdjacent(negInfInterval));
assert(!negInfInterval.isAdjacent(PosInfInterval!Date(Date(2010, 7, 3))));
assert(!negInfInterval.isAdjacent(PosInfInterval!Date(Date(2010, 7, 4))));
assert(!negInfInterval.isAdjacent(PosInfInterval!Date(Date(2010, 7, 5))));
assert(!negInfInterval.isAdjacent(PosInfInterval!Date(Date(2012, 1, 6))));
assert(negInfInterval.isAdjacent(PosInfInterval!Date(Date(2012, 1, 7))));
assert(!negInfInterval.isAdjacent(PosInfInterval!Date(Date(2012, 1, 8))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.isAdjacent(interval)));
static assert(__traits(compiles, negInfInterval.isAdjacent(cInterval)));
static assert(__traits(compiles, negInfInterval.isAdjacent(iInterval)));
static assert(__traits(compiles, negInfInterval.isAdjacent(posInfInterval)));
static assert(__traits(compiles, negInfInterval.isAdjacent(cPosInfInterval)));
static assert(__traits(compiles, negInfInterval.isAdjacent(iPosInfInterval)));
static assert(__traits(compiles, negInfInterval.isAdjacent(negInfInterval)));
static assert(__traits(compiles, negInfInterval.isAdjacent(cNegInfInterval)));
static assert(__traits(compiles, negInfInterval.isAdjacent(iNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAdjacent(interval)));
static assert(__traits(compiles, cNegInfInterval.isAdjacent(cInterval)));
static assert(__traits(compiles, cNegInfInterval.isAdjacent(iInterval)));
static assert(__traits(compiles, cNegInfInterval.isAdjacent(posInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAdjacent(cPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAdjacent(iPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAdjacent(negInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAdjacent(cNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.isAdjacent(iNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAdjacent(interval)));
static assert(__traits(compiles, iNegInfInterval.isAdjacent(cInterval)));
static assert(__traits(compiles, iNegInfInterval.isAdjacent(iInterval)));
static assert(__traits(compiles, iNegInfInterval.isAdjacent(posInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAdjacent(cPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAdjacent(iPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAdjacent(negInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAdjacent(cNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.isAdjacent(iNegInfInterval)));
//Verify Examples.
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(Interval!Date(Date(1999, 1, 12), Date(2012, 3, 1))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(Interval!Date(Date(2012, 3, 1), Date(2019, 2, 2))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(Interval!Date(Date(2022, 10, 19), Date(2027, 6, 3))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(PosInfInterval!Date(Date(1999, 5, 4))));
assert(NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(PosInfInterval!Date(Date(2012, 3, 1))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(NegInfInterval!Date(Date(1996, 5, 4))));
assert(!NegInfInterval!Date(Date(2012, 3, 1)).isAdjacent(NegInfInterval!Date(Date(2012, 3, 1))));
}
}
//Test NegInfInterval's merge().
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(I, J)(in I interval1, in J interval2)
{
interval1.merge(interval2);
}
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))));
_assertPred!"=="(negInfInterval.merge(negInfInterval),
negInfInterval);
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))),
NegInfInterval!Date(Date(2013, 7, 3)));
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 8)));
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 8)));
_assertPred!"=="(negInfInterval.merge(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 8)));
_assertPred!"=="(negInfInterval.merge(NegInfInterval!Date(Date(2010, 7, 3))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(NegInfInterval!Date(Date(2010, 7, 4))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(NegInfInterval!Date(Date(2010, 7, 5))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(NegInfInterval!Date(Date(2012, 1, 6))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(NegInfInterval!Date(Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.merge(NegInfInterval!Date(Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 8)));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 7, 3)).merge(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 7, 4)).merge(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 7, 5)).merge(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2012, 1, 6)).merge(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2012, 1, 7)).merge(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2012, 1, 8)).merge(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 8)));
static assert(!__traits(compiles, negInfInterval.merge(PosInfInterval!Date(Date(2010, 7, 3)))));
static assert(!__traits(compiles, negInfInterval.merge(PosInfInterval!Date(Date(2010, 7, 4)))));
static assert(!__traits(compiles, negInfInterval.merge(PosInfInterval!Date(Date(2010, 7, 5)))));
static assert(!__traits(compiles, negInfInterval.merge(PosInfInterval!Date(Date(2012, 1, 6)))));
static assert(!__traits(compiles, negInfInterval.merge(PosInfInterval!Date(Date(2012, 1, 7)))));
static assert(!__traits(compiles, negInfInterval.merge(PosInfInterval!Date(Date(2012, 1, 8)))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.merge(interval)));
static assert(__traits(compiles, negInfInterval.merge(cInterval)));
static assert(__traits(compiles, negInfInterval.merge(iInterval)));
static assert(!__traits(compiles, negInfInterval.merge(posInfInterval)));
static assert(!__traits(compiles, negInfInterval.merge(cPosInfInterval)));
static assert(!__traits(compiles, negInfInterval.merge(iPosInfInterval)));
static assert(__traits(compiles, negInfInterval.merge(negInfInterval)));
static assert(__traits(compiles, negInfInterval.merge(cNegInfInterval)));
static assert(__traits(compiles, negInfInterval.merge(iNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.merge(interval)));
static assert(__traits(compiles, cNegInfInterval.merge(cInterval)));
static assert(__traits(compiles, cNegInfInterval.merge(iInterval)));
static assert(!__traits(compiles, cNegInfInterval.merge(posInfInterval)));
static assert(!__traits(compiles, cNegInfInterval.merge(cPosInfInterval)));
static assert(!__traits(compiles, cNegInfInterval.merge(iPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.merge(negInfInterval)));
static assert(__traits(compiles, cNegInfInterval.merge(cNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.merge(iNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.merge(interval)));
static assert(__traits(compiles, iNegInfInterval.merge(cInterval)));
static assert(__traits(compiles, iNegInfInterval.merge(iInterval)));
static assert(!__traits(compiles, iNegInfInterval.merge(posInfInterval)));
static assert(!__traits(compiles, iNegInfInterval.merge(cPosInfInterval)));
static assert(!__traits(compiles, iNegInfInterval.merge(iPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.merge(negInfInterval)));
static assert(__traits(compiles, iNegInfInterval.merge(cNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.merge(iNegInfInterval)));
//Verify Examples.
assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) == NegInfInterval!Date(Date(2012, 3 , 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(Interval!Date(Date(1999, 1, 12), Date(2015, 9, 2))) == NegInfInterval!Date(Date(2015, 9 , 2)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(NegInfInterval!Date(Date(1999, 7, 6))) == NegInfInterval!Date(Date(2012, 3 , 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).merge(NegInfInterval!Date(Date(2013, 1, 12))) == NegInfInterval!Date(Date(2013, 1 , 12)));
}
}
//Test NegInfInterval's span().
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(I, J)(in I interval1, in J interval2)
{
interval1.span(interval2);
}
assertThrown!DateTimeException(testInterval(negInfInterval, Interval!Date(Date(2010, 7, 4), dur!"days"(0))));
_assertPred!"=="(negInfInterval.span(negInfInterval),
negInfInterval);
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2010, 7, 1), Date(2010, 7, 3))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2010, 7, 1), Date(2013, 7, 3))),
NegInfInterval!Date(Date(2013, 7, 3)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 4))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2010, 7, 3), Date(2010, 7, 5))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2010, 7, 3), Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 8)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 6))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2010, 7, 5), Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2012, 1, 6), Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 8)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2012, 1, 7), Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 8)));
_assertPred!"=="(negInfInterval.span(Interval!Date(Date(2012, 1, 8), Date(2012, 1, 9))),
NegInfInterval!Date(Date(2012, 1, 9)));
_assertPred!"=="(negInfInterval.span(NegInfInterval!Date(Date(2010, 7, 3))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(NegInfInterval!Date(Date(2010, 7, 4))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(NegInfInterval!Date(Date(2010, 7, 5))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(NegInfInterval!Date(Date(2012, 1, 6))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(NegInfInterval!Date(Date(2012, 1, 7))),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(negInfInterval.span(NegInfInterval!Date(Date(2012, 1, 8))),
NegInfInterval!Date(Date(2012, 1, 8)));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 7, 3)).span(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 7, 4)).span(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 7, 5)).span(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2012, 1, 6)).span(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2012, 1, 7)).span(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 7)));
_assertPred!"=="(NegInfInterval!Date(Date(2012, 1, 8)).span(negInfInterval),
NegInfInterval!Date(Date(2012, 1, 8)));
static assert(!__traits(compiles, negInfInterval.span(PosInfInterval!Date(Date(2010, 7, 3)))));
static assert(!__traits(compiles, negInfInterval.span(PosInfInterval!Date(Date(2010, 7, 4)))));
static assert(!__traits(compiles, negInfInterval.span(PosInfInterval!Date(Date(2010, 7, 5)))));
static assert(!__traits(compiles, negInfInterval.span(PosInfInterval!Date(Date(2012, 1, 6)))));
static assert(!__traits(compiles, negInfInterval.span(PosInfInterval!Date(Date(2012, 1, 7)))));
static assert(!__traits(compiles, negInfInterval.span(PosInfInterval!Date(Date(2012, 1, 8)))));
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
const cInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
immutable iInterval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
immutable iPosInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, negInfInterval.span(interval)));
static assert(__traits(compiles, negInfInterval.span(cInterval)));
static assert(__traits(compiles, negInfInterval.span(iInterval)));
static assert(!__traits(compiles, negInfInterval.span(posInfInterval)));
static assert(!__traits(compiles, negInfInterval.span(cPosInfInterval)));
static assert(!__traits(compiles, negInfInterval.span(iPosInfInterval)));
static assert(__traits(compiles, negInfInterval.span(negInfInterval)));
static assert(__traits(compiles, negInfInterval.span(cNegInfInterval)));
static assert(__traits(compiles, negInfInterval.span(iNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.span(interval)));
static assert(__traits(compiles, cNegInfInterval.span(cInterval)));
static assert(__traits(compiles, cNegInfInterval.span(iInterval)));
static assert(!__traits(compiles, cNegInfInterval.span(posInfInterval)));
static assert(!__traits(compiles, cNegInfInterval.span(cPosInfInterval)));
static assert(!__traits(compiles, cNegInfInterval.span(iPosInfInterval)));
static assert(__traits(compiles, cNegInfInterval.span(negInfInterval)));
static assert(__traits(compiles, cNegInfInterval.span(cNegInfInterval)));
static assert(__traits(compiles, cNegInfInterval.span(iNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.span(interval)));
static assert(__traits(compiles, iNegInfInterval.span(cInterval)));
static assert(__traits(compiles, iNegInfInterval.span(iInterval)));
static assert(!__traits(compiles, iNegInfInterval.span(posInfInterval)));
static assert(!__traits(compiles, iNegInfInterval.span(cPosInfInterval)));
static assert(!__traits(compiles, iNegInfInterval.span(iPosInfInterval)));
static assert(__traits(compiles, iNegInfInterval.span(negInfInterval)));
static assert(__traits(compiles, iNegInfInterval.span(cNegInfInterval)));
static assert(__traits(compiles, iNegInfInterval.span(iNegInfInterval)));
//Verify Examples.
assert(NegInfInterval!Date(Date(2012, 3, 1)).span(Interval!Date(Date(1990, 7, 6), Date(2000, 8, 2))) == NegInfInterval!Date(Date(2012, 3 , 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).span(Interval!Date(Date(1999, 1, 12), Date(2015, 9, 2))) == NegInfInterval!Date(Date(2015, 9 , 2)));
assert(NegInfInterval!Date(Date(1600, 1, 7)).span(Interval!Date(Date(2012, 3, 11), Date(2017, 7, 1))) == NegInfInterval!Date(Date(2017, 7 , 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).span(NegInfInterval!Date(Date(1999, 7, 6))) == NegInfInterval!Date(Date(2012, 3 , 1)));
assert(NegInfInterval!Date(Date(2012, 3, 1)).span(NegInfInterval!Date(Date(2013, 1, 12))) == NegInfInterval!Date(Date(2013, 1 , 12)));
}
}
//Test NegInfInterval's shift().
unittest
{
version(testStdDateTime)
{
auto interval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(I)(I interval, in Duration duration, in I expected, size_t line = __LINE__)
{
interval.shift(duration);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, dur!"days"(22), NegInfInterval!Date(Date(2012, 1, 29)));
testInterval(interval, dur!"days"(-22), NegInfInterval!Date(Date(2011, 12, 16)));
const cInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(!__traits(compiles, cInterval.shift(dur!"days"(5))));
static assert(!__traits(compiles, iInterval.shift(dur!"days"(5))));
//Verify Examples.
auto interval1 = NegInfInterval!Date(Date(2012, 4, 5));
auto interval2 = NegInfInterval!Date(Date(2012, 4, 5));
interval1.shift(dur!"days"(50));
assert(interval1 == NegInfInterval!Date(Date(2012, 5, 25)));
interval2.shift(dur!"days"(-50));
assert(interval2 == NegInfInterval!Date( Date(2012, 2, 15)));
}
}
//Test NegInfInterval's shift(int, int, AllowDayOverflow).
unittest
{
version(testStdDateTime)
{
{
auto interval = NegInfInterval!Date(Date(2012, 1, 7));
static void testIntervalFail(I)(I interval, int years, int months)
{
interval.shift(years, months);
}
static void testInterval(I)(I interval, int years, int months, AllowDayOverflow allow, in I expected, size_t line = __LINE__)
{
interval.shift(years, months, allow);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, 5, 0, AllowDayOverflow.yes, NegInfInterval!Date(Date(2017, 1, 7)));
testInterval(interval, -5, 0, AllowDayOverflow.yes, NegInfInterval!Date(Date(2007, 1, 7)));
auto interval2 = NegInfInterval!Date(Date(2010, 5, 31));
testInterval(interval2, 1, 1, AllowDayOverflow.yes, NegInfInterval!Date(Date(2011, 7, 1)));
testInterval(interval2, 1, -1, AllowDayOverflow.yes, NegInfInterval!Date(Date(2011, 5, 1)));
testInterval(interval2, -1, -1, AllowDayOverflow.yes, NegInfInterval!Date(Date(2009, 5, 1)));
testInterval(interval2, -1, 1, AllowDayOverflow.yes, NegInfInterval!Date(Date(2009, 7, 1)));
testInterval(interval2, 1, 1, AllowDayOverflow.no, NegInfInterval!Date(Date(2011, 6, 30)));
testInterval(interval2, 1, -1, AllowDayOverflow.no, NegInfInterval!Date(Date(2011, 4, 30)));
testInterval(interval2, -1, -1, AllowDayOverflow.no, NegInfInterval!Date(Date(2009, 4, 30)));
testInterval(interval2, -1, 1, AllowDayOverflow.no, NegInfInterval!Date(Date(2009, 6, 30)));
}
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(!__traits(compiles, cNegInfInterval.shift(1)));
static assert(!__traits(compiles, iNegInfInterval.shift(1)));
//Verify Examples.
auto interval1 = NegInfInterval!Date(Date(2012, 3, 1));
auto interval2 = NegInfInterval!Date(Date(2012, 3, 1));
interval1.shift(2);
assert(interval1 == NegInfInterval!Date(Date(2014, 3, 1)));
interval2.shift(-2);
assert(interval2 == NegInfInterval!Date(Date(2010, 3, 1)));
}
}
//Test NegInfInterval's expand().
unittest
{
version(testStdDateTime)
{
auto interval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(I)(I interval, in Duration duration, in I expected, size_t line = __LINE__)
{
interval.expand(duration);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, dur!"days"(22), NegInfInterval!Date(Date(2012, 1, 29)));
testInterval(interval, dur!"days"(-22), NegInfInterval!Date(Date(2011, 12, 16)));
const cInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(!__traits(compiles, cInterval.expand(dur!"days"(5))));
static assert(!__traits(compiles, iInterval.expand(dur!"days"(5))));
//Verify Examples.
auto interval1 = NegInfInterval!Date(Date(2012, 3, 1));
auto interval2 = NegInfInterval!Date(Date(2012, 3, 1));
interval1.expand(dur!"days"(2));
assert(interval1 == NegInfInterval!Date(Date(2012, 3, 3)));
interval2.expand(dur!"days"(-2));
assert(interval2 == NegInfInterval!Date(Date(2012, 2, 28)));
}
}
//Test NegInfInterval's expand(int, int, AllowDayOverflow).
unittest
{
version(testStdDateTime)
{
{
auto interval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(I)(I interval, int years, int months, AllowDayOverflow allow, in I expected, size_t line = __LINE__)
{
interval.expand(years, months, allow);
_assertPred!"=="(interval, expected, "", __FILE__, line);
}
testInterval(interval, 5, 0, AllowDayOverflow.yes, NegInfInterval!Date(Date(2017, 1, 7)));
testInterval(interval, -5, 0, AllowDayOverflow.yes, NegInfInterval!Date(Date(2007, 1, 7)));
auto interval2 = NegInfInterval!Date(Date(2010, 5, 31));
testInterval(interval2, 1, 1, AllowDayOverflow.yes, NegInfInterval!Date(Date(2011, 7, 1)));
testInterval(interval2, 1, -1, AllowDayOverflow.yes, NegInfInterval!Date(Date(2011, 5, 1)));
testInterval(interval2, -1, -1, AllowDayOverflow.yes, NegInfInterval!Date(Date(2009, 5, 1)));
testInterval(interval2, -1, 1, AllowDayOverflow.yes, NegInfInterval!Date(Date(2009, 7, 1)));
testInterval(interval2, 1, 1, AllowDayOverflow.no, NegInfInterval!Date(Date(2011, 6, 30)));
testInterval(interval2, 1, -1, AllowDayOverflow.no, NegInfInterval!Date(Date(2011, 4, 30)));
testInterval(interval2, -1, -1, AllowDayOverflow.no, NegInfInterval!Date(Date(2009, 4, 30)));
testInterval(interval2, -1, 1, AllowDayOverflow.no, NegInfInterval!Date( Date(2009, 6, 30)));
}
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(!__traits(compiles, cNegInfInterval.expand(1)));
static assert(!__traits(compiles, iNegInfInterval.expand(1)));
//Verify Examples.
auto interval1 = NegInfInterval!Date(Date(2012, 3, 1));
auto interval2 = NegInfInterval!Date(Date(2012, 3, 1));
interval1.expand(2);
assert(interval1 == NegInfInterval!Date(Date(2014, 3, 1)));
interval2.expand(-2);
assert(interval2 == NegInfInterval!Date(Date(2010, 3, 1)));
}
}
//Test NegInfInterval's bwdRange().
unittest
{
version(testStdDateTime)
{
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static void testInterval(NegInfInterval!Date negInfInterval)
{
negInfInterval.bwdRange(everyDayOfWeek!(Date, Direction.fwd)(DayOfWeek.fri)).popFront();
}
assertThrown!DateTimeException(testInterval(negInfInterval));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 10, 1)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri)).front,
Date(2010, 10, 1));
_assertPred!"=="(NegInfInterval!Date(Date(2010, 10, 1)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri), PopFirst.yes).front,
Date(2010, 9, 24));
//Verify Examples.
auto interval = NegInfInterval!Date(Date(2010, 9, 9));
auto func = (in Date date)
{
if((date.day & 1) == 0)
return date - dur!"days"(2);
return date - dur!"days"(1);
};
auto range = interval.bwdRange(func);
//An odd day. Using PopFirst.yes would have made this Date(2010, 9, 8).
assert(range.front == Date(2010, 9, 9));
range.popFront();
assert(range.front == Date(2010, 9, 8));
range.popFront();
assert(range.front == Date(2010, 9, 6));
range.popFront();
assert(range.front == Date(2010, 9, 4));
range.popFront();
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(!range.empty);
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, cNegInfInterval.bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri))));
static assert(__traits(compiles, iNegInfInterval.bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri))));
}
}
//Test NegInfInterval's toString().
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(NegInfInterval!Date(Date(2012, 1, 7)).toString(), "[-∞ - 2012-Jan-07)");
const cNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
immutable iNegInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
static assert(__traits(compiles, cNegInfInterval.toString()));
static assert(__traits(compiles, iNegInfInterval.toString()));
}
}
/++
Range-generating function.
Returns a delegate which returns the next time point with the given
$(D DayOfWeek) in a range.
Using this delegate allows you to iterate over successive time points which
are all the same day of the week. e.g. passing $(D DayOfWeek.mon) to
$(D everyDayOfWeek) would result in a delegate which could be used to
iterate over all of the Mondays in a range.
Params:
dir = The direction to iterate in. If passing the return value to
$(D fwdRange), use $(D Direction.fwd). If passing it to
$(D bwdRange), use $(D Direction.bwd).
dayOfWeek = The week that each time point in the range will be.
Examples:
--------------------
auto interval = Interval!Date(Date(2010, 9, 2), Date(2010, 9, 27));
auto func = everyDayOfWeek!Date(DayOfWeek.mon);
auto range = interval.fwdRange(func);
//A Thursday. Using PopFirst.yes would have made this Date(2010, 9, 6).
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.front == Date(2010, 9, 6));
range.popFront();
assert(range.front == Date(2010, 9, 13));
range.popFront();
assert(range.front == Date(2010, 9, 20));
range.popFront();
assert(range.empty);
--------------------
+/
static TP delegate(in TP) everyDayOfWeek(TP, Direction dir = Direction.fwd)(DayOfWeek dayOfWeek) nothrow
if(isTimePoint!TP &&
(dir == Direction.fwd || dir == Direction.bwd) &&
__traits(hasMember, TP, "dayOfWeek") &&
!__traits(isStaticFunction, TP.dayOfWeek) &&
is(ReturnType!(TP.dayOfWeek) == DayOfWeek) &&
(functionAttributes!(TP.dayOfWeek) & FunctionAttribute.PROPERTY) &&
(functionAttributes!(TP.dayOfWeek) & FunctionAttribute.NOTHROW))
{
TP func(in TP tp)
{
TP retval = cast(TP)tp;
immutable days = daysToDayOfWeek(retval.dayOfWeek, dayOfWeek);
static if(dir == Direction.fwd)
immutable adjustedDays = days == 0 ? 7 : days;
else
immutable adjustedDays = days == 0 ? -7 : days - 7;
return retval += dur!"days"(adjustedDays);
}
return &func;
}
unittest
{
version(testStdDateTime)
{
auto funcFwd = everyDayOfWeek!Date(DayOfWeek.mon);
auto funcBwd = everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.mon);
_assertPred!"=="(funcFwd(Date(2010, 8, 28)), Date(2010, 8, 30));
_assertPred!"=="(funcFwd(Date(2010, 8, 29)), Date(2010, 8, 30));
_assertPred!"=="(funcFwd(Date(2010, 8, 30)), Date(2010, 9, 6));
_assertPred!"=="(funcFwd(Date(2010, 8, 31)), Date(2010, 9, 6));
_assertPred!"=="(funcFwd(Date(2010, 9, 1)), Date(2010, 9, 6));
_assertPred!"=="(funcFwd(Date(2010, 9, 2)), Date(2010, 9, 6));
_assertPred!"=="(funcFwd(Date(2010, 9, 3)), Date(2010, 9, 6));
_assertPred!"=="(funcFwd(Date(2010, 9, 4)), Date(2010, 9, 6));
_assertPred!"=="(funcFwd(Date(2010, 9, 5)), Date(2010, 9, 6));
_assertPred!"=="(funcFwd(Date(2010, 9, 6)), Date(2010, 9, 13));
_assertPred!"=="(funcFwd(Date(2010, 9, 7)), Date(2010, 9, 13));
_assertPred!"=="(funcBwd(Date(2010, 8, 28)), Date(2010, 8, 23));
_assertPred!"=="(funcBwd(Date(2010, 8, 29)), Date(2010, 8, 23));
_assertPred!"=="(funcBwd(Date(2010, 8, 30)), Date(2010, 8, 23));
_assertPred!"=="(funcBwd(Date(2010, 8, 31)), Date(2010, 8, 30));
_assertPred!"=="(funcBwd(Date(2010, 9, 1)), Date(2010, 8, 30));
_assertPred!"=="(funcBwd(Date(2010, 9, 2)), Date(2010, 8, 30));
_assertPred!"=="(funcBwd(Date(2010, 9, 3)), Date(2010, 8, 30));
_assertPred!"=="(funcBwd(Date(2010, 9, 4)), Date(2010, 8, 30));
_assertPred!"=="(funcBwd(Date(2010, 9, 5)), Date(2010, 8, 30));
_assertPred!"=="(funcBwd(Date(2010, 9, 6)), Date(2010, 8, 30));
_assertPred!"=="(funcBwd(Date(2010, 9, 7)), Date(2010, 9, 6));
static assert(!__traits(compiles, everyDayOfWeek!(TimeOfDay)(DayOfWeek.mon)));
static assert(__traits(compiles, everyDayOfWeek!(DateTime)(DayOfWeek.mon)));
static assert(__traits(compiles, everyDayOfWeek!(SysTime)(DayOfWeek.mon)));
//Verify Examples.
auto interval = Interval!Date(Date(2010, 9, 2), Date(2010, 9, 27));
auto func = everyDayOfWeek!Date(DayOfWeek.mon);
auto range = interval.fwdRange(func);
//A Thursday. Using PopFirst.yes would have made this Date(2010, 9, 6).
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.front == Date(2010, 9, 6));
range.popFront();
assert(range.front == Date(2010, 9, 13));
range.popFront();
assert(range.front == Date(2010, 9, 20));
range.popFront();
assert(range.empty);
}
}
/++
Range-generating function.
Returns a delegate which returns the next time point with the given month
which would be reached by adding months to the given time point.
So, using this delegate allows you to iterate over successive time points
which are in the same month but different years. For example, you could
iterate over each successive December 25th in an interval by starting with a
date which had the 25th as its day and passed $(D Month.dec) to
$(D everyMonth) to create the delegate.
Since it wouldn't really make sense to be iterating over a specific month
and end up with some of the time points in the succeeding month or two years
after the previous time point, $(D AllowDayOverflow.no) is always used when
calculating the next time point.
Params:
dir = The direction to iterate in. If passing the return value to
$(D fwdRange), use $(D Direction.fwd). If passing it to
$(D bwdRange), use $(D Direction.bwd).
month = The month that each time point in the range will be in.
Examples:
--------------------
auto interval = Interval!Date(Date(2000, 1, 30), Date(2004, 8, 5));
auto func = everyMonth!(Date)(Month.feb);
auto range = interval.fwdRange(func);
//Using PopFirst.yes would have made this Date(2010, 2, 29).
assert(range.front == Date(2000, 1, 30));
range.popFront();
assert(range.front == Date(2000, 2, 29));
range.popFront();
assert(range.front == Date(2001, 2, 28));
range.popFront();
assert(range.front == Date(2002, 2, 28));
range.popFront();
assert(range.front == Date(2003, 2, 28));
range.popFront();
assert(range.front == Date(2004, 2, 28));
range.popFront();
assert(range.empty);
--------------------
+/
static TP delegate(in TP) everyMonth(TP, Direction dir = Direction.fwd)(int month)
if(isTimePoint!TP &&
(dir == Direction.fwd || dir == Direction.bwd) &&
__traits(hasMember, TP, "month") &&
!__traits(isStaticFunction, TP.month) &&
is(ReturnType!(TP.month) == Month) &&
(functionAttributes!(TP.month) & FunctionAttribute.PROPERTY) &&
(functionAttributes!(TP.month) & FunctionAttribute.NOTHROW))
{
enforceValid!"months"(month);
TP func(in TP tp)
{
TP retval = cast(TP)tp;
immutable months = monthsToMonth(retval.month, month);
static if(dir == Direction.fwd)
immutable adjustedMonths = months == 0 ? 12 : months;
else
immutable adjustedMonths = months == 0 ? -12 : months - 12;
retval.add!"months"(adjustedMonths, AllowDayOverflow.no);
if(retval.month != month)
{
retval.add!"months"(-1);
assert(retval.month == month);
}
return retval;
}
return &func;
}
unittest
{
version(testStdDateTime)
{
auto funcFwd = everyMonth!Date(Month.jun);
auto funcBwd = everyMonth!(Date, Direction.bwd)(Month.jun);
_assertPred!"=="(funcFwd(Date(2010, 5, 31)), Date(2010, 6, 30));
_assertPred!"=="(funcFwd(Date(2010, 6, 30)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2010, 7, 31)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2010, 8, 31)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2010, 9, 30)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2010, 10, 31)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2010, 11, 30)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2010, 12, 31)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2011, 1, 31)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2011, 2, 28)), Date(2011, 6, 28));
_assertPred!"=="(funcFwd(Date(2011, 3, 31)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2011, 4, 30)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2011, 5, 31)), Date(2011, 6, 30));
_assertPred!"=="(funcFwd(Date(2011, 6, 30)), Date(2012, 6, 30));
_assertPred!"=="(funcFwd(Date(2011, 7, 31)), Date(2012, 6, 30));
_assertPred!"=="(funcBwd(Date(2010, 5, 31)), Date(2009, 6, 30));
_assertPred!"=="(funcBwd(Date(2010, 6, 30)), Date(2009, 6, 30));
_assertPred!"=="(funcBwd(Date(2010, 7, 31)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2010, 8, 31)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2010, 9, 30)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2010, 10, 31)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2010, 11, 30)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2010, 12, 31)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2011, 1, 31)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2011, 2, 28)), Date(2010, 6, 28));
_assertPred!"=="(funcBwd(Date(2011, 3, 31)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2011, 4, 30)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2011, 5, 31)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2011, 6, 30)), Date(2010, 6, 30));
_assertPred!"=="(funcBwd(Date(2011, 7, 30)), Date(2011, 6, 30));
static assert(!__traits(compiles, everyMonth!(TimeOfDay)(Month.jan)));
static assert(__traits(compiles, everyMonth!(DateTime)(Month.jan)));
static assert(__traits(compiles, everyMonth!(SysTime)(Month.jan)));
//Verify Examples.
auto interval = Interval!Date(Date(2000, 1, 30), Date(2004, 8, 5));
auto func = everyMonth!(Date)(Month.feb);
auto range = interval.fwdRange(func);
//Using PopFirst.yes would have made this Date(2010, 2, 29).
assert(range.front == Date(2000, 1, 30));
range.popFront();
assert(range.front == Date(2000, 2, 29));
range.popFront();
assert(range.front == Date(2001, 2, 28));
range.popFront();
assert(range.front == Date(2002, 2, 28));
range.popFront();
assert(range.front == Date(2003, 2, 28));
range.popFront();
assert(range.front == Date(2004, 2, 28));
range.popFront();
assert(range.empty);
}
}
/++
Range-generating function.
Returns a delegate which returns the next time point which is the given
duration later.
Using this delegate allows you to iterate over successive time points which
are apart by the given duration e.g. passing $(D dur!"days"(3)) to
$(D everyDuration) would result in a delegate which could be used to iterate
over a range of days which are each 3 days apart.
Params:
dir = The direction to iterate in. If passing the return value to
$(D fwdRange), use $(D Direction.fwd). If passing it to
$(D bwdRange), use $(D Direction.bwd).
duration = The duration which separates each successive time point in
the range.
Examples:
--------------------
auto interval = Interval!Date(Date(2010, 9, 2), Date(2010, 9, 27));
auto func = everyDuration!Date(dur!"days"(8));
auto range = interval.fwdRange(func);
//Using PopFirst.yes would have made this Date(2010, 9, 10).
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.front == Date(2010, 9, 10));
range.popFront();
assert(range.front == Date(2010, 9, 18));
range.popFront();
assert(range.front == Date(2010, 9, 26));
range.popFront();
assert(range.empty);
--------------------
+/
static TP delegate(in TP) everyDuration(TP, Direction dir = Direction.fwd, D)
(D duration) nothrow
if(isTimePoint!TP &&
__traits(compiles, TP.init + duration) &&
(dir == Direction.fwd || dir == Direction.bwd))
{
TP func(in TP tp)
{
static if(dir == Direction.fwd)
return tp + duration;
else
return tp - duration;
}
return &func;
}
unittest
{
version(testStdDateTime)
{
auto funcFwd = everyDuration!Date(dur!"days"(27));
auto funcBwd = everyDuration!(Date, Direction.bwd)(dur!"days"(27));
_assertPred!"=="(funcFwd(Date(2009, 12, 25)), Date(2010, 1, 21));
_assertPred!"=="(funcFwd(Date(2009, 12, 26)), Date(2010, 1, 22));
_assertPred!"=="(funcFwd(Date(2009, 12, 27)), Date(2010, 1, 23));
_assertPred!"=="(funcFwd(Date(2009, 12, 28)), Date(2010, 1, 24));
_assertPred!"=="(funcBwd(Date(2010, 1, 21)), Date(2009, 12, 25));
_assertPred!"=="(funcBwd(Date(2010, 1, 22)), Date(2009, 12, 26));
_assertPred!"=="(funcBwd(Date(2010, 1, 23)), Date(2009, 12, 27));
_assertPred!"=="(funcBwd(Date(2010, 1, 24)), Date(2009, 12, 28));
static assert(__traits(compiles, everyDuration!Date(dur!"hnsecs"(1))));
static assert(__traits(compiles, everyDuration!TimeOfDay(dur!"hnsecs"(1))));
static assert(__traits(compiles, everyDuration!DateTime(dur!"hnsecs"(1))));
static assert(__traits(compiles, everyDuration!SysTime(dur!"hnsecs"(1))));
//Verify Examples.
auto interval = Interval!Date(Date(2010, 9, 2), Date(2010, 9, 27));
auto func = everyDuration!Date(dur!"days"(8));
auto range = interval.fwdRange(func);
//Using PopFirst.yes would have made this Date(2010, 9, 10).
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.front == Date(2010, 9, 10));
range.popFront();
assert(range.front == Date(2010, 9, 18));
range.popFront();
assert(range.front == Date(2010, 9, 26));
range.popFront();
assert(range.empty);
}
}
/++
Range-generating function.
Returns a delegate which returns the next time point which is the given
number of years, month, and duration later.
The difference between this version of $(D everyDuration) and the version
which just takes a $(D Duration) is that this one also takes the number of
years and months (along with an $(D AllowDayOverflow) to indicate whether
adding years and months should allow the days to overflow).
Note that if iterating forward, $(D add!"years"()) is called on the given
time point, then $(D add!"months"()), and finally the duration is added
to it. However, if iterating backwards, the duration is added first, then
$(D add!"months"()) is called, and finally $(D add!"years"()) is called.
That way, going backwards generates close to the same time points that
iterating forward does, but since adding years and months is not entirely
reversible (due to possible day overflow, regardless of whether
$(D AllowDayOverflow.yes) or $(D AllowDayOverflow.no) is used), it can't be
guaranteed that iterating backwards will give you the same time points as
iterating forward would have (even assuming that the end of the range is a
time point which would be returned by the delegate when iterating forward
from $(D begin)).
Params:
dir = The direction to iterate in. If passing the return
value to $(D fwdRange), use $(D Direction.fwd). If
passing it to $(D bwdRange), use $(D Direction.bwd).
years = The number of years to add to the time point passed to
the delegate.
months = The number of months to add to the time point passed to
the delegate.
allowOverflow = Whether the days should be allowed to overflow on
$(D begin) and $(D end), causing their month to
increment.
duration = The duration to add to the time point passed to the
delegate.
Examples:
--------------------
auto interval = Interval!Date(Date(2010, 9, 2), Date(2025, 9, 27));
auto func = everyDuration!Date(4, 1, AllowDayOverflow.yes, dur!"days"(2));
auto range = interval.fwdRange(func);
//Using PopFirst.yes would have made this Date(2014, 10, 12).
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.front == Date(2014, 10, 4));
range.popFront();
assert(range.front == Date(2018, 11, 6));
range.popFront();
assert(range.front == Date(2022, 12, 8));
range.popFront();
assert(range.empty);
--------------------
+/
static TP delegate(in TP) everyDuration(TP, Direction dir = Direction.fwd, D)
(int years,
int months = 0,
AllowDayOverflow allowOverflow = AllowDayOverflow.yes,
D duration = dur!"days"(0)) nothrow
if(isTimePoint!TP &&
__traits(compiles, TP.init + duration) &&
__traits(compiles, TP.init.add!"years"(years)) &&
__traits(compiles, TP.init.add!"months"(months)) &&
(dir == Direction.fwd || dir == Direction.bwd))
{
TP func(in TP tp)
{
static if(dir == Direction.fwd)
{
TP retval = cast(TP)tp;
retval.add!"years"(years, allowOverflow);
retval.add!"months"(months, allowOverflow);
return retval + duration;
}
else
{
TP retval = tp - duration;
retval.add!"months"(-months, allowOverflow);
retval.add!"years"(-years, allowOverflow);
return retval;
}
}
return &func;
}
unittest
{
version(testStdDateTime)
{
{
auto funcFwd = everyDuration!Date(1, 2, AllowDayOverflow.yes, dur!"days"(3));
auto funcBwd = everyDuration!(Date, Direction.bwd)(1, 2, AllowDayOverflow.yes, dur!"days"(3));
_assertPred!"=="(funcFwd(Date(2009, 12, 25)), Date(2011, 2, 28));
_assertPred!"=="(funcFwd(Date(2009, 12, 26)), Date(2011, 3, 1));
_assertPred!"=="(funcFwd(Date(2009, 12, 27)), Date(2011, 3, 2));
_assertPred!"=="(funcFwd(Date(2009, 12, 28)), Date(2011, 3, 3));
_assertPred!"=="(funcFwd(Date(2009, 12, 29)), Date(2011, 3, 4));
_assertPred!"=="(funcBwd(Date(2011, 2, 28)), Date(2009, 12, 25));
_assertPred!"=="(funcBwd(Date(2011, 3, 1)), Date(2009, 12, 26));
_assertPred!"=="(funcBwd(Date(2011, 3, 2)), Date(2009, 12, 27));
_assertPred!"=="(funcBwd(Date(2011, 3, 3)), Date(2009, 12, 28));
_assertPred!"=="(funcBwd(Date(2011, 3, 4)), Date(2010, 1, 1));
}
{
auto funcFwd = everyDuration!Date(1, 2, AllowDayOverflow.no, dur!"days"(3));
auto funcBwd = everyDuration!(Date, Direction.bwd)(1, 2, AllowDayOverflow.yes, dur!"days"(3));
_assertPred!"=="(funcFwd(Date(2009, 12, 25)), Date(2011, 2, 28));
_assertPred!"=="(funcFwd(Date(2009, 12, 26)), Date(2011, 3, 1));
_assertPred!"=="(funcFwd(Date(2009, 12, 27)), Date(2011, 3, 2));
_assertPred!"=="(funcFwd(Date(2009, 12, 28)), Date(2011, 3, 3));
_assertPred!"=="(funcFwd(Date(2009, 12, 29)), Date(2011, 3, 3));
_assertPred!"=="(funcBwd(Date(2011, 2, 28)), Date(2009, 12, 25));
_assertPred!"=="(funcBwd(Date(2011, 3, 1)), Date(2009, 12, 26));
_assertPred!"=="(funcBwd(Date(2011, 3, 2)), Date(2009, 12, 27));
_assertPred!"=="(funcBwd(Date(2011, 3, 3)), Date(2009, 12, 28));
_assertPred!"=="(funcBwd(Date(2011, 3, 4)), Date(2010, 1, 1));
}
static assert(__traits(compiles, everyDuration!Date(1, 2, AllowDayOverflow.yes, dur!"hnsecs"(1))));
static assert(!__traits(compiles, everyDuration!TimeOfDay(1, 2, AllowDayOverflow.yes, dur!"hnsecs"(1))));
static assert(__traits(compiles, everyDuration!DateTime(1, 2, AllowDayOverflow.yes, dur!"hnsecs"(1))));
static assert(__traits(compiles, everyDuration!SysTime(1, 2, AllowDayOverflow.yes, dur!"hnsecs"(1))));
//Verify Examples.
auto interval = Interval!Date(Date(2010, 9, 2), Date(2025, 9, 27));
auto func = everyDuration!Date(4, 1, AllowDayOverflow.yes, dur!"days"(2));
auto range = interval.fwdRange(func);
//Using PopFirst.yes would have made this Date(2014, 10, 12).
assert(range.front == Date(2010, 9, 2));
range.popFront();
assert(range.front == Date(2014, 10, 4));
range.popFront();
assert(range.front == Date(2018, 11, 6));
range.popFront();
assert(range.front == Date(2022, 12, 8));
range.popFront();
assert(range.empty);
}
}
//TODO Add function to create a range generating function based on a date recurrence pattern string.
// This may or may not involve creating a date recurrence pattern class of some sort - probably
// yes if we want to make it easy to build them. However, there is a standard recurrence
// pattern string format which we'd want to support with a range generator (though if we have
// the class/struct, we'd probably want a version of the range generating function which took
// that rather than a string).
//==============================================================================
// Section with ranges.
//==============================================================================
/++
A range over an $(D Interval).
$(D IntervalRange) is only ever constructed by $(D Interval). However, when
it is constructed, it is given a function, $(D func), which is used to
generate the time points which are iterated over. $(D func) takes a time
point and returns a time point of the same type. So, for instance, if you
had an $(D Interval!Date), and you wanted to iterate over all of the days in
that interval, you would pass a function to $(D Interval)'s $(D fwdRange)
where that function took a $(D Date) and returned a $(D Date) which was one
day later. That function would then be used by $(D IntervalRange)'s
$(D popFront) to iterate over the $(D Date)s in the interval.
If $(D dir == Direction.fwd), then a range iterates forward in time, whereas
if $(D dir == Direction.bwd), then it iterates backwards in time. So, if
$(D dir == Direction.fwd) then $(D front == interval.begin), whereas if
$(D dir == Direction.bwd) then $(D front == interval.end). $(D func) must
generate a time point going in the proper direction of iteration, or a
$(D DateTimeException) will be thrown. So, if you're iterating forward in
time, the time point that $(D func) generates must be later in time than the
one passed to it. If it's either identical or earlier in time, then a
$(D DateTimeException) will be thrown. If you're iterating backwards, then
the generated time point must be before the time point which was passed in.
If the generated time point is ever passed the edge of the range in the
proper direction, then the edge of that range will be used instead. So, if
iterating forward, and the generated time point is past the interval's
$(D end), then $(D front) becomes $(D end). If iterating backwards, and the
generated time point is before $(D begin), then $(D front) becomes
$(D begin). In either case, the range would then be empty.
Also note that while normally the $(D begin) of an interval is included in
it and its $(D end) is excluded from it, if $(D dir == Direction.bwd), then
$(D begin) is treated as excluded and $(D end) is treated as included. This
allows for the same behavior in both directions. This works because none of
$(D Interval)'s functions which care about whether $(D begin) or $(D end) is
included or excluded are ever called by $(D IntervalRange). $(D interval)
returns a normal interval, regardless of whether $(D dir == Direction.fwd)
or if $(D dir == Direction.bwd), so any $(D Interval) functions which are
called on it which care about whether $(D begin) or $(D end) are included or
excluded will treat $(D begin) as included and $(D end) as excluded.
+/
struct IntervalRange(TP, Direction dir)
if(isTimePoint!TP && dir != Direction.both)
{
public:
/++
Params:
rhs = The $(D IntervalRange) to assign to this one.
+/
/+ref+/ IntervalRange opAssign(ref IntervalRange rhs) pure nothrow
{
_interval = rhs._interval;
_func = rhs._func;
return this;
}
/++
Whether this $(D IntervalRange) is empty.
+/
@property bool empty() const pure nothrow
{
return _interval.empty;
}
/++
The first time point in the range.
Throws:
$(D DateTimeException) if the range is empty.
+/
@property TP front() const pure
{
_enforceNotEmpty();
static if(dir == Direction.fwd)
return _interval.begin;
else
return _interval.end;
}
/++
Pops $(D front) from the range, using $(D func) to generate the next
time point in the range. If the generated time point is beyond the edge
of the range, then $(D front) is set to that edge, and the range is then
empty. So, if iterating forwards, and the generated time point is
greater than the interval's $(D end), then $(D front) is set to
$(D end). If iterating backwards, and the generated time point is less
than the interval's $(D begin), then $(D front) is set to $(D begin).
Throws:
$(D DateTimeException) if the range is empty or if the generated
time point is in the wrong direction (i.e. if you're iterating
forward and the generated time point is before $(D front), or if
you're iterating backwards, and the generated time point is after
$(D front)).
+/
void popFront()
{
_enforceNotEmpty();
static if(dir == Direction.fwd)
{
auto begin = _func(_interval.begin);
if(begin > _interval.end)
begin = _interval.end;
_enforceCorrectDirection(begin);
_interval.begin = begin;
}
else
{
auto end = _func(_interval.end);
if(end < _interval.begin)
end = _interval.begin;
_enforceCorrectDirection(end);
_interval.end = end;
}
}
/++
Returns a copy of $(D this).
+/
@property IntervalRange save() pure nothrow
{
return this;
}
/++
The interval that this $(D IntervalRange) currently covers.
+/
@property Interval!TP interval() const pure nothrow
{
return cast(Interval!TP)_interval;
}
/++
The function used to generate the next time point in the range.
+/
TP delegate(in TP) func() pure nothrow @property
{
return _func;
}
/++
The $(D Direction) that this range iterates in.
+/
@property Direction direction() const pure nothrow
{
return dir;
}
private:
/+
Params:
interval = The interval that this range covers.
func = The function used to generate the time points which are
iterated over.
+/
this(in Interval!TP interval, TP delegate(in TP) func) pure nothrow
{
_func = func;
_interval = interval;
}
/+
Throws:
$(D DateTimeException) if this interval is empty.
+/
void _enforceNotEmpty(size_t line = __LINE__) const pure
{
if(empty)
throw new DateTimeException("Invalid operation for an empty IntervalRange.", __FILE__, line);
}
/+
Throws:
$(D DateTimeException) if $(D_PARAM newTP) is in the wrong
direction.
+/
void _enforceCorrectDirection(in TP newTP, size_t line = __LINE__) const
{
static if(dir == Direction.fwd)
{
enforce(newTP > _interval._begin,
new DateTimeException(format("Generated time point is before previous begin: prev [%s] new [%s]",
interval._begin,
newTP),
__FILE__,
line));
}
else
{
enforce(newTP < _interval._end,
new DateTimeException(format("Generated time point is after previous end: prev [%s] new [%s]",
interval._end,
newTP),
__FILE__,
line));
}
}
Interval!TP _interval;
TP delegate(in TP) _func;
}
//Test that IntervalRange satisfies the range predicates that it's supposed to satisfy.
unittest
{
version(testStdDateTime)
{
static assert(isInputRange!(IntervalRange!(Date, Direction.fwd)));
static assert(isForwardRange!(IntervalRange!(Date, Direction.fwd)));
//Commented out due to bug http://d.puremagic.com/issues/show_bug.cgi?id=4895
//static assert(!isOutputRange!(IntervalRange!(Date, Direction.fwd), Date));
static assert(!isBidirectionalRange!(IntervalRange!(Date, Direction.fwd)));
static assert(!isRandomAccessRange!(IntervalRange!(Date, Direction.fwd)));
static assert(!hasSwappableElements!(IntervalRange!(Date, Direction.fwd)));
static assert(!hasAssignableElements!(IntervalRange!(Date, Direction.fwd)));
static assert(!hasLength!(IntervalRange!(Date, Direction.fwd)));
static assert(!isInfinite!(IntervalRange!(Date, Direction.fwd)));
static assert(!hasSlicing!(IntervalRange!(Date, Direction.fwd)));
static assert(is(ElementType!(IntervalRange!(Date, Direction.fwd)) == Date));
static assert(is(ElementType!(IntervalRange!(TimeOfDay, Direction.fwd)) == TimeOfDay));
static assert(is(ElementType!(IntervalRange!(DateTime, Direction.fwd)) == DateTime));
static assert(is(ElementType!(IntervalRange!(SysTime, Direction.fwd)) == SysTime));
}
}
//Test construction of IntervalRange.
unittest
{
version(testStdDateTime)
{
{
Date dateFunc(in Date date)
{
return date;
}
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto ir = IntervalRange!(Date, Direction.fwd)(interval, &dateFunc);
}
{
TimeOfDay todFunc(in TimeOfDay tod)
{
return tod;
}
auto interval = Interval!TimeOfDay(TimeOfDay(12, 1, 7), TimeOfDay(14, 0, 0));
auto ir = IntervalRange!(TimeOfDay, Direction.fwd)(interval, &todFunc);
}
{
DateTime dtFunc(in DateTime dt)
{
return dt;
}
auto interval = Interval!DateTime(DateTime(2010, 7, 4, 12, 1, 7), DateTime(2012, 1, 7, 14, 0, 0));
auto ir = IntervalRange!(DateTime, Direction.fwd)(interval, &dtFunc);
}
{
SysTime stFunc(in SysTime st)
{
return cast(SysTime)st;
}
auto interval = Interval!SysTime(SysTime(DateTime(2010, 7, 4, 12, 1, 7)), SysTime(DateTime(2012, 1, 7, 14, 0, 0)));
auto ir = IntervalRange!(SysTime, Direction.fwd)(interval, &stFunc);
}
}
}
//Test IntervalRange's empty().
unittest
{
version(testStdDateTime)
{
//fwd
{
auto range = Interval!Date(Date(2010, 9, 19), Date(2010, 9, 21)).fwdRange(everyDayOfWeek!Date(DayOfWeek.fri));
assert(!range.empty);
range.popFront();
assert(range.empty);
const cRange = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).fwdRange(everyDayOfWeek!Date(DayOfWeek.fri));
static assert(__traits(compiles, cRange.empty));
//Apparently, creating an immutable IntervalRange!Date doesn't work, so we can't test if
//empty works with it. However, since an immutable range is pretty useless, it's no great loss.
}
//bwd
{
auto range = Interval!Date(Date(2010, 9, 19), Date(2010, 9, 21)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri));
assert(!range.empty);
range.popFront();
assert(range.empty);
const cRange = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri));
static assert(__traits(compiles, cRange.empty));
//Apparently, creating an immutable IntervalRange!Date doesn't work, so we can't test if
//empty works with it. However, since an immutable range is pretty useless, it's no great loss.
}
}
}
//Test IntervalRange's front.
unittest
{
version(testStdDateTime)
{
//fwd
{
auto emptyRange = Interval!Date(Date(2010, 9, 19), Date(2010, 9, 20)).fwdRange(everyDayOfWeek!Date(DayOfWeek.wed), PopFirst.yes);
assertThrown!DateTimeException((in IntervalRange!(Date, Direction.fwd) range){range.front;}(emptyRange));
auto range = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).fwdRange(everyDayOfWeek!Date(DayOfWeek.wed));
_assertPred!"=="(range.front, Date(2010, 7, 4));
auto poppedRange = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).fwdRange(everyDayOfWeek!Date(DayOfWeek.wed), PopFirst.yes);
_assertPred!"=="(poppedRange.front, Date(2010, 7, 7));
const cRange = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).fwdRange(everyDayOfWeek!Date(DayOfWeek.fri));
static assert(__traits(compiles, cRange.front));
}
//bwd
{
auto emptyRange = Interval!Date(Date(2010, 9, 19), Date(2010, 9, 20)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.wed), PopFirst.yes);
assertThrown!DateTimeException((in IntervalRange!(Date, Direction.bwd) range){range.front;}(emptyRange));
auto range = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.wed));
_assertPred!"=="(range.front, Date(2012, 1, 7));
auto poppedRange = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.wed), PopFirst.yes);
_assertPred!"=="(poppedRange.front, Date(2012, 1, 4));
const cRange = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri));
static assert(__traits(compiles, cRange.front));
}
}
}
//Test IntervalRange's popFront().
unittest
{
version(testStdDateTime)
{
//fwd
{
auto emptyRange = Interval!Date(Date(2010, 9, 19), Date(2010, 9, 20)).fwdRange(everyDayOfWeek!Date(DayOfWeek.wed), PopFirst.yes);
assertThrown!DateTimeException((IntervalRange!(Date, Direction.fwd) range){range.popFront();}(emptyRange));
auto range = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).fwdRange(everyDayOfWeek!Date(DayOfWeek.wed), PopFirst.yes);
auto expected = range.front;
foreach(date; range)
{
_assertPred!"=="(date, expected);
expected += dur!"days"(7);
}
_assertPred!"=="(walkLength(range), 79);
const cRange = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).fwdRange(everyDayOfWeek!Date(DayOfWeek.fri));
static assert(__traits(compiles, cRange.front));
}
//bwd
{
auto emptyRange = Interval!Date(Date(2010, 9, 19), Date(2010, 9, 20)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.wed), PopFirst.yes);
assertThrown!DateTimeException((IntervalRange!(Date, Direction.bwd) range){range.popFront();}(emptyRange));
auto range = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.wed), PopFirst.yes);
auto expected = range.front;
foreach(date; range)
{
_assertPred!"=="(date, expected);
expected += dur!"days"(-7);
}
_assertPred!"=="(walkLength(range), 79);
const cRange = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri));
static assert(!__traits(compiles, cRange.popFront()));
}
}
}
//Test IntervalRange's save.
unittest
{
version(testStdDateTime)
{
//fwd
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto func = everyDayOfWeek!Date(DayOfWeek.fri);
auto range = interval.fwdRange(func);
assert(range.save == range);
}
//bwd
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto func = everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri);
auto range = interval.bwdRange(func);
assert(range.save == range);
}
}
}
//Test IntervalRange's interval.
unittest
{
version(testStdDateTime)
{
//fwd
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto func = everyDayOfWeek!Date(DayOfWeek.fri);
auto range = interval.fwdRange(func);
assert(range.interval == interval);
const cRange = range;
static assert(__traits(compiles, cRange.interval));
}
//bwd
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto func = everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri);
auto range = interval.bwdRange(func);
assert(range.interval == interval);
const cRange = range;
static assert(__traits(compiles, cRange.interval));
}
}
}
//Test IntervalRange's func.
unittest
{
version(testStdDateTime)
{
//fwd
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto func = everyDayOfWeek!Date(DayOfWeek.fri);
auto range = interval.fwdRange(func);
assert(range.func == func);
}
//bwd
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto func = everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri);
auto range = interval.bwdRange(func);
assert(range.func == func);
}
}
}
//Test IntervalRange's direction.
unittest
{
version(testStdDateTime)
{
//fwd
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto func = everyDayOfWeek!Date(DayOfWeek.fri);
auto range = interval.fwdRange(func);
assert(range.direction == Direction.fwd);
const cRange = range;
static assert(__traits(compiles, cRange.direction));
}
//bwd
{
auto interval = Interval!Date(Date(2010, 7, 4), Date(2012, 1, 7));
auto func = everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri);
auto range = interval.bwdRange(func);
assert(range.direction == Direction.bwd);
const cRange = range;
static assert(__traits(compiles, cRange.direction));
}
}
}
/++
A range over a $(D PosInfInterval). It is an infinite range.
$(D PosInfIntervalRange) is only ever constructed by $(D PosInfInterval).
However, when it is constructed, it is given a function, $(D func), which
is used to generate the time points which are iterated over. $(D func)
takes a time point and returns a time point of the same type. So, for
instance, if you had a $(D PosInfInterval!Date), and you wanted to iterate
over all of the days in that interval, you would pass a function to
$(D PosInfInterval)'s $(D fwdRange) where that function took a $(D Date) and
returned a $(D Date) which was one day later. That function would then be
used by $(D PosInfIntervalRange)'s $(D popFront) to iterate over the
$(D Date)s in the interval - though obviously, since the range is infinite,
you would use a function such as $(D std.range.take) with it rather than
iterating over $(I all) of the dates.
As the interval goes to positive infinity, the range is always iterated over
forwards, never backwards. $(D func) must generate a time point going in
the proper direction of iteration, or a $(D DateTimeException) will be
thrown. So, the time points that $(D func) generates must be later in time
than the one passed to it. If it's either identical or earlier in time, then
a $(D DateTimeException) will be thrown.
+/
struct PosInfIntervalRange(TP)
if(isTimePoint!TP)
{
public:
/++
Params:
rhs = The $(D PosInfIntervalRange) to assign to this one.
+/
/+ref+/ PosInfIntervalRange opAssign(ref PosInfIntervalRange rhs) pure nothrow
{
_interval = rhs._interval;
_func = rhs._func;
return this;
}
/++
This is an infinite range, so it is never empty.
+/
enum bool empty = false;
/++
The first time point in the range.
+/
@property TP front() const pure nothrow
{
return _interval.begin;
}
/++
Pops $(D front) from the range, using $(D func) to generate the next
time point in the range.
Throws:
$(D DateTimeException) if the generated time point is less than
$(D front).
+/
void popFront()
{
auto begin = _func(_interval.begin);
_enforceCorrectDirection(begin);
_interval.begin = begin;
}
/++
Returns a copy of $(D this).
+/
@property PosInfIntervalRange save() pure nothrow
{
return this;
}
/++
The interval that this range currently covers.
+/
@property PosInfInterval!TP interval() const pure nothrow
{
return cast(PosInfInterval!TP)_interval;
}
/++
The function used to generate the next time point in the range.
+/
TP delegate(in TP) func() pure nothrow @property
{
return _func;
}
private:
/+
Params:
interval = The interval that this range covers.
func = The function used to generate the time points which are
iterated over.
+/
this(in PosInfInterval!TP interval, TP delegate(in TP) func) pure nothrow
{
_func = func;
_interval = interval;
}
/+
Throws:
$(D DateTimeException) if $(D_PARAME newTP) is in the wrong
direction.
+/
void _enforceCorrectDirection(in TP newTP, size_t line = __LINE__) const
{
enforce(newTP > _interval._begin,
new DateTimeException(format("Generated time point is before previous begin: prev [%s] new [%s]",
interval._begin,
newTP),
__FILE__,
line));
}
PosInfInterval!TP _interval;
TP delegate(in TP) _func;
}
//Test that PosInfIntervalRange satisfies the range predicates that it's supposed to satisfy.
unittest
{
version(testStdDateTime)
{
static assert(isInputRange!(PosInfIntervalRange!Date));
static assert(isForwardRange!(PosInfIntervalRange!Date));
static assert(isInfinite!(PosInfIntervalRange!Date));
//Commented out due to bug http://d.puremagic.com/issues/show_bug.cgi?id=4895
//static assert(!isOutputRange!(PosInfIntervalRange!Date, Date));
static assert(!isBidirectionalRange!(PosInfIntervalRange!Date));
static assert(!isRandomAccessRange!(PosInfIntervalRange!Date));
static assert(!hasSwappableElements!(PosInfIntervalRange!Date));
static assert(!hasAssignableElements!(PosInfIntervalRange!Date));
static assert(!hasLength!(PosInfIntervalRange!Date));
static assert(!hasSlicing!(PosInfIntervalRange!Date));
static assert(is(ElementType!(PosInfIntervalRange!Date) == Date));
static assert(is(ElementType!(PosInfIntervalRange!TimeOfDay) == TimeOfDay));
static assert(is(ElementType!(PosInfIntervalRange!DateTime) == DateTime));
static assert(is(ElementType!(PosInfIntervalRange!SysTime) == SysTime));
}
}
//Test construction of PosInfIntervalRange.
unittest
{
version(testStdDateTime)
{
{
Date dateFunc(in Date date)
{
return date;
}
auto posInfInterval = PosInfInterval!Date(Date(2010, 7, 4));
auto ir = PosInfIntervalRange!Date(posInfInterval, &dateFunc);
}
{
TimeOfDay todFunc(in TimeOfDay tod)
{
return tod;
}
auto posInfInterval = PosInfInterval!TimeOfDay(TimeOfDay(12, 1, 7));
auto ir = PosInfIntervalRange!(TimeOfDay)(posInfInterval, &todFunc);
}
{
DateTime dtFunc(in DateTime dt)
{
return dt;
}
auto posInfInterval = PosInfInterval!DateTime(DateTime(2010, 7, 4, 12, 1, 7));
auto ir = PosInfIntervalRange!(DateTime)(posInfInterval, &dtFunc);
}
{
SysTime stFunc(in SysTime st)
{
return cast(SysTime)st;
}
auto posInfInterval = PosInfInterval!SysTime(SysTime(DateTime(2010, 7, 4, 12, 1, 7)));
auto ir = PosInfIntervalRange!(SysTime)(posInfInterval, &stFunc);
}
}
}
//Test PosInfIntervalRange's front.
unittest
{
version(testStdDateTime)
{
auto range = PosInfInterval!Date(Date(2010, 7, 4)).fwdRange(everyDayOfWeek!Date(DayOfWeek.wed));
_assertPred!"=="(range.front, Date(2010, 7, 4));
auto poppedRange = PosInfInterval!Date(Date(2010, 7, 4)).fwdRange(everyDayOfWeek!Date(DayOfWeek.wed), PopFirst.yes);
_assertPred!"=="(poppedRange.front, Date(2010, 7, 7));
const cRange = PosInfInterval!Date(Date(2010, 7, 4)).fwdRange(everyDayOfWeek!Date(DayOfWeek.fri));
static assert(__traits(compiles, cRange.front));
}
}
//Test PosInfIntervalRange's popFront().
unittest
{
version(testStdDateTime)
{
auto range = PosInfInterval!Date(Date(2010, 7, 4)).fwdRange(everyDayOfWeek!Date(DayOfWeek.wed), PopFirst.yes);
auto expected = range.front;
foreach(date; take(range, 79))
{
_assertPred!"=="(date, expected);
expected += dur!"days"(7);
}
const cRange = PosInfInterval!Date(Date(2010, 7, 4)).fwdRange(everyDayOfWeek!Date(DayOfWeek.fri));
static assert(!__traits(compiles, cRange.popFront()));
}
}
//Test PosInfIntervalRange's save.
unittest
{
version(testStdDateTime)
{
auto interval = PosInfInterval!Date(Date(2010, 7, 4));
auto func = everyDayOfWeek!Date(DayOfWeek.fri);
auto range = interval.fwdRange(func);
assert(range.save == range);
}
}
//Test PosInfIntervalRange's interval.
unittest
{
version(testStdDateTime)
{
auto interval = PosInfInterval!Date(Date(2010, 7, 4));
auto func = everyDayOfWeek!Date(DayOfWeek.fri);
auto range = interval.fwdRange(func);
assert(range.interval == interval);
const cRange = range;
static assert(__traits(compiles, cRange.interval));
}
}
//Test PosInfIntervalRange's func.
unittest
{
version(testStdDateTime)
{
auto interval = PosInfInterval!Date(Date(2010, 7, 4));
auto func = everyDayOfWeek!Date(DayOfWeek.fri);
auto range = interval.fwdRange(func);
assert(range.func == func);
}
}
/++
A range over a $(D NegInfInterval). It is an infinite range.
$(D NegInfIntervalRange) is only ever constructed by $(D NegInfInterval).
However, when it is constructed, it is given a function, $(D func), which
is used to generate the time points which are iterated over. $(D func)
takes a time point and returns a time point of the same type. So, for
instance, if you had a $(D NegInfInterval!Date), and you wanted to iterate
over all of the days in that interval, you would pass a function to
$(D NegInfInterval)'s $(D bwdRange) where that function took a $(D Date) and
returned a $(D Date) which was one day earlier. That function would then be
used by $(D NegInfIntervalRange)'s $(D popFront) to iterate over the
$(D Date)s in the interval - though obviously, since the range is infinite,
you would use a function such as $(D std.range.take) with it rather than
iterating over $(I all) of the dates.
As the interval goes to negative infinity, the range is always iterated over
backwards, never forwards. $(D func) must generate a time point going in
the proper direction of iteration, or a $(D DateTimeException) will be
thrown. So, the time points that $(D func) generates must be earlier in time
than the one passed to it. If it's either identical or later in time, then a
$(D DateTimeException) will be thrown.
Also note that while normally the $(D end) of an interval is excluded from
it, $(D NegInfIntervalRange) treats it as if it were included. This allows
for the same behavior as you get with $(D PosInfIntervalRange). This works
because none of $(D NegInfInterval)'s functions which care about whether
$(D end) is included or excluded are ever called by
$(D NegInfIntervalRange). $(D interval) returns a normal interval, so any
$(D NegInfInterval) functions which are called on it which care about
whether $(D end) is included or excluded will treat $(D end) as excluded.
+/
struct NegInfIntervalRange(TP)
if(isTimePoint!TP)
{
public:
/++
Params:
rhs = The $(D NegInfIntervalRange) to assign to this one.
+/
/+ref+/ NegInfIntervalRange opAssign(ref NegInfIntervalRange rhs) pure nothrow
{
_interval = rhs._interval;
_func = rhs._func;
return this;
}
/++
This is an infinite range, so it is never empty.
+/
enum bool empty = false;
/++
The first time point in the range.
+/
@property TP front() const pure nothrow
{
return _interval.end;
}
/++
Pops $(D front) from the range, using $(D func) to generate the next
time point in the range.
Throws:
$(D DateTimeException) if the generated time point is greater than
$(D front).
+/
void popFront()
{
auto end = _func(_interval.end);
_enforceCorrectDirection(end);
_interval.end = end;
}
/++
Returns a copy of $(D this).
+/
@property NegInfIntervalRange save() pure nothrow
{
return this;
}
/++
The interval that this range currently covers.
+/
@property NegInfInterval!TP interval() const pure nothrow
{
return cast(NegInfInterval!TP)_interval;
}
/++
The function used to generate the next time point in the range.
+/
TP delegate(in TP) func() pure nothrow @property
{
return _func;
}
private:
/+
Params:
interval = The interval that this range covers.
func = The function used to generate the time points which are
iterated over.
+/
this(in NegInfInterval!TP interval, TP delegate(in TP) func) pure nothrow
{
_func = func;
_interval = interval;
}
/+
Throws:
$(D DateTimeException) if $(D_PARAM newTP) is in the wrong
direction.
+/
void _enforceCorrectDirection(in TP newTP, size_t line = __LINE__) const
{
enforce(newTP < _interval._end,
new DateTimeException(format("Generated time point is before previous end: prev [%s] new [%s]",
interval._end,
newTP),
__FILE__,
line));
}
NegInfInterval!TP _interval;
TP delegate(in TP) _func;
}
//Test that NegInfIntervalRange satisfies the range predicates that it's supposed to satisfy.
unittest
{
version(testStdDateTime)
{
static assert(isInputRange!(NegInfIntervalRange!Date));
static assert(isForwardRange!(NegInfIntervalRange!Date));
static assert(isInfinite!(NegInfIntervalRange!Date));
//Commented out due to bug http://d.puremagic.com/issues/show_bug.cgi?id=4895
//static assert(!isOutputRange!(NegInfIntervalRange!Date, Date));
static assert(!isBidirectionalRange!(NegInfIntervalRange!Date));
static assert(!isRandomAccessRange!(NegInfIntervalRange!Date));
static assert(!hasSwappableElements!(NegInfIntervalRange!Date));
static assert(!hasAssignableElements!(NegInfIntervalRange!Date));
static assert(!hasLength!(NegInfIntervalRange!Date));
static assert(!hasSlicing!(NegInfIntervalRange!Date));
static assert(is(ElementType!(NegInfIntervalRange!Date) == Date));
static assert(is(ElementType!(NegInfIntervalRange!TimeOfDay) == TimeOfDay));
static assert(is(ElementType!(NegInfIntervalRange!DateTime) == DateTime));
}
}
//Test construction of NegInfIntervalRange.
unittest
{
version(testStdDateTime)
{
{
Date dateFunc(in Date date)
{
return date;
}
auto negInfInterval = NegInfInterval!Date(Date(2012, 1, 7));
auto ir = NegInfIntervalRange!Date(negInfInterval, &dateFunc);
}
{
TimeOfDay todFunc(in TimeOfDay tod)
{
return tod;
}
auto negInfInterval = NegInfInterval!TimeOfDay(TimeOfDay(14, 0, 0));
auto ir = NegInfIntervalRange!(TimeOfDay)(negInfInterval, &todFunc);
}
{
DateTime dtFunc(in DateTime dt)
{
return dt;
}
auto negInfInterval = NegInfInterval!DateTime(DateTime(2012, 1, 7, 14, 0, 0));
auto ir = NegInfIntervalRange!(DateTime)(negInfInterval, &dtFunc);
}
{
SysTime stFunc(in SysTime st)
{
return cast(SysTime)(st);
}
auto negInfInterval = NegInfInterval!SysTime(SysTime(DateTime(2012, 1, 7, 14, 0, 0)));
auto ir = NegInfIntervalRange!(SysTime)(negInfInterval, &stFunc);
}
}
}
//Test NegInfIntervalRange's front.
unittest
{
version(testStdDateTime)
{
auto range = NegInfInterval!Date(Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.wed));
_assertPred!"=="(range.front, Date(2012, 1, 7));
auto poppedRange = NegInfInterval!Date(Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.wed), PopFirst.yes);
_assertPred!"=="(poppedRange.front, Date(2012, 1, 4));
const cRange = NegInfInterval!Date(Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri));
static assert(__traits(compiles, cRange.front));
}
}
//Test NegInfIntervalRange's popFront().
unittest
{
version(testStdDateTime)
{
auto range = NegInfInterval!Date(Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.wed), PopFirst.yes);
auto expected = range.front;
foreach(date; take(range, 79))
{
_assertPred!"=="(date, expected);
expected += dur!"days"(-7);
}
const cRange = NegInfInterval!Date(Date(2012, 1, 7)).bwdRange(everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri));
static assert(!__traits(compiles, cRange.popFront()));
}
}
//Test NegInfIntervalRange's save.
unittest
{
version(testStdDateTime)
{
auto interval = NegInfInterval!Date(Date(2012, 1, 7));
auto func = everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri);
auto range = interval.bwdRange(func);
assert(range.save == range);
}
}
//Test NegInfIntervalRange's interval.
unittest
{
version(testStdDateTime)
{
auto interval = NegInfInterval!Date(Date(2012, 1, 7));
auto func = everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri);
auto range = interval.bwdRange(func);
assert(range.interval == interval);
const cRange = range;
static assert(__traits(compiles, cRange.interval));
}
}
//Test NegInfIntervalRange's func.
unittest
{
version(testStdDateTime)
{
auto interval = NegInfInterval!Date(Date(2012, 1, 7));
auto func = everyDayOfWeek!(Date, Direction.bwd)(DayOfWeek.fri);
auto range = interval.bwdRange(func);
assert(range.func == func);
}
}
//==============================================================================
// Section with time zones.
//==============================================================================
/++
Represents a time zone. It is used with $(D SysTime) to indicate the time
zone of a $(D SysTime).
+/
abstract class TimeZone
{
public:
/++
The name of the time zone per the TZ Database. This is the name used to
get a $(D TimeZone) by name with $(D TimeZone.getTimeZone).
See_Also:
$(WEB en.wikipedia.org/wiki/Tz_database, Wikipedia entry on TZ
Database)
$(WEB en.wikipedia.org/wiki/List_of_tz_database_time_zones, List of
Time Zones)
+/
@property string name() const nothrow
{
return _name;
}
/++
Typically, the abbreviation (generally 3 or 4 letters) for the time zone
when DST is $(I not) in effect (e.g. PST). It is not necessarily unique.
However, on Windows, it may be the unabbreviated name (e.g. Pacific
Standard Time). Regardless, it is not the same as name.
+/
@property string stdName() const nothrow
{
return _stdName;
}
/++
Typically, the abbreviation (generally 3 or 4 letters) for the time zone
when DST $(I is) in effect (e.g. PDT). It is not necessarily unique.
However, on Windows, it may be the unabbreviated name (e.g. Pacific
Daylight Time). Regardless, it is not the same as name.
+/
@property string dstName() const nothrow
{
return _dstName;
}
/++
Whether this time zone has Daylight Savings Time at any point in time.
Note that for some time zone types it may not have DST for current dates
but will still return true for $(D hasDST) because the time zone did at
some point have DST.
+/
@property abstract bool hasDST() const nothrow;
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D.
in UTC time (i.e. std time) and returns whether DST is effect in this
time zone at the given point in time.
Params:
stdTime = The UTC time that needs to be checked for DST in this time
zone.
+/
abstract bool dstInEffect(long stdTime) const nothrow;
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D.
in UTC time (i.e. std time) and converts it to this time zone's time.
Params:
stdTime = The UTC time that needs to be adjusted to this time zone's
time.
+/
abstract long utcToTZ(long stdTime) const nothrow;
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D.
in this time zone's time and converts it to UTC (i.e. std time).
Params:
adjTime = The time in this time zone that needs to be adjusted to
UTC time.
+/
abstract long tzToUTC(long adjTime) const nothrow;
/++
Returns a $(D TimeZone) with the give name per the TZ Database.
This returns a $(D PosixTimeZone) on Posix systems and a
$(D WindowsTimeZone) on Windows systems. If you want a
$(D PosixTimeZone) on Windows, then call $(D PosixTimeZone.getTimeZone)
directly and give it the location of the TZ Database time zone files on
disk.
On Windows, the given TZ Database name is converted to the corresponding
time zone name on Windows prior to calling
$(D WindowsTimeZone.getTimeZone). So, this function allows you to use
the same time zone names on both Windows and Posix systems.
See_Also:
$(WEB en.wikipedia.org/wiki/Tz_database, Wikipedia entry on TZ
Database)
$(WEB en.wikipedia.org/wiki/List_of_tz_database_time_zones, List of
Time Zones)
$(WEB unicode.org/repos/cldr-tmp/trunk/diff/supplemental/zone_tzid.html,
Windows <-> TZ Database Name Conversion Table)
Params:
name = The TZ Database name of the time zone that you're looking for.
Throws:
$(D DateTimeException) if the given time zone could not be found.
Examples:
--------------------
auto tz = TimeZone.getTimeZone("America/Los_Angeles");
--------------------
+/
static immutable(TimeZone) getTimeZone(string name)
{
version(Posix)
return PosixTimeZone.getTimeZone(name);
else version(Windows)
return WindowsTimeZone.getTimeZone(tzDatabaseNameToWindowsTZName(name));
}
//Since reading in the time zone files could be expensive, most unit tests
//are consolidated into this one unittest block which minimizes how often it
//reads a time zone file.
version(testStdDateTime) unittest
{
version(Posix) scope(exit) clearTZEnvVar();
static void testTZ(string tzName,
string stdName,
string dstName,
int utcOffset,
int dstOffset,
bool north = true)
{
scope(failure) writefln("Failed time zone: %s", tzName);
immutable tz = TimeZone.getTimeZone(tzName);
immutable hasDST = dstOffset != 0;
version(Posix)
_assertPred!"=="(tz.name, tzName);
else version(Windows)
_assertPred!"=="(tz.name, stdName);
_assertPred!"=="(tz.stdName, stdName);
_assertPred!"=="(tz.dstName, dstName);
_assertPred!"=="(tz.hasDST, hasDST);
immutable stdDate = DateTime(2010, north ? 1 : 7, 1, 6, 0, 0);
immutable dstDate = DateTime(2010, north ? 7 : 1, 1, 6, 0, 0);
auto std = SysTime(stdDate, tz);
auto dst = SysTime(dstDate, tz);
auto stdUTC = SysTime(stdDate - dur!"minutes"(utcOffset), UTC());
auto dstUTC = SysTime(stdDate - dur!"minutes"(utcOffset + dstOffset), UTC());
assert(!std.dstInEffect);
_assertPred!"=="(dst.dstInEffect, hasDST);
_assertPred!"=="(cast(DateTime)std, stdDate);
_assertPred!"=="(cast(DateTime)dst, dstDate);
_assertPred!"=="(std, stdUTC);
version(Posix)
{
setTZEnvVar(tzName);
static void testTM(in SysTime st)
{
time_t unixTime = st.toUnixTime();
tm* osTimeInfo = localtime(&unixTime);
tm ourTimeInfo = st.toTM();
_assertPred!"=="(ourTimeInfo.tm_sec, osTimeInfo.tm_sec);
_assertPred!"=="(ourTimeInfo.tm_min, osTimeInfo.tm_min);
_assertPred!"=="(ourTimeInfo.tm_hour, osTimeInfo.tm_hour);
_assertPred!"=="(ourTimeInfo.tm_min, osTimeInfo.tm_min);
_assertPred!"=="(ourTimeInfo.tm_mday, osTimeInfo.tm_mday);
_assertPred!"=="(ourTimeInfo.tm_mon, osTimeInfo.tm_mon);
_assertPred!"=="(ourTimeInfo.tm_year, osTimeInfo.tm_year);
_assertPred!"=="(ourTimeInfo.tm_wday, osTimeInfo.tm_wday);
_assertPred!"=="(ourTimeInfo.tm_yday, osTimeInfo.tm_yday);
_assertPred!"=="(ourTimeInfo.tm_isdst, osTimeInfo.tm_isdst);
_assertPred!"=="(ourTimeInfo.tm_gmtoff, osTimeInfo.tm_gmtoff);
_assertPred!"=="(to!string(ourTimeInfo.tm_zone),
to!string(osTimeInfo.tm_zone));
}
testTM(std);
testTM(dst);
//Apparently, right/ does not exist on Mac OS X. I don't know
//whether or not it exists on FreeBSD. It's rather pointless
//normally, since the Posix standard requires that leap seconds
//be ignored, so it does make some sense that right/ wouldn't
//be there, but since PosixTimeZone _does_ use leap seconds if
//the time zone file does, we'll test that functionality if the
//appropriate files exist.
if((PosixTimeZone.defaultTZDatabaseDir ~ "right/" ~ tzName).exists())
{
auto leapTZ = PosixTimeZone.getTimeZone("right/" ~ tzName);
assert(leapTZ.name == "right/" ~ tzName);
assert(leapTZ.stdName == stdName);
assert(leapTZ.dstName == dstName);
assert(leapTZ.hasDST == hasDST);
auto leapSTD = SysTime(std.stdTime, leapTZ);
auto leapDST = SysTime(dst.stdTime, leapTZ);
assert(!leapSTD.dstInEffect);
assert(leapDST.dstInEffect == hasDST);
_assertPred!"=="(leapSTD.stdTime, std.stdTime);
_assertPred!"=="(leapDST.stdTime, dst.stdTime);
//Whenever a leap second is added/removed,
//this will have to be adjusted.
enum leapDiff = convert!("seconds", "hnsecs")(24);
_assertPred!"=="(leapSTD.adjTime - leapDiff, std.adjTime);
_assertPred!"=="(leapDST.adjTime - leapDiff, dst.adjTime);
}
}
}
version(Posix)
{
version(FreeBSD) enum utcZone = "Etc/UTC";
version(linux) enum utcZone = "UTC";
version(OSX) enum utcZone = "UTC";
testTZ("America/Los_Angeles", "PST", "PDT", -8 * 60, 60);
testTZ("America/New_York", "EST", "EDT", -5 * 60, 60);
testTZ(utcZone, "UTC", "UTC", 0, 0);
testTZ("Europe/Paris", "CET", "CEST", 60, 60);
testTZ("Australia/Adelaide", "CST", "CST", 9 * 60 + 30, 60, false);
assertThrown!DateTimeException(PosixTimeZone.getTimeZone("hello_world"));
}
version(Windows)
{
testTZ("America/Los_Angeles", "Pacific Standard Time",
"Pacific Daylight Time", -8 * 60, 60);
testTZ("America/New_York", "Eastern Standard Time",
"Eastern Daylight Time", -5 * 60, 60);
testTZ("Atlantic/Reykjavik", "Greenwich Standard Time",
"Greenwich Daylight Time", 0, 0);
testTZ("Europe/Paris", "Romance Standard Time",
"Romance Daylight Time", 60, 60);
testTZ("Australia/Adelaide", "Cen. Australia Standard Time",
"Cen. Australia Daylight Time", 9 * 60 + 30, 60, false);
assertThrown!DateTimeException(WindowsTimeZone.getTimeZone("hello_world"));
}
}
/++
Returns a list of the names of the time zones installed on the system.
You can provide a sub-name to narrow down the list of time zones (which
will likely be in the thousands if you get them all). For example,
if you pass in "America" as the sub-name, then only the time zones which
begin with "America" will be returned.
On Windows, this function will convert the Windows time zone names to
the corresponding TZ Database names with
$(D windowsTZNameToTZDatabaseName). If you want the actual Windows time
zone names, use $(D WindowsTimeZone.getInstalledTZNames) directly.
Params:
subName = The first part of the time zones that you want.
Throws:
$(D FileException) on Posix systems if it fails to read from disk.
$(D DateTimeException) on Windows systems if it fails to read the
registry.
+/
static string[] getInstalledTZNames(string subName = "")
{
version(Posix)
return PosixTimeZone.getInstalledTZNames(subName);
else version(Windows)
{
auto windowsNames = WindowsTimeZone.getInstalledTZNames();
auto retval = appender!(string[])();
foreach(winName; windowsNames)
{
auto tzName = windowsTZNameToTZDatabaseName(winName);
if(tzName.startsWith(subName))
retval.put(tzName);
}
sort(retval.data);
return retval.data;
}
}
unittest
{
version(testStdDateTime)
{
static void testPZSuccess(string tzName)
{
scope(failure) writefln("TZName which threw: %s", tzName);
TimeZone.getTimeZone(tzName);
}
auto tzNames = getInstalledTZNames();
foreach(tzName; tzNames)
assertNotThrown!DateTimeException(testPZSuccess(tzName));
}
}
private:
/+
Params:
name = The TZ Database name for the time zone.
stdName = The abbreviation for the time zone during std time.
dstName = The abbreviation for the time zone during DST.
+/
this(string name, string stdName, string dstName) immutable pure
{
_name = name;
_stdName = stdName;
_dstName = dstName;
}
immutable string _name;
immutable string _stdName;
immutable string _dstName;
}
/++
A TimeZone which represents the current local time zone on
the system running your program.
This uses the underlying C calls to adjust the time rather than using
specific D code based off of system settings to calculate the time such as
$(D PosixTimeZone) and $(D WindowsTimeZone) do. That also means that it will
use whatever the current time zone is on the system, even if the system's
time zone changes while the program is running.
+/
final class LocalTime : TimeZone
{
public:
/++
$(D LocalTime) is a singleton class. $(D LocalTime) returns its only
instance.
+/
static immutable(LocalTime) opCall() pure nothrow
{
return _localTime;
}
version(StdDdoc)
{
/++
The name of the time zone per the TZ Database. This is the name used to
get a $(D TimeZone) by name with $(D TimeZone.getTimeZone).
Note that this always returns the empty string. This is because time
zones cannot be uniquely identified by the attributes given by the
OS (such as the $(D stdName) and $(D dstName)), and neither Posix
systems nor Windows systems provide an easy way to get the TZ
Database name of the local time zone.
See_Also:
$(WEB en.wikipedia.org/wiki/Tz_database, Wikipedia entry on TZ
Database)
$(WEB en.wikipedia.org/wiki/List_of_tz_database_time_zones, List
of Time Zones)
+/
@property override string name() const nothrow;
}
/++
Typically, the abbreviation (generally 3 or 4 letters) for the time zone
when DST is $(I not) in effect (e.g. PST). It is not necessarily unique.
However, on Windows, it may be the unabbreviated name (e.g. Pacific
Standard Time). Regardless, it is not the same as name.
This property is overridden because the local time of the system could
change while the program is running and we need to determine it
dynamically rather than it being fixed like it would be with most time
zones.
+/
@property override string stdName() const nothrow
{
version(Posix)
{
try
return to!string(tzname[0]);
catch(Exception e)
assert(0, "to!string(tzname[0]) failed.");
}
else version(Windows)
{
try
{
TIME_ZONE_INFORMATION tzInfo;
GetTimeZoneInformation(&tzInfo);
//Cannot use to!string() like this should, probably due to bug http://d.puremagic.com/issues/show_bug.cgi?id=5016
//return to!string(tzInfo.StandardName);
wchar[32] str;
foreach(i, ref wchar c; str)
c = tzInfo.StandardName[i];
string retval;
foreach(dchar c; str)
{
if(c == '\0')
break;
retval ~= c;
}
return retval;
}
catch(Exception e)
assert(0, "GetTimeZoneInformation() threw.");
}
}
unittest
{
version(testStdDateTime)
{
assert(LocalTime().stdName !is null);
version(Posix)
{
scope(exit) clearTZEnvVar();
setTZEnvVar("America/Los_Angeles");
_assertPred!"=="(LocalTime().stdName, "PST");
setTZEnvVar("America/New_York");
_assertPred!"=="(LocalTime().stdName, "EST");
}
}
}
/++
Typically, the abbreviation (generally 3 or 4 letters) for the time zone
when DST $(I is) in effect (e.g. PDT). It is not necessarily unique.
However, on Windows, it may be the unabbreviated name (e.g. Pacific
Daylight Time). Regardless, it is not the same as name.
This property is overridden because the local time of the system could
change while the program is running and we need to determine it
dynamically rather than it being fixed like it would be with most time
zones.
+/
@property override string dstName() const nothrow
{
version(Posix)
{
try
return to!string(tzname[1]);
catch(Exception e)
assert(0, "to!string(tzname[1]) failed.");
}
else version(Windows)
{
try
{
TIME_ZONE_INFORMATION tzInfo;
GetTimeZoneInformation(&tzInfo);
//Cannot use to!string() like this should, probably due to bug http://d.puremagic.com/issues/show_bug.cgi?id=5016
//return to!string(tzInfo.DaylightName);
wchar[32] str;
foreach(i, ref wchar c; str)
c = tzInfo.DaylightName[i];
string retval;
foreach(dchar c; str)
{
if(c == '\0')
break;
retval ~= c;
}
return retval;
}
catch(Exception e)
assert(0, "GetTimeZoneInformation() threw.");
}
}
unittest
{
version(testStdDateTime)
{
assert(LocalTime().dstName !is null);
version(Posix)
{
scope(exit) clearTZEnvVar();
setTZEnvVar("America/Los_Angeles");
_assertPred!"=="(LocalTime().dstName, "PDT");
setTZEnvVar("America/New_York");
_assertPred!"=="(LocalTime().dstName, "EDT");
}
}
}
/++
Whether this time zone has Daylight Savings Time at any point in time.
Note that for some time zone types it may not have DST for current
dates but will still return true for $(D hasDST) because the time zone
did at some point have DST.
+/
@property override bool hasDST() const nothrow
{
version(Posix)
{
static if(is(typeof(daylight)))
return cast(bool)(daylight);
else
{
try
{
auto currYear = (cast(Date)Clock.currTime()).year;
auto janOffset = SysTime(Date(currYear, 1, 4), this).stdTime -
SysTime(Date(currYear, 1, 4), UTC()).stdTime;
auto julyOffset = SysTime(Date(currYear, 7, 4), this).stdTime -
SysTime(Date(currYear, 7, 4), UTC()).stdTime;
return janOffset != julyOffset;
}
catch(Exception e)
assert(0, "Clock.currTime() threw.");
}
}
else version(Windows)
{
try
{
TIME_ZONE_INFORMATION tzInfo;
GetTimeZoneInformation(&tzInfo);
return tzInfo.DaylightDate.wMonth != 0;
}
catch(Exception e)
assert(0, "GetTimeZoneInformation() threw.");
}
}
unittest
{
version(testStdDateTime)
{
LocalTime().hasDST;
version(Posix)
{
scope(exit) clearTZEnvVar();
setTZEnvVar("America/Los_Angeles");
assert(LocalTime().hasDST);
setTZEnvVar("America/New_York");
assert(LocalTime().hasDST);
setTZEnvVar("UTC");
assert(!LocalTime().hasDST);
}
}
}
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D.
in UTC time (i.e. std time) and returns whether DST is in effect in this
time zone at the given point in time.
Params:
stdTime = The UTC time that needs to be checked for DST in this time
zone.
+/
override bool dstInEffect(long stdTime) const nothrow
{
time_t unixTime = stdTimeToUnixTime(stdTime);
version(Posix)
{
tm* timeInfo = localtime(&unixTime);
return cast(bool)(timeInfo.tm_isdst);
}
else version(Windows)
{
//Apparently Windows isn't smart enough to deal with negative time_t.
if(unixTime >= 0)
{
tm* timeInfo = localtime(&unixTime);
if(timeInfo)
return cast(bool)(timeInfo.tm_isdst);
}
TIME_ZONE_INFORMATION tzInfo;
try
GetTimeZoneInformation(&tzInfo);
catch(Exception e)
assert(0, "The impossible happened. GetTimeZoneInformation() threw.");
return WindowsTimeZone._dstInEffect(&tzInfo, stdTime);
}
}
unittest
{
version(testStdDateTime)
{
auto currTime = Clock.currStdTime;
LocalTime().dstInEffect(currTime);
version(Posix)
{
scope(exit) clearTZEnvVar();
auto std = SysTime(DateTime(2010, 1, 1, 12, 0, 0), LocalTime());
auto dst = SysTime(DateTime(2010, 7, 1, 12, 0, 0), LocalTime());
setTZEnvVar("America/Los_Angeles");
assert(!LocalTime().dstInEffect(std.stdTime));
assert(LocalTime().dstInEffect(dst.stdTime));
assert(!std.dstInEffect);
assert(dst.dstInEffect);
setTZEnvVar("America/New_York");
assert(!LocalTime().dstInEffect(std.stdTime));
assert(LocalTime().dstInEffect(dst.stdTime));
assert(!std.dstInEffect);
assert(dst.dstInEffect);
}
}
}
/++
Returns hnsecs in the local time zone using the standard C function
calls on Posix systems and the standard Windows system calls on Windows
systems to adjust the time to the appropriate time zone from std time.
Params:
stdTime = The UTC time that needs to be adjusted to this time zone's
time.
See_Also:
$(D TimeZone.utcToTZ)
+/
override long utcToTZ(long stdTime) const nothrow
{
version(Posix)
{
time_t unixTime = stdTimeToUnixTime(stdTime);
tm* timeInfo = localtime(&unixTime);
return stdTime + convert!("seconds", "hnsecs")(timeInfo.tm_gmtoff);
}
else version(Windows)
{
TIME_ZONE_INFORMATION tzInfo;
try
GetTimeZoneInformation(&tzInfo);
catch(Exception e)
assert(0, "GetTimeZoneInformation() threw.");
return WindowsTimeZone._utcToTZ(&tzInfo, stdTime, hasDST);
}
}
unittest
{
version(testStdDateTime)
{
LocalTime().utcToTZ(0);
version(Posix)
{
scope(exit) clearTZEnvVar();
{
setTZEnvVar("America/Los_Angeles");
auto std = SysTime(Date(2010, 1, 1));
auto dst = SysTime(Date(2010, 7, 1));
_assertPred!"=="(LocalTime().utcToTZ(std.stdTime), SysTime(DateTime(2009, 12, 31, 16, 0, 0)).stdTime);
_assertPred!"=="(LocalTime().utcToTZ(dst.stdTime), SysTime(DateTime(2010, 6, 30, 17, 0, 0)).stdTime);
}
{
setTZEnvVar("America/New_York");
auto std = SysTime(Date(2010, 1, 1));
auto dst = SysTime(Date(2010, 7, 1));
_assertPred!"=="(LocalTime().utcToTZ(std.stdTime), SysTime(DateTime(2009, 12, 31, 19, 0, 0)).stdTime);
_assertPred!"=="(LocalTime().utcToTZ(dst.stdTime), SysTime(DateTime(2010, 6, 30, 20, 0, 0)).stdTime);
}
}
}
}
/++
Returns std time using the standard C function calls on Posix systems
and the standard Windows system calls on Windows systems to adjust the
time to UTC from the appropriate time zone.
See_Also:
$(D TimeZone.tzToUTC)
Params:
adjTime = The time in this time zone that needs to be adjusted to
UTC time.
+/
override long tzToUTC(long adjTime) const nothrow
{
version(Posix)
{
time_t unixTime = stdTimeToUnixTime(adjTime);
tm* timeInfo = localtime(&unixTime);
return adjTime - convert!("seconds", "hnsecs")(timeInfo.tm_gmtoff);
}
else version(Windows)
{
TIME_ZONE_INFORMATION tzInfo;
try
GetTimeZoneInformation(&tzInfo);
catch(Exception e)
assert(0, "GetTimeZoneInformation() threw.");
return WindowsTimeZone._tzToUTC(&tzInfo, adjTime, hasDST);
}
}
unittest
{
version(testStdDateTime)
{
LocalTime().tzToUTC(0);
_assertPred!"=="(LocalTime().tzToUTC(LocalTime().utcToTZ(0)), 0);
_assertPred!"=="(LocalTime().utcToTZ(LocalTime().tzToUTC(0)), 0);
version(Posix)
{
scope(exit) clearTZEnvVar();
{
setTZEnvVar("America/Los_Angeles");
auto std = SysTime(DateTime(2009, 12, 31, 16, 0, 0));
auto dst = SysTime(DateTime(2010, 6, 30, 17, 0, 0));
_assertPred!"=="(LocalTime().tzToUTC(std.stdTime), SysTime(Date(2010, 1, 1)).stdTime);
_assertPred!"=="(LocalTime().tzToUTC(dst.stdTime), SysTime(Date(2010, 7, 1)).stdTime);
}
{
setTZEnvVar("America/New_York");
auto std = SysTime(DateTime(2009, 12, 31, 19, 0, 0));
auto dst = SysTime(DateTime(2010, 6, 30, 20, 0, 0));
_assertPred!"=="(LocalTime().tzToUTC(std.stdTime), SysTime(Date(2010, 1, 1)).stdTime);
_assertPred!"=="(LocalTime().tzToUTC(dst.stdTime), SysTime(Date(2010, 7, 1)).stdTime);
}
}
}
}
private:
this() immutable pure
{
super("", "", "");
}
static immutable LocalTime _localTime;
shared static this()
{
tzset();
_localTime = new immutable(LocalTime)();
}
}
/++
A $(D TimeZone) which represents UTC.
+/
final class UTC : TimeZone
{
public:
/++
$(D UTC) is a singleton class. $(D UTC) returns its only instance.
+/
static immutable(UTC) opCall() pure nothrow
{
return _utc;
}
/++
Always returns false.
+/
@property override bool hasDST() const nothrow
{
return false;
}
/++
Always returns false.
+/
override bool dstInEffect(long stdTime) const nothrow
{
return false;
}
/++
Returns the given hnsecs without changing them at all.
Params:
stdTime = The UTC time that needs to be adjusted to this time zone's
time.
See_Also:
$(D TimeZone.utcToTZ)
+/
override long utcToTZ(long stdTime) const nothrow
{
return stdTime;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(UTC().utcToTZ(0), 0);
version(Posix)
{
scope(exit) clearTZEnvVar();
setTZEnvVar("UTC");
auto std = SysTime(Date(2010, 1, 1));
auto dst = SysTime(Date(2010, 7, 1));
_assertPred!"=="(UTC().utcToTZ(std.stdTime), std.stdTime);
_assertPred!"=="(UTC().utcToTZ(dst.stdTime), dst.stdTime);
}
}
}
/++
Returns the given hnsecs without changing them at all.
See_Also:
$(D TimeZone.tzToUTC)
Params:
adjTime = The time in this time zone that needs to be adjusted to
UTC time.
+/
override long tzToUTC(long adjTime) const nothrow
{
return adjTime;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(UTC().tzToUTC(0), 0);
version(Posix)
{
scope(exit) clearTZEnvVar();
setTZEnvVar("UTC");
auto std = SysTime(Date(2010, 1, 1));
auto dst = SysTime(Date(2010, 7, 1));
_assertPred!"=="(UTC().tzToUTC(std.stdTime), std.stdTime);
_assertPred!"=="(UTC().tzToUTC(dst.stdTime), dst.stdTime);
}
}
}
private:
this() immutable pure
{
super("UTC", "UTC", "UTC");
}
static immutable UTC _utc;
shared static this()
{
_utc = new immutable(UTC)();
}
}
/++
Represents a time zone with an offset (in minutes, west is negative) from
UTC but no DST.
It's primarily used as the time zone in the result of $(D SysTime)'s
$(D fromISOString), $(D fromISOExtString), and $(D fromSimpleString).
$(D name) and $(D dstName) are always the empty string since this time zone
has no DST, and while it may be meant to represent a time zone which is in
the TZ Database, obviously it's not likely to be following the exact rules
of any of the time zones in the TZ Database, so it makes no sense to set it.
+/
final class SimpleTimeZone : TimeZone
{
public:
/++
Always returns false.
+/
@property override bool hasDST() const nothrow
{
return false;
}
/++
Always returns false.
+/
override bool dstInEffect(long stdTime) const nothrow
{
return false;
}
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D.
in UTC time (i.e. std time) and converts it to this time zone's time.
Params:
stdTime = The UTC time that needs to be adjusted to this time zone's
time.
+/
override long utcToTZ(long stdTime) const nothrow
{
return stdTime + convert!("minutes", "hnsecs")(utcOffset);
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="((new SimpleTimeZone(-8 * 60)).utcToTZ(0), -288_000_000_000L);
_assertPred!"=="((new SimpleTimeZone(8 * 60)).utcToTZ(0), 288_000_000_000L);
_assertPred!"=="((new SimpleTimeZone(-8 * 60)).utcToTZ(54_321_234_567_890L), 54_033_234_567_890L);
auto stz = new SimpleTimeZone(-8 * 60);
const cstz = new SimpleTimeZone(-8 * 60);
static assert(__traits(compiles, stz.utcToTZ(50002)));
static assert(__traits(compiles, cstz.utcToTZ(50002)));
}
}
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D.
in this time zone's time and converts it to UTC (i.e. std time).
Params:
adjTime = The time in this time zone that needs to be adjusted to
UTC time.
+/
override long tzToUTC(long adjTime) const nothrow
{
return adjTime - convert!("minutes", "hnsecs")(utcOffset);
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="((new SimpleTimeZone(-8 * 60)).tzToUTC(-288_000_000_000L), 0);
_assertPred!"=="((new SimpleTimeZone(8 * 60)).tzToUTC(288_000_000_000L), 0);
_assertPred!"=="((new SimpleTimeZone(-8 * 60)).tzToUTC(54_033_234_567_890L), 54_321_234_567_890L);
auto stz = new SimpleTimeZone(-8 * 60);
const cstz = new SimpleTimeZone(-8 * 60);
static assert(__traits(compiles, stz.tzToUTC(20005)));
static assert(__traits(compiles, cstz.tzToUTC(20005)));
}
}
/++
Params:
utcOffset = This time zone's offset from UTC in minutes with west of
UTC being negative (it is added to UTC to get the
adjusted time).
stdName = The $(D stdName) for this time zone.
+/
this(int utcOffset, string stdName = "") immutable
{
//FIXME This probably needs to be changed to something like (-12 - 13).
enforce(std.math.abs(utcOffset) < 1440, new DateTimeException("Offset from UTC must be within range (-24:00 - 24:00)."));
super("", stdName, "");
this.utcOffset = utcOffset;
}
unittest
{
version(testStdDateTime)
{
auto stz = new SimpleTimeZone(-8 * 60, "PST");
_assertPred!"=="(stz.name, "");
_assertPred!"=="(stz.stdName, "PST");
_assertPred!"=="(stz.dstName, "");
_assertPred!"=="(stz.utcOffset, -8 * 60);
}
}
/++
The number of minutes the offset from UTC is (negative is west of UTC,
positive is east).
+/
immutable int utcOffset;
private:
/+
Returns a time zone as a string with an offset from UTC.
Time zone offsets will be in the form +HH:MM or -HH:MM.
Params:
utcOffset = The number of minutes offset from UTC (negative means
west).
+/
static string toISOString(int utcOffset)
{
immutable absOffset = std.math.abs(utcOffset);
enforce(absOffset < 1440, new DateTimeException("Offset from UTC must be within range (-24:00 - 24:00)."));
immutable hours = convert!("minutes", "hours")(absOffset);
immutable minutes = absOffset - convert!("hours", "minutes")(hours);
if(utcOffset < 0)
return format("-%02d:%02d", hours, minutes);
return format("+%02d:%02d", hours, minutes);
}
unittest
{
version(testStdDateTime)
{
static string testSTZInvalid(int offset)
{
return SimpleTimeZone.toISOString(offset);
}
assertThrown!DateTimeException(testSTZInvalid(1440));
assertThrown!DateTimeException(testSTZInvalid(-1440));
_assertPred!"=="(toISOString(0), "+00:00");
_assertPred!"=="(toISOString(1), "+00:01");
_assertPred!"=="(toISOString(10), "+00:10");
_assertPred!"=="(toISOString(59), "+00:59");
_assertPred!"=="(toISOString(60), "+01:00");
_assertPred!"=="(toISOString(90), "+01:30");
_assertPred!"=="(toISOString(120), "+02:00");
_assertPred!"=="(toISOString(480), "+08:00");
_assertPred!"=="(toISOString(1439), "+23:59");
_assertPred!"=="(toISOString(-1), "-00:01");
_assertPred!"=="(toISOString(-10), "-00:10");
_assertPred!"=="(toISOString(-59), "-00:59");
_assertPred!"=="(toISOString(-60), "-01:00");
_assertPred!"=="(toISOString(-90), "-01:30");
_assertPred!"=="(toISOString(-120), "-02:00");
_assertPred!"=="(toISOString(-480), "-08:00");
_assertPred!"=="(toISOString(-1439), "-23:59");
}
}
/+
Takes a time zone as a string with an offset from UTC and returns a
$(D SimpleTimeZone) which matches.
The accepted formats for time zone offsets
are +H, -H, +HH, -HH, +H:MM, -H:MM, +HH:MM, and -HH:MM.
Params:
isoString = A string which represents a time zone in the ISO format.
+/
static immutable(SimpleTimeZone) fromISOString(S)(S isoString)
if(isSomeString!(S))
{
auto dstr = to!dstring(strip(isoString));
enforce(dstr.startsWith("-") || dstr.startsWith("+"), new DateTimeException("Invalid ISO String"));
auto sign = dstr.startsWith("-") ? -1 : 1;
dstr.popFront();
enforce(!dstr.empty, new DateTimeException("Invalid ISO String"));
immutable colon = dstr.stds_indexOf(":");
dstring hoursStr;
dstring minutesStr;
if(colon != -1)
{
hoursStr = dstr[0 .. colon];
minutesStr = dstr[colon + 1 .. $];
enforce(minutesStr.length == 2, new DateTimeException(format("Invalid ISO String: %s", dstr)));
}
else
hoursStr = dstr;
enforce(!canFind!(not!isDigit)(hoursStr), new DateTimeException(format("Invalid ISO String: %s", dstr)));
enforce(!canFind!(not!isDigit)(minutesStr), new DateTimeException(format("Invalid ISO String: %s", dstr)));
immutable hours = to!int(hoursStr);
immutable minutes = minutesStr.empty ? 0 : to!int(minutesStr);
return new SimpleTimeZone(sign * cast(int)(convert!("hours", "minutes")(hours) + minutes));
}
unittest
{
version(testStdDateTime)
{
assertThrown!DateTimeException(SimpleTimeZone.fromISOString(""));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("Z"));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("-"));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("+"));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("-:"));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("+:"));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("-1:"));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("+1:"));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("1"));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("-24:00"));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("+24:00"));
assertThrown!DateTimeException(SimpleTimeZone.fromISOString("+1:0"));
_assertPred!"=="(SimpleTimeZone.fromISOString("+00:00").utcOffset, (new SimpleTimeZone(0)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+00:01").utcOffset, (new SimpleTimeZone(1)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+00:10").utcOffset, (new SimpleTimeZone(10)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+00:59").utcOffset, (new SimpleTimeZone(59)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+01:00").utcOffset, (new SimpleTimeZone(60)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+01:30").utcOffset, (new SimpleTimeZone(90)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+02:00").utcOffset, (new SimpleTimeZone(120)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+08:00").utcOffset, (new SimpleTimeZone(480)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+23:59").utcOffset, (new SimpleTimeZone(1439)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-00:01").utcOffset, (new SimpleTimeZone(-1)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-00:10").utcOffset, (new SimpleTimeZone(-10)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-00:59").utcOffset, (new SimpleTimeZone(-59)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-01:00").utcOffset, (new SimpleTimeZone(-60)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-01:30").utcOffset, (new SimpleTimeZone(-90)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-02:00").utcOffset, (new SimpleTimeZone(-120)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-08:00").utcOffset, (new SimpleTimeZone(-480)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-23:59").utcOffset, (new SimpleTimeZone(-1439)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+0").utcOffset, (new SimpleTimeZone(0)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+1").utcOffset, (new SimpleTimeZone(60)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+2").utcOffset, (new SimpleTimeZone(120)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+23").utcOffset, (new SimpleTimeZone(1380)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+2").utcOffset, (new SimpleTimeZone(120)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+0").utcOffset, (new SimpleTimeZone(0)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+1").utcOffset, (new SimpleTimeZone(60)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+2").utcOffset, (new SimpleTimeZone(120)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+23").utcOffset, (new SimpleTimeZone(1380)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+1:00").utcOffset, (new SimpleTimeZone(60)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("+1:01").utcOffset, (new SimpleTimeZone(61)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-0").utcOffset, (new SimpleTimeZone(0)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-1").utcOffset, (new SimpleTimeZone(-60)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-2").utcOffset, (new SimpleTimeZone(-120)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-23").utcOffset, (new SimpleTimeZone(-1380)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-1:00").utcOffset, (new SimpleTimeZone(-60)).utcOffset);
_assertPred!"=="(SimpleTimeZone.fromISOString("-1:01").utcOffset, (new SimpleTimeZone(-61)).utcOffset);
}
}
//Test that converting from an ISO string to a SimpleTimeZone to an ISO String works properly.
unittest
{
version(testStdDateTime)
{
static void testSTZ(in string isoString, int expectedOffset, size_t line = __LINE__)
{
auto stz = SimpleTimeZone.fromISOString(isoString);
_assertPred!"=="(stz.utcOffset, expectedOffset, "", __FILE__, line);
auto result = SimpleTimeZone.toISOString(stz.utcOffset);
_assertPred!"=="(result, isoString, "", __FILE__, line);
}
testSTZ("+00:00", 0);
testSTZ("+00:01", 1);
testSTZ("+00:10", 10);
testSTZ("+00:59", 59);
testSTZ("+01:00", 60);
testSTZ("+01:30", 90);
testSTZ("+02:00", 120);
testSTZ("+08:00", 480);
testSTZ("+08:00", 480);
testSTZ("+23:59", 1439);
testSTZ("-00:01", -1);
testSTZ("-00:10", -10);
testSTZ("-00:59", -59);
testSTZ("-01:00", -60);
testSTZ("-01:30", -90);
testSTZ("-02:00", -120);
testSTZ("-08:00", -480);
testSTZ("-08:00", -480);
testSTZ("-23:59", -1439);
}
}
}
/++
Represents a time zone from a TZ Database time zone file. Files from the TZ
database are how Posix systems hold their time zone information.
Unfortunately, Windows does not use the TZ Database. You can, however, use
$(D PosixTimeZone) (which reads its information from the TZ Database files
on disk) on Windows if you provide the TZ Database files
( $(WEB elsie.nci.nih.gov/pub/, Repository with the TZ Database files (tzdata)) )
yourself and tell $(D PosixTimeZone.getTimeZone) where the directory holding
them is.
To get a $(D PosixTimeZone), either call $(D PosixTimeZone.getTimeZone)
(which will allow you to specify the location the time zone files) or call
$(D TimeZone.getTimeZone) (which will give you a $(D PosixTimeZone) on Posix
systems and a $(D WindowsTimeZone) on Windows systems).
Note:
Unless your system's local time zone deals with leap seconds (which is
highly unlikely), then only way that you will get a time zone which
takes leap seconds into account is if you use $(D PosixTimeZone) with a
time zone whose name starts with "right/". Those time zone files do
include leap seconds, and $(D PosixTimeZone) will take them into account
(though posix systems which use a "right/" time zone as their local time
zone will $(I not) take leap seconds into account even though they're
in the file).
See_Also:
$(WEB en.wikipedia.org/wiki/Tz_database, Wikipedia entry on TZ Database)
$(WEB en.wikipedia.org/wiki/List_of_tz_database_time_zones, List of Time
Zones)
+/
final class PosixTimeZone : TimeZone
{
public:
/++
Whether this time zone has Daylight Savings Time at any point in time.
Note that for some time zone types it may not have DST for current
dates but will still return true for $(D hasDST) because the time zone
did at some point have DST.
+/
@property override bool hasDST() const nothrow
{
return _hasDST;
}
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D.
in UTC time (i.e. std time) and returns whether DST is in effect in this
time zone at the given point in time.
Params:
stdTime = The UTC time that needs to be checked for DST in this time
zone.
+/
override bool dstInEffect(long stdTime) const nothrow
{
assert(!_transitions.empty);
try
{
immutable unixTime = stdTimeToUnixTime(stdTime);
if(_transitions.front.timeT >= unixTime)
return _transitions.front.ttInfo.isDST;
auto found = std.algorithm.countUntil!"b < a.timeT"(cast(Transition[])_transitions, unixTime);
if(found == -1)
return _transitions.back.ttInfo.isDST;
auto transition = found == 0 ? _transitions[0] : _transitions[found - 1];
return transition.ttInfo.isDST;
}
catch(Exception e)
assert(0, format("Nothing in calculateLeapSeconds() should be throwing. Caught Exception: %s", e));
}
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D.
in UTC time (i.e. std time) and converts it to this time zone's time.
Params:
stdTime = The UTC time that needs to be adjusted to this time zone's
time.
+/
override long utcToTZ(long stdTime) const nothrow
{
assert(!_transitions.empty);
try
{
immutable leapSecs = calculateLeapSeconds(stdTime);
immutable unixTime = stdTimeToUnixTime(stdTime);
if(_transitions.front.timeT >= unixTime)
return stdTime + convert!("seconds", "hnsecs")(_transitions.front.ttInfo.utcOffset + leapSecs);
auto found = std.algorithm.countUntil!"b < a.timeT"(cast(Transition[])_transitions, unixTime);
if(found == -1)
return stdTime + convert!("seconds", "hnsecs")(_transitions.back.ttInfo.utcOffset + leapSecs);
auto transition = found == 0 ? _transitions[0] : _transitions[found - 1];
return stdTime + convert!("seconds", "hnsecs")(transition.ttInfo.utcOffset + leapSecs);
}
catch(Exception e)
assert(0, format("Nothing in calculateLeapSeconds() should be throwing. Caught Exception: %s", e));
}
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st, 1 A.D.
in this time zone's time and converts it to UTC (i.e. std time).
Params:
adjTime = The time in this time zone that needs to be adjusted to
UTC time.
+/
override long tzToUTC(long adjTime) const nothrow
{
assert(!_transitions.empty);
try
{
immutable leapSecs = calculateLeapSeconds(adjTime);
immutable unixTime = stdTimeToUnixTime(adjTime);
if(_transitions.front.timeT >= unixTime)
return adjTime - convert!("seconds", "hnsecs")(_transitions.front.ttInfo.utcOffset + leapSecs);
//Okay, casting is a hack, but countUntil shouldn't be changing it,
//and it would be too inefficient to have to keep duping it every
//time we have to calculate the time. Hopefully, countUntil will
//properly support immutable ranges at some point.
auto found = std.algorithm.countUntil!"b < a.timeT"(cast(Transition[])_transitions, unixTime);
if(found == -1)
return adjTime - convert!("seconds", "hnsecs")(_transitions.back.ttInfo.utcOffset + leapSecs);
auto transition = found == 0 ? _transitions[0] : _transitions[found - 1];
return adjTime - convert!("seconds", "hnsecs")(transition.ttInfo.utcOffset + leapSecs);
}
catch(Exception e)
assert(0, format("Nothing in calculateLeapSeconds() should be throwing. Caught Exception: %s", e));
}
version(Posix)
{
/++
The default directory where the TZ Database files are. It's empty
for Windows, since Windows doesn't have them.
+/
enum defaultTZDatabaseDir = "/usr/share/zoneinfo/";
}
else version(Windows)
{
/++ The default directory where the TZ Database files are. It's empty
for Windows, since Windows doesn't have them.
+/
enum defaultTZDatabaseDir = "";
}
/++
Returns a $(D TimeZone) with the give name per the TZ Database. The time
zone information is fetched from the TZ Database time zone files in the
given directory.
See_Also:
$(WEB en.wikipedia.org/wiki/Tz_database, Wikipedia entry on TZ
Database)
$(WEB en.wikipedia.org/wiki/List_of_tz_database_time_zones, List of
Time Zones)
Params:
name = The TZ Database name of the time zone that you're
looking for.
tzDatabaseDir = The directory where the TZ Database files are
located. Because these files are not located on
Windows systems, you will need to provide them
yourself and give their location here if you wish to
use $(D PosixTimeZone)s.
Throws:
$(D DateTimeException) if the given time zone could not be found or
$(D FileException) if the TZ Database file could not be opened.
Examples:
--------------------
auto tz = PosixTimeZone.getTimeZone("America/Los_Angeles");
assert(tz.name == "America/Los_Angeles");
assert(tz.stdName == "PST");
assert(tz.dstName == "PDT");
--------------------
+/
//TODO make it possible for tzDatabaseDir to be gzipped tar file rather than an uncompressed
// directory.
static immutable(PosixTimeZone) getTimeZone(string name, string tzDatabaseDir = defaultTZDatabaseDir)
{
name = strip(name);
enforce(tzDatabaseDir.exists, new DateTimeException(format("Directory %s does not exist.", tzDatabaseDir)));
enforce(tzDatabaseDir.isDir, new DateTimeException(format("%s is not a directory.", tzDatabaseDir)));
version(Posix)
auto file = tzDatabaseDir ~ name;
else version(Windows)
auto file = tzDatabaseDir ~ replace(strip(name), "/", sep);
enforce(file.exists, new DateTimeException(format("File %s does not exist.", file)));
enforce(file.isFile, new DateTimeException(format("%s is not a file.", file)));
auto tzFile = File(file);
immutable gmtZone = file.canFind("GMT");
try
{
_enforceValidTZFile(readVal!(char[])(tzFile, 4) == "TZif");
immutable char tzFileVersion = readVal!char(tzFile);
_enforceValidTZFile(tzFileVersion == '\0' || tzFileVersion == '2');
{
auto zeroBlock = readVal!(ubyte[])(tzFile, 15);
bool allZeroes = true;
foreach(val; zeroBlock)
{
if(val != 0)
{
allZeroes = false;
break;
}
}
_enforceValidTZFile(allZeroes);
}
//The number of UTC/local indicators stored in the file.
auto tzh_ttisgmtcnt = readVal!int(tzFile);
//The number of standard/wall indicators stored in the file.
auto tzh_ttisstdcnt = readVal!int(tzFile);
//The number of leap seconds for which data is stored in the file.
auto tzh_leapcnt = readVal!int(tzFile);
//The number of "transition times" for which data is stored in the file.
auto tzh_timecnt = readVal!int(tzFile);
//The number of "local time types" for which data is stored in the file (must not be zero).
auto tzh_typecnt = readVal!int(tzFile);
_enforceValidTZFile(tzh_typecnt != 0);
//The number of characters of "timezone abbreviation strings" stored in the file.
auto tzh_charcnt = readVal!int(tzFile);
//time_ts where DST transitions occur.
auto transitionTimeTs = new long[](tzh_timecnt);
foreach(ref transition; transitionTimeTs)
transition = readVal!int(tzFile);
//Indices into ttinfo structs indicating the changes
//to be made at the corresponding DST transition.
auto ttInfoIndices = new ubyte[](tzh_timecnt);
foreach(ref ttInfoIndex; ttInfoIndices)
ttInfoIndex = readVal!ubyte(tzFile);
//ttinfos which give info on DST transitions.
auto tempTTInfos = new TempTTInfo[](tzh_typecnt);
foreach(ref ttInfo; tempTTInfos)
ttInfo = readVal!TempTTInfo(tzFile);
//The array of time zone abbreviation characters.
auto tzAbbrevChars = readVal!(char[])(tzFile, tzh_charcnt);
auto leapSeconds = new LeapSecond[](tzh_leapcnt);
foreach(ref leapSecond; leapSeconds)
{
//The time_t when the leap second occurs.
auto timeT = readVal!int(tzFile);
//The total number of leap seconds to be applied after
//the corresponding leap second.
auto total = readVal!int(tzFile);
leapSecond = LeapSecond(timeT, total);
}
//Indicate whether each corresponding DST transition were specified
//in standard time or wall clock time.
auto transitionIsStd = new bool[](tzh_ttisstdcnt);
foreach(ref isStd; transitionIsStd)
isStd = readVal!bool(tzFile);
//Indicate whether each corresponding DST transition associated with
//local time types are specified in UTC or local time.
auto transitionInUTC = new bool[](tzh_ttisgmtcnt);
foreach(ref inUTC; transitionInUTC)
inUTC = readVal!bool(tzFile);
_enforceValidTZFile(!tzFile.eof());
//If version 2, the information is duplicated in 64-bit.
if(tzFileVersion == '2')
{
_enforceValidTZFile(readVal!(char[])(tzFile, 4) == "TZif");
_enforceValidTZFile(readVal!(char)(tzFile) == '2');
{
auto zeroBlock = readVal!(ubyte[])(tzFile, 15);
bool allZeroes = true;
foreach(val; zeroBlock)
{
if(val != 0)
{
allZeroes = false;
break;
}
}
_enforceValidTZFile(allZeroes);
}
//The number of UTC/local indicators stored in the file.
tzh_ttisgmtcnt = readVal!int(tzFile);
//The number of standard/wall indicators stored in the file.
tzh_ttisstdcnt = readVal!int(tzFile);
//The number of leap seconds for which data is stored in the file.
tzh_leapcnt = readVal!int(tzFile);
//The number of "transition times" for which data is stored in the file.
tzh_timecnt = readVal!int(tzFile);
//The number of "local time types" for which data is stored in the file (must not be zero).
tzh_typecnt = readVal!int(tzFile);
_enforceValidTZFile(tzh_typecnt != 0);
//The number of characters of "timezone abbreviation strings" stored in the file.
tzh_charcnt = readVal!int(tzFile);
//time_ts where DST transitions occur.
transitionTimeTs = new long[](tzh_timecnt);
foreach(ref transition; transitionTimeTs)
transition = readVal!long(tzFile);
//Indices into ttinfo structs indicating the changes
//to be made at the corresponding DST transition.
ttInfoIndices = new ubyte[](tzh_timecnt);
foreach(ref ttInfoIndex; ttInfoIndices)
ttInfoIndex = readVal!ubyte(tzFile);
//ttinfos which give info on DST transitions.
tempTTInfos = new TempTTInfo[](tzh_typecnt);
foreach(ref ttInfo; tempTTInfos)
ttInfo = readVal!TempTTInfo(tzFile);
//The array of time zone abbreviation characters.
tzAbbrevChars = readVal!(char[])(tzFile, tzh_charcnt);
leapSeconds = new LeapSecond[](tzh_leapcnt);
foreach(ref leapSecond; leapSeconds)
{
//The time_t when the leap second occurs.
auto timeT = readVal!long(tzFile);
//The total number of leap seconds to be applied after
//the corresponding leap second.
auto total = readVal!int(tzFile);
leapSecond = LeapSecond(timeT, total);
}
//Indicate whether each corresponding DST transition were specified
//in standard time or wall clock time.
transitionIsStd = new bool[](tzh_ttisstdcnt);
foreach(ref isStd; transitionIsStd)
isStd = readVal!bool(tzFile);
//Indicate whether each corresponding DST transition associated with
//local time types are specified in UTC or local time.
transitionInUTC = new bool[](tzh_ttisgmtcnt);
foreach(ref inUTC; transitionInUTC)
inUTC = readVal!bool(tzFile);
}
_enforceValidTZFile(tzFile.readln().strip().empty());
auto posixEnvStr = tzFile.readln().strip();
_enforceValidTZFile(tzFile.readln().strip().empty());
_enforceValidTZFile(tzFile.eof());
auto transitionTypes = new TransitionType*[](tempTTInfos.length);
foreach(i, ref ttype; transitionTypes)
{
bool isStd = false;
if(i < transitionIsStd.length && !transitionIsStd.empty)
isStd = transitionIsStd[i];
bool inUTC = false;
if(i < transitionInUTC.length && !transitionInUTC.empty)
inUTC = transitionInUTC[i];
ttype = new TransitionType(isStd, inUTC);
}
auto ttInfos = new immutable(TTInfo)*[](tempTTInfos.length);
foreach(i, ref ttInfo; ttInfos)
{
auto tempTTInfo = tempTTInfos[i];
if(gmtZone)
tempTTInfo.tt_gmtoff = -tempTTInfo.tt_gmtoff;
auto abbrevChars = tzAbbrevChars[tempTTInfo.tt_abbrind .. $];
string abbrev = abbrevChars[0 .. abbrevChars.stds_indexOf("\0")].idup;
ttInfo = new immutable(TTInfo)(tempTTInfos[i], abbrev);
}
auto tempTransitions = new TempTransition[](transitionTimeTs.length);
foreach(i, ref tempTransition; tempTransitions)
{
immutable ttiIndex = ttInfoIndices[i];
auto transitionTimeT = transitionTimeTs[i];
auto ttype = transitionTypes[ttiIndex];
auto ttInfo = ttInfos[ttiIndex];
tempTransition = TempTransition(transitionTimeT, ttInfo, ttype);
}
if(tempTransitions.empty)
{
_enforceValidTZFile(ttInfos.length == 1 && transitionTypes.length == 1);
tempTransitions ~= TempTransition(0, ttInfos[0], transitionTypes[0]);
}
sort!"a.timeT < b.timeT"(tempTransitions);
sort!"a.timeT < b.timeT"(leapSeconds);
auto transitions = new Transition[](tempTransitions.length);
foreach(i, ref transition; transitions)
{
auto tempTransition = tempTransitions[i];
auto transitionTimeT = tempTransition.timeT;
auto ttInfo = tempTransition.ttInfo;
auto ttype = tempTransition.ttype;
_enforceValidTZFile(i == 0 || transitionTimeT > tempTransitions[i - 1].timeT);
transition = Transition(transitionTimeT, ttInfo);
}
string stdName;
string dstName;
bool hasDST = false;
foreach(transition; retro(transitions))
{
auto ttInfo = transition.ttInfo;
if(ttInfo.isDST)
{
if(dstName.empty)
dstName = ttInfo.abbrev;
hasDST = true;
}
else
{
if(stdName.empty)
stdName = ttInfo.abbrev;
}
if(!stdName.empty && !dstName.empty)
break;
}
return new PosixTimeZone(transitions.idup, leapSeconds.idup, name, stdName, dstName, hasDST);
}
catch(DateTimeException dte)
throw dte;
catch(Exception e)
throw new DateTimeException("Not a valid TZ data file", __FILE__, __LINE__, e);
}
/++
Returns a list of the names of the time zones installed on the system.
You can provide a sub-name to narrow down the list of time zones (which
will likely be in the thousands if you get them all). For example,
if you pass in "America" as the sub-name, then only the time zones which
begin with "America" will be returned.
Params:
subName = The first part of the time zones that you want.
Throws:
$(D FileException) if it fails to read from disk.
+/
static string[] getInstalledTZNames(string subName = "", string tzDatabaseDir = defaultTZDatabaseDir)
{
version(Posix)
subName = strip(subName);
else version(Windows)
subName = replace(strip(subName), "/", sep);
if(!tzDatabaseDir.endsWith(sep))
tzDatabaseDir ~= sep;
enforce(tzDatabaseDir.exists, new DateTimeException(format("Directory %s does not exist.", tzDatabaseDir)));
enforce(tzDatabaseDir.isDir, new DateTimeException(format("%s is not a directory.", tzDatabaseDir)));
auto timezones = appender!(string[])();
foreach(DirEntry dentry; dirEntries(tzDatabaseDir, SpanMode.depth))
{
if(dentry.isFile)
{
auto tzName = dentry.name[tzDatabaseDir.length .. $];
if(!tzName.getExt().empty() ||
!tzName.startsWith(subName) ||
tzName == "+VERSION")
{
continue;
}
timezones.put(tzName);
}
}
sort(timezones.data);
return timezones.data;
}
unittest
{
version(testStdDateTime)
{
version(Posix)
{
static void testPTZSuccess(string tzName)
{
scope(failure) writefln("TZName which threw: %s", tzName);
PosixTimeZone.getTimeZone(tzName);
}
static void testPTZFailure(string tzName)
{
scope(success) writefln("TZName which was supposed to throw: %s", tzName);
PosixTimeZone.getTimeZone(tzName);
}
auto tzNames = getInstalledTZNames();
foreach(tzName; tzNames)
assertNotThrown!DateTimeException(testPTZSuccess(tzName));
foreach(DirEntry dentry; dirEntries(defaultTZDatabaseDir, SpanMode.depth))
{
if(dentry.isFile)
{
auto tzName = dentry.name[defaultTZDatabaseDir.length .. $];
if(!canFind(tzNames, tzName))
assertThrown!DateTimeException(testPTZFailure(tzName));
}
}
}
}
}
private:
/+
Holds information on when a time transition occures (usually a
transition to or from DST) as well as a pointer to the $(D TTInfo) which
holds information on the utc offset passed the transition.
+/
struct Transition
{
this(long timeT, immutable (TTInfo)* ttInfo)
{
this.timeT = timeT;
this.ttInfo = ttInfo;
}
long timeT;
immutable (TTInfo)* ttInfo;
}
/+
Holds information on when a leap second occurs.
+/
struct LeapSecond
{
this(long timeT, int total)
{
this.timeT = timeT;
this.total = total;
}
long timeT;
int total;
}
/+
Holds information on the utc offset after a transition as well as
whether DST is in effect after that transition.
+/
struct TTInfo
{
this(in TempTTInfo tempTTInfo, string abbrev) immutable
{
utcOffset = tempTTInfo.tt_gmtoff;
isDST = tempTTInfo.tt_isdst;
this.abbrev = abbrev;
}
immutable int utcOffset; /// Offset from UTC.
immutable bool isDST; /// Whether DST is in effect.
immutable string abbrev; /// The current abbreviation for the time zone.
}
/+
Struct used to hold information relating to $(D TTInfo) while organizing
the time zone information prior to putting it in its final form.
+/
struct TempTTInfo
{
this(int gmtOff, bool isDST, ubyte abbrInd)
{
tt_gmtoff = gmtOff;
tt_isdst = isDST;
tt_abbrind = abbrInd;
}
int tt_gmtoff;
bool tt_isdst;
ubyte tt_abbrind;
}
/+
Struct used to hold information relating to $(D Transition) while
organizing the time zone information prior to putting it in its final
form.
+/
struct TempTransition
{
this(long timeT, immutable (TTInfo)* ttInfo, TransitionType* ttype)
{
this.timeT = timeT;
this.ttInfo = ttInfo;
this.ttype = ttype;
}
long timeT;
immutable (TTInfo)* ttInfo;
TransitionType* ttype;
}
/+
Struct used to hold information relating to $(D Transition) and
$(D TTInfo) while organizing the time zone information prior to putting
it in its final form.
+/
struct TransitionType
{
this(bool isStd, bool inUTC)
{
this.isStd = isStd;
this.inUTC = inUTC;
}
/// Whether the transition is in std time (as opposed to wall clock time).
bool isStd;
/// Whether the transition is in UTC (as opposed to local time).
bool inUTC;
}
/+
Reads an int from a TZ file.
+/
static T readVal(T)(ref File tzFile)
if(is(T == int))
{
T[1] buff;
_enforceValidTZFile(!tzFile.eof());
tzFile.rawRead(buff);
return cast(int)ntohl(buff[0]);
}
/+
Reads a long from a TZ file.
+/
static T readVal(T)(ref File tzFile)
if(is(T == long))
{
T[1] buff;
_enforceValidTZFile(!tzFile.eof());
tzFile.rawRead(buff);
return cast(long)ntoh64(buff[0]);
}
/+
Reads an array of values from a TZ file.
+/
static T readVal(T)(ref File tzFile, size_t length)
if(isArray!T)
{
auto buff = new T(length);
_enforceValidTZFile(!tzFile.eof());
tzFile.rawRead(buff);
return buff;
}
/+
Reads a $(D TempTTInfo) from a TZ file.
+/
static T readVal(T)(ref File tzFile)
if(is(T == TempTTInfo))
{
return TempTTInfo(readVal!int(tzFile),
readVal!bool(tzFile),
readVal!ubyte(tzFile));
}
/+
Reads a value from a TZ file.
+/
static T readVal(T)(ref File tzFile)
if(!is(T == int) &&
!is(T == long) &&
!is(T == char[]) &&
!is(T == TempTTInfo))
{
T[1] buff;
_enforceValidTZFile(!tzFile.eof());
tzFile.rawRead(buff);
return buff[0];
}
/+
64 bit version of $(D ntoh). Unfortunately, for some reason, most
systems provide only 16 and 32 bit versions of this, so we need to
provide it ourselves. We really should declare a version of this in core
somewhere.
+/
static ulong ntoh64(ulong val)
{
static if(endian == Endian.LittleEndian)
return endianSwap64(val);
else
return val;
}
/+
Swaps the endianness of a 64-bit value. We really should declare a
version of this in core somewhere.
+/
static ulong endianSwap64(ulong val)
{
return ((val & 0xff00000000000000UL) >> 56) |
((val & 0x00ff000000000000UL) >> 40) |
((val & 0x0000ff0000000000UL) >> 24) |
((val & 0x000000ff00000000UL) >> 8) |
((val & 0x00000000ff000000UL) << 8) |
((val & 0x0000000000ff0000UL) << 24) |
((val & 0x000000000000ff00UL) << 40) |
((val & 0x00000000000000ffUL) << 56);
}
/+
Throws:
$(D DateTimeException) if $(D result) is false.
+/
static void _enforceValidTZFile(bool result, size_t line = __LINE__)
{
if(!result)
throw new DateTimeException("Not a valid tzdata file.", __FILE__, line);
}
int calculateLeapSeconds(long stdTime) const nothrow
{
try
{
if(_leapSeconds.empty)
return 0;
immutable unixTime = stdTimeToUnixTime(stdTime);
if(_leapSeconds.front.timeT >= unixTime)
return 0;
//Okay, casting is a hack, but countUntil shouldn't be changing it,
//and it would be too inefficient to have to keep duping it every
//time we have to calculate the time. Hopefully, countUntil will
//properly support immutable ranges at some point.
auto found = std.algorithm.countUntil!"b < a.timeT"(cast(LeapSecond[])_leapSeconds, unixTime);
if(found == -1)
return _leapSeconds.back.total;
auto leapSecond = found == 0 ? _leapSeconds[0] : _leapSeconds[found - 1];
return leapSecond.total;
}
catch(Exception e)
assert(0, format("Nothing in calculateLeapSeconds() should be throwing. Caught Exception: %s", e));
}
this(immutable Transition[] transitions,
immutable LeapSecond[] leapSeconds,
string name,
string stdName,
string dstName,
bool hasDST) immutable
{
if(dstName.empty && !stdName.empty)
dstName = stdName;
else if(stdName.empty && !dstName.empty)
stdName = dstName;
super(name, stdName, dstName);
if(!transitions.empty)
{
foreach(i, transition; transitions[0 .. $-1])
_enforceValidTZFile(transition.timeT < transitions[i + 1].timeT);
}
foreach(i, leapSecond; leapSeconds)
_enforceValidTZFile(i == leapSeconds.length - 1 || leapSecond.timeT < leapSeconds[i + 1].timeT);
_transitions = transitions;
_leapSeconds = leapSeconds;
_hasDST = hasDST;
}
/// List of times when the utc offset changes.
immutable Transition[] _transitions;
/// List of leap second occurrences.
immutable LeapSecond[] _leapSeconds;
/// Whether DST is in effect for this time zone at any point in time.
immutable bool _hasDST;
}
version(StdDdoc)
{
/++
$(BLUE This class is Windows-Only.)
Represents a time zone from the Windows registry. Unfortunately, Windows
does not use the TZ Database. You can, however, use $(D PosixTimeZone)
(which reads its information from the TZ Database files on disk) on
Windows if you provide the TZ Database files
( $(WEB ftp://elsie.nci.nih.gov/pub/,
Repository with the TZ Database files (tzdata)) )
yourself and tell $(D PosixTimeZone.getTimeZone) where the directory
holding them is.
The TZ Dabatase files and Windows are not likely to always match,
particularly for historical dates, so if you want complete consistency
between Posix and Windows, then you should provide the appropriate
TZ Database files on Windows and use $(D PosixTimeZone). But as
$(D WindowsTimeZone) uses the Windows functions, $(D WindowsTimeZone)
is more likely to match the behavior of other Windows programs.
$(D WindowsTimeZone) should be fine for most programs.
$(D WindowsTimeZone) does not exist on Posix systems.
To get a $(D WindowsTimeZone), either call
$(D WindowsTimeZone.getTimeZone) or call $(D TimeZone.getTimeZone)
(which will give you a $(D PosixTimeZone) on Posix systems and a
$(D WindowsTimeZone) on Windows systems).
+/
final class WindowsTimeZone : TimeZone
{
public:
/++
Whether this time zone has Daylight Savings Time at any point in
time. Note that for some time zone types it may not have DST for
current dates but will still return true for $(D hasDST) because the
time zone did at some point have DST.
+/
@property override bool hasDST() const nothrow;
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st,
1 A.D. in UTC time (i.e. std time) and returns whether DST is in
effect in this time zone at the given point in time.
Params:
stdTime = The UTC time that needs to be checked for DST in this
time zone.
+/
override bool dstInEffect(long stdTime) const nothrow;
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st,
1 A.D. in UTC time (i.e. std time) and converts it to this time
zone's time.
Params:
stdTime = The UTC time that needs to be adjusted to this time
zone's time.
+/
override long utcToTZ(long stdTime) const nothrow;
/++
Takes the number of hnsecs (100 ns) since midnight, January 1st,
1 A.D. in this time zone's time and converts it to UTC (i.e. std
time).
Params:
adjTime = The time in this time zone that needs to be adjusted
to UTC time.
+/
override long tzToUTC(long adjTime) const nothrow;
/++
Returns a $(D TimeZone) with the given name per the Windows time
zone names. The time zone information is fetched from the Windows
registry.
See_Also:
$(WEB en.wikipedia.org/wiki/Tz_database, Wikipedia entry on TZ
Database)
$(WEB en.wikipedia.org/wiki/List_of_tz_database_time_zones, List
of Time Zones)
Params:
name = The TZ Database name of the time zone that you're looking
for.
Throws:
$(D DateTimeException) if the given time zone could not be
found.
Examples:
--------------------
auto tz = TimeZone.getTimeZone("America/Los_Angeles");
--------------------
+/
static immutable(WindowsTimeZone) getTimeZone(string name);
/++
Returns a list of the names of the time zones installed on the
system.
+/
static string[] getInstalledTZNames();
private:
version(Windows) {}
else
alias void* TIME_ZONE_INFORMATION;
static bool _dstInEffect(const TIME_ZONE_INFORMATION* tzInfo, long stdTime) nothrow;
static long _utcToTZ(const TIME_ZONE_INFORMATION* tzInfo, long stdTime, bool hasDST) nothrow;
static long _tzToUTC(const TIME_ZONE_INFORMATION* tzInfo, long adjTime, bool hasDST) nothrow;
this() immutable pure
{
super("", "", "");
}
}
}
else version(Windows)
{
//Should be in core.sys.windows.windows, but for some reason it isn't.
extern(Windows)
{
export LONG RegQueryValueExA(HKEY hKey, LPCSTR name, LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD count);
struct REG_TZI_FORMAT
{
LONG Bias;
LONG StandardBias;
LONG DaylightBias;
SYSTEMTIME StandardDate;
SYSTEMTIME DaylightDate;
}
}
final class WindowsTimeZone : TimeZone
{
public:
@property override bool hasDST() const nothrow
{
return _tzInfo.DaylightDate.wMonth != 0;
}
override bool dstInEffect(long stdTime) const nothrow
{
return _dstInEffect(&_tzInfo, stdTime);
}
override long utcToTZ(long stdTime) const nothrow
{
return _utcToTZ(&_tzInfo, stdTime, hasDST);
}
override long tzToUTC(long adjTime) const nothrow
{
return _tzToUTC(&_tzInfo, adjTime, hasDST);
}
static immutable(WindowsTimeZone) getTimeZone(string name)
{
auto keyStr = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\0";
HKEY baseKey;
{
auto result = RegOpenKeyExA(HKEY_LOCAL_MACHINE, keyStr.ptr, 0, KEY_READ, &baseKey);
if(result != ERROR_SUCCESS)
throw new DateTimeException(format("Failed to open registry. Error: %s", result));
}
scope(exit) RegCloseKey(baseKey);
char[1024] keyName;
auto nameLen = keyName.length;
int result;
for(DWORD index = 0;
(result = RegEnumKeyExA(baseKey, index, keyName.ptr, &nameLen, null, null, null, null)) != ERROR_NO_MORE_ITEMS;
++index, nameLen = keyName.length)
{
if(result == ERROR_SUCCESS)
{
HKEY tzKey;
if(RegOpenKeyExA(baseKey, keyName.ptr, 0, KEY_READ, &tzKey) == ERROR_SUCCESS)
{
scope(exit) RegCloseKey(tzKey);
char[1024] strVal;
auto strValLen = strVal.length;
bool queryStringValue(string name, size_t lineNum = __LINE__)
{
strValLen = strVal.length;
return RegQueryValueExA(tzKey, name.ptr, null, null, cast(ubyte*)strVal.ptr, &strValLen) == ERROR_SUCCESS;
}
if(to!string(keyName.ptr) == name)
{
if(queryStringValue("Std\0"))
{
//Cannot use to!wstring(char*), probably due to bug http://d.puremagic.com/issues/show_bug.cgi?id=5016
static wstring conv(char* cstr, size_t strValLen)
{
cstr[strValLen - 1] = '\0';
string retval;
for(;; ++cstr)
{
if(*cstr == '\0')
break;
retval ~= *cstr;
}
return to!wstring(retval);
}
//auto stdName = to!wstring(strVal.ptr);
auto stdName = conv(strVal.ptr, strValLen);
if(queryStringValue("Dlt\0"))
{
//auto dstName = to!wstring(strVal.ptr);
auto dstName = conv(strVal.ptr, strValLen);
enum tzi = "TZI\0";
REG_TZI_FORMAT binVal;
auto binValLen = REG_TZI_FORMAT.sizeof;
if(RegQueryValueExA(tzKey, tzi.ptr, null, null, cast(ubyte*)&binVal, &binValLen) == ERROR_SUCCESS)
{
TIME_ZONE_INFORMATION tzInfo;
auto stdNameLen = stdName.length > 32 ? 32 : stdName.length;
auto dstNameLen = dstName.length > 32 ? 32 : dstName.length;
tzInfo.Bias = binVal.Bias;
tzInfo.StandardName[0 .. stdNameLen] = stdName[0 .. stdNameLen];
tzInfo.StandardName[stdNameLen .. $] = '\0';
tzInfo.StandardDate = binVal.StandardDate;
tzInfo.StandardBias = binVal.StandardBias;
tzInfo.DaylightName[0 .. dstNameLen] = dstName[0 .. dstNameLen];
tzInfo.DaylightName[dstNameLen .. $] = '\0';
tzInfo.DaylightDate = binVal.DaylightDate;
tzInfo.DaylightBias = binVal.DaylightBias;
return new WindowsTimeZone(name, tzInfo);
}
}
}
}
}
}
}
throw new DateTimeException(format("Failed to find time zone: %s", name));
}
static string[] getInstalledTZNames()
{
auto timezones = appender!(string[])();
auto keyStr = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones";
HKEY baseKey;
{
auto result = RegOpenKeyExA(HKEY_LOCAL_MACHINE, keyStr.ptr, 0, KEY_READ, &baseKey);
if(result != ERROR_SUCCESS)
throw new DateTimeException(format("Failed to open registry. Error: %s", result));
}
scope(exit) RegCloseKey(baseKey);
char[1024] keyName;
auto nameLen = keyName.length;
int result;
for(DWORD index = 0;
(result = RegEnumKeyExA(baseKey, index, keyName.ptr, &nameLen, null, null, null, null)) != ERROR_NO_MORE_ITEMS;
++index, nameLen = keyName.length)
{
if(result == ERROR_SUCCESS)
timezones.put(to!string(keyName.ptr));
}
sort(timezones.data);
return timezones.data;
}
unittest
{
version(testStdDateTime)
{
static void testWTZSuccess(string tzName)
{
scope(failure) writefln("TZName which threw: %s", tzName);
WindowsTimeZone.getTimeZone(tzName);
}
auto tzNames = getInstalledTZNames();
foreach(tzName; tzNames)
assertNotThrown!DateTimeException(testWTZSuccess(tzName));
}
}
private:
static bool _dstInEffect(const TIME_ZONE_INFORMATION* tzInfo, long stdTime) nothrow
{
try
{
if(tzInfo.DaylightDate.wMonth == 0)
return false;
auto utcDateTime = cast(DateTime)SysTime(stdTime, UTC());
//The limits of what SystemTimeToTZSpecificLocalTime will accept.
if(utcDateTime.year < 1601)
{
if(utcDateTime.month == Month.feb && utcDateTime.day == 29)
utcDateTime.day = 28;
utcDateTime.year = 1601;
}
else if(utcDateTime.year > 30_827)
{
if(utcDateTime.month == Month.feb && utcDateTime.day == 29)
utcDateTime.day = 28;
utcDateTime.year = 30_827;
}
//SystemTimeToTZSpecificLocalTime doesn't act correctly at the
//beginning or end of the year (bleh). Unless some bizarre time
//zone changes DST on January 1st or December 31st, this should
//fix the problem.
if(utcDateTime.month == Month.jan)
{
if(utcDateTime.day == 1)
utcDateTime.day = 2;
}
else if(utcDateTime.month == Month.dec && utcDateTime.day == 31)
utcDateTime.day = 30;
SYSTEMTIME utcTime = void;
SYSTEMTIME otherTime = void;
utcTime.wYear = utcDateTime.year;
utcTime.wMonth = utcDateTime.month;
utcTime.wDay = utcDateTime.day;
utcTime.wHour = utcDateTime.hour;
utcTime.wMinute = utcDateTime.minute;
utcTime.wSecond = utcDateTime.second;
utcTime.wMilliseconds = 0;
immutable result = SystemTimeToTzSpecificLocalTime(cast(TIME_ZONE_INFORMATION*)tzInfo,
&utcTime,
&otherTime);
assert(result);
immutable otherDateTime = DateTime(otherTime.wYear,
otherTime.wMonth,
otherTime.wDay,
otherTime.wHour,
otherTime.wMinute,
otherTime.wSecond);
immutable diff = utcDateTime - otherDateTime;
immutable minutes = diff.total!"minutes"() - tzInfo.Bias;
if(minutes == tzInfo.DaylightBias)
return true;
assert(minutes == tzInfo.StandardBias);
return false;
}
catch(Exception e)
assert(0, "DateTime's constructor threw.");
}
version(testStdDateTime) unittest
{
TIME_ZONE_INFORMATION tzInfo;
GetTimeZoneInformation(&tzInfo);
foreach(year; [1600, 1601, 30_827, 30_828])
WindowsTimeZone._dstInEffect(&tzInfo, SysTime(DateTime(year, 1, 1)).stdTime);
}
static long _utcToTZ(const TIME_ZONE_INFORMATION* tzInfo, long stdTime, bool hasDST) nothrow
{
if(hasDST && WindowsTimeZone._dstInEffect(tzInfo, stdTime))
return stdTime - convert!("minutes", "hnsecs")(tzInfo.Bias + tzInfo.DaylightBias);
return stdTime - convert!("minutes", "hnsecs")(tzInfo.Bias + tzInfo.StandardBias);
}
static long _tzToUTC(const TIME_ZONE_INFORMATION* tzInfo, long adjTime, bool hasDST) nothrow
{
if(hasDST)
{
try
{
bool dstInEffectForLocalDateTime(DateTime localDateTime)
{
//The limits of what SystemTimeToTZSpecificLocalTime will accept.
if(localDateTime.year < 1601)
{
if(localDateTime.month == Month.feb && localDateTime.day == 29)
localDateTime.day = 28;
localDateTime.year = 1601;
}
else if(localDateTime.year > 30_827)
{
if(localDateTime.month == Month.feb && localDateTime.day == 29)
localDateTime.day = 28;
localDateTime.year = 30_827;
}
//SystemTimeToTZSpecificLocalTime doesn't act correctly at the
//beginning or end of the year (bleh). Unless some bizarre time
//zone changes DST on January 1st or December 31st, this should
//fix the problem.
if(localDateTime.month == Month.jan)
{
if(localDateTime.day == 1)
localDateTime.day = 2;
}
else if(localDateTime.month == Month.dec && localDateTime.day == 31)
localDateTime.day = 30;
SYSTEMTIME utcTime = void;
SYSTEMTIME localTime = void;
localTime.wYear = localDateTime.year;
localTime.wMonth = localDateTime.month;
localTime.wDay = localDateTime.day;
localTime.wHour = localDateTime.hour;
localTime.wMinute = localDateTime.minute;
localTime.wSecond = localDateTime.second;
localTime.wMilliseconds = 0;
immutable result = SystemTimeToTzSpecificLocalTime(cast(TIME_ZONE_INFORMATION*)tzInfo,
&localTime,
&utcTime);
assert(result);
immutable utcDateTime = DateTime(utcTime.wYear,
utcTime.wMonth,
utcTime.wDay,
utcTime.wHour,
utcTime.wMinute,
utcTime.wSecond);
immutable diff = localDateTime - utcDateTime;
immutable minutes = diff.total!"minutes"() - tzInfo.Bias;
if(minutes == tzInfo.DaylightBias)
return true;
assert(minutes == tzInfo.StandardBias);
return false;
}
auto localDateTime = cast(DateTime)SysTime(adjTime, UTC());
auto localDateTimeBefore = localDateTime - dur!"hours"(1);
auto localDateTimeAfter = localDateTime + dur!"hours"(1);
auto dstInEffectNow = dstInEffectForLocalDateTime(localDateTime);
auto dstInEffectBefore = dstInEffectForLocalDateTime(localDateTimeBefore);
auto dstInEffectAfter = dstInEffectForLocalDateTime(localDateTimeAfter);
bool isDST;
if(dstInEffectBefore && dstInEffectNow && dstInEffectAfter)
isDST = true;
else if(!dstInEffectBefore && !dstInEffectNow && !dstInEffectAfter)
isDST = false;
else if((!dstInEffectBefore && dstInEffectAfter) ||
(dstInEffectBefore && !dstInEffectAfter))
{
isDST = dstInEffectNow;
}
else
assert(0, "Bad Logic.");
if(isDST)
return adjTime + convert!("minutes", "hnsecs")(tzInfo.Bias + tzInfo.DaylightBias);
}
catch(Exception e)
assert(0, "SysTime's constructor threw.");
}
return adjTime + convert!("minutes", "hnsecs")(tzInfo.Bias + tzInfo.StandardBias);
}
this(string name, TIME_ZONE_INFORMATION tzInfo) immutable
{
//Cannot use to!string(wchar*), probably due to bug http://d.puremagic.com/issues/show_bug.cgi?id=5016
static string conv(wchar* wcstr)
{
wcstr[31] = '\0';
wstring retval;
for(;; ++wcstr)
{
if(*wcstr == '\0')
break;
retval ~= *wcstr;
}
return to!string(retval);
}
//super(name, to!string(tzInfo.StandardName.ptr), to!string(tzInfo.DaylightName.ptr));
super(name, conv(tzInfo.StandardName.ptr), conv(tzInfo.DaylightName.ptr));
_tzInfo = tzInfo;
}
TIME_ZONE_INFORMATION _tzInfo;
}
}
version(StdDdoc)
{
/++
$(BLUE This function is Posix-Only.)
Allows you to set the local time zone on Posix systems with the TZ
database name by setting the TZ environment variable.
Unfortunately, there is no way to do it on Windows using the TZ
database name, so this function only exists on Posix systems.
+/
void setTZEnvVar(string tzDatabaseName);
/++
$(BLUE This function is Posix-Only.)
Clears the TZ environment variable.
+/
void clearTZEnvVar();
}
else version(Posix)
{
void setTZEnvVar(string tzDatabaseName) nothrow
{
try
{
auto value = PosixTimeZone.defaultTZDatabaseDir ~ tzDatabaseName ~ "\0";
setenv("TZ", value.ptr, 1);
tzset();
}
catch(Exception e)
assert(0, "The impossible happened. setenv or tzset threw.");
}
void clearTZEnvVar() nothrow
{
try
{
unsetenv("TZ");
tzset();
}
catch(Exception e)
assert(0, "The impossible happened. unsetenv or tzset threw.");
}
}
/++
Converts the given TZ Database name to the corresponding Windows time zone
name.
Note that in a few cases, a TZ Dabatase name corresponds to two different
Windows time zone names. So, while in most cases converting from one to the
other and back again will result in the same time zone name that you started
with, in a few cases, you will get a different name.
Also, there are far more TZ Database names than Windows time zones, so some
of the more exotic TZ Database names don't have corresponding Windows time
zone names.
See_Also:
$(WEB unicode.org/repos/cldr-tmp/trunk/diff/supplemental/zone_tzid.html,
Windows <-> TZ Database Name Conversion Table)
Params:
tzName = The TZ Database name to convert.
Throws:
$(D DateTimeException) if the given $(D_PARAM tzName) cannot be
converted.
+/
string tzDatabaseNameToWindowsTZName(string tzName)
{
switch(tzName)
{
case "Africa/Cairo": return "Egypt Standard Time";
case "Africa/Casablanca": return "Morocco Standard Time";
case "Africa/Johannesburg": return "South Africa Standard Time";
case "Africa/Lagos": return "W. Central Africa Standard Time";
case "Africa/Nairobi": return "E. Africa Standard Time";
case "Africa/Windhoek": return "Namibia Standard Time";
case "America/Anchorage": return "Alaskan Standard Time";
case "America/Asuncion": return "Paraguay Standard Time";
case "America/Bogota": return "SA Pacific Standard Time";
case "America/Buenos_Aires": return "Argentina Standard Time";
case "America/Caracas": return "Venezuela Standard Time";
case "America/Cayenne": return "SA Eastern Standard Time";
case "America/Chicago": return "Central Standard Time";
case "America/Chihuahua": return "Mountain Standard Time (Mexico)";
case "America/Cuiaba": return "Central Brazilian Standard Time";
case "America/Denver": return "Mountain Standard Time";
case "America/Godthab": return "Greenland Standard Time";
case "America/Guatemala": return "Central America Standard Time";
case "America/Halifax": return "Atlantic Standard Time";
case "America/La_Paz": return "SA Western Standard Time";
case "America/Los_Angeles": return "Pacific Standard Time";
case "America/Mexico_City": return "Central Standard Time (Mexico)";
case "America/Montevideo": return "Montevideo Standard Time";
case "America/New_York": return "Eastern Standard Time";
case "America/Phoenix": return "US Mountain Standard Time";
case "America/Regina": return "Canada Central Standard Time";
case "America/Santa_Isabel": return "Pacific Standard Time (Mexico)";
case "America/Santiago": return "Pacific SA Standard Time";
case "America/Sao_Paulo": return "E. South America Standard Time";
case "America/St_Johns": return "Newfoundland Standard Time";
case "Asia/Almaty": return "Central Asia Standard Time";
case "Asia/Amman": return "Jordan Standard Time";
case "Asia/Baghdad": return "Arabic Standard Time";
case "Asia/Baku": return "Azerbaijan Standard Time";
case "Asia/Bangkok": return "SE Asia Standard Time";
case "Asia/Beirut": return "Middle East Standard Time";
case "Asia/Calcutta": return "India Standard Time";
case "Asia/Colombo": return "Sri Lanka Standard Time";
case "Asia/Damascus": return "Syria Standard Time";
case "Asia/Dhaka": return "Bangladesh Standard Time";
case "Asia/Dubai": return "Arabian Standard Time";
case "Asia/Irkutsk": return "North Asia East Standard Time";
case "Asia/Jerusalem": return "Israel Standard Time";
case "Asia/Kabul": return "Afghanistan Standard Time";
case "Asia/Kamchatka": return "Kamchatka Standard Time";
case "Asia/Karachi": return "Pakistan Standard Time";
case "Asia/Katmandu": return "Nepal Standard Time";
case "Asia/Krasnoyarsk": return "North Asia Standard Time";
case "Asia/Magadan": return "Magadan Standard Time";
case "Asia/Novosibirsk": return "N. Central Asia Standard Time";
case "Asia/Rangoon": return "Myanmar Standard Time";
case "Asia/Riyadh": return "Arab Standard Time";
case "Asia/Seoul": return "Korea Standard Time";
case "Asia/Shanghai": return "China Standard Time";
case "Asia/Singapore": return "Singapore Standard Time";
case "Asia/Taipei": return "Taipei Standard Time";
case "Asia/Tashkent": return "West Asia Standard Time";
case "Asia/Tbilisi": return "Georgian Standard Time";
case "Asia/Tehran": return "Iran Standard Time";
case "Asia/Tokyo": return "Tokyo Standard Time";
case "Asia/Ulaanbaatar": return "Ulaanbaatar Standard Time";
case "Asia/Vladivostok": return "Vladivostok Standard Time";
case "Asia/Yakutsk": return "Yakutsk Standard Time";
case "Asia/Yekaterinburg": return "Ekaterinburg Standard Time";
case "Asia/Yerevan": return "Caucasus Standard Time";
case "Atlantic/Azores": return "Azores Standard Time";
case "Atlantic/Cape_Verde": return "Cape Verde Standard Time";
case "Atlantic/Reykjavik": return "Greenwich Standard Time";
case "Australia/Adelaide": return "Cen. Australia Standard Time";
case "Australia/Brisbane": return "E. Australia Standard Time";
case "Australia/Darwin": return "AUS Central Standard Time";
case "Australia/Hobart": return "Tasmania Standard Time";
case "Australia/Perth": return "W. Australia Standard Time";
case "Australia/Sydney": return "AUS Eastern Standard Time";
case "Etc/GMT-12": return "UTC+12";
case "Etc/GMT": return "UTC";
case "Etc/GMT+11": return "UTC-11";
case "Etc/GMT+12": return "Dateline Standard Time";
case "Etc/GMT+2": return "Mid-Atlantic Standard Time";
case "Etc/GMT+5": return "US Eastern Standard Time";
case "Europe/Berlin": return "W. Europe Standard Time";
case "Europe/Budapest": return "Central Europe Standard Time";
case "Europe/Istanbul": return "GTB Standard Time";
case "Europe/Kiev": return "FLE Standard Time";
case "Europe/London": return "GMT Standard Time";
case "Europe/Minsk": return "E. Europe Standard Time";
case "Europe/Moscow": return "Russian Standard Time";
case "Europe/Paris": return "Romance Standard Time";
case "Europe/Warsaw": return "Central European Standard Time";
case "Indian/Mauritius": return "Mauritius Standard Time";
case "Pacific/Apia": return "Samoa Standard Time";
case "Pacific/Auckland": return "New Zealand Standard Time";
case "Pacific/Fiji": return "Fiji Standard Time";
case "Pacific/Guadalcanal": return "Central Pacific Standard Time";
case "Pacific/Honolulu": return "Hawaiian Standard Time";
case "Pacific/Port_Moresby": return "West Pacific Standard Time";
case "Pacific/Tongatapu": return "Tonga Standard Time";
default:
throw new DateTimeException(format("Could not find Windows time zone name for: %s.", tzName));
}
}
unittest
{
version(testStdDateTime)
{
version(Windows)
{
static void testTZSuccess(string tzName)
{
scope(failure) writefln("TZName which threw: %s", tzName);
tzDatabaseNameToWindowsTZName(tzName);
}
auto timeZones = TimeZone.getInstalledTZNames();
foreach(tzname; timeZones)
assertNotThrown!DateTimeException(testTZSuccess(tzname));
}
}
}
/++
Converts the given Windows time zone name to a corresponding TZ Database
name.
See_Also:
$(WEB unicode.org/repos/cldr-tmp/trunk/diff/supplemental/zone_tzid.html,
Windows <-> TZ Database Name Conversion Table)
Params:
tzName = The TZ Database name to convert.
Throws:
$(D DateTimeException) if the given $(D_PARAM tzName) cannot be
converted.
+/
string windowsTZNameToTZDatabaseName(string tzName)
{
switch(tzName)
{
case "AUS Central Standard Time": return "Australia/Darwin";
case "AUS Eastern Standard Time": return "Australia/Sydney";
case "Afghanistan Standard Time": return "Asia/Kabul";
case "Alaskan Standard Time": return "America/Anchorage";
case "Arab Standard Time": return "Asia/Riyadh";
case "Arabian Standard Time": return "Asia/Dubai";
case "Arabic Standard Time": return "Asia/Baghdad";
case "Argentina Standard Time": return "America/Buenos_Aires";
case "Armenian Standard Time": return "Asia/Yerevan";
case "Atlantic Standard Time": return "America/Halifax";
case "Azerbaijan Standard Time": return "Asia/Baku";
case "Azores Standard Time": return "Atlantic/Azores";
case "Bangladesh Standard Time": return "Asia/Dhaka";
case "Canada Central Standard Time": return "America/Regina";
case "Cape Verde Standard Time": return "Atlantic/Cape_Verde";
case "Caucasus Standard Time": return "Asia/Yerevan";
case "Cen. Australia Standard Time": return "Australia/Adelaide";
case "Central America Standard Time": return "America/Guatemala";
case "Central Asia Standard Time": return "Asia/Almaty";
case "Central Brazilian Standard Time": return "America/Cuiaba";
case "Central Europe Standard Time": return "Europe/Budapest";
case "Central European Standard Time": return "Europe/Warsaw";
case "Central Pacific Standard Time": return "Pacific/Guadalcanal";
case "Central Standard Time": return "America/Chicago";
case "Central Standard Time (Mexico)": return "America/Mexico_City";
case "China Standard Time": return "Asia/Shanghai";
case "Dateline Standard Time": return "Etc/GMT+12";
case "E. Africa Standard Time": return "Africa/Nairobi";
case "E. Australia Standard Time": return "Australia/Brisbane";
case "E. Europe Standard Time": return "Europe/Minsk";
case "E. South America Standard Time": return "America/Sao_Paulo";
case "Eastern Standard Time": return "America/New_York";
case "Egypt Standard Time": return "Africa/Cairo";
case "Ekaterinburg Standard Time": return "Asia/Yekaterinburg";
case "FLE Standard Time": return "Europe/Kiev";
case "Fiji Standard Time": return "Pacific/Fiji";
case "GMT Standard Time": return "Europe/London";
case "GTB Standard Time": return "Europe/Istanbul";
case "Georgian Standard Time": return "Asia/Tbilisi";
case "Greenland Standard Time": return "America/Godthab";
case "Greenwich Standard Time": return "Atlantic/Reykjavik";
case "Hawaiian Standard Time": return "Pacific/Honolulu";
case "India Standard Time": return "Asia/Calcutta";
case "Iran Standard Time": return "Asia/Tehran";
case "Israel Standard Time": return "Asia/Jerusalem";
case "Jordan Standard Time": return "Asia/Amman";
case "Kamchatka Standard Time": return "Asia/Kamchatka";
case "Korea Standard Time": return "Asia/Seoul";
case "Magadan Standard Time": return "Asia/Magadan";
case "Mauritius Standard Time": return "Indian/Mauritius";
case "Mexico Standard Time": return "America/Mexico_City";
case "Mexico Standard Time 2": return "America/Chihuahua";
case "Mid-Atlantic Standard Time": return "Etc/GMT+2";
case "Middle East Standard Time": return "Asia/Beirut";
case "Montevideo Standard Time": return "America/Montevideo";
case "Morocco Standard Time": return "Africa/Casablanca";
case "Mountain Standard Time": return "America/Denver";
case "Mountain Standard Time (Mexico)": return "America/Chihuahua";
case "Myanmar Standard Time": return "Asia/Rangoon";
case "N. Central Asia Standard Time": return "Asia/Novosibirsk";
case "Namibia Standard Time": return "Africa/Windhoek";
case "Nepal Standard Time": return "Asia/Katmandu";
case "New Zealand Standard Time": return "Pacific/Auckland";
case "Newfoundland Standard Time": return "America/St_Johns";
case "North Asia East Standard Time": return "Asia/Irkutsk";
case "North Asia Standard Time": return "Asia/Krasnoyarsk";
case "Pacific SA Standard Time": return "America/Santiago";
case "Pacific Standard Time": return "America/Los_Angeles";
case "Pacific Standard Time (Mexico)": return "America/Santa_Isabel";
case "Pakistan Standard Time": return "Asia/Karachi";
case "Paraguay Standard Time": return "America/Asuncion";
case "Romance Standard Time": return "Europe/Paris";
case "Russian Standard Time": return "Europe/Moscow";
case "SA Eastern Standard Time": return "America/Cayenne";
case "SA Pacific Standard Time": return "America/Bogota";
case "SA Western Standard Time": return "America/La_Paz";
case "SE Asia Standard Time": return "Asia/Bangkok";
case "Samoa Standard Time": return "Pacific/Apia";
case "Singapore Standard Time": return "Asia/Singapore";
case "South Africa Standard Time": return "Africa/Johannesburg";
case "Sri Lanka Standard Time": return "Asia/Colombo";
case "Syria Standard Time": return "Asia/Damascus";
case "Taipei Standard Time": return "Asia/Taipei";
case "Tasmania Standard Time": return "Australia/Hobart";
case "Tokyo Standard Time": return "Asia/Tokyo";
case "Tonga Standard Time": return "Pacific/Tongatapu";
case "US Eastern Standard Time": return "Etc/GMT+5";
case "US Mountain Standard Time": return "America/Phoenix";
case "UTC": return "Etc/GMT";
case "UTC+12": return "Etc/GMT-12";
case "UTC-02": return "Etc/GMT+2";
case "UTC-11": return "Etc/GMT+11";
case "Ulaanbaatar Standard Time": return "Asia/Ulaanbaatar";
case "Venezuela Standard Time": return "America/Caracas";
case "Vladivostok Standard Time": return "Asia/Vladivostok";
case "W. Australia Standard Time": return "Australia/Perth";
case "W. Central Africa Standard Time": return "Africa/Lagos";
case "W. Europe Standard Time": return "Europe/Berlin";
case "West Asia Standard Time": return "Asia/Tashkent";
case "West Pacific Standard Time": return "Pacific/Port_Moresby";
case "Yakutsk Standard Time": return "Asia/Yakutsk";
default:
throw new DateTimeException(format("Could not find TZ Database name for: %s.", tzName));
}
}
unittest
{
version(testStdDateTime)
{
version(Windows)
{
static void testTZSuccess(string tzName)
{
scope(failure) writefln("TZName which threw: %s", tzName);
windowsTZNameToTZDatabaseName(tzName);
}
auto timeZones = WindowsTimeZone.getInstalledTZNames();
foreach(tzname; timeZones)
assertNotThrown!DateTimeException(testTZSuccess(tzname));
}
}
}
//==============================================================================
// Section with StopWatch and Benchmark Code.
//==============================================================================
/++
$(D StopWatch) measures time as precisely as possible.
This class uses a high-performance counter. On Windows systems, it uses
$(D QueryPerformanceCounter), and on Posix systems, it uses
$(D clock_gettime) if available, and $(D gettimeofday) otherwise.
But the precision of $(D StopWatch) differs from system to system. It is
impossible to for it to be the same from system to system since the precision
of the system clock varies from system to system, and other system-dependent
and situation-dependent stuff (such as the overhead of a context switch
between threads) can also affect $(D StopWatch)'s accuracy.
Examples:
--------------------
void foo()
{
StopWatch sw;
enum n = 100;
TickDuration[n] times;
TickDuration last = TickDuration.from!"seconds"(0);
foreach(i; 0..n)
{
sw.start(); //start/resume mesuring.
foreach(unused; 0..1_000_000)
bar();
sw.stop(); //stop/pause measuring.
//Return value of peek() after having stopped are the always same.
writeln((i + 1) * 1_000_000, " times done, lap time: ",
sw.peek().msecs, "[ms]");
times[i] = sw.peek() - last;
last = sw.peek();
}
real sum = 0;
// When you want to know the number of seconds,
// you can use properties of TickDuration.
// (seconds, mseconds, useconds, hnsecs)
foreach(t; times)
sum += t.hnsecs;
writeln("Average time: ", sum/n, " hnsecs");
}
--------------------
+/
@safe struct StopWatch
{
public:
//Verify Example
@safe unittest
{
void writeln(S...)(S args){}
static void bar() {}
StopWatch sw;
enum n = 100;
TickDuration[n] times;
TickDuration last = TickDuration.from!"seconds"(0);
foreach(i; 0..n)
{
sw.start(); //start/resume mesuring.
foreach(unused; 0..1_000_000)
bar();
sw.stop(); //stop/pause measuring.
//Return value of peek() after having stopped are the always same.
writeln((i + 1) * 1_000_000, " times done, lap time: ",
sw.peek().msecs, "[ms]");
times[i] = sw.peek() - last;
last = sw.peek();
}
real sum = 0;
// When you want to know the number of seconds,
// you can use properties of TickDuration.
// (seconds, mseconds, useconds, hnsecs)
foreach(t; times)
sum += t.hnsecs;
writeln("Average time: ", sum/n, " hnsecs");
}
/++
Auto start with constructor.
+/
this(AutoStart autostart)
{
if(autostart)
start();
}
version(testStdDateTime) @safe unittest
{
auto sw = StopWatch(AutoStart.yes);
sw.stop();
}
///
bool opEquals(const ref StopWatch rhs) const pure nothrow
{
return _timeStart == rhs._timeStart &&
_timeMeasured == rhs._timeMeasured;
}
/++
Resets the stop watch.
+/
void reset()
{
if(_flagStarted)
{
// Set current system time if StopWatch is measuring.
_timeStart = Clock.currSystemTick;
}
else
{
// Set zero if StopWatch is not measuring.
_timeStart.length = 0;
}
_timeMeasured.length = 0;
}
version(testStdDateTime) @safe unittest
{
StopWatch sw;
sw.start();
sw.stop();
sw.reset();
assert(sw.peek().to!("seconds", real) == 0);
}
/++
Starts the stop watch.
+/
void start()
{
assert(!_flagStarted);
StopWatch sw;
_flagStarted = true;
_timeStart = Clock.currSystemTick;
}
version(testStdDateTime) @trusted unittest
{
StopWatch sw;
sw.start();
auto t1 = sw.peek();
bool doublestart = true;
try
sw.start();
catch(AssertError e)
doublestart = false;
assert(!doublestart);
sw.stop();
assert((t1 - sw.peek()).to!("seconds", real) <= 0);
}
/++
Stops the stop watch.
+/
void stop()
{
assert(_flagStarted);
_flagStarted = false;
_timeMeasured += Clock.currSystemTick - _timeStart;
}
version(testStdDateTime) @trusted unittest
{
StopWatch sw;
sw.start();
sw.stop();
auto t1 = sw.peek();
bool doublestop = true;
try
sw.stop();
catch(AssertError e)
doublestop = false;
assert(!doublestop);
assert((t1 - sw.peek()).to!("seconds", real) == 0);
}
/++
Peek at the amount of time which has passed since the stop watch was
started.
+/
TickDuration peek() const
{
if(_flagStarted)
return Clock.currSystemTick - _timeStart + _timeMeasured;
return _timeMeasured;
}
version(testStdDateTime) @safe unittest
{
StopWatch sw;
sw.start();
auto t1 = sw.peek();
sw.stop();
auto t2 = sw.peek();
auto t3 = sw.peek();
assert(t1 <= t2);
assert(t2 == t3);
}
private:
// true if observing.
bool _flagStarted = false;
// TickDuration at the time of StopWatch starting measurement.
TickDuration _timeStart;
// Total time that StopWatch ran.
TickDuration _timeMeasured;
}
// workaround for bug4886
@safe size_t lengthof(aliases...)() pure nothrow
{
return aliases.length;
}
/++
Benchmarks code for speed assessment and comparison.
Params:
fun = aliases of callable objects (e.g. function names). Each should
take no arguments.
n = The number of times each function is to be executed.
Returns:
The amount of time (as a $(CXREF time, TickDuration)) that it took to
call each function $(D n) times. The first value is the length of time
that it took to call $(D fun[0]) $(D n) times. The second value is the
length of time it took to call $(D fun[1]) $(D n) times. Etc.
Examples:
--------------------
int a;
void f0() {}
void f1() {auto b = a;}
void f2() {auto b = to!(string)(a);}
auto r = benchmark!(f0, f1, f2)(10_000_000);
writefln("Milliseconds to call fun[0] n times: %s", r[0].to!("msecs", int));
--------------------
+/
@safe TickDuration[lengthof!(fun)()] benchmark(fun...)(uint n)
if(areAllSafe!fun)
{
TickDuration[lengthof!(fun)()] result;
StopWatch sw;
sw.start();
foreach(i, unused; fun)
{
sw.reset();
foreach(j; 0 .. n)
fun[i]();
result[i] = sw.peek();
}
return result;
}
/++ Ditto +/
TickDuration[lengthof!(fun)()] benchmark(fun...)(uint times)
if(!areAllSafe!fun)
{
TickDuration[lengthof!(fun)()] result;
StopWatch sw;
sw.start();
foreach(i, unused; fun)
{
sw.reset();
foreach(j; 0 .. times)
fun[i]();
result[i] = sw.peek();
}
return result;
}
//Verify Examples.
version(testStdDateTime) unittest
{
void writefln(S...)(S args){}
int a;
void f0() {}
void f1() {auto b = a;}
void f2() {auto b = to!(string)(a);}
auto r = benchmark!(f0, f1, f2)(10_000_000);
writefln("Milliseconds to call fun[0] n times: %s", r[0].to!("msecs", int));
}
version(testStdDateTime) @safe unittest
{
int a;
void f0() {}
//void f1() {auto b = to!(string)(a);}
void f2() {auto b = (a);}
auto r = benchmark!(f0, f2)(100);
}
/++
Return value of benchmark with two functions comparing.
+/
@safe struct ComparingBenchmarkResult
{
/++
Evaluation value
This returns the evaluation value of performance as the ratio of
baseFunc's time over targetFunc's time. If performance is high, this
returns a high value.
+/
@property real point() const pure nothrow
{
return _baseTime.length / cast(const real)_targetTime.length;
}
/++
The time required of the base function
+/
@property public TickDuration baseTime() const pure nothrow
{
return _baseTime;
}
/++
The time required of the target function
+/
@property public TickDuration targetTime() const pure nothrow
{
return _targetTime;
}
private:
this(TickDuration baseTime, TickDuration targetTime) pure nothrow
{
_baseTime = baseTime;
_targetTime = targetTime;
}
TickDuration _baseTime;
TickDuration _targetTime;
}
/++
Benchmark with two functions comparing.
Params:
baseFunc = The function to become the base of the speed.
targetFunc = The function that wants to measure speed.
times = The number of times each function is to be executed.
Examples:
--------------------
void f1() {
// ...
}
void f2() {
// ...
}
void main() {
auto b = comparingBenchmark!(f1, f2, 0x80);
writeln(b.point);
}
--------------------
+/
@safe ComparingBenchmarkResult comparingBenchmark(alias baseFunc,
alias targetFunc,
int times = 0xfff)()
if(isSafe!baseFunc && isSafe!targetFunc)
{
auto t = benchmark!(baseFunc, targetFunc)(times);
return ComparingBenchmarkResult(t[0], t[1]);
}
/++ Ditto +/
ComparingBenchmarkResult comparingBenchmark(alias baseFunc,
alias targetFunc,
int times = 0xfff)()
if(!isSafe!baseFunc || !isSafe!targetFunc)
{
auto t = benchmark!(baseFunc, targetFunc)(times);
return ComparingBenchmarkResult(t[0], t[1]);
}
version(testStdDateTime) @safe unittest
{
void f1x() {}
void f2x() {}
@safe void f1o() {}
@safe void f2o() {}
auto b1 = comparingBenchmark!(f1o, f2o, 1); // OK
//static auto b2 = comparingBenchmark!(f1x, f2x, 1); // NG
}
version(testStdDateTime) unittest
{
void f1x() {}
void f2x() {}
@safe void f1o() {}
@safe void f2o() {}
auto b1 = comparingBenchmark!(f1o, f2o, 1); // OK
auto b2 = comparingBenchmark!(f1x, f2x, 1); // OK
}
//==============================================================================
// Section with public helper functions and templates.
//==============================================================================
/++
$(RED Scheduled for deprecation in August 2011. This is only here to help
transition code which uses std.date to using std.datetime.)
Returns a $(D d_time) for the given $(D SysTime).
+/
long sysTimeToDTime(in SysTime sysTime)
{
return convert!("hnsecs", "msecs")(sysTime.stdTime - 621355968000000000L);
}
version(testStdDateTime) unittest
{
_assertPred!"=="(sysTimeToDTime(SysTime(DateTime(1970, 1, 1), UTC())),
0);
_assertPred!"=="(sysTimeToDTime(SysTime(DateTime(1970, 1, 1), FracSec.from!"msecs"(1), UTC())),
1);
_assertPred!"=="(sysTimeToDTime(SysTime(DateTime(1969, 12, 31, 23, 59, 59), FracSec.from!"msecs"(999), UTC())),
-1);
_assertPred!"=="(sysTimeToDTime(SysTime(DateTime(1970, 1, 2), UTC())),
86_400_000);
_assertPred!"=="(sysTimeToDTime(SysTime(DateTime(1969, 12, 31), UTC())),
-86_400_000);
}
/++
$(RED Scheduled for deprecation in August 2011. This is only here to help
transition code which uses std.date to using std.datetime.)
Returns a $(D SysTime) for the given $(D d_time).
+/
SysTime dTimeToSysTime(long dTime, immutable TimeZone tz = null)
{
immutable hnsecs = convert!("msecs", "hnsecs")(dTime) + 621355968000000000L;
return SysTime(hnsecs, tz);
}
version(testStdDateTime) unittest
{
_assertPred!"=="(dTimeToSysTime(0),
SysTime(DateTime(1970, 1, 1), UTC()));
_assertPred!"=="(dTimeToSysTime(1),
SysTime(DateTime(1970, 1, 1), FracSec.from!"msecs"(1), UTC()));
_assertPred!"=="(dTimeToSysTime(-1),
SysTime(DateTime(1969, 12, 31, 23, 59, 59), FracSec.from!"msecs"(999), UTC()));
_assertPred!"=="(dTimeToSysTime(86_400_000),
SysTime(DateTime(1970, 1, 2), UTC()));
_assertPred!"=="(dTimeToSysTime(-86_400_000),
SysTime(DateTime(1969, 12, 31), UTC()));
}
/++
Returns the absolute value of a duration.
+/
D abs(D)(D duration)
if(is(Unqual!D == Duration) ||
is(Unqual!D == TickDuration))
{
static if(is(Unqual!D == Duration))
return dur!"hnsecs"(std.math.abs(duration.total!"hnsecs"()));
else static if(is(Unqual!D == TickDuration))
return TickDuration(std.math.abs(duration.length));
else
static assert(0);
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(abs(dur!"msecs"(5)), dur!"msecs"(5));
_assertPred!"=="(abs(dur!"msecs"(-5)), dur!"msecs"(5));
_assertPred!"=="(abs(TickDuration(17)), TickDuration(17));
_assertPred!"=="(abs(TickDuration(-17)), TickDuration(17));
}
}
/++
Whether the given type defines all of the necessary functions for it to
function as a time point.
+/
template isTimePoint(T)
{
enum isTimePoint = hasMin!T &&
hasMax!T &&
hasOverloadedOpBinaryWithDuration!T &&
hasOverloadedOpAssignWithDuration!T &&
hasOverloadedOpBinaryWithSelf!T;
}
unittest
{
version(testStdDateTime)
{
static assert(isTimePoint!(Date));
static assert(isTimePoint!(DateTime));
static assert(isTimePoint!(TimeOfDay));
static assert(isTimePoint!(SysTime));
static assert(isTimePoint!(const Date));
static assert(isTimePoint!(const DateTime));
static assert(isTimePoint!(const TimeOfDay));
static assert(isTimePoint!(const SysTime));
static assert(isTimePoint!(immutable Date));
static assert(isTimePoint!(immutable DateTime));
static assert(isTimePoint!(immutable TimeOfDay));
static assert(isTimePoint!(immutable SysTime));
}
}
/++
Whether the given Gregorian Year is a leap year.
Params:
year = The year to to be tested.
+/
static bool yearIsLeapYear(int year) pure nothrow
{
if(year % 400 == 0)
return true;
if(year % 100 == 0)
return false;
return year % 4 == 0;
}
version(testStdDateTime) unittest
{
foreach(year; [1, 2, 3, 5, 6, 7, 100, 200, 300, 500, 600, 700, 1998, 1999,
2001, 2002, 2003, 2005, 2006, 2007, 2009, 2010, 2011])
{
assert(!yearIsLeapYear(year), format("year: %s.", year));
assert(!yearIsLeapYear(-year), format("year: %s.", year));
}
foreach(year; [0, 4, 8, 400, 800, 1600, 1996, 2000, 2004, 2008, 2012])
{
assert(yearIsLeapYear(year), format("year: %s.", year));
assert(yearIsLeapYear(-year), format("year: %s.", year));
}
}
/++
Converts a $(D time_t) (which uses midnight, January 1st, 1970 UTC as its
epoch and seconds as its units) to std time (which uses midnight,
January 1st, 1 A.D. UTC and hnsecs as its units).
Params:
unixTime = The $(D time_t) to convert.
+/
long unixTimeToStdTime(time_t unixTime) pure nothrow
{
return 621_355_968_000_000_000L + convert!("seconds", "hnsecs")(unixTime);
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(unixTimeToStdTime(0), 621_355_968_000_000_000L); //Midnight, January 1st, 1970
_assertPred!"=="(unixTimeToStdTime(86_400), 621_355_968_000_000_000L + 864_000_000_000L); //Midnight, January 2nd, 1970
_assertPred!"=="(unixTimeToStdTime(-86_400), 621_355_968_000_000_000L - 864_000_000_000L); //Midnight, December 31st, 1969
_assertPred!"=="(unixTimeToStdTime(0), (Date(1970, 1, 1) - Date(1, 1, 1)).total!"hnsecs");
_assertPred!"=="(unixTimeToStdTime(0), (DateTime(1970, 1, 1) - DateTime(1, 1, 1)).total!"hnsecs");
}
}
/++
Converts std time (which uses midnight, January 1st, 1 A.D. UTC as its epoch
and hnsecs as its units) to $(D time_t) (which uses midnight, January 1st,
1970 UTC as its epoch and seconds as its units). If $(D time_t) is 32 bits,
rather than 64, and the result can't fit in a 32-bit value, then the closest
value that can be held in 32 bits will be used (so $(D time_t.max) if it
goes over and $(D time_t.min) if it goes under).
Note:
While Windows systems require that $(D time_t) be non-negative (in spite
of $(D time_t) being signed), this function still returns negative
numbers on Windows, since it's more flexible to allow negative time_t
for those who need it. So, if you're on Windows and are using the
standard C functions or Win32 API functions which take a $(D time_t),
you may want to check whether the return value of
$(D stdTimeToUnixTime) is non-negative.
Params:
stdTime = The std time to convert.
+/
time_t stdTimeToUnixTime(long stdTime) pure nothrow
{
immutable unixTime = convert!("hnsecs", "seconds")(stdTime - 621_355_968_000_000_000L);
static if(time_t.sizeof >= long.sizeof)
return cast(time_t)unixTime;
else
{
if(unixTime > 0)
{
if(unixTime > time_t.max)
return time_t.max;
return cast(time_t)unixTime;
}
if(unixTime < time_t.min)
return time_t.min;
return cast(time_t)unixTime;
}
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(stdTimeToUnixTime(621_355_968_000_000_000L), 0); //Midnight, January 1st, 1970
_assertPred!"=="(stdTimeToUnixTime(621_355_968_000_000_000L + 864_000_000_000L), 86_400); //Midnight, January 2nd, 1970
_assertPred!"=="(stdTimeToUnixTime(621_355_968_000_000_000L - 864_000_000_000L), -86_400); //Midnight, December 31st, 1969
_assertPred!"=="(stdTimeToUnixTime((Date(1970, 1, 1) - Date(1, 1, 1)).total!"hnsecs"), 0);
_assertPred!"=="(stdTimeToUnixTime((DateTime(1970, 1, 1) - DateTime(1, 1, 1)).total!"hnsecs"), 0);
}
}
version(StdDdoc)
{
version(Windows) {}
else
{
alias void* SYSTEMTIME;
alias void* FILETIME;
}
/++
$(BLUE This function is Windows-Only.)
Converts a $(D SYSTEMTIME) struct to a $(D SysTime).
Params:
st = The $(D SYSTEMTIME) struct to convert.
tz = The time zone that the time in the $(D SYSTEMTIME) struct is
assumed to be (if the $(D SYSTEMTIME) was supplied by a Windows
system call, the $(D SYSTEMTIME) will either be in local time
or UTC, depending on the call).
Throws:
$(D DateTimeException) if the given $(D SYSTEMTIME) will not fit in
a $(D SysTime), which is highly unlikely to happen given that
$(D SysTime.max) is in 29,228 A.D. and the maximum $(D SYSTEMTIME)
is in 30,827 A.D.
+/
SysTime SYSTEMTIMEToSysTime(const SYSTEMTIME* st, immutable TimeZone tz = LocalTime());
/++
$(BLUE This function is Windows-Only.)
Converts a $(D SysTime) to a $(D SYSTEMTIME) struct.
The $(D SYSTEMTIME) which is returned will be set using the given
$(D SysTime)'s time zone, so if you want the $(D SYSTEMTIME) to be in
UTC, set the $(D SysTime)'s time zone to UTC.
Params:
sysTime = The $(D SysTime) to convert.
Throws:
$(D DateTimeException) if the given $(D SysTime) will not fit in a
$(D SYSTEMTIME). This will only happen if the $(D SysTime)'s date is
prior to 1601 A.D.
+/
SYSTEMTIME SysTimeToSYSTEMTIME(in SysTime sysTime);
/++
$(BLUE This function is Windows-Only.)
Converts a $(D FILETIME) struct to a $(D SysTime).
Params:
ft = The $(D FILETIME) struct to convert.
tz = The time zone that the $(D SysTime) will be in ($(D FILETIME)s
are in UTC).
Throws:
$(D DateTimeException) if the given $(D FILETIME) will not fit in a
$(D SysTime) or if the $(D FILETIME) cannot be converted to a
$(D SYSTEMTIME).
+/
SysTime FILETIMEToSysTime(const FILETIME* ft, immutable TimeZone tz = LocalTime());
/++
$(BLUE This function is Windows-Only.)
Converts a $(D SysTime) to a $(D FILETIME) struct.
$(D FILETIME)s are always in UTC.
Params:
sysTime = The $(D SysTime) to convert.
Throws:
$(D DateTimeException) if the given $(D SysTime) will not fit in a
$(D FILETIME).
+/
FILETIME SysTimeToFILETIME(SysTime sysTime);
}
else version(Windows)
{
SysTime SYSTEMTIMEToSysTime(const SYSTEMTIME* st, immutable TimeZone tz = LocalTime())
{
const max = SysTime.max;
static void throwLaterThanMax()
{
throw new DateTimeException("The given SYSTEMTIME is for a date greater than SysTime.max.");
}
if(st.wYear > max.year)
throwLaterThanMax();
else if(st.wYear == max.year)
{
if(st.wMonth > max.month)
throwLaterThanMax();
else if(st.wMonth == max.month)
{
if(st.wDay > max.day)
throwLaterThanMax();
else if(st.wDay == max.day)
{
if(st.wHour > max.hour)
throwLaterThanMax();
else if(st.wHour == max.hour)
{
if(st.wMinute > max.minute)
throwLaterThanMax();
else if(st.wMinute == max.minute)
{
if(st.wSecond > max.second)
throwLaterThanMax();
else if(st.wSecond == max.second)
{
if(st.wMilliseconds > max.fracSec.msecs)
throwLaterThanMax();
}
}
}
}
}
}
auto dt = DateTime(st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond);
return SysTime(dt, FracSec.from!"msecs"(st.wMilliseconds), tz);
}
unittest
{
version(testStdDateTime)
{
auto sysTime = Clock.currTime(UTC());
SYSTEMTIME st = void;
GetSystemTime(&st);
auto converted = SYSTEMTIMEToSysTime(&st, UTC());
_assertPred!"<="(abs((converted - sysTime)),
dur!"seconds"(2));
}
}
SYSTEMTIME SysTimeToSYSTEMTIME(in SysTime sysTime)
{
immutable dt = cast(DateTime)sysTime;
if(dt.year < 1601)
throw new DateTimeException("SYSTEMTIME cannot hold dates prior to the year 1601.");
SYSTEMTIME st;
st.wYear = dt.year;
st.wMonth = dt.month;
st.wDayOfWeek = dt.dayOfWeek;
st.wDay = dt.day;
st.wHour = dt.hour;
st.wMinute = dt.minute;
st.wSecond = dt.second;
st.wMilliseconds = cast(ushort)sysTime.fracSec.msecs;
return st;
}
unittest
{
version(testStdDateTime)
{
SYSTEMTIME st = void;
GetSystemTime(&st);
auto sysTime = SYSTEMTIMEToSysTime(&st, UTC());
SYSTEMTIME result = SysTimeToSYSTEMTIME(sysTime);
_assertPred!"=="(st.wYear, result.wYear);
_assertPred!"=="(st.wMonth, result.wMonth);
_assertPred!"=="(st.wDayOfWeek, result.wDayOfWeek);
_assertPred!"=="(st.wDay, result.wDay);
_assertPred!"=="(st.wHour, result.wHour);
_assertPred!"=="(st.wMinute, result.wMinute);
_assertPred!"=="(st.wSecond, result.wSecond);
_assertPred!"=="(st.wMilliseconds, result.wMilliseconds);
}
}
SysTime FILETIMEToSysTime(const FILETIME* ft, immutable TimeZone tz = LocalTime())
{
SYSTEMTIME st = void;
if(!FileTimeToSystemTime(ft, &st))
throw new DateTimeException("FileTimeToSystemTime() failed.");
auto sysTime = SYSTEMTIMEToSysTime(&st, UTC());
sysTime.timezone = tz;
return sysTime;
}
unittest
{
version(testStdDateTime)
{
auto sysTime = Clock.currTime(UTC());
SYSTEMTIME st = void;
GetSystemTime(&st);
FILETIME ft = void;
SystemTimeToFileTime(&st, &ft);
auto converted = FILETIMEToSysTime(&ft);
_assertPred!"<="(abs((converted - sysTime)),
dur!"seconds"(2));
}
}
FILETIME SysTimeToFILETIME(SysTime sysTime)
{
SYSTEMTIME st = SysTimeToSYSTEMTIME(sysTime.toUTC());
FILETIME ft = void;
SystemTimeToFileTime(&st, &ft);
return ft;
}
unittest
{
version(testStdDateTime)
{
SYSTEMTIME st = void;
GetSystemTime(&st);
FILETIME ft = void;
SystemTimeToFileTime(&st, &ft);
auto sysTime = FILETIMEToSysTime(&ft, UTC());
FILETIME result = SysTimeToFILETIME(sysTime);
_assertPred!"=="(ft.dwLowDateTime, result.dwLowDateTime);
_assertPred!"=="(ft.dwHighDateTime, result.dwHighDateTime);
}
}
}
/++
Type representing the DOS file date/time format.
+/
typedef uint DosFileTime;
/++
Converts from DOS file date/time to $(D SysTime).
Params:
dft = The DOS file time to convert.
tz = The time zone which the DOS file time is assumed to be in.
Throws:
$(D DateTimeException) if the $(D DosFileTime) is invalid.
+/
SysTime DosFileTimeToSysTime(DosFileTime dft, immutable TimeZone tz = LocalTime())
{
uint dt = cast(uint)dft;
if(dt == 0)
throw new DateTimeException("Invalid DosFileTime.");
int year = ((dt >> 25) & 0x7F) + 1980;
int month = ((dt >> 21) & 0x0F); // 1..12
int dayOfMonth = ((dt >> 16) & 0x1F); // 1..31
int hour = (dt >> 11) & 0x1F; // 0..23
int minute = (dt >> 5) & 0x3F; // 0..59
int second = (dt << 1) & 0x3E; // 0..58 (in 2 second increments)
SysTime sysTime = void;
try
return SysTime(DateTime(year, month, dayOfMonth, hour, minute, second), tz);
catch(DateTimeException dte)
throw new DateTimeException("Invalid DosFileTime", __FILE__, __LINE__, dte);
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(DosFileTimeToSysTime(0b00000000001000010000000000000000),
SysTime(DateTime(1980, 1, 1, 0, 0, 0)));
_assertPred!"=="(DosFileTimeToSysTime(0b11111111100111111011111101111101),
SysTime(DateTime(2107, 12, 31, 23, 59, 58)));
_assertPred!"=="(DosFileTimeToSysTime(0x3E3F8456),
SysTime(DateTime(2011, 1, 31, 16, 34, 44)));
}
}
/++
Converts from $(D SysTime) to DOS file date/time.
Params:
sysTime = The $(D SysTime) to convert.
Throws:
$(D DateTimeException) if the given $(D SysTime) cannot be converted to
a $(D DosFileTime).
+/
DosFileTime SysTimeToDosFileTime(SysTime sysTime)
{
auto dateTime = cast(DateTime)sysTime;
if(dateTime.year < 1980)
throw new DateTimeException("DOS File Times cannot hold dates prior to 1980.");
if(dateTime.year > 2107)
throw new DateTimeException("DOS File Times cannot hold dates passed 2107.");
uint retval = 0;
retval = (dateTime.year - 1980) << 25;
retval |= (dateTime.month & 0x0F) << 21;
retval |= (dateTime.day & 0x1F) << 16;
retval |= (dateTime.hour & 0x1F) << 11;
retval |= (dateTime.minute & 0x3F) << 5;
retval |= (dateTime.second >> 1) & 0x1F;
return cast(DosFileTime)retval;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(SysTimeToDosFileTime(SysTime(DateTime(1980, 1, 1, 0, 0, 0))),
0b00000000001000010000000000000000);
_assertPred!"=="(SysTimeToDosFileTime(SysTime(DateTime(2107, 12, 31, 23, 59, 58))),
0b11111111100111111011111101111101);
_assertPred!"=="(SysTimeToDosFileTime(SysTime(DateTime(2011, 1, 31, 16, 34, 44))),
0x3E3F8456);
}
}
/++
Whether all of the given strings are valid units of time.
$(D "nsecs") is not considered a valid unit of time. Nothing in std.datetime
can handle precision greater than hnsecs, and the few functions in core.time
which deal with "nsecs" deal with it explicitly.
+/
bool validTimeUnits(string[] units...)
{
foreach(str; units)
{
if(!canFind(timeStrings.dup, str))
return false;
}
return true;
}
/++
Compares two time unit strings. $(D "years") are the largest units and
$(D "hnsecs") are the smallest.
Returns:
$(BOOKTABLE,
$(TR $(TD this < rhs) $(TD < 0))
$(TR $(TD this == rhs) $(TD 0))
$(TR $(TD this > rhs) $(TD > 0))
)
Throws:
$(D DateTimeException) if either of the given strings is not a valid
time unit string.
+/
int cmpTimeUnits(string lhs, string rhs)
{
auto tstrings = timeStrings.dup;
immutable indexOfLHS = std.algorithm.countUntil(tstrings, lhs);
immutable indexOfRHS = std.algorithm.countUntil(tstrings, rhs);
enforce(indexOfLHS != -1, format("%s is not a valid TimeString", lhs));
enforce(indexOfRHS != -1, format("%s is not a valid TimeString", rhs));
if(indexOfLHS < indexOfRHS)
return -1;
if(indexOfLHS > indexOfRHS)
return 1;
return 0;
}
unittest
{
version(testStdDateTime)
{
foreach(i, outerUnits; timeStrings)
{
_assertPred!"=="(cmpTimeUnits(outerUnits, outerUnits), 0);
//For some reason, $ won't compile.
foreach(innerUnits; timeStrings[i+1 .. timeStrings.length])
_assertPred!"=="(cmpTimeUnits(outerUnits, innerUnits), -1);
}
foreach(i, outerUnits; timeStrings)
{
foreach(innerUnits; timeStrings[0 .. i])
_assertPred!"=="(cmpTimeUnits(outerUnits, innerUnits), 1);
}
}
}
/++
Compares two time unit strings at compile time. $(D "years") are the largest
units and $(D "hnsecs") are the smallest.
This template is used instead of $(D cmpTimeUnits) because exceptions
can't be thrown at compile time and $(D cmpTimeUnits) must enforce that
the strings it's given are valid time unit strings. This template uses a
template constraint instead.
Returns:
$(BOOKTABLE,
$(TR $(TD this < rhs) $(TD < 0))
$(TR $(TD this == rhs) $(TD 0))
$(TR $(TD this > rhs) $(TD > 0))
)
+/
template CmpTimeUnits(string lhs, string rhs)
if(validTimeUnits(lhs, rhs))
{
enum CmpTimeUnits = cmpTimeUnitsCTFE(lhs, rhs);
}
/+
Helper function for $(D CmpTimeUnits).
+/
private int cmpTimeUnitsCTFE(string lhs, string rhs)
{
auto tstrings = timeStrings.dup;
immutable indexOfLHS = std.algorithm.countUntil(tstrings, lhs);
immutable indexOfRHS = std.algorithm.countUntil(tstrings, rhs);
if(indexOfLHS < indexOfRHS)
return -1;
if(indexOfLHS > indexOfRHS)
return 1;
return 0;
}
unittest
{
version(testStdDateTime)
{
static string genTest(size_t index)
{
auto currUnits = timeStrings[index];
auto test = `_assertPred!"=="(CmpTimeUnits!("` ~ currUnits ~ `", "` ~ currUnits ~ `"), 0); `;
//For some reason, $ won't compile.
foreach(units; timeStrings[index + 1 .. timeStrings.length])
test ~= `_assertPred!"=="(CmpTimeUnits!("` ~ currUnits ~ `", "` ~ units ~ `"), -1); `;
foreach(units; timeStrings[0 .. index])
test ~= `_assertPred!"=="(CmpTimeUnits!("` ~ currUnits ~ `", "` ~ units ~ `"), 1); `;
return test;
}
mixin(genTest(0));
mixin(genTest(1));
mixin(genTest(2));
mixin(genTest(3));
mixin(genTest(4));
mixin(genTest(5));
mixin(genTest(6));
mixin(genTest(7));
mixin(genTest(8));
mixin(genTest(9));
}
}
/++
Returns whether the given value is valid for the given unit type when in a
time point. Naturally, a duration is not held to a particular range, but
the values in a time point are (e.g. a month must be in the range of
1 - 12 inclusive).
Params:
units = The units of time to validate.
value = The number to validate.
Examples:
--------------------
assert(valid!"hours"(12));
assert(!valid!"hours"(32));
assert(valid!"months"(12));
assert(!valid!"months"(13));
--------------------
+/
bool valid(string units)(int value) pure nothrow
if(units == "months" ||
units == "hours" ||
units == "minutes" ||
units == "seconds")
{
static if(units == "months")
return value >= Month.jan && value <= Month.dec;
else static if(units == "hours")
return value >= 0 && value <= TimeOfDay.maxHour;
else static if(units == "minutes")
return value >= 0 && value <= TimeOfDay.maxMinute;
else static if(units == "seconds")
return value >= 0 && value <= TimeOfDay.maxSecond;
}
unittest
{
version(testStdDateTime)
{
//Verify Examples.
assert(valid!"hours"(12));
assert(!valid!"hours"(32));
assert(valid!"months"(12));
assert(!valid!"months"(13));
}
}
/++
Returns whether the given day is valid for the given year and month.
Params:
units = The units of time to validate.
year = The year of the day to validate.
month = The month of the day to validate.
day = The day to validate.
+/
bool valid(string units)(int year, int month, int day) pure nothrow
if(units == "days")
{
return day > 0 && day <= maxDay(year, month);
}
/++
Params:
units = The units of time to validate.
value = The number to validate.
file = The file that the $(D DateTimeException) will list if thrown.
line = The line number that the $(D DateTimeException) will list if
thrown.
Throws:
$(D DateTimeException) if $(D valid!units(value)) is false.
+/
void enforceValid(string units)(int value, string file = __FILE__, size_t line = __LINE__) pure
if(units == "months" ||
units == "hours" ||
units == "minutes" ||
units == "seconds")
{
static if(units == "months")
{
if(!valid!units(value))
throw new DateTimeException(numToString(value) ~ " is not a valid month of the year.", file, line);
}
else static if(units == "hours")
{
if(!valid!units(value))
throw new DateTimeException(numToString(value) ~ " is not a valid hour of the day.", file, line);
}
else static if(units == "minutes")
{
if(!valid!units(value))
throw new DateTimeException(numToString(value) ~ " is not a valid minute of an hour.", file, line);
}
else static if(units == "seconds")
{
if(!valid!units(value))
throw new DateTimeException(numToString(value) ~ " is not a valid second of a minute.", file, line);
}
}
/++
Params:
units = The units of time to validate.
year = The year of the day to validate.
month = The month of the day to validate.
day = The day to validate.
file = The file that the $(D DateTimeException) will list if thrown.
line = The line number that the $(D DateTimeException) will list if
thrown.
Throws:
$(D DateTimeException) if $(D valid!"days"(year, month, day)) is false.
+/
void enforceValid(string units)(int year, Month month, int day, string file = __FILE__, size_t line = __LINE__) pure
if(units == "days")
{
if(!valid!"days"(year, month, day))
{
throw new DateTimeException(numToString(day) ~
" is not a valid day in " ~
monthToString(month) ~
" in " ~
numToString(year), file, line);
}
}
/++
Returns the number of months from the current months of the year to the
given month of the year. If they are the same, then the result is 0.
Params:
currMonth = The current month of the year.
month = The month of the year to get the number of months to.
+/
static int monthsToMonth(int currMonth, int month) pure
{
enforceValid!"months"(currMonth);
enforceValid!"months"(month);
if(currMonth == month)
return 0;
if(currMonth < month)
return month - currMonth;
return (Month.dec - currMonth) + month;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(monthsToMonth(Month.jan, Month.jan), 0);
_assertPred!"=="(monthsToMonth(Month.jan, Month.feb), 1);
_assertPred!"=="(monthsToMonth(Month.jan, Month.mar), 2);
_assertPred!"=="(monthsToMonth(Month.jan, Month.apr), 3);
_assertPred!"=="(monthsToMonth(Month.jan, Month.may), 4);
_assertPred!"=="(monthsToMonth(Month.jan, Month.jun), 5);
_assertPred!"=="(monthsToMonth(Month.jan, Month.jul), 6);
_assertPred!"=="(monthsToMonth(Month.jan, Month.aug), 7);
_assertPred!"=="(monthsToMonth(Month.jan, Month.sep), 8);
_assertPred!"=="(monthsToMonth(Month.jan, Month.oct), 9);
_assertPred!"=="(monthsToMonth(Month.jan, Month.nov), 10);
_assertPred!"=="(monthsToMonth(Month.jan, Month.dec), 11);
_assertPred!"=="(monthsToMonth(Month.may, Month.jan), 8);
_assertPred!"=="(monthsToMonth(Month.may, Month.feb), 9);
_assertPred!"=="(monthsToMonth(Month.may, Month.mar), 10);
_assertPred!"=="(monthsToMonth(Month.may, Month.apr), 11);
_assertPred!"=="(monthsToMonth(Month.may, Month.may), 0);
_assertPred!"=="(monthsToMonth(Month.may, Month.jun), 1);
_assertPred!"=="(monthsToMonth(Month.may, Month.jul), 2);
_assertPred!"=="(monthsToMonth(Month.may, Month.aug), 3);
_assertPred!"=="(monthsToMonth(Month.may, Month.sep), 4);
_assertPred!"=="(monthsToMonth(Month.may, Month.oct), 5);
_assertPred!"=="(monthsToMonth(Month.may, Month.nov), 6);
_assertPred!"=="(monthsToMonth(Month.may, Month.dec), 7);
_assertPred!"=="(monthsToMonth(Month.oct, Month.jan), 3);
_assertPred!"=="(monthsToMonth(Month.oct, Month.feb), 4);
_assertPred!"=="(monthsToMonth(Month.oct, Month.mar), 5);
_assertPred!"=="(monthsToMonth(Month.oct, Month.apr), 6);
_assertPred!"=="(monthsToMonth(Month.oct, Month.may), 7);
_assertPred!"=="(monthsToMonth(Month.oct, Month.jun), 8);
_assertPred!"=="(monthsToMonth(Month.oct, Month.jul), 9);
_assertPred!"=="(monthsToMonth(Month.oct, Month.aug), 10);
_assertPred!"=="(monthsToMonth(Month.oct, Month.sep), 11);
_assertPred!"=="(monthsToMonth(Month.oct, Month.oct), 0);
_assertPred!"=="(monthsToMonth(Month.oct, Month.nov), 1);
_assertPred!"=="(monthsToMonth(Month.oct, Month.dec), 2);
_assertPred!"=="(monthsToMonth(Month.dec, Month.jan), 1);
_assertPred!"=="(monthsToMonth(Month.dec, Month.feb), 2);
_assertPred!"=="(monthsToMonth(Month.dec, Month.mar), 3);
_assertPred!"=="(monthsToMonth(Month.dec, Month.apr), 4);
_assertPred!"=="(monthsToMonth(Month.dec, Month.may), 5);
_assertPred!"=="(monthsToMonth(Month.dec, Month.jun), 6);
_assertPred!"=="(monthsToMonth(Month.dec, Month.jul), 7);
_assertPred!"=="(monthsToMonth(Month.dec, Month.aug), 8);
_assertPred!"=="(monthsToMonth(Month.dec, Month.sep), 9);
_assertPred!"=="(monthsToMonth(Month.dec, Month.oct), 10);
_assertPred!"=="(monthsToMonth(Month.dec, Month.nov), 11);
_assertPred!"=="(monthsToMonth(Month.dec, Month.dec), 0);
}
}
/++
Returns the number of days from the current day of the week to the given
day of the week. If they are the same, then the result is 0.
Params:
currDoW = The current day of the week.
dow = The day of the week to get the number of days to.
+/
static int daysToDayOfWeek(DayOfWeek currDoW, DayOfWeek dow) pure nothrow
{
if(currDoW == dow)
return 0;
if(currDoW < dow)
return dow - currDoW;
return (DayOfWeek.sat - currDoW) + dow + 1;
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sun, DayOfWeek.sun), 0);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sun, DayOfWeek.mon), 1);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sun, DayOfWeek.tue), 2);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sun, DayOfWeek.wed), 3);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sun, DayOfWeek.thu), 4);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sun, DayOfWeek.fri), 5);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sun, DayOfWeek.sat), 6);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.mon, DayOfWeek.sun), 6);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.mon, DayOfWeek.mon), 0);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.mon, DayOfWeek.tue), 1);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.mon, DayOfWeek.wed), 2);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.mon, DayOfWeek.thu), 3);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.mon, DayOfWeek.fri), 4);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.mon, DayOfWeek.sat), 5);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.tue, DayOfWeek.sun), 5);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.tue, DayOfWeek.mon), 6);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.tue, DayOfWeek.tue), 0);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.tue, DayOfWeek.wed), 1);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.tue, DayOfWeek.thu), 2);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.tue, DayOfWeek.fri), 3);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.tue, DayOfWeek.sat), 4);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.wed, DayOfWeek.sun), 4);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.wed, DayOfWeek.mon), 5);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.wed, DayOfWeek.tue), 6);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.wed, DayOfWeek.wed), 0);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.wed, DayOfWeek.thu), 1);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.wed, DayOfWeek.fri), 2);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.wed, DayOfWeek.sat), 3);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.thu, DayOfWeek.sun), 3);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.thu, DayOfWeek.mon), 4);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.thu, DayOfWeek.tue), 5);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.thu, DayOfWeek.wed), 6);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.thu, DayOfWeek.thu), 0);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.thu, DayOfWeek.fri), 1);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.thu, DayOfWeek.sat), 2);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.fri, DayOfWeek.sun), 2);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.fri, DayOfWeek.mon), 3);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.fri, DayOfWeek.tue), 4);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.fri, DayOfWeek.wed), 5);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.fri, DayOfWeek.thu), 6);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.fri, DayOfWeek.fri), 0);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.fri, DayOfWeek.sat), 1);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sat, DayOfWeek.sun), 1);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sat, DayOfWeek.mon), 2);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sat, DayOfWeek.tue), 3);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sat, DayOfWeek.wed), 4);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sat, DayOfWeek.thu), 5);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sat, DayOfWeek.fri), 6);
_assertPred!"=="(daysToDayOfWeek(DayOfWeek.sat, DayOfWeek.sat), 0);
}
}
version(StdDdoc)
{
/++
Function for starting to a stop watch time when the function is called
and stopping it when its return value goes out of scope and is destroyed.
When the value that is returned by this function is destroyed,
$(D func) will run. $(D func) is a unary function that takes a
$(CXREF TickDuration).
Examples:
--------------------
writeln("benchmark start!");
{
auto mt = measureTime!((a){assert(a.seconds);});
doSomething();
}
writeln("benchmark end!");
--------------------
+/
auto measureTime(alias func)();
}
else
{
@safe auto measureTime(alias func)()
if(isSafe!func)
{
struct Result
{
private StopWatch _sw = void;
this(AutoStart as)
{
_sw = StopWatch(as);
}
~this()
{
unaryFun!(func)(_sw.peek());
}
}
return Result(AutoStart.yes);
}
auto measureTime(alias func)()
if(!isSafe!func)
{
struct Result
{
private StopWatch _sw = void;
this(AutoStart as)
{
_sw = StopWatch(as);
}
~this()
{
unaryFun!(func)(_sw.peek());
}
}
return Result(AutoStart.yes);
}
}
version(testStdDateTime) @safe unittest
{
@safe static void func(TickDuration td)
{
assert(td.to!("seconds", real) <>= 0);
}
auto mt = measureTime!(func)();
/+
with (measureTime!((a){assert(a.seconds);}))
{
// doSomething();
// @@@BUG@@@ doesn't work yet.
}
+/
}
version(testStdDateTime) unittest
{
static void func(TickDuration td)
{
assert(td.to!("seconds", real) <>= 0);
}
auto mt = measureTime!(func)();
/+
with (measureTime!((a){assert(a.seconds);}))
{
// doSomething();
// @@@BUG@@@ doesn't work yet.
}
+/
}
//==============================================================================
// Private Section.
//==============================================================================
private:
//==============================================================================
// Section with private enums and constants.
//==============================================================================
enum daysInYear = 365; /// The number of days in a non-leap year.
enum daysInLeapYear = 366; /// The numbef or days in a leap year.
enum daysIn4Years = daysInYear * 3 + daysInLeapYear; /// Number of days in 4 years.
enum daysIn100Years = daysIn4Years * 25 - 1; /// The number of days in 100 years.
enum daysIn400Years = daysIn100Years * 4 + 1; /// The number of days in 400 years.
//==============================================================================
// Section with private helper functions and templates.
//==============================================================================
/+
Template to help with converting between time units.
+/
template hnsecsPer(string units)
if(CmpTimeUnits!(units, "months") < 0)
{
static if(units == "hnsecs")
enum hnsecsPer = 1L;
else static if(units == "usecs")
enum hnsecsPer = 10L;
else static if(units == "msecs")
enum hnsecsPer = 1000 * hnsecsPer!"usecs";
else static if(units == "seconds")
enum hnsecsPer = 1000 * hnsecsPer!"msecs";
else static if(units == "minutes")
enum hnsecsPer = 60 * hnsecsPer!"seconds";
else static if(units == "hours")
enum hnsecsPer = 60 * hnsecsPer!"minutes";
else static if(units == "days")
enum hnsecsPer = 24 * hnsecsPer!"hours";
else static if(units == "weeks")
enum hnsecsPer = 7 * hnsecsPer!"days";
}
/+
Splits out a particular unit from hnsecs and gives you the value for that
unit and the remaining hnsecs. It really shouldn't be used unless unless
all units larger than the given units have already been split out.
Params:
units = The units to split out.
hnsecs = The current total hnsecs. Upon returning, it is the hnsecs left
after splitting out the given units.
Returns:
The number of the given units from converting hnsecs to those units.
Examples:
--------------------
auto hnsecs = 2595000000007L;
immutable days = splitUnitsFromHNSecs!"days"(hnsecs);
assert(days == 3);
assert(hnsecs == 3000000007);
immutable minutes = splitUnitsFromHNSecs!"minutes"(hnsecs);
assert(minutes == 5);
assert(hnsecs == 7);
--------------------
+/
long splitUnitsFromHNSecs(string units)(ref long hnsecs) pure nothrow
if(validTimeUnits(units) &&
CmpTimeUnits!(units, "months") < 0)
{
immutable value = convert!("hnsecs", units)(hnsecs);
hnsecs -= convert!(units, "hnsecs")(value);
return value;
}
unittest
{
version(testStdDateTime)
{
//Verify Example.
auto hnsecs = 2595000000007L;
immutable days = splitUnitsFromHNSecs!"days"(hnsecs);
assert(days == 3);
assert(hnsecs == 3000000007);
immutable minutes = splitUnitsFromHNSecs!"minutes"(hnsecs);
assert(minutes == 5);
assert(hnsecs == 7);
}
}
/+
This function is used to split out the units without getting the remaining
hnsecs.
See_Also:
splitUnitsFromHNSecs()
Params:
units = The units to split out.
hnsecs = The current total hnsecs.
Returns:
The split out value.
Examples:
--------------------
auto hnsecs = 2595000000007L;
immutable days = getUnitsFromHNSecs!"days"(hnsecs);
assert(days == 3);
assert(hnsecs == 2595000000007L);
--------------------
+/
long getUnitsFromHNSecs(string units)(long hnsecs) pure nothrow
if(validTimeUnits(units) &&
CmpTimeUnits!(units, "months") < 0)
{
return convert!("hnsecs", units)(hnsecs);
}
unittest
{
version(testStdDateTime)
{
//Verify Example.
auto hnsecs = 2595000000007L;
immutable days = getUnitsFromHNSecs!"days"(hnsecs);
assert(days == 3);
assert(hnsecs == 2595000000007L);
}
}
/+
This function is used to split out the units without getting the units but
just the remaining hnsecs.
See_Also:
splitUnitsFromHNSecs()
Params:
units = The units to split out.
hnsecs = The current total hnsecs.
Returns:
The remaining hnsecs.
Examples:
--------------------
auto hnsecs = 2595000000007L;
auto returned = removeUnitsFromHNSecs!"days"(hnsecs);
assert(returned == 3000000007);
assert(hnsecs == 2595000000007L);
--------------------
+/
long removeUnitsFromHNSecs(string units)(long hnsecs) pure nothrow
if(validTimeUnits(units) &&
CmpTimeUnits!(units, "months") < 0)
{
immutable value = convert!("hnsecs", units)(hnsecs);
return hnsecs - convert!(units, "hnsecs")(value);
}
unittest
{
version(testStdDateTime)
{
//Verify Example.
auto hnsecs = 2595000000007L;
auto returned = removeUnitsFromHNSecs!"days"(hnsecs);
assert(returned == 3000000007);
assert(hnsecs == 2595000000007L);
}
}
/+
The maximum valid Day in the given month in the given year.
Params:
year = The year to get the day for.
month = The month of the Gregorian Calendar to get the day for.
+/
static ubyte maxDay(int year, int month) pure nothrow
in
{
assert(valid!"months"(month));
}
body
{
switch(month)
{
case Month.jan, Month.mar, Month.may, Month.jul, Month.aug, Month.oct, Month.dec:
return 31;
case Month.feb:
return yearIsLeapYear(year) ? 29 : 28;
case Month.apr, Month.jun, Month.sep, Month.nov:
return 30;
default:
assert(0, "Invalid month.");
}
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(maxDay(1999, 1), 31);
_assertPred!"=="(maxDay(1999, 2), 28);
_assertPred!"=="(maxDay(1999, 3), 31);
_assertPred!"=="(maxDay(1999, 4), 30);
_assertPred!"=="(maxDay(1999, 5), 31);
_assertPred!"=="(maxDay(1999, 6), 30);
_assertPred!"=="(maxDay(1999, 7), 31);
_assertPred!"=="(maxDay(1999, 8), 31);
_assertPred!"=="(maxDay(1999, 9), 30);
_assertPred!"=="(maxDay(1999, 10), 31);
_assertPred!"=="(maxDay(1999, 11), 30);
_assertPred!"=="(maxDay(1999, 12), 31);
_assertPred!"=="(maxDay(2000, 1), 31);
_assertPred!"=="(maxDay(2000, 2), 29);
_assertPred!"=="(maxDay(2000, 3), 31);
_assertPred!"=="(maxDay(2000, 4), 30);
_assertPred!"=="(maxDay(2000, 5), 31);
_assertPred!"=="(maxDay(2000, 6), 30);
_assertPred!"=="(maxDay(2000, 7), 31);
_assertPred!"=="(maxDay(2000, 8), 31);
_assertPred!"=="(maxDay(2000, 9), 30);
_assertPred!"=="(maxDay(2000, 10), 31);
_assertPred!"=="(maxDay(2000, 11), 30);
_assertPred!"=="(maxDay(2000, 12), 31);
//Test B.C.
_assertPred!"=="(maxDay(-1999, 1), 31);
_assertPred!"=="(maxDay(-1999, 2), 28);
_assertPred!"=="(maxDay(-1999, 3), 31);
_assertPred!"=="(maxDay(-1999, 4), 30);
_assertPred!"=="(maxDay(-1999, 5), 31);
_assertPred!"=="(maxDay(-1999, 6), 30);
_assertPred!"=="(maxDay(-1999, 7), 31);
_assertPred!"=="(maxDay(-1999, 8), 31);
_assertPred!"=="(maxDay(-1999, 9), 30);
_assertPred!"=="(maxDay(-1999, 10), 31);
_assertPred!"=="(maxDay(-1999, 11), 30);
_assertPred!"=="(maxDay(-1999, 12), 31);
_assertPred!"=="(maxDay(-2000, 1), 31);
_assertPred!"=="(maxDay(-2000, 2), 29);
_assertPred!"=="(maxDay(-2000, 3), 31);
_assertPred!"=="(maxDay(-2000, 4), 30);
_assertPred!"=="(maxDay(-2000, 5), 31);
_assertPred!"=="(maxDay(-2000, 6), 30);
_assertPred!"=="(maxDay(-2000, 7), 31);
_assertPred!"=="(maxDay(-2000, 8), 31);
_assertPred!"=="(maxDay(-2000, 9), 30);
_assertPred!"=="(maxDay(-2000, 10), 31);
_assertPred!"=="(maxDay(-2000, 11), 30);
_assertPred!"=="(maxDay(-2000, 12), 31);
}
}
/+
Returns the day of the week for the given day of the Gregorian Calendar.
Params:
day = The day of the Gregorian Calendar for which to get the day of
the week.
+/
DayOfWeek getDayOfWeek(int day) pure nothrow
{
//January 1st, 1 A.D. was a Monday
if(day >= 0)
return cast(DayOfWeek)(day % 7);
else
{
immutable dow = cast(DayOfWeek)((day % 7) + 7);
if(dow == 7)
return DayOfWeek.sun;
else
return dow;
}
}
unittest
{
version(testStdDateTime)
{
//Test A.D.
_assertPred!"=="(getDayOfWeek(SysTime(Date(1, 1, 1)).dayOfGregorianCal), DayOfWeek.mon);
_assertPred!"=="(getDayOfWeek(SysTime(Date(1, 1, 2)).dayOfGregorianCal), DayOfWeek.tue);
_assertPred!"=="(getDayOfWeek(SysTime(Date(1, 1, 3)).dayOfGregorianCal), DayOfWeek.wed);
_assertPred!"=="(getDayOfWeek(SysTime(Date(1, 1, 4)).dayOfGregorianCal), DayOfWeek.thu);
_assertPred!"=="(getDayOfWeek(SysTime(Date(1, 1, 5)).dayOfGregorianCal), DayOfWeek.fri);
_assertPred!"=="(getDayOfWeek(SysTime(Date(1, 1, 6)).dayOfGregorianCal), DayOfWeek.sat);
_assertPred!"=="(getDayOfWeek(SysTime(Date(1, 1, 7)).dayOfGregorianCal), DayOfWeek.sun);
_assertPred!"=="(getDayOfWeek(SysTime(Date(1, 1, 8)).dayOfGregorianCal), DayOfWeek.mon);
_assertPred!"=="(getDayOfWeek(SysTime(Date(1, 1, 9)).dayOfGregorianCal), DayOfWeek.tue);
_assertPred!"=="(getDayOfWeek(SysTime(Date(2, 1, 1)).dayOfGregorianCal), DayOfWeek.tue);
_assertPred!"=="(getDayOfWeek(SysTime(Date(3, 1, 1)).dayOfGregorianCal), DayOfWeek.wed);
_assertPred!"=="(getDayOfWeek(SysTime(Date(4, 1, 1)).dayOfGregorianCal), DayOfWeek.thu);
_assertPred!"=="(getDayOfWeek(SysTime(Date(5, 1, 1)).dayOfGregorianCal), DayOfWeek.sat);
_assertPred!"=="(getDayOfWeek(SysTime(Date(2000, 1, 1)).dayOfGregorianCal), DayOfWeek.sat);
_assertPred!"=="(getDayOfWeek(SysTime(Date(2010, 8, 22)).dayOfGregorianCal), DayOfWeek.sun);
_assertPred!"=="(getDayOfWeek(SysTime(Date(2010, 8, 23)).dayOfGregorianCal), DayOfWeek.mon);
_assertPred!"=="(getDayOfWeek(SysTime(Date(2010, 8, 24)).dayOfGregorianCal), DayOfWeek.tue);
_assertPred!"=="(getDayOfWeek(SysTime(Date(2010, 8, 25)).dayOfGregorianCal), DayOfWeek.wed);
_assertPred!"=="(getDayOfWeek(SysTime(Date(2010, 8, 26)).dayOfGregorianCal), DayOfWeek.thu);
_assertPred!"=="(getDayOfWeek(SysTime(Date(2010, 8, 27)).dayOfGregorianCal), DayOfWeek.fri);
_assertPred!"=="(getDayOfWeek(SysTime(Date(2010, 8, 28)).dayOfGregorianCal), DayOfWeek.sat);
_assertPred!"=="(getDayOfWeek(SysTime(Date(2010, 8, 29)).dayOfGregorianCal), DayOfWeek.sun);
//Test B.C.
_assertPred!"=="(getDayOfWeek(SysTime(Date(0, 12, 31)).dayOfGregorianCal), DayOfWeek.sun);
_assertPred!"=="(getDayOfWeek(SysTime(Date(0, 12, 30)).dayOfGregorianCal), DayOfWeek.sat);
_assertPred!"=="(getDayOfWeek(SysTime(Date(0, 12, 29)).dayOfGregorianCal), DayOfWeek.fri);
_assertPred!"=="(getDayOfWeek(SysTime(Date(0, 12, 28)).dayOfGregorianCal), DayOfWeek.thu);
_assertPred!"=="(getDayOfWeek(SysTime(Date(0, 12, 27)).dayOfGregorianCal), DayOfWeek.wed);
_assertPred!"=="(getDayOfWeek(SysTime(Date(0, 12, 26)).dayOfGregorianCal), DayOfWeek.tue);
_assertPred!"=="(getDayOfWeek(SysTime(Date(0, 12, 25)).dayOfGregorianCal), DayOfWeek.mon);
_assertPred!"=="(getDayOfWeek(SysTime(Date(0, 12, 24)).dayOfGregorianCal), DayOfWeek.sun);
_assertPred!"=="(getDayOfWeek(SysTime(Date(0, 12, 23)).dayOfGregorianCal), DayOfWeek.sat);
}
}
/+
Returns the string representation of the given month.
Params:
useLongName = Whether the long or short version of the month name should
be used.
plural = Whether the string should be plural or not.
Throws:
$(D DateTimeException) if the given month is not a valid month.
+/
string monthToString(Month month, bool useLongName = true) pure
{
if(useLongName == true)
{
switch(month)
{
case Month.jan:
return "January";
case Month.feb:
return "February";
case Month.mar:
return "March";
case Month.apr:
return "April";
case Month.may:
return "May";
case Month.jun:
return "June";
case Month.jul:
return "July";
case Month.aug:
return "August";
case Month.sep:
return "September";
case Month.oct:
return "October";
case Month.nov:
return "November";
case Month.dec:
return "December";
default:
throw new DateTimeException("Invalid month: " ~ numToString(month));
}
}
else
{
switch(month)
{
case Month.jan:
return "Jan";
case Month.feb:
return "Feb";
case Month.mar:
return "Mar";
case Month.apr:
return "Apr";
case Month.may:
return "May";
case Month.jun:
return "Jun";
case Month.jul:
return "Jul";
case Month.aug:
return "Aug";
case Month.sep:
return "Sep";
case Month.oct:
return "Oct";
case Month.nov:
return "Nov";
case Month.dec:
return "Dec";
default:
throw new DateTimeException("Invalid month: " ~ numToString(month));
}
}
}
unittest
{
version(testStdDateTime)
{
static void testMTSInvalid(Month month, bool useLongName)
{
monthToString(month, useLongName);
}
assertThrown!DateTimeException(testMTSInvalid(cast(Month)0, true));
assertThrown!DateTimeException(testMTSInvalid(cast(Month)0, false));
assertThrown!DateTimeException(testMTSInvalid(cast(Month)13, true));
assertThrown!DateTimeException(testMTSInvalid(cast(Month)13, false));
_assertPred!"=="(monthToString(Month.jan), "January");
_assertPred!"=="(monthToString(Month.feb), "February");
_assertPred!"=="(monthToString(Month.mar), "March");
_assertPred!"=="(monthToString(Month.apr), "April");
_assertPred!"=="(monthToString(Month.may), "May");
_assertPred!"=="(monthToString(Month.jun), "June");
_assertPred!"=="(monthToString(Month.jul), "July");
_assertPred!"=="(monthToString(Month.aug), "August");
_assertPred!"=="(monthToString(Month.sep), "September");
_assertPred!"=="(monthToString(Month.oct), "October");
_assertPred!"=="(monthToString(Month.nov), "November");
_assertPred!"=="(monthToString(Month.dec), "December");
_assertPred!"=="(monthToString(Month.jan, false), "Jan");
_assertPred!"=="(monthToString(Month.feb, false), "Feb");
_assertPred!"=="(monthToString(Month.mar, false), "Mar");
_assertPred!"=="(monthToString(Month.apr, false), "Apr");
_assertPred!"=="(monthToString(Month.may, false), "May");
_assertPred!"=="(monthToString(Month.jun, false), "Jun");
_assertPred!"=="(monthToString(Month.jul, false), "Jul");
_assertPred!"=="(monthToString(Month.aug, false), "Aug");
_assertPred!"=="(monthToString(Month.sep, false), "Sep");
_assertPred!"=="(monthToString(Month.oct, false), "Oct");
_assertPred!"=="(monthToString(Month.nov, false), "Nov");
_assertPred!"=="(monthToString(Month.dec, false), "Dec");
}
}
/+
Returns the Month corresponding to the given string. Casing is ignored.
Params:
monthStr = The string representation of the month to get the Month for.
Throws:
$(D DateTimeException) if the given month is not a valid month string.
+/
Month monthFromString(string monthStr)
{
switch(toLower(monthStr))
{
case "january":
case "jan":
return Month.jan;
case "february":
case "feb":
return Month.feb;
case "march":
case "mar":
return Month.mar;
case "april":
case "apr":
return Month.apr;
case "may":
return Month.may;
case "june":
case "jun":
return Month.jun;
case "july":
case "jul":
return Month.jul;
case "august":
case "aug":
return Month.aug;
case "september":
case "sep":
return Month.sep;
case "october":
case "oct":
return Month.oct;
case "november":
case "nov":
return Month.nov;
case "december":
case "dec":
return Month.dec;
default:
throw new DateTimeException(format("Invalid month %s", monthStr));
}
}
unittest
{
version(testStdDateTime)
{
static void testMFSInvalid(string monthStr)
{
monthFromString(monthStr);
}
assertThrown!DateTimeException(testMFSInvalid("Ja"));
assertThrown!DateTimeException(testMFSInvalid("Janu"));
assertThrown!DateTimeException(testMFSInvalid("Januar"));
assertThrown!DateTimeException(testMFSInvalid("Januarys"));
assertThrown!DateTimeException(testMFSInvalid("JJanuary"));
_assertPred!"=="(monthFromString(monthToString(Month.jan)), Month.jan);
_assertPred!"=="(monthFromString(monthToString(Month.feb)), Month.feb);
_assertPred!"=="(monthFromString(monthToString(Month.mar)), Month.mar);
_assertPred!"=="(monthFromString(monthToString(Month.apr)), Month.apr);
_assertPred!"=="(monthFromString(monthToString(Month.may)), Month.may);
_assertPred!"=="(monthFromString(monthToString(Month.jun)), Month.jun);
_assertPred!"=="(monthFromString(monthToString(Month.jul)), Month.jul);
_assertPred!"=="(monthFromString(monthToString(Month.aug)), Month.aug);
_assertPred!"=="(monthFromString(monthToString(Month.sep)), Month.sep);
_assertPred!"=="(monthFromString(monthToString(Month.oct)), Month.oct);
_assertPred!"=="(monthFromString(monthToString(Month.nov)), Month.nov);
_assertPred!"=="(monthFromString(monthToString(Month.dec)), Month.dec);
_assertPred!"=="(monthFromString(monthToString(Month.jan, false)), Month.jan);
_assertPred!"=="(monthFromString(monthToString(Month.feb, false)), Month.feb);
_assertPred!"=="(monthFromString(monthToString(Month.mar, false)), Month.mar);
_assertPred!"=="(monthFromString(monthToString(Month.apr, false)), Month.apr);
_assertPred!"=="(monthFromString(monthToString(Month.may, false)), Month.may);
_assertPred!"=="(monthFromString(monthToString(Month.jun, false)), Month.jun);
_assertPred!"=="(monthFromString(monthToString(Month.jul, false)), Month.jul);
_assertPred!"=="(monthFromString(monthToString(Month.aug, false)), Month.aug);
_assertPred!"=="(monthFromString(monthToString(Month.sep, false)), Month.sep);
_assertPred!"=="(monthFromString(monthToString(Month.oct, false)), Month.oct);
_assertPred!"=="(monthFromString(monthToString(Month.nov, false)), Month.nov);
_assertPred!"=="(monthFromString(monthToString(Month.dec, false)), Month.dec);
_assertPred!"=="(monthFromString("JANUARY"), Month.jan);
_assertPred!"=="(monthFromString("JAN"), Month.jan);
_assertPred!"=="(monthFromString("january"), Month.jan);
_assertPred!"=="(monthFromString("jan"), Month.jan);
_assertPred!"=="(monthFromString("jaNuary"), Month.jan);
_assertPred!"=="(monthFromString("jaN"), Month.jan);
_assertPred!"=="(monthFromString("jaNuaRy"), Month.jan);
_assertPred!"=="(monthFromString("jAn"), Month.jan);
}
}
/+
The time units which are one step smaller than the given units.
Examples:
--------------------
assert(nextSmallerTimeUnits!"years" == "months");
assert(nextSmallerTimeUnits!"usecs" == "hnsecs");
--------------------
+/
template nextSmallerTimeUnits(string units)
if(validTimeUnits(units) &&
timeStrings.front != units)
{
enum nextSmallerTimeUnits = timeStrings[std.algorithm.countUntil(timeStrings.dup, units) - 1];
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(nextSmallerTimeUnits!"months", "weeks");
_assertPred!"=="(nextSmallerTimeUnits!"weeks", "days");
_assertPred!"=="(nextSmallerTimeUnits!"days", "hours");
_assertPred!"=="(nextSmallerTimeUnits!"hours", "minutes");
_assertPred!"=="(nextSmallerTimeUnits!"minutes", "seconds");
_assertPred!"=="(nextSmallerTimeUnits!"seconds", "msecs");
_assertPred!"=="(nextSmallerTimeUnits!"msecs", "usecs");
static assert(!__traits(compiles, nextSmallerTimeUnits!"hnsecs"));
//Verify Examples.
assert(nextSmallerTimeUnits!"years" == "months");
assert(nextSmallerTimeUnits!"usecs" == "hnsecs");
}
}
/+
The time units which are one step larger than the given units.
Examples:
--------------------
assert(nextLargerTimeUnits!"months" == "years");
assert(nextLargerTimeUnits!"hnsecs" == "usecs");
--------------------
+/
template nextLargerTimeUnits(string units)
if(validTimeUnits(units) &&
timeStrings.back != units)
{
enum nextLargerTimeUnits = timeStrings[std.algorithm.countUntil(timeStrings.dup, units) + 1];
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(nextLargerTimeUnits!"usecs", "msecs");
_assertPred!"=="(nextLargerTimeUnits!"msecs", "seconds");
_assertPred!"=="(nextLargerTimeUnits!"seconds", "minutes");
_assertPred!"=="(nextLargerTimeUnits!"minutes", "hours");
_assertPred!"=="(nextLargerTimeUnits!"hours", "days");
_assertPred!"=="(nextLargerTimeUnits!"days", "weeks");
_assertPred!"=="(nextLargerTimeUnits!"weeks", "months");
static assert(!__traits(compiles, nextLargerTimeUnits!"years"));
//Verify Examples.
assert(nextLargerTimeUnits!"months" == "years");
assert(nextLargerTimeUnits!"hnsecs" == "usecs");
}
}
/+
Returns the given hnsecs as an ISO string of fractional seconds.
+/
static string fracSecToISOString(int hnsecs) nothrow
in
{
assert(hnsecs >= 0);
}
body
{
try
{
string isoString = format(".%07d", hnsecs);
while(isoString.endsWith("0"))
isoString.popBack();
if(isoString.length == 1)
return "";
return isoString;
}
catch(Exception e)
assert(0, "format() threw.");
}
unittest
{
version(testStdDateTime)
{
_assertPred!"=="(fracSecToISOString(0), "");
_assertPred!"=="(fracSecToISOString(1), ".0000001");
_assertPred!"=="(fracSecToISOString(10), ".000001");
_assertPred!"=="(fracSecToISOString(100), ".00001");
_assertPred!"=="(fracSecToISOString(1000), ".0001");
_assertPred!"=="(fracSecToISOString(10_000), ".001");
_assertPred!"=="(fracSecToISOString(100_000), ".01");
_assertPred!"=="(fracSecToISOString(1_000_000), ".1");
_assertPred!"=="(fracSecToISOString(1_000_001), ".1000001");
_assertPred!"=="(fracSecToISOString(1_001_001), ".1001001");
_assertPred!"=="(fracSecToISOString(1_071_601), ".1071601");
_assertPred!"=="(fracSecToISOString(1_271_641), ".1271641");
_assertPred!"=="(fracSecToISOString(9_999_999), ".9999999");
_assertPred!"=="(fracSecToISOString(9_999_990), ".999999");
_assertPred!"=="(fracSecToISOString(9_999_900), ".99999");
_assertPred!"=="(fracSecToISOString(9_999_000), ".9999");
_assertPred!"=="(fracSecToISOString(9_990_000), ".999");
_assertPred!"=="(fracSecToISOString(9_900_000), ".99");
_assertPred!"=="(fracSecToISOString(9_000_000), ".9");
_assertPred!"=="(fracSecToISOString(999), ".0000999");
_assertPred!"=="(fracSecToISOString(9990), ".000999");
_assertPred!"=="(fracSecToISOString(99_900), ".00999");
_assertPred!"=="(fracSecToISOString(999_000), ".0999");
}
}
/+
Returns a FracSec corresponding to to the given ISO string of
fractional seconds.
+/
static FracSec fracSecFromISOString(S)(in S isoString)
if(isSomeString!S)
{
if(isoString.empty)
return FracSec.from!"hnsecs"(0);
auto dstr = to!dstring(isoString);
enforce(dstr.startsWith("."), new DateTimeException("Invalid ISO String"));
dstr.popFront();
enforce(!dstr.empty && dstr.length <= 7, new DateTimeException("Invalid ISO String"));
enforce(!canFind!(not!isDigit)(dstr), new DateTimeException("Invalid ISO String"));
dchar[7] fullISOString;
foreach(i, ref dchar c; fullISOString)
{
if(i < dstr.length)
c = dstr[i];
else
c = '0';
}
return FracSec.from!"hnsecs"(to!int(fullISOString[]));
}
unittest
{
version(testStdDateTime)
{
static void testFSInvalid(string isoString)
{
fracSecFromISOString(isoString);
}
assertThrown!DateTimeException(testFSInvalid("."));
assertThrown!DateTimeException(testFSInvalid("0."));
assertThrown!DateTimeException(testFSInvalid("0"));
assertThrown!DateTimeException(testFSInvalid("0000000"));
assertThrown!DateTimeException(testFSInvalid(".00000000"));
assertThrown!DateTimeException(testFSInvalid(".00000001"));
assertThrown!DateTimeException(testFSInvalid("T"));
assertThrown!DateTimeException(testFSInvalid("T."));
assertThrown!DateTimeException(testFSInvalid(".T"));
_assertPred!"=="(fracSecFromISOString(""), FracSec.from!"hnsecs"(0));
_assertPred!"=="(fracSecFromISOString(".0000001"), FracSec.from!"hnsecs"(1));
_assertPred!"=="(fracSecFromISOString(".000001"), FracSec.from!"hnsecs"(10));
_assertPred!"=="(fracSecFromISOString(".00001"), FracSec.from!"hnsecs"(100));
_assertPred!"=="(fracSecFromISOString(".0001"), FracSec.from!"hnsecs"(1000));
_assertPred!"=="(fracSecFromISOString(".001"), FracSec.from!"hnsecs"(10_000));
_assertPred!"=="(fracSecFromISOString(".01"), FracSec.from!"hnsecs"(100_000));
_assertPred!"=="(fracSecFromISOString(".1"), FracSec.from!"hnsecs"(1_000_000));
_assertPred!"=="(fracSecFromISOString(".1000001"), FracSec.from!"hnsecs"(1_000_001));
_assertPred!"=="(fracSecFromISOString(".1001001"), FracSec.from!"hnsecs"(1_001_001));
_assertPred!"=="(fracSecFromISOString(".1071601"), FracSec.from!"hnsecs"(1_071_601));
_assertPred!"=="(fracSecFromISOString(".1271641"), FracSec.from!"hnsecs"(1_271_641));
_assertPred!"=="(fracSecFromISOString(".9999999"), FracSec.from!"hnsecs"(9_999_999));
_assertPred!"=="(fracSecFromISOString(".9999990"), FracSec.from!"hnsecs"(9_999_990));
_assertPred!"=="(fracSecFromISOString(".999999"), FracSec.from!"hnsecs"(9_999_990));
_assertPred!"=="(fracSecFromISOString(".9999900"), FracSec.from!"hnsecs"(9_999_900));
_assertPred!"=="(fracSecFromISOString(".99999"), FracSec.from!"hnsecs"(9_999_900));
_assertPred!"=="(fracSecFromISOString(".9999000"), FracSec.from!"hnsecs"(9_999_000));
_assertPred!"=="(fracSecFromISOString(".9999"), FracSec.from!"hnsecs"(9_999_000));
_assertPred!"=="(fracSecFromISOString(".9990000"), FracSec.from!"hnsecs"(9_990_000));
_assertPred!"=="(fracSecFromISOString(".999"), FracSec.from!"hnsecs"(9_990_000));
_assertPred!"=="(fracSecFromISOString(".9900000"), FracSec.from!"hnsecs"(9_900_000));
_assertPred!"=="(fracSecFromISOString(".9900"), FracSec.from!"hnsecs"(9_900_000));
_assertPred!"=="(fracSecFromISOString(".99"), FracSec.from!"hnsecs"(9_900_000));
_assertPred!"=="(fracSecFromISOString(".9000000"), FracSec.from!"hnsecs"(9_000_000));
_assertPred!"=="(fracSecFromISOString(".9"), FracSec.from!"hnsecs"(9_000_000));
_assertPred!"=="(fracSecFromISOString(".0000999"), FracSec.from!"hnsecs"(999));
_assertPred!"=="(fracSecFromISOString(".0009990"), FracSec.from!"hnsecs"(9990));
_assertPred!"=="(fracSecFromISOString(".000999"), FracSec.from!"hnsecs"(9990));
_assertPred!"=="(fracSecFromISOString(".0099900"), FracSec.from!"hnsecs"(99_900));
_assertPred!"=="(fracSecFromISOString(".00999"), FracSec.from!"hnsecs"(99_900));
_assertPred!"=="(fracSecFromISOString(".0999000"), FracSec.from!"hnsecs"(999_000));
_assertPred!"=="(fracSecFromISOString(".0999"), FracSec.from!"hnsecs"(999_000));
}
}
/+
Whether the given type defines the static property min which returns the
minimum value for the type.
+/
template hasMin(T)
{
enum hasMin = __traits(hasMember, T, "min") &&
__traits(isStaticFunction, T.min) &&
is(ReturnType!(T.min) == Unqual!T) &&
(functionAttributes!(T.min) & FunctionAttribute.PROPERTY) &&
(functionAttributes!(T.min) & FunctionAttribute.NOTHROW);
//(functionAttributes!(T.min) & FunctionAttribute.PURE); //Ideally this would be the case, but SysTime's min() can't currently be pure.
}
unittest
{
version(testStdDateTime)
{
static assert(hasMin!(Date));
static assert(hasMin!(TimeOfDay));
static assert(hasMin!(DateTime));
static assert(hasMin!(SysTime));
static assert(hasMin!(const Date));
static assert(hasMin!(const TimeOfDay));
static assert(hasMin!(const DateTime));
static assert(hasMin!(const SysTime));
static assert(hasMin!(immutable Date));
static assert(hasMin!(immutable TimeOfDay));
static assert(hasMin!(immutable SysTime));
}
}
/+
Whether the given type defines the static property max which returns the
maximum value for the type.
+/
template hasMax(T)
{
enum hasMax = __traits(hasMember, T, "max") &&
__traits(isStaticFunction, T.max) &&
is(ReturnType!(T.max) == Unqual!T) &&
(functionAttributes!(T.max) & FunctionAttribute.PROPERTY) &&
(functionAttributes!(T.max) & FunctionAttribute.NOTHROW);
//(functionAttributes!(T.max) & FunctionAttribute.PURE); //Ideally this would be the case, but SysTime's max() can't currently be pure.
}
unittest
{
version(testStdDateTime)
{
static assert(hasMax!(Date));
static assert(hasMax!(TimeOfDay));
static assert(hasMax!(DateTime));
static assert(hasMax!(SysTime));
static assert(hasMax!(const Date));
static assert(hasMax!(const TimeOfDay));
static assert(hasMax!(const DateTime));
static assert(hasMax!(const SysTime));
static assert(hasMax!(immutable Date));
static assert(hasMax!(immutable TimeOfDay));
static assert(hasMax!(immutable DateTime));
static assert(hasMax!(immutable SysTime));
}
}
/+
Whether the given type defines the overloaded opBinary operators that a time
point is supposed to define which work with time durations. Namely:
$(BOOKTABLE,
$(TR $(TD TimePoint opBinary"+"(duration)))
$(TR $(TD TimePoint opBinary"-"(duration)))
)
+/
template hasOverloadedOpBinaryWithDuration(T)
{
enum hasOverloadedOpBinaryWithDuration = __traits(compiles, T.init + dur!"days"(5)) &&
is(typeof(T.init + dur!"days"(5)) == Unqual!T) &&
__traits(compiles, T.init - dur!"days"(5)) &&
is(typeof(T.init - dur!"days"(5)) == Unqual!T) &&
__traits(compiles, T.init + TickDuration.from!"hnsecs"(5)) &&
is(typeof(T.init + TickDuration.from!"hnsecs"(5)) == Unqual!T) &&
__traits(compiles, T.init - TickDuration.from!"hnsecs"(5)) &&
is(typeof(T.init - TickDuration.from!"hnsecs"(5)) == Unqual!T);
}
unittest
{
version(testStdDateTime)
{
static assert(hasOverloadedOpBinaryWithDuration!(Date));
static assert(hasOverloadedOpBinaryWithDuration!(TimeOfDay));
static assert(hasOverloadedOpBinaryWithDuration!(DateTime));
static assert(hasOverloadedOpBinaryWithDuration!(SysTime));
static assert(hasOverloadedOpBinaryWithDuration!(const Date));
static assert(hasOverloadedOpBinaryWithDuration!(const TimeOfDay));
static assert(hasOverloadedOpBinaryWithDuration!(const DateTime));
static assert(hasOverloadedOpBinaryWithDuration!(const SysTime));
static assert(hasOverloadedOpBinaryWithDuration!(immutable Date));
static assert(hasOverloadedOpBinaryWithDuration!(immutable TimeOfDay));
static assert(hasOverloadedOpBinaryWithDuration!(immutable DateTime));
static assert(hasOverloadedOpBinaryWithDuration!(immutable SysTime));
}
}
/+
Whether the given type defines the overloaded opOpAssign operators that a time point is supposed
to define. Namely:
$(BOOKTABLE,
$(TR $(TD TimePoint opOpAssign"+"(duration)))
$(TR $(TD TimePoint opOpAssign"-"(duration)))
)
+/
template hasOverloadedOpAssignWithDuration(T)
{
enum hasOverloadedOpAssignWithDuration = __traits(compiles, T.init += dur!"days"(5)) &&
is(typeof(T.init += dur!"days"(5)) == Unqual!T) &&
__traits(compiles, T.init -= dur!"days"(5)) &&
is(typeof(T.init -= dur!"days"(5)) == Unqual!T) &&
__traits(compiles, T.init += TickDuration.from!"hnsecs"(5)) &&
is(typeof(T.init += TickDuration.from!"hnsecs"(5)) == Unqual!T) &&
__traits(compiles, T.init -= TickDuration.from!"hnsecs"(5)) &&
is(typeof(T.init -= TickDuration.from!"hnsecs"(5)) == Unqual!T);
}
unittest
{
version(testStdDateTime)
{
static assert(hasOverloadedOpAssignWithDuration!(Date));
static assert(hasOverloadedOpAssignWithDuration!(TimeOfDay));
static assert(hasOverloadedOpAssignWithDuration!(DateTime));
static assert(hasOverloadedOpAssignWithDuration!(SysTime));
static assert(hasOverloadedOpAssignWithDuration!(const Date));
static assert(hasOverloadedOpAssignWithDuration!(const TimeOfDay));
static assert(hasOverloadedOpAssignWithDuration!(const DateTime));
static assert(hasOverloadedOpAssignWithDuration!(const SysTime));
static assert(hasOverloadedOpAssignWithDuration!(immutable Date));
static assert(hasOverloadedOpAssignWithDuration!(immutable TimeOfDay));
static assert(hasOverloadedOpAssignWithDuration!(immutable DateTime));
static assert(hasOverloadedOpAssignWithDuration!(immutable SysTime));
}
}
/+
Whether the given type defines the overloaded opBinary operator that a time point is supposed
to define which works with itself. Namely:
$(BOOKTABLE,
$(TR $(TD duration opBinary"-"(Date)))
)
+/
template hasOverloadedOpBinaryWithSelf(T)
{
enum hasOverloadedOpBinaryWithSelf = __traits(compiles, T.init - T.init) &&
is(Unqual!(typeof(T.init - T.init)) == Duration);
}
unittest
{
version(testStdDateTime)
{
static assert(hasOverloadedOpBinaryWithSelf!(Date));
static assert(hasOverloadedOpBinaryWithSelf!(TimeOfDay));
static assert(hasOverloadedOpBinaryWithSelf!(DateTime));
static assert(hasOverloadedOpBinaryWithSelf!(SysTime));
static assert(hasOverloadedOpBinaryWithSelf!(const Date));
static assert(hasOverloadedOpBinaryWithSelf!(const TimeOfDay));
static assert(hasOverloadedOpBinaryWithSelf!(const DateTime));
static assert(hasOverloadedOpBinaryWithSelf!(const SysTime));
static assert(hasOverloadedOpBinaryWithSelf!(immutable Date));
static assert(hasOverloadedOpBinaryWithSelf!(immutable TimeOfDay));
static assert(hasOverloadedOpBinaryWithSelf!(immutable DateTime));
static assert(hasOverloadedOpBinaryWithSelf!(immutable SysTime));
}
}
/+
Unfortunately, to!string() is not pure, so here's a way to convert
a number to a string which is. Once to!string() is properly pure
(like it hopefully will be at some point), this function should
be removed in favor of using to!string().
+/
string numToString(long value) pure nothrow
{
try
{
immutable negative = value < 0;
char[25] str;
size_t i = str.length;
if(negative)
value = -value;
while(1)
{
char digit = cast(char)('0' + value % 10);
value /= 10;
str[--i] = digit;
assert(i > 0);
if(value == 0)
break;
}
if(negative)
return "-" ~ str[i .. $].idup;
else
return str[i .. $].idup;
}
catch(Exception e)
assert(0, "Something threw when nothing can throw.");
}
/+
A temporary replacement for Rebindable!() until bug http://d.puremagic.com/issues/show_bug.cgi?id=4977
is fixed.
+/
template DTRebindable(T) if (is(T == class) || is(T == interface) || isArray!(T))
{
static if(!is(T X == const(U), U) && !is(T X == immutable(U), U))
{
alias T DTRebindable;
}
else static if(isArray!(T))
{
alias const(ElementType!(T))[] DTRebindable;
}
else
{
struct DTRebindable
{
private union
{
T original;
U stripped;
}
void opAssign(T another) pure nothrow
{
stripped = cast(U) another;
}
void opAssign(DTRebindable another) pure nothrow
{
stripped = another.stripped;
}
static if(is(T == const U))
{
// safely assign immutable to const
void opAssign(DTRebindable!(immutable U) another) pure nothrow
{
stripped = another.stripped;
}
}
this(T initializer) pure nothrow
{
opAssign(initializer);
}
@property ref T get() pure nothrow
{
return original;
}
@property ref T get() const pure nothrow
{
return original;
}
alias get this;
T opDot() pure nothrow
{
return original;
}
T opDot() const pure nothrow
{
return original;
}
}
}
}
version(unittest)
{
//Variables to help in testing.
Duration currLocalDiffFromUTC;
immutable (TimeZone)[] testTZs;
//All of these helper arrays are sorted in ascending order.
auto testYearsBC = [-1999, -1200, -600, -4, -1, 0];
auto testYearsAD = [1, 4, 1000, 1999, 2000, 2012];
//I'd use a Tuple, but I get forward reference errors if I try.
struct MonthDay
{
Month month;
short day;
this(int m, short d)
{
month = cast(Month)m;
day = d;
}
}
MonthDay[] testMonthDays = [MonthDay(1, 1),
MonthDay(1, 2),
MonthDay(3, 17),
MonthDay(7, 4),
MonthDay(10, 27),
MonthDay(12, 30),
MonthDay(12, 31)];
auto testDays = [1, 2, 9, 10, 16, 20, 25, 28, 29, 30, 31];
auto testTODs = [TimeOfDay(0, 0, 0),
TimeOfDay(0, 0, 1),
TimeOfDay(0, 1, 0),
TimeOfDay(1, 0, 0),
TimeOfDay(13, 13, 13),
TimeOfDay(23, 59, 59)];
auto testHours = [0, 1, 12, 22, 23];
auto testMinSecs = [0, 1, 30, 58, 59];
//Throwing exceptions is incredibly expensive, so we want to use a smaller
//set of values for tests using assertThrown.
auto testTODsThrown = [TimeOfDay(0, 0, 0),
TimeOfDay(13, 13, 13),
TimeOfDay(23, 59, 59)];
Date[] testDatesBC;
Date[] testDatesAD;
DateTime[] testDateTimesBC;
DateTime[] testDateTimesAD;
FracSec[] testFracSecs;
SysTime[] testSysTimesBC;
SysTime[] testSysTimesAD;
//I'd use a Tuple, but I get forward reference errors if I try.
struct GregDay { int day; Date date; }
auto testGregDaysBC = [GregDay(-1_373_427, Date(-3760, 9, 7)), //Start of the Hebrew Calendar
GregDay(-735_233, Date(-2012, 1, 1)),
GregDay(-735_202, Date(-2012, 2, 1)),
GregDay(-735_175, Date(-2012, 2, 28)),
GregDay(-735_174, Date(-2012, 2, 29)),
GregDay(-735_173, Date(-2012, 3, 1)),
GregDay(-734_502, Date(-2010, 1, 1)),
GregDay(-734_472, Date(-2010, 1, 31)),
GregDay(-734_471, Date(-2010, 2, 1)),
GregDay(-734_444, Date(-2010, 2, 28)),
GregDay(-734_443, Date(-2010, 3, 1)),
GregDay(-734_413, Date(-2010, 3, 31)),
GregDay(-734_412, Date(-2010, 4, 1)),
GregDay(-734_383, Date(-2010, 4, 30)),
GregDay(-734_382, Date(-2010, 5, 1)),
GregDay(-734_352, Date(-2010, 5, 31)),
GregDay(-734_351, Date(-2010, 6, 1)),
GregDay(-734_322, Date(-2010, 6, 30)),
GregDay(-734_321, Date(-2010, 7, 1)),
GregDay(-734_291, Date(-2010, 7, 31)),
GregDay(-734_290, Date(-2010, 8, 1)),
GregDay(-734_260, Date(-2010, 8, 31)),
GregDay(-734_259, Date(-2010, 9, 1)),
GregDay(-734_230, Date(-2010, 9, 30)),
GregDay(-734_229, Date(-2010, 10, 1)),
GregDay(-734_199, Date(-2010, 10, 31)),
GregDay(-734_198, Date(-2010, 11, 1)),
GregDay(-734_169, Date(-2010, 11, 30)),
GregDay(-734_168, Date(-2010, 12, 1)),
GregDay(-734_139, Date(-2010, 12, 30)),
GregDay(-734_138, Date(-2010, 12, 31)),
GregDay(-731_215, Date(-2001, 1, 1)),
GregDay(-730_850, Date(-2000, 1, 1)),
GregDay(-730_849, Date(-2000, 1, 2)),
GregDay(-730_486, Date(-2000, 12, 30)),
GregDay(-730_485, Date(-2000, 12, 31)),
GregDay(-730_484, Date(-1999, 1, 1)),
GregDay(-694_690, Date(-1901, 1, 1)),
GregDay(-694_325, Date(-1900, 1, 1)),
GregDay(-585_118, Date(-1601, 1, 1)),
GregDay(-584_753, Date(-1600, 1, 1)),
GregDay(-584_388, Date(-1600, 12, 31)),
GregDay(-584_387, Date(-1599, 1, 1)),
GregDay(-365_972, Date(-1001, 1, 1)),
GregDay(-365_607, Date(-1000, 1, 1)),
GregDay(-183_351, Date(-501, 1, 1)),
GregDay(-182_986, Date(-500, 1, 1)),
GregDay(-182_621, Date(-499, 1, 1)),
GregDay(-146_827, Date(-401, 1, 1)),
GregDay(-146_462, Date(-400, 1, 1)),
GregDay(-146_097, Date(-400, 12, 31)),
GregDay(-110_302, Date(-301, 1, 1)),
GregDay(-109_937, Date(-300, 1, 1)),
GregDay(-73_778, Date(-201, 1, 1)),
GregDay(-73_413, Date(-200, 1, 1)),
GregDay(-38_715, Date(-105, 1, 1)),
GregDay(-37_254, Date(-101, 1, 1)),
GregDay(-36_889, Date(-100, 1, 1)),
GregDay(-36_524, Date(-99, 1, 1)),
GregDay(-36_160, Date(-99, 12, 31)),
GregDay(-35_794, Date(-97, 1, 1)),
GregDay(-18_627, Date(-50, 1, 1)),
GregDay(-18_262, Date(-49, 1, 1)),
GregDay(-3652, Date(-9, 1, 1)),
GregDay(-2191, Date(-5, 1, 1)),
GregDay(-1827, Date(-5, 12, 31)),
GregDay(-1826, Date(-4, 1, 1)),
GregDay(-1825, Date(-4, 1, 2)),
GregDay(-1462, Date(-4, 12, 30)),
GregDay(-1461, Date(-4, 12, 31)),
GregDay(-1460, Date(-3, 1, 1)),
GregDay(-1096, Date(-3, 12, 31)),
GregDay(-1095, Date(-2, 1, 1)),
GregDay(-731, Date(-2, 12, 31)),
GregDay(-730, Date(-1, 1, 1)),
GregDay(-367, Date(-1, 12, 30)),
GregDay(-366, Date(-1, 12, 31)),
GregDay(-365, Date(0, 1, 1)),
GregDay(-31, Date(0, 11, 30)),
GregDay(-30, Date(0, 12, 1)),
GregDay(-1, Date(0, 12, 30)),
GregDay(0, Date(0, 12, 31))];
auto testGregDaysAD = [GregDay(1, Date(1, 1, 1)),
GregDay(2, Date(1, 1, 2)),
GregDay(32, Date(1, 2, 1)),
GregDay(365, Date(1, 12, 31)),
GregDay(366, Date(2, 1, 1)),
GregDay(731, Date(3, 1, 1)),
GregDay(1096, Date(4, 1, 1)),
GregDay(1097, Date(4, 1, 2)),
GregDay(1460, Date(4, 12, 30)),
GregDay(1461, Date(4, 12, 31)),
GregDay(1462, Date(5, 1, 1)),
GregDay(17_898, Date(50, 1, 1)),
GregDay(35_065, Date(97, 1, 1)),
GregDay(36_160, Date(100, 1, 1)),
GregDay(36_525, Date(101, 1, 1)),
GregDay(37_986, Date(105, 1, 1)),
GregDay(72_684, Date(200, 1, 1)),
GregDay(73_049, Date(201, 1, 1)),
GregDay(109_208, Date(300, 1, 1)),
GregDay(109_573, Date(301, 1, 1)),
GregDay(145_732, Date(400, 1, 1)),
GregDay(146_098, Date(401, 1, 1)),
GregDay(182_257, Date(500, 1, 1)),
GregDay(182_622, Date(501, 1, 1)),
GregDay(364_878, Date(1000, 1, 1)),
GregDay(365_243, Date(1001, 1, 1)),
GregDay(584_023, Date(1600, 1, 1)),
GregDay(584_389, Date(1601, 1, 1)),
GregDay(693_596, Date(1900, 1, 1)),
GregDay(693_961, Date(1901, 1, 1)),
GregDay(729_755, Date(1999, 1, 1)),
GregDay(730_120, Date(2000, 1, 1)),
GregDay(730_121, Date(2000, 1, 2)),
GregDay(730_484, Date(2000, 12, 30)),
GregDay(730_485, Date(2000, 12, 31)),
GregDay(730_486, Date(2001, 1, 1)),
GregDay(733_773, Date(2010, 1, 1)),
GregDay(733_774, Date(2010, 1, 2)),
GregDay(733_803, Date(2010, 1, 31)),
GregDay(733_804, Date(2010, 2, 1)),
GregDay(733_831, Date(2010, 2, 28)),
GregDay(733_832, Date(2010, 3, 1)),
GregDay(733_862, Date(2010, 3, 31)),
GregDay(733_863, Date(2010, 4, 1)),
GregDay(733_892, Date(2010, 4, 30)),
GregDay(733_893, Date(2010, 5, 1)),
GregDay(733_923, Date(2010, 5, 31)),
GregDay(733_924, Date(2010, 6, 1)),
GregDay(733_953, Date(2010, 6, 30)),
GregDay(733_954, Date(2010, 7, 1)),
GregDay(733_984, Date(2010, 7, 31)),
GregDay(733_985, Date(2010, 8, 1)),
GregDay(734_015, Date(2010, 8, 31)),
GregDay(734_016, Date(2010, 9, 1)),
GregDay(734_045, Date(2010, 9, 30)),
GregDay(734_046, Date(2010, 10, 1)),
GregDay(734_076, Date(2010, 10, 31)),
GregDay(734_077, Date(2010, 11, 1)),
GregDay(734_106, Date(2010, 11, 30)),
GregDay(734_107, Date(2010, 12, 1)),
GregDay(734_136, Date(2010, 12, 30)),
GregDay(734_137, Date(2010, 12, 31)),
GregDay(734_503, Date(2012, 1, 1)),
GregDay(734_534, Date(2012, 2, 1)),
GregDay(734_561, Date(2012, 2, 28)),
GregDay(734_562, Date(2012, 2, 29)),
GregDay(734_563, Date(2012, 3, 1)),
GregDay(734_858, Date(2012, 12, 21))];
//I'd use a Tuple, but I get forward reference errors if I try.
struct DayOfYear { int day; MonthDay md; }
auto testDaysOfYear = [DayOfYear(1, MonthDay(1, 1)),
DayOfYear(2, MonthDay(1, 2)),
DayOfYear(3, MonthDay(1, 3)),
DayOfYear(31, MonthDay(1, 31)),
DayOfYear(32, MonthDay(2, 1)),
DayOfYear(59, MonthDay(2, 28)),
DayOfYear(60, MonthDay(3, 1)),
DayOfYear(90, MonthDay(3, 31)),
DayOfYear(91, MonthDay(4, 1)),
DayOfYear(120, MonthDay(4, 30)),
DayOfYear(121, MonthDay(5, 1)),
DayOfYear(151, MonthDay(5, 31)),
DayOfYear(152, MonthDay(6, 1)),
DayOfYear(181, MonthDay(6, 30)),
DayOfYear(182, MonthDay(7, 1)),
DayOfYear(212, MonthDay(7, 31)),
DayOfYear(213, MonthDay(8, 1)),
DayOfYear(243, MonthDay(8, 31)),
DayOfYear(244, MonthDay(9, 1)),
DayOfYear(273, MonthDay(9, 30)),
DayOfYear(274, MonthDay(10, 1)),
DayOfYear(304, MonthDay(10, 31)),
DayOfYear(305, MonthDay(11, 1)),
DayOfYear(334, MonthDay(11, 30)),
DayOfYear(335, MonthDay(12, 1)),
DayOfYear(363, MonthDay(12, 29)),
DayOfYear(364, MonthDay(12, 30)),
DayOfYear(365, MonthDay(12, 31))];
auto testDaysOfLeapYear = [DayOfYear(1, MonthDay(1, 1)),
DayOfYear(2, MonthDay(1, 2)),
DayOfYear(3, MonthDay(1, 3)),
DayOfYear(31, MonthDay(1, 31)),
DayOfYear(32, MonthDay(2, 1)),
DayOfYear(59, MonthDay(2, 28)),
DayOfYear(60, MonthDay(2, 29)),
DayOfYear(61, MonthDay(3, 1)),
DayOfYear(91, MonthDay(3, 31)),
DayOfYear(92, MonthDay(4, 1)),
DayOfYear(121, MonthDay(4, 30)),
DayOfYear(122, MonthDay(5, 1)),
DayOfYear(152, MonthDay(5, 31)),
DayOfYear(153, MonthDay(6, 1)),
DayOfYear(182, MonthDay(6, 30)),
DayOfYear(183, MonthDay(7, 1)),
DayOfYear(213, MonthDay(7, 31)),
DayOfYear(214, MonthDay(8, 1)),
DayOfYear(244, MonthDay(8, 31)),
DayOfYear(245, MonthDay(9, 1)),
DayOfYear(274, MonthDay(9, 30)),
DayOfYear(275, MonthDay(10, 1)),
DayOfYear(305, MonthDay(10, 31)),
DayOfYear(306, MonthDay(11, 1)),
DayOfYear(335, MonthDay(11, 30)),
DayOfYear(336, MonthDay(12, 1)),
DayOfYear(364, MonthDay(12, 29)),
DayOfYear(365, MonthDay(12, 30)),
DayOfYear(366, MonthDay(12, 31))];
static this()
{
currLocalDiffFromUTC = Clock.currTime(UTC()) -
Clock.currTime(LocalTime());
immutable simpleTZ = new SimpleTimeZone(cast(int)
(currLocalDiffFromUTC + dur!"hours"(2)).total!"minutes"());
immutable lt = LocalTime().utcToTZ(0);
immutable st = simpleTZ.utcToTZ(0);
auto diffs = [0, lt, st];
auto diffAA = [0 : cast(immutable TimeZone)UTC(),
lt : cast(immutable TimeZone)LocalTime(),
st : cast(immutable TimeZone)simpleTZ];
sort(diffs);
testTZs = [diffAA[diffs[0]], diffAA[diffs[1]], diffAA[diffs[2]]];
testFracSecs = [FracSec.from!"hnsecs"(0),
FracSec.from!"hnsecs"(1),
FracSec.from!"hnsecs"(5007),
FracSec.from!"hnsecs"(9999999)];
foreach(year; testYearsBC)
{
foreach(md; testMonthDays)
testDatesBC ~= Date(year, md.month, md.day);
}
foreach(year; testYearsAD)
{
foreach(md; testMonthDays)
testDatesAD ~= Date(year, md.month, md.day);
}
foreach(dt; testDatesBC)
{
foreach(tod; testTODs)
testDateTimesBC ~= DateTime(dt, tod);
}
foreach(dt; testDatesAD)
{
foreach(tod; testTODs)
testDateTimesAD ~= DateTime(dt, tod);
}
foreach(dt; testDateTimesBC)
{
foreach(tz; testTZs)
{
foreach(fs; testFracSecs)
testSysTimesBC ~= SysTime(dt, fs, tz);
}
}
foreach(dt; testDateTimesAD)
{
foreach(tz; testTZs)
{
foreach(fs; testFracSecs)
testSysTimesAD ~= SysTime(dt, fs, tz);
}
}
}
}
//==============================================================================
// Unit testing functions.
//==============================================================================
void _assertPred(string op, L, R)
(L lhs, R rhs, lazy string msg = null, string file = __FILE__, size_t line = __LINE__)
if((op == "<" ||
op == "<=" ||
op == "==" ||
op == "!=" ||
op == ">=" ||
op == ">") &&
__traits(compiles, mixin("lhs " ~ op ~ " rhs")) &&
_isPrintable!L &&
_isPrintable!R)
{
immutable result = mixin("lhs " ~ op ~ " rhs");
if(!result)
{
if(msg.empty)
throw new AssertError(format(`_assertPred!"%s" failed: [%s] is not %s [%s].`, op, lhs, op, rhs), file, line);
else
throw new AssertError(format(`_assertPred!"%s" failed: [%s] is not %s [%s]: %s`, op, lhs, op, rhs, msg), file, line);
}
}
unittest
{
version(testStdDateTime)
{
struct IntWrapper
{
int value;
this(int value)
{
this.value = value;
}
string toString()
{
return to!string(value);
}
}
//Test ==.
assertNotThrown!AssertError(_assertPred!"=="(6, 6));
assertNotThrown!AssertError(_assertPred!"=="(6, 6.0));
assertNotThrown!AssertError(_assertPred!"=="(IntWrapper(6), IntWrapper(6)));
assertThrown!AssertError(_assertPred!"=="(6, 7));
assertThrown!AssertError(_assertPred!"=="(6, 6.1));
assertThrown!AssertError(_assertPred!"=="(IntWrapper(6), IntWrapper(7)));
assertThrown!AssertError(_assertPred!"=="(IntWrapper(7), IntWrapper(6)));
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"=="(6, 7)),
`_assertPred!"==" failed: [6] is not == [7].`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"=="(6, 7, "It failed!")),
`_assertPred!"==" failed: [6] is not == [7]: It failed!`);
//Test !=.
assertNotThrown!AssertError(_assertPred!"!="(6, 7));
assertNotThrown!AssertError(_assertPred!"!="(6, 6.1));
assertNotThrown!AssertError(_assertPred!"!="(IntWrapper(6), IntWrapper(7)));
assertNotThrown!AssertError(_assertPred!"!="(IntWrapper(7), IntWrapper(6)));
assertThrown!AssertError(_assertPred!"!="(6, 6));
assertThrown!AssertError(_assertPred!"!="(6, 6.0));
assertThrown!AssertError(_assertPred!"!="(IntWrapper(6), IntWrapper(6)));
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"!="(6, 6)),
`_assertPred!"!=" failed: [6] is not != [6].`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"!="(6, 6, "It failed!")),
`_assertPred!"!=" failed: [6] is not != [6]: It failed!`);
//Test <, <=, >=, >.
assertNotThrown!AssertError(_assertPred!"<"(5, 7));
assertNotThrown!AssertError(_assertPred!"<="(5, 7));
assertNotThrown!AssertError(_assertPred!"<="(5, 5));
assertNotThrown!AssertError(_assertPred!">="(7, 7));
assertNotThrown!AssertError(_assertPred!">="(7, 5));
assertNotThrown!AssertError(_assertPred!">"(7, 5));
assertThrown!AssertError(_assertPred!"<"(7, 5));
assertThrown!AssertError(_assertPred!"<="(7, 5));
assertThrown!AssertError(_assertPred!">="(5, 7));
assertThrown!AssertError(_assertPred!">"(5, 7));
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"<"(7, 5)),
`_assertPred!"<" failed: [7] is not < [5].`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"<"(7, 5, "It failed!")),
`_assertPred!"<" failed: [7] is not < [5]: It failed!`);
//Verify Examples.
//Equivalent to assert(5 / 2 + 4 < 27);
_assertPred!"<"(5 / 2 + 4, 27);
//Equivalent to assert(4 <= 5);
_assertPred!"<="(4, 5);
//Equivalent to assert(1 * 2.1 == 2.1);
_assertPred!"=="(1 * 2.1, 2.1);
//Equivalent to assert("hello " ~ "world" != "goodbye world");
_assertPred!"!="("hello " ~ "world", "goodbye world");
//Equivalent to assert(14.2 >= 14);
_assertPred!">="(14.2, 14);
//Equivalent to assert(15 > 2 + 1);
_assertPred!">"(15, 2 + 1);
assert(collectExceptionMsg!AssertError(_assertPred!"=="("hello", "goodbye")) ==
`_assertPred!"==" failed: [hello] is not == [goodbye].`);
assert(collectExceptionMsg!AssertError(_assertPred!"<"(5, 2, "My test failed!")) ==
`_assertPred!"<" failed: [5] is not < [2]: My test failed!`);
}
}
void _assertPred(string func, string expected, L, R)
(L lhs, R rhs, lazy string msg = null, string file = __FILE__, size_t line = __LINE__)
if(func == "opCmp" &&
(expected == "<" ||
expected == "==" ||
expected == ">") &&
__traits(compiles, lhs.opCmp(rhs)) &&
_isPrintable!L &&
_isPrintable!R)
{
immutable result = lhs.opCmp(rhs);
static if(expected == "<")
{
if(result < 0)
return;
if(result == 0)
{
if(msg.empty)
throw new AssertError(format(`_assertPred!("opCmp", "<") failed: [%s] == [%s].`, lhs, rhs), file, line);
else
throw new AssertError(format(`_assertPred!("opCmp", "<") failed: [%s] == [%s]: %s`, lhs, rhs, msg), file, line);
}
else
{
if(msg.empty)
throw new AssertError(format(`_assertPred!("opCmp", "<") failed: [%s] > [%s].`, lhs, rhs), file, line);
else
throw new AssertError(format(`_assertPred!("opCmp", "<") failed: [%s] > [%s]: %s`, lhs, rhs, msg), file, line);
}
}
else static if(expected == "==")
{
if(result == 0)
return;
if(result < 0)
{
if(msg.empty)
throw new AssertError(format(`_assertPred!("opCmp", "==") failed: [%s] < [%s].`, lhs, rhs), file, line);
else
throw new AssertError(format(`_assertPred!("opCmp", "==") failed: [%s] < [%s]: %s`, lhs, rhs, msg), file, line);
}
else
{
if(msg.empty)
throw new AssertError(format(`_assertPred!("opCmp", "==") failed: [%s] > [%s].`, lhs, rhs), file, line);
else
throw new AssertError(format(`_assertPred!("opCmp", "==") failed: [%s] > [%s]: %s`, lhs, rhs, msg), file, line);
}
}
else static if(expected == ">")
{
if(result > 0)
return;
if(result < 0)
{
if(msg.empty)
throw new AssertError(format(`_assertPred!("opCmp", ">") failed: [%s] < [%s].`, lhs, rhs), file, line);
else
throw new AssertError(format(`_assertPred!("opCmp", ">") failed: [%s] < [%s]: %s`, lhs, rhs, msg), file, line);
}
else
{
if(msg.empty)
throw new AssertError(format(`_assertPred!("opCmp", ">") failed: [%s] == [%s].`, lhs, rhs), file, line);
else
throw new AssertError(format(`_assertPred!("opCmp", ">") failed: [%s] == [%s]: %s`, lhs, rhs, msg), file, line);
}
}
else
static assert(0);
}
void _assertPred(string op, L, R, E)
(L lhs, R rhs, E expected, lazy string msg = null, string file = __FILE__, size_t line = __LINE__)
if((op == "+=" ||
op == "-=" ||
op == "*=" ||
op == "/=" ||
op == "%=" ||
op == "^^=" ||
op == "&=" ||
op == "|=" ||
op == "^=" ||
op == "<<=" ||
op == ">>=" ||
op == ">>>=" ||
op == "~=") &&
__traits(compiles, mixin("lhs " ~ op ~ " rhs")) &&
__traits(compiles, mixin("(lhs " ~ op ~ " rhs) == expected")) &&
_isPrintable!L &&
_isPrintable!R)
{
immutable origLHSStr = to!string(lhs);
const result = mixin("lhs " ~ op ~ " rhs");
if(lhs != expected)
{
if(msg.empty)
{
throw new AssertError(format(`_assertPred!"%s" failed: After [%s] %s [%s], lhs was assigned to [%s] instead of [%s].`,
op,
origLHSStr,
op,
rhs,
lhs,
expected),
file,
line);
}
else
{
throw new AssertError(format(`_assertPred!"%s" failed: After [%s] %s [%s], lhs was assigned to [%s] instead of [%s]: %s`,
op,
origLHSStr,
op,
rhs,
lhs,
expected,
msg),
file,
line);
}
}
if(result != expected)
{
if(msg.empty)
{
throw new AssertError(format(`_assertPred!"%s" failed: Return value of [%s] %s [%s] was [%s] instead of [%s].`,
op,
origLHSStr,
op,
rhs,
result,
expected),
file,
line);
}
else
{
throw new AssertError(format(`_assertPred!"%s" failed: Return value of [%s] %s [%s] was [%s] instead of [%s]: %s`,
op,
origLHSStr,
op,
rhs,
result,
expected,
msg),
file,
line);
}
}
}
unittest
{
version(testStdDateTime)
{
assertNotThrown!AssertError(_assertPred!"+="(7, 5, 12));
assertNotThrown!AssertError(_assertPred!"-="(7, 5, 2));
assertNotThrown!AssertError(_assertPred!"*="(7, 5, 35));
assertNotThrown!AssertError(_assertPred!"/="(7, 5, 1));
assertNotThrown!AssertError(_assertPred!"%="(7, 5, 2));
assertNotThrown!AssertError(_assertPred!"^^="(7, 5, 16_807));
assertNotThrown!AssertError(_assertPred!"&="(7, 5, 5));
assertNotThrown!AssertError(_assertPred!"|="(7, 5, 7));
assertNotThrown!AssertError(_assertPred!"^="(7, 5, 2));
assertNotThrown!AssertError(_assertPred!"<<="(7, 1, 14));
assertNotThrown!AssertError(_assertPred!">>="(7, 1, 3));
assertNotThrown!AssertError(_assertPred!">>>="(-7, 1, 2_147_483_644));
assertNotThrown!AssertError(_assertPred!"~="("hello ", "world", "hello world"));
assertThrown!AssertError(_assertPred!"+="(7, 5, 0));
assertThrown!AssertError(_assertPred!"-="(7, 5, 0));
assertThrown!AssertError(_assertPred!"*="(7, 5, 0));
assertThrown!AssertError(_assertPred!"/="(7, 5, 0));
assertThrown!AssertError(_assertPred!"%="(7, 5, 0));
assertThrown!AssertError(_assertPred!"^^="(7, 5, 0));
assertThrown!AssertError(_assertPred!"&="(7, 5, 0));
assertThrown!AssertError(_assertPred!"|="(7, 5, 0));
assertThrown!AssertError(_assertPred!"^="(7, 5, 0));
assertThrown!AssertError(_assertPred!"<<="(7, 1, 0));
assertThrown!AssertError(_assertPred!">>="(7, 1, 0));
assertThrown!AssertError(_assertPred!">>>="(-7, 1, 0));
assertThrown!AssertError(_assertPred!"~="("hello ", "world", "goodbye world"));
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"+="(7, 5, 11)),
`_assertPred!"+=" failed: After [7] += [5], lhs was assigned to [12] instead of [11].`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"+="(7, 5, 11, "It failed!")),
`_assertPred!"+=" failed: After [7] += [5], lhs was assigned to [12] instead of [11]: It failed!`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"^^="(7, 5, 42)),
`_assertPred!"^^=" failed: After [7] ^^= [5], lhs was assigned to [16807] instead of [42].`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"^^="(7, 5, 42, "It failed!")),
`_assertPred!"^^=" failed: After [7] ^^= [5], lhs was assigned to [16807] instead of [42]: It failed!`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"~="("hello ", "world", "goodbye world")),
`_assertPred!"~=" failed: After [hello ] ~= [world], lhs was assigned to [hello world] instead of [goodbye world].`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"~="("hello ", "world", "goodbye world", "It failed!")),
`_assertPred!"~=" failed: After [hello ] ~= [world], lhs was assigned to [hello world] instead of [goodbye world]: It failed!`);
struct IntWrapper
{
int value;
this(int value)
{
this.value = value;
}
IntWrapper opOpAssign(string op)(IntWrapper rhs)
{
mixin("this.value " ~ op ~ "= rhs.value;");
return this;
}
string toString()
{
return to!string(value);
}
}
struct IntWrapper_BadAssign
{
int value;
this(int value)
{
this.value = value;
}
IntWrapper_BadAssign opOpAssign(string op)(IntWrapper_BadAssign rhs)
{
auto old = this.value;
mixin("this.value " ~ op ~ "= -rhs.value;");
return IntWrapper_BadAssign(mixin("old " ~ op ~ " rhs.value"));
}
string toString()
{
return to!string(value);
}
}
struct IntWrapper_BadReturn
{
int value;
this(int value)
{
this.value = value;
}
IntWrapper_BadReturn opOpAssign(string op)(IntWrapper_BadReturn rhs)
{
mixin("this.value " ~ op ~ "= rhs.value;");
return IntWrapper_BadReturn(rhs.value);
}
string toString()
{
return to!string(value);
}
}
assertNotThrown!AssertError(_assertPred!"+="(IntWrapper(5), IntWrapper(2), IntWrapper(7)));
assertNotThrown!AssertError(_assertPred!"*="(IntWrapper(5), IntWrapper(2), IntWrapper(10)));
assertThrown!AssertError(_assertPred!"+="(IntWrapper_BadAssign(5), IntWrapper_BadAssign(2), IntWrapper_BadAssign(7)));
assertThrown!AssertError(_assertPred!"+="(IntWrapper_BadReturn(5), IntWrapper_BadReturn(2), IntWrapper_BadReturn(7)));
assertThrown!AssertError(_assertPred!"*="(IntWrapper_BadAssign(5), IntWrapper_BadAssign(2), IntWrapper_BadAssign(10)));
assertThrown!AssertError(_assertPred!"*="(IntWrapper_BadReturn(5), IntWrapper_BadReturn(2), IntWrapper_BadReturn(10)));
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"+="(IntWrapper_BadAssign(5), IntWrapper_BadAssign(2), IntWrapper_BadAssign(7))),
`_assertPred!"+=" failed: After [5] += [2], lhs was assigned to [3] instead of [7].`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"+="(IntWrapper_BadAssign(5), IntWrapper_BadAssign(2), IntWrapper_BadAssign(7), "It failed!")),
`_assertPred!"+=" failed: After [5] += [2], lhs was assigned to [3] instead of [7]: It failed!`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"+="(IntWrapper_BadReturn(5), IntWrapper_BadReturn(2), IntWrapper_BadReturn(7))),
`_assertPred!"+=" failed: Return value of [5] += [2] was [2] instead of [7].`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"+="(IntWrapper_BadReturn(5), IntWrapper_BadReturn(2), IntWrapper_BadReturn(7), "It failed!")),
`_assertPred!"+=" failed: Return value of [5] += [2] was [2] instead of [7]: It failed!`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"*="(IntWrapper_BadAssign(5), IntWrapper_BadAssign(2), IntWrapper_BadAssign(10))),
`_assertPred!"*=" failed: After [5] *= [2], lhs was assigned to [-10] instead of [10].`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"*="(IntWrapper_BadAssign(5), IntWrapper_BadAssign(2), IntWrapper_BadAssign(10), "It failed!")),
`_assertPred!"*=" failed: After [5] *= [2], lhs was assigned to [-10] instead of [10]: It failed!`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"*="(IntWrapper_BadReturn(5), IntWrapper_BadReturn(2), IntWrapper_BadReturn(10))),
`_assertPred!"*=" failed: Return value of [5] *= [2] was [2] instead of [10].`);
_assertPred!"=="(collectExceptionMsg!AssertError(_assertPred!"*="(IntWrapper_BadReturn(5), IntWrapper_BadReturn(2), IntWrapper_BadReturn(10), "It failed!")),
`_assertPred!"*=" failed: Return value of [5] *= [2] was [2] instead of [10]: It failed!`);
}
}
template _isPrintable(T...)
{
static if(T.length == 0)
enum _isPrintable = true;
else static if(T.length == 1)
{
enum _isPrintable = (!isArray!(T[0]) && __traits(compiles, to!string(T[0].init))) ||
(isArray!(T[0]) && __traits(compiles, to!string(T[0].init[0])));
}
else
{
enum _isPrintable = _isPrintable!(T[0]) && _isPrintable!(T[1 .. $]);
}
}
template softDeprec(string vers, string date, string oldFunc, string newFunc)
{
enum softDeprec = Format!("Warning: As of Phobos %s, std.datetime.%s has been scheduled " ~
"for deprecation in %s. Please use std.datetime.%s instead.",
vers, oldFunc, date, newFunc);
}
| D |
/**
Utility functions for memory management
Note that this module currently is a big sand box for testing allocation related stuff.
Nothing here, including the interfaces, is final but rather a lot of experimentation.
Copyright: © 2012-2013 RejectedSoftware e.K.
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Sönke Ludwig
*/
module vibe.utils.memory;
import vibe.internal.meta.traits : synchronizedIsNothrow;
import core.exception : OutOfMemoryError;
import core.stdc.stdlib;
import core.memory;
import std.conv;
import std.exception : enforceEx;
import std.traits;
import std.algorithm;
Allocator defaultAllocator() nothrow
{
version(VibeManualMemoryManagement){
return manualAllocator();
} else {
static __gshared Allocator alloc;
if (!alloc) {
alloc = new GCAllocator;
//alloc = new AutoFreeListAllocator(alloc);
//alloc = new DebugAllocator(alloc);
alloc = new LockAllocator(alloc);
}
return alloc;
}
}
Allocator manualAllocator() nothrow
{
static __gshared Allocator alloc;
if( !alloc ){
alloc = new MallocAllocator;
alloc = new AutoFreeListAllocator(alloc);
//alloc = new DebugAllocator(alloc);
alloc = new LockAllocator(alloc);
}
return alloc;
}
Allocator threadLocalAllocator() nothrow
{
static Allocator alloc;
if (!alloc) {
version(VibeManualMemoryManagement) alloc = new MallocAllocator;
else alloc = new GCAllocator;
alloc = new AutoFreeListAllocator(alloc);
// alloc = new DebugAllocator(alloc);
}
return alloc;
}
Allocator threadLocalManualAllocator() nothrow
{
static Allocator alloc;
if (!alloc) {
alloc = new MallocAllocator;
alloc = new AutoFreeListAllocator(alloc);
// alloc = new DebugAllocator(alloc);
}
return alloc;
}
auto allocObject(T, bool MANAGED = true, ARGS...)(Allocator allocator, ARGS args)
{
auto mem = allocator.alloc(AllocSize!T);
static if( MANAGED ){
static if( hasIndirections!T )
GC.addRange(mem.ptr, mem.length);
return internalEmplace!T(mem, args);
}
else static if( is(T == class) ) return cast(T)mem.ptr;
else return cast(T*)mem.ptr;
}
T[] allocArray(T, bool MANAGED = true)(Allocator allocator, size_t n)
{
auto mem = allocator.alloc(T.sizeof * n);
auto ret = cast(T[])mem;
static if( MANAGED ){
static if( hasIndirections!T )
GC.addRange(mem.ptr, mem.length);
// TODO: use memset for class, pointers and scalars
foreach (ref el; ret) {
internalEmplace!T(cast(void[])((&el)[0 .. 1]));
}
}
return ret;
}
void freeArray(T, bool MANAGED = true)(Allocator allocator, ref T[] array, bool call_destructors = true)
{
static if (MANAGED) {
static if (hasIndirections!T)
GC.removeRange(array.ptr);
static if (hasElaborateDestructor!T)
if (call_destructors)
foreach_reverse (ref el; array)
destroy(el);
}
allocator.free(cast(void[])array);
array = null;
}
interface Allocator {
nothrow:
enum size_t alignment = 0x10;
enum size_t alignmentMask = alignment-1;
void[] alloc(size_t sz)
out { assert((cast(size_t)__result.ptr & alignmentMask) == 0, "alloc() returned misaligned data."); }
void[] realloc(void[] mem, size_t new_sz)
in {
assert(mem.ptr !is null, "realloc() called with null array.");
assert((cast(size_t)mem.ptr & alignmentMask) == 0, "misaligned pointer passed to realloc().");
}
out { assert((cast(size_t)__result.ptr & alignmentMask) == 0, "realloc() returned misaligned data."); }
void free(void[] mem)
in {
assert(mem.ptr !is null, "free() called with null array.");
assert((cast(size_t)mem.ptr & alignmentMask) == 0, "misaligned pointer passed to free().");
}
}
/**
Simple proxy allocator protecting its base allocator with a mutex.
*/
class LockAllocator : Allocator {
private {
Allocator m_base;
}
this(Allocator base) nothrow { m_base = base; }
void[] alloc(size_t sz) {
static if (!synchronizedIsNothrow)
scope (failure) assert(0, "Internal error: function should be nothrow");
synchronized (this)
return m_base.alloc(sz);
}
void[] realloc(void[] mem, size_t new_sz)
in {
assert(mem.ptr !is null, "realloc() called with null array.");
assert((cast(size_t)mem.ptr & alignmentMask) == 0, "misaligned pointer passed to realloc().");
}
body {
static if (!synchronizedIsNothrow)
scope (failure) assert(0, "Internal error: function should be nothrow");
synchronized(this)
return m_base.realloc(mem, new_sz);
}
void free(void[] mem)
in {
assert(mem.ptr !is null, "free() called with null array.");
assert((cast(size_t)mem.ptr & alignmentMask) == 0, "misaligned pointer passed to free().");
}
body {
static if (!synchronizedIsNothrow)
scope (failure) assert(0, "Internal error: function should be nothrow");
synchronized(this)
m_base.free(mem);
}
}
final class DebugAllocator : Allocator {
import vibe.utils.hashmap : HashMap;
private {
Allocator m_baseAlloc;
HashMap!(void*, size_t) m_blocks;
size_t m_bytes;
size_t m_maxBytes;
}
this(Allocator base_allocator) nothrow
{
m_baseAlloc = base_allocator;
m_blocks = HashMap!(void*, size_t)(manualAllocator());
}
@property size_t allocatedBlockCount() const { return m_blocks.length; }
@property size_t bytesAllocated() const { return m_bytes; }
@property size_t maxBytesAllocated() const { return m_maxBytes; }
void[] alloc(size_t sz)
{
auto ret = m_baseAlloc.alloc(sz);
assert(ret.length == sz, "base.alloc() returned block with wrong size.");
assert(m_blocks.getNothrow(ret.ptr, size_t.max) == size_t.max, "base.alloc() returned block that is already allocated.");
m_blocks[ret.ptr] = sz;
m_bytes += sz;
if( m_bytes > m_maxBytes ){
m_maxBytes = m_bytes;
logDebug_("New allocation maximum: %d (%d blocks)", m_maxBytes, m_blocks.length);
}
return ret;
}
void[] realloc(void[] mem, size_t new_size)
{
auto sz = m_blocks.getNothrow(mem.ptr, size_t.max);
assert(sz != size_t.max, "realloc() called with non-allocated pointer.");
assert(sz == mem.length, "realloc() called with block of wrong size.");
auto ret = m_baseAlloc.realloc(mem, new_size);
assert(ret.length == new_size, "base.realloc() returned block with wrong size.");
assert(ret.ptr is mem.ptr || m_blocks.getNothrow(ret.ptr, size_t.max) == size_t.max, "base.realloc() returned block that is already allocated.");
m_bytes -= sz;
m_blocks.remove(mem.ptr);
m_blocks[ret.ptr] = new_size;
m_bytes += new_size;
return ret;
}
void free(void[] mem)
{
auto sz = m_blocks.getNothrow(mem.ptr, size_t.max);
assert(sz != size_t.max, "free() called with non-allocated object.");
assert(sz == mem.length, "free() called with block of wrong size.");
m_baseAlloc.free(mem);
m_bytes -= sz;
m_blocks.remove(mem.ptr);
}
}
final class MallocAllocator : Allocator {
void[] alloc(size_t sz)
{
static err = new immutable OutOfMemoryError;
auto ptr = .malloc(sz + Allocator.alignment);
if (ptr is null) throw err;
return adjustPointerAlignment(ptr)[0 .. sz];
}
void[] realloc(void[] mem, size_t new_size)
{
size_t csz = min(mem.length, new_size);
auto p = extractUnalignedPointer(mem.ptr);
size_t oldmisalign = mem.ptr - p;
auto pn = cast(ubyte*).realloc(p, new_size+Allocator.alignment);
if (p == pn) return pn[oldmisalign .. new_size+oldmisalign];
auto pna = cast(ubyte*)adjustPointerAlignment(pn);
auto newmisalign = pna - pn;
// account for changed alignment after realloc (move memory back to aligned position)
if (oldmisalign != newmisalign) {
if (newmisalign > oldmisalign) {
foreach_reverse (i; 0 .. csz)
pn[i + newmisalign] = pn[i + oldmisalign];
} else {
foreach (i; 0 .. csz)
pn[i + newmisalign] = pn[i + oldmisalign];
}
}
return pna[0 .. new_size];
}
void free(void[] mem)
{
.free(extractUnalignedPointer(mem.ptr));
}
}
final class GCAllocator : Allocator {
void[] alloc(size_t sz)
{
auto mem = GC.malloc(sz+Allocator.alignment);
auto alignedmem = adjustPointerAlignment(mem);
assert(alignedmem - mem <= Allocator.alignment);
auto ret = alignedmem[0 .. sz];
ensureValidMemory(ret);
return ret;
}
void[] realloc(void[] mem, size_t new_size)
{
size_t csz = min(mem.length, new_size);
auto p = extractUnalignedPointer(mem.ptr);
size_t misalign = mem.ptr - p;
assert(misalign <= Allocator.alignment);
void[] ret;
auto extended = GC.extend(p, new_size - mem.length, new_size - mem.length);
if (extended) {
assert(extended >= new_size+Allocator.alignment);
ret = p[misalign .. new_size+misalign];
} else {
ret = alloc(new_size);
ret[0 .. csz] = mem[0 .. csz];
}
ensureValidMemory(ret);
return ret;
}
void free(void[] mem)
{
// For safety reasons, the GCAllocator should never explicitly free memory.
//GC.free(extractUnalignedPointer(mem.ptr));
}
}
final class AutoFreeListAllocator : Allocator {
import std.typetuple;
private {
enum minExponent = 5;
enum freeListCount = 14;
FreeListAlloc[freeListCount] m_freeLists;
Allocator m_baseAlloc;
}
this(Allocator base_allocator) nothrow
{
m_baseAlloc = base_allocator;
foreach (i; iotaTuple!freeListCount)
m_freeLists[i] = new FreeListAlloc(nthFreeListSize!(i), m_baseAlloc);
}
void[] alloc(size_t sz)
{
auto idx = getAllocatorIndex(sz);
return idx < freeListCount ? m_freeLists[idx].alloc()[0 .. sz] : m_baseAlloc.alloc(sz);
}
void[] realloc(void[] data, size_t sz)
{
auto curidx = getAllocatorIndex(data.length);
auto newidx = getAllocatorIndex(sz);
if (curidx == newidx) {
if (curidx == freeListCount) {
// forward large blocks to the base allocator
return m_baseAlloc.realloc(data, sz);
} else {
// just grow the slice if it still fits into the free list slot
return data.ptr[0 .. sz];
}
}
// otherwise re-allocate manually
auto newd = alloc(sz);
assert(newd.ptr+sz <= data.ptr || newd.ptr >= data.ptr+data.length, "New block overlaps old one!?");
auto len = min(data.length, sz);
newd[0 .. len] = data[0 .. len];
free(data);
return newd;
}
void free(void[] data)
{
//logTrace("AFL free %08X(%s)", data.ptr, data.length);
auto idx = getAllocatorIndex(data.length);
if (idx < freeListCount) m_freeLists[idx].free(data.ptr[0 .. 1 << (idx + minExponent)]);
else m_baseAlloc.free(data);
}
// does a CT optimized binary search for the right allocater
private int getAllocatorIndex(size_t sz)
@safe nothrow @nogc {
//pragma(msg, getAllocatorIndexStr!(0, freeListCount));
return mixin(getAllocatorIndexStr!(0, freeListCount));
}
private template getAllocatorIndexStr(int low, int high)
{
static if (__VERSION__ <= 2066) import std.string : format;
else import std.format : format;
static if (low == high) enum getAllocatorIndexStr = format("%s", low);
else {
enum mid = (low + high) / 2;
enum getAllocatorIndexStr =
"sz > nthFreeListSize!%s ? %s : %s"
.format(mid, getAllocatorIndexStr!(mid+1, high), getAllocatorIndexStr!(low, mid));
}
}
unittest {
auto a = new AutoFreeListAllocator(null);
assert(a.getAllocatorIndex(0) == 0);
foreach (i; iotaTuple!freeListCount) {
assert(a.getAllocatorIndex(nthFreeListSize!i-1) == i);
assert(a.getAllocatorIndex(nthFreeListSize!i) == i);
assert(a.getAllocatorIndex(nthFreeListSize!i+1) == i+1);
}
assert(a.getAllocatorIndex(size_t.max) == freeListCount);
}
private static pure size_t nthFreeListSize(size_t i)() { return 1 << (i + minExponent); }
private template iotaTuple(size_t i) {
static if (i > 1) alias iotaTuple = TypeTuple!(iotaTuple!(i-1), i-1);
else alias iotaTuple = TypeTuple!(0);
}
}
final class PoolAllocator : Allocator {
static struct Pool { Pool* next; void[] data; void[] remaining; }
static struct Destructor { Destructor* next; void function(void*) destructor; void* object; }
private {
Allocator m_baseAllocator;
Pool* m_freePools;
Pool* m_fullPools;
Destructor* m_destructors;
size_t m_poolSize;
}
this(size_t pool_size, Allocator base) nothrow
{
m_poolSize = pool_size;
m_baseAllocator = base;
}
@property size_t totalSize()
{
size_t amt = 0;
for (auto p = m_fullPools; p; p = p.next)
amt += p.data.length;
for (auto p = m_freePools; p; p = p.next)
amt += p.data.length;
return amt;
}
@property size_t allocatedSize()
{
size_t amt = 0;
for (auto p = m_fullPools; p; p = p.next)
amt += p.data.length;
for (auto p = m_freePools; p; p = p.next)
amt += p.data.length - p.remaining.length;
return amt;
}
void[] alloc(size_t sz)
{
auto aligned_sz = alignedSize(sz);
Pool* pprev = null;
Pool* p = cast(Pool*)m_freePools;
while( p && p.remaining.length < aligned_sz ){
pprev = p;
p = p.next;
}
if( !p ){
auto pmem = m_baseAllocator.alloc(AllocSize!Pool);
p = emplace!Pool(cast(Pool*)pmem.ptr);
p.data = m_baseAllocator.alloc(max(aligned_sz, m_poolSize));
p.remaining = p.data;
p.next = cast(Pool*)m_freePools;
m_freePools = p;
pprev = null;
}
auto ret = p.remaining[0 .. aligned_sz];
p.remaining = p.remaining[aligned_sz .. $];
if( !p.remaining.length ){
if( pprev ){
pprev.next = p.next;
} else {
m_freePools = p.next;
}
p.next = cast(Pool*)m_fullPools;
m_fullPools = p;
}
return ret[0 .. sz];
}
void[] realloc(void[] arr, size_t newsize)
{
auto aligned_sz = alignedSize(arr.length);
auto aligned_newsz = alignedSize(newsize);
if( aligned_newsz <= aligned_sz ) return arr[0 .. newsize]; // TODO: back up remaining
auto pool = m_freePools;
bool last_in_pool = pool && arr.ptr+aligned_sz == pool.remaining.ptr;
if( last_in_pool && pool.remaining.length+aligned_sz >= aligned_newsz ){
pool.remaining = pool.remaining[aligned_newsz-aligned_sz .. $];
arr = arr.ptr[0 .. aligned_newsz];
assert(arr.ptr+arr.length == pool.remaining.ptr, "Last block does not align with the remaining space!?");
return arr[0 .. newsize];
} else {
auto ret = alloc(newsize);
assert(ret.ptr >= arr.ptr+aligned_sz || ret.ptr+ret.length <= arr.ptr, "New block overlaps old one!?");
ret[0 .. min(arr.length, newsize)] = arr[0 .. min(arr.length, newsize)];
return ret;
}
}
void free(void[] mem)
{
}
void freeAll()
{
version(VibeManualMemoryManagement){
// destroy all initialized objects
for (auto d = m_destructors; d; d = d.next)
d.destructor(cast(void*)d.object);
m_destructors = null;
// put all full Pools into the free pools list
for (Pool* p = cast(Pool*)m_fullPools, pnext; p; p = pnext) {
pnext = p.next;
p.next = cast(Pool*)m_freePools;
m_freePools = cast(Pool*)p;
}
// free up all pools
for (Pool* p = cast(Pool*)m_freePools; p; p = p.next)
p.remaining = p.data;
}
}
void reset()
{
version(VibeManualMemoryManagement){
freeAll();
Pool* pnext;
for (auto p = cast(Pool*)m_freePools; p; p = pnext) {
pnext = p.next;
m_baseAllocator.free(p.data);
m_baseAllocator.free((cast(void*)p)[0 .. AllocSize!Pool]);
}
m_freePools = null;
}
}
private static destroy(T)(void* ptr)
{
static if( is(T == class) ) .destroy(cast(T)ptr);
else .destroy(*cast(T*)ptr);
}
}
final class FreeListAlloc : Allocator
{
nothrow:
private static struct FreeListSlot { FreeListSlot* next; }
private {
FreeListSlot* m_firstFree = null;
size_t m_nalloc = 0;
size_t m_nfree = 0;
Allocator m_baseAlloc;
immutable size_t m_elemSize;
}
this(size_t elem_size, Allocator base_allocator)
{
assert(elem_size >= size_t.sizeof);
m_elemSize = elem_size;
m_baseAlloc = base_allocator;
logDebug_("Create FreeListAlloc %d", m_elemSize);
}
@property size_t elementSize() const { return m_elemSize; }
void[] alloc(size_t sz)
{
assert(sz == m_elemSize, "Invalid allocation size.");
return alloc();
}
void[] alloc()
{
void[] mem;
if( m_firstFree ){
auto slot = m_firstFree;
m_firstFree = slot.next;
slot.next = null;
mem = (cast(void*)slot)[0 .. m_elemSize];
debug m_nfree--;
} else {
mem = m_baseAlloc.alloc(m_elemSize);
//logInfo("Alloc %d bytes: alloc: %d, free: %d", SZ, s_nalloc, s_nfree);
}
debug m_nalloc++;
//logInfo("Alloc %d bytes: alloc: %d, free: %d", SZ, s_nalloc, s_nfree);
return mem;
}
void[] realloc(void[] mem, size_t sz)
{
assert(mem.length == m_elemSize);
assert(sz == m_elemSize);
return mem;
}
void free(void[] mem)
{
assert(mem.length == m_elemSize, "Memory block passed to free has wrong size.");
auto s = cast(FreeListSlot*)mem.ptr;
s.next = m_firstFree;
m_firstFree = s;
m_nalloc--;
m_nfree++;
}
}
struct FreeListObjectAlloc(T, bool USE_GC = true, bool INIT = true)
{
enum ElemSize = AllocSize!T;
enum ElemSlotSize = max(AllocSize!T, Slot.sizeof);
static if( is(T == class) ){
alias TR = T;
} else {
alias TR = T*;
}
struct Slot { Slot* next; }
private static Slot* s_firstFree;
static TR alloc(ARGS...)(ARGS args)
{
void[] mem;
if (s_firstFree !is null) {
auto ret = s_firstFree;
s_firstFree = s_firstFree.next;
ret.next = null;
mem = (cast(void*)ret)[0 .. ElemSize];
} else {
//logInfo("alloc %s/%d", T.stringof, ElemSize);
mem = manualAllocator().alloc(ElemSlotSize);
static if( hasIndirections!T ) GC.addRange(mem.ptr, ElemSlotSize);
}
static if (INIT) return cast(TR)internalEmplace!(Unqual!T)(mem, args); // FIXME: this emplace has issues with qualified types, but Unqual!T may result in the wrong constructor getting called.
else return cast(TR)mem.ptr;
}
static void free(TR obj)
{
static if (INIT) {
scope (failure) assert(0, "You shouldn't throw in destructors");
auto objc = obj;
static if (is(TR == T*)) .destroy(*objc);//typeid(T).destroy(cast(void*)obj);
else .destroy(objc);
}
auto sl = cast(Slot*)obj;
sl.next = s_firstFree;
s_firstFree = sl;
//static if( hasIndirections!T ) GC.removeRange(cast(void*)obj);
//manualAllocator().free((cast(void*)obj)[0 .. ElemSlotSize]);
}
}
template AllocSize(T)
{
static if (is(T == class)) {
// workaround for a strange bug where AllocSize!SSLStream == 0: TODO: dustmite!
enum dummy = T.stringof ~ __traits(classInstanceSize, T).stringof;
enum AllocSize = __traits(classInstanceSize, T);
} else {
enum AllocSize = T.sizeof;
}
}
struct FreeListRef(T, bool INIT = true)
{
alias ObjAlloc = FreeListObjectAlloc!(T, true, INIT);
enum ElemSize = AllocSize!T;
static if( is(T == class) ){
alias TR = T;
} else {
alias TR = T*;
}
private TR m_object;
private size_t m_magic = 0x1EE75817; // workaround for compiler bug
static FreeListRef opCall(ARGS...)(ARGS args)
{
//logInfo("refalloc %s/%d", T.stringof, ElemSize);
FreeListRef ret;
ret.m_object = ObjAlloc.alloc(args);
ret.refCount = 1;
return ret;
}
~this()
{
//if( m_object ) logInfo("~this!%s(): %d", T.stringof, this.refCount);
//if( m_object ) logInfo("ref %s destructor %d", T.stringof, refCount);
//else logInfo("ref %s destructor %d", T.stringof, 0);
clear();
m_magic = 0;
m_object = null;
}
this(this)
{
checkInvariants();
if( m_object ){
//if( m_object ) logInfo("this!%s(this): %d", T.stringof, this.refCount);
this.refCount++;
}
}
void opAssign(FreeListRef other)
{
clear();
m_object = other.m_object;
if( m_object ){
//logInfo("opAssign!%s(): %d", T.stringof, this.refCount);
refCount++;
}
}
void clear()
{
checkInvariants();
if (m_object) {
if (--this.refCount == 0)
ObjAlloc.free(m_object);
}
m_object = null;
m_magic = 0x1EE75817;
}
@property const(TR) get() const { checkInvariants(); return m_object; }
@property TR get() { checkInvariants(); return m_object; }
alias get this;
private @property ref int refCount()
const {
auto ptr = cast(ubyte*)cast(void*)m_object;
ptr += ElemSize;
return *cast(int*)ptr;
}
private void checkInvariants()
const {
assert(m_magic == 0x1EE75817);
assert(!m_object || refCount > 0);
}
}
private void* extractUnalignedPointer(void* base) nothrow
{
ubyte misalign = *(cast(ubyte*)base-1);
assert(misalign <= Allocator.alignment);
return base - misalign;
}
private void* adjustPointerAlignment(void* base) nothrow
{
ubyte misalign = Allocator.alignment - (cast(size_t)base & Allocator.alignmentMask);
base += misalign;
*(cast(ubyte*)base-1) = misalign;
return base;
}
unittest {
void test_align(void* p, size_t adjustment) {
void* pa = adjustPointerAlignment(p);
assert((cast(size_t)pa & Allocator.alignmentMask) == 0, "Non-aligned pointer.");
assert(*(cast(ubyte*)pa-1) == adjustment, "Invalid adjustment "~to!string(p)~": "~to!string(*(cast(ubyte*)pa-1)));
void* pr = extractUnalignedPointer(pa);
assert(pr == p, "Recovered base != original");
}
void* ptr = .malloc(0x40);
ptr += Allocator.alignment - (cast(size_t)ptr & Allocator.alignmentMask);
test_align(ptr++, 0x10);
test_align(ptr++, 0x0F);
test_align(ptr++, 0x0E);
test_align(ptr++, 0x0D);
test_align(ptr++, 0x0C);
test_align(ptr++, 0x0B);
test_align(ptr++, 0x0A);
test_align(ptr++, 0x09);
test_align(ptr++, 0x08);
test_align(ptr++, 0x07);
test_align(ptr++, 0x06);
test_align(ptr++, 0x05);
test_align(ptr++, 0x04);
test_align(ptr++, 0x03);
test_align(ptr++, 0x02);
test_align(ptr++, 0x01);
test_align(ptr++, 0x10);
}
private size_t alignedSize(size_t sz) nothrow
{
return ((sz + Allocator.alignment - 1) / Allocator.alignment) * Allocator.alignment;
}
unittest {
foreach( i; 0 .. 20 ){
auto ia = alignedSize(i);
assert(ia >= i);
assert((ia & Allocator.alignmentMask) == 0);
assert(ia < i+Allocator.alignment);
}
}
private void ensureValidMemory(void[] mem) nothrow
{
auto bytes = cast(ubyte[])mem;
swap(bytes[0], bytes[$-1]);
swap(bytes[0], bytes[$-1]);
}
/// See issue #14194
private T internalEmplace(T, Args...)(void[] chunk, auto ref Args args)
if (is(T == class))
in {
import std.string, std.format;
assert(chunk.length >= T.sizeof,
format("emplace: Chunk size too small: %s < %s size = %s",
chunk.length, T.stringof, T.sizeof));
assert((cast(size_t) chunk.ptr) % T.alignof == 0,
format("emplace: Misaligned memory block (0x%X): it must be %s-byte aligned for type %s", chunk.ptr, T.alignof, T.stringof));
} body {
enum classSize = __traits(classInstanceSize, T);
auto result = cast(T) chunk.ptr;
// Initialize the object in its pre-ctor state
chunk[0 .. classSize] = typeid(T).init[];
// Call the ctor if any
static if (is(typeof(result.__ctor(args))))
{
// T defines a genuine constructor accepting args
// Go the classic route: write .init first, then call ctor
result.__ctor(args);
}
else
{
static assert(args.length == 0 && !is(typeof(&T.__ctor)),
"Don't know how to initialize an object of type "
~ T.stringof ~ " with arguments " ~ Args.stringof);
}
return result;
}
/// Dittor
private auto internalEmplace(T, Args...)(void[] chunk, auto ref Args args)
if (!is(T == class))
in {
import std.string, std.format;
assert(chunk.length >= T.sizeof,
format("emplace: Chunk size too small: %s < %s size = %s",
chunk.length, T.stringof, T.sizeof));
assert((cast(size_t) chunk.ptr) % T.alignof == 0,
format("emplace: Misaligned memory block (0x%X): it must be %s-byte aligned for type %s", chunk.ptr, T.alignof, T.stringof));
} body {
return emplace(cast(T*)chunk.ptr, args);
}
private void logDebug_(ARGS...)(string msg, ARGS args) {}
| D |
/* -------------------- CZ CHANGELOG -------------------- */
/*
v1.01:
CanLearnMagicCircleNext_ABCZ - upraveny podmínky učení se magických kruhů (na žádost hráčů)
*/
instance DIA_MiltenOW_EXIT(C_Info)
{
npc = PC_Mage_OW;
nr = 999;
condition = DIA_MiltenOW_EXIT_Condition;
information = DIA_MiltenOW_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_MiltenOW_EXIT_Condition()
{
return TRUE;
};
func void DIA_MiltenOW_EXIT_Info()
{
AI_StopProcessInfos(self);
};
instance DIA_MiltenOW_Hello(C_Info)
{
npc = PC_Mage_OW;
nr = TRUE;
condition = DIA_MiltenOW_Hello_Condition;
information = DIA_MiltenOW_Hello_Info;
permanent = FALSE;
important = TRUE;
};
func int DIA_MiltenOW_Hello_Condition()
{
return TRUE;
};
func void DIA_MiltenOW_Hello_Info()
{
AI_Output(self,other,"DIA_MiltenOW_Hello_03_00"); //Podívejme, kdo se vrátil! Náš hrdina od bariéry!
Info_ClearChoices(DIA_MiltenOW_Hello);
Info_AddChoice(DIA_MiltenOW_Hello,"Rád tě vidím, Miltene.",DIA_MiltenOW_Hello_YES);
Info_AddChoice(DIA_MiltenOW_Hello,"Měl bych tě znát?",DIA_MiltenOW_Hello_NO);
};
func void B_Milten_GornDiegoLester()
{
AI_Output(self,other,"DIA_MiltenOW_Hello_NO_03_02"); //Vzpomínáš si na Gorna, Diega a Lestera?
};
func void DIA_MiltenOW_Hello_YES()
{
B_GivePlayerXP(50);
AI_Output(other,self,"DIA_MiltenOW_Hello_YES_15_00"); //Rád tě vidím, Miltene?
AI_Output(self,other,"DIA_MiltenOW_Hello_YES_03_01"); //Pořád. Co padla bariéra, vstoupil jsem do kláštera mágů Ohně.
AI_Output(self,other,"DIA_MiltenOW_Hello_YES_03_02"); //Ale jakmile se ukázalo, že sem chtějí přijít paladinové, přišly k duhu moje zkušenosti a znalost okolí.
AI_Output(self,other,"DIA_MiltenOW_Hello_YES_03_03"); //Rozhodli se tedy, že mě pověří svatým posláním poskytnout této výpravě magickou podporu.
B_Milten_GornDiegoLester();
Info_ClearChoices(DIA_MiltenOW_Hello);
Info_AddChoice(DIA_MiltenOW_Hello,"Samozřejmě, že si kluky pamatuju.",DIA_MiltenOW_Hello_Friends);
Info_AddChoice(DIA_MiltenOW_Hello,"Ta jména mi vážně nic neříkají.",DIA_MiltenOW_Hello_Forget);
};
func void DIA_MiltenOW_Hello_NO()
{
AI_Output(other,self,"DIA_MiltenOW_Hello_NO_15_00"); //Měl bych je znát?
AI_Output(self,other,"DIA_MiltenOW_Hello_NO_03_01"); //Asi toho máš za sebou dost, co?
B_Milten_GornDiegoLester();
Info_ClearChoices(DIA_MiltenOW_Hello);
Info_AddChoice(DIA_MiltenOW_Hello,"Samozřejmě, že si kluky pamatuju.",DIA_MiltenOW_Hello_Friends);
Info_AddChoice(DIA_MiltenOW_Hello,"Ta jména mi vážně nic neříkají.",DIA_MiltenOW_Hello_Forget);
};
func void DIA_MiltenOW_Hello_Friends()
{
B_GivePlayerXP(50);
AI_Output(other,self,"DIA_MiltenOW_Hello_Friends_15_00"); //Samozřejmě, že si kluky pamatuju.
AI_Output(self,other,"DIA_MiltenOW_Hello_Friends_03_01"); //No, Gorn a Diego se daleko nedostali. Sebrali je paladinové tady v údolí.
AI_Output(self,other,"DIA_MiltenOW_Hello_Friends_03_02"); //Ale Lester zmizel - vůbec netuším, kde by se tak mohl flákat.
if(Npc_KnowsInfo(other,DIA_Lester_Hello))
{
AI_Output(other,self,"DIA_MiltenOW_Hello_Friends_15_03"); //S Lesterem jsem se setkal - je teď s Xardasem.
AI_Output(self,other,"DIA_MiltenOW_Hello_Friends_03_04"); //Aspoň jedna dobrá zpráva.
};
AI_Output(self,other,"DIA_MiltenOW_Hello_Friends_03_05"); //No, já žádné dobré zprávy nemám.
Knows_Diego = TRUE;
Info_ClearChoices(DIA_MiltenOW_Hello);
};
func void DIA_MiltenOW_Hello_Forget()
{
AI_Output(other,self,"DIA_MiltenOW_Hello_Forget_15_00"); //Ta jména mi vážně nic neříkají.
AI_Output(self,other,"DIA_MiltenOW_Hello_Forget_03_01"); //Hodně jsi toho zapomněl, co? No, nechme minulost odpočívat v pokoji a věnujme se tomu, co máme před sebou.
AI_Output(self,other,"DIA_MiltenOW_Hello_Forget_03_02"); //I když nemám nic příjemného, co bych mohl nahlásit.
Info_ClearChoices(DIA_MiltenOW_Hello);
};
instance DIA_MiltenOW_Bericht(C_Info)
{
npc = PC_Mage_OW;
nr = 3;
condition = DIA_MiltenOW_Bericht_Condition;
information = DIA_MiltenOW_Bericht_Info;
permanent = FALSE;
description = "A co bys rád nahlásil?";
};
func int DIA_MiltenOW_Bericht_Condition()
{
if(Npc_KnowsInfo(other,DIA_MiltenOW_Hello))
{
return TRUE;
};
};
func void DIA_MiltenOW_Bericht_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Bericht_15_00"); //A co bys rád nahlásil?
AI_Output(self,other,"DIA_MiltenOW_Bericht_03_01"); //Přišli sem paladinové a chtějí odvézt magickou rudu.
AI_Output(self,other,"DIA_MiltenOW_Bericht_03_02"); //Ale když si vezmu všechny ty draky a skřety, netuším, jak chtějí paladinové rudu dostat a pak se taky dostat pryč.
AI_Output(self,other,"DIA_MiltenOW_Bericht_03_03"); //Ne, u Innose - cítím přítomnost něčeho temného... roste tu nějaké zlo. Vychází to z tohohle údolí.
AI_Output(self,other,"DIA_MiltenOW_Bericht_03_04"); //Za zlikvidování Spáče jsme zaplatili vysokou cenu. Pád bariéry poznamenal i tohle místo.
AI_Output(self,other,"DIA_MiltenOW_Bericht_03_05"); //Budeme mít opravdu velké štěstí, když to přežijeme.
};
instance DIA_MiltenOW_Pashal(C_Info)
{
npc = PC_Mage_OW;
nr = 3;
condition = DIA_MiltenOW_Pashal_Condition;
information = DIA_MiltenOW_Pashal_Info;
permanent = FALSE;
description = "Chtěl bych se tě na něco zeptat.";
};
func int DIA_MiltenOW_Pashal_Condition()
{
if((MIS_PashalQuest == LOG_Running) && (PashalQuestMageStep == TRUE) && (PashalQuestCaveStep == FALSE))
{
return TRUE;
};
};
func void DIA_MiltenOW_Pashal_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Pashal_01_00"); //Chtěl bych se tě na něco zeptat.
AI_Output(self,other,"DIA_MiltenOW_Pashal_01_01"); //Na co?
AI_Output(other,self,"DIA_MiltenOW_Pashal_01_02"); //Už si někdy slyšel o jednom magickém artefaktu, který absorboval veškerou moc tohoto světa?
AI_Output(self,other,"DIA_MiltenOW_Pashal_01_03"); //Hmmm... (zamyšleně) Ano! Vzpomínám si... můj mistr ze Starého tábora se jednou zmínil.
AI_Output(self,other,"DIA_MiltenOW_Pashal_01_04"); //Měl dokonce plán, použít ten artefakt ke zničení magické bariéry!
AI_Output(self,other,"DIA_MiltenOW_Pashal_01_05"); //Protože se ten artefakt nikdy nenašel, tak zůstaly jenom slova.
AI_Output(other,self,"DIA_MiltenOW_Pashal_01_06"); //Co konkrétně bys mi mohl říct?
AI_Output(self,other,"DIA_MiltenOW_Pashal_01_07"); //Jak si tak vzpomínám, jeden mág byl poslán aby ho našel.
AI_Output(self,other,"DIA_MiltenOW_Pashal_01_08"); //Ale nikdy se nevrátil zpátky! A my jsme ho hledaly marně.
AI_Output(other,self,"DIA_MiltenOW_Pashal_01_09"); //Dobře.
PashalQuestCaveStep = TRUE;
B_LogEntry(TOPIC_PashalQuest,"Milten mi řekl že mágové Ohně se ten artefakt snažily najít, dokonce jeden z nich byl pověřen speciálním posláním, bohužel bylo vše marné.");
Wld_InsertNpc(KDF_4569_AlexOne,"OW_ALEXONE");
};
instance DIA_MiltenOW_Erz(C_Info)
{
npc = PC_Mage_OW;
nr = 4;
condition = DIA_MiltenOW_Erz_Condition;
information = DIA_MiltenOW_Erz_Info;
permanent = FALSE;
description = "Kolik rudy jste zatím nashromáždili?";
};
func int DIA_MiltenOW_Erz_Condition()
{
if(Npc_KnowsInfo(other,DIA_MiltenOW_Bericht))
{
return TRUE;
};
};
func void DIA_MiltenOW_Erz_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Erz_15_00"); //Kolik rudy jste zatím nashromáždili?
AI_Output(self,other,"DIA_MiltenOW_Erz_03_01"); //Kolik rudy...? Ani jedinou bednu! Už před nějakou dobou jsme ztratili kontakt s kopáči.
AI_Output(self,other,"DIA_MiltenOW_Erz_03_02"); //Vůbec by mě nepřekvapilo, kdyby byli dávno mrtví. A ke všemu na nás útočí draci a oblehli nás skřeti!
AI_Output(self,other,"DIA_MiltenOW_Erz_03_03"); //Celá tahle expedice je naprostá katastrofa.
};
instance DIA_MiltenOW_Wo(C_Info)
{
npc = PC_Mage_OW;
nr = 5;
condition = DIA_MiltenOW_Wo_Condition;
information = DIA_MiltenOW_Wo_Info;
permanent = FALSE;
description = "Kde jsou teď Gorn a Diego?";
};
func int DIA_MiltenOW_Wo_Condition()
{
if(Npc_KnowsInfo(other,DIA_MiltenOW_Hello) && (Knows_Diego == TRUE))
{
return TRUE;
};
};
func void DIA_MiltenOW_Wo_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Wo_Forget_15_00"); //Kde jsou teď Gorn a Diego?
AI_Output(self,other,"DIA_MiltenOW_Wo_Forget_03_01"); //Inu, Gorn sedí tady v žaláři - bránil se zatčení.
AI_Output(self,other,"DIA_MiltenOW_Wo_Forget_03_02"); //Diega přiřadili ke skupině kopáčů - když tak se zeptej paladina Parcivala, ten dával ty skupiny dohromady.
KnowsAboutGorn = TRUE;
SearchForDiego = LOG_Running;
};
instance DIA_MiltenOW_Gorn(C_Info)
{
npc = PC_Mage_OW;
nr = 5;
condition = DIA_MiltenOW_Gorn_Condition;
information = DIA_MiltenOW_Gorn_Info;
permanent = FALSE;
description = "Pojďme osvobodit Gorna!";
};
func int DIA_MiltenOW_Gorn_Condition()
{
if((KnowsAboutGorn == TRUE) && (Kapitel == 2))
{
return TRUE;
};
};
func void DIA_MiltenOW_Gorn_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Gorn_15_00"); //Pojďme osvobodit Gorna!
AI_Output(self,other,"DIA_MiltenOW_Gorn_03_01"); //No, je tady jeden malý problém - Gorn je usvědčený trestanec.
AI_Output(self,other,"DIA_MiltenOW_Gorn_03_02"); //Ale když budeme mít štěstí, podaří se nám domluvit se s Garondem a vykoupit ho.
AI_Output(other,self,"DIA_MiltenOW_Gorn_15_03"); //Ano, možná...
AI_Output(self,other,"DIA_MiltenOW_Gorn_03_04"); //Udržuj mě v obraze.
Log_CreateTopic(TOPIC_RescueGorn,LOG_MISSION);
Log_SetTopicStatus(TOPIC_RescueGorn,LOG_Running);
B_LogEntry(TOPIC_RescueGorn,"Velitel Garond nechal Gorna zavřít. Snad tak trochu naletěl, a tak bychom mu měli pomoci z nesnází.");
};
instance DIA_MiltenOW_Preis(C_Info)
{
npc = PC_Mage_OW;
nr = 5;
condition = DIA_MiltenOW_Preis_Condition;
information = DIA_MiltenOW_Preis_Info;
permanent = FALSE;
description = "Garond chce za Gorna 1000 zlatých.";
};
func int DIA_MiltenOW_Preis_Condition()
{
if((MIS_RescueGorn == LOG_Running) && (Kapitel == 2))
{
return TRUE;
};
};
func void DIA_MiltenOW_Preis_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Preis_15_00"); //Garond chce za Gorna 1000 zlatých.
AI_Output(self,other,"DIA_MiltenOW_Preis_03_01"); //Hezká sumička. Můžu přispět 250 zlatými.
B_GiveInvItems(self,other,ItMi_Gold,250);
B_LogEntry(TOPIC_RescueGorn,"Milten mi dal 250 zlatých, abych zaplatil za Gornovo propuštění.");
};
instance DIA_MiltenOW_Mehr(C_Info)
{
npc = PC_Mage_OW;
nr = 5;
condition = DIA_MiltenOW_Mehr_Condition;
information = DIA_MiltenOW_Mehr_Info;
permanent = FALSE;
description = "Pokud mám Gorna vykoupit, budu potřebovat víc zlata.";
};
func int DIA_MiltenOW_Mehr_Condition()
{
if((MIS_RescueGorn == LOG_Running) && (Kapitel == 2) && (Npc_HasItems(other,ItMi_Gold) < 1000) && Npc_KnowsInfo(other,DIA_MiltenOW_Preis))
{
return TRUE;
};
};
func void DIA_MiltenOW_Mehr_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Mehr_15_00"); //Pokud mám Gorna vykoupit, budu potřebovat víc zlata.
AI_Output(self,other,"DIA_MiltenOW_Mehr_03_01"); //Víc zlata... hm. Diego o takových věcech ví dost - ale ten tady není.
AI_Output(self,other,"DIA_MiltenOW_Mehr_03_02"); //Možná si Gorn sám schoval nějaké zlato na horší časy - měli bychom se na to podívat.
AI_Output(self,other,"DIA_MiltenOW_Mehr_03_03"); //Napíšu mu vzkaz. Zkus mu ho nějak propašovat do žaláře.
B_GiveInvItems(self,other,ItWr_LetterForGorn_MIS,1);
B_LogEntry(TOPIC_RescueGorn,"Milten mi předal zprávu pro Gorna. Když mu ji nějak propašuji do vězení, může nám prozradit, jestli nemá někde ulité nějaké zlato.");
};
instance DIA_MiltenOW_Equipment(C_Info)
{
npc = PC_Mage_OW;
nr = 5;
condition = DIA_MiltenOW_Equipment_Condition;
information = DIA_MiltenOW_Equipment_Info;
permanent = FALSE;
description = "Mohl bys mi dát nějakou výbavu?";
};
func int DIA_MiltenOW_Equipment_Condition()
{
if(Npc_KnowsInfo(other,DIA_Garond_Equipment) && (other.guild == GIL_KDF))
{
return TRUE;
};
};
func void DIA_MiltenOW_Equipment_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Equipmentt_15_00"); //Mohl bys mi dát nějakou výbavu? Garond mě požádal, jestli bych se nevypravil do dolů.
AI_Output(self,other,"DIA_MiltenOW_Equipment_03_01"); //A kde bych to tak asi měl sehnat? Jediné, co ti můžu dát, je cenný runový kámen.
B_GiveInvItems(self,other,ItMi_RuneBlank,1);
};
instance DIA_MiltenOW_Versteck(C_Info)
{
npc = PC_Mage_OW;
nr = 1;
condition = DIA_MiltenOW_Versteck_Condition;
information = DIA_MiltenOW_Versteck_Info;
permanent = FALSE;
important = FALSE;
description = "Mám odpověď od Gorna...";
};
func int DIA_MiltenOW_Versteck_Condition()
{
if((GornsTreasure == TRUE) && (Npc_HasItems(other,ItMi_GornsTreasure_MIS) <= 0) && (Gorns_Beutel == FALSE) && (Kapitel == 2))
{
return TRUE;
};
};
func void DIA_MiltenOW_Versteck_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Versteck_15_00"); //Mám odpověď od Gorna. Říká, že zlato je u jižní brány.
AI_Output(self,other,"DIA_MiltenOW_Versteck_03_01"); //(trpce) Chtěl jsi říct u bývalé jižní brány. Ten drak z ní udělal hromadu suti.
AI_Output(other,self,"DIA_MiltenOW_Versteck_15_02"); //Jak se tam dostanu?
AI_Output(self,other,"DIA_MiltenOW_Versteck_03_03"); //Je to poblíž skřetího beranidla. Jižní brána byla napravo od něj.
AI_Output(self,other,"DIA_MiltenOW_Versteck_03_04"); //Nebude to nijak snadné - buď opatrný a pospěš si.
B_LogEntry(TOPIC_RescueGorn,"Bývalá jižní brána leží přímo naproti skřetím zátarasům. Gornovo zlato by mělo být někde tam.");
};
instance DIA_MiltenOW_Frei(C_Info)
{
npc = PC_Mage_OW;
nr = 5;
condition = DIA_MiltenOW_Frei_Condition;
information = DIA_MiltenOW_Frei_Info;
permanent = FALSE;
description = "Osvobodil jsem Gorna.";
};
func int DIA_MiltenOW_Frei_Condition()
{
if((MIS_RescueGorn == LOG_SUCCESS) && (Kapitel == 2))
{
return TRUE;
};
};
func void DIA_MiltenOW_Frei_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Frei_15_00"); //Osvobodil jsem Gorna.
AI_Output(self,other,"DIA_MiltenOW_Frei_03_01"); //Dobře. Měli bychom si promyslet, co bude dál.
};
instance DIA_MiltenOW_Lehren(C_Info)
{
npc = PC_Mage_OW;
nr = 9;
condition = DIA_MiltenOW_Lehren_Condition;
information = DIA_MiltenOW_Lehren_Info;
permanent = FALSE;
description = "Můžeš mě něčemu naučit?";
};
func int DIA_MiltenOW_Lehren_Condition()
{
if((other.guild == GIL_KDF) && (Kapitel == 2))
{
return TRUE;
};
};
func void DIA_MiltenOW_Lehren_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Lehren_15_00"); //Můžeš mě něčemu naučit?
AI_Output(self,other,"DIA_MiltenOW_Lehren_03_01"); //Mohu tě naučit trochu magie z druhého kruhu, případně ti také mohu pomoci zvýšit magické síly.
AI_Output(self,other,"DIA_MiltenOW_Lehren_03_02"); //Jestli jsi připravený na zvýšení magické síly, mohu tě začít učit.
};
instance DIA_MILTENOW_CASSIA(C_Info)
{
npc = PC_Mage_OW;
nr = 10;
condition = dia_miltenow_cassia_condition;
information = dia_miltenow_cassia_info;
permanent = FALSE;
description = "Asi bys nevěděl...";
};
func int dia_miltenow_cassia_condition()
{
if((MIS_CASSIAGOLDCUP == LOG_Running) && (Npc_HasItems(other,ItKe_OC_Store) == 0))
{
return TRUE;
};
};
func void dia_miltenow_cassia_info()
{
AI_Output(other,self,"DIA_Milten_Cassia_15_00"); //Asi bys nevěděl, kde je klíč od skladiště paladinů?
AI_Output(self,other,"DIA_Milten_Cassia_03_01"); //Jsi snad nějaký zloděj? No, stejně bys toho moc neodnesl.
AI_Output(self,other,"DIA_Milten_Cassia_03_02"); //Jednoho krásného dne se Engor šel projít na čerstvý vzduch a ten klíč ztratil - prostě se vrátil bez něj.
AI_Output(self,other,"DIA_Milten_Cassia_03_03"); //Myslím, že Garnod dříve nebo později dá ty dveře vyrazit a Engor je bude muset spravit.
AI_Output(self,other,"DIA_Milten_Cassia_03_04"); //Jo, ještě něco...
AI_Output(self,other,"DIA_Milten_Cassia_03_05"); //Jestli ten klíč najdeš, hoď ho do Engorova pokoje.
AI_Output(self,other,"DIA_Milten_Cassia_03_06"); //Bude to tak lepší, když ho najde.
AI_Output(other,self,"DIA_Milten_Cassia_15_07"); //Jasně.
B_LogEntry(TOPIC_CASSIAGOLDCUP,"Engor ztratil klíč od skladiště paladinů když se šel projít na čerstvý vzduch.");
MILTENSAYABOUTOCKEY = TRUE;
};
instance DIA_MiltenOW_TeachCircle2(C_Info)
{
npc = PC_Mage_OW;
nr = 91;
condition = DIA_MiltenOW_TeachCircle2_Condition;
information = DIA_MiltenOW_TeachCircle2_Info;
permanent = TRUE;
description = "Nauč mě druhý kruh magie. (VB: 30)";
};
func int DIA_MiltenOW_TeachCircle2_Condition()
{
if((other.guild == GIL_KDF) && Npc_KnowsInfo(other,DIA_MiltenOW_Lehren) && (Npc_GetTalentSkill(other,NPC_TALENT_MAGE) < 2) && (CanLearnMagicCircleNext_ABCZ(2) == TRUE))
{
return TRUE;
};
};
func void DIA_MiltenOW_TeachCircle2_Info()
{
AI_Output(other,self,"DIA_Milten_Add_15_00"); //Nauč mě druhý kruh magie!
AI_Output(self,other,"DIA_Milten_Add_03_01"); //Většinou to je privilegium vyhrazené učitelům našeho řádu.
AI_Output(self,other,"DIA_Milten_Add_03_02"); //Ale myslím, že v tomto případě můžeme udělat výjimku...
if(B_TeachMagicCircle(self,other,2))
{
AI_Output(self,other,"DIA_Milten_Add_03_03"); //Nevím, jestli si pamatuju ta oficiální slova správně...
AI_Output(self,other,"DIA_Milten_Add_03_04"); //Vstup nyní do Druhého kruhu. Ehm... Ukáže ti směr - cestu však budou tvořit skutky tvé - nebo tak nějak to bylo...
AI_Output(self,other,"DIA_Milten_Add_03_05"); //Myslím, že víš, co to má znamenat...
};
};
instance DIA_MiltenOW_Teach(C_Info)
{
npc = PC_Mage_OW;
nr = 90;
condition = DIA_MiltenOW_Teach_Condition;
information = DIA_MiltenOW_Teach_Info;
permanent = TRUE;
description = "Chci se naučit nějaká nová kouzla.";
};
func int DIA_MiltenOW_Teach_Condition()
{
if((other.guild == GIL_KDF) && Npc_KnowsInfo(other,DIA_MiltenOW_Lehren) && (Kapitel == 2))
{
return TRUE;
};
};
func void DIA_MiltenOW_Teach_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Teach_15_00"); //Chci se naučit nějaká nová kouzla.
if(Npc_GetTalentSkill(other,NPC_TALENT_MAGE) >= 2)
{
Info_ClearChoices(DIA_MiltenOW_Teach);
Info_AddChoice(DIA_MiltenOW_Teach,Dialog_Back,DIA_MiltenOW_Teach_BACK);
if(PLAYER_TALENT_RUNES[SPL_InstantFireball] == FALSE)
{
Info_AddChoice(DIA_MiltenOW_Teach,b_buildlearnstringforrunes(NAME_SPL_InstantFireball,B_GetLearnCostTalent(other,NPC_TALENT_RUNES,SPL_InstantFireball)),DIA_MiltenOW_Teach_Feuerball);
};
if((PLAYER_TALENT_RUNES[SPL_RapidFirebolt] == FALSE) && (LegoSpells == TRUE))
{
Info_AddChoice(DIA_MiltenOW_Teach,b_buildlearnstringforrunes(NAME_SPL_RapidFirebolt,B_GetLearnCostTalent(other,NPC_TALENT_RUNES,SPL_RapidFirebolt)),DIA_MiltenOW_Teach_RapidFirebolt);
};
}
else
{
AI_Output(self,other,"DIA_MiltenOW_Teach_03_01"); //Ještě jsi nevstoupil do Druhého kruhu magie. Nemůžu tě nic naučit.
};
};
func void DIA_MiltenOW_Teach_BACK()
{
Info_ClearChoices(DIA_MiltenOW_Teach);
};
func void DIA_MiltenOW_Teach_Feuerball()
{
B_TeachPlayerTalentRunes(self,other,SPL_InstantFireball);
};
func void DIA_MiltenOW_Teach_RapidFirebolt()
{
B_TeachPlayerTalentRunes(self,other,SPL_RapidFirebolt);
};
instance DIA_MiltenOW_Mana(C_Info)
{
npc = PC_Mage_OW;
nr = 100;
condition = DIA_MiltenOW_Mana_Condition;
information = DIA_MiltenOW_Mana_Info;
permanent = TRUE;
description = "Chtěl bych posílit svoji magickou moc.";
};
func int DIA_MiltenOW_Mana_Condition()
{
if((other.guild == GIL_KDF) && Npc_KnowsInfo(other,DIA_MiltenOW_Lehren) && (Kapitel == 2))
{
return TRUE;
};
};
func void DIA_MiltenOW_Mana_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Mana_15_00"); //Chtěl bych posílit svoji magickou moc.
Info_ClearChoices(DIA_MiltenOW_Mana);
Info_AddChoice(DIA_MiltenOW_Mana,Dialog_Back,DIA_MiltenOW_Mana_BACK);
Info_AddChoice(DIA_MiltenOW_Mana,b_buildlearnstringforskills(PRINT_LearnMANA1,B_GetLearnCostAttribute(other,ATR_MANA_MAX)),DIA_MiltenOW_Mana_1);
Info_AddChoice(DIA_MiltenOW_Mana,b_buildlearnstringforskills(PRINT_LearnMANA5,B_GetLearnCostAttribute(other,ATR_MANA_MAX) * 5),DIA_MiltenOW_Mana_5);
};
func void DIA_MiltenOW_Mana_BACK()
{
if(other.attribute[ATR_MANA_MAX] >= T_MED)
{
AI_Output(self,other,"DIA_MiltenOW_Mana_03_00"); //Tvoje magická síla je veliká. Příliš velká na to, abych ti ji mohl pomoci ještě zvýšit.
};
Info_ClearChoices(DIA_MiltenOW_Mana);
};
func void DIA_MiltenOW_Mana_1()
{
B_TeachAttributePoints(self,other,ATR_MANA_MAX,1,T_MED);
Info_ClearChoices(DIA_MiltenOW_Mana);
Info_AddChoice(DIA_MiltenOW_Mana,Dialog_Back,DIA_MiltenOW_Mana_BACK);
Info_AddChoice(DIA_MiltenOW_Mana,b_buildlearnstringforskills(PRINT_LearnMANA1,B_GetLearnCostAttribute(other,ATR_MANA_MAX)),DIA_MiltenOW_Mana_1);
Info_AddChoice(DIA_MiltenOW_Mana,b_buildlearnstringforskills(PRINT_LearnMANA5,B_GetLearnCostAttribute(other,ATR_MANA_MAX) * 5),DIA_MiltenOW_Mana_5);
};
func void DIA_MiltenOW_Mana_5()
{
B_TeachAttributePoints(self,other,ATR_MANA_MAX,5,T_MED);
Info_ClearChoices(DIA_MiltenOW_Mana);
Info_AddChoice(DIA_MiltenOW_Mana,Dialog_Back,DIA_MiltenOW_Mana_BACK);
Info_AddChoice(DIA_MiltenOW_Mana,b_buildlearnstringforskills(PRINT_LearnMANA1,B_GetLearnCostAttribute(other,ATR_MANA_MAX)),DIA_MiltenOW_Mana_1);
Info_AddChoice(DIA_MiltenOW_Mana,b_buildlearnstringforskills(PRINT_LearnMANA5,B_GetLearnCostAttribute(other,ATR_MANA_MAX) * 5),DIA_MiltenOW_Mana_5);
};
instance DIA_MiltenOW_Perm(C_Info)
{
npc = PC_Mage_OW;
nr = 101;
condition = DIA_MiltenOW_Perm_Condition;
information = DIA_MiltenOW_Perm_Info;
permanent = TRUE;
description = "Co tady máš za úkol?";
};
func int DIA_MiltenOW_Perm_Condition()
{
if((Kapitel == 2) && (Npc_KnowsInfo(other,DIA_MiltenOW_Frei) == FALSE))
{
return TRUE;
};
};
func void DIA_MiltenOW_Perm_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Perm_15_00"); //Co tady máš za úkol?
AI_Output(self,other,"DIA_MiltenOW_Perm_03_01"); //Původně jsem měl provádět rozbor magické rudy. Zatím jsme jí ale moc nedostali.
AI_Output(self,other,"DIA_MiltenOW_Perm_03_02"); //Teď se soustřeďuji na studium alchymie.
};
instance DIA_MiltenOW_Plan(C_Info)
{
npc = PC_Mage_OW;
nr = 101;
condition = DIA_MiltenOW_Plan_Condition;
information = DIA_MiltenOW_Plan_Info;
permanent = TRUE;
description = "Co máš v plánu?";
};
func int DIA_MiltenOW_Plan_Condition()
{
if((Kapitel == 2) && Npc_KnowsInfo(other,DIA_MiltenOW_Frei))
{
return TRUE;
};
};
func void DIA_MiltenOW_Plan_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Plan_15_00"); //Co máš v plánu?
AI_Output(self,other,"DIA_MiltenOW_Plan_03_01"); //Vrátím se. Chvíli ještě počkám, ale teď, když je Gorn na svobodě, můžu vyrazit společně s ním.
AI_Output(self,other,"DIA_MiltenOW_Plan_03_02"); //Je naprosto nezbytné, aby se Pyrokar dozvěděl, jak to tady vypadá.
AI_Output(other,self,"DIA_MiltenOW_Plan_15_03"); //Když myslíš.
AI_Output(self,other,"DIA_MiltenOW_Plan_03_04"); //Doufám, že lord Hagen rozpozná, co za hrozbu vychází z tohoto údolí. Lepší si nepředstavovat, co by se stalo, kdyby skřeti přešli přes průsmyk.
AI_Output(other,self,"DIA_MiltenOW_Plan_15_05"); //No, v tom případě ti přeju bezpečnou cestu.
};
instance DIA_MiltenOW_Baby(C_Info)
{
npc = PC_Mage_OW;
nr = 101;
condition = DIA_MiltenOW_Baby_Condition;
information = DIA_MiltenOW_Baby_Info;
permanent = FALSE;
description = "Mám pro tebe zvláštní prosbu.";
};
func int DIA_MiltenOW_Baby_Condition()
{
if((Kapitel < 3) && (MIS_BrutusBaby == LOG_Running))
{
return TRUE;
};
};
func void DIA_MiltenOW_Baby_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Baby_01_00"); //Mám pro tebe zvláštní prosbu.
AI_Output(self,other,"DIA_MiltenOW_Baby_01_01"); //Tak mluv, víš pro kamaráda udělám vždy co bude v mích silách.
AI_Output(other,self,"DIA_MiltenOW_Baby_01_02"); //Jeden chlápek z hradu... mě požádal, abych tě požádal, abys vyčaroval ženu pro něj a jeho kamarády.
AI_Output(other,self,"DIA_MiltenOW_Baby_01_03"); //No víš co tím myslím.
AI_Output(self,other,"DIA_MiltenOW_Baby_01_04"); //(zmatený) Po pravdě řečeno bych od tebe nečekal takový zvěrstva.
AI_Output(other,self,"DIA_MiltenOW_Baby_01_05"); //Takže jim můžeš pomoct?
AI_Output(self,other,"DIA_MiltenOW_Baby_01_06"); //No... Já jsem v takových případech... ne příliš zkušený. Ale když se ptáš, zkusím něco vymyslet.
AI_Output(other,self,"DIA_MiltenOW_Baby_01_07"); //Vynikající! Jsem si jistý že kluci budou prostě přešťastný. Kdy to bude?
AI_Output(self,other,"DIA_MiltenOW_Baby_01_08"); //Myslím že zítra večer, ne dříve. Musím se dobře připravit.
AI_Output(other,self,"DIA_MiltenOW_Baby_01_09"); //Tak předem děkuju.
B_LogEntry(TOPIC_BrutusBaby,"Je ironií že Milten souhlasil že pomůže. Podle něj se v odpoledních hodinách zítra připraví a potom vykouzlí krásku.");
AI_StopProcessInfos(self);
};
instance DIA_MiltenOW_Baby_Done(C_Info)
{
npc = PC_Mage_OW;
nr = 101;
condition = DIA_MiltenOW_Baby_Done_Condition;
information = DIA_MiltenOW_Baby_Done_Info;
permanent = FALSE;
description = "Všechno připraveno?";
};
func int DIA_MiltenOW_Baby_Done_Condition()
{
if((Kapitel < 3) && (MIS_BrutusBaby == LOG_Running) && (BrutusGoParty == TRUE) && (BrutusGoPartyNever == FALSE) && (Npc_GetDistToWP(self,"OC_DRAGO") <= 500))
{
return TRUE;
};
};
func void DIA_MiltenOW_Baby_Done_Info()
{
AI_Output(other,self,"DIA_MiltenOW_Baby_Done_01_00"); //Všechno připraveno?
AI_Output(self,other,"DIA_MiltenOW_Baby_Done_01_01"); //Ano, všechny přípravky jsou dokončeny. Zbývá jen přečíst kouzlo.
AI_Output(other,self,"DIA_MiltenOW_Baby_Done_01_02"); //Tak ho přečti.
AI_Output(self,other,"DIA_MiltenOW_Baby_Done_01_03"); //Je lepší to udělat takhle protože musím udržovat koncentraci během toho všeho.
AI_Output(self,other,"DIA_MiltenOW_Baby_Done_01_04"); //Tady, vem si tenhle svitek, mluví za vše.
B_GiveInvItems(self,other,ItWr_MiltenSummon,1);
AI_Output(other,self,"DIA_MiltenOW_Baby_Done_01_05"); //Dobře, pojď sem.
Info_ClearChoices(DIA_MiltenOW_Baby_Done);
Info_AddChoice(DIA_MiltenOW_Baby_Done,"Použít svitek...",DIA_MiltenOW_Baby_Done_Do);
};
func void DIA_MiltenOW_Baby_Done_Do()
{
B_GivePlayerXP(500);
Npc_RemoveInvItems(other,ItWr_MiltenSummon,1);
B_HeroUseFakeScroll();
MIS_BrutusBaby = LOG_Success;
Log_SetTopicStatus(TOPIC_BrutusBaby,LOG_Success);
B_LogEntry(TOPIC_BrutusBaby,"Vypadá to že Milten něco zpackal v kouzle. Místo krásných dívek uprostřed obrovského pentagramu se objevil arcidémon. Nicméně je to neškodné.");
MiltenSummon = TRUE;
AI_StopProcessInfos(self);
Wld_InsertNpc(Demon_Lord_Milten,"OC_MAGE_CENTER");
};
| D |
INSTANCE Swampshark_Weiss (Npc_Default)
{
// ------ NSC ------
name = "Weißer Sumpfhai";
guild = GIL_SWAMPSHARK;
id = 11024;
voice = 18;
npctype = NPCTYPE_MAIN;
// ------ Attribute ------
B_SetAttributesToChapter (self, 5);
// ------ Kampf-Taktik ------
fight_tactic = FAI_SWAMPSHARK;
// ------ Equippte Waffen ------
// ------ Inventory ------
// Händler
// ------ visuals ------
Mdl_SetVisual (self, "Swampshark.mds");
// Body-Mesh Body-Tex Skin-Color Head-MMS Head-Tex Teeth-Tex ARMOR
Mdl_SetVisualBody (self, "Swa_Body", 6, DEFAULT, "", DEFAULT, DEFAULT, -1);
Npc_SetToFistMode(self);
aivar[AIV_FightDistCancel] = FIGHT_DIST_CANCEL;
senses = SENSE_HEAR | SENSE_SEE | SENSE_SMELL;
senses_range = PERC_DIST_MONSTER_ACTIVE_MAX;
aivar[AIV_MM_FollowTime] = FOLLOWTIME_MEDIUM;
aivar[AIV_MM_FollowInWater] = TRUE;
aivar[AIV_MM_Packhunter] = FALSE;
// ------ TA anmelden ------
daily_routine = Rtn_Start_11024;
};
FUNC VOID Rtn_Start_11024 ()
{
TA_Roam (05,00,00,00,"ADW_SHARK_09");
TA_Roam (00,00,05,00,"ADW_SHARK_09");
};
FUNC VOID Rtn_Tot_11024 ()
{
TA_Roam (05,00,00,00,"TOT");
TA_Roam (00,00,05,00,"TOT");
}; | D |
src/norimaki.ml: Array Csv Printf
| D |
/*******************************************************************************
@file UChar.d
Copyright (c) 2004 Kris Bell
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for damages
of any kind arising from the use of this software.
Permission is hereby granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and/or
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 within documentation of
said product 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 distribution
of the source.
4. Derivative works are permitted, but they must carry this notice
in full and credit the original source.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@version Initial version, October 2004
@author Kris
Note that this package and documentation is built around the ICU
project (http://oss.software.ibm.com/icu/). Below is the license
statement as specified by that software:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ICU License - ICU 1.8.1 and later
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 1995-2003 International Business Machines Corporation and
others.
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, and/or sell copies of the Software, and to permit persons
to whom the Software is furnished to do so, provided that the above
copyright notice(s) and this permission notice appear in all copies of
the Software and that both the above copyright notice(s) and this
permission notice appear in supporting documentation.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder
shall not be used in advertising or otherwise to promote the sale, use
or other dealings in this Software without prior written authorization
of the copyright holder.
----------------------------------------------------------------------
All trademarks and registered trademarks mentioned herein are the
property of their respective owners.
*******************************************************************************/
module com.ibm.icu.mangoicu.UChar;
private import com.ibm.icu.mangoicu.ICU;
/*******************************************************************************
This API provides low-level access to the Unicode Character
Database. In addition to raw property values, some convenience
functions calculate derived properties, for example for Java-style
programming.
Unicode assigns each code point (not just assigned character)
values for many properties. Most of them are simple boolean
flags, or constants from a small enumerated list. For some
properties, values are strings or other relatively more complex
types.
For more information see "About the Unicode Character Database"
(http://www.unicode.org/ucd/) and the ICU User Guide chapter on
Properties (http://oss.software.ibm.com/icu/userguide/properties.html).
Many functions are designed to match java.lang.Character functions.
See the individual function documentation, and see the JDK 1.4.1
java.lang.Character documentation at
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Character.html
There are also functions that provide easy migration from C/POSIX
functions like isblank(). Their use is generally discouraged because
the C/POSIX standards do not define their semantics beyond the ASCII
range, which means that different implementations exhibit very different
behavior. Instead, Unicode properties should be used directly.
There are also only a few, broad C/POSIX character classes, and they
tend to be used for conflicting purposes. For example, the "isalpha()"
class is sometimes used to determine word boundaries, while a more
sophisticated approach would at least distinguish initial letters from
continuation characters (the latter including combining marks). (In
ICU, BreakIterator is the most sophisticated API for word boundaries.)
Another example: There is no "istitle()" class for titlecase characters.
A summary of the behavior of some C/POSIX character classification
implementations for Unicode is available at
http://oss.software.ibm.com/cvs/icu/~checkout~/icuhtml/design/posix_classes.html
See <A HREF="http://oss.software.ibm.com/icu/apiref/uchar_8h.html">
this page</A> for full details.
*******************************************************************************/
class UChar : ICU
{
public enum Property
{
Alphabetic = 0,
BinaryStart = Alphabetic,
AsciiHexDigit,
BidiControl,
BidiMirrored,
Dash,
DefaultIgnorableCodePoint,
Deprecated,
Diacritic,
Extender,
FullCompositionExclusion,
GraphemeBase,
GraphemeExtend,
GraphemeLink,
HexDigit,
Hyphen,
IdContinue,
IdStart,
Ideographic,
IdsBinaryOperator,
IdsTrinaryOperator,
JoinControl,
LogicalOrderException,
Lowercase,
Math,
NoncharacterCodePoint,
QuotationMark,
Radical,
SoftDotted,
TerminalPunctuation,
UnifiedIdeograph,
Uppercase,
WhiteSpace,
XidContinue,
XidStart,
CaseSensitive,
STerm,
VariationSelector,
NfdInert,
NfkdInert,
NfcInert,
NfkcInert,
SegmentStarter,
BinaryLimit,
BidiClass = 0x1000,
IntStart = BidiClass,
Block, CanonicalCombiningClass,
DecompositionType,
EastAsianWidth,
GeneralCategory,
JoiningGroup,
JoiningType,
LineBreak,
NumericType,
Script,
HangulSyllableType,
NfdQuickCheck,
NfkdQuickCheck,
NfcQuickCheck,
NfkcQuickCheck,
LeadCanonicalCombiningClass,
TrailCanonicalCombiningClass,
IntLimit,
GeneralCategoryMask = 0x2000,
MaskStart = GeneralCategoryMask,
MaskLimit,
NumericValue = 0x3000,
DoubleStart = NumericValue,
DoubleLimit,
Age = 0x4000,
StringStart = Age,
BidiMirroringGlyph,
CaseFolding,
IsoComment,
LowercaseMapping,
Name,
SimpleCaseFolding,
SimpleLowercaseMapping,
SimpleTitlecaseMapping,
SimpleUppercaseMapping,
TitlecaseMapping,
Unicode1Name,
UppercaseMapping,
StringLimit,
InvalidCode = -1
}
public enum Category
{
Unassigned = 0,
GeneralOtherTypes = 0,
UppercaseLetter = 1,
LowercaseLetter = 2,
TitlecaseLetter = 3,
ModifierLetter = 4,
OtherLetter = 5,
NonSpacingMark = 6,
EnclosingMark = 7,
CombiningSpacingMark = 8,
DecimalDigitNumber = 9,
LetterNumber = 10,
OtherNumber = 11,
SpaceSeparator = 12,
LineSeparator = 13,
ParagraphSeparator = 14,
ControlChar = 15,
FormatChar = 16,
PrivateUseChar = 17,
Surrogate = 18,
DashPunctuation = 19,
StartPunctuation = 20,
EndPunctuation = 21,
ConnectorPunctuation = 22,
OtherPunctuation = 23,
MathSymbol = 24,
CurrencySymbol = 25,
ModifierSymbol = 26,
OtherSymbol = 27,
InitialPunctuation = 28,
FinalPunctuation = 29,
Count
}
public enum Direction
{
LeftToRight = 0,
RightToLeft = 1,
EuropeanNumber = 2,
EuropeanNumberSeparator = 3,
EuropeanNumberTerminator = 4,
ArabicNumber = 5,
CommonNumberSeparator = 6,
BlockSeparator = 7,
SegmentSeparator = 8,
WhiteSpaceNeutral = 9,
OtherNeutral = 10,
LeftToRightEmbedding = 11,
LeftToRightOverride = 12,
RightToLeftArabic = 13,
RightToLeftEmbedding = 14,
RightToLeftOverride = 15,
PopDirectionalFormat = 16,
DirNonSpacingMark = 17,
BoundaryNeutral = 18,
Count
}
public enum BlockCode
{
NoBlock = 0,
BasicLatin = 1,
Latin1Supplement = 2,
LatinExtendedA = 3,
LatinExtendedB = 4,
IpaExtensions = 5,
SpacingModifierLetters = 6,
CombiningDiacriticalMarks = 7,
Greek = 8,
Cyrillic = 9,
Armenian = 10,
Hebrew = 11,
Arabic = 12,
Syriac = 13,
Thaana = 14,
Devanagari = 15,
Bengali = 16,
Gurmukhi = 17,
Gujarati = 18,
Oriya = 19,
Tamil = 20,
Telugu = 21,
Kannada = 22,
Malayalam = 23,
Sinhala = 24,
Thai = 25,
Lao = 26,
Tibetan = 27,
Myanmar = 28,
Georgian = 29,
HangulJamo = 30,
Ethiopic = 31,
Cherokee = 32,
UnifiedCanadianAboriginalSyllabics = 33,
Ogham = 34,
Runic = 35,
Khmer = 36,
Mongolian = 37,
LatinExtendedAdditional = 38,
GreekExtended = 39,
GeneralPunctuation = 40,
SuperscriptsAndSubscripts = 41,
CurrencySymbols = 42,
CombiningMarksForSymbols = 43,
LetterlikeSymbols = 44,
NumberForms = 45,
Arrows = 46,
MathematicalOperators = 47,
MiscellaneousTechnical = 48,
ControlPictures = 49,
OpticalCharacterRecognition = 50,
EnclosedAlphanumerics = 51,
BoxDrawing = 52,
BlockElements = 53,
GeometricShapes = 54,
MiscellaneousSymbols = 55,
Dingbats = 56,
BraillePatterns = 57,
CjkRadicalsSupplement = 58,
KangxiRadicals = 59,
IdeographicDescriptionCharacters = 60,
CjkSymbolsAndPunctuation = 61,
Hiragana = 62,
Katakana = 63,
Bopomofo = 64,
HangulCompatibilityJamo = 65,
Kanbun = 66,
BopomofoExtended = 67,
EnclosedCjkLettersAndMonths = 68,
CjkCompatibility = 69,
CjkUnifiedIdeographsExtensionA = 70,
CjkUnifiedIdeographs = 71,
YiSyllables = 72,
YiRadicals = 73,
HangulSyllables = 74,
HighSurrogates = 75,
HighPrivateUseSurrogates = 76,
LowSurrogates = 77,
PrivateUse = 78,
PrivateUseArea = PrivateUse,
CjkCompatibilityIdeographs = 79,
AlphabeticPresentationForms = 80,
ArabicPresentationFormsA = 81,
CombiningHalfMarks = 82,
CjkCompatibilityForms = 83,
SmallFormVariants = 84,
ArabicPresentationFormsB = 85,
Specials = 86,
HalfwidthAndFullwidthForms = 87,
OldItalic = 88,
Gothic = 89,
Deseret = 90,
ByzantineMusicalSymbols = 91,
MusicalSymbols = 92,
MathematicalAlphanumericSymbols = 93,
CjkUnifiedIdeographsExtensionB = 94,
CjkCompatibilityIdeographsSupplement = 95,
Tags = 96,
CyrillicSupplementary = 97,
CyrillicSupplement = CyrillicSupplementary,
Tagalog = 98,
Hanunoo = 99,
Buhid = 100,
Tagbanwa = 101,
MiscellaneousMathematicalSymbolsA = 102,
SupplementalArrowsA = 103,
SupplementalArrowsB = 104,
MiscellaneousMathematicalSymbolsB = 105,
SupplementalMathematicalOperators = 106,
KatakanaPhoneticExtensions = 107,
VariationSelectors = 108,
SupplementaryPrivateUseAreaA = 109,
SupplementaryPrivateUseAreaB = 110,
Limbu = 111,
TaiLe = 112,
KhmerSymbols = 113,
PhoneticExtensions = 114,
MiscellaneousSymbolsAndArrows = 115,
YijingHexagramSymbols = 116,
LinearBSyllabary = 117,
LinearBIdeograms = 118,
AegeanNumbers = 119,
Ugaritic = 120,
Shavian = 121,
Osmanya = 122,
CypriotSyllabary = 123,
TaiXuanJingSymbols = 124,
VariationSelectorsSupplement = 125,
Count,
InvalidCode = -1
}
public enum EastAsianWidth
{
Neutral,
Ambiguous,
Halfwidth,
Fullwidth,
Narrow,
Wide,
Count
}
public enum CharNameChoice
{
Unicode,
Unicode10,
Extended,
Count
}
public enum NameChoice
{
Short,
Long,
Count
}
public enum DecompositionType
{
None,
Canonical,
Compat,
Circle,
Final,
Font,
Fraction,
Initial,
Isolated,
Medial,
Narrow,
Nobreak,
Small,
Square,
Sub,
Super,
Vertical,
Wide,
Count
}
public enum JoiningType
{
NonJoining,
JoinCausing,
DualJoining,
LeftJoining,
RightJoining,
Transparent,
Count
}
public enum JoiningGroup
{
NoJoiningGroup,
Ain,
Alaph,
Alef,
Beh,
Beth,
Dal,
DalathRish,
E,
Feh,
FinalSemkath,
Gaf,
Gamal,
Hah,
HamzaOnHehGoal,
He,
Heh,
HehGoal,
Heth,
Kaf,
Kaph,
KnottedHeh,
Lam,
Lamadh,
Meem,
Mim,
Noon,
Nun,
Pe,
Qaf,
Qaph,
Reh,
Reversed_Pe,
Sad,
Sadhe,
Seen,
Semkath,
Shin,
Swash_Kaf,
Syriac_Waw,
Tah,
Taw,
Teh_Marbuta,
Teth,
Waw,
Yeh,
Yeh_Barree,
Yeh_With_Tail,
Yudh,
Yudh_He,
Zain,
Fe,
Khaph,
Zhain,
Count
}
public enum LineBreak
{
Unknown,
Ambiguous,
Alphabetic,
BreakBoth,
BreakAfter,
BreakBefore,
MandatoryBreak,
ContingentBreak,
ClosePunctuation,
CombiningMark,
CarriageReturn,
Exclamation,
Glue,
Hyphen,
Ideographic,
Inseperable,
Inseparable = Inseperable,
InfixNumeric,
LineFeed,
Nonstarter,
Numeric,
OpenPunctuation,
PostfixNumeric,
PrefixNumeric,
Quotation,
ComplexContext,
Surrogate,
Space,
BreakSymbols,
Zwspace,
NextLine,
WordJoiner,
Count
}
public enum NumericType
{
None,
Decimal,
Digit,
Numeric,
Count
}
public enum HangulSyllableType
{
NotApplicable,
LeadingJamo,
VowelJamo,
TrailingJamo,
LvSyllable,
LvtSyllable,
Count
}
/***********************************************************************
Get the property value for an enumerated or integer
Unicode property for a code point. Also returns binary
and mask property values.
Unicode, especially in version 3.2, defines many more
properties than the original set in UnicodeData.txt.
The properties APIs are intended to reflect Unicode
properties as defined in the Unicode Character Database
(UCD) and Unicode Technical Reports (UTR). For details
about the properties see http://www.unicode.org/ . For
names of Unicode properties see the file PropertyAliases.txt
***********************************************************************/
uint getProperty (dchar c, Property p)
{
return u_getIntPropertyValue (cast(uint) c, cast(uint) p);
}
/***********************************************************************
Get the minimum value for an enumerated/integer/binary
Unicode property
***********************************************************************/
uint getPropertyMinimum (Property p)
{
return u_getIntPropertyMinValue (p);
}
/***********************************************************************
Get the maximum value for an enumerated/integer/binary
Unicode property
***********************************************************************/
uint getPropertyMaximum (Property p)
{
return u_getIntPropertyMaxValue (p);
}
/***********************************************************************
Returns the bidirectional category value for the code
point, which is used in the Unicode bidirectional algorithm
(UAX #9 http://www.unicode.org/reports/tr9/).
***********************************************************************/
Direction charDirection (dchar c)
{
return cast(Direction) u_charDirection (c);
}
/***********************************************************************
Returns the Unicode allocation block that contains the
character
***********************************************************************/
BlockCode getBlockCode (dchar c)
{
return cast(BlockCode) ublock_getCode (c);
}
/***********************************************************************
Retrieve the name of a Unicode character.
***********************************************************************/
char[] getCharName (dchar c, CharNameChoice choice, ref char[] dst)
{
UErrorCode e;
uint len = u_charName (c, choice, dst.ptr, dst.length, e);
testError (e, "failed to extract char name (buffer too small?)");
return dst [0..len];
}
/***********************************************************************
Get the ISO 10646 comment for a character.
***********************************************************************/
char[] getComment (dchar c, ref char[] dst)
{
UErrorCode e;
uint len = u_getISOComment (c, dst.ptr, dst.length, e);
testError (e, "failed to extract comment (buffer too small?)");
return dst [0..len];
}
/***********************************************************************
Find a Unicode character by its name and return its code
point value.
***********************************************************************/
dchar charFromName (CharNameChoice choice, char[] name)
{
UErrorCode e;
dchar c = u_charFromName (choice, toString(name), e);
testError (e, "failed to locate char name");
return c;
}
/***********************************************************************
Return the Unicode name for a given property, as given in the
Unicode database file PropertyAliases.txt
***********************************************************************/
char[] getPropertyName (Property p, NameChoice choice)
{
return toArray (u_getPropertyName (p, choice));
}
/***********************************************************************
Return the Unicode name for a given property value, as given
in the Unicode database file PropertyValueAliases.txt.
***********************************************************************/
char[] getPropertyValueName (Property p, NameChoice choice, uint value)
{
return toArray (u_getPropertyValueName (p, value, choice));
}
/***********************************************************************
Gets the Unicode version information
***********************************************************************/
void getUnicodeVersion (ref Version v)
{
u_getUnicodeVersion (v);
}
/***********************************************************************
Get the "age" of the code point
***********************************************************************/
void getCharAge (dchar c, ref Version v)
{
u_charAge (c, v);
}
/***********************************************************************
These are externalised directly to the client (sans wrapper),
but this may have to change for linux, depending upon the
ICU function-naming conventions within the Posix libraries.
***********************************************************************/
static extern (C)
{
/***************************************************************
Check if a code point has the Alphabetic Unicode
property.
***************************************************************/
bool function (dchar c) isUAlphabetic;
/***************************************************************
Check if a code point has the Lowercase Unicode
property.
***************************************************************/
bool function (dchar c) isULowercase;
/***************************************************************
Check if a code point has the Uppercase Unicode
property.
***************************************************************/
bool function (dchar c) isUUppercase;
/***************************************************************
Check if a code point has the White_Space Unicode
property.
***************************************************************/
bool function (dchar c) isUWhiteSpace;
/***************************************************************
Determines whether the specified code point has the
general category "Ll" (lowercase letter).
***************************************************************/
bool function (dchar c) isLower;
/***************************************************************
Determines whether the specified code point has the
general category "Lu" (uppercase letter).
***************************************************************/
bool function (dchar c) isUpper;
/***************************************************************
Determines whether the specified code point is a
titlecase letter.
***************************************************************/
bool function (dchar c) isTitle;
/***************************************************************
Determines whether the specified code point is a
digit character according to Java.
***************************************************************/
bool function (dchar c) isDigit;
/***************************************************************
Determines whether the specified code point is a
letter character.
***************************************************************/
bool function (dchar c) isAlpha;
/***************************************************************
Determines whether the specified code point is an
alphanumeric character (letter or digit) according
to Java.
***************************************************************/
bool function (dchar c) isAlphaNumeric;
/***************************************************************
Determines whether the specified code point is a
hexadecimal digit.
***************************************************************/
bool function (dchar c) isHexDigit;
/***************************************************************
Determines whether the specified code point is a
punctuation character.
***************************************************************/
bool function (dchar c) isPunct;
/***************************************************************
Determines whether the specified code point is a
"graphic" character (printable, excluding spaces).
***************************************************************/
bool function (dchar c) isGraph;
/***************************************************************
Determines whether the specified code point is a
"blank" or "horizontal space", a character that
visibly separates words on a line.
***************************************************************/
bool function (dchar c) isBlank;
/***************************************************************
Determines whether the specified code point is
"defined", which usually means that it is assigned
a character.
***************************************************************/
bool function (dchar c) isDefined;
/***************************************************************
Determines if the specified character is a space
character or not.
***************************************************************/
bool function (dchar c) isSpace;
/***************************************************************
Determine if the specified code point is a space
character according to Java.
***************************************************************/
bool function (dchar c) isJavaSpaceChar;
/***************************************************************
Determines if the specified code point is a whitespace
character according to Java/ICU.
***************************************************************/
bool function (dchar c) isWhiteSpace;
/***************************************************************
Determines whether the specified code point is a
control character (as defined by this function).
***************************************************************/
bool function (dchar c) isCtrl;
/***************************************************************
Determines whether the specified code point is an ISO
control code.
***************************************************************/
bool function (dchar c) isISOControl;
/***************************************************************
Determines whether the specified code point is a
printable character.
***************************************************************/
bool function (dchar c) isPrint;
/***************************************************************
Determines whether the specified code point is a
base character.
***************************************************************/
bool function (dchar c) isBase;
/***************************************************************
Determines if the specified character is permissible
as the first character in an identifier according to
Unicode (The Unicode Standard, Version 3.0, chapter
5.16 Identifiers).
***************************************************************/
bool function (dchar c) isIDStart;
/***************************************************************
Determines if the specified character is permissible
in an identifier according to Java.
***************************************************************/
bool function (dchar c) isIDPart;
/***************************************************************
Determines if the specified character should be
regarded as an ignorable character in an identifier,
according to Java.
***************************************************************/
bool function (dchar c) isIDIgnorable;
/***************************************************************
Determines if the specified character is permissible
as the first character in a Java identifier.
***************************************************************/
bool function (dchar c) isJavaIDStart;
/***************************************************************
Determines if the specified character is permissible
in a Java identifier.
***************************************************************/
bool function (dchar c) isJavaIDPart;
/***************************************************************
Determines whether the code point has the
Bidi_Mirrored property.
***************************************************************/
bool function (dchar c) isMirrored;
/***************************************************************
Returns the decimal digit value of a decimal digit
character.
***************************************************************/
ubyte function (dchar c) charDigitValue;
/***************************************************************
Maps the specified character to a "mirror-image"
character.
***************************************************************/
dchar function (dchar c) charMirror;
/***************************************************************
Returns the general category value for the code point.
***************************************************************/
ubyte function (dchar c) charType;
/***************************************************************
Returns the combining class of the code point as
specified in UnicodeData.txt.
***************************************************************/
ubyte function (dchar c) getCombiningClass;
/***************************************************************
The given character is mapped to its lowercase
equivalent according to UnicodeData.txt; if the
character has no lowercase equivalent, the
character itself is returned.
***************************************************************/
dchar function (dchar c) toLower;
/***************************************************************
The given character is mapped to its uppercase equivalent
according to UnicodeData.txt; if the character has no
uppercase equivalent, the character itself is returned.
***************************************************************/
dchar function (dchar c) toUpper;
/***************************************************************
The given character is mapped to its titlecase
equivalent according to UnicodeData.txt; if none
is defined, the character itself is returned.
***************************************************************/
dchar function (dchar c) toTitle;
/***************************************************************
The given character is mapped to its case folding
equivalent according to UnicodeData.txt and
CaseFolding.txt; if the character has no case folding
equivalent, the character itself is returned.
***************************************************************/
dchar function (dchar c, uint options) foldCase;
/***************************************************************
Returns the decimal digit value of the code point in
the specified radix.
***************************************************************/
uint function (dchar ch, ubyte radix) digit;
/***************************************************************
Determines the character representation for a specific
digit in the specified radix.
***************************************************************/
dchar function (uint digit, ubyte radix) forDigit;
/***************************************************************
Get the numeric value for a Unicode code point as
defined in the Unicode Character Database.
***************************************************************/
double function (dchar c) getNumericValue;
}
/***********************************************************************
Bind the ICU functions from a shared library. This is
complicated by the issues regarding D and DLLs on the
Windows platform
***********************************************************************/
mixin(genICUNative!("uc"
,"uint function (uint, uint)", "u_getIntPropertyValue"
,"uint function (uint)", "u_getIntPropertyMinValue"
,"uint function (uint)", "u_getIntPropertyMaxValue"
,"uint function (dchar)", "u_charDirection"
,"uint function (dchar)", "ublock_getCode"
,"uint function (dchar, uint, char*, uint, ref UErrorCode)", "u_charName"
,"uint function (dchar, char*, uint, ref UErrorCode)", "u_getISOComment"
,"uint function (uint, char*, ref UErrorCode)", "u_charFromName"
,"char* function (uint, uint)", "u_getPropertyName"
,"char* function (uint, uint, uint)", "u_getPropertyValueName"
,"void function (ref Version)", "u_getUnicodeVersion"
,"void function (dchar, ref Version)", "u_charAge"
));
}
| D |
// Templatized variable declaration
int twice(int x) = 2 * x;
const int twice(int x) = 2 * x;
immutable int twice(int x) = 2 * x;
void foo()
{
immutable int twice(int x) = 2 * x;
} | D |
module android.java.android.media.MediaDescription_d_interface;
import arsd.jni : IJavaObjectImplementation, JavaPackageId, JavaName, IJavaObject, ImportExportImpl, JavaInterfaceMembers;
static import arsd.jni;
import import1 = android.java.android.graphics.Bitmap_d_interface;
import import0 = android.java.java.lang.CharSequence_d_interface;
import import5 = android.java.java.lang.Class_d_interface;
import import4 = android.java.android.os.Parcel_d_interface;
import import2 = android.java.android.net.Uri_d_interface;
import import3 = android.java.android.os.Bundle_d_interface;
final class MediaDescription : IJavaObject {
static immutable string[] _d_canCastTo = [
"android/os/Parcelable",
];
@Import string getMediaId();
@Import import0.CharSequence getTitle();
@Import import0.CharSequence getSubtitle();
@Import import0.CharSequence getDescription();
@Import import1.Bitmap getIconBitmap();
@Import import2.Uri getIconUri();
@Import import3.Bundle getExtras();
@Import import2.Uri getMediaUri();
@Import int describeContents();
@Import void writeToParcel(import4.Parcel, int);
@Import bool equals(IJavaObject);
@Import @JavaName("toString") string toString_();
override string toString() { return arsd.jni.javaObjectToString(this); }
@Import import5.Class getClass();
@Import int hashCode();
@Import void notify();
@Import void notifyAll();
@Import void wait(long);
@Import void wait(long, int);
@Import void wait();
mixin IJavaObjectImplementation!(false);
public static immutable string _javaParameterString = "Landroid/media/MediaDescription;";
}
| D |
#Hello in dbpass Apps
Saving your social media passwords
| D |
void main() {
auto N = ri;
long k;
auto P = readAs!(int[]);
auto Q = readAs!(int[]);
auto arr = P.dup.sort().array;
long a, b;
do {
if(arr == P) a = k;
if(arr == Q) b = k;
k++;
//debug arr.writeln;
} while(nextPermutation(arr));
writeln(abs(a - b));
}
// ===================================
import std.stdio;
import std.string;
import std.functional;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;
T readAs(T)() if (isBasicType!T) {
return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
return readln.split.to!T;
}
T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
auto res = new T[][](height, width);
foreach(i; 0..height) {
res[i] = readAs!(T[]);
}
return res;
}
T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
auto res = new T[][](height, width);
foreach(i; 0..height) {
auto s = rs;
foreach(j; 0..width) res[i][j] = s[j].to!T;
}
return res;
}
int ri() {
return readAs!int;
}
double rd() {
return readAs!double;
}
string rs() {
return readln.chomp;
} | D |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 3.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Team15 library.
*
* The Initial Developer of the Original Code is
* Vladimir Panteleev <vladimir@thecybershadow.net>
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of the
* GNU General Public License Version 3 (the "GPL") or later, in which case
* the provisions of the GPL are applicable instead of those above. If you
* wish to allow use of your version of this file only under the terms of the
* GPL, and not to allow others to use your version of this file under the
* terms of the MPL, indicate your decision by deleting the provisions above
* and replace them with the notice and other provisions required by the GPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under the terms of either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
/// Time string formatting and such.
module ae.utils.time;
import std.datetime;
import std.string;
import std.conv : text;
import std.utf : decode, stride;
import std.math : abs;
import ae.utils.textout;
struct TimeFormats
{
static:
const ATOM = `Y-m-d\TH:i:sP`;
const COOKIE = `l, d-M-y H:i:s T`;
const ISO8601 = `Y-m-d\TH:i:sO`;
const RFC822 = `D, d M y H:i:s O`;
const RFC850 = `l, d-M-y H:i:s T`;
const RFC1036 = `D, d M y H:i:s O`;
const RFC1123 = `D, d M Y H:i:s O`;
const RFC2822 = `D, d M Y H:i:s O`;
const RFC3339 = `Y-m-d\TH:i:sP`;
const RSS = `D, d M Y H:i:s O`;
const W3C = `Y-m-d\TH:i:sP`;
const HTML5DATE = `Y-m-d`;
/// Format produced by std.date.toString, e.g. "Tue Jun 07 13:23:19 GMT+0100 2011"
const STD_DATE = `D M d H:i:s \G\M\TO Y`;
}
private const WeekdayShortNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
private const WeekdayLongNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
private const MonthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
private const MonthLongNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
/// Format a SysTime using a PHP date() format string.
string formatTime(string fmt, SysTime t = Clock.currTime)
{
auto result = StringBuilder(48);
putTime(result, fmt, t);
return result.get();
}
/// ditto
void putTime(S)(ref S sink, string fmt, SysTime t = Clock.currTime)
// if (IsStringSink!S)
{
auto dt = cast(DateTime)t;
auto date = dt.date;
static char oneDigit(uint i)
{
debug assert(i < 10);
return cast(char)('0' + i);
}
static char[2] twoDigits(uint i)
{
debug assert(i < 100);
char[2] result;
result[0] = cast(char)('0' + i / 10);
result[1] = cast(char)('0' + i % 10);
return result;
}
static string oneOrTwoDigits(uint i)
{
debug assert(i < 100);
if (i < 10)
return [cast(char)('0' + i)];
else
return twoDigits(i).idup;
}
static char[4] fourDigits(uint i)
{
debug assert(i < 10000);
char[4] result;
result[0] = cast(char)('0' + i / 1000 );
result[1] = cast(char)('0' + i / 100 % 10);
result[2] = cast(char)('0' + i / 10 % 10);
result[3] = cast(char)('0' + i % 10);
return result;
}
string timezoneFallback(string tzStr, string fallbackFormat)
{
if (tzStr.length)
return tzStr;
else
return formatTime(fallbackFormat, t);
}
size_t idx = 0;
dchar c;
while (idx < fmt.length)
switch (c = decode(fmt, idx))
{
// Day
case 'd':
sink.put(twoDigits(dt.day));
break;
case 'D':
sink.put(WeekdayShortNames[dt.dayOfWeek]);
break;
case 'j':
sink.put(oneOrTwoDigits(dt.day));
break;
case 'l':
sink.put(WeekdayLongNames[dt.dayOfWeek]);
break;
case 'N':
sink.put(oneDigit((dt.dayOfWeek+6)%7 + 1));
break;
case 'S':
switch (dt.day)
{
case 1:
case 21:
case 31:
sink.put("st");
break;
case 2:
case 22:
sink.put("nd");
break;
case 3:
case 23:
sink.put("rd");
break;
default:
sink.put("th");
}
break;
case 'w':
sink.put(oneDigit(cast(int)dt.dayOfWeek));
break;
case 'z':
sink.put(text(dt.dayOfYear-1));
break;
// Week
case 'W':
sink.put(twoDigits(dt.isoWeek));
break;
// Month
case 'F':
sink.put(MonthLongNames[dt.month-1]);
break;
case 'm':
sink.put(twoDigits(dt.month));
break;
case 'M':
sink.put(MonthShortNames[dt.month-1]);
break;
case 'n':
sink.put(oneOrTwoDigits(dt.month));
break;
case 't':
sink.put(oneOrTwoDigits(dt.daysInMonth));
break;
// Year
case 'L':
sink.put(dt.isLeapYear ? '1' : '0');
break;
// case 'o': TODO (ISO 8601 year number)
case 'Y':
sink.put(fourDigits(dt.year));
break;
case 'y':
sink.put(twoDigits(dt.year % 100));
break;
// Time
case 'a':
sink.put(dt.hour < 12 ? "am" : "pm");
break;
case 'A':
sink.put(dt.hour < 12 ? "AM" : "PM");
break;
// case 'B': TODO (Swatch Internet time)
case 'g':
sink.put(oneOrTwoDigits((dt.hour+11)%12 + 1));
break;
case 'G':
sink.put(oneOrTwoDigits(dt.hour));
break;
case 'h':
sink.put(twoDigits((dt.hour+11)%12 + 1));
break;
case 'H':
sink.put(twoDigits(dt.hour));
break;
case 'i':
sink.put(twoDigits(dt.minute));
break;
case 's':
sink.put(twoDigits(dt.second));
break;
case 'u':
sink.put(format("%06d", t.fracSec.usecs));
break;
case 'E': // not standard
sink.put(format("%03d", t.fracSec.msecs));
break;
// Timezone
case 'e':
sink.put(timezoneFallback(t.timezone.name, "P"));
break;
case 'I':
sink.put(t.dstInEffect ? '1': '0');
break;
case 'O':
{
auto minutes = (t.timezone.utcToTZ(t.stdTime) - t.stdTime) / 10_000_000 / 60;
sink.put(format("%+03d%02d", minutes/60, abs(minutes%60)));
break;
}
case 'P':
{
auto minutes = (t.timezone.utcToTZ(t.stdTime) - t.stdTime) / 10_000_000 / 60;
sink.put(format("%+03d:%02d", minutes/60, abs(minutes%60)));
break;
}
case 'T':
sink.put(timezoneFallback(t.timezone.stdName, "P"));
break;
case 'Z':
sink.put(text((t.timezone.utcToTZ(t.stdTime) - t.stdTime) / 10_000_000));
break;
// Full date/time
case 'c':
sink.put(dt.toISOExtString());
break;
case 'r':
sink.put(formatTime(TimeFormats.RFC2822, t));
break;
case 'U':
sink.put(text(t.toUnixTime));
break;
// Escape next character
case '\\':
put(sink, decode(fmt, idx));
break;
// Other characters (whitespace, delimiters)
default:
put(sink, c);
}
}
import std.exception : enforce;
import std.conv : to;
import std.ascii : isDigit, isWhite;
/// Attempt to parse a time string using a PHP date() format string.
/// Supports only a small subset of format characters.
SysTime parseTime(string fmt, string t)
{
string take(size_t n)
{
enforce(t.length >= n, "Not enough characters in date string");
auto result = t[0..n];
t = t[n..$];
return result;
}
int takeNumber(size_t n, sizediff_t max = -1)
{
if (max==-1) max=n;
enforce(t.length >= n, "Not enough characters in date string");
foreach (i, c; t[0..n])
enforce((i==0 && c=='-') || isDigit(c) || isWhite(c), "Number expected");
while (n < max && t.length > n && isDigit(t[n]))
n++;
return to!int(strip(take(n)));
}
int takeWord(in string[] words, string name)
{
foreach (idx, string word; words)
if (t.startsWith(word))
{
t = t[word.length..$];
return cast(int)idx;
}
throw new Exception(name ~ " expected");
}
int year=0, month=1, day=1, hour=0, minute=0, second=0, usecs=0;
int hour12 = 0; bool pm;
TimeZone tz = null;
int dow = -1;
size_t idx = 0;
dchar c;
while (idx < fmt.length)
switch (c = decode(fmt, idx))
{
// Day
case 'd':
day = takeNumber(2);
break;
case 'D':
dow = takeWord(WeekdayShortNames, "Weekday");
break;
case 'j':
day = takeNumber(1, 2);
break;
case 'l':
dow = takeWord(WeekdayLongNames, "Weekday");
break;
case 'N':
dow = takeNumber(1) % 7;
break;
case 'S': // ordinal suffix
take(2);
break;
case 'w':
dow = takeNumber(1);
break;
//case 'z': TODO
// Week
//case 'W': TODO
// Month
case 'F':
month = takeWord(MonthLongNames, "Month") + 1;
break;
case 'm':
month = takeNumber(2);
break;
case 'M':
month = takeWord(MonthShortNames, "Month") + 1;
break;
case 'n':
month = takeNumber(1, 2);
break;
case 't':
takeNumber(1, 2); // TODO: validate DIM?
break;
// Year
case 'L':
takeNumber(1); // TODO: validate leapness?
break;
// case 'o': TODO (ISO 8601 year number)
case 'Y':
year = takeNumber(4);
break;
case 'y':
year = takeNumber(2);
if (year > 50) // TODO: find correct logic for this
year += 1900;
else
year += 2000;
break;
// Time
case 'a':
pm = takeWord(["am", "pm"], "am/pm")==1;
break;
case 'A':
pm = takeWord(["AM", "PM"], "AM/PM")==1;
break;
// case 'B': TODO (Swatch Internet time)
case 'g':
hour12 = takeNumber(1, 2);
break;
case 'G':
hour = takeNumber(1, 2);
break;
case 'h':
hour12 = takeNumber(2);
break;
case 'H':
hour = takeNumber(2);
break;
case 'i':
minute = takeNumber(2);
break;
case 's':
second = takeNumber(2);
break;
case 'u':
usecs = takeNumber(6);
break;
case 'E': // not standard
usecs = 1000 * takeNumber(3);
break;
// Timezone
// case 'e': ???
case 'I':
takeNumber(1);
break;
case 'O':
{
auto tzStr = take(5);
enforce(tzStr[0]=='-' || tzStr[0]=='+', "-/+ expected");
auto minutes = (to!int(tzStr[1..3]) * 60 + to!int(tzStr[3..5])) * (tzStr[0]=='-' ? -1 : 1);
tz = new SimpleTimeZone(minutes);
break;
}
case 'P':
{
auto tzStr = take(6);
enforce(tzStr[0]=='-' || tzStr[0]=='+', "-/+ expected");
enforce(tzStr[3]==':', ": expected");
auto minutes = (to!int(tzStr[1..3]) * 60 + to!int(tzStr[4..6])) * (tzStr[0]=='-' ? -1 : 1);
tz = new SimpleTimeZone(minutes);
break;
}
case 'T':
tz = cast(TimeZone)TimeZone.getTimeZone(take(t.length)); // $!#%!$# constness
break;
case 'Z':
{
// TODO: is this correct?
auto seconds = takeNumber(1, 6);
enforce(seconds % 60 == 0, "Timezone granularity lower than minutes not supported");
tz = new SimpleTimeZone(seconds / 60);
break;
}
// Full date/time
//case 'c': TODO
//case 'r': TODO
//case 'U': TODO
// Escape next character
case '\\':
{
// Ugh
string next = fmt[idx..idx+stride(fmt, idx)];
idx += next.length;
enforce(t.length, next ~ " expected");
enforce(take(stride(t, 0)) == next, next ~ " expected");
break;
}
// Other characters (whitespace, delimiters)
default:
{
enforce(t.length, to!string([c]) ~ " expected or unsupported format character");
size_t stride = 0;
enforce(decode(t, stride) == c, to!string([c]) ~ " expected or unsupported format character");
t = t[stride..$];
}
}
if (hour12)
hour = hour12%12 + (pm ? 12 : 0);
auto result = SysTime(
DateTime(year, month, day, hour, minute, second),
FracSec.from!"usecs"(usecs),
cast(immutable(TimeZone))tz);
if (dow >= 0)
enforce(result.dayOfWeek == dow, "Mismatching weekday");
return result;
}
| D |
func int BanditKilled(var int print_alive) {
var int ammount; ammount = 0;
var string alives; alives = "";
// ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
if (npc_isdead (NASZ_306_Perrot)) { ammount += 1; }
else { alives = ConcatStrings(alives,ConcatStrings(" ",IntToString(NASZ_306_Perrot.id))); };
if (npc_isdead (NASZ_315_Bandzior)) { ammount += 1; }
else { alives = ConcatStrings(alives,ConcatStrings(" ",IntToString(NASZ_315_Bandzior.id))); };
if (npc_isdead (NASZ_316_Carry)) { ammount += 1; }
else { alives = ConcatStrings(alives,ConcatStrings(" ",IntToString(NASZ_316_Carry.id))); };
if (npc_isdead (NASZ_317_Bandzior)) { ammount += 1; }
else { alives = ConcatStrings(alives,ConcatStrings(" ",IntToString(NASZ_317_Bandzior.id))); };
if (npc_isdead (NASZ_318_Gobby)) { ammount += 1; }
else { alives = ConcatStrings(alives,ConcatStrings(" ",IntToString(NASZ_318_Gobby.id))); };
if (npc_isdead (NASZ_326_Domenic)) { ammount += 1; }
else { alives = ConcatStrings(alives,ConcatStrings(" ",IntToString(NASZ_326_Domenic.id))); };
if (npc_isdead (NASZ_327_Danny)) { ammount += 1; }
else { alives = ConcatStrings(alives,ConcatStrings(" ",IntToString(NASZ_327_Danny.id))); };
// ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
if (print_alive == TRUE) { Print(alives); };
return ammount;
};
// ----- ----- ----- ----- -----
// RESET BANDIT ATTACK VARS
var int ResetBanditAttackVar303;
var int ResetBanditAttackVar304;
var int ResetBanditAttackVar305;
var int ResetBanditAttackVar306;
var int ResetBanditAttackVar307;
var int ResetBanditAttackVar308;
var int ResetBanditAttackVar309;
var int ResetBanditAttackVar310;
var int ResetBanditAttackVar311;
var int ResetBanditAttackVar312;
var int ResetBanditAttackVar313;
var int ResetBanditAttackVar314;
var int ResetBanditAttackVar315;
var int ResetBanditAttackVar316;
var int ResetBanditAttackVar317;
var int ResetBanditAttackVar318;
var int ResetBanditAttackVar326;
var int ResetBanditAttackVar327;
var int ResetBanditAttackVar319;
var int ResetBanditAttackVar320;
var int ResetBanditAttackVar321;
var int ResetBanditAttackVar322;
var int ResetBanditAttackVar323;
var int ResetBanditAttackVar324;
// ----- ----- ----- ----- -----
func void ResetBanditAttitude(var C_NPC bandit) {
bandit.guild = GIL_SLD;
Npc_SetTrueGuild (bandit, GIL_SLD);
Npc_SetAttitude(bandit, ATT_NEUTRAL);
Npc_SetTempAttitude(bandit, ATT_NEUTRAL);
bandit.aivar[AIV_NpcSawPlayerCommit] = CRIME_NONE;
bandit.aivar[AIV_LastFightAgainstPlayer] = FIGHT_NONE;
};
func void ResetBanditAttack(var C_NPC slf) {
slf.aivar[AIV_PursuitEnd] = true;
Npc_ClearAIQueue(slf);
AI_StandUpQuick(slf);
// PERCEPTIONS B_ClearPerceptions(slf);
Npc_PercDisable (slf, PERC_ASSESSPLAYER );
Npc_PercDisable (slf, PERC_ASSESSENEMY );
Npc_PercDisable (slf, PERC_ASSESSBODY );
Npc_PercDisable (slf, PERC_ASSESSMAGIC );
Npc_PercDisable (slf, PERC_ASSESSDAMAGE );
Npc_PercDisable (slf, PERC_ASSESSMURDER );
Npc_PercDisable (slf, PERC_ASSESSTHEFT );
Npc_PercDisable (slf, PERC_ASSESSUSEMOB );
Npc_PercDisable (slf, PERC_ASSESSENTERROOM );
Npc_PercDisable (slf, PERC_ASSESSTHREAT );
Npc_PercDisable (slf, PERC_DRAWWEAPON );
Npc_PercDisable (slf, PERC_ASSESSFIGHTSOUND );
Npc_PercDisable (slf, PERC_ASSESSQUIETSOUND );
Npc_PercDisable (slf, PERC_ASSESSWARN );
Npc_PercDisable (slf, PERC_ASSESSTALK );
Npc_PercDisable (slf, PERC_MOVEMOB );
Npc_PercDisable (slf, PERC_ASSESSOTHERSDAMAGE );
Npc_PercDisable (slf, PERC_ASSESSSTOPMAGIC );
Npc_PercDisable (slf, PERC_ASSESSSURPRISE );
};
// ret TRUE iif end loop
// ret FALSE iif dn't end loop
func int CheckBanditsVar(var C_NPC slf) {
if (slf.id == 303 && ResetBanditAttackVar303) { ResetBanditAttackVar303 = FALSE; ResetBanditAttack(NASZ_303_Nod); return TRUE; };
if (slf.id == 304 && ResetBanditAttackVar304) { ResetBanditAttackVar304 = FALSE; ResetBanditAttack(NASZ_304_Bam); return TRUE; };
if (slf.id == 305 && ResetBanditAttackVar305) { ResetBanditAttackVar305 = FALSE; ResetBanditAttack(NASZ_305_Rabon); return TRUE; };
if (slf.id == 306 && ResetBanditAttackVar306) { ResetBanditAttackVar306 = FALSE; ResetBanditAttack(NASZ_306_Perrot); return TRUE; };
if (slf.id == 307 && ResetBanditAttackVar307) { ResetBanditAttackVar307 = FALSE; ResetBanditAttack(NASZ_307_Monk); return TRUE; };
if (slf.id == 308 && ResetBanditAttackVar308) { ResetBanditAttackVar308 = FALSE; ResetBanditAttack(NASZ_308_Frut); return TRUE; };
if (slf.id == 309 && ResetBanditAttackVar309) { ResetBanditAttackVar309 = FALSE; ResetBanditAttack(NASZ_309_Straznik); return TRUE; };
if (slf.id == 310 && ResetBanditAttackVar310) { ResetBanditAttackVar310 = FALSE; ResetBanditAttack(NASZ_310_Bandzior); return TRUE; };
if (slf.id == 311 && ResetBanditAttackVar311) { ResetBanditAttackVar311 = FALSE; ResetBanditAttack(NASZ_311_Bandzior); return TRUE; };
if (slf.id == 312 && ResetBanditAttackVar312) { ResetBanditAttackVar312 = FALSE; ResetBanditAttack(NASZ_312_Bandzior); return TRUE; };
if (slf.id == 313 && ResetBanditAttackVar313) { ResetBanditAttackVar313 = FALSE; ResetBanditAttack(NASZ_313_Bandzior); return TRUE; };
if (slf.id == 314 && ResetBanditAttackVar314) { ResetBanditAttackVar314 = FALSE; ResetBanditAttack(NASZ_314_Bandzior); return TRUE; };
if (slf.id == 315 && ResetBanditAttackVar315) { ResetBanditAttackVar315 = FALSE; ResetBanditAttack(NASZ_315_Bandzior); return TRUE; };
if (slf.id == 316 && ResetBanditAttackVar316) { ResetBanditAttackVar316 = FALSE; ResetBanditAttack(NASZ_316_Carry); return TRUE; };
if (slf.id == 317 && ResetBanditAttackVar317) { ResetBanditAttackVar317 = FALSE; ResetBanditAttack(NASZ_317_Bandzior); return TRUE; };
if (slf.id == 318 && ResetBanditAttackVar318) { ResetBanditAttackVar318 = FALSE; ResetBanditAttack(NASZ_318_Gobby); return TRUE; };
if (slf.id == 326 && ResetBanditAttackVar326) { ResetBanditAttackVar326 = FALSE; ResetBanditAttack(NASZ_326_Domenic); return TRUE; };
if (slf.id == 327 && ResetBanditAttackVar327) { ResetBanditAttackVar327 = FALSE; ResetBanditAttack(NASZ_327_Danny); return TRUE; };
if (slf.id == 319 && ResetBanditAttackVar319) { ResetBanditAttackVar319 = FALSE; ResetBanditAttack(NASZ_319_Niewolnik); return TRUE; };
if (slf.id == 320 && ResetBanditAttackVar320) { ResetBanditAttackVar320 = FALSE; ResetBanditAttack(NASZ_320_Niewolnik); return TRUE; };
if (slf.id == 321 && ResetBanditAttackVar321) { ResetBanditAttackVar321 = FALSE; ResetBanditAttack(NASZ_321_Niewolnik); return TRUE; };
if (slf.id == 322 && ResetBanditAttackVar322) { ResetBanditAttackVar322 = FALSE; ResetBanditAttack(NASZ_322_Niewolnik); return TRUE; };
if (slf.id == 323 && ResetBanditAttackVar323) { ResetBanditAttackVar323 = FALSE; ResetBanditAttack(NASZ_323_Niewolnik); return TRUE; };
if (slf.id == 324 && ResetBanditAttackVar324) { ResetBanditAttackVar324 = FALSE; ResetBanditAttack(NASZ_324_Niewolnik); return TRUE; };
return FALSE;
};
// funkcja do resetowania nastawienia bandytow, jesli cie juz gdzies widzieli i atakuja
// -> wywoluje ja Gestath, gdy posyla cie do Noda, mozna wywolac tez u NASZ_999_Test
func void ResetBanditsAttitude() {
ResetBanditAttackVar303 = TRUE;
ResetBanditAttackVar304 = TRUE;
ResetBanditAttackVar305 = TRUE;
ResetBanditAttackVar306 = TRUE;
ResetBanditAttackVar307 = TRUE;
ResetBanditAttackVar308 = TRUE;
ResetBanditAttackVar309 = TRUE;
ResetBanditAttackVar310 = TRUE;
ResetBanditAttackVar311 = TRUE;
ResetBanditAttackVar312 = TRUE;
ResetBanditAttackVar313 = TRUE;
ResetBanditAttackVar314 = TRUE;
ResetBanditAttackVar315 = TRUE;
ResetBanditAttackVar316 = TRUE;
ResetBanditAttackVar317 = TRUE;
ResetBanditAttackVar318 = TRUE;
ResetBanditAttackVar326 = TRUE;
ResetBanditAttackVar327 = TRUE;
ResetBanditAttackVar319 = TRUE;
ResetBanditAttackVar320 = TRUE;
ResetBanditAttackVar321 = TRUE;
ResetBanditAttackVar322 = TRUE;
ResetBanditAttackVar323 = TRUE;
ResetBanditAttackVar324 = TRUE;
ResetBanditAttitude(NASZ_303_Nod);
ResetBanditAttitude(NASZ_304_Bam);
ResetBanditAttitude(NASZ_305_Rabon);
ResetBanditAttitude(NASZ_306_Perrot);
ResetBanditAttitude(NASZ_307_Monk);
ResetBanditAttitude(NASZ_308_Frut);
ResetBanditAttitude(NASZ_309_Straznik);
ResetBanditAttitude(NASZ_310_Bandzior);
ResetBanditAttitude(NASZ_311_Bandzior);
ResetBanditAttitude(NASZ_312_Bandzior);
ResetBanditAttitude(NASZ_313_Bandzior);
ResetBanditAttitude(NASZ_314_Bandzior);
ResetBanditAttitude(NASZ_315_Bandzior);
ResetBanditAttitude(NASZ_316_Carry);
ResetBanditAttitude(NASZ_317_Bandzior);
ResetBanditAttitude(NASZ_318_Gobby);
ResetBanditAttitude(NASZ_326_Domenic);
ResetBanditAttitude(NASZ_327_Danny);
ResetBanditAttitude(NASZ_319_Niewolnik);
ResetBanditAttitude(NASZ_320_Niewolnik);
ResetBanditAttitude(NASZ_321_Niewolnik);
ResetBanditAttitude(NASZ_322_Niewolnik);
ResetBanditAttitude(NASZ_323_Niewolnik);
ResetBanditAttitude(NASZ_324_Niewolnik);
};
| D |
/home/oscar/Documents/git_repo/e7020e_2019/target/rls/debug/examples/bare3_4-6dd21a2c9f35c340.rmeta: examples/bare3_4.rs
/home/oscar/Documents/git_repo/e7020e_2019/target/rls/debug/examples/bare3_4-6dd21a2c9f35c340.d: examples/bare3_4.rs
examples/bare3_4.rs:
| D |
// URL: https://yukicoder.me/problems/no/728
import std.algorithm, std.array, std.container, std.math, std.range, std.typecons, std.string;
version(unittest) {} else
void main()
{
int N; io.getV(N);
int[] A; io.getA(N, A);
int[] L, R; io.getC(N, L, R);
struct B { int x, i, t; }
auto b = new B[](N*2);
foreach (i; 0..N) {
b[i] = B(A[i], i, 0);
b[i+N] = B(A[i]-L[i], i, 1);
}
b.multiSort!("a.x<b.x", "a.t>b.t");
auto as = A.assumeSorted, ft = fenwickTree!int(N), ans = 0L;
foreach (bi; b) {
auto i = bi.i;
switch (bi.t) {
case 0:
auto k = as.lowerBound(A[i]+R[i]+1).length;
ans += ft[i+1..k];
break;
case 1:
++ft[i];
break;
default:
assert(0);
}
}
io.put(ans);
}
import lib.data_structure.fenwick_tree;
auto io = IO!()();
import lib.io;
| D |
instance VLK_586_Grimes (Npc_Default)
{
//-------- primary data --------
name = "Grimes";
npctype = npctype_main;
guild = GIL_VLK;
level = 5;
voice = 4;
id = 586;
//-------- abilities --------
attribute[ATR_STRENGTH] = 25;
attribute[ATR_DEXTERITY] = 15;
attribute[ATR_MANA_MAX] = 0;
attribute[ATR_MANA] = 0;
attribute[ATR_HITPOINTS_MAX] = 100;
attribute[ATR_HITPOINTS] = 100;
//-------- visuals --------
// animations
Mdl_SetVisual (self,"HUMANS.MDS");
Mdl_ApplyOverlayMds (self,"Humans_Tired.mds");
// body mesh,head mesh,hairmesh,face-tex,hair-tex,skin
Mdl_SetVisualBody (self,"hum_body_Naked0",3,1,"Hum_Head_Thief",110,2,-1);
B_Scale (self);
Mdl_SetModelFatness (self,0);
fight_tactic = FAI_HUMAN_COWARD;
//-------- Talents --------
Npc_SetTalentSkill (self,NPC_TALENT_1H,1);
//-------- inventory --------
CreateInvItem (self,ItFo_Potion_Water_01);
CreateInvItem (self,ItMwPickaxe);
//-------------Daily Routine-------------
/*B_InitNPCAddins(self);*/ daily_routine = Rtn_Start_586;
};
FUNC VOID Rtn_Start_586 ()
{
TA_Stand (10,00,17,00,"OCR_OUTSIDE_HUT_44");
TA_CookForMe (17,00,20,00,"OCR_OUTSIDE_HUT_44");
TA_SitAround (20,00,10,00,"OCR_OUTSIDE_HUT_44");
};
| D |
/**
* Written in the D programming language.
* This module provides OSX-specific support for sections.
*
* Copyright: Copyright Digital Mars 2008 - 2012.
* License: Distributed under the
* $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
* (See accompanying file LICENSE)
* Authors: Walter Bright, Sean Kelly, Martin Nowak
* Source: $(DRUNTIMESRC src/rt/_sections_osx.d)
*/
module rt.sections_osx;
version(OSX):
// debug = PRINTF;
import core.stdc.stdio;
import core.stdc.string, core.stdc.stdlib;
import core.sys.posix.pthread;
import core.sys.osx.mach.dyld;
import core.sys.osx.mach.getsect;
import rt.deh, rt.minfo;
import rt.util.container.array;
struct SectionGroup
{
static int opApply(scope int delegate(ref SectionGroup) dg)
{
return dg(_sections);
}
static int opApplyReverse(scope int delegate(ref SectionGroup) dg)
{
return dg(_sections);
}
@property immutable(ModuleInfo*)[] modules() const
{
return _moduleGroup.modules;
}
@property ref inout(ModuleGroup) moduleGroup() inout
{
return _moduleGroup;
}
@property inout(void[])[] gcRanges() inout
{
return _gcRanges[];
}
@property immutable(FuncTable)[] ehTables() const
{
return _ehTables[];
}
private:
immutable(FuncTable)[] _ehTables;
ModuleGroup _moduleGroup;
Array!(void[]) _gcRanges;
immutable(void)[][2] _tlsImage;
}
/****
* Boolean flag set to true while the runtime is initialized.
*/
__gshared bool _isRuntimeInitialized;
/****
* Gets called on program startup just before GC is initialized.
*/
void initSections()
{
pthread_key_create(&_tlsKey, null);
_dyld_register_func_for_add_image(§ions_osx_onAddImage);
_isRuntimeInitialized = true;
}
/***
* Gets called on program shutdown just after GC is terminated.
*/
void finiSections()
{
_sections._gcRanges.reset();
pthread_key_delete(_tlsKey);
_isRuntimeInitialized = false;
}
void[]* initTLSRanges()
{
return &getTLSBlock();
}
void finiTLSRanges(void[]* rng)
{
.free(rng.ptr);
.free(rng);
}
void scanTLSRanges(void[]* rng, scope void delegate(void* pbeg, void* pend) nothrow dg) nothrow
{
dg(rng.ptr, rng.ptr + rng.length);
}
// NOTE: The Mach-O object file format does not allow for thread local
// storage declarations. So instead we roll our own by putting tls
// into the __tls_data and the __tlscoal_nt sections.
//
// This function is called by the code emitted by the compiler. It
// is expected to translate an address into the TLS static data to
// the corresponding address in the TLS dynamic per-thread data.
// NB: the compiler mangles this function as '___tls_get_addr' even though it is extern(D)
extern(D) void* ___tls_get_addr( void* p )
{
immutable off = tlsOffset(p);
auto tls = getTLSBlockAlloc();
assert(off < tls.length);
return tls.ptr + off;
}
private:
__gshared pthread_key_t _tlsKey;
size_t tlsOffset(void* p)
in
{
assert(_sections._tlsImage[0].ptr !is null ||
_sections._tlsImage[1].ptr !is null);
}
body
{
// NOTE: p is an address in the TLS static data emitted by the
// compiler. If it isn't, something is disastrously wrong.
immutable off0 = cast(size_t)(p - _sections._tlsImage[0].ptr);
if (off0 < _sections._tlsImage[0].length)
{
return off0;
}
immutable off1 = cast(size_t)(p - _sections._tlsImage[1].ptr);
if (off1 < _sections._tlsImage[1].length)
{
size_t sz = (_sections._tlsImage[0].length + 15) & ~cast(size_t)15;
return sz + off1;
}
assert(0);
}
ref void[] getTLSBlock()
{
auto pary = cast(void[]*)pthread_getspecific(_tlsKey);
if (pary is null)
{
pary = cast(void[]*).calloc(1, (void[]).sizeof);
if (pthread_setspecific(_tlsKey, pary) != 0)
{
import core.stdc.stdio;
perror("pthread_setspecific failed with");
assert(0);
}
}
return *pary;
}
ref void[] getTLSBlockAlloc()
{
auto pary = &getTLSBlock();
if (!pary.length)
{
auto imgs = _sections._tlsImage;
immutable sz0 = (imgs[0].length + 15) & ~cast(size_t)15;
immutable sz2 = sz0 + imgs[1].length;
auto p = .malloc(sz2);
memcpy(p, imgs[0].ptr, imgs[0].length);
memcpy(p + sz0, imgs[1].ptr, imgs[1].length);
*pary = p[0 .. sz2];
}
return *pary;
}
__gshared SectionGroup _sections;
extern (C) void sections_osx_onAddImage(in mach_header* h, intptr_t slide)
{
foreach (e; dataSegs)
{
if (auto sect = getSection(h, slide, e.seg.ptr, e.sect.ptr))
_sections._gcRanges.insertBack((cast(void*)sect.ptr)[0 .. sect.length]);
}
if (auto sect = getSection(h, slide, "__DATA", "__minfodata"))
{
// no support for multiple images yet
// take the sections from the last static image which is the executable
if (_isRuntimeInitialized)
{
fprintf(stderr, "Loading shared libraries isn't yet supported on OSX.\n");
return;
}
else if (_sections.modules.ptr !is null)
{
fprintf(stderr, "Shared libraries are not yet supported on OSX.\n");
}
debug(PRINTF) printf(" minfodata\n");
auto p = cast(immutable(ModuleInfo*)*)sect.ptr;
immutable len = sect.length / (*p).sizeof;
_sections._moduleGroup = ModuleGroup(p[0 .. len]);
}
if (auto sect = getSection(h, slide, "__DATA", "__deh_eh"))
{
debug(PRINTF) printf(" deh_eh\n");
auto p = cast(immutable(FuncTable)*)sect.ptr;
immutable len = sect.length / (*p).sizeof;
_sections._ehTables = p[0 .. len];
}
if (auto sect = getSection(h, slide, "__DATA", "__tls_data"))
{
debug(PRINTF) printf(" tls_data %p %p\n", sect.ptr, sect.ptr + sect.length);
_sections._tlsImage[0] = (cast(immutable(void)*)sect.ptr)[0 .. sect.length];
}
if (auto sect = getSection(h, slide, "__DATA", "__tlscoal_nt"))
{
debug(PRINTF) printf(" tlscoal_nt %p %p\n", sect.ptr, sect.ptr + sect.length);
_sections._tlsImage[1] = (cast(immutable(void)*)sect.ptr)[0 .. sect.length];
}
}
struct SegRef
{
string seg;
string sect;
}
static immutable SegRef[] dataSegs = [{SEG_DATA, SECT_DATA},
{SEG_DATA, SECT_BSS},
{SEG_DATA, SECT_COMMON}];
ubyte[] getSection(in mach_header* header, intptr_t slide,
in char* segmentName, in char* sectionName)
{
version (X86)
{
assert(header.magic == MH_MAGIC);
auto sect = getsectbynamefromheader(header,
segmentName,
sectionName);
}
else version (X86_64)
{
assert(header.magic == MH_MAGIC_64);
auto sect = getsectbynamefromheader_64(cast(mach_header_64*)header,
segmentName,
sectionName);
}
else
static assert(0, "unimplemented");
if (sect !is null && sect.size > 0)
return (cast(ubyte*)sect.addr + slide)[0 .. cast(size_t)sect.size];
return null;
}
| D |
import std.stdio;
enum a = __traits(isUnsigned, uint);
enum b = __traits(isUnsigned, 10 + 11);
enum c = __traits(isUnsigned, 10u + 11u);
enum d = __traits(isUnsigned, uint, 10u + 11u, 10.0 - 9.0);
static assert(a);
static assert(!b);
static assert(c);
static assert(!d);
struct Point {
int x, y;
}
void main() {
pragma(msg, __traits(allMembers,Point));
}
| D |
/// Generate by tools
module org.restlet.routing.VirtualHost;
import java.lang.exceptions;
public class VirtualHost
{
public this()
{
implMissing();
}
}
| D |
/*
* Problem 17
*
* 17 May 2002
*
* If the numbers 1 to 5 are written out in words: one, two, three,
* four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in
* total.
*
* If all the numbers from 1 to 1000 (one thousand) inclusive were
* written out in words, how many letters would be used?
*
*
* NOTE: Do not count spaces or hyphens. For example, 342 (three
* hundred and forty-two) contains 23 letters and 115 (one hundred and
* fifteen) contains 20 letters. The use of "and" when writing out
* numbers is in compliance with British usage.
*
* 21124
*/
import std.stdio;
import std.ascii;
void main() {
auto count = 0;
foreach (x; 1 .. 1001) {
foreach (ch; textify(x))
if (isAlpha(ch))
++count;
}
writeln(count);
}
const string[] oneNames = [
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen" ];
const string[] tenNames = [
"ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety" ];
string textify(uint x) in {
assert(x <= 1000);
} body {
if (x == 1000) return "one thousand";
if (x >= 100) {
auto num = x % 100;
auto and = num != 0 ? "and " : "";
return ones(x / 100) ~ " hundred " ~ and ~ textify(num);
}
if (x >= 20) {
auto num = x % 10;
auto hyphen = num > 0 ? "-" : " ";
return tens(x / 10) ~ hyphen ~ textify(num);
}
if (x >= 1) {
return ones(x);
}
// Zero.
return "";
}
string ones(uint x) {
return oneNames[x-1];
}
string tens(uint x) {
return tenNames[x-1];
}
| D |
/** DGui project file.
Copyright: Trogu Antonio Davide 2011-2013
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Trogu Antonio Davide
*/
module dgui.button;
import dgui.core.controls.abstractbutton;
/// Standarde windows _Button
class Button: AbstractButton
{
/**
Returns:
A DialogResult enum (ok, ignore, close, yes, no, cancel, ...)
See_Also:
Form.showDialog()
*/
@property public DialogResult dialogResult()
{
return this._dr;
}
/**
Sets DialogResult for a button
Params:
dr = DialogResult of the button.
See_Also:
Form.showDialog()
*/
@property public void dialogResult(DialogResult dr)
{
this._dr = dr;
}
protected override void createControlParams(ref CreateControlParams ccp)
{
switch(this._drawMode)
{
case OwnerDrawMode.normal:
this.setStyle(BS_PUSHBUTTON, true);
break;
case OwnerDrawMode.fixed, OwnerDrawMode.variable:
this.setStyle(BS_OWNERDRAW, true);
break;
default:
break;
}
ccp.className = WC_DBUTTON;
super.createControlParams(ccp);
}
}
/// Standard windows _CheckBox
class CheckBox: CheckedButton
{
protected override void createControlParams(ref CreateControlParams ccp)
{
switch(this._drawMode)
{
case OwnerDrawMode.normal:
this.setStyle(BS_AUTOCHECKBOX, true);
break;
case OwnerDrawMode.fixed, OwnerDrawMode.variable:
this.setStyle(BS_OWNERDRAW, true);
break;
default:
break;
}
ccp.className = WC_DCHECKBOX;
super.createControlParams(ccp);
}
}
/// Standard windows _RadioButton
class RadioButton: CheckedButton
{
protected override void createControlParams(ref CreateControlParams ccp)
{
switch(this._drawMode)
{
case OwnerDrawMode.normal:
this.setStyle(BS_AUTORADIOBUTTON, true);
break;
case OwnerDrawMode.fixed, OwnerDrawMode.variable:
this.setStyle(BS_OWNERDRAW, true);
break;
default:
break;
}
ccp.className = WC_DRADIOBUTTON;
super.createControlParams(ccp);
}
}
| D |
the tangible substance that goes into the makeup of a physical object
information (data or ideas or observations) that can be used or reworked into a finished form
artifact made by weaving or felting or knitting or crocheting natural or synthetic fibers
things needed for doing or making something
a person judged suitable for admission or employment
concerned with worldly rather than spiritual interests
derived from or composed of matter
directly relevant to a matter especially a law case
concerned with or affecting physical as distinct from intellectual or psychological well-being
having material or physical form or substance
having substance or capable of being treated as fact
| D |
/Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/WebSocket.swift.o : /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocketFrameSequence.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocketHandler.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket+Server.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket+Client.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOSHA1/include/CNIOSHA1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/asn1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/tls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dtls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs12.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl23.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509v3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/md5.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs7.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509.h /usr/local/Cellar/libressl/3.0.2/include/openssl/sha.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rsa.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOZlib/include/CNIOZlib.h /usr/local/Cellar/libressl/3.0.2/include/openssl/obj_mac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/hmac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ec.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rand.h /usr/local/Cellar/libressl/3.0.2/include/openssl/conf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslconf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/lhash.h /usr/local/Cellar/libressl/3.0.2/include/openssl/stack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/safestack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-ssl/Sources/CNIOOpenSSL/include/c_nio_openssl.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CCryptoOpenSSL/include/c_crypto_openssl.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bn.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bio.h /usr/local/Cellar/libressl/3.0.2/include/openssl/crypto.h /usr/local/Cellar/libressl/3.0.2/include/openssl/srtp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/evp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/3.0.2/include/openssl/buffer.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/CNIOHTTPParser.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/c_nio_http_parser.h /usr/local/Cellar/libressl/3.0.2/include/openssl/err.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/3.0.2/include/openssl/objects.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslv.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509_vfy.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/MySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentMySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CBase32/include/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CBcrypt/include/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-zlib-support/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-ssl-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/WebSocket~partial.swiftmodule : /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocketFrameSequence.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocketHandler.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket+Server.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket+Client.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOSHA1/include/CNIOSHA1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/asn1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/tls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dtls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs12.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl23.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509v3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/md5.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs7.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509.h /usr/local/Cellar/libressl/3.0.2/include/openssl/sha.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rsa.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOZlib/include/CNIOZlib.h /usr/local/Cellar/libressl/3.0.2/include/openssl/obj_mac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/hmac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ec.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rand.h /usr/local/Cellar/libressl/3.0.2/include/openssl/conf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslconf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/lhash.h /usr/local/Cellar/libressl/3.0.2/include/openssl/stack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/safestack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-ssl/Sources/CNIOOpenSSL/include/c_nio_openssl.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CCryptoOpenSSL/include/c_crypto_openssl.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bn.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bio.h /usr/local/Cellar/libressl/3.0.2/include/openssl/crypto.h /usr/local/Cellar/libressl/3.0.2/include/openssl/srtp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/evp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/3.0.2/include/openssl/buffer.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/CNIOHTTPParser.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/c_nio_http_parser.h /usr/local/Cellar/libressl/3.0.2/include/openssl/err.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/3.0.2/include/openssl/objects.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslv.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509_vfy.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/MySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentMySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CBase32/include/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CBcrypt/include/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-zlib-support/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-ssl-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/WebSocket~partial.swiftdoc : /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocketFrameSequence.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocketHandler.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket+Server.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket+Client.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOSHA1/include/CNIOSHA1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/asn1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/tls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dtls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs12.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl23.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509v3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/md5.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs7.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509.h /usr/local/Cellar/libressl/3.0.2/include/openssl/sha.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rsa.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOZlib/include/CNIOZlib.h /usr/local/Cellar/libressl/3.0.2/include/openssl/obj_mac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/hmac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ec.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rand.h /usr/local/Cellar/libressl/3.0.2/include/openssl/conf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslconf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/lhash.h /usr/local/Cellar/libressl/3.0.2/include/openssl/stack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/safestack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-ssl/Sources/CNIOOpenSSL/include/c_nio_openssl.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CCryptoOpenSSL/include/c_crypto_openssl.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bn.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bio.h /usr/local/Cellar/libressl/3.0.2/include/openssl/crypto.h /usr/local/Cellar/libressl/3.0.2/include/openssl/srtp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/evp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/3.0.2/include/openssl/buffer.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/CNIOHTTPParser.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/c_nio_http_parser.h /usr/local/Cellar/libressl/3.0.2/include/openssl/err.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/3.0.2/include/openssl/objects.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslv.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509_vfy.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/MySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentMySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CBase32/include/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CBcrypt/include/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-zlib-support/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-ssl-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/WebSocket~partial.swiftsourceinfo : /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocketFrameSequence.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocketHandler.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket+Server.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/websocket/Sources/WebSocket/WebSocket+Client.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOSHA1/include/CNIOSHA1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/asn1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/tls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dtls1.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs12.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem2.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl23.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509v3.h /usr/local/Cellar/libressl/3.0.2/include/openssl/md5.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pkcs7.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509.h /usr/local/Cellar/libressl/3.0.2/include/openssl/sha.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdsa.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rsa.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOZlib/include/CNIOZlib.h /usr/local/Cellar/libressl/3.0.2/include/openssl/obj_mac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/hmac.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ec.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /usr/local/Cellar/libressl/3.0.2/include/openssl/rand.h /usr/local/Cellar/libressl/3.0.2/include/openssl/conf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslconf.h /usr/local/Cellar/libressl/3.0.2/include/openssl/dh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ecdh.h /usr/local/Cellar/libressl/3.0.2/include/openssl/lhash.h /usr/local/Cellar/libressl/3.0.2/include/openssl/stack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/safestack.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ssl.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-ssl/Sources/CNIOOpenSSL/include/c_nio_openssl.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CCryptoOpenSSL/include/c_crypto_openssl.h /usr/local/Cellar/libressl/3.0.2/include/openssl/pem.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bn.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /usr/local/Cellar/libressl/3.0.2/include/openssl/bio.h /usr/local/Cellar/libressl/3.0.2/include/openssl/crypto.h /usr/local/Cellar/libressl/3.0.2/include/openssl/srtp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/evp.h /usr/local/Cellar/libressl/3.0.2/include/openssl/ossl_typ.h /usr/local/Cellar/libressl/3.0.2/include/openssl/buffer.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/CNIOHTTPParser.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include/c_nio_http_parser.h /usr/local/Cellar/libressl/3.0.2/include/openssl/err.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslfeatures.h /usr/local/Cellar/libressl/3.0.2/include/openssl/objects.h /usr/local/Cellar/libressl/3.0.2/include/openssl/opensslv.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /usr/local/Cellar/libressl/3.0.2/include/openssl/x509_vfy.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/MySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentMySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CBase32/include/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/crypto/Sources/CBcrypt/include/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-zlib-support/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-ssl-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
| D |
/*
* XMLRPC server
* Pavel Kirienko, 2013 (pavel.kirienko@gmail.com)
*/
module xmlrpc.server;
import xmlrpc.encoder : encodeResponse;
import xmlrpc.decoder : decodeCall;
import xmlrpc.data : MethodCallData, MethodResponseData;
import xmlrpc.paramconv : paramsToVariantArray, variantArrayToParams;
import xmlrpc.error : XmlRpcException, MethodFaultException, FciFaultCodes, makeFaultValue;
import std.exception : enforce;
import std.variant : Variant, VariantException;
import std.string : format;
import std.conv : to;
import std.stdio : writefln;
import std.traits : isCallable, ParameterTypeTuple, ReturnType;
alias void delegate(string) ErrorLogHandler;
alias Variant[] delegate(Variant[]) RawMethodHandler;
@trusted:
class Server
{
/**
* Params:
* errorLogHandler = Error logging delegate. Disabled by default. Refer to the property description.
*/
this(ErrorLogHandler errorLogHandler = null)
{
errorLogHandler_ = errorLogHandler;
addSystemMethods(this);
}
/**
* Handles one XML-RPC request. Can be used with HTTP server directly.
* Params:
* encodedRequest = Raw request, encoded in XML
* Returns: XML-encoded response
*/
string handleRequest(string encodedRequest)
{
try
{
// Decode the request
MethodCallData callData;
try
callData = decodeCall(encodedRequest);
catch (Exception ex)
throw new MethodFaultException(ex.msg, FciFaultCodes.serverErrorInvalidXmlRpc);
debug (xmlrpc)
writefln("server <== %s", callData.toString());
MethodResponseData responseData = callMethod(callData);
// Encode the response
debug (xmlrpc)
writefln("server ==> %s", responseData.toString());
return encodeResponse(responseData);
}
catch (MethodFaultException ex)
{
tryLogError("Method fault: %s", ex.msg);
auto responseData = makeMethodFaultResponse(ex);
return encodeResponse(responseData);
}
catch (Exception ex)
{
tryLogError("Server exception: %s", ex);
MethodResponseData responseData;
responseData.fault = true;
responseData.params ~= makeFaultValue(ex.msg, FciFaultCodes.serverErrorInternalXmlRpcError);
return encodeResponse(responseData);
}
}
/**
* Adds one method.
* Throws: MethodExistsException if method already registered
*/
void addRawMethod(RawMethodHandler handler, string name, string help = "", string[][] signatures = null)
{
enforce(name.length, new XmlRpcException("Method name must not be empty"));
if (name in methods_)
throw new MethodExistsException(name);
methods_[name] = MethodInfo(handler, help, signatures);
}
/**
* Removes method if exists, otherwise does nothing
* Returns: True if the method was removed, false otherwise.
*/
nothrow bool removeMethod(string name)
{
return methods_.remove(name);
}
/**
* Lists all registered methods, including system methods.
*/
@property string[] methods() const { return methods_.keys(); }
/**
* Configures error logging. 'null' disables logging.
* Examples:
* --------------------
* server.errorLogHandler = (msg) => write(msg); // Write to stdout
* server.errorLogHandler = null; // Disable logging
* --------------------
*/
@property void errorLogHandler(ErrorLogHandler lh) { errorLogHandler_ = lh; }
@property nothrow ErrorLogHandler errorLogHandler() { return errorLogHandler_; }
private:
MethodResponseData callMethod(MethodCallData callData)
{
try
{
const methodInfoPtr = callData.name in methods_;
if (methodInfoPtr is null)
{
const msg = "Unknown method: " ~ callData.name;
throw new MethodFaultException(msg, FciFaultCodes.serverErrorMethodNotFound);
}
enforce(methodInfoPtr.handler != null, new XmlRpcException("Impossible happens!"));
MethodResponseData responseData;
responseData.params = methodInfoPtr.handler(callData.params);
return responseData;
}
catch (MethodFaultException ex)
{
throw ex; // Propagate further, no conversion required
}
catch (Exception ex)
{
const msg = format("%s:%s: %s: %s", ex.file, ex.line, typeid(ex), ex.msg);
throw new MethodFaultException(msg, FciFaultCodes.applicationError);
}
}
nothrow void tryLogError(S...)(string fmt, S s)
{
if (errorLogHandler_ is null)
return;
try
errorLogHandler_(format(fmt, s) ~ "\n");
catch (Exception ex)
{
debug (xmlrpc)
{
try writefln("Log handler exception: %s", ex);
catch (Exception) { }
}
}
}
static struct MethodInfo
{
RawMethodHandler handler;
string help;
string[][] signatures;
}
ErrorLogHandler errorLogHandler_;
MethodInfo[string] methods_;
}
class MethodExistsException : XmlRpcException
{
private this(string methodName)
{
this.methodName = methodName;
super("Method already exists: " ~ methodName);
}
string methodName;
}
/**
* Registers anything callable as XML-RPC method.
* By default method name is derived from the callable's identifier.
*
* We can't use member function here because that doesn't work with local handlers:
* Error: template instance addMethod!(method) cannot use local 'method' as parameter to non-global template <...>
*/
void addMethod(alias method, string name = __traits(identifier, method))(Server server, string help = "",
string[][] signatures = null)
{
static assert(name.length, "Method name must not be empty");
auto handler = makeRawMethod!method();
server.addRawMethod(handler, name, help, signatures);
}
private:
/**
* Takes anything callable at compile-time, returns delegate that conforms RawMethodHandler type.
* The code that converts XML-RPC types into the native types and back will be generated at compile time.
*/
RawMethodHandler makeRawMethod(alias method)()
{
static assert(isCallable!method, "Method handler must be callable");
alias ParameterTypeTuple!method Input;
alias ReturnType!method Output;
auto tryVariantArrayToParams(Args...)(Variant[] variants)
{
try
return variantArrayToParams!(Args)(variants);
catch (Exception ex)
throw new MethodFaultException(ex.msg, FciFaultCodes.serverErrorInvalidMethodParams);
}
return (Variant[] inputVariant) // Well, the life is getting tough now.
{
static if (Input.length == 0)
{
enforce(inputVariant.length == 0,
new MethodFaultException("Method expects no arguments", FciFaultCodes.serverErrorInvalidMethodParams));
static if (is(Output == void))
method();
else
Output output = method();
}
else
{
Input input = tryVariantArrayToParams!(Input)(inputVariant);
static if (is(Output == void))
method(input);
else
Output output = method(input);
}
static if (is(Output == void))
{
Variant[] dummy;
return dummy;
}
else static if (is(typeof( paramsToVariantArray(output.expand) )))
return paramsToVariantArray(output.expand);
else
return paramsToVariantArray(output);
};
}
MethodResponseData makeMethodFaultResponse(MethodFaultException ex)
{
MethodResponseData responseData;
responseData.fault = true;
responseData.params ~= ex.value;
return responseData;
}
void addSystemMethods(Server server)
{
Server.MethodInfo* findMethod(string methodName)
{
auto infoPtr = methodName in server.methods_;
const msg = "No such method: " ~ methodName;
enforce(infoPtr, new MethodFaultException(msg, -1));
return infoPtr;
}
string[] listMethods() { return server.methods_.keys(); }
string methodHelp(string name) { return findMethod(name).help; }
Variant methodSignature(string name) // This one is tricky
{
auto signatures = findMethod(name).signatures;
if (signatures.length == 0)
return Variant("undef"); // Return type is computed at runtime
Variant[] variantSignatures;
variantSignatures.length = signatures.length;
foreach (signIndex, sign; signatures)
{
Variant[] variantSign;
variantSign.length = sign.length;
foreach (typeIndex, type; sign)
variantSign[typeIndex] = Variant(type);
variantSignatures[signIndex] = variantSign;
}
return Variant(variantSignatures); // Array of arrays of strings
}
string[string][string] getCapabilities()
{
string[string][string] capabilities;
void cap(string name, string specUrl, string specVersion)
{
capabilities[name] = ["specUrl": specUrl, "specVersion": specVersion];
}
cap("xmlrpc", "http://www.xmlrpc.com/spec", "1");
cap("introspection", "http://phpxmlrpc.sourceforge.net/doc-2/ch10.html", "2");
cap("system.multicall", "http://www.xmlrpc.com/discuss/msgReader$1208", "1");
return capabilities;
}
Variant[] multicall(Variant[] calls)
{
MethodResponseData invoke(Variant callParams)
{
MethodCallData callData;
try
{
callData.name = callParams["methodName"].get!string();
callData.params = callParams["params"].get!(Variant[])();
}
catch (VariantException ex)
throw new MethodFaultException(ex.msg, FciFaultCodes.serverErrorInvalidMethodParams);
if (callData.name == "system.multicall")
throw new MethodFaultException("Recursive system.multicall is forbidden", -1);
return server.callMethod(callData);
}
Variant[] responses;
responses.length = calls.length;
foreach (idx, call; calls)
{
MethodResponseData response;
try
response = invoke(call);
catch (MethodFaultException ex)
response = makeMethodFaultResponse(ex);
if (response.fault)
{
assert(response.params.length == 1, "Invalid fault from server: " ~ to!string(response.params));
responses[idx] = response.params[0];
}
else
responses[idx] = response.params;
}
return responses;
}
server.addMethod!(listMethods, "system.listMethods")();
server.addMethod!(methodHelp, "system.methodHelp")();
server.addMethod!(methodSignature, "system.methodSignature")();
server.addMethod!(getCapabilities, "system.getCapabilities")();
server.addMethod!(multicall, "system.multicall")();
}
version (xmlrpc_unittest) unittest
{
import xmlrpc.encoder : encodeCall;
import xmlrpc.decoder : decodeResponse;
import std.math : approxEqual;
import std.typecons : tuple;
import std.exception : assertThrown;
import std.algorithm : canFind;
import std.stdio : writeln, write;
/*
* Issue a request on the server instance
*/
template call(string methodName, ReturnTypes...)
{
auto call(Args...)(Args args)
{
auto requestParams = paramsToVariantArray(args);
auto callData = MethodCallData(methodName, requestParams);
const requestString = encodeCall(callData);
const responseString = server.handleRequest(requestString);
auto responseData = decodeResponse(responseString);
if (responseData.fault)
throw new MethodFaultException(responseData.params[0]);
static if (ReturnTypes.length == 0)
{
assert(responseData.params.length == 0);
return;
}
else
{
return variantArrayToParams!(ReturnTypes)(responseData.params);
}
}
}
auto server = new Server();
server.errorLogHandler = (msg) => write(msg);
/*
* Various combinations of the argument types and the return types are tested below.
* This way we can be sure that the magic inside makeRawMethod() works as expected.
*/
// Returns tuple
auto swap(int a, int b) { return tuple(b, a); }
server.addMethod!swap();
auto resp1 = call!("swap", int, int)(123, 456);
assert(resp1[0] == 456);
assert(resp1[1] == 123);
// Returns scalar
auto doWeirdThing(real a, real b, real c) { return a * b + c; }
server.addMethod!doWeirdThing();
double resp2 = call!("doWeirdThing", double)(1.2, 3.4, 5.6);
assert(approxEqual(resp2, 9.68));
// Takes nothing
auto ultimateAnswer() { return 42; }
server.addMethod!ultimateAnswer();
assert(call!("ultimateAnswer", int)() == 42);
// Returns nothing
void blackHole(dstring s) { assert(s == "goodbye"d); }
server.addMethod!blackHole();
call!"blackHole"("goodbye");
// Takes nothing, returns nothing
void nothingGetsNothingGives() { writefln("Awkward."); }
server.addMethod!nothingGetsNothingGives();
call!"nothingGetsNothingGives"();
/*
* Make sure that the methods can be removed properly
*/
assert(server.removeMethod("nothingGetsNothingGives"));
assert(!server.removeMethod("nothingGetsNothingGives"));
/*
* Error handling
*/
int methodFaultErrorCode(Expr, size_t line = __LINE__)(lazy Expr expression)
{
try
expression();
catch (MethodFaultException ex)
return ex.value["faultCode"].get!int();
assert(false, to!string(line));
}
// Non-existent method
auto errcode = methodFaultErrorCode(call!"nothingGetsNothingGives"());
assert(errcode == FciFaultCodes.serverErrorMethodNotFound);
// Wrong parameter types, non-convertible to int
errcode = methodFaultErrorCode(call!"swap"("ck", "fu"));
assert(errcode == FciFaultCodes.serverErrorInvalidMethodParams);
// Wrong number of arguments
errcode = methodFaultErrorCode(call!"swap"("ck", "fu", "give"));
assert(errcode == FciFaultCodes.serverErrorInvalidMethodParams);
errcode = methodFaultErrorCode(call!"swap"());
assert(errcode == FciFaultCodes.serverErrorInvalidMethodParams);
errcode = methodFaultErrorCode(call!("ultimateAnswer", int)(123, 456));
assert(errcode == FciFaultCodes.serverErrorInvalidMethodParams);
// Malformed XML
auto responseString = server.handleRequest("I am broken XML. <phew>");
auto responseData = decodeResponse(responseString);
assert(responseData.fault);
errcode = responseData.params[0]["faultCode"].get!int();
assert(errcode == FciFaultCodes.serverErrorInvalidXmlRpc);
// Application error
void throwWeirdException() { throw new Exception("Come break me down bury me bury me"); }
server.addMethod!throwWeirdException();
errcode = methodFaultErrorCode(call!"throwWeirdException"());
assert(errcode == FciFaultCodes.applicationError, to!string(errcode));
// Application throws an FCI error
void throwFciException() { throw new MethodFaultException("Hi!", 1); }
server.addMethod!throwFciException();
errcode = methodFaultErrorCode(call!"throwFciException"());
assert(errcode == 1);
/*
* Introspection
*/
auto capabilities = call!("system.getCapabilities", string[string][string])();
assert(capabilities.length == 3);
assert(capabilities["xmlrpc"] == ["specUrl": "http://www.xmlrpc.com/spec", "specVersion": "1"]);
assert(capabilities["introspection"] ==
["specUrl": "http://phpxmlrpc.sourceforge.net/doc-2/ch10.html", "specVersion": "2"]);
assert(capabilities["system.multicall"] ==
["specUrl": "http://www.xmlrpc.com/discuss/msgReader$1208", "specVersion": "1"]);
// Playing with one method and system.listMethods()
assertThrown!MethodExistsException(server.addMethod!swap());
server.removeMethod("swap");
string[] methods = call!("system.listMethods", string[])();
assert(!canFind(methods, "swap"));
server.addMethod!swap("Help string for swap", [["int, int", "int", "int"]]);
methods = call!("system.listMethods", string[])();
assert(canFind(methods, "swap"));
// Checking the help strings
assert(call!("system.methodHelp", string)("swap") == "Help string for swap");
assert(call!("system.methodHelp", string)("ultimateAnswer") == "");
errcode = methodFaultErrorCode(call!("system.methodHelp", string)("noSuchMethod"));
assert(errcode == -1);
// Checking the signatures
string[][] signatures = call!("system.methodSignature", string[][])("swap"); // Return type is string[][]
assert(signatures == [["int, int", "int", "int"]]);
string noSignature = call!("system.methodSignature", string)("ultimateAnswer"); // Return type is string
assert(noSignature == "undef");
/*
* Multicall
*/
Variant[] multicallArgs;
void addCall(Args...)(string method, Args args)
{
auto call = Variant([
"methodName": Variant(method),
"params": Variant(paramsToVariantArray(args))
]);
multicallArgs ~= call;
}
addCall("swap", 123, 456);
addCall("ultimateAnswer");
addCall("ultimateAnswer", "unexpected");
addCall("system.multicall"); // will fail
addCall("throwWeirdException");
Variant[] multicallResponses = call!("system.multicall", Variant[])(multicallArgs);
auto fetchMulticallResponse(Types...)()
{
auto v = multicallResponses[0].get!(Variant[])();
multicallResponses = multicallResponses[1..$];
return variantArrayToParams!(Types)(v);
}
auto assertMulticallFault(int errorCode)
{
auto v = multicallResponses[0];
multicallResponses = multicallResponses[1..$];
writeln("Mulitcall fault: ", v["faultString"].get!string());
assert(errorCode == v["faultCode"].get!int());
}
// swap
auto mcresp = fetchMulticallResponse!(int, int)();
assert(mcresp[0] == 456);
assert(mcresp[1] == 123);
// ultimateAnswer
assert(fetchMulticallResponse!(int)() == 42);
// ultimateAnswer - unepected arg
assertMulticallFault(FciFaultCodes.serverErrorInvalidMethodParams);
// system.multicall
assertMulticallFault(-1);
// throwWeirdException
assertMulticallFault(FciFaultCodes.applicationError);
// Make sure the multicall will not fail on empty request
Variant[] emptyMulticallArgs;
assert(call!("system.multicall", Variant[])(emptyMulticallArgs).length == 0);
}
| D |
# FIXED
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/user/src/32b/user.c
user.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/math.h
user.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/linkage.h
user.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/_defs.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/solutions/instaspin_motion/boards/drv8301kit_revD/f28x/f2806xM/src/user.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/types/src/types.h
user.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/stdbool.h
user.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/string.h
user.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/stdint.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/motor/src/32b/motor.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/est/src/32b/est.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/math/src/32b/math.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/iqmath/src/32b/IQmathLib.h
user.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/limits.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/est/src/est_states.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/est/src/est_Flux_states.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/est/src/est_Ls_states.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/est/src/est_Rs_states.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/ctrl/src/32b/ctrl_obj.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/ctrl/src/ctrl_states.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/clarke/src/32b/clarke.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/park/src/32b/park.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/ipark/src/32b/ipark.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/offset/src/32b/offset.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/filter/src/32b/filter_fo.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/pid/src/32b/pid.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/svgen/src/32b/svgen.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/traj/src/32b/traj.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/vs_freq/src/32b/vs_freq.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/angle_gen/src/32b/angle_gen.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/datalog/src/32b/datalog.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/fast/src/32b/userParams.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/ctrl/src/32b/ctrl.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/hal/boards/drv8301kit_revD/f28x/f2806x/src/hal_obj.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/adc/src/32b/f28x/f2806x/adc.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/cpu/src/32b/f28x/f2806x/cpu.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/clk/src/32b/f28x/f2806x/clk.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/pwm/src/32b/f28x/f2806x/pwm.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/flash/src/32b/f28x/f2806x/flash.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/gpio/src/32b/f28x/f2806x/gpio.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/osc/src/32b/f28x/f2806x/osc.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/pie/src/32b/f28x/f2806x/pie.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/pll/src/32b/f28x/f2806x/pll.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/pwmdac/src/32b/f28x/f2806x/pwmdac.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/pwr/src/32b/f28x/f2806x/pwr.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/spi/src/32b/f28x/f2806x/spi.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/timer/src/32b/f28x/f2806x/timer.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/wdog/src/32b/f28x/f2806x/wdog.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/drivers/drvic/drv8301/src/32b/f28x/f2806x/drv8301.h
user.obj: C:/ti/motorware/motorware_1_01_00_18/sw/modules/usDelay/src/32b/usDelay.h
C:/ti/motorware/motorware_1_01_00_18/sw/modules/user/src/32b/user.c:
C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/math.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/linkage.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/_defs.h:
C:/ti/motorware/motorware_1_01_00_18/sw/solutions/instaspin_motion/boards/drv8301kit_revD/f28x/f2806xM/src/user.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/types/src/types.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/stdbool.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/string.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/stdint.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/motor/src/32b/motor.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/est/src/32b/est.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/math/src/32b/math.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/iqmath/src/32b/IQmathLib.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-c2000_16.9.3.LTS/include/limits.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/est/src/est_states.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/est/src/est_Flux_states.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/est/src/est_Ls_states.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/est/src/est_Rs_states.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/ctrl/src/32b/ctrl_obj.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/ctrl/src/ctrl_states.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/clarke/src/32b/clarke.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/park/src/32b/park.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/ipark/src/32b/ipark.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/offset/src/32b/offset.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/filter/src/32b/filter_fo.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/pid/src/32b/pid.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/svgen/src/32b/svgen.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/traj/src/32b/traj.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/vs_freq/src/32b/vs_freq.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/angle_gen/src/32b/angle_gen.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/datalog/src/32b/datalog.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/fast/src/32b/userParams.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/ctrl/src/32b/ctrl.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/hal/boards/drv8301kit_revD/f28x/f2806x/src/hal_obj.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/adc/src/32b/f28x/f2806x/adc.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/cpu/src/32b/f28x/f2806x/cpu.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/clk/src/32b/f28x/f2806x/clk.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/pwm/src/32b/f28x/f2806x/pwm.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/flash/src/32b/f28x/f2806x/flash.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/gpio/src/32b/f28x/f2806x/gpio.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/osc/src/32b/f28x/f2806x/osc.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/pie/src/32b/f28x/f2806x/pie.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/pll/src/32b/f28x/f2806x/pll.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/pwmdac/src/32b/f28x/f2806x/pwmdac.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/pwr/src/32b/f28x/f2806x/pwr.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/spi/src/32b/f28x/f2806x/spi.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/timer/src/32b/f28x/f2806x/timer.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/wdog/src/32b/f28x/f2806x/wdog.h:
C:/ti/motorware/motorware_1_01_00_18/sw/drivers/drvic/drv8301/src/32b/f28x/f2806x/drv8301.h:
C:/ti/motorware/motorware_1_01_00_18/sw/modules/usDelay/src/32b/usDelay.h:
| D |
<?xml version="1.0" encoding="ASCII" standalone="no"?>
<di:SashWindowsMngr xmlns:di="http://www.eclipse.org/papyrus/0.7.0/sashdi" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmi:version="2.0">
<pageList>
<availablePage>
<emfPageIdentifier href="VAR_9_MobileMedia-4333483641.notation#_copSALmGEeKQQp7P9cQvNQ"/>
</availablePage>
</pageList>
<sashModel currentSelection="//@sashModel/@windows.0/@children.0">
<windows>
<children xsi:type="di:TabFolder">
<children>
<emfPageIdentifier href="VAR_9_MobileMedia-4333483641.notation#_copSALmGEeKQQp7P9cQvNQ"/>
</children>
</children>
</windows>
</sashModel>
</di:SashWindowsMngr>
| D |
module org.serviio.upnp.service.contentdirectory.command.video.ListLastAddedVideosCommand;
import java.lang.String;
import java.util.List;
import org.serviio.config.Configuration;
import org.serviio.library.entities.AccessGroup;
import org.serviio.library.entities.Video;
import org.serviio.library.local.service.VideoService;
import org.serviio.profile.Profile;
import org.serviio.upnp.service.contentdirectory.ObjectType;
import org.serviio.upnp.service.contentdirectory.SearchCriteria;
import org.serviio.upnp.service.contentdirectory.classes.ObjectClassType;
import org.serviio.upnp.service.contentdirectory.command.video.AbstractVideosRetrievalCommand;
public class ListLastAddedVideosCommand : AbstractVideosRetrievalCommand
{
public this(String contextIdentifier, ObjectType objectType, SearchCriteria searchCriteria, ObjectClassType containerClassType, ObjectClassType itemClassType, Profile rendererProfile, AccessGroup accessGroup, String idPrefix, int startIndex, int count, bool disablePresentationSettings)
{
super(contextIdentifier, objectType, searchCriteria, containerClassType, itemClassType, rendererProfile, accessGroup, idPrefix, startIndex, count, disablePresentationSettings);
}
override protected List!(Video) retrieveEntityList()
{
List!(Video) videos = VideoService.getListOfLastAddedVideos(Configuration.getNumberOfFilesForDynamicCategories().intValue(), this.accessGroup, this.startIndex, this.count);
return videos;
}
public int retrieveItemCount()
{
return VideoService.getNumberOfLastAddedVideos(Configuration.getNumberOfFilesForDynamicCategories().intValue(), this.accessGroup);
}
}
/* Location: C:\Users\Main\Downloads\serviio.jar
* Qualified Name: org.serviio.upnp.service.contentdirectory.command.video.ListLastAddedVideosCommand
* JD-Core Version: 0.7.0.1
*/ | D |
/home/andy/source/rust/rust_course/lost_property/learn_stack2/target/rls/debug/deps/learn_stack2-9b6b71a4ccf789c0.rmeta: src/main.rs
/home/andy/source/rust/rust_course/lost_property/learn_stack2/target/rls/debug/deps/learn_stack2-9b6b71a4ccf789c0.d: src/main.rs
src/main.rs:
| D |
module foo.bar;
import core.vararg;
import std.stdio;
pragma (lib, "test");
pragma (msg, "Hello World");
static assert(true, "message");
alias mydbl = double;
int testmain()
in
{
assert(1 + (2 + 3) == -(1 - 2 * 3));
}
out(result)
{
assert(result == 0);
}
body
{
float f = (float).infinity;
int i = cast(int)f;
writeln((i , 1), 2);
writeln(cast(int)(float).max);
assert(i == cast(int)(float).max);
assert(i == 2147483648u);
return 0;
}
struct S
{
int m;
int n;
}
template Foo(T, int V)
{
void foo(...)
{
static if (is(Object _ : X!TL, alias X, TL...))
{
}
auto x = __traits(hasMember, Object, "noMember");
auto y = is(Object : X!TL, alias X, TL...);
assert(!x && !y, "message");
S s = {1, 2};
auto a = [1, 2, 3];
auto aa = [1:1, 2:2, 3:3];
int n, m;
}
int bar(double d, int x)
{
if (d)
{
d++;
}
else
d--;
asm { naked; }
asm { mov EAX,3; }
for (;;)
{
{
d = d + 1;
}
}
for (int i = 0;
i < 10; i++)
{
{
d = i ? d + 1 : 5;
}
}
char[] s;
foreach (char c; s)
{
d *= 2;
if (d)
break;
else
continue;
}
switch (V)
{
case 1:
{
}
case 2:
{
break;
}
case 3:
{
goto case 1;
}
case 4:
{
goto default;
}
default:
{
d /= 8;
break;
}
}
enum Label
{
A,
B,
C,
}
;
void fswitch(Label l)
{
final switch (l)
{
case A:
{
break;
}
case B:
{
break;
}
case C:
{
break;
}
}
}
loop:
while (x)
{
x--;
if (x)
break loop;
else
continue loop;
}
do
{
x++;
}
while (x < 10);
try
{
try
{
bar(1, 2);
}
catch(Object o)
{
x++;
}
}
finally
{
x--;
}
Object o;
synchronized(o) {
x = ~x;
}
synchronized {
x = x < 3;
}
with (o)
{
toString();
}
}
}
static this();
nothrow pure @nogc @safe static this();
nothrow pure @nogc @safe static this();
nothrow pure @nogc @safe shared static this();
nothrow pure @nogc @safe shared static this();
interface iFoo
{
}
class xFoo : iFoo
{
}
interface iFoo2
{
}
class xFoo2 : iFoo, iFoo2
{
}
class Foo3
{
this(int a, ...)
{
}
this(int* a)
{
}
}
alias myint = int;
static notquit = 1;
class Test
{
void a()
{
}
void b()
{
}
void c()
{
}
void d()
{
}
void e()
{
}
void f()
{
}
void g()
{
}
void h()
{
}
void i()
{
}
void j()
{
}
void k()
{
}
void l()
{
}
void m()
{
}
void n()
{
}
void o()
{
}
void p()
{
}
void q()
{
}
void r()
{
}
void s()
{
}
void t()
{
}
void u()
{
}
void v()
{
}
void w()
{
}
void x()
{
}
void y()
{
}
void z()
{
}
void aa()
{
}
void bb()
{
}
void cc()
{
}
void dd()
{
}
void ee()
{
}
template A(T)
{
}
alias getHUint = A!uint;
alias getHInt = A!int;
alias getHFloat = A!float;
alias getHUlong = A!ulong;
alias getHLong = A!long;
alias getHDouble = A!double;
alias getHByte = A!byte;
alias getHUbyte = A!ubyte;
alias getHShort = A!short;
alias getHUShort = A!ushort;
alias getHReal = A!real;
alias void F();
nothrow pure @nogc @safe new(size_t sz)
{
return null;
}
nothrow pure @nogc @safe delete(void* p)
{
}
}
void templ(T)(T val)
{
pragma (msg, "Invalid destination type.");
}
static char[] charArray = ['"', '\''];
class Point
{
auto x = 10;
uint y = 20;
}
template Foo2(bool bar)
{
void test()
{
static if (bar)
{
int i;
}
else
{
}
static if (!bar)
{
}
else
{
}
}
}
template Foo4()
{
void bar()
{
}
}
template Foo4x(T...)
{
}
class Baz4
{
mixin Foo4!() foo;
mixin Foo4x!(int, "str") foox;
alias baz = foo.bar;
}
int test(T)(T t)
{
if (auto o = cast(Object)t)
return 1;
return 0;
}
enum x6 = 1;
bool foo6(int a, int b, int c, int d)
{
return (a < b) != (c < d);
}
auto foo7(int x)
{
return 5;
}
class D8
{
}
void func8()
{
scope a = new D8;
}
T func9(T)() if (true)
{
T i;
scope(exit) i = 1;
scope(success) i = 2;
scope(failure) i = 3;
return i;
}
template V10(T)
{
void func()
{
for (int i, j = 4; i < 3; i++)
{
{
}
}
}
}
int foo11(int function() fn)
{
return fn();
}
int bar11(T)()
{
return foo11(function int()
{
return 0;
}
);
}
struct S6360
{
const pure nothrow @property long weeks1()
{
return 0;
}
const pure nothrow @property long weeks2()
{
return 0;
}
}
struct S12
{
nothrow this(int n)
{
}
nothrow this(string s)
{
}
}
struct T12
{
immutable this()(int args)
{
}
immutable this(A...)(A args)
{
}
}
import std.stdio : writeln, F = File;
void foo6591()()
{
import std.stdio : writeln, F = File;
}
version (unittest)
{
public {}
extern (C) {}
align {}
}
template Foo10334(T) if (Bar10334!())
{
}
template Foo10334(T) if (Bar10334!100)
{
}
template Foo10334(T) if (Bar10334!3.14)
{
}
template Foo10334(T) if (Bar10334!"str")
{
}
template Foo10334(T) if (Bar10334!1.4i)
{
}
template Foo10334(T) if (Bar10334!null)
{
}
template Foo10334(T) if (Bar10334!true)
{
}
template Foo10334(T) if (Bar10334!false)
{
}
template Foo10334(T) if (Bar10334!'A')
{
}
template Foo10334(T) if (Bar10334!int)
{
}
template Foo10334(T) if (Bar10334!string)
{
}
template Foo10334(T) if (Bar10334!wstring)
{
}
template Foo10334(T) if (Bar10334!dstring)
{
}
template Foo10334(T) if (Bar10334!this)
{
}
template Foo10334(T) if (Bar10334!([1, 2, 3]))
{
}
template Foo10334(T) if (Bar10334!(Baz10334!()))
{
}
template Foo10334(T) if (Bar10334!(Baz10334!T))
{
}
template Foo10334(T) if (Bar10334!(Baz10334!100))
{
}
template Foo10334(T) if (Bar10334!(.foo))
{
}
template Foo10334(T) if (Bar10334!(const(int)))
{
}
template Foo10334(T) if (Bar10334!(shared(T)))
{
}
template Test10334(T...)
{
}
mixin Test10334!int a;
mixin Test10334!(int, long) b;
mixin Test10334!"str" c;
auto clamp12266a(T1, T2, T3)(T1 x, T2 min_val, T3 max_val)
{
return 0;
}
pure clamp12266b(T1, T2, T3)(T1 x, T2 min_val, T3 max_val)
{
return 0;
}
@disable pure clamp12266c(T1, T2, T3)(T1 x, T2 min_val, T3 max_val)
{
return 0;
}
alias Dg13832 = ref int delegate();
class TestClass
{
int aa;
int b1;
int b2;
this(int b1, int b2)
{
this.b1 = b1;
this.b2 = b2;
}
ref foo()
{
return aa;
}
ref return retFunc()
{
return aa;
}
@trusted @nogc @disable ~this()
{
}
}
class FooA
{
protected void method42()
{
}
@safe ~this()
{
}
}
class Bar : FooA
{
override void method42()
{
}
}
@trusted double foo()
{
int a = 5;
return a;
}
struct Foo1(size_t Size = 42 / magic())
{
}
size_t magic()
{
return 42;
}
class Foo2A
{
immutable(FooA) Dummy = new immutable(FooA);
private immutable pure nothrow @nogc @safe this()
{
}
}
| D |
module setup;
version(safe) {
@safe:
}
import base;
/// Main setup struct
struct Setup {
private:
string _settingsFileName;
string _settingsSoundsSet;
string _settingsProjectLot;
string _settingsProject;
string _alphabetSet;
string _settingsFont;
int _settingsReadOutPausesMilSecs;
public:
auto settingsSoundsSet() { return _settingsSoundsSet; }
void settingsSoundsSet(in string soundsSet) { _settingsSoundsSet = soundsSet; }
auto settingsProjectLot() { return _settingsProjectLot; }
void settingsProjectLot(in string projectLot) { _settingsProjectLot = projectLot; }
auto settingsProject() { return _settingsProject; }
void settingsProject(in string project) { _settingsProject = project; }
auto alphabetSet() { return _alphabetSet; }
void alphabetSet(in string alphabetSet) { _alphabetSet = alphabetSet; }
auto settingsReadOutPausesMilSecs() { return _settingsReadOutPausesMilSecs; }
void setSettingsFileName(in string fileName) {
_settingsFileName = fileName;
}
auto settingsFont() { return _settingsFont; }
void settingsFont(in string font) {
import std.path: buildPath;
import std.file: exists;
if (buildPath("Fonts", font).exists) {
_settingsFont = font;
} else {
import std.stdio: writeln;
writeln(font, " - not exist!");
}
}
bool fileNameExists() {
import std.file: exists;
return exists(_settingsFileName);
}
void saveSettings() {
import std.stdio: File;
auto file = File(_settingsFileName, "w");
with(file) {
writeln("[settings]");
writefln("soundsSet=%s", _settingsSoundsSet);
writefln("projectLot=%s", _settingsProjectLot);
writefln("project=%s", _settingsProject);
writefln("alphabetSet=%s", _alphabetSet);
writefln("font=%s", _settingsFont);
writefln("readOutPausesMilSecs=%s", _settingsReadOutPausesMilSecs);
}
}
void loadSettings() {
if (fileNameExists) {
import std.conv: to;
auto ini = Ini.Parse(_settingsFileName);
_settingsSoundsSet = ini["settings"].getKey("soundsSet");
_settingsProjectLot = ini["settings"].getKey("projectLot");
_settingsProject = ini["settings"].getKey("project");
_alphabetSet = ini["settings"].getKey("alphabetSet");
settingsFont = ini["settings"].getKey("font");
_settingsReadOutPausesMilSecs = ini["settings"].getKey("readOutPausesMilSecs").to!int;
} else {
import std.stdio: stderr, writeln;
stderr.writeln(_settingsFileName, " - not found");
}
}
int setup() {
import std.stdio: writeln;
writeln("Spell It - Setup started");
import std.path: buildPath;
immutable WELCOME = "Welcome to Spell-It! Press [System] + [Q] to quit";
/+
g_window = new RenderWindow(VideoMode.getDesktopMode, WELCOME);
import jec.setup : setup;
g_font = new Font;
g_font.loadFromFile(buildPath("Fonts", g_setup.settingsFont));
if (! g_font) {
import std.stdio: writeln;
writeln("Font not load");
return -2;
}
g_checkPoints = true;
if (int retVal = jec.setup != 0) {
import std.stdio: writefln;
writefln("File: %s, Error function: %s, Line: %s, Return value: %s", __FILE__, __FUNCTION__, __LINE__, retVal);
return -1;
}
+/
//immutable size = 100, lower = 40;
immutable size = g_fontSize, lower = g_fontSize / 2;
jx = new InputJex(/* position */ Point(0, SCREEN_HEIGHT - size - lower),
/* font size */ size,
/* header */ "Word: ",
/* Type (oneLine, or history) */ InputType.history);
jx.setColour(Color(255, 200, 0));
jx.addToHistory(""d);
jx.edge = false;
g_terminal = true;
jx.addToHistory(WELCOME);
jx.showHistory = false;
//g_window.setFramerateLimit(60);
writeln("Spell It - Setup finished");
return 0;
}
}
| D |
import std.stdio;
import std.file;
import std.string;
import std.range;
import std.regex;
import std.algorithm;
int main(string[] args)
{
bool error;
auto r = regex(r" +\n");
foreach(a; args[1..$])
{
auto str = a.readText();
if (str.canFind("\r\n"))
{
writefln("Error - file '%s' contains windows line endings", a);
error = true;
}
if (str.canFind('\t'))
{
writefln("Error - file '%s' contains tabs", a);
error = true;
}
if (!str.matchFirst(r).empty)
{
writefln("Error - file '%s' contains trailing whitespace", a);
error = true;
}
}
return error ? 1 : 0;
}
| D |
instance GRD_214_Torwache (Npc_Default)
{
//-------- primary data --------
name = NAME_Torwache;
npctype = npctype_ambient;
guild = GIL_GRD;
level = 15;
voice = 7;
id = 214;
//-------- abilities --------
attribute[ATR_STRENGTH] = 70;
attribute[ATR_DEXTERITY] = 50;
attribute[ATR_MANA_MAX] = 0;
attribute[ATR_MANA] = 0;
attribute[ATR_HITPOINTS_MAX]= 220;
attribute[ATR_HITPOINTS] = 220;
//-------- visuals --------
// animations
Mdl_SetVisual (self,"HUMANS.MDS");
Mdl_ApplyOverlayMds (self,"Humans_Militia.mds");
// body mesh ,bdytex,skin,head mesh ,headtex,teethtex,ruestung
Mdl_SetVisualBody (self,"hum_body_Naked0",0,0,"Hum_Head_Bald",2,3,GRD_ARMOR_M);
B_Scale (self);
Mdl_SetModelFatness(self,0);
Npc_SetAivar(self,AIV_IMPORTANT, TRUE);
fight_tactic = FAI_HUMAN_STRONG;
//-------- Talente --------
Npc_SetTalentSkill (self,NPC_TALENT_1H,1);
//-------- inventory --------
CreateInvItem (self,GRD_MW_02);
CreateInvItem (self,ItFoApple);
CreateInvItems (self,ItMiNugget,10);
//-------------Daily Routine-------------
/*B_InitNPCAddins(self);*/ daily_routine = Rtn_start_214;
};
FUNC VOID Rtn_start_214 ()
{
TA_Guard (06,00,21,00,"OCR_MAINGATE_LEFT_GUARD");
TA_Guard (21,00,06,00,"OCR_MAINGATE_LEFT_GUARD");
};
FUNC VOID Rtn_FMTaken_214 ()
{
TA_StayNeutral (06,00,21,00,"OCR_MAINGATE_LEFT_GUARD");
TA_StayNeutral (21,00,06,00,"OCR_MAINGATE_LEFT_GUARD");
};
FUNC VOID Rtn_FMTaken2_214 ()
{
TA_Guard (06,00,21,00,"OCR_MAINGATE_LEFT_GUARD");
TA_Guard (21,00,06,00,"OCR_MAINGATE_LEFT_GUARD");
};
FUNC VOID Rtn_NC1_214 ()
{
TA_HostileGuard (06,00,21,00,"NC_HUT02_OUT");
TA_HostileGuard (21,00,06,00,"NC_HUT02_OUT");
};
| D |
/Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Build/Intermediates/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/InfiniteSequence.o : /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Deprecated.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Cancelable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObservableType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObserverType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Reactive.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/RecursiveLock.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DeprecationWarner.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Errors.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/AtomicInt.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Event.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/First.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Rx.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/Platform.Linux.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/Target\ Support\ Files/RxAtomic/RxAtomic-umbrella.h /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxAtomic/RxAtomic/include/RxAtomic.h /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Build/Intermediates/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Build/Intermediates/Pods.build/Debug-iphonesimulator/RxAtomic.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Build/Intermediates/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/InfiniteSequence~partial.swiftmodule : /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Deprecated.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Cancelable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObservableType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObserverType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Reactive.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/RecursiveLock.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DeprecationWarner.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Errors.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/AtomicInt.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Event.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/First.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Rx.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/Platform.Linux.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/Target\ Support\ Files/RxAtomic/RxAtomic-umbrella.h /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxAtomic/RxAtomic/include/RxAtomic.h /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Build/Intermediates/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Build/Intermediates/Pods.build/Debug-iphonesimulator/RxAtomic.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Build/Intermediates/Pods.build/Debug-iphonesimulator/RxSwift.build/Objects-normal/x86_64/InfiniteSequence~partial.swiftdoc : /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Amb.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Deferred.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Deprecated.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Enumerated.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Maybe.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Sequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/ObservableType+PrimitiveSequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Debounce.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Reduce.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Range.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Merge.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Take.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Cancelable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Completable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/GroupedObservable.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Single.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/AsSingle.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Sample.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Throttle.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObservableType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ConnectableObservableType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/SchedulerType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObserverType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/SubjectType.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Create.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Generate.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/Queue.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Reactive.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Materialize.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/AddRef.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DataStructures/Bag.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Using.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Debug.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Catch.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Switch.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/StartWith.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/Lock.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/RecursiveLock.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Sink.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Optional.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Scan.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/Platform.Darwin.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Do.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Map.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Zip.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Skip.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Producer.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Buffer.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Timer.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DeprecationWarner.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Filter.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Never.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/AnyObserver.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Error.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Disposables/Disposables.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Errors.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ElementAt.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Concat.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Repeat.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/AtomicInt.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Event.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/SwiftSupport/SwiftSupport.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/TakeLast.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Multicast.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/First.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Just.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Timeout.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Window.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Extensions/String+Rx.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Rx.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/RxMutableBox.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/Platform/Platform.Linux.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/GroupBy.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Delay.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/ToArray.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/Empty.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/Target\ Support\ Files/RxAtomic/RxAtomic-umbrella.h /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/Target\ Support\ Files/RxSwift/RxSwift-umbrella.h /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Pods/RxAtomic/RxAtomic/include/RxAtomic.h /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Build/Intermediates/Pods.build/Debug-iphonesimulator/RxSwift.build/unextended-module.modulemap /Users/bernardo.tolosa/Documents/workspace/iosworks/basicmvvm/Build/Intermediates/Pods.build/Debug-iphonesimulator/RxAtomic.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/OpenGLES.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreImage.framework/Headers/CoreImage.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/QuartzCore.framework/Headers/QuartzCore.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Metal.framework/Headers/Metal.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
| D |
import std.stdio;
import std.string;
import std.array;
int[] dx = [0, -1, 0, 1, 0];
int[] dy = [-1, 0, 0, 0, 1];
string str;
string[10] s;
char[10][10] ch;
int[10][10] ans;
void main(){
int n;
readf("%d\n", &n);
for (int i = 0; i < n; i++) {
foreach (j; 0..10) s[j] = replace(chomp(readln()), " ", "");
// try all patterns in 1st line
for (int j = 0; j < 2^^10 ; j++) {
str = format("%010b", j);
foreach (k; 0..10) {
ch[k] = s[k];
ans[k] = 0;
}
if (solve()) break;
}
// print
foreach (y; 0..10) {
write(ans[y][0]);
foreach (x; 1..10) {
write(" ", ans[y][x]);
}
writeln();
}
}
}
void toggle(int px, int py){
int x, y;
foreach (i; 0..5) {
x = dx[i]+px;
y = dy[i]+py;
if (x < 0 || x > 9 || y < 0 || y > 9) continue;
if(ch[y][x] == '0') ch[y][x] = '1';
else ch[y][x] = '0';
}
}
bool solve(){
foreach (y; 0..10) {
foreach (x; 0..10) {
if ((y == 0 && str[x] == '1') || (y > 0 && ch[y-1][x] == '1')) {
toggle(x, y);
ans[y][x] = 1;
}
}
}
// check
foreach (y; 0..10)
foreach (x; 0..10)
if (ch[y][x] == '1') return false;
return true;
}
| D |
/Users/Avinash/Documents/Code/Guru/Guru/DerivedData/Guru/Build/Intermediates/Pods.build/Debug-iphonesimulator/Cosmos.build/Objects-normal/x86_64/CosmosLocalizedRating.o : /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosAccessibility.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosDefaultSettings.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosLayerHelper.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosLayers.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosLocalizedRating.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosRating.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosSettings.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosSize.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosText.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosTouch.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/Helpers/CosmosTouchTarget.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosView.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/Helpers/RightToLeft.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/StarFillMode.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/StarLayer.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/Avinash/Documents/Code/Guru/Guru/Pods/Target\ Support\ Files/Cosmos/Cosmos-umbrella.h /Users/Avinash/Documents/Code/Guru/Guru/DerivedData/Guru/Build/Intermediates/Pods.build/Debug-iphonesimulator/Cosmos.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule
/Users/Avinash/Documents/Code/Guru/Guru/DerivedData/Guru/Build/Intermediates/Pods.build/Debug-iphonesimulator/Cosmos.build/Objects-normal/x86_64/CosmosLocalizedRating~partial.swiftmodule : /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosAccessibility.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosDefaultSettings.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosLayerHelper.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosLayers.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosLocalizedRating.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosRating.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosSettings.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosSize.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosText.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosTouch.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/Helpers/CosmosTouchTarget.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosView.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/Helpers/RightToLeft.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/StarFillMode.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/StarLayer.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/Avinash/Documents/Code/Guru/Guru/Pods/Target\ Support\ Files/Cosmos/Cosmos-umbrella.h /Users/Avinash/Documents/Code/Guru/Guru/DerivedData/Guru/Build/Intermediates/Pods.build/Debug-iphonesimulator/Cosmos.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule
/Users/Avinash/Documents/Code/Guru/Guru/DerivedData/Guru/Build/Intermediates/Pods.build/Debug-iphonesimulator/Cosmos.build/Objects-normal/x86_64/CosmosLocalizedRating~partial.swiftdoc : /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosAccessibility.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosDefaultSettings.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosLayerHelper.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosLayers.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosLocalizedRating.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosRating.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosSettings.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosSize.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosText.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosTouch.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/Helpers/CosmosTouchTarget.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/CosmosView.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/Helpers/RightToLeft.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/StarFillMode.swift /Users/Avinash/Documents/Code/Guru/Guru/Pods/Cosmos/Cosmos/StarLayer.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Users/Avinash/Documents/Code/Guru/Guru/Pods/Target\ Support\ Files/Cosmos/Cosmos-umbrella.h /Users/Avinash/Documents/Code/Guru/Guru/DerivedData/Guru/Build/Intermediates/Pods.build/Debug-iphonesimulator/Cosmos.build/unextended-module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule
| D |
module android.java.android.provider.ContactsContract_CommonDataKinds_Identity;
public import android.java.android.provider.ContactsContract_CommonDataKinds_Identity_d_interface;
import arsd.jni : ImportExportImpl;
mixin ImportExportImpl!ContactsContract_CommonDataKinds_Identity;
import import0 = android.java.java.lang.Class;
| D |
/**
* DMD-specific parameters.
*
* Copyright: Copyright (C) 1999-2023 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/dmdparams.d, _dmdparams.d)
* Documentation: https://dlang.org/phobos/dmd_dmdparams.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dmdparams.d
*/
module dmd.dmdparams;
import dmd.target;
/// Position Indepent Code setting
enum PIC : ubyte
{
fixed, /// located at a specific address
pic, /// Position Independent Code
pie, /// Position Independent Executable
}
struct DMDparams
{
bool alwaysframe; // always emit standard stack frame
ubyte dwarf; // DWARF version
bool map; // generate linker .map file
bool vasm; // print generated assembler for each function
bool dll; // generate shared dynamic library
bool lib; // write library file instead of object file(s)
bool link = true; // perform link
bool oneobj; // write one object file instead of multiple ones
bool optimize; // run optimizer
bool nofloat; // code should not pull in floating point support
bool ibt; // generate indirect branch tracking
PIC pic = PIC.fixed; // generate fixed, pic or pie code
bool stackstomp; // add stack stomping code
bool symdebug; // insert debug symbolic information
bool symdebugref; // insert debug information for all referenced types, too
const(char)[] defaultlibname; // default library for non-debug builds
const(char)[] debuglibname; // default library for debug builds
const(char)[] mscrtlib; // MS C runtime library
// Hidden debug switches
bool debugb;
bool debugc;
bool debugf;
bool debugr;
bool debugx;
bool debugy;
}
/**
Sets CPU Operating System, and optionally C/C++ runtime environment from the given triple
e.g.
x86_64+avx2-apple-darwin20.3.0
x86-unknown-linux-musl-clang
x64-windows-msvc
x64-pc-windows-msvc
*/
struct Triple
{
private const(char)[] source;
CPU cpu;
bool isX86_64;
bool isLP64;
Target.OS os;
ubyte osMajor;
TargetC.Runtime cenv;
TargetCPP.Runtime cppenv;
this(const(char)* _triple)
{
import dmd.root.string : toDString, toCStringThen;
const(char)[] triple = _triple.toDString();
const(char)[] next()
{
size_t i = 0;
const tmp = triple;
while (triple.length && triple[0] != '-')
{
triple = triple[1 .. $];
++i;
}
if (triple.length && triple[0] == '-')
{
triple = triple[1 .. $];
}
return tmp[0 .. i];
}
parseArch(next);
const(char)[] vendorOrOS = next();
const(char)[] _os;
if (tryParseVendor(vendorOrOS))
_os = next();
else
_os = vendorOrOS;
os = parseOS(_os, osMajor);
const(char)[] _cenv = next();
if (_cenv.length)
cenv = parseCEnv(_cenv);
else if (this.os == Target.OS.Windows)
cenv = TargetC.Runtime.Microsoft;
const(char)[] _cppenv = next();
if (_cppenv.length)
cppenv = parseCPPEnv(_cppenv);
else if (this.os == Target.OS.Windows)
cppenv = TargetCPP.Runtime.Microsoft;
}
private extern(D):
void unknown(const(char)[] unk, const(char)* what)
{
import dmd.errors : error;
import dmd.root.string : toCStringThen;
import dmd.location;
unk.toCStringThen!(p => error(Loc.initial,"unknown %s `%s` for `-target`", what, p.ptr));
}
void parseArch(const(char)[] arch)
{
bool matches(const(char)[] str)
{
import dmd.root.string : startsWith;
if (!arch.ptr.startsWith(str))
return false;
arch = arch[str.length .. $];
return true;
}
if (matches("x86_64"))
isX86_64 = true;
else if (matches("x86"))
isX86_64 = false;
else if (matches("x64"))
isX86_64 = true;
else if (matches("x32"))
{
isX86_64 = true;
isLP64 = false;
}
else
return unknown(arch, "architecture");
if (!arch.length)
return;
switch (arch)
{
case "+sse2": cpu = CPU.sse2; break;
case "+avx": cpu = CPU.avx; break;
case "+avx2": cpu = CPU.avx2; break;
default:
unknown(arch, "architecture feature");
}
}
// try parsing vendor if present
bool tryParseVendor(const(char)[] vendor) @safe
{
switch (vendor)
{
case "unknown": return true;
case "apple": return true;
case "pc": return true;
case "amd": return true;
default: return false;
}
}
/********************************
* Parse OS and osMajor version number.
* Params:
* _os = string to check for operating system followed by version number
* osMajor = set to version number (if any), otherwise set to 0.
* Set to 255 if version number is 255 or larger and error is generated
* Returns:
* detected operating system, Target.OS.none if none
*/
Target.OS parseOS(const(char)[] _os, out ubyte osMajor)
{
import dmd.errors : error;
import dmd.location;
bool matches(const(char)[] str)
{
import dmd.root.string : startsWith;
if (!_os.ptr.startsWith(str))
return false;
_os = _os[str.length .. $];
return true;
}
Target.OS os;
if (matches("darwin"))
os = Target.OS.OSX;
else if (matches("dragonfly"))
os = Target.OS.DragonFlyBSD;
else if (matches("freebsd"))
os = Target.OS.FreeBSD;
else if (matches("openbsd"))
os = Target.OS.OpenBSD;
else if (matches("linux"))
os = Target.OS.linux;
else if (matches("windows"))
os = Target.OS.Windows;
else
{
unknown(_os, "operating system");
return Target.OS.none;
}
bool overflow;
auto major = parseNumber(_os, overflow);
if (overflow || major >= 255)
{
error(Loc.initial, "OS version overflowed max of 254");
major = 255;
}
osMajor = cast(ubyte)major;
/* Note that anything after the number up to the end or '-',
* such as '.3.4.hello.betty', is ignored
*/
return os;
}
/*******************************
* Parses a decimal number out of the str and returns it.
* Params:
* str = string to parse the number from, updated to text after the number
* overflow = set to true iff an overflow happens
* Returns:
* parsed number
*/
private pure @safe static
uint parseNumber(ref const(char)[] str, ref bool overflow)
{
auto s = str;
ulong n;
while (s.length)
{
const c = s[0];
if (c < '0' || '9' < c)
break;
n = n * 10 + (c - '0');
overflow |= (n > uint.max); // sticky overflow check
s = s[1 .. $]; // consume digit
}
str = s;
return cast(uint)n;
}
TargetC.Runtime parseCEnv(const(char)[] cenv)
{
with (TargetC.Runtime) switch (cenv)
{
case "musl": return Musl;
case "msvc": return Microsoft;
case "bionic": return Bionic;
case "digital_mars": return DigitalMars;
case "newlib": return Newlib;
case "uclibc": return UClibc;
case "glibc": return Glibc;
default:
{
unknown(cenv, "C runtime environment");
return Unspecified;
}
}
}
TargetCPP.Runtime parseCPPEnv(const(char)[] cppenv)
{
with (TargetCPP.Runtime) switch (cppenv)
{
case "clang": return Clang;
case "gcc": return Gcc;
case "msvc": return Microsoft;
case "sun": return Sun;
case "digital_mars": return DigitalMars;
default:
{
unknown(cppenv, "C++ runtime environment");
return Unspecified;
}
}
}
}
void setTriple(ref Target target, const ref Triple triple) @safe
{
target.cpu = triple.cpu;
target.isX86_64 = triple.isX86_64;
target.isLP64 = triple.isLP64;
target.os = triple.os;
target.osMajor = triple.osMajor;
target.c.runtime = triple.cenv;
target.cpp.runtime = triple.cppenv;
}
/**
Returns: the final defaultlibname based on the command-line parameters
*/
extern (D) const(char)[] finalDefaultlibname()
{
import dmd.globals : global;
return global.params.betterC ? null :
driverParams.symdebug ? driverParams.debuglibname : driverParams.defaultlibname;
}
__gshared DMDparams driverParams = DMDparams.init;
| D |
/**
* cl4d - object-oriented wrapper for the OpenCL C API
* written in the D programming language
*
* Copyright:
* (C) 2009-2011 Andreas Hollandt
*
* License:
* see LICENSE.txt
*/
module opencl.image;
import opencl.c.cl;
import opencl.c.cl_gl;
import opencl.context;
import opencl.error;
import opencl.memory;
import opencl.wrapper;
/**
* base class for the different image types
*
* used to store a one-, two- or three- dimensional texture, frame-buffer or image.
* The elements of an image object are selected from a list of predefined image formats.
* The minimum number of elements in a memory object is one
*/
struct CLImage
{
CLMemory sup;
alias sup this;
this(cl_mem obj)
{
sup = CLMemory(obj);
}
@property
{
//!image format descriptor specified when image was created
auto format()
{
return this.getInfo!(cl_image_format, clGetImageInfo)(CL_IMAGE_FORMAT);
}
/**
* size of each element of the image memory object given by image. An
* element is made up of n channels. The value of n is given in cl_image_format descriptor.
*/
size_t elementSize()
{
return this.getInfo!(size_t, clGetImageInfo)(CL_IMAGE_ELEMENT_SIZE);
}
//! size in bytes of a row of elements of the image object given by image
size_t rowPitch()
{
return this.getInfo!(size_t, clGetImageInfo)(CL_IMAGE_ROW_PITCH);
}
/**
* size in bytes of a 2D slice for the 3D image object given by image.
*
* For a 2D image object this value will be 0.
*/
size_t slicePitch()
{
return this.getInfo!(size_t, clGetImageInfo)(CL_IMAGE_SLICE_PITCH);
}
//! width in pixels
size_t width()
{
return this.getInfo!(size_t, clGetImageInfo)(CL_IMAGE_WIDTH);
}
//! height in pixels
size_t height()
{
return this.getInfo!(size_t, clGetImageInfo)(CL_IMAGE_HEIGHT);
}
/**
* depth of the image in pixels
*
* For a 2D image object, depth = 0
*/
size_t depth()
{
return this.getInfo!(size_t, clGetImageInfo)(CL_IMAGE_DEPTH);
}
//! The target argument specified in CLImage2DGL, CLImage3DGL constructors
cl_GLenum textureTarget()
{
return this.getInfo!(cl_GLenum, clGetGLTextureInfo)(CL_GL_TEXTURE_TARGET);
}
//! The miplevel argument specified in CLImage2DGL, CLImage3DGL constructors
cl_GLint mipmapLevel()
{
return this.getInfo!(cl_GLint, clGetGLTextureInfo)(CL_GL_MIPMAP_LEVEL);
}
} // of @property
}
//! 2D Image
struct CLImage2D
{
CLImage sup;
alias sup this;
this(cl_mem obj)
{
sup = CLImage(obj);
}
/**
* Params:
* flags = used to specify allocation and usage info for the image object
* format = describes image format properties
* rowPitch= scan-line pitch in bytes
* hostPtr = can be a pointer to host-allocated image data to be used
*/
this(CLContext context, cl_mem_flags flags, const cl_image_format format, size_t width, size_t height, size_t rowPitch, void* hostPtr = null)
{
// call "base constructor"
cl_errcode res;
sup = CLImage(clCreateImage2D(context.cptr, flags, &format, width, height, rowPitch, hostPtr, &res));
mixin(exceptionHandling(
["CL_INVALID_CONTEXT", ""],
["CL_INVALID_VALUE", "invalid image flags"],
["CL_INVALID_IMAGE_FORMAT_DESCRIPTOR", "values specified in format are not valid or format is null"],
["CL_INVALID_IMAGE_SIZE", "width or height are 0 OR exceed CL_DEVICE_IMAGE2D_MAX_WIDTH or CL_DEVICE_IMAGE2D_MAX_HEIGHT resp. OR rowPitch is not valid"],
["CL_INVALID_HOST_PTR", "hostPtr is null and CL_MEM_USE_HOST_PTR or CL_MEM_COPY_HOST_PTR are set in flags or if hostPtr is not null but CL_MEM_COPY_HOST_PTR or CL_MEM_USE_HOST_PTR are not set in"],
["CL_IMAGE_FORMAT_NOT_SUPPORTED", "format is not supported"],
["CL_MEM_OBJECT_ALLOCATION_FAILURE", "couldn't allocate memory for image object"],
["CL_INVALID_OPERATION", "there are no devices in context that support images (i.e. CL_DEVICE_IMAGE_SUPPORT is CL_FALSE)"],
["CL_OUT_OF_RESOURCES", ""],
["CL_OUT_OF_HOST_MEMORY", ""]
));
}
}
//! 2D image for GL interop.
struct CLImage2DGL
{
CLImage2D sup;
alias sup this;
/**
* creates an OpenCL 2D image object from an OpenGL 2D texture object, or a single face of an OpenGL cubemap texture object
*
* Params:
* flags = only CL_MEM_READ_ONLY, CL_MEM_WRITE_ONLY and CL_MEM_READ_WRITE may be used
* target = used only to define the image type of texture. No reference to a bound GL texture object is made or implied by this parameter
* miplevel= mipmap level to be used
* texobj = name of a complete GL 2D, cubemap or rectangle texture object
*/
this(const CLContext context, cl_mem_flags flags, cl_GLenum target, cl_GLint miplevel, cl_GLuint texobj)
{
// call "base constructor"
cl_errcode res;
sup = CLImage2D(clCreateFromGLTexture2D(context.cptr, flags, target, miplevel, texobj, &res));
mixin(exceptionHandling(
["CL_INVALID_CONTEXT", "context is not a valid context or was not created from a GL context"],
["CL_INVALID_VALUE", "flags or target not valid"],
["CL_INVALID_MIP_LEVEL", "miplevel is invalid OR OpenGL implementation does not support creating from mipmap levels > 0"],
["CL_INVALID_GL_OBJECT", "texobj is not a GL texture object whose type matches target OR the specified miplevel of texture is not defined OR width or height of the specified miplevel is zero"],
["CL_INVALID_IMAGE_FORMAT_DESCRIPTOR", "the OpenGL texture internal format does not map to a supported OpenCL image format"],
["CL_INVALID_OPERATION", "texobj is a GL texture object created with a border width value greater than zero (OR implementation does not support miplevel values > 0?)"],
["CL_OUT_OF_RESOURCES", ""],
["CL_OUT_OF_HOST_MEMORY", ""]
));
}
}
//! 3D Image
struct CLImage3D
{
CLImage sup;
alias sup this;
this(cl_mem obj)
{
sup = CLImage(obj);
}
/**
* Params:
* flags = used to specify allocation and usage info for the image object
* format = describes image format properties
* rowPitch = scan-line pitch in bytes
* slicePitch = size in bytes of each 2D slice in the 3D image
* hostPtr = can be a pointer to host-allocated image data to be used
*/
this(CLContext context, cl_mem_flags flags, const cl_image_format format, size_t width, size_t height, size_t depth, size_t rowPitch, size_t slicePitch, void* hostPtr = null)
{
// call "base constructor"
cl_errcode res;
sup = CLImage(clCreateImage3D(context.cptr, flags, &format, width, height, depth, rowPitch, slicePitch, hostPtr, &res));
mixin(exceptionHandling(
["CL_INVALID_CONTEXT", ""],
["CL_INVALID_VALUE", "invalid image flags"],
["CL_INVALID_IMAGE_FORMAT_DESCRIPTOR", "values specified in format are not valid or format is null"],
["CL_INVALID_IMAGE_SIZE", "width or height are 0 or depth <= 1 OR exceed CL_DEVICE_IMAGE3D_MAX_WIDTH or CL_DEVICE_IMAGE3D_MAX_HEIGHT or CL_DEVICE_IMAGE3D_MAX_DEPTH resp. OR rowPitch or slicePitch is not valid"],
["CL_INVALID_HOST_PTR", "hostPtr is null and CL_MEM_USE_HOST_PTR or CL_MEM_COPY_HOST_PTR are set in flags or if hostPtr is not null but CL_MEM_COPY_HOST_PTR or CL_MEM_USE_HOST_PTR are not set in"],
["CL_IMAGE_FORMAT_NOT_SUPPORTED", "format is not supported"],
["CL_MEM_OBJECT_ALLOCATION_FAILURE", "couldn't allocate memory for image object"],
["CL_INVALID_OPERATION", "there are no devices in context that support images (i.e. CL_DEVICE_IMAGE_SUPPORT is CL_FALSE)"],
["CL_OUT_OF_RESOURCES", ""],
["CL_OUT_OF_HOST_MEMORY", ""]
));
}
}
//! 3D image for GL interop.
struct CLImage3DGL
{
CLImage3D sup;
alias sup this;
/**
* creates an OpenCL 3D image object from an OpenGL 3D texture object
*
* Params:
* flags = only CL_MEM_READ_ONLY, CL_MEM_WRITE_ONLY and CL_MEM_READ_WRITE may be used
* target = used only to define the image type of texture. No reference to a bound GL texture object is made or implied by this parameter. must be GL_TEXTURE_3D
* miplevel= mipmap level to be used
* texobj = name of a complete GL 3D texture object
*/
this(const CLContext context, cl_mem_flags flags, cl_GLenum target, cl_GLint miplevel, cl_GLuint texobj)
{
cl_errcode res;
sup = CLImage3D(clCreateFromGLTexture3D(context.cptr, flags, target, miplevel, texobj, &res));
mixin(exceptionHandling(
["CL_INVALID_CONTEXT", "context is not a valid context or was not created from a GL context"],
["CL_INVALID_VALUE", "flags or target not valid"],
["CL_INVALID_MIP_LEVEL", "miplevel is invalid OR OpenGL implementation does not support creating from mipmap levels > 0"],
["CL_INVALID_GL_OBJECT", "texobj is not a GL texture object whose type matches target OR the specified miplevel of texture is not defined OR width or height of the specified miplevel is zero"],
["CL_INVALID_IMAGE_FORMAT_DESCRIPTOR", "the OpenGL texture internal format does not map to a supported OpenCL image format"],
["CL_INVALID_OPERATION", "texobj is a GL texture object created with a border width value greater than zero (OR implementation does not support miplevel values > 0?)"],
["CL_OUT_OF_RESOURCES", ""],
["CL_OUT_OF_HOST_MEMORY", ""]
));
}
}
| D |
// Written in the D programming language.
/**
<script type="text/javascript">inhibitQuickIndex = 1</script>
$(BOOKTABLE ,
$(TR $(TH Category) $(TH Functions)
)
$(TR $(TDNW Searching) $(TD $(MYREF balancedParens) $(MYREF
boyerMooreFinder) $(MYREF canFind) $(MYREF count) $(MYREF countUntil)
$(MYREF endsWith) $(MYREF find) $(MYREF findAdjacent) $(MYREF
findAmong) $(MYREF findSkip) $(MYREF findSplit) $(MYREF
findSplitAfter) $(MYREF findSplitBefore) $(MYREF indexOf) $(MYREF
minCount) $(MYREF minPos) $(MYREF mismatch) $(MYREF skipOver) $(MYREF
startsWith) $(MYREF until) )
)
$(TR $(TDNW Comparison) $(TD $(MYREF cmp) $(MYREF equal) $(MYREF
levenshteinDistance) $(MYREF levenshteinDistanceAndPath) $(MYREF max)
$(MYREF min) $(MYREF mismatch) )
)
$(TR $(TDNW Iteration) $(TD $(MYREF filter) $(MYREF filterBidirectional)
$(MYREF group) $(MYREF joiner) $(MYREF map) $(MYREF reduce) $(MYREF
splitter) $(MYREF uniq) )
)
$(TR $(TDNW Sorting) $(TD $(MYREF completeSort) $(MYREF isPartitioned)
$(MYREF isSorted) $(MYREF makeIndex) $(MYREF partialSort) $(MYREF
partition) $(MYREF partition3) $(MYREF schwartzSort) $(MYREF sort)
$(MYREF topN) $(MYREF topNCopy) )
)
$(TR $(TDNW Set operations) $(TD $(MYREF
largestPartialIntersection) $(MYREF largestPartialIntersectionWeighted)
$(MYREF nWayUnion) $(MYREF setDifference) $(MYREF setIntersection) $(MYREF
setSymmetricDifference) $(MYREF setUnion) )
)
$(TR $(TDNW Mutation) $(TD $(MYREF bringToFront) $(MYREF copy) $(MYREF
fill) $(MYREF initializeAll) $(MYREF move) $(MYREF moveAll) $(MYREF
moveSome) $(MYREF remove) $(MYREF reverse) $(MYREF swap) $(MYREF
swapRanges) $(MYREF uninitializedFill) ))
)
Implements algorithms oriented mainly towards processing of
sequences. Some functions are semantic equivalents or supersets of
those found in the $(D $(LESS)_algorithm$(GREATER)) header in $(WEB
sgi.com/tech/stl/, Alexander Stepanov's Standard Template Library) for
C++.
Many functions in this module are parameterized with a function or a
$(GLOSSARY predicate). The predicate may be passed either as a
function name, a delegate name, a $(GLOSSARY functor) name, or a
compile-time string. The string may consist of $(B any) legal D
expression that uses the symbol $(D a) (for unary functions) or the
symbols $(D a) and $(D b) (for binary functions). These names will NOT
interfere with other homonym symbols in user code because they are
evaluated in a different context. The default for all binary
comparison predicates is $(D "a == b") for unordered operations and
$(D "a < b") for ordered operations.
Example:
----
int[] a = ...;
static bool greater(int a, int b)
{
return a > b;
}
sort!(greater)(a); // predicate as alias
sort!("a > b")(a); // predicate as string
// (no ambiguity with array name)
sort(a); // no predicate, "a < b" is implicit
----
$(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description)
)
$(LEADINGROW Searching
)
$(TR $(TDNW $(LREF balancedParens)) $(TD $(D
balancedParens("((1 + 1) / 2)")) returns $(D true) because the string
has balanced parentheses.)
)
$(TR $(TDNW $(LREF boyerMooreFinder)) $(TD $(D find("hello
world", boyerMooreFinder("or"))) returns $(D "orld") using the $(LUCKY
Boyer-Moore _algorithm).)
)
$(TR $(TDNW $(LREF canFind)) $(TD $(D canFind("hello world",
"or")) returns $(D true).)
)
$(TR $(TDNW $(LREF count)) $(TD Counts elements that are equal
to a specified value or satisfy a predicate. $(D count([1, 2, 1], 1))
returns $(D 2) and $(D count!"a < 0"([1, -3, 0])) returns $(D 1).)
)
$(TR $(TDNW $(LREF countUntil)) $(TD $(D countUntil(a, b))
returns the number of steps taken in $(D a) to reach $(D b); for
example, $(D countUntil("hello!", "o")) returns $(D 4).)
)
$(TR $(TDNW $(LREF endsWith)) $(TD $(D endsWith("rocks", "ks"))
returns $(D true).)
)
$(TR $(TD $(LREF find)) $(TD $(D find("hello world",
"or")) returns $(D "orld") using linear search.)
)
$(TR $(TDNW $(LREF findAdjacent)) $(TD $(D findAdjacent([1, 2,
3, 3, 4])) returns the subrange starting with two equal adjacent
elements, i.e. $(D [3, 3, 4]).)
)
$(TR $(TDNW $(LREF findAmong)) $(TD $(D findAmong("abcd",
"qcx")) returns $(D "cd") because $(D 'c') is among $(D "qcx").)
)
$(TR $(TDNW $(LREF findSkip)) $(TD If $(D a = "abcde"), then
$(D findSkip(a, "x")) returns $(D false) and leaves $(D a) unchanged,
whereas $(D findSkip(a, 'c')) advances $(D a) to $(D "cde") and
returns $(D true).)
)
$(TR $(TDNW $(LREF findSplit)) $(TD $(D findSplit("abcdefg",
"de")) returns the three ranges $(D "abc"), $(D "de"), and $(D
"fg").)
)
$(TR $(TDNW $(LREF findSplitAfter)) $(TD $(D
findSplitAfter("abcdefg", "de")) returns the two ranges $(D "abcde")
and $(D "fg").)
)
$(TR $(TDNW $(LREF findSplitBefore)) $(TD $(D
findSplitBefore("abcdefg", "de")) returns the two ranges $(D "abc") and
$(D "defg").)
)
$(TR $(TDNW $(LREF minCount)) $(TD $(D minCount([2, 1, 1, 4,
1])) returns $(D tuple(1, 3)).)
)
$(TR $(TDNW $(LREF minPos)) $(TD $(D minPos([2, 3, 1, 3, 4,
1])) returns the subrange $(D [1, 3, 4, 1]), i.e., positions the range
at the first occurrence of its minimal element.)
)
$(TR $(TDNW $(LREF skipOver)) $(TD Assume $(D a = "blah"). Then
$(D skipOver(a, "bi")) leaves $(D a) unchanged and returns $(D false),
whereas $(D skipOver(a, "bl")) advances $(D a) to refer to $(D "ah")
and returns $(D true).)
)
$(TR $(TDNW $(LREF startsWith)) $(TD $(D startsWith("hello,
world", "hello")) returns $(D true).)
)
$(TR $(TDNW $(LREF until)) $(TD Lazily iterates a range
until a specific value is found.)
)
$(LEADINGROW Comparison
)
$(TR $(TDNW $(LREF cmp)) $(TD $(D cmp("abc", "abcd")) is $(D
-1), $(D cmp("abc", aba")) is $(D 1), and $(D cmp("abc", "abc")) is
$(D 0).)
)
$(TR $(TDNW $(LREF equal)) $(TD Compares ranges for
element-by-element equality, e.g. $(D equal([1, 2, 3], [1.0, 2.0,
3.0])) returns $(D true).)
)
$(TR $(TDNW $(LREF levenshteinDistance)) $(TD $(D
levenshteinDistance("kitten", "sitting")) returns $(D 3) by using the
$(LUCKY Levenshtein distance _algorithm).)
)
$(TR $(TDNW $(LREF levenshteinDistanceAndPath)) $(TD $(D
levenshteinDistanceAndPath("kitten", "sitting")) returns $(D tuple(3,
"snnnsni")) by using the $(LUCKY Levenshtein distance _algorithm).)
)
$(TR $(TDNW $(LREF max)) $(TD $(D max(3, 4, 2)) returns $(D
4).)
)
$(TR $(TDNW $(LREF min)) $(TD $(D min(3, 4, 2)) returns $(D
2).)
)
$(TR $(TDNW $(LREF mismatch)) $(TD $(D mismatch("oh hi",
"ohayo")) returns $(D tuple(" hi", "ayo")).)
)
$(LEADINGROW Iteration
)
$(TR $(TDNW $(LREF filter)) $(TD $(D filter!"a > 0"([1, -1, 2,
0, -3])) iterates over elements $(D 1), $(D 2), and $(D 0).)
)
$(TR $(TDNW $(LREF filterBidirectional)) $(TD Similar to $(D
filter), but also provides $(D back) and $(D popBack) at a small
increase in cost.)
)
$(TR $(TDNW $(LREF group)) $(TD $(D group([5, 2, 2, 3, 3]))
returns a range containing the tuples $(D tuple(5, 1)),
$(D tuple(2, 2)), and $(D tuple(3, 2)).)
)
$(TR $(TDNW $(LREF joiner)) $(TD $(D joiner(["hello",
"world!"], ";")) returns a range that iterates over the characters $(D
"hello; world!"). No new string is created - the existing inputs are
iterated.)
)
$(TR $(TDNW $(LREF map)) $(TD $(D map!"2 * a"([1, 2, 3]))
lazily returns a range with the numbers $(D 2), $(D 4), $(D 6).)
)
$(TR $(TDNW $(LREF reduce)) $(TD $(D reduce!"a + b"([1, 2, 3,
4])) returns $(D 10).)
)
$(TR $(TDNW $(LREF splitter)) $(TD Lazily splits a range by a
separator.)
)
$(TR $(TDNW $(LREF uniq)) $(TD Iterates over the unique elements
in a range, which is assumed sorted.)
)
$(LEADINGROW Sorting
)
$(TR $(TDNW $(LREF completeSort)) $(TD If $(D a = [10, 20, 30])
and $(D b = [40, 6, 15]), then $(D completeSort(a, b)) leaves $(D a =
[6, 10, 15]) and $(D b = [20, 30, 40]). The range $(D a) must be
sorted prior to the call, and as a result the combination $(D $(XREF
range,chain)(a, b)) is sorted.)
)
$(TR $(TDNW $(LREF isPartitioned)) $(TD $(D isPartitioned!"a <
0"([-1, -2, 1, 0, 2])) returns $(D true) because the predicate is $(D
true) for a portion of the range and $(D false) afterwards.)
)
$(TR $(TDNW $(LREF isSorted)) $(TD $(D isSorted([1, 1, 2, 3]))
returns $(D true).)
)
$(TR $(TDNW $(LREF makeIndex)) $(TD Creates a separate index
for a range.)
)
$(TR $(TDNW $(LREF partialSort)) $(TD If $(D a = [5, 4, 3, 2,
1]), then $(D partialSort(a, 3)) leaves $(D a[0 .. 3] = [1, 2,
3]). The other elements of $(D a) are left in an unspecified order.)
)
$(TR $(TDNW $(LREF partition)) $(TD Partitions a range
according to a predicate.)
)
$(TR $(TDNW $(LREF schwartzSort)) $(TD Sorts with the help of
the $(LUCKY Schwartzian transform).)
)
$(TR $(TDNW $(LREF sort)) $(TD Sorts.)
)
$(TR $(TDNW $(LREF topN)) $(TD Separates the top elements in a
range.)
)
$(TR $(TDNW $(LREF topNCopy)) $(TD Copies out the top elements
of a range.)
)
$(LEADINGROW Set operations
)
$(TR $(TDNW $(LREF largestPartialIntersection)) $(TD Copies out
the values that occur most frequently in a range of ranges.)
)
$(TR $(TDNW $(LREF largestPartialIntersectionWeighted)) $(TD
Copies out the values that occur most frequently (multiplied by
per-value weights) in a range of ranges.)
)
$(TR $(TDNW $(LREF nWayUnion)) $(TD Computes the union of a set
of sets implemented as a range of sorted ranges.)
)
$(TR $(TDNW $(LREF setDifference)) $(TD Lazily computes the set
difference of two or more sorted ranges.)
)
$(TR $(TDNW $(LREF setIntersection)) $(TD Lazily computes the
set difference of two or more sorted ranges.)
)
$(TR $(TDNW $(LREF setSymmetricDifference)) $(TD Lazily
computes the symmetric set difference of two or more sorted ranges.)
)
$(TR $(TDNW $(LREF setUnion)) $(TD Lazily computes the set
union of two or more sorted ranges.)
)
$(LEADINGROW Mutation
)
$(TR $(TDNW $(LREF bringToFront)) $(TD If $(D a = [1, 2, 3])
and $(D b = [4, 5, 6, 7]), $(D bringToFront(a, b)) leaves $(D a = [4,
5, 6]) and $(D b = [7, 1, 2, 3]).)
)
$(TR $(TDNW $(LREF copy)) $(TD Copies a range to another. If
$(D a = [1, 2, 3]) and $(D b = new int[5]), then $(D copy(a, b))
leaves $(D b = [1, 2, 3, 0, 0]) and returns $(D b[3 .. $]).)
)
$(TR $(TDNW $(LREF fill)) $(TD Fills a range with a pattern,
e.g., if $(D a = new int[3]), then $(D fill(a, 4)) leaves $(D a = [4,
4, 4]) and $(D fill(a, [3, 4])) leaves $(D a = [3, 4, 3]).)
)
$(TR $(TDNW $(LREF initializeAll)) $(TD If $(D a = [1.2, 3.4]),
then $(D initializeAll(a)) leaves $(D a = [double.init,
double.init]).)
)
$(TR $(TDNW $(LREF move)) $(TD $(D move(a, b)) moves $(D a)
into $(D b). $(D move(a)) reads $(D a) destructively.)
)
$(TR $(TDNW $(LREF moveAll)) $(TD Moves all elements from one
range to another.)
)
$(TR $(TDNW $(LREF moveSome)) $(TD Moves as many elements as
possible from one range to another.)
)
$(TR $(TDNW $(LREF reverse)) $(TD If $(D a = [1, 2, 3]), $(D
reverse(a)) changes it to $(D [3, 2, 1]).)
)
$(TR $(TDNW $(LREF swap)) $(TD Swaps two values.)
)
$(TR $(TDNW $(LREF swapRanges)) $(TD Swaps all elements of two
ranges.)
)
$(TR $(TDNW $(LREF uninitializedFill)) $(TD Fills a range
(assumed uninitialized) with a value.)
)
)
Macros:
WIKI = Phobos/StdAlgorithm
MYREF = <font face='Consolas, "Bitstream Vera Sans Mono", "Andale Mono", Monaco, "DejaVu Sans Mono", "Lucida Console", monospace'><a href="#$1">$1</a> </font>
Copyright: Andrei Alexandrescu 2008-.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB erdani.com, Andrei Alexandrescu)
Source: $(PHOBOSSRC std/_algorithm.d)
*/
module std.algorithm;
//debug = std_algorithm;
import std.c.string;
import std.array, std.ascii, std.container, std.conv, std.exception,
std.functional, std.math, std.metastrings, std.range, std.string,
std.traits, std.typecons, std.typetuple, std.uni;
version(unittest)
{
import std.random, std.stdio, std.string;
mixin(dummyRanges);
}
/**
Implements the homonym function (also known as $(D transform)) present
in many languages of functional flavor. The call $(D map!(fun)(range))
returns a range of which elements are obtained by applying $(D fun(x))
left to right for all $(D x) in $(D range). The original ranges are
not changed. Evaluation is done lazily. The range returned by $(D map)
caches the last value such that evaluating $(D front) multiple times
does not result in multiple calls to $(D fun).
Example:
----
int[] arr1 = [ 1, 2, 3, 4 ];
int[] arr2 = [ 5, 6 ];
auto squares = map!("a * a")(chain(arr1, arr2));
assert(equal(squares, [ 1, 4, 9, 16, 25, 36 ]));
----
Multiple functions can be passed to $(D map). In that case, the
element type of $(D map) is a tuple containing one element for each
function.
Example:
----
auto arr1 = [ 1, 2, 3, 4 ];
foreach (e; map!("a + a", "a * a")(arr1))
{
writeln(e[0], " ", e[1]);
}
----
You may alias $(D map) with some function(s) to a symbol and use
it separately:
----
alias map!(to!string) stringize;
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
----
*/
template map(fun...) if (fun.length >= 1)
{
auto map(Range)(Range r) if (isInputRange!(Unqual!Range))
{
static if (fun.length > 1)
{
alias adjoin!(staticMap!(unaryFun, fun)) _fun;
}
else
{
alias unaryFun!fun _fun;
}
struct Result
{
alias Unqual!Range R;
alias typeof(_fun(.ElementType!R.init)) ElementType;
R _input;
static if (isBidirectionalRange!R)
{
@property auto ref back()
{
return _fun(_input.back);
}
void popBack()
{
_input.popBack();
}
}
this(R input)
{
_input = input;
}
static if (isInfinite!R)
{
// Propagate infinite-ness.
enum bool empty = false;
}
else
{
@property bool empty()
{
return _input.empty;
}
}
void popFront()
{
_input.popFront();
}
@property auto ref front()
{
return _fun(_input.front);
}
static if (isRandomAccessRange!R)
{
auto ref opIndex(size_t index)
{
return _fun(_input[index]);
}
}
static if (hasLength!R || isSomeString!R)
{
@property auto length()
{
return _input.length;
}
alias length opDollar;
}
static if (hasSlicing!R)
{
auto opSlice(size_t lowerBound, size_t upperBound)
{
return typeof(this)(_input[lowerBound..upperBound]);
}
}
static if (isForwardRange!R)
@property auto save()
{
auto result = this;
result._input = result._input.save;
return result;
}
}
return Result(r);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
alias map!(to!string) stringize;
assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));
uint counter;
alias map!((a) { return counter++; }) count;
assert(equal(count([ 10, 2, 30, 4 ]), [ 0, 1, 2, 3 ]));
counter = 0;
adjoin!((a) { return counter++; }, (a) { return counter++; })(1);
alias map!((a) { return counter++; }, (a) { return counter++; }) countAndSquare;
//assert(equal(countAndSquare([ 10, 2 ]), [ tuple(0u, 100), tuple(1u, 4) ]));
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] arr1 = [ 1, 2, 3, 4 ];
const int[] arr1Const = arr1;
int[] arr2 = [ 5, 6 ];
auto squares = map!("a * a")(arr1Const);
assert(squares[$ - 1] == 16);
assert(equal(squares, [ 1, 4, 9, 16 ][]));
assert(equal(map!("a * a")(chain(arr1, arr2)), [ 1, 4, 9, 16, 25, 36 ][]));
// Test the caching stuff.
assert(squares.back == 16);
auto squares2 = squares.save;
assert(squares2.back == 16);
assert(squares2.front == 1);
squares2.popFront();
assert(squares2.front == 4);
squares2.popBack();
assert(squares2.front == 4);
assert(squares2.back == 9);
assert(equal(map!("a * a")(chain(arr1, arr2)), [ 1, 4, 9, 16, 25, 36 ][]));
uint i;
foreach (e; map!("a", "a * a")(arr1))
{
assert(e[0] == ++i);
assert(e[1] == i * i);
}
// Test length.
assert(squares.length == 4);
assert(map!"a * a"(chain(arr1, arr2)).length == 6);
// Test indexing.
assert(squares[0] == 1);
assert(squares[1] == 4);
assert(squares[2] == 9);
assert(squares[3] == 16);
// Test slicing.
auto squareSlice = squares[1..squares.length - 1];
assert(equal(squareSlice, [4, 9][]));
assert(squareSlice.back == 9);
assert(squareSlice[1] == 9);
// Test on a forward range to make sure it compiles when all the fancy
// stuff is disabled.
auto fibsSquares = map!"a * a"(recurrence!("a[n-1] + a[n-2]")(1, 1));
assert(fibsSquares.front == 1);
fibsSquares.popFront();
fibsSquares.popFront();
assert(fibsSquares.front == 4);
fibsSquares.popFront();
assert(fibsSquares.front == 9);
auto repeatMap = map!"a"(repeat(1));
static assert(isInfinite!(typeof(repeatMap)));
auto intRange = map!"a"([1,2,3]);
static assert(isRandomAccessRange!(typeof(intRange)));
foreach(DummyType; AllDummyRanges)
{
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]));
}
}
unittest
{
auto LL = iota(1L, 4L);
auto m = map!"a*a"(LL);
assert(equal(m, [1L, 4L, 9L]));
}
// reduce
/**
Implements the homonym function (also known as $(D accumulate), $(D
compress), $(D inject), or $(D foldl)) present in various programming
languages of functional flavor. The call $(D reduce!(fun)(seed,
range)) first assigns $(D seed) to an internal variable $(D result),
also called the accumulator. Then, for each element $(D x) in $(D
range), $(D result = fun(result, x)) gets evaluated. Finally, $(D
result) is returned. The one-argument version $(D reduce!(fun)(range))
works similarly, but it uses the first element of the range as the
seed (the range must be non-empty).
Many aggregate range operations turn out to be solved with $(D reduce)
quickly and easily. The example below illustrates $(D reduce)'s
remarkable power and flexibility.
Example:
----
int[] arr = [ 1, 2, 3, 4, 5 ];
// Sum all elements
auto sum = reduce!("a + b")(0, arr);
assert(sum == 15);
// Compute the maximum of all elements
auto largest = reduce!(max)(arr);
assert(largest == 5);
// Compute the number of odd elements
auto odds = reduce!("a + (b & 1)")(0, arr);
assert(odds == 3);
// Compute the sum of squares
auto ssquares = reduce!("a + b * b")(0, arr);
assert(ssquares == 55);
// Chain multiple ranges into seed
int[] a = [ 3, 4 ];
int[] b = [ 100 ];
auto r = reduce!("a + b")(chain(a, b));
assert(r == 107);
// Mixing convertible types is fair game, too
double[] c = [ 2.5, 3.0 ];
auto r1 = reduce!("a + b")(chain(a, b, c));
assert(r1 == 112.5);
----
$(DDOC_SECTION_H Multiple functions:) Sometimes it is very useful to
compute multiple aggregates in one pass. One advantage is that the
computation is faster because the looping overhead is shared. That's
why $(D reduce) accepts multiple functions. If two or more functions
are passed, $(D reduce) returns a $(XREF typecons, Tuple) object with
one member per passed-in function. The number of seeds must be
correspondingly increased.
Example:
----
double[] a = [ 3.0, 4, 7, 11, 3, 2, 5 ];
// Compute minimum and maximum in one pass
auto r = reduce!(min, max)(a);
// The type of r is Tuple!(double, double)
assert(r[0] == 2); // minimum
assert(r[1] == 11); // maximum
// Compute sum and sum of squares in one pass
r = reduce!("a + b", "a + b * b")(tuple(0.0, 0.0), a);
assert(r[0] == 35); // sum
assert(r[1] == 233); // sum of squares
// Compute average and standard deviation from the above
auto avg = r[0] / a.length;
auto stdev = sqrt(r[1] / a.length - avg * avg);
----
*/
template reduce(fun...) if (fun.length >= 1)
{
auto reduce(Args...)(Args args)
if (Args.length > 0 && Args.length <= 2 && isIterable!(Args[$ - 1]))
{
static if(isInputRange!(Args[$ - 1]))
{
static if (Args.length == 2)
{
alias args[0] seed;
alias args[1] r;
Unqual!(Args[0]) result = seed;
for (; !r.empty; r.popFront())
{
static if (fun.length == 1)
{
result = binaryFun!(fun[0])(result, r.front);
}
else
{
foreach (i, Unused; Args[0].Types)
{
result[i] = binaryFun!(fun[i])(result[i], r.front);
}
}
}
return result;
}
else
{
enforce(!args[$ - 1].empty,
"Cannot reduce an empty range w/o an explicit seed value.");
alias args[0] r;
static if (fun.length == 1)
{
auto seed = r.front;
r.popFront();
return reduce(seed, r);
}
else
{
static assert(fun.length > 1);
typeof(adjoin!(staticMap!(binaryFun, fun))(r.front, r.front))
result = void;
foreach (i, T; result.Types)
{
emplace(&result[i], r.front);
}
r.popFront();
return reduce(result, r);
}
}
}
else
{ // opApply case. Coded as a separate case because efficiently
// handling all of the small details like avoiding unnecessary
// copying, iterating by dchar over strings, and dealing with the
// no explicit start value case would become an unreadable mess
// if these were merged.
alias args[$ - 1] r;
alias Args[$ - 1] R;
alias ForeachType!R E;
static if(args.length == 2)
{
static if(fun.length == 1)
{
auto result = Tuple!(Unqual!(Args[0]))(args[0]);
}
else
{
Unqual!(Args[0]) result = args[0];
}
enum bool initialized = true;
}
else static if(fun.length == 1)
{
Tuple!(typeof(binaryFun!fun(E.init, E.init))) result = void;
bool initialized = false;
}
else
{
typeof(adjoin!(staticMap!(binaryFun, fun))(E.init, E.init))
result = void;
bool initialized = false;
}
// For now, just iterate using ref to avoid unnecessary copying.
// When Bug 2443 is fixed, this may need to change.
foreach(ref elem; r)
{
if(initialized)
{
foreach(i, T; result.Types)
{
result[i] = binaryFun!(fun[i])(result[i], elem);
}
}
else
{
static if(is(typeof(&initialized)))
{
initialized = true;
}
foreach (i, T; result.Types)
{
emplace(&result[i], elem);
}
}
}
enforce(initialized,
"Cannot reduce an empty iterable w/o an explicit seed value.");
static if(fun.length == 1)
{
return result[0];
}
else
{
return result;
}
}
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
double[] a = [ 3, 4 ];
auto r = reduce!("a + b")(0.0, a);
assert(r == 7);
r = reduce!("a + b")(a);
assert(r == 7);
r = reduce!(min)(a);
assert(r == 3);
double[] b = [ 100 ];
auto r1 = reduce!("a + b")(chain(a, b));
assert(r1 == 107);
// two funs
auto r2 = reduce!("a + b", "a - b")(tuple(0., 0.), a);
assert(r2[0] == 7 && r2[1] == -7);
auto r3 = reduce!("a + b", "a - b")(a);
assert(r3[0] == 7 && r3[1] == -1);
a = [ 1, 2, 3, 4, 5 ];
// Stringize with commas
string rep = reduce!("a ~ `, ` ~ to!(string)(b)")("", a);
assert(rep[2 .. $] == "1, 2, 3, 4, 5", "["~rep[2 .. $]~"]");
// Test the opApply case.
static struct OpApply
{
bool actEmpty;
int opApply(int delegate(ref int) dg)
{
int res;
if(actEmpty) return res;
foreach(i; 0..100)
{
res = dg(i);
if(res) break;
}
return res;
}
}
OpApply oa;
auto hundredSum = reduce!"a + b"(iota(100));
assert(reduce!"a + b"(5, oa) == hundredSum + 5);
assert(reduce!"a + b"(oa) == hundredSum);
assert(reduce!("a + b", max)(oa) == tuple(hundredSum, 99));
assert(reduce!("a + b", max)(tuple(5, 0), oa) == tuple(hundredSum + 5, 99));
// Test for throwing on empty range plus no seed.
try {
reduce!"a + b"([1, 2][0..0]);
assert(0);
} catch(Exception) {}
oa.actEmpty = true;
try {
reduce!"a + b"(oa);
assert(0);
} catch(Exception) {}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
const float a = 0.0;
const float[] b = [ 1.2, 3, 3.3 ];
float[] c = [ 1.2, 3, 3.3 ];
auto r = reduce!"a + b"(a, b);
r = reduce!"a + b"(a, c);
}
/**
Fills a range with a value.
Example:
----
int[] a = [ 1, 2, 3, 4 ];
fill(a, 5);
assert(a == [ 5, 5, 5, 5 ]);
----
*/
void fill(Range, Value)(Range range, Value filler)
if (isForwardRange!Range && is(typeof(range.front = filler)))
{
alias ElementType!Range T;
static if (hasElaborateCopyConstructor!T || !isDynamicArray!Range)
{
for (; !range.empty; range.popFront())
{
range.front = filler;
}
}
else
{
if (range.empty) return;
// Range is a dynamic array of bald values, just fill memory
// Can't use memcpy or memmove coz ranges overlap
range.front = filler;
auto bytesToFill = T.sizeof * (range.length - 1);
auto bytesFilled = T.sizeof;
while (bytesToFill)
{
auto fillNow = min(bytesToFill, bytesFilled);
memcpy(cast(void*) range.ptr + bytesFilled,
cast(void*) range.ptr,
fillNow);
bytesToFill -= fillNow;
bytesFilled += fillNow;
}
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3 ];
fill(a, 6);
assert(a == [ 6, 6, 6 ], text(a));
void fun0()
{
foreach (i; 0 .. 1000)
{
foreach (ref e; a) e = 6;
}
}
void fun1() { foreach (i; 0 .. 1000) fill(a, 6); }
//void fun2() { foreach (i; 0 .. 1000) fill2(a, 6); }
//writeln(benchmark!(fun0, fun1, fun2)(10000));
}
/**
Fills $(D range) with a pattern copied from $(D filler). The length of
$(D range) does not have to be a multiple of the length of $(D
filler). If $(D filler) is empty, an exception is thrown.
Example:
----
int[] a = [ 1, 2, 3, 4, 5 ];
int[] b = [ 8, 9 ];
fill(a, b);
assert(a == [ 8, 9, 8, 9, 8 ]);
----
*/
void fill(Range1, Range2)(Range1 range, Range2 filler)
if (isForwardRange!Range1 && isForwardRange!Range2
&& is(typeof(Range1.init.front = Range2.init.front)))
{
enforce(!filler.empty);
auto t = filler.save;
for (; !range.empty; range.popFront(), t.popFront())
{
if (t.empty) t = filler;
range.front = t.front;
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3, 4, 5 ];
int[] b = [1, 2];
fill(a, b);
assert(a == [ 1, 2, 1, 2, 1 ]);
}
/**
Fills a range with a value. Assumes that the range does not currently
contain meaningful content. This is of interest for structs that
define copy constructors (for all other types, fill and
uninitializedFill are equivalent).
Example:
----
struct S { ... }
S[] s = (cast(S*) malloc(5 * S.sizeof))[0 .. 5];
uninitializedFill(s, 42);
assert(s == [ 42, 42, 42, 42, 42 ]);
----
*/
void uninitializedFill(Range, Value)(Range range, Value filler)
if (isForwardRange!Range && is(typeof(range.front = filler)))
{
alias ElementType!Range T;
static if (hasElaborateCopyConstructor!T)
{
// Must construct stuff by the book
for (; !range.empty; range.popFront())
{
emplace(&range.front, filler);
}
}
else
{
// Doesn't matter whether fill is initialized or not
return fill(range, filler);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3 ];
uninitializedFill(a, 6);
assert(a == [ 6, 6, 6 ]);
void fun0()
{
foreach (i; 0 .. 1000)
{
foreach (ref e; a) e = 6;
}
}
void fun1() { foreach (i; 0 .. 1000) fill(a, 6); }
//void fun2() { foreach (i; 0 .. 1000) fill2(a, 6); }
//writeln(benchmark!(fun0, fun1, fun2)(10000));
}
/**
Initializes all elements of a range with their $(D .init)
value. Assumes that the range does not currently contain meaningful
content.
Example:
----
struct S { ... }
S[] s = (cast(S*) malloc(5 * S.sizeof))[0 .. 5];
initializeAll(s);
assert(s == [ 0, 0, 0, 0, 0 ]);
----
*/
void initializeAll(Range)(Range range)
if (isForwardRange!Range && is(typeof(range.front = range.front)))
{
alias ElementType!Range T;
static assert(is(typeof(&(range.front()))) || !hasElaborateAssign!T,
"Cannot initialize a range that does not expose"
" references to its elements");
static if (!isDynamicArray!Range)
{
static if (is(typeof(&(range.front()))))
{
// Range exposes references
for (; !range.empty; range.popFront())
{
memcpy(&(range.front()), &T.init, T.sizeof);
}
}
else
{
// Go the slow route
for (; !range.empty; range.popFront())
{
range.front = filler;
}
}
}
else
{
fill(range, T.init);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3 ];
uninitializedFill(a, 6);
assert(a == [ 6, 6, 6 ]);
initializeAll(a);
assert(a == [ 0, 0, 0 ]);
void fun0()
{
foreach (i; 0 .. 1000)
{
foreach (ref e; a) e = 6;
}
}
void fun1() { foreach (i; 0 .. 1000) fill(a, 6); }
//void fun2() { foreach (i; 0 .. 1000) fill2(a, 6); }
//writeln(benchmark!(fun0, fun1, fun2)(10000));
}
// filter
/**
Implements the homonym function present in various programming
languages of functional flavor. The call $(D filter!(fun)(range))
returns a new range only containing elements $(D x) in $(D r) for
which $(D predicate(x)) is $(D true).
Example:
----
int[] arr = [ 1, 2, 3, 4, 5 ];
// Sum all elements
auto small = filter!("a < 3")(arr);
assert(equal(small, [ 1, 2 ]));
// In combination with chain() to span multiple ranges
int[] a = [ 3, -2, 400 ];
int[] b = [ 100, -101, 102 ];
auto r = filter!("a > 0")(chain(a, b));
assert(equal(r, [ 3, 400, 100, 102 ]));
// Mixing convertible types is fair game, too
double[] c = [ 2.5, 3.0 ];
auto r1 = filter!("cast(int) a != a")(chain(c, a, b));
assert(equal(r1, [ 2.5 ]));
----
*/
template filter(alias pred) if (is(typeof(unaryFun!pred)))
{
auto filter(Range)(Range rs) if (isInputRange!(Unqual!Range))
{
struct Result
{
alias Unqual!Range R;
R _input;
this(R r)
{
_input = r;
while (!_input.empty && !unaryFun!pred(_input.front))
{
_input.popFront();
}
}
auto opSlice() { return this; }
static if (isInfinite!Range)
{
enum bool empty = false;
}
else
{
@property bool empty() { return _input.empty; }
}
void popFront()
{
do
{
_input.popFront();
} while (!_input.empty && !unaryFun!pred(_input.front));
}
@property auto ref front()
{
return _input.front;
}
static if(isForwardRange!R)
{
@property auto save()
{
return Result(_input);
}
}
}
return Result(rs);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 3, 4, 2 ];
auto r = filter!("a > 3")(a);
static assert(isForwardRange!(typeof(r)));
assert(equal(r, [ 4 ][]));
a = [ 1, 22, 3, 42, 5 ];
auto under10 = filter!("a < 10")(a);
assert(equal(under10, [1, 3, 5][]));
static assert(isForwardRange!(typeof(under10)));
under10.front() = 4;
assert(equal(under10, [4, 3, 5][]));
under10.front() = 40;
assert(equal(under10, [40, 3, 5][]));
under10.front() = 1;
auto infinite = filter!"a > 2"(repeat(3));
static assert(isInfinite!(typeof(infinite)));
static assert(isForwardRange!(typeof(infinite)));
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)));
}
}
// With delegates
int x = 10;
int overX(int a) { return a > x; }
typeof(filter!overX(a)) getFilter()
{
return filter!overX(a);
}
auto r1 = getFilter();
assert(equal(r1, [22, 42]));
// With chain
auto nums = [0,1,2,3,4];
assert(equal(filter!overX(chain(a, nums)), [22, 42]));
// With copying of inner struct Filter to Map
auto arr = [1,2,3,4,5];
auto m = map!"a + 1"(filter!"a < 4"(arr));
}
unittest
{
int[] a = [ 3, 4 ];
const aConst = a;
auto r = filter!("a > 3")(aConst);
assert(equal(r, [ 4 ][]));
a = [ 1, 22, 3, 42, 5 ];
auto under10 = filter!("a < 10")(a);
assert(equal(under10, [1, 3, 5][]));
assert(equal(under10.save, [1, 3, 5][]));
assert(equal(under10.save, under10));
// With copying of inner struct Filter to Map
auto arr = [1,2,3,4,5];
auto m = map!"a + 1"(filter!"a < 4"(arr));
}
unittest
{
assert(equal(compose!(map!"2 * a", filter!"a & 1")([1,2,3,4,5]),
[2,6,10]));
assert(equal(pipe!(filter!"a & 1", map!"2 * a")([1,2,3,4,5]),
[2,6,10]));
}
unittest
{
int x = 10;
int underX(int a) { return a < x; }
const(int)[] list = [ 1, 2, 10, 11, 3, 4 ];
assert(equal(filter!underX(list), [ 1, 2, 3, 4 ]));
}
// filterBidirectional
/**
* Similar to $(D filter), except it defines a bidirectional
* range. There is a speed disadvantage - the constructor spends time
* finding the last element in the range that satisfies the filtering
* condition (in addition to finding the first one). The advantage is
* that the filtered range can be spanned from both directions. Also,
* $(XREF range, retro) can be applied against the filtered range.
*
Example:
----
int[] arr = [ 1, 2, 3, 4, 5 ];
auto small = filterBidirectional!("a < 3")(arr);
assert(small.back == 2);
assert(equal(small, [ 1, 2 ]));
assert(equal(retro(small), [ 2, 1 ]));
// In combination with chain() to span multiple ranges
int[] a = [ 3, -2, 400 ];
int[] b = [ 100, -101, 102 ];
auto r = filterBidirectional!("a > 0")(chain(a, b));
assert(r.back == 102);
----
*/
template filterBidirectional(alias pred)
{
auto filterBidirectional(Range)(Range r) if (isBidirectionalRange!(Unqual!Range))
{
struct Result
{
alias Unqual!Range R;
alias unaryFun!pred predFun;
R _input;
this(R r)
{
_input = r;
while (!_input.empty && !predFun(_input.front)) _input.popFront();
while (!_input.empty && !predFun(_input.back)) _input.popBack();
}
@property bool empty() { return _input.empty; }
void popFront()
{
do
{
_input.popFront();
} while (!_input.empty && !predFun(_input.front));
}
@property auto ref front()
{
return _input.front;
}
void popBack()
{
do
{
_input.popBack();
} while (!_input.empty && !predFun(_input.back));
}
@property auto ref back()
{
return _input.back;
}
@property auto save()
{
Result result;
result._input = _input.save;
return result;
}
}
return Result(r);
}
}
unittest
{
int[] arr = [ 1, 2, 3, 4, 5 ];
auto small = filterBidirectional!("a < 3")(arr);
static assert(isBidirectionalRange!(typeof(small)));
assert(small.back == 2);
assert(equal(small, [ 1, 2 ]));
assert(equal(retro(small), [ 2, 1 ]));
// In combination with chain() to span multiple ranges
int[] a = [ 3, -2, 400 ];
int[] b = [ 100, -101, 102 ];
auto r = filterBidirectional!("a > 0")(chain(a, b));
assert(r.back == 102);
}
// move
/**
Moves $(D source) into $(D target) via a destructive
copy. Specifically: $(UL $(LI If $(D hasAliasing!T) is true (see
$(XREF traits, hasAliasing)), then the representation of $(D source)
is bitwise copied into $(D target) and then $(D source = T.init) is
evaluated.) $(LI Otherwise, $(D target = source) is evaluated.)) See
also $(XREF contracts, pointsTo).
Preconditions:
$(D &source == &target || !pointsTo(source, source))
*/
void move(T)(ref T source, ref T target)
{
if (&source == &target) return;
assert(!pointsTo(source, source));
static if (is(T == struct))
{
// Most complicated case. Destroy whatever target had in it
// and bitblast source over it
static if (hasElaborateDestructor!T) typeid(T).destroy(&target);
memcpy(&target, &source, T.sizeof);
// If the source defines a destructor or a postblit hook, we must obliterate the
// object in order to avoid double freeing and undue aliasing
static if (hasElaborateDestructor!T || hasElaborateCopyConstructor!T)
{
static T empty;
memcpy(&source, &empty, T.sizeof);
}
}
else
{
// Primitive data (including pointers and arrays) or class -
// assignment works great
target = source;
// static if (is(typeof(source = null)))
// {
// // Nullify the source to help the garbage collector
// source = null;
// }
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
Object obj1 = new Object;
Object obj2 = obj1;
Object obj3;
move(obj2, obj3);
assert(obj3 is obj1);
static struct S1 { int a = 1, b = 2; }
S1 s11 = { 10, 11 };
S1 s12;
move(s11, s12);
assert(s11.a == 10 && s11.b == 11 && s12.a == 10 && s12.b == 11);
static struct S2 { int a = 1; int * b; }
S2 s21 = { 10, null };
s21.b = new int;
S2 s22;
move(s21, s22);
assert(s21 == s22);
// Issue 5661 test(1)
static struct S3
{
static struct X { int n = 0; ~this(){n = 0;} }
X x;
}
static assert(hasElaborateDestructor!S3);
S3 s31, s32;
s31.x.n = 1;
move(s31, s32);
assert(s31.x.n == 0);
assert(s32.x.n == 1);
// Issue 5661 test(2)
static struct S4
{
static struct X { int n = 0; this(this){n = 0;} }
X x;
}
static assert(hasElaborateCopyConstructor!S4);
S4 s41, s42;
s41.x.n = 1;
move(s41, s42);
assert(s41.x.n == 0);
assert(s42.x.n == 1);
}
/// Ditto
T move(T)(ref T src)
{
T result;
move(src, result);
return result;
}
// moveAll
/**
For each element $(D a) in $(D src) and each element $(D b) in $(D
tgt) in lockstep in increasing order, calls $(D move(a, b)). Returns
the leftover portion of $(D tgt). Throws an exeption if there is not
enough room in $(D tgt) to acommodate all of $(D src).
Preconditions:
$(D walkLength(src) >= walkLength(tgt))
*/
Range2 moveAll(Range1, Range2)(Range1 src, Range2 tgt)
if (isInputRange!Range1 && isInputRange!Range2
&& is(typeof(move(src.front, tgt.front))))
{
for (; !src.empty; src.popFront(), tgt.popFront())
{
enforce(!tgt.empty);
move(src.front, tgt.front);
}
return tgt;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3 ];
int[] b = new int[5];
assert(moveAll(a, b) is b[3 .. $]);
assert(a == b[0 .. 3]);
assert(a == [ 1, 2, 3 ]);
}
// moveSome
/**
For each element $(D a) in $(D src) and each element $(D b) in $(D
tgt) in lockstep in increasing order, calls $(D move(a, b)). Stops
when either $(D src) or $(D tgt) have been exhausted. Returns the
leftover portions of the two ranges.
*/
Tuple!(Range1, Range2) moveSome(Range1, Range2)(Range1 src, Range2 tgt)
if (isInputRange!Range1 && isInputRange!Range2
&& is(typeof(move(src.front, tgt.front))))
{
for (; !src.empty && !tgt.empty; src.popFront(), tgt.popFront())
{
enforce(!tgt.empty);
move(src.front, tgt.front);
}
return tuple(src, tgt);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3, 4, 5 ];
int[] b = new int[3];
assert(moveSome(a, b)[0] is a[3 .. $]);
assert(a[0 .. 3] == b);
assert(a == [ 1, 2, 3, 4, 5 ]);
}
// swap
/**
Swaps $(D lhs) and $(D rhs). See also $(XREF exception, pointsTo).
Preconditions:
$(D !pointsTo(lhs, lhs) && !pointsTo(lhs, rhs) && !pointsTo(rhs, lhs)
&& !pointsTo(rhs, rhs))
*/
void swap(T)(ref T lhs, ref T rhs) @trusted pure nothrow
if (isMutable!T && !is(typeof(T.init.proxySwap(T.init))))
{
static if (hasElaborateAssign!T)
{
if (&lhs != &rhs) {
// For structs with non-trivial assignment, move memory directly
// First check for undue aliasing
assert(!pointsTo(lhs, rhs) && !pointsTo(rhs, lhs)
&& !pointsTo(lhs, lhs) && !pointsTo(rhs, rhs));
// Swap bits
ubyte[T.sizeof] t = void;
auto a = (cast(ubyte*) &lhs)[0 .. T.sizeof];
auto b = (cast(ubyte*) &rhs)[0 .. T.sizeof];
t[] = a[];
a[] = b[];
b[] = t[];
}
}
else
{
// Temporary fix Bug 4789. Wor around the fact that assigning a static
// array to itself doesn't work properly.
static if(isStaticArray!T) {
if(lhs.ptr is rhs.ptr) {
return;
}
}
// For non-struct types, suffice to do the classic swap
auto tmp = lhs;
lhs = rhs;
rhs = tmp;
}
}
// Not yet documented
void swap(T)(T lhs, T rhs) if (is(typeof(T.init.proxySwap(T.init))))
{
lhs.proxySwap(rhs);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int a = 42, b = 34;
swap(a, b);
assert(a == 34 && b == 42);
static struct S { int x; char c; int[] y; }
S s1 = { 0, 'z', [ 1, 2 ] };
S s2 = { 42, 'a', [ 4, 6 ] };
//writeln(s2.tupleof.stringof);
swap(s1, s2);
assert(s1.x == 42);
assert(s1.c == 'a');
assert(s1.y == [ 4, 6 ]);
assert(s2.x == 0);
assert(s2.c == 'z');
assert(s2.y == [ 1, 2 ]);
immutable int imm1, imm2;
static assert(!__traits(compiles, swap(imm1, imm2)));
}
unittest
{
static struct NoCopy
{
this(this) { assert(0); }
int n;
string s;
}
NoCopy nc1, nc2;
nc1.n = 127; nc1.s = "abc";
nc2.n = 513; nc2.s = "uvwxyz";
swap(nc1, nc2);
assert(nc1.n == 513 && nc1.s == "uvwxyz");
assert(nc2.n == 127 && nc2.s == "abc");
swap(nc1, nc1);
swap(nc2, nc2);
assert(nc1.n == 513 && nc1.s == "uvwxyz");
assert(nc2.n == 127 && nc2.s == "abc");
static struct NoCopyHolder
{
NoCopy noCopy;
}
NoCopyHolder h1, h2;
h1.noCopy.n = 31; h1.noCopy.s = "abc";
h2.noCopy.n = 65; h2.noCopy.s = null;
swap(h1, h2);
assert(h1.noCopy.n == 65 && h1.noCopy.s == null);
assert(h2.noCopy.n == 31 && h2.noCopy.s == "abc");
swap(h1, h1);
swap(h2, h2);
assert(h1.noCopy.n == 65 && h1.noCopy.s == null);
assert(h2.noCopy.n == 31 && h2.noCopy.s == "abc");
const NoCopy const1, const2;
static assert(!__traits(compiles, swap(const1, const2)));
}
void swapFront(R1, R2)(R1 r1, R2 r2)
if (isInputRange!R1 && isInputRange!R2)
{
static if (is(typeof(swap(r1.front, r2.front))))
{
swap(r1.front, r2.front);
}
else
{
auto t1 = moveFront(r1), t2 = moveFront(r2);
r1.front = move(t2);
r2.front = move(t1);
}
}
// splitter
/**
Splits a range using an element as a separator. This can be used with
any range type, but is most popular with string types.
Two adjacent separators are considered to surround an empty element in
the split range.
If the empty range is given, the result is a range with one empty
element. If a range with one separator is given, the result is a range
with two empty elements.
Example:
---
assert(equal(splitter("hello world", ' '), [ "hello", "", "world" ]));
int[] a = [ 1, 2, 0, 0, 3, 0, 4, 5, 0 ];
int[][] w = [ [1, 2], [], [3], [4, 5] ];
assert(equal(splitter(a, 0), w));
a = null;
assert(equal(splitter(a, 0), [ (int[]).init ]));
a = [ 0 ];
assert(equal(splitter(a, 0), [ (int[]).init, (int[]).init ]));
a = [ 0, 1 ];
assert(equal(splitter(a, 0), [ [], [1] ]));
----
*/
auto splitter(Range, Separator)(Range r, Separator s)
if (is(typeof(ElementType!Range.init == Separator.init))
&& (hasSlicing!Range || isNarrowString!Range))
{
static struct Result
{
private:
Range _input;
Separator _separator;
// Do we need hasLength!Range? popFront uses _input.length...
alias typeof(unsigned(_input.length)) IndexType;
enum IndexType _unComputed = IndexType.max - 1, _atEnd = IndexType.max;
IndexType _frontLength = _unComputed;
IndexType _backLength = _unComputed;
static if(isBidirectionalRange!Range)
{
static IndexType lastIndexOf(Range haystack, Separator needle)
{
immutable index = countUntil(retro(haystack), needle);
return (index == -1) ? -1 : haystack.length - 1 - index;
}
}
public:
this(Range input, Separator separator)
{
_input = input;
_separator = separator;
}
static if (isInfinite!Range)
{
enum bool empty = false;
}
else
{
@property bool empty()
{
return _frontLength == _atEnd;
}
}
@property Range front()
{
assert(!empty);
if (_frontLength == _unComputed)
{
_frontLength = countUntil(_input, _separator);
if (_frontLength == -1) _frontLength = _input.length;
}
return _input[0 .. _frontLength];
}
void popFront()
{
assert(!empty);
if (_frontLength == _unComputed)
{
front;
}
assert(_frontLength <= _input.length);
if (_frontLength == _input.length)
{
// no more input and need to fetch => done
_frontLength = _atEnd;
// Probably don't need this, but just for consistency:
_backLength = _atEnd;
}
else
{
_input = _input[_frontLength .. _input.length];
skipOver(_input, _separator) || assert(false);
_frontLength = _unComputed;
}
}
static if(isForwardRange!Range)
{
@property typeof(this) save()
{
auto ret = this;
ret._input = _input.save;
return ret;
}
}
static if(isBidirectionalRange!Range)
{
@property Range back()
{
assert(!empty);
if (_backLength == _unComputed)
{
immutable lastIndex = lastIndexOf(_input, _separator);
if(lastIndex == -1)
{
_backLength = _input.length;
}
else
{
_backLength = _input.length - lastIndex - 1;
}
}
return _input[_input.length - _backLength .. _input.length];
}
void popBack()
{
assert(!empty);
if (_backLength == _unComputed)
{
// evaluate back to make sure it's computed
back;
}
assert(_backLength <= _input.length);
if (_backLength == _input.length)
{
// no more input and need to fetch => done
_frontLength = _atEnd;
_backLength = _atEnd;
}
else
{
_input = _input[0 .. _input.length - _backLength];
if (!_input.empty && _input.back == _separator)
{
_input.popBack();
}
else
{
assert(false);
}
_backLength = _unComputed;
}
}
}
}
return Result(r, s);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
assert(equal(splitter("hello world", ' '), [ "hello", "", "world" ]));
int[] a = [ 1, 2, 0, 0, 3, 0, 4, 5, 0 ];
int[][] w = [ [1, 2], [], [3], [4, 5], [] ];
static assert(isForwardRange!(typeof(splitter(a, 0))));
// foreach (x; splitter(a, 0)) {
// writeln("[", x, "]");
// }
assert(equal(splitter(a, 0), w));
a = null;
assert(equal(splitter(a, 0), [ (int[]).init ][]));
a = [ 0 ];
assert(equal(splitter(a, 0), [ (int[]).init, (int[]).init ][]));
a = [ 0, 1 ];
assert(equal(splitter(a, 0), [ [], [1] ][]));
// Thoroughly exercise the bidirectional stuff.
auto str = "abc abcd abcde ab abcdefg abcdefghij ab ac ar an at ada";
assert(equal(
retro(splitter(str, 'a')),
retro(array(splitter(str, 'a')))
));
// Test interleaving front and back.
auto split = splitter(str, 'a');
assert(split.front == "");
assert(split.back == "");
split.popBack();
assert(split.back == "d");
split.popFront();
assert(split.front == "bc ");
assert(split.back == "d");
split.popFront();
split.popBack();
assert(split.back == "t ");
split.popBack();
split.popBack();
split.popFront();
split.popFront();
assert(split.front == "b ");
assert(split.back == "r ");
foreach(DummyType; AllDummyRanges) { // Bug 4408
static if(isRandomAccessRange!DummyType) {
static assert(isBidirectionalRange!DummyType);
DummyType d;
auto s = splitter(d, 5);
assert(equal(s.front, [1,2,3,4]));
assert(equal(s.back, [6,7,8,9,10]));
auto s2 = splitter(d, [4, 5]);
assert(equal(s2.front, [1,2,3]));
assert(equal(s2.back, [6,7,8,9,10]));
}
}
}
unittest
{
auto L = retro(iota(1L, 10L));
auto s = splitter(L, 5L);
assert(equal(s.front, [9L, 8L, 7L, 6L]));
s.popFront();
assert(equal(s.front, [4L, 3L, 2L, 1L]));
s.popFront();
assert(s.empty);
}
/**
Splits a range using another range as a separator. This can be used
with any range type, but is most popular with string types.
*/
auto splitter(Range, Separator)(Range r, Separator s)
if (is(typeof(Range.init.front == Separator.init.front) : bool))
{
static struct Result
{
private:
Range _input;
Separator _separator;
alias typeof(unsigned(_input.length)) RIndexType;
// _frontLength == size_t.max means empty
RIndexType _frontLength = RIndexType.max;
static if (isBidirectionalRange!Range)
RIndexType _backLength = RIndexType.max;
@property auto separatorLength() { return _separator.length; }
void ensureFrontLength()
{
if (_frontLength != _frontLength.max) return;
assert(!_input.empty);
// compute front length
_frontLength = _input.length - find(_input, _separator).length;
static if (isBidirectionalRange!Range)
if (_frontLength == _input.length) _backLength = _frontLength;
}
void ensureBackLength()
{
static if (isBidirectionalRange!Range)
if (_backLength != _backLength.max) return;
assert(!_input.empty);
// compute back length
static if (isBidirectionalRange!Range)
{
_backLength = _input.length -
find(retro(_input), retro(_separator)).source.length;
}
}
public:
this(Range input, Separator separator)
{
_input = input;
_separator = separator;
}
@property Range front()
{
assert(!empty);
ensureFrontLength();
return _input[0 .. _frontLength];
}
static if (isInfinite!Range)
{
enum bool empty = false; // Propagate infiniteness
}
else
{
@property bool empty()
{
return _frontLength == RIndexType.max && _input.empty;
}
}
void popFront()
{
assert(!empty);
ensureFrontLength();
if (_frontLength == _input.length)
{
// done, there's no separator in sight
_input = _input[_frontLength .. _frontLength];
_frontLength = _frontLength.max;
static if (isBidirectionalRange!Range)
_backLength = _backLength.max;
return;
}
if (_frontLength + separatorLength == _input.length)
{
// Special case: popping the first-to-last item; there is
// an empty item right after this.
_input = _input[_input.length .. _input.length];
_frontLength = 0;
static if (isBidirectionalRange!Range)
_backLength = 0;
return;
}
// Normal case, pop one item and the separator, get ready for
// reading the next item
_input = _input[_frontLength + separatorLength .. _input.length];
// mark _frontLength as uninitialized
_frontLength = _frontLength.max;
}
static if(isForwardRange!Range)
{
@property typeof(this) save()
{
auto ret = this;
ret._input = _input.save;
return ret;
}
}
// Bidirectional functionality as suggested by Brad Roberts.
static if (isBidirectionalRange!Range)
{
@property Range back()
{
ensureBackLength();
return _input[_input.length - _backLength .. _input.length];
}
void popBack()
{
ensureBackLength();
if (_backLength == _input.length)
{
// done
_input = _input[0 .. 0];
_frontLength = _frontLength.max;
_backLength = _backLength.max;
return;
}
if (_backLength + separatorLength == _input.length)
{
// Special case: popping the first-to-first item; there is
// an empty item right before this. Leave the separator in.
_input = _input[0 .. 0];
_frontLength = 0;
_backLength = 0;
return;
}
// Normal case
_input = _input[0 .. _input.length - _backLength - separatorLength];
_backLength = _backLength.max;
}
}
}
return Result(r, s);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto s = ",abc, de, fg,hi,";
auto sp0 = splitter(s, ',');
// //foreach (e; sp0) writeln("[", e, "]");
assert(equal(sp0, ["", "abc", " de", " fg", "hi", ""][]));
auto s1 = ", abc, de, fg, hi, ";
auto sp1 = splitter(s1, ", ");
//foreach (e; sp1) writeln("[", e, "]");
assert(equal(sp1, ["", "abc", "de", " fg", "hi", ""][]));
static assert(isForwardRange!(typeof(sp1)));
int[] a = [ 1, 2, 0, 3, 0, 4, 5, 0 ];
int[][] w = [ [1, 2], [3], [4, 5], [] ];
uint i;
foreach (e; splitter(a, 0))
{
assert(i < w.length);
assert(e == w[i++]);
}
assert(i == w.length);
// // Now go back
// auto s2 = splitter(a, 0);
// foreach (e; retro(s2))
// {
// assert(i > 0);
// assert(equal(e, w[--i]), text(e));
// }
// assert(i == 0);
wstring names = ",peter,paul,jerry,";
auto words = split(names, ",");
assert(walkLength(words) == 5, text(walkLength(words)));
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto s6 = ",";
auto sp6 = splitter(s6, ',');
foreach (e; sp6)
{
//writeln("{", e, "}");
}
assert(equal(sp6, ["", ""][]));
}
auto splitter(alias isTerminator, Range)(Range input)
if (is(typeof(unaryFun!(isTerminator)(ElementType!(Range).init))))
{
struct Result
{
private Range _input;
private size_t _end;
private alias unaryFun!isTerminator _isTerminator;
this(Range input)
{
_input = input;
if (_input.empty)
{
_end = _end.max;
}
else
{
// Chase first terminator
while (_end < _input.length && !_isTerminator(_input[_end]))
{
++_end;
}
}
}
static if (isInfinite!Range)
{
enum bool empty = false; // Propagate infiniteness.
}
else
{
@property bool empty()
{
return _end == _end.max;
}
}
@property Range front()
{
assert(!empty);
return _input[0 .. _end];
}
void popFront()
{
assert(!empty);
if (_input.empty)
{
_end = _end.max;
return;
}
// Skip over existing word
_input = _input[_end .. _input.length];
// Skip terminator
for (;;)
{
if (_input.empty)
{
// Nothing following the terminator - done
_end = _end.max;
return;
}
if (!_isTerminator(_input.front))
{
// Found a legit next field
break;
}
_input.popFront();
}
assert(!_input.empty && !_isTerminator(_input.front));
// Prepare _end
_end = 1;
while (_end < _input.length && !_isTerminator(_input[_end]))
{
++_end;
}
}
static if(isForwardRange!Range)
{
@property typeof(this) save()
{
auto ret = this;
ret._input = _input.save;
return ret;
}
}
}
return Result(input);
}
unittest
{
auto L = iota(1L, 10L);
auto s = splitter(L, [5L, 6L]);
assert(equal(s.front, [1L, 2L, 3L, 4L]));
s.popFront();
assert(equal(s.front, [7L, 8L, 9L]));
s.popFront();
assert(s.empty);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
void compare(string sentence, string[] witness)
{
foreach (word; splitter!"a == ' '"(sentence))
{
assert(word == witness.front, word);
witness.popFront();
}
assert(witness.empty, witness[0]);
}
compare(" Mary has a little lamb. ",
["", "Mary", "has", "a", "little", "lamb."]);
compare("Mary has a little lamb. ",
["Mary", "has", "a", "little", "lamb."]);
compare("Mary has a little lamb.",
["Mary", "has", "a", "little", "lamb."]);
compare("", []);
compare(" ", [""]);
static assert(isForwardRange!(typeof(splitter!"a == ' '"("ABC"))));
foreach(DummyType; AllDummyRanges)
{
static if(isRandomAccessRange!DummyType)
{
auto rangeSplit = splitter!"a == 5"(DummyType.init);
assert(equal(rangeSplit.front, [1,2,3,4]));
rangeSplit.popFront();
assert(equal(rangeSplit.front, [6,7,8,9,10]));
}
}
}
auto splitter(Range)(Range input)
if (isSomeString!Range)
{
return splitter!(std.uni.isWhite)(input);
}
unittest
{
// TDPL example, page 8
uint[string] dictionary;
char[][3] lines;
lines[0] = "line one".dup;
lines[1] = "line \ttwo".dup;
lines[2] = "yah last line\ryah".dup;
foreach (line; lines) {
foreach (word; splitter(strip(line))) {
if (word in dictionary) continue; // Nothing to do
auto newID = dictionary.length;
dictionary[to!string(word)] = cast(uint)newID;
}
}
assert(dictionary.length == 5);
assert(dictionary["line"]== 0);
assert(dictionary["one"]== 1);
assert(dictionary["two"]== 2);
assert(dictionary["yah"]== 3);
assert(dictionary["last"]== 4);
}
// joiner
/**
Lazily joins a range of ranges with a separator. The separator itself
is a range.
Example:
----
assert(equal(joiner([""], "xyz"), ""));
assert(equal(joiner(["", ""], "xyz"), "xyz"));
assert(equal(joiner(["", "abc"], "xyz"), "xyzabc"));
assert(equal(joiner(["abc", ""], "xyz"), "abcxyz"));
assert(equal(joiner(["abc", "def"], "xyz"), "abcxyzdef"));
assert(equal(joiner(["Mary", "has", "a", "little", "lamb"], "..."),
"Mary...has...a...little...lamb"));
----
*/
auto joiner(RoR, Separator)(RoR r, Separator sep)
if (isInputRange!RoR && isInputRange!(ElementType!RoR)
&& isForwardRange!Separator
&& is(ElementType!Separator : ElementType!(ElementType!RoR)))
{
static struct Result
{
private RoR _items;
private ElementType!RoR _current;
private Separator _sep, _currentSep;
private void useSeparator()
{
assert(_currentSep.empty && _current.empty,
"joiner: internal error");
if (_sep.empty)
{
// Advance to the next range in the
// input
//_items.popFront();
for (;; _items.popFront())
{
if (_items.empty) return;
if (!_items.front.empty) break;
}
_current = _items.front;
_items.popFront();
}
else
{
// Must make sure something is coming after the
// separator - it's a separator, not a terminator!
if (_items.empty) return;
_currentSep = _sep.save;
assert(!_currentSep.empty);
}
}
private void useItem()
{
assert(_currentSep.empty && _current.empty,
"joiner: internal error");
// Use the input
if (_items.empty) return;
_current = _items.front;
_items.popFront();
if (!_current.empty)
{
return;
}
// No data in the current item - toggle to use the
// separator
useSeparator();
}
this(RoR items, Separator sep)
{
_items = items;
_sep = sep;
useItem();
// We need the separator if the input has at least two
// elements
if (_current.empty && _items.empty)
{
// Vacate the whole thing
_currentSep = _currentSep.init;
}
}
@property auto empty()
{
return _current.empty && _currentSep.empty;
}
@property ElementType!(ElementType!RoR) front()
{
if (!_currentSep.empty) return _currentSep.front;
assert(!_current.empty);
return _current.front;
}
void popFront()
{
assert(!empty);
// Using separator?
if (!_currentSep.empty)
{
_currentSep.popFront();
if (!_currentSep.empty) return;
useItem();
}
else
{
// we're using the range
_current.popFront();
if (!_current.empty) return;
useSeparator();
}
}
static if (isForwardRange!RoR && isForwardRange!(ElementType!RoR))
{
@property auto save()
{
Result copy;
copy._items = _items.save;
copy._current = _current.save;
copy._sep = _sep.save;
copy._currentSep = _currentSep.save;
return copy;
}
}
}
return Result(r, sep);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
static assert(isInputRange!(typeof(joiner([""], ""))));
static assert(isForwardRange!(typeof(joiner([""], ""))));
assert(equal(joiner([""], "xyz"), ""), text(joiner([""], "xyz")));
assert(equal(joiner(["", ""], "xyz"), "xyz"), text(joiner(["", ""], "xyz")));
assert(equal(joiner(["", "abc"], "xyz"), "xyzabc"));
assert(equal(joiner(["abc", ""], "xyz"), "abcxyz"));
assert(equal(joiner(["abc", "def"], "xyz"), "abcxyzdef"));
assert(equal(joiner(["Mary", "has", "a", "little", "lamb"], "..."),
"Mary...has...a...little...lamb"));
}
unittest
{
// joiner() should work for non-forward ranges too.
InputRange!string r = inputRangeObject(["abc", "def"]);
assert (equal(joiner(r, "xyz"), "abcxyzdef"));
}
auto joiner(RoR)(RoR r)
if (isInputRange!RoR && isInputRange!(ElementType!RoR))
{
static struct Result
{
private:
RoR _items;
ElementType!RoR _current;
void prepare()
{
for (;; _items.popFront())
{
if (_items.empty) return;
if (!_items.front.empty) break;
}
_current = _items.front;
_items.popFront();
}
public:
this(RoR r)
{
_items = r;
prepare();
}
static if (isInfinite!(ElementType!RoR))
{
enum bool empty = false;
}
else
{
@property auto empty()
{
return _current.empty;
}
}
@property auto ref front()
{
assert(!empty);
return _current.front;
}
void popFront()
{
assert(!_current.empty);
_current.popFront();
if (_current.empty) prepare();
}
static if (isForwardRange!RoR && isForwardRange!(ElementType!RoR))
{
@property auto save()
{
Result copy;
copy._items = _items.save;
copy._current = _current.save;
return copy;
}
}
}
return Result(r);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
static assert(isInputRange!(typeof(joiner([""]))));
static assert(isForwardRange!(typeof(joiner([""]))));
assert(equal(joiner([""]), ""));
assert(equal(joiner(["", ""]), ""));
assert(equal(joiner(["", "abc"]), "abc"));
assert(equal(joiner(["abc", ""]), "abc"));
assert(equal(joiner(["abc", "def"]), "abcdef"));
assert(equal(joiner(["Mary", "has", "a", "little", "lamb"]),
"Maryhasalittlelamb"));
assert(equal(joiner(std.range.repeat("abc", 3)), "abcabcabc"));
// joiner allows in-place mutation!
auto a = [ [1, 2, 3], [42, 43] ];
auto j = joiner(a);
j.front() = 44;
assert(a == [ [44, 2, 3], [42, 43] ]);
}
// uniq
/**
Iterates unique consecutive elements of the given range (functionality
akin to the $(WEB wikipedia.org/wiki/_Uniq, _uniq) system
utility). Equivalence of elements is assessed by using the predicate
$(D pred), by default $(D "a == b"). If the given range is
bidirectional, $(D uniq) also yields a bidirectional range.
Example:
----
int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
assert(equal(uniq(arr), [ 1, 2, 3, 4, 5 ][]));
----
*/
auto uniq(alias pred = "a == b", Range)(Range r)
if (isInputRange!Range && is(typeof(binaryFun!pred(r.front, r.front)) == bool))
{
struct Result
{
Range _input;
this(Range input)
{
_input = input;
}
auto opSlice()
{
return this;
}
void popFront()
{
auto last = _input.front;
do
{
_input.popFront();
}
while (!_input.empty && binaryFun!(pred)(last, _input.front));
}
@property ElementType!Range front() { return _input.front; }
static if (isBidirectionalRange!Range)
{
void popBack()
{
auto last = _input.back;
do
{
_input.popBack();
}
while (!_input.empty && binaryFun!pred(last, _input.back));
}
@property ElementType!Range back() { return _input.back; }
}
static if (isInfinite!Range)
{
enum bool empty = false; // Propagate infiniteness.
}
else
{
@property bool empty() { return _input.empty; }
}
static if (isForwardRange!Range) {
@property typeof(this) save() {
return typeof(this)(_input.save);
}
}
}
return Result(r);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
auto r = uniq(arr);
static assert(isForwardRange!(typeof(r)));
assert(equal(r, [ 1, 2, 3, 4, 5 ][]));
assert(equal(retro(r), retro([ 1, 2, 3, 4, 5 ][])));
foreach(DummyType; AllDummyRanges) {
DummyType d;
auto u = uniq(d);
assert(equal(u, [1,2,3,4,5,6,7,8,9,10]));
static assert(d.rt == RangeType.Input || isForwardRange!(typeof(u)));
static if (d.rt >= RangeType.Bidirectional) {
assert(equal(retro(u), [10,9,8,7,6,5,4,3,2,1]));
}
}
}
// group
/**
Similarly to $(D uniq), $(D group) iterates unique consecutive
elements of the given range. The element type is $(D
Tuple!(ElementType!R, uint)) because it includes the count of
equivalent elements seen. Equivalence of elements is assessed by using
the predicate $(D pred), by default $(D "a == b").
$(D Group) is an input range if $(D R) is an input range, and a
forward range in all other cases.
Example:
----
int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
assert(equal(group(arr), [ tuple(1, 1u), tuple(2, 4u), tuple(3, 1u),
tuple(4, 3u), tuple(5, 1u) ][]));
----
*/
struct Group(alias pred, R) if (isInputRange!R)
{
private R _input;
private Tuple!(ElementType!R, uint) _current;
private alias binaryFun!pred comp;
this(R input)
{
_input = input;
if (!_input.empty) popFront();
}
void popFront()
{
if (_input.empty)
{
_current[1] = 0;
}
else
{
_current = tuple(_input.front, 1u);
_input.popFront();
while (!_input.empty && comp(_current[0], _input.front))
{
++_current[1];
_input.popFront();
}
}
}
static if (isInfinite!R)
{
enum bool empty = false; // Propagate infiniteness.
}
else
{
@property bool empty()
{
return _current[1] == 0;
}
}
@property ref Tuple!(ElementType!R, uint) front()
{
assert(!empty);
return _current;
}
static if (isForwardRange!R) {
@property typeof(this) save() {
typeof(this) ret;
ret._input = this._input.save;
ret._current = this._current;
return ret;
}
}
}
/// Ditto
Group!(pred, Range) group(alias pred = "a == b", Range)(Range r)
{
return typeof(return)(r);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
assert(equal(group(arr), [ tuple(1, 1u), tuple(2, 4u), tuple(3, 1u),
tuple(4, 3u), tuple(5, 1u) ][]));
static assert(isForwardRange!(typeof(group(arr))));
foreach(DummyType; AllDummyRanges) {
DummyType d;
auto g = group(d);
static assert(d.rt == RangeType.Input || isForwardRange!(typeof(g)));
assert(equal(g, [tuple(1, 1u), tuple(2, 1u), tuple(3, 1u), tuple(4, 1u),
tuple(5, 1u), tuple(6, 1u), tuple(7, 1u), tuple(8, 1u),
tuple(9, 1u), tuple(10, 1u)]));
}
}
// overwriteAdjacent
/*
Reduces $(D r) by shifting it to the left until no adjacent elements
$(D a), $(D b) remain in $(D r) such that $(D pred(a, b)). Shifting is
performed by evaluating $(D move(source, target)) as a primitive. The
algorithm is stable and runs in $(BIGOH r.length) time. Returns the
reduced range.
The default $(XREF _algorithm, move) performs a potentially
destructive assignment of $(D source) to $(D target), so the objects
beyond the returned range should be considered "empty". By default $(D
pred) compares for equality, in which case $(D overwriteAdjacent)
collapses adjacent duplicate elements to one (functionality akin to
the $(WEB wikipedia.org/wiki/Uniq, uniq) system utility).
Example:
----
int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
auto r = overwriteAdjacent(arr);
assert(r == [ 1, 2, 3, 4, 5 ]);
----
*/
// Range overwriteAdjacent(alias pred, alias move, Range)(Range r)
// {
// if (r.empty) return r;
// //auto target = begin(r), e = end(r);
// auto target = r;
// auto source = r;
// source.popFront();
// while (!source.empty)
// {
// if (!pred(target.front, source.front))
// {
// target.popFront();
// continue;
// }
// // found an equal *source and *target
// for (;;)
// {
// //@@@
// //move(source.front, target.front);
// target[0] = source[0];
// source.popFront();
// if (source.empty) break;
// if (!pred(target.front, source.front)) target.popFront();
// }
// break;
// }
// return range(begin(r), target + 1);
// }
// /// Ditto
// Range overwriteAdjacent(
// string fun = "a == b",
// alias move = .move,
// Range)(Range r)
// {
// return .overwriteAdjacent!(binaryFun!(fun), move, Range)(r);
// }
// unittest
// {
// int[] arr = [ 1, 2, 2, 2, 2, 3, 4, 4, 4, 5 ];
// auto r = overwriteAdjacent(arr);
// assert(r == [ 1, 2, 3, 4, 5 ]);
// assert(arr == [ 1, 2, 3, 4, 5, 3, 4, 4, 4, 5 ]);
// }
// find
/**
Finds an individual element in an input range. Elements of $(D
haystack) are compared with $(D needle) by using predicate $(D
pred). Performs $(BIGOH walkLength(haystack)) evaluations of $(D
pred). See also $(WEB sgi.com/tech/stl/_find.html, STL's _find).
To _find the last occurence of $(D needle) in $(D haystack), call $(D
find(retro(haystack), needle)). See also $(XREF range, retro).
Params:
haystack = The range searched in.
needle = The element searched for.
Constraints:
$(D isInputRange!R && is(typeof(binaryFun!pred(haystack.front, needle)
: bool)))
Returns:
$(D haystack) advanced such that $(D binaryFun!pred(haystack.front,
needle)) is $(D true) (if no such position exists, returns $(D
haystack) after exhaustion).
Example:
----
assert(find("hello, world", ',') == ", world");
assert(find([1, 2, 3, 5], 4) == []);
assert(find(SList!int(1, 2, 3, 4, 5)[], 4) == SList!int(4, 5)[]);
assert(find!"a > b"([1, 2, 3, 5], 2) == [3, 5]);
auto a = [ 1, 2, 3 ];
assert(find(a, 5).empty); // not found
assert(!find(a, 2).empty); // found
// Case-insensitive find of a string
string[] s = [ "Hello", "world", "!" ];
assert(!find!("toLower(a) == b")(s, "hello").empty);
----
*/
R find(alias pred = "a == b", R, E)(R haystack, E needle)
if (isInputRange!R &&
is(typeof(binaryFun!pred(haystack.front, needle)) : bool))
{
for (; !haystack.empty; haystack.popFront())
{
if (binaryFun!pred(haystack.front, needle)) break;
}
return haystack;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto lst = SList!int(1, 2, 5, 7, 3);
assert(lst.front == 1);
auto r = find(lst[], 5);
assert(equal(r, SList!int(5, 7, 3)[]));
assert(find([1, 2, 3, 5], 4).empty);
}
/**
Finds a forward range in another. Elements are compared for
equality. Performs $(BIGOH walkLength(haystack) * walkLength(needle))
comparisons in the worst case. Specializations taking advantage of
bidirectional or random access (where present) may accelerate search
depending on the statistics of the two ranges' content.
Params:
haystack = The range searched in.
needle = The range searched for.
Constraints:
$(D isForwardRange!R1 && isForwardRange!R2 &&
is(typeof(binaryFun!pred(haystack.front, needle.front) : bool)))
Returns:
$(D haystack) advanced such that $(D needle) is a prefix of it (if no
such position exists, returns $(D haystack) advanced to termination).
----
assert(find("hello, world", "World").empty);
assert(find("hello, world", "wo") == "world");
assert(find([1, 2, 3, 4], SList!(2, 3)[]) == [2, 3, 4]);
----
*/
R1 find(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)
if (isForwardRange!R1 && isForwardRange!R2
&& is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool)
&& !isRandomAccessRange!R1)
{
static if (is(typeof(pred == "a == b")) && pred == "a == b" && isSomeString!R1 && isSomeString!R2
&& haystack[0].sizeof == needle[0].sizeof)
{
//return cast(R1) find(representation(haystack), representation(needle));
// Specialization for simple string search
alias Select!(haystack[0].sizeof == 1, ubyte[],
Select!(haystack[0].sizeof == 2, ushort[], uint[]))
Representation;
// Will use the array specialization
return cast(R1) .find!(pred, Representation, Representation)
(cast(Representation) haystack, cast(Representation) needle);
}
else
{
return simpleMindedFind!pred(haystack, needle);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto lst = SList!int(1, 2, 5, 7, 3);
static assert(isForwardRange!(int[]));
static assert(isForwardRange!(typeof(lst[])));
auto r = find(lst[], [2, 5]);
assert(equal(r, SList!int(2, 5, 7, 3)[]));
}
// Specialization for searching a random-access range for a
// bidirectional range
R1 find(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)
if (isRandomAccessRange!R1 && isBidirectionalRange!R2
&& is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool))
{
if (needle.empty) return haystack;
const needleLength = walkLength(needle);
if (needleLength > haystack.length)
{
// @@@BUG@@@
//return haystack[$ .. $];
return haystack[haystack.length .. haystack.length];
}
// @@@BUG@@@
// auto needleBack = moveBack(needle);
// Stage 1: find the step
size_t step = 1;
auto needleBack = needle.back;
needle.popBack();
for (auto i = needle.save; !i.empty && !binaryFun!pred(i.back, needleBack);
i.popBack(), ++step)
{
}
// Stage 2: linear find
size_t scout = needleLength - 1;
for (;;)
{
if (scout >= haystack.length)
{
return haystack[haystack.length .. haystack.length];
}
if (!binaryFun!pred(haystack[scout], needleBack))
{
++scout;
continue;
}
// Found a match with the last element in the needle
auto cand = haystack[scout + 1 - needleLength .. haystack.length];
if (startsWith!pred(cand, needle))
{
// found
return cand;
}
// Continue with the stride
scout += step;
}
}
unittest
{
//scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done.");
// @@@BUG@@@ removing static below makes unittest fail
static struct BiRange
{
int[] payload;
@property bool empty() { return payload.empty; }
@property BiRange save() { return this; }
@property ref int front() { return payload[0]; }
@property ref int back() { return payload[$ - 1]; }
void popFront() { return payload.popFront(); }
void popBack() { return payload.popBack(); }
}
//static assert(isBidirectionalRange!BiRange);
auto r = BiRange([1, 2, 3, 10, 11, 4]);
//assert(equal(find(r, [3, 10]), BiRange([3, 10, 11, 4])));
//assert(find("abc", "bc").length == 2);
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
//assert(find!"a == b"("abc", "bc").length == 2);
}
// Leftover specialization: searching a random-access range for a
// non-bidirectional forward range
R1 find(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)
if (isRandomAccessRange!R1 && isForwardRange!R2 && !isBidirectionalRange!R2
&& is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool))
{
static if (!is(ElementType!R1 == ElementType!R2))
{
return simpleMindedFind!pred(haystack, needle);
}
else
{
// Prepare the search with needle's first element
if (needle.empty) return haystack;
haystack = .find!pred(haystack, needle.front);
if (haystack.empty) return haystack;
needle.popFront();
size_t matchLen = 1;
// Loop invariant: haystack[0 .. matchLen] matches everything in
// the initial needle that was popped out of needle.
for (;;)
{
// Extend matchLength as much as possible
for (;;)
{
if (needle.empty || haystack.empty) return haystack;
if (!binaryFun!pred(haystack[matchLen], needle.front)) break;
++matchLen;
needle.popFront();
}
auto bestMatch = haystack[0 .. matchLen];
haystack.popFront();
haystack = .find!pred(haystack, bestMatch);
}
}
}
unittest
{
assert(find([ 1, 2, 3 ], SList!int(2, 3)[]) == [ 2, 3 ]);
assert(find([ 1, 2, 1, 2, 3, 3 ], SList!int(2, 3)[]) == [ 2, 3, 3 ]);
}
// Internally used by some find() overloads above. Can't make it
// private due to bugs in the compiler.
/*private*/ R1 simpleMindedFind(alias pred, R1, R2)(R1 haystack, R2 needle)
{
enum estimateNeedleLength = hasLength!R1 && !hasLength!R2;
static if (hasLength!R1)
{
static if (hasLength!R2)
size_t estimatedNeedleLength = 0;
else
immutable size_t estimatedNeedleLength = needle.length;
}
bool haystackTooShort()
{
static if (hasLength!R1)
{
return haystack.length < estimatedNeedleLength;
}
else
{
return haystack.empty;
}
}
searching:
for (;; haystack.popFront())
{
if (haystackTooShort())
{
// Failed search
static if (hasLength!R1)
{
static if (is(typeof(haystack[haystack.length ..
haystack.length]) : R1))
return haystack[haystack.length .. haystack.length];
else
return R1.init;
}
else
{
assert(haystack.empty);
return haystack;
}
}
static if (estimateNeedleLength)
size_t matchLength = 0;
for (auto h = haystack.save, n = needle.save;
!n.empty;
h.popFront(), n.popFront())
{
if (h.empty || !binaryFun!pred(h.front, n.front))
{
// Failed searching n in h
static if (estimateNeedleLength)
{
if (estimatedNeedleLength < matchLength)
estimatedNeedleLength = matchLength;
}
continue searching;
}
static if (estimateNeedleLength)
++matchLength;
}
break;
}
return haystack;
}
/**
Finds two or more $(D needles) into a $(D haystack). The predicate $(D
pred) is used throughout to compare elements. By default, elements are
compared for equality.
Params:
haystack = The target of the search. Must be an $(GLOSSARY input
range). If any of $(D needles) is a range with elements comparable to
elements in $(D haystack), then $(D haystack) must be a $(GLOSSARY
forward range) such that the search can backtrack.
needles = One or more items to search for. Each of $(D needles) must
be either comparable to one element in $(D haystack), or be itself a
$(GLOSSARY forward range) with elements comparable with elements in
$(D haystack).
Returns:
A tuple containing $(D haystack) positioned to match one of the
needles and also the 1-based index of the matching element in $(D
needles) (0 if none of $(D needles) matched, 1 if $(D needles[0])
matched, 2 if $(D needles[1]) matched...). The first needle to be found
will be the one that matches. If multiple needles are found at the
same spot in the range, then the shortest one is the one which matches
(if multiple needles of the same length are found at the same spot (e.g
$(D "a") and $(D 'a')), then the left-most of them in the argument list
matches).
The relationship between $(D haystack) and $(D needles) simply means
that one can e.g. search for individual $(D int)s or arrays of $(D
int)s in an array of $(D int)s. In addition, if elements are
individually comparable, searches of heterogeneous types are allowed
as well: a $(D double[]) can be searched for an $(D int) or a $(D
short[]), and conversely a $(D long) can be searched for a $(D float)
or a $(D double[]). This makes for efficient searches without the need
to coerce one side of the comparison into the other's side type.
Example:
----
int[] a = [ 1, 4, 2, 3 ];
assert(find(a, 4) == [ 4, 2, 3 ]);
assert(find(a, [ 1, 4 ]) == [ 1, 4, 2, 3 ]);
assert(find(a, [ 1, 3 ], 4) == tuple([ 4, 2, 3 ], 2));
// Mixed types allowed if comparable
assert(find(a, 5, [ 1.2, 3.5 ], 2.0, [ 1 ]) == tuple([ 2, 3 ], 3));
----
The complexity of the search is $(BIGOH haystack.length *
max(needles.length)). (For needles that are individual items, length
is considered to be 1.) The strategy used in searching several
subranges at once maximizes cache usage by moving in $(D haystack) as
few times as possible.
*/
Tuple!(Range, size_t) find(alias pred = "a == b", Range, Ranges...)
(Range haystack, Ranges needles)
if (Ranges.length > 1 && allSatisfy!(isForwardRange, Ranges))
{
for (;; haystack.popFront())
{
size_t r = startsWith!pred(haystack, needles);
if (r || haystack.empty)
{
return tuple(haystack, r);
}
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto s1 = "Mary has a little lamb";
//writeln(find(s1, "has a", "has an"));
assert(find(s1, "has a", "has an") == tuple("has a little lamb", 1));
assert(find("abc", "bc").length == 2);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3 ];
assert(find(a, 5).empty);
assert(find(a, 2) == [2, 3]);
foreach (T; TypeTuple!(int, double))
{
auto b = rndstuff!(T)();
if (!b.length) continue;
b[$ / 2] = 200;
b[$ / 4] = 200;
assert(find(b, 200).length == b.length - b.length / 4);
}
// Case-insensitive find of a string
string[] s = [ "Hello", "world", "!" ];
//writeln(find!("toUpper(a) == toUpper(b)")(s, "hello"));
assert(find!("toUpper(a) == toUpper(b)")(s, "hello").length == 3);
static bool f(string a, string b) { return toUpper(a) == toUpper(b); }
assert(find!(f)(s, "hello").length == 3);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3, 2, 6 ];
assert(find(std.range.retro(a), 5).empty);
assert(equal(find(std.range.retro(a), 2), [ 2, 3, 2, 1 ][]));
foreach (T; TypeTuple!(int, double))
{
auto b = rndstuff!(T)();
if (!b.length) continue;
b[$ / 2] = 200;
b[$ / 4] = 200;
assert(find(std.range.retro(b), 200).length ==
b.length - (b.length - 1) / 2);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ -1, 0, 1, 2, 3, 4, 5 ];
int[] b = [ 1, 2, 3 ];
assert(find(a, b) == [ 1, 2, 3, 4, 5 ]);
assert(find(b, a).empty);
foreach(DummyType; AllDummyRanges) {
DummyType d;
auto findRes = find(d, 5);
assert(equal(findRes, [5,6,7,8,9,10]));
}
}
/// Ditto
struct BoyerMooreFinder(alias pred, Range)
{
private:
size_t skip[];
sizediff_t[ElementType!(Range)] occ;
Range needle;
sizediff_t occurrence(ElementType!(Range) c)
{
auto p = c in occ;
return p ? *p : -1;
}
/*
This helper function checks whether the last "portion" bytes of
"needle" (which is "nlen" bytes long) exist within the "needle" at
offset "offset" (counted from the end of the string), and whether the
character preceding "offset" is not a match. Notice that the range
being checked may reach beyond the beginning of the string. Such range
is ignored.
*/
static bool needlematch(R)(R needle,
size_t portion, size_t offset)
{
sizediff_t virtual_begin = needle.length - offset - portion;
sizediff_t ignore = 0;
if (virtual_begin < 0) {
ignore = -virtual_begin;
virtual_begin = 0;
}
if (virtual_begin > 0
&& needle[virtual_begin - 1] == needle[$ - portion - 1])
return 0;
immutable delta = portion - ignore;
return equal(needle[needle.length - delta .. needle.length],
needle[virtual_begin .. virtual_begin + delta]);
}
public:
this(Range needle)
{
if (!needle.length) return;
this.needle = needle;
/* Populate table with the analysis of the needle */
/* But ignoring the last letter */
foreach (i, n ; needle[0 .. $ - 1])
{
this.occ[n] = i;
}
/* Preprocess #2: init skip[] */
/* Note: This step could be made a lot faster.
* A simple implementation is shown here. */
this.skip = new size_t[needle.length];
foreach (a; 0 .. needle.length)
{
size_t value = 0;
while (value < needle.length
&& !needlematch(needle, a, value))
{
++value;
}
this.skip[needle.length - a - 1] = value;
}
}
Range beFound(Range haystack)
{
if (!needle.length) return haystack;
if (needle.length > haystack.length) return haystack[$ .. $];
/* Search: */
auto limit = haystack.length - needle.length;
for (size_t hpos = 0; hpos <= limit; )
{
size_t npos = needle.length - 1;
while (pred(needle[npos], haystack[npos+hpos]))
{
if (npos == 0) return haystack[hpos .. $];
--npos;
}
hpos += max(skip[npos], npos - occurrence(haystack[npos+hpos]));
}
return haystack[$ .. $];
}
@property size_t length()
{
return needle.length;
}
alias length opDollar;
}
/// Ditto
BoyerMooreFinder!(binaryFun!(pred), Range) boyerMooreFinder
(alias pred = "a == b", Range)
(Range needle) if (isRandomAccessRange!(Range) || isSomeString!Range)
{
return typeof(return)(needle);
}
// Oddly this is not disabled by bug 4759
Range1 find(Range1, alias pred, Range2)(
Range1 haystack, BoyerMooreFinder!(pred, Range2) needle)
{
return needle.beFound(haystack);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
string h = "/homes/aalexand/d/dmd/bin/../lib/libphobos.a(dmain2.o)"
"(.gnu.linkonce.tmain+0x74): In function `main' undefined reference"
" to `_Dmain':";
string[] ns = ["libphobos", "function", " undefined", "`", ":"];
foreach (n ; ns) {
auto p = find(h, boyerMooreFinder(n));
assert(!p.empty);
}
int[] a = [ -1, 0, 1, 2, 3, 4, 5 ];
int[] b = [ 1, 2, 3 ];
//writeln(find(a, boyerMooreFinder(b)));
assert(find(a, boyerMooreFinder(b)) == [ 1, 2, 3, 4, 5 ]);
assert(find(b, boyerMooreFinder(a)).empty);
}
/**
Advances the input range $(D haystack) by calling $(D haystack.popFront)
until either $(D pred(haystack.front)), or $(D
haystack.empty). Performs $(BIGOH haystack.length) evaluations of $(D
pred). See also $(WEB sgi.com/tech/stl/find_if.html, STL's find_if).
To find the last element of a bidirectional $(D haystack) satisfying
$(D pred), call $(D find!(pred)(retro(haystack))). See also $(XREF
range, retro).
Example:
----
auto arr = [ 1, 2, 3, 4, 1 ];
assert(find!("a > 2")(arr) == [ 3, 4, 1 ]);
// with predicate alias
bool pred(int x) { return x + 1 > 1.5; }
assert(find!(pred)(arr) == arr);
----
*/
Range find(alias pred, Range)(Range haystack) if (isInputRange!(Range))
{
alias unaryFun!(pred) predFun;
for (; !haystack.empty && !predFun(haystack.front); haystack.popFront())
{
}
return haystack;
}
unittest
{
//scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3 ];
assert(find!("a > 2")(a) == [3]);
bool pred(int x) { return x + 1 > 1.5; }
assert(find!(pred)(a) == a);
}
// findSkip
/**
* If $(D needle) occurs in $(D haystack), positions $(D haystack)
* right after the first occurrence of $(D needle) and returns $(D
* true). Otherwise, leaves $(D haystack) as is and returns $(D
* false).
*
* Example:
----
string s = "abcdef";
assert(findSkip(s, "cd") && s == "ef");
s = "abcdef";
assert(!findSkip(s, "cxd") && s == "abcdef");
assert(findSkip(s, "def") && s.empty);
----
*/
bool findSkip(alias pred = "a == b", R1, R2)(ref R1 haystack, R2 needle)
if (isForwardRange!R1 && isForwardRange!R2
&& is(typeof(binaryFun!pred(haystack.front, needle.front))))
{
auto parts = findSplit!pred(haystack, needle);
if (parts[1].empty) return false;
// found
haystack = parts[2];
return true;
}
unittest
{
string s = "abcdef";
assert(findSkip(s, "cd") && s == "ef");
s = "abcdef";
assert(!findSkip(s, "cxd") && s == "abcdef");
s = "abcdef";
assert(findSkip(s, "def") && s.empty);
}
/**
These functions find the first occurrence of $(D needle) in $(D
haystack) and then split $(D haystack) as follows.
$(D findSplit) returns a tuple $(D result) containing $(I three)
ranges. $(D result[0]) is the portion of $(D haystack) before $(D
needle), $(D result[1]) is the portion of $(D haystack) that matches
$(D needle), and $(D result[2]) is the portion of $(D haystack) after
the match.
$(D findSplitBefore) returns a tuple $(D result) containing two
ranges. $(D result[0]) is the portion of $(D haystack) before $(D
needle), and $(D result[1]) is the balance of $(D haystack) starting
with the match. If $(D needle) was not found, $(D result[0])
comprehends $(D haystack) entirely and $(D result[1]) is empty.
$(D findSplitAfter) returns a tuple $(D result) containing two ranges.
$(D result[0]) is the portion of $(D haystack) up to and including the
match, and $(D result[1]) is the balance of $(D haystack) starting
after the match. If $(D needle) was not found, $(D result[0]) is empty
and $(D result[1]) is $(D haystack).
In all cases, the concatenation of the returned ranges spans the
entire $(D haystack).
If $(D haystack) is a random-access range, all three components of the
tuple have the same type as $(D haystack). Otherwise, $(D haystack)
must be a forward range and the type of $(D result[0]) and $(D
result[1]) is the same as $(XREF range,takeExactly).
Example:
----
auto a = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
auto r = findSplit(a, [9, 1]);
assert(r[0] == a);
assert(r[1].empty);
assert(r[2].empty);
r = findSplit(a, [ 3, 4 ]);
assert(r[0] == a[0 .. 2]);
assert(r[1] == a[2 .. 4]);
assert(r[2] == a[4 .. $]);
auto r1 = findSplitBefore(a, [ 7, 8 ]);
assert(r1[0] == a[0 .. 6]);
assert(r1[1] == a[6 .. $]);
auto r1 = findSplitAfter(a, [ 7, 8 ]);
assert(r1[0] == a);
assert(r1[1].empty);
----
*/
auto findSplit(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)
if (isForwardRange!R1 && isForwardRange!R2)
{
static if (isSomeString!R1 && isSomeString!R2
|| isRandomAccessRange!R1 && hasLength!R2)
{
auto balance = find!pred(haystack, needle);
immutable pos1 = haystack.length - balance.length;
immutable pos2 = balance.empty ? pos1 : pos1 + needle.length;
return tuple(haystack[0 .. pos1],
haystack[pos1 .. pos2],
haystack[pos2 .. haystack.length]);
}
else
{
auto original = haystack.save;
auto h = haystack.save;
auto n = needle.save;
size_t pos1, pos2;
while (!n.empty && !h.empty)
{
if (binaryFun!pred(h.front, n.front))
{
h.popFront();
n.popFront();
++pos2;
}
else
{
haystack.popFront();
n = needle.save;
h = haystack.save;
pos2 = ++pos1;
}
}
return tuple(takeExactly(original, pos1),
takeExactly(haystack, pos2 - pos1),
h);
}
}
/// Ditto
auto findSplitBefore(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)
if (isForwardRange!R1 && isForwardRange!R2)
{
static if (isSomeString!R1 && isSomeString!R2
|| isRandomAccessRange!R1 && hasLength!R2)
{
auto balance = find!pred(haystack, needle);
immutable pos = haystack.length - balance.length;
return tuple(haystack[0 .. pos], haystack[pos .. haystack.length]);
}
else
{
auto original = haystack.save;
auto h = haystack.save;
auto n = needle.save;
size_t pos;
while (!n.empty && !h.empty)
{
if (binaryFun!pred(h.front, n.front))
{
h.popFront();
n.popFront();
}
else
{
haystack.popFront();
n = needle.save;
h = haystack.save;
++pos;
}
}
return tuple(takeExactly(original, pos), haystack);
}
}
/// Ditto
auto findSplitAfter(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)
if (isForwardRange!R1 && isForwardRange!R2)
{
static if (isSomeString!R1 && isSomeString!R2
|| isRandomAccessRange!R1 && hasLength!R2)
{
auto balance = find!pred(haystack, needle);
immutable pos = balance.empty ? 0 : haystack.length - balance.length + needle.length;
return tuple(haystack[0 .. pos], haystack[pos .. haystack.length]);
}
else
{
auto original = haystack.save;
auto h = haystack.save;
auto n = needle.save;
size_t pos1, pos2;
while (!n.empty)
{
if (h.empty)
{
// Failed search
return tuple(takeExactly(original, 0), original);
}
if (binaryFun!pred(h.front, n.front))
{
h.popFront();
n.popFront();
++pos2;
}
else
{
haystack.popFront();
n = needle.save;
h = haystack.save;
pos2 = ++pos1;
}
}
return tuple(takeExactly(original, pos2), h);
}
}
unittest
{
auto a = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
auto r = findSplit(a, [9, 1]);
assert(r[0] == a);
assert(r[1].empty);
assert(r[2].empty);
r = findSplit(a, [3]);
assert(r[0] == a[0 .. 2]);
assert(r[1] == a[2 .. 3]);
assert(r[2] == a[3 .. $]);
auto r1 = findSplitBefore(a, [9, 1]);
assert(r1[0] == a);
assert(r1[1].empty);
r1 = findSplitBefore(a, [3, 4]);
assert(r1[0] == a[0 .. 2]);
assert(r1[1] == a[2 .. $]);
r1 = findSplitAfter(a, [9, 1]);
assert(r1[0].empty);
assert(r1[1] == a);
r1 = findSplitAfter(a, [3, 4]);
assert(r1[0] == a[0 .. 4]);
assert(r1[1] == a[4 .. $]);
}
unittest
{
auto a = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
auto fwd = filter!"a > 0"(a);
auto r = findSplit(fwd, [9, 1]);
assert(equal(r[0], a));
assert(r[1].empty);
assert(r[2].empty);
r = findSplit(fwd, [3]);
assert(equal(r[0], a[0 .. 2]));
assert(equal(r[1], a[2 .. 3]));
assert(equal(r[2], a[3 .. $]));
auto r1 = findSplitBefore(fwd, [9, 1]);
assert(equal(r1[0], a));
assert(r1[1].empty);
r1 = findSplitBefore(fwd, [3, 4]);
assert(equal(r1[0], a[0 .. 2]));
assert(equal(r1[1], a[2 .. $]));
r1 = findSplitAfter(fwd, [9, 1]);
assert(r1[0].empty);
assert(equal(r1[1], a));
r1 = findSplitAfter(fwd, [3, 4]);
assert(equal(r1[0], a[0 .. 4]));
assert(equal(r1[1], a[4 .. $]));
}
/++
Returns the number of elements which must be popped from the front of
$(D haystack) before reaching an element for which
$(D startsWith!pred(haystack, needle)) is $(D true). If
$(D startsWith!pred(haystack, needle)) is not $(D true) for any element in
$(D haystack), then -1 is returned.
$(D needle) may be either an element or a range.
Examples:
--------------------
assert(countUntil("hello world", "world") == 6);
assert(countUntil("hello world", 'r') == 8);
assert(countUntil("hello world", "programming") == -1);
assert(countUntil([0, 7, 12, 22, 9], [12, 22]) == 2);
assert(countUntil([0, 7, 12, 22, 9], 9) == 4);
assert(countUntil!"a > b"([0, 7, 12, 22, 9], 20) == 3);
--------------------
+/
sizediff_t countUntil(alias pred = "a == b", R, N)(R haystack, N needle)
if (is(typeof(startsWith!pred(haystack, needle))))
{
static if (isNarrowString!R)
{
// Narrow strings are handled a bit differently
auto length = haystack.length;
for (; !haystack.empty; haystack.popFront())
{
if (startsWith!pred(haystack, needle))
{
return length - haystack.length;
}
}
}
else
{
typeof(return) result;
for (; !haystack.empty; ++result, haystack.popFront())
{
if (startsWith!pred(haystack, needle)) return result;
}
}
return -1;
}
//Verify Examples.
unittest
{
assert(countUntil("hello world", "world") == 6);
assert(countUntil("hello world", 'r') == 8);
assert(countUntil("hello world", "programming") == -1);
assert(countUntil([0, 7, 12, 22, 9], [12, 22]) == 2);
assert(countUntil([0, 7, 12, 22, 9], 9) == 4);
assert(countUntil!"a > b"([0, 7, 12, 22, 9], 20) == 3);
}
/++
Returns the number of elements which must be popped from $(D haystack)
before $(D pred(hastack.front)) is $(D true.).
Examples:
--------------------
assert(countUntil!(std.uni.isWhite)("hello world") == 5);
assert(countUntil!(std.ascii.isDigit)("hello world") == -1);
assert(countUntil!"a > 20"([0, 7, 12, 22, 9]) == 3);
--------------------
+/
sizediff_t countUntil(alias pred, R)(R haystack)
if (isForwardRange!R && is(typeof(unaryFun!pred(haystack.front)) == bool))
{
static if (isNarrowString!R)
{
// Narrow strings are handled a bit differently
auto length = haystack.length;
for (; !haystack.empty; haystack.popFront())
{
if (unaryFun!pred(haystack.front))
{
return length - haystack.length;
}
}
}
else
{
typeof(return) result;
for (; !haystack.empty; ++result, haystack.popFront())
{
if (unaryFun!pred(haystack.front)) return result;
}
}
return -1;
}
//Verify Examples.
unittest
{
assert(countUntil!(std.uni.isWhite)("hello world") == 5);
assert(countUntil!(std.ascii.isDigit)("hello world") == -1);
assert(countUntil!"a > 20"([0, 7, 12, 22, 9]) == 3);
}
/**
* $(RED Scheduled for deprecation. Please use $(XREF algorithm, countUntil)
* instead.)
*
* Same as $(D countUntil). This symbol has been scheduled for
* deprecation because it is easily confused with the homonym function
* in $(D std.string).
*/
sizediff_t indexOf(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)
if (is(typeof(startsWith!pred(haystack, needle))))
{
return countUntil!pred(haystack, needle);
}
/**
Interval option specifier for $(D until) (below) and others.
*/
enum OpenRight
{
no, /// Interval is closed to the right (last element included)
yes /// Interval is open to the right (last element is not included)
}
/**
Lazily iterates $(D range) until value $(D sentinel) is found, at
which point it stops.
Example:
----
int[] a = [ 1, 2, 4, 7, 7, 2, 4, 7, 3, 5];
assert(equal(a.until(7), [1, 2, 4][]));
assert(equal(a.until(7, OpenRight.no), [1, 2, 4, 7][]));
----
*/
struct Until(alias pred, Range, Sentinel) if (isInputRange!Range)
{
private Range _input;
static if (!is(Sentinel == void))
private Sentinel _sentinel;
// mixin(bitfields!(
// OpenRight, "_openRight", 1,
// bool, "_done", 1,
// uint, "", 6));
// OpenRight, "_openRight", 1,
// bool, "_done", 1,
OpenRight _openRight;
bool _done;
static if (!is(Sentinel == void))
this(Range input, Sentinel sentinel,
OpenRight openRight = OpenRight.yes)
{
_input = input;
_sentinel = sentinel;
_openRight = openRight;
_done = _input.empty || openRight && predSatisfied();
}
else
this(Range input, OpenRight openRight = OpenRight.yes)
{
_input = input;
_openRight = openRight;
_done = _input.empty || openRight && predSatisfied();
}
@property bool empty()
{
return _done;
}
@property ElementType!Range front()
{
assert(!empty);
return _input.front;
}
private bool predSatisfied()
{
static if (is(Sentinel == void))
return unaryFun!pred(_input.front);
else
return startsWith!pred(_input, _sentinel);
}
void popFront()
{
assert(!empty);
if (!_openRight)
{
if (predSatisfied())
{
_done = true;
return;
}
_input.popFront();
_done = _input.empty;
}
else
{
_input.popFront();
_done = _input.empty || predSatisfied();
}
}
static if (isForwardRange!Range)
{
static if (!is(Sentinel == void))
@property Until save()
{
Until result;
result._input = _input.save;
result._sentinel = _sentinel;
result._openRight = _openRight;
result._done = _done;
return result;
}
else
@property Until save()
{
Until result;
result._input = _input.save;
result._openRight = _openRight;
result._done = _done;
return result;
}
}
}
/// Ditto
Until!(pred, Range, Sentinel)
until(alias pred = "a == b", Range, Sentinel)
(Range range, Sentinel sentinel, OpenRight openRight = OpenRight.yes)
if (!is(Sentinel == OpenRight))
{
return typeof(return)(range, sentinel, openRight);
}
/// Ditto
Until!(pred, Range, void)
until(alias pred, Range)
(Range range, OpenRight openRight = OpenRight.yes)
{
return typeof(return)(range, openRight);
}
unittest
{
//scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 4, 7, 7, 2, 4, 7, 3, 5];
static assert(isForwardRange!(typeof(a.until(7))));
static assert(isForwardRange!(typeof(until!"a == 2"(a, OpenRight.no))));
assert(equal(a.until(7), [1, 2, 4][]));
assert(equal(a.until([7, 2]), [1, 2, 4, 7][]));
assert(equal(a.until(7, OpenRight.no), [1, 2, 4, 7][]));
assert(equal(until!"a == 2"(a, OpenRight.no), [1, 2][]));
}
/**
If the range $(D doesThisStart) starts with $(I any) of the $(D
withOneOfThese) ranges or elements, returns 1 if it starts with $(D
withOneOfThese[0]), 2 if it starts with $(D withOneOfThese[1]), and so
on. If none match, returns 0. In the case where $(D doesThisStart) starts
with multiple of the ranges or elements in $(D withOneOfThese), then the
shortest one matches (if there are two which match which are of the same
length (e.g. $(D "a") and $(D 'a')), then the left-most of them in the argument
list matches).
Example:
----
assert(startsWith("abc", ""));
assert(startsWith("abc", "a"));
assert(!startsWith("abc", "b"));
assert(startsWith("abc", 'a', "b") == 1);
assert(startsWith("abc", "b", "a") == 2);
assert(startsWith("abc", "a", "a") == 1);
assert(startsWith("abc", "ab", "a") == 2);
assert(startsWith("abc", "x", "a", "b") == 2);
assert(startsWith("abc", "x", "aa", "ab") == 3);
assert(startsWith("abc", "x", "aaa", "sab") == 0);
assert(startsWith("abc", "x", "aaa", "a", "sab") == 3);
----
*/
uint startsWith(alias pred = "a == b", Range, Ranges...)
(Range doesThisStart, Ranges withOneOfThese)
if (isInputRange!Range && Ranges.length > 1 &&
is(typeof(.startsWith!pred(doesThisStart, withOneOfThese[0])) : bool ) &&
is(typeof(.startsWith!pred(doesThisStart, withOneOfThese[1 .. $])) : uint))
{
alias doesThisStart haystack;
alias withOneOfThese needles;
// Make one pass looking for empty ranges
foreach (i, Unused; Ranges)
{
// Empty range matches everything
static if (!is(typeof(binaryFun!pred(haystack.front, needles[i])) : bool))
{
if (needles[i].empty) return i + 1;
}
}
for (; !haystack.empty; haystack.popFront())
{
foreach (i, Unused; Ranges)
{
static if (is(typeof(binaryFun!pred(haystack.front, needles[i])) : bool))
{
// Single-element
if (binaryFun!pred(haystack.front, needles[i]))
{
// found, but continue to account for one-element
// range matches (consider startsWith("ab", "a",
// 'a') should return 1, not 2).
continue;
}
}
else
{
if (binaryFun!pred(haystack.front, needles[i].front))
{
continue;
}
}
// This code executed on failure to match
// Out with this guy, check for the others
uint result = startsWith!pred(haystack, needles[0 .. i], needles[i + 1 .. $]);
if (result > i) ++result;
return result;
}
// If execution reaches this point, then the front matches for all
// needles ranges. What we need to do now is to lop off the front of
// all ranges involved and recurse.
foreach (i, Unused; Ranges)
{
static if (is(typeof(binaryFun!pred(haystack.front, needles[i])) : bool))
{
// Test has passed in the previous loop
return i + 1;
}
else
{
needles[i].popFront();
if (needles[i].empty) return i + 1;
}
}
}
return 0;
}
/// Ditto
bool startsWith(alias pred = "a == b", R1, R2)
(R1 doesThisStart, R2 withThis)
if (isInputRange!R1 &&
isInputRange!R2 &&
is(typeof(binaryFun!pred(doesThisStart.front, withThis.front)) : bool))
{
alias doesThisStart haystack;
alias withThis needle;
static if(is(typeof(pred) : string))
enum isDefaultPred = pred == "a == b";
else
enum isDefaultPred = false;
// Special case for two arrays
static if (isArray!R1 && isArray!R2 &&
((!isSomeString!R1 && !isSomeString!R2) ||
(isSomeString!R1 && isSomeString!R2 &&
is(Unqual!(typeof(haystack[0])) == Unqual!(typeof(needle[0]))) &&
isDefaultPred)))
{
if (haystack.length < needle.length) return false;
foreach (j; 0 .. needle.length)
{
if (!binaryFun!pred(needle[j], haystack[j]))
// not found
return false;
}
// found!
return true;
}
else
{
static if (hasLength!R1 && hasLength!R2)
{
if (haystack.length < needle.length) return false;
}
if (needle.empty) return true;
for (; !haystack.empty; haystack.popFront())
{
if (!binaryFun!pred(haystack.front, needle.front)) break;
needle.popFront();
if (needle.empty) return true;
}
return false;
}
}
/// Ditto
bool startsWith(alias pred = "a == b", R, E)
(R doesThisStart, E withThis)
if (isInputRange!R &&
is(typeof(binaryFun!pred(doesThisStart.front, withThis)) : bool))
{
return doesThisStart.empty
? false
: binaryFun!pred(doesThisStart.front, withThis);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
//foreach (S; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
foreach (S; TypeTuple!(char[], wstring))
{
assert(!startsWith(to!S("abc"), 'c'));
assert(startsWith(to!S("abc"), 'a', 'c') == 1);
assert(!startsWith(to!S("abc"), 'x', 'n', 'b'));
assert(startsWith(to!S("abc"), 'x', 'n', 'a') == 3);
assert(startsWith(to!S("\uFF28abc"), 'a', '\uFF28', 'c') == 2);
//foreach (T; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
foreach (T; TypeTuple!(dchar[], string))
{
assert(startsWith(to!S("abc"), to!T("")));
assert(startsWith(to!S("ab"), to!T("a")));
assert(startsWith(to!S("abc"), to!T("a")));
assert(!startsWith(to!S("abc"), to!T("b")));
assert(!startsWith(to!S("abc"), to!T("b"), "bc", "abcd", "xyz"));
assert(startsWith(to!S("abc"), to!T("ab"), 'a') == 2);
assert(startsWith(to!S("abc"), to!T("a"), "b") == 1);
assert(startsWith(to!S("abc"), to!T("b"), "a") == 2);
assert(startsWith(to!S("abc"), to!T("a"), 'a') == 1);
assert(startsWith(to!S("abc"), 'a', to!T("a")) == 1);
assert(startsWith(to!S("abc"), to!T("x"), "a", "b") == 2);
assert(startsWith(to!S("abc"), to!T("x"), "aa", "ab") == 3);
assert(startsWith(to!S("abc"), to!T("x"), "aaa", "sab") == 0);
assert(startsWith(to!S("abc"), 'a'));
assert(!startsWith(to!S("abc"), to!T("sab")));
assert(startsWith(to!S("abc"), 'x', to!T("aaa"), 'a', "sab") == 3);
assert(startsWith(to!S("\uFF28el\uFF4co"), to!T("\uFF28el")));
assert(startsWith(to!S("\uFF28el\uFF4co"), to!T("Hel"), to!T("\uFF28el")) == 2);
}
}
assert(startsWith([0, 1, 2, 3, 4, 5], cast(int[])null));
assert(!startsWith([0, 1, 2, 3, 4, 5], 5));
assert(!startsWith([0, 1, 2, 3, 4, 5], 1));
assert(startsWith([0, 1, 2, 3, 4, 5], 0));
assert(startsWith([0, 1, 2, 3, 4, 5], 5, 0, 1) == 2);
assert(startsWith([0, 1, 2, 3, 4, 5], [0]));
assert(startsWith([0, 1, 2, 3, 4, 5], [0, 1]));
assert(startsWith([0, 1, 2, 3, 4, 5], [0, 1], 7) == 1);
assert(!startsWith([0, 1, 2, 3, 4, 5], [0, 1, 7]));
assert(startsWith([0, 1, 2, 3, 4, 5], [0, 1, 7], [0, 1, 2]) == 2);
assert(!startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), 1));
assert(startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), 0));
assert(startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), [0]));
assert(startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), [0, 1]));
assert(startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), [0, 1], 7) == 1);
assert(!startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), [0, 1, 7]));
assert(startsWith(filter!"true"([0, 1, 2, 3, 4, 5]), [0, 1, 7], [0, 1, 2]) == 2);
assert(startsWith([0, 1, 2, 3, 4, 5], filter!"true"([0, 1])));
assert(startsWith([0, 1, 2, 3, 4, 5], filter!"true"([0, 1]), 7) == 1);
assert(!startsWith([0, 1, 2, 3, 4, 5], filter!"true"([0, 1, 7])));
assert(startsWith([0, 1, 2, 3, 4, 5], [0, 1, 7], filter!"true"([0, 1, 2])) == 2);
}
/**
If $(D startsWith(r1, r2)), consume the corresponding elements off $(D
r1) and return $(D true). Otherwise, leave $(D r1) unchanged and
return $(D false).
*/
bool skipOver(alias pred = "a == b", R1, R2)(ref R1 r1, R2 r2)
if (is(typeof(binaryFun!pred(r1.front, r2.front))))
{
auto r = r1.save;
while (!r2.empty && !r.empty && binaryFun!pred(r.front, r2.front))
{
r.popFront();
r2.popFront();
}
return r2.empty ? (r1 = r, true) : false;
}
unittest
{
//scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto s1 = "Hello world";
assert(!skipOver(s1, "Ha"));
assert(s1 == "Hello world");
assert(skipOver(s1, "Hell") && s1 == "o world");
}
/**
Checks whether a range starts with an element, and if so, consume that
element off $(D r) and return $(D true). Otherwise, leave $(D r)
unchanged and return $(D false).
*/
bool skipOver(alias pred = "a == b", R, E)(ref R r, E e)
if (is(typeof(binaryFun!pred(r.front, e))))
{
return binaryFun!pred(r.front, e)
? (r.popFront(), true)
: false;
}
unittest {
auto s1 = "Hello world";
assert(!skipOver(s1, "Ha"));
assert(s1 == "Hello world");
assert(skipOver(s1, "Hell") && s1 == "o world");
}
/* (Not yet documented.)
Consume all elements from $(D r) that are equal to one of the elements
$(D es).
*/
void skipAll(alias pred = "a == b", R, Es...)(ref R r, Es es)
//if (is(typeof(binaryFun!pred(r1.front, es[0]))))
{
loop:
for (; !r.empty; r.popFront())
{
foreach (i, E; Es)
{
if (binaryFun!pred(r.front, es[i]))
{
continue loop;
}
}
break;
}
}
unittest
{
//scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto s1 = "Hello world";
skipAll(s1, 'H', 'e');
assert(s1 == "llo world");
}
/**
The reciprocal of $(D startsWith).
Example:
----
assert(endsWith("abc", ""));
assert(!endsWith("abc", "b"));
assert(endsWith("abc", "a", 'c') == 2);
assert(endsWith("abc", "c", "a") == 1);
assert(endsWith("abc", "c", "c") == 1);
assert(endsWith("abc", "bc", "c") == 2);
assert(endsWith("abc", "x", "c", "b") == 2);
assert(endsWith("abc", "x", "aa", "bc") == 3);
assert(endsWith("abc", "x", "aaa", "sab") == 0);
assert(endsWith("abc", "x", "aaa", 'c', "sab") == 3);
----
*/
uint endsWith(alias pred = "a == b", Range, Ranges...)
(Range doesThisEnd, Ranges withOneOfThese)
if (isInputRange!Range && Ranges.length > 1 &&
is(typeof(.endsWith!pred(doesThisEnd, withOneOfThese[0])) : bool) &&
is(typeof(.endsWith!pred(doesThisEnd, withOneOfThese[1 .. $])) : uint))
{
alias doesThisEnd haystack;
alias withOneOfThese needles;
// Make one pass looking for empty ranges
foreach (i, Unused; Ranges)
{
// Empty range matches everything
static if (!is(typeof(binaryFun!pred(haystack.back, needles[i])) : bool))
{
if (needles[i].empty) return i + 1;
}
}
for (; !haystack.empty; haystack.popBack())
{
foreach (i, Unused; Ranges)
{
static if (is(typeof(binaryFun!pred(haystack.back, needles[i])) : bool))
{
// Single-element
if (binaryFun!pred(haystack.back, needles[i]))
{
// found, but continue to account for one-element
// range matches (consider endsWith("ab", "b",
// 'b') should return 1, not 2).
continue;
}
}
else
{
if (binaryFun!pred(haystack.back, needles[i].back))
continue;
}
// This code executed on failure to match
// Out with this guy, check for the others
uint result = endsWith!pred(haystack, needles[0 .. i], needles[i + 1 .. $]);
if (result > i) ++result;
return result;
}
// If execution reaches this point, then the back matches for all
// needles ranges. What we need to do now is to lop off the back of
// all ranges involved and recurse.
foreach (i, Unused; Ranges)
{
static if (is(typeof(binaryFun!pred(haystack.back, needles[i])) : bool))
{
// Test has passed in the previous loop
return i + 1;
}
else
{
needles[i].popBack();
if (needles[i].empty) return i + 1;
}
}
}
return 0;
}
/// Ditto
bool endsWith(alias pred = "a == b", R1, R2)
(R1 doesThisEnd, R2 withThis)
if (isInputRange!R1 &&
isInputRange!R2 &&
is(typeof(binaryFun!pred(doesThisEnd.back, withThis.back)) : bool))
{
alias doesThisEnd haystack;
alias withThis needle;
static if(is(typeof(pred) : string))
enum isDefaultPred = pred == "a == b";
else
enum isDefaultPred = false;
// Special case for two arrays
static if (isArray!R1 && isArray!R2 &&
((!isSomeString!R1 && !isSomeString!R2) ||
(isSomeString!R1 && isSomeString!R2 &&
is(Unqual!(typeof(haystack[0])) == Unqual!(typeof(needle[0]))) &&
isDefaultPred)))
{
if (haystack.length < needle.length) return false;
immutable diff = haystack.length - needle.length;
foreach (j; 0 .. needle.length)
{
if (!binaryFun!(pred)(needle[j], haystack[j + diff]))
// not found
return false;
}
// found!
return true;
}
else
{
static if (hasLength!R1 && hasLength!R2)
{
if (haystack.length < needle.length) return false;
}
if (needle.empty) return true;
for (; !haystack.empty; haystack.popBack())
{
if (!binaryFun!pred(haystack.back, needle.back)) break;
needle.popBack();
if (needle.empty) return true;
}
return false;
}
}
/// Ditto
bool endsWith(alias pred = "a == b", R, E)
(R doesThisEnd, E withThis)
if (isInputRange!R &&
is(typeof(binaryFun!pred(doesThisEnd.back, withThis)) : bool))
{
return doesThisEnd.empty
? false
: binaryFun!pred(doesThisEnd.back, withThis);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
//This is because we need to run some tests on ranges which _aren't_ arrays,
//and as far as I can tell, all of the functions which would wrap an array
//in a range (such as filter) don't return bidirectional ranges, so I'm
//creating one here.
auto static wrap(R)(R r)
if (isBidirectionalRange!R)
{
static struct Result
{
@property auto ref front() {return _range.front;}
@property auto ref back() {return _range.back;}
@property bool empty() {return _range.empty;}
void popFront() {_range.popFront();}
void popBack() {_range.popBack();}
R _range;
}
return Result(r);
}
//foreach (S; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
foreach (S; TypeTuple!(char[], wstring))
{
assert(!endsWith(to!S("abc"), 'a'));
assert(endsWith(to!S("abc"), 'a', 'c') == 2);
assert(!endsWith(to!S("abc"), 'x', 'n', 'b'));
assert(endsWith(to!S("abc"), 'x', 'n', 'c') == 3);
assert(endsWith(to!S("abc\uFF28"), 'a', '\uFF28', 'c') == 2);
//foreach (T; TypeTuple!(char[], wchar[], dchar[], string, wstring, dstring))
foreach (T; TypeTuple!(dchar[], string))
{
assert(endsWith(to!S("abc"), to!T("")));
assert(!endsWith(to!S("abc"), to!T("a")));
assert(!endsWith(to!S("abc"), to!T("b")));
assert(endsWith(to!S("abc"), to!T("bc"), 'c') == 2);
assert(endsWith(to!S("abc"), to!T("a"), "c") == 2);
assert(endsWith(to!S("abc"), to!T("c"), "a") == 1);
assert(endsWith(to!S("abc"), to!T("c"), "c") == 1);
assert(endsWith(to!S("abc"), to!T("x"), 'c', "b") == 2);
assert(endsWith(to!S("abc"), 'x', to!T("aa"), "bc") == 3);
assert(endsWith(to!S("abc"), to!T("x"), "aaa", "sab") == 0);
assert(endsWith(to!S("abc"), to!T("x"), "aaa", "c", "sab") == 3);
assert(endsWith(to!S("\uFF28el\uFF4co"), to!T("l\uFF4co")));
assert(endsWith(to!S("\uFF28el\uFF4co"), to!T("lo"), to!T("l\uFF4co")) == 2);
}
}
assert(endsWith([0, 1, 2, 3, 4, 5], cast(int[])null));
assert(!endsWith([0, 1, 2, 3, 4, 5], 0));
assert(!endsWith([0, 1, 2, 3, 4, 5], 4));
assert(endsWith([0, 1, 2, 3, 4, 5], 5));
assert(endsWith([0, 1, 2, 3, 4, 5], 0, 4, 5) == 3);
assert(endsWith([0, 1, 2, 3, 4, 5], [5]));
assert(endsWith([0, 1, 2, 3, 4, 5], [4, 5]));
assert(endsWith([0, 1, 2, 3, 4, 5], [4, 5], 7) == 1);
assert(!endsWith([0, 1, 2, 3, 4, 5], [2, 4, 5]));
assert(endsWith([0, 1, 2, 3, 4, 5], [2, 4, 5], [3, 4, 5]) == 2);
assert(!endsWith(wrap([0, 1, 2, 3, 4, 5]), 4));
assert(endsWith(wrap([0, 1, 2, 3, 4, 5]), 5));
assert(endsWith(wrap([0, 1, 2, 3, 4, 5]), [5]));
assert(endsWith(wrap([0, 1, 2, 3, 4, 5]), [4, 5]));
assert(endsWith(wrap([0, 1, 2, 3, 4, 5]), [4, 5], 7) == 1);
assert(!endsWith(wrap([0, 1, 2, 3, 4, 5]), [2, 4, 5]));
assert(endsWith(wrap([0, 1, 2, 3, 4, 5]), [2, 4, 5], [3, 4, 5]) == 2);
assert(endsWith([0, 1, 2, 3, 4, 5], wrap([4, 5])));
assert(endsWith([0, 1, 2, 3, 4, 5], wrap([4, 5]), 7) == 1);
assert(!endsWith([0, 1, 2, 3, 4, 5], wrap([2, 4, 5])));
assert(endsWith([0, 1, 2, 3, 4, 5], [2, 4, 5], wrap([3, 4, 5])) == 2);
}
// findAdjacent
/**
Advances $(D r) until it finds the first two adjacent elements $(D a),
$(D b) that satisfy $(D pred(a, b)). Performs $(BIGOH r.length)
evaluations of $(D pred). See also $(WEB
sgi.com/tech/stl/adjacent_find.html, STL's adjacent_find).
Example:
----
int[] a = [ 11, 10, 10, 9, 8, 8, 7, 8, 9 ];
auto r = findAdjacent(a);
assert(r == [ 10, 10, 9, 8, 8, 7, 8, 9 ]);
p = findAdjacent!("a < b")(a);
assert(p == [ 7, 8, 9 ]);
----
*/
Range findAdjacent(alias pred = "a == b", Range)(Range r)
if (isForwardRange!(Range))
{
auto ahead = r;
if (!ahead.empty)
{
for (ahead.popFront(); !ahead.empty; r.popFront(), ahead.popFront())
{
if (binaryFun!(pred)(r.front, ahead.front)) return r;
}
}
return ahead;
}
unittest
{
//scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 11, 10, 10, 9, 8, 8, 7, 8, 9 ];
auto p = findAdjacent(a);
assert(p == [10, 10, 9, 8, 8, 7, 8, 9 ]);
p = findAdjacent!("a < b")(a);
assert(p == [7, 8, 9]);
// empty
a = [];
p = findAdjacent(a);
assert(p.empty);
// not found
a = [ 1, 2, 3, 4, 5 ];
p = findAdjacent(a);
assert(p.empty);
p = findAdjacent!"a > b"(a);
assert(p.empty);
}
// findAmong
/**
Advances $(D seq) by calling $(D seq.popFront) until either $(D
find!(pred)(choices, seq.front)) is $(D true), or $(D seq) becomes
empty. Performs $(BIGOH seq.length * choices.length) evaluations of
$(D pred). See also $(WEB sgi.com/tech/stl/find_first_of.html, STL's
find_first_of).
Example:
----
int[] a = [ -1, 0, 1, 2, 3, 4, 5 ];
int[] b = [ 3, 1, 2 ];
assert(findAmong(a, b) == a[2 .. $]);
----
*/
Range1 findAmong(alias pred = "a == b", Range1, Range2)(
Range1 seq, Range2 choices)
if (isInputRange!Range1 && isForwardRange!Range2)
{
for (; !seq.empty && find!pred(choices, seq.front).empty; seq.popFront())
{
}
return seq;
}
unittest
{
//scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ -1, 0, 2, 1, 2, 3, 4, 5 ];
int[] b = [ 1, 2, 3 ];
assert(findAmong(a, b) == [2, 1, 2, 3, 4, 5 ]);
assert(findAmong(b, [ 4, 6, 7 ][]).empty);
assert(findAmong!("a==b")(a, b).length == a.length - 2);
assert(findAmong!("a==b")(b, [ 4, 6, 7 ][]).empty);
}
// count
/**
The first version counts the number of elements $(D x) in $(D r) for
which $(D pred(x, value)) is $(D true). $(D pred) defaults to
equality. Performs $(BIGOH r.length) evaluations of $(D pred).
The second version returns the number of times $(D needle) occurs in
$(D haystack). Throws an exception if $(D needle.empty), as the _count
of the empty range in any range would be infinite. Overlapped counts
are not considered, for example $(D count("aaa", "aa")) is $(D 1), not
$(D 2).
The third version counts the elements for which $(D pred(x)) is $(D
true). Performs $(BIGOH r.length) evaluations of $(D pred).
Example:
----
// count elements in range
int[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ];
assert(count(a, 2) == 3);
assert(count!("a > b")(a, 2) == 5);
// count range in range
assert(count("abcadfabf", "ab") == 2);
assert(count("ababab", "abab") == 1);
assert(count("ababab", "abx") == 0);
// count predicate in range
assert(count!("a > 1")(a) == 8);
----
*/
size_t count(alias pred = "a == b", Range, E)(Range r, E value)
if (isInputRange!Range && is(typeof(binaryFun!pred(r.front, value)) == bool))
{
bool pred2(ElementType!(Range) a) { return binaryFun!pred(a, value); }
return count!(pred2)(r);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ];
assert(count(a, 2) == 3, text(count(a, 2)));
assert(count!("a > b")(a, 2) == 5, text(count!("a > b")(a, 2)));
// check strings
assert(count("日本語") == 3);
assert(count("日本語"w) == 3);
assert(count("日本語"d) == 3);
assert(count!("a == '日'")("日本語") == 1);
assert(count!("a == '本'")("日本語"w) == 1);
assert(count!("a == '語'")("日本語"d) == 1);
}
unittest
{
debug(std_algorithm) printf("algorithm.count.unittest\n");
string s = "This is a fofofof list";
string sub = "fof";
assert(count(s, sub) == 2);
}
/// Ditto
size_t count(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)
if (isInputRange!R1 && isForwardRange!R2 && is(typeof(binaryFun!pred(haystack, needle)) == bool))
{
enforce(!needle.empty, "Cannot count occurrences of an empty range");
size_t result;
for (; findSkip!pred(haystack, needle); ++result)
{
}
return result;
}
unittest
{
assert(count("abcadfabf", "ab") == 2);
assert(count("ababab", "abab") == 1);
assert(count("ababab", "abx") == 0);
}
/// Ditto
size_t count(alias pred = "true", Range)(Range r) if (isInputRange!(Range))
{
size_t result;
for (; !r.empty; r.popFront())
{
if (unaryFun!pred(r.front)) ++result;
}
return result;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ];
assert(count!("a == 3")(a) == 2);
}
// balancedParens
/**
Checks whether $(D r) has "balanced parentheses", i.e. all instances
of $(D lPar) are closed by corresponding instances of $(D rPar). The
parameter $(D maxNestingLevel) controls the nesting level allowed. The
most common uses are the default or $(D 0). In the latter case, no
nesting is allowed.
Example:
----
auto s = "1 + (2 * (3 + 1 / 2)";
assert(!balancedParens(s, '(', ')'));
s = "1 + (2 * (3 + 1) / 2)";
assert(balancedParens(s, '(', ')'));
s = "1 + (2 * (3 + 1) / 2)";
assert(!balancedParens(s, '(', ')', 1));
s = "1 + (2 * 3 + 1) / (2 - 5)";
assert(balancedParens(s, '(', ')', 1));
----
*/
bool balancedParens(Range, E)(Range r, E lPar, E rPar,
size_t maxNestingLevel = size_t.max)
if (isInputRange!(Range) && is(typeof(r.front == lPar)))
{
size_t count;
for (; !r.empty; r.popFront())
{
if (r.front == lPar)
{
if (count > maxNestingLevel) return false;
++count;
}
else if (r.front == rPar)
{
if (!count) return false;
--count;
}
}
return count == 0;
}
unittest
{
auto s = "1 + (2 * (3 + 1 / 2)";
assert(!balancedParens(s, '(', ')'));
s = "1 + (2 * (3 + 1) / 2)";
assert(balancedParens(s, '(', ')'));
s = "1 + (2 * (3 + 1) / 2)";
assert(!balancedParens(s, '(', ')', 0));
s = "1 + (2 * 3 + 1) / (2 - 5)";
assert(balancedParens(s, '(', ')', 0));
}
// equal
/**
Returns $(D true) if and only if the two ranges compare equal element
for element, according to binary predicate $(D pred). The ranges may
have different element types, as long as $(D pred(a, b)) evaluates to
$(D bool) for $(D a) in $(D r1) and $(D b) in $(D r2). Performs
$(BIGOH min(r1.length, r2.length)) evaluations of $(D pred). See also
$(WEB sgi.com/tech/stl/_equal.html, STL's _equal).
Example:
----
int[] a = [ 1, 2, 4, 3 ];
assert(!equal(a, a[1..$]));
assert(equal(a, a));
// different types
double[] b = [ 1., 2, 4, 3];
assert(!equal(a, b[1..$]));
assert(equal(a, b));
// predicated: ensure that two vectors are approximately equal
double[] c = [ 1.005, 2, 4, 3];
assert(equal!(approxEqual)(b, c));
----
*/
bool equal(alias pred = "a == b", Range1, Range2)(Range1 r1, Range2 r2)
if (isInputRange!(Range1) && isInputRange!(Range2)
&& is(typeof(binaryFun!pred(r1.front, r2.front))))
{
for (; !r1.empty; r1.popFront(), r2.popFront())
{
if (r2.empty) return false;
if (!binaryFun!(pred)(r1.front, r2.front)) return false;
}
return r2.empty;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 4, 3];
assert(!equal(a, a[1..$]));
assert(equal(a, a));
// test with different types
double[] b = [ 1., 2, 4, 3];
assert(!equal(a, b[1..$]));
assert(equal(a, b));
// predicated
double[] c = [ 1.005, 2, 4, 3];
assert(equal!(approxEqual)(b, c));
// utf-8 strings
assert(equal("æøå", "æøå"));
}
// cmp
/**********************************
Performs three-way lexicographical comparison on two input ranges
according to predicate $(D pred). Iterating $(D r1) and $(D r2) in
lockstep, $(D cmp) compares each element $(D e1) of $(D r1) with the
corresponding element $(D e2) in $(D r2). If $(D binaryFun!pred(e1,
e2)), $(D cmp) returns a negative value. If $(D binaryFun!pred(e2,
e1)), $(D cmp) returns a positive value. If one of the ranges has been
finished, $(D cmp) returns a negative value if $(D r1) has fewer
elements than $(D r2), a positive value if $(D r1) has more elements
than $(D r2), and $(D 0) if the ranges have the same number of
elements.
If the ranges are strings, $(D cmp) performs UTF decoding
appropriately and compares the ranges one code point at a time.
*/
int cmp(alias pred = "a < b", R1, R2)(R1 r1, R2 r2)
if (isInputRange!R1 && isInputRange!R2 && !(isSomeString!R1 && isSomeString!R2))
{
for (;; r1.popFront(), r2.popFront())
{
if (r1.empty) return -cast(int)!r2.empty;
if (r2.empty) return !r1.empty;
auto a = r1.front, b = r2.front;
if (binaryFun!pred(a, b)) return -1;
if (binaryFun!pred(b, a)) return 1;
}
}
// Specialization for strings (for speed purposes)
int cmp(alias pred = "a < b", R1, R2)(R1 r1, R2 r2) if (isSomeString!R1 && isSomeString!R2)
{
static if(is(typeof(pred) : string))
enum isLessThan = pred == "a < b";
else
enum isLessThan = false;
// For speed only
static int threeWay(size_t a, size_t b)
{
static if (size_t.sizeof == int.sizeof && isLessThan)
return a - b;
else
return binaryFun!pred(b, a) ? 1 : binaryFun!pred(a, b) ? -1 : 0;
}
// For speed only
// @@@BUG@@@ overloading should be allowed for nested functions
static int threeWayInt(int a, int b)
{
static if (isLessThan)
return a - b;
else
return binaryFun!pred(b, a) ? 1 : binaryFun!pred(a, b) ? -1 : 0;
}
static if (typeof(r1[0]).sizeof == typeof(r2[0]).sizeof && isLessThan)
{
static if (typeof(r1[0]).sizeof == 1)
{
immutable len = min(r1.length, r2.length);
immutable result = std.c.string.memcmp(r1.ptr, r2.ptr, len);
if (result) return result;
}
else
{
auto p1 = r1.ptr, p2 = r2.ptr,
pEnd = p1 + min(r1.length, r2.length);
for (; p1 != pEnd; ++p1, ++p2)
{
if (*p1 != *p2) return threeWayInt(cast(int) *p1, cast(int) *p2);
}
}
return threeWay(r1.length, r2.length);
}
else
{
for (size_t i1, i2;;)
{
if (i1 == r1.length) return threeWay(i2, r2.length);
if (i2 == r2.length) return threeWay(r1.length, i1);
immutable c1 = std.utf.decode(r1, i1),
c2 = std.utf.decode(r2, i2);
if (c1 != c2) return threeWayInt(cast(int) c1, cast(int) c2);
}
}
}
unittest
{
int result;
debug(string) printf("string.cmp.unittest\n");
result = cmp("abc", "abc");
assert(result == 0);
// result = cmp(null, null);
// assert(result == 0);
result = cmp("", "");
assert(result == 0);
result = cmp("abc", "abcd");
assert(result < 0);
result = cmp("abcd", "abc");
assert(result > 0);
result = cmp("abc"d, "abd");
assert(result < 0);
result = cmp("bbc", "abc"w);
assert(result > 0);
result = cmp("aaa", "aaaa"d);
assert(result < 0);
result = cmp("aaaa", "aaa"d);
assert(result > 0);
result = cmp("aaa", "aaa"d);
assert(result == 0);
result = cmp(cast(int[])[], cast(int[])[]);
assert(result == 0);
result = cmp([1, 2, 3], [1, 2, 3]);
assert(result == 0);
result = cmp([1, 3, 2], [1, 2, 3]);
assert(result > 0);
result = cmp([1, 2, 3], [1L, 2, 3, 4]);
assert(result < 0);
result = cmp([1L, 2, 3], [1, 2]);
assert(result > 0);
}
// MinType
template MinType(T...)
{
static assert(T.length >= 2);
static if (T.length == 2)
{
static if (!is(typeof(T[0].min)))
alias CommonType!(T[0 .. 2]) MinType;
else static if (mostNegative!(T[1]) < mostNegative!(T[0]))
alias T[1] MinType;
else static if (mostNegative!(T[1]) > mostNegative!(T[0]))
alias T[0] MinType;
else static if (T[1].max < T[0].max)
alias T[1] MinType;
else
alias T[0] MinType;
}
else
{
alias MinType!(MinType!(T[0 .. 2]), T[2 .. $]) MinType;
}
}
// min
/**
Returns the minimum of the passed-in values. The type of the result is
computed by using $(XREF traits, CommonType).
*/
MinType!(T1, T2, T) min(T1, T2, T...)(T1 a, T2 b, T xs)
{
static if (T.length == 0)
{
static if (isIntegral!(T1) && isIntegral!(T2)
&& (mostNegative!(T1) < 0) != (mostNegative!(T2) < 0))
static if (mostNegative!(T1) < 0)
immutable chooseB = b < a && a > 0;
else
immutable chooseB = b < a || b < 0;
else
immutable chooseB = b < a;
return cast(typeof(return)) (chooseB ? b : a);
}
else
{
return min(min(a, b), xs);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int a = 5;
short b = 6;
double c = 2;
auto d = min(a, b);
assert(is(typeof(d) == int));
assert(d == 5);
auto e = min(a, b, c);
assert(is(typeof(e) == double));
assert(e == 2);
// mixed signedness test
a = -10;
uint f = 10;
static assert(is(typeof(min(a, f)) == int));
assert(min(a, f) == -10);
}
// MaxType
template MaxType(T...)
{
static assert(T.length >= 2);
static if (T.length == 2)
{
static if (!is(typeof(T[0].min)))
alias CommonType!(T[0 .. 2]) MaxType;
else static if (T[1].max > T[0].max)
alias T[1] MaxType;
else
alias T[0] MaxType;
}
else
{
alias MaxType!(MaxType!(T[0], T[1]), T[2 .. $]) MaxType;
}
}
// max
/**
Returns the maximum of the passed-in values. The type of the result is
computed by using $(XREF traits, CommonType).
Example:
----
int a = 5;
short b = 6;
double c = 2;
auto d = max(a, b);
assert(is(typeof(d) == int));
assert(d == 6);
auto e = min(a, b, c);
assert(is(typeof(e) == double));
assert(e == 2);
----
*/
MaxType!(T1, T2, T) max(T1, T2, T...)(T1 a, T2 b, T xs)
{
static if (T.length == 0)
{
static if (isIntegral!(T1) && isIntegral!(T2)
&& (mostNegative!(T1) < 0) != (mostNegative!(T2) < 0))
static if (mostNegative!(T1) < 0)
immutable chooseB = b > a || a < 0;
else
immutable chooseB = b > a && b > 0;
else
immutable chooseB = b > a;
return cast(typeof(return)) (chooseB ? b : a);
}
else
{
return max(max(a, b), xs);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int a = 5;
short b = 6;
double c = 2;
auto d = max(a, b);
assert(is(typeof(d) == int));
assert(d == 6);
auto e = max(a, b, c);
assert(is(typeof(e) == double));
assert(e == 6);
// mixed sign
a = -5;
uint f = 5;
static assert(is(typeof(max(a, f)) == uint));
assert(max(a, f) == 5);
}
/**
Returns the minimum element of a range together with the number of
occurrences. The function can actually be used for counting the
maximum or any other ordering predicate (that's why $(D maxCount) is
not provided).
Example:
----
int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ];
// Minimum is 1 and occurs 3 times
assert(minCount(a) == tuple(1, 3));
// Maximum is 4 and occurs 2 times
assert(minCount!("a > b")(a) == tuple(4, 2));
----
*/
Tuple!(ElementType!(Range), size_t)
minCount(alias pred = "a < b", Range)(Range range)
{
if (range.empty) return typeof(return)();
auto p = &(range.front());
size_t occurrences = 1;
for (range.popFront(); !range.empty; range.popFront())
{
if (binaryFun!(pred)(*p, range.front)) continue;
if (binaryFun!(pred)(range.front, *p))
{
// change the min
p = &(range.front());
occurrences = 1;
}
else
{
++occurrences;
}
}
return tuple(*p, occurrences);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ];
assert(minCount(a) == tuple(1, 3));
assert(minCount!("a > b")(a) == tuple(4, 2));
int[][] b = [ [4], [2, 4], [4], [4] ];
auto c = minCount!("a[0] < b[0]")(b);
assert(c == tuple([2, 4], 1), text(c[0]));
}
// minPos
/**
Returns the position of the minimum element of forward range $(D
range), i.e. a subrange of $(D range) starting at the position of its
smallest element and with the same ending as $(D range). The function
can actually be used for counting the maximum or any other ordering
predicate (that's why $(D maxPos) is not provided).
Example:
----
int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ];
// Minimum is 1 and first occurs in position 3
assert(minPos(a) == [ 1, 2, 4, 1, 1, 2 ]);
// Maximum is 4 and first occurs in position 2
assert(minPos!("a > b")(a) == [ 4, 1, 2, 4, 1, 1, 2 ]);
----
*/
Range minPos(alias pred = "a < b", Range)(Range range)
{
if (range.empty) return range;
auto result = range;
for (range.popFront(); !range.empty; range.popFront())
{
if (binaryFun!(pred)(result.front, range.front)
|| !binaryFun!(pred)(range.front, result.front)) continue;
// change the min
result = range;
}
return result;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 2, 3, 4, 1, 2, 4, 1, 1, 2 ];
// Minimum is 1 and first occurs in position 3
assert(minPos(a) == [ 1, 2, 4, 1, 1, 2 ]);
// Maximum is 4 and first occurs in position 5
assert(minPos!("a > b")(a) == [ 4, 1, 2, 4, 1, 1, 2 ]);
}
// mismatch
/**
Sequentially compares elements in $(D r1) and $(D r2) in lockstep, and
stops at the first mismatch (according to $(D pred), by default
equality). Returns a tuple with the reduced ranges that start with the
two mismatched values. Performs $(BIGOH min(r1.length, r2.length))
evaluations of $(D pred). See also $(WEB
sgi.com/tech/stl/_mismatch.html, STL's _mismatch).
Example:
----
int[] x = [ 1, 5, 2, 7, 4, 3 ];
double[] y = [ 1., 5, 2, 7.3, 4, 8 ];
auto m = mismatch(x, y);
assert(m[0] == x[3 .. $]);
assert(m[1] == y[3 .. $]);
----
*/
Tuple!(Range1, Range2)
mismatch(alias pred = "a == b", Range1, Range2)(Range1 r1, Range2 r2)
if (isInputRange!(Range1) && isInputRange!(Range2))
{
for (; !r1.empty && !r2.empty; r1.popFront(), r2.popFront())
{
if (!binaryFun!(pred)(r1.front, r2.front)) break;
}
return tuple(r1, r2);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
// doc example
int[] x = [ 1, 5, 2, 7, 4, 3 ];
double[] y = [ 1., 5, 2, 7.3, 4, 8 ];
auto m = mismatch(x, y);
assert(m[0] == [ 7, 4, 3 ]);
assert(m[1] == [ 7.3, 4, 8 ]);
int[] a = [ 1, 2, 3 ];
int[] b = [ 1, 2, 4, 5 ];
auto mm = mismatch(a, b);
assert(mm[0] == [3]);
assert(mm[1] == [4, 5]);
}
// levenshteinDistance
/**
Encodes $(WEB realityinteractive.com/rgrzywinski/archives/000249.html,
edit operations) necessary to transform one sequence into
another. Given sequences $(D s) (source) and $(D t) (target), a
sequence of $(D EditOp) encodes the steps that need to be taken to
convert $(D s) into $(D t). For example, if $(D s = "cat") and $(D
"cars"), the minimal sequence that transforms $(D s) into $(D t) is:
skip two characters, replace 't' with 'r', and insert an 's'. Working
with edit operations is useful in applications such as spell-checkers
(to find the closest word to a given misspelled word), approximate
searches, diff-style programs that compute the difference between
files, efficient encoding of patches, DNA sequence analysis, and
plagiarism detection.
*/
enum EditOp : char
{
/** Current items are equal; no editing is necessary. */
none = 'n',
/** Substitute current item in target with current item in source. */
substitute = 's',
/** Insert current item from the source into the target. */
insert = 'i',
/** Remove current item from the target. */
remove = 'r'
}
struct Levenshtein(Range, alias equals, CostType = size_t)
{
void deletionIncrement(CostType n)
{
_deletionIncrement = n;
InitMatrix();
}
void insertionIncrement(CostType n)
{
_insertionIncrement = n;
InitMatrix();
}
CostType distance(Range s, Range t)
{
auto slen = walkLength(s), tlen = walkLength(t);
AllocMatrix(slen + 1, tlen + 1);
foreach (i; 1 .. rows)
{
auto sfront = s.front;
s.popFront();
auto tt = t;
foreach (j; 1 .. cols)
{
auto cSub = _matrix[i - 1][j - 1]
+ (equals(sfront, tt.front) ? 0 : _substitutionIncrement);
tt.popFront();
auto cIns = _matrix[i][j - 1] + _insertionIncrement;
auto cDel = _matrix[i - 1][j] + _deletionIncrement;
switch (min_index(cSub, cIns, cDel)) {
case 0:
_matrix[i][j] = cSub;
break;
case 1:
_matrix[i][j] = cIns;
break;
default:
_matrix[i][j] = cDel;
break;
}
}
}
return _matrix[slen][tlen];
}
EditOp[] path(Range s, Range t)
{
distance(s, t);
return path();
}
EditOp[] path()
{
EditOp[] result;
size_t i = rows - 1, j = cols - 1;
// restore the path
while (i || j) {
auto cIns = j == 0 ? CostType.max : _matrix[i][j - 1];
auto cDel = i == 0 ? CostType.max : _matrix[i - 1][j];
auto cSub = i == 0 || j == 0
? CostType.max
: _matrix[i - 1][j - 1];
switch (min_index(cSub, cIns, cDel)) {
case 0:
result ~= _matrix[i - 1][j - 1] == _matrix[i][j]
? EditOp.none
: EditOp.substitute;
--i;
--j;
break;
case 1:
result ~= EditOp.insert;
--j;
break;
default:
result ~= EditOp.remove;
--i;
break;
}
}
reverse(result);
return result;
}
private:
CostType _deletionIncrement = 1,
_insertionIncrement = 1,
_substitutionIncrement = 1;
CostType[][] _matrix;
size_t rows, cols;
void AllocMatrix(size_t r, size_t c) {
rows = r;
cols = c;
if (!_matrix || _matrix.length < r || _matrix[0].length < c) {
delete _matrix;
_matrix = new CostType[][](r, c);
InitMatrix();
}
}
void InitMatrix() {
foreach (i, row; _matrix) {
row[0] = i * _deletionIncrement;
}
if (!_matrix) return;
for (auto i = 0u; i != _matrix[0].length; ++i) {
_matrix[0][i] = i * _insertionIncrement;
}
}
static uint min_index(CostType i0, CostType i1, CostType i2)
{
if (i0 <= i1)
{
return i0 <= i2 ? 0 : 2;
}
else
{
return i1 <= i2 ? 1 : 2;
}
}
}
/**
Returns the $(WEB wikipedia.org/wiki/Levenshtein_distance, Levenshtein
distance) between $(D s) and $(D t). The Levenshtein distance computes
the minimal amount of edit operations necessary to transform $(D s)
into $(D t). Performs $(BIGOH s.length * t.length) evaluations of $(D
equals) and occupies $(BIGOH s.length * t.length) storage.
Example:
----
assert(levenshteinDistance("cat", "rat") == 1);
assert(levenshteinDistance("parks", "spark") == 2);
assert(levenshteinDistance("kitten", "sitting") == 3);
// ignore case
assert(levenshteinDistance!("std.uni.toUpper(a) == std.uni.toUpper(b)")
("parks", "SPARK") == 2);
----
*/
size_t levenshteinDistance(alias equals = "a == b", Range1, Range2)
(Range1 s, Range2 t)
if (isForwardRange!(Range1) && isForwardRange!(Range2))
{
Levenshtein!(Range1, binaryFun!(equals), size_t) lev;
return lev.distance(s, t);
}
//Verify Examples.
unittest
{
assert(levenshteinDistance("cat", "rat") == 1);
assert(levenshteinDistance("parks", "spark") == 2);
assert(levenshteinDistance("kitten", "sitting") == 3);
assert(levenshteinDistance!("std.uni.toUpper(a) == std.uni.toUpper(b)")
("parks", "SPARK") == 2);
}
/**
Returns the Levenshtein distance and the edit path between $(D s) and
$(D t).
Example:
---
string a = "Saturday", b = "Sunday";
auto p = levenshteinDistanceAndPath(a, b);
assert(p[0] == 3);
assert(equal(p[1], "nrrnsnnn"));
---
*/
Tuple!(size_t, EditOp[])
levenshteinDistanceAndPath(alias equals = "a == b", Range1, Range2)
(Range1 s, Range2 t)
if (isForwardRange!(Range1) && isForwardRange!(Range2))
{
Levenshtein!(Range1, binaryFun!(equals)) lev;
auto d = lev.distance(s, t);
return tuple(d, lev.path());
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
assert(levenshteinDistance("a", "a") == 0);
assert(levenshteinDistance("a", "b") == 1);
assert(levenshteinDistance("aa", "ab") == 1);
assert(levenshteinDistance("aa", "abc") == 2);
assert(levenshteinDistance("Saturday", "Sunday") == 3);
assert(levenshteinDistance("kitten", "sitting") == 3);
//lev.deletionIncrement = 2;
//lev.insertionIncrement = 100;
string a = "Saturday", b = "Sunday";
auto p = levenshteinDistanceAndPath(a, b);
assert(cast(string) p[1] == "nrrnsnnn");
}
// copy
/**
Copies the content of $(D source) into $(D target) and returns the
remaining (unfilled) part of $(D target). See also $(WEB
sgi.com/tech/stl/_copy.html, STL's _copy). If a behavior similar to
$(WEB sgi.com/tech/stl/copy_backward.html, STL's copy_backward) is
needed, use $(D copy(retro(source), retro(target))). See also $(XREF
range, retro).
Example:
----
int[] a = [ 1, 5 ];
int[] b = [ 9, 8 ];
int[] c = new int[a.length + b.length + 10];
auto d = copy(b, copy(a, c));
assert(c[0 .. a.length + b.length] == a ~ b);
assert(d.length == 10);
----
As long as the target range elements support assignment from source
range elements, different types of ranges are accepted.
Example:
----
float[] a = [ 1.0f, 5 ];
double[] b = new double[a.length];
auto d = copy(a, b);
----
To copy at most $(D n) elements from range $(D a) to range $(D b), you
may want to use $(D copy(take(a, n), b)). To copy those elements from
range $(D a) that satisfy predicate $(D pred) to range $(D b), you may
want to use $(D copy(filter!(pred)(a), b)).
Example:
----
int[] a = [ 1, 5, 8, 9, 10, 1, 2, 0 ];
auto b = new int[a.length];
auto c = copy(filter!("(a & 1) == 1")(a), b);
assert(b[0 .. $ - c.length] == [ 1, 5, 9, 1 ]);
----
*/
Range2 copy(Range1, Range2)(Range1 source, Range2 target)
if (isInputRange!Range1 && isOutputRange!(Range2, ElementType!Range1))
{
static Range2 genericImpl(Range1 source, Range2 target)
{
for (; !source.empty; source.popFront())
{
put(target, source.front);
}
return target;
}
static if(isArray!Range1 && isArray!Range2 &&
is(Unqual!(typeof(source[0])) == Unqual!(typeof(target[0]))))
{
immutable overlaps =
(source.ptr >= target.ptr &&
source.ptr < target.ptr + target.length) ||
(target.ptr >= source.ptr &&
target.ptr < source.ptr + source.length);
if(overlaps)
{
return genericImpl(source, target);
}
else
{
// Array specialization. This uses optimized memory copying
// routines under the hood and is about 10-20x faster than the
// generic implementation.
enforce(target.length >= source.length,
"Cannot copy a source array into a smaller target array.");
target[0..source.length] = source;
return target[source.length..$];
}
}
else
{
return genericImpl(source, target);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
{
int[] a = [ 1, 5 ];
int[] b = [ 9, 8 ];
int[] c = new int[a.length + b.length + 10];
auto d = copy(b, copy(a, c));
assert(c[0 .. a.length + b.length] == a ~ b);
assert(d.length == 10);
}
{
int[] a = [ 1, 5 ];
int[] b = [ 9, 8 ];
auto e = copy(filter!("a > 1")(a), b);
assert(b[0] == 5 && e.length == 1);
}
{
int[] a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
copy(a[5..10], a[4..9]);
assert(a[4..9] == [6, 7, 8, 9, 10]);
}
}
// swapRanges
/**
Swaps all elements of $(D r1) with successive elements in $(D r2).
Returns a tuple containing the remainder portions of $(D r1) and $(D
r2) that were not swapped (one of them will be empty). The ranges may
be of different types but must have the same element type and support
swapping.
Example:
----
int[] a = [ 100, 101, 102, 103 ];
int[] b = [ 0, 1, 2, 3 ];
auto c = swapRanges(a[1 .. 3], b[2 .. 4]);
assert(c[0].empty && c[1].empty);
assert(a == [ 100, 2, 3, 103 ]);
assert(b == [ 0, 1, 101, 102 ]);
----
*/
Tuple!(Range1, Range2)
swapRanges(Range1, Range2)(Range1 r1, Range2 r2)
if (isInputRange!(Range1) && isInputRange!(Range2)
&& hasSwappableElements!(Range1) && hasSwappableElements!(Range2)
&& is(ElementType!(Range1) == ElementType!(Range2)))
{
for (; !r1.empty && !r2.empty; r1.popFront(), r2.popFront())
{
swap(r1.front, r2.front);
}
return tuple(r1, r2);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 100, 101, 102, 103 ];
int[] b = [ 0, 1, 2, 3 ];
auto c = swapRanges(a[1 .. 3], b[2 .. 4]);
assert(c[0].empty && c[1].empty);
assert(a == [ 100, 2, 3, 103 ]);
assert(b == [ 0, 1, 101, 102 ]);
}
// reverse
/**
Reverses $(D r) in-place. Performs $(D r.length / 2) evaluations of $(D
swap). See also $(WEB sgi.com/tech/stl/_reverse.html, STL's _reverse).
Example:
----
int[] arr = [ 1, 2, 3 ];
reverse(arr);
assert(arr == [ 3, 2, 1 ]);
----
*/
void reverse(Range)(Range r)
if (isBidirectionalRange!(Range) && hasSwappableElements!(Range))
{
while (!r.empty)
{
swap(r.front, r.back);
r.popFront();
if (r.empty) break;
r.popBack();
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] range = null;
reverse(range);
range = [ 1 ];
reverse(range);
assert(range == [1]);
range = [1, 2];
reverse(range);
assert(range == [2, 1]);
range = [1, 2, 3];
reverse(range);
assert(range == [3, 2, 1]);
}
/**
Reverses $(D r) in-place, where $(D r) is a narrow string (having
elements of type $(D char) or $(D wchar)). UTF sequences consisting of
multiple code units are preserved properly.
Example:
----
char[] arr = "hello\U00010143\u0100\U00010143".dup;
reverse(arr);
assert(arr == "\U00010143\u0100\U00010143olleh");
----
*/
void reverse(Char)(Char[] s)
if (isNarrowString!(Char[]) && !is(Char == const) && !is(Char == immutable))
{
auto r = representation(s);
for (size_t i = 0; i < s.length; )
{
immutable step = std.utf.stride(s, i);
if (step > 1)
{
.reverse(r[i .. i + step]);
i += step;
}
else
{
++i;
}
}
reverse(r);
}
unittest
{
void test(string a, string b)
{
auto c = a.dup;
reverse(c);
assert(c == b, c ~ " != " ~ b);
}
test("a", "a");
test(" ", " ");
test("\u2029", "\u2029");
test("\u0100", "\u0100");
test("\u0430", "\u0430");
test("\U00010143", "\U00010143");
test("abcdefcdef", "fedcfedcba");
test("hello\U00010143\u0100\U00010143", "\U00010143\u0100\U00010143olleh");
}
// bringToFront
/**
The $(D bringToFront) function has considerable flexibility and
usefulness. It can rotate elements in one buffer left or right, swap
buffers of equal length, and even move elements across disjoint
buffers of different types and different lengths.
$(D bringToFront) takes two ranges $(D front) and $(D back), which may
be of different types. Considering the concatenation of $(D front) and
$(D back) one unified range, $(D bringToFront) rotates that unified
range such that all elements in $(D back) are brought to the beginning
of the unified range. The relative ordering of elements in $(D front)
and $(D back), respectively, remains unchanged.
The simplest use of $(D bringToFront) is for rotating elements in a
buffer. For example:
----
auto arr = [4, 5, 6, 7, 1, 2, 3];
bringToFront(arr[0 .. 4], arr[4 .. $]);
assert(arr == [ 1, 2, 3, 4, 5, 6, 7 ]);
----
The $(D front) range may actually "step over" the $(D back)
range. This is very useful with forward ranges that cannot compute
comfortably right-bounded subranges like $(D arr[0 .. 4]) above. In
the example below, $(D r2) is a right subrange of $(D r1).
----
auto list = SList!(int)(4, 5, 6, 7, 1, 2, 3);
auto r1 = list[];
auto r2 = list[]; popFrontN(r2, 4);
assert(equal(r2, [ 1, 2, 3 ]));
bringToFront(r1, r2);
assert(equal(list[], [ 1, 2, 3, 4, 5, 6, 7 ]));
----
Elements can be swapped across ranges of different types:
----
auto list = SList!(int)(4, 5, 6, 7);
auto vec = [ 1, 2, 3 ];
bringToFront(list[], vec);
assert(equal(list[], [ 1, 2, 3, 4 ]));
assert(equal(vec, [ 5, 6, 7 ]));
----
Performs $(BIGOH max(front.length, back.length)) evaluations of $(D
swap). See also $(WEB sgi.com/tech/stl/_rotate.html, STL's rotate).
Preconditions:
Either $(D front) and $(D back) are disjoint, or $(D back) is
reachable from $(D front) and $(D front) is not reachable from $(D
back).
Returns:
The number of elements brought to the front, i.e., the length of $(D
back).
*/
size_t bringToFront(Range1, Range2)(Range1 front, Range2 back)
if (isInputRange!Range1 && isForwardRange!Range2)
{
enum bool sameHeadExists = is(typeof(front.sameHead(back)));
size_t result;
for (bool semidone; !front.empty && !back.empty; )
{
static if (sameHeadExists)
{
if (front.sameHead(back)) break; // shortcut
}
// Swap elements until front and/or back ends.
auto back0 = back.save;
size_t nswaps;
do
{
static if (sameHeadExists)
{
// Detect the stepping-over condition.
if (front.sameHead(back0)) back0 = back.save;
}
swapFront(front, back);
++nswaps;
front.popFront();
back.popFront();
}
while (!front.empty && !back.empty);
if (!semidone) result += nswaps;
// Now deal with the remaining elements.
if (back.empty)
{
if (front.empty) break;
// Right side was shorter, which means that we've brought
// all the back elements to the front.
semidone = true;
// Next pass: bringToFront(front, back0) to adjust the rest.
back = back0;
}
else
{
assert(front.empty);
// Left side was shorter. Let's step into the back.
static if (is(Range1 == Take!Range2))
{
front = take(back0, nswaps);
}
else
{
immutable subresult = bringToFront(take(back0, nswaps),
back);
if (!semidone) result += subresult;
break; // done
}
}
}
return result;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
// doc example
{
int[] arr = [4, 5, 6, 7, 1, 2, 3];
auto p = bringToFront(arr[0 .. 4], arr[4 .. $]);
assert(p == arr.length - 4);
assert(arr == [ 1, 2, 3, 4, 5, 6, 7 ], text(arr));
}
{
auto list = SList!(int)(4, 5, 6, 7, 1, 2, 3);
auto r1 = list[];
auto r2 = list[]; popFrontN(r2, 4);
assert(equal(r2, [ 1, 2, 3 ]));
bringToFront(r1, r2);
assert(equal(list[], [ 1, 2, 3, 4, 5, 6, 7 ]));
}
{
auto list = SList!(int)(4, 5, 6, 7);
auto vec = [ 1, 2, 3 ];
bringToFront(list[], vec);
assert(equal(list[], [ 1, 2, 3, 4 ]));
assert(equal(vec, [ 5, 6, 7 ]));
}
// a more elaborate test
{
auto rnd = Random(unpredictableSeed);
int[] a = new int[uniform(100, 200, rnd)];
int[] b = new int[uniform(100, 200, rnd)];
foreach (ref e; a) e = uniform(-100, 100, rnd);
foreach (ref e; b) e = uniform(-100, 100, rnd);
int[] c = a ~ b;
// writeln("a= ", a);
// writeln("b= ", b);
auto n = bringToFront(c[0 .. a.length], c[a.length .. $]);
//writeln("c= ", c);
assert(n == b.length);
assert(c == b ~ a, text(c, "\n", a, "\n", b));
}
// different types, moveFront, no sameHead
{
static struct R(T)
{
T[] data;
size_t i;
@property
{
R save() { return this; }
bool empty() { return i >= data.length; }
T front() { return data[i]; }
T front(real e) { return data[i] = cast(T) e; }
alias front moveFront;
}
void popFront() { ++i; }
}
auto a = R!int([1, 2, 3, 4, 5]);
auto b = R!real([6, 7, 8, 9]);
auto n = bringToFront(a, b);
assert(n == 4);
assert(a.data == [6, 7, 8, 9, 1]);
assert(b.data == [2, 3, 4, 5]);
}
// front steps over back
{
int[] arr, r1, r2;
// back is shorter
arr = [4, 5, 6, 7, 1, 2, 3];
r1 = arr;
r2 = arr[4 .. $];
bringToFront(r1, r2) == 3 || assert(0);
assert(equal(arr, [1, 2, 3, 4, 5, 6, 7]));
// front is shorter
arr = [5, 6, 7, 1, 2, 3, 4];
r1 = arr;
r2 = arr[3 .. $];
bringToFront(r1, r2) == 4 || assert(0);
assert(equal(arr, [1, 2, 3, 4, 5, 6, 7]));
}
}
// SwapStrategy
/**
Defines the swapping strategy for algorithms that need to swap
elements in a range (such as partition and sort). The strategy
concerns the swapping of elements that are not the core concern of the
algorithm. For example, consider an algorithm that sorts $(D [ "abc",
"b", "aBc" ]) according to $(D toUpper(a) < toUpper(b)). That
algorithm might choose to swap the two equivalent strings $(D "abc")
and $(D "aBc"). That does not affect the sorting since both $(D [
"abc", "aBc", "b" ]) and $(D [ "aBc", "abc", "b" ]) are valid
outcomes.
Some situations require that the algorithm must NOT ever change the
relative ordering of equivalent elements (in the example above, only
$(D [ "abc", "aBc", "b" ]) would be the correct result). Such
algorithms are called $(B stable). If the ordering algorithm may swap
equivalent elements discretionarily, the ordering is called $(B
unstable).
Yet another class of algorithms may choose an intermediate tradeoff by
being stable only on a well-defined subrange of the range. There is no
established terminology for such behavior; this library calls it $(B
semistable).
Generally, the $(D stable) ordering strategy may be more costly in
time and/or space than the other two because it imposes additional
constraints. Similarly, $(D semistable) may be costlier than $(D
unstable). As (semi-)stability is not needed very often, the ordering
algorithms in this module parameterized by $(D SwapStrategy) all
choose $(D SwapStrategy.unstable) as the default.
*/
enum SwapStrategy
{
/**
Allows freely swapping of elements as long as the output
satisfies the algorithm's requirements.
*/
unstable,
/**
In algorithms partitioning ranges in two, preserve relative
ordering of elements only to the left of the partition point.
*/
semistable,
/**
Preserve the relative ordering of elements to the largest
extent allowed by the algorithm's requirements.
*/
stable,
}
/**
Eliminates elements at given offsets from $(D range) and returns the
shortened range. In the simplest call, one element is removed.
----
int[] a = [ 3, 5, 7, 8 ];
assert(remove(a, 1) == [ 3, 7, 8 ]);
assert(a == [ 3, 7, 8, 8 ]);
----
In the case above the element at offset $(D 1) is removed and $(D
remove) returns the range smaller by one element. The original array
has remained of the same length because all functions in $(D
std.algorithm) only change $(I content), not $(I topology). The value
$(D 8) is repeated because $(XREF algorithm, move) was invoked to move
elements around and on integers $(D move) simply copies the source to
the destination. To replace $(D a) with the effect of the removal,
simply assign $(D a = remove(a, 1)). The slice will be rebound to the
shorter array and the operation completes with maximal efficiency.
Multiple indices can be passed into $(D remove). In that case,
elements at the respective indices are all removed. The indices must
be passed in increasing order, otherwise an exception occurs.
----
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove(a, 1, 3, 5) ==
[ 0, 2, 4, 6, 7, 8, 9, 10 ]);
----
(Note how all indices refer to slots in the $(I original) array, not
in the array as it is being progressively shortened.) Finally, any
combination of integral offsets and tuples composed of two integral
offsets can be passed in.
----
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove(a, 1, tuple(3, 5), 9) == [ 0, 2, 6, 7, 8, 10 ]);
----
In this case, the slots at positions 1, 3, 4, and 9 are removed from
the array. The tuple passes in a range closed to the left and open to
the right (consistent with built-in slices), e.g. $(D tuple(3, 5))
means indices $(D 3) and $(D 4) but not $(D 5).
If the need is to remove some elements in the range but the order of
the remaining elements does not have to be preserved, you may want to
pass $(D SwapStrategy.unstable) to $(D remove).
----
int[] a = [ 0, 1, 2, 3 ];
assert(remove!(SwapStrategy.unstable)(a, 1) == [ 0, 3, 2 ]);
----
In the case above, the element at slot $(D 1) is removed, but replaced
with the last element of the range. Taking advantage of the relaxation
of the stability requirement, $(D remove) moved elements from the end
of the array over the slots to be removed. This way there is less data
movement to be done which improves the execution time of the function.
The function $(D remove) works on any forward range. The moving
strategy is (listed from fastest to slowest): $(UL $(LI If $(D s ==
SwapStrategy.unstable && isRandomAccessRange!Range &&
hasLength!Range), then elements are moved from the end of the range
into the slots to be filled. In this case, the absolute minimum of
moves is performed.) $(LI Otherwise, if $(D s ==
SwapStrategy.unstable && isBidirectionalRange!Range &&
hasLength!Range), then elements are still moved from the end of the
range, but time is spent on advancing between slots by repeated calls
to $(D range.popFront).) $(LI Otherwise, elements are moved incrementally
towards the front of $(D range); a given element is never moved
several times, but more elements are moved than in the previous
cases.))
*/
Range remove
(SwapStrategy s = SwapStrategy.stable, Range, Offset...)
(Range range, Offset offset)
if (isBidirectionalRange!Range && hasLength!Range && s != SwapStrategy.stable
&& Offset.length >= 1)
{
enum bool tupleLeft = is(typeof(offset[0][0]))
&& is(typeof(offset[0][1]));
enum bool tupleRight = is(typeof(offset[$ - 1][0]))
&& is(typeof(offset[$ - 1][1]));
static if (!tupleLeft)
{
alias offset[0] lStart;
auto lEnd = lStart + 1;
}
else
{
auto lStart = offset[0][0];
auto lEnd = offset[0][1];
}
static if (!tupleRight)
{
alias offset[$ - 1] rStart;
auto rEnd = rStart + 1;
}
else
{
auto rStart = offset[$ - 1][0];
auto rEnd = offset[$ - 1][1];
}
// Begin. Test first to see if we need to remove the rightmost
// element(s) in the range. In that case, life is simple - chop
// and recurse.
if (rEnd == range.length)
{
// must remove the last elements of the range
range.popBackN(rEnd - rStart);
static if (Offset.length > 1)
{
return .remove!(s, Range, Offset[0 .. $ - 1])
(range, offset[0 .. $ - 1]);
}
else
{
return range;
}
}
// Ok, there are "live" elements at the end of the range
auto t = range;
auto lDelta = lEnd - lStart, rDelta = rEnd - rStart;
auto rid = min(lDelta, rDelta);
foreach (i; 0 .. rid)
{
move(range.back, t.front);
range.popBack();
t.popFront();
}
if (rEnd - rStart == lEnd - lStart)
{
// We got rid of both left and right
static if (Offset.length > 2)
{
return .remove!(s, Range, Offset[1 .. $ - 1])
(range, offset[1 .. $ - 1]);
}
else
{
return range;
}
}
else if (rEnd - rStart < lEnd - lStart)
{
// We got rid of the entire right subrange
static if (Offset.length > 2)
{
return .remove!(s, Range)
(range, tuple(lStart + rid, lEnd),
offset[1 .. $ - 1]);
}
else
{
auto tmp = tuple(lStart + rid, lEnd);
return .remove!(s, Range, typeof(tmp))
(range, tmp);
}
}
else
{
// We got rid of the entire left subrange
static if (Offset.length > 2)
{
return .remove!(s, Range)
(range, offset[1 .. $ - 1],
tuple(rStart, lEnd - rid));
}
else
{
auto tmp = tuple(rStart, lEnd - rid);
return .remove!(s, Range, typeof(tmp))
(range, tmp);
}
}
}
// Ditto
Range remove
(SwapStrategy s = SwapStrategy.stable, Range, Offset...)
(Range range, Offset offset)
if ((isForwardRange!Range && !isBidirectionalRange!Range
|| !hasLength!Range || s == SwapStrategy.stable)
&& Offset.length >= 1)
{
auto result = range;
auto src = range, tgt = range;
size_t pos;
foreach (i; offset)
{
static if (is(typeof(i[0])) && is(typeof(i[1])))
{
auto from = i[0], delta = i[1] - i[0];
}
else
{
auto from = i;
enum delta = 1;
}
assert(pos <= from);
for (; pos < from; ++pos, src.popFront(), tgt.popFront())
{
move(src.front, tgt.front);
}
// now skip source to the "to" position
src.popFrontN(delta);
pos += delta;
foreach (j; 0 .. delta) result.popBack();
}
// leftover move
moveAll(src, tgt);
return result;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
//writeln(remove!(SwapStrategy.stable)(a, 1));
a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove!(SwapStrategy.stable)(a, 1) ==
[ 0, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]);
a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove!(SwapStrategy.unstable)(a, 0, 10) ==
[ 9, 1, 2, 3, 4, 5, 6, 7, 8 ]);
a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove!(SwapStrategy.unstable)(a, 0, tuple(9, 11)) ==
[ 8, 1, 2, 3, 4, 5, 6, 7 ]);
a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
//writeln(remove!(SwapStrategy.stable)(a, 1, 5));
a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove!(SwapStrategy.stable)(a, 1, 5) ==
[ 0, 2, 3, 4, 6, 7, 8, 9, 10 ]);
a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
//writeln(remove!(SwapStrategy.stable)(a, 1, 3, 5));
a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove!(SwapStrategy.stable)(a, 1, 3, 5)
== [ 0, 2, 4, 6, 7, 8, 9, 10]);
a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
//writeln(remove!(SwapStrategy.stable)(a, 1, tuple(3, 5)));
a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
assert(remove!(SwapStrategy.stable)(a, 1, tuple(3, 5))
== [ 0, 2, 5, 6, 7, 8, 9, 10]);
}
/**
Reduces the length of the bidirectional range $(D range) by only
keeping elements that satisfy $(D pred). If $(D s =
SwapStrategy.unstable), elements are moved from the right end of the
range over the elements to eliminate. If $(D s = SwapStrategy.stable)
(the default), elements are moved progressively to front such that
their relative order is preserved. Returns the tail portion of the
range that was moved.
Example:
----
int[] a = [ 1, 2, 3, 2, 3, 4, 5, 2, 5, 6 ];
assert(a[0 .. remove!("a == 2")(a).length] == [ 1, 3, 3, 4, 5, 5, 6 ]);
----
*/
Range remove(alias pred, SwapStrategy s = SwapStrategy.stable, Range)
(Range range)
if (isBidirectionalRange!Range)
{
auto result = range;
static if (s != SwapStrategy.stable)
{
for (;!range.empty;)
{
if (!unaryFun!(pred)(range.front))
{
range.popFront();
continue;
}
move(range.back, range.front);
range.popBack();
result.popBack();
}
}
else
{
auto tgt = range;
for (; !range.empty; range.popFront())
{
if (unaryFun!(pred)(range.front))
{
// yank this guy
result.popBack();
continue;
}
// keep this guy
move(range.front, tgt.front);
tgt.popFront();
}
}
return result;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3, 2, 3, 4, 5, 2, 5, 6 ];
assert(remove!("a == 2", SwapStrategy.unstable)(a) ==
[ 1, 6, 3, 5, 3, 4, 5 ]);
a = [ 1, 2, 3, 2, 3, 4, 5, 2, 5, 6 ];
//writeln(remove!("a != 2", SwapStrategy.stable)(a));
assert(remove!("a == 2", SwapStrategy.stable)(a) ==
[ 1, 3, 3, 4, 5, 5, 6 ]);
}
// eliminate
/* *
Reduces $(D r) by overwriting all elements $(D x) that satisfy $(D
pred(x)). Returns the reduced range.
Example:
----
int[] arr = [ 1, 2, 3, 4, 5 ];
// eliminate even elements
auto r = eliminate!("(a & 1) == 0")(arr);
assert(r == [ 1, 3, 5 ]);
assert(arr == [ 1, 3, 5, 4, 5 ]);
----
*/
// Range eliminate(alias pred,
// SwapStrategy ss = SwapStrategy.unstable,
// alias move = .move,
// Range)(Range r)
// {
// alias Iterator!(Range) It;
// static void assignIter(It a, It b) { move(*b, *a); }
// return range(begin(r), partitionold!(not!(pred), ss, assignIter, Range)(r));
// }
// unittest
// {
// int[] arr = [ 1, 2, 3, 4, 5 ];
// // eliminate even elements
// auto r = eliminate!("(a & 1) == 0")(arr);
// assert(find!("(a & 1) == 0")(r).empty);
// }
/* *
Reduces $(D r) by overwriting all elements $(D x) that satisfy $(D
pred(x, v)). Returns the reduced range.
Example:
----
int[] arr = [ 1, 2, 3, 2, 4, 5, 2 ];
// keep elements different from 2
auto r = eliminate(arr, 2);
assert(r == [ 1, 3, 4, 5 ]);
assert(arr == [ 1, 3, 4, 5, 4, 5, 2 ]);
----
*/
// Range eliminate(alias pred = "a == b",
// SwapStrategy ss = SwapStrategy.semistable,
// Range, Value)(Range r, Value v)
// {
// alias Iterator!(Range) It;
// bool comp(typeof(*It) a) { return !binaryFun!(pred)(a, v); }
// static void assignIterB(It a, It b) { *a = *b; }
// return range(begin(r),
// partitionold!(comp,
// ss, assignIterB, Range)(r));
// }
// unittest
// {
// int[] arr = [ 1, 2, 3, 2, 4, 5, 2 ];
// // keep elements different from 2
// auto r = eliminate(arr, 2);
// assert(r == [ 1, 3, 4, 5 ]);
// assert(arr == [ 1, 3, 4, 5, 4, 5, 2 ]);
// }
// partition
/**
Partitions a range in two using $(D pred) as a
predicate. Specifically, reorders the range $(D r = [left,
right$(RPAREN)) using $(D swap) such that all elements $(D i) for
which $(D pred(i)) is $(D true) come before all elements $(D j) for
which $(D pred(j)) returns $(D false).
Performs $(BIGOH r.length) (if unstable or semistable) or $(BIGOH
r.length * log(r.length)) (if stable) evaluations of $(D less) and $(D
swap). The unstable version computes the minimum possible evaluations
of $(D swap) (roughly half of those performed by the semistable
version).
See also STL's $(WEB sgi.com/tech/stl/_partition.html, _partition) and
$(WEB sgi.com/tech/stl/stable_partition.html, stable_partition).
Returns:
The right part of $(D r) after partitioning.
If $(D ss == SwapStrategy.stable), $(D partition) preserves the
relative ordering of all elements $(D a), $(D b) in $(D r) for which
$(D pred(a) == pred(b)). If $(D ss == SwapStrategy.semistable), $(D
partition) preserves the relative ordering of all elements $(D a), $(D
b) in the left part of $(D r) for which $(D pred(a) == pred(b)).
Example:
----
auto Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto arr = Arr.dup;
static bool even(int a) { return (a & 1) == 0; }
// Partition arr such that even numbers come first
auto r = partition!(even)(arr);
// Now arr is separated in evens and odds.
// Numbers may have become shuffled due to instability
assert(r == arr[5 .. $]);
assert(count!(even)(arr[0 .. 5]) == 5);
assert(find!(even)(r).empty);
// Can also specify the predicate as a string.
// Use 'a' as the predicate argument name
arr[] = Arr[];
r = partition!(q{(a & 1) == 0})(arr);
assert(r == arr[5 .. $]);
// Now for a stable partition:
arr[] = Arr[];
r = partition!(q{(a & 1) == 0}, SwapStrategy.stable)(arr);
// Now arr is [2 4 6 8 10 1 3 5 7 9], and r points to 1
assert(arr == [2, 4, 6, 8, 10, 1, 3, 5, 7, 9] && r == arr[5 .. $]);
// In case the predicate needs to hold its own state, use a delegate:
arr[] = Arr[];
int x = 3;
// Put stuff greater than 3 on the left
bool fun(int a) { return a > x; }
r = partition!(fun, SwapStrategy.semistable)(arr);
// Now arr is [4 5 6 7 8 9 10 2 3 1] and r points to 2
assert(arr == [4, 5, 6, 7, 8, 9, 10, 2, 3, 1] && r == arr[7 .. $]);
----
*/
Range partition(alias predicate,
SwapStrategy ss = SwapStrategy.unstable, Range)(Range r)
if ((ss == SwapStrategy.stable && isRandomAccessRange!(Range))
|| (ss != SwapStrategy.stable && isForwardRange!(Range)))
{
alias unaryFun!(predicate) pred;
if (r.empty) return r;
static if (ss == SwapStrategy.stable)
{
if (r.length == 1)
{
if (pred(r.front)) r.popFront();
return r;
}
const middle = r.length / 2;
alias .partition!(pred, ss, Range) recurse;
auto lower = recurse(r[0 .. middle]);
auto upper = recurse(r[middle .. $]);
bringToFront(lower, r[middle .. r.length - upper.length]);
return r[r.length - lower.length - upper.length .. r.length];
}
else static if (ss == SwapStrategy.semistable)
{
for (; !r.empty; r.popFront())
{
// skip the initial portion of "correct" elements
if (pred(r.front)) continue;
// hit the first "bad" element
auto result = r;
for (r.popFront(); !r.empty; r.popFront())
{
if (!pred(r.front)) continue;
swap(result.front, r.front);
result.popFront();
}
return result;
}
return r;
}
else // ss == SwapStrategy.unstable
{
// Inspired from www.stepanovpapers.com/PAM3-partition_notes.pdf,
// section "Bidirectional Partition Algorithm (Hoare)"
auto result = r;
for (;;)
{
for (;;)
{
if (r.empty) return result;
if (!pred(r.front)) break;
r.popFront();
result.popFront();
}
// found the left bound
assert(!r.empty);
for (;;)
{
if (pred(r.back)) break;
r.popBack();
if (r.empty) return result;
}
// found the right bound, swap & make progress
static if (is(typeof(swap(r.front, r.back))))
{
swap(r.front, r.back);
}
else
{
auto t1 = moveFront(r), t2 = moveBack(r);
r.front = t2;
r.back = t1;
}
r.popFront();
result.popFront();
r.popBack();
}
}
}
unittest // partition
{
auto Arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto arr = Arr.dup;
static bool even(int a) { return (a & 1) == 0; }
// Partition a such that even numbers come first
auto p1 = partition!(even)(arr);
// Now arr is separated in evens and odds.
assert(p1 == arr[5 .. $], text(p1));
assert(count!(even)(arr[0 .. $ - p1.length]) == p1.length);
assert(find!(even)(p1).empty);
// Notice that numbers have become shuffled due to instability
arr[] = Arr[];
// Can also specify the predicate as a string.
// Use 'a' as the predicate argument name
p1 = partition!(q{(a & 1) == 0})(arr);
assert(p1 == arr[5 .. $]);
// Same result as above. Now for a stable partition:
arr[] = Arr[];
p1 = partition!(q{(a & 1) == 0}, SwapStrategy.stable)(arr);
// Now arr is [2 4 6 8 10 1 3 5 7 9], and p points to 1
assert(arr == [2, 4, 6, 8, 10, 1, 3, 5, 7, 9], text(arr));
assert(p1 == arr[5 .. $], text(p1));
// In case the predicate needs to hold its own state, use a delegate:
arr[] = Arr[];
int x = 3;
// Put stuff greater than 3 on the left
bool fun(int a) { return a > x; }
p1 = partition!(fun, SwapStrategy.semistable)(arr);
// Now arr is [4 5 6 7 8 9 10 2 3 1] and p points to 2
assert(arr == [4, 5, 6, 7, 8, 9, 10, 2, 3, 1] && p1 == arr[7 .. $]);
// test with random data
auto a = rndstuff!(int)();
partition!(even)(a);
assert(isPartitioned!(even)(a));
auto b = rndstuff!(string)();
partition!(`a.length < 5`)(b);
assert(isPartitioned!(`a.length < 5`)(b));
}
/**
Returns $(D true) if $(D r) is partitioned according to predicate $(D
pred).
Example:
----
int[] r = [ 1, 3, 5, 7, 8, 2, 4, ];
assert(isPartitioned!("a & 1")(r));
----
*/
bool isPartitioned(alias pred, Range)(Range r)
if (isForwardRange!(Range))
{
for (; !r.empty; r.popFront())
{
if (unaryFun!(pred)(r.front)) continue;
for (r.popFront(); !r.empty; r.popFront())
{
if (unaryFun!(pred)(r.front)) return false;
}
break;
}
return true;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] r = [ 1, 3, 5, 7, 8, 2, 4, ];
assert(isPartitioned!("a & 1")(r));
}
// partition3
/**
Rearranges elements in $(D r) in three adjacent ranges and returns
them. The first and leftmost range only contains elements in $(D r)
less than $(D pivot). The second and middle range only contains
elements in $(D r) that are equal to $(D pivot). Finally, the third
and rightmost range only contains elements in $(D r) that are greater
than $(D pivot). The less-than test is defined by the binary function
$(D less).
Example:
----
auto a = [ 8, 3, 4, 1, 4, 7, 4 ];
auto pieces = partition3(a, 4);
assert(a == [ 1, 3, 4, 4, 4, 7, 8 ];
assert(pieces[0] == [ 1, 3 ]);
assert(pieces[1] == [ 4, 4, 4 ]);
assert(pieces[2] == [ 7, 8 ]);
----
BUGS: stable $(D partition3) has not been implemented yet.
*/
auto partition3(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, E)
(Range r, E pivot)
if (ss == SwapStrategy.unstable && isRandomAccessRange!Range
&& hasSwappableElements!Range && hasLength!Range
&& is(typeof(binaryFun!less(r.front, pivot)) == bool)
&& is(typeof(binaryFun!less(pivot, r.front)) == bool)
&& is(typeof(binaryFun!less(r.front, r.front)) == bool))
{
// The algorithm is described in "Engineering a sort function" by
// Jon Bentley et al, pp 1257.
alias binaryFun!less lessFun;
size_t i, j, k = r.length, l = k;
bigloop:
for (;;)
{
for (;; ++j)
{
if (j == k) break bigloop;
assert(j < r.length);
if (lessFun(r[j], pivot)) continue;
if (lessFun(pivot, r[j])) break;
swap(r[i++], r[j]);
}
assert(j < k);
for (;;)
{
assert(k > 0);
if (!lessFun(pivot, r[--k]))
{
if (lessFun(r[k], pivot)) break;
swap(r[k], r[--l]);
}
if (j == k) break bigloop;
}
// Here we know r[j] > pivot && r[k] < pivot
swap(r[j++], r[k]);
}
// Swap the equal ranges from the extremes into the middle
auto strictlyLess = j - i, strictlyGreater = l - k;
auto swapLen = min(i, strictlyLess);
swapRanges(r[0 .. swapLen], r[j - swapLen .. j]);
swapLen = min(r.length - l, strictlyGreater);
swapRanges(r[k .. k + swapLen], r[r.length - swapLen .. r.length]);
return tuple(r[0 .. strictlyLess],
r[strictlyLess .. r.length - strictlyGreater],
r[r.length - strictlyGreater .. r.length]);
}
unittest
{
auto a = [ 8, 3, 4, 1, 4, 7, 4 ];
auto pieces = partition3(a, 4);
assert(a == [ 1, 3, 4, 4, 4, 8, 7 ]);
assert(pieces[0] == [ 1, 3 ]);
assert(pieces[1] == [ 4, 4, 4 ]);
assert(pieces[2] == [ 8, 7 ]);
a = null;
pieces = partition3(a, 4);
assert(a.empty);
assert(pieces[0].empty);
assert(pieces[1].empty);
assert(pieces[2].empty);
a.length = uniform(0, 100);
foreach (ref e; a)
{
e = uniform(0, 50);
}
pieces = partition3(a, 25);
assert(pieces[0].length + pieces[1].length + pieces[2].length == a.length);
foreach (e; pieces[0])
{
assert(e < 25);
}
foreach (e; pieces[1])
{
assert(e == 25);
}
foreach (e; pieces[2])
{
assert(e > 25);
}
}
// topN
/**
Reorders the range $(D r) using $(D swap) such that $(D r[nth]) refers
to the element that would fall there if the range were fully
sorted. In addition, it also partitions $(D r) such that all elements
$(D e1) from $(D r[0]) to $(D r[nth]) satisfy $(D !less(r[nth], e1)),
and all elements $(D e2) from $(D r[nth]) to $(D r[r.length]) satisfy
$(D !less(e2, r[nth])). Effectively, it finds the nth smallest
(according to $(D less)) elements in $(D r). Performs $(BIGOH
r.length) (if unstable) or $(BIGOH r.length * log(r.length)) (if
stable) evaluations of $(D less) and $(D swap). See also $(WEB
sgi.com/tech/stl/nth_element.html, STL's nth_element).
Example:
----
int[] v = [ 25, 7, 9, 2, 0, 5, 21 ];
auto n = 4;
topN!(less)(v, n);
assert(v[n] == 9);
// Equivalent form:
topN!("a < b")(v, n);
assert(v[n] == 9);
----
BUGS:
Stable topN has not been implemented yet.
*/
void topN(alias less = "a < b",
SwapStrategy ss = SwapStrategy.unstable,
Range)(Range r, size_t nth)
if (isRandomAccessRange!(Range) && hasLength!Range)
{
static assert(ss == SwapStrategy.unstable,
"Stable topN not yet implemented");
while (r.length > nth)
{
auto pivot = r.length / 2;
swap(r[pivot], r.back);
assert(!binaryFun!(less)(r.back, r.back));
bool pred(ElementType!(Range) a)
{
return binaryFun!(less)(a, r.back);
}
auto right = partition!(pred, ss)(r);
assert(right.length >= 1);
swap(right.front, r.back);
pivot = r.length - right.length;
if (pivot == nth)
{
return;
}
if (pivot < nth)
{
++pivot;
r = r[pivot .. $];
nth -= pivot;
}
else
{
assert(pivot < r.length);
r = r[0 .. pivot];
}
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
//scope(failure) writeln(stderr, "Failure testing algorithm");
//auto v = ([ 25, 7, 9, 2, 0, 5, 21 ]).dup;
int[] v = [ 7, 6, 5, 4, 3, 2, 1, 0 ];
sizediff_t n = 3;
topN!("a < b")(v, n);
assert(reduce!max(v[0 .. n]) <= v[n]);
assert(reduce!min(v[n + 1 .. $]) >= v[n]);
//
v = ([3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]).dup;
n = 3;
topN(v, n);
assert(reduce!max(v[0 .. n]) <= v[n]);
assert(reduce!min(v[n + 1 .. $]) >= v[n]);
//
v = ([3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]).dup;
n = 1;
topN(v, n);
assert(reduce!max(v[0 .. n]) <= v[n]);
assert(reduce!min(v[n + 1 .. $]) >= v[n]);
//
v = ([3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]).dup;
n = v.length - 1;
topN(v, n);
assert(v[n] == 7);
//
v = ([3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]).dup;
n = 0;
topN(v, n);
assert(v[n] == 1);
double[][] v1 = [[-10, -5], [-10, -3], [-10, -5], [-10, -4],
[-10, -5], [-9, -5], [-9, -3], [-9, -5],];
// double[][] v1 = [ [-10, -5], [-10, -4], [-9, -5], [-9, -5],
// [-10, -5], [-10, -3], [-10, -5], [-9, -3],];
double[]*[] idx = [ &v1[0], &v1[1], &v1[2], &v1[3], &v1[4], &v1[5], &v1[6],
&v1[7], ];
auto mid = v1.length / 2;
topN!((a, b){ return (*a)[1] < (*b)[1]; })(idx, mid);
foreach (e; idx[0 .. mid]) assert((*e)[1] <= (*idx[mid])[1]);
foreach (e; idx[mid .. $]) assert((*e)[1] >= (*idx[mid])[1]);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = new int[uniform(1, 10000)];
foreach (ref e; a) e = uniform(-1000, 1000);
auto k = uniform(0, a.length);
topN(a, k);
if (k > 0)
{
auto left = reduce!max(a[0 .. k]);
assert(left <= a[k]);
}
if (k + 1 < a.length)
{
auto right = reduce!min(a[k + 1 .. $]);
assert(right >= a[k]);
}
}
/**
Stores the smallest elements of the two ranges in the left-hand range.
*/
void topN(alias less = "a < b",
SwapStrategy ss = SwapStrategy.unstable,
Range1, Range2)(Range1 r1, Range2 r2)
if (isRandomAccessRange!(Range1) && hasLength!Range1 &&
isInputRange!Range2 && is(ElementType!Range1 == ElementType!Range2))
{
static assert(ss == SwapStrategy.unstable,
"Stable topN not yet implemented");
auto heap = BinaryHeap!Range1(r1);
for (; !r2.empty; r2.popFront())
{
heap.conditionalInsert(r2.front);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 5, 7, 2, 6, 7 ];
int[] b = [ 2, 1, 5, 6, 7, 3, 0 ];
topN(a, b);
sort(a);
sort(b);
assert(a == [0, 1, 2, 2, 3]);
}
// sort
/**
Sorts a random-access range according to predicate $(D less). Performs
$(BIGOH r.length * log(r.length)) (if unstable) or $(BIGOH r.length *
log(r.length) * log(r.length)) (if stable) evaluations of $(D less)
and $(D swap). See also STL's $(WEB sgi.com/tech/stl/_sort.html, _sort)
and $(WEB sgi.com/tech/stl/stable_sort.html, stable_sort).
Example:
----
int[] array = [ 1, 2, 3, 4 ];
// sort in descending order
sort!("a > b")(array);
assert(array == [ 4, 3, 2, 1 ]);
// sort in ascending order
sort(array);
assert(array == [ 1, 2, 3, 4 ]);
// sort with a delegate
bool myComp(int x, int y) { return x > y; }
sort!(myComp)(array);
assert(array == [ 4, 3, 2, 1 ]);
// Showcase stable sorting
string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ];
sort!("toUpper(a) < toUpper(b)", SwapStrategy.stable)(words);
assert(words == [ "a", "aBc", "abc", "ABC", "b", "c" ]);
----
*/
SortedRange!(Range, less)
sort(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable,
Range)(Range r)
{
alias binaryFun!(less) lessFun;
static if (is(typeof(lessFun(r.front, r.front)) == bool))
{
sortImpl!(lessFun, ss)(r);
static if(is(typeof(text(r))))
{
enum maxLen = 8;
assert(isSorted!lessFun(r), text("Failed to sort range of type ",
Range.stringof, ". Actual result is: ",
r[0 .. r.length > maxLen ? maxLen : r.length ],
r.length > maxLen ? "..." : ""));
}
else
assert(isSorted!lessFun(r), text("Unable to sort range of type ",
Range.stringof, ": <unable to print elements>"));
}
else
{
static assert(false, "Invalid predicate passed to sort: "~less);
}
return assumeSorted!less(r);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
// sort using delegate
int a[] = new int[100];
auto rnd = Random(unpredictableSeed);
foreach (ref e; a) {
e = uniform(-100, 100, rnd);
}
int i = 0;
bool greater2(int a, int b) { return a + i > b + i; }
bool delegate(int, int) greater = &greater2;
sort!(greater)(a);
assert(isSorted!(greater)(a));
// sort using string
sort!("a < b")(a);
assert(isSorted!("a < b")(a));
// sort using function; all elements equal
foreach (ref e; a) {
e = 5;
}
static bool less(int a, int b) { return a < b; }
sort!(less)(a);
assert(isSorted!(less)(a));
string[] words = [ "aBc", "a", "abc", "b", "ABC", "c" ];
bool lessi(string a, string b) { return toUpper(a) < toUpper(b); }
sort!(lessi, SwapStrategy.stable)(words);
assert(words == [ "a", "aBc", "abc", "ABC", "b", "c" ]);
// sort using ternary predicate
//sort!("b - a")(a);
//assert(isSorted!(less)(a));
a = rndstuff!(int)();
sort(a);
assert(isSorted(a));
auto b = rndstuff!(string)();
sort!("toLower(a) < toLower(b)")(b);
assert(isSorted!("toUpper(a) < toUpper(b)")(b));
}
private template validPredicates(E, less...) {
static if (less.length == 0)
enum validPredicates = true;
else static if (less.length == 1 && is(typeof(less[0]) == SwapStrategy))
enum validPredicates = true;
else
enum validPredicates =
is(typeof(binaryFun!(less[0])(E.init, E.init)) == bool) &&
validPredicates!(E, less[1 .. $]);
}
/**
Sorts a range by multiple keys. The call $(D multiSort!("a.id < b.id",
"a.date > b.date")(r)) sorts the range $(D r) by $(D id) ascending,
and sorts elements that have the same $(D id) by $(D date)
descending. Such a call is equivalent to $(D sort!"a.id != b.id ? a.id
< b.id : a.date > b.date"(r)), but $(D multiSort) is faster because it
does fewer comparisons (in addition to being more convenient).
Example:
----
static struct Point { int x, y; }
auto pts1 = [ Point(0, 0), Point(5, 5), Point(0, 1), Point(0, 2) ];
auto pts2 = [ Point(0, 0), Point(0, 1), Point(0, 2), Point(5, 5) ];
multiSort!("a.x < b.x", "a.y < b.y", SwapStrategy.unstable)(pts1);
assert(pts1 == pts2);
----
*/
template multiSort(less...) //if (less.length > 1)
{
void multiSort(Range)(Range r)
if (validPredicates!(ElementType!Range, less))
{
static if (is(typeof(less[$ - 1]) == SwapStrategy))
{
enum ss = less[$ - 1];
alias less[0 .. $ - 1] funs;
}
else
{
alias SwapStrategy.unstable ss;
alias less funs;
}
alias binaryFun!(funs[0]) lessFun;
static if (funs.length > 1)
{
while (r.length > 1)
{
auto p = getPivot!lessFun(r);
auto t = partition3!(less[0], ss)(r, r[p]);
if (t[0].length <= t[2].length)
{
.multiSort!less(t[0]);
.multiSort!(less[1 .. $])(t[1]);
r = t[2];
}
else
{
.multiSort!(less[1 .. $])(t[1]);
.multiSort!less(t[2]);
r = t[0];
}
}
}
else
{
sort!(lessFun, ss)(r);
}
}
}
unittest
{
static struct Point { int x, y; }
auto pts1 = [ Point(5, 6), Point(1, 0), Point(5, 7), Point(1, 1), Point(1, 2), Point(0, 1) ];
auto pts2 = [ Point(0, 1), Point(1, 0), Point(1, 1), Point(1, 2), Point(5, 6), Point(5, 7) ];
static assert(validPredicates!(Point, "a.x < b.x", "a.y < b.y"));
multiSort!("a.x < b.x", "a.y < b.y", SwapStrategy.unstable)(pts1);
assert(pts1 == pts2);
auto pts3 = indexed(pts1, iota(pts1.length));
multiSort!("a.x < b.x", "a.y < b.y", SwapStrategy.unstable)(pts3);
assert(equal(pts3, pts2));
}
private size_t getPivot(alias less, Range)(Range r)
{
// This algorithm sorts the first, middle and last elements of r,
// then returns the index of the middle element. In effect, it uses the
// median-of-three heuristic.
alias binaryFun!(less) pred;
immutable len = r.length;
immutable size_t mid = len / 2;
immutable uint result = ((cast(uint) (pred(r[0], r[mid]))) << 2) |
((cast(uint) (pred(r[0], r[len - 1]))) << 1) |
(cast(uint) (pred(r[mid], r[len - 1])));
switch(result) {
case 0b001:
swapAt(r, 0, len - 1);
swapAt(r, 0, mid);
break;
case 0b110:
swapAt(r, mid, len - 1);
break;
case 0b011:
swapAt(r, 0, mid);
break;
case 0b100:
swapAt(r, mid, len - 1);
swapAt(r, 0, mid);
break;
case 0b000:
swapAt(r, 0, len - 1);
break;
case 0b111:
break;
default:
assert(0);
}
return mid;
}
private void optimisticInsertionSort(alias less, Range)(Range r)
{
alias binaryFun!(less) pred;
if(r.length < 2) {
return ;
}
immutable maxJ = r.length - 1;
for(size_t i = r.length - 2; i != size_t.max; --i) {
size_t j = i;
auto temp = r[i];
for(; j < maxJ && pred(r[j + 1], temp); ++j) {
r[j] = r[j + 1];
}
r[j] = temp;
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto rnd = Random(1);
int a[] = new int[uniform(100, 200, rnd)];
foreach (ref e; a) {
e = uniform(-100, 100, rnd);
}
optimisticInsertionSort!(binaryFun!("a < b"), int[])(a);
assert(isSorted(a));
}
// private
void swapAt(R)(R r, size_t i1, size_t i2)
{
static if (is(typeof(&r[i1])))
{
swap(r[i1], r[i2]);
}
else
{
if (i1 == i2) return;
auto t1 = moveAt(r, i1);
auto t2 = moveAt(r, i2);
r[i2] = t1;
r[i1] = t2;
}
}
private void sortImpl(alias less, SwapStrategy ss, Range)(Range r)
{
alias ElementType!(Range) Elem;
enum size_t optimisticInsertionSortGetsBetter = 25;
static assert(optimisticInsertionSortGetsBetter >= 1);
while (r.length > optimisticInsertionSortGetsBetter)
{
const pivotIdx = getPivot!(less)(r);
auto pivot = r[pivotIdx];
// partition
static if (ss == SwapStrategy.unstable)
{
alias binaryFun!(less) pred;
// partition
swapAt(r, pivotIdx, r.length - 1);
size_t lessI = size_t.max, greaterI = r.length - 1;
while(true)
{
while(pred(r[++lessI], pivot)) {}
while(greaterI > 0 && pred(pivot, r[--greaterI])) {}
if(lessI < greaterI)
{
swapAt(r, lessI, greaterI);
}
else
{
break;
}
}
swapAt(r, r.length - 1, lessI);
auto right = r[lessI + 1..r.length];
auto left = r[0..min(lessI, greaterI + 1)];
if (right.length > left.length)
{
swap(left, right);
}
.sortImpl!(less, ss, Range)(right);
r = left;
}
else // handle semistable and stable the same
{
static assert(ss != SwapStrategy.semistable);
bool pred(Elem a) { return less(a, pivot); }
auto right = partition!(pred, ss)(r);
if (r.length == right.length)
{
// bad, bad pivot. pivot <= everything
// find the first occurrence of the pivot
bool pred1(Elem a) { return !less(pivot, a); }
//auto firstPivotPos = find!(pred1)(r).ptr;
auto pivotSpan = find!(pred1)(r);
assert(!pivotSpan.empty);
assert(!less(pivotSpan.front, pivot)
&& !less(pivot, pivotSpan.front));
// find the last occurrence of the pivot
bool pred2(Elem a) { return less(pivot, a); }
//auto lastPivotPos = find!(pred2)(pivotsRight[1 .. $]).ptr;
auto pivotRunLen = find!(pred2)(pivotSpan[1 .. $]).length;
pivotSpan = pivotSpan[0 .. pivotRunLen + 1];
// now rotate firstPivotPos..lastPivotPos to the front
bringToFront(r, pivotSpan);
r = r[pivotSpan.length .. $];
}
else
{
.sortImpl!(less, ss, Range)(r[0 .. r.length - right.length]);
r = right;
}
}
}
// residual sort
static if (optimisticInsertionSortGetsBetter > 1)
{
optimisticInsertionSort!(less, Range)(r);
}
}
// schwartzSort
/**
Sorts a range using an algorithm akin to the $(WEB
wikipedia.org/wiki/Schwartzian_transform, Schwartzian transform), also
known as the decorate-sort-undecorate pattern in Python and Lisp. (Not
to be confused with $(WEB youtube.com/watch?v=S25Zf8svHZQ, the other
Schwartz).) This function is helpful when the sort comparison includes
an expensive computation. The complexity is the same as that of the
corresponding $(D sort), but $(D schwartzSort) evaluates $(D
transform) only $(D r.length) times (less than half when compared to
regular sorting). The usage can be best illustrated with an example.
Example:
----
uint hashFun(string) { ... expensive computation ... }
string[] array = ...;
// Sort strings by hash, slow
sort!("hashFun(a) < hashFun(b)")(array);
// Sort strings by hash, fast (only computes arr.length hashes):
schwartzSort!(hashFun, "a < b")(array);
----
The $(D schwartzSort) function might require less temporary data and
be faster than the Perl idiom or the decorate-sort-undecorate idiom
present in Python and Lisp. This is because sorting is done in-place
and only minimal extra data (one array of transformed elements) is
created.
To check whether an array was sorted and benefit of the speedup of
Schwartz sorting, a function $(D schwartzIsSorted) is not provided
because the effect can be achieved by calling $(D
isSorted!less(map!transform(r))).
*/
void schwartzSort(alias transform, alias less = "a < b",
SwapStrategy ss = SwapStrategy.unstable, Range)(Range r)
if (isRandomAccessRange!(Range) && hasLength!(Range))
{
alias typeof(transform(r.front)) XformType;
auto xform = new XformType[r.length];
foreach (i, e; r)
{
xform[i] = transform(e);
}
auto z = zip(xform, r);
alias typeof(z.front()) ProxyType;
bool myLess(ProxyType a, ProxyType b)
{
return binaryFun!less(a[0], b[0]);
}
sort!(myLess, ss)(z);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
static double entropy(double[] probs) {
double result = 0;
foreach (p; probs) {
if (!p) continue;
//enforce(p > 0 && p <= 1, "Wrong probability passed to entropy");
result -= p * log2(p);
}
return result;
}
auto lowEnt = ([ 1.0, 0, 0 ]).dup,
midEnt = ([ 0.1, 0.1, 0.8 ]).dup,
highEnt = ([ 0.31, 0.29, 0.4 ]).dup;
double arr[][] = new double[][3];
arr[0] = midEnt;
arr[1] = lowEnt;
arr[2] = highEnt;
schwartzSort!(entropy, q{a > b})(arr);
assert(arr[0] == highEnt);
assert(arr[1] == midEnt);
assert(arr[2] == lowEnt);
assert(isSorted!("a > b")(map!(entropy)(arr)));
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
static double entropy(double[] probs) {
double result = 0;
foreach (p; probs) {
if (!p) continue;
//enforce(p > 0 && p <= 1, "Wrong probability passed to entropy");
result -= p * log2(p);
}
return result;
}
auto lowEnt = ([ 1.0, 0, 0 ]).dup,
midEnt = ([ 0.1, 0.1, 0.8 ]).dup,
highEnt = ([ 0.31, 0.29, 0.4 ]).dup;
double arr[][] = new double[][3];
arr[0] = midEnt;
arr[1] = lowEnt;
arr[2] = highEnt;
schwartzSort!(entropy, q{a < b})(arr);
assert(arr[0] == lowEnt);
assert(arr[1] == midEnt);
assert(arr[2] == highEnt);
assert(isSorted!("a < b")(map!(entropy)(arr)));
}
// partialSort
/**
Reorders the random-access range $(D r) such that the range $(D r[0
.. mid]) is the same as if the entire $(D r) were sorted, and leaves
the range $(D r[mid .. r.length]) in no particular order. Performs
$(BIGOH r.length * log(mid)) evaluations of $(D pred). The
implementation simply calls $(D topN!(less, ss)(r, n)) and then $(D
sort!(less, ss)(r[0 .. n])).
Example:
----
int[] a = [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ];
partialSort(a, 5);
assert(a[0 .. 5] == [ 0, 1, 2, 3, 4 ]);
----
*/
void partialSort(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable,
Range)(Range r, size_t n)
if (isRandomAccessRange!(Range) && hasLength!(Range) && hasSlicing!(Range))
{
topN!(less, ss)(r, n);
sort!(less, ss)(r[0 .. n]);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ];
partialSort(a, 5);
assert(a[0 .. 5] == [ 0, 1, 2, 3, 4 ]);
}
// completeSort
/**
Sorts the random-access range $(D chain(lhs, rhs)) according to
predicate $(D less). The left-hand side of the range $(D lhs) is
assumed to be already sorted; $(D rhs) is assumed to be unsorted. The
exact strategy chosen depends on the relative sizes of $(D lhs) and
$(D rhs). Performs $(BIGOH lhs.length + rhs.length * log(rhs.length))
(best case) to $(BIGOH (lhs.length + rhs.length) * log(lhs.length +
rhs.length)) (worst-case) evaluations of $(D swap).
Example:
----
int[] a = [ 1, 2, 3 ];
int[] b = [ 4, 0, 6, 5 ];
completeSort(assumeSorted(a), b);
assert(a == [ 0, 1, 2 ]);
assert(b == [ 3, 4, 5, 6 ]);
----
*/
void completeSort(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable,
Range1, Range2)(SortedRange!(Range1, less) lhs, Range2 rhs)
if (hasLength!(Range2) && hasSlicing!(Range2))
{
// Probably this algorithm can be optimized by using in-place
// merge
auto lhsOriginal = lhs.release();
foreach (i; 0 .. rhs.length)
{
auto sortedSoFar = chain(lhsOriginal, rhs[0 .. i]);
auto ub = assumeSorted!less(sortedSoFar).upperBound(rhs[i]);
if (!ub.length) continue;
bringToFront(ub.release(), rhs[i .. i + 1]);
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 3 ];
int[] b = [ 4, 0, 6, 5 ];
// @@@BUG@@@ The call below should work
// completeSort(assumeSorted(a), b);
completeSort!("a < b", SwapStrategy.unstable, int[], int[])(
assumeSorted(a), b);
assert(a == [ 0, 1, 2 ]);
assert(b == [ 3, 4, 5, 6 ]);
}
// isSorted
/**
Checks whether a forward range is sorted according to the comparison
operation $(D less). Performs $(BIGOH r.length) evaluations of $(D
less).
Example:
----
int[] arr = [4, 3, 2, 1];
assert(!isSorted(arr));
sort(arr);
assert(isSorted(arr));
sort!("a > b")(arr);
assert(isSorted!("a > b")(arr));
----
*/
bool isSorted(alias less = "a < b", Range)(Range r) if (isForwardRange!(Range))
{
// @@@BUG@@@ Should work with inlined predicate
bool pred(ElementType!Range a, ElementType!Range b)
{
return binaryFun!less(b, a);
}
return findAdjacent!pred(r).empty;
}
// makeIndex
/**
Computes an index for $(D r) based on the comparison $(D less). The
index is a sorted array of pointers or indices into the original
range. This technique is similar to sorting, but it is more flexible
because (1) it allows "sorting" of immutable collections, (2) allows
binary search even if the original collection does not offer random
access, (3) allows multiple indexes, each on a different predicate,
and (4) may be faster when dealing with large objects. However, using
an index may also be slower under certain circumstances due to the
extra indirection, and is always larger than a sorting-based solution
because it needs space for the index in addition to the original
collection. The complexity is the same as $(D sort)'s.
$(D makeIndex) overwrites its second argument with the result, but
never reallocates it. If the second argument's length is less than
that of the range indexed, an exception is thrown.
The first overload of $(D makeIndex) writes to a range containing
pointers, and the second writes to a range containing offsets. The
first overload requires $(D Range) to be a forward range, and the
latter requires it to be a random-access range.
Example:
----
immutable(int[]) arr = [ 2, 3, 1, 5, 0 ];
// index using pointers
auto index1 = new immutable(int)*[arr.length];
makeIndex!("a < b")(arr, index1);
assert(isSorted!("*a < *b")(index1));
// index using offsets
auto index2 = new size_t[arr.length];
makeIndex!("a < b")(arr, index2);
assert(isSorted!
((size_t a, size_t b){ return arr[a] < arr[b];})
(index2));
----
*/
void makeIndex(
alias less = "a < b",
SwapStrategy ss = SwapStrategy.unstable,
Range,
RangeIndex)
(Range r, RangeIndex index)
if (isForwardRange!(Range) && isRandomAccessRange!(RangeIndex)
&& is(ElementType!(RangeIndex) : ElementType!(Range)*))
{
// assume collection already ordered
size_t i;
for (; !r.empty; r.popFront(), ++i)
index[i] = &(r.front);
enforce(index.length == i);
// sort the index
static bool indirectLess(ElementType!(RangeIndex) a,
ElementType!(RangeIndex) b)
{
return binaryFun!(less)(*a, *b);
}
sort!(indirectLess, ss)(index);
}
/// Ditto
void makeIndex(
alias less = "a < b",
SwapStrategy ss = SwapStrategy.unstable,
Range,
RangeIndex)
(Range r, RangeIndex index)
if (isRandomAccessRange!(Range) && !isInfinite!(Range) &&
isRandomAccessRange!(RangeIndex) && !isInfinite!(RangeIndex) &&
isIntegral!(ElementType!(RangeIndex)))
{
alias Unqual!(ElementType!RangeIndex) I;
enforce(r.length == index.length,
"r and index must be same length for makeIndex.");
static if(I.sizeof < size_t.sizeof)
{
enforce(r.length <= I.max, "Cannot create an index with " ~
"element type " ~ I.stringof ~ " with length " ~
to!string(r.length) ~ "."
);
}
for(I i = 0; i < r.length; ++i)
{
index[cast(size_t) i] = i;
}
// sort the index
bool indirectLess(ElementType!(RangeIndex) a, ElementType!(RangeIndex) b)
{
return binaryFun!(less)(r[cast(size_t) a], r[cast(size_t) b]);
}
sort!(indirectLess, ss)(index);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
immutable(int)[] arr = [ 2, 3, 1, 5, 0 ];
// index using pointers
auto index1 = new immutable(int)*[arr.length];
alias typeof(arr) ImmRange;
alias typeof(index1) ImmIndex;
static assert(isForwardRange!(ImmRange));
static assert(isRandomAccessRange!(ImmIndex));
static assert(!isIntegral!(ElementType!(ImmIndex)));
static assert(is(ElementType!(ImmIndex) : ElementType!(ImmRange)*));
makeIndex!("a < b")(arr, index1);
assert(isSorted!("*a < *b")(index1));
// index using offsets
auto index2 = new long[arr.length];
makeIndex(arr, index2);
assert(isSorted!
((long a, long b){
return arr[cast(size_t) a] < arr[cast(size_t) b];
})(index2));
// index strings using offsets
string[] arr1 = ["I", "have", "no", "chocolate"];
auto index3 = new byte[arr1.length];
makeIndex(arr1, index3);
assert(isSorted!
((byte a, byte b){ return arr1[a] < arr1[b];})
(index3));
}
/**
Specifies whether the output of certain algorithm is desired in sorted
format.
*/
enum SortOutput {
no, /// Don't sort output
yes, /// Sort output
}
void topNIndex(
alias less = "a < b",
SwapStrategy ss = SwapStrategy.unstable,
Range, RangeIndex)(Range r, RangeIndex index, SortOutput sorted = SortOutput.no)
if (isIntegral!(ElementType!(RangeIndex)))
{
if (index.empty) return;
enforce(ElementType!(RangeIndex).max >= index.length,
"Index type too small");
bool indirectLess(ElementType!(RangeIndex) a, ElementType!(RangeIndex) b)
{
return binaryFun!(less)(r[a], r[b]);
}
auto heap = BinaryHeap!(RangeIndex, indirectLess)(index, 0);
foreach (i; 0 .. r.length)
{
heap.conditionalInsert(cast(ElementType!RangeIndex) i);
}
if (sorted == SortOutput.yes)
{
while (!heap.empty) heap.removeFront();
}
}
void topNIndex(
alias less = "a < b",
SwapStrategy ss = SwapStrategy.unstable,
Range, RangeIndex)(Range r, RangeIndex index,
SortOutput sorted = SortOutput.no)
if (is(ElementType!(RangeIndex) == ElementType!(Range)*))
{
if (index.empty) return;
static bool indirectLess(const ElementType!(RangeIndex) a,
const ElementType!(RangeIndex) b)
{
return binaryFun!less(*a, *b);
}
auto heap = BinaryHeap!(RangeIndex, indirectLess)(index, 0);
foreach (i; 0 .. r.length)
{
heap.conditionalInsert(&r[i]);
}
if (sorted == SortOutput.yes)
{
while (!heap.empty) heap.removeFront();
}
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
{
int[] a = [ 10, 8, 9, 2, 4, 6, 7, 1, 3, 5 ];
int*[] b = new int*[5];
topNIndex!("a > b")(a, b, SortOutput.yes);
//foreach (e; b) writeln(*e);
assert(b == [ &a[0], &a[2], &a[1], &a[6], &a[5]]);
}
{
int[] a = [ 10, 8, 9, 2, 4, 6, 7, 1, 3, 5 ];
auto b = new ubyte[5];
topNIndex!("a > b")(a, b, SortOutput.yes);
//foreach (e; b) writeln(e, ":", a[e]);
assert(b == [ cast(ubyte) 0, cast(ubyte)2, cast(ubyte)1, cast(ubyte)6, cast(ubyte)5], text(b));
}
}
/+
// topNIndexImpl
// @@@BUG1904
/*private*/ void topNIndexImpl(
alias less,
bool sortAfter,
SwapStrategy ss,
SRange, TRange)(SRange source, TRange target)
{
alias binaryFun!(less) lessFun;
static assert(ss == SwapStrategy.unstable,
"Stable indexing not yet implemented");
alias Iterator!(SRange) SIter;
alias std.iterator.ElementType!(TRange) TElem;
enum usingInt = isIntegral!(TElem);
static if (usingInt)
{
enforce(source.length <= TElem.max,
"Numeric overflow at risk in computing topNIndexImpl");
}
// types and functions used within
SIter index2iter(TElem a)
{
static if (!usingInt)
return a;
else
return begin(source) + a;
}
bool indirectLess(TElem a, TElem b)
{
return lessFun(*index2iter(a), *index2iter(b));
}
void indirectCopy(SIter from, ref TElem to)
{
static if (!usingInt)
to = from;
else
to = cast(TElem)(from - begin(source));
}
// copy beginning of collection into the target
auto sb = begin(source), se = end(source),
tb = begin(target), te = end(target);
for (; sb != se; ++sb, ++tb)
{
if (tb == te) break;
indirectCopy(sb, *tb);
}
// if the index's size is same as the source size, just quicksort it
// otherwise, heap-insert stuff in it.
if (sb == se)
{
// everything in source is now in target... just sort the thing
static if (sortAfter) sort!(indirectLess, ss)(target);
}
else
{
// heap-insert
te = tb;
tb = begin(target);
target = range(tb, te);
makeHeap!(indirectLess)(target);
// add stuff to heap
for (; sb != se; ++sb)
{
if (!lessFun(*sb, *index2iter(*tb))) continue;
// copy the source over the smallest
indirectCopy(sb, *tb);
heapify!(indirectLess)(target, tb);
}
static if (sortAfter) sortHeap!(indirectLess)(target);
}
}
/**
topNIndex
*/
void topNIndex(
alias less,
SwapStrategy ss = SwapStrategy.unstable,
SRange, TRange)(SRange source, TRange target)
{
return .topNIndexImpl!(less, false, ss)(source, target);
}
/// Ditto
void topNIndex(
string less,
SwapStrategy ss = SwapStrategy.unstable,
SRange, TRange)(SRange source, TRange target)
{
return .topNIndexImpl!(binaryFun!(less), false, ss)(source, target);
}
// partialIndex
/**
Computes an index for $(D source) based on the comparison $(D less)
and deposits the result in $(D target). It is acceptable that $(D
target.length < source.length), in which case only the smallest $(D
target.length) elements in $(D source) get indexed. The target
provides a sorted "view" into $(D source). This technique is similar
to sorting and partial sorting, but it is more flexible because (1) it
allows "sorting" of immutable collections, (2) allows binary search
even if the original collection does not offer random access, (3)
allows multiple indexes, each on a different comparison criterion, (4)
may be faster when dealing with large objects. However, using an index
may also be slower under certain circumstances due to the extra
indirection, and is always larger than a sorting-based solution
because it needs space for the index in addition to the original
collection. The complexity is $(BIGOH source.length *
log(target.length)).
Two types of indexes are accepted. They are selected by simply passing
the appropriate $(D target) argument: $(OL $(LI Indexes of type $(D
Iterator!(Source)), in which case the index will be sorted with the
predicate $(D less(*a, *b));) $(LI Indexes of an integral type
(e.g. $(D size_t)), in which case the index will be sorted with the
predicate $(D less(source[a], source[b])).))
Example:
----
immutable arr = [ 2, 3, 1 ];
int* index[3];
partialIndex(arr, index);
assert(*index[0] == 1 && *index[1] == 2 && *index[2] == 3);
assert(isSorted!("*a < *b")(index));
----
*/
void partialIndex(
alias less,
SwapStrategy ss = SwapStrategy.unstable,
SRange, TRange)(SRange source, TRange target)
{
return .topNIndexImpl!(less, true, ss)(source, target);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
immutable arr = [ 2, 3, 1 ];
auto index = new immutable(int)*[3];
partialIndex!(binaryFun!("a < b"))(arr, index);
assert(*index[0] == 1 && *index[1] == 2 && *index[2] == 3);
assert(isSorted!("*a < *b")(index));
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
static bool less(int a, int b) { return a < b; }
{
string[] x = ([ "c", "a", "b", "d" ]).dup;
// test with integrals
auto index1 = new size_t[x.length];
partialIndex!(q{a < b})(x, index1);
assert(index1[0] == 1 && index1[1] == 2 && index1[2] == 0
&& index1[3] == 3);
// half-sized
index1 = new size_t[x.length / 2];
partialIndex!(q{a < b})(x, index1);
assert(index1[0] == 1 && index1[1] == 2);
// and with iterators
auto index = new string*[x.length];
partialIndex!(q{a < b})(x, index);
assert(isSorted!(q{*a < *b})(index));
assert(*index[0] == "a" && *index[1] == "b" && *index[2] == "c"
&& *index[3] == "d");
}
{
immutable arr = [ 2, 3, 1 ];
auto index = new immutable(int)*[arr.length];
partialIndex!(less)(arr, index);
assert(*index[0] == 1 && *index[1] == 2 && *index[2] == 3);
assert(isSorted!(q{*a < *b})(index));
}
// random data
auto b = rndstuff!(string)();
auto index = new string*[b.length];
partialIndex!("std.uni.toUpper(a) < std.uni.toUpper(b)")(b, index);
assert(isSorted!("std.uni.toUpper(*a) < std.uni.toUpper(*b)")(index));
// random data with indexes
auto index1 = new size_t[b.length];
bool cmp(string x, string y) { return std.uni.toUpper(x) < std.uni.toUpper(y); }
partialIndex!(cmp)(b, index1);
bool check(size_t x, size_t y) { return std.uni.toUpper(b[x]) < std.uni.toUpper(b[y]); }
assert(isSorted!(check)(index1));
}
// Commented out for now, needs reimplementation
// // schwartzMakeIndex
// /**
// Similar to $(D makeIndex) but using $(D schwartzSort) to sort the
// index.
// Example:
// ----
// string[] arr = [ "ab", "c", "Ab", "C" ];
// auto index = schwartzMakeIndex!(toUpper, less, SwapStrategy.stable)(arr);
// assert(*index[0] == "ab" && *index[1] == "Ab"
// && *index[2] == "c" && *index[2] == "C");
// assert(isSorted!("toUpper(*a) < toUpper(*b)")(index));
// ----
// */
// Iterator!(Range)[] schwartzMakeIndex(
// alias transform,
// alias less,
// SwapStrategy ss = SwapStrategy.unstable,
// Range)(Range r)
// {
// alias Iterator!(Range) Iter;
// auto result = new Iter[r.length];
// // assume collection already ordered
// size_t i = 0;
// foreach (it; begin(r) .. end(r))
// {
// result[i++] = it;
// }
// // sort the index
// alias typeof(transform(*result[0])) Transformed;
// static bool indirectLess(Transformed a, Transformed b)
// {
// return less(a, b);
// }
// static Transformed indirectTransform(Iter a)
// {
// return transform(*a);
// }
// schwartzSort!(indirectTransform, less, ss)(result);
// return result;
// }
// /// Ditto
// Iterator!(Range)[] schwartzMakeIndex(
// alias transform,
// string less = q{a < b},
// SwapStrategy ss = SwapStrategy.unstable,
// Range)(Range r)
// {
// return .schwartzMakeIndex!(
// transform, binaryFun!(less), ss, Range)(r);
// }
// version (wyda) unittest
// {
// string[] arr = [ "D", "ab", "c", "Ab", "C" ];
// auto index = schwartzMakeIndex!(toUpper, "a < b",
// SwapStrategy.stable)(arr);
// assert(isSorted!(q{toUpper(*a) < toUpper(*b)})(index));
// assert(*index[0] == "ab" && *index[1] == "Ab"
// && *index[2] == "c" && *index[3] == "C");
// // random data
// auto b = rndstuff!(string)();
// auto index1 = schwartzMakeIndex!(toUpper)(b);
// assert(isSorted!("toUpper(*a) < toUpper(*b)")(index1));
// }
+/
// canFind
/**
Returns $(D true) if and only if $(D value) can be found in $(D
range). Performs $(BIGOH r.length) evaluations of $(D pred). */
bool canFind(alias pred = "a == b", Range, V)(Range range, V value)
if (is(typeof(find!pred(range, value))))
{
return !find!pred(range, value).empty;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto a = rndstuff!(int)();
if (a.length)
{
auto b = a[a.length / 2];
assert(canFind(a, b));
}
}
/**
Forwards to $(D any) for backwards compatibility.
$(RED Scheduled for deprecation in August 2012. Please use $(D any) instead.)
*/
bool canFind(alias pred, Range)(Range range)
{
return any!pred(range);
}
/**
Returns $(D true) if and only if a value $(D v) satisfying the
predicate $(D pred) can be found in the forward range $(D
range). Performs $(BIGOH r.length) evaluations of $(D pred).
*/
bool any(alias pred, Range)(Range range)
if (is(typeof(find!pred(range))))
{
return !find!pred(range).empty;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto a = [ 1, 2, 0, 4 ];
assert(canFind!"a == 2"(a));
assert(any!"a == 2"(a));
}
/**
Returns $(D true) if and only if all values in $(D range) satisfy the
predicate $(D pred). Performs $(BIGOH r.length) evaluations of $(D pred).
Examples:
---
assert(all!"a & 1"([1, 3, 5, 7, 9]));
assert(!all!"a & 1"([1, 2, 3, 5, 7, 9]));
---
*/
bool all(alias pred, R)(R range)
if(isInputRange!R && is(typeof(unaryFun!pred(range.front))))
{
return find!(not!(unaryFun!pred))(range).empty;
}
unittest
{
assert(all!"a & 1"([1, 3, 5, 7, 9]));
assert(!all!"a & 1"([1, 2, 3, 5, 7, 9]));
}
// Scheduled for deprecation. Use std.range.SortedRange.canFind.
bool canFindSorted(alias pred = "a < b", Range, V)(Range range, V value) {
pragma(msg, "std.algorithm.canFindSorted is scheduled for " ~
"deprecation. Use std.range.SortedRange.canFind instead.");
return assumeSorted!pred(range).canFind!V(value);
}
// Scheduled for deprecation. Use std.range.SortedRange.lowerBound.
Range lowerBound(alias pred = "a < b", Range, V)(Range range, V value) {
pragma(msg, "std.algorithm.lowerBound is scheduled for " ~
"deprecation. Use std.range.SortedRange.lowerBound instead.");
return assumeSorted!pred(range).lowerBound!V(value).release;
}
// Scheduled for deprecation. Use std.range.SortedRange.upperBound.
Range upperBound(alias pred = "a < b", Range, V)(Range range, V value) {
pragma(msg, "std.algorithm.upperBound is scheduled for " ~
"deprecation. Use std.range.SortedRange.upperBound instead.");
return assumeSorted!pred(range).upperBound!V(value).release;
}
// Scheduled for deprecation. Use std.range.SortedRange.equalRange.
Range equalRange(alias pred = "a < b", Range, V)(Range range, V value) {
pragma(msg, "std.algorithm.equalRange is scheduled for " ~
"deprecation. Use std.range.SortedRange.equalRange instead.");
return assumeSorted!pred(range).equalRange!V(value).release;
}
/**
Copies the top $(D n) elements of the input range $(D source) into the
random-access range $(D target), where $(D n =
target.length). Elements of $(D source) are not touched. If $(D
sorted) is $(D true), the target is sorted. Otherwise, the target
respects the $(WEB en.wikipedia.org/wiki/Binary_heap, heap property).
Example:
----
int[] a = [ 10, 16, 2, 3, 1, 5, 0 ];
int[] b = new int[3];
topNCopy(a, b, true);
assert(b == [ 0, 1, 2 ]);
----
*/
TRange topNCopy(alias less = "a < b", SRange, TRange)
(SRange source, TRange target, SortOutput sorted = SortOutput.no)
if (isInputRange!(SRange) && isRandomAccessRange!(TRange)
&& hasLength!(TRange) && hasSlicing!(TRange))
{
if (target.empty) return target;
auto heap = BinaryHeap!(TRange, less)(target, 0);
foreach (e; source) heap.conditionalInsert(e);
auto result = target[0 .. heap.length];
if (sorted == SortOutput.yes)
{
while (!heap.empty) heap.removeFront();
}
return result;
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 10, 16, 2, 3, 1, 5, 0 ];
int[] b = new int[3];
topNCopy(a, b, SortOutput.yes);
assert(b == [ 0, 1, 2 ]);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
auto r = Random(unpredictableSeed);
sizediff_t[] a = new sizediff_t[uniform(1, 1000, r)];
foreach (i, ref e; a) e = i;
randomShuffle(a, r);
auto n = uniform(0, a.length, r);
sizediff_t[] b = new sizediff_t[n];
topNCopy!(binaryFun!("a < b"))(a, b, SortOutput.yes);
assert(isSorted!(binaryFun!("a < b"))(b));
}
/**
Lazily computes the union of two or more ranges $(D rs). The ranges
are assumed to be sorted by $(D less). Elements in the output are not
unique; the length of the output is the sum of the lengths of the
inputs. (The $(D length) member is offered if all ranges also have
length.) The element types of all ranges must have a common type.
Example:
----
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 10 ];
assert(setUnion(a, b).length == a.length + b.length);
assert(equal(setUnion(a, b), [0, 1, 1, 2, 2, 4, 4, 5, 7, 7, 8, 9][]));
assert(equal(setUnion(a, c, b),
[0, 1, 1, 2, 2, 4, 4, 5, 7, 7, 8, 9, 10][]));
----
*/
struct SetUnion(alias less = "a < b", Rs...) if (allSatisfy!(isInputRange, Rs))
{
private:
Rs _r;
alias binaryFun!(less) comp;
uint _crt;
void adjustPosition(uint candidate = 0)()
{
static if (candidate == Rs.length)
{
_crt = _crt.max;
}
else
{
if (_r[candidate].empty)
{
adjustPosition!(candidate + 1)();
return;
}
foreach (i, U; Rs[candidate + 1 .. $])
{
enum j = candidate + i + 1;
if (_r[j].empty) continue;
if (comp(_r[j].front, _r[candidate].front))
{
// a new candidate was found
adjustPosition!(j)();
return;
}
}
// Found a successful candidate
_crt = candidate;
}
}
public:
alias CommonType!(staticMap!(.ElementType, Rs)) ElementType;
this(Rs rs)
{
this._r = rs;
adjustPosition();
}
@property bool empty()
{
return _crt == _crt.max;
}
void popFront()
{
// Assumes _crt is correct
assert(!empty);
foreach (i, U; Rs)
{
if (i < _crt) continue;
// found _crt
assert(!_r[i].empty);
_r[i].popFront();
adjustPosition();
return;
}
assert(false);
}
@property ElementType front()
{
assert(!empty);
// Assume _crt is correct
foreach (i, U; Rs)
{
if (i < _crt) continue;
assert(!_r[i].empty);
return _r[i].front;
}
assert(false);
}
static if(allSatisfy!(isForwardRange, Rs))
{
@property typeof(this) save()
{
auto ret = this;
foreach(ti, elem; _r)
{
ret._r[ti] = elem.save;
}
return ret;
}
}
static if (allSatisfy!(hasLength, Rs))
{
@property size_t length()
{
size_t result;
foreach (i, U; Rs)
{
result += _r[i].length;
}
return result;
}
alias length opDollar;
}
}
/// Ditto
SetUnion!(less, Rs) setUnion(alias less = "a < b", Rs...)
(Rs rs)
{
return typeof(return)(rs);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 10 ];
//foreach (e; setUnion(a, b)) writeln(e);
assert(setUnion(a, b).length == a.length + b.length);
assert(equal(setUnion(a, b), [0, 1, 1, 2, 2, 4, 4, 5, 7, 7, 8, 9][]));
assert(equal(setUnion(a, c, b),
[0, 1, 1, 2, 2, 4, 4, 5, 7, 7, 8, 9, 10][]));
static assert(isForwardRange!(typeof(setUnion(a, b))));
}
/**
Lazily computes the intersection of two or more input ranges $(D
rs). The ranges are assumed to be sorted by $(D less). The element
types of all ranges must have a common type.
Example:
----
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 0, 1, 4, 5, 7, 8 ];
assert(equal(setIntersection(a, a), a));
assert(equal(setIntersection(a, b), [1, 2, 4, 7][]));
assert(equal(setIntersection(a, b, c), [1, 4, 7][]));
----
*/
struct SetIntersection(alias less = "a < b", Rs...)
if (allSatisfy!(isInputRange, Rs))
{
static assert(Rs.length == 2);
private:
Rs _input;
alias binaryFun!(less) comp;
alias CommonType!(staticMap!(.ElementType, Rs)) ElementType;
void adjustPosition()
{
// Positions to the first two elements that are equal
while (!empty)
{
if (comp(_input[0].front, _input[1].front))
{
_input[0].popFront();
}
else if (comp(_input[1].front, _input[0].front))
{
_input[1].popFront();
}
else
{
break;
}
}
}
public:
this(Rs input)
{
this._input = input;
// position to the first element
adjustPosition();
}
@property bool empty()
{
foreach (i, U; Rs)
{
if (_input[i].empty) return true;
}
return false;
}
void popFront()
{
assert(!empty);
assert(!comp(_input[0].front, _input[1].front)
&& !comp(_input[1].front, _input[0].front));
_input[0].popFront();
_input[1].popFront();
adjustPosition();
}
@property ElementType front()
{
assert(!empty);
return _input[0].front;
}
static if(allSatisfy!(isForwardRange, Rs))
{
@property typeof(this) save()
{
auto ret = this;
foreach(ti, elem; _input)
{
ret._input[ti] = elem.save;
}
return ret;
}
}
}
/// Ditto
SetIntersection!(less, Rs) setIntersection(alias less = "a < b", Rs...)
(Rs ranges)
if (allSatisfy!(isInputRange, Rs))
{
return typeof(return)(ranges);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 0, 1, 4, 5, 7, 8 ];
//foreach (e; setIntersection(a, b, c)) writeln(e);
assert(equal(setIntersection(a, b), [1, 2, 4, 7][]));
assert(equal(setIntersection(a, a), a));
static assert(isForwardRange!(typeof(setIntersection(a, a))));
// assert(equal(setIntersection(a, b, b, a), [1, 2, 4, 7][]));
// assert(equal(setIntersection(a, b, c), [1, 4, 7][]));
// assert(equal(setIntersection(a, c, b), [1, 4, 7][]));
// assert(equal(setIntersection(b, a, c), [1, 4, 7][]));
// assert(equal(setIntersection(b, c, a), [1, 4, 7][]));
// assert(equal(setIntersection(c, a, b), [1, 4, 7][]));
// assert(equal(setIntersection(c, b, a), [1, 4, 7][]));
}
/**
Lazily computes the difference of $(D r1) and $(D r2). The two ranges
are assumed to be sorted by $(D less). The element types of the two
ranges must have a common type.
Example:
----
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
assert(equal(setDifference(a, b), [5, 9][]));
----
*/
struct SetDifference(alias less = "a < b", R1, R2)
if (isInputRange!(R1) && isInputRange!(R2))
{
private:
R1 r1;
R2 r2;
alias binaryFun!(less) comp;
void adjustPosition()
{
while (!r1.empty)
{
if (r2.empty || comp(r1.front, r2.front)) break;
if (comp(r2.front, r1.front))
{
r2.popFront();
}
else
{
// both are equal
r1.popFront();
r2.popFront();
}
}
}
public:
this(R1 r1, R2 r2)
{
this.r1 = r1;
this.r2 = r2;
// position to the first element
adjustPosition();
}
void popFront()
{
r1.popFront();
adjustPosition();
}
@property ElementType!(R1) front()
{
assert(!empty);
return r1.front;
}
static if(isForwardRange!R1 && isForwardRange!R2)
{
@property typeof(this) save()
{
auto ret = this;
ret.r1 = r1.save;
ret.r2 = r2.save;
return ret;
}
}
@property bool empty() { return r1.empty; }
}
/// Ditto
SetDifference!(less, R1, R2) setDifference(alias less = "a < b", R1, R2)
(R1 r1, R2 r2)
{
return typeof(return)(r1, r2);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
//foreach (e; setDifference(a, b)) writeln(e);
assert(equal(setDifference(a, b), [5, 9][]));
static assert(isForwardRange!(typeof(setDifference(a, b))));
}
/**
Lazily computes the symmetric difference of $(D r1) and $(D r2),
i.e. the elements that are present in exactly one of $(D r1) and $(D
r2). The two ranges are assumed to be sorted by $(D less), and the
output is also sorted by $(D less). The element types of the two
ranges must have a common type.
Example:
----
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
assert(equal(setSymmetricDifference(a, b), [0, 5, 8, 9][]));
----
*/
struct SetSymmetricDifference(alias less = "a < b", R1, R2)
if (isInputRange!(R1) && isInputRange!(R2))
{
private:
R1 r1;
R2 r2;
//bool usingR2;
alias binaryFun!(less) comp;
void adjustPosition()
{
while (!r1.empty && !r2.empty)
{
if (comp(r1.front, r2.front) || comp(r2.front, r1.front))
{
break;
}
// equal, pop both
r1.popFront();
r2.popFront();
}
}
public:
this(R1 r1, R2 r2)
{
this.r1 = r1;
this.r2 = r2;
// position to the first element
adjustPosition();
}
void popFront()
{
assert(!empty);
if (r1.empty) r2.popFront();
else if (r2.empty) r1.popFront();
else
{
// neither is empty
if (comp(r1.front, r2.front))
{
r1.popFront();
}
else
{
assert(comp(r2.front, r1.front));
r2.popFront();
}
}
adjustPosition();
}
@property ElementType!(R1) front()
{
assert(!empty);
if (r2.empty || !r1.empty && comp(r1.front, r2.front))
{
return r1.front;
}
assert(r1.empty || comp(r2.front, r1.front));
return r2.front;
}
static if(isForwardRange!R1 && isForwardRange!R2)
{
@property typeof(this) save()
{
auto ret = this;
ret.r1 = r1.save;
ret.r2 = r2.save;
return ret;
}
}
ref auto opSlice() { return this; }
@property bool empty() { return r1.empty && r2.empty; }
}
/// Ditto
SetSymmetricDifference!(less, R1, R2)
setSymmetricDifference(alias less = "a < b", R1, R2)
(R1 r1, R2 r2)
{
return typeof(return)(r1, r2);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
//foreach (e; setSymmetricDifference(a, b)) writeln(e);
assert(equal(setSymmetricDifference(a, b), [0, 5, 8, 9][]));
static assert(isForwardRange!(typeof(setSymmetricDifference(a, b))));
}
// Internal random array generators
version(unittest)
{
private enum size_t maxArraySize = 50;
private enum size_t minArraySize = maxArraySize - 1;
private string[] rndstuff(T : string)()
{
static Random rnd;
static bool first = true;
if (first)
{
rnd = Random(unpredictableSeed);
first = false;
}
string[] result =
new string[uniform(minArraySize, maxArraySize, rnd)];
string alpha = "abcdefghijABCDEFGHIJ";
foreach (ref s; result)
{
foreach (i; 0 .. uniform(0u, 20u, rnd))
{
auto j = uniform(0, alpha.length - 1, rnd);
s ~= alpha[j];
}
}
return result;
}
private int[] rndstuff(T : int)()
{
static Random rnd;
static bool first = true;
if (first)
{
rnd = Random(unpredictableSeed);
first = false;
}
int[] result = new int[uniform(minArraySize, maxArraySize, rnd)];
foreach (ref i; result)
{
i = uniform(-100, 100, rnd);
}
return result;
}
private double[] rndstuff(T : double)()
{
double[] result;
foreach (i; rndstuff!(int)())
{
result ~= i / 50.;
}
return result;
}
}
// NWayUnion
/**
Computes the union of multiple sets. The input sets are passed as a
range of ranges and each is assumed to be sorted by $(D
less). Computation is done lazily, one union element at a time. The
complexity of one $(D popFront) operation is $(BIGOH
log(ror.length)). However, the length of $(D ror) decreases as ranges
in it are exhausted, so the complexity of a full pass through $(D
NWayUnion) is dependent on the distribution of the lengths of ranges
contained within $(D ror). If all ranges have the same length $(D n)
(worst case scenario), the complexity of a full pass through $(D
NWayUnion) is $(BIGOH n * ror.length * log(ror.length)), i.e., $(D
log(ror.length)) times worse than just spanning all ranges in
turn. The output comes sorted (unstably) by $(D less).
Warning: Because $(D NWayUnion) does not allocate extra memory, it
will leave $(D ror) modified. Namely, $(D NWayUnion) assumes ownership
of $(D ror) and discretionarily swaps and advances elements of it. If
you want $(D ror) to preserve its contents after the call, you may
want to pass a duplicate to $(D NWayUnion) (and perhaps cache the
duplicate in between calls).
Example:
----
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto witness = [
1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8
];
assert(equal(nWayUnion(a), witness[]));
----
*/
struct NWayUnion(alias less, RangeOfRanges)
{
private alias .ElementType!(.ElementType!RangeOfRanges) ElementType;
private alias binaryFun!less comp;
private RangeOfRanges _ror;
static bool compFront(.ElementType!RangeOfRanges a,
.ElementType!RangeOfRanges b)
{
// revert comparison order so we get the smallest elements first
return comp(b.front, a.front);
}
BinaryHeap!(RangeOfRanges, compFront) _heap;
this(RangeOfRanges ror)
{
// Preemptively get rid of all empty ranges in the input
// No need for stability either
_ror = remove!("a.empty", SwapStrategy.unstable)(ror);
//Build the heap across the range
_heap.acquire(_ror);
}
@property bool empty() { return _ror.empty; }
@property ref ElementType front()
{
return _heap.front.front;
}
void popFront()
{
_heap.removeFront();
// let's look at the guy just popped
_ror.back.popFront();
if (_ror.back.empty)
{
_ror.popBack();
// nothing else to do: the empty range is not in the
// heap and not in _ror
return;
}
// Put the popped range back in the heap
_heap.conditionalInsert(_ror.back) || assert(false);
}
}
/// Ditto
NWayUnion!(less, RangeOfRanges) nWayUnion
(alias less = "a < b", RangeOfRanges)
(RangeOfRanges ror)
{
return typeof(return)(ror);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto witness = [
1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8
];
//foreach (e; nWayUnion(a)) writeln(e);
assert(equal(nWayUnion(a), witness[]));
}
// largestPartialIntersection
/**
Given a range of sorted forward ranges $(D ror), copies to $(D tgt)
the elements that are common to most ranges, along with their number
of occurrences. All ranges in $(D ror) are assumed to be sorted by $(D
less). Only the most frequent $(D tgt.length) elements are returned.
Example:
----
// Figure which number can be found in most arrays of the set of
// arrays below.
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto b = new Tuple!(double, uint)[1];
largestPartialIntersection(a, b);
// First member is the item, second is the occurrence count
assert(b[0] == tuple(7.0, 4u));
----
$(D 7.0) is the correct answer because it occurs in $(D 4) out of the
$(D 5) inputs, more than any other number. The second member of the
resulting tuple is indeed $(D 4) (recording the number of occurrences
of $(D 7.0)). If more of the top-frequent numbers are needed, just
create a larger $(D tgt) range. In the axample above, creating $(D b)
with length $(D 2) yields $(D tuple(1.0, 3u)) in the second position.
The function $(D largestPartialIntersection) is useful for
e.g. searching an $(LUCKY inverted index) for the documents most
likely to contain some terms of interest. The complexity of the search
is $(BIGOH n * log(tgt.length)), where $(D n) is the sum of lengths of
all input ranges. This approach is faster than keeping an associative
array of the occurrences and then selecting its top items, and also
requires less memory ($(D largestPartialIntersection) builds its
result directly in $(D tgt) and requires no extra memory).
Warning: Because $(D largestPartialIntersection) does not allocate
extra memory, it will leave $(D ror) modified. Namely, $(D
largestPartialIntersection) assumes ownership of $(D ror) and
discretionarily swaps and advances elements of it. If you want $(D
ror) to preserve its contents after the call, you may want to pass a
duplicate to $(D largestPartialIntersection) (and perhaps cache the
duplicate in between calls).
*/
void largestPartialIntersection
(alias less = "a < b", RangeOfRanges, Range)
(RangeOfRanges ror, Range tgt, SortOutput sorted = SortOutput.no)
{
struct UnitWeights
{
static int opIndex(ElementType!(ElementType!RangeOfRanges)) { return 1; }
}
return largestPartialIntersectionWeighted!less(ror, tgt, UnitWeights(),
sorted);
}
// largestPartialIntersectionWeighted
/**
Similar to $(D largestPartialIntersection), but associates a weight
with each distinct element in the intersection.
Example:
----
// Figure which number can be found in most arrays of the set of
// arrays below, with specific per-element weights
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto b = new Tuple!(double, uint)[1];
double[double] weights = [ 1:1.2, 4:2.3, 7:1.1, 8:1.1 ];
largestPartialIntersectionWeighted(a, b, weights);
// First member is the item, second is the occurrence count
assert(b[0] == tuple(4.0, 2u));
----
The correct answer in this case is $(D 4.0), which, although only
appears two times, has a total weight $(D 4.6) (three times its weight
$(D 2.3)). The value $(D 7) is weighted with $(D 1.1) and occurs four
times for a total weight $(D 4.4).
*/
void largestPartialIntersectionWeighted
(alias less = "a < b", RangeOfRanges, Range, WeightsAA)
(RangeOfRanges ror, Range tgt, WeightsAA weights, SortOutput sorted = SortOutput.no)
{
if (tgt.empty) return;
alias ElementType!Range InfoType;
bool heapComp(InfoType a, InfoType b)
{
return weights[a[0]] * a[1] > weights[b[0]] * b[1];
}
topNCopy!heapComp(group(nWayUnion!less(ror)), tgt, sorted);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto b = new Tuple!(double, uint)[2];
largestPartialIntersection(a, b, SortOutput.yes);
//sort(b);
//writeln(b);
assert(b == [ tuple(7., 4u), tuple(1., 3u) ][], text(b));
assert(a[0].empty);
}
unittest
{
debug(std_algorithm) scope(success)
writeln("unittest @", __FILE__, ":", __LINE__, " done.");
string[][] a =
[
[ "1", "4", "7", "8" ],
[ "1", "7" ],
[ "1", "7", "8"],
[ "4" ],
[ "7" ],
];
auto b = new Tuple!(string, uint)[2];
largestPartialIntersection(a, b, SortOutput.yes);
//writeln(b);
assert(b == [ tuple("7", 4u), tuple("1", 3u) ][], text(b));
}
unittest
{
//scope(success) writeln("unittest @", __FILE__, ":", __LINE__, " done.");
// Figure which number can be found in most arrays of the set of
// arrays below, with specific per-element weights
double[][] a =
[
[ 1, 4, 7, 8 ],
[ 1, 7 ],
[ 1, 7, 8],
[ 4 ],
[ 7 ],
];
auto b = new Tuple!(double, uint)[1];
double[double] weights = [ 1:1.2, 4:2.3, 7:1.1, 8:1.1 ];
largestPartialIntersectionWeighted(a, b, weights);
// First member is the item, second is the occurrence count
//writeln(b[0]);
assert(b[0] == tuple(4.0, 2u));
}
| D |
a condition characterized by abnormal deposits of melanin (especially in the skin)
| D |
// Written in the D programming language.
/**
Bit-level manipulation facilities.
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE,
$(TR $(TH Category) $(TH Functions))
$(TR $(TD Bit constructs) $(TD
$(LREF BitArray)
$(LREF bitfields)
$(LREF bitsSet)
))
$(TR $(TD Endianness conversion) $(TD
$(LREF bigEndianToNative)
$(LREF littleEndianToNative)
$(LREF nativeToBigEndian)
$(LREF nativeToLittleEndian)
$(LREF swapEndian)
))
$(TR $(TD Integral ranges) $(TD
$(LREF append)
$(LREF peek)
$(LREF read)
$(LREF write)
))
$(TR $(TD Floating-Point manipulation) $(TD
$(LREF DoubleRep)
$(LREF FloatRep)
))
$(TR $(TD Tagging) $(TD
$(LREF taggedClassRef)
$(LREF taggedPointer)
))
))
Copyright: Copyright The D Language Foundation 2007 - 2011.
License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP digitalmars.com, Walter Bright),
$(HTTP erdani.org, Andrei Alexandrescu),
$(HTTP jmdavisprog.com, Jonathan M Davis),
Alex Rønne Petersen,
Damian Ziemba,
Amaury SECHET
Source: $(PHOBOSSRC std/bitmanip.d)
*/
/*
Copyright The D Language Foundation 2007 - 2012.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.bitmanip;
import std.range.primitives;
public import std.system : Endian;
import std.traits;
private string myToString(ulong n) pure @safe
{
import core.internal.string : UnsignedStringBuf, unsignedToTempString;
UnsignedStringBuf buf;
auto s = unsignedToTempString(n, buf);
// pure allows implicit cast to string
return s ~ (n > uint.max ? "UL" : "U");
}
@safe pure unittest
{
assert(myToString(5) == "5U");
assert(myToString(uint.max) == "4294967295U");
assert(myToString(uint.max + 1UL) == "4294967296UL");
}
private template createAccessors(
string store, T, string name, size_t len, size_t offset)
{
static if (!name.length)
{
// No need to create any accessor
enum createAccessors = "";
}
else static if (len == 0)
{
// Fields of length 0 are always zero
enum createAccessors = "enum "~T.stringof~" "~name~" = 0;\n";
}
else
{
enum ulong
maskAllElse = ((~0uL) >> (64 - len)) << offset,
signBitCheck = 1uL << (len - 1);
static if (T.min < 0)
{
enum long minVal = -(1uL << (len - 1));
enum ulong maxVal = (1uL << (len - 1)) - 1;
alias UT = Unsigned!(T);
enum UT extendSign = cast(UT)~((~0uL) >> (64 - len));
}
else
{
enum ulong minVal = 0;
enum ulong maxVal = (~0uL) >> (64 - len);
enum extendSign = 0;
}
static if (is(T == bool))
{
enum createAccessors =
// getter
"@property bool " ~ name ~ "() @safe pure nothrow @nogc const { return "
~"("~store~" & "~myToString(maskAllElse)~") != 0;}\n"
// setter
~"@property void " ~ name ~ "(bool v) @safe pure nothrow @nogc { "
~"if (v) "~store~" |= "~myToString(maskAllElse)~";"
~"else "~store~" &= cast(typeof("~store~"))(-1-cast(typeof("~store~"))"~myToString(maskAllElse)~");}\n";
}
else
{
// getter
enum createAccessors = "@property "~T.stringof~" "~name~"() @safe pure nothrow @nogc const { auto result = "
~"("~store~" & "
~ myToString(maskAllElse) ~ ") >>"
~ myToString(offset) ~ ";"
~ (T.min < 0
? "if (result >= " ~ myToString(signBitCheck)
~ ") result |= " ~ myToString(extendSign) ~ ";"
: "")
~ " return cast("~T.stringof~") result;}\n"
// setter
~"@property void "~name~"("~T.stringof~" v) @safe pure nothrow @nogc { "
~"assert(v >= "~name~`_min, "Value is smaller than the minimum value of bitfield '`~name~`'"); `
~"assert(v <= "~name~`_max, "Value is greater than the maximum value of bitfield '`~name~`'"); `
~store~" = cast(typeof("~store~"))"
~" (("~store~" & (-1-cast(typeof("~store~"))"~myToString(maskAllElse)~"))"
~" | ((cast(typeof("~store~")) v << "~myToString(offset)~")"
~" & "~myToString(maskAllElse)~"));}\n"
// constants
~"enum "~T.stringof~" "~name~"_min = cast("~T.stringof~")"
~myToString(minVal)~"; "
~" enum "~T.stringof~" "~name~"_max = cast("~T.stringof~")"
~myToString(maxVal)~"; ";
}
}
}
private template createStoreName(Ts...)
{
static if (Ts.length < 2)
enum createStoreName = "_bf";
else
enum createStoreName = "_" ~ Ts[1] ~ createStoreName!(Ts[3 .. $]);
}
private template createStorageAndFields(Ts...)
{
enum Name = createStoreName!Ts;
enum Size = sizeOfBitField!Ts;
static if (Size == ubyte.sizeof * 8)
alias StoreType = ubyte;
else static if (Size == ushort.sizeof * 8)
alias StoreType = ushort;
else static if (Size == uint.sizeof * 8)
alias StoreType = uint;
else static if (Size == ulong.sizeof * 8)
alias StoreType = ulong;
else
{
import std.conv : to;
static assert(false, "Field widths must sum to 8, 16, 32, or 64, not " ~ to!string(Size));
alias StoreType = ulong; // just to avoid another error msg
}
enum createStorageAndFields
= "private " ~ StoreType.stringof ~ " " ~ Name ~ ";"
~ createFields!(Name, 0, Ts);
}
private template createFields(string store, size_t offset, Ts...)
{
static if (Ts.length > 0)
enum createFields
= createAccessors!(store, Ts[0], Ts[1], Ts[2], offset)
~ createFields!(store, offset + Ts[2], Ts[3 .. $]);
else
enum createFields = "";
}
private ulong getBitsForAlign(ulong a)
{
ulong bits = 0;
while ((a & 0x01) == 0)
{
bits++;
a >>= 1;
}
assert(a == 1, "alignment is not a power of 2");
return bits;
}
private template createReferenceAccessor(string store, T, ulong bits, string name)
{
enum storage = "private void* " ~ store ~ "_ptr;\n";
enum storage_accessor = "@property ref size_t " ~ store ~ "() return @trusted pure nothrow @nogc const { "
~ "return *cast(size_t*) &" ~ store ~ "_ptr;}\n"
~ "@property void " ~ store ~ "(size_t v) @trusted pure nothrow @nogc { "
~ "" ~ store ~ "_ptr = cast(void*) v;}\n";
enum mask = (1UL << bits) - 1;
// getter
enum ref_accessor = "@property "~T.stringof~" "~name~"() @trusted pure nothrow @nogc const { auto result = "
~ "("~store~" & "~myToString(~mask)~"); "
~ "return cast("~T.stringof~") cast(void*) result;}\n"
// setter
~"@property void "~name~"("~T.stringof~" v) @trusted pure nothrow @nogc { "
~"assert(((cast(typeof("~store~")) cast(void*) v) & "~myToString(mask)
~`) == 0, "Value not properly aligned for '`~name~`'"); `
~store~" = cast(typeof("~store~"))"
~" (("~store~" & (cast(typeof("~store~")) "~myToString(mask)~"))"
~" | ((cast(typeof("~store~")) cast(void*) v) & (cast(typeof("~store~")) "~myToString(~mask)~")));}\n";
enum createReferenceAccessor = storage ~ storage_accessor ~ ref_accessor;
}
private template sizeOfBitField(T...)
{
static if (T.length < 2)
enum sizeOfBitField = 0;
else
enum sizeOfBitField = T[2] + sizeOfBitField!(T[3 .. $]);
}
private template createTaggedReference(T, ulong a, string name, Ts...)
{
static assert(
sizeOfBitField!Ts <= getBitsForAlign(a),
"Fields must fit in the bits know to be zero because of alignment."
);
enum StoreName = createStoreName!(T, name, 0, Ts);
enum createTaggedReference
= createReferenceAccessor!(StoreName, T, sizeOfBitField!Ts, name)
~ createFields!(StoreName, 0, Ts, size_t, "", T.sizeof * 8 - sizeOfBitField!Ts);
}
/**
Allows creating `bitfields` inside `structs`, `classes` and `unions`.
A `bitfield` consists of one or more entries with a fixed number of
bits reserved for each of the entries. The types of the entries can
be `bool`s, integral types or enumerated types, arbitrarily mixed.
The most efficient type to store in `bitfields` is `bool`, followed
by unsigned types, followed by signed types.
Each non-`bool` entry of the `bitfield` will be represented by the
number of bits specified by the user. The minimum and the maximum
numbers that represent this domain can be queried by using the name
of the variable followed by `_min` or `_max`.
Limitation: The number of bits in a `bitfield` is limited to 8, 16,
32 or 64. If padding is needed, an entry should be explicitly
allocated with an empty name.
Implementation_details: `Bitfields` are internally stored in an
`ubyte`, `ushort`, `uint` or `ulong` depending on the number of bits
used. The bits are filled in the order given by the parameters,
starting with the lowest significant bit. The name of the (private)
variable used for saving the `bitfield` is created by a prefix `_bf`
and concatenating all of the variable names, each preceded by an
underscore.
Params: T = A list of template parameters divided into chunks of 3
items. Each chunk consists (in this order) of a type, a
name and a number. Together they define an entry
of the `bitfield`: a variable of the given type and name,
which can hold as many bits as the number denotes.
Returns: A string that can be used in a `mixin` to add the `bitfield`.
See_Also: $(REF BitFlags, std,typecons)
*/
string bitfields(T...)()
{
import std.conv : to;
static assert(T.length % 3 == 0,
"Wrong number of arguments (" ~ to!string(T.length) ~ "): Must be a multiple of 3");
static foreach (i, ARG; T)
{
static if (i % 3 == 0)
static assert(is (typeof({ARG tmp = cast (ARG)0; if (ARG.min < 0) {} }())),
"Integral type or `bool` expected, found " ~ ARG.stringof);
// would be nice to check for valid variable names too
static if (i % 3 == 1)
static assert(is (typeof(ARG) == string),
"Variable name expected, found " ~ ARG.stringof);
static if (i % 3 == 2)
{
static assert(is (typeof({ulong tmp = ARG;}())),
"Integral value expected, found " ~ ARG.stringof);
static if (T[i-1] != "")
{
static assert(!is (T[i-2] : bool) || ARG <= 1,
"Type `bool` is only allowed for single-bit fields");
static assert(ARG >= 0 && ARG <= T[i-2].sizeof * 8,
"Wrong size of bitfield: " ~ ARG.stringof);
}
}
}
return createStorageAndFields!T;
}
/**
Create a `bitfield` pack of eight bits, which fit in
one `ubyte`. The `bitfields` are allocated starting from the
least significant bit, i.e. `x` occupies the two least significant bits
of the `bitfields` storage.
*/
@safe unittest
{
struct A
{
int a;
mixin(bitfields!(
uint, "x", 2,
int, "y", 3,
uint, "z", 2,
bool, "flag", 1));
}
A obj;
obj.x = 2;
obj.z = obj.x;
assert(obj.x == 2);
assert(obj.y == 0);
assert(obj.z == 2);
assert(obj.flag == false);
}
/**
The sum of all bit lengths in one `bitfield` instantiation
must be exactly 8, 16, 32, or 64. If padding is needed, just allocate
one bitfield with an empty name.
*/
@safe unittest
{
struct A
{
mixin(bitfields!(
bool, "flag1", 1,
bool, "flag2", 1,
uint, "", 6));
}
A a;
assert(a.flag1 == 0);
a.flag1 = 1;
assert(a.flag1 == 1);
a.flag1 = 0;
assert(a.flag1 == 0);
}
/// enums can be used too
@safe unittest
{
enum ABC { A, B, C }
struct EnumTest
{
mixin(bitfields!(
ABC, "x", 2,
bool, "y", 1,
ubyte, "z", 5));
}
}
@safe pure nothrow @nogc
unittest
{
// Degenerate bitfields tests mixed with range tests
// https://issues.dlang.org/show_bug.cgi?id=8474
// https://issues.dlang.org/show_bug.cgi?id=11160
struct Test1
{
mixin(bitfields!(uint, "a", 32,
uint, "b", 4,
uint, "c", 4,
uint, "d", 8,
uint, "e", 16,));
static assert(Test1.b_min == 0);
static assert(Test1.b_max == 15);
}
struct Test2
{
mixin(bitfields!(bool, "a", 0,
ulong, "b", 64));
static assert(Test2.b_min == ulong.min);
static assert(Test2.b_max == ulong.max);
}
struct Test1b
{
mixin(bitfields!(bool, "a", 0,
int, "b", 8));
}
struct Test2b
{
mixin(bitfields!(int, "a", 32,
int, "b", 4,
int, "c", 4,
int, "d", 8,
int, "e", 16,));
static assert(Test2b.b_min == -8);
static assert(Test2b.b_max == 7);
}
struct Test3b
{
mixin(bitfields!(bool, "a", 0,
long, "b", 64));
static assert(Test3b.b_min == long.min);
static assert(Test3b.b_max == long.max);
}
struct Test4b
{
mixin(bitfields!(long, "a", 32,
int, "b", 32));
}
// Sign extension tests
Test2b t2b;
Test4b t4b;
t2b.b = -5; assert(t2b.b == -5);
t2b.d = -5; assert(t2b.d == -5);
t2b.e = -5; assert(t2b.e == -5);
t4b.a = -5; assert(t4b.a == -5L);
}
// https://issues.dlang.org/show_bug.cgi?id=6686
@safe unittest
{
union S {
ulong bits = ulong.max;
mixin (bitfields!(
ulong, "back", 31,
ulong, "front", 33)
);
}
S num;
num.bits = ulong.max;
num.back = 1;
assert(num.bits == 0xFFFF_FFFF_8000_0001uL);
}
// https://issues.dlang.org/show_bug.cgi?id=5942
@safe unittest
{
struct S
{
mixin(bitfields!(
int, "a" , 32,
int, "b" , 32
));
}
S data;
data.b = 42;
data.a = 1;
assert(data.b == 42);
}
@safe unittest
{
struct Test
{
mixin(bitfields!(bool, "a", 1,
uint, "b", 3,
short, "c", 4));
}
@safe void test() pure nothrow
{
Test t;
t.a = true;
t.b = 5;
t.c = 2;
assert(t.a);
assert(t.b == 5);
assert(t.c == 2);
}
test();
}
@safe unittest
{
{
static struct Integrals {
bool checkExpectations(bool eb, int ei, short es) { return b == eb && i == ei && s == es; }
mixin(bitfields!(
bool, "b", 1,
uint, "i", 3,
short, "s", 4));
}
Integrals i;
assert(i.checkExpectations(false, 0, 0));
i.b = true;
assert(i.checkExpectations(true, 0, 0));
i.i = 7;
assert(i.checkExpectations(true, 7, 0));
i.s = -8;
assert(i.checkExpectations(true, 7, -8));
i.s = 7;
assert(i.checkExpectations(true, 7, 7));
}
//https://issues.dlang.org/show_bug.cgi?id=8876
{
struct MoreIntegrals {
bool checkExpectations(uint eu, ushort es, uint ei) { return u == eu && s == es && i == ei; }
mixin(bitfields!(
uint, "u", 24,
short, "s", 16,
int, "i", 24));
}
MoreIntegrals i;
assert(i.checkExpectations(0, 0, 0));
i.s = 20;
assert(i.checkExpectations(0, 20, 0));
i.i = 72;
assert(i.checkExpectations(0, 20, 72));
i.u = 8;
assert(i.checkExpectations(8, 20, 72));
i.s = 7;
assert(i.checkExpectations(8, 7, 72));
}
enum A { True, False }
enum B { One, Two, Three, Four }
static struct Enums {
bool checkExpectations(A ea, B eb) { return a == ea && b == eb; }
mixin(bitfields!(
A, "a", 1,
B, "b", 2,
uint, "", 5));
}
Enums e;
assert(e.checkExpectations(A.True, B.One));
e.a = A.False;
assert(e.checkExpectations(A.False, B.One));
e.b = B.Three;
assert(e.checkExpectations(A.False, B.Three));
static struct SingleMember {
bool checkExpectations(bool eb) { return b == eb; }
mixin(bitfields!(
bool, "b", 1,
uint, "", 7));
}
SingleMember f;
assert(f.checkExpectations(false));
f.b = true;
assert(f.checkExpectations(true));
}
// https://issues.dlang.org/show_bug.cgi?id=12477
@system unittest
{
import core.exception : AssertError;
import std.algorithm.searching : canFind;
static struct S
{
mixin(bitfields!(
uint, "a", 6,
int, "b", 2));
}
S s;
try { s.a = uint.max; assert(0); }
catch (AssertError ae)
{ assert(ae.msg.canFind("Value is greater than the maximum value of bitfield 'a'"), ae.msg); }
try { s.b = int.min; assert(0); }
catch (AssertError ae)
{ assert(ae.msg.canFind("Value is smaller than the minimum value of bitfield 'b'"), ae.msg); }
}
// https://issues.dlang.org/show_bug.cgi?id=15305
@safe unittest
{
struct S {
mixin(bitfields!(
bool, "alice", 1,
ulong, "bob", 63,
));
}
S s;
s.bob = long.max - 1;
s.alice = false;
assert(s.bob == long.max - 1);
}
// https://issues.dlang.org/show_bug.cgi?id=21634
@safe unittest
{
struct A
{
mixin(bitfields!(int, "", 1,
int, "gshared", 7));
}
}
/**
This string mixin generator allows one to create tagged pointers inside $(D_PARAM struct)s and $(D_PARAM class)es.
A tagged pointer uses the bits known to be zero in a normal pointer or class reference to store extra information.
For example, a pointer to an integer must be 4-byte aligned, so there are 2 bits that are always known to be zero.
One can store a 2-bit integer there.
The example above creates a tagged pointer in the struct A. The pointer is of type
`uint*` as specified by the first argument, and is named x, as specified by the second
argument.
Following arguments works the same way as `bitfield`'s. The bitfield must fit into the
bits known to be zero because of the pointer alignment.
*/
template taggedPointer(T : T*, string name, Ts...) {
enum taggedPointer = createTaggedReference!(T*, T.alignof, name, Ts);
}
///
@safe unittest
{
struct A
{
int a;
mixin(taggedPointer!(
uint*, "x",
bool, "b1", 1,
bool, "b2", 1));
}
A obj;
obj.x = new uint;
obj.b1 = true;
obj.b2 = false;
}
@system unittest
{
struct Test5
{
mixin(taggedPointer!(
int*, "a",
uint, "b", 2));
}
Test5 t5;
t5.a = null;
t5.b = 3;
assert(t5.a is null);
assert(t5.b == 3);
int myint = 42;
t5.a = &myint;
assert(t5.a is &myint);
assert(t5.b == 3);
}
/**
This string mixin generator allows one to create tagged class reference inside $(D_PARAM struct)s and $(D_PARAM class)es.
A tagged class reference uses the bits known to be zero in a normal class reference to store extra information.
For example, a pointer to an integer must be 4-byte aligned, so there are 2 bits that are always known to be zero.
One can store a 2-bit integer there.
The example above creates a tagged reference to an Object in the struct A. This expects the same parameters
as `taggedPointer`, except the first argument which must be a class type instead of a pointer type.
*/
template taggedClassRef(T, string name, Ts...)
if (is(T == class))
{
enum taggedClassRef = createTaggedReference!(T, 8, name, Ts);
}
///
@safe unittest
{
struct A
{
int a;
mixin(taggedClassRef!(
Object, "o",
uint, "i", 2));
}
A obj;
obj.o = new Object();
obj.i = 3;
}
@system unittest
{
struct Test6
{
mixin(taggedClassRef!(
Object, "o",
bool, "b", 1));
}
Test6 t6;
t6.o = null;
t6.b = false;
assert(t6.o is null);
assert(t6.b == false);
auto o = new Object();
t6.o = o;
t6.b = true;
assert(t6.o is o);
assert(t6.b == true);
}
@safe unittest
{
static assert(!__traits(compiles,
taggedPointer!(
int*, "a",
uint, "b", 3)));
static assert(!__traits(compiles,
taggedClassRef!(
Object, "a",
uint, "b", 4)));
struct S {
mixin(taggedClassRef!(
Object, "a",
bool, "b", 1));
}
const S s;
void bar(S s) {}
static assert(!__traits(compiles, bar(s)));
}
/**
Allows manipulating the fraction, exponent, and sign parts of a
$(D_PARAM float) separately. The definition is:
----
struct FloatRep
{
union
{
float value;
mixin(bitfields!(
uint, "fraction", 23,
ubyte, "exponent", 8,
bool, "sign", 1));
}
enum uint bias = 127, fractionBits = 23, exponentBits = 8, signBits = 1;
}
----
*/
struct FloatRep
{
union
{
float value;
mixin(bitfields!(
uint, "fraction", 23,
ubyte, "exponent", 8,
bool, "sign", 1));
}
enum uint bias = 127, fractionBits = 23, exponentBits = 8, signBits = 1;
}
///
@safe unittest
{
FloatRep rep = {value: 0};
assert(rep.fraction == 0);
assert(rep.exponent == 0);
assert(!rep.sign);
rep.value = 42;
assert(rep.fraction == 2621440);
assert(rep.exponent == 132);
assert(!rep.sign);
rep.value = 10;
assert(rep.fraction == 2097152);
assert(rep.exponent == 130);
}
///
@safe unittest
{
FloatRep rep = {value: 1};
assert(rep.fraction == 0);
assert(rep.exponent == 127);
assert(!rep.sign);
rep.exponent = 126;
assert(rep.value == 0.5);
rep.exponent = 130;
assert(rep.value == 8);
}
///
@safe unittest
{
FloatRep rep = {value: 1};
rep.value = -0.5;
assert(rep.fraction == 0);
assert(rep.exponent == 126);
assert(rep.sign);
rep.value = -1. / 3;
assert(rep.fraction == 2796203);
assert(rep.exponent == 125);
assert(rep.sign);
}
/**
Allows manipulating the fraction, exponent, and sign parts of a
$(D_PARAM double) separately. The definition is:
----
struct DoubleRep
{
union
{
double value;
mixin(bitfields!(
ulong, "fraction", 52,
ushort, "exponent", 11,
bool, "sign", 1));
}
enum uint bias = 1023, signBits = 1, fractionBits = 52, exponentBits = 11;
}
----
*/
struct DoubleRep
{
union
{
double value;
mixin(bitfields!(
ulong, "fraction", 52,
ushort, "exponent", 11,
bool, "sign", 1));
}
enum uint bias = 1023, signBits = 1, fractionBits = 52, exponentBits = 11;
}
///
@safe unittest
{
DoubleRep rep = {value: 0};
assert(rep.fraction == 0);
assert(rep.exponent == 0);
assert(!rep.sign);
rep.value = 42;
assert(rep.fraction == 1407374883553280);
assert(rep.exponent == 1028);
assert(!rep.sign);
rep.value = 10;
assert(rep.fraction == 1125899906842624);
assert(rep.exponent == 1026);
}
///
@safe unittest
{
DoubleRep rep = {value: 1};
assert(rep.fraction == 0);
assert(rep.exponent == 1023);
assert(!rep.sign);
rep.exponent = 1022;
assert(rep.value == 0.5);
rep.exponent = 1026;
assert(rep.value == 8);
}
///
@safe unittest
{
DoubleRep rep = {value: 1};
rep.value = -0.5;
assert(rep.fraction == 0);
assert(rep.exponent == 1022);
assert(rep.sign);
rep.value = -1. / 3;
assert(rep.fraction == 1501199875790165);
assert(rep.exponent == 1021);
assert(rep.sign);
}
/// Reading
@safe unittest
{
DoubleRep x;
x.value = 1.0;
assert(x.fraction == 0 && x.exponent == 1023 && !x.sign);
x.value = -0.5;
assert(x.fraction == 0 && x.exponent == 1022 && x.sign);
x.value = 0.5;
assert(x.fraction == 0 && x.exponent == 1022 && !x.sign);
}
/// Writing
@safe unittest
{
DoubleRep x;
x.fraction = 1125899906842624;
x.exponent = 1025;
x.sign = true;
assert(x.value == -5.0);
}
/**
A dynamic array of bits. Each bit in a `BitArray` can be manipulated individually
or by the standard bitwise operators `&`, `|`, `^`, `~`, `>>`, `<<` and also by
other effective member functions; most of them work relative to the `BitArray`'s
dimension (see $(LREF dim)), instead of its $(LREF length).
*/
struct BitArray
{
private:
import core.bitop : btc, bts, btr, bsf, bt;
import std.format : FormatSpec;
size_t _len;
size_t* _ptr;
enum bitsPerSizeT = size_t.sizeof * 8;
@property size_t fullWords() const @nogc pure nothrow
{
return _len / bitsPerSizeT;
}
// Number of bits after the last full word
@property size_t endBits() const @nogc pure nothrow
{
return _len % bitsPerSizeT;
}
// Bit mask to extract the bits after the last full word
@property size_t endMask() const @nogc pure nothrow
{
return (size_t(1) << endBits) - 1;
}
static size_t lenToDim(size_t len) @nogc pure nothrow @safe
{
return (len + (bitsPerSizeT-1)) / bitsPerSizeT;
}
public:
/**
Creates a `BitArray` from a `bool` array, such that `bool` values read
from left to right correspond to subsequent bits in the `BitArray`.
Params: ba = Source array of `bool` values.
*/
this(in bool[] ba) nothrow pure
{
length = ba.length;
foreach (i, b; ba)
{
this[i] = b;
}
}
///
@system unittest
{
import std.algorithm.comparison : equal;
bool[] input = [true, false, false, true, true];
auto a = BitArray(input);
assert(a.length == 5);
assert(a.bitsSet.equal([0, 3, 4]));
// This also works because an implicit cast to bool[] occurs for this array.
auto b = BitArray([0, 0, 1]);
assert(b.length == 3);
assert(b.bitsSet.equal([2]));
}
///
@system unittest
{
import std.algorithm.comparison : equal;
import std.array : array;
import std.range : iota, repeat;
BitArray a = true.repeat(70).array;
assert(a.length == 70);
assert(a.bitsSet.equal(iota(0, 70)));
}
/**
Creates a `BitArray` from the raw contents of the source array. The
source array is not copied but simply acts as the underlying array
of bits, which stores data as `size_t` units.
That means a particular care should be taken when passing an array
of a type different than `size_t`, firstly because its length should
be a multiple of `size_t.sizeof`, and secondly because how the bits
are mapped:
---
size_t[] source = [1, 2, 3, 3424234, 724398, 230947, 389492];
enum sbits = size_t.sizeof * 8;
auto ba = BitArray(source, source.length * sbits);
foreach (n; 0 .. source.length * sbits)
{
auto nth_bit = cast(bool) (source[n / sbits] & (1L << (n % sbits)));
assert(ba[n] == nth_bit);
}
---
The least significant bit in any `size_t` unit is the starting bit of this
unit, and the most significant bit is the last bit of this unit. Therefore,
passing e.g. an array of `int`s may result in a different `BitArray`
depending on the processor's endianness.
This constructor is the inverse of $(LREF opCast).
Params:
v = Source array. `v.length` must be a multple of `size_t.sizeof`.
numbits = Number of bits to be mapped from the source array, i.e.
length of the created `BitArray`.
*/
this(void[] v, size_t numbits) @nogc nothrow pure
in
{
assert(numbits <= v.length * 8,
"numbits must be less than or equal to v.length * 8");
assert(v.length % size_t.sizeof == 0,
"v.length must be a multiple of the size of size_t");
}
do
{
_ptr = cast(size_t*) v.ptr;
_len = numbits;
}
///
@system unittest
{
import std.algorithm.comparison : equal;
auto a = BitArray([1, 0, 0, 1, 1]);
// Inverse of the cast.
auto v = cast(void[]) a;
auto b = BitArray(v, a.length);
assert(b.length == 5);
assert(b.bitsSet.equal([0, 3, 4]));
// a and b share the underlying data.
a[0] = 0;
assert(b[0] == 0);
assert(a == b);
}
///
@system unittest
{
import std.algorithm.comparison : equal;
size_t[] source = [0b1100, 0b0011];
enum sbits = size_t.sizeof * 8;
auto ba = BitArray(source, source.length * sbits);
// The least significant bit in each unit is this unit's starting bit.
assert(ba.bitsSet.equal([2, 3, sbits, sbits + 1]));
}
///
@system unittest
{
// Example from the doc for this constructor.
static immutable size_t[] sourceData = [1, 0b101, 3, 3424234, 724398, 230947, 389492];
size_t[] source = sourceData.dup;
enum sbits = size_t.sizeof * 8;
auto ba = BitArray(source, source.length * sbits);
foreach (n; 0 .. source.length * sbits)
{
auto nth_bit = cast(bool) (source[n / sbits] & (1L << (n % sbits)));
assert(ba[n] == nth_bit);
}
// Example of mapping only part of the array.
import std.algorithm.comparison : equal;
auto bc = BitArray(source, sbits + 1);
assert(bc.bitsSet.equal([0, sbits]));
// Source array has not been modified.
assert(source == sourceData);
}
// Deliberately undocumented: raw initialization of bit array.
this(size_t len, size_t* ptr) @nogc nothrow pure
{
_len = len;
_ptr = ptr;
}
/**
Returns: Dimension i.e. the number of native words backing this `BitArray`.
Technically, this is the length of the underlying array storing bits, which
is equal to `ceil(length / (size_t.sizeof * 8))`, as bits are packed into
`size_t` units.
*/
@property size_t dim() const @nogc nothrow pure @safe
{
return lenToDim(_len);
}
/**
Returns: Number of bits in the `BitArray`.
*/
@property size_t length() const @nogc nothrow pure @safe
{
return _len;
}
/**********************************************
* Sets the amount of bits in the `BitArray`.
* $(RED Warning: increasing length may overwrite bits in
* the final word of the current underlying data regardless
* of whether it is shared between BitArray objects. i.e. D
* dynamic array extension semantics are not followed.)
*/
@property size_t length(size_t newlen) pure nothrow @system
{
if (newlen != _len)
{
size_t olddim = dim;
immutable newdim = lenToDim(newlen);
if (newdim != olddim)
{
// Create a fake array so we can use D's realloc machinery
auto b = _ptr[0 .. olddim];
b.length = newdim; // realloc
_ptr = b.ptr;
}
auto oldlen = _len;
_len = newlen;
if (oldlen < newlen)
{
auto end = ((oldlen / bitsPerSizeT) + 1) * bitsPerSizeT;
if (end > newlen)
end = newlen;
this[oldlen .. end] = 0;
}
}
return _len;
}
// https://issues.dlang.org/show_bug.cgi?id=20240
@system unittest
{
BitArray ba;
ba.length = 1;
ba[0] = 1;
ba.length = 0;
ba.length = 1;
assert(ba[0] == 0); // OK
ba.length = 2;
ba[1] = 1;
ba.length = 1;
ba.length = 2;
assert(ba[1] == 0); // Fail
}
/**********************************************
* Gets the `i`'th bit in the `BitArray`.
*/
bool opIndex(size_t i) const @nogc pure nothrow
in
{
assert(i < _len, "i must be less than the length");
}
do
{
return cast(bool) bt(_ptr, i);
}
///
@system unittest
{
static void fun(const BitArray arr)
{
auto x = arr[0];
assert(x == 1);
}
BitArray a;
a.length = 3;
a[0] = 1;
fun(a);
}
/**********************************************
* Sets the `i`'th bit in the `BitArray`.
*/
bool opIndexAssign(bool b, size_t i) @nogc pure nothrow
in
{
assert(i < _len, "i must be less than the length");
}
do
{
if (b)
bts(_ptr, i);
else
btr(_ptr, i);
return b;
}
/**
Sets all the values in the `BitArray` to the
value specified by `val`.
*/
void opSliceAssign(bool val) @nogc pure nothrow
{
_ptr[0 .. fullWords] = val ? ~size_t(0) : 0;
if (endBits)
{
if (val)
_ptr[fullWords] |= endMask;
else
_ptr[fullWords] &= ~endMask;
}
}
///
@system pure nothrow unittest
{
import std.algorithm.comparison : equal;
auto b = BitArray([1, 0, 1, 0, 1, 1]);
b[] = true;
// all bits are set
assert(b.bitsSet.equal([0, 1, 2, 3, 4, 5]));
b[] = false;
// none of the bits are set
assert(b.bitsSet.empty);
}
/**
Sets the bits of a slice of `BitArray` starting
at index `start` and ends at index ($D end - 1)
with the values specified by `val`.
*/
void opSliceAssign(bool val, size_t start, size_t end) @nogc pure nothrow
in
{
assert(start <= end, "start must be less or equal to end");
assert(end <= length, "end must be less or equal to the length");
}
do
{
size_t startBlock = start / bitsPerSizeT;
size_t endBlock = end / bitsPerSizeT;
size_t startOffset = start % bitsPerSizeT;
size_t endOffset = end % bitsPerSizeT;
if (startBlock == endBlock)
{
size_t startBlockMask = ~((size_t(1) << startOffset) - 1);
size_t endBlockMask = (size_t(1) << endOffset) - 1;
size_t joinMask = startBlockMask & endBlockMask;
if (val)
_ptr[startBlock] |= joinMask;
else
_ptr[startBlock] &= ~joinMask;
return;
}
if (startOffset != 0)
{
size_t startBlockMask = ~((size_t(1) << startOffset) - 1);
if (val)
_ptr[startBlock] |= startBlockMask;
else
_ptr[startBlock] &= ~startBlockMask;
++startBlock;
}
if (endOffset != 0)
{
size_t endBlockMask = (size_t(1) << endOffset) - 1;
if (val)
_ptr[endBlock] |= endBlockMask;
else
_ptr[endBlock] &= ~endBlockMask;
}
_ptr[startBlock .. endBlock] = size_t(0) - size_t(val);
}
///
@system pure nothrow unittest
{
import std.algorithm.comparison : equal;
import std.range : iota;
import std.stdio;
auto b = BitArray([1, 0, 0, 0, 1, 1, 0]);
b[1 .. 3] = true;
assert(b.bitsSet.equal([0, 1, 2, 4, 5]));
bool[72] bitArray;
auto b1 = BitArray(bitArray);
b1[63 .. 67] = true;
assert(b1.bitsSet.equal([63, 64, 65, 66]));
b1[63 .. 67] = false;
assert(b1.bitsSet.empty);
b1[0 .. 64] = true;
assert(b1.bitsSet.equal(iota(0, 64)));
b1[0 .. 64] = false;
assert(b1.bitsSet.empty);
bool[256] bitArray2;
auto b2 = BitArray(bitArray2);
b2[3 .. 245] = true;
assert(b2.bitsSet.equal(iota(3, 245)));
b2[3 .. 245] = false;
assert(b2.bitsSet.empty);
}
/**
Flips all the bits in the `BitArray`
*/
void flip() @nogc pure nothrow
{
foreach (i; 0 .. fullWords)
_ptr[i] = ~_ptr[i];
if (endBits)
_ptr[fullWords] = (~_ptr[fullWords]) & endMask;
}
///
@system pure nothrow unittest
{
import std.algorithm.comparison : equal;
import std.range : iota;
// positions 0, 2, 4 are set
auto b = BitArray([1, 0, 1, 0, 1, 0]);
b.flip();
// after flipping, positions 1, 3, 5 are set
assert(b.bitsSet.equal([1, 3, 5]));
bool[270] bits;
auto b1 = BitArray(bits);
b1.flip();
assert(b1.bitsSet.equal(iota(0, 270)));
}
/**
Flips a single bit, specified by `pos`
*/
void flip(size_t i) @nogc pure nothrow
{
bt(_ptr, i) ? btr(_ptr, i) : bts(_ptr, i);
}
///
@system pure nothrow unittest
{
auto ax = BitArray([1, 0, 0, 1]);
ax.flip(0);
assert(ax[0] == 0);
bool[200] y;
y[90 .. 130] = true;
auto ay = BitArray(y);
ay.flip(100);
assert(ay[100] == 0);
}
/**********************************************
* Counts all the set bits in the `BitArray`
*/
size_t count() const @nogc pure nothrow
{
if (_ptr)
{
size_t bitCount;
foreach (i; 0 .. fullWords)
bitCount += countBitsSet(_ptr[i]);
bitCount += countBitsSet(_ptr[fullWords] & endMask);
return bitCount;
}
else
{
return 0;
}
}
///
@system pure nothrow unittest
{
auto a = BitArray([0, 1, 1, 0, 0, 1, 1]);
assert(a.count == 4);
BitArray b;
assert(b.count == 0);
bool[200] boolArray;
boolArray[45 .. 130] = true;
auto c = BitArray(boolArray);
assert(c.count == 85);
}
/**********************************************
* Duplicates the `BitArray` and its contents.
*/
@property BitArray dup() const pure nothrow
{
BitArray ba;
auto b = _ptr[0 .. dim].dup;
ba._len = _len;
ba._ptr = b.ptr;
return ba;
}
///
@system unittest
{
BitArray a;
BitArray b;
a.length = 3;
a[0] = 1; a[1] = 0; a[2] = 1;
b = a.dup;
assert(b.length == 3);
foreach (i; 0 .. 3)
assert(b[i] == (((i ^ 1) & 1) ? true : false));
}
/**********************************************
* Support for `foreach` loops for `BitArray`.
*/
int opApply(scope int delegate(ref bool) dg)
{
int result;
foreach (i; 0 .. _len)
{
bool b = opIndex(i);
result = dg(b);
this[i] = b;
if (result)
break;
}
return result;
}
/** ditto */
int opApply(scope int delegate(bool) dg) const
{
int result;
foreach (i; 0 .. _len)
{
immutable b = opIndex(i);
result = dg(b);
if (result)
break;
}
return result;
}
/** ditto */
int opApply(scope int delegate(size_t, ref bool) dg)
{
int result;
foreach (i; 0 .. _len)
{
bool b = opIndex(i);
result = dg(i, b);
this[i] = b;
if (result)
break;
}
return result;
}
/** ditto */
int opApply(scope int delegate(size_t, bool) dg) const
{
int result;
foreach (i; 0 .. _len)
{
immutable b = opIndex(i);
result = dg(i, b);
if (result)
break;
}
return result;
}
///
@system unittest
{
bool[] ba = [1,0,1];
auto a = BitArray(ba);
int i;
foreach (b;a)
{
switch (i)
{
case 0: assert(b == true); break;
case 1: assert(b == false); break;
case 2: assert(b == true); break;
default: assert(0);
}
i++;
}
foreach (j,b;a)
{
switch (j)
{
case 0: assert(b == true); break;
case 1: assert(b == false); break;
case 2: assert(b == true); break;
default: assert(0);
}
}
}
/**********************************************
* Reverses the bits of the `BitArray`.
*/
@property BitArray reverse() @nogc pure nothrow
out (result)
{
assert(result == this, "the result must be equal to this");
}
do
{
if (_len >= 2)
{
bool t;
size_t lo, hi;
lo = 0;
hi = _len - 1;
for (; lo < hi; lo++, hi--)
{
t = this[lo];
this[lo] = this[hi];
this[hi] = t;
}
}
return this;
}
///
@system unittest
{
BitArray b;
bool[5] data = [1,0,1,1,0];
b = BitArray(data);
b.reverse;
foreach (i; 0 .. data.length)
assert(b[i] == data[4 - i]);
}
/**********************************************
* Sorts the `BitArray`'s elements.
*/
@property BitArray sort() @nogc pure nothrow
out (result)
{
assert(result == this, "the result must be equal to this");
}
do
{
if (_len >= 2)
{
size_t lo, hi;
lo = 0;
hi = _len - 1;
while (1)
{
while (1)
{
if (lo >= hi)
goto Ldone;
if (this[lo] == true)
break;
lo++;
}
while (1)
{
if (lo >= hi)
goto Ldone;
if (this[hi] == false)
break;
hi--;
}
this[lo] = false;
this[hi] = true;
lo++;
hi--;
}
}
Ldone:
return this;
}
///
@system unittest
{
size_t x = 0b1100011000;
auto ba = BitArray(10, &x);
ba.sort;
foreach (i; 0 .. 6)
assert(ba[i] == false);
foreach (i; 6 .. 10)
assert(ba[i] == true);
}
/***************************************
* Support for operators == and != for `BitArray`.
*/
bool opEquals(const ref BitArray a2) const @nogc pure nothrow
{
if (this.length != a2.length)
return false;
auto p1 = this._ptr;
auto p2 = a2._ptr;
if (p1[0 .. fullWords] != p2[0 .. fullWords])
return false;
if (!endBits)
return true;
auto i = fullWords;
return (p1[i] & endMask) == (p2[i] & endMask);
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1];
bool[] bc = [1,0,1,0,1,0,1];
bool[] bd = [1,0,1,1,1];
bool[] be = [1,0,1,0,1];
bool[] bf = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
bool[] bg = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1];
auto a = BitArray(ba);
auto b = BitArray(bb);
auto c = BitArray(bc);
auto d = BitArray(bd);
auto e = BitArray(be);
auto f = BitArray(bf);
auto g = BitArray(bg);
assert(a != b);
assert(a != c);
assert(a != d);
assert(a == e);
assert(f != g);
}
/***************************************
* Supports comparison operators for `BitArray`.
*/
int opCmp(BitArray a2) const @nogc pure nothrow
{
const lesser = this.length < a2.length ? &this : &a2;
immutable fullWords = lesser.fullWords;
immutable endBits = lesser.endBits;
auto p1 = this._ptr;
auto p2 = a2._ptr;
foreach (i; 0 .. fullWords)
{
if (p1[i] != p2[i])
{
return p1[i] & (size_t(1) << bsf(p1[i] ^ p2[i])) ? 1 : -1;
}
}
if (endBits)
{
immutable i = fullWords;
immutable diff = p1[i] ^ p2[i];
if (diff)
{
immutable index = bsf(diff);
if (index < endBits)
{
return p1[i] & (size_t(1) << index) ? 1 : -1;
}
}
}
// Standard:
// A bool value can be implicitly converted to any integral type,
// with false becoming 0 and true becoming 1
return (this.length > a2.length) - (this.length < a2.length);
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1];
bool[] bc = [1,0,1,0,1,0,1];
bool[] bd = [1,0,1,1,1];
bool[] be = [1,0,1,0,1];
bool[] bf = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1];
bool[] bg = [1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
auto c = BitArray(bc);
auto d = BitArray(bd);
auto e = BitArray(be);
auto f = BitArray(bf);
auto g = BitArray(bg);
assert(a > b);
assert(a >= b);
assert(a < c);
assert(a <= c);
assert(a < d);
assert(a <= d);
assert(a == e);
assert(a <= e);
assert(a >= e);
assert(f < g);
assert(g <= g);
}
@system unittest
{
bool[] v;
foreach (i; 1 .. 256)
{
v.length = i;
v[] = false;
auto x = BitArray(v);
v[i-1] = true;
auto y = BitArray(v);
assert(x < y);
assert(x <= y);
}
BitArray a1, a2;
for (size_t len = 4; len <= 256; len <<= 1)
{
a1.length = a2.length = len;
a1[len-2] = a2[len-1] = true;
assert(a1 > a2);
a1[len-2] = a2[len-1] = false;
}
foreach (j; 1 .. a1.length)
{
a1[j-1] = a2[j] = true;
assert(a1 > a2);
a1[j-1] = a2[j] = false;
}
}
/***************************************
* Support for hashing for `BitArray`.
*/
size_t toHash() const @nogc pure nothrow
{
size_t hash = 3557;
auto fullBytes = _len / 8;
foreach (i; 0 .. fullBytes)
{
hash *= 3559;
hash += (cast(byte*) this._ptr)[i];
}
foreach (i; 8*fullBytes .. _len)
{
hash *= 3571;
hash += this[i];
}
return hash;
}
/***************************************
* Convert to `void[]`.
*/
inout(void)[] opCast(T : const void[])() inout @nogc pure nothrow
{
return cast(inout void[]) _ptr[0 .. dim];
}
/***************************************
* Convert to `size_t[]`.
*/
inout(size_t)[] opCast(T : const size_t[])() inout @nogc pure nothrow
{
return _ptr[0 .. dim];
}
///
@system unittest
{
import std.array : array;
import std.range : repeat, take;
// bit array with 300 elements
auto a = BitArray(true.repeat.take(300).array);
size_t[] v = cast(size_t[]) a;
const blockSize = size_t.sizeof * 8;
assert(v.length == (a.length + blockSize - 1) / blockSize);
}
// https://issues.dlang.org/show_bug.cgi?id=20606
@system unittest
{
import std.meta : AliasSeq;
static foreach (alias T; AliasSeq!(void, size_t))
{{
BitArray m;
T[] ma = cast(T[]) m;
const BitArray c;
const(T)[] ca = cast(const T[]) c;
immutable BitArray i;
immutable(T)[] ia = cast(immutable T[]) i;
// Cross-mutability
ca = cast(const T[]) m;
ca = cast(const T[]) i;
// Invalid cast don't compile
static assert(!is(typeof(cast(T[]) c)));
static assert(!is(typeof(cast(T[]) i)));
static assert(!is(typeof(cast(immutable T[]) m)));
static assert(!is(typeof(cast(immutable T[]) c)));
}}
}
/***************************************
* Support for unary operator ~ for `BitArray`.
*/
BitArray opUnary(string op)() const pure nothrow
if (op == "~")
{
auto dim = this.dim;
BitArray result;
result.length = _len;
result._ptr[0 .. dim] = ~this._ptr[0 .. dim];
// Avoid putting garbage in extra bits
// Remove once we zero on length extension
if (endBits)
result._ptr[dim - 1] &= endMask;
return result;
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
auto a = BitArray(ba);
BitArray b = ~a;
assert(b[0] == 0);
assert(b[1] == 1);
assert(b[2] == 0);
assert(b[3] == 1);
assert(b[4] == 0);
}
/***************************************
* Support for binary bitwise operators for `BitArray`.
*/
BitArray opBinary(string op)(const BitArray e2) const pure nothrow
if (op == "-" || op == "&" || op == "|" || op == "^")
in
{
assert(e2.length == _len, "e2 must have the same length as this");
}
do
{
auto dim = this.dim;
BitArray result;
result.length = _len;
static if (op == "-")
result._ptr[0 .. dim] = this._ptr[0 .. dim] & ~e2._ptr[0 .. dim];
else
mixin("result._ptr[0 .. dim] = this._ptr[0 .. dim]"~op~" e2._ptr[0 .. dim];");
// Avoid putting garbage in extra bits
// Remove once we zero on length extension
if (endBits)
result._ptr[dim - 1] &= endMask;
return result;
}
///
@system unittest
{
static bool[] ba = [1,0,1,0,1];
static bool[] bb = [1,0,1,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
BitArray c = a & b;
assert(c[0] == 1);
assert(c[1] == 0);
assert(c[2] == 1);
assert(c[3] == 0);
assert(c[4] == 0);
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
BitArray c = a | b;
assert(c[0] == 1);
assert(c[1] == 0);
assert(c[2] == 1);
assert(c[3] == 1);
assert(c[4] == 1);
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
BitArray c = a ^ b;
assert(c[0] == 0);
assert(c[1] == 0);
assert(c[2] == 0);
assert(c[3] == 1);
assert(c[4] == 1);
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
BitArray c = a - b;
assert(c[0] == 0);
assert(c[1] == 0);
assert(c[2] == 0);
assert(c[3] == 0);
assert(c[4] == 1);
}
/***************************************
* Support for operator op= for `BitArray`.
*/
BitArray opOpAssign(string op)(const BitArray e2) @nogc pure nothrow
if (op == "-" || op == "&" || op == "|" || op == "^")
in
{
assert(e2.length == _len, "e2 must have the same length as this");
}
do
{
foreach (i; 0 .. fullWords)
{
static if (op == "-")
_ptr[i] &= ~e2._ptr[i];
else
mixin("_ptr[i] "~op~"= e2._ptr[i];");
}
if (!endBits)
return this;
size_t i = fullWords;
size_t endWord = _ptr[i];
static if (op == "-")
endWord &= ~e2._ptr[i];
else
mixin("endWord "~op~"= e2._ptr[i];");
_ptr[i] = (_ptr[i] & ~endMask) | (endWord & endMask);
return this;
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1,1,0,1,0,1];
bool[] bb = [1,0,1,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
BitArray c = a;
c.length = 5;
c &= b;
assert(a[5] == 1);
assert(a[6] == 0);
assert(a[7] == 1);
assert(a[8] == 0);
assert(a[9] == 1);
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
a &= b;
assert(a[0] == 1);
assert(a[1] == 0);
assert(a[2] == 1);
assert(a[3] == 0);
assert(a[4] == 0);
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
a |= b;
assert(a[0] == 1);
assert(a[1] == 0);
assert(a[2] == 1);
assert(a[3] == 1);
assert(a[4] == 1);
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
a ^= b;
assert(a[0] == 0);
assert(a[1] == 0);
assert(a[2] == 0);
assert(a[3] == 1);
assert(a[4] == 1);
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
bool[] bb = [1,0,1,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
a -= b;
assert(a[0] == 0);
assert(a[1] == 0);
assert(a[2] == 0);
assert(a[3] == 0);
assert(a[4] == 1);
}
/***************************************
* Support for operator ~= for `BitArray`.
* $(RED Warning: This will overwrite a bit in the final word
* of the current underlying data regardless of whether it is
* shared between BitArray objects. i.e. D dynamic array
* concatenation semantics are not followed)
*/
BitArray opOpAssign(string op)(bool b) pure nothrow
if (op == "~")
{
length = _len + 1;
this[_len - 1] = b;
return this;
}
///
@system unittest
{
bool[] ba = [1,0,1,0,1];
auto a = BitArray(ba);
BitArray b;
b = (a ~= true);
assert(a[0] == 1);
assert(a[1] == 0);
assert(a[2] == 1);
assert(a[3] == 0);
assert(a[4] == 1);
assert(a[5] == 1);
assert(b == a);
}
/***************************************
* ditto
*/
BitArray opOpAssign(string op)(BitArray b) pure nothrow
if (op == "~")
{
auto istart = _len;
length = _len + b.length;
for (auto i = istart; i < _len; i++)
this[i] = b[i - istart];
return this;
}
///
@system unittest
{
bool[] ba = [1,0];
bool[] bb = [0,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
BitArray c;
c = (a ~= b);
assert(a.length == 5);
assert(a[0] == 1);
assert(a[1] == 0);
assert(a[2] == 0);
assert(a[3] == 1);
assert(a[4] == 0);
assert(c == a);
}
/***************************************
* Support for binary operator ~ for `BitArray`.
*/
BitArray opBinary(string op)(bool b) const pure nothrow
if (op == "~")
{
BitArray r;
r = this.dup;
r.length = _len + 1;
r[_len] = b;
return r;
}
/** ditto */
BitArray opBinaryRight(string op)(bool b) const pure nothrow
if (op == "~")
{
BitArray r;
r.length = _len + 1;
r[0] = b;
foreach (i; 0 .. _len)
r[1 + i] = this[i];
return r;
}
/** ditto */
BitArray opBinary(string op)(BitArray b) const pure nothrow
if (op == "~")
{
BitArray r;
r = this.dup;
r ~= b;
return r;
}
///
@system unittest
{
bool[] ba = [1,0];
bool[] bb = [0,1,0];
auto a = BitArray(ba);
auto b = BitArray(bb);
BitArray c;
c = (a ~ b);
assert(c.length == 5);
assert(c[0] == 1);
assert(c[1] == 0);
assert(c[2] == 0);
assert(c[3] == 1);
assert(c[4] == 0);
c = (a ~ true);
assert(c.length == 3);
assert(c[0] == 1);
assert(c[1] == 0);
assert(c[2] == 1);
c = (false ~ a);
assert(c.length == 3);
assert(c[0] == 0);
assert(c[1] == 1);
assert(c[2] == 0);
}
// Rolls double word (upper, lower) to the right by n bits and returns the
// lower word of the result.
private static size_t rollRight()(size_t upper, size_t lower, size_t nbits)
pure @safe nothrow @nogc
in
{
assert(nbits < bitsPerSizeT, "nbits must be less than bitsPerSizeT");
}
do
{
if (nbits == 0)
return lower;
return (upper << (bitsPerSizeT - nbits)) | (lower >> nbits);
}
@safe unittest
{
static if (size_t.sizeof == 8)
{
size_t x = 0x12345678_90ABCDEF;
size_t y = 0xFEDBCA09_87654321;
assert(rollRight(x, y, 32) == 0x90ABCDEF_FEDBCA09);
assert(rollRight(y, x, 4) == 0x11234567_890ABCDE);
}
else static if (size_t.sizeof == 4)
{
size_t x = 0x12345678;
size_t y = 0x90ABCDEF;
assert(rollRight(x, y, 16) == 0x567890AB);
assert(rollRight(y, x, 4) == 0xF1234567);
}
else
static assert(0, "Unsupported size_t width");
}
// Rolls double word (upper, lower) to the left by n bits and returns the
// upper word of the result.
private static size_t rollLeft()(size_t upper, size_t lower, size_t nbits)
pure @safe nothrow @nogc
in
{
assert(nbits < bitsPerSizeT, "nbits must be less than bitsPerSizeT");
}
do
{
if (nbits == 0)
return upper;
return (upper << nbits) | (lower >> (bitsPerSizeT - nbits));
}
@safe unittest
{
static if (size_t.sizeof == 8)
{
size_t x = 0x12345678_90ABCDEF;
size_t y = 0xFEDBCA09_87654321;
assert(rollLeft(x, y, 32) == 0x90ABCDEF_FEDBCA09);
assert(rollLeft(y, x, 4) == 0xEDBCA098_76543211);
}
else static if (size_t.sizeof == 4)
{
size_t x = 0x12345678;
size_t y = 0x90ABCDEF;
assert(rollLeft(x, y, 16) == 0x567890AB);
assert(rollLeft(y, x, 4) == 0x0ABCDEF1);
}
}
/**
* Operator `<<=` support.
*
* Shifts all the bits in the array to the left by the given number of
* bits. The leftmost bits are dropped, and 0's are appended to the end
* to fill up the vacant bits.
*
* $(RED Warning: unused bits in the final word up to the next word
* boundary may be overwritten by this operation. It does not attempt to
* preserve bits past the end of the array.)
*/
void opOpAssign(string op)(size_t nbits) @nogc pure nothrow
if (op == "<<")
{
size_t wordsToShift = nbits / bitsPerSizeT;
size_t bitsToShift = nbits % bitsPerSizeT;
if (wordsToShift < dim)
{
foreach_reverse (i; 1 .. dim - wordsToShift)
{
_ptr[i + wordsToShift] = rollLeft(_ptr[i], _ptr[i-1],
bitsToShift);
}
_ptr[wordsToShift] = rollLeft(_ptr[0], 0, bitsToShift);
}
import std.algorithm.comparison : min;
foreach (i; 0 .. min(wordsToShift, dim))
{
_ptr[i] = 0;
}
}
/**
* Operator `>>=` support.
*
* Shifts all the bits in the array to the right by the given number of
* bits. The rightmost bits are dropped, and 0's are inserted at the back
* to fill up the vacant bits.
*
* $(RED Warning: unused bits in the final word up to the next word
* boundary may be overwritten by this operation. It does not attempt to
* preserve bits past the end of the array.)
*/
void opOpAssign(string op)(size_t nbits) @nogc pure nothrow
if (op == ">>")
{
size_t wordsToShift = nbits / bitsPerSizeT;
size_t bitsToShift = nbits % bitsPerSizeT;
if (wordsToShift + 1 < dim)
{
foreach (i; 0 .. dim - wordsToShift - 1)
{
_ptr[i] = rollRight(_ptr[i + wordsToShift + 1],
_ptr[i + wordsToShift], bitsToShift);
}
}
// The last word needs some care, as it must shift in 0's from past the
// end of the array.
if (wordsToShift < dim)
{
if (bitsToShift == 0)
_ptr[dim - wordsToShift - 1] = _ptr[dim - 1];
else
{
// Special case: if endBits == 0, then also endMask == 0.
size_t lastWord = (endBits ? (_ptr[fullWords] & endMask) : _ptr[fullWords - 1]);
_ptr[dim - wordsToShift - 1] = rollRight(0, lastWord, bitsToShift);
}
}
import std.algorithm.comparison : min;
foreach (i; 0 .. min(wordsToShift, dim))
{
_ptr[dim - i - 1] = 0;
}
}
// https://issues.dlang.org/show_bug.cgi?id=17467
@system unittest
{
import std.algorithm.comparison : equal;
import std.range : iota;
bool[] buf = new bool[64*3];
buf[0 .. 64] = true;
BitArray b = BitArray(buf);
assert(equal(b.bitsSet, iota(0, 64)));
b <<= 64;
assert(equal(b.bitsSet, iota(64, 128)));
buf = new bool[64*3];
buf[64*2 .. 64*3] = true;
b = BitArray(buf);
assert(equal(b.bitsSet, iota(64*2, 64*3)));
b >>= 64;
assert(equal(b.bitsSet, iota(64, 128)));
}
// https://issues.dlang.org/show_bug.cgi?id=18134
// shifting right when length is a multiple of 8 * size_t.sizeof.
@system unittest
{
import std.algorithm.comparison : equal;
import std.array : array;
import std.range : repeat, iota;
immutable r = size_t.sizeof * 8;
BitArray a = true.repeat(r / 2).array;
a >>= 0;
assert(a.bitsSet.equal(iota(0, r / 2)));
a >>= 1;
assert(a.bitsSet.equal(iota(0, r / 2 - 1)));
BitArray b = true.repeat(r).array;
b >>= 0;
assert(b.bitsSet.equal(iota(0, r)));
b >>= 1;
assert(b.bitsSet.equal(iota(0, r - 1)));
BitArray c = true.repeat(2 * r).array;
c >>= 0;
assert(c.bitsSet.equal(iota(0, 2 * r)));
c >>= 10;
assert(c.bitsSet.equal(iota(0, 2 * r - 10)));
}
///
@system unittest
{
import std.format : format;
auto b = BitArray([1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1]);
b <<= 1;
assert(format("%b", b) == "01100_10101101");
b >>= 1;
assert(format("%b", b) == "11001_01011010");
b <<= 4;
assert(format("%b", b) == "00001_10010101");
b >>= 5;
assert(format("%b", b) == "10010_10100000");
b <<= 13;
assert(format("%b", b) == "00000_00000000");
b = BitArray([1, 0, 1, 1, 0, 1, 1, 1]);
b >>= 8;
assert(format("%b", b) == "00000000");
}
// Test multi-word case
@system unittest
{
import std.format : format;
// This has to be long enough to occupy more than one size_t. On 64-bit
// machines, this would be at least 64 bits.
auto b = BitArray([
1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0,
1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0,
1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0,
1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1,
]);
b <<= 8;
assert(format("%b", b) ==
"00000000_10000000_"~
"11000000_11100000_"~
"11110000_11111000_"~
"11111100_11111110_"~
"11111111_10101010");
// Test right shift of more than one size_t's worth of bits
b <<= 68;
assert(format("%b", b) ==
"00000000_00000000_"~
"00000000_00000000_"~
"00000000_00000000_"~
"00000000_00000000_"~
"00000000_00001000");
b = BitArray([
1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0,
1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0,
1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0,
1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1,
]);
b >>= 8;
assert(format("%b", b) ==
"11000000_11100000_"~
"11110000_11111000_"~
"11111100_11111110_"~
"11111111_10101010_"~
"01010101_00000000");
// Test left shift of more than 1 size_t's worth of bits
b >>= 68;
assert(format("%b", b) ==
"01010000_00000000_"~
"00000000_00000000_"~
"00000000_00000000_"~
"00000000_00000000_"~
"00000000_00000000");
}
/***************************************
* Return a string representation of this BitArray.
*
* Two format specifiers are supported:
* $(LI $(B %s) which prints the bits as an array, and)
* $(LI $(B %b) which prints the bits as 8-bit byte packets)
* separated with an underscore.
*
* Params:
* sink = A `char` accepting
* $(REF_ALTTEXT output range, isOutputRange, std, range, primitives).
* fmt = A $(REF FormatSpec, std,format) which controls how the data
* is displayed.
*/
void toString(W)(ref W sink, scope const ref FormatSpec!char fmt) const
if (isOutputRange!(W, char))
{
const spec = fmt.spec;
switch (spec)
{
case 'b':
return formatBitString(sink);
case 's':
return formatBitArray(sink);
default:
throw new Exception("Unknown format specifier: %" ~ spec);
}
}
///
@system pure unittest
{
import std.format : format;
auto b = BitArray([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);
auto s1 = format("%s", b);
assert(s1 == "[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]");
auto s2 = format("%b", b);
assert(s2 == "00001111_00001111");
}
/***************************************
* Return a lazy range of the indices of set bits.
*/
@property auto bitsSet() const nothrow
{
import std.algorithm.iteration : filter, map, joiner;
import std.range : iota, chain;
return chain(
iota(fullWords)
.filter!(i => _ptr[i])()
.map!(i => BitsSet!size_t(_ptr[i], i * bitsPerSizeT))()
.joiner(),
iota(fullWords * bitsPerSizeT, _len)
.filter!(i => this[i])()
);
}
///
@system unittest
{
import std.algorithm.comparison : equal;
auto b1 = BitArray([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);
assert(b1.bitsSet.equal([4, 5, 6, 7, 12, 13, 14, 15]));
BitArray b2;
b2.length = 1000;
b2[333] = true;
b2[666] = true;
b2[999] = true;
assert(b2.bitsSet.equal([333, 666, 999]));
}
@system unittest
{
import std.algorithm.comparison : equal;
import std.range : iota;
BitArray b;
enum wordBits = size_t.sizeof * 8;
b = BitArray([size_t.max], 0);
assert(b.bitsSet.empty);
b = BitArray([size_t.max], 1);
assert(b.bitsSet.equal([0]));
b = BitArray([size_t.max], wordBits);
assert(b.bitsSet.equal(iota(wordBits)));
b = BitArray([size_t.max, size_t.max], wordBits);
assert(b.bitsSet.equal(iota(wordBits)));
b = BitArray([size_t.max, size_t.max], wordBits + 1);
assert(b.bitsSet.equal(iota(wordBits + 1)));
b = BitArray([size_t.max, size_t.max], wordBits * 2);
assert(b.bitsSet.equal(iota(wordBits * 2)));
}
// https://issues.dlang.org/show_bug.cgi?id=20241
@system unittest
{
BitArray ba;
ba.length = 2;
ba[1] = 1;
ba.length = 1;
assert(ba.bitsSet.empty);
}
private void formatBitString(Writer)(auto ref Writer sink) const
{
if (!length)
return;
auto leftover = _len % 8;
foreach (idx; 0 .. leftover)
{
put(sink, cast(char)(this[idx] + '0'));
}
if (leftover && _len > 8)
put(sink, "_");
size_t count;
foreach (idx; leftover .. _len)
{
put(sink, cast(char)(this[idx] + '0'));
if (++count == 8 && idx != _len - 1)
{
put(sink, "_");
count = 0;
}
}
}
private void formatBitArray(Writer)(auto ref Writer sink) const
{
put(sink, "[");
foreach (idx; 0 .. _len)
{
put(sink, cast(char)(this[idx] + '0'));
if (idx + 1 < _len)
put(sink, ", ");
}
put(sink, "]");
}
// https://issues.dlang.org/show_bug.cgi?id=20639
// Separate @nogc test because public tests use array literals
// (and workarounds needlessly uglify those examples)
@system @nogc unittest
{
size_t[2] buffer;
BitArray b = BitArray(buffer[], buffer.sizeof * 8);
b[] = true;
b[0 .. 1] = true;
b.flip();
b.flip(1);
cast(void) b.count();
}
}
/// Slicing & bitsSet
@system unittest
{
import std.algorithm.comparison : equal;
import std.range : iota;
bool[] buf = new bool[64 * 3];
buf[0 .. 64] = true;
BitArray b = BitArray(buf);
assert(b.bitsSet.equal(iota(0, 64)));
b <<= 64;
assert(b.bitsSet.equal(iota(64, 128)));
}
/// Concatenation and appending
@system unittest
{
import std.algorithm.comparison : equal;
auto b = BitArray([1, 0]);
b ~= true;
assert(b[2] == 1);
b ~= BitArray([0, 1]);
auto c = BitArray([1, 0, 1, 0, 1]);
assert(b == c);
assert(b.bitsSet.equal([0, 2, 4]));
}
/// Bit flipping
@system unittest
{
import std.algorithm.comparison : equal;
auto b = BitArray([1, 1, 0, 1]);
b &= BitArray([0, 1, 1, 0]);
assert(b.bitsSet.equal([1]));
b.flip;
assert(b.bitsSet.equal([0, 2, 3]));
}
/// String format of bitarrays
@system unittest
{
import std.format : format;
auto b = BitArray([1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);
assert(format("%b", b) == "1_00001111_00001111");
}
///
@system unittest
{
import std.format : format;
BitArray b;
b = BitArray([]);
assert(format("%s", b) == "[]");
assert(format("%b", b) is null);
b = BitArray([1]);
assert(format("%s", b) == "[1]");
assert(format("%b", b) == "1");
b = BitArray([0, 0, 0, 0]);
assert(format("%b", b) == "0000");
b = BitArray([0, 0, 0, 0, 1, 1, 1, 1]);
assert(format("%s", b) == "[0, 0, 0, 0, 1, 1, 1, 1]");
assert(format("%b", b) == "00001111");
b = BitArray([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);
assert(format("%s", b) == "[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]");
assert(format("%b", b) == "00001111_00001111");
b = BitArray([1, 0, 0, 0, 0, 1, 1, 1, 1]);
assert(format("%b", b) == "1_00001111");
b = BitArray([1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]);
assert(format("%b", b) == "1_00001111_00001111");
}
/++
Swaps the endianness of the given integral value or character.
+/
T swapEndian(T)(const T val) @safe pure nothrow @nogc
if (isIntegral!T || isSomeChar!T || isBoolean!T)
{
import core.bitop : bswap, byteswap;
static if (val.sizeof == 1)
return val;
else static if (T.sizeof == 2)
return cast(T) byteswap(cast(ushort) val);
else static if (T.sizeof == 4)
return cast(T) bswap(cast(uint) val);
else static if (T.sizeof == 8)
return cast(T) bswap(cast(ulong) val);
else
static assert(0, T.stringof ~ " unsupported by swapEndian.");
}
///
@safe unittest
{
assert(42.swapEndian == 704643072);
assert(42.swapEndian.swapEndian == 42); // reflexive
assert(1.swapEndian == 16777216);
assert(true.swapEndian == true);
assert(byte(10).swapEndian == 10);
assert(char(10).swapEndian == 10);
assert(ushort(10).swapEndian == 2560);
assert(long(10).swapEndian == 720575940379279360);
assert(ulong(10).swapEndian == 720575940379279360);
}
@safe unittest
{
import std.meta;
import std.stdio;
static foreach (T; AliasSeq!(bool, byte, ubyte, short, ushort, int, uint, long, ulong, char, wchar, dchar))
{{
scope(failure) writeln("Failed type: ", T.stringof);
T val;
const T cval;
immutable T ival;
assert(swapEndian(swapEndian(val)) == val);
assert(swapEndian(swapEndian(cval)) == cval);
assert(swapEndian(swapEndian(ival)) == ival);
assert(swapEndian(swapEndian(T.min)) == T.min);
assert(swapEndian(swapEndian(T.max)) == T.max);
// Check CTFE compiles.
static assert(swapEndian(swapEndian(T(1))) is T(1));
foreach (i; 2 .. 10)
{
immutable T maxI = cast(T)(T.max / i);
immutable T minI = cast(T)(T.min / i);
assert(swapEndian(swapEndian(maxI)) == maxI);
static if (isSigned!T)
assert(swapEndian(swapEndian(minI)) == minI);
}
static if (isSigned!T)
assert(swapEndian(swapEndian(cast(T) 0)) == 0);
// used to trigger https://issues.dlang.org/show_bug.cgi?id=6354
static if (T.sizeof > 1 && isUnsigned!T)
{
T left = 0xffU;
left <<= (T.sizeof - 1) * 8;
T right = 0xffU;
for (size_t i = 1; i < T.sizeof; ++i)
{
assert(swapEndian(left) == right);
assert(swapEndian(right) == left);
left >>= 8;
right <<= 8;
}
}
}}
}
private union EndianSwapper(T)
if (canSwapEndianness!T)
{
Unqual!T value;
ubyte[T.sizeof] array;
static if (is(FloatingPointTypeOf!(Unqual!T) == float))
uint intValue;
else static if (is(FloatingPointTypeOf!(Unqual!T) == double))
ulong intValue;
}
// Can't use EndianSwapper union during CTFE.
private auto ctfeRead(T)(const ubyte[T.sizeof] array)
if (__traits(isIntegral, T))
{
Unqual!T result;
version (LittleEndian)
foreach_reverse (b; array)
result = cast(Unqual!T) ((result << 8) | b);
else
foreach (b; array)
result = cast(Unqual!T) ((result << 8) | b);
return cast(T) result;
}
// Can't use EndianSwapper union during CTFE.
private auto ctfeBytes(T)(const T value)
if (__traits(isIntegral, T))
{
ubyte[T.sizeof] result;
Unqual!T tmp = value;
version (LittleEndian)
{
foreach (i; 0 .. T.sizeof)
{
result[i] = cast(ubyte) tmp;
tmp = cast(Unqual!T) (tmp >>> 8);
}
}
else
{
foreach_reverse (i; 0 .. T.sizeof)
{
result[i] = cast(ubyte) tmp;
tmp = cast(Unqual!T) (tmp >>> 8);
}
}
return result;
}
/++
Converts the given value from the native endianness to big endian and
returns it as a `ubyte[n]` where `n` is the size of the given type.
Returning a `ubyte[n]` helps prevent accidentally using a swapped value
as a regular one (and in the case of floating point values, it's necessary,
because the FPU will mess up any swapped floating point values. So, you
can't actually have swapped floating point values as floating point values).
`real` is not supported, because its size is implementation-dependent
and therefore could vary from machine to machine (which could make it
unusable if you tried to transfer it to another machine).
+/
auto nativeToBigEndian(T)(const T val) @safe pure nothrow @nogc
if (canSwapEndianness!T)
{
version (LittleEndian)
return nativeToEndianImpl!true(val);
else
return nativeToEndianImpl!false(val);
}
///
@safe unittest
{
int i = 12345;
ubyte[4] swappedI = nativeToBigEndian(i);
assert(i == bigEndianToNative!int(swappedI));
float f = 123.45f;
ubyte[4] swappedF = nativeToBigEndian(f);
assert(f == bigEndianToNative!float(swappedF));
const float cf = 123.45f;
ubyte[4] swappedCF = nativeToBigEndian(cf);
assert(cf == bigEndianToNative!float(swappedCF));
double d = 123.45;
ubyte[8] swappedD = nativeToBigEndian(d);
assert(d == bigEndianToNative!double(swappedD));
const double cd = 123.45;
ubyte[8] swappedCD = nativeToBigEndian(cd);
assert(cd == bigEndianToNative!double(swappedCD));
}
private auto nativeToEndianImpl(bool swap, T)(const T val) @safe pure nothrow @nogc
if (__traits(isIntegral, T))
{
if (!__ctfe)
{
static if (swap)
return EndianSwapper!T(swapEndian(val)).array;
else
return EndianSwapper!T(val).array;
}
else
{
// Can't use EndianSwapper in CTFE.
static if (swap)
return ctfeBytes(swapEndian(val));
else
return ctfeBytes(val);
}
}
@safe unittest
{
import std.meta;
import std.stdio;
static foreach (T; AliasSeq!(bool, byte, ubyte, short, ushort, int, uint, long, ulong,
char, wchar, dchar
/* The trouble here is with floats and doubles being compared against nan
* using a bit compare. There are two kinds of nans, quiet and signaling.
* When a nan passes through the x87, it converts signaling to quiet.
* When a nan passes through the XMM, it does not convert signaling to quiet.
* float.init is a signaling nan.
* The binary API sometimes passes the data through the XMM, sometimes through
* the x87, meaning these will fail the 'is' bit compare under some circumstances.
* I cannot think of a fix for this that makes consistent sense.
*/
/*,float, double*/))
{{
scope(failure) writeln("Failed type: ", T.stringof);
T val;
const T cval;
immutable T ival;
//is instead of == because of NaN for floating point values.
assert(bigEndianToNative!T(nativeToBigEndian(val)) is val);
assert(bigEndianToNative!T(nativeToBigEndian(cval)) is cval);
assert(bigEndianToNative!T(nativeToBigEndian(ival)) is ival);
assert(bigEndianToNative!T(nativeToBigEndian(T.min)) == T.min);
assert(bigEndianToNative!T(nativeToBigEndian(T.max)) == T.max);
//Check CTFE compiles.
static assert(bigEndianToNative!T(nativeToBigEndian(T(1))) is T(1));
static if (isSigned!T)
assert(bigEndianToNative!T(nativeToBigEndian(cast(T) 0)) == 0);
static if (!is(T == bool))
{
foreach (i; [2, 4, 6, 7, 9, 11])
{
immutable T maxI = cast(T)(T.max / i);
immutable T minI = cast(T)(T.min / i);
assert(bigEndianToNative!T(nativeToBigEndian(maxI)) == maxI);
static if (T.sizeof > 1)
assert(nativeToBigEndian(maxI) != nativeToLittleEndian(maxI));
else
assert(nativeToBigEndian(maxI) == nativeToLittleEndian(maxI));
static if (isSigned!T)
{
assert(bigEndianToNative!T(nativeToBigEndian(minI)) == minI);
static if (T.sizeof > 1)
assert(nativeToBigEndian(minI) != nativeToLittleEndian(minI));
else
assert(nativeToBigEndian(minI) == nativeToLittleEndian(minI));
}
}
}
static if (isUnsigned!T || T.sizeof == 1 || is(T == wchar))
assert(nativeToBigEndian(T.max) == nativeToLittleEndian(T.max));
else
assert(nativeToBigEndian(T.max) != nativeToLittleEndian(T.max));
static if (isUnsigned!T || T.sizeof == 1 || isSomeChar!T)
assert(nativeToBigEndian(T.min) == nativeToLittleEndian(T.min));
else
assert(nativeToBigEndian(T.min) != nativeToLittleEndian(T.min));
}}
}
/++
Converts the given value from big endian to the native endianness and
returns it. The value is given as a `ubyte[n]` where `n` is the size
of the target type. You must give the target type as a template argument,
because there are multiple types with the same size and so the type of the
argument is not enough to determine the return type.
Taking a `ubyte[n]` helps prevent accidentally using a swapped value
as a regular one (and in the case of floating point values, it's necessary,
because the FPU will mess up any swapped floating point values. So, you
can't actually have swapped floating point values as floating point values).
+/
T bigEndianToNative(T, size_t n)(ubyte[n] val) @safe pure nothrow @nogc
if (canSwapEndianness!T && n == T.sizeof)
{
version (LittleEndian)
return endianToNativeImpl!(true, T, n)(val);
else
return endianToNativeImpl!(false, T, n)(val);
}
///
@safe unittest
{
ushort i = 12345;
ubyte[2] swappedI = nativeToBigEndian(i);
assert(i == bigEndianToNative!ushort(swappedI));
dchar c = 'D';
ubyte[4] swappedC = nativeToBigEndian(c);
assert(c == bigEndianToNative!dchar(swappedC));
}
/++
Converts the given value from the native endianness to little endian and
returns it as a `ubyte[n]` where `n` is the size of the given type.
Returning a `ubyte[n]` helps prevent accidentally using a swapped value
as a regular one (and in the case of floating point values, it's necessary,
because the FPU will mess up any swapped floating point values. So, you
can't actually have swapped floating point values as floating point values).
+/
auto nativeToLittleEndian(T)(const T val) @safe pure nothrow @nogc
if (canSwapEndianness!T)
{
version (BigEndian)
return nativeToEndianImpl!true(val);
else
return nativeToEndianImpl!false(val);
}
///
@safe unittest
{
int i = 12345;
ubyte[4] swappedI = nativeToLittleEndian(i);
assert(i == littleEndianToNative!int(swappedI));
double d = 123.45;
ubyte[8] swappedD = nativeToLittleEndian(d);
assert(d == littleEndianToNative!double(swappedD));
}
@safe unittest
{
import std.meta;
import std.stdio;
static foreach (T; AliasSeq!(bool, byte, ubyte, short, ushort, int, uint, long, ulong,
char, wchar, dchar/*,
float, double*/))
{{
scope(failure) writeln("Failed type: ", T.stringof);
T val;
const T cval;
immutable T ival;
//is instead of == because of NaN for floating point values.
assert(littleEndianToNative!T(nativeToLittleEndian(val)) is val);
assert(littleEndianToNative!T(nativeToLittleEndian(cval)) is cval);
assert(littleEndianToNative!T(nativeToLittleEndian(ival)) is ival);
assert(littleEndianToNative!T(nativeToLittleEndian(T.min)) == T.min);
assert(littleEndianToNative!T(nativeToLittleEndian(T.max)) == T.max);
//Check CTFE compiles.
static assert(littleEndianToNative!T(nativeToLittleEndian(T(1))) is T(1));
static if (isSigned!T)
assert(littleEndianToNative!T(nativeToLittleEndian(cast(T) 0)) == 0);
static if (!is(T == bool))
{
foreach (i; 2 .. 10)
{
immutable T maxI = cast(T)(T.max / i);
immutable T minI = cast(T)(T.min / i);
assert(littleEndianToNative!T(nativeToLittleEndian(maxI)) == maxI);
static if (isSigned!T)
assert(littleEndianToNative!T(nativeToLittleEndian(minI)) == minI);
}
}
}}
}
/++
Converts the given value from little endian to the native endianness and
returns it. The value is given as a `ubyte[n]` where `n` is the size
of the target type. You must give the target type as a template argument,
because there are multiple types with the same size and so the type of the
argument is not enough to determine the return type.
Taking a `ubyte[n]` helps prevent accidentally using a swapped value
as a regular one (and in the case of floating point values, it's necessary,
because the FPU will mess up any swapped floating point values. So, you
can't actually have swapped floating point values as floating point values).
`real` is not supported, because its size is implementation-dependent
and therefore could vary from machine to machine (which could make it
unusable if you tried to transfer it to another machine).
+/
T littleEndianToNative(T, size_t n)(ubyte[n] val) @safe pure nothrow @nogc
if (canSwapEndianness!T && n == T.sizeof)
{
version (BigEndian)
return endianToNativeImpl!(true, T, n)(val);
else
return endianToNativeImpl!(false, T, n)(val);
}
///
@safe unittest
{
ushort i = 12345;
ubyte[2] swappedI = nativeToLittleEndian(i);
assert(i == littleEndianToNative!ushort(swappedI));
dchar c = 'D';
ubyte[4] swappedC = nativeToLittleEndian(c);
assert(c == littleEndianToNative!dchar(swappedC));
}
private T endianToNativeImpl(bool swap, T, size_t n)(ubyte[n] val) @nogc nothrow pure @safe
if (__traits(isIntegral, T) && n == T.sizeof)
{
if (!__ctfe)
{
EndianSwapper!T es = { array: val };
static if (swap)
return swapEndian(es.value);
else
return es.value;
}
else
{
static if (swap)
return swapEndian(ctfeRead!T(val));
else
return ctfeRead!T(val);
}
}
private auto nativeToEndianImpl(bool swap, T)(const T val) @trusted pure nothrow @nogc
if (isFloatOrDouble!T)
{
if (!__ctfe)
{
EndianSwapper!T es = EndianSwapper!T(val);
static if (swap)
es.intValue = swapEndian(es.intValue);
return es.array;
}
else
{
static if (T.sizeof == 4)
uint intValue = *cast(const uint*) &val;
else static if (T.sizeof == 8)
ulong intValue = *cast(const ulong*) & val;
static if (swap)
intValue = swapEndian(intValue);
return ctfeBytes(intValue);
}
}
private auto endianToNativeImpl(bool swap, T, size_t n)(ubyte[n] val) @trusted pure nothrow @nogc
if (isFloatOrDouble!T && n == T.sizeof)
{
if (!__ctfe)
{
EndianSwapper!T es = { array: val };
static if (swap)
es.intValue = swapEndian(es.intValue);
return es.value;
}
else
{
static if (n == 4)
uint x = ctfeRead!uint(val);
else static if (n == 8)
ulong x = ctfeRead!ulong(val);
static if (swap)
x = swapEndian(x);
return *cast(T*) &x;
}
}
private template isFloatOrDouble(T)
{
enum isFloatOrDouble = isFloatingPoint!T &&
!is(immutable FloatingPointTypeOf!T == immutable real);
}
@safe unittest
{
import std.meta;
static foreach (T; AliasSeq!(float, double))
{
static assert(isFloatOrDouble!(T));
static assert(isFloatOrDouble!(const T));
static assert(isFloatOrDouble!(immutable T));
static assert(isFloatOrDouble!(shared T));
static assert(isFloatOrDouble!(shared(const T)));
static assert(isFloatOrDouble!(shared(immutable T)));
}
static assert(!isFloatOrDouble!(real));
static assert(!isFloatOrDouble!(const real));
static assert(!isFloatOrDouble!(immutable real));
static assert(!isFloatOrDouble!(shared real));
static assert(!isFloatOrDouble!(shared(const real)));
static assert(!isFloatOrDouble!(shared(immutable real)));
}
private template canSwapEndianness(T)
{
enum canSwapEndianness = isIntegral!T ||
isSomeChar!T ||
isBoolean!T ||
isFloatOrDouble!T;
}
@safe unittest
{
import std.meta;
static foreach (T; AliasSeq!(bool, ubyte, byte, ushort, short, uint, int, ulong,
long, char, wchar, dchar, float, double))
{
static assert(canSwapEndianness!(T));
static assert(canSwapEndianness!(const T));
static assert(canSwapEndianness!(immutable T));
static assert(canSwapEndianness!(shared(T)));
static assert(canSwapEndianness!(shared(const T)));
static assert(canSwapEndianness!(shared(immutable T)));
}
//!
static foreach (T; AliasSeq!(real, string, wstring, dstring))
{
static assert(!canSwapEndianness!(T));
static assert(!canSwapEndianness!(const T));
static assert(!canSwapEndianness!(immutable T));
static assert(!canSwapEndianness!(shared(T)));
static assert(!canSwapEndianness!(shared(const T)));
static assert(!canSwapEndianness!(shared(immutable T)));
}
}
/++
Takes a range of `ubyte`s and converts the first `T.sizeof` bytes to
`T`. The value returned is converted from the given endianness to the
native endianness. The range is not consumed.
Params:
T = The integral type to convert the first `T.sizeof` bytes to.
endianness = The endianness that the bytes are assumed to be in.
range = The range to read from.
index = The index to start reading from (instead of starting at the
front). If index is a pointer, then it is updated to the index
after the bytes read. The overloads with index are only
available if `hasSlicing!R` is `true`.
+/
T peek(T, Endian endianness = Endian.bigEndian, R)(R range)
if (canSwapEndianness!T &&
isForwardRange!R &&
is(ElementType!R : const ubyte))
{
static if (hasSlicing!R)
const ubyte[T.sizeof] bytes = range[0 .. T.sizeof];
else
{
ubyte[T.sizeof] bytes;
//Make sure that range is not consumed, even if it's a class.
range = range.save;
foreach (ref e; bytes)
{
e = range.front;
range.popFront();
}
}
static if (endianness == Endian.bigEndian)
return bigEndianToNative!T(bytes);
else
return littleEndianToNative!T(bytes);
}
/++ Ditto +/
T peek(T, Endian endianness = Endian.bigEndian, R)(R range, size_t index)
if (canSwapEndianness!T &&
isForwardRange!R &&
hasSlicing!R &&
is(ElementType!R : const ubyte))
{
return peek!(T, endianness)(range, &index);
}
/++ Ditto +/
T peek(T, Endian endianness = Endian.bigEndian, R)(R range, size_t* index)
if (canSwapEndianness!T &&
isForwardRange!R &&
hasSlicing!R &&
is(ElementType!R : const ubyte))
{
assert(index, "index must not point to null");
immutable begin = *index;
immutable end = begin + T.sizeof;
const ubyte[T.sizeof] bytes = range[begin .. end];
*index = end;
static if (endianness == Endian.bigEndian)
return bigEndianToNative!T(bytes);
else
return littleEndianToNative!T(bytes);
}
///
@system unittest
{
ubyte[] buffer = [1, 5, 22, 9, 44, 255, 8];
assert(buffer.peek!uint() == 17110537);
assert(buffer.peek!ushort() == 261);
assert(buffer.peek!ubyte() == 1);
assert(buffer.peek!uint(2) == 369700095);
assert(buffer.peek!ushort(2) == 5641);
assert(buffer.peek!ubyte(2) == 22);
size_t index = 0;
assert(buffer.peek!ushort(&index) == 261);
assert(index == 2);
assert(buffer.peek!uint(&index) == 369700095);
assert(index == 6);
assert(buffer.peek!ubyte(&index) == 8);
assert(index == 7);
}
///
@safe unittest
{
import std.algorithm.iteration : filter;
ubyte[] buffer = [1, 5, 22, 9, 44, 255, 7];
auto range = filter!"true"(buffer);
assert(range.peek!uint() == 17110537);
assert(range.peek!ushort() == 261);
assert(range.peek!ubyte() == 1);
}
@system unittest
{
{
//bool
ubyte[] buffer = [0, 1];
assert(buffer.peek!bool() == false);
assert(buffer.peek!bool(1) == true);
size_t index = 0;
assert(buffer.peek!bool(&index) == false);
assert(index == 1);
assert(buffer.peek!bool(&index) == true);
assert(index == 2);
}
{
//char (8bit)
ubyte[] buffer = [97, 98, 99, 100];
assert(buffer.peek!char() == 'a');
assert(buffer.peek!char(1) == 'b');
size_t index = 0;
assert(buffer.peek!char(&index) == 'a');
assert(index == 1);
assert(buffer.peek!char(&index) == 'b');
assert(index == 2);
}
{
//wchar (16bit - 2x ubyte)
ubyte[] buffer = [1, 5, 32, 29, 1, 7];
assert(buffer.peek!wchar() == 'ą');
assert(buffer.peek!wchar(2) == '”');
assert(buffer.peek!wchar(4) == 'ć');
size_t index = 0;
assert(buffer.peek!wchar(&index) == 'ą');
assert(index == 2);
assert(buffer.peek!wchar(&index) == '”');
assert(index == 4);
assert(buffer.peek!wchar(&index) == 'ć');
assert(index == 6);
}
{
//dchar (32bit - 4x ubyte)
ubyte[] buffer = [0, 0, 1, 5, 0, 0, 32, 29, 0, 0, 1, 7];
assert(buffer.peek!dchar() == 'ą');
assert(buffer.peek!dchar(4) == '”');
assert(buffer.peek!dchar(8) == 'ć');
size_t index = 0;
assert(buffer.peek!dchar(&index) == 'ą');
assert(index == 4);
assert(buffer.peek!dchar(&index) == '”');
assert(index == 8);
assert(buffer.peek!dchar(&index) == 'ć');
assert(index == 12);
}
{
//float (32bit - 4x ubyte)
ubyte[] buffer = [66, 0, 0, 0, 65, 200, 0, 0];
assert(buffer.peek!float()== 32.0);
assert(buffer.peek!float(4) == 25.0f);
size_t index = 0;
assert(buffer.peek!float(&index) == 32.0f);
assert(index == 4);
assert(buffer.peek!float(&index) == 25.0f);
assert(index == 8);
}
{
//double (64bit - 8x ubyte)
ubyte[] buffer = [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0];
assert(buffer.peek!double() == 32.0);
assert(buffer.peek!double(8) == 25.0);
size_t index = 0;
assert(buffer.peek!double(&index) == 32.0);
assert(index == 8);
assert(buffer.peek!double(&index) == 25.0);
assert(index == 16);
}
{
//enum
ubyte[] buffer = [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 30];
enum Foo
{
one = 10,
two = 20,
three = 30
}
assert(buffer.peek!Foo() == Foo.one);
assert(buffer.peek!Foo(0) == Foo.one);
assert(buffer.peek!Foo(4) == Foo.two);
assert(buffer.peek!Foo(8) == Foo.three);
size_t index = 0;
assert(buffer.peek!Foo(&index) == Foo.one);
assert(index == 4);
assert(buffer.peek!Foo(&index) == Foo.two);
assert(index == 8);
assert(buffer.peek!Foo(&index) == Foo.three);
assert(index == 12);
}
{
//enum - bool
ubyte[] buffer = [0, 1];
enum Bool: bool
{
bfalse = false,
btrue = true,
}
assert(buffer.peek!Bool() == Bool.bfalse);
assert(buffer.peek!Bool(0) == Bool.bfalse);
assert(buffer.peek!Bool(1) == Bool.btrue);
size_t index = 0;
assert(buffer.peek!Bool(&index) == Bool.bfalse);
assert(index == 1);
assert(buffer.peek!Bool(&index) == Bool.btrue);
assert(index == 2);
}
{
//enum - float
ubyte[] buffer = [66, 0, 0, 0, 65, 200, 0, 0];
enum Float: float
{
one = 32.0f,
two = 25.0f
}
assert(buffer.peek!Float() == Float.one);
assert(buffer.peek!Float(0) == Float.one);
assert(buffer.peek!Float(4) == Float.two);
size_t index = 0;
assert(buffer.peek!Float(&index) == Float.one);
assert(index == 4);
assert(buffer.peek!Float(&index) == Float.two);
assert(index == 8);
}
{
//enum - double
ubyte[] buffer = [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0];
enum Double: double
{
one = 32.0,
two = 25.0
}
assert(buffer.peek!Double() == Double.one);
assert(buffer.peek!Double(0) == Double.one);
assert(buffer.peek!Double(8) == Double.two);
size_t index = 0;
assert(buffer.peek!Double(&index) == Double.one);
assert(index == 8);
assert(buffer.peek!Double(&index) == Double.two);
assert(index == 16);
}
{
//enum - real
ubyte[] buffer = [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0];
enum Real: real
{
one = 32.0,
two = 25.0
}
static assert(!__traits(compiles, buffer.peek!Real()));
}
}
/++
Takes a range of `ubyte`s and converts the first `T.sizeof` bytes to
`T`. The value returned is converted from the given endianness to the
native endianness. The `T.sizeof` bytes which are read are consumed from
the range.
Params:
T = The integral type to convert the first `T.sizeof` bytes to.
endianness = The endianness that the bytes are assumed to be in.
range = The range to read from.
+/
T read(T, Endian endianness = Endian.bigEndian, R)(ref R range)
if (canSwapEndianness!T && isInputRange!R && is(ElementType!R : const ubyte))
{
static if (hasSlicing!R && is(typeof(R.init[0 .. 0]) : const(ubyte)[]))
{
const ubyte[T.sizeof] bytes = range[0 .. T.sizeof];
range.popFrontN(T.sizeof);
}
else
{
ubyte[T.sizeof] bytes;
foreach (ref e; bytes)
{
e = range.front;
range.popFront();
}
}
static if (endianness == Endian.bigEndian)
return bigEndianToNative!T(bytes);
else
return littleEndianToNative!T(bytes);
}
///
@safe unittest
{
import std.range.primitives : empty;
ubyte[] buffer = [1, 5, 22, 9, 44, 255, 8];
assert(buffer.length == 7);
assert(buffer.read!ushort() == 261);
assert(buffer.length == 5);
assert(buffer.read!uint() == 369700095);
assert(buffer.length == 1);
assert(buffer.read!ubyte() == 8);
assert(buffer.empty);
}
@safe unittest
{
{
//bool
ubyte[] buffer = [0, 1];
assert(buffer.length == 2);
assert(buffer.read!bool() == false);
assert(buffer.length == 1);
assert(buffer.read!bool() == true);
assert(buffer.empty);
}
{
//char (8bit)
ubyte[] buffer = [97, 98, 99];
assert(buffer.length == 3);
assert(buffer.read!char() == 'a');
assert(buffer.length == 2);
assert(buffer.read!char() == 'b');
assert(buffer.length == 1);
assert(buffer.read!char() == 'c');
assert(buffer.empty);
}
{
//wchar (16bit - 2x ubyte)
ubyte[] buffer = [1, 5, 32, 29, 1, 7];
assert(buffer.length == 6);
assert(buffer.read!wchar() == 'ą');
assert(buffer.length == 4);
assert(buffer.read!wchar() == '”');
assert(buffer.length == 2);
assert(buffer.read!wchar() == 'ć');
assert(buffer.empty);
}
{
//dchar (32bit - 4x ubyte)
ubyte[] buffer = [0, 0, 1, 5, 0, 0, 32, 29, 0, 0, 1, 7];
assert(buffer.length == 12);
assert(buffer.read!dchar() == 'ą');
assert(buffer.length == 8);
assert(buffer.read!dchar() == '”');
assert(buffer.length == 4);
assert(buffer.read!dchar() == 'ć');
assert(buffer.empty);
}
{
//float (32bit - 4x ubyte)
ubyte[] buffer = [66, 0, 0, 0, 65, 200, 0, 0];
assert(buffer.length == 8);
assert(buffer.read!float()== 32.0);
assert(buffer.length == 4);
assert(buffer.read!float() == 25.0f);
assert(buffer.empty);
}
{
//double (64bit - 8x ubyte)
ubyte[] buffer = [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0];
assert(buffer.length == 16);
assert(buffer.read!double() == 32.0);
assert(buffer.length == 8);
assert(buffer.read!double() == 25.0);
assert(buffer.empty);
}
{
//enum - uint
ubyte[] buffer = [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 30];
assert(buffer.length == 12);
enum Foo
{
one = 10,
two = 20,
three = 30
}
assert(buffer.read!Foo() == Foo.one);
assert(buffer.length == 8);
assert(buffer.read!Foo() == Foo.two);
assert(buffer.length == 4);
assert(buffer.read!Foo() == Foo.three);
assert(buffer.empty);
}
{
//enum - bool
ubyte[] buffer = [0, 1];
assert(buffer.length == 2);
enum Bool: bool
{
bfalse = false,
btrue = true,
}
assert(buffer.read!Bool() == Bool.bfalse);
assert(buffer.length == 1);
assert(buffer.read!Bool() == Bool.btrue);
assert(buffer.empty);
}
{
//enum - float
ubyte[] buffer = [66, 0, 0, 0, 65, 200, 0, 0];
assert(buffer.length == 8);
enum Float: float
{
one = 32.0f,
two = 25.0f
}
assert(buffer.read!Float() == Float.one);
assert(buffer.length == 4);
assert(buffer.read!Float() == Float.two);
assert(buffer.empty);
}
{
//enum - double
ubyte[] buffer = [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0];
assert(buffer.length == 16);
enum Double: double
{
one = 32.0,
two = 25.0
}
assert(buffer.read!Double() == Double.one);
assert(buffer.length == 8);
assert(buffer.read!Double() == Double.two);
assert(buffer.empty);
}
{
//enum - real
ubyte[] buffer = [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0];
enum Real: real
{
one = 32.0,
two = 25.0
}
static assert(!__traits(compiles, buffer.read!Real()));
}
}
// https://issues.dlang.org/show_bug.cgi?id=17247
@safe unittest
{
struct UbyteRange
{
ubyte[] impl;
@property bool empty() { return impl.empty; }
@property ubyte front() { return impl.front; }
void popFront() { impl.popFront(); }
@property UbyteRange save() { return this; }
// N.B. support slicing but do not return ubyte[] slices.
UbyteRange opSlice(size_t start, size_t end)
{
return UbyteRange(impl[start .. end]);
}
@property size_t length() { return impl.length; }
alias opDollar = length;
}
static assert(hasSlicing!UbyteRange);
auto r = UbyteRange([0x01, 0x00, 0x00, 0x00]);
int x = r.read!(int, Endian.littleEndian)();
assert(x == 1);
}
/++
Takes an integral value, converts it to the given endianness, and writes it
to the given range of `ubyte`s as a sequence of `T.sizeof` `ubyte`s
starting at index. `hasSlicing!R` must be `true`.
Params:
T = The integral type to convert the first `T.sizeof` bytes to.
endianness = The endianness to _write the bytes in.
range = The range to _write to.
value = The value to _write.
index = The index to start writing to. If index is a pointer, then it
is updated to the index after the bytes read.
+/
void write(T, Endian endianness = Endian.bigEndian, R)(R range, const T value, size_t index)
if (canSwapEndianness!T &&
isForwardRange!R &&
hasSlicing!R &&
is(ElementType!R : ubyte))
{
write!(T, endianness)(range, value, &index);
}
/++ Ditto +/
void write(T, Endian endianness = Endian.bigEndian, R)(R range, const T value, size_t* index)
if (canSwapEndianness!T &&
isForwardRange!R &&
hasSlicing!R &&
is(ElementType!R : ubyte))
{
assert(index, "index must not point to null");
static if (endianness == Endian.bigEndian)
immutable bytes = nativeToBigEndian!T(value);
else
immutable bytes = nativeToLittleEndian!T(value);
immutable begin = *index;
immutable end = begin + T.sizeof;
*index = end;
range[begin .. end] = bytes[0 .. T.sizeof];
}
///
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0];
buffer.write!uint(29110231u, 0);
assert(buffer == [1, 188, 47, 215, 0, 0, 0, 0]);
buffer.write!ushort(927, 0);
assert(buffer == [3, 159, 47, 215, 0, 0, 0, 0]);
buffer.write!ubyte(42, 0);
assert(buffer == [42, 159, 47, 215, 0, 0, 0, 0]);
}
///
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0];
buffer.write!uint(142700095u, 2);
assert(buffer == [0, 0, 8, 129, 110, 63, 0, 0, 0]);
buffer.write!ushort(19839, 2);
assert(buffer == [0, 0, 77, 127, 110, 63, 0, 0, 0]);
buffer.write!ubyte(132, 2);
assert(buffer == [0, 0, 132, 127, 110, 63, 0, 0, 0]);
}
///
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0];
size_t index = 0;
buffer.write!ushort(261, &index);
assert(buffer == [1, 5, 0, 0, 0, 0, 0, 0]);
assert(index == 2);
buffer.write!uint(369700095u, &index);
assert(buffer == [1, 5, 22, 9, 44, 255, 0, 0]);
assert(index == 6);
buffer.write!ubyte(8, &index);
assert(buffer == [1, 5, 22, 9, 44, 255, 8, 0]);
assert(index == 7);
}
/// bool
@system unittest
{
ubyte[] buffer = [0, 0];
buffer.write!bool(false, 0);
assert(buffer == [0, 0]);
buffer.write!bool(true, 0);
assert(buffer == [1, 0]);
buffer.write!bool(true, 1);
assert(buffer == [1, 1]);
buffer.write!bool(false, 1);
assert(buffer == [1, 0]);
size_t index = 0;
buffer.write!bool(false, &index);
assert(buffer == [0, 0]);
assert(index == 1);
buffer.write!bool(true, &index);
assert(buffer == [0, 1]);
assert(index == 2);
}
/// char(8-bit)
@system unittest
{
ubyte[] buffer = [0, 0, 0];
buffer.write!char('a', 0);
assert(buffer == [97, 0, 0]);
buffer.write!char('b', 1);
assert(buffer == [97, 98, 0]);
size_t index = 0;
buffer.write!char('a', &index);
assert(buffer == [97, 98, 0]);
assert(index == 1);
buffer.write!char('b', &index);
assert(buffer == [97, 98, 0]);
assert(index == 2);
buffer.write!char('c', &index);
assert(buffer == [97, 98, 99]);
assert(index == 3);
}
/// wchar (16bit - 2x ubyte)
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0];
buffer.write!wchar('ą', 0);
assert(buffer == [1, 5, 0, 0]);
buffer.write!wchar('”', 2);
assert(buffer == [1, 5, 32, 29]);
size_t index = 0;
buffer.write!wchar('ć', &index);
assert(buffer == [1, 7, 32, 29]);
assert(index == 2);
buffer.write!wchar('ą', &index);
assert(buffer == [1, 7, 1, 5]);
assert(index == 4);
}
/// dchar (32bit - 4x ubyte)
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0];
buffer.write!dchar('ą', 0);
assert(buffer == [0, 0, 1, 5, 0, 0, 0, 0]);
buffer.write!dchar('”', 4);
assert(buffer == [0, 0, 1, 5, 0, 0, 32, 29]);
size_t index = 0;
buffer.write!dchar('ć', &index);
assert(buffer == [0, 0, 1, 7, 0, 0, 32, 29]);
assert(index == 4);
buffer.write!dchar('ą', &index);
assert(buffer == [0, 0, 1, 7, 0, 0, 1, 5]);
assert(index == 8);
}
/// float (32bit - 4x ubyte)
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0];
buffer.write!float(32.0f, 0);
assert(buffer == [66, 0, 0, 0, 0, 0, 0, 0]);
buffer.write!float(25.0f, 4);
assert(buffer == [66, 0, 0, 0, 65, 200, 0, 0]);
size_t index = 0;
buffer.write!float(25.0f, &index);
assert(buffer == [65, 200, 0, 0, 65, 200, 0, 0]);
assert(index == 4);
buffer.write!float(32.0f, &index);
assert(buffer == [65, 200, 0, 0, 66, 0, 0, 0]);
assert(index == 8);
}
/// double (64bit - 8x ubyte)
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
buffer.write!double(32.0, 0);
assert(buffer == [64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
buffer.write!double(25.0, 8);
assert(buffer == [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0]);
size_t index = 0;
buffer.write!double(25.0, &index);
assert(buffer == [64, 57, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0]);
assert(index == 8);
buffer.write!double(32.0, &index);
assert(buffer == [64, 57, 0, 0, 0, 0, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0]);
assert(index == 16);
}
/// enum
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
enum Foo
{
one = 10,
two = 20,
three = 30
}
buffer.write!Foo(Foo.one, 0);
assert(buffer == [0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0]);
buffer.write!Foo(Foo.two, 4);
assert(buffer == [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 0]);
buffer.write!Foo(Foo.three, 8);
assert(buffer == [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 30]);
size_t index = 0;
buffer.write!Foo(Foo.three, &index);
assert(buffer == [0, 0, 0, 30, 0, 0, 0, 20, 0, 0, 0, 30]);
assert(index == 4);
buffer.write!Foo(Foo.one, &index);
assert(buffer == [0, 0, 0, 30, 0, 0, 0, 10, 0, 0, 0, 30]);
assert(index == 8);
buffer.write!Foo(Foo.two, &index);
assert(buffer == [0, 0, 0, 30, 0, 0, 0, 10, 0, 0, 0, 20]);
assert(index == 12);
}
// enum - bool
@system unittest
{
ubyte[] buffer = [0, 0];
enum Bool: bool
{
bfalse = false,
btrue = true,
}
buffer.write!Bool(Bool.btrue, 0);
assert(buffer == [1, 0]);
buffer.write!Bool(Bool.btrue, 1);
assert(buffer == [1, 1]);
size_t index = 0;
buffer.write!Bool(Bool.bfalse, &index);
assert(buffer == [0, 1]);
assert(index == 1);
buffer.write!Bool(Bool.bfalse, &index);
assert(buffer == [0, 0]);
assert(index == 2);
}
/// enum - float
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0];
enum Float: float
{
one = 32.0f,
two = 25.0f
}
buffer.write!Float(Float.one, 0);
assert(buffer == [66, 0, 0, 0, 0, 0, 0, 0]);
buffer.write!Float(Float.two, 4);
assert(buffer == [66, 0, 0, 0, 65, 200, 0, 0]);
size_t index = 0;
buffer.write!Float(Float.two, &index);
assert(buffer == [65, 200, 0, 0, 65, 200, 0, 0]);
assert(index == 4);
buffer.write!Float(Float.one, &index);
assert(buffer == [65, 200, 0, 0, 66, 0, 0, 0]);
assert(index == 8);
}
/// enum - double
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
enum Double: double
{
one = 32.0,
two = 25.0
}
buffer.write!Double(Double.one, 0);
assert(buffer == [64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
buffer.write!Double(Double.two, 8);
assert(buffer == [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0]);
size_t index = 0;
buffer.write!Double(Double.two, &index);
assert(buffer == [64, 57, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0]);
assert(index == 8);
buffer.write!Double(Double.one, &index);
assert(buffer == [64, 57, 0, 0, 0, 0, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0]);
assert(index == 16);
}
/// enum - real
@system unittest
{
ubyte[] buffer = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
enum Real: real
{
one = 32.0,
two = 25.0
}
static assert(!__traits(compiles, buffer.write!Real(Real.one)));
}
/++
Takes an integral value, converts it to the given endianness, and appends
it to the given range of `ubyte`s (using `put`) as a sequence of
`T.sizeof` `ubyte`s starting at index. `hasSlicing!R` must be
`true`.
Params:
T = The integral type to convert the first `T.sizeof` bytes to.
endianness = The endianness to write the bytes in.
range = The range to _append to.
value = The value to _append.
+/
void append(T, Endian endianness = Endian.bigEndian, R)(R range, const T value)
if (canSwapEndianness!T && isOutputRange!(R, ubyte))
{
static if (endianness == Endian.bigEndian)
immutable bytes = nativeToBigEndian!T(value);
else
immutable bytes = nativeToLittleEndian!T(value);
put(range, bytes[]);
}
///
@safe unittest
{
import std.array;
auto buffer = appender!(const ubyte[])();
buffer.append!ushort(261);
assert(buffer.data == [1, 5]);
buffer.append!uint(369700095u);
assert(buffer.data == [1, 5, 22, 9, 44, 255]);
buffer.append!ubyte(8);
assert(buffer.data == [1, 5, 22, 9, 44, 255, 8]);
}
/// bool
@safe unittest
{
import std.array : appender;
auto buffer = appender!(const ubyte[])();
buffer.append!bool(true);
assert(buffer.data == [1]);
buffer.append!bool(false);
assert(buffer.data == [1, 0]);
}
/// char wchar dchar
@safe unittest
{
import std.array : appender;
auto buffer = appender!(const ubyte[])();
buffer.append!char('a');
assert(buffer.data == [97]);
buffer.append!char('b');
assert(buffer.data == [97, 98]);
buffer.append!wchar('ą');
assert(buffer.data == [97, 98, 1, 5]);
buffer.append!dchar('ą');
assert(buffer.data == [97, 98, 1, 5, 0, 0, 1, 5]);
}
/// float double
@safe unittest
{
import std.array : appender;
auto buffer = appender!(const ubyte[])();
buffer.append!float(32.0f);
assert(buffer.data == [66, 0, 0, 0]);
buffer.append!double(32.0);
assert(buffer.data == [66, 0, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0]);
}
/// enum
@safe unittest
{
import std.array : appender;
auto buffer = appender!(const ubyte[])();
enum Foo
{
one = 10,
two = 20,
three = 30
}
buffer.append!Foo(Foo.one);
assert(buffer.data == [0, 0, 0, 10]);
buffer.append!Foo(Foo.two);
assert(buffer.data == [0, 0, 0, 10, 0, 0, 0, 20]);
buffer.append!Foo(Foo.three);
assert(buffer.data == [0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 30]);
}
/// enum - bool
@safe unittest
{
import std.array : appender;
auto buffer = appender!(const ubyte[])();
enum Bool: bool
{
bfalse = false,
btrue = true,
}
buffer.append!Bool(Bool.btrue);
assert(buffer.data == [1]);
buffer.append!Bool(Bool.bfalse);
assert(buffer.data == [1, 0]);
buffer.append!Bool(Bool.btrue);
assert(buffer.data == [1, 0, 1]);
}
/// enum - float
@safe unittest
{
import std.array : appender;
auto buffer = appender!(const ubyte[])();
enum Float: float
{
one = 32.0f,
two = 25.0f
}
buffer.append!Float(Float.one);
assert(buffer.data == [66, 0, 0, 0]);
buffer.append!Float(Float.two);
assert(buffer.data == [66, 0, 0, 0, 65, 200, 0, 0]);
}
/// enum - double
@safe unittest
{
import std.array : appender;
auto buffer = appender!(const ubyte[])();
enum Double: double
{
one = 32.0,
two = 25.0
}
buffer.append!Double(Double.one);
assert(buffer.data == [64, 64, 0, 0, 0, 0, 0, 0]);
buffer.append!Double(Double.two);
assert(buffer.data == [64, 64, 0, 0, 0, 0, 0, 0, 64, 57, 0, 0, 0, 0, 0, 0]);
}
/// enum - real
@safe unittest
{
import std.array : appender;
auto buffer = appender!(const ubyte[])();
enum Real: real
{
one = 32.0,
two = 25.0
}
static assert(!__traits(compiles, buffer.append!Real(Real.one)));
}
@system unittest
{
import std.array;
import std.format : format;
import std.meta : AliasSeq;
static foreach (endianness; [Endian.bigEndian, Endian.littleEndian])
{{
auto toWrite = appender!(ubyte[])();
alias Types = AliasSeq!(uint, int, long, ulong, short, ubyte, ushort, byte, uint);
ulong[] values = [42, -11, long.max, 1098911981329L, 16, 255, 19012, 2, 17];
assert(Types.length == values.length);
size_t index = 0;
size_t length = 0;
static foreach (T; Types)
{
toWrite.append!(T, endianness)(cast(T) values[index++]);
length += T.sizeof;
}
auto toRead = toWrite.data;
assert(toRead.length == length);
index = 0;
static foreach (T; Types)
{
assert(toRead.peek!(T, endianness)() == values[index], format("Failed Index: %s", index));
assert(toRead.peek!(T, endianness)(0) == values[index], format("Failed Index: %s", index));
assert(toRead.length == length,
format("Failed Index [%s], Actual Length: %s", index, toRead.length));
assert(toRead.read!(T, endianness)() == values[index], format("Failed Index: %s", index));
length -= T.sizeof;
assert(toRead.length == length,
format("Failed Index [%s], Actual Length: %s", index, toRead.length));
++index;
}
assert(toRead.empty);
}}
}
/**
Counts the number of set bits in the binary representation of `value`.
For signed integers, the sign bit is included in the count.
*/
private uint countBitsSet(T)(const T value) @nogc pure nothrow
if (isIntegral!T)
{
static if (T.sizeof == 8)
{
import core.bitop : popcnt;
const c = popcnt(cast(ulong) value);
}
else static if (T.sizeof == 4)
{
import core.bitop : popcnt;
const c = popcnt(cast(uint) value);
}
// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
else static if (T.sizeof == 2)
{
uint c = value - ((value >> 1) & 0x5555);
c = ((c >> 2) & 0x3333) + (c & 0X3333);
c = ((c >> 4) + c) & 0x0F0F;
c = ((c >> 8) + c) & 0x00FF;
}
else static if (T.sizeof == 1)
{
uint c = value - ((value >> 1) & 0x55);
c = ((c >> 2) & 0x33) + (c & 0X33);
c = ((c >> 4) + c) & 0x0F;
}
else
{
static assert(false, "countBitsSet only supports 1, 2, 4, or 8 byte sized integers.");
}
return cast(uint) c;
}
@safe unittest
{
assert(countBitsSet(1) == 1);
assert(countBitsSet(0) == 0);
assert(countBitsSet(int.min) == 1);
assert(countBitsSet(uint.max) == 32);
}
@safe unittest
{
import std.meta;
static foreach (T; AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong))
{
assert(countBitsSet(cast(T) 0) == 0);
assert(countBitsSet(cast(T) 1) == 1);
assert(countBitsSet(cast(T) 2) == 1);
assert(countBitsSet(cast(T) 3) == 2);
assert(countBitsSet(cast(T) 4) == 1);
assert(countBitsSet(cast(T) 5) == 2);
assert(countBitsSet(cast(T) 127) == 7);
static if (isSigned!T)
{
assert(countBitsSet(cast(T)-1) == 8 * T.sizeof);
assert(countBitsSet(T.min) == 1);
}
else
{
assert(countBitsSet(T.max) == 8 * T.sizeof);
}
// Check CTFE compiles.
static assert(countBitsSet(cast(T) 1) == 1);
}
assert(countBitsSet(1_000_000) == 7);
foreach (i; 0 .. 63)
assert(countBitsSet(1UL << i) == 1);
}
private struct BitsSet(T)
{
static assert(T.sizeof <= 8, "bitsSet assumes T is no more than 64-bit.");
@nogc pure nothrow:
this(T value, size_t startIndex = 0)
{
_value = value;
// Further calculation is only valid and needed when the range is non-empty.
if (!_value)
return;
import core.bitop : bsf;
immutable trailingZerosCount = bsf(value);
_value >>>= trailingZerosCount;
_index = startIndex + trailingZerosCount;
}
@property size_t front() const
{
return _index;
}
@property bool empty() const
{
return !_value;
}
void popFront()
{
assert(_value, "Cannot call popFront on empty range.");
_value >>>= 1;
// Further calculation is only valid and needed when the range is non-empty.
if (!_value)
return;
import core.bitop : bsf;
immutable trailingZerosCount = bsf(_value);
_value >>>= trailingZerosCount;
_index += trailingZerosCount + 1;
}
@property BitsSet save() const
{
return this;
}
@property size_t length() const
{
return countBitsSet(_value);
}
private T _value;
private size_t _index;
}
/**
Range that iterates the indices of the set bits in `value`.
Index 0 corresponds to the least significant bit.
For signed integers, the highest index corresponds to the sign bit.
*/
auto bitsSet(T)(const T value) @nogc pure nothrow
if (isIntegral!T)
{
return BitsSet!T(value);
}
///
@safe unittest
{
import std.algorithm.comparison : equal;
import std.range : iota;
assert(bitsSet(1).equal([0]));
assert(bitsSet(5).equal([0, 2]));
assert(bitsSet(-1).equal(iota(32)));
assert(bitsSet(int.min).equal([31]));
}
@safe unittest
{
import std.algorithm.comparison : equal;
import std.range : iota;
import std.meta;
static foreach (T; AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong))
{
assert(bitsSet(cast(T) 0).empty);
assert(bitsSet(cast(T) 1).equal([0]));
assert(bitsSet(cast(T) 2).equal([1]));
assert(bitsSet(cast(T) 3).equal([0, 1]));
assert(bitsSet(cast(T) 4).equal([2]));
assert(bitsSet(cast(T) 5).equal([0, 2]));
assert(bitsSet(cast(T) 127).equal(iota(7)));
static if (isSigned!T)
{
assert(bitsSet(cast(T)-1).equal(iota(8 * T.sizeof)));
assert(bitsSet(T.min).equal([8 * T.sizeof - 1]));
}
else
{
assert(bitsSet(T.max).equal(iota(8 * T.sizeof)));
}
}
assert(bitsSet(1_000_000).equal([6, 9, 14, 16, 17, 18, 19]));
foreach (i; 0 .. 63)
assert(bitsSet(1UL << i).equal([i]));
}
| D |
// Copyright © 2011, Jakob Bornecrantz. All rights reserved.
// See copyright notice in src/charge/charge.d (GPLv2 only).
module test.game;
import std.math : pow, fmin, acos, PI;
import charge.charge;
import lib.sdl.sdl;
class Ticker : GameActor, GameTicker
{
protected:
GfxActor gfx;
PhyBody phy;
public:
this(GameWorld w)
{
super(w);
w.addTicker(this);
}
~this()
{
w.remTicker(this);
delete gfx;
delete phy;
}
void tick()
{
gfx.position = phy.position;
gfx.rotation = phy.rotation;
if (phy.position.y < -50) {
phy.position = Point3d(0.0, 3.0, -6.0);
phy.rotation = Quatd();
}
}
void force(bool inverse)
{
Vector3d vec = Point3d(0.0, 10.0, 0.0) - phy.position;
vec.normalize();
vec.scale(9.8);
if (inverse)
vec.scale(-1.0);
phy.addForce(vec);
}
}
class Cube : Ticker
{
this(GameWorld w, Point3d pos)
{
super(w);
gfx = GfxRigidModel(w.gfx, "res/cube.bin");
gfx.position = pos;
phy = new PhyCube(w.phy, pos);
}
}
class Sphere : Ticker
{
this(GameWorld w, Point3d pos)
{
super(w);
gfx = GfxRigidModel(w.gfx, "res/sphere.bin");
gfx.position = pos;
phy = new PhySphere(w.phy, pos);
}
}
class Car : Ticker
{
this(GameWorld w, Point3d pos)
{
super(w);
gfx = GfxRigidModel(w.gfx, "res/car.bin");
gfx.position = pos;
phy = car = new PhyCar(w.phy, pos);
car.massSetBox(10.0, 2.0, 1.0, 3.0);
car.collisionBoxAt(Point3d(0, 0.275, 0.075), 2.0, 0.75, 4.75);
car.collisionBoxAt(Point3d(0, 0.8075, 0.85), 1.3, 0.45, 2.4);
car.wheel[0].powered = true;
car.wheel[0].radius = 0.36;
car.wheel[0].rayLength = 0.76;
car.wheel[0].rayOffset = Vector3d( 0.82, 0.26, -1.5);
car.wheel[0].opposit = 1;
car.wheel[1].powered = true;
car.wheel[1].radius = 0.36;
car.wheel[1].rayLength = 0.76;
car.wheel[1].rayOffset = Vector3d(-0.82, 0.26, -1.5);
car.wheel[1].opposit = 0;
car.wheel[2].powered = false;
car.wheel[2].radius = 0.36;
car.wheel[2].rayLength = 0.76;
car.wheel[2].rayOffset = Vector3d( 0.82, 0.26, 1.5);
car.wheel[2].opposit = 3;
car.wheel[3].powered = false;
car.wheel[3].radius = 0.36;
car.wheel[3].rayLength = 0.76;
car.wheel[3].rayOffset = Vector3d(-0.82, 0.26, 1.5);
car.wheel[3].opposit = 2;
car.carPower = 0;
car.carDesiredVel = 0;
car.carBreakingMuFactor = 1.0;
car.carBreakingMuLimit = 20000;
car.carSpringMu = 0.01;
car.carSpringMu2 = 1.5;
car.carSpringErp = 0.2;
car.carSpringCfm = 0.03;
car.carDesiredTurn = 0;
car.carTurnSpeed = 0;
car.carTurn = 0;
car.carSwayFactor = 25.0;
car.carSwayForceLimit = 20000;
car.carSlip2Factor = 0.004;
car.carSlip2Limit = 0.01;
for (int i; i < 4; i++) {
wheels[i] = GfxRigidModel(w.gfx, "res/wheel2.bin");
}
}
~this()
{
foreach(w; wheels)
delete w;
}
void tick()
{
gfx.position = phy.position - (phy.rotation * Vector3d(0.0, 0.2, 0.0));
gfx.rotation = phy.rotation * Quatd(PI, Vector3d.Up);
for (int i; i < 4; i++)
car.setMoveWheel(i, wheels[i]);
auto v = car.velocity;
auto l = v.length;
v.normalize;
auto a = pow(cast(real)l, cast(uint)2);
v.scale(-0.01 * a);
car.addForce(v);
if (phy.position.y < -50) {
phy.position = Point3d(0.0, 3.0, -6.0);
phy.rotation = Quatd();
}
}
GfxCube coll;
GfxActor wheels[4];
PhyCar car;
}
class Game : GameSimpleApp
{
private:
bool moveing;
double heading;
double pitch;
bool force;
bool inverse;
bool forward;
bool backwards;
SysZipFile basePackage;
Car car;
GameWorld w;
Ticker removable[];
GfxSimpleLight sl;
GfxSpotLight spl;
GfxProjCamera cam;
GfxRenderer r;
GfxRigidModel model;
public:
mixin SysLogging;
this(string[] args)
{
/* This will initalize Core and other important things */
super();
basePackage = SysZipFile("base.chz");
running = true;
GfxRenderer.init();
w = new GameWorld();
sl = new GfxSimpleLight();
GfxDefaultTarget rt = GfxDefaultTarget();
cam = new GfxProjCamera(45.0, cast(double)rt.width / rt.height, 1, 150);
r = GfxRenderer.create();
cam.position = Point3d(0.0, 5.0, 15.0);
sl.rotation = Quatd(PI/3, -PI/4, 0.0);//Quatd(PI, Vector3d.Up) * sl.rotation;
sl.shadow = true;
w.gfx.add(sl);
auto pl = new GfxPointLight();
pl.position = Point3d(0.0, 0.0, 0.0);
pl.size = 20;
w.gfx.add(pl);
spl = new GfxSpotLight();
spl.position = Point3d(0.0, 5.0, 15.0);
spl.far = 150;
w.gfx.add(spl);
w.phy.setStepLength(10);
new GameStaticCube(w, Point3d(0.0, -5.0, 0.0), Quatd(), 200.0, 10.0, 200.0);
new GameStaticRigid(w, Point3d(0.0, 0.0, -15.0), Quatd(), "res/bath.bin", "res/bath.bin");
heading = 0.0;
pitch = 0.0;
l.info("Press 's' 'c' 'f' 'g' for fun");
car = new Car(w, Point3d(0.0, 3.0, -6.0));
new Car(w, Point3d(0.0, 3.0, 10.0));
}
~this()
{
delete basePackage;
delete w;
}
protected:
void addRemovable(Ticker t)
{
removable ~= t;
}
void input()
{
SDL_Event e;
while(SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
running = false;
}
if (e.type == SDL_KEYDOWN) {
if (e.key.keysym.sym == SDLK_r) {
car.car.position = Point3d(0.0, 3.0, -6.0);
car.car.rotation = Quatd();
}
if (e.key.keysym.sym == SDLK_f)
force = true;
if (e.key.keysym.sym == SDLK_g)
inverse = true;
if (e.key.keysym.sym == SDLK_UP)
forward = true;
if (e.key.keysym.sym == SDLK_DOWN)
backwards = true;
if (e.key.keysym.sym == SDLK_RIGHT) {
double s = -PI * 0.20;
car.car.setTurning(s, 0.01);
}
if (e.key.keysym.sym == SDLK_LEFT) {
double s = PI * 0.20;
car.car.setTurning(s, 0.01);
}
}
if (e.type == SDL_KEYUP) {
if (e.key.keysym.sym == SDLK_UP)
forward = false;
if (e.key.keysym.sym == SDLK_DOWN)
backwards = false;
if (e.key.keysym.sym == SDLK_RIGHT) {
car.car.setTurning(0, 0.15);
}
if (e.key.keysym.sym == SDLK_LEFT) {
car.car.setTurning(0, 0.15);
}
if (e.key.keysym.sym == SDLK_f)
force = false;
if (e.key.keysym.sym == SDLK_g)
inverse = false;
if (e.key.keysym.sym == SDLK_ESCAPE)
running = false;
if (e.key.keysym.sym == SDLK_s)
addRemovable(new Sphere(w, Point3d(0, 1, 0)));
if (e.key.keysym.sym == SDLK_c)
addRemovable(new Cube(w, Point3d(0, 1, 0)));
if (e.key.keysym.sym == SDLK_p) {
addRemovable(new Cube(w, Point3d( 4, 1, 0)));
addRemovable(new Cube(w, Point3d( 3, 1, 0)));
addRemovable(new Cube(w, Point3d( 2, 1, 0)));
addRemovable(new Cube(w, Point3d( 1, 1, 0)));
addRemovable(new Cube(w, Point3d( 0, 1, 0)));
addRemovable(new Cube(w, Point3d(-1, 1, 0)));
addRemovable(new Cube(w, Point3d(-2, 1, 0)));
addRemovable(new Cube(w, Point3d(-3, 1, 0)));
addRemovable(new Cube(w, Point3d(-4, 1, 0)));
addRemovable(new Cube(w, Point3d( 3.5, 2, 0)));
addRemovable(new Cube(w, Point3d( 2.5, 2, 0)));
addRemovable(new Cube(w, Point3d( 1.5, 2, 0)));
addRemovable(new Cube(w, Point3d( 0.5, 2, 0)));
addRemovable(new Cube(w, Point3d(-0.5, 2, 0)));
addRemovable(new Cube(w, Point3d(-1.5, 2, 0)));
addRemovable(new Cube(w, Point3d(-2.5, 2, 0)));
addRemovable(new Cube(w, Point3d(-3.5, 2, 0)));
addRemovable(new Cube(w, Point3d( 3, 3, 0)));
addRemovable(new Cube(w, Point3d( 2, 3, 0)));
addRemovable(new Cube(w, Point3d( 1, 3, 0)));
addRemovable(new Cube(w, Point3d( 0, 3, 0)));
addRemovable(new Cube(w, Point3d(-1, 3, 0)));
addRemovable(new Cube(w, Point3d(-2, 3, 0)));
addRemovable(new Cube(w, Point3d(-3, 3, 0)));
addRemovable(new Cube(w, Point3d( 2.5, 4, 0)));
addRemovable(new Cube(w, Point3d( 1.5, 4, 0)));
addRemovable(new Cube(w, Point3d( 0.5, 4, 0)));
addRemovable(new Cube(w, Point3d(-0.5, 4, 0)));
addRemovable(new Cube(w, Point3d(-1.5, 4, 0)));
addRemovable(new Cube(w, Point3d(-2.5, 4, 0)));
addRemovable(new Cube(w, Point3d( 2, 5, 0)));
addRemovable(new Cube(w, Point3d( 1, 5, 0)));
addRemovable(new Cube(w, Point3d( 0, 5, 0)));
addRemovable(new Cube(w, Point3d(-1, 5, 0)));
addRemovable(new Cube(w, Point3d(-2, 5, 0)));
addRemovable(new Cube(w, Point3d( 1.5, 6, 0)));
addRemovable(new Cube(w, Point3d( 0.5, 6, 0)));
addRemovable(new Cube(w, Point3d(-0.5, 6, 0)));
addRemovable(new Cube(w, Point3d(-1.5, 6, 0)));
addRemovable(new Cube(w, Point3d( 1, 7, 0)));
addRemovable(new Cube(w, Point3d( 0, 7, 0)));
addRemovable(new Cube(w, Point3d(-1, 7, 0)));
addRemovable(new Cube(w, Point3d( 0.5, 8, 0)));
addRemovable(new Cube(w, Point3d(-0.5, 8, 0)));
addRemovable(new Cube(w, Point3d( 0, 9, 0)));
}
if (e.key.keysym.sym == SDLK_o) {
foreach(r; removable)
delete r;
removable.length = 0;
}
}
if (e.type == SDL_MOUSEMOTION && moveing) {
double xrel = e.motion.xrel;
double yrel = e.motion.yrel;
heading += xrel / 1000.0;
pitch += yrel / 1000.0;
cam.rotation = Quatd(heading, 0, pitch);
}
if (e.type == SDL_MOUSEBUTTONDOWN && e.button.button == 1)
moveing = true;
if (e.type == SDL_MOUSEBUTTONUP && e.button.button == 1)
moveing = false;
}
}
void logic()
{
w.tick();
if (force || inverse)
foreach(a; w.actors) {
auto ticker = cast(Ticker)a;
if (ticker !is null)
ticker.force(inverse);
}
if (forward && !backwards)
car.car.setAllWheelPower(100.0, 40.0);
else if (!forward && backwards)
car.car.setAllWheelPower(-10.0, 40.0);
else
car.car.setAllWheelPower(0.0, 0.0);
spl.position = car.car.position;
spl.rotation = car.car.rotation;
auto v = car.car.rotation.rotateHeading;
v.y = 0;
v.normalize();
v.scale(-10.0);
v.y = 3.0;
v = (car.car.position + v) - cam.position;
double scale = v.lengthSqrd * 0.002 + v.length * 0.04;
scale = fmin(v.length, scale);
v.normalize();
v.scale(scale);
cam.position = cam.position + v;
auto v2 = car.car.position - cam.position;
v2.y = 0;
v2.normalize();
auto angle = acos(Vector3d.Heading.dot(v2));
/* since we actualy don't do a cross to get the axis */
if (v2.x > 0)
angle = -angle;
cam.rotation = Quatd(angle, Vector3d.Up);
}
void render()
{
GfxDefaultTarget rt = GfxDefaultTarget();
rt.clear();
r.target = rt;
r.render(cam, w.gfx);
rt.swap();
}
void network()
{
}
void close()
{
}
}
| D |
/*
REQUIRED_ARGS: -HC=verbose -c -o-
PERMUTE_ARGS:
TEST_OUTPUT:
---
// Automatically generated by Digital Mars D Compiler v$n$
#pragma once
#include <assert.h>
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#ifdef CUSTOM_D_ARRAY_TYPE
#define _d_dynamicArray CUSTOM_D_ARRAY_TYPE
#else
/// Represents a D [] array
template<typename T>
struct _d_dynamicArray final
{
size_t length;
T *ptr;
_d_dynamicArray() : length(0), ptr(NULL) { }
_d_dynamicArray(size_t length_in, T *ptr_in)
: length(length_in), ptr(ptr_in) { }
T& operator[](const size_t idx) {
assert(idx < length);
return ptr[idx];
}
const T& operator[](const size_t idx) const {
assert(idx < length);
return ptr[idx];
}
};
#endif
struct Foo final
{
int32_t a;
enum : int32_t { b = 2 };
// Ignored enum `dtoh_21217.Foo.c` because it is `private`.
protected:
enum : int32_t { d = 4 };
enum : int32_t { e = 5 };
public:
enum : int32_t { f = 6 };
enum : int32_t { g = 7 };
private:
enum class Bar
{
a = 1,
b = 2,
};
// Ignored enum `dtoh_21217.Foo.h` because it is `private`.
public:
Foo() :
a(1)
{
}
Foo(int32_t a) :
a(a)
{}
};
---
*/
extern(C++) struct Foo {
int a = 1;
enum b = 2;
private enum c = 3;
protected enum d = 4;
package enum e = 5;
public enum f = 6;
export enum g = 7;
private enum Bar { a = 1, b = 2 }
private enum h = Bar.a;
}
| D |
/**
* Generates the .pdata and .xdata sections for Win64
*
* Compiler implementation of the
* $(LINK2 https://www.dlang.org, D programming language).
*
* Copyright: Copyright (C) 2012-2023 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/backend/pdata.d, backend/pdata.d)
*/
module dmd.backend.pdata;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import dmd.backend.cc;
import dmd.backend.cdef;
import dmd.backend.code;
import dmd.backend.code_x86;
import dmd.backend.dt;
import dmd.backend.el;
import dmd.backend.global;
import dmd.backend.obj;
import dmd.backend.rtlsym;
import dmd.backend.ty;
import dmd.backend.type;
extern (C++):
nothrow:
// Determine if this Symbol is stored in a COMDAT
private bool symbol_iscomdat3(Symbol* s)
{
return s.Sclass == SC.comdat ||
config.flags2 & CFG2comdat && s.Sclass == SC.inline ||
config.flags4 & CFG4allcomdat && s.Sclass == SC.global;
}
enum ALLOCA_LIMIT = 0x10000;
/**********************************
* The .pdata section is used on Win64 by the VS debugger and dbghelp to get information
* to walk the stack and unwind exceptions.
* Absent it, it is assumed to be a "leaf function" where [RSP] is the return address.
* Creates an instance of struct RUNTIME_FUNCTION:
* https://msdn.microsoft.com/en-US/library/ft9x1kdx%28v=vs.100%29.aspx
*
* Params:
* sf = function to generate unwind data for
*/
public void win64_pdata(Symbol *sf)
{
//printf("win64_pdata()\n");
assert(config.exe == EX_WIN64);
// Generate the pdata name, which is $pdata$funcname
size_t sflen = strlen(sf.Sident.ptr);
char *pdata_name = cast(char *)(sflen < ALLOCA_LIMIT ? alloca(7 + sflen + 1) : malloc(7 + sflen + 1));
assert(pdata_name);
memcpy(pdata_name, "$pdata$".ptr, 7);
memcpy(pdata_name + 7, sf.Sident.ptr, sflen + 1); // include terminating 0
Symbol *spdata = symbol_name(pdata_name[0 .. 7 + sflen],SC.static_,tstypes[TYint]);
symbol_keep(spdata);
symbol_debug(spdata);
Symbol *sunwind = win64_unwind(sf);
/* 3 pointers are emitted:
* 1. pointer to start of function sf
* 2. pointer past end of function sf
* 3. pointer to unwind data
*/
auto dtb = DtBuilder(0);
dtb.xoff(sf,0,TYint); // Note the TYint, these are 32 bit fixups
dtb.xoff(sf,cast(uint)(retoffset + retsize),TYint);
dtb.xoff(sunwind,0,TYint);
spdata.Sdt = dtb.finish();
spdata.Sseg = symbol_iscomdat3(sf) ? MsCoffObj_seg_pdata_comdat(sf) : MsCoffObj_seg_pdata();
spdata.Salignment = 4;
outdata(spdata);
if (sflen >= ALLOCA_LIMIT) free(pdata_name);
}
private:
/**************************************************
* Unwind data symbol goes in the .xdata section.
* Input:
* sf function to generate unwind data for
* Returns:
* generated symbol referring to unwind data
*/
private Symbol *win64_unwind(Symbol *sf)
{
// Generate the unwind name, which is $unwind$funcname
size_t sflen = strlen(sf.Sident.ptr);
char *unwind_name = cast(char *)(sflen < ALLOCA_LIMIT ? alloca(8 + sflen + 1) : malloc(8 + sflen + 1));
assert(unwind_name);
memcpy(unwind_name, "$unwind$".ptr, 8);
memcpy(unwind_name + 8, sf.Sident.ptr, sflen + 1); // include terminating 0
Symbol *sunwind = symbol_name(unwind_name[0 .. 8 + sflen],SC.static_,tstypes[TYint]);
symbol_keep(sunwind);
symbol_debug(sunwind);
sunwind.Sdt = unwind_data();
sunwind.Sseg = symbol_iscomdat3(sf) ? MsCoffObj_seg_xdata_comdat(sf) : MsCoffObj_seg_xdata();
sunwind.Salignment = 1;
outdata(sunwind);
if (sflen >= ALLOCA_LIMIT) free(unwind_name);
return sunwind;
}
/************************* Win64 Unwind Data ******************************************/
/************************************************************************
* Creates an instance of struct UNWIND_INFO:
* https://msdn.microsoft.com/en-US/library/ddssxxy8%28v=vs.100%29.aspx
*/
enum UWOP
{ // http://www.osronline.com/ddkx/kmarch/64bitamd_7btz.htm
// http://uninformed.org/index.cgi?v=4&a=1&p=17
PUSH_NONVOL, // push saved register, OpInfo is register
ALLOC_LARGE, // alloc large size on stack, OpInfo is 0 or 1
ALLOC_SMALL, // alloc small size on stack, OpInfo is size / 8 - 1
SET_FPREG, // set frame pointer
SAVE_NONVOL, // save register, OpInfo is reg, frame offset in next FrameOffset
SAVE_NONVOL_FAR, // save register, OpInfo is reg, frame offset in next 2 FrameOffsets
SAVE_XMM128, // save 64 bits of XMM reg, frame offset in next FrameOffset
SAVE_XMM128_FAR, // save 64 bits of XMM reg, frame offset in next 2 FrameOffsets
PUSH_MACHFRAME // push interrupt frame, OpInfo is 0 or 1 (pushes error code too)
}
union UNWIND_CODE
{
/+
struct
{
ubyte CodeOffset; // offset of start of next instruction
ubyte UnwindOp : 4; // UWOP
ubyte OpInfo : 4; // extra information depending on UWOP
} op;
+/
ushort FrameOffset;
}
ushort setUnwindCode(ubyte CodeOffset, ubyte UnwindOp, ubyte OpInfo)
{
return cast(ushort)(CodeOffset | (UnwindOp << 8) | (OpInfo << 12));
}
enum
{
UNW_FLAG_EHANDLER = 1, // function has an exception handler
UNW_FLAG_UHANDLER = 2, // function has a termination handler
UNW_FLAG_CHAININFO = 4 // not the primary one for the function
}
struct UNWIND_INFO
{
ubyte Version; //: 3; // 1
//ubyte Flags : 5; // UNW_FLAG_xxxx
ubyte SizeOfProlog; // bytes in the function prolog
ubyte CountOfCodes; // dimension of UnwindCode[]
ubyte FrameRegister; //: 4; // if !=0, then frame pointer register
//ubyte FrameOffset : 4; // frame register offset from RSP divided by 16
UNWIND_CODE[6] UnwindCode;
static if (0)
{
UNWIND_CODE[((CountOfCodes + 1) & ~1) - 1] MoreUnwindCode;
union
{
// UNW_FLAG_EHANDLER | UNW_FLAG_UHANDLER
struct
{
uint ExceptionHandler;
void[n] Language_specific_handler_data;
}
// UNW_FLAG_CHAININFO
RUNTIME_FUNCTION chained_unwind_info;
}
}
}
private dt_t *unwind_data()
{
UNWIND_INFO ui;
/* 4 allocation size strategy:
* 0: no unwind instruction
* 8..128: UWOP.ALLOC_SMALL
* 136..512K-8: UWOP.ALLOC_LARGE, OpInfo = 0
* 512K..4GB-8: UWOP.ALLOC_LARGE, OpInfo = 1
*/
targ_size_t sz = localsize;
assert((localsize & 7) == 0);
int strategy;
if (sz == 0)
strategy = 0;
else if (sz <= 128)
strategy = 1;
else if (sz <= 512 * 1024 - 8)
strategy = 2;
else
// 512KB to 4GB-8
strategy = 3;
ui.Version = 1;
//ui.Flags = 0;
ui.SizeOfProlog = cast(ubyte)startoffset;
static if (0)
{
ui.CountOfCodes = strategy + 1;
ui.FrameRegister = 0;
//ui.FrameOffset = 0;
}
else
{
strategy = 0;
ui.CountOfCodes = cast(ubyte)(strategy + 2);
ui.FrameRegister = BP;
//ui.FrameOffset = 0; //cod3_spoff() / 16;
}
static if (0)
{
switch (strategy)
{
case 0:
break;
case 1:
ui.UnwindCode[0].FrameOffset = setUnwindCode(prolog_allocoffset, UWOP.ALLOC_SMALL, (sz - 8) / 8);
break;
case 2:
ui.UnwindCode[0].FrameOffset = setUnwindCode(prolog_allocoffset, UWOP.ALLOC_LARGE, 0);
ui.UnwindCode[1].FrameOffset = (sz - 8) / 8;
break;
case 3:
ui.UnwindCode[0].FrameOffset = setUnwindCode(prolog_allocoffset, UWOP.ALLOC_LARGE, 1);
ui.UnwindCode[1].FrameOffset = sz & 0x0FFFF;
ui.UnwindCode[2].FrameOffset = sz / 0x10000;
break;
}
}
static if (1)
{
ui.UnwindCode[ui.CountOfCodes-2].FrameOffset = setUnwindCode(4, UWOP.SET_FPREG, 0);
}
ui.UnwindCode[ui.CountOfCodes-1].FrameOffset = setUnwindCode(1, UWOP.PUSH_NONVOL, BP);
auto dtb = DtBuilder(0);
dtb.nbytes(4 + ((ui.CountOfCodes + 1) & ~1) * 2,cast(char *)&ui);
return dtb.finish();
}
| D |
module mach.math.sqrt;
private:
import core.math : coresqrt = sqrt;
import mach.traits : isFloatingPoint, isIntegral, isImaginary, isComplex;
import mach.traits : isSigned, FloatingPointType, ImaginaryType;
import mach.math.floats.properties : fiszero;
import mach.math.sign : signof;
import mach.math.abs : uabs;
/++ Docs
This module defines the `sqrt` and `isqrt` functions.
`sqrt` may be used to determine the square root of any numeric, imaginary, or
complex input.
When pasing an integer or float to `sqrt`, the return type is a float.
Negative inputs produce a NaN output. Infinity produces an infinite output.
When passing an imaginary or complex number to `sqrt`, the return type is a
complex number.
+/
unittest{ /// Example
assert(sqrt(4) == 2);
assert(sqrt(256) == 16);
}
/++ Docs
The `isqrt` function is an optimized equivalent to calling `floor(sqrt(abs(i)))`
for some integer input.
Its return type is the same as its input type.
+/
unittest{ /// Example
assert(isqrt(4) == 2);
assert(isqrt(15) == 3);
}
public:
/// Positive square root of 2.
enum real Sqrt2 = 1.414213562373095048801688724209698078569671875376948073176L;
/// Get the principal square root of an integer as a floating point number.
auto sqrt(T)(in T value) if(isIntegral!T){
return sqrt(cast(real) value);
}
/// Get the principal square root of a floating point number.
auto sqrt(T)(in T value) if(isFloatingPoint!T){
return coresqrt(value);
}
/// Get the principal square root of an imaginary number, which is a complex number.
auto sqrt(T)(in T value) if(isImaginary!T){
alias F = FloatingPointType!T;
immutable x = (F(1) / F(Sqrt2)) * sqrt(value.im);
return x + x * T(1i);
}
auto sqrt(T)(in T value) if(isComplex!T) out{
// Workaround https://issues.dlang.org/show_bug.cgi?id=17173
}body{
alias F = FloatingPointType!T;
alias I = ImaginaryType!T;
if(value.im.fiszero){
if(value.re > 0){
return sqrt(value.re) + I(0i);
}else{
return F(0) + sqrt(-value.re) * I(1i);
}
}else{
immutable x = sqrt(value.re * value.re + value.im * value.im);
return (F(1) / F(Sqrt2)) * (
sqrt(x + value.re) + sqrt(x - value.re) * signof(value.im) * I(1i)
);
}
}
/// Get floor(sqrt(abs(i))) of an integer as a value of the same integer type.
/// Credit http://stackoverflow.com/a/1101217/3478907
auto isqrt(T)(in T value) if(isIntegral!T){
static if(isSigned!T){
return cast(T) isqrt(uabs(value));
}else{
T one = T(1) << (T.sizeof * 8 - 2);
T op = value;
T result = 0;
while(one > value) one >>= 2;
while(one){
if(op >= result + one){
op -= result + one;
result += one << 1;
}
result >>= 1;
one >>= 2;
}
return result;
}
}
private version(unittest){
import mach.traits.primitives : NumericTypes, IntegralTypes, FloatingPointTypes;
import mach.math.abs : abs;
import mach.math.floats.properties;
import mach.math.floats.compare : fnearequal;
}
unittest{ /// Perfect squares
foreach(T; NumericTypes){
assert(sqrt(T(0)) == 0);
assert(sqrt(T(1)) == 1);
assert(sqrt(T(4)) == 2);
assert(sqrt(T(64)) == 8);
assert(sqrt(T(81)) == 9);
assert(sqrt(T(100)) == 10);
}
}
unittest{ /// Special float cases
foreach(T; FloatingPointTypes){
assert(sqrt(T(-0.0)) == 0);
assert(sqrt(T.infinity).fisposinf);
assert(sqrt(-T.infinity).fisnan);
assert(sqrt(T.nan).fisnan);
assert(sqrt(T(-1)).fisnan);
assert(sqrt(T(-1000)).fisnan);
}
}
unittest{ /// Negative integers
assert(sqrt(int(-1)).fisnan);
assert(sqrt(short.min).fisnan);
}
unittest{ /// Imaginary numbers
assert(sqrt(0i) == 0);
assert(fnearequal(sqrt(8i).re, 2.0));
assert(fnearequal(sqrt(8i).im, 2.0));
assert(fnearequal(sqrt(128i).re, 8.0));
assert(fnearequal(sqrt(128i).im, 8.0));
immutable result = sqrt(ireal(14i));
immutable expected = 2.6457513110645905905016L;
immutable epsilon = 1e-18;
assert(result.re == result.im);
assert(abs(expected - result.re) < epsilon);
}
unittest{ /// Complex numbers
assert(sqrt(0 + 0i) == 0);
assert(fnearequal(sqrt(64 + 0i), 8+0i));
assert(fnearequal(sqrt(-64 + 0i), 0+8i));
immutable aresult = sqrt(creal(+64 + 64i));
immutable bresult = sqrt(creal(-64 + 64i));
immutable expectedre = 8.7894729077424797283184L;
immutable expectedim = 3.6407188844978187304348L;
immutable epsilon = 1e-18;
assert(abs(expectedre - aresult.re) < epsilon);
assert(abs(expectedim - aresult.im) < epsilon);
assert(abs(expectedre - bresult.im) < epsilon);
assert(abs(expectedim - bresult.re) < epsilon);
}
unittest{ /// Integer sqrt
foreach(T; IntegralTypes){
// Perfect squares
assert(isqrt(T(0)) == 0);
assert(isqrt(T(1)) == 1);
assert(isqrt(T(4)) == 2);
assert(isqrt(T(16)) == 4);
assert(isqrt(T(100)) == 10);
// Imperfect, rounded down
assert(isqrt(T(2)) == 1);
assert(isqrt(T(3)) == 1);
assert(isqrt(T(5)) == 2);
assert(isqrt(T(15)) == 3);
assert(isqrt(T(120)) == 10);
// Negative inputs
static if(isSigned!T){
assert(isqrt(T(-4)) == 2);
assert(isqrt(T(-16)) == 4);
assert(isqrt(T(-99)) == 9);
}
}
}
| D |
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Port to the D programming language:
* Frank Benoit <benoit@tionex.de>
*******************************************************************************/
module dwtx.draw2d.RoutingAnimator;
import dwt.dwthelper.utils;
import dwtx.draw2d.geometry.Point;
import dwtx.draw2d.geometry.PointList;
import dwtx.draw2d.Animator;
import dwtx.draw2d.RoutingListener;
import dwtx.draw2d.IFigure;
import dwtx.draw2d.Connection;
import dwtx.draw2d.Animation;
/**
* Animates the routing of a connection. The animator will capture the effects of the
* connection's router, and the play back the placement of the routing, interpolating the
* intermediate routes.
* <P>
* To use a routing animator, hook it as a routing listener for the connection whose
* points are to be animated, by calling {@link
* PolylineConnection#addRoutingListener(RoutingListener)}. An animator is active
* only when the Animation utility is activated.
*
* @since 3.2
*/
public class RoutingAnimator : Animator , RoutingListener {
private static RoutingAnimator INSTANCE_;
static RoutingAnimator INSTANCE(){
if( INSTANCE_ is null ){
synchronized( RoutingAnimator.classinfo ){
if( INSTANCE_ is null ){
INSTANCE_ = new RoutingAnimator();
}
}
}
return INSTANCE_;
}
/**
* Constructs a routing animator for use with one or more connections. The default
* instance ({@link #getDefault()} can be used on any number of connections.
*
* @since 3.2
*/
protected this() { }
/**
* Overridden to sync initial and final states.
* @see Animator#playbackStarting(IFigure)
*/
public void playbackStarting(IFigure connection) {
reconcileStates(cast(Connection)connection);
}
/**
* Returns the current state of the connection. Currently, this is a copy of the list of
* points. However this Object could change in future releases and should not be
* considered API.
* @see Animator#getCurrentState(IFigure)
*/
protected Object getCurrentState(IFigure connection) {
return (cast(Connection)connection).getPoints().getCopy();
}
/**
* Returns the default instance.
* @return the default instance
* @since 3.2
*/
public static RoutingAnimator getDefault() {
return INSTANCE;
}
/**
* Hooks invalidate for animation purposes.
* @see RoutingListener#invalidate(Connection)
*/
public final void invalidate(Connection conn) {
if (Animation.isInitialRecording())
Animation.hookAnimator(conn, this);
}
/**
* Plays back the interpolated state.
* @see Animator#playback(IFigure)
*/
protected bool playback(IFigure figure) {
Connection conn = cast(Connection) figure;
PointList list1 = cast(PointList)Animation.getInitialState(this, conn);
PointList list2 = cast(PointList)Animation.getFinalState(this, conn);
if (list1 is null) {
conn.setVisible(false);
return true;
}
float progress = Animation.getProgress();
if (list1.size() is list2.size()) {
Point pt1 = new Point(), pt2 = new Point();
PointList points = conn.getPoints();
points.removeAllPoints();
for (int i = 0; i < list1.size(); i++) {
list1.getPoint(pt2, i);
list2.getPoint(pt1, i);
pt1.x = cast(int)Math.round(pt1.x * progress + (1 - progress) * pt2.x);
pt1.y = cast(int)Math.round(pt1.y * progress + (1 - progress) * pt2.y);
points.addPoint(pt1);
}
conn.setPoints(points);
}
return true;
}
/**
* Hooks post routing for animation purposes.
* @see RoutingListener#postRoute(Connection)
*/
public final void postRoute(Connection connection) {
if (Animation.isFinalRecording())
Animation.hookNeedsCapture(connection, this);
}
private void reconcileStates(Connection conn) {
PointList points1 = cast(PointList)Animation.getInitialState(this, conn);
PointList points2 = cast(PointList)Animation.getFinalState(this, conn);
if (points1 !is null && points1.size() !is points2.size()) {
Point p = new Point(), q = new Point();
int size1 = points1.size() - 1;
int size2 = points2.size() - 1;
int i1 = size1;
int i2 = size2;
double current1 = 1.0;
double current2 = 1.0;
double prev1 = 1.0;
double prev2 = 1.0;
while (i1 > 0 || i2 > 0) {
if (Math.abs(current1 - current2) < 0.1
&& i1 > 0 && i2 > 0) {
//Both points are the same, use them and go on;
prev1 = current1;
prev2 = current2;
i1--;
i2--;
current1 = cast(double)i1 / size1;
current2 = cast(double)i2 / size2;
} else if (current1 < current2) {
//2 needs to catch up
// current1 < current2 < prev1
points1.getPoint(p, i1);
points1.getPoint(q, i1 + 1);
p.x = cast(int)(((q.x * (current2 - current1) + p.x * (prev1 - current2))
/ (prev1 - current1)));
p.y = cast(int)(((q.y * (current2 - current1) + p.y * (prev1 - current2))
/ (prev1 - current1)));
points1.insertPoint(p, i1 + 1);
prev1 = prev2 = current2;
i2--;
current2 = cast(double)i2 / size2;
} else {
//1 needs to catch up
// current2< current1 < prev2
points2.getPoint(p, i2);
points2.getPoint(q, i2 + 1);
p.x = cast(int)(((q.x * (current1 - current2) + p.x * (prev2 - current1))
/ (prev2 - current2)));
p.y = cast(int)(((q.y * (current1 - current2) + p.y * (prev2 - current1))
/ (prev2 - current2)));
points2.insertPoint(p, i2 + 1);
prev2 = prev1 = current1;
i1--;
current1 = cast(double)i1 / size1;
}
}
}
}
/**
* This callback is unused. Reserved for possible future use.
* @see RoutingListener#remove(Connection)
*/
public final void remove(Connection connection) { }
/**
* Hooks route to intercept routing during animation playback.
* @see RoutingListener#route(Connection)
*/
public final bool route(Connection conn) {
return Animation.isAnimating() && Animation.hookPlayback(conn, this);
}
/**
* This callback is unused. Reserved for possible future use.
* @see RoutingListener#setConstraint(Connection, Object)
*/
public final void setConstraint(Connection connection, Object constraint) { }
}
| D |
instance Mod_537_NONE_Lehmar_NW (Npc_Default)
{
// ------ NSC ------
name = "Lehmar";
guild = GIL_pal;
id = 537;
voice = 0;
flags = 0;
npctype = NPCTYPE_MAIN;
//-----------AIVARS----------------
aivar[AIV_ToughGuy] = TRUE;
// ------ Attribute ------
B_SetAttributesToChapter (self, 2);
// ------ Kampf-Taktik ------
fight_tactic = FAI_HUMAN_STRONG;
// ------ Equippte Waffen ------
EquipItem (self, ItMw_1H_Eminem_AchillesSchwert_01);
// ------ Inventory ------
B_CreateAmbientInv (self);
CreateInvItems (self, ItKe_Lehmar, 1);
CreateInvItems (self, ItMi_LostInnosStatue_Daron, 1);
// ------ visuals ------
B_SetNpcVisual (self, MALE, "Hum_Head_FatBald", Face_N_Whistler, BodyTex_N,ITAR_Vlk_M);
Mdl_SetModelFatness (self,0);
Mdl_ApplyOverlayMds (self, "Humans_Relaxed.mds");
// ------ NSC-relevante Talente vergeben ------
B_GiveNpcTalents (self);
// ------ Kampf-Talente ------
B_SetFightSkills (self, 50);
// ------ TA anmelden ------
daily_routine = Rtn_Start_537;
};
FUNC VOID Rtn_Start_537()
{
TA_Sit_Throne (06,30,00,30,"NW_CITY_HABOUR_HUT_08_IN_C");
TA_Sleep (00,30,06,30,"NW_CITY_HABOUR_HUT_08_BED_02");
}; | D |
auto identity(T)(T t) { return t; }
| D |
/**
* Copyright © DiamondMVC 2019
* License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
* Author: Jacob Jensen (bausshf)
*/
module diamond.seo.schema.schemaobject;
import diamond.core.apptype;
static if (isWeb)
{
import std.variant;
/// Wrapper around a schema object.
abstract class SchemaObject
{
private:
/// The type of the schema object.
string _type;
/// Boolean determining whether the object is a child or not.
package(diamond) bool _isChild;
/// ALl fields attached to the schema object.
Variant[string] _fields;
public:
final:
/**
* Creates a new schema object.
* Params:
* type = The type of the schema object. Equivalent to "@type"
*/
this(string type)
{
_type = type;
}
@property
{
/// Gets a boolean determining whether the schema object is a root object or not.
bool isRoot() { return !_isChild; }
}
/**
* Adds a schema object field to the schema object.
* Params:
* key = The key of the field.
* schemaObject = The schema object to add.
*/
void addField(T : SchemaObject)(string key, T schemaObject)
{
auto schema = cast(SchemaObject)schemaObject;
if (schema)
{
schema._isChild = true;
}
_fields[key] = schema;
}
/**
* Adds an array of schema objects to the schema object.
* Params:
* key = The key of the field.
* values = An array of schema objects to add.
*/
void addField(T : SchemaObject)(string key, T[] values)
{
SchemaObject[] arrayResult;
if (values)
{
foreach (child; values)
{
child._isChild = true;
arrayResult ~= child;
}
_fields[key] = arrayResult ? arrayResult : [];
}
else
{
_fields[key] = arrayResult;
}
}
/**
* Adds a field to the schema object.
* Params:
* key = The key of the field.
* value = The value of the field.
*/
void addField(T)(string key, T value)
{
_fields[key] = value;
}
/**
* Removes a field from the schema object.
* Params:
* key = The key of the field to remove.
*/
void removeField(string key)
{
_fields.remove(key);
}
/// Converts the schema object to a string that represent a JSON-LD object.
override string toString()
{
import std.string : format;
import std.conv : to;
import std.array : join;
string[] fieldsValue;
if (_fields && _fields.length)
{
foreach (k,v; _fields)
{
if (!v.hasValue)
{
continue;
}
if (v.convertsTo!SchemaObject)
{
auto schemaObject = v.get!SchemaObject;
fieldsValue ~= "\"%s\": %s".format(k,schemaObject.toString());
}
else if (v.convertsTo!(SchemaObject[]))
{
auto schemaObjects = v.get!(SchemaObject[]);
if (schemaObjects)
{
fieldsValue ~= "\"%s\": %s".format(k,to!string(schemaObjects));
}
else
{
fieldsValue ~= "\"%s\": null".format(k);
}
}
else if (v.convertsTo!string)
{
auto stringValue = v.get!string;
fieldsValue ~= "\"%s\": \"%s\"".format(k,stringValue);
}
else
{
fieldsValue ~= "\"%s\": %s".format(k,v.toString());
}
}
}
if (!_isChild)
{
return `{
"@context" : "http://schema.org",
"@type": "%s"
%s
}`.format
(
_type,
fieldsValue && fieldsValue.length ? (", " ~ fieldsValue.join(",\r\n")) : ""
);
}
else
{
return `{
"@type": "%s"
%s
}`.format
(
_type,
fieldsValue && fieldsValue.length ? (", " ~ fieldsValue.join(",\r\n")) : ""
);
}
}
}
}
| D |
/**
* Authors: The D DBI project
*
* Version: 0.2.5
*
* Copyright: BSD license
*/
module dbi.msql.MsqlResult;
private import dbi.DBIException, dbi.Result, dbi.Row;
private import dbi.msql.imp;
/**
* Manage a result set from a mSQL database query.
*
* See_Also:
* Result is the interface of which this provides an implementation.
*/
class MsqlResult : Result {
public:
this () {
}
/**
* Get the next row from a result set.
*
* Returns:
* A Row object with the queried information or null for an empty set.
*/
override Row fetchRow () {
return null;
}
/**
* Free all database resources used by a result set.
*/
override void finish () {
}
private:
} | D |
//Written in the D programming language
/++
Module containing core time functionality, such as $(LREF Duration) (which
represents a duration of time) or $(LREF MonoTime) (which represents a
timestamp of the system's monotonic clock).
Various functions take a string (or strings) to represent a unit of time
(e.g. $(D convert!("days", "hours")(numDays))). The valid strings to use
with such functions are "years", "months", "weeks", "days", "hours",
"minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds),
"hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There
are a few functions that also allow "nsecs", but very little actually
has precision greater than hnsecs.
$(BOOKTABLE Cheat Sheet,
$(TR $(TH Symbol) $(TH Description))
$(LEADINGROW Types)
$(TR $(TDNW $(LREF Duration)) $(TD Represents a duration of time of weeks
or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds).))
$(TR $(TDNW $(LREF TickDuration)) $(TD Represents a duration of time in
system clock ticks, using the highest precision that the system provides.))
$(TR $(TDNW $(LREF MonoTime)) $(TD Represents a monotonic timestamp in
system clock ticks, using the highest precision that the system provides.))
$(TR $(TDNW $(LREF FracSec)) $(TD Represents fractional seconds
(portions of time smaller than a second).))
$(LEADINGROW Functions)
$(TR $(TDNW $(LREF convert)) $(TD Generic way of converting between two time
units.))
$(TR $(TDNW $(LREF dur)) $(TD Allows constructing a $(LREF Duration) from
the given time units with the given length.))
$(TR $(TDNW $(LREF weeks)$(NBSP)$(LREF days)$(NBSP)$(LREF hours)$(BR)
$(LREF minutes)$(NBSP)$(LREF seconds)$(NBSP)$(LREF msecs)$(BR)
$(LREF usecs)$(NBSP)$(LREF hnsecs)$(NBSP)$(LREF nsecs))
$(TD Convenience aliases for $(LREF dur).))
$(TR $(TDNW $(LREF abs)) $(TD Returns the absolute value of a duration.))
)
$(BOOKTABLE Conversions,
$(TR $(TH )
$(TH From $(LREF Duration))
$(TH From $(LREF TickDuration))
$(TH From $(LREF FracSec))
$(TH From units)
)
$(TR $(TD $(B To $(LREF Duration)))
$(TD -)
$(TD $(D tickDuration.)$(REF_SHORT to, std,conv)$(D !Duration()))
$(TD -)
$(TD $(D dur!"msecs"(5)) or $(D 5.msecs()))
)
$(TR $(TD $(B To $(LREF TickDuration)))
$(TD $(D duration.)$(REF_SHORT to, std,conv)$(D !TickDuration()))
$(TD -)
$(TD -)
$(TD $(D TickDuration.from!"msecs"(msecs)))
)
$(TR $(TD $(B To $(LREF FracSec)))
$(TD $(D duration.fracSec))
$(TD -)
$(TD -)
$(TD $(D FracSec.from!"msecs"(msecs)))
)
$(TR $(TD $(B To units))
$(TD $(D duration.total!"days"))
$(TD $(D tickDuration.msecs))
$(TD $(D fracSec.msecs))
$(TD $(D convert!("days", "msecs")(msecs)))
))
Copyright: Copyright 2010 - 2012
License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Jonathan M Davis and Kato Shoichi
Source: $(DRUNTIMESRC core/_time.d)
Macros:
NBSP=
+/
module core.time;
import core.exception;
import core.stdc.time;
import core.stdc.stdio;
import core.internal.traits : _Unqual = Unqual;
import core.internal.string;
version(Windows)
{
import core.sys.windows.windows;
}
else version(Posix)
{
import core.sys.posix.time;
import core.sys.posix.sys.time;
}
version (OSX)
version = Darwin;
else version (iOS)
version = Darwin;
else version (TVOS)
version = Darwin;
else version (WatchOS)
version = Darwin;
//This probably should be moved somewhere else in druntime which
//is Darwin-specific.
version(Darwin)
{
public import core.sys.darwin.mach.kern_return;
extern(C) nothrow @nogc
{
struct mach_timebase_info_data_t
{
uint numer;
uint denom;
}
alias mach_timebase_info_data_t* mach_timebase_info_t;
kern_return_t mach_timebase_info(mach_timebase_info_t);
ulong mach_absolute_time();
}
}
//To verify that an lvalue isn't required.
version(unittest) private T copy(T)(T t)
{
return t;
}
/++
What type of clock to use with $(LREF MonoTime) / $(LREF MonoTimeImpl) or
$(D std.datetime.Clock.currTime). They default to $(D ClockType.normal),
and most programs do not need to ever deal with the others.
The other $(D ClockType)s are provided so that other clocks provided by the
underlying C, system calls can be used with $(LREF MonoTimeImpl) or
$(D std.datetime.Clock.currTime) without having to use the C API directly.
In the case of the monotonic time, $(LREF MonoTimeImpl) is templatized on
$(D ClockType), whereas with $(D std.datetime.Clock.currTime), its a runtime
argument, since in the case of the monotonic time, the type of the clock
affects the resolution of a $(LREF MonoTimeImpl) object, whereas with
$(REF SysTime, std,datetime), its resolution is always hecto-nanoseconds
regardless of the source of the time.
$(D ClockType.normal), $(D ClockType.coarse), and $(D ClockType.precise)
work with both $(D Clock.currTime) and $(LREF MonoTimeImpl).
$(D ClockType.second) only works with $(D Clock.currTime). The others only
work with $(LREF MonoTimeImpl).
+/
version(CoreDdoc) enum ClockType
{
/++
Use the normal clock.
+/
normal = 0,
/++
$(BLUE Linux-Only)
Uses $(D CLOCK_BOOTTIME).
+/
bootTime = 1,
/++
Use the coarse clock, not the normal one (e.g. on Linux, that would be
$(D CLOCK_REALTIME_COARSE) instead of $(D CLOCK_REALTIME) for
$(D clock_gettime) if a function is using the realtime clock). It's
generally faster to get the time with the coarse clock than the normal
clock, but it's less precise (e.g. 1 msec instead of 1 usec or 1 nsec).
Howeover, it $(I is) guaranteed to still have sub-second precision
(just not as high as with $(D ClockType.normal)).
On systems which do not support a coarser clock,
$(D MonoTimeImpl!(ClockType.coarse)) will internally use the same clock
as $(D Monotime) does, and $(D Clock.currTime!(ClockType.coarse)) will
use the same clock as $(D Clock.currTime). This is because the coarse
clock is doing the same thing as the normal clock (just at lower
precision), whereas some of the other clock types
(e.g. $(D ClockType.processCPUTime)) mean something fundamentally
different. So, treating those as $(D ClockType.normal) on systems where
they weren't natively supported would give misleading results.
Most programs should not use the coarse clock, exactly because it's
less precise, and most programs don't need to get the time often
enough to care, but for those rare programs that need to get the time
extremely frequently (e.g. hundreds of thousands of times a second) but
don't care about high precision, the coarse clock might be appropriate.
Currently, only Linux and FreeBSD support a coarser clock, and on other
platforms, it's treated as $(D ClockType.normal).
+/
coarse = 2,
/++
Uses a more precise clock than the normal one (which is already very
precise), but it takes longer to get the time. Similarly to
$(D ClockType.coarse), if it's used on a system that does not support a
more precise clock than the normal one, it's treated as equivalent to
$(D ClockType.normal).
Currently, only FreeBSD supports a more precise clock, where it uses
$(D CLOCK_MONOTONIC_PRECISE) for the monotonic time and
$(D CLOCK_REALTIME_PRECISE) for the wall clock time.
+/
precise = 3,
/++
$(BLUE Linux,Solaris-Only)
Uses $(D CLOCK_PROCESS_CPUTIME_ID).
+/
processCPUTime = 4,
/++
$(BLUE Linux-Only)
Uses $(D CLOCK_MONOTONIC_RAW).
+/
raw = 5,
/++
Uses a clock that has a precision of one second (contrast to the coarse
clock, which has sub-second precision like the normal clock does).
FreeBSD is the only system which specifically has a clock set up for
this (it has $(D CLOCK_SECOND) to use with $(D clock_gettime) which
takes advantage of an in-kernel cached value), but on other systems, the
fastest function available will be used, and the resulting $(D SysTime)
will be rounded down to the second if the clock that was used gave the
time at a more precise resolution. So, it's guaranteed that the time
will be given at a precision of one second and it's likely the case that
will be faster than $(D ClockType.normal), since there tend to be
several options on a system to get the time at low resolutions, and they
tend to be faster than getting the time at high resolutions.
So, the primary difference between $(D ClockType.coarse) and
$(D ClockType.second) is that $(D ClockType.coarse) sacrifices some
precision in order to get speed but is still fairly precise, whereas
$(D ClockType.second) tries to be as fast as possible at the expense of
all sub-second precision.
+/
second = 6,
/++
$(BLUE Linux,Solaris-Only)
Uses $(D CLOCK_THREAD_CPUTIME_ID).
+/
threadCPUTime = 7,
/++
$(BLUE FreeBSD-Only)
Uses $(D CLOCK_UPTIME).
+/
uptime = 8,
/++
$(BLUE FreeBSD-Only)
Uses $(D CLOCK_UPTIME_FAST).
+/
uptimeCoarse = 9,
/++
$(BLUE FreeBSD-Only)
Uses $(D CLOCK_UPTIME_PRECISE).
+/
uptimePrecise = 10,
}
else version(Windows) enum ClockType
{
normal = 0,
coarse = 2,
precise = 3,
second = 6,
}
else version(Darwin) enum ClockType
{
normal = 0,
coarse = 2,
precise = 3,
second = 6,
}
else version(linux) enum ClockType
{
normal = 0,
bootTime = 1,
coarse = 2,
precise = 3,
processCPUTime = 4,
raw = 5,
second = 6,
threadCPUTime = 7,
}
else version(FreeBSD) enum ClockType
{
normal = 0,
coarse = 2,
precise = 3,
second = 6,
uptime = 8,
uptimeCoarse = 9,
uptimePrecise = 10,
}
else version(Solaris) enum ClockType
{
normal = 0,
coarse = 2,
precise = 3,
processCPUTime = 4,
second = 6,
threadCPUTime = 7,
}
else
{
// It needs to be decided (and implemented in an appropriate version branch
// here) which clock types new platforms are going to support. At minimum,
// the ones _not_ marked with $(D Blue Foo-Only) should be supported.
static assert(0, "What are the clock types supported by this system?");
}
// private, used to translate clock type to proper argument to clock_xxx
// functions on posix systems
version(CoreDdoc)
private int _posixClock(ClockType clockType) { return 0; }
else
version(Posix)
{
private auto _posixClock(ClockType clockType)
{
version(linux)
{
import core.sys.linux.time;
with(ClockType) final switch(clockType)
{
case bootTime: return CLOCK_BOOTTIME;
case coarse: return CLOCK_MONOTONIC_COARSE;
case normal: return CLOCK_MONOTONIC;
case precise: return CLOCK_MONOTONIC;
case processCPUTime: return CLOCK_PROCESS_CPUTIME_ID;
case raw: return CLOCK_MONOTONIC_RAW;
case threadCPUTime: return CLOCK_THREAD_CPUTIME_ID;
case second: assert(0);
}
}
else version(FreeBSD)
{
import core.sys.freebsd.time;
with(ClockType) final switch(clockType)
{
case coarse: return CLOCK_MONOTONIC_FAST;
case normal: return CLOCK_MONOTONIC;
case precise: return CLOCK_MONOTONIC_PRECISE;
case uptime: return CLOCK_UPTIME;
case uptimeCoarse: return CLOCK_UPTIME_FAST;
case uptimePrecise: return CLOCK_UPTIME_PRECISE;
case second: assert(0);
}
}
else version(Solaris)
{
import core.sys.solaris.time;
with(ClockType) final switch(clockType)
{
case coarse: return CLOCK_MONOTONIC;
case normal: return CLOCK_MONOTONIC;
case precise: return CLOCK_MONOTONIC;
case processCPUTime: return CLOCK_PROCESS_CPUTIME_ID;
case threadCPUTime: return CLOCK_THREAD_CPUTIME_ID;
case second: assert(0);
}
}
else
// It needs to be decided (and implemented in an appropriate
// version branch here) which clock types new platforms are going
// to support. Also, ClockType's documentation should be updated to
// mention it if a new platform uses anything that's not supported
// on all platforms..
assert(0, "What are the monotonic clock types supported by this system?");
}
}
unittest
{
// Make sure that the values are the same across platforms.
static if(is(typeof(ClockType.normal))) static assert(ClockType.normal == 0);
static if(is(typeof(ClockType.bootTime))) static assert(ClockType.bootTime == 1);
static if(is(typeof(ClockType.coarse))) static assert(ClockType.coarse == 2);
static if(is(typeof(ClockType.precise))) static assert(ClockType.precise == 3);
static if(is(typeof(ClockType.processCPUTime))) static assert(ClockType.processCPUTime == 4);
static if(is(typeof(ClockType.raw))) static assert(ClockType.raw == 5);
static if(is(typeof(ClockType.second))) static assert(ClockType.second == 6);
static if(is(typeof(ClockType.threadCPUTime))) static assert(ClockType.threadCPUTime == 7);
static if(is(typeof(ClockType.uptime))) static assert(ClockType.uptime == 8);
static if(is(typeof(ClockType.uptimeCoarse))) static assert(ClockType.uptimeCoarse == 9);
static if(is(typeof(ClockType.uptimePrecise))) static assert(ClockType.uptimePrecise == 10);
}
/++
Represents a duration of time of weeks or less (kept internally as hnsecs).
(e.g. 22 days or 700 seconds).
It is used when representing a duration of time - such as how long to
sleep with $(REF Thread.sleep, core,thread).
In std.datetime, it is also used as the result of various arithmetic
operations on time points.
Use the $(LREF dur) function or one of its non-generic aliases to create
$(D Duration)s.
It's not possible to create a Duration of months or years, because the
variable number of days in a month or year makes it impossible to convert
between months or years and smaller units without a specific date. So,
nothing uses $(D Duration)s when dealing with months or years. Rather,
functions specific to months and years are defined. For instance,
$(REF Date, std,datetime) has $(D add!"years") and $(D add!"months") for adding
years and months rather than creating a Duration of years or months and
adding that to a $(REF Date, std,datetime). But Duration is used when dealing
with weeks or smaller.
Examples:
--------------------
assert(dur!"days"(12) == dur!"hnsecs"(10_368_000_000_000L));
assert(dur!"hnsecs"(27) == dur!"hnsecs"(27));
assert(std.datetime.Date(2010, 9, 7) + dur!"days"(5) ==
std.datetime.Date(2010, 9, 12));
assert(days(-12) == dur!"hnsecs"(-10_368_000_000_000L));
assert(hnsecs(-27) == dur!"hnsecs"(-27));
assert(std.datetime.Date(2010, 9, 7) - std.datetime.Date(2010, 10, 3) ==
days(-26));
--------------------
+/
struct Duration
{
@safe pure:
public:
/++
A $(D Duration) of $(D 0). It's shorter than doing something like
$(D dur!"seconds"(0)) and more explicit than $(D Duration.init).
+/
static @property nothrow @nogc Duration zero() { return Duration(0); }
/++
Largest $(D Duration) possible.
+/
static @property nothrow @nogc Duration max() { return Duration(long.max); }
/++
Most negative $(D Duration) possible.
+/
static @property nothrow @nogc Duration min() { return Duration(long.min); }
unittest
{
assert(zero == dur!"seconds"(0));
assert(Duration.max == Duration(long.max));
assert(Duration.min == Duration(long.min));
assert(Duration.min < Duration.zero);
assert(Duration.zero < Duration.max);
assert(Duration.min < Duration.max);
assert(Duration.min - dur!"hnsecs"(1) == Duration.max);
assert(Duration.max + dur!"hnsecs"(1) == Duration.min);
}
/++
Compares this $(D Duration) with the given $(D Duration).
Returns:
$(TABLE
$(TR $(TD this < rhs) $(TD < 0))
$(TR $(TD this == rhs) $(TD 0))
$(TR $(TD this > rhs) $(TD > 0))
)
+/
int opCmp(Duration rhs) const nothrow @nogc
{
if(_hnsecs < rhs._hnsecs)
return -1;
if(_hnsecs > rhs._hnsecs)
return 1;
return 0;
}
unittest
{
foreach(T; _TypeTuple!(Duration, const Duration, immutable Duration))
{
foreach(U; _TypeTuple!(Duration, const Duration, immutable Duration))
{
T t = 42;
U u = t;
assert(t == u);
assert(copy(t) == u);
assert(t == copy(u));
}
}
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
foreach(E; _TypeTuple!(Duration, const Duration, immutable Duration))
{
assert((cast(D)Duration(12)).opCmp(cast(E)Duration(12)) == 0);
assert((cast(D)Duration(-12)).opCmp(cast(E)Duration(-12)) == 0);
assert((cast(D)Duration(10)).opCmp(cast(E)Duration(12)) < 0);
assert((cast(D)Duration(-12)).opCmp(cast(E)Duration(12)) < 0);
assert((cast(D)Duration(12)).opCmp(cast(E)Duration(10)) > 0);
assert((cast(D)Duration(12)).opCmp(cast(E)Duration(-12)) > 0);
assert(copy(cast(D)Duration(12)).opCmp(cast(E)Duration(12)) == 0);
assert(copy(cast(D)Duration(-12)).opCmp(cast(E)Duration(-12)) == 0);
assert(copy(cast(D)Duration(10)).opCmp(cast(E)Duration(12)) < 0);
assert(copy(cast(D)Duration(-12)).opCmp(cast(E)Duration(12)) < 0);
assert(copy(cast(D)Duration(12)).opCmp(cast(E)Duration(10)) > 0);
assert(copy(cast(D)Duration(12)).opCmp(cast(E)Duration(-12)) > 0);
assert((cast(D)Duration(12)).opCmp(copy(cast(E)Duration(12))) == 0);
assert((cast(D)Duration(-12)).opCmp(copy(cast(E)Duration(-12))) == 0);
assert((cast(D)Duration(10)).opCmp(copy(cast(E)Duration(12))) < 0);
assert((cast(D)Duration(-12)).opCmp(copy(cast(E)Duration(12))) < 0);
assert((cast(D)Duration(12)).opCmp(copy(cast(E)Duration(10))) > 0);
assert((cast(D)Duration(12)).opCmp(copy(cast(E)Duration(-12))) > 0);
}
}
}
/++
Adds, subtracts or calculates the modulo of two durations.
The legal types of arithmetic for $(D Duration) using this operator are
$(TABLE
$(TR $(TD Duration) $(TD +) $(TD Duration) $(TD -->) $(TD Duration))
$(TR $(TD Duration) $(TD -) $(TD Duration) $(TD -->) $(TD Duration))
$(TR $(TD Duration) $(TD %) $(TD Duration) $(TD -->) $(TD Duration))
$(TR $(TD Duration) $(TD +) $(TD TickDuration) $(TD -->) $(TD Duration))
$(TR $(TD Duration) $(TD -) $(TD TickDuration) $(TD -->) $(TD Duration))
)
Params:
rhs = The duration to add to or subtract from this $(D Duration).
+/
Duration opBinary(string op, D)(D rhs) const nothrow @nogc
if(((op == "+" || op == "-" || op == "%") && is(_Unqual!D == Duration)) ||
((op == "+" || op == "-") && is(_Unqual!D == TickDuration)))
{
static if(is(_Unqual!D == Duration))
return Duration(mixin("_hnsecs " ~ op ~ " rhs._hnsecs"));
else if(is(_Unqual!D == TickDuration))
return Duration(mixin("_hnsecs " ~ op ~ " rhs.hnsecs"));
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
foreach(E; _TypeTuple!(Duration, const Duration, immutable Duration))
{
assert((cast(D)Duration(5)) + (cast(E)Duration(7)) == Duration(12));
assert((cast(D)Duration(5)) - (cast(E)Duration(7)) == Duration(-2));
assert((cast(D)Duration(5)) % (cast(E)Duration(7)) == Duration(5));
assert((cast(D)Duration(7)) + (cast(E)Duration(5)) == Duration(12));
assert((cast(D)Duration(7)) - (cast(E)Duration(5)) == Duration(2));
assert((cast(D)Duration(7)) % (cast(E)Duration(5)) == Duration(2));
assert((cast(D)Duration(5)) + (cast(E)Duration(-7)) == Duration(-2));
assert((cast(D)Duration(5)) - (cast(E)Duration(-7)) == Duration(12));
assert((cast(D)Duration(5)) % (cast(E)Duration(-7)) == Duration(5));
assert((cast(D)Duration(7)) + (cast(E)Duration(-5)) == Duration(2));
assert((cast(D)Duration(7)) - (cast(E)Duration(-5)) == Duration(12));
assert((cast(D)Duration(7)) % (cast(E)Duration(-5)) == Duration(2));
assert((cast(D)Duration(-5)) + (cast(E)Duration(7)) == Duration(2));
assert((cast(D)Duration(-5)) - (cast(E)Duration(7)) == Duration(-12));
assert((cast(D)Duration(-5)) % (cast(E)Duration(7)) == Duration(-5));
assert((cast(D)Duration(-7)) + (cast(E)Duration(5)) == Duration(-2));
assert((cast(D)Duration(-7)) - (cast(E)Duration(5)) == Duration(-12));
assert((cast(D)Duration(-7)) % (cast(E)Duration(5)) == Duration(-2));
assert((cast(D)Duration(-5)) + (cast(E)Duration(-7)) == Duration(-12));
assert((cast(D)Duration(-5)) - (cast(E)Duration(-7)) == Duration(2));
assert((cast(D)Duration(-5)) % (cast(E)Duration(7)) == Duration(-5));
assert((cast(D)Duration(-7)) + (cast(E)Duration(-5)) == Duration(-12));
assert((cast(D)Duration(-7)) - (cast(E)Duration(-5)) == Duration(-2));
assert((cast(D)Duration(-7)) % (cast(E)Duration(5)) == Duration(-2));
}
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
assertApprox((cast(D)Duration(5)) + cast(T)TickDuration.from!"usecs"(7), Duration(70), Duration(80));
assertApprox((cast(D)Duration(5)) - cast(T)TickDuration.from!"usecs"(7), Duration(-70), Duration(-60));
assertApprox((cast(D)Duration(7)) + cast(T)TickDuration.from!"usecs"(5), Duration(52), Duration(62));
assertApprox((cast(D)Duration(7)) - cast(T)TickDuration.from!"usecs"(5), Duration(-48), Duration(-38));
assertApprox((cast(D)Duration(5)) + cast(T)TickDuration.from!"usecs"(-7), Duration(-70), Duration(-60));
assertApprox((cast(D)Duration(5)) - cast(T)TickDuration.from!"usecs"(-7), Duration(70), Duration(80));
assertApprox((cast(D)Duration(7)) + cast(T)TickDuration.from!"usecs"(-5), Duration(-48), Duration(-38));
assertApprox((cast(D)Duration(7)) - cast(T)TickDuration.from!"usecs"(-5), Duration(52), Duration(62));
assertApprox((cast(D)Duration(-5)) + cast(T)TickDuration.from!"usecs"(7), Duration(60), Duration(70));
assertApprox((cast(D)Duration(-5)) - cast(T)TickDuration.from!"usecs"(7), Duration(-80), Duration(-70));
assertApprox((cast(D)Duration(-7)) + cast(T)TickDuration.from!"usecs"(5), Duration(38), Duration(48));
assertApprox((cast(D)Duration(-7)) - cast(T)TickDuration.from!"usecs"(5), Duration(-62), Duration(-52));
assertApprox((cast(D)Duration(-5)) + cast(T)TickDuration.from!"usecs"(-7), Duration(-80), Duration(-70));
assertApprox((cast(D)Duration(-5)) - cast(T)TickDuration.from!"usecs"(-7), Duration(60), Duration(70));
assertApprox((cast(D)Duration(-7)) + cast(T)TickDuration.from!"usecs"(-5), Duration(-62), Duration(-52));
assertApprox((cast(D)Duration(-7)) - cast(T)TickDuration.from!"usecs"(-5), Duration(38), Duration(48));
}
}
}
/++
Adds or subtracts two durations.
The legal types of arithmetic for $(D Duration) using this operator are
$(TABLE
$(TR $(TD TickDuration) $(TD +) $(TD Duration) $(TD -->) $(TD Duration))
$(TR $(TD TickDuration) $(TD -) $(TD Duration) $(TD -->) $(TD Duration))
)
Params:
lhs = The $(D TickDuration) to add to this $(D Duration) or to
subtract this $(D Duration) from.
+/
Duration opBinaryRight(string op, D)(D lhs) const nothrow @nogc
if((op == "+" || op == "-") &&
is(_Unqual!D == TickDuration))
{
return Duration(mixin("lhs.hnsecs " ~ op ~ " _hnsecs"));
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
assertApprox((cast(T)TickDuration.from!"usecs"(7)) + cast(D)Duration(5), Duration(70), Duration(80));
assertApprox((cast(T)TickDuration.from!"usecs"(7)) - cast(D)Duration(5), Duration(60), Duration(70));
assertApprox((cast(T)TickDuration.from!"usecs"(5)) + cast(D)Duration(7), Duration(52), Duration(62));
assertApprox((cast(T)TickDuration.from!"usecs"(5)) - cast(D)Duration(7), Duration(38), Duration(48));
assertApprox((cast(T)TickDuration.from!"usecs"(-7)) + cast(D)Duration(5), Duration(-70), Duration(-60));
assertApprox((cast(T)TickDuration.from!"usecs"(-7)) - cast(D)Duration(5), Duration(-80), Duration(-70));
assertApprox((cast(T)TickDuration.from!"usecs"(-5)) + cast(D)Duration(7), Duration(-48), Duration(-38));
assertApprox((cast(T)TickDuration.from!"usecs"(-5)) - cast(D)Duration(7), Duration(-62), Duration(-52));
assertApprox((cast(T)TickDuration.from!"usecs"(7)) + (cast(D)Duration(-5)), Duration(60), Duration(70));
assertApprox((cast(T)TickDuration.from!"usecs"(7)) - (cast(D)Duration(-5)), Duration(70), Duration(80));
assertApprox((cast(T)TickDuration.from!"usecs"(5)) + (cast(D)Duration(-7)), Duration(38), Duration(48));
assertApprox((cast(T)TickDuration.from!"usecs"(5)) - (cast(D)Duration(-7)), Duration(52), Duration(62));
assertApprox((cast(T)TickDuration.from!"usecs"(-7)) + cast(D)Duration(-5), Duration(-80), Duration(-70));
assertApprox((cast(T)TickDuration.from!"usecs"(-7)) - cast(D)Duration(-5), Duration(-70), Duration(-60));
assertApprox((cast(T)TickDuration.from!"usecs"(-5)) + cast(D)Duration(-7), Duration(-62), Duration(-52));
assertApprox((cast(T)TickDuration.from!"usecs"(-5)) - cast(D)Duration(-7), Duration(-48), Duration(-38));
}
}
}
/++
Adds, subtracts or calculates the modulo of two durations as well as
assigning the result to this $(D Duration).
The legal types of arithmetic for $(D Duration) using this operator are
$(TABLE
$(TR $(TD Duration) $(TD +) $(TD Duration) $(TD -->) $(TD Duration))
$(TR $(TD Duration) $(TD -) $(TD Duration) $(TD -->) $(TD Duration))
$(TR $(TD Duration) $(TD %) $(TD Duration) $(TD -->) $(TD Duration))
$(TR $(TD Duration) $(TD +) $(TD TickDuration) $(TD -->) $(TD Duration))
$(TR $(TD Duration) $(TD -) $(TD TickDuration) $(TD -->) $(TD Duration))
)
Params:
rhs = The duration to add to or subtract from this $(D Duration).
+/
ref Duration opOpAssign(string op, D)(in D rhs) nothrow @nogc
if(((op == "+" || op == "-" || op == "%") && is(_Unqual!D == Duration)) ||
((op == "+" || op == "-") && is(_Unqual!D == TickDuration)))
{
static if(is(_Unqual!D == Duration))
mixin("_hnsecs " ~ op ~ "= rhs._hnsecs;");
else if(is(_Unqual!D == TickDuration))
mixin("_hnsecs " ~ op ~ "= rhs.hnsecs;");
return this;
}
unittest
{
static void test1(string op, E)(Duration actual, in E rhs, Duration expected, size_t line = __LINE__)
{
if(mixin("actual " ~ op ~ " rhs") != expected)
throw new AssertError("op failed", __FILE__, line);
if(actual != expected)
throw new AssertError("op assign failed", __FILE__, line);
}
static void test2(string op, E)
(Duration actual, in E rhs, Duration lower, Duration upper, size_t line = __LINE__)
{
assertApprox(mixin("actual " ~ op ~ " rhs"), lower, upper, "op failed", line);
assertApprox(actual, lower, upper, "op assign failed", line);
}
foreach(E; _TypeTuple!(Duration, const Duration, immutable Duration))
{
test1!"+="(Duration(5), (cast(E)Duration(7)), Duration(12));
test1!"-="(Duration(5), (cast(E)Duration(7)), Duration(-2));
test1!"%="(Duration(5), (cast(E)Duration(7)), Duration(5));
test1!"+="(Duration(7), (cast(E)Duration(5)), Duration(12));
test1!"-="(Duration(7), (cast(E)Duration(5)), Duration(2));
test1!"%="(Duration(7), (cast(E)Duration(5)), Duration(2));
test1!"+="(Duration(5), (cast(E)Duration(-7)), Duration(-2));
test1!"-="(Duration(5), (cast(E)Duration(-7)), Duration(12));
test1!"%="(Duration(5), (cast(E)Duration(-7)), Duration(5));
test1!"+="(Duration(7), (cast(E)Duration(-5)), Duration(2));
test1!"-="(Duration(7), (cast(E)Duration(-5)), Duration(12));
test1!"%="(Duration(7), (cast(E)Duration(-5)), Duration(2));
test1!"+="(Duration(-5), (cast(E)Duration(7)), Duration(2));
test1!"-="(Duration(-5), (cast(E)Duration(7)), Duration(-12));
test1!"%="(Duration(-5), (cast(E)Duration(7)), Duration(-5));
test1!"+="(Duration(-7), (cast(E)Duration(5)), Duration(-2));
test1!"-="(Duration(-7), (cast(E)Duration(5)), Duration(-12));
test1!"%="(Duration(-7), (cast(E)Duration(5)), Duration(-2));
test1!"+="(Duration(-5), (cast(E)Duration(-7)), Duration(-12));
test1!"-="(Duration(-5), (cast(E)Duration(-7)), Duration(2));
test1!"%="(Duration(-5), (cast(E)Duration(-7)), Duration(-5));
test1!"+="(Duration(-7), (cast(E)Duration(-5)), Duration(-12));
test1!"-="(Duration(-7), (cast(E)Duration(-5)), Duration(-2));
test1!"%="(Duration(-7), (cast(E)Duration(-5)), Duration(-2));
}
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
test2!"+="(Duration(5), cast(T)TickDuration.from!"usecs"(7), Duration(70), Duration(80));
test2!"-="(Duration(5), cast(T)TickDuration.from!"usecs"(7), Duration(-70), Duration(-60));
test2!"+="(Duration(7), cast(T)TickDuration.from!"usecs"(5), Duration(52), Duration(62));
test2!"-="(Duration(7), cast(T)TickDuration.from!"usecs"(5), Duration(-48), Duration(-38));
test2!"+="(Duration(5), cast(T)TickDuration.from!"usecs"(-7), Duration(-70), Duration(-60));
test2!"-="(Duration(5), cast(T)TickDuration.from!"usecs"(-7), Duration(70), Duration(80));
test2!"+="(Duration(7), cast(T)TickDuration.from!"usecs"(-5), Duration(-48), Duration(-38));
test2!"-="(Duration(7), cast(T)TickDuration.from!"usecs"(-5), Duration(52), Duration(62));
test2!"+="(Duration(-5), cast(T)TickDuration.from!"usecs"(7), Duration(60), Duration(70));
test2!"-="(Duration(-5), cast(T)TickDuration.from!"usecs"(7), Duration(-80), Duration(-70));
test2!"+="(Duration(-7), cast(T)TickDuration.from!"usecs"(5), Duration(38), Duration(48));
test2!"-="(Duration(-7), cast(T)TickDuration.from!"usecs"(5), Duration(-62), Duration(-52));
test2!"+="(Duration(-5), cast(T)TickDuration.from!"usecs"(-7), Duration(-80), Duration(-70));
test2!"-="(Duration(-5), cast(T)TickDuration.from!"usecs"(-7), Duration(60), Duration(70));
test2!"+="(Duration(-7), cast(T)TickDuration.from!"usecs"(-5), Duration(-62), Duration(-52));
test2!"-="(Duration(-7), cast(T)TickDuration.from!"usecs"(-5), Duration(38), Duration(48));
}
foreach(D; _TypeTuple!(const Duration, immutable Duration))
{
foreach(E; _TypeTuple!(Duration, const Duration, immutable Duration,
TickDuration, const TickDuration, immutable TickDuration))
{
D lhs = D(120);
E rhs = E(120);
static assert(!__traits(compiles, lhs += rhs), D.stringof ~ " " ~ E.stringof);
}
}
}
/++
Multiplies or divides the duration by an integer value.
The legal types of arithmetic for $(D Duration) using this operator
overload are
$(TABLE
$(TR $(TD Duration) $(TD *) $(TD long) $(TD -->) $(TD Duration))
$(TR $(TD Duration) $(TD /) $(TD long) $(TD -->) $(TD Duration))
)
Params:
value = The value to multiply this $(D Duration) by.
+/
Duration opBinary(string op)(long value) const nothrow @nogc
if(op == "*" || op == "/")
{
mixin("return Duration(_hnsecs " ~ op ~ " value);");
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
assert((cast(D)Duration(5)) * 7 == Duration(35));
assert((cast(D)Duration(7)) * 5 == Duration(35));
assert((cast(D)Duration(5)) * -7 == Duration(-35));
assert((cast(D)Duration(7)) * -5 == Duration(-35));
assert((cast(D)Duration(-5)) * 7 == Duration(-35));
assert((cast(D)Duration(-7)) * 5 == Duration(-35));
assert((cast(D)Duration(-5)) * -7 == Duration(35));
assert((cast(D)Duration(-7)) * -5 == Duration(35));
assert((cast(D)Duration(5)) * 0 == Duration(0));
assert((cast(D)Duration(-5)) * 0 == Duration(0));
}
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
assert((cast(D)Duration(5)) / 7 == Duration(0));
assert((cast(D)Duration(7)) / 5 == Duration(1));
assert((cast(D)Duration(5)) / -7 == Duration(0));
assert((cast(D)Duration(7)) / -5 == Duration(-1));
assert((cast(D)Duration(-5)) / 7 == Duration(0));
assert((cast(D)Duration(-7)) / 5 == Duration(-1));
assert((cast(D)Duration(-5)) / -7 == Duration(0));
assert((cast(D)Duration(-7)) / -5 == Duration(1));
}
}
/++
Multiplies/Divides the duration by an integer value as well as
assigning the result to this $(D Duration).
The legal types of arithmetic for $(D Duration) using this operator
overload are
$(TABLE
$(TR $(TD Duration) $(TD *) $(TD long) $(TD -->) $(TD Duration))
$(TR $(TD Duration) $(TD /) $(TD long) $(TD -->) $(TD Duration))
)
Params:
value = The value to multiply/divide this $(D Duration) by.
+/
ref Duration opOpAssign(string op)(long value) nothrow @nogc
if(op == "*" || op == "/")
{
mixin("_hnsecs " ~ op ~ "= value;");
return this;
}
unittest
{
static void test(D)(D actual, long value, Duration expected, size_t line = __LINE__)
{
if((actual *= value) != expected)
throw new AssertError("op failed", __FILE__, line);
if(actual != expected)
throw new AssertError("op assign failed", __FILE__, line);
}
test(Duration(5), 7, Duration(35));
test(Duration(7), 5, Duration(35));
test(Duration(5), -7, Duration(-35));
test(Duration(7), -5, Duration(-35));
test(Duration(-5), 7, Duration(-35));
test(Duration(-7), 5, Duration(-35));
test(Duration(-5), -7, Duration(35));
test(Duration(-7), -5, Duration(35));
test(Duration(5), 0, Duration(0));
test(Duration(-5), 0, Duration(0));
const cdur = Duration(12);
immutable idur = Duration(12);
static assert(!__traits(compiles, cdur *= 12));
static assert(!__traits(compiles, idur *= 12));
}
unittest
{
static void test(Duration actual, long value, Duration expected, size_t line = __LINE__)
{
if((actual /= value) != expected)
throw new AssertError("op failed", __FILE__, line);
if(actual != expected)
throw new AssertError("op assign failed", __FILE__, line);
}
test(Duration(5), 7, Duration(0));
test(Duration(7), 5, Duration(1));
test(Duration(5), -7, Duration(0));
test(Duration(7), -5, Duration(-1));
test(Duration(-5), 7, Duration(0));
test(Duration(-7), 5, Duration(-1));
test(Duration(-5), -7, Duration(0));
test(Duration(-7), -5, Duration(1));
const cdur = Duration(12);
immutable idur = Duration(12);
static assert(!__traits(compiles, cdur /= 12));
static assert(!__traits(compiles, idur /= 12));
}
/++
Divides two durations.
The legal types of arithmetic for $(D Duration) using this operator are
$(TABLE
$(TR $(TD Duration) $(TD /) $(TD Duration) $(TD -->) $(TD long))
)
Params:
rhs = The duration to divide this $(D Duration) by.
+/
long opBinary(string op)(Duration rhs) const nothrow @nogc
if(op == "/")
{
return _hnsecs / rhs._hnsecs;
}
unittest
{
assert(Duration(5) / Duration(7) == 0);
assert(Duration(7) / Duration(5) == 1);
assert(Duration(8) / Duration(4) == 2);
assert(Duration(5) / Duration(-7) == 0);
assert(Duration(7) / Duration(-5) == -1);
assert(Duration(8) / Duration(-4) == -2);
assert(Duration(-5) / Duration(7) == 0);
assert(Duration(-7) / Duration(5) == -1);
assert(Duration(-8) / Duration(4) == -2);
assert(Duration(-5) / Duration(-7) == 0);
assert(Duration(-7) / Duration(-5) == 1);
assert(Duration(-8) / Duration(-4) == 2);
}
/++
Multiplies an integral value and a $(D Duration).
The legal types of arithmetic for $(D Duration) using this operator
overload are
$(TABLE
$(TR $(TD long) $(TD *) $(TD Duration) $(TD -->) $(TD Duration))
)
Params:
value = The number of units to multiply this $(D Duration) by.
+/
Duration opBinaryRight(string op)(long value) const nothrow @nogc
if(op == "*")
{
return opBinary!op(value);
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
assert(5 * cast(D)Duration(7) == Duration(35));
assert(7 * cast(D)Duration(5) == Duration(35));
assert(5 * cast(D)Duration(-7) == Duration(-35));
assert(7 * cast(D)Duration(-5) == Duration(-35));
assert(-5 * cast(D)Duration(7) == Duration(-35));
assert(-7 * cast(D)Duration(5) == Duration(-35));
assert(-5 * cast(D)Duration(-7) == Duration(35));
assert(-7 * cast(D)Duration(-5) == Duration(35));
assert(0 * cast(D)Duration(-5) == Duration(0));
assert(0 * cast(D)Duration(5) == Duration(0));
}
}
/++
Returns the negation of this $(D Duration).
+/
Duration opUnary(string op)() const nothrow @nogc
if(op == "-")
{
return Duration(-_hnsecs);
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
assert(-(cast(D)Duration(7)) == Duration(-7));
assert(-(cast(D)Duration(5)) == Duration(-5));
assert(-(cast(D)Duration(-7)) == Duration(7));
assert(-(cast(D)Duration(-5)) == Duration(5));
assert(-(cast(D)Duration(0)) == Duration(0));
}
}
/++
Returns a $(LREF TickDuration) with the same number of hnsecs as this
$(D Duration).
Note that the conventional way to convert between $(D Duration) and
$(D TickDuration) is using $(REF to, std,conv), e.g.:
$(D duration.to!TickDuration())
+/
TickDuration opCast(T)() const nothrow @nogc
if(is(_Unqual!T == TickDuration))
{
return TickDuration.from!"hnsecs"(_hnsecs);
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
foreach(units; _TypeTuple!("seconds", "msecs", "usecs", "hnsecs"))
{
enum unitsPerSec = convert!("seconds", units)(1);
if(TickDuration.ticksPerSec >= unitsPerSec)
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
auto t = TickDuration.from!units(1);
assertApprox(cast(T)cast(D)dur!units(1), t - TickDuration(1), t + TickDuration(1), units);
t = TickDuration.from!units(2);
assertApprox(cast(T)cast(D)dur!units(2), t - TickDuration(1), t + TickDuration(1), units);
}
}
else
{
auto t = TickDuration.from!units(1);
assert(t.to!(units, long)() == 0, units);
t = TickDuration.from!units(1_000_000);
assert(t.to!(units, long)() >= 900_000, units);
assert(t.to!(units, long)() <= 1_100_000, units);
}
}
}
}
//Temporary hack until bug http://d.puremagic.com/issues/show_bug.cgi?id=5747 is fixed.
Duration opCast(T)() const nothrow @nogc
if(is(_Unqual!T == Duration))
{
return this;
}
/++
Splits out the Duration into the given units.
split takes the list of time units to split out as template arguments.
The time unit strings must be given in decreasing order. How it returns
the values for those units depends on the overload used.
The overload which accepts function arguments takes integral types in
the order that the time unit strings were given, and those integers are
passed by $(D ref). split assigns the values for the units to each
corresponding integer. Any integral type may be used, but no attempt is
made to prevent integer overflow, so don't use small integral types in
circumstances where the values for those units aren't likely to fit in
an integral type that small.
The overload with no arguments returns the values for the units in a
struct with members whose names are the same as the given time unit
strings. The members are all $(D long)s. This overload will also work
with no time strings being given, in which case $(I all) of the time
units from weeks through hnsecs will be provided (but no nsecs, since it
would always be $(D 0)).
For both overloads, the entire value of the Duration is split among the
units (rather than splitting the Duration across all units and then only
providing the values for the requested units), so if only one unit is
given, the result is equivalent to $(LREF total).
$(D "nsecs") is accepted by split, but $(D "years") and $(D "months")
are not.
For negative durations, all of the split values will be negative.
+/
template split(units...)
if(allAreAcceptedUnits!("weeks", "days", "hours", "minutes", "seconds",
"msecs", "usecs", "hnsecs", "nsecs")(units) &&
unitsAreInDescendingOrder(units))
{
/++ Ditto +/
void split(Args...)(out Args args) const nothrow @nogc
if(units.length != 0 && args.length == units.length && allAreMutableIntegralTypes!Args)
{
long hnsecs = _hnsecs;
foreach(i, unit; units)
{
static if(unit == "nsecs")
args[i] = cast(typeof(args[i]))convert!("hnsecs", "nsecs")(hnsecs);
else
args[i] = cast(typeof(args[i]))splitUnitsFromHNSecs!unit(hnsecs);
}
}
/++ Ditto +/
auto split() const nothrow @nogc
{
static if(units.length == 0)
return split!("weeks", "days", "hours", "minutes", "seconds", "msecs", "usecs", "hnsecs")();
else
{
static string genMemberDecls()
{
string retval;
foreach(unit; units)
{
retval ~= "long ";
retval ~= unit;
retval ~= "; ";
}
return retval;
}
static struct SplitUnits
{
mixin(genMemberDecls());
}
static string genSplitCall()
{
auto retval = "split(";
foreach(i, unit; units)
{
retval ~= "su.";
retval ~= unit;
if(i < units.length - 1)
retval ~= ", ";
else
retval ~= ");";
}
return retval;
}
SplitUnits su = void;
mixin(genSplitCall());
return su;
}
}
/+
Whether all of the given arguments are integral types.
+/
private template allAreMutableIntegralTypes(Args...)
{
static if(Args.length == 0)
enum allAreMutableIntegralTypes = true;
else static if(!is(Args[0] == long) &&
!is(Args[0] == int) &&
!is(Args[0] == short) &&
!is(Args[0] == byte) &&
!is(Args[0] == ulong) &&
!is(Args[0] == uint) &&
!is(Args[0] == ushort) &&
!is(Args[0] == ubyte))
{
enum allAreMutableIntegralTypes = false;
}
else
enum allAreMutableIntegralTypes = allAreMutableIntegralTypes!(Args[1 .. $]);
}
unittest
{
foreach(T; _TypeTuple!(long, int, short, byte, ulong, uint, ushort, ubyte))
static assert(allAreMutableIntegralTypes!T);
foreach(T; _TypeTuple!(long, int, short, byte, ulong, uint, ushort, ubyte))
static assert(!allAreMutableIntegralTypes!(const T));
foreach(T; _TypeTuple!(char, wchar, dchar, float, double, real, string))
static assert(!allAreMutableIntegralTypes!T);
static assert(allAreMutableIntegralTypes!(long, int, short, byte));
static assert(!allAreMutableIntegralTypes!(long, int, short, char, byte));
static assert(!allAreMutableIntegralTypes!(long, int*, short));
}
}
///
unittest
{
{
auto d = dur!"days"(12) + dur!"minutes"(7) + dur!"usecs"(501223);
long days;
int seconds;
short msecs;
d.split!("days", "seconds", "msecs")(days, seconds, msecs);
assert(days == 12);
assert(seconds == 7 * 60);
assert(msecs == 501);
auto splitStruct = d.split!("days", "seconds", "msecs")();
assert(splitStruct.days == 12);
assert(splitStruct.seconds == 7 * 60);
assert(splitStruct.msecs == 501);
auto fullSplitStruct = d.split();
assert(fullSplitStruct.weeks == 1);
assert(fullSplitStruct.days == 5);
assert(fullSplitStruct.hours == 0);
assert(fullSplitStruct.minutes == 7);
assert(fullSplitStruct.seconds == 0);
assert(fullSplitStruct.msecs == 501);
assert(fullSplitStruct.usecs == 223);
assert(fullSplitStruct.hnsecs == 0);
assert(d.split!"minutes"().minutes == d.total!"minutes");
}
{
auto d = dur!"days"(12);
assert(d.split!"weeks"().weeks == 1);
assert(d.split!"days"().days == 12);
assert(d.split().weeks == 1);
assert(d.split().days == 5);
}
{
auto d = dur!"days"(7) + dur!"hnsecs"(42);
assert(d.split!("seconds", "nsecs")().nsecs == 4200);
}
{
auto d = dur!"days"(-7) + dur!"hours"(-9);
auto result = d.split!("days", "hours")();
assert(result.days == -7);
assert(result.hours == -9);
}
}
pure nothrow unittest
{
foreach(D; _TypeTuple!(const Duration, immutable Duration))
{
D d = dur!"weeks"(3) + dur!"days"(5) + dur!"hours"(19) + dur!"minutes"(7) +
dur!"seconds"(2) + dur!"hnsecs"(1234567);
byte weeks;
ubyte days;
short hours;
ushort minutes;
int seconds;
uint msecs;
long usecs;
ulong hnsecs;
long nsecs;
d.split!("weeks", "days", "hours", "minutes", "seconds", "msecs", "usecs", "hnsecs", "nsecs")
(weeks, days, hours, minutes, seconds, msecs, usecs, hnsecs, nsecs);
assert(weeks == 3);
assert(days == 5);
assert(hours == 19);
assert(minutes == 7);
assert(seconds == 2);
assert(msecs == 123);
assert(usecs == 456);
assert(hnsecs == 7);
assert(nsecs == 0);
d.split!("weeks", "days", "hours", "seconds", "usecs")(weeks, days, hours, seconds, usecs);
assert(weeks == 3);
assert(days == 5);
assert(hours == 19);
assert(seconds == 422);
assert(usecs == 123456);
d.split!("days", "minutes", "seconds", "nsecs")(days, minutes, seconds, nsecs);
assert(days == 26);
assert(minutes == 1147);
assert(seconds == 2);
assert(nsecs == 123456700);
d.split!("minutes", "msecs", "usecs", "hnsecs")(minutes, msecs, usecs, hnsecs);
assert(minutes == 38587);
assert(msecs == 2123);
assert(usecs == 456);
assert(hnsecs == 7);
{
auto result = d.split!("weeks", "days", "hours", "minutes", "seconds",
"msecs", "usecs", "hnsecs", "nsecs");
assert(result.weeks == 3);
assert(result.days == 5);
assert(result.hours == 19);
assert(result.minutes == 7);
assert(result.seconds == 2);
assert(result.msecs == 123);
assert(result.usecs == 456);
assert(result.hnsecs == 7);
assert(result.nsecs == 0);
}
{
auto result = d.split!("weeks", "days", "hours", "seconds", "usecs");
assert(result.weeks == 3);
assert(result.days == 5);
assert(result.hours == 19);
assert(result.seconds == 422);
assert(result.usecs == 123456);
}
{
auto result = d.split!("days", "minutes", "seconds", "nsecs")();
assert(result.days == 26);
assert(result.minutes == 1147);
assert(result.seconds == 2);
assert(result.nsecs == 123456700);
}
{
auto result = d.split!("minutes", "msecs", "usecs", "hnsecs")();
assert(result.minutes == 38587);
assert(result.msecs == 2123);
assert(result.usecs == 456);
assert(result.hnsecs == 7);
}
{
auto result = d.split();
assert(result.weeks == 3);
assert(result.days == 5);
assert(result.hours == 19);
assert(result.minutes == 7);
assert(result.seconds == 2);
assert(result.msecs == 123);
assert(result.usecs == 456);
assert(result.hnsecs == 7);
static assert(!is(typeof(result.nsecs)));
}
static assert(!is(typeof(d.split("seconds", "hnsecs")(seconds))));
static assert(!is(typeof(d.split("hnsecs", "seconds", "minutes")(hnsecs, seconds, minutes))));
static assert(!is(typeof(d.split("hnsecs", "seconds", "msecs")(hnsecs, seconds, msecs))));
static assert(!is(typeof(d.split("seconds", "hnecs", "msecs")(seconds, hnsecs, msecs))));
static assert(!is(typeof(d.split("seconds", "msecs", "msecs")(seconds, msecs, msecs))));
static assert(!is(typeof(d.split("hnsecs", "seconds", "minutes")())));
static assert(!is(typeof(d.split("hnsecs", "seconds", "msecs")())));
static assert(!is(typeof(d.split("seconds", "hnecs", "msecs")())));
static assert(!is(typeof(d.split("seconds", "msecs", "msecs")())));
alias _TypeTuple!("nsecs", "hnsecs", "usecs", "msecs", "seconds",
"minutes", "hours", "days", "weeks") timeStrs;
foreach(i, str; timeStrs[1 .. $])
static assert(!is(typeof(d.split!(timeStrs[i - 1], str)())));
D nd = -d;
{
auto result = nd.split();
assert(result.weeks == -3);
assert(result.days == -5);
assert(result.hours == -19);
assert(result.minutes == -7);
assert(result.seconds == -2);
assert(result.msecs == -123);
assert(result.usecs == -456);
assert(result.hnsecs == -7);
}
{
auto result = nd.split!("weeks", "days", "hours", "minutes", "seconds", "nsecs")();
assert(result.weeks == -3);
assert(result.days == -5);
assert(result.hours == -19);
assert(result.minutes == -7);
assert(result.seconds == -2);
assert(result.nsecs == -123456700);
}
}
}
/++
Returns the total number of the given units in this $(D Duration).
So, unlike $(D split), it does not strip out the larger units.
+/
@property long total(string units)() const nothrow @nogc
if(units == "weeks" ||
units == "days" ||
units == "hours" ||
units == "minutes" ||
units == "seconds" ||
units == "msecs" ||
units == "usecs" ||
units == "hnsecs" ||
units == "nsecs")
{
static if(units == "nsecs")
return convert!("hnsecs", "nsecs")(_hnsecs);
else
return getUnitsFromHNSecs!units(_hnsecs);
}
///
unittest
{
assert(dur!"weeks"(12).total!"weeks" == 12);
assert(dur!"weeks"(12).total!"days" == 84);
assert(dur!"days"(13).total!"weeks" == 1);
assert(dur!"days"(13).total!"days" == 13);
assert(dur!"hours"(49).total!"days" == 2);
assert(dur!"hours"(49).total!"hours" == 49);
assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
assert(dur!"nsecs"(2007).total!"nsecs" == 2000);
}
unittest
{
foreach(D; _TypeTuple!(const Duration, immutable Duration))
{
assert((cast(D)dur!"weeks"(12)).total!"weeks" == 12);
assert((cast(D)dur!"weeks"(12)).total!"days" == 84);
assert((cast(D)dur!"days"(13)).total!"weeks" == 1);
assert((cast(D)dur!"days"(13)).total!"days" == 13);
assert((cast(D)dur!"hours"(49)).total!"days" == 2);
assert((cast(D)dur!"hours"(49)).total!"hours" == 49);
assert((cast(D)dur!"nsecs"(2007)).total!"hnsecs" == 20);
assert((cast(D)dur!"nsecs"(2007)).total!"nsecs" == 2000);
}
}
/+
Converts this $(D Duration) to a $(D string).
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString()
{
return _toStringImpl();
}
/++
Converts this $(D Duration) to a $(D string).
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString() const nothrow
{
return _toStringImpl();
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
assert((cast(D)Duration(0)).toString() == "0 hnsecs");
assert((cast(D)Duration(1)).toString() == "1 hnsec");
assert((cast(D)Duration(7)).toString() == "7 hnsecs");
assert((cast(D)Duration(10)).toString() == "1 μs");
assert((cast(D)Duration(20)).toString() == "2 μs");
assert((cast(D)Duration(10_000)).toString() == "1 ms");
assert((cast(D)Duration(20_000)).toString() == "2 ms");
assert((cast(D)Duration(10_000_000)).toString() == "1 sec");
assert((cast(D)Duration(20_000_000)).toString() == "2 secs");
assert((cast(D)Duration(600_000_000)).toString() == "1 minute");
assert((cast(D)Duration(1_200_000_000)).toString() == "2 minutes");
assert((cast(D)Duration(36_000_000_000)).toString() == "1 hour");
assert((cast(D)Duration(72_000_000_000)).toString() == "2 hours");
assert((cast(D)Duration(864_000_000_000)).toString() == "1 day");
assert((cast(D)Duration(1_728_000_000_000)).toString() == "2 days");
assert((cast(D)Duration(6_048_000_000_000)).toString() == "1 week");
assert((cast(D)Duration(12_096_000_000_000)).toString() == "2 weeks");
assert((cast(D)Duration(12)).toString() == "1 μs and 2 hnsecs");
assert((cast(D)Duration(120_795)).toString() == "12 ms, 79 μs, and 5 hnsecs");
assert((cast(D)Duration(12_096_020_900_003)).toString() == "2 weeks, 2 secs, 90 ms, and 3 hnsecs");
assert((cast(D)Duration(-1)).toString() == "-1 hnsecs");
assert((cast(D)Duration(-7)).toString() == "-7 hnsecs");
assert((cast(D)Duration(-10)).toString() == "-1 μs");
assert((cast(D)Duration(-20)).toString() == "-2 μs");
assert((cast(D)Duration(-10_000)).toString() == "-1 ms");
assert((cast(D)Duration(-20_000)).toString() == "-2 ms");
assert((cast(D)Duration(-10_000_000)).toString() == "-1 secs");
assert((cast(D)Duration(-20_000_000)).toString() == "-2 secs");
assert((cast(D)Duration(-600_000_000)).toString() == "-1 minutes");
assert((cast(D)Duration(-1_200_000_000)).toString() == "-2 minutes");
assert((cast(D)Duration(-36_000_000_000)).toString() == "-1 hours");
assert((cast(D)Duration(-72_000_000_000)).toString() == "-2 hours");
assert((cast(D)Duration(-864_000_000_000)).toString() == "-1 days");
assert((cast(D)Duration(-1_728_000_000_000)).toString() == "-2 days");
assert((cast(D)Duration(-6_048_000_000_000)).toString() == "-1 weeks");
assert((cast(D)Duration(-12_096_000_000_000)).toString() == "-2 weeks");
assert((cast(D)Duration(-12)).toString() == "-1 μs and -2 hnsecs");
assert((cast(D)Duration(-120_795)).toString() == "-12 ms, -79 μs, and -5 hnsecs");
assert((cast(D)Duration(-12_096_020_900_003)).toString() == "-2 weeks, -2 secs, -90 ms, and -3 hnsecs");
}
}
/++
Returns whether this $(D Duration) is negative.
+/
@property bool isNegative() const nothrow @nogc
{
return _hnsecs < 0;
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
assert(!(cast(D)Duration(100)).isNegative);
assert(!(cast(D)Duration(1)).isNegative);
assert(!(cast(D)Duration(0)).isNegative);
assert((cast(D)Duration(-1)).isNegative);
assert((cast(D)Duration(-100)).isNegative);
}
}
private:
/+
Since we have two versions of toString, we have _toStringImpl
so that they can share implementations.
+/
string _toStringImpl() const nothrow
{
static void appListSep(ref string res, uint pos, bool last) nothrow
{
if (pos == 0)
return;
if (!last)
res ~= ", ";
else
res ~= pos == 1 ? " and " : ", and ";
}
static void appUnitVal(string units)(ref string res, long val) nothrow
{
immutable plural = val != 1;
string unit;
static if (units == "seconds")
unit = plural ? "secs" : "sec";
else static if (units == "msecs")
unit = "ms";
else static if (units == "usecs")
unit = "μs";
else
unit = plural ? units : units[0 .. $-1];
res ~= signedToTempString(val, 10);
res ~= " ";
res ~= unit;
}
if (_hnsecs == 0) return "0 hnsecs";
template TT(T...) { alias T TT; }
alias units = TT!("weeks", "days", "hours", "minutes", "seconds", "msecs", "usecs");
long hnsecs = _hnsecs; string res; uint pos;
foreach (unit; units)
{
if (auto val = splitUnitsFromHNSecs!unit(hnsecs))
{
appListSep(res, pos++, hnsecs == 0);
appUnitVal!unit(res, val);
}
if (hnsecs == 0) break;
}
if (hnsecs != 0)
{
appListSep(res, pos++, true);
appUnitVal!"hnsecs"(res, hnsecs);
}
return res;
}
/+
Params:
hnsecs = The total number of hecto-nanoseconds in this $(D Duration).
+/
this(long hnsecs) nothrow @nogc
{
_hnsecs = hnsecs;
}
long _hnsecs;
}
///
unittest
{
import core.time;
// using the dur template
auto numDays = dur!"days"(12);
// using the days function
numDays = days(12);
// alternatively using UFCS syntax
numDays = 12.days;
auto myTime = 100.msecs + 20_000.usecs + 30_000.hnsecs;
assert(myTime == 123.msecs);
}
/++
Converts a $(D TickDuration) to the given units as either an integral
value or a floating point value.
Params:
units = The units to convert to. Accepts $(D "seconds") and smaller
only.
T = The type to convert to (either an integral type or a
floating point type).
td = The TickDuration to convert
+/
T to(string units, T, D)(D td) @safe pure nothrow @nogc
if(is(_Unqual!D == TickDuration) &&
(units == "seconds" ||
units == "msecs" ||
units == "usecs" ||
units == "hnsecs" ||
units == "nsecs"))
{
static if(__traits(isIntegral, T) && T.sizeof >= 4)
{
enum unitsPerSec = convert!("seconds", units)(1);
return cast(T) (td.length / (TickDuration.ticksPerSec / cast(real) unitsPerSec));
}
else static if(__traits(isFloating, T))
{
static if(units == "seconds")
return td.length / cast(T)TickDuration.ticksPerSec;
else
{
enum unitsPerSec = convert!("seconds", units)(1);
return cast(T) (td.length /
(TickDuration.ticksPerSec / cast(real) unitsPerSec));
}
}
else
static assert(0, "Incorrect template constraint.");
}
///
unittest
{
auto t = TickDuration.from!"seconds"(1000);
long tl = to!("seconds",long)(t);
assert(tl == 1000);
double td = to!("seconds",double)(t);
assert(_abs(td - 1000) < 0.001);
}
unittest
{
void testFun(string U)() {
auto t1v = 1000;
auto t2v = 333;
auto t1 = TickDuration.from!U(t1v);
auto t2 = TickDuration.from!U(t2v);
auto _str(F)(F val)
{
static if(is(F == int) || is(F == long))
return signedToTempString(val, 10);
else
return unsignedToTempString(val, 10);
}
foreach (F; _TypeTuple!(int,uint,long,ulong,float,double,real))
{
F t1f = to!(U,F)(t1);
F t2f = to!(U,F)(t2);
auto t12d = t1 / t2v;
auto t12m = t1 - t2;
F t3f = to!(U,F)(t12d);
F t4f = to!(U,F)(t12m);
static if(is(F == float) || is(F == double) || is(F == real))
{
assert((t1f - cast(F)t1v) <= 3.0,
F.stringof ~ " " ~ U ~ " " ~ doubleToString(t1f) ~ " " ~
doubleToString(cast(F)t1v)
);
assert((t2f - cast(F)t2v) <= 3.0,
F.stringof ~ " " ~ U ~ " " ~ doubleToString(t2f) ~ " " ~
doubleToString(cast(F)t2v)
);
assert(t3f - (cast(F)t1v) / (cast(F)t2v) <= 3.0,
F.stringof ~ " " ~ U ~ " " ~ doubleToString(t3f) ~ " " ~
doubleToString((cast(F)t1v)/(cast(F)t2v))
);
assert(t4f - (cast(F)(t1v - t2v)) <= 3.0,
F.stringof ~ " " ~ U ~ " " ~ doubleToString(t4f) ~ " " ~
doubleToString(cast(F)(t1v - t2v))
);
}
else
{
// even though this should be exact math it is not as internal
// in "to" floating point is used
assert(_abs(t1f) - _abs(cast(F)t1v) <= 3,
F.stringof ~ " " ~ U ~ " " ~ _str(t1f) ~ " " ~
_str(cast(F)t1v)
);
assert(_abs(t2f) - _abs(cast(F)t2v) <= 3,
F.stringof ~ " " ~ U ~ " " ~ _str(t2f) ~ " " ~
_str(cast(F)t2v)
);
assert(_abs(t3f) - _abs((cast(F)t1v) / (cast(F)t2v)) <= 3,
F.stringof ~ " " ~ U ~ " " ~ _str(t3f) ~ " " ~
_str((cast(F)t1v) / (cast(F)t2v))
);
assert(_abs(t4f) - _abs((cast(F)t1v) - (cast(F)t2v)) <= 3,
F.stringof ~ " " ~ U ~ " " ~ _str(t4f) ~ " " ~
_str((cast(F)t1v) - (cast(F)t2v))
);
}
}
}
testFun!"seconds"();
testFun!"msecs"();
testFun!"usecs"();
}
/++
These allow you to construct a $(D Duration) from the given time units
with the given length.
You can either use the generic function $(D dur) and give it the units as
a $(D string) or use the named aliases.
The possible values for units are $(D "weeks"), $(D "days"), $(D "hours"),
$(D "minutes"), $(D "seconds"), $(D "msecs") (milliseconds), $(D "usecs"),
(microseconds), $(D "hnsecs") (hecto-nanoseconds, i.e. 100 ns), and
$(D "nsecs").
Params:
units = The time units of the $(D Duration) (e.g. $(D "days")).
length = The number of units in the $(D Duration).
+/
Duration dur(string units)(long length) @safe pure nothrow @nogc
if(units == "weeks" ||
units == "days" ||
units == "hours" ||
units == "minutes" ||
units == "seconds" ||
units == "msecs" ||
units == "usecs" ||
units == "hnsecs" ||
units == "nsecs")
{
return Duration(convert!(units, "hnsecs")(length));
}
alias weeks = dur!"weeks"; /// Ditto
alias days = dur!"days"; /// Ditto
alias hours = dur!"hours"; /// Ditto
alias minutes = dur!"minutes"; /// Ditto
alias seconds = dur!"seconds"; /// Ditto
alias msecs = dur!"msecs"; /// Ditto
alias usecs = dur!"usecs"; /// Ditto
alias hnsecs = dur!"hnsecs"; /// Ditto
alias nsecs = dur!"nsecs"; /// Ditto
///
unittest
{
// Generic
assert(dur!"weeks"(142).total!"weeks" == 142);
assert(dur!"days"(142).total!"days" == 142);
assert(dur!"hours"(142).total!"hours" == 142);
assert(dur!"minutes"(142).total!"minutes" == 142);
assert(dur!"seconds"(142).total!"seconds" == 142);
assert(dur!"msecs"(142).total!"msecs" == 142);
assert(dur!"usecs"(142).total!"usecs" == 142);
assert(dur!"hnsecs"(142).total!"hnsecs" == 142);
assert(dur!"nsecs"(142).total!"nsecs" == 100);
// Non-generic
assert(weeks(142).total!"weeks" == 142);
assert(days(142).total!"days" == 142);
assert(hours(142).total!"hours" == 142);
assert(minutes(142).total!"minutes" == 142);
assert(seconds(142).total!"seconds" == 142);
assert(msecs(142).total!"msecs" == 142);
assert(usecs(142).total!"usecs" == 142);
assert(hnsecs(142).total!"hnsecs" == 142);
assert(nsecs(142).total!"nsecs" == 100);
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
assert(dur!"weeks"(7).total!"weeks" == 7);
assert(dur!"days"(7).total!"days" == 7);
assert(dur!"hours"(7).total!"hours" == 7);
assert(dur!"minutes"(7).total!"minutes" == 7);
assert(dur!"seconds"(7).total!"seconds" == 7);
assert(dur!"msecs"(7).total!"msecs" == 7);
assert(dur!"usecs"(7).total!"usecs" == 7);
assert(dur!"hnsecs"(7).total!"hnsecs" == 7);
assert(dur!"nsecs"(7).total!"nsecs" == 0);
assert(dur!"weeks"(1007) == weeks(1007));
assert(dur!"days"(1007) == days(1007));
assert(dur!"hours"(1007) == hours(1007));
assert(dur!"minutes"(1007) == minutes(1007));
assert(dur!"seconds"(1007) == seconds(1007));
assert(dur!"msecs"(1007) == msecs(1007));
assert(dur!"usecs"(1007) == usecs(1007));
assert(dur!"hnsecs"(1007) == hnsecs(1007));
assert(dur!"nsecs"(10) == nsecs(10));
}
}
// used in MonoTimeImpl
private string _clockTypeName(ClockType clockType)
{
final switch(clockType)
{
foreach(name; __traits(allMembers, ClockType))
{
case __traits(getMember, ClockType, name):
return name;
}
}
assert(0);
}
// used in MonoTimeImpl
private size_t _clockTypeIdx(ClockType clockType)
{
final switch(clockType)
{
foreach(i, name; __traits(allMembers, ClockType))
{
case __traits(getMember, ClockType, name):
return i;
}
}
assert(0);
}
/++
alias for $(D MonoTimeImpl) instantiated with $(D ClockType.normal). This is
what most programs should use. It's also what much of $(D MonoTimeImpl) uses
in its documentation (particularly in the examples), because that's what's
going to be used in most code.
+/
alias MonoTime = MonoTimeImpl!(ClockType.normal);
/++
Represents a timestamp of the system's monotonic clock.
A monotonic clock is one which always goes forward and never moves
backwards, unlike the system's wall clock time (as represented by
$(REF SysTime, std,datetime)). The system's wall clock time can be adjusted
by the user or by the system itself via services such as NTP, so it is
unreliable to use the wall clock time for timing. Timers which use the wall
clock time could easily end up never going off due to changes made to the
wall clock time or otherwise waiting for a different period of time than
that specified by the programmer. However, because the monotonic clock
always increases at a fixed rate and is not affected by adjustments to the
wall clock time, it is ideal for use with timers or anything which requires
high precision timing.
So, MonoTime should be used for anything involving timers and timing,
whereas $(REF SysTime, std,datetime) should be used when the wall clock time
is required.
The monotonic clock has no relation to wall clock time. Rather, it holds
its time as the number of ticks of the clock which have occurred since the
clock started (typically when the system booted up). So, to determine how
much time has passed between two points in time, one monotonic time is
subtracted from the other to determine the number of ticks which occurred
between the two points of time, and those ticks are divided by the number of
ticks that occur every second (as represented by MonoTime.ticksPerSecond)
to get a meaningful duration of time. Normally, MonoTime does these
calculations for the programmer, but the $(D ticks) and $(D ticksPerSecond)
properties are provided for those who require direct access to the system
ticks. The normal way that MonoTime would be used is
--------------------
MonoTime before = MonoTime.currTime;
// do stuff...
MonoTime after = MonoTime.currTime;
Duration timeElapsed = after - before;
--------------------
$(LREF MonoTime) is an alias to $(D MonoTimeImpl!(ClockType.normal)) and is
what most programs should use for the monotonic clock, so that's what is
used in most of $(D MonoTimeImpl)'s documentation. But $(D MonoTimeImpl)
can be instantiated with other clock types for those rare programs that need
it.
See_Also:
$(LREF ClockType)
+/
struct MonoTimeImpl(ClockType clockType)
{
private enum _clockIdx = _clockTypeIdx(clockType);
private enum _clockName = _clockTypeName(clockType);
@safe:
version(Windows)
{
static if(clockType != ClockType.coarse &&
clockType != ClockType.normal &&
clockType != ClockType.precise)
{
static assert(0, "ClockType." ~ _clockName ~
" is not supported by MonoTimeImpl on this system.");
}
}
else version(Darwin)
{
static if(clockType != ClockType.coarse &&
clockType != ClockType.normal &&
clockType != ClockType.precise)
{
static assert(0, "ClockType." ~ _clockName ~
" is not supported by MonoTimeImpl on this system.");
}
}
else version(Posix)
{
enum clockArg = _posixClock(clockType);
}
else
static assert(0, "Unsupported platform");
// POD value, test mutable/const/immutable conversion
unittest
{
MonoTimeImpl m;
const MonoTimeImpl cm = m;
immutable MonoTimeImpl im = m;
m = cm;
m = im;
}
/++
The current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, $(D QueryPerformanceCounter) is used. On Mac OS X,
$(D mach_absolute_time) is used, while on other POSIX systems,
$(D clock_gettime) is used.
$(RED Warning): On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
+/
static @property MonoTimeImpl currTime() @trusted nothrow @nogc
{
if(ticksPerSecond == 0)
{
import core.internal.abort : abort;
abort("MonoTimeImpl!(ClockType." ~ _clockName ~
") failed to get the frequency of the system's monotonic clock.");
}
version(Windows)
{
long ticks;
if(QueryPerformanceCounter(&ticks) == 0)
{
// This probably cannot happen on Windows 95 or later
import core.internal.abort : abort;
abort("Call to QueryPerformanceCounter failed.");
}
return MonoTimeImpl(ticks);
}
else version(Darwin)
return MonoTimeImpl(mach_absolute_time());
else version(Posix)
{
timespec ts;
if(clock_gettime(clockArg, &ts) != 0)
{
import core.internal.abort : abort;
abort("Call to clock_gettime failed.");
}
return MonoTimeImpl(convClockFreq(ts.tv_sec * 1_000_000_000L + ts.tv_nsec,
1_000_000_000L,
ticksPerSecond));
}
}
static @property pure nothrow @nogc
{
/++
A $(D MonoTime) of $(D 0) ticks. It's provided to be consistent with
$(D Duration.zero), and it's more explicit than $(D MonoTime.init).
+/
MonoTimeImpl zero() { return MonoTimeImpl(0); }
/++
Largest $(D MonoTime) possible.
+/
MonoTimeImpl max() { return MonoTimeImpl(long.max); }
/++
Most negative $(D MonoTime) possible.
+/
MonoTimeImpl min() { return MonoTimeImpl(long.min); }
}
unittest
{
assert(MonoTimeImpl.zero == MonoTimeImpl(0));
assert(MonoTimeImpl.max == MonoTimeImpl(long.max));
assert(MonoTimeImpl.min == MonoTimeImpl(long.min));
assert(MonoTimeImpl.min < MonoTimeImpl.zero);
assert(MonoTimeImpl.zero < MonoTimeImpl.max);
assert(MonoTimeImpl.min < MonoTimeImpl.max);
}
/++
Compares this MonoTime with the given MonoTime.
Returns:
$(BOOKTABLE,
$(TR $(TD this < rhs) $(TD < 0))
$(TR $(TD this == rhs) $(TD 0))
$(TR $(TD this > rhs) $(TD > 0))
)
+/
int opCmp(MonoTimeImpl rhs) const pure nothrow @nogc
{
if(_ticks < rhs._ticks)
return -1;
return _ticks > rhs._ticks ? 1 : 0;
}
unittest
{
const t = MonoTimeImpl.currTime;
assert(t == copy(t));
}
unittest
{
const before = MonoTimeImpl.currTime;
auto after = MonoTimeImpl(before._ticks + 42);
assert(before < after);
assert(copy(before) <= before);
assert(copy(after) > before);
assert(after >= copy(after));
}
unittest
{
const currTime = MonoTimeImpl.currTime;
assert(MonoTimeImpl(long.max) > MonoTimeImpl(0));
assert(MonoTimeImpl(0) > MonoTimeImpl(long.min));
assert(MonoTimeImpl(long.max) > currTime);
assert(currTime > MonoTimeImpl(0));
assert(MonoTimeImpl(0) < currTime);
assert(MonoTimeImpl(0) < MonoTimeImpl(long.max));
assert(MonoTimeImpl(long.min) < MonoTimeImpl(0));
}
/++
Subtracting two MonoTimes results in a $(LREF Duration) representing
the amount of time which elapsed between them.
The primary way that programs should time how long something takes is to
do
--------------------
MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;
// How long it took.
Duration timeElapsed = after - before;
--------------------
or to use a wrapper (such as a stop watch type) which does that.
$(RED Warning):
Because $(LREF Duration) is in hnsecs, whereas MonoTime is in system
ticks, it's usually the case that this assertion will fail
--------------------
auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);
--------------------
This is generally fine, and by its very nature, converting from
system ticks to any type of seconds (hnsecs, nsecs, etc.) will
introduce rounding errors, but if code needs to avoid any of the
small rounding errors introduced by conversion, then it needs to use
MonoTime's $(D ticks) property and keep all calculations in ticks
rather than using $(LREF Duration).
+/
Duration opBinary(string op)(MonoTimeImpl rhs) const pure nothrow @nogc
if(op == "-")
{
immutable diff = _ticks - rhs._ticks;
return Duration(convClockFreq(diff , ticksPerSecond, hnsecsPer!"seconds"));
}
unittest
{
const t = MonoTimeImpl.currTime;
assert(t - copy(t) == Duration.zero);
static assert(!__traits(compiles, t + t));
}
unittest
{
static void test(in MonoTimeImpl before, in MonoTimeImpl after, in Duration min)
{
immutable diff = after - before;
assert(diff >= min);
auto calcAfter = before + diff;
assertApprox(calcAfter, calcAfter - Duration(1), calcAfter + Duration(1));
assert(before - after == -diff);
}
const before = MonoTimeImpl.currTime;
test(before, MonoTimeImpl(before._ticks + 4202), Duration.zero);
test(before, MonoTimeImpl.currTime, Duration.zero);
const durLargerUnits = dur!"minutes"(7) + dur!"seconds"(22);
test(before, before + durLargerUnits + dur!"msecs"(33) + dur!"hnsecs"(571), durLargerUnits);
}
/++
Adding or subtracting a $(LREF Duration) to/from a MonoTime results in
a MonoTime which is adjusted by that amount.
+/
MonoTimeImpl opBinary(string op)(Duration rhs) const pure nothrow @nogc
if(op == "+" || op == "-")
{
immutable rhsConverted = convClockFreq(rhs._hnsecs, hnsecsPer!"seconds", ticksPerSecond);
mixin("return MonoTimeImpl(_ticks " ~ op ~ " rhsConverted);");
}
unittest
{
const t = MonoTimeImpl.currTime;
assert(t + Duration(0) == t);
assert(t - Duration(0) == t);
}
unittest
{
const t = MonoTimeImpl.currTime;
// We reassign ticks in order to get the same rounding errors
// that we should be getting with Duration (e.g. MonoTimeImpl may be
// at a higher precision than hnsecs, meaning that 7333 would be
// truncated when converting to hnsecs).
long ticks = 7333;
auto hnsecs = convClockFreq(ticks, ticksPerSecond, hnsecsPer!"seconds");
ticks = convClockFreq(hnsecs, hnsecsPer!"seconds", ticksPerSecond);
assert(t - Duration(hnsecs) == MonoTimeImpl(t._ticks - ticks));
assert(t + Duration(hnsecs) == MonoTimeImpl(t._ticks + ticks));
}
/++ Ditto +/
ref MonoTimeImpl opOpAssign(string op)(Duration rhs) pure nothrow @nogc
if(op == "+" || op == "-")
{
immutable rhsConverted = convClockFreq(rhs._hnsecs, hnsecsPer!"seconds", ticksPerSecond);
mixin("_ticks " ~ op ~ "= rhsConverted;");
return this;
}
unittest
{
auto mt = MonoTimeImpl.currTime;
const initial = mt;
mt += Duration(0);
assert(mt == initial);
mt -= Duration(0);
assert(mt == initial);
// We reassign ticks in order to get the same rounding errors
// that we should be getting with Duration (e.g. MonoTimeImpl may be
// at a higher precision than hnsecs, meaning that 7333 would be
// truncated when converting to hnsecs).
long ticks = 7333;
auto hnsecs = convClockFreq(ticks, ticksPerSecond, hnsecsPer!"seconds");
ticks = convClockFreq(hnsecs, hnsecsPer!"seconds", ticksPerSecond);
auto before = MonoTimeImpl(initial._ticks - ticks);
assert((mt -= Duration(hnsecs)) == before);
assert(mt == before);
assert((mt += Duration(hnsecs)) == initial);
assert(mt == initial);
}
/++
The number of ticks in the monotonic time.
Most programs should not use this directly, but it's exposed for those
few programs that need it.
The main reasons that a program might need to use ticks directly is if
the system clock has higher precision than hnsecs, and the program needs
that higher precision, or if the program needs to avoid the rounding
errors caused by converting to hnsecs.
+/
@property long ticks() const pure nothrow @nogc
{
return _ticks;
}
unittest
{
const mt = MonoTimeImpl.currTime;
assert(mt.ticks == mt._ticks);
}
/++
The number of ticks that MonoTime has per second - i.e. the resolution
or frequency of the system's monotonic clock.
e.g. if the system clock had a resolution of microseconds, then
ticksPerSecond would be $(D 1_000_000).
+/
static @property long ticksPerSecond() pure nothrow @nogc
{
return _ticksPerSecond[_clockIdx];
}
unittest
{
assert(MonoTimeImpl.ticksPerSecond == _ticksPerSecond[_clockIdx]);
}
///
string toString() const pure nothrow
{
static if(clockType == ClockType.normal)
return "MonoTime(" ~ signedToTempString(_ticks, 10) ~ " ticks, " ~ signedToTempString(ticksPerSecond, 10) ~ " ticks per second)";
else
return "MonoTimeImpl!(ClockType." ~ _clockName ~ ")(" ~ signedToTempString(_ticks, 10) ~ " ticks, " ~
signedToTempString(ticksPerSecond, 10) ~ " ticks per second)";
}
unittest
{
static min(T)(T a, T b) { return a < b ? a : b; }
static void eat(ref string s, const(char)[] exp)
{
assert(s[0 .. min($, exp.length)] == exp, s~" != "~exp);
s = s[exp.length .. $];
}
immutable mt = MonoTimeImpl.currTime;
auto str = mt.toString();
static if(is(typeof(this) == MonoTime))
eat(str, "MonoTime(");
else
eat(str, "MonoTimeImpl!(ClockType."~_clockName~")(");
eat(str, signedToTempString(mt._ticks, 10));
eat(str, " ticks, ");
eat(str, signedToTempString(ticksPerSecond, 10));
eat(str, " ticks per second)");
}
private:
// static immutable long _ticksPerSecond;
unittest
{
assert(_ticksPerSecond[_clockIdx]);
}
long _ticks;
}
// This is supposed to be a static variable in MonoTimeImpl with the static
// constructor being in there, but https://issues.dlang.org/show_bug.cgi?id=14517
// prevents that from working. However, moving it back to a static ctor will
// reraise issues with other systems using MonoTime, so we should leave this
// here even when that bug is fixed.
private immutable long[__traits(allMembers, ClockType).length] _ticksPerSecond;
// This is called directly from the runtime initilization function (rt_init),
// instead of using a static constructor. Other subsystems inside the runtime
// (namely, the GC) may need time functionality, but cannot wait until the
// static ctors have run. Therefore, we initialize these specially. Because
// it's a normal function, we need to do some dangerous casting PLEASE take
// care when modifying this function, and it should NOT be called except from
// the runtime init.
//
// NOTE: the code below SPECIFICALLY does not assert when it cannot initialize
// the ticks per second array. This allows cases where a clock is never used on
// a system that doesn't support it. See bugzilla issue
// https://issues.dlang.org/show_bug.cgi?id=14863
// The assert will occur when someone attempts to use _ticksPerSecond for that
// value.
extern(C) void _d_initMonoTime()
{
// We need a mutable pointer to the ticksPerSecond array. Although this
// would appear to break immutability, it is logically the same as a static
// ctor. So we should ONLY write these values once (we will check for 0
// values when setting to ensure this is truly only called once).
auto tps = cast(long[])_ticksPerSecond[];
// If we try to do anything with ClockType in the documentation build, it'll
// trigger the static assertions related to ClockType, since the
// documentation build defines all of the possible ClockTypes, which won't
// work when they're used in the static ifs, because no system supports them
// all.
version(CoreDdoc)
{}
else version(Windows)
{
long ticksPerSecond;
if(QueryPerformanceFrequency(&ticksPerSecond) != 0)
{
foreach(i, typeStr; __traits(allMembers, ClockType))
{
// ensure we are only writing immutable data once
if(tps[i] != 0)
// should only be called once
assert(0);
tps[i] = ticksPerSecond;
}
}
}
else version(Darwin)
{
immutable long ticksPerSecond = machTicksPerSecond();
foreach(i, typeStr; __traits(allMembers, ClockType))
{
// ensure we are only writing immutable data once
if(tps[i] != 0)
// should only be called once
assert(0);
tps[i] = ticksPerSecond;
}
}
else version(Posix)
{
timespec ts;
foreach(i, typeStr; __traits(allMembers, ClockType))
{
static if(typeStr != "second")
{
enum clockArg = _posixClock(__traits(getMember, ClockType, typeStr));
if(clock_getres(clockArg, &ts) == 0)
{
// ensure we are only writing immutable data once
if(tps[i] != 0)
// should only be called once
assert(0);
// For some reason, on some systems, clock_getres returns
// a resolution which is clearly wrong:
// - it's a millisecond or worse, but the time is updated
// much more frequently than that.
// - it's negative
// - it's zero
// In such cases, we'll just use nanosecond resolution.
tps[i] = ts.tv_sec != 0 || ts.tv_nsec <= 0 || ts.tv_nsec >= 1000
? 1_000_000_000L : 1_000_000_000L / ts.tv_nsec;
}
}
}
}
}
// Tests for MonoTimeImpl.currTime. It has to be outside, because MonoTimeImpl
// is a template. This unittest block also makes sure that MonoTimeImpl actually
// is instantiated with all of the various ClockTypes so that those types and
// their tests are compiled and run.
unittest
{
// This test is separate so that it can be tested with MonoTime and not just
// MonoTimeImpl.
auto norm1 = MonoTime.currTime;
auto norm2 = MonoTimeImpl!(ClockType.normal).currTime;
assert(norm1 <= norm2);
static bool clockSupported(ClockType c)
{
version (Linux_Pre_2639) // skip CLOCK_BOOTTIME on older linux kernels
return c != ClockType.second && c != ClockType.bootTime;
else
return c != ClockType.second; // second doesn't work with MonoTimeImpl
}
foreach(typeStr; __traits(allMembers, ClockType))
{
mixin("alias type = ClockType." ~ typeStr ~ ";");
static if (clockSupported(type))
{
auto v1 = MonoTimeImpl!type.currTime;
auto v2 = MonoTimeImpl!type.currTime;
scope(failure)
{
printf("%s: v1 %s, v2 %s, tps %s\n",
(type.stringof ~ "\0").ptr,
numToStringz(v1._ticks),
numToStringz(v2._ticks),
numToStringz(typeof(v1).ticksPerSecond));
}
assert(v1 <= v2);
foreach(otherStr; __traits(allMembers, ClockType))
{
mixin("alias other = ClockType." ~ otherStr ~ ";");
static if (clockSupported(other))
{
static assert(is(typeof({auto o1 = MonTimeImpl!other.currTime; auto b = v1 <= o1;})) ==
is(type == other));
}
}
}
}
}
/++
Converts the given time from one clock frequency/resolution to another.
See_Also:
$(LREF ticksToNSecs)
+/
long convClockFreq(long ticks, long srcTicksPerSecond, long dstTicksPerSecond) @safe pure nothrow @nogc
{
// This would be more straightforward with floating point arithmetic,
// but we avoid it here in order to avoid the rounding errors that that
// introduces. Also, by splitting out the units in this way, we're able
// to deal with much larger values before running into problems with
// integer overflow.
return ticks / srcTicksPerSecond * dstTicksPerSecond +
ticks % srcTicksPerSecond * dstTicksPerSecond / srcTicksPerSecond;
}
///
unittest
{
// one tick is one second -> one tick is a hecto-nanosecond
assert(convClockFreq(45, 1, 10_000_000) == 450_000_000);
// one tick is one microsecond -> one tick is a millisecond
assert(convClockFreq(9029, 1_000_000, 1_000) == 9);
// one tick is 1/3_515_654 of a second -> 1/1_001_010 of a second
assert(convClockFreq(912_319, 3_515_654, 1_001_010) == 259_764);
// one tick is 1/MonoTime.ticksPerSecond -> one tick is a nanosecond
// Equivalent to ticksToNSecs
auto nsecs = convClockFreq(1982, MonoTime.ticksPerSecond, 1_000_000_000);
}
unittest
{
assert(convClockFreq(99, 43, 57) == 131);
assert(convClockFreq(131, 57, 43) == 98);
assert(convClockFreq(1234567890, 10_000_000, 1_000_000_000) == 123456789000);
assert(convClockFreq(1234567890, 1_000_000_000, 10_000_000) == 12345678);
assert(convClockFreq(123456789000, 1_000_000_000, 10_000_000) == 1234567890);
assert(convClockFreq(12345678, 10_000_000, 1_000_000_000) == 1234567800);
assert(convClockFreq(13131, 3_515_654, 10_000_000) == 37350);
assert(convClockFreq(37350, 10_000_000, 3_515_654) == 13130);
assert(convClockFreq(37350, 3_515_654, 10_000_000) == 106239);
assert(convClockFreq(106239, 10_000_000, 3_515_654) == 37349);
// It would be too expensive to cover a large range of possible values for
// ticks, so we use random values in an attempt to get reasonable coverage.
import core.stdc.stdlib;
immutable seed = cast(int)time(null);
srand(seed);
scope(failure) printf("seed %d\n", seed);
enum freq1 = 5_527_551L;
enum freq2 = 10_000_000L;
enum freq3 = 1_000_000_000L;
enum freq4 = 98_123_320L;
immutable freq5 = MonoTime.ticksPerSecond;
// This makes it so that freq6 is the first multiple of 10 which is greater
// than or equal to freq5, which at one point was considered for MonoTime's
// ticksPerSecond rather than using the system's actual clock frequency, so
// it seemed like a good test case to have.
import core.stdc.math;
immutable numDigitsMinus1 = cast(int)floor(log10(freq5));
auto freq6 = cast(long)pow(10, numDigitsMinus1);
if(freq5 > freq6)
freq6 *= 10;
foreach(_; 0 .. 10_000)
{
long[2] values = [rand(), cast(long)rand() * (rand() % 16)];
foreach(i; values)
{
scope(failure) printf("i %s\n", numToStringz(i));
assertApprox(convClockFreq(convClockFreq(i, freq1, freq2), freq2, freq1), i - 10, i + 10);
assertApprox(convClockFreq(convClockFreq(i, freq2, freq1), freq1, freq2), i - 10, i + 10);
assertApprox(convClockFreq(convClockFreq(i, freq3, freq4), freq4, freq3), i - 100, i + 100);
assertApprox(convClockFreq(convClockFreq(i, freq4, freq3), freq3, freq4), i - 100, i + 100);
scope(failure) printf("sys %s mt %s\n", numToStringz(freq5), numToStringz(freq6));
assertApprox(convClockFreq(convClockFreq(i, freq5, freq6), freq6, freq5), i - 10, i + 10);
assertApprox(convClockFreq(convClockFreq(i, freq6, freq5), freq5, freq6), i - 10, i + 10);
// This is here rather than in a unittest block immediately after
// ticksToNSecs in order to avoid code duplication in the unit tests.
assert(convClockFreq(i, MonoTime.ticksPerSecond, 1_000_000_000) == ticksToNSecs(i));
}
}
}
/++
Convenience wrapper around $(LREF convClockFreq) which converts ticks at
a clock frequency of $(D MonoTime.ticksPerSecond) to nanoseconds.
It's primarily of use when $(D MonoTime.ticksPerSecond) is greater than
hecto-nanosecond resolution, and an application needs a higher precision
than hecto-nanoceconds.
See_Also:
$(LREF convClockFreq)
+/
long ticksToNSecs(long ticks) @safe pure nothrow @nogc
{
return convClockFreq(ticks, MonoTime.ticksPerSecond, 1_000_000_000);
}
///
unittest
{
auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto diffInTicks = after.ticks - before.ticks;
auto diffInNSecs = ticksToNSecs(diffInTicks);
assert(diffInNSecs == convClockFreq(diffInTicks, MonoTime.ticksPerSecond, 1_000_000_000));
}
/++
The reverse of $(LREF ticksToNSecs).
+/
long nsecsToTicks(long ticks) @safe pure nothrow @nogc
{
return convClockFreq(ticks, 1_000_000_000, MonoTime.ticksPerSecond);
}
unittest
{
long ticks = 123409832717333;
auto nsecs = convClockFreq(ticks, MonoTime.ticksPerSecond, 1_000_000_000);
ticks = convClockFreq(nsecs, 1_000_000_000, MonoTime.ticksPerSecond);
assert(nsecsToTicks(nsecs) == ticks);
}
/++
$(RED Warning: TickDuration will be deprecated in the near future (once all
uses of it in Phobos have been deprecated). Please use
$(LREF MonoTime) for the cases where a monotonic timestamp is needed
and $(LREF Duration) when a duration is needed, rather than using
TickDuration. It has been decided that TickDuration is too confusing
(e.g. it conflates a monotonic timestamp and a duration in monotonic
clock ticks) and that having multiple duration types is too awkward
and confusing.)
Represents a duration of time in system clock ticks.
The system clock ticks are the ticks of the system clock at the highest
precision that the system provides.
+/
struct TickDuration
{
/++
The number of ticks that the system clock has in one second.
If $(D ticksPerSec) is $(D 0), then then $(D TickDuration) failed to
get the value of $(D ticksPerSec) on the current system, and
$(D TickDuration) is not going to work. That would be highly abnormal
though.
+/
static immutable long ticksPerSec;
/++
The tick of the system clock (as a $(D TickDuration)) when the
application started.
+/
static immutable TickDuration appOrigin;
static @property @safe pure nothrow @nogc
{
/++
It's the same as $(D TickDuration(0)), but it's provided to be
consistent with $(D Duration) and $(D FracSec), which provide $(D zero)
properties.
+/
TickDuration zero() { return TickDuration(0); }
/++
Largest $(D TickDuration) possible.
+/
TickDuration max() { return TickDuration(long.max); }
/++
Most negative $(D TickDuration) possible.
+/
TickDuration min() { return TickDuration(long.min); }
}
unittest
{
assert(zero == TickDuration(0));
assert(TickDuration.max == TickDuration(long.max));
assert(TickDuration.min == TickDuration(long.min));
assert(TickDuration.min < TickDuration.zero);
assert(TickDuration.zero < TickDuration.max);
assert(TickDuration.min < TickDuration.max);
assert(TickDuration.min - TickDuration(1) == TickDuration.max);
assert(TickDuration.max + TickDuration(1) == TickDuration.min);
}
@trusted shared static this()
{
version(Windows)
{
if(QueryPerformanceFrequency(cast(long*)&ticksPerSec) == 0)
ticksPerSec = 0;
}
else version(Darwin)
{
ticksPerSec = machTicksPerSecond();
}
else version(Posix)
{
static if(is(typeof(clock_gettime)))
{
timespec ts;
if(clock_getres(CLOCK_MONOTONIC, &ts) != 0)
ticksPerSec = 0;
else
{
//For some reason, on some systems, clock_getres returns
//a resolution which is clearly wrong (it's a millisecond
//or worse, but the time is updated much more frequently
//than that). In such cases, we'll just use nanosecond
//resolution.
ticksPerSec = ts.tv_nsec >= 1000 ? 1_000_000_000
: 1_000_000_000 / ts.tv_nsec;
}
}
else
ticksPerSec = 1_000_000;
}
if(ticksPerSec != 0)
appOrigin = TickDuration.currSystemTick;
}
unittest
{
assert(ticksPerSec);
}
/++
The number of system ticks in this $(D TickDuration).
You can convert this $(D length) into the number of seconds by dividing
it by $(D ticksPerSec) (or using one the appropriate property function
to do it).
+/
long length;
/++
Returns the total number of seconds in this $(D TickDuration).
+/
@property long seconds() @safe const pure nothrow @nogc
{
return this.to!("seconds", long)();
}
unittest
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
assert((cast(T)TickDuration(ticksPerSec)).seconds == 1);
assert((cast(T)TickDuration(ticksPerSec - 1)).seconds == 0);
assert((cast(T)TickDuration(ticksPerSec * 2)).seconds == 2);
assert((cast(T)TickDuration(ticksPerSec * 2 - 1)).seconds == 1);
assert((cast(T)TickDuration(-1)).seconds == 0);
assert((cast(T)TickDuration(-ticksPerSec - 1)).seconds == -1);
assert((cast(T)TickDuration(-ticksPerSec)).seconds == -1);
}
}
/++
Returns the total number of milliseconds in this $(D TickDuration).
+/
@property long msecs() @safe const pure nothrow @nogc
{
return this.to!("msecs", long)();
}
/++
Returns the total number of microseconds in this $(D TickDuration).
+/
@property long usecs() @safe const pure nothrow @nogc
{
return this.to!("usecs", long)();
}
/++
Returns the total number of hecto-nanoseconds in this $(D TickDuration).
+/
@property long hnsecs() @safe const pure nothrow @nogc
{
return this.to!("hnsecs", long)();
}
/++
Returns the total number of nanoseconds in this $(D TickDuration).
+/
@property long nsecs() @safe const pure nothrow @nogc
{
return this.to!("nsecs", long)();
}
/++
This allows you to construct a $(D TickDuration) from the given time
units with the given length.
Params:
units = The time units of the $(D TickDuration) (e.g. $(D "msecs")).
length = The number of units in the $(D TickDuration).
+/
static TickDuration from(string units)(long length) @safe pure nothrow @nogc
if(units == "seconds" ||
units == "msecs" ||
units == "usecs" ||
units == "hnsecs" ||
units == "nsecs")
{
enum unitsPerSec = convert!("seconds", units)(1);
return TickDuration(cast(long)(length * (ticksPerSec / cast(real)unitsPerSec)));
}
unittest
{
foreach(units; _TypeTuple!("seconds", "msecs", "usecs", "nsecs"))
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
assertApprox((cast(T)TickDuration.from!units(1000)).to!(units, long)(),
500, 1500, units);
assertApprox((cast(T)TickDuration.from!units(1_000_000)).to!(units, long)(),
900_000, 1_100_000, units);
assertApprox((cast(T)TickDuration.from!units(2_000_000)).to!(units, long)(),
1_900_000, 2_100_000, units);
}
}
}
/++
Returns a $(LREF Duration) with the same number of hnsecs as this
$(D TickDuration).
Note that the conventional way to convert between $(D TickDuration)
and $(D Duration) is using $(REF to, std,conv), e.g.:
$(D tickDuration.to!Duration())
+/
Duration opCast(T)() @safe const pure nothrow @nogc
if(is(_Unqual!T == Duration))
{
return Duration(hnsecs);
}
unittest
{
foreach(D; _TypeTuple!(Duration, const Duration, immutable Duration))
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
auto expected = dur!"seconds"(1);
assert(cast(D)cast(T)TickDuration.from!"seconds"(1) == expected);
foreach(units; _TypeTuple!("msecs", "usecs", "hnsecs"))
{
D actual = cast(D)cast(T)TickDuration.from!units(1_000_000);
assertApprox(actual, dur!units(900_000), dur!units(1_100_000));
}
}
}
}
//Temporary hack until bug http://d.puremagic.com/issues/show_bug.cgi?id=5747 is fixed.
TickDuration opCast(T)() @safe const pure nothrow @nogc
if(is(_Unqual!T == TickDuration))
{
return this;
}
/++
Adds or subtracts two $(D TickDuration)s as well as assigning the result
to this $(D TickDuration).
The legal types of arithmetic for $(D TickDuration) using this operator
are
$(TABLE
$(TR $(TD TickDuration) $(TD +=) $(TD TickDuration) $(TD -->) $(TD TickDuration))
$(TR $(TD TickDuration) $(TD -=) $(TD TickDuration) $(TD -->) $(TD TickDuration))
)
Params:
rhs = The $(D TickDuration) to add to or subtract from this
$(D $(D TickDuration)).
+/
ref TickDuration opOpAssign(string op)(TickDuration rhs) @safe pure nothrow @nogc
if(op == "+" || op == "-")
{
mixin("length " ~ op ~ "= rhs.length;");
return this;
}
unittest
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
auto a = TickDuration.currSystemTick;
auto result = a += cast(T)TickDuration.currSystemTick;
assert(a == result);
assert(a.to!("seconds", real)() >= 0);
auto b = TickDuration.currSystemTick;
result = b -= cast(T)TickDuration.currSystemTick;
assert(b == result);
assert(b.to!("seconds", real)() <= 0);
foreach(U; _TypeTuple!(const TickDuration, immutable TickDuration))
{
U u = TickDuration(12);
static assert(!__traits(compiles, u += cast(T)TickDuration.currSystemTick));
static assert(!__traits(compiles, u -= cast(T)TickDuration.currSystemTick));
}
}
}
/++
Adds or subtracts two $(D TickDuration)s.
The legal types of arithmetic for $(D TickDuration) using this operator
are
$(TABLE
$(TR $(TD TickDuration) $(TD +) $(TD TickDuration) $(TD -->) $(TD TickDuration))
$(TR $(TD TickDuration) $(TD -) $(TD TickDuration) $(TD -->) $(TD TickDuration))
)
Params:
rhs = The $(D TickDuration) to add to or subtract from this
$(D TickDuration).
+/
TickDuration opBinary(string op)(TickDuration rhs) @safe const pure nothrow @nogc
if(op == "+" || op == "-")
{
return TickDuration(mixin("length " ~ op ~ " rhs.length"));
}
unittest
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
T a = TickDuration.currSystemTick;
T b = TickDuration.currSystemTick;
assert((a + b).seconds > 0);
assert((a - b).seconds <= 0);
}
}
/++
Returns the negation of this $(D TickDuration).
+/
TickDuration opUnary(string op)() @safe const pure nothrow @nogc
if(op == "-")
{
return TickDuration(-length);
}
unittest
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
assert(-(cast(T)TickDuration(7)) == TickDuration(-7));
assert(-(cast(T)TickDuration(5)) == TickDuration(-5));
assert(-(cast(T)TickDuration(-7)) == TickDuration(7));
assert(-(cast(T)TickDuration(-5)) == TickDuration(5));
assert(-(cast(T)TickDuration(0)) == TickDuration(0));
}
}
/++
operator overloading "<, >, <=, >="
+/
int opCmp(TickDuration rhs) @safe const pure nothrow @nogc
{
return length < rhs.length ? -1 : (length == rhs.length ? 0 : 1);
}
unittest
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
foreach(U; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
T t = TickDuration.currSystemTick;
U u = t;
assert(t == u);
assert(copy(t) == u);
assert(t == copy(u));
}
}
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
foreach(U; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
T t = TickDuration.currSystemTick;
U u = t + t;
assert(t < u);
assert(t <= t);
assert(u > t);
assert(u >= u);
assert(copy(t) < u);
assert(copy(t) <= t);
assert(copy(u) > t);
assert(copy(u) >= u);
assert(t < copy(u));
assert(t <= copy(t));
assert(u > copy(t));
assert(u >= copy(u));
}
}
}
/++
The legal types of arithmetic for $(D TickDuration) using this operator
overload are
$(TABLE
$(TR $(TD TickDuration) $(TD *) $(TD long) $(TD -->) $(TD TickDuration))
$(TR $(TD TickDuration) $(TD *) $(TD floating point) $(TD -->) $(TD TickDuration))
)
Params:
value = The value to divide from this duration.
+/
void opOpAssign(string op, T)(T value) @safe pure nothrow @nogc
if(op == "*" &&
(__traits(isIntegral, T) || __traits(isFloating, T)))
{
length = cast(long)(length * value);
}
unittest
{
immutable curr = TickDuration.currSystemTick;
TickDuration t1 = curr;
immutable t2 = curr + curr;
t1 *= 2;
assert(t1 == t2);
t1 = curr;
t1 *= 2.0;
immutable tol = TickDuration(cast(long)(_abs(t1.length) * double.epsilon * 2.0));
assertApprox(t1, t2 - tol, t2 + tol);
t1 = curr;
t1 *= 2.1;
assert(t1 > t2);
foreach(T; _TypeTuple!(const TickDuration, immutable TickDuration))
{
T t = TickDuration.currSystemTick;
assert(!__traits(compiles, t *= 12));
assert(!__traits(compiles, t *= 12.0));
}
}
/++
The legal types of arithmetic for $(D TickDuration) using this operator
overload are
$(TABLE
$(TR $(TD TickDuration) $(TD /) $(TD long) $(TD -->) $(TD TickDuration))
$(TR $(TD TickDuration) $(TD /) $(TD floating point) $(TD -->) $(TD TickDuration))
)
Params:
value = The value to divide from this $(D TickDuration).
Throws:
$(D TimeException) if an attempt to divide by $(D 0) is made.
+/
void opOpAssign(string op, T)(T value) @safe pure
if(op == "/" &&
(__traits(isIntegral, T) || __traits(isFloating, T)))
{
if(value == 0)
throw new TimeException("Attempted division by 0.");
length = cast(long)(length / value);
}
unittest
{
immutable curr = TickDuration.currSystemTick;
immutable t1 = curr;
TickDuration t2 = curr + curr;
t2 /= 2;
assert(t1 == t2);
t2 = curr + curr;
t2 /= 2.0;
immutable tol = TickDuration(cast(long)(_abs(t2.length) * double.epsilon / 2.0));
assertApprox(t1, t2 - tol, t2 + tol);
t2 = curr + curr;
t2 /= 2.1;
assert(t1 > t2);
_assertThrown!TimeException(t2 /= 0);
foreach(T; _TypeTuple!(const TickDuration, immutable TickDuration))
{
T t = TickDuration.currSystemTick;
assert(!__traits(compiles, t /= 12));
assert(!__traits(compiles, t /= 12.0));
}
}
/++
The legal types of arithmetic for $(D TickDuration) using this operator
overload are
$(TABLE
$(TR $(TD TickDuration) $(TD *) $(TD long) $(TD -->) $(TD TickDuration))
$(TR $(TD TickDuration) $(TD *) $(TD floating point) $(TD -->) $(TD TickDuration))
)
Params:
value = The value to divide from this $(D TickDuration).
+/
TickDuration opBinary(string op, T)(T value) @safe const pure nothrow @nogc
if(op == "*" &&
(__traits(isIntegral, T) || __traits(isFloating, T)))
{
return TickDuration(cast(long)(length * value));
}
unittest
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
T t1 = TickDuration.currSystemTick;
T t2 = t1 + t1;
assert(t1 * 2 == t2);
immutable tol = TickDuration(cast(long)(_abs(t1.length) * double.epsilon * 2.0));
assertApprox(t1 * 2.0, t2 - tol, t2 + tol);
assert(t1 * 2.1 > t2);
}
}
/++
The legal types of arithmetic for $(D TickDuration) using this operator
overload are
$(TABLE
$(TR $(TD TickDuration) $(TD /) $(TD long) $(TD -->) $(TD TickDuration))
$(TR $(TD TickDuration) $(TD /) $(TD floating point) $(TD -->) $(TD TickDuration))
)
Params:
value = The value to divide from this $(D TickDuration).
Throws:
$(D TimeException) if an attempt to divide by $(D 0) is made.
+/
TickDuration opBinary(string op, T)(T value) @safe const pure
if(op == "/" &&
(__traits(isIntegral, T) || __traits(isFloating, T)))
{
if(value == 0)
throw new TimeException("Attempted division by 0.");
return TickDuration(cast(long)(length / value));
}
unittest
{
foreach(T; _TypeTuple!(TickDuration, const TickDuration, immutable TickDuration))
{
T t1 = TickDuration.currSystemTick;
T t2 = t1 + t1;
assert(t2 / 2 == t1);
immutable tol = TickDuration(cast(long)(_abs(t2.length) * double.epsilon / 2.0));
assertApprox(t2 / 2.0, t1 - tol, t1 + tol);
assert(t2 / 2.1 < t1);
_assertThrown!TimeException(t2 / 0);
}
}
/++
Params:
ticks = The number of ticks in the TickDuration.
+/
@safe pure nothrow @nogc this(long ticks)
{
this.length = ticks;
}
unittest
{
foreach(i; [-42, 0, 42])
assert(TickDuration(i).length == i);
}
/++
The current system tick. The number of ticks per second varies from
system to system. $(D currSystemTick) uses a monotonic clock, so it's
intended for precision timing by comparing relative time values, not for
getting the current system time.
On Windows, $(D QueryPerformanceCounter) is used. On Mac OS X,
$(D mach_absolute_time) is used, while on other Posix systems,
$(D clock_gettime) is used. If $(D mach_absolute_time) or
$(D clock_gettime) is unavailable, then Posix systems use
$(D gettimeofday) (the decision is made when $(D TickDuration) is
compiled), which unfortunately, is not monotonic, but if
$(D mach_absolute_time) and $(D clock_gettime) aren't available, then
$(D gettimeofday) is the the best that there is.
$(RED Warning):
On some systems, the monotonic clock may stop counting when
the computer goes to sleep or hibernates. So, the monotonic
clock could be off if that occurs. This is known to happen
on Mac OS X. It has not been tested whether it occurs on
either Windows or on Linux.
Throws:
$(D TimeException) if it fails to get the time.
+/
static @property TickDuration currSystemTick() @trusted nothrow @nogc
{
import core.internal.abort : abort;
version(Windows)
{
ulong ticks;
if(QueryPerformanceCounter(cast(long*)&ticks) == 0)
abort("Failed in QueryPerformanceCounter().");
return TickDuration(ticks);
}
else version(Darwin)
{
static if(is(typeof(mach_absolute_time)))
return TickDuration(cast(long)mach_absolute_time());
else
{
timeval tv;
if(gettimeofday(&tv, null) != 0)
abort("Failed in gettimeofday().");
return TickDuration(tv.tv_sec * TickDuration.ticksPerSec +
tv.tv_usec * TickDuration.ticksPerSec / 1000 / 1000);
}
}
else version(Posix)
{
static if(is(typeof(clock_gettime)))
{
timespec ts;
if(clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
abort("Failed in clock_gettime().");
return TickDuration(ts.tv_sec * TickDuration.ticksPerSec +
ts.tv_nsec * TickDuration.ticksPerSec / 1000 / 1000 / 1000);
}
else
{
timeval tv;
if(gettimeofday(&tv, null) != 0)
abort("Failed in gettimeofday().");
return TickDuration(tv.tv_sec * TickDuration.ticksPerSec +
tv.tv_usec * TickDuration.ticksPerSec / 1000 / 1000);
}
}
}
@safe nothrow unittest
{
assert(TickDuration.currSystemTick.length > 0);
}
}
/++
Generic way of converting between two time units. Conversions to smaller
units use truncating division. Years and months can be converted to each
other, small units can be converted to each other, but years and months
cannot be converted to or from smaller units (due to the varying number
of days in a month or year).
Params:
from = The units of time to convert from.
to = The units of time to convert to.
value = The value to convert.
+/
long convert(string from, string to)(long value) @safe pure nothrow @nogc
if(((from == "weeks" ||
from == "days" ||
from == "hours" ||
from == "minutes" ||
from == "seconds" ||
from == "msecs" ||
from == "usecs" ||
from == "hnsecs" ||
from == "nsecs") &&
(to == "weeks" ||
to == "days" ||
to == "hours" ||
to == "minutes" ||
to == "seconds" ||
to == "msecs" ||
to == "usecs" ||
to == "hnsecs" ||
to == "nsecs")) ||
((from == "years" || from == "months") && (to == "years" || to == "months")))
{
static if(from == "years")
{
static if(to == "years")
return value;
else static if(to == "months")
return value * 12;
else
static assert(0, "A generic month or year cannot be converted to or from smaller units.");
}
else static if(from == "months")
{
static if(to == "years")
return value / 12;
else static if(to == "months")
return value;
else
static assert(0, "A generic month or year cannot be converted to or from smaller units.");
}
else static if(from == "nsecs" && to == "nsecs")
return value;
else static if(from == "nsecs")
return convert!("hnsecs", to)(value / 100);
else static if(to == "nsecs")
return convert!(from, "hnsecs")(value) * 100;
else
return (hnsecsPer!from * value) / hnsecsPer!to;
}
///
unittest
{
assert(convert!("years", "months")(1) == 12);
assert(convert!("months", "years")(12) == 1);
assert(convert!("weeks", "days")(1) == 7);
assert(convert!("hours", "seconds")(1) == 3600);
assert(convert!("seconds", "days")(1) == 0);
assert(convert!("seconds", "days")(86_400) == 1);
assert(convert!("nsecs", "nsecs")(1) == 1);
assert(convert!("nsecs", "hnsecs")(1) == 0);
assert(convert!("hnsecs", "nsecs")(1) == 100);
assert(convert!("nsecs", "seconds")(1) == 0);
assert(convert!("seconds", "nsecs")(1) == 1_000_000_000);
}
unittest
{
foreach(units; _TypeTuple!("weeks", "days", "hours", "seconds", "msecs", "usecs", "hnsecs", "nsecs"))
{
static assert(!__traits(compiles, convert!("years", units)(12)), units);
static assert(!__traits(compiles, convert!(units, "years")(12)), units);
}
foreach(units; _TypeTuple!("years", "months", "weeks", "days",
"hours", "seconds", "msecs", "usecs", "hnsecs", "nsecs"))
{
assert(convert!(units, units)(12) == 12);
}
assert(convert!("weeks", "hnsecs")(1) == 6_048_000_000_000L);
assert(convert!("days", "hnsecs")(1) == 864_000_000_000L);
assert(convert!("hours", "hnsecs")(1) == 36_000_000_000L);
assert(convert!("minutes", "hnsecs")(1) == 600_000_000L);
assert(convert!("seconds", "hnsecs")(1) == 10_000_000L);
assert(convert!("msecs", "hnsecs")(1) == 10_000);
assert(convert!("usecs", "hnsecs")(1) == 10);
assert(convert!("hnsecs", "weeks")(6_048_000_000_000L) == 1);
assert(convert!("hnsecs", "days")(864_000_000_000L) == 1);
assert(convert!("hnsecs", "hours")(36_000_000_000L) == 1);
assert(convert!("hnsecs", "minutes")(600_000_000L) == 1);
assert(convert!("hnsecs", "seconds")(10_000_000L) == 1);
assert(convert!("hnsecs", "msecs")(10_000) == 1);
assert(convert!("hnsecs", "usecs")(10) == 1);
assert(convert!("weeks", "days")(1) == 7);
assert(convert!("days", "weeks")(7) == 1);
assert(convert!("days", "hours")(1) == 24);
assert(convert!("hours", "days")(24) == 1);
assert(convert!("hours", "minutes")(1) == 60);
assert(convert!("minutes", "hours")(60) == 1);
assert(convert!("minutes", "seconds")(1) == 60);
assert(convert!("seconds", "minutes")(60) == 1);
assert(convert!("seconds", "msecs")(1) == 1000);
assert(convert!("msecs", "seconds")(1000) == 1);
assert(convert!("msecs", "usecs")(1) == 1000);
assert(convert!("usecs", "msecs")(1000) == 1);
assert(convert!("usecs", "hnsecs")(1) == 10);
assert(convert!("hnsecs", "usecs")(10) == 1);
assert(convert!("weeks", "nsecs")(1) == 604_800_000_000_000L);
assert(convert!("days", "nsecs")(1) == 86_400_000_000_000L);
assert(convert!("hours", "nsecs")(1) == 3_600_000_000_000L);
assert(convert!("minutes", "nsecs")(1) == 60_000_000_000L);
assert(convert!("seconds", "nsecs")(1) == 1_000_000_000L);
assert(convert!("msecs", "nsecs")(1) == 1_000_000);
assert(convert!("usecs", "nsecs")(1) == 1000);
assert(convert!("hnsecs", "nsecs")(1) == 100);
assert(convert!("nsecs", "weeks")(604_800_000_000_000L) == 1);
assert(convert!("nsecs", "days")(86_400_000_000_000L) == 1);
assert(convert!("nsecs", "hours")(3_600_000_000_000L) == 1);
assert(convert!("nsecs", "minutes")(60_000_000_000L) == 1);
assert(convert!("nsecs", "seconds")(1_000_000_000L) == 1);
assert(convert!("nsecs", "msecs")(1_000_000) == 1);
assert(convert!("nsecs", "usecs")(1000) == 1);
assert(convert!("nsecs", "hnsecs")(100) == 1);
}
/++
Represents fractional seconds.
This is the portion of the time which is smaller than a second and it cannot
hold values which would be greater than or equal to a second (or less than
or equal to a negative second).
It holds hnsecs internally, but you can create it using either milliseconds,
microseconds, or hnsecs. What it does is allow for a simple way to set or
adjust the fractional seconds portion of a $(D Duration) or a
$(REF SysTime, std,datetime) without having to worry about whether you're
dealing with milliseconds, microseconds, or hnsecs.
$(D FracSec)'s functions which take time unit strings do accept
$(D "nsecs"), but because the resolution of $(D Duration) and
$(REF SysTime, std,datetime) is hnsecs, you don't actually get precision higher
than hnsecs. $(D "nsecs") is accepted merely for convenience. Any values
given as nsecs will be converted to hnsecs using $(D convert) (which uses
truncating division when converting to smaller units).
+/
struct FracSec
{
@safe pure:
public:
/++
A $(D FracSec) of $(D 0). It's shorter than doing something like
$(D FracSec.from!"msecs"(0)) and more explicit than $(D FracSec.init).
+/
static @property nothrow @nogc FracSec zero() { return FracSec(0); }
unittest
{
assert(zero == FracSec.from!"msecs"(0));
}
/++
Create a $(D FracSec) from the given units ($(D "msecs"), $(D "usecs"),
or $(D "hnsecs")).
Params:
units = The units to create a FracSec from.
value = The number of the given units passed the second.
Throws:
$(D TimeException) if the given value would result in a $(D FracSec)
greater than or equal to $(D 1) second or less than or equal to
$(D -1) seconds.
+/
static FracSec from(string units)(long value)
if(units == "msecs" ||
units == "usecs" ||
units == "hnsecs" ||
units == "nsecs")
{
immutable hnsecs = cast(int)convert!(units, "hnsecs")(value);
_enforceValid(hnsecs);
return FracSec(hnsecs);
}
unittest
{
assert(FracSec.from!"msecs"(0) == FracSec(0));
assert(FracSec.from!"usecs"(0) == FracSec(0));
assert(FracSec.from!"hnsecs"(0) == FracSec(0));
foreach(sign; [1, -1])
{
_assertThrown!TimeException(from!"msecs"(1000 * sign));
assert(FracSec.from!"msecs"(1 * sign) == FracSec(10_000 * sign));
assert(FracSec.from!"msecs"(999 * sign) == FracSec(9_990_000 * sign));
_assertThrown!TimeException(from!"usecs"(1_000_000 * sign));
assert(FracSec.from!"usecs"(1 * sign) == FracSec(10 * sign));
assert(FracSec.from!"usecs"(999 * sign) == FracSec(9990 * sign));
assert(FracSec.from!"usecs"(999_999 * sign) == FracSec(9999_990 * sign));
_assertThrown!TimeException(from!"hnsecs"(10_000_000 * sign));
assert(FracSec.from!"hnsecs"(1 * sign) == FracSec(1 * sign));
assert(FracSec.from!"hnsecs"(999 * sign) == FracSec(999 * sign));
assert(FracSec.from!"hnsecs"(999_999 * sign) == FracSec(999_999 * sign));
assert(FracSec.from!"hnsecs"(9_999_999 * sign) == FracSec(9_999_999 * sign));
assert(FracSec.from!"nsecs"(1 * sign) == FracSec(0));
assert(FracSec.from!"nsecs"(10 * sign) == FracSec(0));
assert(FracSec.from!"nsecs"(99 * sign) == FracSec(0));
assert(FracSec.from!"nsecs"(100 * sign) == FracSec(1 * sign));
assert(FracSec.from!"nsecs"(99_999 * sign) == FracSec(999 * sign));
assert(FracSec.from!"nsecs"(99_999_999 * sign) == FracSec(999_999 * sign));
assert(FracSec.from!"nsecs"(999_999_999 * sign) == FracSec(9_999_999 * sign));
}
}
/++
Returns the negation of this $(D FracSec).
+/
FracSec opUnary(string op)() const nothrow @nogc
if(op == "-")
{
return FracSec(-_hnsecs);
}
unittest
{
foreach(val; [-7, -5, 0, 5, 7])
{
foreach(F; _TypeTuple!(FracSec, const FracSec, immutable FracSec))
{
F fs = FracSec(val);
assert(-fs == FracSec(-val));
}
}
}
/++
The value of this $(D FracSec) as milliseconds.
+/
@property int msecs() const nothrow @nogc
{
return cast(int)convert!("hnsecs", "msecs")(_hnsecs);
}
unittest
{
foreach(F; _TypeTuple!(FracSec, const FracSec, immutable FracSec))
{
assert(FracSec(0).msecs == 0);
foreach(sign; [1, -1])
{
assert((cast(F)FracSec(1 * sign)).msecs == 0);
assert((cast(F)FracSec(999 * sign)).msecs == 0);
assert((cast(F)FracSec(999_999 * sign)).msecs == 99 * sign);
assert((cast(F)FracSec(9_999_999 * sign)).msecs == 999 * sign);
}
}
}
/++
The value of this $(D FracSec) as milliseconds.
Params:
milliseconds = The number of milliseconds passed the second.
Throws:
$(D TimeException) if the given value is not less than $(D 1) second
and greater than a $(D -1) seconds.
+/
@property void msecs(int milliseconds)
{
immutable hnsecs = cast(int)convert!("msecs", "hnsecs")(milliseconds);
_enforceValid(hnsecs);
_hnsecs = hnsecs;
}
unittest
{
static void test(int msecs, FracSec expected = FracSec.init, size_t line = __LINE__)
{
FracSec fs;
fs.msecs = msecs;
if(fs != expected)
throw new AssertError("unittest failure", __FILE__, line);
}
_assertThrown!TimeException(test(-1000));
_assertThrown!TimeException(test(1000));
test(0, FracSec(0));
foreach(sign; [1, -1])
{
test(1 * sign, FracSec(10_000 * sign));
test(999 * sign, FracSec(9_990_000 * sign));
}
foreach(F; _TypeTuple!(const FracSec, immutable FracSec))
{
F fs = FracSec(1234567);
static assert(!__traits(compiles, fs.msecs = 12), F.stringof);
}
}
/++
The value of this $(D FracSec) as microseconds.
+/
@property int usecs() const nothrow @nogc
{
return cast(int)convert!("hnsecs", "usecs")(_hnsecs);
}
unittest
{
foreach(F; _TypeTuple!(FracSec, const FracSec, immutable FracSec))
{
assert(FracSec(0).usecs == 0);
foreach(sign; [1, -1])
{
assert((cast(F)FracSec(1 * sign)).usecs == 0);
assert((cast(F)FracSec(999 * sign)).usecs == 99 * sign);
assert((cast(F)FracSec(999_999 * sign)).usecs == 99_999 * sign);
assert((cast(F)FracSec(9_999_999 * sign)).usecs == 999_999 * sign);
}
}
}
/++
The value of this $(D FracSec) as microseconds.
Params:
microseconds = The number of microseconds passed the second.
Throws:
$(D TimeException) if the given value is not less than $(D 1) second
and greater than a $(D -1) seconds.
+/
@property void usecs(int microseconds)
{
immutable hnsecs = cast(int)convert!("usecs", "hnsecs")(microseconds);
_enforceValid(hnsecs);
_hnsecs = hnsecs;
}
unittest
{
static void test(int usecs, FracSec expected = FracSec.init, size_t line = __LINE__)
{
FracSec fs;
fs.usecs = usecs;
if(fs != expected)
throw new AssertError("unittest failure", __FILE__, line);
}
_assertThrown!TimeException(test(-1_000_000));
_assertThrown!TimeException(test(1_000_000));
test(0, FracSec(0));
foreach(sign; [1, -1])
{
test(1 * sign, FracSec(10 * sign));
test(999 * sign, FracSec(9990 * sign));
test(999_999 * sign, FracSec(9_999_990 * sign));
}
foreach(F; _TypeTuple!(const FracSec, immutable FracSec))
{
F fs = FracSec(1234567);
static assert(!__traits(compiles, fs.usecs = 12), F.stringof);
}
}
/++
The value of this $(D FracSec) as hnsecs.
+/
@property int hnsecs() const nothrow @nogc
{
return _hnsecs;
}
unittest
{
foreach(F; _TypeTuple!(FracSec, const FracSec, immutable FracSec))
{
assert(FracSec(0).hnsecs == 0);
foreach(sign; [1, -1])
{
assert((cast(F)FracSec(1 * sign)).hnsecs == 1 * sign);
assert((cast(F)FracSec(999 * sign)).hnsecs == 999 * sign);
assert((cast(F)FracSec(999_999 * sign)).hnsecs == 999_999 * sign);
assert((cast(F)FracSec(9_999_999 * sign)).hnsecs == 9_999_999 * sign);
}
}
}
/++
The value of this $(D FracSec) as hnsecs.
Params:
hnsecs = The number of hnsecs passed the second.
Throws:
$(D TimeException) if the given value is not less than $(D 1) second
and greater than a $(D -1) seconds.
+/
@property void hnsecs(int hnsecs)
{
_enforceValid(hnsecs);
_hnsecs = hnsecs;
}
unittest
{
static void test(int hnsecs, FracSec expected = FracSec.init, size_t line = __LINE__)
{
FracSec fs;
fs.hnsecs = hnsecs;
if(fs != expected)
throw new AssertError("unittest failure", __FILE__, line);
}
_assertThrown!TimeException(test(-10_000_000));
_assertThrown!TimeException(test(10_000_000));
test(0, FracSec(0));
foreach(sign; [1, -1])
{
test(1 * sign, FracSec(1 * sign));
test(999 * sign, FracSec(999 * sign));
test(999_999 * sign, FracSec(999_999 * sign));
test(9_999_999 * sign, FracSec(9_999_999 * sign));
}
foreach(F; _TypeTuple!(const FracSec, immutable FracSec))
{
F fs = FracSec(1234567);
static assert(!__traits(compiles, fs.hnsecs = 12), F.stringof);
}
}
/++
The value of this $(D FracSec) as nsecs.
Note that this does not give you any greater precision
than getting the value of this $(D FracSec) as hnsecs.
+/
@property int nsecs() const nothrow @nogc
{
return cast(int)convert!("hnsecs", "nsecs")(_hnsecs);
}
unittest
{
foreach(F; _TypeTuple!(FracSec, const FracSec, immutable FracSec))
{
assert(FracSec(0).nsecs == 0);
foreach(sign; [1, -1])
{
assert((cast(F)FracSec(1 * sign)).nsecs == 100 * sign);
assert((cast(F)FracSec(999 * sign)).nsecs == 99_900 * sign);
assert((cast(F)FracSec(999_999 * sign)).nsecs == 99_999_900 * sign);
assert((cast(F)FracSec(9_999_999 * sign)).nsecs == 999_999_900 * sign);
}
}
}
/++
The value of this $(D FracSec) as nsecs.
Note that this does not give you any greater precision
than setting the value of this $(D FracSec) as hnsecs.
Params:
nsecs = The number of nsecs passed the second.
Throws:
$(D TimeException) if the given value is not less than $(D 1) second
and greater than a $(D -1) seconds.
+/
@property void nsecs(long nsecs)
{
immutable hnsecs = cast(int)convert!("nsecs", "hnsecs")(nsecs);
_enforceValid(hnsecs);
_hnsecs = hnsecs;
}
unittest
{
static void test(int nsecs, FracSec expected = FracSec.init, size_t line = __LINE__)
{
FracSec fs;
fs.nsecs = nsecs;
if(fs != expected)
throw new AssertError("unittest failure", __FILE__, line);
}
_assertThrown!TimeException(test(-1_000_000_000));
_assertThrown!TimeException(test(1_000_000_000));
test(0, FracSec(0));
foreach(sign; [1, -1])
{
test(1 * sign, FracSec(0));
test(10 * sign, FracSec(0));
test(100 * sign, FracSec(1 * sign));
test(999 * sign, FracSec(9 * sign));
test(999_999 * sign, FracSec(9999 * sign));
test(9_999_999 * sign, FracSec(99_999 * sign));
}
foreach(F; _TypeTuple!(const FracSec, immutable FracSec))
{
F fs = FracSec(1234567);
static assert(!__traits(compiles, fs.nsecs = 12), F.stringof);
}
}
/+
Converts this $(D TickDuration) to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString()
{
return _toStringImpl();
}
/++
Converts this $(D TickDuration) to a string.
+/
//Due to bug http://d.puremagic.com/issues/show_bug.cgi?id=3715 , we can't
//have versions of toString() with extra modifiers, so we define one version
//with modifiers and one without.
string toString() const nothrow
{
return _toStringImpl();
}
unittest
{
auto fs = FracSec(12);
const cfs = FracSec(12);
immutable ifs = FracSec(12);
assert(fs.toString() == "12 hnsecs");
assert(cfs.toString() == "12 hnsecs");
assert(ifs.toString() == "12 hnsecs");
}
private:
/+
Since we have two versions of $(D toString), we have $(D _toStringImpl)
so that they can share implementations.
+/
string _toStringImpl() const nothrow
{
long hnsecs = _hnsecs;
immutable milliseconds = splitUnitsFromHNSecs!"msecs"(hnsecs);
immutable microseconds = splitUnitsFromHNSecs!"usecs"(hnsecs);
if(hnsecs == 0)
{
if(microseconds == 0)
{
if(milliseconds == 0)
return "0 hnsecs";
else
{
if(milliseconds == 1)
return "1 ms";
else
{
auto r = signedToTempString(milliseconds, 10).idup;
r ~= " ms";
return r;
}
}
}
else
{
immutable fullMicroseconds = getUnitsFromHNSecs!"usecs"(_hnsecs);
if(fullMicroseconds == 1)
return "1 μs";
else
{
auto r = signedToTempString(fullMicroseconds, 10).idup;
r ~= " μs";
return r;
}
}
}
else
{
if(_hnsecs == 1)
return "1 hnsec";
else
{
auto r = signedToTempString(_hnsecs, 10).idup;
r ~= " hnsecs";
return r;
}
}
}
unittest
{
foreach(sign; [1 , -1])
{
immutable signStr = sign == 1 ? "" : "-";
assert(FracSec.from!"msecs"(0 * sign).toString() == "0 hnsecs");
assert(FracSec.from!"msecs"(1 * sign).toString() == signStr ~ "1 ms");
assert(FracSec.from!"msecs"(2 * sign).toString() == signStr ~ "2 ms");
assert(FracSec.from!"msecs"(100 * sign).toString() == signStr ~ "100 ms");
assert(FracSec.from!"msecs"(999 * sign).toString() == signStr ~ "999 ms");
assert(FracSec.from!"usecs"(0* sign).toString() == "0 hnsecs");
assert(FracSec.from!"usecs"(1* sign).toString() == signStr ~ "1 μs");
assert(FracSec.from!"usecs"(2* sign).toString() == signStr ~ "2 μs");
assert(FracSec.from!"usecs"(100* sign).toString() == signStr ~ "100 μs");
assert(FracSec.from!"usecs"(999* sign).toString() == signStr ~ "999 μs");
assert(FracSec.from!"usecs"(1000* sign).toString() == signStr ~ "1 ms");
assert(FracSec.from!"usecs"(2000* sign).toString() == signStr ~ "2 ms");
assert(FracSec.from!"usecs"(9999* sign).toString() == signStr ~ "9999 μs");
assert(FracSec.from!"usecs"(10_000* sign).toString() == signStr ~ "10 ms");
assert(FracSec.from!"usecs"(20_000* sign).toString() == signStr ~ "20 ms");
assert(FracSec.from!"usecs"(100_000* sign).toString() == signStr ~ "100 ms");
assert(FracSec.from!"usecs"(100_001* sign).toString() == signStr ~ "100001 μs");
assert(FracSec.from!"usecs"(999_999* sign).toString() == signStr ~ "999999 μs");
assert(FracSec.from!"hnsecs"(0* sign).toString() == "0 hnsecs");
assert(FracSec.from!"hnsecs"(1* sign).toString() == (sign == 1 ? "1 hnsec" : "-1 hnsecs"));
assert(FracSec.from!"hnsecs"(2* sign).toString() == signStr ~ "2 hnsecs");
assert(FracSec.from!"hnsecs"(100* sign).toString() == signStr ~ "10 μs");
assert(FracSec.from!"hnsecs"(999* sign).toString() == signStr ~ "999 hnsecs");
assert(FracSec.from!"hnsecs"(1000* sign).toString() == signStr ~ "100 μs");
assert(FracSec.from!"hnsecs"(2000* sign).toString() == signStr ~ "200 μs");
assert(FracSec.from!"hnsecs"(9999* sign).toString() == signStr ~ "9999 hnsecs");
assert(FracSec.from!"hnsecs"(10_000* sign).toString() == signStr ~ "1 ms");
assert(FracSec.from!"hnsecs"(20_000* sign).toString() == signStr ~ "2 ms");
assert(FracSec.from!"hnsecs"(100_000* sign).toString() == signStr ~ "10 ms");
assert(FracSec.from!"hnsecs"(100_001* sign).toString() == signStr ~ "100001 hnsecs");
assert(FracSec.from!"hnsecs"(200_000* sign).toString() == signStr ~ "20 ms");
assert(FracSec.from!"hnsecs"(999_999* sign).toString() == signStr ~ "999999 hnsecs");
assert(FracSec.from!"hnsecs"(1_000_001* sign).toString() == signStr ~ "1000001 hnsecs");
assert(FracSec.from!"hnsecs"(9_999_999* sign).toString() == signStr ~ "9999999 hnsecs");
}
}
/+
Returns whether the given number of hnsecs fits within the range of
$(D FracSec).
Params:
hnsecs = The number of hnsecs.
+/
static bool _valid(int hnsecs) nothrow @nogc
{
immutable second = convert!("seconds", "hnsecs")(1);
return hnsecs > -second && hnsecs < second;
}
/+
Throws:
$(D TimeException) if $(D valid(hnsecs)) is $(D false).
+/
static void _enforceValid(int hnsecs)
{
if(!_valid(hnsecs))
throw new TimeException("FracSec must be greater than equal to 0 and less than 1 second.");
}
/+
Params:
hnsecs = The number of hnsecs passed the second.
+/
this(int hnsecs) nothrow @nogc
{
_hnsecs = hnsecs;
}
invariant()
{
if(!_valid(_hnsecs))
throw new AssertError("Invariant Failure: hnsecs [" ~ signedToTempString(_hnsecs, 10).idup ~ "]", __FILE__, __LINE__);
}
int _hnsecs;
}
/++
Exception type used by core.time.
+/
class TimeException : Exception
{
/++
Params:
msg = The message for the exception.
file = The file where the exception occurred.
line = The line number where the exception occurred.
next = The previous exception in the chain of exceptions, if any.
+/
this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) @safe pure nothrow
{
super(msg, file, line, next);
}
/++
Params:
msg = The message for the exception.
next = The previous exception in the chain of exceptions.
file = The file where the exception occurred.
line = The line number where the exception occurred.
+/
this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__) @safe pure nothrow
{
super(msg, file, line, next);
}
}
unittest
{
{
auto e = new TimeException("hello");
assert(e.msg == "hello");
assert(e.file == __FILE__);
assert(e.line == __LINE__ - 3);
assert(e.next is null);
}
{
auto next = new Exception("foo");
auto e = new TimeException("goodbye", next);
assert(e.msg == "goodbye");
assert(e.file == __FILE__);
assert(e.line == __LINE__ - 3);
assert(e.next is next);
}
}
/++
Returns the absolute value of a duration.
+/
Duration abs(Duration duration) @safe pure nothrow @nogc
{
return Duration(_abs(duration._hnsecs));
}
/++ Ditto +/
TickDuration abs(TickDuration duration) @safe pure nothrow @nogc
{
return TickDuration(_abs(duration.length));
}
unittest
{
assert(abs(dur!"msecs"(5)) == dur!"msecs"(5));
assert(abs(dur!"msecs"(-5)) == dur!"msecs"(5));
assert(abs(TickDuration(17)) == TickDuration(17));
assert(abs(TickDuration(-17)) == TickDuration(17));
}
//==============================================================================
// Private Section.
//
// Much of this is a copy or simplified copy of what's in std.datetime.
//==============================================================================
private:
/+
Template to help with converting between time units.
+/
template hnsecsPer(string units)
if(units == "weeks" ||
units == "days" ||
units == "hours" ||
units == "minutes" ||
units == "seconds" ||
units == "msecs" ||
units == "usecs" ||
units == "hnsecs")
{
static if(units == "hnsecs")
enum hnsecsPer = 1L;
else static if(units == "usecs")
enum hnsecsPer = 10L;
else static if(units == "msecs")
enum hnsecsPer = 1000 * hnsecsPer!"usecs";
else static if(units == "seconds")
enum hnsecsPer = 1000 * hnsecsPer!"msecs";
else static if(units == "minutes")
enum hnsecsPer = 60 * hnsecsPer!"seconds";
else static if(units == "hours")
enum hnsecsPer = 60 * hnsecsPer!"minutes";
else static if(units == "days")
enum hnsecsPer = 24 * hnsecsPer!"hours";
else static if(units == "weeks")
enum hnsecsPer = 7 * hnsecsPer!"days";
}
/+
Splits out a particular unit from hnsecs and gives you the value for that
unit and the remaining hnsecs. It really shouldn't be used unless all units
larger than the given units have already been split out.
Params:
units = The units to split out.
hnsecs = The current total hnsecs. Upon returning, it is the hnsecs left
after splitting out the given units.
Returns:
The number of the given units from converting hnsecs to those units.
+/
long splitUnitsFromHNSecs(string units)(ref long hnsecs) @safe pure nothrow @nogc
if(units == "weeks" ||
units == "days" ||
units == "hours" ||
units == "minutes" ||
units == "seconds" ||
units == "msecs" ||
units == "usecs" ||
units == "hnsecs")
{
immutable value = convert!("hnsecs", units)(hnsecs);
hnsecs -= convert!(units, "hnsecs")(value);
return value;
}
///
unittest
{
auto hnsecs = 2595000000007L;
immutable days = splitUnitsFromHNSecs!"days"(hnsecs);
assert(days == 3);
assert(hnsecs == 3000000007);
immutable minutes = splitUnitsFromHNSecs!"minutes"(hnsecs);
assert(minutes == 5);
assert(hnsecs == 7);
}
/+
This function is used to split out the units without getting the remaining
hnsecs.
See_Also:
$(LREF splitUnitsFromHNSecs)
Params:
units = The units to split out.
hnsecs = The current total hnsecs.
Returns:
The split out value.
+/
long getUnitsFromHNSecs(string units)(long hnsecs) @safe pure nothrow @nogc
if(units == "weeks" ||
units == "days" ||
units == "hours" ||
units == "minutes" ||
units == "seconds" ||
units == "msecs" ||
units == "usecs" ||
units == "hnsecs")
{
return convert!("hnsecs", units)(hnsecs);
}
///
unittest
{
auto hnsecs = 2595000000007L;
immutable days = getUnitsFromHNSecs!"days"(hnsecs);
assert(days == 3);
assert(hnsecs == 2595000000007L);
}
/+
This function is used to split out the units without getting the units but
just the remaining hnsecs.
See_Also:
$(LREF splitUnitsFromHNSecs)
Params:
units = The units to split out.
hnsecs = The current total hnsecs.
Returns:
The remaining hnsecs.
+/
long removeUnitsFromHNSecs(string units)(long hnsecs) @safe pure nothrow @nogc
if(units == "weeks" ||
units == "days" ||
units == "hours" ||
units == "minutes" ||
units == "seconds" ||
units == "msecs" ||
units == "usecs" ||
units == "hnsecs")
{
immutable value = convert!("hnsecs", units)(hnsecs);
return hnsecs - convert!(units, "hnsecs")(value);
}
///
unittest
{
auto hnsecs = 2595000000007L;
auto returned = removeUnitsFromHNSecs!"days"(hnsecs);
assert(returned == 3000000007);
assert(hnsecs == 2595000000007L);
}
/+
Whether all of the given strings are among the accepted strings.
+/
bool allAreAcceptedUnits(acceptedUnits...)(string[] units...)
{
foreach(unit; units)
{
bool found = false;
foreach(acceptedUnit; acceptedUnits)
{
if(unit == acceptedUnit)
{
found = true;
break;
}
}
if(!found)
return false;
}
return true;
}
unittest
{
assert(allAreAcceptedUnits!("hours", "seconds")("seconds", "hours"));
assert(!allAreAcceptedUnits!("hours", "seconds")("minutes", "hours"));
assert(!allAreAcceptedUnits!("hours", "seconds")("seconds", "minutes"));
assert(allAreAcceptedUnits!("days", "hours", "minutes", "seconds", "msecs")("minutes"));
assert(!allAreAcceptedUnits!("days", "hours", "minutes", "seconds", "msecs")("usecs"));
assert(!allAreAcceptedUnits!("days", "hours", "minutes", "seconds", "msecs")("secs"));
}
/+
Whether the given time unit strings are arranged in order from largest to
smallest.
+/
bool unitsAreInDescendingOrder(string[] units...)
{
if(units.length <= 1)
return true;
immutable string[] timeStrings = ["nsecs", "hnsecs", "usecs", "msecs", "seconds",
"minutes", "hours", "days", "weeks", "months", "years"];
size_t currIndex = 42;
foreach(i, timeStr; timeStrings)
{
if(units[0] == timeStr)
{
currIndex = i;
break;
}
}
assert(currIndex != 42);
foreach(unit; units[1 .. $])
{
size_t nextIndex = 42;
foreach(i, timeStr; timeStrings)
{
if(unit == timeStr)
{
nextIndex = i;
break;
}
}
assert(nextIndex != 42);
if(currIndex <= nextIndex)
return false;
currIndex = nextIndex;
}
return true;
}
unittest
{
assert(unitsAreInDescendingOrder("years", "months", "weeks", "days", "hours", "minutes",
"seconds", "msecs", "usecs", "hnsecs", "nsecs"));
assert(unitsAreInDescendingOrder("weeks", "hours", "msecs"));
assert(unitsAreInDescendingOrder("days", "hours", "minutes"));
assert(unitsAreInDescendingOrder("hnsecs"));
assert(!unitsAreInDescendingOrder("days", "hours", "hours"));
assert(!unitsAreInDescendingOrder("days", "hours", "days"));
}
/+
The time units which are one step larger than the given units.
+/
template nextLargerTimeUnits(string units)
if(units == "days" ||
units == "hours" ||
units == "minutes" ||
units == "seconds" ||
units == "msecs" ||
units == "usecs" ||
units == "hnsecs" ||
units == "nsecs")
{
static if(units == "days")
enum nextLargerTimeUnits = "weeks";
else static if(units == "hours")
enum nextLargerTimeUnits = "days";
else static if(units == "minutes")
enum nextLargerTimeUnits = "hours";
else static if(units == "seconds")
enum nextLargerTimeUnits = "minutes";
else static if(units == "msecs")
enum nextLargerTimeUnits = "seconds";
else static if(units == "usecs")
enum nextLargerTimeUnits = "msecs";
else static if(units == "hnsecs")
enum nextLargerTimeUnits = "usecs";
else static if(units == "nsecs")
enum nextLargerTimeUnits = "hnsecs";
else
static assert(0, "Broken template constraint");
}
///
unittest
{
assert(nextLargerTimeUnits!"minutes" == "hours");
assert(nextLargerTimeUnits!"hnsecs" == "usecs");
}
unittest
{
assert(nextLargerTimeUnits!"nsecs" == "hnsecs");
assert(nextLargerTimeUnits!"hnsecs" == "usecs");
assert(nextLargerTimeUnits!"usecs" == "msecs");
assert(nextLargerTimeUnits!"msecs" == "seconds");
assert(nextLargerTimeUnits!"seconds" == "minutes");
assert(nextLargerTimeUnits!"minutes" == "hours");
assert(nextLargerTimeUnits!"hours" == "days");
assert(nextLargerTimeUnits!"days" == "weeks");
static assert(!__traits(compiles, nextLargerTimeUnits!"weeks"));
static assert(!__traits(compiles, nextLargerTimeUnits!"months"));
static assert(!__traits(compiles, nextLargerTimeUnits!"years"));
}
version(Darwin)
long machTicksPerSecond()
{
// Be optimistic that ticksPerSecond (1e9*denom/numer) is integral. So far
// so good on Darwin based platforms OS X, iOS.
import core.internal.abort : abort;
mach_timebase_info_data_t info;
if(mach_timebase_info(&info) != 0)
abort("Failed in mach_timebase_info().");
long scaledDenom = 1_000_000_000L * info.denom;
if(scaledDenom % info.numer != 0)
abort("Non integral ticksPerSecond from mach_timebase_info.");
return scaledDenom / info.numer;
}
/+
Local version of abs, since std.math.abs is in Phobos, not druntime.
+/
long _abs(long val) @safe pure nothrow @nogc
{
return val >= 0 ? val : -val;
}
double _abs(double val) @safe pure nothrow @nogc
{
return val >= 0.0 ? val : -val;
}
version(unittest)
string doubleToString(double value) @safe pure nothrow
{
string result;
if(value < 0 && cast(long)value == 0)
result = "-0";
else
result = signedToTempString(cast(long)value, 10).idup;
result ~= '.';
result ~= unsignedToTempString(cast(ulong)(_abs((value - cast(long)value) * 1_000_000) + .5), 10);
while (result[$-1] == '0')
result = result[0 .. $-1];
return result;
}
unittest
{
auto a = 1.337;
auto aStr = doubleToString(a);
assert(aStr == "1.337", aStr);
a = 0.337;
aStr = doubleToString(a);
assert(aStr == "0.337", aStr);
a = -0.337;
aStr = doubleToString(a);
assert(aStr == "-0.337", aStr);
}
version(unittest) const(char)* numToStringz()(long value) @trusted pure nothrow
{
return (signedToTempString(value, 10) ~ "\0").ptr;
}
/+ A copy of std.typecons.TypeTuple. +/
template _TypeTuple(TList...)
{
alias TList _TypeTuple;
}
/+ An adjusted copy of std.exception.assertThrown. +/
version(unittest) void _assertThrown(T : Throwable = Exception, E)
(lazy E expression,
string msg = null,
string file = __FILE__,
size_t line = __LINE__)
{
bool thrown = false;
try
expression();
catch(T t)
thrown = true;
if(!thrown)
{
immutable tail = msg.length == 0 ? "." : ": " ~ msg;
throw new AssertError("assertThrown() failed: No " ~ T.stringof ~ " was thrown" ~ tail, file, line);
}
}
unittest
{
void throwEx(Throwable t)
{
throw t;
}
void nothrowEx()
{}
try
_assertThrown!Exception(throwEx(new Exception("It's an Exception")));
catch(AssertError)
assert(0);
try
_assertThrown!Exception(throwEx(new Exception("It's an Exception")), "It's a message");
catch(AssertError)
assert(0);
try
_assertThrown!AssertError(throwEx(new AssertError("It's an AssertError", __FILE__, __LINE__)));
catch(AssertError)
assert(0);
try
_assertThrown!AssertError(throwEx(new AssertError("It's an AssertError", __FILE__, __LINE__)), "It's a message");
catch(AssertError)
assert(0);
{
bool thrown = false;
try
_assertThrown!Exception(nothrowEx());
catch(AssertError)
thrown = true;
assert(thrown);
}
{
bool thrown = false;
try
_assertThrown!Exception(nothrowEx(), "It's a message");
catch(AssertError)
thrown = true;
assert(thrown);
}
{
bool thrown = false;
try
_assertThrown!AssertError(nothrowEx());
catch(AssertError)
thrown = true;
assert(thrown);
}
{
bool thrown = false;
try
_assertThrown!AssertError(nothrowEx(), "It's a message");
catch(AssertError)
thrown = true;
assert(thrown);
}
}
version(unittest) void assertApprox(D, E)(D actual,
E lower,
E upper,
string msg = "unittest failure",
size_t line = __LINE__)
if(is(D : const Duration) && is(E : const Duration))
{
if(actual < lower)
throw new AssertError(msg ~ ": lower: " ~ actual.toString(), __FILE__, line);
if(actual > upper)
throw new AssertError(msg ~ ": upper: " ~ actual.toString(), __FILE__, line);
}
version(unittest) void assertApprox(D, E)(D actual,
E lower,
E upper,
string msg = "unittest failure",
size_t line = __LINE__)
if(is(D : const TickDuration) && is(E : const TickDuration))
{
if(actual.length < lower.length || actual.length > upper.length)
{
throw new AssertError(msg ~ (": [" ~ signedToTempString(lower.length, 10) ~ "] [" ~
signedToTempString(actual.length, 10) ~ "] [" ~
signedToTempString(upper.length, 10) ~ "]").idup,
__FILE__, line);
}
}
version(unittest) void assertApprox(MT)(MT actual,
MT lower,
MT upper,
string msg = "unittest failure",
size_t line = __LINE__)
if(is(MT == MonoTimeImpl!type, ClockType type))
{
assertApprox(actual._ticks, lower._ticks, upper._ticks, msg, line);
}
version(unittest) void assertApprox()(long actual,
long lower,
long upper,
string msg = "unittest failure",
size_t line = __LINE__)
{
if(actual < lower)
throw new AssertError(msg ~ ": lower: " ~ signedToTempString(actual, 10).idup, __FILE__, line);
if(actual > upper)
throw new AssertError(msg ~ ": upper: " ~ signedToTempString(actual, 10).idup, __FILE__, line);
}
| D |
module imports.test11931d;
import std.array;
import std.algorithm;
struct ConnectionPoint
{
void disconnect()
{
if(_f)
{
_f();
_f = null;
}
}
private void delegate() _f;
}
struct Signal(T, A...)
{
ConnectionPoint add(D f)
{
auto rf = { _arr = _arr.filter!(a => a != f).array; };
return ConnectionPoint();
}
private:
alias D = T delegate(A);
D[] _arr;
}
| D |
/++
$(H2 Constant Interpolation)
See_also: $(REF_ALTTEXT $(TT interp1), interp1, mir, interpolate)
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Copyright: Copyright © 2017, Kaleidic Associates Advisory Limited
Authors: Ilya Yaroshenko
Macros:
SUBREF = $(REF_ALTTEXT $(TT $2), $2, mir, interpolate, $1)$(NBSP)
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
+/
module mir.interpolate.constant;
@optmath:
///
version(mir_test)
@safe pure unittest
{
import mir.ndslice;
import std.math: approxEqual;
immutable x = [0, 1, 2, 3];
immutable y = [10, 20, 30, 40];
auto interpolant = constant!int(x.sliced, y.sliced);
assert(interpolant(-1) == 10);
assert(interpolant(0) == 10);
assert(interpolant(0.5) == 10);
assert(interpolant(1) == 20);
assert(interpolant(3) == 40);
assert(interpolant(4) == 40);
}
import std.traits;
import mir.primitives;
import mir.ndslice.slice;
import mir.internal.utility;
import mir.math.common: optmath;
public import mir.interpolate: atInterval;
import mir.interpolate;
/++
Constructs multivariate constant interpolant with nodes on rectilinear grid.
Params:
grid = `x` values for interpolant
values = `f(x)` values for interpolant
Constraints:
`grid`, `values` must have the same length >= 1
Returns: $(LREF Constant)
+/
template constant(T, size_t N = 1, FirstGridIterator = immutable(T)*, NextGridIterators = Repeat!(N - 1, FirstGridIterator))
if (is(T == Unqual!T) && N <= 6)
{
static if (N > 1) pragma(msg, "Warning: multivariate constant interpolant was not tested.");
import std.meta: AliasSeq;
@optmath:
private alias GridIterators = AliasSeq!(FirstGridIterator, NextGridIterators);
private alias GridVectors = Constant!(T, N, GridIterators).GridVectors;
/++
Params:
grid = immutable `x` values for interpolant
values = `f(x)` values for interpolant
Constraints:
`grid` and `values` must have the same length >= 3
Returns: $(LREF Spline)
+/
Constant!(T, N, GridIterators) constant(yIterator, SliceKind ykind)(
GridVectors grid,
scope Slice!(yIterator, 1, ykind) values
) pure @trusted
{
import std.algorithm.mutation: move;
auto ret = typeof(return)(grid);
ret._data[] = values;
return ret.move;
}
}
/++
Multivariate constant interpolant with nodes on rectilinear grid.
+/
struct Constant(F, size_t N = 1, FirstGridIterator = immutable(F)*, NextGridIterators = Repeat!(N - 1, FirstGridIterator))
if (N && N <= 6 && NextGridIterators.length == N - 1)
{
import mir.rcarray;
import std.meta: AliasSeq, staticMap;
package alias GridIterators = AliasSeq!(FirstGridIterator, NextGridIterators);
package alias GridVectors = staticMap!(GridVector, GridIterators);
@optmath:
/// Aligned buffer allocated with `mir.internal.memory`. $(RED For internal use.)
mir_slice!(mir_rci!F, N) _data;
/// Grid iterators. $(RED For internal use.)
GridIterators _grid;
import mir.utility: min, max;
package enum alignment = min(64u, F.sizeof).max(size_t.sizeof);
/++
+/
this(GridVectors grid) @safe @nogc
{
size_t length = 1;
size_t[N] shape;
enum msg = "constant interpolant: minimal allowed length for the grid equals 1.";
version(D_Exceptions)
static immutable exc = new Exception(msg);
foreach(i, ref x; grid)
{
if (x.length < 1)
{
version(D_Exceptions)
throw exc;
else
assert(0, msg);
}
length *= shape[i] = x.length;
}
auto rca = mir_rcarray!F(length, alignment);
this._data = rca.asSlice.sliced(shape);
this._grid = staticMap!(iter, grid);
}
@trusted:
///
GridVectors[dimension] grid(size_t dimension = 0)() scope return const @property
if (dimension < N)
{
return _grid[dimension].sliced(_data._lengths[dimension]);
}
/++
Returns: intervals count.
+/
size_t intervalCount(size_t dimension = 0)() scope const @property
{
assert(_data._lengths[dimension] > 0);
return _data._lengths[dimension] - 0;
}
///
size_t[N] gridShape()() scope const @property
{
return _data.shape;
}
///
enum uint derivativeOrder = 0;
///
template opCall(uint derivative = 0)
if (derivative <= derivativeOrder)
{
@trusted:
/++
`(x)` and `[x]` operators.
Complexity:
`O(log(grid.length))`
+/
auto opCall(X...)(in X xs) scope const
if (X.length == N)
// @FUTURE@
// X.length == N || derivative == 0 && X.length && X.length <= N
{
size_t[N] indexes = void;
foreach(i; Iota!N)
{
static if (isInterval!(typeof(xs[i])))
indexes[i] = xs[i][1];
else
indexes[i] = _data._lengths[i] > 1 ? this.findInterval!i(xs[i]) : 0;
}
return _data[indexes];
}
}
}
| D |
# FIXED
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/common/cc26xx/onboard.c
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/inc/bcomdef.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/osal/src/inc/comdef.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_types.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/../_common/cc26xx/_hal_types.h
TOOLS/onboard.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdint.h
TOOLS/onboard.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdbool.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/inc/hal_defs.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/common/cc26xx/onboard.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/sys_ctrl.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_types.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/../inc/hw_chip_def.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_memmap.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_ints.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_sysctl.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_prcm.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_nvic.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aon_wuc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aux_wuc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aon_ioc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_ddi_0_osc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_rfc_pwr.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_adi_3_refsys.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aon_sysctl.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aon_rtc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_fcfg1.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/interrupt.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/debug.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/cpu.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_cpu_scs.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../driverlib/rom.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/pwr_ctrl.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_adi_2_refsys.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/osc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_ddi.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/ddi.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aux_smph.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/prcm.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/aon_ioc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/adi.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_uart.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_adi.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/aux_wuc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/aon_wuc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/vims.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_vims.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_mcu.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_types.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/inc/hw_gpio.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/systick.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/uart.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/gpio.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/flash.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_flash.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/ioc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_ioc.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/icall/src/inc/icall.h
TOOLS/onboard.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdlib.h
TOOLS/onboard.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/linkage.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/inc/hal_assert.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_types.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/inc/hal_sleep.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/osal/src/inc/osal.h
TOOLS/onboard.obj: C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/limits.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/osal/src/inc/osal_memory.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/osal/src/inc/osal_timers.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_board_cfg.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_types.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/inc/hal_key.h
TOOLS/onboard.obj: C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/inc/hal_board.h
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/common/cc26xx/onboard.c:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/inc/bcomdef.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/osal/src/inc/comdef.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/../_common/cc26xx/_hal_types.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdint.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdbool.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/inc/hal_defs.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/common/cc26xx/onboard.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/sys_ctrl.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_types.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/../inc/hw_chip_def.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_memmap.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_ints.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_sysctl.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_prcm.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_nvic.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aon_wuc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aux_wuc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aon_ioc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_ddi_0_osc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_rfc_pwr.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_adi_3_refsys.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aon_sysctl.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aon_rtc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_fcfg1.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/interrupt.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/debug.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/cpu.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_cpu_scs.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../driverlib/rom.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/pwr_ctrl.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_adi_2_refsys.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/osc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_ddi.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/ddi.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_aux_smph.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/prcm.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/aon_ioc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/adi.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_uart.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_adi.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/aux_wuc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/aon_wuc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/vims.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_vims.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_mcu.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/inc/hw_gpio.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/systick.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/uart.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/gpio.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/flash.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_flash.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/ioc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/devices/cc26x0r2/driverlib/../inc/hw_ioc.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/icall/src/inc/icall.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/stdlib.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/linkage.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/inc/hal_assert.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/inc/hal_sleep.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/osal/src/inc/osal.h:
C:/ti/ccsv7/tools/compiler/ti-cgt-arm_16.9.6.LTS/include/limits.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/osal/src/inc/osal_memory.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/osal/src/inc/osal_timers.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_board_cfg.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/target/_common/hal_types.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/inc/hal_key.h:
C:/ti/simplelink_cc2640r2_sdk_1_50_00_58/source/ti/blestack/hal/src/inc/hal_board.h:
| D |
////////////////////////////////////////////////////////
// B_LastWarningVatras
////////////////////////////////////////////////////////
func void B_LastWarningVatras ()
{
AI_Output (self, other, "DIA_Addon_Vatras_LastWarning_ADD_05_00"); //Co jsi to udęlal mizero?
AI_Output (self, other, "DIA_Addon_Vatras_LastWarning_ADD_05_01"); //My z âádu Vody jsme tę opakovanę varovali pâed oddáváním se zlu.
AI_Output (self, other, "DIA_Addon_Vatras_LastWarning_ADD_05_02"); //K mým uším se doneslo, že jsi opustil cestu trvalé rovnováhy.
AI_Output (self, other, "DIA_Addon_Vatras_LastWarning_ADD_05_03"); //Vraždící a plundrující procházel jsi krajem, obtęžkán pocitem viny z mnoha zločinů.
AI_Output (self, other, "DIA_Addon_Vatras_LastWarning_ADD_05_04"); //Bezpočet nevinných lidí bylo zavraždęno TVOU rukou.
AI_Output (self, other, "DIA_Addon_Vatras_LastWarning_ADD_05_05"); //Teë jsi spojen s temnými silami.
};
func void B_VatrasPissedOff ()
{
AI_Output (self, other, "DIA_Addon_Vatras_PissedOffPerm_Add_05_00"); //Od teë již nemůžeš počítat s mou podporou.
AI_Output (self, other, "DIA_Addon_Vatras_PissedOffPerm_Add_05_01"); //Odejdi. Jsi pro mę vyvrhel.
if (Vatras_IsOnBoard == LOG_SUCCESS)
{
crewmember_Count = (Crewmember_Count -1);
};
Vatras_IsOnBoard = LOG_FAILED; //Log_Obsolete ->der Sc kann ihn wiederholen, Log_Failed ->hat die Schnauze voll, kommt nicht mehr mit!
self.flags = 0;
VatrasPissedOffForever = TRUE;
AI_StopProcessInfos (self);
Npc_ExchangeRoutine (self,"PRAY");
};
| D |
// Compiler implementation of the D programming language
// Copyright (c) 1999-2015 by Digital Mars
// All Rights Reserved
// written by Walter Bright
// http://www.digitalmars.com
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
module ddmd.statement;
import core.stdc.stdarg;
import core.stdc.stdio;
import ddmd.aggregate;
import ddmd.arrayop;
import ddmd.arraytypes;
import ddmd.attrib;
import ddmd.backend;
import ddmd.canthrow;
import ddmd.clone;
import ddmd.cond;
import ddmd.ctfeexpr;
import ddmd.dcast;
import ddmd.dclass;
import ddmd.declaration;
import ddmd.denum;
import ddmd.dimport;
import ddmd.dinterpret;
import ddmd.dscope;
import ddmd.dsymbol;
import ddmd.dtemplate;
import ddmd.errors;
import ddmd.escape;
import ddmd.expression;
import ddmd.func;
import ddmd.globals;
import ddmd.hdrgen;
import ddmd.id;
import ddmd.identifier;
import ddmd.init;
import ddmd.inline;
import ddmd.intrange;
import ddmd.mtype;
import ddmd.mtype;
import ddmd.nogc;
import ddmd.opover;
import ddmd.parse;
import ddmd.root.outbuffer;
import ddmd.root.rootobject;
import ddmd.sapply;
import ddmd.sideeffect;
import ddmd.staticassert;
import ddmd.target;
import ddmd.tokens;
import ddmd.visitor;
extern extern (C++) Statement asmSemantic(AsmStatement s, Scope* sc);
extern (C++) Identifier fixupLabelName(Scope* sc, Identifier ident)
{
uint flags = (sc.flags & SCOPEcontract);
if (flags && flags != SCOPEinvariant && !(ident.string[0] == '_' && ident.string[1] == '_'))
{
/* CTFE requires FuncDeclaration::labtab for the interpretation.
* So fixing the label name inside in/out contracts is necessary
* for the uniqueness in labtab.
*/
const(char)* prefix = flags == SCOPErequire ? "__in_" : "__out_";
OutBuffer buf;
buf.printf("%s%s", prefix, ident.toChars());
const(char)* name = buf.extractString();
ident = Identifier.idPool(name);
}
return ident;
}
extern (C++) LabelStatement checkLabeledLoop(Scope* sc, Statement statement)
{
if (sc.slabel && sc.slabel.statement == statement)
{
return sc.slabel;
}
return null;
}
enum BE : int
{
BEnone = 0,
BEfallthru = 1,
BEthrow = 2,
BEreturn = 4,
BEgoto = 8,
BEhalt = 0x10,
BEbreak = 0x20,
BEcontinue = 0x40,
BEerrthrow = 0x80,
BEany = (BEfallthru | BEthrow | BEreturn | BEgoto | BEhalt),
}
alias BEnone = BE.BEnone;
alias BEfallthru = BE.BEfallthru;
alias BEthrow = BE.BEthrow;
alias BEreturn = BE.BEreturn;
alias BEgoto = BE.BEgoto;
alias BEhalt = BE.BEhalt;
alias BEbreak = BE.BEbreak;
alias BEcontinue = BE.BEcontinue;
alias BEerrthrow = BE.BEerrthrow;
alias BEany = BE.BEany;
/***********************************************************
*/
extern (C++) class Statement : RootObject
{
public:
Loc loc;
final extern (D) this(Loc loc)
{
this.loc = loc;
// If this is an in{} contract scope statement (skip for determining
// inlineStatus of a function body for header content)
}
Statement syntaxCopy()
{
assert(0);
}
override final void print()
{
fprintf(stderr, "%s\n", toChars());
fflush(stderr);
}
override final char* toChars()
{
HdrGenState hgs;
OutBuffer buf;
.toCBuffer(this, &buf, &hgs);
return buf.extractString();
}
final void error(const(char)* format, ...)
{
va_list ap;
va_start(ap, format);
.verror(loc, format, ap);
va_end(ap);
}
final void warning(const(char)* format, ...)
{
va_list ap;
va_start(ap, format);
.vwarning(loc, format, ap);
va_end(ap);
}
final void deprecation(const(char)* format, ...)
{
va_list ap;
va_start(ap, format);
.vdeprecation(loc, format, ap);
va_end(ap);
}
Statement semantic(Scope* sc)
{
return this;
}
// Same as semanticNoScope(), but do create a new scope
final Statement semanticScope(Scope* sc, Statement sbreak, Statement scontinue)
{
Scope* scd = sc.push();
if (sbreak)
scd.sbreak = sbreak;
if (scontinue)
scd.scontinue = scontinue;
Statement s = semanticNoScope(scd);
scd.pop();
return s;
}
final Statement semanticNoScope(Scope* sc)
{
//printf("Statement::semanticNoScope() %s\n", toChars());
Statement s = this;
if (!s.isCompoundStatement() && !s.isScopeStatement())
{
s = new CompoundStatement(loc, this); // so scopeCode() gets called
}
s = s.semantic(sc);
return s;
}
Statement getRelatedLabeled()
{
return this;
}
bool hasBreak()
{
//printf("Statement::hasBreak()\n");
return false;
}
bool hasContinue()
{
return false;
}
/* ============================================== */
// true if statement uses exception handling
final bool usesEH()
{
extern (C++) final class UsesEH : StoppableVisitor
{
alias visit = super.visit;
public:
override void visit(Statement s)
{
}
override void visit(TryCatchStatement s)
{
stop = true;
}
override void visit(TryFinallyStatement s)
{
stop = true;
}
override void visit(OnScopeStatement s)
{
stop = true;
}
override void visit(SynchronizedStatement s)
{
stop = true;
}
}
scope UsesEH ueh = new UsesEH();
return walkPostorder(this, ueh);
}
/* ============================================== */
/* Only valid after semantic analysis
* If 'mustNotThrow' is true, generate an error if it throws
*/
final int blockExit(FuncDeclaration func, bool mustNotThrow)
{
extern (C++) final class BlockExit : Visitor
{
alias visit = super.visit;
public:
FuncDeclaration func;
bool mustNotThrow;
int result;
extern (D) this(FuncDeclaration func, bool mustNotThrow)
{
this.func = func;
this.mustNotThrow = mustNotThrow;
result = BEnone;
}
override void visit(Statement s)
{
printf("Statement::blockExit(%p)\n", s);
printf("%s\n", s.toChars());
assert(0);
}
override void visit(ErrorStatement s)
{
result = BEany;
}
override void visit(ExpStatement s)
{
result = BEfallthru;
if (s.exp)
{
if (s.exp.op == TOKhalt)
{
result = BEhalt;
return;
}
if (s.exp.op == TOKassert)
{
AssertExp a = cast(AssertExp)s.exp;
if (a.e1.isBool(false)) // if it's an assert(0)
{
result = BEhalt;
return;
}
}
if (canThrow(s.exp, func, mustNotThrow))
result |= BEthrow;
}
}
override void visit(CompileStatement s)
{
assert(global.errors);
result = BEfallthru;
}
override void visit(CompoundStatement cs)
{
//printf("CompoundStatement::blockExit(%p) %d\n", cs, cs->statements->dim);
result = BEfallthru;
Statement slast = null;
foreach (s; *cs.statements)
{
if (s)
{
//printf("result = x%x\n", result);
//printf("s: %s\n", s->toChars());
if (global.params.warnings && result & BEfallthru && slast)
{
slast = slast.last();
if (slast && (slast.isCaseStatement() || slast.isDefaultStatement()) && (s.isCaseStatement() || s.isDefaultStatement()))
{
// Allow if last case/default was empty
CaseStatement sc = slast.isCaseStatement();
DefaultStatement sd = slast.isDefaultStatement();
if (sc && (!sc.statement.hasCode() || sc.statement.isCaseStatement() || sc.statement.isErrorStatement()))
{
}
else if (sd && (!sd.statement.hasCode() || sd.statement.isCaseStatement() || sd.statement.isErrorStatement()))
{
}
else
{
const(char)* gototype = s.isCaseStatement() ? "case" : "default";
s.warning("switch case fallthrough - use 'goto %s;' if intended", gototype);
}
}
}
if (!(result & BEfallthru) && !s.comeFrom())
{
if (s.blockExit(func, mustNotThrow) != BEhalt && s.hasCode())
s.warning("statement is not reachable");
}
else
{
result &= ~BEfallthru;
result |= s.blockExit(func, mustNotThrow);
}
slast = s;
}
}
}
override void visit(UnrolledLoopStatement uls)
{
result = BEfallthru;
foreach (s; *uls.statements)
{
if (s)
{
int r = s.blockExit(func, mustNotThrow);
result |= r & ~(BEbreak | BEcontinue | BEfallthru);
if ((r & (BEfallthru | BEcontinue | BEbreak)) == 0)
result &= ~BEfallthru;
}
}
}
override void visit(ScopeStatement s)
{
//printf("ScopeStatement::blockExit(%p)\n", s->statement);
result = s.statement ? s.statement.blockExit(func, mustNotThrow) : BEfallthru;
}
override void visit(WhileStatement s)
{
assert(global.errors);
result = BEfallthru;
}
override void visit(DoStatement s)
{
if (s._body)
{
result = s._body.blockExit(func, mustNotThrow);
if (result == BEbreak)
{
result = BEfallthru;
return;
}
if (result & BEcontinue)
result |= BEfallthru;
}
else
result = BEfallthru;
if (result & BEfallthru)
{
if (canThrow(s.condition, func, mustNotThrow))
result |= BEthrow;
if (!(result & BEbreak) && s.condition.isBool(true))
result &= ~BEfallthru;
}
result &= ~(BEbreak | BEcontinue);
}
override void visit(ForStatement s)
{
result = BEfallthru;
if (s._init)
{
result = s._init.blockExit(func, mustNotThrow);
if (!(result & BEfallthru))
return;
}
if (s.condition)
{
if (canThrow(s.condition, func, mustNotThrow))
result |= BEthrow;
if (s.condition.isBool(true))
result &= ~BEfallthru;
else if (s.condition.isBool(false))
return;
}
else
result &= ~BEfallthru; // the body must do the exiting
if (s._body)
{
int r = s._body.blockExit(func, mustNotThrow);
if (r & (BEbreak | BEgoto))
result |= BEfallthru;
result |= r & ~(BEfallthru | BEbreak | BEcontinue);
}
if (s.increment && canThrow(s.increment, func, mustNotThrow))
result |= BEthrow;
}
override void visit(ForeachStatement s)
{
result = BEfallthru;
if (canThrow(s.aggr, func, mustNotThrow))
result |= BEthrow;
if (s._body)
result |= s._body.blockExit(func, mustNotThrow) & ~(BEbreak | BEcontinue);
}
override void visit(ForeachRangeStatement s)
{
assert(global.errors);
result = BEfallthru;
}
override void visit(IfStatement s)
{
//printf("IfStatement::blockExit(%p)\n", s);
result = BEnone;
if (canThrow(s.condition, func, mustNotThrow))
result |= BEthrow;
if (s.condition.isBool(true))
{
if (s.ifbody)
result |= s.ifbody.blockExit(func, mustNotThrow);
else
result |= BEfallthru;
}
else if (s.condition.isBool(false))
{
if (s.elsebody)
result |= s.elsebody.blockExit(func, mustNotThrow);
else
result |= BEfallthru;
}
else
{
if (s.ifbody)
result |= s.ifbody.blockExit(func, mustNotThrow);
else
result |= BEfallthru;
if (s.elsebody)
result |= s.elsebody.blockExit(func, mustNotThrow);
else
result |= BEfallthru;
}
//printf("IfStatement::blockExit(%p) = x%x\n", s, result);
}
override void visit(ConditionalStatement s)
{
result = s.ifbody.blockExit(func, mustNotThrow);
if (s.elsebody)
result |= s.elsebody.blockExit(func, mustNotThrow);
}
override void visit(PragmaStatement s)
{
result = BEfallthru;
}
override void visit(StaticAssertStatement s)
{
result = BEfallthru;
}
override void visit(SwitchStatement s)
{
result = BEnone;
if (canThrow(s.condition, func, mustNotThrow))
result |= BEthrow;
if (s._body)
{
result |= s._body.blockExit(func, mustNotThrow);
if (result & BEbreak)
{
result |= BEfallthru;
result &= ~BEbreak;
}
}
else
result |= BEfallthru;
}
override void visit(CaseStatement s)
{
result = s.statement.blockExit(func, mustNotThrow);
}
override void visit(DefaultStatement s)
{
result = s.statement.blockExit(func, mustNotThrow);
}
override void visit(GotoDefaultStatement s)
{
result = BEgoto;
}
override void visit(GotoCaseStatement s)
{
result = BEgoto;
}
override void visit(SwitchErrorStatement s)
{
// Switch errors are non-recoverable
result = BEhalt;
}
override void visit(ReturnStatement s)
{
result = BEreturn;
if (s.exp && canThrow(s.exp, func, mustNotThrow))
result |= BEthrow;
}
override void visit(BreakStatement s)
{
//printf("BreakStatement::blockExit(%p) = x%x\n", s, s->ident ? BEgoto : BEbreak);
result = s.ident ? BEgoto : BEbreak;
}
override void visit(ContinueStatement s)
{
result = s.ident ? BEgoto : BEcontinue;
}
override void visit(SynchronizedStatement s)
{
result = s._body ? s._body.blockExit(func, mustNotThrow) : BEfallthru;
}
override void visit(WithStatement s)
{
result = BEnone;
if (canThrow(s.exp, func, mustNotThrow))
result = BEthrow;
if (s._body)
result |= s._body.blockExit(func, mustNotThrow);
else
result |= BEfallthru;
}
override void visit(TryCatchStatement s)
{
assert(s._body);
result = s._body.blockExit(func, false);
int catchresult = 0;
foreach (c; *s.catches)
{
if (c.type == Type.terror)
continue;
int cresult;
if (c.handler)
cresult = c.handler.blockExit(func, mustNotThrow);
else
cresult = BEfallthru;
/* If we're catching Object, then there is no throwing
*/
Identifier id = c.type.toBasetype().isClassHandle().ident;
if (c.internalCatch && (cresult & BEfallthru))
{
// Bugzilla 11542: leave blockExit flags of the body
cresult &= ~BEfallthru;
}
else if (id == Id.Object || id == Id.Throwable)
{
result &= ~(BEthrow | BEerrthrow);
}
else if (id == Id.Exception)
{
result &= ~BEthrow;
}
catchresult |= cresult;
}
if (mustNotThrow && (result & BEthrow))
{
// now explain why this is nothrow
s._body.blockExit(func, mustNotThrow);
}
result |= catchresult;
}
override void visit(TryFinallyStatement s)
{
result = BEfallthru;
if (s._body)
result = s._body.blockExit(func, false);
// check finally body as well, it may throw (bug #4082)
int finalresult = BEfallthru;
if (s.finalbody)
finalresult = s.finalbody.blockExit(func, false);
// If either body or finalbody halts
if (result == BEhalt)
finalresult = BEnone;
if (finalresult == BEhalt)
result = BEnone;
if (mustNotThrow)
{
// now explain why this is nothrow
if (s._body && (result & BEthrow))
s._body.blockExit(func, mustNotThrow);
if (s.finalbody && (finalresult & BEthrow))
s.finalbody.blockExit(func, mustNotThrow);
}
version (none)
{
// Bugzilla 13201: Mask to prevent spurious warnings for
// destructor call, exit of synchronized statement, etc.
if (result == BEhalt && finalresult != BEhalt && s.finalbody && s.finalbody.hasCode())
{
s.finalbody.warning("statement is not reachable");
}
}
if (!(finalresult & BEfallthru))
result &= ~BEfallthru;
result |= finalresult & ~BEfallthru;
}
override void visit(OnScopeStatement s)
{
// At this point, this statement is just an empty placeholder
result = BEfallthru;
}
override void visit(ThrowStatement s)
{
if (s.internalThrow)
{
// Bugzilla 8675: Allow throwing 'Throwable' object even if mustNotThrow.
result = BEfallthru;
return;
}
Type t = s.exp.type.toBasetype();
ClassDeclaration cd = t.isClassHandle();
assert(cd);
if (cd == ClassDeclaration.errorException || ClassDeclaration.errorException.isBaseOf(cd, null))
{
result = BEerrthrow;
return;
}
if (mustNotThrow)
s.error("%s is thrown but not caught", s.exp.type.toChars());
result = BEthrow;
}
override void visit(GotoStatement s)
{
//printf("GotoStatement::blockExit(%p)\n", s);
result = BEgoto;
}
override void visit(LabelStatement s)
{
//printf("LabelStatement::blockExit(%p)\n", s);
result = s.statement ? s.statement.blockExit(func, mustNotThrow) : BEfallthru;
if (s.breaks)
result |= BEfallthru;
}
override void visit(CompoundAsmStatement s)
{
if (mustNotThrow && !(s.stc & STCnothrow))
s.deprecation("asm statement is assumed to throw - mark it with 'nothrow' if it does not");
// Assume the worst
result = BEfallthru | BEreturn | BEgoto | BEhalt;
if (!(s.stc & STCnothrow))
result |= BEthrow;
}
override void visit(ImportStatement s)
{
result = BEfallthru;
}
}
scope BlockExit be = new BlockExit(func, mustNotThrow);
accept(be);
return be.result;
}
/* ============================================== */
// true if statement 'comes from' somewhere else, like a goto
final bool comeFrom()
{
extern (C++) final class ComeFrom : StoppableVisitor
{
alias visit = super.visit;
public:
override void visit(Statement s)
{
}
override void visit(CaseStatement s)
{
stop = true;
}
override void visit(DefaultStatement s)
{
stop = true;
}
override void visit(LabelStatement s)
{
stop = true;
}
override void visit(AsmStatement s)
{
stop = true;
}
}
scope ComeFrom cf = new ComeFrom();
return walkPostorder(this, cf);
}
/* ============================================== */
// Return true if statement has executable code.
final bool hasCode()
{
extern (C++) final class HasCode : StoppableVisitor
{
alias visit = super.visit;
public:
override void visit(Statement s)
{
stop = true;
}
override void visit(ExpStatement s)
{
stop = s.exp !is null;
}
override void visit(CompoundStatement s)
{
}
override void visit(ScopeStatement s)
{
}
override void visit(ImportStatement s)
{
}
}
scope HasCode hc = new HasCode();
return walkPostorder(this, hc);
}
/****************************************
* If this statement has code that needs to run in a finally clause
* at the end of the current scope, return that code in the form of
* a Statement.
* Output:
* *sentry code executed upon entry to the scope
* *sexception code executed upon exit from the scope via exception
* *sfinally code executed in finally block
*/
Statement scopeCode(Scope* sc, Statement* sentry, Statement* sexception, Statement* sfinally)
{
//printf("Statement::scopeCode()\n");
//print();
*sentry = null;
*sexception = null;
*sfinally = null;
return this;
}
/*********************************
* Flatten out the scope by presenting the statement
* as an array of statements.
* Returns NULL if no flattening necessary.
*/
Statements* flatten(Scope* sc)
{
return null;
}
Statement last()
{
return this;
}
// Avoid dynamic_cast
ErrorStatement isErrorStatement()
{
return null;
}
ScopeStatement isScopeStatement()
{
return null;
}
ExpStatement isExpStatement()
{
return null;
}
CompoundStatement isCompoundStatement()
{
return null;
}
ReturnStatement isReturnStatement()
{
return null;
}
IfStatement isIfStatement()
{
return null;
}
CaseStatement isCaseStatement()
{
return null;
}
DefaultStatement isDefaultStatement()
{
return null;
}
LabelStatement isLabelStatement()
{
return null;
}
DtorExpStatement isDtorExpStatement()
{
return null;
}
void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
* Any Statement that fails semantic() or has a component that is an ErrorExp or
* a TypeError should return an ErrorStatement from semantic().
*/
extern (C++) final class ErrorStatement : Statement
{
public:
extern (D) this()
{
super(Loc());
assert(global.gaggedErrors || global.errors);
}
override Statement syntaxCopy()
{
return this;
}
override Statement semantic(Scope* sc)
{
return this;
}
override ErrorStatement isErrorStatement()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class PeelStatement : Statement
{
public:
Statement s;
extern (D) this(Statement s)
{
super(s.loc);
this.s = s;
}
override Statement semantic(Scope* sc)
{
/* "peel" off this wrapper, and don't run semantic()
* on the result.
*/
return s;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
* Convert TemplateMixin members (== Dsymbols) to Statements.
*/
extern (C++) Statement toStatement(Dsymbol s)
{
extern (C++) final class ToStmt : Visitor
{
alias visit = super.visit;
public:
Statement result;
Statement visitMembers(Loc loc, Dsymbols* a)
{
if (!a)
return null;
auto statements = new Statements();
foreach (s; *a)
{
statements.push(toStatement(s));
}
return new CompoundStatement(loc, statements);
}
override void visit(Dsymbol s)
{
.error(Loc(), "Internal Compiler Error: cannot mixin %s %s\n", s.kind(), s.toChars());
result = new ErrorStatement();
}
override void visit(TemplateMixin tm)
{
auto a = new Statements();
foreach (m; *tm.members)
{
Statement s = toStatement(m);
if (s)
a.push(s);
}
result = new CompoundStatement(tm.loc, a);
}
/* An actual declaration symbol will be converted to DeclarationExp
* with ExpStatement.
*/
Statement declStmt(Dsymbol s)
{
auto de = new DeclarationExp(s.loc, s);
de.type = Type.tvoid; // avoid repeated semantic
return new ExpStatement(s.loc, de);
}
override void visit(VarDeclaration d)
{
result = declStmt(d);
}
override void visit(AggregateDeclaration d)
{
result = declStmt(d);
}
override void visit(FuncDeclaration d)
{
result = declStmt(d);
}
override void visit(EnumDeclaration d)
{
result = declStmt(d);
}
override void visit(AliasDeclaration d)
{
result = declStmt(d);
}
override void visit(TemplateDeclaration d)
{
result = declStmt(d);
}
/* All attributes have been already picked by the semantic analysis of
* 'bottom' declarations (function, struct, class, etc).
* So we don't have to copy them.
*/
override void visit(StorageClassDeclaration d)
{
result = visitMembers(d.loc, d.decl);
}
override void visit(DeprecatedDeclaration d)
{
result = visitMembers(d.loc, d.decl);
}
override void visit(LinkDeclaration d)
{
result = visitMembers(d.loc, d.decl);
}
override void visit(ProtDeclaration d)
{
result = visitMembers(d.loc, d.decl);
}
override void visit(AlignDeclaration d)
{
result = visitMembers(d.loc, d.decl);
}
override void visit(UserAttributeDeclaration d)
{
result = visitMembers(d.loc, d.decl);
}
override void visit(StaticAssert s)
{
}
override void visit(Import s)
{
}
override void visit(PragmaDeclaration d)
{
}
override void visit(ConditionalDeclaration d)
{
result = visitMembers(d.loc, d.include(null, null));
}
override void visit(CompileDeclaration d)
{
result = visitMembers(d.loc, d.include(null, null));
}
}
if (!s)
return null;
scope ToStmt v = new ToStmt();
s.accept(v);
return v.result;
}
/***********************************************************
*/
extern (C++) class ExpStatement : Statement
{
public:
Expression exp;
final extern (D) this(Loc loc, Expression exp)
{
super(loc);
this.exp = exp;
}
final extern (D) this(Loc loc, Dsymbol declaration)
{
super(loc);
this.exp = new DeclarationExp(loc, declaration);
}
final static ExpStatement create(Loc loc, Expression exp)
{
return new ExpStatement(loc, exp);
}
override Statement syntaxCopy()
{
return new ExpStatement(loc, exp ? exp.syntaxCopy() : null);
}
override final Statement semantic(Scope* sc)
{
if (exp)
{
//printf("ExpStatement::semantic() %s\n", exp->toChars());
version (none)
{
// Doesn't work because of difficulty dealing with things like a.b.c!(args).Foo!(args)
// See if this should be rewritten as a TemplateMixin
if (exp.op == TOKdeclaration)
{
DeclarationExp de = cast(DeclarationExp)exp;
Dsymbol s = de.declaration;
printf("s: %s %s\n", s.kind(), s.toChars());
VarDeclaration v = s.isVarDeclaration();
if (v)
{
printf("%s, %d\n", v.type.toChars(), v.type.ty);
}
}
}
exp = exp.semantic(sc);
exp = resolveProperties(sc, exp);
exp = exp.addDtorHook(sc);
discardValue(exp);
exp = exp.optimize(WANTvalue);
exp = checkGC(sc, exp);
if (exp.op == TOKerror)
return new ErrorStatement();
}
return this;
}
override final Statement scopeCode(Scope* sc, Statement* sentry, Statement* sexception, Statement* sfinally)
{
//printf("ExpStatement::scopeCode()\n");
//print();
*sentry = null;
*sexception = null;
*sfinally = null;
if (exp)
{
if (exp.op == TOKdeclaration)
{
DeclarationExp de = cast(DeclarationExp)exp;
VarDeclaration v = de.declaration.isVarDeclaration();
if (v && !v.noscope && !v.isDataseg())
{
Expression e = v.edtor;
if (e)
{
//printf("dtor is: "); e->print();
version (none)
{
if (v.type.toBasetype().ty == Tstruct)
{
/* Need a 'gate' to turn on/off destruction,
* in case v gets moved elsewhere.
*/
Identifier id = Identifier.generateId("__runDtor");
auto ie = new ExpInitializer(loc, new IntegerExp(1));
auto rd = new VarDeclaration(loc, Type.tint32, id, ie);
rd.storage_class |= STCtemp;
*sentry = new ExpStatement(loc, rd);
v.rundtor = rd;
/* Rewrite e as:
* rundtor && e
*/
Expression ve = new VarExp(loc, v.rundtor);
e = new AndAndExp(loc, ve, e);
e.type = Type.tbool;
}
}
*sfinally = new DtorExpStatement(loc, e, v);
}
v.noscope = 1; // don't add in dtor again
}
}
}
return this;
}
override final Statements* flatten(Scope* sc)
{
/* Bugzilla 14243: expand template mixin in statement scope
* to handle variable destructors.
*/
if (exp && exp.op == TOKdeclaration)
{
Dsymbol d = (cast(DeclarationExp)exp).declaration;
if (TemplateMixin tm = d.isTemplateMixin())
{
Expression e = exp.semantic(sc);
if (e.op == TOKerror || tm.errors)
{
auto a = new Statements();
a.push(new ErrorStatement());
return a;
}
assert(tm.members);
Statement s = toStatement(tm);
version (none)
{
OutBuffer buf;
buf.doindent = 1;
HdrGenState hgs;
hgs.hdrgen = true;
toCBuffer(s, &buf, &hgs);
printf("tm ==> s = %s\n", buf.peekString());
}
auto a = new Statements();
a.push(s);
return a;
}
}
return null;
}
override final ExpStatement isExpStatement()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class DtorExpStatement : ExpStatement
{
public:
// Wraps an expression that is the destruction of 'var'
VarDeclaration var;
extern (D) this(Loc loc, Expression exp, VarDeclaration v)
{
super(loc, exp);
this.var = v;
}
override Statement syntaxCopy()
{
return new DtorExpStatement(loc, exp ? exp.syntaxCopy() : null, var);
}
override void accept(Visitor v)
{
v.visit(this);
}
override DtorExpStatement isDtorExpStatement()
{
return this;
}
}
/***********************************************************
*/
extern (C++) final class CompileStatement : Statement
{
public:
Expression exp;
extern (D) this(Loc loc, Expression exp)
{
super(loc);
this.exp = exp;
}
override Statement syntaxCopy()
{
return new CompileStatement(loc, exp.syntaxCopy());
}
override Statements* flatten(Scope* sc)
{
//printf("CompileStatement::flatten() %s\n", exp->toChars());
sc = sc.startCTFE();
exp = exp.semantic(sc);
exp = resolveProperties(sc, exp);
sc = sc.endCTFE();
auto a = new Statements();
if (exp.op != TOKerror)
{
Expression e = exp.ctfeInterpret();
StringExp se = e.toStringExp();
if (!se)
error("argument to mixin must be a string, not (%s) of type %s", exp.toChars(), exp.type.toChars());
else
{
se = se.toUTF8(sc);
uint errors = global.errors;
scope Parser p = new Parser(loc, sc._module, cast(char*)se.string, se.len, 0);
p.nextToken();
while (p.token.value != TOKeof)
{
Statement s = p.parseStatement(PSsemi | PScurlyscope);
if (!s || p.errors)
{
assert(!p.errors || global.errors != errors); // make sure we caught all the cases
goto Lerror;
}
a.push(s);
}
return a;
}
}
Lerror:
a.push(new ErrorStatement());
return a;
}
override Statement semantic(Scope* sc)
{
//printf("CompileStatement::semantic() %s\n", exp->toChars());
Statements* a = flatten(sc);
if (!a)
return null;
Statement s = new CompoundStatement(loc, a);
return s.semantic(sc);
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) class CompoundStatement : Statement
{
public:
Statements* statements;
final extern (D) this(Loc loc, Statements* s)
{
super(loc);
statements = s;
}
final extern (D) this(Loc loc, Statement s1)
{
super(loc);
statements = new Statements();
statements.push(s1);
}
final extern (D) this(Loc loc, Statement s1, Statement s2)
{
super(loc);
statements = new Statements();
statements.reserve(2);
statements.push(s1);
statements.push(s2);
}
final static CompoundStatement create(Loc loc, Statement s1, Statement s2)
{
return new CompoundStatement(loc, s1, s2);
}
override Statement syntaxCopy()
{
auto a = new Statements();
a.setDim(statements.dim);
foreach (i, s; *statements)
{
(*a)[i] = s ? s.syntaxCopy() : null;
}
return new CompoundStatement(loc, a);
}
override Statement semantic(Scope* sc)
{
//printf("CompoundStatement::semantic(this = %p, sc = %p)\n", this, sc);
version (none)
{
foreach (i, s; statements)
{
if (s)
printf("[%d]: %s", i, s.toChars());
}
}
for (size_t i = 0; i < statements.dim;)
{
Statement s = (*statements)[i];
if (s)
{
Statements* flt = s.flatten(sc);
if (flt)
{
statements.remove(i);
statements.insert(i, flt);
continue;
}
s = s.semantic(sc);
(*statements)[i] = s;
if (s)
{
Statement sentry;
Statement sexception;
Statement sfinally;
(*statements)[i] = s.scopeCode(sc, &sentry, &sexception, &sfinally);
if (sentry)
{
sentry = sentry.semantic(sc);
statements.insert(i, sentry);
i++;
}
if (sexception)
sexception = sexception.semantic(sc);
if (sexception)
{
if (i + 1 == statements.dim && !sfinally)
{
}
else
{
/* Rewrite:
* s; s1; s2;
* As:
* s;
* try { s1; s2; }
* catch (Throwable __o)
* { sexception; throw __o; }
*/
auto a = new Statements();
foreach (j; i + 1 .. statements.dim)
{
a.push((*statements)[j]);
}
Statement _body = new CompoundStatement(Loc(), a);
_body = new ScopeStatement(Loc(), _body);
Identifier id = Identifier.generateId("__o");
Statement handler = new PeelStatement(sexception);
if (sexception.blockExit(sc.func, false) & BEfallthru)
{
auto ts = new ThrowStatement(Loc(), new IdentifierExp(Loc(), id));
ts.internalThrow = true;
handler = new CompoundStatement(Loc(), handler, ts);
}
auto catches = new Catches();
auto ctch = new Catch(Loc(), null, id, handler);
ctch.internalCatch = true;
catches.push(ctch);
s = new TryCatchStatement(Loc(), _body, catches);
if (sfinally)
s = new TryFinallyStatement(Loc(), s, sfinally);
s = s.semantic(sc);
statements.setDim(i + 1);
statements.push(s);
break;
}
}
else if (sfinally)
{
if (0 && i + 1 == statements.dim)
{
statements.push(sfinally);
}
else
{
/* Rewrite:
* s; s1; s2;
* As:
* s; try { s1; s2; } finally { sfinally; }
*/
auto a = new Statements();
foreach (j; i + 1 .. statements.dim)
{
a.push((*statements)[j]);
}
Statement _body = new CompoundStatement(Loc(), a);
s = new TryFinallyStatement(Loc(), _body, sfinally);
s = s.semantic(sc);
statements.setDim(i + 1);
statements.push(s);
break;
}
}
}
else
{
/* Remove NULL statements from the list.
*/
statements.remove(i);
continue;
}
}
i++;
}
foreach (i; 0 .. statements.dim)
{
Lagain:
Statement s = (*statements)[i];
if (!s)
continue;
Statement se = s.isErrorStatement();
if (se)
return se;
/* Bugzilla 11653: 'semantic' may return another CompoundStatement
* (eg. CaseRangeStatement), so flatten it here.
*/
Statements* flt = s.flatten(sc);
if (flt)
{
statements.remove(i);
statements.insert(i, flt);
if (statements.dim <= i)
break;
goto Lagain;
}
}
if (statements.dim == 1)
{
return (*statements)[0];
}
return this;
}
override Statements* flatten(Scope* sc)
{
return statements;
}
override final ReturnStatement isReturnStatement()
{
ReturnStatement rs = null;
foreach (s; *statements)
{
if (s)
{
rs = s.isReturnStatement();
if (rs)
break;
}
}
return rs;
}
override final Statement last()
{
Statement s = null;
for (size_t i = statements.dim; i; --i)
{
s = (*statements)[i - 1];
if (s)
{
s = s.last();
if (s)
break;
}
}
return s;
}
override final CompoundStatement isCompoundStatement()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class CompoundDeclarationStatement : CompoundStatement
{
public:
extern (D) this(Loc loc, Statements* s)
{
super(loc, s);
statements = s;
}
override Statement syntaxCopy()
{
auto a = new Statements();
a.setDim(statements.dim);
foreach (i, s; *statements)
{
(*a)[i] = s ? s.syntaxCopy() : null;
}
return new CompoundDeclarationStatement(loc, a);
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
* The purpose of this is so that continue will go to the next
* of the statements, and break will go to the end of the statements.
*/
extern (C++) final class UnrolledLoopStatement : Statement
{
public:
Statements* statements;
extern (D) this(Loc loc, Statements* s)
{
super(loc);
statements = s;
}
override Statement syntaxCopy()
{
auto a = new Statements();
a.setDim(statements.dim);
foreach (i, s; *statements)
{
(*a)[i] = s ? s.syntaxCopy() : null;
}
return new UnrolledLoopStatement(loc, a);
}
override Statement semantic(Scope* sc)
{
//printf("UnrolledLoopStatement::semantic(this = %p, sc = %p)\n", this, sc);
Scope* scd = sc.push();
scd.sbreak = this;
scd.scontinue = this;
Statement serror = null;
foreach (i, ref s; *statements)
{
if (s)
{
//printf("[%d]: %s\n", i, s->toChars());
s = s.semantic(scd);
if (s && !serror)
serror = s.isErrorStatement();
}
}
scd.pop();
return serror ? serror : this;
}
override bool hasBreak()
{
return true;
}
override bool hasContinue()
{
return true;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ScopeStatement : Statement
{
public:
Statement statement;
extern (D) this(Loc loc, Statement s)
{
super(loc);
this.statement = s;
}
override Statement syntaxCopy()
{
return new ScopeStatement(loc, statement ? statement.syntaxCopy() : null);
}
override ScopeStatement isScopeStatement()
{
return this;
}
override ReturnStatement isReturnStatement()
{
if (statement)
return statement.isReturnStatement();
return null;
}
override Statement semantic(Scope* sc)
{
ScopeDsymbol sym;
//printf("ScopeStatement::semantic(sc = %p)\n", sc);
if (statement)
{
sym = new ScopeDsymbol();
sym.parent = sc.scopesym;
sc = sc.push(sym);
Statements* a = statement.flatten(sc);
if (a)
{
statement = new CompoundStatement(loc, a);
}
statement = statement.semantic(sc);
if (statement)
{
if (statement.isErrorStatement())
{
sc.pop();
return statement;
}
Statement sentry;
Statement sexception;
Statement sfinally;
statement = statement.scopeCode(sc, &sentry, &sexception, &sfinally);
assert(!sentry);
assert(!sexception);
if (sfinally)
{
//printf("adding sfinally\n");
sfinally = sfinally.semantic(sc);
statement = new CompoundStatement(loc, statement, sfinally);
}
}
sc.pop();
}
return this;
}
override bool hasBreak()
{
//printf("ScopeStatement::hasBreak() %s\n", toChars());
return statement ? statement.hasBreak() : false;
}
override bool hasContinue()
{
return statement ? statement.hasContinue() : false;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class WhileStatement : Statement
{
public:
Expression condition;
Statement _body;
Loc endloc; // location of closing curly bracket
extern (D) this(Loc loc, Expression c, Statement b, Loc endloc)
{
super(loc);
condition = c;
_body = b;
this.endloc = endloc;
}
override Statement syntaxCopy()
{
return new WhileStatement(loc, condition.syntaxCopy(), _body ? _body.syntaxCopy() : null, endloc);
}
override Statement semantic(Scope* sc)
{
/* Rewrite as a for(;condition;) loop
*/
Statement s = new ForStatement(loc, null, condition, null, _body, endloc);
s = s.semantic(sc);
return s;
}
override bool hasBreak()
{
return true;
}
override bool hasContinue()
{
return true;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class DoStatement : Statement
{
public:
Statement _body;
Expression condition;
extern (D) this(Loc loc, Statement b, Expression c)
{
super(loc);
_body = b;
condition = c;
}
override Statement syntaxCopy()
{
return new DoStatement(loc, _body ? _body.syntaxCopy() : null, condition.syntaxCopy());
}
override Statement semantic(Scope* sc)
{
sc.noctor++;
if (_body)
_body = _body.semanticScope(sc, this, this);
sc.noctor--;
condition = condition.semantic(sc);
condition = resolveProperties(sc, condition);
condition = condition.optimize(WANTvalue);
condition = checkGC(sc, condition);
condition = condition.toBoolean(sc);
if (condition.op == TOKerror)
return new ErrorStatement();
if (_body && _body.isErrorStatement())
return _body;
return this;
}
override bool hasBreak()
{
return true;
}
override bool hasContinue()
{
return true;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ForStatement : Statement
{
public:
Statement _init;
Expression condition;
Expression increment;
Statement _body;
Loc endloc; // location of closing curly bracket
// When wrapped in try/finally clauses, this points to the outermost one,
// which may have an associated label. Internal break/continue statements
// treat that label as referring to this loop.
Statement relatedLabeled;
extern (D) this(Loc loc, Statement _init, Expression condition, Expression increment, Statement _body, Loc endloc)
{
super(loc);
this._init = _init;
this.condition = condition;
this.increment = increment;
this._body = _body;
this.endloc = endloc;
}
override Statement syntaxCopy()
{
return new ForStatement(loc, _init ? _init.syntaxCopy() : null, condition ? condition.syntaxCopy() : null, increment ? increment.syntaxCopy() : null, _body.syntaxCopy(), endloc);
}
override Statement semantic(Scope* sc)
{
//printf("ForStatement::semantic %s\n", toChars());
if (_init)
{
/* Rewrite:
* for (auto v1 = i1, v2 = i2; condition; increment) { ... }
* to:
* { auto v1 = i1, v2 = i2; for (; condition; increment) { ... } }
* then lowered to:
* auto v1 = i1;
* try {
* auto v2 = i2;
* try {
* for (; condition; increment) { ... }
* } finally { v2.~this(); }
* } finally { v1.~this(); }
*/
auto ainit = new Statements();
ainit.push(_init), _init = null;
ainit.push(this);
Statement s = new CompoundStatement(loc, ainit);
s = new ScopeStatement(loc, s);
s = s.semantic(sc);
if (!s.isErrorStatement())
{
if (LabelStatement ls = checkLabeledLoop(sc, this))
ls.gotoTarget = this;
relatedLabeled = s;
}
return s;
}
assert(_init is null);
auto sym = new ScopeDsymbol();
sym.parent = sc.scopesym;
sc = sc.push(sym);
sc.noctor++;
if (condition)
{
condition = condition.semantic(sc);
condition = resolveProperties(sc, condition);
condition = condition.optimize(WANTvalue);
condition = checkGC(sc, condition);
condition = condition.toBoolean(sc);
}
if (increment)
{
increment = increment.semantic(sc);
increment = resolveProperties(sc, increment);
increment = increment.optimize(WANTvalue);
increment = checkGC(sc, increment);
}
sc.sbreak = this;
sc.scontinue = this;
if (_body)
_body = _body.semanticNoScope(sc);
sc.noctor--;
sc.pop();
if (condition && condition.op == TOKerror || increment && increment.op == TOKerror || _body && _body.isErrorStatement())
return new ErrorStatement();
return this;
}
override Statement scopeCode(Scope* sc, Statement* sentry, Statement* sexception, Statement* sfinally)
{
//printf("ForStatement::scopeCode()\n");
Statement.scopeCode(sc, sentry, sexception, sfinally);
return this;
}
override Statement getRelatedLabeled()
{
return relatedLabeled ? relatedLabeled : this;
}
override bool hasBreak()
{
//printf("ForStatement::hasBreak()\n");
return true;
}
override bool hasContinue()
{
return true;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ForeachStatement : Statement
{
public:
TOK op; // TOKforeach or TOKforeach_reverse
Parameters* parameters; // array of Parameter*'s
Expression aggr;
Statement _body;
Loc endloc; // location of closing curly bracket
VarDeclaration key;
VarDeclaration value;
FuncDeclaration func; // function we're lexically in
Statements* cases; // put breaks, continues, gotos and returns here
ScopeStatements* gotos; // forward referenced goto's go here
extern (D) this(Loc loc, TOK op, Parameters* parameters, Expression aggr, Statement _body, Loc endloc)
{
super(loc);
this.op = op;
this.parameters = parameters;
this.aggr = aggr;
this._body = _body;
this.endloc = endloc;
}
override Statement syntaxCopy()
{
return new ForeachStatement(loc, op, Parameter.arraySyntaxCopy(parameters), aggr.syntaxCopy(), _body ? _body.syntaxCopy() : null, endloc);
}
override Statement semantic(Scope* sc)
{
//printf("ForeachStatement::semantic() %p\n", this);
ScopeDsymbol sym;
Statement s = this;
size_t dim = parameters.dim;
TypeAArray taa = null;
Dsymbol sapply = null;
Type tn = null;
Type tnv = null;
func = sc.func;
if (func.fes)
func = func.fes.func;
VarDeclaration vinit = null;
aggr = aggr.semantic(sc);
aggr = resolveProperties(sc, aggr);
aggr = aggr.optimize(WANTvalue);
if (aggr.op == TOKerror)
return new ErrorStatement();
Expression oaggr = aggr;
if (aggr.type && aggr.type.toBasetype().ty == Tstruct && aggr.op != TOKtype && !aggr.isLvalue())
{
// Bugzilla 14653: Extend the life of rvalue aggregate till the end of foreach.
vinit = new VarDeclaration(loc, aggr.type, Identifier.generateId("__aggr"), new ExpInitializer(loc, aggr));
vinit.storage_class |= STCtemp;
vinit.semantic(sc);
aggr = new VarExp(aggr.loc, vinit);
}
if (!inferAggregate(this, sc, sapply))
{
const(char)* msg = "";
if (aggr.type && isAggregate(aggr.type))
{
msg = ", define opApply(), range primitives, or use .tupleof";
}
error("invalid foreach aggregate %s%s", oaggr.toChars(), msg);
return new ErrorStatement();
}
Dsymbol sapplyOld = sapply; // 'sapply' will be NULL if and after 'inferApplyArgTypes' errors
/* Check for inference errors
*/
if (!inferApplyArgTypes(this, sc, sapply))
{
/**
Try and extract the parameter count of the opApply callback function, e.g.:
int opApply(int delegate(int, float)) => 2 args
*/
bool foundMismatch = false;
size_t foreachParamCount = 0;
if (sapplyOld)
{
if (FuncDeclaration fd = sapplyOld.isFuncDeclaration())
{
int fvarargs; // ignored (opApply shouldn't take variadics)
Parameters* fparameters = fd.getParameters(&fvarargs);
if (Parameter.dim(fparameters) == 1)
{
// first param should be the callback function
Parameter fparam = Parameter.getNth(fparameters, 0);
if ((fparam.type.ty == Tpointer || fparam.type.ty == Tdelegate) && fparam.type.nextOf().ty == Tfunction)
{
TypeFunction tf = cast(TypeFunction)fparam.type.nextOf();
foreachParamCount = Parameter.dim(tf.parameters);
foundMismatch = true;
}
}
}
}
//printf("dim = %d, parameters->dim = %d\n", dim, parameters->dim);
if (foundMismatch && dim != foreachParamCount)
{
const(char)* plural = foreachParamCount > 1 ? "s" : "";
error("cannot infer argument types, expected %d argument%s, not %d", foreachParamCount, plural, dim);
}
else
error("cannot uniquely infer foreach argument types");
return new ErrorStatement();
}
Type tab = aggr.type.toBasetype();
if (tab.ty == Ttuple) // don't generate new scope for tuple loops
{
if (dim < 1 || dim > 2)
{
error("only one (value) or two (key,value) arguments for tuple foreach");
return new ErrorStatement();
}
Type paramtype = (*parameters)[dim - 1].type;
if (paramtype)
{
paramtype = paramtype.semantic(loc, sc);
if (paramtype.ty == Terror)
return new ErrorStatement();
}
TypeTuple tuple = cast(TypeTuple)tab;
auto statements = new Statements();
//printf("aggr: op = %d, %s\n", aggr->op, aggr->toChars());
size_t n;
TupleExp te = null;
if (aggr.op == TOKtuple) // expression tuple
{
te = cast(TupleExp)aggr;
n = te.exps.dim;
}
else if (aggr.op == TOKtype) // type tuple
{
n = Parameter.dim(tuple.arguments);
}
else
assert(0);
foreach (j; 0 .. n)
{
size_t k = (op == TOKforeach) ? j : n - 1 - j;
Expression e = null;
Type t = null;
if (te)
e = (*te.exps)[k];
else
t = Parameter.getNth(tuple.arguments, k).type;
Parameter p = (*parameters)[0];
auto st = new Statements();
if (dim == 2)
{
// Declare key
if (p.storageClass & (STCout | STCref | STClazy))
{
error("no storage class for key %s", p.ident.toChars());
return new ErrorStatement();
}
p.type = p.type.semantic(loc, sc);
TY keyty = p.type.ty;
if (keyty != Tint32 && keyty != Tuns32)
{
if (global.params.isLP64)
{
if (keyty != Tint64 && keyty != Tuns64)
{
error("foreach: key type must be int or uint, long or ulong, not %s", p.type.toChars());
return new ErrorStatement();
}
}
else
{
error("foreach: key type must be int or uint, not %s", p.type.toChars());
return new ErrorStatement();
}
}
Initializer ie = new ExpInitializer(Loc(), new IntegerExp(k));
auto var = new VarDeclaration(loc, p.type, p.ident, ie);
var.storage_class |= STCmanifest;
st.push(new ExpStatement(loc, var));
p = (*parameters)[1]; // value
}
// Declare value
if (p.storageClass & (STCout | STClazy) || p.storageClass & STCref && !te)
{
error("no storage class for value %s", p.ident.toChars());
return new ErrorStatement();
}
Dsymbol var;
if (te)
{
Type tb = e.type.toBasetype();
Dsymbol ds = null;
if ((tb.ty == Tfunction || tb.ty == Tsarray) && e.op == TOKvar)
ds = (cast(VarExp)e).var;
else if (e.op == TOKtemplate)
ds = (cast(TemplateExp)e).td;
else if (e.op == TOKimport)
ds = (cast(ScopeExp)e).sds;
else if (e.op == TOKfunction)
{
FuncExp fe = cast(FuncExp)e;
ds = fe.td ? cast(Dsymbol)fe.td : fe.fd;
}
if (ds)
{
var = new AliasDeclaration(loc, p.ident, ds);
if (p.storageClass & STCref)
{
error("symbol %s cannot be ref", s.toChars());
return new ErrorStatement();
}
if (paramtype)
{
error("cannot specify element type for symbol %s", ds.toChars());
return new ErrorStatement();
}
}
else if (e.op == TOKtype)
{
var = new AliasDeclaration(loc, p.ident, e.type);
if (paramtype)
{
error("cannot specify element type for type %s", e.type.toChars());
return new ErrorStatement();
}
}
else
{
p.type = e.type;
if (paramtype)
p.type = paramtype;
Initializer ie = new ExpInitializer(Loc(), e);
auto v = new VarDeclaration(loc, p.type, p.ident, ie);
if (p.storageClass & STCref)
v.storage_class |= STCref | STCforeach;
if (e.isConst() || e.op == TOKstring || e.op == TOKstructliteral || e.op == TOKarrayliteral)
{
if (v.storage_class & STCref)
{
error("constant value %s cannot be ref", ie.toChars());
return new ErrorStatement();
}
else
v.storage_class |= STCmanifest;
}
var = v;
}
}
else
{
var = new AliasDeclaration(loc, p.ident, t);
if (paramtype)
{
error("cannot specify element type for symbol %s", s.toChars());
return new ErrorStatement();
}
}
st.push(new ExpStatement(loc, var));
st.push(_body.syntaxCopy());
s = new CompoundStatement(loc, st);
s = new ScopeStatement(loc, s);
statements.push(s);
}
s = new UnrolledLoopStatement(loc, statements);
if (LabelStatement ls = checkLabeledLoop(sc, this))
ls.gotoTarget = s;
if (te && te.e0)
s = new CompoundStatement(loc, new ExpStatement(te.e0.loc, te.e0), s);
if (vinit)
s = new CompoundStatement(loc, new ExpStatement(loc, vinit), s);
s = s.semantic(sc);
return s;
}
sym = new ScopeDsymbol();
sym.parent = sc.scopesym;
sc = sc.push(sym);
sc.noctor++;
switch (tab.ty)
{
case Tarray:
case Tsarray:
{
if (checkForArgTypes())
return this;
if (dim < 1 || dim > 2)
{
error("only one or two arguments for array foreach");
goto Lerror2;
}
/* Look for special case of parsing char types out of char type
* array.
*/
tn = tab.nextOf().toBasetype();
if (tn.ty == Tchar || tn.ty == Twchar || tn.ty == Tdchar)
{
int i = (dim == 1) ? 0 : 1; // index of value
Parameter p = (*parameters)[i];
p.type = p.type.semantic(loc, sc);
p.type = p.type.addStorageClass(p.storageClass);
tnv = p.type.toBasetype();
if (tnv.ty != tn.ty && (tnv.ty == Tchar || tnv.ty == Twchar || tnv.ty == Tdchar))
{
if (p.storageClass & STCref)
{
error("foreach: value of UTF conversion cannot be ref");
goto Lerror2;
}
if (dim == 2)
{
p = (*parameters)[0];
if (p.storageClass & STCref)
{
error("foreach: key cannot be ref");
goto Lerror2;
}
}
goto Lapply;
}
}
foreach (i; 0 .. dim)
{
// Declare parameterss
Parameter p = (*parameters)[i];
p.type = p.type.semantic(loc, sc);
p.type = p.type.addStorageClass(p.storageClass);
VarDeclaration var;
if (dim == 2 && i == 0)
{
var = new VarDeclaration(loc, p.type.mutableOf(), Identifier.generateId("__key"), null);
var.storage_class |= STCtemp | STCforeach;
if (var.storage_class & (STCref | STCout))
var.storage_class |= STCnodtor;
key = var;
if (p.storageClass & STCref)
{
if (var.type.constConv(p.type) <= MATCHnomatch)
{
error("key type mismatch, %s to ref %s", var.type.toChars(), p.type.toChars());
goto Lerror2;
}
}
if (tab.ty == Tsarray)
{
TypeSArray ta = cast(TypeSArray)tab;
IntRange dimrange = getIntRange(ta.dim);
if (!IntRange.fromType(var.type).contains(dimrange))
{
error("index type '%s' cannot cover index range 0..%llu", p.type.toChars(), ta.dim.toInteger());
goto Lerror2;
}
key.range = new IntRange(SignExtendedNumber(0), dimrange.imax);
}
}
else
{
var = new VarDeclaration(loc, p.type, p.ident, null);
var.storage_class |= STCforeach;
var.storage_class |= p.storageClass & (STCin | STCout | STCref | STC_TYPECTOR);
if (var.storage_class & (STCref | STCout))
var.storage_class |= STCnodtor;
value = var;
if (var.storage_class & STCref)
{
if (aggr.checkModifiable(sc, 1) == 2)
var.storage_class |= STCctorinit;
Type t = tab.nextOf();
if (t.constConv(p.type) <= MATCHnomatch)
{
error("argument type mismatch, %s to ref %s", t.toChars(), p.type.toChars());
goto Lerror2;
}
}
}
}
/* Convert to a ForStatement
* foreach (key, value; a) body =>
* for (T[] tmp = a[], size_t key; key < tmp.length; ++key)
* { T value = tmp[k]; body }
*
* foreach_reverse (key, value; a) body =>
* for (T[] tmp = a[], size_t key = tmp.length; key--; )
* { T value = tmp[k]; body }
*/
Identifier id = Identifier.generateId("__r");
auto ie = new ExpInitializer(loc, new SliceExp(loc, aggr, null, null));
VarDeclaration tmp;
if (aggr.op == TOKarrayliteral && !((*parameters)[dim - 1].storageClass & STCref))
{
ArrayLiteralExp ale = cast(ArrayLiteralExp)aggr;
size_t edim = ale.elements ? ale.elements.dim : 0;
aggr.type = tab.nextOf().sarrayOf(edim);
// for (T[edim] tmp = a, ...)
tmp = new VarDeclaration(loc, aggr.type, id, ie);
}
else
tmp = new VarDeclaration(loc, tab.nextOf().arrayOf(), id, ie);
tmp.storage_class |= STCtemp;
Expression tmp_length = new DotIdExp(loc, new VarExp(loc, tmp), Id.length);
if (!key)
{
Identifier idkey = Identifier.generateId("__key");
key = new VarDeclaration(loc, Type.tsize_t, idkey, null);
key.storage_class |= STCtemp;
}
if (op == TOKforeach_reverse)
key._init = new ExpInitializer(loc, tmp_length);
else
key._init = new ExpInitializer(loc, new IntegerExp(loc, 0, key.type));
auto cs = new Statements();
if (vinit)
cs.push(new ExpStatement(loc, vinit));
cs.push(new ExpStatement(loc, tmp));
cs.push(new ExpStatement(loc, key));
Statement forinit = new CompoundDeclarationStatement(loc, cs);
Expression cond;
if (op == TOKforeach_reverse)
{
// key--
cond = new PostExp(TOKminusminus, loc, new VarExp(loc, key));
}
else
{
// key < tmp.length
cond = new CmpExp(TOKlt, loc, new VarExp(loc, key), tmp_length);
}
Expression increment = null;
if (op == TOKforeach)
{
// key += 1
increment = new AddAssignExp(loc, new VarExp(loc, key), new IntegerExp(loc, 1, key.type));
}
// T value = tmp[key];
value._init = new ExpInitializer(loc, new IndexExp(loc, new VarExp(loc, tmp), new VarExp(loc, key)));
Statement ds = new ExpStatement(loc, value);
if (dim == 2)
{
Parameter p = (*parameters)[0];
if ((p.storageClass & STCref) && p.type.equals(key.type))
{
key.range = null;
auto v = new AliasDeclaration(loc, p.ident, key);
_body = new CompoundStatement(loc, new ExpStatement(loc, v), _body);
}
else
{
auto ei = new ExpInitializer(loc, new IdentifierExp(loc, key.ident));
auto v = new VarDeclaration(loc, p.type, p.ident, ei);
v.storage_class |= STCforeach | (p.storageClass & STCref);
_body = new CompoundStatement(loc, new ExpStatement(loc, v), _body);
if (key.range && !p.type.isMutable())
{
/* Limit the range of the key to the specified range
*/
v.range = new IntRange(key.range.imin, key.range.imax - SignExtendedNumber(1));
}
}
}
_body = new CompoundStatement(loc, ds, _body);
s = new ForStatement(loc, forinit, cond, increment, _body, endloc);
if (LabelStatement ls = checkLabeledLoop(sc, this))
ls.gotoTarget = s;
s = s.semantic(sc);
break;
}
case Taarray:
if (op == TOKforeach_reverse)
warning("cannot use foreach_reverse with an associative array");
if (checkForArgTypes())
return this;
taa = cast(TypeAArray)tab;
if (dim < 1 || dim > 2)
{
error("only one or two arguments for associative array foreach");
goto Lerror2;
}
goto Lapply;
case Tclass:
case Tstruct:
/* Prefer using opApply, if it exists
*/
if (sapply)
goto Lapply;
{
/* Look for range iteration, i.e. the properties
* .empty, .popFront, .popBack, .front and .back
* foreach (e; aggr) { ... }
* translates to:
* for (auto __r = aggr[]; !__r.empty; __r.popFront()) {
* auto e = __r.front;
* ...
* }
*/
AggregateDeclaration ad = (tab.ty == Tclass) ? cast(AggregateDeclaration)(cast(TypeClass)tab).sym : cast(AggregateDeclaration)(cast(TypeStruct)tab).sym;
Identifier idfront;
Identifier idpopFront;
if (op == TOKforeach)
{
idfront = Id.Ffront;
idpopFront = Id.FpopFront;
}
else
{
idfront = Id.Fback;
idpopFront = Id.FpopBack;
}
Dsymbol sfront = ad.search(Loc(), idfront);
if (!sfront)
goto Lapply;
/* Generate a temporary __r and initialize it with the aggregate.
*/
VarDeclaration r;
Statement _init;
if (vinit && aggr.op == TOKvar && (cast(VarExp)aggr).var == vinit)
{
r = vinit;
_init = new ExpStatement(loc, vinit);
}
else
{
Identifier rid = Identifier.generateId("__r");
r = new VarDeclaration(loc, null, rid, new ExpInitializer(loc, aggr));
r.storage_class |= STCtemp;
_init = new ExpStatement(loc, r);
if (vinit)
_init = new CompoundStatement(loc, new ExpStatement(loc, vinit), _init);
}
// !__r.empty
Expression e = new VarExp(loc, r);
e = new DotIdExp(loc, e, Id.Fempty);
Expression condition = new NotExp(loc, e);
// __r.idpopFront()
e = new VarExp(loc, r);
Expression increment = new CallExp(loc, new DotIdExp(loc, e, idpopFront));
/* Declaration statement for e:
* auto e = __r.idfront;
*/
e = new VarExp(loc, r);
Expression einit = new DotIdExp(loc, e, idfront);
Statement makeargs, forbody;
if (dim == 1)
{
Parameter p = (*parameters)[0];
auto ve = new VarDeclaration(loc, p.type, p.ident, new ExpInitializer(loc, einit));
ve.storage_class |= STCforeach;
ve.storage_class |= p.storageClass & (STCin | STCout | STCref | STC_TYPECTOR);
makeargs = new ExpStatement(loc, ve);
}
else
{
Identifier id = Identifier.generateId("__front");
auto ei = new ExpInitializer(loc, einit);
auto vd = new VarDeclaration(loc, null, id, ei);
vd.storage_class |= STCtemp | STCctfe | STCref | STCforeach;
makeargs = new ExpStatement(loc, vd);
Declaration d = sfront.isDeclaration();
if (FuncDeclaration f = d.isFuncDeclaration())
{
if (!f.functionSemantic())
goto Lrangeerr;
}
Expression ve = new VarExp(loc, vd);
ve.type = d.type;
if (ve.type.toBasetype().ty == Tfunction)
ve.type = ve.type.toBasetype().nextOf();
if (!ve.type || ve.type.ty == Terror)
goto Lrangeerr;
// Resolve inout qualifier of front type
ve.type = ve.type.substWildTo(tab.mod);
auto exps = new Expressions();
exps.push(ve);
int pos = 0;
while (exps.dim < dim)
{
pos = expandAliasThisTuples(exps, pos);
if (pos == -1)
break;
}
if (exps.dim != dim)
{
const(char)* plural = exps.dim > 1 ? "s" : "";
error("cannot infer argument types, expected %d argument%s, not %d", exps.dim, plural, dim);
goto Lerror2;
}
foreach (i; 0 .. dim)
{
Parameter p = (*parameters)[i];
Expression exp = (*exps)[i];
version (none)
{
printf("[%d] p = %s %s, exp = %s %s\n", i, p.type ? p.type.toChars() : "?", p.ident.toChars(), exp.type.toChars(), exp.toChars());
}
if (!p.type)
p.type = exp.type;
p.type = p.type.addStorageClass(p.storageClass).semantic(loc, sc);
if (!exp.implicitConvTo(p.type))
goto Lrangeerr;
auto var = new VarDeclaration(loc, p.type, p.ident, new ExpInitializer(loc, exp));
var.storage_class |= STCctfe | STCref | STCforeach;
makeargs = new CompoundStatement(loc, makeargs, new ExpStatement(loc, var));
}
}
forbody = new CompoundStatement(loc, makeargs, this._body);
s = new ForStatement(loc, _init, condition, increment, forbody, endloc);
if (LabelStatement ls = checkLabeledLoop(sc, this))
ls.gotoTarget = s;
version (none)
{
printf("init: %s\n", _init.toChars());
printf("condition: %s\n", condition.toChars());
printf("increment: %s\n", increment.toChars());
printf("body: %s\n", forbody.toChars());
}
s = s.semantic(sc);
break;
Lrangeerr:
error("cannot infer argument types");
goto Lerror2;
}
case Tdelegate:
if (op == TOKforeach_reverse)
deprecation("cannot use foreach_reverse with a delegate");
Lapply:
{
if (checkForArgTypes())
{
_body = _body.semanticNoScope(sc);
return this;
}
TypeFunction tfld = null;
if (sapply)
{
FuncDeclaration fdapply = sapply.isFuncDeclaration();
if (fdapply)
{
assert(fdapply.type && fdapply.type.ty == Tfunction);
tfld = cast(TypeFunction)fdapply.type.semantic(loc, sc);
goto Lget;
}
else if (tab.ty == Tdelegate)
{
tfld = cast(TypeFunction)tab.nextOf();
Lget:
//printf("tfld = %s\n", tfld->toChars());
if (tfld.parameters.dim == 1)
{
Parameter p = Parameter.getNth(tfld.parameters, 0);
if (p.type && p.type.ty == Tdelegate)
{
Type t = p.type.semantic(loc, sc);
assert(t.ty == Tdelegate);
tfld = cast(TypeFunction)t.nextOf();
}
}
}
}
/* Turn body into the function literal:
* int delegate(ref T param) { body }
*/
auto params = new Parameters();
foreach (i; 0 .. dim)
{
Parameter p = (*parameters)[i];
StorageClass stc = STCref;
Identifier id;
p.type = p.type.semantic(loc, sc);
p.type = p.type.addStorageClass(p.storageClass);
if (tfld)
{
Parameter prm = Parameter.getNth(tfld.parameters, i);
//printf("\tprm = %s%s\n", (prm->storageClass&STCref?"ref ":""), prm->ident->toChars());
stc = prm.storageClass & STCref;
id = p.ident; // argument copy is not need.
if ((p.storageClass & STCref) != stc)
{
if (!stc)
{
error("foreach: cannot make %s ref", p.ident.toChars());
goto Lerror2;
}
goto LcopyArg;
}
}
else if (p.storageClass & STCref)
{
// default delegate parameters are marked as ref, then
// argument copy is not need.
id = p.ident;
}
else
{
// Make a copy of the ref argument so it isn't
// a reference.
LcopyArg:
id = Identifier.generateId("__applyArg", cast(int)i);
Initializer ie = new ExpInitializer(Loc(), new IdentifierExp(Loc(), id));
auto v = new VarDeclaration(Loc(), p.type, p.ident, ie);
v.storage_class |= STCtemp;
s = new ExpStatement(Loc(), v);
_body = new CompoundStatement(loc, s, _body);
}
params.push(new Parameter(stc, p.type, id, null));
}
// Bugzilla 13840: Throwable nested function inside nothrow function is acceptable.
StorageClass stc = mergeFuncAttrs(STCsafe | STCpure | STCnogc, func);
tfld = new TypeFunction(params, Type.tint32, 0, LINKd, stc);
cases = new Statements();
gotos = new ScopeStatements();
auto fld = new FuncLiteralDeclaration(loc, Loc(), tfld, TOKdelegate, this);
fld.fbody = _body;
Expression flde = new FuncExp(loc, fld);
flde = flde.semantic(sc);
fld.tookAddressOf = 0;
// Resolve any forward referenced goto's
foreach (i; 0 .. gotos.dim)
{
GotoStatement gs = cast(GotoStatement)(*gotos)[i].statement;
if (!gs.label.statement)
{
// 'Promote' it to this scope, and replace with a return
cases.push(gs);
s = new ReturnStatement(Loc(), new IntegerExp(cases.dim + 1));
(*gotos)[i].statement = s;
}
}
Expression e = null;
Expression ec;
if (vinit)
{
e = new DeclarationExp(loc, vinit);
e = e.semantic(sc);
if (e.op == TOKerror)
goto Lerror2;
}
if (taa)
{
// Check types
Parameter p = (*parameters)[0];
bool isRef = (p.storageClass & STCref) != 0;
Type ta = p.type;
if (dim == 2)
{
Type ti = (isRef ? taa.index.addMod(MODconst) : taa.index);
if (isRef ? !ti.constConv(ta) : !ti.implicitConvTo(ta))
{
error("foreach: index must be type %s, not %s", ti.toChars(), ta.toChars());
goto Lerror2;
}
p = (*parameters)[1];
isRef = (p.storageClass & STCref) != 0;
ta = p.type;
}
Type taav = taa.nextOf();
if (isRef ? !taav.constConv(ta) : !taav.implicitConvTo(ta))
{
error("foreach: value must be type %s, not %s", taav.toChars(), ta.toChars());
goto Lerror2;
}
/* Call:
* extern(C) int _aaApply(void*, in size_t, int delegate(void*))
* _aaApply(aggr, keysize, flde)
*
* extern(C) int _aaApply2(void*, in size_t, int delegate(void*, void*))
* _aaApply2(aggr, keysize, flde)
*/
static __gshared const(char)** name = ["_aaApply", "_aaApply2"];
static __gshared FuncDeclaration* fdapply = [null, null];
static __gshared TypeDelegate* fldeTy = [null, null];
ubyte i = (dim == 2 ? 1 : 0);
if (!fdapply[i])
{
params = new Parameters();
params.push(new Parameter(0, Type.tvoid.pointerTo(), null, null));
params.push(new Parameter(STCin, Type.tsize_t, null, null));
auto dgparams = new Parameters();
dgparams.push(new Parameter(0, Type.tvoidptr, null, null));
if (dim == 2)
dgparams.push(new Parameter(0, Type.tvoidptr, null, null));
fldeTy[i] = new TypeDelegate(new TypeFunction(dgparams, Type.tint32, 0, LINKd));
params.push(new Parameter(0, fldeTy[i], null, null));
fdapply[i] = FuncDeclaration.genCfunc(params, Type.tint32, name[i]);
}
auto exps = new Expressions();
exps.push(aggr);
size_t keysize = cast(size_t)taa.index.size();
keysize = (keysize + (cast(size_t)Target.ptrsize - 1)) & ~(cast(size_t)Target.ptrsize - 1);
// paint delegate argument to the type runtime expects
if (!fldeTy[i].equals(flde.type))
{
flde = new CastExp(loc, flde, flde.type);
flde.type = fldeTy[i];
}
exps.push(new IntegerExp(Loc(), keysize, Type.tsize_t));
exps.push(flde);
ec = new VarExp(Loc(), fdapply[i]);
ec = new CallExp(loc, ec, exps);
ec.type = Type.tint32; // don't run semantic() on ec
}
else if (tab.ty == Tarray || tab.ty == Tsarray)
{
/* Call:
* _aApply(aggr, flde)
*/
static __gshared const(char)** fntab = ["cc", "cw", "cd", "wc", "cc", "wd", "dc", "dw", "dd"];
const(size_t) BUFFER_LEN = 7 + 1 + 2 + dim.sizeof * 3 + 1;
char[BUFFER_LEN] fdname;
int flag;
switch (tn.ty)
{
case Tchar:
flag = 0;
break;
case Twchar:
flag = 3;
break;
case Tdchar:
flag = 6;
break;
default:
assert(0);
}
switch (tnv.ty)
{
case Tchar:
flag += 0;
break;
case Twchar:
flag += 1;
break;
case Tdchar:
flag += 2;
break;
default:
assert(0);
}
const(char)* r = (op == TOKforeach_reverse) ? "R" : "";
int j = sprintf(fdname.ptr, "_aApply%s%.*s%llu", r, 2, fntab[flag], cast(ulong)dim);
assert(j < BUFFER_LEN);
FuncDeclaration fdapply;
TypeDelegate dgty;
params = new Parameters();
params.push(new Parameter(STCin, tn.arrayOf(), null, null));
auto dgparams = new Parameters();
dgparams.push(new Parameter(0, Type.tvoidptr, null, null));
if (dim == 2)
dgparams.push(new Parameter(0, Type.tvoidptr, null, null));
dgty = new TypeDelegate(new TypeFunction(dgparams, Type.tint32, 0, LINKd));
params.push(new Parameter(0, dgty, null, null));
fdapply = FuncDeclaration.genCfunc(params, Type.tint32, fdname.ptr);
if (tab.ty == Tsarray)
aggr = aggr.castTo(sc, tn.arrayOf());
// paint delegate argument to the type runtime expects
if (!dgty.equals(flde.type))
{
flde = new CastExp(loc, flde, flde.type);
flde.type = dgty;
}
ec = new VarExp(Loc(), fdapply);
ec = new CallExp(loc, ec, aggr, flde);
ec.type = Type.tint32; // don't run semantic() on ec
}
else if (tab.ty == Tdelegate)
{
/* Call:
* aggr(flde)
*/
if (aggr.op == TOKdelegate && (cast(DelegateExp)aggr).func.isNested())
{
// See Bugzilla 3560
aggr = (cast(DelegateExp)aggr).e1;
}
ec = new CallExp(loc, aggr, flde);
ec = ec.semantic(sc);
if (ec.op == TOKerror)
goto Lerror2;
if (ec.type != Type.tint32)
{
error("opApply() function for %s must return an int", tab.toChars());
goto Lerror2;
}
}
else
{
assert(tab.ty == Tstruct || tab.ty == Tclass);
assert(sapply);
/* Call:
* aggr.apply(flde)
*/
ec = new DotIdExp(loc, aggr, sapply.ident);
ec = new CallExp(loc, ec, flde);
ec = ec.semantic(sc);
if (ec.op == TOKerror)
goto Lerror2;
if (ec.type != Type.tint32)
{
error("opApply() function for %s must return an int", tab.toChars());
goto Lerror2;
}
}
e = Expression.combine(e, ec);
if (!cases.dim)
{
// Easy case, a clean exit from the loop
e = new CastExp(loc, e, Type.tvoid); // Bugzilla 13899
s = new ExpStatement(loc, e);
}
else
{
// Construct a switch statement around the return value
// of the apply function.
auto a = new Statements();
// default: break; takes care of cases 0 and 1
s = new BreakStatement(Loc(), null);
s = new DefaultStatement(Loc(), s);
a.push(s);
// cases 2...
foreach (i, c; *cases)
{
s = new CaseStatement(Loc(), new IntegerExp(i + 2), c);
a.push(s);
}
s = new CompoundStatement(loc, a);
s = new SwitchStatement(loc, e, s, false);
}
s = s.semantic(sc);
break;
}
case Terror:
Lerror2:
s = new ErrorStatement();
break;
default:
error("foreach: %s is not an aggregate type", aggr.type.toChars());
goto Lerror2;
}
sc.noctor--;
sc.pop();
return s;
}
bool checkForArgTypes()
{
bool result = false;
foreach (p; *parameters)
{
if (!p.type)
{
error("cannot infer type for %s", p.ident.toChars());
p.type = Type.terror;
result = true;
}
}
return result;
}
override bool hasBreak()
{
return true;
}
override bool hasContinue()
{
return true;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ForeachRangeStatement : Statement
{
public:
TOK op; // TOKforeach or TOKforeach_reverse
Parameter prm; // loop index variable
Expression lwr;
Expression upr;
Statement _body;
Loc endloc; // location of closing curly bracket
VarDeclaration key;
extern (D) this(Loc loc, TOK op, Parameter prm, Expression lwr, Expression upr, Statement _body, Loc endloc)
{
super(loc);
this.op = op;
this.prm = prm;
this.lwr = lwr;
this.upr = upr;
this._body = _body;
this.endloc = endloc;
}
override Statement syntaxCopy()
{
return new ForeachRangeStatement(loc, op, prm.syntaxCopy(), lwr.syntaxCopy(), upr.syntaxCopy(), _body ? _body.syntaxCopy() : null, endloc);
}
override Statement semantic(Scope* sc)
{
//printf("ForeachRangeStatement::semantic() %p\n", this);
lwr = lwr.semantic(sc);
lwr = resolveProperties(sc, lwr);
lwr = lwr.optimize(WANTvalue);
if (!lwr.type)
{
error("invalid range lower bound %s", lwr.toChars());
Lerror:
return new ErrorStatement();
}
upr = upr.semantic(sc);
upr = resolveProperties(sc, upr);
upr = upr.optimize(WANTvalue);
if (!upr.type)
{
error("invalid range upper bound %s", upr.toChars());
goto Lerror;
}
if (prm.type)
{
prm.type = prm.type.semantic(loc, sc);
prm.type = prm.type.addStorageClass(prm.storageClass);
lwr = lwr.implicitCastTo(sc, prm.type);
if (upr.implicitConvTo(prm.type) || (prm.storageClass & STCref))
{
upr = upr.implicitCastTo(sc, prm.type);
}
else
{
// See if upr-1 fits in prm->type
Expression limit = new MinExp(loc, upr, new IntegerExp(1));
limit = limit.semantic(sc);
limit = limit.optimize(WANTvalue);
if (!limit.implicitConvTo(prm.type))
{
upr = upr.implicitCastTo(sc, prm.type);
}
}
}
else
{
/* Must infer types from lwr and upr
*/
Type tlwr = lwr.type.toBasetype();
if (tlwr.ty == Tstruct || tlwr.ty == Tclass)
{
/* Just picking the first really isn't good enough.
*/
prm.type = lwr.type;
}
else if (lwr.type == upr.type)
{
/* Same logic as CondExp ?lwr:upr
*/
prm.type = lwr.type;
}
else
{
scope AddExp ea = new AddExp(loc, lwr, upr);
if (typeCombine(ea, sc))
return new ErrorStatement();
prm.type = ea.type;
lwr = ea.e1;
upr = ea.e2;
}
prm.type = prm.type.addStorageClass(prm.storageClass);
}
if (prm.type.ty == Terror || lwr.op == TOKerror || upr.op == TOKerror)
{
return new ErrorStatement();
}
/* Convert to a for loop:
* foreach (key; lwr .. upr) =>
* for (auto key = lwr, auto tmp = upr; key < tmp; ++key)
*
* foreach_reverse (key; lwr .. upr) =>
* for (auto tmp = lwr, auto key = upr; key-- > tmp;)
*/
auto ie = new ExpInitializer(loc, (op == TOKforeach) ? lwr : upr);
key = new VarDeclaration(loc, upr.type.mutableOf(), Identifier.generateId("__key"), ie);
key.storage_class |= STCtemp;
SignExtendedNumber lower = getIntRange(lwr).imin;
SignExtendedNumber upper = getIntRange(upr).imax;
if (lower <= upper)
{
key.range = new IntRange(lower, upper);
}
Identifier id = Identifier.generateId("__limit");
ie = new ExpInitializer(loc, (op == TOKforeach) ? upr : lwr);
auto tmp = new VarDeclaration(loc, upr.type, id, ie);
tmp.storage_class |= STCtemp;
auto cs = new Statements();
// Keep order of evaluation as lwr, then upr
if (op == TOKforeach)
{
cs.push(new ExpStatement(loc, key));
cs.push(new ExpStatement(loc, tmp));
}
else
{
cs.push(new ExpStatement(loc, tmp));
cs.push(new ExpStatement(loc, key));
}
Statement forinit = new CompoundDeclarationStatement(loc, cs);
Expression cond;
if (op == TOKforeach_reverse)
{
cond = new PostExp(TOKminusminus, loc, new VarExp(loc, key));
if (prm.type.isscalar())
{
// key-- > tmp
cond = new CmpExp(TOKgt, loc, cond, new VarExp(loc, tmp));
}
else
{
// key-- != tmp
cond = new EqualExp(TOKnotequal, loc, cond, new VarExp(loc, tmp));
}
}
else
{
if (prm.type.isscalar())
{
// key < tmp
cond = new CmpExp(TOKlt, loc, new VarExp(loc, key), new VarExp(loc, tmp));
}
else
{
// key != tmp
cond = new EqualExp(TOKnotequal, loc, new VarExp(loc, key), new VarExp(loc, tmp));
}
}
Expression increment = null;
if (op == TOKforeach)
{
// key += 1
//increment = new AddAssignExp(loc, new VarExp(loc, key), new IntegerExp(1));
increment = new PreExp(TOKpreplusplus, loc, new VarExp(loc, key));
}
if ((prm.storageClass & STCref) && prm.type.equals(key.type))
{
key.range = null;
auto v = new AliasDeclaration(loc, prm.ident, key);
_body = new CompoundStatement(loc, new ExpStatement(loc, v), _body);
}
else
{
ie = new ExpInitializer(loc, new CastExp(loc, new VarExp(loc, key), prm.type));
auto v = new VarDeclaration(loc, prm.type, prm.ident, ie);
v.storage_class |= STCtemp | STCforeach | (prm.storageClass & STCref);
_body = new CompoundStatement(loc, new ExpStatement(loc, v), _body);
if (key.range && !prm.type.isMutable())
{
/* Limit the range of the key to the specified range
*/
v.range = new IntRange(key.range.imin, key.range.imax - SignExtendedNumber(1));
}
}
if (prm.storageClass & STCref)
{
if (key.type.constConv(prm.type) <= MATCHnomatch)
{
error("prmument type mismatch, %s to ref %s", key.type.toChars(), prm.type.toChars());
goto Lerror;
}
}
auto s = new ForStatement(loc, forinit, cond, increment, _body, endloc);
if (LabelStatement ls = checkLabeledLoop(sc, this))
ls.gotoTarget = s;
return s.semantic(sc);
}
override bool hasBreak()
{
return true;
}
override bool hasContinue()
{
return true;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class IfStatement : Statement
{
public:
Parameter prm;
Expression condition;
Statement ifbody;
Statement elsebody;
VarDeclaration match; // for MatchExpression results
extern (D) this(Loc loc, Parameter prm, Expression condition, Statement ifbody, Statement elsebody)
{
super(loc);
this.prm = prm;
this.condition = condition;
this.ifbody = ifbody;
this.elsebody = elsebody;
}
override Statement syntaxCopy()
{
return new IfStatement(loc, prm ? prm.syntaxCopy() : null, condition.syntaxCopy(), ifbody ? ifbody.syntaxCopy() : null, elsebody ? elsebody.syntaxCopy() : null);
}
override Statement semantic(Scope* sc)
{
// Evaluate at runtime
uint cs0 = sc.callSuper;
uint cs1;
uint* fi0 = sc.saveFieldInit();
uint* fi1 = null;
auto sym = new ScopeDsymbol();
sym.parent = sc.scopesym;
Scope* scd = sc.push(sym);
if (prm)
{
/* Declare prm, which we will set to be the
* result of condition.
*/
match = new VarDeclaration(loc, prm.type, prm.ident, new ExpInitializer(loc, condition));
match.parent = scd.func;
match.storage_class |= prm.storageClass;
match.semantic(scd);
auto de = new DeclarationExp(loc, match);
auto ve = new VarExp(loc, match);
condition = new CommaExp(loc, de, ve);
condition = condition.semantic(scd);
if (match.edtor)
{
Statement sdtor = new ExpStatement(loc, match.edtor);
sdtor = new OnScopeStatement(loc, TOKon_scope_exit, sdtor);
ifbody = new CompoundStatement(loc, sdtor, ifbody);
match.noscope = 1;
}
}
else
{
condition = condition.semantic(scd);
condition = resolveProperties(scd, condition);
condition = condition.addDtorHook(scd);
}
condition = checkGC(scd, condition);
// Convert to boolean after declaring prm so this works:
// if (S prm = S()) {}
// where S is a struct that defines opCast!bool.
condition = condition.toBoolean(scd);
// If we can short-circuit evaluate the if statement, don't do the
// semantic analysis of the skipped code.
// This feature allows a limited form of conditional compilation.
condition = condition.optimize(WANTvalue);
ifbody = ifbody.semanticNoScope(scd);
scd.pop();
cs1 = sc.callSuper;
fi1 = sc.fieldinit;
sc.callSuper = cs0;
sc.fieldinit = fi0;
if (elsebody)
elsebody = elsebody.semanticScope(sc, null, null);
sc.mergeCallSuper(loc, cs1);
sc.mergeFieldInit(loc, fi1);
if (condition.op == TOKerror ||
(ifbody && ifbody.isErrorStatement()) ||
(elsebody && elsebody.isErrorStatement()))
{
return new ErrorStatement();
}
return this;
}
override IfStatement isIfStatement()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ConditionalStatement : Statement
{
public:
Condition condition;
Statement ifbody;
Statement elsebody;
extern (D) this(Loc loc, Condition condition, Statement ifbody, Statement elsebody)
{
super(loc);
this.condition = condition;
this.ifbody = ifbody;
this.elsebody = elsebody;
}
override Statement syntaxCopy()
{
return new ConditionalStatement(loc, condition.syntaxCopy(), ifbody.syntaxCopy(), elsebody ? elsebody.syntaxCopy() : null);
}
override Statement semantic(Scope* sc)
{
//printf("ConditionalStatement::semantic()\n");
// If we can short-circuit evaluate the if statement, don't do the
// semantic analysis of the skipped code.
// This feature allows a limited form of conditional compilation.
if (condition.include(sc, null))
{
DebugCondition dc = condition.isDebugCondition();
if (dc)
{
sc = sc.push();
sc.flags |= SCOPEdebug;
ifbody = ifbody.semantic(sc);
sc.pop();
}
else
ifbody = ifbody.semantic(sc);
return ifbody;
}
else
{
if (elsebody)
elsebody = elsebody.semantic(sc);
return elsebody;
}
}
override Statements* flatten(Scope* sc)
{
Statement s;
//printf("ConditionalStatement::flatten()\n");
if (condition.include(sc, null))
{
DebugCondition dc = condition.isDebugCondition();
if (dc)
s = new DebugStatement(loc, ifbody);
else
s = ifbody;
}
else
s = elsebody;
auto a = new Statements();
a.push(s);
return a;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class PragmaStatement : Statement
{
public:
Identifier ident;
Expressions* args; // array of Expression's
Statement _body;
extern (D) this(Loc loc, Identifier ident, Expressions* args, Statement _body)
{
super(loc);
this.ident = ident;
this.args = args;
this._body = _body;
}
override Statement syntaxCopy()
{
return new PragmaStatement(loc, ident, Expression.arraySyntaxCopy(args), _body ? _body.syntaxCopy() : null);
}
override Statement semantic(Scope* sc)
{
// Should be merged with PragmaDeclaration
//printf("PragmaStatement::semantic() %s\n", toChars());
//printf("body = %p\n", body);
if (ident == Id.msg)
{
if (args)
{
foreach (arg; *args)
{
sc = sc.startCTFE();
auto e = arg.semantic(sc);
e = resolveProperties(sc, e);
sc = sc.endCTFE();
// pragma(msg) is allowed to contain types as well as expressions
e = ctfeInterpretForPragmaMsg(e);
if (e.op == TOKerror)
{
errorSupplemental(loc, "while evaluating pragma(msg, %s)", arg.toChars());
goto Lerror;
}
StringExp se = e.toStringExp();
if (se)
{
se = se.toUTF8(sc);
fprintf(stderr, "%.*s", cast(int)se.len, cast(char*)se.string);
}
else
fprintf(stderr, "%s", e.toChars());
}
fprintf(stderr, "\n");
}
}
else if (ident == Id.lib)
{
version (all)
{
/* Should this be allowed?
*/
error("pragma(lib) not allowed as statement");
goto Lerror;
}
else
{
if (!args || args.dim != 1)
{
error("string expected for library name");
goto Lerror;
}
else
{
Expression e = (*args)[0];
sc = sc.startCTFE();
e = e.semantic(sc);
e = resolveProperties(sc, e);
sc = sc.endCTFE();
e = e.ctfeInterpret();
(*args)[0] = e;
StringExp se = e.toStringExp();
if (!se)
{
error("string expected for library name, not '%s'", e.toChars());
goto Lerror;
}
else if (global.params.verbose)
{
char* name = cast(char*)mem.malloc(se.len + 1);
memcpy(name, se.string, se.len);
name[se.len] = 0;
fprintf(global.stdmsg, "library %s\n", name);
mem.free(name);
}
}
}
}
else if (ident == Id.startaddress)
{
if (!args || args.dim != 1)
error("function name expected for start address");
else
{
Expression e = (*args)[0];
sc = sc.startCTFE();
e = e.semantic(sc);
e = resolveProperties(sc, e);
sc = sc.endCTFE();
e = e.ctfeInterpret();
(*args)[0] = e;
Dsymbol sa = getDsymbol(e);
if (!sa || !sa.isFuncDeclaration())
{
error("function name expected for start address, not '%s'", e.toChars());
goto Lerror;
}
if (_body)
{
_body = _body.semantic(sc);
if (_body.isErrorStatement())
return _body;
}
return this;
}
}
else if (ident == Id.Pinline)
{
PINLINE inlining = PINLINEdefault;
if (!args || args.dim == 0)
inlining = PINLINEdefault;
else if (!args || args.dim != 1)
{
error("boolean expression expected for pragma(inline)");
goto Lerror;
}
else
{
Expression e = (*args)[0];
if (e.op != TOKint64 || !e.type.equals(Type.tbool))
{
error("pragma(inline, true or false) expected, not %s", e.toChars());
goto Lerror;
}
if (e.isBool(true))
inlining = PINLINEalways;
else if (e.isBool(false))
inlining = PINLINEnever;
FuncDeclaration fd = sc.func;
if (!fd)
{
error("pragma(inline) is not inside a function");
goto Lerror;
}
fd.inlining = inlining;
}
}
else
{
error("unrecognized pragma(%s)", ident.toChars());
goto Lerror;
}
if (_body)
{
_body = _body.semantic(sc);
}
return _body;
Lerror:
return new ErrorStatement();
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class StaticAssertStatement : Statement
{
public:
StaticAssert sa;
extern (D) this(StaticAssert sa)
{
super(sa.loc);
this.sa = sa;
}
override Statement syntaxCopy()
{
return new StaticAssertStatement(cast(StaticAssert)sa.syntaxCopy(null));
}
override Statement semantic(Scope* sc)
{
sa.semantic2(sc);
return null;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class SwitchStatement : Statement
{
public:
Expression condition;
Statement _body;
bool isFinal;
DefaultStatement sdefault;
TryFinallyStatement tf;
GotoCaseStatements gotoCases; // array of unresolved GotoCaseStatement's
CaseStatements* cases; // array of CaseStatement's
int hasNoDefault; // !=0 if no default statement
int hasVars; // !=0 if has variable case values
extern (D) this(Loc loc, Expression c, Statement b, bool isFinal)
{
super(loc);
this.condition = c;
this._body = b;
this.isFinal = isFinal;
}
override Statement syntaxCopy()
{
return new SwitchStatement(loc, condition.syntaxCopy(), _body.syntaxCopy(), isFinal);
}
override Statement semantic(Scope* sc)
{
//printf("SwitchStatement::semantic(%p)\n", this);
tf = sc.tf;
if (cases)
return this; // already run
bool conditionError = false;
condition = condition.semantic(sc);
condition = resolveProperties(sc, condition);
TypeEnum te = null;
// preserve enum type for final switches
if (condition.type.ty == Tenum)
te = cast(TypeEnum)condition.type;
if (condition.type.isString())
{
// If it's not an array, cast it to one
if (condition.type.ty != Tarray)
{
condition = condition.implicitCastTo(sc, condition.type.nextOf().arrayOf());
}
condition.type = condition.type.constOf();
}
else
{
condition = integralPromotions(condition, sc);
if (condition.op != TOKerror && !condition.type.isintegral())
{
error("'%s' must be of integral or string type, it is a %s", condition.toChars(), condition.type.toChars());
conditionError = true;
}
}
condition = condition.optimize(WANTvalue);
condition = checkGC(sc, condition);
if (condition.op == TOKerror)
conditionError = true;
bool needswitcherror = false;
sc = sc.push();
sc.sbreak = this;
sc.sw = this;
cases = new CaseStatements();
sc.noctor++; // BUG: should use Scope::mergeCallSuper() for each case instead
_body = _body.semantic(sc);
sc.noctor--;
if (conditionError || _body.isErrorStatement())
goto Lerror;
// Resolve any goto case's with exp
foreach (gcs; gotoCases)
{
if (!gcs.exp)
{
gcs.error("no case statement following goto case;");
goto Lerror;
}
for (Scope* scx = sc; scx; scx = scx.enclosing)
{
if (!scx.sw)
continue;
foreach (cs; *scx.sw.cases)
{
if (cs.exp.equals(gcs.exp))
{
gcs.cs = cs;
goto Lfoundcase;
}
}
}
gcs.error("case %s not found", gcs.exp.toChars());
goto Lerror;
Lfoundcase:
}
if (isFinal)
{
Type t = condition.type;
Dsymbol ds;
EnumDeclaration ed = null;
if (t && ((ds = t.toDsymbol(sc)) !is null))
ed = ds.isEnumDeclaration(); // typedef'ed enum
if (!ed && te && ((ds = te.toDsymbol(sc)) !is null))
ed = ds.isEnumDeclaration();
if (ed)
{
foreach (es; *ed.members)
{
EnumMember em = es.isEnumMember();
if (em)
{
foreach (cs; *cases)
{
if (cs.exp.equals(em.value) || (!cs.exp.type.isString() && !em.value.type.isString() && cs.exp.toInteger() == em.value.toInteger()))
goto L1;
}
error("enum member %s not represented in final switch", em.toChars());
goto Lerror;
}
L1:
}
}
else
needswitcherror = true;
}
if (!sc.sw.sdefault && (!isFinal || needswitcherror || global.params.useAssert))
{
hasNoDefault = 1;
if (!isFinal && !_body.isErrorStatement())
error("switch statement without a default; use 'final switch' or add 'default: assert(0);' or add 'default: break;'");
// Generate runtime error if the default is hit
auto a = new Statements();
CompoundStatement cs;
Statement s;
if (global.params.useSwitchError)
s = new SwitchErrorStatement(loc);
else
s = new ExpStatement(loc, new HaltExp(loc));
a.reserve(2);
sc.sw.sdefault = new DefaultStatement(loc, s);
a.push(_body);
if (_body.blockExit(sc.func, false) & BEfallthru)
a.push(new BreakStatement(Loc(), null));
a.push(sc.sw.sdefault);
cs = new CompoundStatement(loc, a);
_body = cs;
}
sc.pop();
return this;
Lerror:
sc.pop();
return new ErrorStatement();
}
override bool hasBreak()
{
return true;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class CaseStatement : Statement
{
public:
Expression exp;
Statement statement;
int index; // which case it is (since we sort this)
extern (D) this(Loc loc, Expression exp, Statement s)
{
super(loc);
this.exp = exp;
this.statement = s;
}
override Statement syntaxCopy()
{
return new CaseStatement(loc, exp.syntaxCopy(), statement.syntaxCopy());
}
override Statement semantic(Scope* sc)
{
SwitchStatement sw = sc.sw;
bool errors = false;
//printf("CaseStatement::semantic() %s\n", toChars());
sc = sc.startCTFE();
exp = exp.semantic(sc);
exp = resolveProperties(sc, exp);
sc = sc.endCTFE();
if (sw)
{
exp = exp.implicitCastTo(sc, sw.condition.type);
exp = exp.optimize(WANTvalue);
/* This is where variables are allowed as case expressions.
*/
if (exp.op == TOKvar)
{
VarExp ve = cast(VarExp)exp;
VarDeclaration v = ve.var.isVarDeclaration();
Type t = exp.type.toBasetype();
if (v && (t.isintegral() || t.ty == Tclass))
{
/* Flag that we need to do special code generation
* for this, i.e. generate a sequence of if-then-else
*/
sw.hasVars = 1;
if (sw.isFinal)
{
error("case variables not allowed in final switch statements");
errors = true;
}
goto L1;
}
}
else
exp = exp.ctfeInterpret();
if (StringExp se = exp.toStringExp())
exp = se;
else if (exp.op != TOKint64 && exp.op != TOKerror)
{
error("case must be a string or an integral constant, not %s", exp.toChars());
errors = true;
}
L1:
foreach (cs; *sw.cases)
{
//printf("comparing '%s' with '%s'\n", exp->toChars(), cs->exp->toChars());
if (cs.exp.equals(exp))
{
error("duplicate case %s in switch statement", exp.toChars());
errors = true;
break;
}
}
sw.cases.push(this);
// Resolve any goto case's with no exp to this case statement
for (size_t i = 0; i < sw.gotoCases.dim;)
{
GotoCaseStatement gcs = sw.gotoCases[i];
if (!gcs.exp)
{
gcs.cs = this;
sw.gotoCases.remove(i); // remove from array
continue;
}
i++;
}
if (sc.sw.tf != sc.tf)
{
error("switch and case are in different finally blocks");
errors = true;
}
}
else
{
error("case not in switch statement");
errors = true;
}
statement = statement.semantic(sc);
if (statement.isErrorStatement())
return statement;
if (errors || exp.op == TOKerror)
return new ErrorStatement();
return this;
}
override int compare(RootObject obj)
{
// Sort cases so we can do an efficient lookup
CaseStatement cs2 = cast(CaseStatement)obj;
return exp.compare(cs2.exp);
}
override CaseStatement isCaseStatement()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class CaseRangeStatement : Statement
{
public:
Expression first;
Expression last;
Statement statement;
extern (D) this(Loc loc, Expression first, Expression last, Statement s)
{
super(loc);
this.first = first;
this.last = last;
this.statement = s;
}
override Statement syntaxCopy()
{
return new CaseRangeStatement(loc, first.syntaxCopy(), last.syntaxCopy(), statement.syntaxCopy());
}
override Statement semantic(Scope* sc)
{
SwitchStatement sw = sc.sw;
if (sw is null)
{
error("case range not in switch statement");
return new ErrorStatement();
}
//printf("CaseRangeStatement::semantic() %s\n", toChars());
bool errors = false;
if (sw.isFinal)
{
error("case ranges not allowed in final switch");
errors = true;
}
sc = sc.startCTFE();
first = first.semantic(sc);
first = resolveProperties(sc, first);
sc = sc.endCTFE();
first = first.implicitCastTo(sc, sw.condition.type);
first = first.ctfeInterpret();
sc = sc.startCTFE();
last = last.semantic(sc);
last = resolveProperties(sc, last);
sc = sc.endCTFE();
last = last.implicitCastTo(sc, sw.condition.type);
last = last.ctfeInterpret();
if (first.op == TOKerror || last.op == TOKerror || errors)
{
if (statement)
statement.semantic(sc);
return new ErrorStatement();
}
uinteger_t fval = first.toInteger();
uinteger_t lval = last.toInteger();
if ((first.type.isunsigned() && fval > lval) || (!first.type.isunsigned() && cast(sinteger_t)fval > cast(sinteger_t)lval))
{
error("first case %s is greater than last case %s", first.toChars(), last.toChars());
errors = true;
lval = fval;
}
if (lval - fval > 256)
{
error("had %llu cases which is more than 256 cases in case range", lval - fval);
errors = true;
lval = fval + 256;
}
if (errors)
return new ErrorStatement();
/* This works by replacing the CaseRange with an array of Case's.
*
* case a: .. case b: s;
* =>
* case a:
* [...]
* case b:
* s;
*/
auto statements = new Statements();
for (uinteger_t i = fval; i != lval + 1; i++)
{
Statement s = statement;
if (i != lval) // if not last case
s = new ExpStatement(loc, cast(Expression)null);
Expression e = new IntegerExp(loc, i, first.type);
Statement cs = new CaseStatement(loc, e, s);
statements.push(cs);
}
Statement s = new CompoundStatement(loc, statements);
s = s.semantic(sc);
return s;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class DefaultStatement : Statement
{
public:
Statement statement;
extern (D) this(Loc loc, Statement s)
{
super(loc);
this.statement = s;
}
override Statement syntaxCopy()
{
return new DefaultStatement(loc, statement.syntaxCopy());
}
override Statement semantic(Scope* sc)
{
//printf("DefaultStatement::semantic()\n");
bool errors = false;
if (sc.sw)
{
if (sc.sw.sdefault)
{
error("switch statement already has a default");
errors = true;
}
sc.sw.sdefault = this;
if (sc.sw.tf != sc.tf)
{
error("switch and default are in different finally blocks");
errors = true;
}
if (sc.sw.isFinal)
{
error("default statement not allowed in final switch statement");
errors = true;
}
}
else
{
error("default not in switch statement");
errors = true;
}
statement = statement.semantic(sc);
if (errors || statement.isErrorStatement())
return new ErrorStatement();
return this;
}
override DefaultStatement isDefaultStatement()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class GotoDefaultStatement : Statement
{
public:
SwitchStatement sw;
extern (D) this(Loc loc)
{
super(loc);
}
override Statement syntaxCopy()
{
return new GotoDefaultStatement(loc);
}
override Statement semantic(Scope* sc)
{
sw = sc.sw;
if (!sw)
{
error("goto default not in switch statement");
return new ErrorStatement();
}
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class GotoCaseStatement : Statement
{
public:
Expression exp; // null, or which case to goto
CaseStatement cs; // case statement it resolves to
extern (D) this(Loc loc, Expression exp)
{
super(loc);
this.exp = exp;
}
override Statement syntaxCopy()
{
return new GotoCaseStatement(loc, exp ? exp.syntaxCopy() : null);
}
override Statement semantic(Scope* sc)
{
if (!sc.sw)
{
error("goto case not in switch statement");
return new ErrorStatement();
}
if (exp)
{
exp = exp.semantic(sc);
exp = exp.implicitCastTo(sc, sc.sw.condition.type);
exp = exp.optimize(WANTvalue);
if (exp.op == TOKerror)
return new ErrorStatement();
}
sc.sw.gotoCases.push(this);
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class SwitchErrorStatement : Statement
{
public:
extern (D) this(Loc loc)
{
super(loc);
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ReturnStatement : Statement
{
public:
Expression exp;
size_t caseDim;
extern (D) this(Loc loc, Expression exp)
{
super(loc);
this.exp = exp;
}
override Statement syntaxCopy()
{
return new ReturnStatement(loc, exp ? exp.syntaxCopy() : null);
}
override Statement semantic(Scope* sc)
{
//printf("ReturnStatement::semantic() %s\n", toChars());
FuncDeclaration fd = sc.parent.isFuncDeclaration();
if (fd.fes)
fd = fd.fes.func; // fd is now function enclosing foreach
TypeFunction tf = cast(TypeFunction)fd.type;
assert(tf.ty == Tfunction);
if (exp && exp.op == TOKvar && (cast(VarExp)exp).var == fd.vresult)
{
// return vresult;
if (sc.fes)
{
assert(caseDim == 0);
sc.fes.cases.push(this);
return new ReturnStatement(Loc(), new IntegerExp(sc.fes.cases.dim + 1));
}
if (fd.returnLabel)
{
auto gs = new GotoStatement(loc, Id.returnLabel);
gs.label = fd.returnLabel;
return gs;
}
if (!fd.returns)
fd.returns = new ReturnStatements();
fd.returns.push(this);
return this;
}
Type tret = tf.next;
Type tbret = tret ? tret.toBasetype() : null;
bool inferRef = (tf.isref && (fd.storage_class & STCauto));
Expression e0 = null;
bool errors = false;
if (sc.flags & SCOPEcontract)
{
error("return statements cannot be in contracts");
errors = true;
}
if (sc.os && sc.os.tok != TOKon_scope_failure)
{
error("return statements cannot be in %s bodies", Token.toChars(sc.os.tok));
errors = true;
}
if (sc.tf)
{
error("return statements cannot be in finally bodies");
errors = true;
}
if (fd.isCtorDeclaration())
{
if (exp)
{
error("cannot return expression from constructor");
errors = true;
}
// Constructors implicitly do:
// return this;
exp = new ThisExp(Loc());
exp.type = tret;
}
else if (exp)
{
fd.hasReturnExp |= 1;
FuncLiteralDeclaration fld = fd.isFuncLiteralDeclaration();
if (tret)
exp = inferType(exp, tret);
else if (fld && fld.treq)
exp = inferType(exp, fld.treq.nextOf().nextOf());
exp = exp.semantic(sc);
exp = resolveProperties(sc, exp);
if (exp.type && exp.type.ty != Tvoid || exp.op == TOKfunction || exp.op == TOKtype || exp.op == TOKtemplate)
{
// don't make error for void expression
if (exp.checkValue())
exp = new ErrorExp();
}
if (checkNonAssignmentArrayOp(exp))
exp = new ErrorExp();
// Extract side-effect part
exp = Expression.extractLast(exp, &e0);
if (exp.op == TOKcall)
exp = valueNoDtor(exp);
/* Void-return function can have void typed expression
* on return statement.
*/
if (tbret && tbret.ty == Tvoid || exp.type.ty == Tvoid)
{
if (exp.type.ty != Tvoid)
{
error("cannot return non-void from void function");
errors = true;
exp = new CastExp(loc, exp, Type.tvoid);
exp = exp.semantic(sc);
}
/* Replace:
* return exp;
* with:
* exp; return;
*/
e0 = Expression.combine(e0, exp);
exp = null;
}
if (e0)
e0 = checkGC(sc, e0);
}
if (exp)
{
if (fd.inferRetType) // infer return type
{
if (!tret)
{
tf.next = exp.type;
}
else if (tret.ty != Terror && !exp.type.equals(tret))
{
int m1 = exp.type.implicitConvTo(tret);
int m2 = tret.implicitConvTo(exp.type);
//printf("exp->type = %s m2<-->m1 tret %s\n", exp->type->toChars(), tret->toChars());
//printf("m1 = %d, m2 = %d\n", m1, m2);
if (m1 && m2)
{
}
else if (!m1 && m2)
tf.next = exp.type;
else if (m1 && !m2)
{
}
else if (exp.op != TOKerror)
{
error("mismatched function return type inference of %s and %s", exp.type.toChars(), tret.toChars());
errors = true;
tf.next = Type.terror;
}
}
tret = tf.next;
tbret = tret.toBasetype();
}
if (inferRef) // deduce 'auto ref'
{
/* Determine "refness" of function return:
* if it's an lvalue, return by ref, else return by value
*/
if (exp.isLvalue())
{
/* May return by ref
*/
if (checkEscapeRef(sc, exp, true))
tf.isref = false; // return by value
}
else
tf.isref = false; // return by value
/* The "refness" is determined by all of return statements.
* This means:
* return 3; return x; // ok, x can be a value
* return x; return 3; // ok, x can be a value
*/
}
// handle NRVO
if (fd.nrvo_can && exp.op == TOKvar)
{
VarExp ve = cast(VarExp)exp;
VarDeclaration v = ve.var.isVarDeclaration();
if (tf.isref)
{
// Function returns a reference
if (!inferRef)
fd.nrvo_can = 0;
}
else if (!v || v.isOut() || v.isRef())
fd.nrvo_can = 0;
else if (fd.nrvo_var is null)
{
if (!v.isDataseg() && !v.isParameter() && v.toParent2() == fd)
{
//printf("Setting nrvo to %s\n", v->toChars());
fd.nrvo_var = v;
}
else
fd.nrvo_can = 0;
}
else if (fd.nrvo_var != v)
fd.nrvo_can = 0;
}
else //if (!exp->isLvalue()) // keep NRVO-ability
fd.nrvo_can = 0;
}
else
{
// handle NRVO
fd.nrvo_can = 0;
// infer return type
if (fd.inferRetType)
{
if (tf.next && tf.next.ty != Tvoid)
{
if (tf.next.ty != Terror)
{
error("mismatched function return type inference of void and %s", tf.next.toChars());
}
errors = true;
tf.next = Type.terror;
}
else
tf.next = Type.tvoid;
tret = tf.next;
tbret = tret.toBasetype();
}
if (inferRef) // deduce 'auto ref'
tf.isref = false;
if (tbret.ty != Tvoid) // if non-void return
{
if (tbret.ty != Terror)
error("return expression expected");
errors = true;
}
else if (fd.isMain())
{
// main() returns 0, even if it returns void
exp = new IntegerExp(0);
}
}
// If any branches have called a ctor, but this branch hasn't, it's an error
if (sc.callSuper & CSXany_ctor && !(sc.callSuper & (CSXthis_ctor | CSXsuper_ctor)))
{
error("return without calling constructor");
errors = true;
}
sc.callSuper |= CSXreturn;
if (sc.fieldinit)
{
AggregateDeclaration ad = fd.isAggregateMember2();
assert(ad);
size_t dim = sc.fieldinit_dim;
foreach (i; 0 .. dim)
{
VarDeclaration v = ad.fields[i];
bool mustInit = (v.storage_class & STCnodefaultctor || v.type.needsNested());
if (mustInit && !(sc.fieldinit[i] & CSXthis_ctor))
{
error("an earlier return statement skips field %s initialization", v.toChars());
errors = true;
}
sc.fieldinit[i] |= CSXreturn;
}
}
if (errors)
return new ErrorStatement();
if (sc.fes)
{
if (!exp)
{
// Send out "case receiver" statement to the foreach.
// return exp;
Statement s = new ReturnStatement(Loc(), exp);
sc.fes.cases.push(s);
// Immediately rewrite "this" return statement as:
// return cases->dim+1;
this.exp = new IntegerExp(sc.fes.cases.dim + 1);
if (e0)
return new CompoundStatement(loc, new ExpStatement(loc, e0), this);
return this;
}
else
{
fd.buildResultVar(null, exp.type);
bool r = fd.vresult.checkNestedReference(sc, Loc());
assert(!r); // vresult should be always accessible
// Send out "case receiver" statement to the foreach.
// return vresult;
Statement s = new ReturnStatement(Loc(), new VarExp(Loc(), fd.vresult));
sc.fes.cases.push(s);
// Save receiver index for the later rewriting from:
// return exp;
// to:
// vresult = exp; retrun caseDim;
caseDim = sc.fes.cases.dim + 1;
}
}
if (exp)
{
if (!fd.returns)
fd.returns = new ReturnStatements();
fd.returns.push(this);
}
if (e0)
return new CompoundStatement(loc, new ExpStatement(loc, e0), this);
return this;
}
override ReturnStatement isReturnStatement()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class BreakStatement : Statement
{
public:
Identifier ident;
extern (D) this(Loc loc, Identifier ident)
{
super(loc);
this.ident = ident;
}
override Statement syntaxCopy()
{
return new BreakStatement(loc, ident);
}
override Statement semantic(Scope* sc)
{
//printf("BreakStatement::semantic()\n");
// If:
// break Identifier;
if (ident)
{
ident = fixupLabelName(sc, ident);
FuncDeclaration thisfunc = sc.func;
for (Scope* scx = sc; scx; scx = scx.enclosing)
{
if (scx.func != thisfunc) // if in enclosing function
{
if (sc.fes) // if this is the body of a foreach
{
/* Post this statement to the fes, and replace
* it with a return value that caller will put into
* a switch. Caller will figure out where the break
* label actually is.
* Case numbers start with 2, not 0, as 0 is continue
* and 1 is break.
*/
sc.fes.cases.push(this);
Statement s = new ReturnStatement(Loc(), new IntegerExp(sc.fes.cases.dim + 1));
return s;
}
break;
// can't break to it
}
LabelStatement ls = scx.slabel;
if (ls && ls.ident == ident)
{
Statement s = ls.statement;
if (!s || !s.hasBreak())
error("label '%s' has no break", ident.toChars());
else if (ls.tf != sc.tf)
error("cannot break out of finally block");
else
{
ls.breaks = true;
return this;
}
return new ErrorStatement();
}
}
error("enclosing label '%s' for break not found", ident.toChars());
return new ErrorStatement();
}
else if (!sc.sbreak)
{
if (sc.os && sc.os.tok != TOKon_scope_failure)
{
error("break is not inside %s bodies", Token.toChars(sc.os.tok));
}
else if (sc.fes)
{
// Replace break; with return 1;
Statement s = new ReturnStatement(Loc(), new IntegerExp(1));
return s;
}
else
error("break is not inside a loop or switch");
return new ErrorStatement();
}
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ContinueStatement : Statement
{
public:
Identifier ident;
extern (D) this(Loc loc, Identifier ident)
{
super(loc);
this.ident = ident;
}
override Statement syntaxCopy()
{
return new ContinueStatement(loc, ident);
}
override Statement semantic(Scope* sc)
{
//printf("ContinueStatement::semantic() %p\n", this);
if (ident)
{
ident = fixupLabelName(sc, ident);
Scope* scx;
FuncDeclaration thisfunc = sc.func;
for (scx = sc; scx; scx = scx.enclosing)
{
LabelStatement ls;
if (scx.func != thisfunc) // if in enclosing function
{
if (sc.fes) // if this is the body of a foreach
{
for (; scx; scx = scx.enclosing)
{
ls = scx.slabel;
if (ls && ls.ident == ident && ls.statement == sc.fes)
{
// Replace continue ident; with return 0;
return new ReturnStatement(Loc(), new IntegerExp(0));
}
}
/* Post this statement to the fes, and replace
* it with a return value that caller will put into
* a switch. Caller will figure out where the break
* label actually is.
* Case numbers start with 2, not 0, as 0 is continue
* and 1 is break.
*/
sc.fes.cases.push(this);
Statement s = new ReturnStatement(Loc(), new IntegerExp(sc.fes.cases.dim + 1));
return s;
}
break;
// can't continue to it
}
ls = scx.slabel;
if (ls && ls.ident == ident)
{
Statement s = ls.statement;
if (!s || !s.hasContinue())
error("label '%s' has no continue", ident.toChars());
else if (ls.tf != sc.tf)
error("cannot continue out of finally block");
else
return this;
return new ErrorStatement();
}
}
error("enclosing label '%s' for continue not found", ident.toChars());
return new ErrorStatement();
}
else if (!sc.scontinue)
{
if (sc.os && sc.os.tok != TOKon_scope_failure)
{
error("continue is not inside %s bodies", Token.toChars(sc.os.tok));
}
else if (sc.fes)
{
// Replace continue; with return 0;
Statement s = new ReturnStatement(Loc(), new IntegerExp(0));
return s;
}
else
error("continue is not inside a loop");
return new ErrorStatement();
}
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class SynchronizedStatement : Statement
{
public:
Expression exp;
Statement _body;
extern (D) this(Loc loc, Expression exp, Statement _body)
{
super(loc);
this.exp = exp;
this._body = _body;
}
override Statement syntaxCopy()
{
return new SynchronizedStatement(loc, exp ? exp.syntaxCopy() : null, _body ? _body.syntaxCopy() : null);
}
override Statement semantic(Scope* sc)
{
if (exp)
{
exp = exp.semantic(sc);
exp = resolveProperties(sc, exp);
exp = exp.optimize(WANTvalue);
exp = checkGC(sc, exp);
if (exp.op == TOKerror)
goto Lbody;
ClassDeclaration cd = exp.type.isClassHandle();
if (!cd)
{
error("can only synchronize on class objects, not '%s'", exp.type.toChars());
return new ErrorStatement();
}
else if (cd.isInterfaceDeclaration())
{
/* Cast the interface to an object, as the object has the monitor,
* not the interface.
*/
if (!ClassDeclaration.object)
{
error("missing or corrupt object.d");
fatal();
}
Type t = ClassDeclaration.object.type;
t = t.semantic(Loc(), sc).toBasetype();
assert(t.ty == Tclass);
exp = new CastExp(loc, exp, t);
exp = exp.semantic(sc);
}
version (all)
{
/* Rewrite as:
* auto tmp = exp;
* _d_monitorenter(tmp);
* try { body } finally { _d_monitorexit(tmp); }
*/
Identifier id = Identifier.generateId("__sync");
auto ie = new ExpInitializer(loc, exp);
auto tmp = new VarDeclaration(loc, exp.type, id, ie);
tmp.storage_class |= STCtemp;
auto cs = new Statements();
cs.push(new ExpStatement(loc, tmp));
auto args = new Parameters();
args.push(new Parameter(0, ClassDeclaration.object.type, null, null));
FuncDeclaration fdenter = FuncDeclaration.genCfunc(args, Type.tvoid, Id.monitorenter);
Expression e = new CallExp(loc, new VarExp(loc, fdenter), new VarExp(loc, tmp));
e.type = Type.tvoid; // do not run semantic on e
cs.push(new ExpStatement(loc, e));
FuncDeclaration fdexit = FuncDeclaration.genCfunc(args, Type.tvoid, Id.monitorexit);
e = new CallExp(loc, new VarExp(loc, fdexit), new VarExp(loc, tmp));
e.type = Type.tvoid; // do not run semantic on e
Statement s = new ExpStatement(loc, e);
s = new TryFinallyStatement(loc, _body, s);
cs.push(s);
s = new CompoundStatement(loc, cs);
return s.semantic(sc);
}
}
else
{
/* Generate our own critical section, then rewrite as:
* __gshared byte[CriticalSection.sizeof] critsec;
* _d_criticalenter(critsec.ptr);
* try { body } finally { _d_criticalexit(critsec.ptr); }
*/
Identifier id = Identifier.generateId("__critsec");
Type t = new TypeSArray(Type.tint8, new IntegerExp(Target.ptrsize + Target.critsecsize()));
auto tmp = new VarDeclaration(loc, t, id, null);
tmp.storage_class |= STCtemp | STCgshared | STCstatic;
auto cs = new Statements();
cs.push(new ExpStatement(loc, tmp));
/* This is just a dummy variable for "goto skips declaration" error.
* Backend optimizer could remove this unused variable.
*/
auto v = new VarDeclaration(loc, Type.tvoidptr, Identifier.generateId("__sync"), null);
v.semantic(sc);
cs.push(new ExpStatement(loc, v));
auto args = new Parameters();
args.push(new Parameter(0, t.pointerTo(), null, null));
FuncDeclaration fdenter = FuncDeclaration.genCfunc(args, Type.tvoid, Id.criticalenter, STCnothrow);
Expression e = new DotIdExp(loc, new VarExp(loc, tmp), Id.ptr);
e = e.semantic(sc);
e = new CallExp(loc, new VarExp(loc, fdenter), e);
e.type = Type.tvoid; // do not run semantic on e
cs.push(new ExpStatement(loc, e));
FuncDeclaration fdexit = FuncDeclaration.genCfunc(args, Type.tvoid, Id.criticalexit, STCnothrow);
e = new DotIdExp(loc, new VarExp(loc, tmp), Id.ptr);
e = e.semantic(sc);
e = new CallExp(loc, new VarExp(loc, fdexit), e);
e.type = Type.tvoid; // do not run semantic on e
Statement s = new ExpStatement(loc, e);
s = new TryFinallyStatement(loc, _body, s);
cs.push(s);
s = new CompoundStatement(loc, cs);
return s.semantic(sc);
}
Lbody:
if (_body)
_body = _body.semantic(sc);
if (_body && _body.isErrorStatement())
return _body;
return this;
}
override bool hasBreak()
{
return false; //true;
}
override bool hasContinue()
{
return false; //true;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class WithStatement : Statement
{
public:
Expression exp;
Statement _body;
VarDeclaration wthis;
extern (D) this(Loc loc, Expression exp, Statement _body)
{
super(loc);
this.exp = exp;
this._body = _body;
}
override Statement syntaxCopy()
{
return new WithStatement(loc, exp.syntaxCopy(), _body ? _body.syntaxCopy() : null);
}
override Statement semantic(Scope* sc)
{
ScopeDsymbol sym;
Initializer _init;
//printf("WithStatement::semantic()\n");
exp = exp.semantic(sc);
exp = resolveProperties(sc, exp);
exp = exp.optimize(WANTvalue);
exp = checkGC(sc, exp);
if (exp.op == TOKerror)
return new ErrorStatement();
if (exp.op == TOKimport)
{
sym = new WithScopeSymbol(this);
sym.parent = sc.scopesym;
}
else if (exp.op == TOKtype)
{
Dsymbol s = (cast(TypeExp)exp).type.toDsymbol(sc);
if (!s || !s.isScopeDsymbol())
{
error("with type %s has no members", exp.toChars());
return new ErrorStatement();
}
sym = new WithScopeSymbol(this);
sym.parent = sc.scopesym;
}
else
{
Type t = exp.type.toBasetype();
Expression olde = exp;
if (t.ty == Tpointer)
{
exp = new PtrExp(loc, exp);
exp = exp.semantic(sc);
t = exp.type.toBasetype();
}
assert(t);
t = t.toBasetype();
if (t.isClassHandle())
{
_init = new ExpInitializer(loc, exp);
wthis = new VarDeclaration(loc, exp.type, Id.withSym, _init);
wthis.semantic(sc);
sym = new WithScopeSymbol(this);
sym.parent = sc.scopesym;
}
else if (t.ty == Tstruct)
{
if (!exp.isLvalue())
{
/* Re-write to
* {
* auto __withtmp = exp
* with(__withtmp)
* {
* ...
* }
* }
*/
_init = new ExpInitializer(loc, exp);
wthis = new VarDeclaration(loc, exp.type, Identifier.generateId("__withtmp"), _init);
wthis.storage_class |= STCtemp;
auto es = new ExpStatement(loc, wthis);
exp = new VarExp(loc, wthis);
Statement ss = new ScopeStatement(loc, new CompoundStatement(loc, es, this));
return ss.semantic(sc);
}
Expression e = exp.addressOf();
_init = new ExpInitializer(loc, e);
wthis = new VarDeclaration(loc, e.type, Id.withSym, _init);
wthis.semantic(sc);
sym = new WithScopeSymbol(this);
// Need to set the scope to make use of resolveAliasThis
sym.setScope(sc);
sym.parent = sc.scopesym;
}
else
{
error("with expressions must be aggregate types or pointers to them, not '%s'", olde.type.toChars());
return new ErrorStatement();
}
}
if (_body)
{
sym._scope = sc;
sc = sc.push(sym);
sc.insert(sym);
_body = _body.semantic(sc);
sc.pop();
if (_body && _body.isErrorStatement())
return _body;
}
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class TryCatchStatement : Statement
{
public:
Statement _body;
Catches* catches;
extern (D) this(Loc loc, Statement _body, Catches* catches)
{
super(loc);
this._body = _body;
this.catches = catches;
}
override Statement syntaxCopy()
{
auto a = new Catches();
a.setDim(catches.dim);
foreach (i, c; *catches)
{
(*a)[i] = c.syntaxCopy();
}
return new TryCatchStatement(loc, _body.syntaxCopy(), a);
}
override Statement semantic(Scope* sc)
{
_body = _body.semanticScope(sc, null, null);
assert(_body);
/* Even if body is empty, still do semantic analysis on catches
*/
bool catchErrors = false;
foreach (i, c; *catches)
{
c.semantic(sc);
if (c.type.ty == Terror)
{
catchErrors = true;
continue;
}
// Determine if current catch 'hides' any previous catches
foreach (j; 0 .. i)
{
Catch cj = (*catches)[j];
char* si = c.loc.toChars();
char* sj = cj.loc.toChars();
if (c.type.toBasetype().implicitConvTo(cj.type.toBasetype()))
{
error("catch at %s hides catch at %s", sj, si);
catchErrors = true;
}
}
}
if (catchErrors)
return new ErrorStatement();
if (_body.isErrorStatement())
return _body;
/* If the try body never throws, we can eliminate any catches
* of recoverable exceptions.
*/
if (!(_body.blockExit(sc.func, false) & BEthrow) && ClassDeclaration.exception)
{
foreach_reverse (i; 0 .. catches.dim)
{
Catch c = (*catches)[i];
/* If catch exception type is derived from Exception
*/
if (c.type.toBasetype().implicitConvTo(ClassDeclaration.exception.type) && (!c.handler || !c.handler.comeFrom()))
{
// Remove c from the array of catches
catches.remove(i);
}
}
}
if (catches.dim == 0)
return _body.hasCode() ? _body : null;
return this;
}
override bool hasBreak()
{
return false;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class Catch : RootObject
{
public:
Loc loc;
Type type;
Identifier ident;
VarDeclaration var;
Statement handler;
// was generated by the compiler, wasn't present in source code
bool internalCatch;
extern (D) this(Loc loc, Type t, Identifier id, Statement handler)
{
//printf("Catch(%s, loc = %s)\n", id->toChars(), loc.toChars());
this.loc = loc;
this.type = t;
this.ident = id;
this.handler = handler;
}
Catch syntaxCopy()
{
auto c = new Catch(loc, type ? type.syntaxCopy() : null, ident, (handler ? handler.syntaxCopy() : null));
c.internalCatch = internalCatch;
return c;
}
void semantic(Scope* sc)
{
//printf("Catch::semantic(%s)\n", ident->toChars());
static if (!IN_GCC)
{
if (sc.os && sc.os.tok != TOKon_scope_failure)
{
// If enclosing is scope(success) or scope(exit), this will be placed in finally block.
error(loc, "cannot put catch statement inside %s", Token.toChars(sc.os.tok));
}
if (sc.tf)
{
/* This is because the _d_local_unwind() gets the stack munged
* up on this. The workaround is to place any try-catches into
* a separate function, and call that.
* To fix, have the compiler automatically convert the finally
* body into a nested function.
*/
error(loc, "cannot put catch statement inside finally block");
}
}
auto sym = new ScopeDsymbol();
sym.parent = sc.scopesym;
sc = sc.push(sym);
if (!type)
{
// reference .object.Throwable
auto tid = new TypeIdentifier(Loc(), Id.empty);
tid.addIdent(Id.object);
tid.addIdent(Id.Throwable);
type = tid;
}
type = type.semantic(loc, sc);
ClassDeclaration cd = type.toBasetype().isClassHandle();
if (!cd || ((cd != ClassDeclaration.throwable) && !ClassDeclaration.throwable.isBaseOf(cd, null)))
{
if (type != Type.terror)
{
error(loc, "can only catch class objects derived from Throwable, not '%s'", type.toChars());
type = Type.terror;
}
}
else if (sc.func && !sc.intypeof && !internalCatch && cd != ClassDeclaration.exception && !ClassDeclaration.exception.isBaseOf(cd, null) && sc.func.setUnsafe())
{
error(loc, "can only catch class objects derived from Exception in @safe code, not '%s'", type.toChars());
type = Type.terror;
}
else if (ident)
{
var = new VarDeclaration(loc, type, ident, null);
var.semantic(sc);
sc.insert(var);
}
handler = handler.semantic(sc);
sc.pop();
}
}
/***********************************************************
*/
extern (C++) final class TryFinallyStatement : Statement
{
public:
Statement _body;
Statement finalbody;
extern (D) this(Loc loc, Statement _body, Statement finalbody)
{
super(loc);
this._body = _body;
this.finalbody = finalbody;
}
static TryFinallyStatement create(Loc loc, Statement _body, Statement finalbody)
{
return new TryFinallyStatement(loc, _body, finalbody);
}
override Statement syntaxCopy()
{
return new TryFinallyStatement(loc, _body.syntaxCopy(), finalbody.syntaxCopy());
}
override Statement semantic(Scope* sc)
{
//printf("TryFinallyStatement::semantic()\n");
_body = _body.semantic(sc);
sc = sc.push();
sc.tf = this;
sc.sbreak = null;
sc.scontinue = null; // no break or continue out of finally block
finalbody = finalbody.semanticNoScope(sc);
sc.pop();
if (!_body)
return finalbody;
if (!finalbody)
return _body;
if (_body.blockExit(sc.func, false) == BEfallthru)
{
Statement s = new CompoundStatement(loc, _body, finalbody);
return s;
}
return this;
}
override bool hasBreak()
{
return false; //true;
}
override bool hasContinue()
{
return false; //true;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class OnScopeStatement : Statement
{
public:
TOK tok;
Statement statement;
extern (D) this(Loc loc, TOK tok, Statement statement)
{
super(loc);
this.tok = tok;
this.statement = statement;
}
override Statement syntaxCopy()
{
return new OnScopeStatement(loc, tok, statement.syntaxCopy());
}
override Statement semantic(Scope* sc)
{
static if (!IN_GCC)
{
if (tok != TOKon_scope_exit)
{
// scope(success) and scope(failure) are rewritten to try-catch(-finally) statement,
// so the generated catch block cannot be placed in finally block.
// See also Catch::semantic.
if (sc.os && sc.os.tok != TOKon_scope_failure)
{
// If enclosing is scope(success) or scope(exit), this will be placed in finally block.
error("cannot put %s statement inside %s", Token.toChars(tok), Token.toChars(sc.os.tok));
return new ErrorStatement();
}
if (sc.tf)
{
error("cannot put %s statement inside finally block", Token.toChars(tok));
return new ErrorStatement();
}
}
}
sc = sc.push();
sc.tf = null;
sc.os = this;
if (tok != TOKon_scope_failure)
{
// Jump out from scope(failure) block is allowed.
sc.sbreak = null;
sc.scontinue = null;
}
statement = statement.semanticNoScope(sc);
sc.pop();
if (!statement || statement.isErrorStatement())
return statement;
return this;
}
override Statement scopeCode(Scope* sc, Statement* sentry, Statement* sexception, Statement* sfinally)
{
//printf("OnScopeStatement::scopeCode()\n");
//print();
*sentry = null;
*sexception = null;
*sfinally = null;
Statement s = new PeelStatement(statement);
switch (tok)
{
case TOKon_scope_exit:
*sfinally = s;
break;
case TOKon_scope_failure:
*sexception = s;
break;
case TOKon_scope_success:
{
/* Create:
* sentry: bool x = false;
* sexception: x = true;
* sfinally: if (!x) statement;
*/
Identifier id = Identifier.generateId("__os");
auto ie = new ExpInitializer(loc, new IntegerExp(Loc(), 0, Type.tbool));
auto v = new VarDeclaration(loc, Type.tbool, id, ie);
v.storage_class |= STCtemp;
*sentry = new ExpStatement(loc, v);
Expression e = new IntegerExp(Loc(), 1, Type.tbool);
e = new AssignExp(Loc(), new VarExp(Loc(), v), e);
*sexception = new ExpStatement(Loc(), e);
e = new VarExp(Loc(), v);
e = new NotExp(Loc(), e);
*sfinally = new IfStatement(Loc(), null, e, s, null);
break;
}
default:
assert(0);
}
return null;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ThrowStatement : Statement
{
public:
Expression exp;
// was generated by the compiler, wasn't present in source code
bool internalThrow;
extern (D) this(Loc loc, Expression exp)
{
super(loc);
this.exp = exp;
}
override Statement syntaxCopy()
{
auto s = new ThrowStatement(loc, exp.syntaxCopy());
s.internalThrow = internalThrow;
return s;
}
override Statement semantic(Scope* sc)
{
//printf("ThrowStatement::semantic()\n");
FuncDeclaration fd = sc.parent.isFuncDeclaration();
fd.hasReturnExp |= 2;
exp = exp.semantic(sc);
exp = resolveProperties(sc, exp);
exp = checkGC(sc, exp);
if (exp.op == TOKerror)
return new ErrorStatement();
ClassDeclaration cd = exp.type.toBasetype().isClassHandle();
if (!cd || ((cd != ClassDeclaration.throwable) && !ClassDeclaration.throwable.isBaseOf(cd, null)))
{
error("can only throw class objects derived from Throwable, not type %s", exp.type.toChars());
return new ErrorStatement();
}
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class DebugStatement : Statement
{
public:
Statement statement;
extern (D) this(Loc loc, Statement statement)
{
super(loc);
this.statement = statement;
}
override Statement syntaxCopy()
{
return new DebugStatement(loc, statement ? statement.syntaxCopy() : null);
}
override Statement semantic(Scope* sc)
{
if (statement)
{
sc = sc.push();
sc.flags |= SCOPEdebug;
statement = statement.semantic(sc);
sc.pop();
}
return statement;
}
override Statements* flatten(Scope* sc)
{
Statements* a = statement ? statement.flatten(sc) : null;
if (a)
{
foreach (ref s; *a)
{
s = new DebugStatement(loc, s);
}
}
return a;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class GotoStatement : Statement
{
public:
Identifier ident;
LabelDsymbol label;
TryFinallyStatement tf;
OnScopeStatement os;
VarDeclaration lastVar;
extern (D) this(Loc loc, Identifier ident)
{
super(loc);
this.ident = ident;
}
override Statement syntaxCopy()
{
return new GotoStatement(loc, ident);
}
override Statement semantic(Scope* sc)
{
//printf("GotoStatement::semantic()\n");
FuncDeclaration fd = sc.func;
ident = fixupLabelName(sc, ident);
label = fd.searchLabel(ident);
tf = sc.tf;
os = sc.os;
lastVar = sc.lastVar;
if (!label.statement && sc.fes)
{
/* Either the goto label is forward referenced or it
* is in the function that the enclosing foreach is in.
* Can't know yet, so wrap the goto in a scope statement
* so we can patch it later, and add it to a 'look at this later'
* list.
*/
auto ss = new ScopeStatement(loc, this);
sc.fes.gotos.push(ss); // 'look at this later' list
return ss;
}
// Add to fwdref list to check later
if (!label.statement)
{
if (!fd.gotos)
fd.gotos = new GotoStatements();
fd.gotos.push(this);
}
else if (checkLabel())
return new ErrorStatement();
return this;
}
bool checkLabel()
{
if (!label.statement)
{
error("label '%s' is undefined", label.toChars());
return true;
}
if (label.statement.os != os)
{
if (os && os.tok == TOKon_scope_failure && !label.statement.os)
{
// Jump out from scope(failure) block is allowed.
}
else
{
if (label.statement.os)
error("cannot goto in to %s block", Token.toChars(label.statement.os.tok));
else
error("cannot goto out of %s block", Token.toChars(os.tok));
return true;
}
}
if (label.statement.tf != tf)
{
error("cannot goto in or out of finally block");
return true;
}
VarDeclaration vd = label.statement.lastVar;
if (!vd || vd.isDataseg() || (vd.storage_class & STCmanifest))
return false;
VarDeclaration last = lastVar;
while (last && last != vd)
last = last.lastVar;
if (last == vd)
{
// All good, the label's scope has no variables
}
else if (vd.ident == Id.withSym)
{
error("goto skips declaration of with temporary at %s", vd.loc.toChars());
return true;
}
else
{
error("goto skips declaration of variable %s at %s", vd.toPrettyChars(), vd.loc.toChars());
return true;
}
return false;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class LabelStatement : Statement
{
public:
Identifier ident;
Statement statement;
TryFinallyStatement tf;
OnScopeStatement os;
VarDeclaration lastVar;
Statement gotoTarget; // interpret
bool breaks; // someone did a 'break ident'
extern (D) this(Loc loc, Identifier ident, Statement statement)
{
super(loc);
this.ident = ident;
this.statement = statement;
}
override Statement syntaxCopy()
{
return new LabelStatement(loc, ident, statement ? statement.syntaxCopy() : null);
}
override Statement semantic(Scope* sc)
{
//printf("LabelStatement::semantic()\n");
FuncDeclaration fd = sc.parent.isFuncDeclaration();
ident = fixupLabelName(sc, ident);
tf = sc.tf;
os = sc.os;
lastVar = sc.lastVar;
LabelDsymbol ls = fd.searchLabel(ident);
if (ls.statement)
{
error("label '%s' already defined", ls.toChars());
return new ErrorStatement();
}
else
ls.statement = this;
sc = sc.push();
sc.scopesym = sc.enclosing.scopesym;
sc.callSuper |= CSXlabel;
if (sc.fieldinit)
{
size_t dim = sc.fieldinit_dim;
foreach (i; 0 .. dim)
sc.fieldinit[i] |= CSXlabel;
}
sc.slabel = this;
if (statement)
statement = statement.semantic(sc);
sc.pop();
return this;
}
override Statements* flatten(Scope* sc)
{
Statements* a = null;
if (statement)
{
a = statement.flatten(sc);
if (a)
{
if (!a.dim)
{
a.push(new ExpStatement(loc, cast(Expression)null));
}
// reuse 'this' LabelStatement
this.statement = (*a)[0];
(*a)[0] = this;
}
}
return a;
}
override Statement scopeCode(Scope* sc, Statement* sentry, Statement* sexit, Statement* sfinally)
{
//printf("LabelStatement::scopeCode()\n");
if (statement)
statement = statement.scopeCode(sc, sentry, sexit, sfinally);
else
{
*sentry = null;
*sexit = null;
*sfinally = null;
}
return this;
}
override LabelStatement isLabelStatement()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class LabelDsymbol : Dsymbol
{
public:
LabelStatement statement;
extern (D) this(Identifier ident)
{
super(ident);
}
static LabelDsymbol create(Identifier ident)
{
return new LabelDsymbol(ident);
}
// is this a LabelDsymbol()?
override LabelDsymbol isLabel()
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class AsmStatement : Statement
{
public:
Token* tokens;
code* asmcode;
uint asmalign; // alignment of this statement
uint regs; // mask of registers modified (must match regm_t in back end)
bool refparam; // true if function parameter is referenced
bool naked; // true if function is to be naked
extern (D) this(Loc loc, Token* tokens)
{
super(loc);
this.tokens = tokens;
}
override Statement syntaxCopy()
{
return new AsmStatement(loc, tokens);
}
override Statement semantic(Scope* sc)
{
return asmSemantic(this, sc);
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
* a complete asm {} block
*/
extern (C++) final class CompoundAsmStatement : CompoundStatement
{
public:
StorageClass stc; // postfix attributes like nothrow/pure/@trusted
extern (D) this(Loc loc, Statements* s, StorageClass stc)
{
super(loc, s);
this.stc = stc;
}
override CompoundAsmStatement syntaxCopy()
{
auto a = new Statements();
a.setDim(statements.dim);
foreach (i, s; *statements)
{
(*a)[i] = s ? s.syntaxCopy() : null;
}
return new CompoundAsmStatement(loc, a, stc);
}
override CompoundAsmStatement semantic(Scope* sc)
{
foreach (ref s; *statements)
{
s = s ? s.semantic(sc) : null;
}
assert(sc.func);
// use setImpure/setGC when the deprecation cycle is over
PURE purity;
if (!(stc & STCpure) && (purity = sc.func.isPureBypassingInference()) != PUREimpure && purity != PUREfwdref)
deprecation("asm statement is assumed to be impure - mark it with 'pure' if it is not");
if (!(stc & STCnogc) && sc.func.isNogcBypassingInference())
deprecation("asm statement is assumed to use the GC - mark it with '@nogc' if it does not");
if (!(stc & (STCtrusted | STCsafe)) && sc.func.setUnsafe())
error("asm statement is assumed to be @system - mark it with '@trusted' if it is not");
return this;
}
override Statements* flatten(Scope* sc)
{
return null;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class ImportStatement : Statement
{
public:
Dsymbols* imports; // Array of Import's
extern (D) this(Loc loc, Dsymbols* imports)
{
super(loc);
this.imports = imports;
}
override Statement syntaxCopy()
{
auto m = new Dsymbols();
m.setDim(imports.dim);
foreach (i, s; *imports)
{
(*m)[i] = s.syntaxCopy(null);
}
return new ImportStatement(loc, m);
}
override Statement semantic(Scope* sc)
{
foreach (i; 0 .. imports.dim)
{
Import s = (*imports)[i].isImport();
assert(!s.aliasdecls.dim);
foreach (j, name; s.names)
{
Identifier _alias = s.aliases[j];
if (!_alias)
_alias = name;
auto tname = new TypeIdentifier(s.loc, name);
auto ad = new AliasDeclaration(s.loc, _alias, tname);
ad._import = s;
s.aliasdecls.push(ad);
}
s.semantic(sc);
//s->semantic2(sc); // Bugzilla 14666
sc.insert(s);
foreach (aliasdecl; s.aliasdecls)
{
sc.insert(aliasdecl);
}
}
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
| D |
// Written in the D programming language.
/**
Functions and types that manipulate built-in arrays and associative arrays.
This module provides all kinds of functions to create, manipulate or convert arrays:
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE ,
$(TR $(TH Function Name) $(TH Description)
)
$(TR $(TD $(LREF array))
$(TD Returns a copy of the input in a newly allocated dynamic array.
))
$(TR $(TD $(LREF appender))
$(TD Returns a new $(LREF Appender) or $(LREF RefAppender) initialized with a given array.
))
$(TR $(TD $(LREF assocArray))
$(TD Returns a newly allocated associative array from a range of key/value tuples.
))
$(TR $(TD $(LREF byPair))
$(TD Construct a range iterating over an associative array by key/value tuples.
))
$(TR $(TD $(LREF insertInPlace))
$(TD Inserts into an existing array at a given position.
))
$(TR $(TD $(LREF join))
$(TD Concatenates a range of ranges into one array.
))
$(TR $(TD $(LREF minimallyInitializedArray))
$(TD Returns a new array of type `T`.
))
$(TR $(TD $(LREF replace))
$(TD Returns a new array with all occurrences of a certain subrange replaced.
))
$(TR $(TD $(LREF replaceFirst))
$(TD Returns a new array with the first occurrence of a certain subrange replaced.
))
$(TR $(TD $(LREF replaceInPlace))
$(TD Replaces all occurrences of a certain subrange and puts the result into a given array.
))
$(TR $(TD $(LREF replaceInto))
$(TD Replaces all occurrences of a certain subrange and puts the result into an output range.
))
$(TR $(TD $(LREF replaceLast))
$(TD Returns a new array with the last occurrence of a certain subrange replaced.
))
$(TR $(TD $(LREF replaceSlice))
$(TD Returns a new array with a given slice replaced.
))
$(TR $(TD $(LREF replicate))
$(TD Creates a new array out of several copies of an input array or range.
))
$(TR $(TD $(LREF sameHead))
$(TD Checks if the initial segments of two arrays refer to the same
place in memory.
))
$(TR $(TD $(LREF sameTail))
$(TD Checks if the final segments of two arrays refer to the same place
in memory.
))
$(TR $(TD $(LREF split))
$(TD Eagerly split a range or string into an array.
))
$(TR $(TD $(LREF staticArray))
$(TD Creates a new static array from given data.
))
$(TR $(TD $(LREF uninitializedArray))
$(TD Returns a new array of type `T` without initializing its elements.
))
))
Copyright: Copyright Andrei Alexandrescu 2008- and Jonathan M Davis 2011-.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP erdani.org, Andrei Alexandrescu) and
$(HTTP jmdavisprog.com, Jonathan M Davis)
Source: $(PHOBOSSRC std/array.d)
*/
module std.array;
import std.functional;
import std.meta;
import std.traits;
import std.range.primitives;
public import std.range.primitives : save, empty, popFront, popBack, front, back;
/**
* Allocates an array and initializes it with copies of the elements
* of range `r`.
*
* Narrow strings are handled as follows:
* - If autodecoding is turned on (default), then they are handled as a separate overload.
* - If autodecoding is turned off, then this is equivalent to duplicating the array.
*
* Params:
* r = range (or aggregate with `opApply` function) whose elements are copied into the allocated array
* Returns:
* allocated and initialized array
*/
ForeachType!Range[] array(Range)(Range r)
if (isIterable!Range && !isAutodecodableString!Range && !isInfinite!Range)
{
if (__ctfe)
{
// Compile-time version to avoid memcpy calls.
// Also used to infer attributes of array().
typeof(return) result;
foreach (e; r)
result ~= e;
return result;
}
alias E = ForeachType!Range;
static if (hasLength!Range)
{
auto length = r.length;
if (length == 0)
return null;
import core.internal.lifetime : emplaceRef;
auto result = (() @trusted => uninitializedArray!(Unqual!E[])(length))();
// Every element of the uninitialized array must be initialized
size_t i;
foreach (e; r)
{
emplaceRef!E(result[i], e);
++i;
}
return (() @trusted => cast(E[]) result)();
}
else
{
auto a = appender!(E[])();
foreach (e; r)
{
a.put(e);
}
return a.data;
}
}
/// ditto
ForeachType!(PointerTarget!Range)[] array(Range)(Range r)
if (isPointer!Range && isIterable!(PointerTarget!Range) && !isAutodecodableString!Range && !isInfinite!Range)
{
return array(*r);
}
///
@safe pure nothrow unittest
{
auto a = array([1, 2, 3, 4, 5][]);
assert(a == [ 1, 2, 3, 4, 5 ]);
}
@safe pure nothrow unittest
{
import std.algorithm.comparison : equal;
struct Foo
{
int a;
}
auto a = array([Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)][]);
assert(equal(a, [Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)]));
}
@safe pure nothrow unittest
{
struct MyRange
{
enum front = 123;
enum empty = true;
void popFront() {}
}
auto arr = (new MyRange).array;
assert(arr.empty);
}
@system pure nothrow unittest
{
immutable int[] a = [1, 2, 3, 4];
auto b = (&a).array;
assert(b == a);
}
@safe unittest
{
import std.algorithm.comparison : equal;
struct Foo
{
int a;
void opAssign(Foo)
{
assert(0);
}
auto opEquals(Foo foo)
{
return a == foo.a;
}
}
auto a = array([Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)][]);
assert(equal(a, [Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)]));
}
// https://issues.dlang.org/show_bug.cgi?id=12315
@safe unittest
{
static struct Bug12315 { immutable int i; }
enum bug12315 = [Bug12315(123456789)].array();
static assert(bug12315[0].i == 123456789);
}
@safe unittest
{
import std.range;
static struct S{int* p;}
auto a = array(immutable(S).init.repeat(5));
assert(a.length == 5);
}
version (StdUnittest)
private extern(C) void _d_delarray_t(void[] *p, TypeInfo_Struct ti);
// https://issues.dlang.org/show_bug.cgi?id=18995
@system unittest
{
int nAlive = 0;
struct S
{
bool alive;
this(int) { alive = true; ++nAlive; }
this(this) { nAlive += alive; }
~this() { nAlive -= alive; alive = false; }
}
import std.algorithm.iteration : map;
import std.range : iota;
auto arr = iota(3).map!(a => S(a)).array;
assert(nAlive == 3);
// No good way to ensure the GC frees this, just call the lifetime function
// directly. If delete wasn't deprecated, this is what delete would do.
_d_delarray_t(cast(void[]*)&arr, typeid(S));
assert(nAlive == 0);
}
/**
Convert a narrow autodecoding string to an array type that fully supports
random access. This is handled as a special case and always returns an array
of `dchar`
NOTE: This function is never used when autodecoding is turned off.
Params:
str = `isNarrowString` to be converted to an array of `dchar`
Returns:
a `dchar[]`, `const(dchar)[]`, or `immutable(dchar)[]` depending on the constness of
the input.
*/
CopyTypeQualifiers!(ElementType!String,dchar)[] array(String)(scope String str)
if (isAutodecodableString!String)
{
import std.utf : toUTF32;
auto temp = str.toUTF32;
/* Unsafe cast. Allowed because toUTF32 makes a new array
and copies all the elements.
*/
return () @trusted { return cast(CopyTypeQualifiers!(ElementType!String, dchar)[]) temp; } ();
}
///
@safe unittest
{
import std.range.primitives : isRandomAccessRange;
import std.traits : isAutodecodableString;
// note that if autodecoding is turned off, `array` will not transcode these.
static if (isAutodecodableString!string)
assert("Hello D".array == "Hello D"d);
else
assert("Hello D".array == "Hello D");
static if (isAutodecodableString!wstring)
assert("Hello D"w.array == "Hello D"d);
else
assert("Hello D"w.array == "Hello D"w);
static assert(isRandomAccessRange!dstring == true);
}
@safe unittest
{
import std.conv : to;
static struct TestArray { int x; string toString() @safe { return to!string(x); } }
static struct OpAssign
{
uint num;
this(uint num) { this.num = num; }
// Templating opAssign to make sure the bugs with opAssign being
// templated are fixed.
void opAssign(T)(T rhs) { this.num = rhs.num; }
}
static struct OpApply
{
int opApply(scope int delegate(ref int) @safe dg)
{
int res;
foreach (i; 0 .. 10)
{
res = dg(i);
if (res) break;
}
return res;
}
}
auto a = array([1, 2, 3, 4, 5][]);
assert(a == [ 1, 2, 3, 4, 5 ]);
auto b = array([TestArray(1), TestArray(2)][]);
assert(b == [TestArray(1), TestArray(2)]);
class C
{
int x;
this(int y) { x = y; }
override string toString() const @safe { return to!string(x); }
}
auto c = array([new C(1), new C(2)][]);
assert(c[0].x == 1);
assert(c[1].x == 2);
auto d = array([1.0, 2.2, 3][]);
assert(is(typeof(d) == double[]));
assert(d == [1.0, 2.2, 3]);
auto e = [OpAssign(1), OpAssign(2)];
auto f = array(e);
assert(e == f);
assert(array(OpApply.init) == [0,1,2,3,4,5,6,7,8,9]);
static if (isAutodecodableString!string)
{
assert(array("ABC") == "ABC"d);
assert(array("ABC".dup) == "ABC"d.dup);
}
}
// https://issues.dlang.org/show_bug.cgi?id=8233
@safe unittest
{
assert(array("hello world"d) == "hello world"d);
immutable a = [1, 2, 3, 4, 5];
assert(array(a) == a);
const b = a;
assert(array(b) == a);
//To verify that the opAssign branch doesn't get screwed up by using Unqual.
//EDIT: array no longer calls opAssign.
struct S
{
ref S opAssign(S)(const ref S rhs)
{
assert(0);
}
int i;
}
static foreach (T; AliasSeq!(S, const S, immutable S))
{{
auto arr = [T(1), T(2), T(3), T(4)];
assert(array(arr) == arr);
}}
}
// https://issues.dlang.org/show_bug.cgi?id=9824
@safe unittest
{
static struct S
{
@disable void opAssign(S);
int i;
}
auto arr = [S(0), S(1), S(2)];
arr.array();
}
// https://issues.dlang.org/show_bug.cgi?id=10220
@safe unittest
{
import std.algorithm.comparison : equal;
import std.exception;
import std.range : repeat;
static struct S
{
int val;
@disable this();
this(int v) { val = v; }
}
assertCTFEable!(
{
auto r = S(1).repeat(2).array();
assert(equal(r, [S(1), S(1)]));
});
}
@safe unittest
{
//Turn down infinity:
static assert(!is(typeof(
repeat(1).array()
)));
}
/**
Returns a newly allocated associative array from a range of key/value tuples
or from a range of keys and a range of values.
Params:
r = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of tuples of keys and values.
keys = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) of keys
values = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) of values
Returns:
A newly allocated associative array out of elements of the input
range, which must be a range of tuples (Key, Value) or
a range of keys and a range of values. If given two ranges of unequal
lengths after the elements of the shorter are exhausted the remaining
elements of the longer will not be considered.
Returns a null associative array reference when given an empty range.
Duplicates: Associative arrays have unique keys. If r contains duplicate keys,
then the result will contain the value of the last pair for that key in r.
See_Also: $(REF Tuple, std,typecons), $(REF zip, std,range)
*/
auto assocArray(Range)(Range r)
if (isInputRange!Range)
{
import std.typecons : isTuple;
alias E = ElementType!Range;
static assert(isTuple!E, "assocArray: argument must be a range of tuples,"
~" but was a range of "~E.stringof);
static assert(E.length == 2, "assocArray: tuple dimension must be 2");
alias KeyType = E.Types[0];
alias ValueType = E.Types[1];
static assert(isMutable!ValueType, "assocArray: value type must be mutable");
ValueType[KeyType] aa;
foreach (t; r)
aa[t[0]] = t[1];
return aa;
}
/// ditto
auto assocArray(Keys, Values)(Keys keys, Values values)
if (isInputRange!Values && isInputRange!Keys)
{
static if (isDynamicArray!Keys && isDynamicArray!Values
&& !isNarrowString!Keys && !isNarrowString!Values)
{
void* aa;
{
// aaLiteral is nothrow when the destructors don't throw
static if (is(typeof(() nothrow
{
import std.range : ElementType;
import std.traits : hasElaborateDestructor;
alias KeyElement = ElementType!Keys;
static if (hasElaborateDestructor!KeyElement)
KeyElement.init.__xdtor();
alias ValueElement = ElementType!Values;
static if (hasElaborateDestructor!ValueElement)
ValueElement.init.__xdtor();
})))
{
scope(failure) assert(false, "aaLiteral must not throw");
}
if (values.length > keys.length)
values = values[0 .. keys.length];
else if (keys.length > values.length)
keys = keys[0 .. values.length];
aa = aaLiteral(keys, values);
}
alias Key = typeof(keys[0]);
alias Value = typeof(values[0]);
return (() @trusted => cast(Value[Key]) aa)();
}
else
{
// zip is not always able to infer nothrow
alias Key = ElementType!Keys;
alias Value = ElementType!Values;
static assert(isMutable!Value, "assocArray: value type must be mutable");
Value[Key] aa;
foreach (key; keys)
{
if (values.empty) break;
// aa[key] is incorrectly not @safe if the destructor throws
// https://issues.dlang.org/show_bug.cgi?id=18592
static if (is(typeof(() @safe
{
import std.range : ElementType;
import std.traits : hasElaborateDestructor;
alias KeyElement = ElementType!Keys;
static if (hasElaborateDestructor!KeyElement)
KeyElement.init.__xdtor();
alias ValueElement = ElementType!Values;
static if (hasElaborateDestructor!ValueElement)
ValueElement.init.__xdtor();
})))
{
() @trusted {
aa[key] = values.front;
}();
}
else
{
aa[key] = values.front;
}
values.popFront();
}
return aa;
}
}
///
@safe pure /*nothrow*/ unittest
{
import std.range : repeat, zip;
import std.typecons : tuple;
import std.range.primitives : autodecodeStrings;
auto a = assocArray(zip([0, 1, 2], ["a", "b", "c"])); // aka zipMap
static assert(is(typeof(a) == string[int]));
assert(a == [0:"a", 1:"b", 2:"c"]);
auto b = assocArray([ tuple("foo", "bar"), tuple("baz", "quux") ]);
static assert(is(typeof(b) == string[string]));
assert(b == ["foo":"bar", "baz":"quux"]);
static if (autodecodeStrings)
alias achar = dchar;
else
alias achar = immutable(char);
auto c = assocArray("ABCD", true.repeat);
static assert(is(typeof(c) == bool[achar]));
bool[achar] expected = ['D':true, 'A':true, 'B':true, 'C':true];
assert(c == expected);
}
// Cannot be version (StdUnittest) - recursive instantiation error
// https://issues.dlang.org/show_bug.cgi?id=11053
@safe unittest
{
import std.typecons;
static assert(!__traits(compiles, [ 1, 2, 3 ].assocArray()));
static assert(!__traits(compiles, [ tuple("foo", "bar", "baz") ].assocArray()));
static assert(!__traits(compiles, [ tuple("foo") ].assocArray()));
assert([ tuple("foo", "bar") ].assocArray() == ["foo": "bar"]);
}
// https://issues.dlang.org/show_bug.cgi?id=13909
@safe unittest
{
import std.typecons;
auto a = [tuple!(const string, string)("foo", "bar")];
auto b = [tuple!(string, const string)("foo", "bar")];
assert(a == b);
assert(assocArray(a) == [cast(const(string)) "foo": "bar"]);
static assert(!__traits(compiles, assocArray(b)));
}
// https://issues.dlang.org/show_bug.cgi?id=5502
@safe unittest
{
auto a = assocArray([0, 1, 2], ["a", "b", "c"]);
static assert(is(typeof(a) == string[int]));
assert(a == [0:"a", 1:"b", 2:"c"]);
auto b = assocArray([0, 1, 2], [3L, 4, 5]);
static assert(is(typeof(b) == long[int]));
assert(b == [0: 3L, 1: 4, 2: 5]);
}
// https://issues.dlang.org/show_bug.cgi?id=5502
@safe unittest
{
import std.algorithm.iteration : filter, map;
import std.range : enumerate;
import std.range.primitives : autodecodeStrings;
auto r = "abcde".enumerate.filter!(a => a.index == 2);
auto a = assocArray(r.map!(a => a.value), r.map!(a => a.index));
static if (autodecodeStrings)
alias achar = dchar;
else
alias achar = immutable(char);
static assert(is(typeof(a) == size_t[achar]));
assert(a == [achar('c'): size_t(2)]);
}
@safe nothrow pure unittest
{
import std.range : iota;
auto b = assocArray(3.iota, 3.iota(6));
static assert(is(typeof(b) == int[int]));
assert(b == [0: 3, 1: 4, 2: 5]);
b = assocArray([0, 1, 2], [3, 4, 5]);
assert(b == [0: 3, 1: 4, 2: 5]);
}
@safe unittest
{
struct ThrowingElement
{
int i;
static bool b;
~this(){
if (b)
throw new Exception("");
}
}
static assert(!__traits(compiles, () nothrow { assocArray([ThrowingElement()], [0]);}));
assert(assocArray([ThrowingElement()], [0]) == [ThrowingElement(): 0]);
static assert(!__traits(compiles, () nothrow { assocArray([0], [ThrowingElement()]);}));
assert(assocArray([0], [ThrowingElement()]) == [0: ThrowingElement()]);
import std.range : iota;
static assert(!__traits(compiles, () nothrow { assocArray(1.iota, [ThrowingElement()]);}));
assert(assocArray(1.iota, [ThrowingElement()]) == [0: ThrowingElement()]);
}
@system unittest
{
import std.range : iota;
struct UnsafeElement
{
int i;
static bool b;
~this(){
int[] arr;
void* p = arr.ptr + 1; // unsafe
}
}
static assert(!__traits(compiles, () @safe { assocArray(1.iota, [UnsafeElement()]);}));
assert(assocArray(1.iota, [UnsafeElement()]) == [0: UnsafeElement()]);
}
/**
Construct a range iterating over an associative array by key/value tuples.
Params:
aa = The associative array to iterate over.
Returns: A $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
of Tuple's of key and value pairs from the given associative array. The members
of each pair can be accessed by name (`.key` and `.value`). or by integer
index (0 and 1 respectively).
*/
auto byPair(AA)(AA aa)
if (isAssociativeArray!AA)
{
import std.algorithm.iteration : map;
import std.typecons : tuple;
return aa.byKeyValue
.map!(pair => tuple!("key", "value")(pair.key, pair.value));
}
///
@safe unittest
{
import std.algorithm.sorting : sort;
import std.typecons : tuple, Tuple;
auto aa = ["a": 1, "b": 2, "c": 3];
Tuple!(string, int)[] pairs;
// Iteration over key/value pairs.
foreach (pair; aa.byPair)
{
if (pair.key == "b")
pairs ~= tuple("B", pair.value);
else
pairs ~= pair;
}
// Iteration order is implementation-dependent, so we should sort it to get
// a fixed order.
pairs.sort();
assert(pairs == [
tuple("B", 2),
tuple("a", 1),
tuple("c", 3)
]);
}
@safe unittest
{
import std.typecons : tuple, Tuple;
import std.meta : AliasSeq;
auto aa = ["a":2];
auto pairs = aa.byPair();
alias PT = typeof(pairs.front);
static assert(is(PT : Tuple!(string,int)));
static assert(PT.fieldNames == AliasSeq!("key", "value"));
static assert(isForwardRange!(typeof(pairs)));
assert(!pairs.empty);
assert(pairs.front == tuple("a", 2));
auto savedPairs = pairs.save;
pairs.popFront();
assert(pairs.empty);
assert(!savedPairs.empty);
assert(savedPairs.front == tuple("a", 2));
}
// https://issues.dlang.org/show_bug.cgi?id=17711
@safe unittest
{
const(int[string]) aa = [ "abc": 123 ];
// Ensure that byKeyValue is usable with a const AA.
auto kv = aa.byKeyValue;
assert(!kv.empty);
assert(kv.front.key == "abc" && kv.front.value == 123);
kv.popFront();
assert(kv.empty);
// Ensure byPair is instantiable with const AA.
auto r = aa.byPair;
static assert(isInputRange!(typeof(r)));
assert(!r.empty && r.front[0] == "abc" && r.front[1] == 123);
r.popFront();
assert(r.empty);
}
private template blockAttribute(T)
{
import core.memory;
static if (hasIndirections!(T) || is(T == void))
{
enum blockAttribute = 0;
}
else
{
enum blockAttribute = GC.BlkAttr.NO_SCAN;
}
}
@safe unittest
{
import core.memory : UGC = GC;
static assert(!(blockAttribute!void & UGC.BlkAttr.NO_SCAN));
}
// Returns the number of dimensions in an array T.
private template nDimensions(T)
{
static if (isArray!T)
{
enum nDimensions = 1 + nDimensions!(typeof(T.init[0]));
}
else
{
enum nDimensions = 0;
}
}
@safe unittest
{
static assert(nDimensions!(uint[]) == 1);
static assert(nDimensions!(float[][]) == 2);
}
/++
Returns a new array of type `T` allocated on the garbage collected heap
without initializing its elements. This can be a useful optimization if every
element will be immediately initialized. `T` may be a multidimensional
array. In this case sizes may be specified for any number of dimensions from 0
to the number in `T`.
uninitializedArray is `nothrow` and weakly `pure`.
uninitializedArray is `@system` if the uninitialized element type has pointers.
Params:
T = The type of the resulting array elements
sizes = The length dimension(s) of the resulting array
Returns:
An array of `T` with `I.length` dimensions.
+/
auto uninitializedArray(T, I...)(I sizes) nothrow @system
if (isDynamicArray!T && allSatisfy!(isIntegral, I) && hasIndirections!(ElementEncodingType!T))
{
enum isSize_t(E) = is (E : size_t);
alias toSize_t(E) = size_t;
static assert(allSatisfy!(isSize_t, I),
"Argument types in "~I.stringof~" are not all convertible to size_t: "
~Filter!(templateNot!(isSize_t), I).stringof);
//Eagerlly transform non-size_t into size_t to avoid template bloat
alias ST = staticMap!(toSize_t, I);
return arrayAllocImpl!(false, T, ST)(sizes);
}
/// ditto
auto uninitializedArray(T, I...)(I sizes) nothrow @trusted
if (isDynamicArray!T && allSatisfy!(isIntegral, I) && !hasIndirections!(ElementEncodingType!T))
{
enum isSize_t(E) = is (E : size_t);
alias toSize_t(E) = size_t;
static assert(allSatisfy!(isSize_t, I),
"Argument types in "~I.stringof~" are not all convertible to size_t: "
~Filter!(templateNot!(isSize_t), I).stringof);
//Eagerlly transform non-size_t into size_t to avoid template bloat
alias ST = staticMap!(toSize_t, I);
return arrayAllocImpl!(false, T, ST)(sizes);
}
///
@system nothrow pure unittest
{
double[] arr = uninitializedArray!(double[])(100);
assert(arr.length == 100);
double[][] matrix = uninitializedArray!(double[][])(42, 31);
assert(matrix.length == 42);
assert(matrix[0].length == 31);
char*[] ptrs = uninitializedArray!(char*[])(100);
assert(ptrs.length == 100);
}
/++
Returns a new array of type `T` allocated on the garbage collected heap.
Partial initialization is done for types with indirections, for preservation
of memory safety. Note that elements will only be initialized to 0, but not
necessarily the element type's `.init`.
minimallyInitializedArray is `nothrow` and weakly `pure`.
Params:
T = The type of the array elements
sizes = The length dimension(s) of the resulting array
Returns:
An array of `T` with `I.length` dimensions.
+/
auto minimallyInitializedArray(T, I...)(I sizes) nothrow @trusted
if (isDynamicArray!T && allSatisfy!(isIntegral, I))
{
enum isSize_t(E) = is (E : size_t);
alias toSize_t(E) = size_t;
static assert(allSatisfy!(isSize_t, I),
"Argument types in "~I.stringof~" are not all convertible to size_t: "
~Filter!(templateNot!(isSize_t), I).stringof);
//Eagerlly transform non-size_t into size_t to avoid template bloat
alias ST = staticMap!(toSize_t, I);
return arrayAllocImpl!(true, T, ST)(sizes);
}
///
@safe pure nothrow unittest
{
import std.algorithm.comparison : equal;
import std.range : repeat;
auto arr = minimallyInitializedArray!(int[])(42);
assert(arr.length == 42);
// Elements aren't necessarily initialized to 0, so don't do this:
// assert(arr.equal(0.repeat(42)));
// If that is needed, initialize the array normally instead:
auto arr2 = new int[42];
assert(arr2.equal(0.repeat(42)));
}
@safe pure nothrow unittest
{
cast(void) minimallyInitializedArray!(int[][][][][])();
double[] arr = minimallyInitializedArray!(double[])(100);
assert(arr.length == 100);
double[][] matrix = minimallyInitializedArray!(double[][])(42);
assert(matrix.length == 42);
foreach (elem; matrix)
{
assert(elem.ptr is null);
}
}
// from rt/lifetime.d
private extern(C) void[] _d_newarrayU(const TypeInfo ti, size_t length) pure nothrow;
private auto arrayAllocImpl(bool minimallyInitialized, T, I...)(I sizes) nothrow
{
static assert(I.length <= nDimensions!T,
I.length.stringof~"dimensions specified for a "~nDimensions!T.stringof~" dimensional array.");
alias E = ElementEncodingType!T;
E[] ret;
static if (I.length != 0)
{
static assert(is(I[0] == size_t), "I[0] must be of type size_t not "
~ I[0].stringof);
alias size = sizes[0];
}
static if (I.length == 1)
{
if (__ctfe)
{
static if (__traits(compiles, new E[](size)))
ret = new E[](size);
else static if (__traits(compiles, ret ~= E.init))
{
try
{
//Issue: if E has an impure postblit, then all of arrayAllocImpl
//Will be impure, even during non CTFE.
foreach (i; 0 .. size)
ret ~= E.init;
}
catch (Exception e)
assert(0, e.msg);
}
else
assert(0, "No postblit nor default init on " ~ E.stringof ~
": At least one is required for CTFE.");
}
else
{
import core.stdc.string : memset;
/+
NOTES:
_d_newarrayU is part of druntime, and creates an uninitialized
block, just like GC.malloc. However, it also sets the appropriate
bits, and sets up the block as an appendable array of type E[],
which will inform the GC how to destroy the items in the block
when it gets collected.
_d_newarrayU returns a void[], but with the length set according
to E.sizeof.
+/
*(cast(void[]*)&ret) = _d_newarrayU(typeid(E[]), size);
static if (minimallyInitialized && hasIndirections!E)
// _d_newarrayU would have asserted if the multiplication below
// had overflowed, so we don't have to check it again.
memset(ret.ptr, 0, E.sizeof * ret.length);
}
}
else static if (I.length > 1)
{
ret = arrayAllocImpl!(false, E[])(size);
foreach (ref elem; ret)
elem = arrayAllocImpl!(minimallyInitialized, E)(sizes[1..$]);
}
return ret;
}
@safe nothrow pure unittest
{
auto s1 = uninitializedArray!(int[])();
auto s2 = minimallyInitializedArray!(int[])();
assert(s1.length == 0);
assert(s2.length == 0);
}
// https://issues.dlang.org/show_bug.cgi?id=9803
@safe nothrow pure unittest
{
auto a = minimallyInitializedArray!(int*[])(1);
assert(a[0] == null);
auto b = minimallyInitializedArray!(int[][])(1);
assert(b[0].empty);
auto c = minimallyInitializedArray!(int*[][])(1, 1);
assert(c[0][0] == null);
}
// https://issues.dlang.org/show_bug.cgi?id=10637
@safe unittest
{
static struct S
{
static struct I{int i; alias i this;}
int* p;
this() @disable;
this(int i)
{
p = &(new I(i)).i;
}
this(this)
{
p = &(new I(*p)).i;
}
~this()
{
// note, this assert is invalid -- a struct should always be able
// to run its dtor on the .init value, I'm leaving it here
// commented out because the original test case had it. I'm not
// sure what it's trying to prove.
//
// What happens now that minimallyInitializedArray adds the
// destructor run to the GC, is that this assert would fire in the
// GC, which triggers an invalid memory operation.
//assert(p != null);
}
}
auto a = minimallyInitializedArray!(S[])(1);
assert(a[0].p == null);
enum b = minimallyInitializedArray!(S[])(1);
assert(b[0].p == null);
}
@safe nothrow unittest
{
static struct S1
{
this() @disable;
this(this) @disable;
}
auto a1 = minimallyInitializedArray!(S1[][])(2, 2);
assert(a1);
static struct S2
{
this() @disable;
//this(this) @disable;
}
auto a2 = minimallyInitializedArray!(S2[][])(2, 2);
assert(a2);
enum b2 = minimallyInitializedArray!(S2[][])(2, 2);
assert(b2);
static struct S3
{
//this() @disable;
this(this) @disable;
}
auto a3 = minimallyInitializedArray!(S3[][])(2, 2);
assert(a3);
enum b3 = minimallyInitializedArray!(S3[][])(2, 2);
assert(b3);
}
/++
Returns the overlapping portion, if any, of two arrays. Unlike `equal`,
`overlap` only compares the pointers and lengths in the
ranges, not the values referred by them. If `r1` and `r2` have an
overlapping slice, returns that slice. Otherwise, returns the null
slice.
Params:
a = The first array to compare
b = The second array to compare
Returns:
The overlapping portion of the two arrays.
+/
CommonType!(T[], U[]) overlap(T, U)(T[] a, U[] b) @trusted
if (is(typeof(a.ptr < b.ptr) == bool))
{
import std.algorithm.comparison : min;
auto end = min(a.ptr + a.length, b.ptr + b.length);
// CTFE requires pairing pointer comparisons, which forces a
// slightly inefficient implementation.
if (a.ptr <= b.ptr && b.ptr < a.ptr + a.length)
{
return b.ptr[0 .. end - b.ptr];
}
if (b.ptr <= a.ptr && a.ptr < b.ptr + b.length)
{
return a.ptr[0 .. end - a.ptr];
}
return null;
}
///
@safe pure nothrow unittest
{
int[] a = [ 10, 11, 12, 13, 14 ];
int[] b = a[1 .. 3];
assert(overlap(a, b) == [ 11, 12 ]);
b = b.dup;
// overlap disappears even though the content is the same
assert(overlap(a, b).empty);
static test()() @nogc
{
auto a = "It's three o'clock"d;
auto b = a[5 .. 10];
return b.overlap(a);
}
//works at compile-time
static assert(test == "three"d);
}
@safe nothrow unittest
{
static void test(L, R)(L l, R r)
{
assert(overlap(l, r) == [ 100, 12 ]);
assert(overlap(l, l[0 .. 2]) is l[0 .. 2]);
assert(overlap(l, l[3 .. 5]) is l[3 .. 5]);
assert(overlap(l[0 .. 2], l) is l[0 .. 2]);
assert(overlap(l[3 .. 5], l) is l[3 .. 5]);
}
int[] a = [ 10, 11, 12, 13, 14 ];
int[] b = a[1 .. 3];
a[1] = 100;
immutable int[] c = a.idup;
immutable int[] d = c[1 .. 3];
test(a, b);
assert(overlap(a, b.dup).empty);
test(c, d);
assert(overlap(c, d.dup.idup).empty);
}
// https://issues.dlang.org/show_bug.cgi?id=9836
@safe pure nothrow unittest
{
// range primitives for array should work with alias this types
struct Wrapper
{
int[] data;
alias data this;
@property Wrapper save() { return this; }
}
auto w = Wrapper([1,2,3,4]);
std.array.popFront(w); // should work
static assert(isInputRange!Wrapper);
static assert(isForwardRange!Wrapper);
static assert(isBidirectionalRange!Wrapper);
static assert(isRandomAccessRange!Wrapper);
}
private void copyBackwards(T)(T[] src, T[] dest)
{
import core.stdc.string : memmove;
import std.format : format;
assert(src.length == dest.length, format!
"src.length %s must equal dest.length %s"(src.length, dest.length));
if (!__ctfe || hasElaborateCopyConstructor!T)
{
/* insertInPlace relies on dest being uninitialized, so no postblits allowed,
* as this is a MOVE that overwrites the destination, not a COPY.
* BUG: insertInPlace will not work with ctfe and postblits
*/
memmove(dest.ptr, src.ptr, src.length * T.sizeof);
}
else
{
immutable len = src.length;
for (size_t i = len; i-- > 0;)
{
dest[i] = src[i];
}
}
}
/++
Inserts `stuff` (which must be an input range or any number of
implicitly convertible items) in `array` at position `pos`.
Params:
array = The array that `stuff` will be inserted into.
pos = The position in `array` to insert the `stuff`.
stuff = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives),
or any number of implicitly convertible items to insert into `array`.
+/
void insertInPlace(T, U...)(ref T[] array, size_t pos, U stuff)
if (!isSomeString!(T[])
&& allSatisfy!(isInputRangeOrConvertible!T, U) && U.length > 0)
{
static if (allSatisfy!(isInputRangeWithLengthOrConvertible!T, U))
{
import core.internal.lifetime : emplaceRef;
immutable oldLen = array.length;
size_t to_insert = 0;
foreach (i, E; U)
{
static if (is(E : T)) //a single convertible value, not a range
to_insert += 1;
else
to_insert += stuff[i].length;
}
if (to_insert)
{
array.length += to_insert;
// Takes arguments array, pos, stuff
// Spread apart array[] at pos by moving elements
(() @trusted { copyBackwards(array[pos .. oldLen], array[pos+to_insert..$]); })();
// Initialize array[pos .. pos+to_insert] with stuff[]
auto j = 0;
foreach (i, E; U)
{
static if (is(E : T))
{
emplaceRef!T(array[pos + j++], stuff[i]);
}
else
{
foreach (v; stuff[i])
{
emplaceRef!T(array[pos + j++], v);
}
}
}
}
}
else
{
// stuff has some InputRanges in it that don't have length
// assume that stuff to be inserted is typically shorter
// then the array that can be arbitrary big
// TODO: needs a better implementation as there is no need to build an _array_
// a singly-linked list of memory blocks (rope, etc.) will do
auto app = appender!(T[])();
foreach (i, E; U)
app.put(stuff[i]);
insertInPlace(array, pos, app.data);
}
}
/// Ditto
void insertInPlace(T, U...)(ref T[] array, size_t pos, U stuff)
if (isSomeString!(T[]) && allSatisfy!(isCharOrStringOrDcharRange, U))
{
static if (is(Unqual!T == T)
&& allSatisfy!(isInputRangeWithLengthOrConvertible!dchar, U))
{
import std.utf : codeLength, byDchar;
// mutable, can do in place
//helper function: re-encode dchar to Ts and store at *ptr
static T* putDChar(T* ptr, dchar ch)
{
static if (is(T == dchar))
{
*ptr++ = ch;
return ptr;
}
else
{
import std.utf : encode;
T[dchar.sizeof/T.sizeof] buf;
immutable len = encode(buf, ch);
final switch (len)
{
static if (T.sizeof == char.sizeof)
{
case 4:
ptr[3] = buf[3];
goto case;
case 3:
ptr[2] = buf[2];
goto case;
}
case 2:
ptr[1] = buf[1];
goto case;
case 1:
ptr[0] = buf[0];
}
ptr += len;
return ptr;
}
}
size_t to_insert = 0;
//count up the number of *codeunits* to insert
foreach (i, E; U)
to_insert += codeLength!T(stuff[i]);
array.length += to_insert;
@trusted static void moveToRight(T[] arr, size_t gap)
{
static assert(!hasElaborateCopyConstructor!T,
"T must not have an elaborate copy constructor");
import core.stdc.string : memmove;
if (__ctfe)
{
for (size_t i = arr.length - gap; i; --i)
arr[gap + i - 1] = arr[i - 1];
}
else
memmove(arr.ptr + gap, arr.ptr, (arr.length - gap) * T.sizeof);
}
moveToRight(array[pos .. $], to_insert);
auto ptr = array.ptr + pos;
foreach (i, E; U)
{
static if (is(E : dchar))
{
ptr = putDChar(ptr, stuff[i]);
}
else
{
foreach (ch; stuff[i].byDchar)
ptr = putDChar(ptr, ch);
}
}
assert(ptr == array.ptr + pos + to_insert, "(ptr == array.ptr + pos + to_insert) is false");
}
else
{
// immutable/const, just construct a new array
auto app = appender!(T[])();
app.put(array[0 .. pos]);
foreach (i, E; U)
app.put(stuff[i]);
app.put(array[pos..$]);
array = app.data;
}
}
///
@safe pure unittest
{
int[] a = [ 1, 2, 3, 4 ];
a.insertInPlace(2, [ 1, 2 ]);
assert(a == [ 1, 2, 1, 2, 3, 4 ]);
a.insertInPlace(3, 10u, 11);
assert(a == [ 1, 2, 1, 10, 11, 2, 3, 4]);
}
//constraint helpers
private template isInputRangeWithLengthOrConvertible(E)
{
template isInputRangeWithLengthOrConvertible(R)
{
//hasLength not defined for char[], wchar[] and dchar[]
enum isInputRangeWithLengthOrConvertible =
(isInputRange!R && is(typeof(R.init.length))
&& is(ElementType!R : E)) || is(R : E);
}
}
//ditto
private template isCharOrStringOrDcharRange(T)
{
enum isCharOrStringOrDcharRange = isSomeString!T || isSomeChar!T ||
(isInputRange!T && is(ElementType!T : dchar));
}
//ditto
private template isInputRangeOrConvertible(E)
{
template isInputRangeOrConvertible(R)
{
enum isInputRangeOrConvertible =
(isInputRange!R && is(ElementType!R : E)) || is(R : E);
}
}
@system unittest
{
// @system due to insertInPlace
import core.exception;
import std.algorithm.comparison : equal;
import std.algorithm.iteration : filter;
import std.conv : to;
import std.exception;
bool test(T, U, V)(T orig, size_t pos, U toInsert, V result)
{
{
static if (is(T == typeof(T.init.dup)))
auto a = orig.dup;
else
auto a = orig.idup;
a.insertInPlace(pos, toInsert);
if (!equal(a, result))
return false;
}
static if (isInputRange!U)
{
orig.insertInPlace(pos, filter!"true"(toInsert));
return equal(orig, result);
}
else
return true;
}
assert(test([1, 2, 3, 4], 0, [6, 7], [6, 7, 1, 2, 3, 4]));
assert(test([1, 2, 3, 4], 2, [8, 9], [1, 2, 8, 9, 3, 4]));
assert(test([1, 2, 3, 4], 4, [10, 11], [1, 2, 3, 4, 10, 11]));
assert(test([1, 2, 3, 4], 0, 22, [22, 1, 2, 3, 4]));
assert(test([1, 2, 3, 4], 2, 23, [1, 2, 23, 3, 4]));
assert(test([1, 2, 3, 4], 4, 24, [1, 2, 3, 4, 24]));
void testStr(T, U)(string file = __FILE__, size_t line = __LINE__)
{
auto l = to!T("hello");
auto r = to!U(" વિશ્વ");
enforce(test(l, 0, r, " વિશ્વhello"),
new AssertError("testStr failure 1", file, line));
enforce(test(l, 3, r, "hel વિશ્વlo"),
new AssertError("testStr failure 2", file, line));
enforce(test(l, l.length, r, "hello વિશ્વ"),
new AssertError("testStr failure 3", file, line));
}
static foreach (T; AliasSeq!(char, wchar, dchar,
immutable(char), immutable(wchar), immutable(dchar)))
{
static foreach (U; AliasSeq!(char, wchar, dchar,
immutable(char), immutable(wchar), immutable(dchar)))
{
testStr!(T[], U[])();
}
}
// variadic version
bool testVar(T, U...)(T orig, size_t pos, U args)
{
static if (is(T == typeof(T.init.dup)))
auto a = orig.dup;
else
auto a = orig.idup;
auto result = args[$-1];
a.insertInPlace(pos, args[0..$-1]);
if (!equal(a, result))
return false;
return true;
}
assert(testVar([1, 2, 3, 4], 0, 6, 7u, [6, 7, 1, 2, 3, 4]));
assert(testVar([1L, 2, 3, 4], 2, 8, 9L, [1, 2, 8, 9, 3, 4]));
assert(testVar([1L, 2, 3, 4], 4, 10L, 11, [1, 2, 3, 4, 10, 11]));
assert(testVar([1L, 2, 3, 4], 4, [10, 11], 40L, 42L,
[1, 2, 3, 4, 10, 11, 40, 42]));
assert(testVar([1L, 2, 3, 4], 4, 10, 11, [40L, 42],
[1, 2, 3, 4, 10, 11, 40, 42]));
assert(testVar("t".idup, 1, 'e', 's', 't', "test"));
assert(testVar("!!"w.idup, 1, "\u00e9ll\u00f4", 'x', "TTT"w, 'y',
"!\u00e9ll\u00f4xTTTy!"));
assert(testVar("flipflop"d.idup, 4, '_',
"xyz"w, '\U00010143', '_', "abc"d, "__",
"flip_xyz\U00010143_abc__flop"));
}
@system unittest
{
import std.algorithm.comparison : equal;
// insertInPlace interop with postblit
static struct Int
{
int* payload;
this(int k)
{
payload = new int;
*payload = k;
}
this(this)
{
int* np = new int;
*np = *payload;
payload = np;
}
~this()
{
if (payload)
*payload = 0; //'destroy' it
}
@property int getPayload(){ return *payload; }
alias getPayload this;
}
Int[] arr = [Int(1), Int(4), Int(5)];
assert(arr[0] == 1);
insertInPlace(arr, 1, Int(2), Int(3));
assert(equal(arr, [1, 2, 3, 4, 5])); //check it works with postblit
}
@safe unittest
{
import std.exception;
assertCTFEable!(
{
int[] a = [1, 2];
a.insertInPlace(2, 3);
a.insertInPlace(0, -1, 0);
return a == [-1, 0, 1, 2, 3];
});
}
// https://issues.dlang.org/show_bug.cgi?id=6874
@system unittest
{
import core.memory;
// allocate some space
byte[] a;
a.length = 1;
// fill it
a.length = a.capacity;
// write beyond
byte[] b = a[$ .. $];
b.insertInPlace(0, a);
// make sure that reallocation has happened
assert(GC.addrOf(&b[0]) == GC.addrOf(&b[$-1]));
}
/++
Returns whether the `front`s of `lhs` and `rhs` both refer to the
same place in memory, making one of the arrays a slice of the other which
starts at index `0`.
Params:
lhs = the first array to compare
rhs = the second array to compare
Returns:
`true` if $(D lhs.ptr == rhs.ptr), `false` otherwise.
+/
@safe
pure nothrow bool sameHead(T)(in T[] lhs, in T[] rhs)
{
return lhs.ptr == rhs.ptr;
}
///
@safe pure nothrow unittest
{
auto a = [1, 2, 3, 4, 5];
auto b = a[0 .. 2];
assert(a.sameHead(b));
}
/++
Returns whether the `back`s of `lhs` and `rhs` both refer to the
same place in memory, making one of the arrays a slice of the other which
end at index `$`.
Params:
lhs = the first array to compare
rhs = the second array to compare
Returns:
`true` if both arrays are the same length and $(D lhs.ptr == rhs.ptr),
`false` otherwise.
+/
@trusted
pure nothrow bool sameTail(T)(in T[] lhs, in T[] rhs)
{
return lhs.ptr + lhs.length == rhs.ptr + rhs.length;
}
///
@safe pure nothrow unittest
{
auto a = [1, 2, 3, 4, 5];
auto b = a[3..$];
assert(a.sameTail(b));
}
@safe pure nothrow unittest
{
static foreach (T; AliasSeq!(int[], const(int)[], immutable(int)[], const int[], immutable int[]))
{{
T a = [1, 2, 3, 4, 5];
T b = a;
T c = a[1 .. $];
T d = a[0 .. 1];
T e = null;
assert(sameHead(a, a));
assert(sameHead(a, b));
assert(!sameHead(a, c));
assert(sameHead(a, d));
assert(!sameHead(a, e));
assert(sameTail(a, a));
assert(sameTail(a, b));
assert(sameTail(a, c));
assert(!sameTail(a, d));
assert(!sameTail(a, e));
//verifies R-value compatibilty
assert(a.sameHead(a[0 .. 0]));
assert(a.sameTail(a[$ .. $]));
}}
}
/**
Params:
s = an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
or a dynamic array
n = number of times to repeat `s`
Returns:
An array that consists of `s` repeated `n` times. This function allocates, fills, and
returns a new array.
See_Also:
For a lazy version, refer to $(REF repeat, std,range).
*/
ElementEncodingType!S[] replicate(S)(S s, size_t n)
if (isDynamicArray!S)
{
alias RetType = ElementEncodingType!S[];
// Optimization for return join(std.range.repeat(s, n));
if (n == 0)
return RetType.init;
if (n == 1)
return cast(RetType) s;
auto r = new Unqual!(typeof(s[0]))[n * s.length];
if (s.length == 1)
r[] = s[0];
else
{
immutable len = s.length, nlen = n * len;
for (size_t i = 0; i < nlen; i += len)
{
r[i .. i + len] = s[];
}
}
return r;
}
/// ditto
ElementType!S[] replicate(S)(S s, size_t n)
if (isInputRange!S && !isDynamicArray!S)
{
import std.range : repeat;
return join(std.range.repeat(s, n));
}
///
@safe unittest
{
auto a = "abc";
auto s = replicate(a, 3);
assert(s == "abcabcabc");
auto b = [1, 2, 3];
auto c = replicate(b, 3);
assert(c == [1, 2, 3, 1, 2, 3, 1, 2, 3]);
auto d = replicate(b, 0);
assert(d == []);
}
@safe unittest
{
import std.conv : to;
static foreach (S; AliasSeq!(string, wstring, dstring, char[], wchar[], dchar[]))
{{
immutable S t = "abc";
assert(replicate(to!S("1234"), 0) is null);
assert(replicate(to!S("1234"), 0) is null);
assert(replicate(to!S("1234"), 1) == "1234");
assert(replicate(to!S("1234"), 2) == "12341234");
assert(replicate(to!S("1"), 4) == "1111");
assert(replicate(t, 3) == "abcabcabc");
assert(replicate(cast(S) null, 4) is null);
}}
}
/++
Eagerly splits `range` into an array, using `sep` as the delimiter.
When no delimiter is provided, strings are split into an array of words,
using whitespace as delimiter.
Runs of whitespace are merged together (no empty words are produced).
The `range` must be a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives).
The separator can be a value of the same type as the elements in `range`
or it can be another forward `range`.
Params:
s = the string to split by word if no separator is given
range = the range to split
sep = a value of the same type as the elements of `range` or another
isTerminator = a predicate that splits the range when it returns `true`.
Returns:
An array containing the divided parts of `range` (or the words of `s`).
See_Also:
$(REF splitter, std,algorithm,iteration) for a lazy version without allocating memory.
$(REF splitter, std,regex) for a version that splits using a regular
expression defined separator.
+/
S[] split(S)(S s) @safe pure
if (isSomeString!S)
{
size_t istart;
bool inword = false;
auto result = appender!(S[]);
foreach (i, dchar c ; s)
{
import std.uni : isWhite;
if (isWhite(c))
{
if (inword)
{
put(result, s[istart .. i]);
inword = false;
}
}
else
{
if (!inword)
{
istart = i;
inword = true;
}
}
}
if (inword)
put(result, s[istart .. $]);
return result.data;
}
///
@safe unittest
{
import std.uni : isWhite;
assert("Learning,D,is,fun".split(",") == ["Learning", "D", "is", "fun"]);
assert("Learning D is fun".split!isWhite == ["Learning", "D", "is", "fun"]);
assert("Learning D is fun".split(" D ") == ["Learning", "is fun"]);
}
///
@safe unittest
{
string str = "Hello World!";
assert(str.split == ["Hello", "World!"]);
string str2 = "Hello\t\tWorld\t!";
assert(str2.split == ["Hello", "World", "!"]);
}
@safe unittest
{
import std.conv : to;
import std.format;
import std.typecons;
static auto makeEntry(S)(string l, string[] r)
{return tuple(l.to!S(), r.to!(S[])());}
static foreach (S; AliasSeq!(string, wstring, dstring,))
{{
auto entries =
[
makeEntry!S("", []),
makeEntry!S(" ", []),
makeEntry!S("hello", ["hello"]),
makeEntry!S(" hello ", ["hello"]),
makeEntry!S(" h e l l o ", ["h", "e", "l", "l", "o"]),
makeEntry!S("peter\t\npaul\rjerry", ["peter", "paul", "jerry"]),
makeEntry!S(" \t\npeter paul\tjerry \n", ["peter", "paul", "jerry"]),
makeEntry!S("\u2000日\u202F本\u205F語\u3000", ["日", "本", "語"]),
makeEntry!S(" 哈・郎博尔德} ___一个", ["哈・郎博尔德}", "___一个"])
];
foreach (entry; entries)
assert(entry[0].split() == entry[1], format("got: %s, expected: %s.", entry[0].split(), entry[1]));
}}
//Just to test that an immutable is split-able
immutable string s = " \t\npeter paul\tjerry \n";
assert(split(s) == ["peter", "paul", "jerry"]);
}
@safe unittest //purity, ctfe ...
{
import std.exception;
void dg() @safe pure {
assert(split("hello world"c) == ["hello"c, "world"c]);
assert(split("hello world"w) == ["hello"w, "world"w]);
assert(split("hello world"d) == ["hello"d, "world"d]);
}
dg();
assertCTFEable!dg;
}
///
@safe unittest
{
assert(split("hello world") == ["hello","world"]);
assert(split("192.168.0.1", ".") == ["192", "168", "0", "1"]);
auto a = split([1, 2, 3, 4, 5, 1, 2, 3, 4, 5], [2, 3]);
assert(a == [[1], [4, 5, 1], [4, 5]]);
}
///ditto
auto split(Range, Separator)(Range range, Separator sep)
if (isForwardRange!Range && (
is(typeof(ElementType!Range.init == Separator.init)) ||
is(typeof(ElementType!Range.init == ElementType!Separator.init)) && isForwardRange!Separator
))
{
import std.algorithm.iteration : splitter;
return range.splitter(sep).array;
}
///ditto
auto split(alias isTerminator, Range)(Range range)
if (isForwardRange!Range && is(typeof(unaryFun!isTerminator(range.front))))
{
import std.algorithm.iteration : splitter;
return range.splitter!isTerminator.array;
}
@safe unittest
{
import std.algorithm.comparison : cmp;
import std.conv;
static foreach (S; AliasSeq!(string, wstring, dstring,
immutable(string), immutable(wstring), immutable(dstring),
char[], wchar[], dchar[],
const(char)[], const(wchar)[], const(dchar)[],
const(char[]), immutable(char[])))
{{
S s = to!S(",peter,paul,jerry,");
auto words = split(s, ",");
assert(words.length == 5, text(words.length));
assert(cmp(words[0], "") == 0);
assert(cmp(words[1], "peter") == 0);
assert(cmp(words[2], "paul") == 0);
assert(cmp(words[3], "jerry") == 0);
assert(cmp(words[4], "") == 0);
auto s1 = s[0 .. s.length - 1]; // lop off trailing ','
words = split(s1, ",");
assert(words.length == 4);
assert(cmp(words[3], "jerry") == 0);
auto s2 = s1[1 .. s1.length]; // lop off leading ','
words = split(s2, ",");
assert(words.length == 3);
assert(cmp(words[0], "peter") == 0);
auto s3 = to!S(",,peter,,paul,,jerry,,");
words = split(s3, ",,");
assert(words.length == 5);
assert(cmp(words[0], "") == 0);
assert(cmp(words[1], "peter") == 0);
assert(cmp(words[2], "paul") == 0);
assert(cmp(words[3], "jerry") == 0);
assert(cmp(words[4], "") == 0);
auto s4 = s3[0 .. s3.length - 2]; // lop off trailing ',,'
words = split(s4, ",,");
assert(words.length == 4);
assert(cmp(words[3], "jerry") == 0);
auto s5 = s4[2 .. s4.length]; // lop off leading ',,'
words = split(s5, ",,");
assert(words.length == 3);
assert(cmp(words[0], "peter") == 0);
}}
}
/+
Conservative heuristic to determine if a range can be iterated cheaply.
Used by `join` in decision to do an extra iteration of the range to
compute the resultant length. If iteration is not cheap then precomputing
length could be more expensive than using `Appender`.
For now, we only assume arrays are cheap to iterate.
+/
private enum bool hasCheapIteration(R) = isArray!R;
/++
Eagerly concatenates all of the ranges in `ror` together (with the GC)
into one array using `sep` as the separator if present.
Params:
ror = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of input ranges
sep = An input range, or a single element, to join the ranges on
Returns:
An array of elements
See_Also:
For a lazy version, see $(REF joiner, std,algorithm,iteration)
+/
ElementEncodingType!(ElementType!RoR)[] join(RoR, R)(RoR ror, scope R sep)
if (isInputRange!RoR &&
isInputRange!(Unqual!(ElementType!RoR)) &&
isInputRange!R &&
(is(immutable ElementType!(ElementType!RoR) == immutable ElementType!R) ||
(isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!(ElementType!R))
))
{
alias RetType = typeof(return);
alias RetTypeElement = Unqual!(ElementEncodingType!RetType);
alias RoRElem = ElementType!RoR;
if (ror.empty)
return RetType.init;
// Constraint only requires input range for sep.
// This converts sep to an array (forward range) if it isn't one,
// and makes sure it has the same string encoding for string types.
static if (isSomeString!RetType &&
!is(immutable ElementEncodingType!RetType == immutable ElementEncodingType!R))
{
import std.conv : to;
auto sepArr = to!RetType(sep);
}
else static if (!isArray!R)
auto sepArr = array(sep);
else
alias sepArr = sep;
static if (hasCheapIteration!RoR && (hasLength!RoRElem || isNarrowString!RoRElem))
{
import core.internal.lifetime : emplaceRef;
size_t length; // length of result array
size_t rorLength; // length of range ror
foreach (r; ror.save)
{
length += r.length;
++rorLength;
}
if (!rorLength)
return null;
length += (rorLength - 1) * sepArr.length;
auto result = (() @trusted => uninitializedArray!(RetTypeElement[])(length))();
size_t len;
foreach (e; ror.front)
emplaceRef(result[len++], e);
ror.popFront();
foreach (r; ror)
{
foreach (e; sepArr)
emplaceRef(result[len++], e);
foreach (e; r)
emplaceRef(result[len++], e);
}
assert(len == result.length);
return (() @trusted => cast(RetType) result)();
}
else
{
auto result = appender!RetType();
put(result, ror.front);
ror.popFront();
for (; !ror.empty; ror.popFront())
{
put(result, sepArr);
put(result, ror.front);
}
return result.data;
}
}
// https://issues.dlang.org/show_bug.cgi?id=14230
@safe unittest
{
string[] ary = ["","aa","bb","cc"]; // leaded by _empty_ element
assert(ary.join(" @") == " @aa @bb @cc"); // OK in 2.067b1 and olders
}
// https://issues.dlang.org/show_bug.cgi?id=21337
@system unittest
{
import std.algorithm.iteration : map;
static class Once
{
bool empty;
void popFront()
{
empty = true;
}
int front()
{
return 0;
}
}
assert([1, 2].map!"[a]".join(new Once) == [1, 0, 2]);
}
/// Ditto
ElementEncodingType!(ElementType!RoR)[] join(RoR, E)(RoR ror, scope E sep)
if (isInputRange!RoR &&
isInputRange!(Unqual!(ElementType!RoR)) &&
((is(E : ElementType!(ElementType!RoR))) ||
(!autodecodeStrings && isSomeChar!(ElementType!(ElementType!RoR)) &&
isSomeChar!E)))
{
alias RetType = typeof(return);
alias RetTypeElement = Unqual!(ElementEncodingType!RetType);
alias RoRElem = ElementType!RoR;
if (ror.empty)
return RetType.init;
static if (hasCheapIteration!RoR && (hasLength!RoRElem || isNarrowString!RoRElem))
{
static if (isSomeChar!E && isSomeChar!RetTypeElement && E.sizeof > RetTypeElement.sizeof)
{
import std.utf : encode;
RetTypeElement[4 / RetTypeElement.sizeof] encodeSpace;
immutable size_t sepArrLength = encode(encodeSpace, sep);
return join(ror, encodeSpace[0 .. sepArrLength]);
}
else
{
import core.internal.lifetime : emplaceRef;
import std.format : format;
size_t length;
size_t rorLength;
foreach (r; ror.save)
{
length += r.length;
++rorLength;
}
if (!rorLength)
return null;
length += rorLength - 1;
auto result = uninitializedArray!(RetTypeElement[])(length);
size_t len;
foreach (e; ror.front)
emplaceRef(result[len++], e);
ror.popFront();
foreach (r; ror)
{
emplaceRef(result[len++], sep);
foreach (e; r)
emplaceRef(result[len++], e);
}
assert(len == result.length, format!
"len %s must equal result.lenght %s"(len, result.length));
return (() @trusted => cast(RetType) result)();
}
}
else
{
auto result = appender!RetType();
put(result, ror.front);
ror.popFront();
for (; !ror.empty; ror.popFront())
{
put(result, sep);
put(result, ror.front);
}
return result.data;
}
}
// https://issues.dlang.org/show_bug.cgi?id=10895
@safe unittest
{
class A
{
string name;
alias name this;
this(string name) { this.name = name; }
}
auto a = [new A(`foo`)];
assert(a[0].length == 3);
auto temp = join(a, " ");
assert(a[0].length == 3);
assert(temp.length == 3);
}
// https://issues.dlang.org/show_bug.cgi?id=14230
@safe unittest
{
string[] ary = ["","aa","bb","cc"];
assert(ary.join('@') == "@aa@bb@cc");
}
/// Ditto
ElementEncodingType!(ElementType!RoR)[] join(RoR)(RoR ror)
if (isInputRange!RoR &&
isInputRange!(Unqual!(ElementType!RoR)))
{
alias RetType = typeof(return);
alias ConstRetTypeElement = ElementEncodingType!RetType;
static if (isAssignable!(Unqual!ConstRetTypeElement, ConstRetTypeElement))
{
alias RetTypeElement = Unqual!ConstRetTypeElement;
}
else
{
alias RetTypeElement = ConstRetTypeElement;
}
alias RoRElem = ElementType!RoR;
if (ror.empty)
return RetType.init;
static if (hasCheapIteration!RoR && (hasLength!RoRElem || isNarrowString!RoRElem))
{
import core.internal.lifetime : emplaceRef;
size_t length;
foreach (r; ror.save)
length += r.length;
auto result = (() @trusted => uninitializedArray!(RetTypeElement[])(length))();
size_t len;
foreach (r; ror)
foreach (e; r)
emplaceRef!RetTypeElement(result[len++], e);
assert(len == result.length,
"emplaced an unexpected number of elements");
return (() @trusted => cast(RetType) result)();
}
else
{
auto result = appender!RetType();
for (; !ror.empty; ror.popFront())
put(result, ror.front);
return result.data;
}
}
///
@safe pure nothrow unittest
{
assert(join(["hello", "silly", "world"], " ") == "hello silly world");
assert(join(["hello", "silly", "world"]) == "hellosillyworld");
assert(join([[1, 2, 3], [4, 5]], [72, 73]) == [1, 2, 3, 72, 73, 4, 5]);
assert(join([[1, 2, 3], [4, 5]]) == [1, 2, 3, 4, 5]);
const string[] arr = ["apple", "banana"];
assert(arr.join(",") == "apple,banana");
assert(arr.join() == "applebanana");
}
@safe pure unittest
{
import std.conv : to;
import std.range.primitives : autodecodeStrings;
static foreach (T; AliasSeq!(string,wstring,dstring))
{{
auto arr2 = "Здравствуй Мир Unicode".to!(T);
auto arr = ["Здравствуй", "Мир", "Unicode"].to!(T[]);
assert(join(arr) == "ЗдравствуйМирUnicode");
static foreach (S; AliasSeq!(char,wchar,dchar))
{{
auto jarr = arr.join(to!S(' '));
static assert(is(typeof(jarr) == T));
assert(jarr == arr2);
}}
static foreach (S; AliasSeq!(string,wstring,dstring))
{{
auto jarr = arr.join(to!S(" "));
static assert(is(typeof(jarr) == T));
assert(jarr == arr2);
}}
}}
static foreach (T; AliasSeq!(string,wstring,dstring))
{{
auto arr2 = "Здравствуй\u047CМир\u047CUnicode".to!(T);
auto arr = ["Здравствуй", "Мир", "Unicode"].to!(T[]);
static foreach (S; AliasSeq!(wchar,dchar))
{{
auto jarr = arr.join(to!S('\u047C'));
static assert(is(typeof(jarr) == T));
assert(jarr == arr2);
}}
}}
const string[] arr = ["apple", "banana"];
assert(arr.join(',') == "apple,banana");
}
@safe unittest
{
class A { }
const A[][] array;
auto result = array.join; // can't remove constness, so don't try
static assert(is(typeof(result) == const(A)[]));
}
@safe unittest
{
import std.algorithm;
import std.conv : to;
import std.range;
static foreach (R; AliasSeq!(string, wstring, dstring))
{{
R word1 = "日本語";
R word2 = "paul";
R word3 = "jerry";
R[] words = [word1, word2, word3];
auto filteredWord1 = filter!"true"(word1);
auto filteredLenWord1 = takeExactly(filteredWord1, word1.walkLength());
auto filteredWord2 = filter!"true"(word2);
auto filteredLenWord2 = takeExactly(filteredWord2, word2.walkLength());
auto filteredWord3 = filter!"true"(word3);
auto filteredLenWord3 = takeExactly(filteredWord3, word3.walkLength());
auto filteredWordsArr = [filteredWord1, filteredWord2, filteredWord3];
auto filteredLenWordsArr = [filteredLenWord1, filteredLenWord2, filteredLenWord3];
auto filteredWords = filter!"true"(filteredWordsArr);
static foreach (S; AliasSeq!(string, wstring, dstring))
{{
assert(join(filteredWords, to!S(", ")) == "日本語, paul, jerry");
assert(join(filteredWords, to!(ElementType!S)(',')) == "日本語,paul,jerry");
assert(join(filteredWordsArr, to!(ElementType!(S))(',')) == "日本語,paul,jerry");
assert(join(filteredWordsArr, to!S(", ")) == "日本語, paul, jerry");
assert(join(filteredWordsArr, to!(ElementType!(S))(',')) == "日本語,paul,jerry");
assert(join(filteredLenWordsArr, to!S(", ")) == "日本語, paul, jerry");
assert(join(filter!"true"(words), to!S(", ")) == "日本語, paul, jerry");
assert(join(words, to!S(", ")) == "日本語, paul, jerry");
assert(join(filteredWords, to!S("")) == "日本語pauljerry");
assert(join(filteredWordsArr, to!S("")) == "日本語pauljerry");
assert(join(filteredLenWordsArr, to!S("")) == "日本語pauljerry");
assert(join(filter!"true"(words), to!S("")) == "日本語pauljerry");
assert(join(words, to!S("")) == "日本語pauljerry");
assert(join(filter!"true"([word1]), to!S(", ")) == "日本語");
assert(join([filteredWord1], to!S(", ")) == "日本語");
assert(join([filteredLenWord1], to!S(", ")) == "日本語");
assert(join(filter!"true"([filteredWord1]), to!S(", ")) == "日本語");
assert(join([word1], to!S(", ")) == "日本語");
assert(join(filteredWords, to!S(word1)) == "日本語日本語paul日本語jerry");
assert(join(filteredWordsArr, to!S(word1)) == "日本語日本語paul日本語jerry");
assert(join(filteredLenWordsArr, to!S(word1)) == "日本語日本語paul日本語jerry");
assert(join(filter!"true"(words), to!S(word1)) == "日本語日本語paul日本語jerry");
assert(join(words, to!S(word1)) == "日本語日本語paul日本語jerry");
auto filterComma = filter!"true"(to!S(", "));
assert(join(filteredWords, filterComma) == "日本語, paul, jerry");
assert(join(filteredWordsArr, filterComma) == "日本語, paul, jerry");
assert(join(filteredLenWordsArr, filterComma) == "日本語, paul, jerry");
assert(join(filter!"true"(words), filterComma) == "日本語, paul, jerry");
assert(join(words, filterComma) == "日本語, paul, jerry");
}}
assert(join(filteredWords) == "日本語pauljerry");
assert(join(filteredWordsArr) == "日本語pauljerry");
assert(join(filteredLenWordsArr) == "日本語pauljerry");
assert(join(filter!"true"(words)) == "日本語pauljerry");
assert(join(words) == "日本語pauljerry");
assert(join(filteredWords, filter!"true"(", ")) == "日本語, paul, jerry");
assert(join(filteredWordsArr, filter!"true"(", ")) == "日本語, paul, jerry");
assert(join(filteredLenWordsArr, filter!"true"(", ")) == "日本語, paul, jerry");
assert(join(filter!"true"(words), filter!"true"(", ")) == "日本語, paul, jerry");
assert(join(words, filter!"true"(", ")) == "日本語, paul, jerry");
assert(join(filter!"true"(cast(typeof(filteredWordsArr))[]), ", ").empty);
assert(join(cast(typeof(filteredWordsArr))[], ", ").empty);
assert(join(cast(typeof(filteredLenWordsArr))[], ", ").empty);
assert(join(filter!"true"(cast(R[])[]), ", ").empty);
assert(join(cast(R[])[], ", ").empty);
assert(join(filter!"true"(cast(typeof(filteredWordsArr))[])).empty);
assert(join(cast(typeof(filteredWordsArr))[]).empty);
assert(join(cast(typeof(filteredLenWordsArr))[]).empty);
assert(join(filter!"true"(cast(R[])[])).empty);
assert(join(cast(R[])[]).empty);
}}
assert(join([[1, 2], [41, 42]], [5, 6]) == [1, 2, 5, 6, 41, 42]);
assert(join([[1, 2], [41, 42]], cast(int[])[]) == [1, 2, 41, 42]);
assert(join([[1, 2]], [5, 6]) == [1, 2]);
assert(join(cast(int[][])[], [5, 6]).empty);
assert(join([[1, 2], [41, 42]]) == [1, 2, 41, 42]);
assert(join(cast(int[][])[]).empty);
alias f = filter!"true";
assert(join([[1, 2], [41, 42]], [5, 6]) == [1, 2, 5, 6, 41, 42]);
assert(join(f([[1, 2], [41, 42]]), [5, 6]) == [1, 2, 5, 6, 41, 42]);
assert(join([f([1, 2]), f([41, 42])], [5, 6]) == [1, 2, 5, 6, 41, 42]);
assert(join(f([f([1, 2]), f([41, 42])]), [5, 6]) == [1, 2, 5, 6, 41, 42]);
assert(join([[1, 2], [41, 42]], f([5, 6])) == [1, 2, 5, 6, 41, 42]);
assert(join(f([[1, 2], [41, 42]]), f([5, 6])) == [1, 2, 5, 6, 41, 42]);
assert(join([f([1, 2]), f([41, 42])], f([5, 6])) == [1, 2, 5, 6, 41, 42]);
assert(join(f([f([1, 2]), f([41, 42])]), f([5, 6])) == [1, 2, 5, 6, 41, 42]);
}
// https://issues.dlang.org/show_bug.cgi?id=10683
@safe unittest
{
import std.range : join;
import std.typecons : tuple;
assert([[tuple(1)]].join == [tuple(1)]);
assert([[tuple("x")]].join == [tuple("x")]);
}
// https://issues.dlang.org/show_bug.cgi?id=13877
@safe unittest
{
// Test that the range is iterated only once.
import std.algorithm.iteration : map;
int c = 0;
auto j1 = [1, 2, 3].map!(_ => [c++]).join;
assert(c == 3);
assert(j1 == [0, 1, 2]);
c = 0;
auto j2 = [1, 2, 3].map!(_ => [c++]).join(9);
assert(c == 3);
assert(j2 == [0, 9, 1, 9, 2]);
c = 0;
auto j3 = [1, 2, 3].map!(_ => [c++]).join([9]);
assert(c == 3);
assert(j3 == [0, 9, 1, 9, 2]);
}
/++
Replace occurrences of `from` with `to` in `subject` in a new array.
Params:
subject = the array to scan
from = the item to replace
to = the item to replace all instances of `from` with
Returns:
A new array without changing the contents of `subject`, or the original
array if no match is found.
See_Also:
$(REF substitute, std,algorithm,iteration) for a lazy replace.
+/
E[] replace(E, R1, R2)(E[] subject, R1 from, R2 to)
if ((isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2)) ||
is(Unqual!E : Unqual!R1))
{
import std.algorithm.searching : find;
import std.range : dropOne;
static if (isInputRange!R1)
{
if (from.empty) return subject;
alias rSave = a => a.save;
}
else
{
alias rSave = a => a;
}
auto balance = find(subject, rSave(from));
if (balance.empty)
return subject;
auto app = appender!(E[])();
app.put(subject[0 .. subject.length - balance.length]);
app.put(rSave(to));
// replacing an element in an array is different to a range replacement
static if (is(Unqual!E : Unqual!R1))
replaceInto(app, balance.dropOne, from, to);
else
replaceInto(app, balance[from.length .. $], from, to);
return app.data;
}
///
@safe unittest
{
assert("Hello Wörld".replace("o Wö", "o Wo") == "Hello World");
assert("Hello Wörld".replace("l", "h") == "Hehho Wörhd");
}
@safe unittest
{
assert([1, 2, 3, 4, 2].replace([2], [5]) == [1, 5, 3, 4, 5]);
assert([3, 3, 3].replace([3], [0]) == [0, 0, 0]);
assert([3, 3, 4, 3].replace([3, 3], [1, 1, 1]) == [1, 1, 1, 4, 3]);
}
// https://issues.dlang.org/show_bug.cgi?id=18215
@safe unittest
{
auto arr = ["aaa.dd", "b"];
arr = arr.replace("aaa.dd", ".");
assert(arr == [".", "b"]);
arr = ["_", "_", "aaa.dd", "b", "c", "aaa.dd", "e"];
arr = arr.replace("aaa.dd", ".");
assert(arr == ["_", "_", ".", "b", "c", ".", "e"]);
}
// https://issues.dlang.org/show_bug.cgi?id=18215
@safe unittest
{
assert([[0], [1, 2], [0], [3]].replace([0], [4]) == [[4], [1, 2], [4], [3]]);
assert([[0], [1, 2], [0], [3], [1, 2]]
.replace([1, 2], [0]) == [[0], [0], [0], [3], [0]]);
assert([[0], [1, 2], [0], [3], [1, 2], [0], [1, 2]]
.replace([[0], [1, 2]], [[4]]) == [[4], [0], [3], [1, 2], [4]]);
}
// https://issues.dlang.org/show_bug.cgi?id=10930
@safe unittest
{
assert([0, 1, 2].replace(1, 4) == [0, 4, 2]);
assert("äbö".replace('ä', 'a') == "abö");
}
// empty array
@safe unittest
{
int[] arr;
assert(replace(arr, 1, 2) == []);
}
/++
Replace occurrences of `from` with `to` in `subject` and output the result into
`sink`.
Params:
sink = an $(REF_ALTTEXT output range, isOutputRange, std,range,primitives)
subject = the array to scan
from = the item to replace
to = the item to replace all instances of `from` with
See_Also:
$(REF substitute, std,algorithm,iteration) for a lazy replace.
+/
void replaceInto(E, Sink, R1, R2)(Sink sink, E[] subject, R1 from, R2 to)
if (isOutputRange!(Sink, E) &&
((isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2)) ||
is(Unqual!E : Unqual!R1)))
{
import std.algorithm.searching : find;
import std.range : dropOne;
static if (isInputRange!R1)
{
if (from.empty)
{
sink.put(subject);
return;
}
alias rSave = a => a.save;
}
else
{
alias rSave = a => a;
}
for (;;)
{
auto balance = find(subject, rSave(from));
if (balance.empty)
{
sink.put(subject);
break;
}
sink.put(subject[0 .. subject.length - balance.length]);
sink.put(rSave(to));
// replacing an element in an array is different to a range replacement
static if (is(Unqual!E : Unqual!R1))
subject = balance.dropOne;
else
subject = balance[from.length .. $];
}
}
///
@safe unittest
{
auto arr = [1, 2, 3, 4, 5];
auto from = [2, 3];
auto to = [4, 6];
auto sink = appender!(int[])();
replaceInto(sink, arr, from, to);
assert(sink.data == [1, 4, 6, 4, 5]);
}
// empty array
@safe unittest
{
auto sink = appender!(int[])();
int[] arr;
replaceInto(sink, arr, 1, 2);
assert(sink.data == []);
}
@safe unittest
{
import std.algorithm.comparison : cmp;
import std.conv : to;
static foreach (S; AliasSeq!(string, wstring, dstring, char[], wchar[], dchar[]))
{
static foreach (T; AliasSeq!(string, wstring, dstring, char[], wchar[], dchar[]))
{{
auto s = to!S("This is a foo foo list");
auto from = to!T("foo");
auto into = to!S("silly");
S r;
int i;
r = replace(s, from, into);
i = cmp(r, "This is a silly silly list");
assert(i == 0);
r = replace(s, to!S(""), into);
i = cmp(r, "This is a foo foo list");
assert(i == 0);
assert(replace(r, to!S("won't find this"), to!S("whatever")) is r);
}}
}
immutable s = "This is a foo foo list";
assert(replace(s, "foo", "silly") == "This is a silly silly list");
}
@safe unittest
{
import std.algorithm.searching : skipOver;
import std.conv : to;
struct CheckOutput(C)
{
C[] desired;
this(C[] arr){ desired = arr; }
void put(C[] part){ assert(skipOver(desired, part)); }
}
static foreach (S; AliasSeq!(string, wstring, dstring, char[], wchar[], dchar[]))
{{
alias Char = ElementEncodingType!S;
S s = to!S("yet another dummy text, yet another ...");
S from = to!S("yet another");
S into = to!S("some");
replaceInto(CheckOutput!(Char)(to!S("some dummy text, some ..."))
, s, from, into);
}}
}
// https://issues.dlang.org/show_bug.cgi?id=10930
@safe unittest
{
auto sink = appender!(int[])();
replaceInto(sink, [0, 1, 2], 1, 5);
assert(sink.data == [0, 5, 2]);
auto sink2 = appender!(dchar[])();
replaceInto(sink2, "äbö", 'ä', 'a');
assert(sink2.data == "abö");
}
/++
Replaces elements from `array` with indices ranging from `from`
(inclusive) to `to` (exclusive) with the range `stuff`.
Params:
subject = the array to scan
from = the starting index
to = the ending index
stuff = the items to replace in-between `from` and `to`
Returns:
A new array without changing the contents of `subject`.
See_Also:
$(REF substitute, std,algorithm,iteration) for a lazy replace.
+/
T[] replace(T, Range)(T[] subject, size_t from, size_t to, Range stuff)
if (isInputRange!Range &&
(is(ElementType!Range : T) ||
isSomeString!(T[]) && is(ElementType!Range : dchar)))
{
static if (hasLength!Range && is(ElementEncodingType!Range : T))
{
import std.algorithm.mutation : copy;
assert(from <= to, "from must be before or equal to to");
immutable sliceLen = to - from;
auto retval = new Unqual!(T)[](subject.length - sliceLen + stuff.length);
retval[0 .. from] = subject[0 .. from];
if (!stuff.empty)
copy(stuff, retval[from .. from + stuff.length]);
retval[from + stuff.length .. $] = subject[to .. $];
static if (is(T == const) || is(T == immutable))
{
return () @trusted { return cast(T[]) retval; } ();
}
else
{
return cast(T[]) retval;
}
}
else
{
auto app = appender!(T[])();
app.put(subject[0 .. from]);
app.put(stuff);
app.put(subject[to .. $]);
return app.data;
}
}
///
@safe unittest
{
auto a = [ 1, 2, 3, 4 ];
auto b = a.replace(1, 3, [ 9, 9, 9 ]);
assert(a == [ 1, 2, 3, 4 ]);
assert(b == [ 1, 9, 9, 9, 4 ]);
}
@system unittest
{
import core.exception;
import std.algorithm.iteration : filter;
import std.conv : to;
import std.exception;
auto a = [ 1, 2, 3, 4 ];
assert(replace(a, 0, 0, [5, 6, 7]) == [5, 6, 7, 1, 2, 3, 4]);
assert(replace(a, 0, 2, cast(int[])[]) == [3, 4]);
assert(replace(a, 0, 4, [5, 6, 7]) == [5, 6, 7]);
assert(replace(a, 0, 2, [5, 6, 7]) == [5, 6, 7, 3, 4]);
assert(replace(a, 2, 4, [5, 6, 7]) == [1, 2, 5, 6, 7]);
assert(replace(a, 0, 0, filter!"true"([5, 6, 7])) == [5, 6, 7, 1, 2, 3, 4]);
assert(replace(a, 0, 2, filter!"true"(cast(int[])[])) == [3, 4]);
assert(replace(a, 0, 4, filter!"true"([5, 6, 7])) == [5, 6, 7]);
assert(replace(a, 0, 2, filter!"true"([5, 6, 7])) == [5, 6, 7, 3, 4]);
assert(replace(a, 2, 4, filter!"true"([5, 6, 7])) == [1, 2, 5, 6, 7]);
assert(a == [ 1, 2, 3, 4 ]);
void testStr(T, U)(string file = __FILE__, size_t line = __LINE__)
{
auto l = to!T("hello");
auto r = to!U(" world");
enforce(replace(l, 0, 0, r) == " worldhello",
new AssertError("testStr failure 1", file, line));
enforce(replace(l, 0, 3, r) == " worldlo",
new AssertError("testStr failure 2", file, line));
enforce(replace(l, 3, l.length, r) == "hel world",
new AssertError("testStr failure 3", file, line));
enforce(replace(l, 0, l.length, r) == " world",
new AssertError("testStr failure 4", file, line));
enforce(replace(l, l.length, l.length, r) == "hello world",
new AssertError("testStr failure 5", file, line));
}
testStr!(string, string)();
testStr!(string, wstring)();
testStr!(string, dstring)();
testStr!(wstring, string)();
testStr!(wstring, wstring)();
testStr!(wstring, dstring)();
testStr!(dstring, string)();
testStr!(dstring, wstring)();
testStr!(dstring, dstring)();
enum s = "0123456789";
enum w = "⁰¹²³⁴⁵⁶⁷⁸⁹"w;
enum d = "⁰¹²³⁴⁵⁶⁷⁸⁹"d;
assert(replace(s, 0, 0, "***") == "***0123456789");
assert(replace(s, 10, 10, "***") == "0123456789***");
assert(replace(s, 3, 8, "1012") == "012101289");
assert(replace(s, 0, 5, "43210") == "4321056789");
assert(replace(s, 5, 10, "43210") == "0123443210");
assert(replace(w, 0, 0, "***"w) == "***⁰¹²³⁴⁵⁶⁷⁸⁹"w);
assert(replace(w, 10, 10, "***"w) == "⁰¹²³⁴⁵⁶⁷⁸⁹***"w);
assert(replace(w, 3, 8, "¹⁰¹²"w) == "⁰¹²¹⁰¹²⁸⁹"w);
assert(replace(w, 0, 5, "⁴³²¹⁰"w) == "⁴³²¹⁰⁵⁶⁷⁸⁹"w);
assert(replace(w, 5, 10, "⁴³²¹⁰"w) == "⁰¹²³⁴⁴³²¹⁰"w);
assert(replace(d, 0, 0, "***"d) == "***⁰¹²³⁴⁵⁶⁷⁸⁹"d);
assert(replace(d, 10, 10, "***"d) == "⁰¹²³⁴⁵⁶⁷⁸⁹***"d);
assert(replace(d, 3, 8, "¹⁰¹²"d) == "⁰¹²¹⁰¹²⁸⁹"d);
assert(replace(d, 0, 5, "⁴³²¹⁰"d) == "⁴³²¹⁰⁵⁶⁷⁸⁹"d);
assert(replace(d, 5, 10, "⁴³²¹⁰"d) == "⁰¹²³⁴⁴³²¹⁰"d);
}
// https://issues.dlang.org/show_bug.cgi?id=18166
@safe pure unittest
{
auto str = replace("aaaaa"d, 1, 4, "***"d);
assert(str == "a***a");
}
/++
Replaces elements from `array` with indices ranging from `from`
(inclusive) to `to` (exclusive) with the range `stuff`. Expands or
shrinks the array as needed.
Params:
array = the array to scan
from = the starting index
to = the ending index
stuff = the items to replace in-between `from` and `to`
+/
void replaceInPlace(T, Range)(ref T[] array, size_t from, size_t to, Range stuff)
if (is(typeof(replace(array, from, to, stuff))))
{
static if (isDynamicArray!Range &&
is(Unqual!(ElementEncodingType!Range) == T) &&
!isNarrowString!(T[]))
{
// optimized for homogeneous arrays that can be overwritten.
import std.algorithm.mutation : remove;
import std.typecons : tuple;
if (overlap(array, stuff).length)
{
// use slower/conservative method
array = array[0 .. from] ~ stuff ~ array[to .. $];
}
else if (stuff.length <= to - from)
{
// replacement reduces length
immutable stuffEnd = from + stuff.length;
array[from .. stuffEnd] = stuff[];
if (stuffEnd < to)
array = remove(array, tuple(stuffEnd, to));
}
else
{
// replacement increases length
// @@@TODO@@@: optimize this
immutable replaceLen = to - from;
array[from .. to] = stuff[0 .. replaceLen];
insertInPlace(array, to, stuff[replaceLen .. $]);
}
}
else
{
// default implementation, just do what replace does.
array = replace(array, from, to, stuff);
}
}
///
@safe unittest
{
int[] a = [1, 4, 5];
replaceInPlace(a, 1u, 2u, [2, 3, 4]);
assert(a == [1, 2, 3, 4, 5]);
replaceInPlace(a, 1u, 2u, cast(int[])[]);
assert(a == [1, 3, 4, 5]);
replaceInPlace(a, 1u, 3u, a[2 .. 4]);
assert(a == [1, 4, 5, 5]);
}
// https://issues.dlang.org/show_bug.cgi?id=12889
@safe unittest
{
int[1][] arr = [[0], [1], [2], [3], [4], [5], [6]];
int[1][] stuff = [[0], [1]];
replaceInPlace(arr, 4, 6, stuff);
assert(arr == [[0], [1], [2], [3], [0], [1], [6]]);
}
@system unittest
{
// https://issues.dlang.org/show_bug.cgi?id=14925
char[] a = "mon texte 1".dup;
char[] b = "abc".dup;
replaceInPlace(a, 4, 9, b);
assert(a == "mon abc 1");
// ensure we can replace in place with different encodings
string unicoded = "\U00010437";
string unicodedLong = "\U00010437aaaaa";
string base = "abcXXXxyz";
string result = "abc\U00010437xyz";
string resultLong = "abc\U00010437aaaaaxyz";
size_t repstart = 3;
size_t repend = 3 + 3;
void testStringReplaceInPlace(T, U)()
{
import std.algorithm.comparison : equal;
import std.conv;
auto a = unicoded.to!(U[]);
auto b = unicodedLong.to!(U[]);
auto test = base.to!(T[]);
test.replaceInPlace(repstart, repend, a);
assert(equal(test, result), "Failed for types " ~ T.stringof ~ " and " ~ U.stringof);
test = base.to!(T[]);
test.replaceInPlace(repstart, repend, b);
assert(equal(test, resultLong), "Failed for types " ~ T.stringof ~ " and " ~ U.stringof);
}
import std.meta : AliasSeq;
alias allChars = AliasSeq!(char, immutable(char), const(char),
wchar, immutable(wchar), const(wchar),
dchar, immutable(dchar), const(dchar));
foreach (T; allChars)
foreach (U; allChars)
testStringReplaceInPlace!(T, U)();
void testInout(inout(int)[] a)
{
// will be transferred to the 'replace' function
replaceInPlace(a, 1, 2, [1,2,3]);
}
}
@safe unittest
{
// the constraint for the first overload used to match this, which wouldn't compile.
import std.algorithm.comparison : equal;
long[] a = [1L, 2, 3];
int[] b = [4, 5, 6];
a.replaceInPlace(1, 2, b);
assert(equal(a, [1L, 4, 5, 6, 3]));
}
@system unittest
{
import core.exception;
import std.algorithm.comparison : equal;
import std.algorithm.iteration : filter;
import std.conv : to;
import std.exception;
bool test(T, U, V)(T orig, size_t from, size_t to, U toReplace, V result)
{
{
static if (is(T == typeof(T.init.dup)))
auto a = orig.dup;
else
auto a = orig.idup;
a.replaceInPlace(from, to, toReplace);
if (!equal(a, result))
return false;
}
static if (isInputRange!U)
{
orig.replaceInPlace(from, to, filter!"true"(toReplace));
return equal(orig, result);
}
else
return true;
}
assert(test([1, 2, 3, 4], 0, 0, [5, 6, 7], [5, 6, 7, 1, 2, 3, 4]));
assert(test([1, 2, 3, 4], 0, 2, cast(int[])[], [3, 4]));
assert(test([1, 2, 3, 4], 0, 4, [5, 6, 7], [5, 6, 7]));
assert(test([1, 2, 3, 4], 0, 2, [5, 6, 7], [5, 6, 7, 3, 4]));
assert(test([1, 2, 3, 4], 2, 4, [5, 6, 7], [1, 2, 5, 6, 7]));
assert(test([1, 2, 3, 4], 0, 0, filter!"true"([5, 6, 7]), [5, 6, 7, 1, 2, 3, 4]));
assert(test([1, 2, 3, 4], 0, 2, filter!"true"(cast(int[])[]), [3, 4]));
assert(test([1, 2, 3, 4], 0, 4, filter!"true"([5, 6, 7]), [5, 6, 7]));
assert(test([1, 2, 3, 4], 0, 2, filter!"true"([5, 6, 7]), [5, 6, 7, 3, 4]));
assert(test([1, 2, 3, 4], 2, 4, filter!"true"([5, 6, 7]), [1, 2, 5, 6, 7]));
void testStr(T, U)(string file = __FILE__, size_t line = __LINE__)
{
auto l = to!T("hello");
auto r = to!U(" world");
enforce(test(l, 0, 0, r, " worldhello"),
new AssertError("testStr failure 1", file, line));
enforce(test(l, 0, 3, r, " worldlo"),
new AssertError("testStr failure 2", file, line));
enforce(test(l, 3, l.length, r, "hel world"),
new AssertError("testStr failure 3", file, line));
enforce(test(l, 0, l.length, r, " world"),
new AssertError("testStr failure 4", file, line));
enforce(test(l, l.length, l.length, r, "hello world"),
new AssertError("testStr failure 5", file, line));
}
testStr!(string, string)();
testStr!(string, wstring)();
testStr!(string, dstring)();
testStr!(wstring, string)();
testStr!(wstring, wstring)();
testStr!(wstring, dstring)();
testStr!(dstring, string)();
testStr!(dstring, wstring)();
testStr!(dstring, dstring)();
}
/++
Replaces the first occurrence of `from` with `to` in `subject`.
Params:
subject = the array to scan
from = the item to replace
to = the item to replace `from` with
Returns:
A new array without changing the contents of `subject`, or the original
array if no match is found.
+/
E[] replaceFirst(E, R1, R2)(E[] subject, R1 from, R2 to)
if (isDynamicArray!(E[]) &&
isForwardRange!R1 && is(typeof(appender!(E[])().put(from[0 .. 1]))) &&
isForwardRange!R2 && is(typeof(appender!(E[])().put(to[0 .. 1]))))
{
if (from.empty) return subject;
static if (isSomeString!(E[]))
{
import std.string : indexOf;
immutable idx = subject.indexOf(from);
}
else
{
import std.algorithm.searching : countUntil;
immutable idx = subject.countUntil(from);
}
if (idx == -1)
return subject;
auto app = appender!(E[])();
app.put(subject[0 .. idx]);
app.put(to);
static if (isSomeString!(E[]) && isSomeString!R1)
{
import std.utf : codeLength;
immutable fromLength = codeLength!(Unqual!E, R1)(from);
}
else
immutable fromLength = from.length;
app.put(subject[idx + fromLength .. $]);
return app.data;
}
///
@safe unittest
{
auto a = [1, 2, 2, 3, 4, 5];
auto b = a.replaceFirst([2], [1337]);
assert(b == [1, 1337, 2, 3, 4, 5]);
auto s = "This is a foo foo list";
auto r = s.replaceFirst("foo", "silly");
assert(r == "This is a silly foo list");
}
@safe unittest
{
import std.algorithm.comparison : cmp;
import std.conv : to;
static foreach (S; AliasSeq!(string, wstring, dstring, char[], wchar[], dchar[],
const(char[]), immutable(char[])))
{
static foreach (T; AliasSeq!(string, wstring, dstring, char[], wchar[], dchar[],
const(char[]), immutable(char[])))
{{
auto s = to!S("This is a foo foo list");
auto s2 = to!S("Thüs is a ßöö foo list");
auto from = to!T("foo");
auto from2 = to!T("ßöö");
auto into = to!T("silly");
auto into2 = to!T("sälly");
S r1 = replaceFirst(s, from, into);
assert(cmp(r1, "This is a silly foo list") == 0);
S r11 = replaceFirst(s2, from2, into2);
assert(cmp(r11, "Thüs is a sälly foo list") == 0,
to!string(r11) ~ " : " ~ S.stringof ~ " " ~ T.stringof);
S r2 = replaceFirst(r1, from, into);
assert(cmp(r2, "This is a silly silly list") == 0);
S r3 = replaceFirst(s, to!T(""), into);
assert(cmp(r3, "This is a foo foo list") == 0);
assert(replaceFirst(r3, to!T("won't find"), to!T("whatever")) is r3);
}}
}
}
// https://issues.dlang.org/show_bug.cgi?id=8187
@safe unittest
{
auto res = ["a", "a"];
assert(replace(res, "a", "b") == ["b", "b"]);
assert(replaceFirst(res, "a", "b") == ["b", "a"]);
}
/++
Replaces the last occurrence of `from` with `to` in `subject`.
Params:
subject = the array to scan
from = the item to replace
to = the item to replace `from` with
Returns:
A new array without changing the contents of `subject`, or the original
array if no match is found.
+/
E[] replaceLast(E, R1, R2)(E[] subject, R1 from , R2 to)
if (isDynamicArray!(E[]) &&
isForwardRange!R1 && is(typeof(appender!(E[])().put(from[0 .. 1]))) &&
isForwardRange!R2 && is(typeof(appender!(E[])().put(to[0 .. 1]))))
{
import std.range : retro;
if (from.empty) return subject;
static if (isSomeString!(E[]))
{
import std.string : lastIndexOf;
auto idx = subject.lastIndexOf(from);
}
else
{
import std.algorithm.searching : countUntil;
auto idx = retro(subject).countUntil(retro(from));
}
if (idx == -1)
return subject;
static if (isSomeString!(E[]) && isSomeString!R1)
{
import std.utf : codeLength;
auto fromLength = codeLength!(Unqual!E, R1)(from);
}
else
auto fromLength = from.length;
auto app = appender!(E[])();
static if (isSomeString!(E[]))
app.put(subject[0 .. idx]);
else
app.put(subject[0 .. $ - idx - fromLength]);
app.put(to);
static if (isSomeString!(E[]))
app.put(subject[idx+fromLength .. $]);
else
app.put(subject[$ - idx .. $]);
return app.data;
}
///
@safe unittest
{
auto a = [1, 2, 2, 3, 4, 5];
auto b = a.replaceLast([2], [1337]);
assert(b == [1, 2, 1337, 3, 4, 5]);
auto s = "This is a foo foo list";
auto r = s.replaceLast("foo", "silly");
assert(r == "This is a foo silly list", r);
}
@safe unittest
{
import std.algorithm.comparison : cmp;
import std.conv : to;
static foreach (S; AliasSeq!(string, wstring, dstring, char[], wchar[], dchar[],
const(char[]), immutable(char[])))
{
static foreach (T; AliasSeq!(string, wstring, dstring, char[], wchar[], dchar[],
const(char[]), immutable(char[])))
{{
auto s = to!S("This is a foo foo list");
auto s2 = to!S("Thüs is a ßöö ßöö list");
auto from = to!T("foo");
auto from2 = to!T("ßöö");
auto into = to!T("silly");
auto into2 = to!T("sälly");
S r1 = replaceLast(s, from, into);
assert(cmp(r1, "This is a foo silly list") == 0, to!string(r1));
S r11 = replaceLast(s2, from2, into2);
assert(cmp(r11, "Thüs is a ßöö sälly list") == 0,
to!string(r11) ~ " : " ~ S.stringof ~ " " ~ T.stringof);
S r2 = replaceLast(r1, from, into);
assert(cmp(r2, "This is a silly silly list") == 0);
S r3 = replaceLast(s, to!T(""), into);
assert(cmp(r3, "This is a foo foo list") == 0);
assert(replaceLast(r3, to!T("won't find"), to!T("whatever")) is r3);
}}
}
}
/++
Creates a new array such that the items in `slice` are replaced with the
items in `replacement`. `slice` and `replacement` do not need to be the
same length. The result will grow or shrink based on the items given.
Params:
s = the base of the new array
slice = the slice of `s` to be replaced
replacement = the items to replace `slice` with
Returns:
A new array that is `s` with `slice` replaced by
`replacement[]`.
See_Also:
$(REF substitute, std,algorithm,iteration) for a lazy replace.
+/
inout(T)[] replaceSlice(T)(inout(T)[] s, in T[] slice, in T[] replacement)
in
{
// Verify that slice[] really is a slice of s[]
assert(overlap(s, slice) is slice, "slice[] is not a subslice of s[]");
}
do
{
auto result = new T[s.length - slice.length + replacement.length];
immutable so = &slice[0] - &s[0];
result[0 .. so] = s[0 .. so];
result[so .. so + replacement.length] = replacement[];
result[so + replacement.length .. result.length] =
s[so + slice.length .. s.length];
return () @trusted inout {
return cast(inout(T)[]) result;
}();
}
///
@safe unittest
{
auto a = [1, 2, 3, 4, 5];
auto b = replaceSlice(a, a[1 .. 4], [0, 0, 0]);
assert(b == [1, 0, 0, 0, 5]);
}
@safe unittest
{
import std.algorithm.comparison : cmp;
string s = "hello";
string slice = s[2 .. 4];
auto r = replaceSlice(s, slice, "bar");
int i;
i = cmp(r, "hebaro");
assert(i == 0);
}
/**
Implements an output range that appends data to an array. This is
recommended over $(D array ~= data) when appending many elements because it is more
efficient. `Appender` maintains its own array metadata locally, so it can avoid
global locking for each append where $(LREF capacity) is non-zero.
Params:
A = the array type to simulate.
See_Also: $(LREF appender)
*/
struct Appender(A)
if (isDynamicArray!A)
{
import core.memory : GC;
private alias T = ElementEncodingType!A;
private struct Data
{
size_t capacity;
Unqual!T[] arr;
bool canExtend = false;
}
private Data* _data;
/**
* Constructs an `Appender` with a given array. Note that this does not copy the
* data. If the array has a larger capacity as determined by `arr.capacity`,
* it will be used by the appender. After initializing an appender on an array,
* appending to the original array will reallocate.
*/
this(A arr) @trusted pure nothrow
{
// initialize to a given array.
_data = new Data;
_data.arr = cast(Unqual!T[]) arr; //trusted
if (__ctfe)
return;
// We want to use up as much of the block the array is in as possible.
// if we consume all the block that we can, then array appending is
// safe WRT built-in append, and we can use the entire block.
// We only do this for mutable types that can be extended.
static if (isMutable!T && is(typeof(arr.length = size_t.max)))
{
immutable cap = arr.capacity; //trusted
// Replace with "GC.setAttr( Not Appendable )" once pure (and fixed)
if (cap > arr.length)
arr.length = cap;
}
_data.capacity = arr.length;
}
/**
* Reserve at least newCapacity elements for appending. Note that more elements
* may be reserved than requested. If `newCapacity <= capacity`, then nothing is
* done.
*
* Params:
* newCapacity = the capacity the `Appender` should have
*/
void reserve(size_t newCapacity)
{
if (_data)
{
if (newCapacity > _data.capacity)
ensureAddable(newCapacity - _data.arr.length);
}
else
{
ensureAddable(newCapacity);
}
}
/**
* Returns: the capacity of the array (the maximum number of elements the
* managed array can accommodate before triggering a reallocation). If any
* appending will reallocate, `0` will be returned.
*/
@property size_t capacity() const @safe pure nothrow
{
return _data ? _data.capacity : 0;
}
/**
* Use opSlice() from now on.
* Returns: The managed array.
*/
@property inout(ElementEncodingType!A)[] data() inout @trusted pure nothrow
{
return this[];
}
/**
* Returns: The managed array.
*/
@property inout(ElementEncodingType!A)[] opSlice() inout @trusted pure nothrow
{
/* @trusted operation:
* casting Unqual!T[] to inout(T)[]
*/
return cast(typeof(return))(_data ? _data.arr : null);
}
// ensure we can add nelems elements, resizing as necessary
private void ensureAddable(size_t nelems)
{
if (!_data)
_data = new Data;
immutable len = _data.arr.length;
immutable reqlen = len + nelems;
if (_data.capacity >= reqlen)
return;
// need to increase capacity
if (__ctfe)
{
static if (__traits(compiles, new Unqual!T[1]))
{
_data.arr.length = reqlen;
}
else
{
// avoid restriction of @disable this()
_data.arr = _data.arr[0 .. _data.capacity];
foreach (i; _data.capacity .. reqlen)
_data.arr ~= Unqual!T.init;
}
_data.arr = _data.arr[0 .. len];
_data.capacity = reqlen;
}
else
{
// Time to reallocate.
// We need to almost duplicate what's in druntime, except we
// have better access to the capacity field.
auto newlen = appenderNewCapacity!(T.sizeof)(_data.capacity, reqlen);
// first, try extending the current block
if (_data.canExtend)
{
immutable u = (() @trusted => GC.extend(_data.arr.ptr, nelems * T.sizeof, (newlen - len) * T.sizeof))();
if (u)
{
// extend worked, update the capacity
_data.capacity = u / T.sizeof;
return;
}
}
// didn't work, must reallocate
import core.checkedint : mulu;
bool overflow;
const nbytes = mulu(newlen, T.sizeof, overflow);
if (overflow) assert(false, "the reallocation would exceed the "
~ "available pointer range");
auto bi = (() @trusted => GC.qalloc(nbytes, blockAttribute!T))();
_data.capacity = bi.size / T.sizeof;
import core.stdc.string : memcpy;
if (len)
() @trusted { memcpy(bi.base, _data.arr.ptr, len * T.sizeof); }();
_data.arr = (() @trusted => (cast(Unqual!T*) bi.base)[0 .. len])();
_data.canExtend = true;
// leave the old data, for safety reasons
}
}
private template canPutItem(U)
{
enum bool canPutItem =
isImplicitlyConvertible!(Unqual!U, Unqual!T) ||
isSomeChar!T && isSomeChar!U;
}
private template canPutConstRange(Range)
{
enum bool canPutConstRange =
isInputRange!(Unqual!Range) &&
!isInputRange!Range &&
is(typeof(Appender.init.put(Range.init.front)));
}
private template canPutRange(Range)
{
enum bool canPutRange =
isInputRange!Range &&
is(typeof(Appender.init.put(Range.init.front)));
}
/**
* Appends `item` to the managed array. Performs encoding for
* `char` types if `A` is a differently typed `char` array.
*
* Params:
* item = the single item to append
*/
void put(U)(U item) if (canPutItem!U)
{
static if (isSomeChar!T && isSomeChar!U && T.sizeof < U.sizeof)
{
/* may throwable operation:
* - std.utf.encode
*/
// must do some transcoding around here
import std.utf : encode;
Unqual!T[T.sizeof == 1 ? 4 : 2] encoded;
auto len = encode(encoded, item);
put(encoded[0 .. len]);
}
else
{
import core.internal.lifetime : emplaceRef;
ensureAddable(1);
immutable len = _data.arr.length;
auto bigData = (() @trusted => _data.arr.ptr[0 .. len + 1])();
emplaceRef!(Unqual!T)(bigData[len], cast() item);
//We do this at the end, in case of exceptions
_data.arr = bigData;
}
}
// Const fixing hack.
void put(Range)(Range items) if (canPutConstRange!Range)
{
alias p = put!(Unqual!Range);
p(items);
}
/**
* Appends an entire range to the managed array. Performs encoding for
* `char` elements if `A` is a differently typed `char` array.
*
* Params:
* items = the range of items to append
*/
void put(Range)(Range items) if (canPutRange!Range)
{
// note, we disable this branch for appending one type of char to
// another because we can't trust the length portion.
static if (!(isSomeChar!T && isSomeChar!(ElementType!Range) &&
!is(immutable Range == immutable T[])) &&
is(typeof(items.length) == size_t))
{
// optimization -- if this type is something other than a string,
// and we are adding exactly one element, call the version for one
// element.
static if (!isSomeChar!T)
{
if (items.length == 1)
{
put(items.front);
return;
}
}
// make sure we have enough space, then add the items
auto bigDataFun(size_t extra)
{
ensureAddable(extra);
return (() @trusted => _data.arr.ptr[0 .. _data.arr.length + extra])();
}
auto bigData = bigDataFun(items.length);
immutable len = _data.arr.length;
immutable newlen = bigData.length;
alias UT = Unqual!T;
static if (is(typeof(_data.arr[] = items[])) &&
!hasElaborateAssign!UT && isAssignable!(UT, ElementEncodingType!Range))
{
bigData[len .. newlen] = items[];
}
else
{
import core.internal.lifetime : emplaceRef;
foreach (ref it ; bigData[len .. newlen])
{
emplaceRef!T(it, items.front);
items.popFront();
}
}
//We do this at the end, in case of exceptions
_data.arr = bigData;
}
else static if (isSomeChar!T && isSomeChar!(ElementType!Range) &&
!is(immutable T == immutable ElementType!Range))
{
// need to decode and encode
import std.utf : decodeFront;
while (!items.empty)
{
auto c = items.decodeFront;
put(c);
}
}
else
{
//pragma(msg, Range.stringof);
// Generic input range
for (; !items.empty; items.popFront())
{
put(items.front);
}
}
}
/**
* Appends to the managed array.
*
* See_Also: $(LREF Appender.put)
*/
alias opOpAssign(string op : "~") = put;
// only allow overwriting data on non-immutable and non-const data
static if (isMutable!T)
{
/**
* Clears the managed array. This allows the elements of the array to be reused
* for appending.
*
* Note: clear is disabled for immutable or const element types, due to the
* possibility that `Appender` might overwrite immutable data.
*/
void clear() @trusted pure nothrow
{
if (_data)
{
_data.arr = _data.arr.ptr[0 .. 0];
}
}
/**
* Shrinks the managed array to the given length.
*
* Throws: `Exception` if newlength is greater than the current array length.
* Note: shrinkTo is disabled for immutable or const element types.
*/
void shrinkTo(size_t newlength) @trusted pure
{
import std.exception : enforce;
if (_data)
{
enforce(newlength <= _data.arr.length, "Attempting to shrink Appender with newlength > length");
_data.arr = _data.arr.ptr[0 .. newlength];
}
else
enforce(newlength == 0, "Attempting to shrink empty Appender with non-zero newlength");
}
}
/**
* Gives a string in the form of `Appender!(A)(data)`.
*
* Params:
* w = A `char` accepting
* $(REF_ALTTEXT output range, isOutputRange, std, range, primitives).
* fmt = A $(REF FormatSpec, std, format) which controls how the array
* is formatted.
* Returns:
* A `string` if `writer` is not set; `void` otherwise.
*/
string toString()() const
{
import std.format : singleSpec;
auto app = appender!string();
auto spec = singleSpec("%s");
immutable len = _data ? _data.arr.length : 0;
// different reserve lengths because each element in a
// non-string-like array uses two extra characters for `, `.
static if (isSomeString!A)
{
app.reserve(len + 25);
}
else
{
// Multiplying by three is a very conservative estimate of
// length, as it assumes each element is only one char
app.reserve((len * 3) + 25);
}
toString(app, spec);
return app.data;
}
/// ditto
template toString(Writer)
if (isOutputRange!(Writer, char))
{
import std.format : FormatSpec;
void toString(ref Writer w, scope const ref std.format.FormatSpec!char fmt) const
{
import std.format : formatValue;
import std.range.primitives : put;
put(w, Unqual!(typeof(this)).stringof);
put(w, '(');
formatValue(w, data, fmt);
put(w, ')');
}
}
}
///
@safe unittest
{
auto app = appender!string();
string b = "abcdefg";
foreach (char c; b)
app.put(c);
assert(app[] == "abcdefg");
int[] a = [ 1, 2 ];
auto app2 = appender(a);
app2.put(3);
app2.put([ 4, 5, 6 ]);
assert(app2[] == [ 1, 2, 3, 4, 5, 6 ]);
}
@safe pure unittest
{
import std.format : format, singleSpec;
auto app = appender!(int[])();
app.put(1);
app.put(2);
app.put(3);
assert("%s".format(app) == "Appender!(int[])(%s)".format([1,2,3]));
auto app2 = appender!string();
auto spec = singleSpec("%s");
app.toString(app2, spec);
assert(app2[] == "Appender!(int[])([1, 2, 3])");
auto app3 = appender!string();
spec = singleSpec("%(%04d, %)");
app.toString(app3, spec);
assert(app3[] == "Appender!(int[])(0001, 0002, 0003)");
}
// https://issues.dlang.org/show_bug.cgi?id=17251
@safe unittest
{
static struct R
{
int front() const { return 0; }
bool empty() const { return true; }
void popFront() {}
}
auto app = appender!(R[]);
const(R)[1] r;
app.put(r[0]);
app.put(r[]);
}
// https://issues.dlang.org/show_bug.cgi?id=13300
@safe unittest
{
static test(bool isPurePostblit)()
{
static if (!isPurePostblit)
static int i;
struct Simple
{
@disable this(); // Without this, it works.
static if (!isPurePostblit)
this(this) { i++; }
else
pure this(this) { }
private:
this(int tmp) { }
}
struct Range
{
@property Simple front() { return Simple(0); }
void popFront() { count++; }
@property empty() { return count < 3; }
size_t count;
}
Range r;
auto a = r.array();
}
static assert(__traits(compiles, () pure { test!true(); }));
static assert(!__traits(compiles, () pure { test!false(); }));
}
// https://issues.dlang.org/show_bug.cgi?id=19572
@system unittest
{
static struct Struct
{
int value;
int fun() const { return 23; }
alias fun this;
}
Appender!(Struct[]) appender;
appender.put(const(Struct)(42));
auto result = appender[][0];
assert(result.value != 23);
}
@safe unittest
{
import std.conv : to;
import std.utf : byCodeUnit;
auto str = "ウェブサイト";
auto wstr = appender!wstring();
put(wstr, str.byCodeUnit);
assert(wstr.data == str.to!wstring);
}
// https://issues.dlang.org/show_bug.cgi?id=21256
@safe unittest
{
Appender!string app1;
app1.toString();
Appender!(int[]) app2;
app2.toString();
}
//Calculates an efficient growth scheme based on the old capacity
//of data, and the minimum requested capacity.
//arg curLen: The current length
//arg reqLen: The length as requested by the user
//ret sugLen: A suggested growth.
private size_t appenderNewCapacity(size_t TSizeOf)(size_t curLen, size_t reqLen) @safe pure nothrow
{
import core.bitop : bsr;
import std.algorithm.comparison : max;
if (curLen == 0)
return max(reqLen,8);
ulong mult = 100 + (1000UL) / (bsr(curLen * TSizeOf) + 1);
// limit to doubling the length, we don't want to grow too much
if (mult > 200)
mult = 200;
auto sugLen = cast(size_t)((curLen * mult + 99) / 100);
return max(reqLen, sugLen);
}
/**
* A version of $(LREF Appender) that can update an array in-place.
* It forwards all calls to an underlying appender implementation.
* Any calls made to the appender also update the pointer to the
* original array passed in.
*
* Tip: Use the `arrayPtr` overload of $(LREF appender) for construction with type-inference.
*
* Params:
* A = The array type to simulate
*/
struct RefAppender(A)
if (isDynamicArray!A)
{
private
{
Appender!A impl;
A* arr;
}
/**
* Constructs a `RefAppender` with a given array reference. This does not copy the
* data. If the array has a larger capacity as determined by `arr.capacity`, it
* will be used by the appender.
*
* Note: Do not use built-in appending (i.e. `~=`) on the original array
* until you are done with the appender, because subsequent calls to the appender
* will reallocate the array data without those appends.
*
* Params:
* arr = Pointer to an array. Must not be _null.
*/
this(A* arr)
{
impl = Appender!A(*arr);
this.arr = arr;
}
/** Wraps remaining `Appender` methods such as $(LREF put).
* Params:
* fn = Method name to call.
* args = Arguments to pass to the method.
*/
void opDispatch(string fn, Args...)(Args args)
if (__traits(compiles, (Appender!A a) => mixin("a." ~ fn ~ "(args)")))
{
// we do it this way because we can't cache a void return
scope(exit) *this.arr = impl[];
mixin("return impl." ~ fn ~ "(args);");
}
/**
* Appends `rhs` to the managed array.
* Params:
* rhs = Element or range.
*/
void opOpAssign(string op : "~", U)(U rhs)
if (__traits(compiles, (Appender!A a){ a.put(rhs); }))
{
scope(exit) *this.arr = impl[];
impl.put(rhs);
}
/**
* Returns the capacity of the array (the maximum number of elements the
* managed array can accommodate before triggering a reallocation). If any
* appending will reallocate, `capacity` returns `0`.
*/
@property size_t capacity() const
{
return impl.capacity;
}
/* Use opSlice() instead.
* Returns: the managed array.
*/
@property inout(ElementEncodingType!A)[] data() inout
{
return impl[];
}
/**
* Returns: the managed array.
*/
@property inout(ElementEncodingType!A)[] opSlice() inout
{
return impl[];
}
}
///
@system pure nothrow
unittest
{
int[] a = [1, 2];
auto app2 = appender(&a);
assert(app2[] == [1, 2]);
assert(a == [1, 2]);
app2 ~= 3;
app2 ~= [4, 5, 6];
assert(app2[] == [1, 2, 3, 4, 5, 6]);
assert(a == [1, 2, 3, 4, 5, 6]);
app2.reserve(5);
assert(app2.capacity >= 5);
}
/++
Convenience function that returns an $(LREF Appender) instance,
optionally initialized with `array`.
+/
Appender!A appender(A)()
if (isDynamicArray!A)
{
return Appender!A(null);
}
/// ditto
Appender!(E[]) appender(A : E[], E)(auto ref A array)
{
static assert(!isStaticArray!A || __traits(isRef, array),
"Cannot create Appender from an rvalue static array");
return Appender!(E[])(array);
}
@safe pure nothrow unittest
{
import std.exception;
{
auto app = appender!(char[])();
string b = "abcdefg";
foreach (char c; b) app.put(c);
assert(app[] == "abcdefg");
}
{
auto app = appender!(char[])();
string b = "abcdefg";
foreach (char c; b) app ~= c;
assert(app[] == "abcdefg");
}
{
int[] a = [ 1, 2 ];
auto app2 = appender(a);
assert(app2[] == [ 1, 2 ]);
app2.put(3);
app2.put([ 4, 5, 6 ][]);
assert(app2[] == [ 1, 2, 3, 4, 5, 6 ]);
app2.put([ 7 ]);
assert(app2[] == [ 1, 2, 3, 4, 5, 6, 7 ]);
}
int[] a = [ 1, 2 ];
auto app2 = appender(a);
assert(app2[] == [ 1, 2 ]);
app2 ~= 3;
app2 ~= [ 4, 5, 6 ][];
assert(app2[] == [ 1, 2, 3, 4, 5, 6 ]);
app2 ~= [ 7 ];
assert(app2[] == [ 1, 2, 3, 4, 5, 6, 7 ]);
app2.reserve(5);
assert(app2.capacity >= 5);
try // shrinkTo may throw
{
app2.shrinkTo(3);
}
catch (Exception) assert(0);
assert(app2[] == [ 1, 2, 3 ]);
assertThrown(app2.shrinkTo(5));
const app3 = app2;
assert(app3.capacity >= 3);
assert(app3[] == [1, 2, 3]);
auto app4 = appender([]);
try // shrinkTo may throw
{
app4.shrinkTo(0);
}
catch (Exception) assert(0);
// https://issues.dlang.org/show_bug.cgi?id=5663
// https://issues.dlang.org/show_bug.cgi?id=9725
static foreach (S; AliasSeq!(char[], const(char)[], string))
{
{
Appender!S app5663i;
assertNotThrown(app5663i.put("\xE3"));
assert(app5663i[] == "\xE3");
Appender!S app5663c;
assertNotThrown(app5663c.put(cast(const(char)[])"\xE3"));
assert(app5663c[] == "\xE3");
Appender!S app5663m;
assertNotThrown(app5663m.put("\xE3".dup));
assert(app5663m[] == "\xE3");
}
// ditto for ~=
{
Appender!S app5663i;
assertNotThrown(app5663i ~= "\xE3");
assert(app5663i[] == "\xE3");
Appender!S app5663c;
assertNotThrown(app5663c ~= cast(const(char)[])"\xE3");
assert(app5663c[] == "\xE3");
Appender!S app5663m;
assertNotThrown(app5663m ~= "\xE3".dup);
assert(app5663m[] == "\xE3");
}
}
static struct S10122
{
int val;
@disable this();
this(int v) @safe pure nothrow { val = v; }
}
assertCTFEable!(
{
auto w = appender!(S10122[])();
w.put(S10122(1));
assert(w[].length == 1 && w[][0].val == 1);
});
}
///
@safe pure nothrow
unittest
{
auto w = appender!string;
// pre-allocate space for at least 10 elements (this avoids costly reallocations)
w.reserve(10);
assert(w.capacity >= 10);
w.put('a'); // single elements
w.put("bc"); // multiple elements
// use the append syntax
w ~= 'd';
w ~= "ef";
assert(w[] == "abcdef");
}
@safe pure nothrow unittest
{
{
auto w = appender!string();
w.reserve(4);
cast(void) w.capacity;
cast(void) w[];
try
{
wchar wc = 'a';
dchar dc = 'a';
w.put(wc); // decoding may throw
w.put(dc); // decoding may throw
}
catch (Exception) assert(0);
}
{
auto w = appender!(int[])();
w.reserve(4);
cast(void) w.capacity;
cast(void) w[];
w.put(10);
w.put([10]);
w.clear();
try
{
w.shrinkTo(0);
}
catch (Exception) assert(0);
struct N
{
int payload;
alias payload this;
}
w.put(N(1));
w.put([N(2)]);
struct S(T)
{
@property bool empty() { return true; }
@property T front() { return T.init; }
void popFront() {}
}
S!int r;
w.put(r);
}
}
// https://issues.dlang.org/show_bug.cgi?id=10690
@safe unittest
{
import std.algorithm;
import std.typecons;
[tuple(1)].filter!(t => true).array; // No error
[tuple("A")].filter!(t => true).array; // error
}
@safe unittest
{
import std.range;
//Coverage for put(Range)
struct S1
{
}
struct S2
{
void opAssign(S2){}
}
auto a1 = Appender!(S1[])();
auto a2 = Appender!(S2[])();
auto au1 = Appender!(const(S1)[])();
a1.put(S1().repeat().take(10));
a2.put(S2().repeat().take(10));
auto sc1 = const(S1)();
au1.put(sc1.repeat().take(10));
}
@system unittest
{
import std.range;
struct S2
{
void opAssign(S2){}
}
auto au2 = Appender!(const(S2)[])();
auto sc2 = const(S2)();
au2.put(sc2.repeat().take(10));
}
@system unittest
{
struct S
{
int* p;
}
auto a0 = Appender!(S[])();
auto a1 = Appender!(const(S)[])();
auto a2 = Appender!(immutable(S)[])();
auto s0 = S(null);
auto s1 = const(S)(null);
auto s2 = immutable(S)(null);
a1.put(s0);
a1.put(s1);
a1.put(s2);
a1.put([s0]);
a1.put([s1]);
a1.put([s2]);
a0.put(s0);
static assert(!is(typeof(a0.put(a1))));
static assert(!is(typeof(a0.put(a2))));
a0.put([s0]);
static assert(!is(typeof(a0.put([a1]))));
static assert(!is(typeof(a0.put([a2]))));
static assert(!is(typeof(a2.put(a0))));
static assert(!is(typeof(a2.put(a1))));
a2.put(s2);
static assert(!is(typeof(a2.put([a0]))));
static assert(!is(typeof(a2.put([a1]))));
a2.put([s2]);
}
// https://issues.dlang.org/show_bug.cgi?id=9528
@safe unittest
{
const(E)[] fastCopy(E)(E[] src) {
auto app = appender!(const(E)[])();
foreach (i, e; src)
app.put(e);
return app[];
}
class C {}
struct S { const(C) c; }
S[] s = [ S(new C) ];
auto t = fastCopy(s); // Does not compile
assert(t.length == 1);
}
// https://issues.dlang.org/show_bug.cgi?id=10753
@safe unittest
{
import std.algorithm.iteration : map;
struct Foo {
immutable dchar d;
}
struct Bar {
immutable int x;
}
"12".map!Foo.array;
[1, 2].map!Bar.array;
}
@safe unittest
{
import std.algorithm.comparison : equal;
//New appender signature tests
alias mutARR = int[];
alias conARR = const(int)[];
alias immARR = immutable(int)[];
mutARR mut;
conARR con;
immARR imm;
auto app1 = Appender!mutARR(mut); //Always worked. Should work. Should not create a warning.
app1.put(7);
assert(equal(app1[], [7]));
static assert(!is(typeof(Appender!mutARR(con)))); //Never worked. Should not work.
static assert(!is(typeof(Appender!mutARR(imm)))); //Never worked. Should not work.
auto app2 = Appender!conARR(mut); //Always worked. Should work. Should not create a warning.
app2.put(7);
assert(equal(app2[], [7]));
auto app3 = Appender!conARR(con); //Didn't work. Now works. Should not create a warning.
app3.put(7);
assert(equal(app3[], [7]));
auto app4 = Appender!conARR(imm); //Didn't work. Now works. Should not create a warning.
app4.put(7);
assert(equal(app4[], [7]));
//{auto app = Appender!immARR(mut);} //Worked. Will cease to work. Creates warning.
//static assert(!is(typeof(Appender!immARR(mut)))); //Worked. Will cease to work. Uncomment me after full deprecation.
static assert(!is(typeof(Appender!immARR(con)))); //Never worked. Should not work.
auto app5 = Appender!immARR(imm); //Didn't work. Now works. Should not create a warning.
app5.put(7);
assert(equal(app5[], [7]));
//Deprecated. Please uncomment and make sure this doesn't work:
//char[] cc;
//static assert(!is(typeof(Appender!string(cc))));
//This should always work:
auto app6 = appender!string(null);
assert(app6[] == null);
auto app7 = appender!(const(char)[])(null);
assert(app7[] == null);
auto app8 = appender!(char[])(null);
assert(app8[] == null);
}
@safe unittest //Test large allocations (for GC.extend)
{
import std.algorithm.comparison : equal;
import std.range;
Appender!(char[]) app;
app.reserve(1); //cover reserve on non-initialized
foreach (_; 0 .. 100_000)
app.put('a');
assert(equal(app[], 'a'.repeat(100_000)));
}
@safe unittest
{
auto reference = new ubyte[](2048 + 1); //a number big enough to have a full page (EG: the GC extends)
auto arr = reference.dup;
auto app = appender(arr[0 .. 0]);
app.reserve(1); //This should not trigger a call to extend
app.put(ubyte(1)); //Don't clobber arr
assert(reference[] == arr[]);
}
@safe unittest // clear method is supported only for mutable element types
{
Appender!string app;
app.put("foo");
static assert(!__traits(compiles, app.clear()));
assert(app[] == "foo");
}
@safe unittest
{
static struct D//dynamic
{
int[] i;
alias i this;
}
static struct S//static
{
int[5] i;
alias i this;
}
static assert(!is(Appender!(char[5])));
static assert(!is(Appender!D));
static assert(!is(Appender!S));
enum int[5] a = [];
int[5] b;
D d;
S s;
int[5] foo(){return a;}
static assert(!is(typeof(appender(a))));
static assert( is(typeof(appender(b))));
static assert( is(typeof(appender(d))));
static assert( is(typeof(appender(s))));
static assert(!is(typeof(appender(foo()))));
}
@system unittest
{
// https://issues.dlang.org/show_bug.cgi?id=13077
static class A {}
// reduced case
auto w = appender!(shared(A)[])();
w.put(new shared A());
// original case
import std.range;
InputRange!(shared A) foo()
{
return [new shared A].inputRangeObject;
}
auto res = foo.array;
assert(res.length == 1);
}
/++
Convenience function that returns a $(LREF RefAppender) instance initialized
with `arrayPtr`. Don't use null for the array pointer, use the other
version of `appender` instead.
+/
RefAppender!(E[]) appender(P : E[]*, E)(P arrayPtr)
{
return RefAppender!(E[])(arrayPtr);
}
///
@system pure nothrow
unittest
{
int[] a = [1, 2];
auto app2 = appender(&a);
assert(app2[] == [1, 2]);
assert(a == [1, 2]);
app2 ~= 3;
app2 ~= [4, 5, 6];
assert(app2[] == [1, 2, 3, 4, 5, 6]);
assert(a == [1, 2, 3, 4, 5, 6]);
app2.reserve(5);
assert(app2.capacity >= 5);
}
@system unittest
{
import std.exception;
{
auto arr = new char[0];
auto app = appender(&arr);
string b = "abcdefg";
foreach (char c; b) app.put(c);
assert(app[] == "abcdefg");
assert(arr == "abcdefg");
}
{
auto arr = new char[0];
auto app = appender(&arr);
string b = "abcdefg";
foreach (char c; b) app ~= c;
assert(app[] == "abcdefg");
assert(arr == "abcdefg");
}
{
int[] a = [ 1, 2 ];
auto app2 = appender(&a);
assert(app2[] == [ 1, 2 ]);
assert(a == [ 1, 2 ]);
app2.put(3);
app2.put([ 4, 5, 6 ][]);
assert(app2[] == [ 1, 2, 3, 4, 5, 6 ]);
assert(a == [ 1, 2, 3, 4, 5, 6 ]);
}
int[] a = [ 1, 2 ];
auto app2 = appender(&a);
assert(app2[] == [ 1, 2 ]);
assert(a == [ 1, 2 ]);
app2 ~= 3;
app2 ~= [ 4, 5, 6 ][];
assert(app2[] == [ 1, 2, 3, 4, 5, 6 ]);
assert(a == [ 1, 2, 3, 4, 5, 6 ]);
app2.reserve(5);
assert(app2.capacity >= 5);
try // shrinkTo may throw
{
app2.shrinkTo(3);
}
catch (Exception) assert(0);
assert(app2[] == [ 1, 2, 3 ]);
assertThrown(app2.shrinkTo(5));
const app3 = app2;
assert(app3.capacity >= 3);
assert(app3[] == [1, 2, 3]);
}
// https://issues.dlang.org/show_bug.cgi?id=14605
@safe unittest
{
static assert(isOutputRange!(Appender!(int[]), int));
static assert(isOutputRange!(RefAppender!(int[]), int));
}
@safe unittest
{
Appender!(int[]) app;
short[] range = [1, 2, 3];
app.put(range);
assert(app[] == [1, 2, 3]);
}
@safe unittest
{
string s = "hello".idup;
char[] a = "hello".dup;
auto appS = appender(s);
auto appA = appender(a);
put(appS, 'w');
put(appA, 'w');
s ~= 'a'; //Clobbers here?
a ~= 'a'; //Clobbers here?
assert(appS[] == "hellow");
assert(appA[] == "hellow");
}
/++
Constructs a static array from `a`.
The type of elements can be specified implicitly so that $(D [1, 2].staticArray) results in `int[2]`,
or explicitly, e.g. $(D [1, 2].staticArray!float) returns `float[2]`.
When `a` is a range whose length is not known at compile time, the number of elements must be
given as template argument (e.g. `myrange.staticArray!2`).
Size and type can be combined, if the source range elements are implicitly
convertible to the requested element type (eg: `2.iota.staticArray!(long[2])`).
When the range `a` is known at compile time, it can also be specified as a
template argument to avoid having to specify the number of elements
(e.g.: `staticArray!(2.iota)` or `staticArray!(double, 2.iota)`).
Note: `staticArray` returns by value, so expressions involving large arrays may be inefficient.
Params:
a = The input elements. If there are less elements than the specified length of the static array,
the rest of it is default-initialized. If there are more than specified, the first elements
up to the specified length are used.
rangeLength = outputs the number of elements used from `a` to it. Optional.
Returns: A static array constructed from `a`.
+/
pragma(inline, true) T[n] staticArray(T, size_t n)(auto ref T[n] a)
{
return a;
}
/// static array from array literal
nothrow pure @safe unittest
{
auto a = [0, 1].staticArray;
static assert(is(typeof(a) == int[2]));
assert(a == [0, 1]);
}
pragma(inline, true) U[n] staticArray(U, T, size_t n)(auto ref T[n] a)
if (!is(T == U) && is(T : U))
{
return a[].staticArray!(U[n]);
}
/// static array from array with implicit casting of elements
nothrow pure @safe unittest
{
auto b = [0, 1].staticArray!long;
static assert(is(typeof(b) == long[2]));
assert(b == [0, 1]);
}
nothrow pure @safe unittest
{
int val = 3;
static immutable gold = [1, 2, 3];
[1, 2, val].staticArray.checkStaticArray!int([1, 2, 3]);
@nogc void checkNogc()
{
[1, 2, val].staticArray.checkStaticArray!int(gold);
}
checkNogc();
[1, 2, val].staticArray!double.checkStaticArray!double(gold);
[1, 2, 3].staticArray!int.checkStaticArray!int(gold);
[1, 2, 3].staticArray!(const(int)).checkStaticArray!(const(int))(gold);
[1, 2, 3].staticArray!(const(double)).checkStaticArray!(const(double))(gold);
{
const(int)[3] a2 = [1, 2, 3].staticArray;
}
[cast(byte) 1, cast(byte) 129].staticArray.checkStaticArray!byte([1, -127]);
}
/// ditto
auto staticArray(size_t n, T)(scope T a)
if (isInputRange!T)
{
alias U = ElementType!T;
return staticArray!(U[n], U, n)(a);
}
/// ditto
auto staticArray(size_t n, T)(scope T a, out size_t rangeLength)
if (isInputRange!T)
{
alias U = ElementType!T;
return staticArray!(U[n], U, n)(a, rangeLength);
}
/// ditto
auto staticArray(Un : U[n], U, size_t n, T)(scope T a)
if (isInputRange!T && is(ElementType!T : U))
{
size_t extraStackSpace;
return staticArray!(Un, U, n)(a, extraStackSpace);
}
/// ditto
auto staticArray(Un : U[n], U, size_t n, T)(scope T a, out size_t rangeLength)
if (isInputRange!T && is(ElementType!T : U))
{
import std.algorithm.mutation : uninitializedFill;
import std.range : take;
import core.internal.lifetime : emplaceRef;
if (__ctfe)
{
size_t i;
// Compile-time version to avoid unchecked memory access.
Unqual!U[n] ret;
for (auto iter = a.take(n); !iter.empty; iter.popFront())
{
ret[i] = iter.front;
i++;
}
rangeLength = i;
return (() @trusted => cast(U[n]) ret)();
}
auto ret = (() @trusted
{
Unqual!U[n] theArray = void;
return theArray;
}());
size_t i;
if (true)
{
// ret was void-initialized so let's initialize the unfilled part manually.
// also prevents destructors to be called on uninitialized memory if
// an exception is thrown
scope (exit) ret[i .. $].uninitializedFill(U.init);
for (auto iter = a.take(n); !iter.empty; iter.popFront())
{
emplaceRef!U(ret[i++], iter.front);
}
}
rangeLength = i;
return (() @trusted => cast(U[n]) ret)();
}
/// static array from range + size
nothrow pure @safe unittest
{
import std.range : iota;
auto input = 3.iota;
auto a = input.staticArray!2;
static assert(is(typeof(a) == int[2]));
assert(a == [0, 1]);
auto b = input.staticArray!(long[4]);
static assert(is(typeof(b) == long[4]));
assert(b == [0, 1, 2, 0]);
}
// Tests that code compiles when there is an elaborate destructor and exceptions
// are thrown. Unfortunately can't test that memory is initialized
// before having a destructor called on it.
// @system required because of https://issues.dlang.org/show_bug.cgi?id=18872.
@system nothrow unittest
{
// exists only to allow doing something in the destructor. Not tested
// at the end because value appears to depend on implementation of the.
// function.
static int preventersDestroyed = 0;
static struct CopyPreventer
{
bool on = false;
this(this)
{
if (on) throw new Exception("Thou shalt not copy past me!");
}
~this()
{
preventersDestroyed++;
}
}
auto normalArray =
[
CopyPreventer(false),
CopyPreventer(false),
CopyPreventer(true),
CopyPreventer(false),
CopyPreventer(true),
];
try
{
auto staticArray = normalArray.staticArray!5;
assert(false);
}
catch (Exception e){}
}
nothrow pure @safe unittest
{
auto a = [1, 2].staticArray;
assert(is(typeof(a) == int[2]) && a == [1, 2]);
import std.range : iota;
2.iota.staticArray!2.checkStaticArray!int([0, 1]);
2.iota.staticArray!(double[2]).checkStaticArray!double([0, 1]);
2.iota.staticArray!(long[2]).checkStaticArray!long([0, 1]);
}
nothrow pure @system unittest
{
import std.range : iota;
size_t copiedAmount;
2.iota.staticArray!1(copiedAmount);
assert(copiedAmount == 1);
2.iota.staticArray!3(copiedAmount);
assert(copiedAmount == 2);
}
/// ditto
auto staticArray(alias a)()
if (isInputRange!(typeof(a)))
{
return .staticArray!(size_t(a.length))(a);
}
/// ditto
auto staticArray(U, alias a)()
if (isInputRange!(typeof(a)))
{
return .staticArray!(U[size_t(a.length)])(a);
}
/// static array from CT range
nothrow pure @safe unittest
{
import std.range : iota;
enum a = staticArray!(2.iota);
static assert(is(typeof(a) == int[2]));
assert(a == [0, 1]);
enum b = staticArray!(long, 2.iota);
static assert(is(typeof(b) == long[2]));
assert(b == [0, 1]);
}
nothrow pure @safe unittest
{
import std.range : iota;
enum a = staticArray!(2.iota);
staticArray!(2.iota).checkStaticArray!int([0, 1]);
staticArray!(double, 2.iota).checkStaticArray!double([0, 1]);
staticArray!(long, 2.iota).checkStaticArray!long([0, 1]);
}
version (StdUnittest) private void checkStaticArray(T, T1, T2)(T1 a, T2 b) nothrow @safe pure @nogc
{
static assert(is(T1 == T[T1.length]));
assert(a == b, "a must be equal to b");
}
| D |
module dcrypt.benchmark.Benchmark;
public import std.datetime: StopWatch;
import std.conv;
import dcrypt.benchmark.BlockCipherBenchmark;
import dcrypt.benchmark.AEADCipherBenchmark;
import dcrypt.benchmark.DigestBenchmark;
//import dcrypt.benchmark.PKSS52ParameterGeneratorBenchmark;
import dcrypt.crypto.blockcipher;
import dcrypt.crypto.digest;
import dcrypt.crypto.modes.aead;
import std.stdio;
import std.string;
public class Benchmark {
/// Params:
/// length = the length of benchmark in bytes
/// ciphers = BlockCiphers to test
public static void doBenchmark(ulong length, BlockCipher[] ciphers...) {
writeln();
printTabbed(BlockCipherBenchmark.header);
writeln();
foreach(c; ciphers) {
auto bench = new BlockCipherBenchmark(c);
printTabbed(bench.benchmark(length));
stdout.flush();
}
}
public static void doBenchmark(ulong length, AEADCipher[] ciphers...) {
writeln();
printTabbed(AEADCipherBenchmark.header);
writeln();
foreach(c; ciphers) {
auto bench = new AEADCipherBenchmark(c);
printTabbed(bench.benchmark(length));
stdout.flush();
}
}
public static void doBenchmark(ulong length, Digest[] digests...) {
writeln();
printTabbed(DigestBenchmark.header);
writeln();
foreach(d; digests) {
auto bench = new DigestBenchmark(d);
printTabbed(bench.benchmark(length));
stdout.flush();
}
}
public static void doCurved25519Benchmark(ulong length) {
import dcrypt.benchmark.curved25519;
writeln();
printTabbed(Curved25519Benchmark.header);
writeln();
auto bench = new Curved25519Benchmark;
printTabbed(bench.benchmark(length));
stdout.flush();
}
public static void doEd25519Benchmark(ulong length) {
import dcrypt.benchmark.curved25519;
writeln();
printTabbed(Ed25519Benchmark.header);
writeln();
auto bench = new Ed25519Benchmark;
printTabbed(bench.benchmark(length));
stdout.flush();
}
public static void doSphincs256Benchmark(ulong length) {
import dcrypt.benchmark.sphincs256;
writeln();
printTabbed(Sphincs256Benchmark.header);
writeln();
auto bench = new Sphincs256Benchmark;
printTabbed(bench.benchmark(length));
stdout.flush();
}
// public static void doBenchmark(T)(PKCS5S2ParametersGenerator!T[] gen...) {
// writeln();
// writeln(tabbed(padding, "algorithm", "iterations/s"));
// writeln();
// foreach(g; gen) {
// auto bench = new PKSS52ParameterGeneratorBenchmark(g);
// writeln(bench.benchmark(0));
// stdout.flush();
// }
// }
/// do the calculations, (compute hashes, encrypt data, ...)
/// Params: length = length of benchmark (numbers of bytes to process)
/// Returns: a string containing the benchmark results
public abstract string[] benchmark(ulong length);
@trusted
static void printTabbed(string[] strs...) {
writefln("%-(%-20s%)", strs);
}
public string numberFormat(double d) {
return format("%10.2f", d);
}
} | D |
/*******************************************************************************
Utility class that keeps a queue of yielded `RequestOnConn`s and resumes
them in the next event loop cycle. In order to work `YieldedRequestOnConns`
needs to be registered with the `EpollSelectDispatcher` that executes the
application event loop.
Copyright: Copyright (c) 2016-2017 sociomantic labs GmbH. All rights reserved
License:
Boost Software License Version 1.0. See LICENSE_BOOST.txt for details.
*******************************************************************************/
module swarm.neo.connection.YieldedRequestOnConns;
/*******************************************************************************
Imports
*******************************************************************************/
import ocean.io.select.client.SelectEvent;
/******************************************************************************/
class YieldedRequestOnConns: ISelectEvent
{
import swarm.neo.util.TreeQueue;
/***************************************************************************
The interface for a resumable `RequestOnConn`.
***************************************************************************/
interface IYieldedRequestOnConn
{
/***********************************************************************
Resumes this `RequestOnConn`.
***********************************************************************/
void resume ( );
}
/***************************************************************************
The queue of `RequestOnConn`s to resume.
***************************************************************************/
private YieldedQueue queue;
/***************************************************************************
Adds `roc` to be resumed on the next event loop cycle, if it hasn't
already been added.
Note that this method stores `roc` in a location that is invisible to
the GC.
Params:
roc = a `RequestOnConn` to be resumed on the next event loop cycle
Returns:
true if added or false if `roc` was already in the queue so it has
not been added again.
***************************************************************************/
public bool add ( IYieldedRequestOnConn roc )
{
bool first = this.queue.is_empty;
if (this.queue.push(roc))
{
// Trigger the event so that it fires and is handled on the next
// event loop cycle.
if (first)
this.trigger();
return true;
}
else
{
return false;
}
}
/***************************************************************************
Removes `roc` from the queue.
Params:
roc = the `RequestOnConn` to be removed
Returns:
true if `roc` was removed or false if not found.
***************************************************************************/
public bool remove ( IYieldedRequestOnConn roc )
{
return this.queue.remove(roc);
}
/***************************************************************************
Select event handler, pops all `RequestOnConn`s from the queue and
resumes each.
Params:
n = the number of times the select event was triggered since it
fired the last time
Returns:
true to stay registered with epoll.
***************************************************************************/
override protected bool handle_ ( ulong n )
{
this.queue.swapAndPop(
(IYieldedRequestOnConn yielded) {yielded.resume();}
);
return true;
}
/***************************************************************************
Manages the queue of `RequestOnConn`s, which are actually two queues: At
each time only one, `queue[active]`, is active while the other queue,
`queue[!active]`, is inactive.
All methods except `swapAndPop()` use the active queue. `swapAndPop()`
swaps the active and inactive queue, then pops all `RequestOnConn`s from
the previously active and now inactive queue. This is to allow for
pushing and removing `RequestOnConn`s while in the loop of popping.
***************************************************************************/
private static struct YieldedQueue
{
/***********************************************************************
The two queues of yielded `RequestOnConn`s.
***********************************************************************/
private TreeQueue!(YieldedRequestOnConns.IYieldedRequestOnConn)[2] queue;
/***********************************************************************
Flag telling which queue `add()` and `remove()` should use.
***********************************************************************/
private bool active = false;
/***********************************************************************
Returns:
false if a `RequestOnConn` has been pushed and `swapAndPop()`
was not called since then, or true otherwise.
***********************************************************************/
public bool is_empty ( )
{
return this.queue[this.active].is_empty;
}
/***********************************************************************
Pushes `roc` to the active queue if it isn't in the queue already.
Note that this method stores `roc` in a location that is invisible
to the GC.
Params:
roc = a `RequestOnConn` to be pushed to the active queue
Returns:
true if pushed or false if `roc` was already in the active
queue so it has not been pushed again.
***********************************************************************/
public bool push ( IYieldedRequestOnConn roc )
{
return this.queue[this.active].push(roc);
}
/***********************************************************************
Swaps the active and inactive queues, then pops all `RequestOnConn`s
from the now inactive queue, calling `dg` with each popped
`RequestOnConn`.
Params:
dg = delegate to call with each popped `RequestOnConn`
***********************************************************************/
public void swapAndPop ( void delegate ( IYieldedRequestOnConn popped_roc ) dg )
in
{
assert(this.queue[!this.active].is_empty, typeof(this).stringof ~
".swapAndPop: " ~
"Expected the inactive queue to be empty when called");
}
out
{
assert(this.queue[!this.active].is_empty, typeof(this).stringof ~
".swapAndPop: " ~
"Expected the inactive queue to be empty when returning");
}
body
{
this.active = !this.active;
foreach (roc; this.queue[!this.active])
dg(roc);
}
/***********************************************************************
Removes `roc` from the queue.
Params:
roc = the `RequestOnConn` to be removed
Returns:
true if `roc` was removed or false if not found.
***********************************************************************/
public bool remove ( IYieldedRequestOnConn roc )
{
return this.queue[this.active].remove(roc);
}
}
}
| D |
/*
* Copyright (c) 2012-2019 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
module antlr.v4.runtime.atn.PredictionContextCache;
import std.conv;
import antlr.v4.runtime.atn.PredictionContext;
/**
* Used to cache {@link PredictionContext} objects. Its used for the shared
* context cash associated with contexts in DFA states. This cache
* can be used for both lexers and parsers.
*/
class PredictionContextCache
{
protected PredictionContext[PredictionContext] cache;
/**
* Add a context to the cache and return it. If the context already exists,
* return that one instead and do not add a new context to the cache.
* Protect shared cache from unsafe thread access.
*/
public PredictionContext add(PredictionContext ctx)
{
if (ctx == PredictionContext.EMPTY)
return ctx;
if (hasKey(ctx)) {
// System.out.println(name+" reuses "+existing);
return cache[ctx];
}
cache[ctx] = ctx;
return ctx;
}
public PredictionContext get(PredictionContext ctx)
{
return cache[ctx];
}
public size_t size()
{
return cache.length;
}
public bool hasKey(PredictionContext predictionContext)
{
if (predictionContext in cache)
return true;
return false;
}
}
| D |
a person or thing represented or foreshadowed by a type or symbol
an opposite or contrasting type
| D |
/Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/SQL.build/SQLInsertBuilder.swift.o : /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLBind.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLJoinMethod.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDropTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLAlterTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSerializable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDataType.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLUpdate.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDelete.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLLiteral.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLBoolLiteral.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDefaultLiteral.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTableConstraintAlgorithm.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnConstraintAlgorithm.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLJoin.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLExpression.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSelectExpression.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCollation.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLForeignKeyAction.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLConnection.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDirection.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLFunction.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnDefinition.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateTableBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDropTableBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLAlterTableBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLPredicateBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLUpdateBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDeleteBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLPredicateGroupBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSelectBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLInsertBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLRawBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateIndexBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQueryBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQueryEncoder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQueryFetcher.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLIndexModifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLIdentifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTableIdentifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnIdentifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLBinaryOperator.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/Exports.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSelect.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDistinct.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLFunctionArgument.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTableConstraint.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnConstraint.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLInsert.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateIndex.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDropIndex.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLGroupBy.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLOrderBy.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLForeignKey.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLPrimaryKey.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQuery.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/cpp_magic.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIODarwin/include/c_nio_darwin.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/c-atomics.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/c_nio_linux.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--1071467962839356487/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/SQL.build/SQLInsertBuilder~partial.swiftmodule : /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLBind.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLJoinMethod.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDropTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLAlterTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSerializable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDataType.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLUpdate.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDelete.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLLiteral.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLBoolLiteral.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDefaultLiteral.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTableConstraintAlgorithm.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnConstraintAlgorithm.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLJoin.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLExpression.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSelectExpression.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCollation.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLForeignKeyAction.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLConnection.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDirection.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLFunction.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnDefinition.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateTableBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDropTableBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLAlterTableBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLPredicateBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLUpdateBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDeleteBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLPredicateGroupBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSelectBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLInsertBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLRawBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateIndexBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQueryBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQueryEncoder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQueryFetcher.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLIndexModifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLIdentifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTableIdentifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnIdentifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLBinaryOperator.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/Exports.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSelect.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDistinct.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLFunctionArgument.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTableConstraint.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnConstraint.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLInsert.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateIndex.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDropIndex.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLGroupBy.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLOrderBy.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLForeignKey.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLPrimaryKey.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQuery.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/cpp_magic.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIODarwin/include/c_nio_darwin.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/c-atomics.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/c_nio_linux.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--1071467962839356487/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
/Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/SQL.build/SQLInsertBuilder~partial.swiftdoc : /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLBind.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLJoinMethod.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDropTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLAlterTable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSerializable.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDataType.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLUpdate.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDelete.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLLiteral.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLBoolLiteral.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDefaultLiteral.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTableConstraintAlgorithm.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnConstraintAlgorithm.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLJoin.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLExpression.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSelectExpression.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCollation.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLForeignKeyAction.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLConnection.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDirection.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLFunction.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnDefinition.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateTableBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDropTableBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLAlterTableBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLPredicateBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLUpdateBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDeleteBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLPredicateGroupBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSelectBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLInsertBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLRawBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateIndexBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQueryBuilder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQueryEncoder.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQueryFetcher.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLIndexModifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLIdentifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTableIdentifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnIdentifier.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLBinaryOperator.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/Exports.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLSelect.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDistinct.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLFunctionArgument.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLTableConstraint.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLColumnConstraint.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLInsert.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLCreateIndex.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLDropIndex.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLGroupBy.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLOrderBy.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLForeignKey.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLPrimaryKey.swift /Users/Khanh/vapor/TILApp/.build/checkouts/sql.git-2678105727451989607/Sources/SQL/SQLQuery.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/ObjectiveC.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/NIO.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Async.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Service.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Core.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Debugging.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Dispatch.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/CoreGraphics.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/NIOConcurrencyHelpers.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/Bits.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/NIOFoundationCompat.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/IOKit.swiftmodule /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/DatabaseKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/x86_64/SwiftOnoneSupport.swiftmodule /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/cpp_magic.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIODarwin/include/c_nio_darwin.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOAtomics/include/c-atomics.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio.git-3108475404973543938/Sources/CNIOLinux/include/c_nio_linux.h /Users/Khanh/vapor/TILApp/.build/checkouts/swift-nio-zlib-support.git--1071467962839356487/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOSHA1.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOOpenSSL.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOZlib.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIODarwin.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOHTTPParser.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOAtomics.build/module.modulemap /Users/Khanh/vapor/TILApp/.build/x86_64-apple-macosx10.10/debug/CNIOLinux.build/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes
| D |
/home/philip/LearnDemo/rust-lang-book/Chapter07/Module7_11/target/debug/deps/Module7_11-f4a14a4c90be2988: src/main.rs
/home/philip/LearnDemo/rust-lang-book/Chapter07/Module7_11/target/debug/deps/Module7_11-f4a14a4c90be2988.d: src/main.rs
src/main.rs:
| D |
/*
TEST_OUTPUT:
---
fail_compilation/ice9540.d(34): Error: function ice9540.A.test.AddFront!(this, f).AddFront.dg `(int _param_0)` is not callable using argument types `()`
fail_compilation/ice9540.d(25): Error: template instance ice9540.A.test.AddFront!(this, f) error instantiating
---
*/
template Tuple(E...) { alias E Tuple; }
alias Tuple!(int) Args;
void main() {
(new A).test ();
}
void test1 (int delegate (int) f) { f (-2); }
class A
{
int f (int a) {
return a;
}
void test () {
test1 (&AddFront!(this, f));
}
}
template AddFront (alias ctx, alias fun) {
auto AddFront(Args args) {
auto dg (Args dgArgs) {
return fun (dgArgs);
}
dg.ptr = ctx;
return dg(args);
}
}
| D |
module wx.Caret;
public import wx.common;
public import wx.Window;
//! \cond EXTERN
extern (C) ЦелУкз wxCaret_ctor();
extern (C) проц wxCaret_dtor(ЦелУкз сам);
extern (C) бул wxCaret_Create(ЦелУкз сам, ЦелУкз окно, цел ширь, цел высь);
extern (C) бул wxCaret_IsOk(ЦелУкз сам);
extern (C) бул wxCaret_IsVisible(ЦелУкз сам);
extern (C) проц wxCaret_GetPosition(ЦелУкз сам, out цел x, out цел y);
extern (C) проц wxCaret_GetSize(ЦелУкз сам, out цел ширь, out цел высь);
extern (C) ЦелУкз wxCaret_GetWindow(ЦелУкз сам);
extern (C) проц wxCaret_SetSize(ЦелУкз сам, цел ширь, цел высь);
extern (C) проц wxCaret_Move(ЦелУкз сам, цел x, цел y);
extern (C) проц wxCaret_Show(ЦелУкз сам, бул показ);
extern (C) проц wxCaret_Hide(ЦелУкз сам);
extern (C) цел wxCaret_GetBlinkTime();
extern (C) проц wxCaret_SetBlinkTime(цел миллисек);
//! \endcond
//---------------------------------------------------------------------
export class Каретка : ВизОбъект
{
export this()
{
this(wxCaret_ctor(), да);
}
export this(ЦелУкз объ)
{
super(объ);
}
export this(ЦелУкз объ, бул памСобств)
{
super(объ);
this.памСобств = памСобств;
}
export this(Окно ок, Размер рм)
{
this(ок, рм.ширь, рм.высь);
}
export this(Окно окно, цел ширь, цел высь)
{
this(wxCaret_ctor(), да);
if (!wxCaret_Create(вхобъ, ВизОбъект.безопУк(окно), ширь, высь))
{
throw new ИсклНевернОперации("Не удалось создать Каретку");
}
}
//---------------------------------------------------------------------
/*
override protected проц dtor()
{
wxCaret_dtor(вхобъ);
}
*/
//----------------------------
export ~this(){wxCaret_dtor(this.м_вхобъ);}
//----------------------------
//---------------------------------------------------------------------
export бул создай(Окно окно, цел ширь, цел высь)
{
return wxCaret_Create(this.м_вхобъ, ВизОбъект.безопУк(окно), ширь, высь);
}
//---------------------------------------------------------------------
export бул Ок()
{
return wxCaret_IsOk(this.м_вхобъ);
}
export бул виден()
{
return wxCaret_IsVisible(this.м_вхобъ);
}
//---------------------------------------------------------------------
export Точка позиция()
{
Точка точка;
wxCaret_GetPosition(this.м_вхобъ, точка.Х, точка.У);
return точка;
}
export проц позиция(Точка значение)
{
wxCaret_Move(this.м_вхобъ, значение.Х, значение.У);
}
//---------------------------------------------------------------------
export Размер размер()
{
Размер рм;
wxCaret_GetSize(this.м_вхобъ, рм.ширь, рм.высь);
return рм;
}
export проц размер(Размер значение)
{
wxCaret_SetSize(this.м_вхобъ, значение.ширь, значение.высь);
}
//---------------------------------------------------------------------
export Окно окно()
{
return cast(Окно)найдиОбъект(wxCaret_GetWindow(this.м_вхобъ));
}
//---------------------------------------------------------------------
export проц показ(бул показать)
{
wxCaret_Show(this.м_вхобъ, показать);
}
export проц спрячь()
{
wxCaret_Hide(this.м_вхобъ);
}
//---------------------------------------------------------------------
static цел времяМигания()
{
return wxCaret_GetBlinkTime();
}
static проц времяМигания(цел значение)
{
wxCaret_SetBlinkTime(значение);
}
export static ВизОбъект Нов(ЦелУкз ptr)
{
return new Каретка(ptr);
}
//---------------------------------------------------------------------
}
//! \cond EXTERN
extern (C) ЦелУкз wxCaretSuspend_ctor(ЦелУкз ок);
extern (C) проц wxCaretSuspend_dtor(ЦелУкз сам);
//! \endcond
//---------------------------------------------------------------------
export class СуспендКаретки : ВизОбъект
{
export this(Окно ок)
{
this(wxCaretSuspend_ctor(ВизОбъект.безопУк(ок)), да);
}
export this(ЦелУкз объ)
{
super(объ);
}
export this(ЦелУкз вхобъ, бул памСобств)
{
super(вхобъ);
this.памСобств = памСобств;
}
//----------------------------
export ~this(){wxCaretSuspend_dtor(this.м_вхобъ);}
//----------------------------
//---------------------------------------------------------------------
/*
override protected проц dtor()
{
wxCaretSuspend_dtor(вхобъ);
}
*/
}
| D |
// D import file generated from 'all.d'
public
{
import std.stdio;
import std.conv;
import gamelib.all;
import core.memory;
import controller;
import mylib.yaml;
import replay;
import mylib.matrix;
import material.transitiontable;
import mylib.camellia;
import mylib.csv;
import mylib.table;
import std.md5;
import std.zip;
import particle;
import scoredata;
import score;
import gameobj;
import tables;
import state;
import scene;
import gamescene;
import gameplayscene;
import gamereplayscene;
import titlescene;
import logoscene;
import level;
import ability;
import moverfactory;
import stardata;
}
| D |
/*******************************************************************************
Naive implementation of DLS `GetSize` request
Copyright:
Copyright (c) 2015-2017 sociomantic labs GmbH. All rights reserved.
License:
Boost Software License Version 1.0. See LICENSE.txt for details.
*******************************************************************************/
module fakedls.request.GetSize;
/*******************************************************************************
Imports
*******************************************************************************/
import Protocol = dlsproto.node.request.GetSize;
/*******************************************************************************
GetChannels request protocol
*******************************************************************************/
public scope class GetSize : Protocol.GetSize
{
import fakedls.mixins.RequestConstruction;
import fakedls.Storage;
/***************************************************************************
Adds this.resources and constructor to initialize it and forward
arguments to base
***************************************************************************/
mixin RequestConstruction!();
}
| D |
/Users/Polina/XcodeApp/diplom_prj/CoreML_test/build/Pods.build/Debug-iphonesimulator/DITranquillity.build/Objects-normal/x86_64/DIScanFramework.o : /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/DIStoryboard.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/MethodSignature.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Synchronize.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/AutoResolve/DIContainer.Reg.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Log.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Hierarchy/DIFramework.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Scan/DIScanFramework.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Scan/DIScan.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/AutoResolve/DIComponentBuilder.Injection.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/StoryboardContainerMap.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DIComponentBuilder.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/MethodMaker.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DIContainer.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/BundleContainer.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Resolver.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/StoryboardResolver.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DITypes.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DISettings.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Helpers.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Component.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Hierarchy/DIPart.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Scan/DIScanPart.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/TypeKey.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/ByTagAndMany.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DIByTagAndMany.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/Target\ Support\ Files/DITranquillity/DITranquillity-umbrella.h /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/iOS-tvOS/DIStoryboardBase.h /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/DITranquillity.h /Users/Polina/XcodeApp/diplom_prj/CoreML_test/build/Pods.build/Debug-iphonesimulator/DITranquillity.build/unextended-module.modulemap
/Users/Polina/XcodeApp/diplom_prj/CoreML_test/build/Pods.build/Debug-iphonesimulator/DITranquillity.build/Objects-normal/x86_64/DIScanFramework~partial.swiftmodule : /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/DIStoryboard.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/MethodSignature.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Synchronize.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/AutoResolve/DIContainer.Reg.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Log.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Hierarchy/DIFramework.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Scan/DIScanFramework.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Scan/DIScan.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/AutoResolve/DIComponentBuilder.Injection.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/StoryboardContainerMap.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DIComponentBuilder.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/MethodMaker.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DIContainer.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/BundleContainer.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Resolver.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/StoryboardResolver.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DITypes.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DISettings.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Helpers.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Component.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Hierarchy/DIPart.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Scan/DIScanPart.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/TypeKey.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/ByTagAndMany.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DIByTagAndMany.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/Target\ Support\ Files/DITranquillity/DITranquillity-umbrella.h /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/iOS-tvOS/DIStoryboardBase.h /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/DITranquillity.h /Users/Polina/XcodeApp/diplom_prj/CoreML_test/build/Pods.build/Debug-iphonesimulator/DITranquillity.build/unextended-module.modulemap
/Users/Polina/XcodeApp/diplom_prj/CoreML_test/build/Pods.build/Debug-iphonesimulator/DITranquillity.build/Objects-normal/x86_64/DIScanFramework~partial.swiftdoc : /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/DIStoryboard.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/MethodSignature.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Synchronize.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/AutoResolve/DIContainer.Reg.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Log.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Hierarchy/DIFramework.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Scan/DIScanFramework.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Scan/DIScan.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/AutoResolve/DIComponentBuilder.Injection.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/StoryboardContainerMap.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DIComponentBuilder.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/MethodMaker.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DIContainer.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/BundleContainer.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Resolver.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/StoryboardResolver.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DITypes.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DISettings.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Helpers.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/Component.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Hierarchy/DIPart.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Scan/DIScanPart.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/TypeKey.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Private/ByTagAndMany.swift /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Core/Public/DIByTagAndMany.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.apinotesc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Metal.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Foundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator/x86_64/SwiftOnoneSupport.swiftmodule /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/Target\ Support\ Files/DITranquillity/DITranquillity-umbrella.h /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/Storyboard/iOS-tvOS/DIStoryboardBase.h /Users/Polina/XcodeApp/diplom_prj/CoreML_test/Pods/DITranquillity/Sources/DITranquillity.h /Users/Polina/XcodeApp/diplom_prj/CoreML_test/build/Pods.build/Debug-iphonesimulator/DITranquillity.build/unextended-module.modulemap
| D |
// Written in the D programming language.
/++
$(SECTION Overview)
$(P The $(D std.uni) module provides an implementation
of fundamental Unicode algorithms and data structures.
This doesn't include UTF encoding and decoding primitives,
see $(XREF _utf, decode) and $(XREF _utf, encode) in std.utf
for this functionality. )
$(P All primitives listed operate on Unicode characters and
sets of characters. For functions which operate on ASCII characters
and ignore Unicode $(CHARACTERS), see $(LINK2 std_ascii.html, std.ascii).
For definitions of Unicode $(CHARACTER), $(CODEPOINT) and other terms
used throughout this module see the $(S_LINK Terminology, terminology) section
below.
)
$(P The focus of this module is the core needs of developing Unicode-aware
applications. To that effect it provides the following optimized primitives:
)
$(UL
$(LI Character classification by category and common properties:
$(LREF isAlpha), $(LREF isWhite) and others.
)
$(LI
Case-insensitive string comparison ($(LREF sicmp), $(LREF icmp)).
)
$(LI
Converting text to any of the four normalization forms via $(LREF normalize).
)
$(LI
Decoding ($(LREF decodeGrapheme)) and iteration ($(LREF byGrapheme), $(LREF graphemeStride))
by user-perceived characters, that is by $(LREF Grapheme) clusters.
)
$(LI
Decomposing and composing of individual character(s) according to canonical
or compatibility rules, see $(LREF compose) and $(LREF decompose),
including the specific version for Hangul syllables $(LREF composeJamo)
and $(LREF decomposeHangul).
)
)
$(P It's recognized that an application may need further enhancements
and extensions, such as less commonly known algorithms,
or tailoring existing ones for region specific needs. To help users
with building any extra functionality beyond the core primitives,
the module provides:
)
$(UL
$(LI
$(LREF CodepointSet), a type for easy manipulation of sets of characters.
Besides the typical set algebra it provides an unusual feature:
a D source code generator for detection of $(CODEPOINTS) in this set.
This is a boon for meta-programming parser frameworks,
and is used internally to power classification in small
sets like $(LREF isWhite).
)
$(LI
A way to construct optimal packed multi-stage tables also known as a
special case of $(LUCKY Trie).
The functions $(LREF codepointTrie), $(LREF codepointSetTrie)
construct custom tries that map dchar to value.
The end result is a fast and predictable $(BIGOH 1) lookup that powers
functions like $(LREF isAlpha) and $(LREF combiningClass),
but for user-defined data sets.
)
$(LI
Generally useful building blocks for customized normalization:
$(LREF combiningClass) for querying combining class
and $(LREF allowedIn) for testing the Quick_Check
property of a given normalization form.
)
$(LI
Access to a large selection of commonly used sets of $(CODEPOINTS).
$(S_LINK Unicode properties, Supported sets) include Script,
Block and General Category. The exact contents of a set can be
observed in the CLDR utility, on the
$(WEB www.unicode.org/cldr/utility/properties.jsp, property index) page
of the Unicode website.
See $(LREF unicode) for easy and (optionally) compile-time checked set
queries.
)
)
$(SECTION Synopsis)
---
import std.uni;
void main()
{
// initialize code point sets using script/block or property name
// now 'set' contains code points from both scripts.
auto set = unicode("Cyrillic") | unicode("Armenian");
// same thing but simpler and checked at compile-time
auto ascii = unicode.ASCII;
auto currency = unicode.Currency_Symbol;
// easy set ops
auto a = set & ascii;
assert(a.empty); // as it has no intersection with ascii
a = set | ascii;
auto b = currency - a; // subtract all ASCII, Cyrillic and Armenian
// some properties of code point sets
assert(b.length > 45); // 46 items in Unicode 6.1, even more in 6.2
// testing presence of a code point in a set
// is just fine, it is O(logN)
assert(!b['$']);
assert(!b['\u058F']); // Armenian dram sign
assert(b['¥']);
// building fast lookup tables, these guarantee O(1) complexity
// 1-level Trie lookup table essentially a huge bit-set ~262Kb
auto oneTrie = toTrie!1(b);
// 2-level far more compact but typically slightly slower
auto twoTrie = toTrie!2(b);
// 3-level even smaller, and a bit slower yet
auto threeTrie = toTrie!3(b);
assert(oneTrie['£']);
assert(twoTrie['£']);
assert(threeTrie['£']);
// build the trie with the most sensible trie level
// and bind it as a functor
auto cyrillicOrArmenian = toDelegate(set);
auto balance = find!(cyrillicOrArmenian)("Hello ընկեր!");
assert(balance == "ընկեր!");
// compatible with bool delegate(dchar)
bool delegate(dchar) bindIt = cyrillicOrArmenian;
// Normalization
string s = "Plain ascii (and not only), is always normalized!";
assert(s is normalize(s));// is the same string
string nonS = "A\u0308ffin"; // A ligature
auto nS = normalize(nonS); // to NFC, the W3C endorsed standard
assert(nS == "Äffin");
assert(nS != nonS);
string composed = "Äffin";
assert(normalize!NFD(composed) == "A\u0308ffin");
// to NFKD, compatibility decomposition useful for fuzzy matching/searching
assert(normalize!NFKD("2¹⁰") == "210");
}
---
$(SECTION Terminology)
$(P The following is a list of important Unicode notions
and definitions. Any conventions used specifically in this
module alone are marked as such. The descriptions are based on the formal
definition as found in ($WEB http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf,
chapter three of The Unicode Standard Core Specification.)
)
$(P $(DEF Abstract character) A unit of information used for the organization,
control, or representation of textual data.
Note that:
$(UL
$(LI When representing data, the nature of that data
is generally symbolic as opposed to some other
kind of data (for example, visual).)
$(LI An abstract character has no concrete form
and should not be confused with a $(S_LINK Glyph, glyph).)
$(LI An abstract character does not necessarily
correspond to what a user thinks of as a “character”
and should not be confused with a $(LREF Grapheme).)
$(LI The abstract characters encoded (see Encoded character)
are known as Unicode abstract characters.)
$(LI Abstract characters not directly
encoded by the Unicode Standard can often be
represented by the use of combining character sequences.)
)
)
$(P $(DEF Canonical decomposition)
The decomposition of a character or character sequence
that results from recursively applying the canonical
mappings found in the Unicode Character Database
and these described in Conjoining Jamo Behavior
(section 12 of
$(WEB www.unicode.org/uni2book/ch03.pdf, Unicode Conformance)).
)
$(P $(DEF Canonical composition)
The precise definition of the Canonical composition
is the algorithm as specified in $(WEB www.unicode.org/uni2book/ch03.pdf,
Unicode Conformance) section 11.
Informally it's the process that does the reverse of the canonical
decomposition with the addition of certain rules
that e.g. prevent legacy characters from appearing in the composed result.
)
$(P $(DEF Canonical equivalent)
Two character sequences are said to be canonical equivalents if
their full canonical decompositions are identical.
)
$(P $(DEF Character) Typically differs by context.
For the purpose of this documentation the term $(I character)
implies $(I encoded character), that is, a code point having
an assigned abstract character (a symbolic meaning).
)
$(P $(DEF Code point) Any value in the Unicode codespace;
that is, the range of integers from 0 to 10FFFF (hex).
Not all code points are assigned to encoded characters.
)
$(P $(DEF Code unit) The minimal bit combination that can represent
a unit of encoded text for processing or interchange.
Depending on the encoding this could be:
8-bit code units in the UTF-8 ($(D char)),
16-bit code units in the UTF-16 ($(D wchar)),
and 32-bit code units in the UTF-32 ($(D dchar)).
$(I Note that in UTF-32, a code unit is a code point
and is represented by the D $(D dchar) type.)
)
$(P $(DEF Combining character) A character with the General Category
of Combining Mark(M).
$(UL
$(LI All characters with non-zero canonical combining class
are combining characters, but the reverse is not the case:
there are combining characters with a zero combining class.
)
$(LI These characters are not normally used in isolation
unless they are being described. They include such characters
as accents, diacritics, Hebrew points, Arabic vowel signs,
and Indic matras.
)
)
)
$(P $(DEF Combining class)
A numerical value used by the Unicode Canonical Ordering Algorithm
to determine which sequences of combining marks are to be
considered canonically equivalent and which are not.
)
$(P $(DEF Compatibility decomposition)
The decomposition of a character or character sequence that results
from recursively applying both the compatibility mappings and
the canonical mappings found in the Unicode Character Database, and those
described in Conjoining Jamo Behavior no characters
can be further decomposed.
)
$(P $(DEF Compatibility equivalent)
Two character sequences are said to be compatibility
equivalents if their full compatibility decompositions are identical.
)
$(P $(DEF Encoded character) An association (or mapping)
between an abstract character and a code point.
)
$(P $(DEF Glyph) The actual, concrete image of a glyph representation
having been rasterized or otherwise imaged onto some display surface.
)
$(P $(DEF Grapheme base) A character with the property
Grapheme_Base, or any standard Korean syllable block.
)
$(P $(DEF Grapheme cluster) Defined as the text between
grapheme boundaries as specified by Unicode Standard Annex #29,
$(WEB www.unicode.org/reports/tr29/, Unicode text segmentation).
Important general properties of a grapheme:
$(UL
$(LI The grapheme cluster represents a horizontally segmentable
unit of text, consisting of some grapheme base (which may
consist of a Korean syllable) together with any number of
nonspacing marks applied to it.
)
$(LI A grapheme cluster typically starts with a grapheme base
and then extends across any subsequent sequence of nonspacing marks.
A grapheme cluster is most directly relevant to text rendering and
processes such as cursor placement and text selection in editing,
but may also be relevant to comparison and searching.
)
$(LI For many processes, a grapheme cluster behaves as if it was a
single character with the same properties as its grapheme base.
Effectively, nonspacing marks apply $(I graphically) to the base,
but do not change its properties.
)
)
$(P This module defines a number of primitives that work with graphemes:
$(LREF Grapheme), $(LREF decodeGrapheme) and $(LREF graphemeStride).
All of them are using $(I extended grapheme) boundaries
as defined in the aforementioned standard annex.
)
)
$(P $(DEF Nonspacing mark) A combining character with the
General Category of Nonspacing Mark (Mn) or Enclosing Mark (Me).
)
$(P $(DEF Spacing mark) A combining character that is not a nonspacing mark.)
$(SECTION Normalization)
$(P The concepts of $(S_LINK Canonical equivalent, canonical equivalent)
or $(S_LINK Compatibility equivalent, compatibility equivalent)
characters in the Unicode Standard make it necessary to have a full, formal
definition of equivalence for Unicode strings.
String equivalence is determined by a process called normalization,
whereby strings are converted into forms which are compared
directly for identity. This is the primary goal of the normalization process,
see the function $(LREF normalize) to convert into any of
the four defined forms.
)
$(P A very important attribute of the Unicode Normalization Forms
is that they must remain stable between versions of the Unicode Standard.
A Unicode string normalized to a particular Unicode Normalization Form
in one version of the standard is guaranteed to remain in that Normalization
Form for implementations of future versions of the standard.
)
$(P The Unicode Standard specifies four normalization forms.
Informally, two of these forms are defined by maximal decomposition
of equivalent sequences, and two of these forms are defined
by maximal $(I composition) of equivalent sequences.
$(UL
$(LI Normalization Form D (NFD): The $(S_LINK Canonical decomposition,
canonical decomposition) of a character sequence.)
$(LI Normalization Form KD (NFKD): The $(S_LINK Compatibility decomposition,
compatibility decomposition) of a character sequence.)
$(LI Normalization Form C (NFC): The canonical composition of the
$(S_LINK Canonical decomposition, canonical decomposition)
of a coded character sequence.)
$(LI Normalization Form KC (NFKC): The canonical composition
of the $(S_LINK Compatibility decomposition,
compatibility decomposition) of a character sequence)
)
)
$(P The choice of the normalization form depends on the particular use case.
NFC is the best form for general text, since it's more compatible with
strings converted from legacy encodings. NFKC is the preferred form for
identifiers, especially where there are security concerns. NFD and NFKD
are the most useful for internal processing.
)
$(SECTION Construction of lookup tables)
$(P The Unicode standard describes a set of algorithms that
depend on having the ability to quickly look up various properties
of a code point. Given the the codespace of about 1 million $(CODEPOINTS),
it is not a trivial task to provide a space-efficient solution for
the multitude of properties.)
$(P Common approaches such as hash-tables or binary search over
sorted code point intervals (as in $(LREF InversionList)) are insufficient.
Hash-tables have enormous memory footprint and binary search
over intervals is not fast enough for some heavy-duty algorithms.
)
$(P The recommended solution (see Unicode Implementation Guidelines)
is using multi-stage tables that are an implementation of the
$(WEB http://en.wikipedia.org/wiki/Trie, Trie) data structure with integer
keys and a fixed number of stages. For the remainder of the section
this will be called a fixed trie. The following describes a particular
implementation that is aimed for the speed of access at the expense
of ideal size savings.
)
$(P Taking a 2-level Trie as an example the principle of operation is as follows.
Split the number of bits in a key (code point, 21 bits) into 2 components
(e.g. 15 and 8). The first is the number of bits in the index of the trie
and the other is number of bits in each page of the trie.
The layout of the trie is then an array of size 2^^bits-of-index followed
an array of memory chunks of size 2^^bits-of-page/bits-per-element.
)
$(P The number of pages is variable (but not less then 1)
unlike the number of entries in the index. The slots of the index
all have to contain a number of a page that is present. The lookup is then
just a couple of operations - slice the upper bits,
lookup an index for these, take a page at this index and use
the lower bits as an offset within this page.
Assuming that pages are laid out consequently
in one array at $(D pages), the pseudo-code is:
)
---
auto elemsPerPage = (2 ^^ bits_per_page) / Value.sizeOfInBits;
pages[index[n >> bits_per_page]][n & (elemsPerPage - 1)];
---
$(P Where if $(D elemsPerPage) is a power of 2 the whole process is
a handful of simple instructions and 2 array reads. Subsequent levels
of the trie are introduced by recursing on this notion - the index array
is treated as values. The number of bits in index is then again
split into 2 parts, with pages over 'current-index' and the new 'upper-index'.
)
$(P For completeness a level 1 trie is simply an array.
The current implementation takes advantage of bit-packing values
when the range is known to be limited in advance (such as $(D bool)).
See also $(LREF BitPacked) for enforcing it manually.
The major size advantage however comes from the fact
that multiple $(B identical pages on every level are merged) by construction.
)
$(P The process of constructing a trie is more involved and is hidden from
the user in a form of the convenience functions $(LREF codepointTrie),
$(LREF codepointSetTrie) and the even more convenient $(LREF toTrie).
In general a set or built-in AA with $(D dchar) type
can be turned into a trie. The trie object in this module
is read-only (immutable); it's effectively frozen after construction.
)
$(SECTION Unicode properties)
$(P This is a full list of Unicode properties accessible through $(LREF unicode)
with specific helpers per category nested within. Consult the
$(WEB www.unicode.org/cldr/utility/properties.jsp, CLDR utility)
when in doubt about the contents of a particular set.)
$(P General category sets listed below are only accessible with the
$(LREF unicode) shorthand accessor.)
$(BOOKTABLE $(B General category ),
$(TR $(TH Abb.) $(TH Long form)
$(TH Abb.) $(TH Long form)$(TH Abb.) $(TH Long form))
$(TR $(TD L) $(TD Letter)
$(TD Cn) $(TD Unassigned) $(TD Po) $(TD Other_Punctuation))
$(TR $(TD Ll) $(TD Lowercase_Letter)
$(TD Co) $(TD Private_Use) $(TD Ps) $(TD Open_Punctuation))
$(TR $(TD Lm) $(TD Modifier_Letter)
$(TD Cs) $(TD Surrogate) $(TD S) $(TD Symbol))
$(TR $(TD Lo) $(TD Other_Letter)
$(TD N) $(TD Number) $(TD Sc) $(TD Currency_Symbol))
$(TR $(TD Lt) $(TD Titlecase_Letter)
$(TD Nd) $(TD Decimal_Number) $(TD Sk) $(TD Modifier_Symbol))
$(TR $(TD Lu) $(TD Uppercase_Letter)
$(TD Nl) $(TD Letter_Number) $(TD Sm) $(TD Math_Symbol))
$(TR $(TD M) $(TD Mark)
$(TD No) $(TD Other_Number) $(TD So) $(TD Other_Symbol))
$(TR $(TD Mc) $(TD Spacing_Mark)
$(TD P) $(TD Punctuation) $(TD Z) $(TD Separator))
$(TR $(TD Me) $(TD Enclosing_Mark)
$(TD Pc) $(TD Connector_Punctuation) $(TD Zl) $(TD Line_Separator))
$(TR $(TD Mn) $(TD Nonspacing_Mark)
$(TD Pd) $(TD Dash_Punctuation) $(TD Zp) $(TD Paragraph_Separator))
$(TR $(TD C) $(TD Other)
$(TD Pe) $(TD Close_Punctuation) $(TD Zs) $(TD Space_Separator))
$(TR $(TD Cc) $(TD Control) $(TD Pf)
$(TD Final_Punctuation) $(TD -) $(TD Any))
$(TR $(TD Cf) $(TD Format)
$(TD Pi) $(TD Initial_Punctuation) $(TD -) $(TD ASCII))
)
$(P Sets for other commonly useful properties that are
accessible with $(LREF unicode):)
$(BOOKTABLE $(B Common binary properties),
$(TR $(TH Name) $(TH Name) $(TH Name))
$(TR $(TD Alphabetic) $(TD Ideographic) $(TD Other_Uppercase))
$(TR $(TD ASCII_Hex_Digit) $(TD IDS_Binary_Operator) $(TD Pattern_Syntax))
$(TR $(TD Bidi_Control) $(TD ID_Start) $(TD Pattern_White_Space))
$(TR $(TD Cased) $(TD IDS_Trinary_Operator) $(TD Quotation_Mark))
$(TR $(TD Case_Ignorable) $(TD Join_Control) $(TD Radical))
$(TR $(TD Dash) $(TD Logical_Order_Exception) $(TD Soft_Dotted))
$(TR $(TD Default_Ignorable_Code_Point) $(TD Lowercase) $(TD STerm))
$(TR $(TD Deprecated) $(TD Math) $(TD Terminal_Punctuation))
$(TR $(TD Diacritic) $(TD Noncharacter_Code_Point) $(TD Unified_Ideograph))
$(TR $(TD Extender) $(TD Other_Alphabetic) $(TD Uppercase))
$(TR $(TD Grapheme_Base) $(TD Other_Default_Ignorable_Code_Point) $(TD Variation_Selector))
$(TR $(TD Grapheme_Extend) $(TD Other_Grapheme_Extend) $(TD White_Space))
$(TR $(TD Grapheme_Link) $(TD Other_ID_Continue) $(TD XID_Continue))
$(TR $(TD Hex_Digit) $(TD Other_ID_Start) $(TD XID_Start))
$(TR $(TD Hyphen) $(TD Other_Lowercase) )
$(TR $(TD ID_Continue) $(TD Other_Math) )
)
$(P Bellow is the table with block names accepted by $(LREF unicode.block).
Note that the shorthand version $(LREF unicode) requires "In"
to be prepended to the names of blocks so as to disambiguate
scripts and blocks.)
$(BOOKTABLE $(B Blocks),
$(TR $(TD Aegean Numbers) $(TD Ethiopic Extended) $(TD Mongolian))
$(TR $(TD Alchemical Symbols) $(TD Ethiopic Extended-A) $(TD Musical Symbols))
$(TR $(TD Alphabetic Presentation Forms) $(TD Ethiopic Supplement) $(TD Myanmar))
$(TR $(TD Ancient Greek Musical Notation) $(TD General Punctuation) $(TD Myanmar Extended-A))
$(TR $(TD Ancient Greek Numbers) $(TD Geometric Shapes) $(TD New Tai Lue))
$(TR $(TD Ancient Symbols) $(TD Georgian) $(TD NKo))
$(TR $(TD Arabic) $(TD Georgian Supplement) $(TD Number Forms))
$(TR $(TD Arabic Extended-A) $(TD Glagolitic) $(TD Ogham))
$(TR $(TD Arabic Mathematical Alphabetic Symbols) $(TD Gothic) $(TD Ol Chiki))
$(TR $(TD Arabic Presentation Forms-A) $(TD Greek and Coptic) $(TD Old Italic))
$(TR $(TD Arabic Presentation Forms-B) $(TD Greek Extended) $(TD Old Persian))
$(TR $(TD Arabic Supplement) $(TD Gujarati) $(TD Old South Arabian))
$(TR $(TD Armenian) $(TD Gurmukhi) $(TD Old Turkic))
$(TR $(TD Arrows) $(TD Halfwidth and Fullwidth Forms) $(TD Optical Character Recognition))
$(TR $(TD Avestan) $(TD Hangul Compatibility Jamo) $(TD Oriya))
$(TR $(TD Balinese) $(TD Hangul Jamo) $(TD Osmanya))
$(TR $(TD Bamum) $(TD Hangul Jamo Extended-A) $(TD Phags-pa))
$(TR $(TD Bamum Supplement) $(TD Hangul Jamo Extended-B) $(TD Phaistos Disc))
$(TR $(TD Basic Latin) $(TD Hangul Syllables) $(TD Phoenician))
$(TR $(TD Batak) $(TD Hanunoo) $(TD Phonetic Extensions))
$(TR $(TD Bengali) $(TD Hebrew) $(TD Phonetic Extensions Supplement))
$(TR $(TD Block Elements) $(TD High Private Use Surrogates) $(TD Playing Cards))
$(TR $(TD Bopomofo) $(TD High Surrogates) $(TD Private Use Area))
$(TR $(TD Bopomofo Extended) $(TD Hiragana) $(TD Rejang))
$(TR $(TD Box Drawing) $(TD Ideographic Description Characters) $(TD Rumi Numeral Symbols))
$(TR $(TD Brahmi) $(TD Imperial Aramaic) $(TD Runic))
$(TR $(TD Braille Patterns) $(TD Inscriptional Pahlavi) $(TD Samaritan))
$(TR $(TD Buginese) $(TD Inscriptional Parthian) $(TD Saurashtra))
$(TR $(TD Buhid) $(TD IPA Extensions) $(TD Sharada))
$(TR $(TD Byzantine Musical Symbols) $(TD Javanese) $(TD Shavian))
$(TR $(TD Carian) $(TD Kaithi) $(TD Sinhala))
$(TR $(TD Chakma) $(TD Kana Supplement) $(TD Small Form Variants))
$(TR $(TD Cham) $(TD Kanbun) $(TD Sora Sompeng))
$(TR $(TD Cherokee) $(TD Kangxi Radicals) $(TD Spacing Modifier Letters))
$(TR $(TD CJK Compatibility) $(TD Kannada) $(TD Specials))
$(TR $(TD CJK Compatibility Forms) $(TD Katakana) $(TD Sundanese))
$(TR $(TD CJK Compatibility Ideographs) $(TD Katakana Phonetic Extensions) $(TD Sundanese Supplement))
$(TR $(TD CJK Compatibility Ideographs Supplement) $(TD Kayah Li) $(TD Superscripts and Subscripts))
$(TR $(TD CJK Radicals Supplement) $(TD Kharoshthi) $(TD Supplemental Arrows-A))
$(TR $(TD CJK Strokes) $(TD Khmer) $(TD Supplemental Arrows-B))
$(TR $(TD CJK Symbols and Punctuation) $(TD Khmer Symbols) $(TD Supplemental Mathematical Operators))
$(TR $(TD CJK Unified Ideographs) $(TD Lao) $(TD Supplemental Punctuation))
$(TR $(TD CJK Unified Ideographs Extension A) $(TD Latin-1 Supplement) $(TD Supplementary Private Use Area-A))
$(TR $(TD CJK Unified Ideographs Extension B) $(TD Latin Extended-A) $(TD Supplementary Private Use Area-B))
$(TR $(TD CJK Unified Ideographs Extension C) $(TD Latin Extended Additional) $(TD Syloti Nagri))
$(TR $(TD CJK Unified Ideographs Extension D) $(TD Latin Extended-B) $(TD Syriac))
$(TR $(TD Combining Diacritical Marks) $(TD Latin Extended-C) $(TD Tagalog))
$(TR $(TD Combining Diacritical Marks for Symbols) $(TD Latin Extended-D) $(TD Tagbanwa))
$(TR $(TD Combining Diacritical Marks Supplement) $(TD Lepcha) $(TD Tags))
$(TR $(TD Combining Half Marks) $(TD Letterlike Symbols) $(TD Tai Le))
$(TR $(TD Common Indic Number Forms) $(TD Limbu) $(TD Tai Tham))
$(TR $(TD Control Pictures) $(TD Linear B Ideograms) $(TD Tai Viet))
$(TR $(TD Coptic) $(TD Linear B Syllabary) $(TD Tai Xuan Jing Symbols))
$(TR $(TD Counting Rod Numerals) $(TD Lisu) $(TD Takri))
$(TR $(TD Cuneiform) $(TD Low Surrogates) $(TD Tamil))
$(TR $(TD Cuneiform Numbers and Punctuation) $(TD Lycian) $(TD Telugu))
$(TR $(TD Currency Symbols) $(TD Lydian) $(TD Thaana))
$(TR $(TD Cypriot Syllabary) $(TD Mahjong Tiles) $(TD Thai))
$(TR $(TD Cyrillic) $(TD Malayalam) $(TD Tibetan))
$(TR $(TD Cyrillic Extended-A) $(TD Mandaic) $(TD Tifinagh))
$(TR $(TD Cyrillic Extended-B) $(TD Mathematical Alphanumeric Symbols) $(TD Transport And Map Symbols))
$(TR $(TD Cyrillic Supplement) $(TD Mathematical Operators) $(TD Ugaritic))
$(TR $(TD Deseret) $(TD Meetei Mayek) $(TD Unified Canadian Aboriginal Syllabics))
$(TR $(TD Devanagari) $(TD Meetei Mayek Extensions) $(TD Unified Canadian Aboriginal Syllabics Extended))
$(TR $(TD Devanagari Extended) $(TD Meroitic Cursive) $(TD Vai))
$(TR $(TD Dingbats) $(TD Meroitic Hieroglyphs) $(TD Variation Selectors))
$(TR $(TD Domino Tiles) $(TD Miao) $(TD Variation Selectors Supplement))
$(TR $(TD Egyptian Hieroglyphs) $(TD Miscellaneous Mathematical Symbols-A) $(TD Vedic Extensions))
$(TR $(TD Emoticons) $(TD Miscellaneous Mathematical Symbols-B) $(TD Vertical Forms))
$(TR $(TD Enclosed Alphanumerics) $(TD Miscellaneous Symbols) $(TD Yijing Hexagram Symbols))
$(TR $(TD Enclosed Alphanumeric Supplement) $(TD Miscellaneous Symbols and Arrows) $(TD Yi Radicals))
$(TR $(TD Enclosed CJK Letters and Months) $(TD Miscellaneous Symbols And Pictographs) $(TD Yi Syllables))
$(TR $(TD Enclosed Ideographic Supplement) $(TD Miscellaneous Technical) )
$(TR $(TD Ethiopic) $(TD Modifier Tone Letters) )
)
$(P Bellow is the table with script names accepted by $(LREF unicode.script)
and by the shorthand version $(LREF unicode):)
$(BOOKTABLE $(B Scripts),
$(TR $(TD Arabic) $(TD Hanunoo) $(TD Old_Italic))
$(TR $(TD Armenian) $(TD Hebrew) $(TD Old_Persian))
$(TR $(TD Avestan) $(TD Hiragana) $(TD Old_South_Arabian))
$(TR $(TD Balinese) $(TD Imperial_Aramaic) $(TD Old_Turkic))
$(TR $(TD Bamum) $(TD Inherited) $(TD Oriya))
$(TR $(TD Batak) $(TD Inscriptional_Pahlavi) $(TD Osmanya))
$(TR $(TD Bengali) $(TD Inscriptional_Parthian) $(TD Phags_Pa))
$(TR $(TD Bopomofo) $(TD Javanese) $(TD Phoenician))
$(TR $(TD Brahmi) $(TD Kaithi) $(TD Rejang))
$(TR $(TD Braille) $(TD Kannada) $(TD Runic))
$(TR $(TD Buginese) $(TD Katakana) $(TD Samaritan))
$(TR $(TD Buhid) $(TD Kayah_Li) $(TD Saurashtra))
$(TR $(TD Canadian_Aboriginal) $(TD Kharoshthi) $(TD Sharada))
$(TR $(TD Carian) $(TD Khmer) $(TD Shavian))
$(TR $(TD Chakma) $(TD Lao) $(TD Sinhala))
$(TR $(TD Cham) $(TD Latin) $(TD Sora_Sompeng))
$(TR $(TD Cherokee) $(TD Lepcha) $(TD Sundanese))
$(TR $(TD Common) $(TD Limbu) $(TD Syloti_Nagri))
$(TR $(TD Coptic) $(TD Linear_B) $(TD Syriac))
$(TR $(TD Cuneiform) $(TD Lisu) $(TD Tagalog))
$(TR $(TD Cypriot) $(TD Lycian) $(TD Tagbanwa))
$(TR $(TD Cyrillic) $(TD Lydian) $(TD Tai_Le))
$(TR $(TD Deseret) $(TD Malayalam) $(TD Tai_Tham))
$(TR $(TD Devanagari) $(TD Mandaic) $(TD Tai_Viet))
$(TR $(TD Egyptian_Hieroglyphs) $(TD Meetei_Mayek) $(TD Takri))
$(TR $(TD Ethiopic) $(TD Meroitic_Cursive) $(TD Tamil))
$(TR $(TD Georgian) $(TD Meroitic_Hieroglyphs) $(TD Telugu))
$(TR $(TD Glagolitic) $(TD Miao) $(TD Thaana))
$(TR $(TD Gothic) $(TD Mongolian) $(TD Thai))
$(TR $(TD Greek) $(TD Myanmar) $(TD Tibetan))
$(TR $(TD Gujarati) $(TD New_Tai_Lue) $(TD Tifinagh))
$(TR $(TD Gurmukhi) $(TD Nko) $(TD Ugaritic))
$(TR $(TD Han) $(TD Ogham) $(TD Vai))
$(TR $(TD Hangul) $(TD Ol_Chiki) $(TD Yi))
)
$(P Bellow is the table of names accepted by $(LREF unicode.hangulSyllableType).)
$(BOOKTABLE $(B Hangul syllable type),
$(TR $(TH Abb.) $(TH Long form))
$(TR $(TD L) $(TD Leading_Jamo))
$(TR $(TD LV) $(TD LV_Syllable))
$(TR $(TD LVT) $(TD LVT_Syllable) )
$(TR $(TD T) $(TD Trailing_Jamo))
$(TR $(TD V) $(TD Vowel_Jamo))
)
References:
$(WEB www.digitalmars.com/d/ascii-table.html, ASCII Table),
$(WEB en.wikipedia.org/wiki/Unicode, Wikipedia),
$(WEB www.unicode.org, The Unicode Consortium),
$(WEB www.unicode.org/reports/tr15/, Unicode normalization forms),
$(WEB www.unicode.org/reports/tr29/, Unicode text segmentation)
$(WEB www.unicode.org/uni2book/ch05.pdf,
Unicode Implementation Guidelines)
$(WEB www.unicode.org/uni2book/ch03.pdf,
Unicode Conformance)
Trademarks:
Unicode(tm) is a trademark of Unicode, Inc.
Macros:
WIKI=Phobos/StdUni
Copyright: Copyright 2013 -
License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Dmitry Olshansky
Source: $(PHOBOSSRC std/_uni.d)
Standards: $(WEB www.unicode.org/versions/Unicode6.2.0/, Unicode v6.2)
Macros:
SECTION = <h3><a id="$1">$0</a></h3>
DEF = <div><a id="$1"><i>$0</i></a></div>
S_LINK = <a href="#$1">$+</a>
CODEPOINT = $(S_LINK Code point, code point)
CODEPOINTS = $(S_LINK Code point, code points)
CHARACTER = $(S_LINK Character, character)
CHARACTERS = $(S_LINK Character, characters)
CLUSTER = $(S_LINK Grapheme cluster, grapheme cluster)
+/
module std.uni;
static import std.ascii;
import std.traits, std.range, std.algorithm, std.conv,
std.typetuple, std.exception, core.stdc.stdlib;
import std.array; //@@BUG UFCS doesn't work with 'local' imports
import core.bitop;
import std.typecons;
// debug = std_uni;
debug(std_uni) import std.stdio;
private:
version(std_uni_bootstrap){}
else
{
import std.internal.unicode_tables; // generated file
}
void copyBackwards(T)(T[] src, T[] dest)
{
assert(src.length == dest.length);
for(size_t i=src.length; i-- > 0; )
dest[i] = src[i];
}
void copyForward(T)(T[] src, T[] dest)
{
assert(src.length == dest.length);
for(size_t i=0; i<src.length; i++)
dest[i] = src[i];
}
// TODO: update to reflect all major CPUs supporting unaligned reads
version(X86)
enum hasUnalignedReads = true;
else version(X86_64)
enum hasUnalignedReads = true;
else
enum hasUnalignedReads = false; // better be safe then sorry
public enum dchar lineSep = '\u2028'; /// Constant $(CODEPOINT) (0x2028) - line separator.
public enum dchar paraSep = '\u2029'; /// Constant $(CODEPOINT) (0x2029) - paragraph separator.
// test the intro example
unittest
{
// initialize code point sets using script/block or property name
// set contains code points from both scripts.
auto set = unicode("Cyrillic") | unicode("Armenian");
// or simpler and statically-checked look
auto ascii = unicode.ASCII;
auto currency = unicode.Currency_Symbol;
// easy set ops
auto a = set & ascii;
assert(a.empty); // as it has no intersection with ascii
a = set | ascii;
auto b = currency - a; // subtract all ASCII, Cyrillic and Armenian
// some properties of code point sets
assert(b.length > 45); // 46 items in Unicode 6.1, even more in 6.2
// testing presence of a code point in a set
// is just fine, it is O(logN)
assert(!b['$']);
assert(!b['\u058F']); // Armenian dram sign
assert(b['¥']);
// building fast lookup tables, these guarantee O(1) complexity
// 1-level Trie lookup table essentially a huge bit-set ~262Kb
auto oneTrie = toTrie!1(b);
// 2-level far more compact but typically slightly slower
auto twoTrie = toTrie!2(b);
// 3-level even smaller, and a bit slower yet
auto threeTrie = toTrie!3(b);
assert(oneTrie['£']);
assert(twoTrie['£']);
assert(threeTrie['£']);
// build the trie with the most sensible trie level
// and bind it as a functor
auto cyrillicOrArmenian = toDelegate(set);
auto balance = find!(cyrillicOrArmenian)("Hello ընկեր!");
assert(balance == "ընկեր!");
// compatible with bool delegate(dchar)
bool delegate(dchar) bindIt = cyrillicOrArmenian;
// Normalization
string s = "Plain ascii (and not only), is always normalized!";
assert(s is normalize(s));// is the same string
string nonS = "A\u0308ffin"; // A ligature
auto nS = normalize(nonS); // to NFC, the W3C endorsed standard
assert(nS == "Äffin");
assert(nS != nonS);
string composed = "Äffin";
assert(normalize!NFD(composed) == "A\u0308ffin");
// to NFKD, compatibility decomposition useful for fuzzy matching/searching
assert(normalize!NFKD("2¹⁰") == "210");
}
enum lastDchar = 0x10FFFF;
auto force(T, F)(F from)
if(isIntegral!T && !is(T == F))
{
assert(from <= T.max && from >= T.min);
return cast(T)from;
}
auto force(T, F)(F from)
if(isBitPacked!T && !is(T == F))
{
assert(from <= 2^^bitSizeOf!T-1);
return T(cast(TypeOfBitPacked!T)from);
}
auto force(T, F)(F from)
if(is(T == F))
{
return from;
}
// cheap algorithm grease ;)
auto adaptIntRange(T, F)(F[] src)
{
//@@@BUG when in the 9 hells will map be copyable again?!
static struct ConvertIntegers
{
private F[] data;
@property T front()
{
return force!T(data.front);
}
void popFront(){ data.popFront(); }
@property bool empty()const { return data.empty; }
@property size_t length()const { return data.length; }
auto opSlice(size_t s, size_t e)
{
return ConvertIntegers(data[s..e]);
}
@property size_t opDollar(){ return data.length; }
}
return ConvertIntegers(src);
}
// repeat X times the bit-pattern in val assuming it's length is 'bits'
size_t replicateBits(size_t times, size_t bits)(size_t val)
{
static if(times == 1)
return val;
else static if(bits == 1)
{
static if(times == size_t.sizeof*8)
return val ? size_t.max : 0;
else
return val ? (1<<times)-1 : 0;
}
else static if(times % 2)
return (replicateBits!(times-1, bits)(val)<<bits) | val;
else
return replicateBits!(times/2, bits*2)((val<<bits) | val);
}
unittest // for replicate
{
size_t m = 0b111;
size_t m2 = 0b01;
foreach(i; TypeTuple!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
{
assert(replicateBits!(i, 3)(m)+1 == (1<<(3*i)));
assert(replicateBits!(i, 2)(m2) == iota(0, i).map!"2^^(2*a)"().reduce!"a+b"());
}
}
// multiple arrays squashed into one memory block
struct MultiArray(Types...)
{
this(size_t[] sizes...)
{
size_t full_size;
foreach(i, v; Types)
{
full_size += spaceFor!(bitSizeOf!v)(sizes[i]);
sz[i] = sizes[i];
static if(i >= 1)
offsets[i] = offsets[i-1] +
spaceFor!(bitSizeOf!(Types[i-1]))(sizes[i-1]);
}
storage = new size_t[full_size];
}
this(const(size_t)[] raw_offsets,
const(size_t)[] raw_sizes, const(size_t)[] data)const
{
offsets[] = raw_offsets[];
sz[] = raw_sizes[];
storage = data;
}
@property auto slice(size_t n)()inout pure nothrow
{
auto ptr = raw_ptr!n;
return packedArrayView!(Types[n])(ptr, sz[n]);
}
@property auto ptr(size_t n)()inout pure nothrow
{
auto ptr = raw_ptr!n;
return inout(PackedPtr!(Types[n]))(ptr);
}
template length(size_t n)
{
@property size_t length()const{ return sz[n]; }
@property void length(size_t new_size)
{
if(new_size > sz[n])
{// extend
size_t delta = (new_size - sz[n]);
sz[n] += delta;
delta = spaceFor!(bitSizeOf!(Types[n]))(delta);
storage.length += delta;// extend space at end
// raw_slice!x must follow resize as it could be moved!
// next stmts move all data past this array, last-one-goes-first
static if(n != dim-1)
{
auto start = raw_ptr!(n+1);
// len includes delta
size_t len = (storage.ptr+storage.length-start);
copyBackwards(start[0..len-delta], start[delta..len]);
start[0..delta] = 0;
// offsets are used for raw_slice, ptr etc.
foreach(i; n+1..dim)
offsets[i] += delta;
}
}
else if(new_size < sz[n])
{// shrink
size_t delta = (sz[n] - new_size);
sz[n] -= delta;
delta = spaceFor!(bitSizeOf!(Types[n]))(delta);
// move all data past this array, forward direction
static if(n != dim-1)
{
auto start = raw_ptr!(n+1);
size_t len = (storage.ptr+storage.length-start);
copyForward(start[0..len-delta], start[delta..len]);
// adjust offsets last, they affect raw_slice
foreach(i; n+1..dim)
offsets[i] -= delta;
}
storage.length -= delta;
}
// else - NOP
}
}
@property size_t bytes(size_t n=size_t.max)() const
{
static if(n == size_t.max)
return storage.length*size_t.sizeof;
else static if(n != Types.length-1)
return (raw_ptr!(n+1)-raw_ptr!n)*size_t.sizeof;
else
return (storage.ptr+storage.length - raw_ptr!n)*size_t.sizeof;
}
void store(OutRange)(scope OutRange sink) const
if(isOutputRange!(OutRange, char))
{
import std.format;
formattedWrite(sink, "[%( 0x%x, %)]", offsets[]);
formattedWrite(sink, ", [%( 0x%x, %)]", sz[]);
formattedWrite(sink, ", [%( 0x%x, %)]", storage);
}
private:
@property auto raw_ptr(size_t n)()inout
{
static if(n == 0)
return storage.ptr;
else
{
return storage.ptr+offsets[n];
}
}
enum dim = Types.length;
size_t[dim] offsets;// offset for level x
size_t[dim] sz;// size of level x
alias staticMap!(bitSizeOf, Types) bitWidth;
size_t[] storage;
}
unittest
{
enum dg = (){
// sizes are:
// lvl0: 3, lvl1 : 2, lvl2: 1
auto m = MultiArray!(int, ubyte, int)(3,2,1);
static void check(size_t k, T)(ref T m, int n)
{
foreach(i; 0..n)
assert(m.slice!(k)[i] == i+1, text("level:",i," : ",m.slice!(k)[0..n]));
}
static void checkB(size_t k, T)(ref T m, int n)
{
foreach(i; 0..n)
assert(m.slice!(k)[i] == n-i, text("level:",i," : ",m.slice!(k)[0..n]));
}
static void fill(size_t k, T)(ref T m, int n)
{
foreach(i; 0..n)
m.slice!(k)[i] = force!ubyte(i+1);
}
static void fillB(size_t k, T)(ref T m, int n)
{
foreach(i; 0..n)
m.slice!(k)[i] = force!ubyte(n-i);
}
m.length!1 = 100;
fill!1(m, 100);
check!1(m, 100);
m.length!0 = 220;
fill!0(m, 220);
check!1(m, 100);
check!0(m, 220);
m.length!2 = 17;
fillB!2(m, 17);
checkB!2(m, 17);
check!0(m, 220);
check!1(m, 100);
m.length!2 = 33;
checkB!2(m, 17);
fillB!2(m, 33);
checkB!2(m, 33);
check!0(m, 220);
check!1(m, 100);
m.length!1 = 195;
fillB!1(m, 195);
checkB!1(m, 195);
checkB!2(m, 33);
check!0(m, 220);
auto marr = MultiArray!(BitPacked!(uint, 4), BitPacked!(uint, 6))(20, 10);
marr.length!0 = 15;
marr.length!1 = 30;
fill!1(marr, 30);
fill!0(marr, 15);
check!1(marr, 30);
check!0(marr, 15);
return 0;
};
enum ct = dg();
auto rt = dg();
}
unittest
{// more bitpacking tests
alias MultiArray!(BitPacked!(size_t, 3)
, BitPacked!(size_t, 4)
, BitPacked!(size_t, 3)
, BitPacked!(size_t, 6)
, bool) Bitty;
alias sliceBits!(13, 16) fn1;
alias sliceBits!( 9, 13) fn2;
alias sliceBits!( 6, 9) fn3;
alias sliceBits!( 0, 6) fn4;
static void check(size_t lvl, MA)(ref MA arr){
for(size_t i = 0; i< arr.length!lvl; i++)
assert(arr.slice!(lvl)[i] == i, text("Mismatch on lvl ", lvl, " idx ", i, " value: ", arr.slice!(lvl)[i]));
}
static void fillIdx(size_t lvl, MA)(ref MA arr){
for(size_t i = 0; i< arr.length!lvl; i++)
arr.slice!(lvl)[i] = i;
}
Bitty m1;
m1.length!4 = 10;
m1.length!3 = 2^^6;
m1.length!2 = 2^^3;
m1.length!1 = 2^^4;
m1.length!0 = 2^^3;
m1.length!4 = 2^^16;
for(size_t i = 0; i< m1.length!4; i++)
m1.slice!(4)[i] = i % 2;
fillIdx!1(m1);
check!1(m1);
fillIdx!2(m1);
check!2(m1);
fillIdx!3(m1);
check!3(m1);
fillIdx!0(m1);
check!0(m1);
check!3(m1);
check!2(m1);
check!1(m1);
for(size_t i=0; i < 2^^16; i++)
{
m1.slice!(4)[i] = i % 2;
m1.slice!(0)[fn1(i)] = fn1(i);
m1.slice!(1)[fn2(i)] = fn2(i);
m1.slice!(2)[fn3(i)] = fn3(i);
m1.slice!(3)[fn4(i)] = fn4(i);
}
for(size_t i=0; i < 2^^16; i++)
{
assert(m1.slice!(4)[i] == i % 2);
assert(m1.slice!(0)[fn1(i)] == fn1(i));
assert(m1.slice!(1)[fn2(i)] == fn2(i));
assert(m1.slice!(2)[fn3(i)] == fn3(i));
assert(m1.slice!(3)[fn4(i)] == fn4(i));
}
}
size_t spaceFor(size_t _bits)(size_t new_len) pure nothrow
{
enum bits = _bits == 1 ? 1 : ceilPowerOf2(_bits);// see PackedArrayView
static if(bits > 8*size_t.sizeof)
{
static assert(bits % (size_t.sizeof*8) == 0);
return new_len * bits/(8*size_t.sizeof);
}
else
{
enum factor = size_t.sizeof*8/bits;
return (new_len+factor-1)/factor; // rounded up
}
}
template isBitPackableType(T)
{
enum isBitPackableType = isBitPacked!T
|| isIntegral!T || is(T == bool) || isSomeChar!T;
}
//============================================================================
template PackedArrayView(T)
if((is(T dummy == BitPacked!(U, sz), U, size_t sz)
&& isBitPackableType!U) || isBitPackableType!T)
{
private enum bits = bitSizeOf!T;
alias PackedArrayView = PackedArrayViewImpl!(T, bits > 1 ? ceilPowerOf2(bits) : 1);
}
//unsafe and fast access to a chunk of RAM as if it contains packed values
template PackedPtr(T)
if((is(T dummy == BitPacked!(U, sz), U, size_t sz)
&& isBitPackableType!U) || isBitPackableType!T)
{
private enum bits = bitSizeOf!T;
alias PackedPtr = PackedPtrImpl!(T, bits > 1 ? ceilPowerOf2(bits) : 1);
}
@trusted struct PackedPtrImpl(T, size_t bits)
{
pure nothrow:
static assert(isPowerOf2(bits));
this(inout(size_t)* ptr)inout
{
origin = ptr;
}
private T simpleIndex(size_t n) inout
{
auto q = n / factor;
auto r = n % factor;
return cast(T)((origin[q] >> bits*r) & mask);
}
private void simpleWrite(TypeOfBitPacked!T val, size_t n)
in
{
static if(isIntegral!T)
assert(val <= mask);
}
body
{
auto q = n / factor;
auto r = n % factor;
size_t tgt_shift = bits*r;
size_t word = origin[q];
origin[q] = (word & ~(mask<<tgt_shift))
| (cast(size_t)val << tgt_shift);
}
static if(factor == bytesPerWord// can safely pack by byte
|| factor == 1 // a whole word at a time
|| ((factor == bytesPerWord/2 || factor == bytesPerWord/4)
&& hasUnalignedReads)) // this needs unaligned reads
{
static if(factor == bytesPerWord)
alias U = ubyte;
else static if(factor == bytesPerWord/2)
alias U = ushort;
else static if(factor == bytesPerWord/4)
alias U = uint;
else static if(size_t.sizeof == 8 && factor == bytesPerWord/8)
alias U = ulong;
T opIndex(size_t idx) inout
{
return __ctfe ? simpleIndex(idx) :
cast(inout(T))(cast(U*)origin)[idx];
}
static if(isBitPacked!T) // lack of user-defined implicit conversion
{
void opIndexAssign(T val, size_t idx)
{
return opIndexAssign(cast(TypeOfBitPacked!T)val, idx);
}
}
void opIndexAssign(TypeOfBitPacked!T val, size_t idx)
{
if(__ctfe)
simpleWrite(val, idx);
else
(cast(U*)origin)[idx] = cast(U)val;
}
}
else
{
T opIndex(size_t n) inout
{
return simpleIndex(n);
}
static if(isBitPacked!T) // lack of user-defined implicit conversion
{
void opIndexAssign(T val, size_t idx)
{
return opIndexAssign(cast(TypeOfBitPacked!T)val, idx);
}
}
void opIndexAssign(TypeOfBitPacked!T val, size_t n)
{
return simpleWrite(val, n);
}
}
private:
// factor - number of elements in one machine word
enum factor = size_t.sizeof*8/bits, mask = 2^^bits-1;
enum bytesPerWord = size_t.sizeof;
size_t* origin;
}
// data is packed only by power of two sized packs per word,
// thus avoiding mul/div overhead at the cost of ultimate packing
// this construct doesn't own memory, only provides access, see MultiArray for usage
@trusted struct PackedArrayViewImpl(T, size_t bits)
{
pure nothrow:
this(inout(size_t)* origin, size_t items)inout
{
ptr = inout(PackedPtr!(T))(origin);
limit = items;
}
bool zeros(size_t s, size_t e)
in
{
assert(s <= e);
}
body
{
foreach(v; this[s..e])
if(v)
return false;
return true;
}
T opIndex(size_t idx) inout
in
{
assert(idx < limit);
}
body
{
return ptr[idx];
}
static if(isBitPacked!T) // lack of user-defined implicit conversion
{
void opIndexAssign(T val, size_t idx)
{
return opIndexAssign(cast(TypeOfBitPacked!T)val, idx);
}
}
void opIndexAssign(TypeOfBitPacked!T val, size_t idx)
in
{
assert(idx < limit);
}
body
{
ptr[idx] = val;
}
static if(isBitPacked!T) // lack of user-defined implicit conversions
{
void opSliceAssign(T val, size_t start, size_t end)
{
opSliceAssign(cast(TypeOfBitPacked!T)val, start, end);
}
}
void opSliceAssign(TypeOfBitPacked!T val, size_t start, size_t end)
in
{
assert(start <= end);
assert(end <= limit);
}
body
{
// rounded to factor granularity
size_t pad_start = (start+factor-1)/factor*factor;// rounded up
if(pad_start >= end) //rounded up >= then end of slice
{
//nothing to gain, use per element assignment
foreach(i; start..end)
ptr[i] = val;
return;
}
size_t pad_end = end/factor*factor; // rounded down
size_t i;
for(i=start; i<pad_start; i++)
ptr[i] = val;
// all in between is x*factor elements
if(pad_start != pad_end)
{
size_t repval = replicateBits!(factor, bits)(val);
for(size_t j=i/factor; i<pad_end; i+=factor, j++)
ptr.origin[j] = repval;// so speed it up by factor
}
for(; i<end; i++)
ptr[i] = val;
}
auto opSlice(size_t from, size_t to)
{
return sliceOverIndexed(from, to, &this);
}
auto opSlice(){ return opSlice(0, length); }
bool opEquals(T)(auto ref T arr) const
{
if(length != arr.length)
return false;
for(size_t i=0;i<length; i++)
if(this[i] != arr[i])
return false;
return true;
}
@property size_t length()const{ return limit; }
private:
// factor - number of elements in one machine word
enum factor = size_t.sizeof*8/bits;
PackedPtr!(T) ptr;
size_t limit;
}
private struct SliceOverIndexed(T)
{
enum assignableIndex = is(typeof((){ T.init[0] = Item.init; }));
enum assignableSlice = is(typeof((){ T.init[0..0] = Item.init; }));
auto opIndex(size_t idx)const
in
{
assert(idx < to - from);
}
body
{
return (*arr)[from+idx];
}
static if(assignableIndex)
void opIndexAssign(Item val, size_t idx)
in
{
assert(idx < to - from);
}
body
{
(*arr)[from+idx] = val;
}
auto opSlice(size_t a, size_t b)
{
return typeof(this)(from+a, from+b, arr);
}
// static if(assignableSlice)
void opSliceAssign(T)(T val, size_t start, size_t end)
{
(*arr)[start+from .. end+from] = val;
}
auto opSlice()
{
return typeof(this)(from, to, arr);
}
@property size_t length()const { return to-from;}
auto opDollar()const { return length; }
@property bool empty()const { return from == to; }
@property auto front()const { return (*arr)[from]; }
static if(assignableIndex)
@property void front(Item val) { (*arr)[from] = val; }
@property auto back()const { return (*arr)[to-1]; }
static if(assignableIndex)
@property void back(Item val) { (*arr)[to-1] = val; }
@property auto save() inout { return this; }
void popFront() { from++; }
void popBack() { to--; }
bool opEquals(T)(auto ref T arr) const
{
if(arr.length != length)
return false;
for(size_t i=0; i <length; i++)
if(this[i] != arr[i])
return false;
return true;
}
private:
alias typeof(T.init[0]) Item;
size_t from, to;
T* arr;
}
static assert(isRandomAccessRange!(SliceOverIndexed!(int[])));
// BUG? forward reference to return type of sliceOverIndexed!Grapheme
SliceOverIndexed!(const(T)) sliceOverIndexed(T)(size_t a, size_t b, const(T)* x)
if(is(Unqual!T == T))
{
return SliceOverIndexed!(const(T))(a, b, x);
}
// BUG? inout is out of reach
//...SliceOverIndexed.arr only parameters or stack based variables can be inout
SliceOverIndexed!T sliceOverIndexed(T)(size_t a, size_t b, T* x)
if(is(Unqual!T == T))
{
return SliceOverIndexed!T(a, b, x);
}
unittest
{
int[] idxArray = [2, 3, 5, 8, 13];
auto sliced = sliceOverIndexed(0, idxArray.length, &idxArray);
assert(!sliced.empty);
assert(sliced.front == 2);
sliced.front = 1;
assert(sliced.front == 1);
assert(sliced.back == 13);
sliced.popFront();
assert(sliced.front == 3);
assert(sliced.back == 13);
sliced.back = 11;
assert(sliced.back == 11);
sliced.popBack();
assert(sliced.front == 3);
assert(sliced[$-1] == 8);
sliced = sliced[];
assert(sliced[0] == 3);
assert(sliced.back == 8);
sliced = sliced[1..$];
assert(sliced.front == 5);
sliced = sliced[0..$-1];
assert(sliced[$-1] == 5);
int[] other = [2, 5];
assert(sliced[] == sliceOverIndexed(1, 2, &other));
sliceOverIndexed(0, 2, &idxArray)[0..2] = -1;
assert(idxArray[0..2] == [-1, -1]);
uint[] nullArr = null;
auto nullSlice = sliceOverIndexed(0, 0, &idxArray);
assert(nullSlice.empty);
}
private auto packedArrayView(T)(inout(size_t)* ptr, size_t items) @trusted pure nothrow
{
return inout(PackedArrayView!T)(ptr, items);
}
//============================================================================
// Partially unrolled binary search using Shar's method
//============================================================================
private import std.math : pow;
string genUnrolledSwitchSearch(size_t size)
{
assert(isPowerOf2(size));
string code = `auto power = bsr(m)+1;
switch(power){`;
size_t i = bsr(size);
foreach_reverse(val; 0..bsr(size))
{
auto v = 2^^val;
code ~= `
case pow:
if(pred(range[idx+m], needle))
idx += m;
goto case;
`.replace("m", to!string(v))
.replace("pow", to!string(i));
i--;
}
code ~= `
case 0:
if(pred(range[idx], needle))
idx += 1;
goto default;
`;
code ~= `
default:
}`;
return code;
}
bool isPowerOf2(size_t sz) @safe pure nothrow
{
return (sz & (sz-1)) == 0;
}
size_t uniformLowerBound(alias pred, Range, T)(Range range, T needle)
if(is(T : ElementType!Range))
{
assert(isPowerOf2(range.length));
size_t idx = 0, m = range.length/2;
while(m != 0)
{
if(pred(range[idx+m], needle))
idx += m;
m /= 2;
}
if(pred(range[idx], needle))
idx += 1;
return idx;
}
size_t switchUniformLowerBound(alias pred, Range, T)(Range range, T needle)
if(is(T : ElementType!Range))
{
assert(isPowerOf2(range.length));
size_t idx = 0, m = range.length/2;
enum max = 1<<10;
while(m >= max)
{
if(pred(range[idx+m], needle))
idx += m;
m /= 2;
}
mixin(genUnrolledSwitchSearch(max));
return idx;
}
//
size_t floorPowerOf2(size_t arg) @safe pure nothrow
{
assert(arg > 1); // else bsr is undefined
return 1<<bsr(arg-1);
}
size_t ceilPowerOf2(size_t arg) @safe pure nothrow
{
assert(arg > 1); // else bsr is undefined
return 1<<bsr(arg-1)+1;
}
template sharMethod(alias uniLowerBound)
{
size_t sharMethod(alias _pred="a<b", Range, T)(Range range, T needle)
if(is(T : ElementType!Range))
{
import std.functional;
alias binaryFun!_pred pred;
if(range.length == 0)
return 0;
if(isPowerOf2(range.length))
return uniLowerBound!pred(range, needle);
size_t n = floorPowerOf2(range.length);
if(pred(range[n-1], needle))
{// search in another 2^^k area that fully covers the tail of range
size_t k = ceilPowerOf2(range.length - n + 1);
return range.length - k + uniLowerBound!pred(range[$-k..$], needle);
}
else
return uniLowerBound!pred(range[0..n], needle);
}
}
alias sharMethod!uniformLowerBound sharLowerBound;
alias sharMethod!switchUniformLowerBound sharSwitchLowerBound;
unittest
{
auto stdLowerBound(T)(T[] range, T needle)
{
return assumeSorted(range).lowerBound(needle).length;
}
immutable MAX = 5*1173;
auto arr = array(iota(5, MAX, 5));
assert(arr.length == MAX/5-1);
foreach(i; 0..MAX+5)
{
auto std = stdLowerBound(arr, i);
assert(std == sharLowerBound(arr, i));
assert(std == sharSwitchLowerBound(arr, i));
}
arr = [];
auto std = stdLowerBound(arr, 33);
assert(std == sharLowerBound(arr, 33));
assert(std == sharSwitchLowerBound(arr, 33));
}
//============================================================================
@safe:
// hope to see simillar stuff in public interface... once Allocators are out
//@@@BUG moveFront and friends? dunno, for now it's POD-only
@trusted size_t genericReplace(Policy=void, T, Range)
(ref T dest, size_t from, size_t to, Range stuff)
{
size_t delta = to - from;
size_t stuff_end = from+stuff.length;
if(stuff.length > delta)
{// replace increases length
delta = stuff.length - delta;// now, new is > old by delta
static if(is(Policy == void))
dest.length = dest.length+delta;//@@@BUG lame @property
else
dest = Policy.realloc(dest, dest.length+delta);
auto rem = copy(retro(dest[to..dest.length-delta])
, retro(dest[to+delta..dest.length]));
assert(rem.empty);
copy(stuff, dest[from..stuff_end]);
}
else if(stuff.length == delta)
{
copy(stuff, dest[from..to]);
}
else
{// replace decreases length by delta
delta = delta - stuff.length;
copy(stuff, dest[from..stuff_end]);
auto rem = copy(dest[to..dest.length]
, dest[stuff_end..dest.length-delta]);
static if(is(Policy == void))
dest.length = dest.length - delta;//@@@BUG lame @property
else
dest = Policy.realloc(dest, dest.length-delta);
assert(rem.empty);
}
return stuff_end;
}
// Simple storage manipulation policy
@trusted public struct GcPolicy
{
static T[] dup(T)(const T[] arr)
{
return arr.dup;
}
static T[] alloc(T)(size_t size)
{
return new T[size];
}
static T[] realloc(T)(T[] arr, size_t sz)
{
arr.length = sz;
return arr;
}
static void replaceImpl(T, Range)(ref T[] dest, size_t from, size_t to, Range stuff)
{
replaceInPlace(dest, from, to, stuff);
}
static void append(T, V)(ref T[] arr, V value)
if(!isInputRange!V)
{
arr ~= force!T(value);
}
static void append(T, V)(ref T[] arr, V value)
if(isInputRange!V)
{
insertInPlace(arr, arr.length, value);
}
static void destroy(T)(ref T arr)
if(isDynamicArray!T && is(Unqual!T == T))
{
version(bug10929) //@@@BUG@@@
{
debug
{
arr[] = cast(typeof(T.init[0]))(0xdead_beef);
}
arr = null;
}
}
static void destroy(T)(ref T arr)
if(isDynamicArray!T && !is(Unqual!T == T))
{
arr = null;
}
}
// ditto
@trusted struct ReallocPolicy
{
static T[] dup(T)(const T[] arr)
{
auto result = alloc!T(arr.length);
result[] = arr[];
return result;
}
static T[] alloc(T)(size_t size)
{
auto ptr = cast(T*)enforce(malloc(T.sizeof*size), "out of memory on C heap");
return ptr[0..size];
}
static T[] realloc(T)(T[] arr, size_t size)
{
if(!size)
{
destroy(arr);
return null;
}
auto ptr = cast(T*)enforce(core.stdc.stdlib.realloc(
arr.ptr, T.sizeof*size), "out of memory on C heap");
return ptr[0..size];
}
static void replaceImpl(T, Range)(ref T[] dest, size_t from, size_t to, Range stuff)
{
genericReplace!(ReallocPolicy)(dest, from, to, stuff);
}
static void append(T, V)(ref T[] arr, V value)
if(!isInputRange!V)
{
arr = realloc(arr, arr.length+1);
arr[$-1] = force!T(value);
}
static void append(T, V)(ref T[] arr, V value)
if(isInputRange!V && hasLength!V)
{
arr = realloc(arr, arr.length+value.length);
copy(value, arr[$-value.length..$]);
}
static void destroy(T)(ref T[] arr)
{
if(arr.ptr)
free(arr.ptr);
arr = null;
}
}
//build hack
alias Uint24Array!ReallocPolicy _RealArray;
unittest
{
with(ReallocPolicy)
{
bool test(T, U, V)(T orig, size_t from, size_t to, U toReplace, V result,
string file = __FILE__, size_t line = __LINE__)
{
{
replaceImpl(orig, from, to, toReplace);
scope(exit) destroy(orig);
if(!equalS(orig, result))
return false;
}
return true;
}
static T[] arr(T)(T[] args... )
{
return dup(args);
}
assert(test(arr([1, 2, 3, 4]), 0, 0, [5, 6, 7], [5, 6, 7, 1, 2, 3, 4]));
assert(test(arr([1, 2, 3, 4]), 0, 2, cast(int[])[], [3, 4]));
assert(test(arr([1, 2, 3, 4]), 0, 4, [5, 6, 7], [5, 6, 7]));
assert(test(arr([1, 2, 3, 4]), 0, 2, [5, 6, 7], [5, 6, 7, 3, 4]));
assert(test(arr([1, 2, 3, 4]), 2, 3, [5, 6, 7], [1, 2, 5, 6, 7, 4]));
}
}
/**
Tests if T is some kind a set of code points. Intended for template constraints.
*/
public template isCodepointSet(T)
{
static if(is(T dummy == InversionList!(Args), Args...))
enum isCodepointSet = true;
else
enum isCodepointSet = false;
}
/**
Tests if $(D T) is a pair of integers that implicitly convert to $(D V).
The following code must compile for any pair $(D T):
---
(T x){ V a = x[0]; V b = x[1];}
---
The following must not compile:
---
(T x){ V c = x[2];}
---
*/
public template isIntegralPair(T, V=uint)
{
enum isIntegralPair = is(typeof((T x){ V a = x[0]; V b = x[1];}))
&& !is(typeof((T x){ V c = x[2]; }));
}
/**
The recommended default type for set of $(CODEPOINTS).
For details, see the current implementation: $(LREF InversionList).
*/
public alias InversionList!GcPolicy CodepointSet;
//@@@BUG: std.typecons tuples depend on std.format to produce fields mixin
// which relies on std.uni.isGraphical and this chain blows up with Forward reference error
// hence below doesn't seem to work
// public alias Tuple!(uint, "a", uint, "b") CodepointInterval;
/**
The recommended type of $(XREF _typecons, Tuple)
to represent [a, b$(RPAREN) intervals of $(CODEPOINTS). As used in $(LREF InversionList).
Any interval type should pass $(LREF isIntegralPair) trait.
*/
public struct CodepointInterval
{
uint[2] _tuple;
alias _tuple this;
this(uint low, uint high)
{
_tuple[0] = low;
_tuple[1] = high;
}
bool opEquals(T)(T val) const
{
return this[0] == val[0] && this[1] == val[1];
}
@property ref uint a(){ return _tuple[0]; }
@property ref uint b(){ return _tuple[1]; }
}
//@@@BUG another forward reference workaround
@trusted bool equalS(R1, R2)(R1 lhs, R2 rhs)
{
for(;;){
if(lhs.empty)
return rhs.empty;
if(rhs.empty)
return false;
if(lhs.front != rhs.front)
return false;
lhs.popFront();
rhs.popFront();
}
}
/**
$(P
$(D InversionList) is a set of $(CODEPOINTS)
represented as an array of open-right [a, b$(RPAREN)
intervals (see $(LREF CodepointInterval) above).
The name comes from the way the representation reads left to right.
For instance a set of all values [10, 50$(RPAREN), [80, 90$(RPAREN),
plus a singular value 60 looks like this:
)
---
10, 50, 60, 61, 80, 90
---
$(P
The way to read this is: start with negative meaning that all numbers
smaller then the next one are not present in this set (and positive
- the contrary). Then switch positive/negative after each
number passed from left to right.
)
$(P This way negative spans until 10, then positive until 50,
then negative until 60, then positive until 61, and so on.
As seen this provides a space-efficient storage of highly redundant data
that comes in long runs. A description which Unicode $(CHARACTER)
properties fit nicely. The technique itself could be seen as a variation
on $(LUCKY RLE encoding).
)
$(P Sets are value types (just like $(D int) is) thus they
are never aliased.
)
Example:
---
auto a = CodepointSet('a', 'z'+1);
auto b = CodepointSet('A', 'Z'+1);
auto c = a;
a = a | b;
assert(a == CodepointSet('A', 'Z'+1, 'a', 'z'+1));
assert(a != c);
---
$(P See also $(LREF unicode) for simpler construction of sets
from predefined ones.
)
$(P Memory usage is 6 bytes per each contiguous interval in a set.
The value semantics are achieved by using the
($WEB http://en.wikipedia.org/wiki/Copy-on-write, COW) technique
and thus it's $(RED not) safe to cast this type to $(D_KEYWORD shared).
)
Note:
$(P It's not recommended to rely on the template parameters
or the exact type of a current $(CODEPOINT) set in $(D std.uni).
The type and parameters may change when the standard
allocators design is finalized.
Use $(LREF isCodepointSet) with templates or just stick with the default
alias $(LREF CodepointSet) throughout the whole code base.
)
*/
@trusted public struct InversionList(SP=GcPolicy)
{
public:
/**
Construct from another code point set of any type.
*/
this(Set)(Set set)
if(isCodepointSet!Set)
{
uint[] arr;
foreach(v; set.byInterval)
{
arr ~= v.a;
arr ~= v.b;
}
data = Uint24Array!(SP)(arr);
}
/**
Construct a set from a range of sorted code point intervals.
*/
this(Range)(Range intervals)
if(isForwardRange!Range && isIntegralPair!(ElementType!Range))
{
auto flattened = roundRobin(intervals.save.map!"a[0]"(),
intervals.save.map!"a[1]"());
data = Uint24Array!(SP)(flattened);
}
/**
Construct a set from plain values of sorted code point intervals.
Example:
---
auto set = CodepointSet('a', 'z'+1, 'а', 'я'+1);
foreach(v; 'a'..'z'+1)
assert(set[v]);
// Cyrillic lowercase interval
foreach(v; 'а'..'я'+1)
assert(set[v]);
---
*/
this()(uint[] intervals...)
in
{
assert(intervals.length % 2 == 0, "Odd number of interval bounds [a, b)!");
for(uint i=1; i<intervals.length; i++)
assert(intervals[i-1] < intervals[i]);
}
body
{
data = Uint24Array!(SP)(intervals);
}
/**
Get range that spans all of the $(CODEPOINT) intervals in this $(LREF InversionList).
Example:
---
import std.algorithm, std.typecons;
auto set = CodepointSet('A', 'D'+1, 'a', 'd'+1);
set.byInterval.equal([tuple('A', 'E'), tuple('a', 'e')]);
---
*/
@property auto byInterval()
{
static struct Intervals
{
this(Uint24Array!SP sp)
{
slice = sp;
start = 0;
end = sp.length;
}
this(Uint24Array!SP sp, size_t s, size_t e)
{
slice = sp;
start = s;
end = e;
}
@property auto front()const
{
uint a = slice[start];
uint b = slice[start+1];
return CodepointInterval(a, b);
}
@property auto back()const
{
uint a = slice[end-2];
uint b = slice[end-1];
return CodepointInterval(a, b);
}
void popFront()
{
start += 2;
}
void popBack()
{
end -= 2;
}
auto opIndex(size_t idx) const
{
uint a = slice[start+idx*2];
uint b = slice[start+idx*2+1];
return CodepointInterval(a, b);
}
auto opSlice(size_t s, size_t e)
{
return Intervals(slice, s*2+start, e*2+start);
}
@property size_t length()const { return slice.length/2; }
@property bool empty()const { return start == end; }
@property auto save(){ return this; }
private:
size_t start, end;
Uint24Array!SP slice;
}
return Intervals(data);
}
/**
Tests the presence of code point $(D val) in this set.
Example:
---
auto gothic = unicode.Gothic;
// Gothic letter ahsa
assert(gothic['\U00010330']);
// no ascii in Gothic obviously
assert(!gothic['$']);
---
*/
bool opIndex(uint val) const
{
// the <= ensures that searching in interval of [a, b) for 'a' you get .length == 1
// return assumeSorted!((a,b) => a<=b)(data[]).lowerBound(val).length & 1;
return sharSwitchLowerBound!"a<=b"(data[], val) & 1;
}
/// Number of $(CODEPOINTS) in this set
@property size_t length()
{
size_t sum = 0;
foreach(iv; byInterval)
{
sum += iv.b - iv.a;
}
return sum;
}
// bootstrap full set operations from 4 primitives (suitable as a template mixin):
// addInterval, skipUpTo, dropUpTo & byInterval iteration
//============================================================================
public:
/**
$(P Sets support natural syntax for set algebra, namely: )
$(BOOKTABLE ,
$(TR $(TH Operator) $(TH Math notation) $(TH Description) )
$(TR $(TD &) $(TD a ∩ b) $(TD intersection) )
$(TR $(TD |) $(TD a ∪ b) $(TD union) )
$(TR $(TD -) $(TD a ∖ b) $(TD subtraction) )
$(TR $(TD ~) $(TD a ~ b) $(TD symmetric set difference i.e. (a ∪ b) \ (a ∩ b)) )
)
Example:
---
auto lower = unicode.LowerCase;
auto upper = unicode.UpperCase;
auto ascii = unicode.ASCII;
assert((lower & upper).empty); // no intersection
auto lowerASCII = lower & ascii;
assert(lowerASCII.byCodepoint.equal(iota('a', 'z'+1)));
// throw away all of the lowercase ASCII
assert((ascii - lower).length == 128 - 26);
auto onlyOneOf = lower ~ ascii;
assert(!onlyOneOf['Δ']); // not ASCII and not lowercase
assert(onlyOneOf['$']); // ASCII and not lowercase
assert(!onlyOneOf['a']); // ASCII and lowercase
assert(onlyOneOf['я']); // not ASCII but lowercase
// throw away all cased letters from ASCII
auto noLetters = ascii - (lower | upper);
assert(noLetters.length == 128 - 26*2);
---
*/
This opBinary(string op, U)(U rhs)
if(isCodepointSet!U || is(U:dchar))
{
static if(op == "&" || op == "|" || op == "~")
{// symmetric ops thus can swap arguments to reuse r-value
static if(is(U:dchar))
{
auto tmp = this;
mixin("tmp "~op~"= rhs; ");
return tmp;
}
else
{
static if(is(Unqual!U == U))
{
// try hard to reuse r-value
mixin("rhs "~op~"= this;");
return rhs;
}
else
{
auto tmp = this;
mixin("tmp "~op~"= rhs;");
return tmp;
}
}
}
else static if(op == "-") // anti-symmetric
{
auto tmp = this;
tmp -= rhs;
return tmp;
}
else
static assert(0, "no operator "~op~" defined for Set");
}
/// The 'op=' versions of the above overloaded operators.
ref This opOpAssign(string op, U)(U rhs)
if(isCodepointSet!U || is(U:dchar))
{
static if(op == "|") // union
{
static if(is(U:dchar))
{
this.addInterval(rhs, rhs+1);
return this;
}
else
return this.add(rhs);
}
else static if(op == "&") // intersection
return this.intersect(rhs);// overloaded
else static if(op == "-") // set difference
return this.sub(rhs);// overloaded
else static if(op == "~") // symmetric set difference
{
auto copy = this & rhs;
this |= rhs;
this -= copy;
return this;
}
else
static assert(0, "no operator "~op~" defined for Set");
}
/**
Tests the presence of codepoint $(D ch) in this set,
the same as $(LREF opIndex).
*/
bool opBinaryRight(string op: "in", U)(U ch) const
if(is(U : dchar))
{
return this[ch];
}
///
unittest
{
assert('я' in unicode.Cyrillic);
assert(!('z' in unicode.Cyrillic));
}
/// Obtains a set that is the inversion of this set. See also $(LREF inverted).
auto opUnary(string op: "!")()
{
return this.inverted;
}
/**
A range that spans each $(CODEPOINT) in this set.
Example:
---
import std.algorithm;
auto set = unicode.ASCII;
set.byCodepoint.equal(iota(0, 0x80));
---
*/
@property auto byCodepoint()
{
@trusted static struct CodepointRange
{
this(This set)
{
r = set.byInterval;
if(!r.empty)
cur = r.front.a;
}
@property dchar front() const
{
return cast(dchar)cur;
}
@property bool empty() const
{
return r.empty;
}
void popFront()
{
cur++;
while(cur >= r.front.b)
{
r.popFront();
if(r.empty)
break;
cur = r.front.a;
}
}
private:
uint cur;
typeof(This.init.byInterval) r;
}
return CodepointRange(this);
}
/**
$(P Obtain textual representation of this set in from of
open-right intervals and feed it to $(D sink).
)
$(P Used by various standard formatting facilities such as
$(XREF _format, formattedWrite), $(XREF _stdio, write),
$(XREF _stdio, writef), $(XREF _conv, to) and others.
)
Example:
---
import std.conv;
assert(unicode.ASCII.to!string == "[0..128$(RPAREN)");
---
*/
void toString(scope void delegate (const(char)[]) sink)
{
import std.format;
auto range = byInterval;
if(range.empty)
return;
auto val = range.front;
formattedWrite(sink, "[%d..%d)", val.a, val.b);
range.popFront();
foreach(i; range)
formattedWrite(sink, " [%d..%d)", i.a, i.b);
}
/**
Add an interval [a, b$(RPAREN) to this set.
Example:
---
CodepointSet someSet;
someSet.add('0', '5').add('A','Z'+1);
someSet.add('5', '9'+1);
assert(someSet['0']);
assert(someSet['5']);
assert(someSet['9']);
assert(someSet['Z']);
---
*/
ref add()(uint a, uint b)
{
addInterval(a, b);
return this;
}
private:
ref intersect(U)(U rhs)
if(isCodepointSet!U)
{
Marker mark;
foreach( i; rhs.byInterval)
{
mark = this.dropUpTo(i.a, mark);
mark = this.skipUpTo(i.b, mark);
}
this.dropUpTo(uint.max, mark);
return this;
}
ref intersect()(dchar ch)
{
foreach(i; byInterval)
if(i.a <= ch && ch < i.b)
return this = This.init.add(ch, ch+1);
this = This.init;
return this;
}
///
unittest
{
assert(unicode.Cyrillic.intersect('-').byInterval.empty);
}
ref sub()(dchar ch)
{
return subChar(ch);
}
// same as the above except that skip & drop parts are swapped
ref sub(U)(U rhs)
if(isCodepointSet!U)
{
uint top;
Marker mark;
foreach(i; rhs.byInterval)
{
mark = this.skipUpTo(i.a, mark);
mark = this.dropUpTo(i.b, mark);
}
return this;
}
ref add(U)(U rhs)
if(isCodepointSet!U)
{
Marker start;
foreach(i; rhs.byInterval)
{
start = addInterval(i.a, i.b, start);
}
return this;
}
// end of mixin-able part
//============================================================================
public:
/**
Obtains a set that is the inversion of this set.
See the '!' $(LREF opUnary) for the same but using operators.
Example:
---
set = unicode.ASCII;
// union with the inverse gets all of the code points in the Unicode
assert((set | set.inverted).length == 0x110000);
// no intersection with the inverse
assert((set & set.inverted).empty);
---
*/
@property auto inverted()
{
InversionList inversion = this;
if(inversion.data.length == 0)
{
inversion.addInterval(0, lastDchar+1);
return inversion;
}
if(inversion.data[0] != 0)
genericReplace(inversion.data, 0, 0, [0]);
else
genericReplace(inversion.data, 0, 1, cast(uint[])null);
if(data[data.length-1] != lastDchar+1)
genericReplace(inversion.data,
inversion.data.length, inversion.data.length, [lastDchar+1]);
else
genericReplace(inversion.data,
inversion.data.length-1, inversion.data.length, cast(uint[])null);
return inversion;
}
/**
Generates string with D source code of unary function with name of
$(D funcName) taking a single $(D dchar) argument. If $(D funcName) is empty
the code is adjusted to be a lambda function.
The function generated tests if the $(CODEPOINT) passed
belongs to this set or not. The result is to be used with string mixin.
The intended usage area is aggressive optimization via meta programming
in parser generators and the like.
Note: Use with care for relatively small or regular sets. It
could end up being slower then just using multi-staged tables.
Example:
---
import std.stdio;
// construct set directly from [a, b) intervals
auto set = CodepointSet(10, 12, 45, 65, 100, 200);
writeln(set);
writeln(set.toSourceCode("func"));
---
The above outputs something along the lines of:
---
bool func(dchar ch)
{
if(ch < 45)
{
if(ch == 10 || ch == 11) return true;
return false;
}
else if (ch < 65) return true;
else
{
if(ch < 100) return false;
if(ch < 200) return true;
return false;
}
}
---
*/
string toSourceCode(string funcName="")
{
import std.string;
enum maxBinary = 3;
static string linearScope(R)(R ivals, string indent)
{
string result = indent~"{\n";
string deeper = indent~" ";
foreach(ival; ivals)
{
auto span = ival[1] - ival[0];
assert(span != 0);
if(span == 1)
{
result ~= format("%sif(ch == %s) return true;\n", deeper, ival[0]);
}
else if(span == 2)
{
result ~= format("%sif(ch == %s || ch == %s) return true;\n",
deeper, ival[0], ival[0]+1);
}
else
{
if(ival[0] != 0) // dchar is unsigned and < 0 is useless
result ~= format("%sif(ch < %s) return false;\n", deeper, ival[0]);
result ~= format("%sif(ch < %s) return true;\n", deeper, ival[1]);
}
}
result ~= format("%sreturn false;\n%s}\n", deeper, indent); // including empty range of intervals
return result;
}
static string binaryScope(R)(R ivals, string indent)
{
// time to do unrolled comparisons?
if(ivals.length < maxBinary)
return linearScope(ivals, indent);
else
return bisect(ivals, ivals.length/2, indent);
}
// not used yet if/elsebinary search is far better with DMD as of 2.061
// and GDC is doing fine job either way
static string switchScope(R)(R ivals, string indent)
{
string result = indent~"switch(ch){\n";
string deeper = indent~" ";
foreach(ival; ivals)
{
if(ival[0]+1 == ival[1])
{
result ~= format("%scase %s: return true;\n",
deeper, ival[0]);
}
else
{
result ~= format("%scase %s: .. case %s: return true;\n",
deeper, ival[0], ival[1]-1);
}
}
result ~= deeper~"default: return false;\n"~indent~"}\n";
return result;
}
static string bisect(R)(R range, size_t idx, string indent)
{
string deeper = indent ~ " ";
// bisect on one [a, b) interval at idx
string result = indent~"{\n";
// less branch, < a
result ~= format("%sif(ch < %s)\n%s",
deeper, range[idx][0], binaryScope(range[0..idx], deeper));
// middle point, >= a && < b
result ~= format("%selse if (ch < %s) return true;\n",
deeper, range[idx][1]);
// greater or equal branch, >= b
result ~= format("%selse\n%s",
deeper, binaryScope(range[idx+1..$], deeper));
return result~indent~"}\n";
}
string code = format("bool %s(dchar ch) @safe pure nothrow\n",
funcName.empty ? "function" : funcName);
auto range = byInterval.array();
// special case first bisection to be on ASCII vs beyond
auto tillAscii = countUntil!"a[0] > 0x80"(range);
if(tillAscii <= 0) // everything is ASCII or nothing is ascii (-1 & 0)
code ~= binaryScope(range, "");
else
code ~= bisect(range, tillAscii, "");
return code;
}
/**
True if this set doesn't contain any $(CODEPOINTS).
Example:
---
CodepointSet emptySet;
assert(emptySet.length == 0);
assert(emptySet.empty);
---
*/
@property bool empty() const
{
return data.length == 0;
}
private:
alias typeof(this) This;
alias size_t Marker;
// special case for normal InversionList
ref subChar(dchar ch)
{
auto mark = skipUpTo(ch);
if(mark != data.length
&& data[mark] == ch && data[mark-1] == ch)
{
// it has split, meaning that ch happens to be in one of intervals
data[mark] = data[mark]+1;
}
return this;
}
//
Marker addInterval(int a, int b, Marker hint=Marker.init)
in
{
assert(a <= b, text(a, " > ", b));
}
body
{
auto range = assumeSorted(data[]);
size_t pos;
size_t a_idx = range.lowerBound(a).length;
if(a_idx == range.length)
{
// [---+++----++++----++++++]
// [ a b]
data.append([a, b]);
return data.length-1;
}
size_t b_idx = range[a_idx..range.length].lowerBound(b).length+a_idx;
uint[] to_insert;
debug(std_uni)
{
writefln("a_idx=%d; b_idx=%d;", a_idx, b_idx);
}
if(b_idx == range.length)
{
// [-------++++++++----++++++-]
// [ s a b]
if(a_idx & 1)// a in positive
{
to_insert = [ b ];
}
else// a in negative
{
to_insert = [a, b];
}
genericReplace(data, a_idx, b_idx, to_insert);
return a_idx+to_insert.length-1;
}
uint top = data[b_idx];
debug(std_uni)
{
writefln("a_idx=%d; b_idx=%d;", a_idx, b_idx);
writefln("a=%s; b=%s; top=%s;", a, b, top);
}
if(a_idx & 1)
{// a in positive
if(b_idx & 1)// b in positive
{
// [-------++++++++----++++++-]
// [ s a b ]
to_insert = [top];
}
else // b in negative
{
// [-------++++++++----++++++-]
// [ s a b ]
if(top == b)
{
assert(b_idx+1 < data.length);
pos = genericReplace(data, a_idx, b_idx+2, [data[b_idx+1]]);
return pos;
}
to_insert = [b, top ];
}
}
else
{ // a in negative
if(b_idx & 1) // b in positive
{
// [----------+++++----++++++-]
// [ a b ]
to_insert = [a, top];
}
else// b in negative
{
// [----------+++++----++++++-]
// [ a s b ]
if(top == b)
{
assert(b_idx+1 < data.length);
pos = genericReplace(data, a_idx, b_idx+2, [a, data[b_idx+1] ]);
return pos;
}
to_insert = [a, b, top];
}
}
pos = genericReplace(data, a_idx, b_idx+1, to_insert);
debug(std_uni)
{
writefln("marker idx: %d; length=%d", pos, data[pos], data.length);
writeln("inserting ", to_insert);
}
return pos;
}
//
Marker dropUpTo(uint a, Marker pos=Marker.init)
in
{
assert(pos % 2 == 0); // at start of interval
}
body
{
auto range = assumeSorted!"a<=b"(data[pos..data.length]);
if(range.empty)
return pos;
size_t idx = pos;
idx += range.lowerBound(a).length;
debug(std_uni)
{
writeln("dropUpTo full length=", data.length);
writeln(pos,"~~~", idx);
}
if(idx == data.length)
return genericReplace(data, pos, idx, cast(uint[])[]);
if(idx & 1)
{ // a in positive
//[--+++----++++++----+++++++------...]
// |<---si s a t
genericReplace(data, pos, idx, [a]);
}
else
{ // a in negative
//[--+++----++++++----+++++++-------+++...]
// |<---si s a t
genericReplace(data, pos, idx, cast(uint[])[]);
}
return pos;
}
//
Marker skipUpTo(uint a, Marker pos=Marker.init)
out(result)
{
assert(result % 2 == 0);// always start of interval
//(may be 0-width after-split)
}
body
{
assert(data.length % 2 == 0);
auto range = assumeSorted!"a<=b"(data[pos..data.length]);
size_t idx = pos+range.lowerBound(a).length;
if(idx >= data.length) // could have Marker point to recently removed stuff
return data.length;
if(idx & 1)// inside of interval, check for split
{
uint top = data[idx];
if(top == a)// no need to split, it's end
return idx+1;
uint start = data[idx-1];
if(a == start)
return idx-1;
// split it up
genericReplace(data, idx, idx+1, [a, a, top]);
return idx+1; // avoid odd index
}
return idx;
}
Uint24Array!SP data;
};
@system unittest
{
// test examples
import std.algorithm, std.typecons;
auto set = CodepointSet('A', 'D'+1, 'a', 'd'+1);
set.byInterval.equalS([tuple('A', 'E'), tuple('a', 'e')]);
set = unicode.ASCII;
assert(set.byCodepoint.equalS(iota(0, 0x80)));
set = CodepointSet('a', 'z'+1, 'а', 'я'+1);
foreach(v; 'a'..'z'+1)
assert(set[v]);
// Cyrillic lowercase interval
foreach(v; 'а'..'я'+1)
assert(set[v]);
auto gothic = unicode.Gothic;
// Gothic letter ahsa
assert(gothic['\U00010330']);
// no ascii in Gothic obviously
assert(!gothic['$']);
CodepointSet emptySet;
assert(emptySet.length == 0);
assert(emptySet.empty);
set = unicode.ASCII;
// union with the inverse gets all of code points in the Unicode
assert((set | set.inverted).length == 0x110000);
// no intersection with inverse
assert((set & set.inverted).empty);
CodepointSet someSet;
someSet.add('0', '5').add('A','Z'+1);
someSet.add('5', '9'+1);
assert(someSet['0']);
assert(someSet['5']);
assert(someSet['9']);
assert(someSet['Z']);
auto lower = unicode.LowerCase;
auto upper = unicode.UpperCase;
auto ascii = unicode.ASCII;
assert((lower & upper).empty); // no intersection
auto lowerASCII = lower & ascii;
assert(lowerASCII.byCodepoint.equalS(iota('a', 'z'+1)));
// throw away all of the lowercase ASCII
assert((ascii - lower).length == 128 - 26);
auto onlyOneOf = lower ~ ascii;
assert(!onlyOneOf['Δ']); // not ASCII and not lowercase
assert(onlyOneOf['$']); // ASCII and not lowercase
assert(!onlyOneOf['a']); // ASCII and lowercase
assert(onlyOneOf['я']); // not ASCII but lowercase
auto noLetters = ascii - (lower | upper);
assert(noLetters.length == 128 - 26*2);
import std.conv;
assert(unicode.ASCII.to!string() == "[0..128)");
}
// pedantic version for ctfe, and aligned-access only architectures
@trusted uint safeRead24(const ubyte* ptr, size_t idx) pure nothrow
{
idx *= 3;
version(LittleEndian)
return ptr[idx] + (cast(uint)ptr[idx+1]<<8)
+ (cast(uint)ptr[idx+2]<<16);
else
return (cast(uint)ptr[idx]<<16) + (cast(uint)ptr[idx+1]<<8)
+ ptr[idx+2];
}
// ditto
@trusted void safeWrite24(ubyte* ptr, uint val, size_t idx) pure nothrow
{
idx *= 3;
version(LittleEndian)
{
ptr[idx] = val & 0xFF;
ptr[idx+1] = (val>>8) & 0xFF;
ptr[idx+2] = (val>>16) & 0xFF;
}
else
{
ptr[idx] = (val>>16) & 0xFF;
ptr[idx+1] = (val>>8) & 0xFF;
ptr[idx+2] = val & 0xFF;
}
}
// unaligned x86-like read/write functions
@trusted uint unalignedRead24(const ubyte* ptr, size_t idx) pure nothrow
{
uint* src = cast(uint*)(ptr+3*idx);
version(LittleEndian)
return *src & 0xFF_FFFF;
else
return *src >> 8;
}
// ditto
@trusted void unalignedWrite24(ubyte* ptr, uint val, size_t idx) pure nothrow
{
uint* dest = cast(uint*)(cast(ubyte*)ptr + 3*idx);
version(LittleEndian)
*dest = val | (*dest & 0xFF00_0000);
else
*dest = (val<<8) | (*dest & 0xFF);
}
uint read24(const ubyte* ptr, size_t idx) pure nothrow
{
static if(hasUnalignedReads)
return __ctfe ? safeRead24(ptr, idx) : unalignedRead24(ptr, idx);
else
return safeRead24(ptr, idx);
}
void write24(ubyte* ptr, uint val, size_t idx) pure nothrow
{
static if(hasUnalignedReads)
return __ctfe ? safeWrite24(ptr, val, idx) : unalignedWrite24(ptr, val, idx);
else
return safeWrite24(ptr, val, idx);
}
// Packed array of 24-bit integers, COW semantics.
@trusted struct Uint24Array(SP=GcPolicy)
{
this(Range)(Range range)
if(isInputRange!Range && hasLength!Range)
{
length = range.length;
copy(range, this[]);
}
this(Range)(Range range)
if(isForwardRange!Range && !hasLength!Range)
{
auto len = walkLength(range.save);
length = len;
copy(range, this[]);
}
this(this)
{
if(!empty)
{
refCount = refCount + 1;
}
}
~this()
{
if(!empty)
{
auto cnt = refCount;
if(cnt == 1)
SP.destroy(data);
else
refCount = cnt - 1;
}
}
// no ref-count for empty U24 array
@property bool empty() const { return data.length == 0; }
// report one less then actual size
@property size_t length() const
{
return data.length ? (data.length-4)/3 : 0;
}
//+ an extra slot for ref-count
@property void length(size_t len)
{
if(len == 0)
{
if(!empty)
freeThisReference();
return;
}
immutable bytes = len*3+4; // including ref-count
if(empty)
{
data = SP.alloc!ubyte(bytes);
refCount = 1;
return;
}
auto cur_cnt = refCount;
if(cur_cnt != 1) // have more references to this memory
{
refCount = cur_cnt - 1;
auto new_data = SP.alloc!ubyte(bytes);
// take shrinking into account
auto to_copy = min(bytes, data.length)-4;
copy(data[0..to_copy], new_data[0..to_copy]);
data = new_data; // before setting refCount!
refCount = 1;
}
else // 'this' is the only reference
{
// use the realloc (hopefully in-place operation)
data = SP.realloc(data, bytes);
refCount = 1; // setup a ref-count in the new end of the array
}
}
alias opDollar = length;
// Read 24-bit packed integer
uint opIndex(size_t idx)const
{
return read24(data.ptr, idx);
}
// Write 24-bit packed integer
void opIndexAssign(uint val, size_t idx)
in
{
assert(!empty && val <= 0xFF_FFFF);
}
body
{
auto cnt = refCount;
if(cnt != 1)
dupThisReference(cnt);
write24(data.ptr, val, idx);
}
//
auto opSlice(size_t from, size_t to)
{
return sliceOverIndexed(from, to, &this);
}
///
auto opSlice(size_t from, size_t to) const
{
return sliceOverIndexed(from, to, &this);
}
// length slices before the ref count
auto opSlice()
{
return opSlice(0, length);
}
// length slices before the ref count
auto opSlice() const
{
return opSlice(0, length);
}
void append(Range)(Range range)
if(isInputRange!Range && hasLength!Range && is(ElementType!Range : uint))
{
size_t nl = length + range.length;
length = nl;
copy(range, this[nl-range.length..nl]);
}
void append()(uint val)
{
length = length + 1;
this[$-1] = val;
}
bool opEquals()(auto const ref Uint24Array rhs)const
{
if(empty ^ rhs.empty)
return false; // one is empty and the other isn't
return empty || data[0..$-4] == rhs.data[0..$-4];
}
private:
// ref-count is right after the data
@property uint refCount() const
{
return read24(data.ptr, length);
}
@property void refCount(uint cnt)
in
{
assert(cnt <= 0xFF_FFFF);
}
body
{
write24(data.ptr, cnt, length);
}
void freeThisReference()
{
auto count = refCount;
if(count != 1) // have more references to this memory
{
// dec shared ref-count
refCount = count - 1;
data = [];
}
else
SP.destroy(data);
version(bug10929)
assert(!data.ptr);
else
data = null;
}
void dupThisReference(uint count)
in
{
assert(!empty && count != 1 && count == refCount);
}
body
{
// dec shared ref-count
refCount = count - 1;
// copy to the new chunk of RAM
auto new_data = SP.alloc!ubyte(data.length);
// bit-blit old stuff except the counter
copy(data[0..$-4], new_data[0..$-4]);
data = new_data; // before setting refCount!
refCount = 1; // so that this updates the right one
}
ubyte[] data;
}
@trusted unittest// Uint24 tests //@@@BUG@@ iota is system ?!
{
void funcRef(T)(ref T u24)
{
u24.length = 2;
u24[1] = 1024;
T u24_c = u24;
assert(u24[1] == 1024);
u24.length = 0;
assert(u24.empty);
u24.append([1, 2]);
assert(equalS(u24[], [1, 2]));
u24.append(111);
assert(equalS(u24[], [1, 2, 111]));
assert(!u24_c.empty && u24_c[1] == 1024);
u24.length = 3;
copy(iota(0, 3), u24[]);
assert(equalS(u24[], iota(0, 3)));
assert(u24_c[1] == 1024);
}
void func2(T)(T u24)
{
T u24_2 = u24;
T u24_3;
u24_3 = u24_2;
assert(u24_2 == u24_3);
assert(equalS(u24[], u24_2[]));
assert(equalS(u24_2[], u24_3[]));
funcRef(u24_3);
assert(equalS(u24_3[], iota(0, 3)));
assert(!equalS(u24_2[], u24_3[]));
assert(equalS(u24_2[], u24[]));
u24_2 = u24_3;
assert(equalS(u24_2[], iota(0, 3)));
// to test that passed arg is intact outside
// plus try out opEquals
u24 = u24_3;
u24 = T.init;
u24_3 = T.init;
assert(u24.empty);
assert(u24 == u24_3);
assert(u24 != u24_2);
}
foreach(Policy; TypeTuple!(GcPolicy, ReallocPolicy))
{
alias typeof(Uint24Array!Policy.init[]) Range;
alias Uint24Array!Policy U24A;
static assert(isForwardRange!Range);
static assert(isBidirectionalRange!Range);
static assert(isOutputRange!(Range, uint));
static assert(isRandomAccessRange!(Range));
auto arr = U24A([42u, 36, 100]);
assert(arr[0] == 42);
assert(arr[1] == 36);
arr[0] = 72;
arr[1] = 0xFE_FEFE;
assert(arr[0] == 72);
assert(arr[1] == 0xFE_FEFE);
assert(arr[2] == 100);
U24A arr2 = arr;
assert(arr2[0] == 72);
arr2[0] = 11;
// test COW-ness
assert(arr[0] == 72);
assert(arr2[0] == 11);
// set this to about 100M to stress-test COW memory management
foreach(v; 0..10_000)
func2(arr);
assert(equalS(arr[], [72, 0xFE_FEFE, 100]));
auto r2 = U24A(iota(0, 100));
assert(equalS(r2[], iota(0, 100)), text(r2[]));
copy(iota(10, 170, 2), r2[10..90]);
assert(equalS(r2[], chain(iota(0, 10), iota(10, 170, 2), iota(90, 100)))
, text(r2[]));
}
}
version(unittest)
{
private alias TypeTuple!(InversionList!GcPolicy, InversionList!ReallocPolicy) AllSets;
}
@trusted unittest// core set primitives test
{
foreach(CodeList; AllSets)
{
CodeList a;
//"plug a hole" test
a.add(10, 20).add(25, 30).add(15, 27);
assert(a == CodeList(10, 30), text(a));
auto x = CodeList.init;
x.add(10, 20).add(30, 40).add(50, 60);
a = x;
a.add(20, 49);//[10, 49) [50, 60)
assert(a == CodeList(10, 49, 50 ,60));
a = x;
a.add(20, 50);
assert(a == CodeList(10, 60), text(a));
// simple unions, mostly edge effects
x = CodeList.init;
x.add(10, 20).add(40, 60);
a = x;
a.add(10, 25); //[10, 25) [40, 60)
assert(a == CodeList(10, 25, 40, 60));
a = x;
a.add(5, 15); //[5, 20) [40, 60)
assert(a == CodeList(5, 20, 40, 60));
a = x;
a.add(0, 10); // [0, 20) [40, 60)
assert(a == CodeList(0, 20, 40, 60));
a = x;
a.add(0, 5); // prepand
assert(a == CodeList(0, 5, 10, 20, 40, 60), text(a));
a = x;
a.add(5, 20);
assert(a == CodeList(5, 20, 40, 60));
a = x;
a.add(3, 37);
assert(a == CodeList(3, 37, 40, 60));
a = x;
a.add(37, 65);
assert(a == CodeList(10, 20, 37, 65));
// some tests on helpers for set intersection
x = CodeList.init.add(10, 20).add(40, 60).add(100, 120);
a = x;
auto m = a.skipUpTo(60);
a.dropUpTo(110, m);
assert(a == CodeList(10, 20, 40, 60, 110, 120), text(a.data[]));
a = x;
a.dropUpTo(100);
assert(a == CodeList(100, 120), text(a.data[]));
a = x;
m = a.skipUpTo(50);
a.dropUpTo(140, m);
assert(a == CodeList(10, 20, 40, 50), text(a.data[]));
a = x;
a.dropUpTo(60);
assert(a == CodeList(100, 120), text(a.data[]));
}
}
@trusted unittest
{ // full set operations
foreach(CodeList; AllSets)
{
CodeList a, b, c, d;
//"plug a hole"
a.add(20, 40).add(60, 80).add(100, 140).add(150, 200);
b.add(40, 60).add(80, 100).add(140, 150);
c = a | b;
d = b | a;
assert(c == CodeList(20, 200), text(CodeList.stringof," ", c));
assert(c == d, text(c," vs ", d));
b = CodeList.init.add(25, 45).add(65, 85).add(95,110).add(150, 210);
c = a | b; //[20,45) [60, 85) [95, 140) [150, 210)
d = b | a;
assert(c == CodeList(20, 45, 60, 85, 95, 140, 150, 210), text(c));
assert(c == d, text(c," vs ", d));
b = CodeList.init.add(10, 20).add(30,100).add(145,200);
c = a | b;//[10, 140) [145, 200)
d = b | a;
assert(c == CodeList(10, 140, 145, 200));
assert(c == d, text(c," vs ", d));
b = CodeList.init.add(0, 10).add(15, 100).add(10, 20).add(200, 220);
c = a | b;//[0, 140) [150, 220)
d = b | a;
assert(c == CodeList(0, 140, 150, 220));
assert(c == d, text(c," vs ", d));
a = CodeList.init.add(20, 40).add(60, 80);
b = CodeList.init.add(25, 35).add(65, 75);
c = a & b;
d = b & a;
assert(c == CodeList(25, 35, 65, 75), text(c));
assert(c == d, text(c," vs ", d));
a = CodeList.init.add(20, 40).add(60, 80).add(100, 140).add(150, 200);
b = CodeList.init.add(25, 35).add(65, 75).add(110, 130).add(160, 180);
c = a & b;
d = b & a;
assert(c == CodeList(25, 35, 65, 75, 110, 130, 160, 180), text(c));
assert(c == d, text(c," vs ", d));
a = CodeList.init.add(20, 40).add(60, 80).add(100, 140).add(150, 200);
b = CodeList.init.add(10, 30).add(60, 120).add(135, 160);
c = a & b;//[20, 30)[60, 80) [100, 120) [135, 140) [150, 160)
d = b & a;
assert(c == CodeList(20, 30, 60, 80, 100, 120, 135, 140, 150, 160),text(c));
assert(c == d, text(c, " vs ",d));
assert((c & a) == c);
assert((d & b) == d);
assert((c & d) == d);
b = CodeList.init.add(40, 60).add(80, 100).add(140, 200);
c = a & b;
d = b & a;
assert(c == CodeList(150, 200), text(c));
assert(c == d, text(c, " vs ",d));
assert((c & a) == c);
assert((d & b) == d);
assert((c & d) == d);
assert((a & a) == a);
assert((b & b) == b);
a = CodeList.init.add(20, 40).add(60, 80).add(100, 140).add(150, 200);
b = CodeList.init.add(30, 60).add(75, 120).add(190, 300);
c = a - b;// [30, 40) [60, 75) [120, 140) [150, 190)
d = b - a;// [40, 60) [80, 100) [200, 300)
assert(c == CodeList(20, 30, 60, 75, 120, 140, 150, 190), text(c));
assert(d == CodeList(40, 60, 80, 100, 200, 300), text(d));
assert(c - d == c, text(c-d, " vs ", c));
assert(d - c == d, text(d-c, " vs ", d));
assert(c - c == CodeList.init);
assert(d - d == CodeList.init);
a = CodeList.init.add(20, 40).add( 60, 80).add(100, 140).add(150, 200);
b = CodeList.init.add(10, 50).add(60, 160).add(190, 300);
c = a - b;// [160, 190)
d = b - a;// [10, 20) [40, 50) [80, 100) [140, 150) [200, 300)
assert(c == CodeList(160, 190), text(c));
assert(d == CodeList(10, 20, 40, 50, 80, 100, 140, 150, 200, 300), text(d));
assert(c - d == c, text(c-d, " vs ", c));
assert(d - c == d, text(d-c, " vs ", d));
assert(c - c == CodeList.init);
assert(d - d == CodeList.init);
a = CodeList.init.add(20, 40).add(60, 80).add(100, 140).add(150, 200);
b = CodeList.init.add(10, 30).add(45, 100).add(130, 190);
c = a ~ b; // [10, 20) [30, 40) [45, 60) [80, 130) [140, 150) [190, 200)
d = b ~ a;
assert(c == CodeList(10, 20, 30, 40, 45, 60, 80, 130, 140, 150, 190, 200),
text(c));
assert(c == d, text(c, " vs ", d));
}
}
@system:
unittest// vs single dchar
{
CodepointSet a = CodepointSet(10, 100, 120, 200);
assert(a - 'A' == CodepointSet(10, 65, 66, 100, 120, 200), text(a - 'A'));
assert((a & 'B') == CodepointSet(66, 67));
}
unittest// iteration & opIndex
{
import std.typecons;
foreach(CodeList; TypeTuple!(InversionList!(ReallocPolicy)))
{
auto arr = "ABCDEFGHIJKLMabcdefghijklm"d;
auto a = CodeList('A','N','a', 'n');
assert(equalS(a.byInterval,
[tuple(cast(uint)'A', cast(uint)'N'), tuple(cast(uint)'a', cast(uint)'n')]
), text(a.byInterval));
// same @@@BUG as in issue 8949 ?
version(bug8949)
{
assert(equalS(retro(a.byInterval),
[tuple(cast(uint)'a', cast(uint)'n'), tuple(cast(uint)'A', cast(uint)'N')]
), text(retro(a.byInterval)));
}
auto achr = a.byCodepoint;
assert(equalS(achr, arr), text(a.byCodepoint));
foreach(ch; a.byCodepoint)
assert(a[ch]);
auto x = CodeList(100, 500, 600, 900, 1200, 1500);
assert(equalS(x.byInterval, [ tuple(100, 500), tuple(600, 900), tuple(1200, 1500)]), text(x.byInterval));
foreach(ch; x.byCodepoint)
assert(x[ch]);
static if(is(CodeList == CodepointSet))
{
auto y = CodeList(x.byInterval);
assert(equalS(x.byInterval, y.byInterval));
}
assert(equalS(CodepointSet.init.byInterval, cast(Tuple!(uint, uint)[])[]));
assert(equalS(CodepointSet.init.byCodepoint, cast(dchar[])[]));
}
}
//============================================================================
// Generic Trie template and various ways to build it
//============================================================================
// debug helper to get a shortened array dump
auto arrayRepr(T)(T x)
{
if(x.length > 32)
{
return text(x[0..16],"~...~", x[x.length-16..x.length]);
}
else
return text(x);
}
/**
Maps $(D Key) to a suitable integer index within the range of $(D size_t).
The mapping is constructed by applying predicates from $(D Prefix) left to right
and concatenating the resulting bits.
The first (leftmost) predicate defines the most significant bits of
the resulting index.
*/
template mapTrieIndex(Prefix...)
{
size_t mapTrieIndex(Key)(Key key)
if(isValidPrefixForTrie!(Key, Prefix))
{
alias Prefix p;
size_t idx;
foreach(i, v; p[0..$-1])
{
idx |= p[i](key);
idx <<= p[i+1].bitSize;
}
idx |= p[$-1](key);
return idx;
}
}
/*
$(D TrieBuilder) is a type used for incremental construction
of $(LREF Trie)s.
See $(LREF buildTrie) for generic helpers built on top of it.
*/
@trusted struct TrieBuilder(Value, Key, Args...)
if(isBitPackableType!Value && isValidArgsForTrie!(Key, Args))
{
private:
// last index is not stored in table, it is used as an offset to values in a block.
static if(is(Value == bool))// always pack bool
alias V = BitPacked!(Value, 1);
else
alias V = Value;
static auto deduceMaxIndex(Preds...)()
{
size_t idx = 1;
foreach(v; Preds)
idx *= 2^^v.bitSize;
return idx;
}
static if(is(typeof(Args[0]) : Key)) // Args start with upper bound on Key
{
alias Prefix = Args[1..$];
enum lastPageSize = 2^^Prefix[$-1].bitSize;
enum translatedMaxIndex = mapTrieIndex!(Prefix)(Args[0]);
enum roughedMaxIndex =
(translatedMaxIndex + lastPageSize-1)/lastPageSize*lastPageSize;
// check warp around - if wrapped, use the default deduction rule
enum maxIndex = roughedMaxIndex < translatedMaxIndex ?
deduceMaxIndex!(Prefix)() : roughedMaxIndex;
}
else
{
alias Prefix = Args;
enum maxIndex = deduceMaxIndex!(Prefix)();
}
alias getIndex = mapTrieIndex!(Prefix);
enum lastLevel = Prefix.length-1;
struct ConstructState
{
size_t idx_zeros, idx_ones;
}
// iteration over levels of Trie, each indexes its own level and thus a shortened domain
size_t[Prefix.length] indices;
// default filler value to use
Value defValue;
// this is a full-width index of next item
size_t curIndex;
// all-zeros page index, all-ones page index (+ indicator if there is such a page)
ConstructState[Prefix.length] state;
// the table being constructed
MultiArray!(idxTypes!(Key, fullBitSize!(Prefix), Prefix[0..$]), V) table;
@disable this();
//shortcut for index variable at level 'level'
@property ref idx(size_t level)(){ return indices[level]; }
// this function assumes no holes in the input so
// indices are going one by one
void addValue(size_t level, T)(T val, size_t numVals)
{
alias j = idx!level;
enum pageSize = 1<<Prefix[level].bitSize;
if(numVals == 0)
return;
auto ptr = table.slice!(level);
if(numVals == 1)
{
static if(level == Prefix.length-1)
ptr[j] = val;
else
{// can incur narrowing conversion
assert(j < ptr.length);
ptr[j] = force!(typeof(ptr[j]))(val);
}
j++;
if(j % pageSize == 0)
spillToNextPage!level(ptr);
return;
}
// longer row of values
// get to the next page boundary
size_t nextPB = (j + pageSize) & ~(pageSize-1);
size_t n = nextPB - j;// can fill right in this page
if(numVals < n) //fits in current page
{
ptr[j..j+numVals] = val;
j += numVals;
return;
}
static if(level != 0)//on the first level it always fits
{
numVals -= n;
//write till the end of current page
ptr[j..j+n] = val;
j += n;
//spill to the next page
spillToNextPage!level(ptr);
// page at once loop
if(state[level].idx_zeros != size_t.max && val == T.init)
{
alias typeof(table.slice!(level-1)[0]) NextIdx;
addValue!(level-1)(force!NextIdx(state[level].idx_zeros),
numVals/pageSize);
ptr = table.slice!level; //table structure might have changed
numVals %= pageSize;
}
else
{
while(numVals >= pageSize)
{
numVals -= pageSize;
ptr[j..j+pageSize] = val;
j += pageSize;
spillToNextPage!level(ptr);
}
}
if(numVals)
{
// the leftovers, an incomplete page
ptr[j..j+numVals] = val;
j += numVals;
}
}
}
void spillToNextPage(size_t level, Slice)(ref Slice ptr)
{
// last level (i.e. topmost) has 1 "page"
// thus it need not to add a new page on upper level
static if(level != 0)
spillToNextPageImpl!(level)(ptr);
}
// this can re-use the current page if duplicate or allocate a new one
// it also makes sure that previous levels point to the correct page in this level
void spillToNextPageImpl(size_t level, Slice)(ref Slice ptr)
{
alias typeof(table.slice!(level-1)[0]) NextIdx;
NextIdx next_lvl_index;
enum pageSize = 1<<Prefix[level].bitSize;
assert(idx!level % pageSize == 0);
auto last = idx!level-pageSize;
auto slice = ptr[idx!level - pageSize..idx!level];
size_t j;
for(j=0; j<last; j+=pageSize)
{
if(equalS(ptr[j..j+pageSize], slice[0..pageSize]))
{
// get index to it, reuse ptr space for the next block
next_lvl_index = force!NextIdx(j/pageSize);
version(none)
{
writefln("LEVEL(%s) page maped idx: %s: 0..%s ---> [%s..%s]"
,level
,indices[level-1], pageSize, j, j+pageSize);
writeln("LEVEL(", level
, ") mapped page is: ", slice, ": ", arrayRepr(ptr[j..j+pageSize]));
writeln("LEVEL(", level
, ") src page is :", ptr, ": ", arrayRepr(slice[0..pageSize]));
}
idx!level -= pageSize; // reuse this page, it is duplicate
break;
}
}
if(j == last)
{
L_allocate_page:
next_lvl_index = force!NextIdx(idx!level/pageSize - 1);
if(state[level].idx_zeros == size_t.max && ptr.zeros(j, j+pageSize))
{
state[level].idx_zeros = next_lvl_index;
}
// allocate next page
version(none)
{
writefln("LEVEL(%s) page allocated: %s"
, level, arrayRepr(slice[0..pageSize]));
writefln("LEVEL(%s) index: %s ; page at this index %s"
, level
, next_lvl_index
, arrayRepr(
table.slice!(level)
[pageSize*next_lvl_index..(next_lvl_index+1)*pageSize]
));
}
table.length!level = table.length!level + pageSize;
}
L_know_index:
// for the previous level, values are indices to the pages in the current level
addValue!(level-1)(next_lvl_index, 1);
ptr = table.slice!level; //re-load the slice after moves
}
// idx - full-width index to fill with v (full-width index != key)
// fills everything in the range of [curIndex, idx) with filler
void putAt(size_t idx, Value v)
{
assert(idx >= curIndex);
size_t numFillers = idx - curIndex;
addValue!lastLevel(defValue, numFillers);
addValue!lastLevel(v, 1);
curIndex = idx + 1;
}
// ditto, but sets the range of [idxA, idxB) to v
void putRangeAt(size_t idxA, size_t idxB, Value v)
{
assert(idxA >= curIndex);
assert(idxB >= idxA);
size_t numFillers = idxA - curIndex;
addValue!lastLevel(defValue, numFillers);
addValue!lastLevel(v, idxB - idxA);
curIndex = idxB; // open-right
}
enum errMsg = "non-monotonic prefix function(s), an unsorted range or "
"duplicate key->value mapping";
public:
/**
Construct a builder, where $(D filler) is a value
to indicate empty slots (or "not found" condition).
*/
this(Value filler)
{
curIndex = 0;
defValue = filler;
// zeros-page index, ones-page index
foreach(ref v; state)
v = ConstructState(size_t.max, size_t.max);
table = typeof(table)(indices);
// one page per level is a bootstrap minimum
foreach(i; Sequence!(0, Prefix.length))
table.length!i = (1<<Prefix[i].bitSize);
}
/**
Put a value $(D v) into interval as
mapped by keys from $(D a) to $(D b).
All slots prior to $(D a) are filled with
the default filler.
*/
void putRange(Key a, Key b, Value v)
{
auto idxA = getIndex(a), idxB = getIndex(b);
// indexes of key should always grow
enforce(idxB >= idxA && idxA >= curIndex, errMsg);
putRangeAt(idxA, idxB, v);
}
/**
Put a value $(D v) into slot mapped by $(D key).
All slots prior to $(D key) are filled with the
default filler.
*/
void putValue(Key key, Value v)
{
auto idx = getIndex(key);
enforce(idx >= curIndex, text(errMsg, " ", idx));
putAt(idx, v);
}
/// Finishes construction of Trie, yielding an immutable Trie instance.
auto build()
{
static if(maxIndex != 0) // doesn't cover full range of size_t
{
assert(curIndex <= maxIndex);
addValue!lastLevel(defValue, maxIndex - curIndex);
}
else
{
if(curIndex != 0 // couldn't wrap around
|| (Prefix.length != 1 && indices[lastLevel] == 0)) // can be just empty
{
addValue!lastLevel(defValue, size_t.max - curIndex);
addValue!lastLevel(defValue, 1);
}
// else curIndex already completed the full range of size_t by wrapping around
}
return Trie!(V, Key, maxIndex, Prefix)(table);
}
}
/*
$(P A generic Trie data-structure for a fixed number of stages.
The design goal is optimal speed with smallest footprint size.
)
$(P It's intentionally read-only and doesn't provide constructors.
To construct one use a special builder,
see $(LREF TrieBuilder) and $(LREF buildTrie).
)
*/
@trusted public struct Trie(Value, Key, Args...)
if(isValidPrefixForTrie!(Key, Args)
|| (isValidPrefixForTrie!(Key, Args[1..$])
&& is(typeof(Args[0]) : size_t)))
{
static if(is(typeof(Args[0]) : size_t))
{
enum maxIndex = Args[0];
enum hasBoundsCheck = true;
alias Prefix = Args[1..$];
}
else
{
enum hasBoundsCheck = false;
alias Prefix = Args;
}
private this()(typeof(_table) table)
{
_table = table;
}
// only for constant Tries constructed from precompiled tables
private this()(const(size_t)[] offsets, const(size_t)[] sizes,
const(size_t)[] data) const
{
_table = typeof(_table)(offsets, sizes, data);
}
/*
$(P Lookup the $(D key) in this $(D Trie). )
$(P The lookup always succeeds if key fits the domain
provided during construction. The whole domain defined
is covered so instead of not found condition
the sentinel (filler) value could be used. )
$(P See $(LREF buildTrie), $(LREF TrieBuilder) for how to
define a domain of $(D Trie) keys and the sentinel value. )
Note:
Domain range-checking is only enabled in debug builds
and results in assertion failure.
*/
// templated to auto-detect pure, @safe and nothrow
TypeOfBitPacked!Value opIndex()(Key key) const
{
static if(hasBoundsCheck)
assert(mapTrieIndex!Prefix(key) < maxIndex);
size_t idx;
alias p = Prefix;
idx = cast(size_t)p[0](key);
foreach(i, v; p[0..$-1])
idx = cast(size_t)((_table.ptr!i[idx]<<p[i+1].bitSize) + p[i+1](key));
return _table.ptr!(p.length-1)[idx];
}
@property size_t bytes(size_t n=size_t.max)() const
{
return _table.bytes!n;
}
@property size_t pages(size_t n)() const
{
return (bytes!n+2^^(Prefix[n].bitSize-1))
/2^^Prefix[n].bitSize;
}
void store(OutRange)(scope OutRange sink) const
if(isOutputRange!(OutRange, char))
{
_table.store(sink);
}
private:
MultiArray!(idxTypes!(Key, fullBitSize!(Prefix), Prefix[0..$]), Value) _table;
}
// create a tuple of 'sliceBits' that slice the 'top' of bits into pieces of sizes 'sizes'
// left-to-right, the most significant bits first
template GetBitSlicing(size_t top, sizes...)
{
static if(sizes.length > 0)
alias TypeTuple!(sliceBits!(top - sizes[0], top)
, GetBitSlicing!(top - sizes[0], sizes[1..$])) GetBitSlicing;
else
alias TypeTuple!() GetBitSlicing;
}
template callableWith(T)
{
template callableWith(alias Pred)
{
static if(!is(typeof(Pred(T.init))))
enum callableWith = false;
else
{
alias Result = typeof(Pred(T.init));
enum callableWith = isBitPackableType!(TypeOfBitPacked!(Result));
}
}
}
/*
Check if $(D Prefix) is a valid set of predicates
for $(D Trie) template having $(D Key) as the type of keys.
This requires all predicates to be callable, take
single argument of type $(D Key) and return unsigned value.
*/
template isValidPrefixForTrie(Key, Prefix...)
{
enum isValidPrefixForTrie = allSatisfy!(callableWith!Key, Prefix); // TODO: tighten the screws
}
/*
Check if $(D Args) is a set of maximum key value followed by valid predicates
for $(D Trie) template having $(D Key) as the type of keys.
*/
template isValidArgsForTrie(Key, Args...)
{
static if(Args.length > 1)
{
enum isValidArgsForTrie = isValidPrefixForTrie!(Key, Args)
|| (isValidPrefixForTrie!(Key, Args[1..$]) && is(typeof(Args[0]) : Key));
}
else
enum isValidArgsForTrie = isValidPrefixForTrie!Args;
}
@property size_t sumOfIntegerTuple(ints...)()
{
size_t count=0;
foreach(v; ints)
count += v;
return count;
}
/**
A shorthand for creating a custom multi-level fixed Trie
from a $(D CodepointSet). $(D sizes) are numbers of bits per level,
with the most significant bits used first.
Note: The sum of $(D sizes) must be equal 21.
See_Also: $(LREF toTrie), which is even simpler.
Example:
---
{
import std.stdio;
auto set = unicode("Number");
auto trie = codepointSetTrie!(8, 5, 8)(set);
writeln("Input code points to test:");
foreach(line; stdin.byLine)
{
int count=0;
foreach(dchar ch; line)
if(trie[ch])// is number
count++;
writefln("Contains %d number code points.", count);
}
}
---
*/
public template codepointSetTrie(sizes...)
if(sumOfIntegerTuple!sizes == 21)
{
auto codepointSetTrie(Set)(Set set)
if(isCodepointSet!Set)
{
auto builder = TrieBuilder!(bool, dchar, lastDchar+1, GetBitSlicing!(21, sizes))(false);
foreach(ival; set.byInterval)
builder.putRange(ival[0], ival[1], true);
return builder.build();
}
}
/// Type of Trie generated by codepointSetTrie function.
public template CodepointSetTrie(sizes...)
if(sumOfIntegerTuple!sizes == 21)
{
alias Prefix = GetBitSlicing!(21, sizes);
alias CodepointSetTrie = typeof(TrieBuilder!(bool, dchar, lastDchar+1, Prefix)(false).build());
}
/**
A slightly more general tool for building fixed $(D Trie)
for the Unicode data.
Specifically unlike $(D codepointSetTrie) it's allows creating mappings
of $(D dchar) to an arbitrary type $(D T).
Note: Overload taking $(D CodepointSet)s will naturally convert
only to bool mapping $(D Trie)s.
Example:
---
// pick characters from the Greek script
auto set = unicode.Greek;
// a user-defined property (or an expensive function)
// that we want to look up
static uint luckFactor(dchar ch)
{
// here we consider a character lucky
// if its code point has a lot of identical hex-digits
// e.g. arabic letter DDAL (\u0688) has a "luck factor" of 2
ubyte[6] nibbles; // 6 4-bit chunks of code point
uint value = ch;
foreach(i; 0..6)
{
nibbles[i] = value & 0xF;
value >>= 4;
}
uint luck;
foreach(n; nibbles)
luck = cast(uint)max(luck, count(nibbles[], n));
return luck;
}
// only unsigned built-ins are supported at the moment
alias LuckFactor = BitPacked!(uint, 3);
// create a temporary associative array (AA)
LuckFactor[dchar] map;
foreach(ch; set.byCodepoint)
map[ch] = luckFactor(ch);
// bits per stage are chosen randomly, fell free to optimize
auto trie = codepointTrie!(LuckFactor, 8, 5, 8)(map);
// from now on the AA is not needed
foreach(ch; set.byCodepoint)
assert(trie[ch] == luckFactor(ch)); // verify
// CJK is not Greek, thus it has the default value
assert(trie['\u4444'] == 0);
// and here is a couple of quite lucky Greek characters:
// Greek small letter epsilon with dasia
assert(trie['\u1F11'] == 3);
// Ancient Greek metretes sign
assert(trie['\U00010181'] == 3);
---
*/
public template codepointTrie(T, sizes...)
if(sumOfIntegerTuple!sizes == 21)
{
alias Prefix = GetBitSlicing!(21, sizes);
static if(is(TypeOfBitPacked!T == bool))
{
auto codepointTrie(Set)(in Set set)
if(isCodepointSet!Set)
{
return codepointSetTrie(set);
}
}
auto codepointTrie()(T[dchar] map, T defValue=T.init)
{
return buildTrie!(T, dchar, Prefix)(map, defValue);
}
// unsorted range of pairs
auto codepointTrie(R)(R range, T defValue=T.init)
if(isInputRange!R
&& is(typeof(ElementType!R.init[0]) : T)
&& is(typeof(ElementType!R.init[1]) : dchar))
{
// build from unsorted array of pairs
// TODO: expose index sorting functions for Trie
return buildTrie!(T, dchar, Prefix)(range, defValue, true);
}
}
unittest // codepointTrie example
{
// pick characters from the Greek script
auto set = unicode.Greek;
// a user-defined property (or an expensive function)
// that we want to look up
static uint luckFactor(dchar ch)
{
// here we consider a character lucky
// if its code point has a lot of identical hex-digits
// e.g. arabic letter DDAL (\u0688) has a "luck factor" of 2
ubyte[6] nibbles; // 6 4-bit chunks of code point
uint value = ch;
foreach(i; 0..6)
{
nibbles[i] = value & 0xF;
value >>= 4;
}
uint luck;
foreach(n; nibbles)
luck = cast(uint)max(luck, count(nibbles[], n));
return luck;
}
// only unsigned built-ins are supported at the moment
alias LuckFactor = BitPacked!(uint, 3);
// create a temporary associative array (AA)
LuckFactor[dchar] map;
foreach(ch; set.byCodepoint)
map[ch] = LuckFactor(luckFactor(ch));
// bits per stage are chosen randomly, fell free to optimize
auto trie = codepointTrie!(LuckFactor, 8, 5, 8)(map);
// from now on the AA is not needed
foreach(ch; set.byCodepoint)
assert(trie[ch] == luckFactor(ch)); // verify
// CJK is not Greek, thus it has the default value
assert(trie['\u4444'] == 0);
// and here is a couple of quite lucky Greek characters:
// Greek small letter epsilon with dasia
assert(trie['\u1F11'] == 3);
// Ancient Greek metretes sign
assert(trie['\U00010181'] == 3);
}
/// Type of Trie as generated by codepointTrie function.
public template CodepointTrie(T, sizes...)
if(sumOfIntegerTuple!sizes == 21)
{
alias Prefix = GetBitSlicing!(21, sizes);
alias CodepointTrie = typeof(TrieBuilder!(T, dchar, lastDchar+1, Prefix)(T.init).build());
}
// @@@BUG multiSort can's access private symbols from uni
public template cmpK0(alias Pred)
{
import std.typecons;
static bool cmpK0(Value, Key)
(Tuple!(Value, Key) a, Tuple!(Value, Key) b)
{
return Pred(a[1]) < Pred(b[1]);
}
}
/*
The most general utility for construction of $(D Trie)s
short of using $(D TrieBuilder) directly.
Provides a number of convenience overloads.
$(D Args) is tuple of maximum key value followed by
predicates to construct index from key.
Alternatively if the first argument is not a value convertible to $(D Key)
then the whole tuple of $(D Args) is treated as predicates
and the maximum Key is deduced from predicates.
*/
public template buildTrie(Value, Key, Args...)
if(isValidArgsForTrie!(Key, Args))
{
static if(is(typeof(Args[0]) : Key)) // prefix starts with upper bound on Key
{
alias Prefix = Args[1..$];
}
else
alias Prefix = Args;
alias getIndex = mapTrieIndex!(Prefix);
// for multi-sort
template GetComparators(size_t n)
{
static if(n > 0)
alias GetComparators =
TypeTuple!(GetComparators!(n-1), cmpK0!(Prefix[n-1]));
else
alias GetComparators = TypeTuple!();
}
/*
Build $(D Trie) from a range of a Key-Value pairs,
assuming it is sorted by Key as defined by the following lambda:
------
(a, b) => mapTrieIndex!(Prefix)(a) < mapTrieIndex!(Prefix)(b)
------
Exception is thrown if it's detected that the above order doesn't hold.
In other words $(LREF mapTrieIndex) should be a
monotonically increasing function that maps $(D Key) to an integer.
See also: $(XREF _algorithm, sort),
$(XREF _range, SortedRange),
$(XREF _algorithm, setUnion).
*/
auto buildTrie(Range)(Range range, Value filler=Value.init)
if(isInputRange!Range && is(typeof(Range.init.front[0]) : Value)
&& is(typeof(Range.init.front[1]) : Key))
{
auto builder = TrieBuilder!(Value, Key, Prefix)(filler);
foreach(v; range)
builder.putValue(v[1], v[0]);
return builder.build();
}
/*
If $(D Value) is bool (or BitPacked!(bool, x)) then it's possible
to build $(D Trie) from a range of open-right intervals of $(D Key)s.
The requirement on the ordering of keys (and the behavior on the
violation of it) is the same as for Key-Value range overload.
Intervals denote ranges of !$(D filler) i.e. the opposite of filler.
If no filler provided keys inside of the intervals map to true,
and $(D filler) is false.
*/
auto buildTrie(Range)(Range range, Value filler=Value.init)
if(is(TypeOfBitPacked!Value == bool)
&& isInputRange!Range && is(typeof(Range.init.front[0]) : Key)
&& is(typeof(Range.init.front[1]) : Key))
{
auto builder = TrieBuilder!(Value, Key, Prefix)(filler);
foreach(ival; range)
builder.putRange(ival[0], ival[1], !filler);
return builder.build();
}
auto buildTrie(Range)(Range range, Value filler, bool unsorted)
if(isInputRange!Range
&& is(typeof(Range.init.front[0]) : Value)
&& is(typeof(Range.init.front[1]) : Key))
{
alias Comps = GetComparators!(Prefix.length);
if(unsorted)
multiSort!(Comps)(range);
return buildTrie(range, filler);
}
/*
If $(D Value) is bool (or BitPacked!(bool, x)) then it's possible
to build $(D Trie) simply from an input range of $(D Key)s.
The requirement on the ordering of keys (and the behavior on the
violation of it) is the same as for Key-Value range overload.
Keys found in range denote !$(D filler) i.e. the opposite of filler.
If no filler provided keys map to true, and $(D filler) is false.
*/
auto buildTrie(Range)(Range range, Value filler=Value.init)
if(is(TypeOfBitPacked!Value == bool)
&& isInputRange!Range && is(typeof(Range.init.front) : Key))
{
auto builder = TrieBuilder!(Value, Key, Prefix)(filler);
foreach(v; range)
builder.putValue(v, !filler);
return builder.build();
}
/*
If $(D Key) is unsigned integer $(D Trie) could be constructed from array
of values where array index serves as key.
*/
auto buildTrie()(Value[] array, Value filler=Value.init)
if(isUnsigned!Key)
{
auto builder = TrieBuilder!(Value, Key, Prefix)(filler);
foreach(idx, v; array)
builder.putValue(idx, v);
return builder.build();
}
/*
Builds $(D Trie) from associative array.
*/
auto buildTrie(Key, Value)(Value[Key] map, Value filler=Value.init)
{
auto range = array(zip(map.values, map.keys));
return buildTrie(range, filler, true); // sort it
}
}
/++
Convenience function to construct optimal configurations for
packed Trie from any $(D set) of $(CODEPOINTS).
The parameter $(D level) indicates the number of trie levels to use,
allowed values are: 1, 2, 3 or 4. Levels represent different trade-offs
speed-size wise.
$(P Level 1 is fastest and the most memory hungry (a bit array). )
$(P Level 4 is the slowest and has the smallest footprint. )
See the $(S_LINK Synopsis, Synopsis) section for example.
Note:
Level 4 stays very practical (being faster and more predictable)
compared to using direct lookup on the $(D set) itself.
+/
public auto toTrie(size_t level, Set)(Set set)
if(isCodepointSet!Set)
{
static if(level == 1)
return codepointSetTrie!(21)(set);
else static if(level == 2)
return codepointSetTrie!(10, 11)(set);
else static if(level == 3)
return codepointSetTrie!(8, 5, 8)(set);
else static if(level == 4)
return codepointSetTrie!(6, 4, 4, 7)(set);
else
static assert(false,
"Sorry, toTrie doesn't support levels > 4, use codepointSetTrie directly");
}
/**
$(P Builds a $(D Trie) with typically optimal speed-size trade-off
and wraps it into a delegate of the following type:
$(D bool delegate(dchar ch)). )
$(P Effectively this creates a 'tester' lambda suitable
for algorithms like std.algorithm.find that take unary predicates. )
See the $(S_LINK Synopsis, Synopsis) section for example.
*/
public auto toDelegate(Set)(Set set)
if(isCodepointSet!Set)
{
// 3 is very small and is almost as fast as 2-level (due to CPU caches?)
auto t = toTrie!3(set);
return (dchar ch) => t[ch];
}
/**
$(P Opaque wrapper around unsigned built-in integers and
code unit (char/wchar/dchar) types.
Parameter $(D sz) indicates that the value is confined
to the range of [0, 2^^sz$(RPAREN). With this knowledge it can be
packed more tightly when stored in certain
data-structures like trie. )
Note:
$(P The $(D BitPacked!(T, sz)) is implicitly convertible to $(D T)
but not vise-versa. Users have to ensure the value fits in
the range required and use the $(D cast)
operator to perform the conversion.)
*/
struct BitPacked(T, size_t sz)
if(isIntegral!T || is(T:dchar))
{
enum bitSize = sz;
T _value;
alias _value this;
}
/*
Depending on the form of the passed argument $(D bitSizeOf) returns
the amount of bits required to represent a given type
or a return type of a given functor.
*/
template bitSizeOf(Args...)
if(Args.length == 1)
{
alias T = Args[0];
static if(__traits(compiles, { size_t val = T.bitSize; })) //(is(typeof(T.bitSize) : size_t))
{
enum bitSizeOf = T.bitSize;
}
else static if(is(ReturnType!T dummy == BitPacked!(U, bits), U, size_t bits))
{
enum bitSizeOf = bitSizeOf!(ReturnType!T);
}
else
{
enum bitSizeOf = T.sizeof*8;
}
}
/**
Tests if $(D T) is some instantiation of $(LREF BitPacked)!(U, x)
and thus suitable for packing.
*/
template isBitPacked(T)
{
static if(is(T dummy == BitPacked!(U, bits), U, size_t bits))
enum isBitPacked = true;
else
enum isBitPacked = false;
}
/**
Gives the type $(D U) from $(LREF BitPacked)!(U, x)
or $(D T) itself for every other type.
*/
template TypeOfBitPacked(T)
{
static if(is(T dummy == BitPacked!(U, bits), U, size_t bits))
alias TypeOfBitPacked = U;
else
alias TypeOfBitPacked = T;
}
/*
Wrapper, used in definition of custom data structures from $(D Trie) template.
Applying it to a unary lambda function indicates that the returned value always
fits within $(D bits) of bits.
*/
struct assumeSize(alias Fn, size_t bits)
{
enum bitSize = bits;
static auto ref opCall(T)(auto ref T arg)
{
return Fn(arg);
}
}
/*
A helper for defining lambda function that yields a slice
of certain bits from an unsigned integral value.
The resulting lambda is wrapped in assumeSize and can be used directly
with $(D Trie) template.
*/
struct sliceBits(size_t from, size_t to)
{
//for now bypass assumeSize, DMD has trouble inlining it
enum bitSize = to-from;
static auto opCall(T)(T x)
out(result)
{
assert(result < (1<<to-from));
}
body
{
static assert(from < to);
return (x >> from) & ((1<<(to-from))-1);
}
}
uint low_8(uint x) { return x&0xFF; }
@safe pure nothrow uint midlow_8(uint x){ return (x&0xFF00)>>8; }
alias assumeSize!(low_8, 8) lo8;
alias assumeSize!(midlow_8, 8) mlo8;
static assert(bitSizeOf!lo8 == 8);
static assert(bitSizeOf!(sliceBits!(4, 7)) == 3);
static assert(bitSizeOf!(BitPacked!(uint, 2)) == 2);
template Sequence(size_t start, size_t end)
{
static if(start < end)
alias TypeTuple!(start, Sequence!(start+1, end)) Sequence;
else
alias TypeTuple!() Sequence;
}
//---- TRIE TESTS ----
unittest
{
static trieStats(TRIE)(TRIE t)
{
version(std_uni_stats)
{
import std.stdio;
writeln("---TRIE FOOTPRINT STATS---");
foreach(i; Sequence!(0, t.table.dim) )
{
writefln("lvl%s = %s bytes; %s pages"
, i, t.bytes!i, t.pages!i);
}
writefln("TOTAL: %s bytes", t.bytes);
version(none)
{
writeln("INDEX (excluding value level):");
foreach(i; Sequence!(0, t.table.dim-1) )
writeln(t.table.slice!(i)[0..t.table.length!i]);
}
writeln("---------------------------");
}
}
//@@@BUG link failure, lambdas not found by linker somehow (in case of trie2)
// alias assumeSize!(8, function (uint x) { return x&0xFF; }) lo8;
// alias assumeSize!(7, function (uint x) { return (x&0x7F00)>>8; }) next8;
alias CodepointSet Set;
auto set = Set('A','Z','a','z');
auto trie = buildTrie!(bool, uint, 256, lo8)(set.byInterval);// simple bool array
for(int a='a'; a<'z';a++)
assert(trie[a]);
for(int a='A'; a<'Z';a++)
assert(trie[a]);
for(int a=0; a<'A'; a++)
assert(!trie[a]);
for(int a ='Z'; a<'a'; a++)
assert(!trie[a]);
trieStats(trie);
auto redundant2 = Set(
1, 18, 256+2, 256+111, 512+1, 512+18, 768+2, 768+111);
auto trie2 = buildTrie!(bool, uint, 1024, mlo8, lo8)(redundant2.byInterval);
trieStats(trie2);
foreach(e; redundant2.byCodepoint)
assert(trie2[e], text(cast(uint)e, " - ", trie2[e]));
foreach(i; 0..1024)
{
assert(trie2[i] == (i in redundant2));
}
auto redundant3 = Set(
2, 4, 6, 8, 16,
2+16, 4+16, 16+6, 16+8, 16+16,
2+32, 4+32, 32+6, 32+8,
);
enum max3 = 256;
// sliceBits
auto trie3 = buildTrie!(bool, uint, max3,
sliceBits!(6,8), sliceBits!(4,6), sliceBits!(0,4)
)(redundant3.byInterval);
trieStats(trie3);
foreach(i; 0..max3)
assert(trie3[i] == (i in redundant3), text(cast(uint)i));
auto redundant4 = Set(
10, 64, 64+10, 128, 128+10, 256, 256+10, 512,
1000, 2000, 3000, 4000, 5000, 6000
);
enum max4 = 2^^16;
auto trie4 = buildTrie!(bool, size_t, max4,
sliceBits!(13, 16), sliceBits!(9, 13), sliceBits!(6, 9) , sliceBits!(0, 6)
)(redundant4.byInterval);
foreach(i; 0..max4){
if(i in redundant4)
assert(trie4[i], text(cast(uint)i));
}
trieStats(trie4);
alias mapToS = mapTrieIndex!(useItemAt!(0, char));
string[] redundantS = ["tea", "start", "orange"];
redundantS.sort!((a,b) => mapToS(a) < mapToS(b))();
auto strie = buildTrie!(bool, string, useItemAt!(0, char))(redundantS);
// using first char only
assert(redundantS == ["orange", "start", "tea"]);
assert(strie["test"], text(strie["test"]));
assert(!strie["aea"]);
assert(strie["s"]);
// a bit size test
auto a = array(map!(x => to!ubyte(x))(iota(0, 256)));
auto bt = buildTrie!(bool, ubyte, sliceBits!(7, 8), sliceBits!(5, 7), sliceBits!(0, 5))(a);
trieStats(bt);
foreach(i; 0..256)
assert(bt[cast(ubyte)i]);
}
template useItemAt(size_t idx, T)
if(isIntegral!T || is(T: dchar))
{
size_t impl(in T[] arr){ return arr[idx]; }
alias useItemAt = assumeSize!(impl, 8*T.sizeof);
}
template useLastItem(T)
{
size_t impl(in T[] arr){ return arr[$-1]; }
alias useLastItem = assumeSize!(impl, 8*T.sizeof);
}
template fullBitSize(Prefix...)
{
static if(Prefix.length > 0)
enum fullBitSize = bitSizeOf!(Prefix[0])+fullBitSize!(Prefix[1..$]);
else
enum fullBitSize = 0;
}
template idxTypes(Key, size_t fullBits, Prefix...)
{
static if(Prefix.length == 1)
{// the last level is value level, so no index once reduced to 1-level
alias TypeTuple!() idxTypes;
}
else
{
// Important note on bit packing
// Each level has to hold enough of bits to address the next one
// The bottom level is known to hold full bit width
// thus it's size in pages is full_bit_width - size_of_last_prefix
// Recourse on this notion
alias TypeTuple!(
idxTypes!(Key, fullBits - bitSizeOf!(Prefix[$-1]), Prefix[0..$-1]),
BitPacked!(typeof(Prefix[$-2](Key.init)), fullBits - bitSizeOf!(Prefix[$-1]))
) idxTypes;
}
}
//============================================================================
@trusted int comparePropertyName(Char1, Char2)(const(Char1)[] a, const(Char2)[] b)
{
alias low = std.ascii.toLower;
return cmp(
a.map!(x => low(x))()
.filter!(x => !isWhite(x) && x != '-' && x != '_')(),
b.map!(x => low(x))()
.filter!(x => !isWhite(x) && x != '-' && x != '_')()
);
}
bool propertyNameLess(Char1, Char2)(const(Char1)[] a, const(Char2)[] b)
{
return comparePropertyName(a, b) < 0;
}
//============================================================================
// Utilities for compression of Unicode code point sets
//============================================================================
@safe void compressTo(uint val, ref ubyte[] arr) pure nothrow
{
// not optimized as usually done 1 time (and not public interface)
if(val < 128)
arr ~= cast(ubyte)val;
else if(val < (1<<13))
{
arr ~= (0b1_00<<5) | cast(ubyte)(val>>8);
arr ~= val & 0xFF;
}
else
{
assert(val < (1<<21));
arr ~= (0b1_01<<5) | cast(ubyte)(val>>16);
arr ~= (val >> 8) & 0xFF;
arr ~= val & 0xFF;
}
}
@safe uint decompressFrom(const(ubyte)[] arr, ref size_t idx) pure
{
uint first = arr[idx++];
if(!(first & 0x80)) // no top bit -> [0..127]
return first;
uint extra = ((first>>5) & 1) + 1; // [1, 2]
uint val = (first & 0x1F);
enforce(idx + extra <= arr.length, "bad code point interval encoding");
foreach(j; 0..extra)
val = (val<<8) | arr[idx+j];
idx += extra;
return val;
}
package ubyte[] compressIntervals(Range)(Range intervals)
if(isInputRange!Range && isIntegralPair!(ElementType!Range))
{
ubyte[] storage;
uint base = 0;
// RLE encode
foreach(val; intervals)
{
compressTo(val[0]-base, storage);
base = val[0];
if(val[1] != lastDchar+1) // till the end of the domain so don't store it
{
compressTo(val[1]-base, storage);
base = val[1];
}
}
return storage;
}
unittest
{
auto run = [tuple(80, 127), tuple(128, (1<<10)+128)];
ubyte[] enc = [cast(ubyte)80, 47, 1, (0b1_00<<5) | (1<<2), 0];
assert(compressIntervals(run) == enc);
auto run2 = [tuple(0, (1<<20)+512+1), tuple((1<<20)+512+4, lastDchar+1)];
ubyte[] enc2 = [cast(ubyte)0, (0b1_01<<5) | (1<<4), 2, 1, 3]; // odd length-ed
assert(compressIntervals(run2) == enc2);
size_t idx = 0;
assert(decompressFrom(enc, idx) == 80);
assert(decompressFrom(enc, idx) == 47);
assert(decompressFrom(enc, idx) == 1);
assert(decompressFrom(enc, idx) == (1<<10));
idx = 0;
assert(decompressFrom(enc2, idx) == 0);
assert(decompressFrom(enc2, idx) == (1<<20)+512+1);
assert(equalS(decompressIntervals(compressIntervals(run)), run));
assert(equalS(decompressIntervals(compressIntervals(run2)), run2));
}
// Creates a range of $(D CodepointInterval) that lazily decodes compressed data.
@safe package auto decompressIntervals(const(ubyte)[] data)
{
return DecompressedIntervals(data);
}
@trusted struct DecompressedIntervals
{
const(ubyte)[] _stream;
size_t _idx;
CodepointInterval _front;
this(const(ubyte)[] stream)
{
_stream = stream;
popFront();
}
@property CodepointInterval front()
{
assert(!empty);
return _front;
}
void popFront()
{
if(_idx == _stream.length)
{
_idx = size_t.max;
return;
}
uint base = _front[1];
_front[0] = base + decompressFrom(_stream, _idx);
if(_idx == _stream.length)// odd length ---> till the end
_front[1] = lastDchar+1;
else
{
base = _front[0];
_front[1] = base + decompressFrom(_stream, _idx);
}
}
@property bool empty() const
{
return _idx == size_t.max;
}
@property DecompressedIntervals save() { return this; }
}
static assert(isInputRange!DecompressedIntervals);
static assert(isForwardRange!DecompressedIntervals);
//============================================================================
version(std_uni_bootstrap){}
else
{
// helper for looking up code point sets
@trusted ptrdiff_t findUnicodeSet(alias table, C)(in C[] name)
{
auto range = assumeSorted!((a,b) => propertyNameLess(a,b))
(table.map!"a.name"());
size_t idx = range.lowerBound(name).length;
if(idx < range.length && comparePropertyName(range[idx], name) == 0)
return idx;
return -1;
}
// another one that loads it
@trusted bool loadUnicodeSet(alias table, Set, C)(in C[] name, ref Set dest)
{
auto idx = findUnicodeSet!table(name);
if(idx >= 0)
{
dest = Set(asSet(table[idx].compressed));
return true;
}
return false;
}
@trusted bool loadProperty(Set=CodepointSet, C)
(in C[] name, ref Set target)
{
alias comparePropertyName ucmp;
// conjure cumulative properties by hand
if(ucmp(name, "L") == 0 || ucmp(name, "Letter") == 0)
{
target |= asSet(uniProps.Lu);
target |= asSet(uniProps.Ll);
target |= asSet(uniProps.Lt);
target |= asSet(uniProps.Lo);
target |= asSet(uniProps.Lm);
}
else if(ucmp(name,"LC") == 0 || ucmp(name,"Cased Letter")==0)
{
target |= asSet(uniProps.Ll);
target |= asSet(uniProps.Lu);
target |= asSet(uniProps.Lt);// Title case
}
else if(ucmp(name, "M") == 0 || ucmp(name, "Mark") == 0)
{
target |= asSet(uniProps.Mn);
target |= asSet(uniProps.Mc);
target |= asSet(uniProps.Me);
}
else if(ucmp(name, "N") == 0 || ucmp(name, "Number") == 0)
{
target |= asSet(uniProps.Nd);
target |= asSet(uniProps.Nl);
target |= asSet(uniProps.No);
}
else if(ucmp(name, "P") == 0 || ucmp(name, "Punctuation") == 0)
{
target |= asSet(uniProps.Pc);
target |= asSet(uniProps.Pd);
target |= asSet(uniProps.Ps);
target |= asSet(uniProps.Pe);
target |= asSet(uniProps.Pi);
target |= asSet(uniProps.Pf);
target |= asSet(uniProps.Po);
}
else if(ucmp(name, "S") == 0 || ucmp(name, "Symbol") == 0)
{
target |= asSet(uniProps.Sm);
target |= asSet(uniProps.Sc);
target |= asSet(uniProps.Sk);
target |= asSet(uniProps.So);
}
else if(ucmp(name, "Z") == 0 || ucmp(name, "Separator") == 0)
{
target |= asSet(uniProps.Zs);
target |= asSet(uniProps.Zl);
target |= asSet(uniProps.Zp);
}
else if(ucmp(name, "C") == 0 || ucmp(name, "Other") == 0)
{
target |= asSet(uniProps.Co);
target |= asSet(uniProps.Lo);
target |= asSet(uniProps.No);
target |= asSet(uniProps.So);
target |= asSet(uniProps.Po);
}
else if(ucmp(name, "graphical") == 0){
target |= asSet(uniProps.Alphabetic);
target |= asSet(uniProps.Mn);
target |= asSet(uniProps.Mc);
target |= asSet(uniProps.Me);
target |= asSet(uniProps.Nd);
target |= asSet(uniProps.Nl);
target |= asSet(uniProps.No);
target |= asSet(uniProps.Pc);
target |= asSet(uniProps.Pd);
target |= asSet(uniProps.Ps);
target |= asSet(uniProps.Pe);
target |= asSet(uniProps.Pi);
target |= asSet(uniProps.Pf);
target |= asSet(uniProps.Po);
target |= asSet(uniProps.Zs);
target |= asSet(uniProps.Sm);
target |= asSet(uniProps.Sc);
target |= asSet(uniProps.Sk);
target |= asSet(uniProps.So);
}
else if(ucmp(name, "any") == 0)
target = Set(0,0x110000);
else if(ucmp(name, "ascii") == 0)
target = Set(0,0x80);
else
return loadUnicodeSet!(uniProps.tab)(name, target);
return true;
}
// CTFE-only helper for checking property names at compile-time
@safe bool isPrettyPropertyName(C)(in C[] name)
{
auto names = [
"L", "Letters",
"LC", "Cased Letter",
"M", "Mark",
"N", "Number",
"P", "Punctuation",
"S", "Symbol",
"Z", "Separator"
"Graphical",
"any",
"ascii"
];
auto x = find!(x => comparePropertyName(x, name) == 0)(names);
return !x.empty;
}
// ditto, CTFE-only, not optimized
@safe private static bool findSetName(alias table, C)(in C[] name)
{
return findUnicodeSet!table(name) >= 0;
}
template SetSearcher(alias table, string kind)
{
/// Run-time checked search.
static auto opCall(C)(in C[] name)
if(is(C : dchar))
{
CodepointSet set;
if(loadUnicodeSet!table(name, set))
return set;
throw new Exception("No unicode set for "~kind~" by name "
~name.to!string()~" was found.");
}
/// Compile-time checked search.
static @property auto opDispatch(string name)()
{
static if(findSetName!table(name))
{
CodepointSet set;
loadUnicodeSet!table(name, set);
return set;
}
else
static assert(false, "No unicode set for "~kind~" by name "
~name~" was found.");
}
}
/**
A single entry point to lookup Unicode $(CODEPOINT) sets by name or alias of
a block, script or general category.
It uses well defined standard rules of property name lookup.
This includes fuzzy matching of names, so that
'White_Space', 'white-SpAce' and 'whitespace' are all considered equal
and yield the same set of white space $(CHARACTERS).
*/
@safe public struct unicode
{
/**
Performs the lookup of set of $(CODEPOINTS)
with compile-time correctness checking.
This short-cut version combines 3 searches:
across blocks, scripts, and common binary properties.
Note that since scripts and blocks overlap the
usual trick to disambiguate is used - to get a block use
$(D unicode.InBlockName), to search a script
use $(D unicode.ScriptName).
See also $(LREF block), $(LREF script)
and (not included in this search) $(LREF hangulSyllableType).
Example:
---
auto ascii = unicode.ASCII;
assert(ascii['A']);
assert(ascii['~']);
assert(!ascii['\u00e0']);
// matching is case-insensitive
assert(ascii == unicode.ascII);
assert(!ascii['à']);
// underscores, '-' and whitespace in names are ignored too
auto latin = unicode.in_latin1_Supplement;
assert(latin['à']);
assert(!latin['$']);
// BTW Latin 1 Supplement is a block, hence "In" prefix
assert(latin == unicode("In Latin 1 Supplement"));
import std.exception;
// run-time look up throws if no such set is found
assert(collectException(unicode("InCyrilliac")));
---
*/
static @property auto opDispatch(string name)()
{
static if(findAny(name))
return loadAny(name);
else
static assert(false, "No unicode set by name "~name~" was found.");
}
/**
The same lookup across blocks, scripts, or binary properties,
but performed at run-time.
This version is provided for cases where $(D name)
is not known beforehand; otherwise compile-time
checked $(LREF opDispatch) is typically a better choice.
See the $(S_LINK Unicode properties, table of properties) for available
sets.
*/
static auto opCall(C)(in C[] name)
if(is(C : dchar))
{
return loadAny(name);
}
/**
Narrows down the search for sets of $(CODEPOINTS) to all Unicode blocks.
See also $(S_LINK Unicode properties, table of properties).
Note:
Here block names are unambiguous as no scripts are searched
and thus to search use simply $(D unicode.block.BlockName) notation.
See $(S_LINK Unicode properties, table of properties) for available sets.
Example:
---
// use .block for explicitness
assert(unicode.block.Greek_and_Coptic == unicode.InGreek_and_Coptic);
---
*/
struct block
{
mixin SetSearcher!(blocks.tab, "block");
}
/**
Narrows down the search for sets of $(CODEPOINTS) to all Unicode scripts.
See the $(S_LINK Unicode properties, table of properties) for available
sets.
Example:
---
auto arabicScript = unicode.script.arabic;
auto arabicBlock = unicode.block.arabic;
// there is an intersection between script and block
assert(arabicBlock['']);
assert(arabicScript['']);
// but they are different
assert(arabicBlock != arabicScript);
assert(arabicBlock == unicode.inArabic);
assert(arabicScript == unicode.arabic);
---
*/
struct script
{
mixin SetSearcher!(scripts.tab, "script");
}
/**
Fetch a set of $(CODEPOINTS) that have the given hangul syllable type.
Other non-binary properties (once supported) follow the same
notation - $(D unicode.propertyName.propertyValue) for compile-time
checked access and $(D unicode.propertyName(propertyValue))
for run-time checked one.
See the $(S_LINK Unicode properties, table of properties) for available
sets.
Example:
---
// L here is syllable type not Letter as in unicode.L short-cut
auto leadingVowel = unicode.hangulSyllableType("L");
// check that some leading vowels are present
foreach(vowel; '\u1110'..'\u115F')
assert(leadingVowel[vowel]);
assert(leadingVowel == unicode.hangulSyllableType.L);
---
*/
struct hangulSyllableType
{
mixin SetSearcher!(hangul.tab, "hangul syllable type");
}
private:
alias ucmp = comparePropertyName;
static bool findAny(string name)
{
return isPrettyPropertyName(name)
|| findSetName!(uniProps.tab)(name) || findSetName!(scripts.tab)(name)
|| (ucmp(name[0..2],"In") == 0 && findSetName!(blocks.tab)(name[2..$]));
}
static auto loadAny(Set=CodepointSet, C)(in C[] name)
{
Set set;
bool loaded = loadProperty(name, set) || loadUnicodeSet!(scripts.tab)(name, set)
|| (ucmp(name[0..2],"In") == 0
&& loadUnicodeSet!(blocks.tab)(name[2..$], set));
if(loaded)
return set;
throw new Exception("No unicode set by name "~name.to!string()~" was found.");
}
// FIXME: re-disable once the compiler is fixed
// Disabled to prevent the mistake of creating instances of this pseudo-struct.
//@disable ~this();
}
unittest
{
auto ascii = unicode.ASCII;
assert(ascii['A']);
assert(ascii['~']);
assert(!ascii['\u00e0']);
// matching is case-insensitive
assert(ascii == unicode.ascII);
assert(!ascii['à']);
// underscores, '-' and whitespace in names are ignored too
auto latin = unicode.Inlatin1_Supplement;
assert(latin['à']);
assert(!latin['$']);
// BTW Latin 1 Supplement is a block, hence "In" prefix
assert(latin == unicode("In Latin 1 Supplement"));
import std.exception;
// R-T look up throws if no such set is found
assert(collectException(unicode("InCyrilliac")));
assert(unicode.block.Greek_and_Coptic == unicode.InGreek_and_Coptic);
// L here is explicitly syllable type not "Letter" as in unicode.L
auto leadingVowel = unicode.hangulSyllableType("L");
// check that some leading vowels are present
foreach(vowel; '\u1110'..'\u115F'+1)
assert(leadingVowel[vowel]);
assert(leadingVowel == unicode.hangulSyllableType.L);
auto arabicScript = unicode.script.arabic;
auto arabicBlock = unicode.block.arabic;
// there is an intersection between script and block
assert(arabicBlock['']);
assert(arabicScript['']);
// but they are different
assert(arabicBlock != arabicScript);
assert(arabicBlock == unicode.inArabic);
assert(arabicScript == unicode.arabic);
}
unittest
{
assert(unicode("InHebrew") == asSet(blocks.Hebrew));
assert(unicode("separator") == (asSet(uniProps.Zs) | asSet(uniProps.Zl) | asSet(uniProps.Zp)));
assert(unicode("In-Kharoshthi") == asSet(blocks.Kharoshthi));
}
enum EMPTY_CASE_TRIE = ushort.max;// from what gen_uni uses internally
// control - '\r'
enum controlSwitch = `
case '\u0000':..case '\u0008':case '\u000E':..case '\u001F':case '\u007F':..case '\u0084':case '\u0086':..case '\u009F': case '\u0009':..case '\u000C': case '\u0085':
`;
// TODO: redo the most of hangul stuff algorithmically in case of Graphemes too
// kill unrolled switches
private static bool isRegionalIndicator(dchar ch)
{
return ch >= '\U0001F1E6' && ch <= '\U0001F1FF';
}
template genericDecodeGrapheme(bool getValue)
{
alias graphemeExtend = graphemeExtendTrie;
alias spacingMark = mcTrie;
static if(getValue)
alias Grapheme Value;
else
alias void Value;
Value genericDecodeGrapheme(Input)(ref Input range)
{
enum GraphemeState {
Start,
CR,
RI,
L,
V,
LVT
}
static if(getValue)
Grapheme grapheme;
auto state = GraphemeState.Start;
enum eat = q{
static if(getValue)
grapheme ~= ch;
range.popFront();
};
dchar ch;
assert(!range.empty, "Attempting to decode grapheme from an empty " ~ Input.stringof);
while(!range.empty)
{
ch = range.front;
final switch(state) with(GraphemeState)
{
case Start:
mixin(eat);
if(ch == '\r')
state = CR;
else if(isRegionalIndicator(ch))
state = RI;
else if(isHangL(ch))
state = L;
else if(hangLV[ch] || isHangV(ch))
state = V;
else if(hangLVT[ch])
state = LVT;
else if(isHangT(ch))
state = LVT;
else
{
switch(ch)
{
mixin(controlSwitch);
goto L_End;
default:
goto L_End_Extend;
}
}
break;
case CR:
if(ch == '\n')
mixin(eat);
goto L_End_Extend;
case RI:
if(isRegionalIndicator(ch))
mixin(eat);
else
goto L_End_Extend;
break;
case L:
if(isHangL(ch))
mixin(eat);
else if(isHangV(ch) || hangLV[ch])
{
state = V;
mixin(eat);
}
else if(hangLVT[ch])
{
state = LVT;
mixin(eat);
}
else
goto L_End_Extend;
break;
case V:
if(isHangV(ch))
mixin(eat);
else if(isHangT(ch))
{
state = LVT;
mixin(eat);
}
else
goto L_End_Extend;
break;
case LVT:
if(isHangT(ch))
{
mixin(eat);
}
else
goto L_End_Extend;
break;
}
}
L_End_Extend:
while(!range.empty)
{
ch = range.front;
// extend & spacing marks
if(!graphemeExtend[ch] && !spacingMark[ch])
break;
mixin(eat);
}
L_End:
static if(getValue)
return grapheme;
}
}
@trusted:
public: // Public API continues
/++
Returns the length of grapheme cluster starting at $(D index).
Both the resulting length and the $(D index) are measured
in $(S_LINK Code unit, code units).
Example:
---
// ASCII as usual is 1 code unit, 1 code point etc.
assert(graphemeStride(" ", 1) == 1);
// A + combing ring above
string city = "A\u030Arhus";
size_t first = graphemeStride(city, 0);
assert(first == 3); //\u030A has 2 UTF-8 code units
assert(city[0..first] == "A\u030A");
assert(city[first..$] == "rhus");
---
+/
size_t graphemeStride(C)(in C[] input, size_t index)
if(is(C : dchar))
{
auto src = input[index..$];
auto n = src.length;
genericDecodeGrapheme!(false)(src);
return n - src.length;
}
// for now tested separately see test_grapheme.d
unittest
{
assert(graphemeStride(" ", 1) == 1);
// A + combing ring above
string city = "A\u030Arhus";
size_t first = graphemeStride(city, 0);
assert(first == 3); //\u030A has 2 UTF-8 code units
assert(city[0..first] == "A\u030A");
assert(city[first..$] == "rhus");
}
/++
Reads one full grapheme cluster from an input range of dchar $(D inp).
For examples see the $(LREF Grapheme) below.
Note:
This function modifies $(D inp) and thus $(D inp)
must be an L-value.
+/
Grapheme decodeGrapheme(Input)(ref Input inp)
if(isInputRange!Input && is(Unqual!(ElementType!Input) == dchar))
{
return genericDecodeGrapheme!true(inp);
}
unittest
{
Grapheme gr;
string s = " \u0020\u0308 ";
gr = decodeGrapheme(s);
assert(gr.length == 1 && gr[0] == ' ');
gr = decodeGrapheme(s);
assert(gr.length == 2 && equalS(gr[0..2], " \u0308"));
s = "\u0300\u0308\u1100";
assert(equalS(decodeGrapheme(s)[], "\u0300\u0308"));
assert(equalS(decodeGrapheme(s)[], "\u1100"));
s = "\u11A8\u0308\uAC01";
assert(equalS(decodeGrapheme(s)[], "\u11A8\u0308"));
assert(equalS(decodeGrapheme(s)[], "\uAC01"));
}
/++
$(P Iterate a string by grapheme.)
$(P Useful for doing string manipulation that needs to be aware
of graphemes.)
See_Also:
$(LREF byCodePoint)
+/
// TODO: Bidirectional access
auto byGrapheme(Range)(Range range)
if(isInputRange!Range && is(Unqual!(ElementType!Range) == dchar))
{
static struct Result
{
private Range _range;
private Grapheme _front;
bool empty() @property
{
return _front.length == 0;
}
Grapheme front() @property
{
return _front;
}
void popFront()
{
_front = _range.empty ? Grapheme.init : _range.decodeGrapheme();
}
static if(isForwardRange!Range)
{
Result save() @property
{
return Result(_range.save, _front);
}
}
}
auto result = Result(range);
result.popFront();
return result;
}
///
unittest
{
auto text = "noe\u0308l"; // noël using e + combining diaeresis
assert(text.walkLength == 5); // 5 code points
auto gText = text.byGrapheme;
assert(gText.walkLength == 4); // 4 graphemes
assert(gText.take(3).equal("noe\u0308".byGrapheme));
assert(gText.drop(3).equal("l".byGrapheme));
}
// For testing non-forward-range input ranges
version(unittest)
private static struct InputRangeString
{
private string s;
bool empty() @property { return s.empty; }
dchar front() @property { return s.front; }
void popFront() { s.popFront(); }
}
unittest
{
assert("".byGrapheme.walkLength == 0);
auto reverse = "le\u0308on";
assert(reverse.walkLength == 5);
auto gReverse = reverse.byGrapheme;
assert(gReverse.walkLength == 4);
foreach(text; TypeTuple!("noe\u0308l"c, "noe\u0308l"w, "noe\u0308l"d))
{
assert(text.walkLength == 5);
static assert(isForwardRange!(typeof(text)));
auto gText = text.byGrapheme;
static assert(isForwardRange!(typeof(gText)));
assert(gText.walkLength == 4);
assert(gText.array.retro.equal(gReverse));
}
auto nonForwardRange = InputRangeString("noe\u0308l").byGrapheme;
static assert(!isForwardRange!(typeof(nonForwardRange)));
assert(nonForwardRange.walkLength == 4);
}
/++
$(P Lazily transform a range of $(LREF Grapheme)s to a range of code points.)
$(P Useful for converting the result to a string after doing operations
on graphemes.)
$(P Acts as the identity function when given a range of code points.)
+/
// TODO: Propagate bidirectional access
auto byCodePoint(Range)(Range range)
if(isInputRange!Range && is(Unqual!(ElementType!Range) == Grapheme))
{
static struct Result
{
private Range _range;
private size_t i = 0;
bool empty() @property
{
return _range.empty;
}
dchar front() @property
{
return _range.front[i];
}
void popFront()
{
++i;
if(i >= _range.front.length)
{
_range.popFront();
i = 0;
}
}
static if(isForwardRange!Range)
{
Result save() @property
{
return Result(_range.save, i);
}
}
}
return Result(range);
}
/// Ditto
Range byCodePoint(Range)(Range range)
if(isInputRange!Range && is(Unqual!(ElementType!Range) == dchar))
{
return range;
}
///
unittest
{
import std.string : text;
string s = "noe\u0308l"; // noël
// reverse it and convert the result to a string
string reverse = s.byGrapheme
.array
.retro
.byCodePoint
.text;
assert(reverse == "le\u0308on"); // lëon
}
unittest
{
assert("".byGrapheme.byCodePoint.equal(""));
string text = "noe\u0308l";
static assert(is(typeof(text.byCodePoint) == string));
auto gText = InputRangeString(text).byGrapheme;
static assert(!isForwardRange!(typeof(gText)));
auto cpText = gText.byCodePoint;
static assert(!isForwardRange!(typeof(cpText)));
assert(cpText.walkLength == text.walkLength);
}
/++
$(P A structure designed to effectively pack $(CHARACTERS)
of a $(CLUSTER).
)
$(P $(D Grapheme) has value semantics so 2 copies of a $(D Grapheme)
always refer to distinct objects. In most actual scenarios a $(D Grapheme)
fits on the stack and avoids memory allocation overhead for all but quite
long clusters.
)
Example:
---
import std.algorithm;
string bold = "ku\u0308hn";
// note that decodeGrapheme takes parameter by ref
// slicing a grapheme yields a range of dchar
assert(decodeGrapheme(bold)[].equal("k"));
// the next grapheme is 2 characters long
auto wideOne = decodeGrapheme(bold);
assert(wideOne.length == 2);
assert(wideOne[].equal("u\u0308"));
// the usual range manipulation is possible
assert(wideOne[].filter!isMark.equal("\u0308"));
---
$(P See also $(LREF decodeGrapheme), $(LREF graphemeStride). )
+/
@trusted struct Grapheme
{
public:
this(C)(in C[] chars...)
if(is(C : dchar))
{
this ~= chars;
}
this(Input)(Input seq)
if(!isDynamicArray!Input
&& isInputRange!Input && is(ElementType!Input : dchar))
{
this ~= seq;
}
/// Gets a $(CODEPOINT) at the given index in this cluster.
dchar opIndex(size_t index) const pure nothrow
{
assert(index < length);
return read24(isBig ? ptr_ : small_.ptr, index);
}
/++
Writes a $(CODEPOINT) $(D ch) at given index in this cluster.
Warning:
Use of this facility may invalidate grapheme cluster,
see also $(LREF Grapheme.valid).
Example:
---
auto g = Grapheme("A\u0302");
assert(g[0] == 'A');
assert(g.valid);
g[1] = '~'; // ASCII tilda is not a combining mark
assert(g[1] == '~');
assert(!g.valid);
---
+/
void opIndexAssign(dchar ch, size_t index) pure nothrow
{
assert(index < length);
write24(isBig ? ptr_ : small_.ptr, ch, index);
}
/++
Random-access range over Grapheme's $(CHARACTERS).
Warning: Invalidates when this Grapheme leaves the scope,
attempts to use it then would lead to memory corruption.
+/
@system auto opSlice(size_t a, size_t b) pure nothrow
{
return sliceOverIndexed(a, b, &this);
}
/// ditto
@system auto opSlice() pure nothrow
{
return sliceOverIndexed(0, length, &this);
}
/// Grapheme cluster length in $(CODEPOINTS).
@property size_t length() const pure nothrow
{
return isBig ? len_ : slen_ & 0x7F;
}
/++
Append $(CHARACTER) $(D ch) to this grapheme.
Warning:
Use of this facility may invalidate grapheme cluster,
see also $(D valid).
Example:
---
auto g = Grapheme("A");
assert(g.valid);
g ~= '\u0301';
assert(g[].equal("A\u0301"));
assert(g.valid);
g ~= "B";
// not a valid grapheme cluster anymore
assert(!g.valid);
// still could be useful though
assert(g[].equal("A\u0301B"));
---
See also $(LREF Grapheme.valid) below.
+/
ref opOpAssign(string op)(dchar ch)
{
static if(op == "~")
{
if(!isBig)
{
if(slen_ + 1 > small_cap)
convertToBig();// & fallthrough to "big" branch
else
{
write24(small_.ptr, ch, smallLength);
slen_++;
return this;
}
}
assert(isBig);
if(len_ + 1 > cap_)
{
cap_ += grow;
ptr_ = cast(ubyte*)enforce(realloc(ptr_, 3*(cap_+1)));
}
write24(ptr_, ch, len_++);
return this;
}
else
static assert(false, "No operation "~op~" defined for Grapheme");
}
/// Append all $(CHARACTERS) from the input range $(D inp) to this Grapheme.
ref opOpAssign(string op, Input)(Input inp)
if(isInputRange!Input && is(ElementType!Input : dchar))
{
static if(op == "~")
{
foreach(dchar ch; inp)
this ~= ch;
return this;
}
else
static assert(false, "No operation "~op~" defined for Grapheme");
}
/++
True if this object contains valid extended grapheme cluster.
Decoding primitives of this module always return a valid $(D Grapheme).
Appending to and direct manipulation of grapheme's $(CHARACTERS) may
render it no longer valid. Certain applications may chose to use
Grapheme as a "small string" of any $(CODEPOINTS) and ignore this property
entirely.
+/
@property bool valid()() /*const*/
{
auto r = this[];
genericDecodeGrapheme!false(r);
return r.length == 0;
}
this(this)
{
if(isBig)
{// dup it
auto raw_cap = 3*(cap_+1);
auto p = cast(ubyte*)enforce(malloc(raw_cap));
p[0..raw_cap] = ptr_[0..raw_cap];
ptr_ = p;
}
}
~this()
{
if(isBig)
{
free(ptr_);
}
}
private:
enum small_bytes = ((ubyte*).sizeof+3*size_t.sizeof-1);
// "out of the blue" grow rate, needs testing
// (though graphemes are typically small < 9)
enum grow = 20;
enum small_cap = small_bytes/3;
enum small_flag = 0x80, small_mask = 0x7F;
// 16 bytes in 32bits, should be enough for the majority of cases
union
{
struct
{
ubyte* ptr_;
size_t cap_;
size_t len_;
size_t padding_;
}
struct
{
ubyte[small_bytes] small_;
ubyte slen_;
}
}
void convertToBig()
{
size_t k = smallLength;
ubyte* p = cast(ubyte*)enforce(malloc(3*(grow+1)));
for(int i=0; i<k; i++)
write24(p, read24(small_.ptr, i), i);
// now we can overwrite small array data
ptr_ = p;
len_ = slen_;
assert(grow > len_);
cap_ = grow;
setBig();
}
void setBig(){ slen_ |= small_flag; }
@property size_t smallLength() pure nothrow
{
return slen_ & small_mask;
}
@property ubyte isBig() const pure nothrow
{
return slen_ & small_flag;
}
}
static assert(Grapheme.sizeof == size_t.sizeof*4);
// verify the example
unittest
{
import std.algorithm;
string bold = "ku\u0308hn";
// note that decodeGrapheme takes parameter by ref
auto first = decodeGrapheme(bold);
assert(first.length == 1);
assert(first[0] == 'k');
// the next grapheme is 2 characters long
auto wideOne = decodeGrapheme(bold);
// slicing a grapheme yields a random-access range of dchar
assert(wideOne[].equalS("u\u0308"));
assert(wideOne.length == 2);
static assert(isRandomAccessRange!(typeof(wideOne[])));
// all of the usual range manipulation is possible
assert(wideOne[].filter!isMark().equalS("\u0308"));
auto g = Grapheme("A");
assert(g.valid);
g ~= '\u0301';
assert(g[].equalS("A\u0301"));
assert(g.valid);
g ~= "B";
// not a valid grapheme cluster anymore
assert(!g.valid);
// still could be useful though
assert(g[].equalS("A\u0301B"));
}
unittest
{
auto g = Grapheme("A\u0302");
assert(g[0] == 'A');
assert(g.valid);
g[1] = '~'; // ASCII tilda is not a combining mark
assert(g[1] == '~');
assert(!g.valid);
}
unittest
{
// not valid clusters (but it just a test)
auto g = Grapheme('a', 'b', 'c', 'd', 'e');
assert(g[0] == 'a');
assert(g[1] == 'b');
assert(g[2] == 'c');
assert(g[3] == 'd');
assert(g[4] == 'e');
g[3] = 'Й';
assert(g[2] == 'c');
assert(g[3] == 'Й', text(g[3], " vs ", 'Й'));
assert(g[4] == 'e');
assert(!g.valid);
g ~= 'ц';
g ~= '~';
assert(g[0] == 'a');
assert(g[1] == 'b');
assert(g[2] == 'c');
assert(g[3] == 'Й');
assert(g[4] == 'e');
assert(g[5] == 'ц');
assert(g[6] == '~');
assert(!g.valid);
Grapheme copy = g;
copy[0] = 'X';
copy[1] = '-';
assert(g[0] == 'a' && copy[0] == 'X');
assert(g[1] == 'b' && copy[1] == '-');
assert(equalS(g[2..g.length], copy[2..copy.length]));
copy = Grapheme("АБВГДЕЁЖЗИКЛМ");
assert(equalS(copy[0..8], "АБВГДЕЁЖ"), text(copy[0..8]));
copy ~= "xyz";
assert(equalS(copy[13..15], "xy"), text(copy[13..15]));
assert(!copy.valid);
Grapheme h;
foreach(dchar v; iota(cast(int)'A', cast(int)'Z'+1).map!"cast(dchar)a"())
h ~= v;
assert(equalS(h[], iota(cast(int)'A', cast(int)'Z'+1)));
}
/++
$(P Does basic case-insensitive comparison of strings $(D str1) and $(D str2).
This function uses simpler comparison rule thus achieving better performance
then $(LREF icmp). However keep in mind the warning below.)
Warning:
This function only handles 1:1 $(CODEPOINT) mapping
and thus is not sufficient for certain alphabets
like German, Greek and few others.
Example:
---
assert(sicmp("Август", "авгусТ") == 0);
// Greek also works as long as there is no 1:M mapping in sight
assert(sicmp("ΌΎ", "όύ") == 0);
// things like the following won't get matched as equal
// Greek small letter iota with dialytika and tonos
assert(sicmp("ΐ", "\u03B9\u0308\u0301") != 0);
// while icmp has no problem with that
assert(icmp("ΐ", "\u03B9\u0308\u0301") == 0);
assert(icmp("ΌΎ", "όύ") == 0);
---
+/
int sicmp(S1, S2)(S1 str1, S2 str2)
if(isForwardRange!S1 && is(Unqual!(ElementType!S1) == dchar)
&& isForwardRange!S2 && is(Unqual!(ElementType!S2) == dchar))
{
import std.utf : decode;
alias sTable = simpleCaseTable;
size_t ridx=0;
foreach(dchar lhs; str1)
{
if(ridx == str2.length)
return 1;
dchar rhs = std.utf.decode(str2, ridx);
int diff = lhs - rhs;
if(!diff)
continue;
size_t idx = simpleCaseTrie[lhs];
size_t idx2 = simpleCaseTrie[rhs];
// simpleCaseTrie is packed index table
if(idx != EMPTY_CASE_TRIE)
{
if(idx2 != EMPTY_CASE_TRIE)
{// both cased chars
// adjust idx --> start of bucket
idx = idx - sTable[idx].n;
idx2 = idx2 - sTable[idx2].n;
if(idx == idx2)// one bucket, equivalent chars
continue;
else// not the same bucket
diff = sTable[idx].ch - sTable[idx2].ch;
}
else
diff = sTable[idx - sTable[idx].n].ch - rhs;
}
else if(idx2 != EMPTY_CASE_TRIE)
{
diff = lhs - sTable[idx2 - sTable[idx2].n].ch;
}
// one of chars is not cased at all
return diff;
}
return ridx == str2.length ? 0 : -1;
}
// overloads for the most common cases to reduce compile time
@safe pure /*TODO nothrow*/
{
int sicmp(const(char)[] str1, const(char)[] str2)
{ return sicmp!(const(char)[], const(char)[])(str1, str2); }
int sicmp(const(wchar)[] str1, const(wchar)[] str2)
{ return sicmp!(const(wchar)[], const(wchar)[])(str1, str2); }
int sicmp(const(dchar)[] str1, const(dchar)[] str2)
{ return sicmp!(const(dchar)[], const(dchar)[])(str1, str2); }
}
private int fullCasedCmp(Range)(dchar lhs, dchar rhs, ref Range rtail)
@trusted pure /*TODO nothrow*/
{
alias fTable = fullCaseTable;
size_t idx = fullCaseTrie[lhs];
// fullCaseTrie is packed index table
if(idx == EMPTY_CASE_TRIE)
return lhs;
size_t start = idx - fTable[idx].n;
size_t end = fTable[idx].size + start;
assert(fTable[start].entry_len == 1);
for(idx=start; idx<end; idx++)
{
auto entryLen = fTable[idx].entry_len;
if(entryLen == 1)
{
if(fTable[idx].seq[0] == rhs)
{
return 0;
}
}
else
{// OK it's a long chunk, like 'ss' for German
dstring seq = fTable[idx].seq[0..entryLen];
if(rhs == seq[0]
&& rtail.skipOver(seq[1..$]))
{
// note that this path modifies rtail
// iff we managed to get there
return 0;
}
}
}
return fTable[start].seq[0]; // new remapped character for accurate diffs
}
/++
$(P Does case insensitive comparison of $(D str1) and $(D str2).
Follows the rules of full case-folding mapping.
This includes matching as equal german ß with "ss" and
other 1:M $(CODEPOINT) mappings unlike $(LREF sicmp).
The cost of $(D icmp) being pedantically correct is
slightly worse performance.
)
Example:
---
assert(icmp("Rußland", "Russland") == 0);
assert(icmp("ᾩ -> \u1F70\u03B9", "\u1F61\u03B9 -> ᾲ") == 0);
---
+/
int icmp(S1, S2)(S1 str1, S2 str2)
if(isForwardRange!S1 && is(Unqual!(ElementType!S1) == dchar)
&& isForwardRange!S2 && is(Unqual!(ElementType!S2) == dchar))
{
for(;;)
{
if(str1.empty)
return str2.empty ? 0 : -1;
dchar lhs = str1.front;
if(str2.empty)
return 1;
dchar rhs = str2.front;
str1.popFront();
str2.popFront();
int diff = lhs - rhs;
if(!diff)
continue;
// first try to match lhs to <rhs,right-tail> sequence
int cmpLR = fullCasedCmp(lhs, rhs, str2);
if(!cmpLR)
continue;
// then rhs to <lhs,left-tail> sequence
int cmpRL = fullCasedCmp(rhs, lhs, str1);
if(!cmpRL)
continue;
// cmpXX contain remapped codepoints
// to obtain stable ordering of icmp
diff = cmpLR - cmpRL;
return diff;
}
}
// overloads for the most common cases to reduce compile time
@safe pure /*TODO nothrow*/
{
int icmp(const(char)[] str1, const(char)[] str2)
{ return icmp!(const(char)[], const(char)[])(str1, str2); }
int icmp(const(wchar)[] str1, const(wchar)[] str2)
{ return icmp!(const(wchar)[], const(wchar)[])(str1, str2); }
int icmp(const(dchar)[] str1, const(dchar)[] str2)
{ return icmp!(const(dchar)[], const(dchar)[])(str1, str2); }
}
unittest
{
assertCTFEable!(
{
foreach(cfunc; TypeTuple!(icmp, sicmp))
{
foreach(S1; TypeTuple!(string, wstring, dstring))
foreach(S2; TypeTuple!(string, wstring, dstring))
{
assert(cfunc("".to!S1(), "".to!S2()) == 0);
assert(cfunc("A".to!S1(), "".to!S2()) > 0);
assert(cfunc("".to!S1(), "0".to!S2()) < 0);
assert(cfunc("abc".to!S1(), "abc".to!S2()) == 0);
assert(cfunc("abcd".to!S1(), "abc".to!S2()) > 0);
assert(cfunc("abc".to!S1(), "abcd".to!S2()) < 0);
assert(cfunc("Abc".to!S1(), "aBc".to!S2()) == 0);
assert(cfunc("авГуст".to!S1(), "АВгУСТ".to!S2()) == 0);
// Check example:
assert(cfunc("Август".to!S1(), "авгусТ".to!S2()) == 0);
assert(cfunc("ΌΎ".to!S1(), "όύ".to!S2()) == 0);
}
// check that the order is properly agnostic to the case
auto strs = [ "Apple", "ORANGE", "orAcle", "amp", "banana"];
sort!((a,b) => cfunc(a,b) < 0)(strs);
assert(strs == ["amp", "Apple", "banana", "orAcle", "ORANGE"]);
}
assert(icmp("ßb", "ssa") > 0);
// Check example:
assert(icmp("Russland", "Rußland") == 0);
assert(icmp("ᾩ -> \u1F70\u03B9", "\u1F61\u03B9 -> ᾲ") == 0);
assert(icmp("ΐ"w, "\u03B9\u0308\u0301") == 0);
assert(sicmp("ΐ", "\u03B9\u0308\u0301") != 0);
//bugzilla 11057
assert( icmp("K", "L") < 0 );
});
}
/++
$(P Returns the $(S_LINK Combining class, combining class) of $(D ch).)
Example:
---
// shorten the code
alias CC = combiningClass;
// combining tilda
assert(CC('\u0303') == 230);
// combining ring below
assert(CC('\u0325') == 220);
// the simple consequence is that "tilda" should be
// placed after a "ring below" in a sequence
---
+/
ubyte combiningClass(dchar ch)
{
return combiningClassTrie[ch];
}
unittest
{
foreach(ch; 0..0x80)
assert(combiningClass(ch) == 0);
assert(combiningClass('\u05BD') == 22);
assert(combiningClass('\u0300') == 230);
assert(combiningClass('\u0317') == 220);
assert(combiningClass('\u1939') == 222);
}
/// Unicode character decomposition type.
enum UnicodeDecomposition {
/// Canonical decomposition. The result is canonically equivalent sequence.
Canonical,
/**
Compatibility decomposition. The result is compatibility equivalent sequence.
Note: Compatibility decomposition is a $(B lossy) conversion,
typically suitable only for fuzzy matching and internal processing.
*/
Compatibility
};
/**
Shorthand aliases for character decomposition type, passed as a
template parameter to $(LREF decompose).
*/
enum {
Canonical = UnicodeDecomposition.Canonical,
Compatibility = UnicodeDecomposition.Compatibility
};
/++
Try to canonically compose 2 $(CHARACTERS).
Returns the composed $(CHARACTER) if they do compose and dchar.init otherwise.
The assumption is that $(D first) comes before $(D second) in the original text,
usually meaning that the first is a starter.
Note: Hangul syllables are not covered by this function.
See $(D composeJamo) below.
Example:
---
assert(compose('A','\u0308') == '\u00C4');
assert(compose('A', 'B') == dchar.init);
assert(compose('C', '\u0301') == '\u0106');
// note that the starter is the first one
// thus the following doesn't compose
assert(compose('\u0308', 'A') == dchar.init);
---
+/
public dchar compose(dchar first, dchar second)
{
import std.internal.unicode_comp;
size_t packed = compositionJumpTrie[first];
if(packed == ushort.max)
return dchar.init;
// unpack offset and length
size_t idx = packed & composeIdxMask, cnt = packed >> composeCntShift;
// TODO: optimize this micro binary search (no more then 4-5 steps)
auto r = compositionTable[idx..idx+cnt].map!"a.rhs"().assumeSorted();
auto target = r.lowerBound(second).length;
if(target == cnt)
return dchar.init;
auto entry = compositionTable[idx+target];
if(entry.rhs != second)
return dchar.init;
return entry.composed;
}
/++
Returns a full $(S_LINK Canonical decomposition, Canonical)
(by default) or $(S_LINK Compatibility decomposition, Compatibility)
decomposition of $(CHARACTER) $(D ch).
If no decomposition is available returns a $(LREF Grapheme)
with the $(D ch) itself.
Note:
This function also decomposes hangul syllables
as prescribed by the standard.
See also $(LREF decomposeHangul) for a restricted version
that takes into account only hangul syllables but
no other decompositions.
Example:
---
import std.algorithm;
assert(decompose('Ĉ')[].equal("C\u0302"));
assert(decompose('D')[].equal("D"));
assert(decompose('\uD4DC')[].equal("\u1111\u1171\u11B7"));
assert(decompose!Compatibility('¹').equal("1"));
---
+/
public Grapheme decompose(UnicodeDecomposition decompType=Canonical)(dchar ch)
{
import std.internal.unicode_decomp;
static if(decompType == Canonical)
{
alias table = decompCanonTable;
alias mapping = canonMappingTrie;
}
else static if(decompType == Compatibility)
{
alias table = decompCompatTable;
alias mapping = compatMappingTrie;
}
ushort idx = mapping[ch];
if(!idx) // not found, check hangul arithmetic decomposition
return decomposeHangul(ch);
auto decomp = table[idx..$].until(0);
return Grapheme(decomp);
}
unittest
{
// verify examples
assert(compose('A','\u0308') == '\u00C4');
assert(compose('A', 'B') == dchar.init);
assert(compose('C', '\u0301') == '\u0106');
// note that the starter is the first one
// thus the following doesn't compose
assert(compose('\u0308', 'A') == dchar.init);
import std.algorithm;
assert(decompose('Ĉ')[].equalS("C\u0302"));
assert(decompose('D')[].equalS("D"));
assert(decompose('\uD4DC')[].equalS("\u1111\u1171\u11B7"));
assert(decompose!Compatibility('¹')[].equalS("1"));
}
//----------------------------------------------------------------------------
// Hangul specific composition/decomposition
enum jamoSBase = 0xAC00;
enum jamoLBase = 0x1100;
enum jamoVBase = 0x1161;
enum jamoTBase = 0x11A7;
enum jamoLCount = 19, jamoVCount = 21, jamoTCount = 28;
enum jamoNCount = jamoVCount * jamoTCount;
enum jamoSCount = jamoLCount * jamoNCount;
// Tests if $(D ch) is a Hangul leading consonant jamo.
bool isJamoL(dchar ch)
{
// first cmp rejects ~ 1M code points above leading jamo range
return ch < jamoLBase+jamoLCount && ch >= jamoLBase;
}
// Tests if $(D ch) is a Hangul vowel jamo.
bool isJamoT(dchar ch)
{
// first cmp rejects ~ 1M code points above trailing jamo range
// Note: ch == jamoTBase doesn't indicate trailing jamo (TIndex must be > 0)
return ch < jamoTBase+jamoTCount && ch > jamoTBase;
}
// Tests if $(D ch) is a Hangul trailnig consonant jamo.
bool isJamoV(dchar ch)
{
// first cmp rejects ~ 1M code points above vowel range
return ch < jamoVBase+jamoVCount && ch >= jamoVBase;
}
int hangulSyllableIndex(dchar ch)
{
int idxS = cast(int)ch - jamoSBase;
return idxS >= 0 && idxS < jamoSCount ? idxS : -1;
}
// internal helper: compose hangul syllables leaving dchar.init in holes
void hangulRecompose(dchar[] seq)
{
for(size_t idx = 0; idx + 1 < seq.length; )
{
if(isJamoL(seq[idx]) && isJamoV(seq[idx+1]))
{
int indexL = seq[idx] - jamoLBase;
int indexV = seq[idx+1] - jamoVBase;
int indexLV = indexL * jamoNCount + indexV * jamoTCount;
if(idx + 2 < seq.length && isJamoT(seq[idx+2]))
{
seq[idx] = jamoSBase + indexLV + seq[idx+2] - jamoTBase;
seq[idx+1] = dchar.init;
seq[idx+2] = dchar.init;
idx += 3;
}
else
{
seq[idx] = jamoSBase + indexLV;
seq[idx+1] = dchar.init;
idx += 2;
}
}
else
idx++;
}
}
//----------------------------------------------------------------------------
public:
/**
Decomposes a Hangul syllable. If $(D ch) is not a composed syllable
then this function returns $(LREF Grapheme) containing only $(D ch) as is.
Example:
---
import std.algorithm;
assert(decomposeHangul('\uD4DB')[].equal("\u1111\u1171\u11B6"));
---
*/
Grapheme decomposeHangul(dchar ch)
{
int idxS = cast(int)ch - jamoSBase;
if(idxS < 0 || idxS >= jamoSCount) return Grapheme(ch);
int idxL = idxS / jamoNCount;
int idxV = (idxS % jamoNCount) / jamoTCount;
int idxT = idxS % jamoTCount;
int partL = jamoLBase + idxL;
int partV = jamoVBase + idxV;
if(idxT > 0) // there is a trailling consonant (T); <L,V,T> decomposition
return Grapheme(partL, partV, jamoTBase + idxT);
else // <L, V> decomposition
return Grapheme(partL, partV);
}
/++
Try to compose hangul syllable out of a leading consonant ($(D lead)),
a $(D vowel) and optional $(D trailing) consonant jamos.
On success returns the composed LV or LVT hangul syllable.
If any of $(D lead) and $(D vowel) are not a valid hangul jamo
of the respective $(CHARACTER) class returns dchar.init.
Example:
---
assert(composeJamo('\u1111', '\u1171', '\u11B6') == '\uD4DB');
// leaving out T-vowel, or passing any codepoint
// that is not trailing consonant composes an LV-syllable
assert(composeJamo('\u1111', '\u1171') == '\uD4CC');
assert(composeJamo('\u1111', '\u1171', ' ') == '\uD4CC');
assert(composeJamo('\u1111', 'A') == dchar.init);
assert(composeJamo('A', '\u1171') == dchar.init);
---
+/
dchar composeJamo(dchar lead, dchar vowel, dchar trailing=dchar.init)
{
if(!isJamoL(lead))
return dchar.init;
int indexL = lead - jamoLBase;
if(!isJamoV(vowel))
return dchar.init;
int indexV = vowel - jamoVBase;
int indexLV = indexL * jamoNCount + indexV * jamoTCount;
dchar syllable = jamoSBase + indexLV;
return isJamoT(trailing) ? syllable + (trailing - jamoTBase) : syllable;
}
unittest
{
static void testDecomp(UnicodeDecomposition T)(dchar ch, string r)
{
Grapheme g = decompose!T(ch);
assert(equalS(g[], r), text(g[], " vs ", r));
}
testDecomp!Canonical('\u1FF4', "\u03C9\u0301\u0345");
testDecomp!Canonical('\uF907', "\u9F9C");
testDecomp!Compatibility('\u33FF', "\u0067\u0061\u006C");
testDecomp!Compatibility('\uA7F9', "\u0153");
// check examples
assert(decomposeHangul('\uD4DB')[].equalS("\u1111\u1171\u11B6"));
assert(composeJamo('\u1111', '\u1171', '\u11B6') == '\uD4DB');
assert(composeJamo('\u1111', '\u1171') == '\uD4CC'); // leave out T-vowel
assert(composeJamo('\u1111', '\u1171', ' ') == '\uD4CC');
assert(composeJamo('\u1111', 'A') == dchar.init);
assert(composeJamo('A', '\u1171') == dchar.init);
}
/**
Enumeration type for normalization forms,
passed as template parameter for functions like $(LREF normalize).
*/
enum NormalizationForm {
NFC,
NFD,
NFKC,
NFKD
}
enum {
/**
Shorthand aliases from values indicating normalization forms.
*/
NFC = NormalizationForm.NFC,
///ditto
NFD = NormalizationForm.NFD,
///ditto
NFKC = NormalizationForm.NFKC,
///ditto
NFKD = NormalizationForm.NFKD
};
/++
Returns $(D input) string normalized to the chosen form.
Form C is used by default.
For more information on normalization forms see
the $(S_LINK Normalization, normalization section).
Note:
In cases where the string in question is already normalized,
it is returned unmodified and no memory allocation happens.
Example:
---
// any encoding works
wstring greet = "Hello world";
assert(normalize(greet) is greet); // the same exact slice
// An example of a character with all 4 forms being different:
// Greek upsilon with acute and hook symbol (code point 0x03D3)
assert(normalize!NFC("ϓ") == "\u03D3");
assert(normalize!NFD("ϓ") == "\u03D2\u0301");
assert(normalize!NFKC("ϓ") == "\u038E");
assert(normalize!NFKD("ϓ") == "\u03A5\u0301");
---
+/
inout(C)[] normalize(NormalizationForm norm=NFC, C)(inout(C)[] input)
{
auto anchors = splitNormalized!norm(input);
if(anchors[0] == input.length && anchors[1] == input.length)
return input;
dchar[] decomposed;
decomposed.reserve(31);
ubyte[] ccc;
ccc.reserve(31);
auto app = appender!(C[])();
do
{
app.put(input[0..anchors[0]]);
foreach(dchar ch; input[anchors[0]..anchors[1]])
static if(norm == NFD || norm == NFC)
{
foreach(dchar c; decompose!Canonical(ch)[])
decomposed ~= c;
}
else // NFKD & NFKC
{
foreach(dchar c; decompose!Compatibility(ch)[])
decomposed ~= c;
}
ccc.length = decomposed.length;
size_t firstNonStable = 0;
ubyte lastClazz = 0;
foreach(idx, dchar ch; decomposed)
{
auto clazz = combiningClass(ch);
ccc[idx] = clazz;
if(clazz == 0 && lastClazz != 0)
{
// found a stable code point after unstable ones
sort!("a[0] < b[0]", SwapStrategy.stable)
(zip(ccc[firstNonStable..idx], decomposed[firstNonStable..idx]));
firstNonStable = decomposed.length;
}
else if(clazz != 0 && lastClazz == 0)
{
// found first unstable code point after stable ones
firstNonStable = idx;
}
lastClazz = clazz;
}
sort!("a[0] < b[0]", SwapStrategy.stable)
(zip(ccc[firstNonStable..$], decomposed[firstNonStable..$]));
static if(norm == NFC || norm == NFKC)
{
size_t idx = 0;
auto first = countUntil(ccc, 0);
if(first >= 0) // no starters?? no recomposition
{
for(;;)
{
auto second = recompose(first, decomposed, ccc);
if(second == decomposed.length)
break;
first = second;
}
// 2nd pass for hangul syllables
hangulRecompose(decomposed);
}
}
static if(norm == NFD || norm == NFKD)
app.put(decomposed);
else
{
auto clean = remove!("a == dchar.init", SwapStrategy.stable)(decomposed);
app.put(decomposed[0 .. clean.length]);
}
// reset variables
decomposed.length = 0;
decomposed.assumeSafeAppend();
ccc.length = 0;
ccc.assumeSafeAppend();
input = input[anchors[1]..$];
// and move on
anchors = splitNormalized!norm(input);
}while(anchors[0] != input.length);
app.put(input[0..anchors[0]]);
return cast(inout(C)[])app.data;
}
unittest
{
assert(normalize!NFD("abc\uF904def") == "abc\u6ED1def", text(normalize!NFD("abc\uF904def")));
assert(normalize!NFKD("2¹⁰") == "210", normalize!NFKD("2¹⁰"));
assert(normalize!NFD("Äffin") == "A\u0308ffin");
// check example
// any encoding works
wstring greet = "Hello world";
assert(normalize(greet) is greet); // the same exact slice
// An example of a character with all 4 forms being different:
// Greek upsilon with acute and hook symbol (code point 0x03D3)
assert(normalize!NFC("ϓ") == "\u03D3");
assert(normalize!NFD("ϓ") == "\u03D2\u0301");
assert(normalize!NFKC("ϓ") == "\u038E");
assert(normalize!NFKD("ϓ") == "\u03A5\u0301");
}
// canonically recompose given slice of code points, works in-place and mutates data
private size_t recompose(size_t start, dchar[] input, ubyte[] ccc)
{
assert(input.length == ccc.length);
int accumCC = -1;// so that it's out of 0..255 range
bool foundSolidStarter = false;
// writefln("recomposing %( %04x %)", input);
// first one is always a starter thus we start at i == 1
size_t i = start+1;
for(; ; )
{
if(i == input.length)
break;
int curCC = ccc[i];
// In any character sequence beginning with a starter S
// a character C is blocked from S if and only if there
// is some character B between S and C, and either B
// is a starter or it has the same or higher combining class as C.
//------------------------
// Applying to our case:
// S is input[0]
// accumCC is the maximum CCC of characters between C and S,
// as ccc are sorted
// C is input[i]
if(curCC > accumCC)
{
dchar comp = compose(input[start], input[i]);
if(comp != dchar.init)
{
input[start] = comp;
input[i] = dchar.init;// put a sentinel
// current was merged so its CCC shouldn't affect
// composing with the next one
}
else {
// if it was a starter then accumCC is now 0, end of loop
accumCC = curCC;
if(accumCC == 0)
break;
}
}
else{
// ditto here
accumCC = curCC;
if(accumCC == 0)
break;
}
i++;
}
return i;
}
// returns tuple of 2 indexes that delimit:
// normalized text, piece that needs normalization and
// the rest of input starting with stable code point
private auto splitNormalized(NormalizationForm norm, C)(const(C)[] input)
{
auto result = input;
ubyte lastCC = 0;
foreach(idx, dchar ch; input)
{
static if(norm == NFC)
if(ch < 0x0300)
{
lastCC = 0;
continue;
}
ubyte CC = combiningClass(ch);
if(lastCC > CC && CC != 0)
{
return seekStable!norm(idx, input);
}
if(notAllowedIn!norm(ch))
{
return seekStable!norm(idx, input);
}
lastCC = CC;
}
return tuple(input.length, input.length);
}
private auto seekStable(NormalizationForm norm, C)(size_t idx, in C[] input)
{
import std.utf : codeLength;
auto br = input[0..idx];
size_t region_start = 0;// default
for(;;)
{
if(br.empty)// start is 0
break;
dchar ch = br.back;
if(combiningClass(ch) == 0 && allowedIn!norm(ch))
{
region_start = br.length - std.utf.codeLength!C(ch);
break;
}
br.popFront();
}
///@@@BUG@@@ can't use find: " find is a nested function and can't be used..."
size_t region_end=input.length;// end is $ by default
foreach(i, dchar ch; input[idx..$])
{
if(combiningClass(ch) == 0 && allowedIn!norm(ch))
{
region_end = i+idx;
break;
}
}
// writeln("Region to normalize: ", input[region_start..region_end]);
return tuple(region_start, region_end);
}
/**
Tests if dchar $(D ch) is always allowed (Quick_Check=YES) in normalization
form $(D norm).
---
// e.g. Cyrillic is always allowed, so is ASCII
assert(allowedIn!NFC('я'));
assert(allowedIn!NFD('я'));
assert(allowedIn!NFKC('я'));
assert(allowedIn!NFKD('я'));
assert(allowedIn!NFC('Z'));
---
*/
public bool allowedIn(NormalizationForm norm)(dchar ch)
{
return !notAllowedIn!norm(ch);
}
// not user friendly name but more direct
private bool notAllowedIn(NormalizationForm norm)(dchar ch)
{
static if(norm == NFC)
alias qcTrie = nfcQCTrie;
else static if(norm == NFD)
alias qcTrie = nfdQCTrie;
else static if(norm == NFKC)
alias qcTrie = nfkcQCTrie;
else static if(norm == NFKD)
alias qcTrie = nfkdQCTrie;
else
static assert("Unknown normalization form "~norm);
return qcTrie[ch];
}
unittest
{
assert(allowedIn!NFC('я'));
assert(allowedIn!NFD('я'));
assert(allowedIn!NFKC('я'));
assert(allowedIn!NFKD('я'));
assert(allowedIn!NFC('Z'));
}
}
version(std_uni_bootstrap)
{
// old version used for bootstrapping of gen_uni.d that generates
// up to date optimal versions of all of isXXX functions
@safe pure nothrow public bool isWhite(dchar c)
{
return std.ascii.isWhite(c) ||
c == lineSep || c == paraSep ||
c == '\u0085' || c == '\u00A0' || c == '\u1680' || c == '\u180E' ||
(c >= '\u2000' && c <= '\u200A') ||
c == '\u202F' || c == '\u205F' || c == '\u3000';
}
}
else
{
// trusted -> avoid bounds check
@trusted pure nothrow
ushort toLowerIndex(dchar c)
{
alias trie = toLowerIndexTrie;
return trie[c];
}
// trusted -> avoid bounds check
@trusted pure nothrow
dchar toLowerTab(size_t idx)
{
return toLowerTable[idx];
}
// trusted -> avoid bounds check
@trusted pure nothrow
ushort toTitleIndex(dchar c)
{
alias trie = toTitleIndexTrie;
return trie[c];
}
// trusted -> avoid bounds check
@trusted pure nothrow
dchar toTitleTab(size_t idx)
{
return toTitleTable[idx];
}
// trusted -> avoid bounds check
@trusted pure nothrow
ushort toUpperIndex(dchar c)
{
alias trie = toUpperIndexTrie;
return trie[c];
}
// trusted -> avoid bounds check
@trusted pure nothrow
dchar toUpperTab(size_t idx)
{
return toUpperTable[idx];
}
public:
/++
Whether or not $(D c) is a Unicode whitespace $(CHARACTER).
(general Unicode category: Part of C0(tab, vertical tab, form feed,
carriage return, and linefeed characters), Zs, Zl, Zp, and NEL(U+0085))
+/
@safe pure nothrow
public bool isWhite(dchar c)
{
return isWhiteGen(c); // call pregenerated binary search
}
/++
Return whether $(D c) is a Unicode lowercase $(CHARACTER).
+/
@safe pure nothrow
bool isLower(dchar c)
{
if(std.ascii.isASCII(c))
return std.ascii.isLower(c);
return lowerCaseTrie[c];
}
@safe unittest
{
foreach(v; 0..0x80)
assert(std.ascii.isLower(v) == isLower(v));
assert(isLower('я'));
assert(isLower('й'));
assert(!isLower('Ж'));
// Greek HETA
assert(!isLower('\u0370'));
assert(isLower('\u0371'));
assert(!isLower('\u039C')); // capital MU
assert(isLower('\u03B2')); // beta
// from extended Greek
assert(!isLower('\u1F18'));
assert(isLower('\u1F00'));
foreach(v; unicode.lowerCase.byCodepoint)
assert(isLower(v) && !isUpper(v));
}
/++
Return whether $(D c) is a Unicode uppercase $(CHARACTER).
+/
@safe pure nothrow
bool isUpper(dchar c)
{
if(std.ascii.isASCII(c))
return std.ascii.isUpper(c);
return upperCaseTrie[c];
}
@safe unittest
{
foreach(v; 0..0x80)
assert(std.ascii.isLower(v) == isLower(v));
assert(!isUpper('й'));
assert(isUpper('Ж'));
// Greek HETA
assert(isUpper('\u0370'));
assert(!isUpper('\u0371'));
assert(isUpper('\u039C')); // capital MU
assert(!isUpper('\u03B2')); // beta
// from extended Greek
assert(!isUpper('\u1F00'));
assert(isUpper('\u1F18'));
foreach(v; unicode.upperCase.byCodepoint)
assert(isUpper(v) && !isLower(v));
}
/++
If $(D c) is a Unicode uppercase $(CHARACTER), then its lowercase equivalent
is returned. Otherwise $(D c) is returned.
Warning: certain alphabets like German and Greek have no 1:1
upper-lower mapping. Use overload of toLower which takes full string instead.
+/
@safe pure nothrow
dchar toLower(dchar c)
{
// optimize ASCII case
if(c < 0xAA)
{
if(c < 'A')
return c;
if(c <= 'Z')
return c + 32;
return c;
}
size_t idx = toLowerIndex(c);
if(idx < MAX_SIMPLE_LOWER)
{
return toLowerTab(idx);
}
return c;
}
//TODO: Hidden for now, needs better API.
//Other transforms could use better API as well, but this one is a new primitive.
@safe pure nothrow
private dchar toTitlecase(dchar c)
{
// optimize ASCII case
if(c < 0xAA)
{
if(c < 'a')
return c;
if(c <= 'z')
return c - 32;
return c;
}
size_t idx = toTitleIndex(c);
if(idx < MAX_SIMPLE_TITLE)
{
return toTitleTab(idx);
}
return c;
}
private alias UpperTriple = TypeTuple!(toUpperIndex, MAX_SIMPLE_UPPER, toUpperTab);
private alias LowerTriple = TypeTuple!(toLowerIndex, MAX_SIMPLE_LOWER, toLowerTab);
// generic toUpper/toLower on whole string, creates new or returns as is
private S toCase(alias indexFn, uint maxIdx, alias tableFn, S)(S s) @trusted pure
if(isSomeString!S)
{
foreach(i, dchar cOuter; s)
{
ushort idx = indexFn(cOuter);
if(idx == ushort.max)
continue;
auto result = s[0 .. i].dup;
foreach(dchar c; s[i .. $])
{
idx = indexFn(c);
if(idx == ushort.max)
result ~= c;
else if(idx < maxIdx)
{
c = tableFn(idx);
result ~= c;
}
else
{
auto val = tableFn(idx);
// unpack length + codepoint
uint len = val>>24;
result ~= cast(dchar)(val & 0xFF_FFFF);
foreach(j; idx+1..idx+len)
result ~= tableFn(j);
}
}
return cast(S) result;
}
return s;
}
// TODO: helper, I wish std.utf was more flexible (and stright)
private size_t encodeTo(char[] buf, size_t idx, dchar c) @trusted pure
{
if (c <= 0x7F)
{
buf[idx] = cast(char)c;
idx++;
}
else if (c <= 0x7FF)
{
buf[idx] = cast(char)(0xC0 | (c >> 6));
buf[idx+1] = cast(char)(0x80 | (c & 0x3F));
idx += 2;
}
else if (c <= 0xFFFF)
{
buf[idx] = cast(char)(0xE0 | (c >> 12));
buf[idx+1] = cast(char)(0x80 | ((c >> 6) & 0x3F));
buf[idx+2] = cast(char)(0x80 | (c & 0x3F));
idx += 3;
}
else if (c <= 0x10FFFF)
{
buf[idx] = cast(char)(0xF0 | (c >> 18));
buf[idx+1] = cast(char)(0x80 | ((c >> 12) & 0x3F));
buf[idx+2] = cast(char)(0x80 | ((c >> 6) & 0x3F));
buf[idx+3] = cast(char)(0x80 | (c & 0x3F));
idx += 4;
}
else
assert(0);
return idx;
}
unittest
{
char[] s = "abcd".dup;
size_t i = 0;
i = encodeTo(s, i, 'X');
assert(s == "Xbcd");
i = encodeTo(s, i, cast(dchar)'\u00A9');
assert(s == "X\xC2\xA9d");
}
// TODO: helper, I wish std.utf was more flexible (and stright)
private size_t encodeTo(wchar[] buf, size_t idx, dchar c) @trusted pure
{
import std.utf;
if (c <= 0xFFFF)
{
if (0xD800 <= c && c <= 0xDFFF)
throw (new UTFException("Encoding an isolated surrogate code point in UTF-16")).setSequence(c);
buf[idx] = cast(wchar)c;
idx++;
}
else if (c <= 0x10FFFF)
{
buf[idx] = cast(wchar)((((c - 0x10000) >> 10) & 0x3FF) + 0xD800);
buf[idx+1] = cast(wchar)(((c - 0x10000) & 0x3FF) + 0xDC00);
idx += 2;
}
else
assert(0);
return idx;
}
private size_t encodeTo(dchar[] buf, size_t idx, dchar c) @trusted pure
{
buf[idx] = c;
idx++;
return idx;
}
private void toCaseInPlace(alias indexFn, uint maxIdx, alias tableFn, C)(ref C[] s) @trusted pure
if (is(C == char) || is(C == wchar) || is(C == dchar))
{
import std.utf;
size_t curIdx = 0;
size_t destIdx = 0;
alias slowToCase = toCaseInPlaceAlloc!(indexFn, maxIdx, tableFn);
size_t lastUnchanged = 0;
// in-buffer move of bytes to a new start index
// the trick is that it may not need to copy at all
static size_t moveTo(C[] str, size_t dest, size_t from, size_t to)
{
// Interestingly we may just bump pointer for a while
// then have to copy if a re-cased char was smaller the original
// later we may regain pace with char that got bigger
// In the end it sometimes flip-flops between the 2 cases below
if(dest == from)
return to;
// got to copy
foreach(C c; str[from..to])
str[dest++] = c;
return dest;
}
while(curIdx != s.length)
{
size_t startIdx = curIdx;
dchar ch = decode(s, curIdx);
// TODO: special case for ASCII
auto caseIndex = indexFn(ch);
if(caseIndex == ushort.max) // unchanged, skip over
{
continue;
}
else if(caseIndex < maxIdx) // 1:1 codepoint mapping
{
// previous cased chars had the same length as uncased ones
// thus can just adjust pointer
destIdx = moveTo(s, destIdx, lastUnchanged, startIdx);
lastUnchanged = curIdx;
dchar cased = tableFn(caseIndex);
auto casedLen = codeLength!C(cased);
if(casedLen + destIdx > curIdx) // no place to fit cased char
{
// switch to slow codepath, where we allocate
return slowToCase(s, startIdx, destIdx);
}
else
{
destIdx = encodeTo(s, destIdx, cased);
}
}
else // 1:m codepoint mapping, slow codepath
{
destIdx = moveTo(s, destIdx, lastUnchanged, startIdx);
lastUnchanged = curIdx;
return slowToCase(s, startIdx, destIdx);
}
assert(destIdx <= curIdx);
}
if(lastUnchanged != s.length)
{
destIdx = moveTo(s, destIdx, lastUnchanged, s.length);
}
s = s[0..destIdx];
}
// helper to precalculate size of case-converted string
private template toCaseLength(alias indexFn, uint maxIdx, alias tableFn)
{
size_t toCaseLength(C)(in C[] str)
{
import std.utf;
size_t codeLen = 0;
size_t lastNonTrivial = 0;
size_t curIdx = 0;
while(curIdx != str.length)
{
size_t startIdx = curIdx;
dchar ch = decode(str, curIdx);
ushort caseIndex = indexFn(ch);
if(caseIndex == ushort.max)
continue;
else if(caseIndex < maxIdx)
{
codeLen += startIdx - lastNonTrivial;
lastNonTrivial = curIdx;
dchar cased = tableFn(caseIndex);
codeLen += codeLength!C(cased);
}
else
{
codeLen += startIdx - lastNonTrivial;
lastNonTrivial = curIdx;
auto val = tableFn(caseIndex);
auto len = val>>24;
dchar cased = val & 0xFF_FFFF;
codeLen += codeLength!C(cased);
foreach(j; caseIndex+1..caseIndex+len)
codeLen += codeLength!C(tableFn(j));
}
}
if(lastNonTrivial != str.length)
codeLen += str.length - lastNonTrivial;
return codeLen;
}
}
unittest
{
import std.conv;
alias toLowerLength = toCaseLength!(LowerTriple);
assert(toLowerLength("abcd") == 4);
assert(toLowerLength("аБВгд456") == 10+3);
}
// slower code path that preallocates and then copies
// case-converted stuf to the new string
private template toCaseInPlaceAlloc(alias indexFn, uint maxIdx, alias tableFn)
{
void toCaseInPlaceAlloc(C)(ref C[] s, size_t curIdx,
size_t destIdx) @trusted pure
if (is(C == char) || is(C == wchar) || is(C == dchar))
{
import std.utf : decode;
alias caseLength = toCaseLength!(indexFn, maxIdx, tableFn);
auto trueLength = destIdx + caseLength(s[curIdx..$]);
C[] ns = new C[trueLength];
ns[0..destIdx] = s[0..destIdx];
size_t lastUnchanged = curIdx;
while(curIdx != s.length)
{
size_t startIdx = curIdx; // start of current codepoint
dchar ch = decode(s, curIdx);
auto caseIndex = indexFn(ch);
if(caseIndex == ushort.max) // skip over
{
continue;
}
else if(caseIndex < maxIdx) // 1:1 codepoint mapping
{
dchar cased = tableFn(caseIndex);
auto toCopy = startIdx - lastUnchanged;
ns[destIdx .. destIdx+toCopy] = s[lastUnchanged .. startIdx];
lastUnchanged = curIdx;
destIdx += toCopy;
destIdx = encodeTo(ns, destIdx, cased);
}
else // 1:m codepoint mapping, slow codepath
{
auto toCopy = startIdx - lastUnchanged;
ns[destIdx .. destIdx+toCopy] = s[lastUnchanged .. startIdx];
lastUnchanged = curIdx;
destIdx += toCopy;
auto val = tableFn(caseIndex);
// unpack length + codepoint
uint len = val>>24;
destIdx = encodeTo(ns, destIdx, cast(dchar)(val & 0xFF_FFFF));
foreach(j; caseIndex+1..caseIndex+len)
destIdx = encodeTo(ns, destIdx, tableFn(j));
}
}
if(lastUnchanged != s.length)
{
auto toCopy = s.length - lastUnchanged;
ns[destIdx..destIdx+toCopy] = s[lastUnchanged..$];
destIdx += toCopy;
}
assert(ns.length == destIdx);
s = ns;
}
}
/++
Converts $(D s) to lowercase (by performing Unicode lowercase mapping) in place.
For a few characters string length may increase after the transformation,
in such a case the function reallocates exactly once.
If $(D s) does not have any uppercase characters, then $(D s) is unaltered.
+/
void toLowerInPlace(C)(ref C[] s) @trusted pure
if (is(C == char) || is(C == wchar) || is(C == dchar))
{
toCaseInPlace!(LowerTriple)(s);
}
// overloads for the most common cases to reduce compile time
@safe pure /*TODO nothrow*/
{
void toLowerInPlace(ref char[] s)
{ toLowerInPlace!char(s); }
void toLowerInPlace(ref wchar[] s)
{ toLowerInPlace!wchar(s); }
void toLowerInPlace(ref dchar[] s)
{ toLowerInPlace!dchar(s); }
}
/++
Converts $(D s) to uppercase (by performing Unicode uppercase mapping) in place.
For a few characters string length may increase after the transformation,
in such a case the function reallocates exactly once.
If $(D s) does not have any lowercase characters, then $(D s) is unaltered.
+/
void toUpperInPlace(C)(ref C[] s) @trusted pure
if (is(C == char) || is(C == wchar) || is(C == dchar))
{
toCaseInPlace!(UpperTriple)(s);
}
// overloads for the most common cases to reduce compile time/code size
@safe pure /*TODO nothrow*/
{
void toUpperInPlace(ref char[] s)
{ toUpperInPlace!char(s); }
void toUpperInPlace(ref wchar[] s)
{ toUpperInPlace!wchar(s); }
void toUpperInPlace(ref dchar[] s)
{ toUpperInPlace!dchar(s); }
}
/++
Returns a string which is identical to $(D s) except that all of its
characters are converted to lowercase (by preforming Unicode lowercase mapping).
If none of $(D s) characters were affected, then $(D s) itself is returned.
+/
S toLower(S)(S s) @trusted pure
if(isSomeString!S)
{
return toCase!(LowerTriple)(s);
}
// overloads for the most common cases to reduce compile time
@safe pure /*TODO nothrow*/
{
string toLower(string s)
{ return toLower!string(s); }
wstring toLower(wstring s)
{ return toLower!wstring(s); }
dstring toLower(dstring s)
{ return toLower!dstring(s); }
}
@trusted unittest //@@@BUG std.format is not @safe
{
import std.string : format;
foreach(ch; 0..0x80)
assert(std.ascii.toLower(ch) == toLower(ch));
assert(toLower('Я') == 'я');
assert(toLower('Δ') == 'δ');
foreach(ch; unicode.upperCase.byCodepoint)
{
dchar low = ch.toLower();
assert(low == ch || isLower(low), format("%s -> %s", ch, low));
}
assert(toLower("АЯ") == "ая");
assert("\u1E9E".toLower == "\u00df");
assert("\u00df".toUpper == "SS");
}
//bugzilla 9629
unittest
{
wchar[] test = "hello þ world"w.dup;
auto piece = test[6..7];
toUpperInPlace(piece);
assert(test == "hello Þ world");
}
unittest
{
string s1 = "FoL";
string s2 = toLower(s1);
assert(cmp(s2, "fol") == 0, s2);
assert(s2 != s1);
char[] s3 = s1.dup;
toLowerInPlace(s3);
assert(s3 == s2);
s1 = "A\u0100B\u0101d";
s2 = toLower(s1);
s3 = s1.dup;
assert(cmp(s2, "a\u0101b\u0101d") == 0);
assert(s2 !is s1);
toLowerInPlace(s3);
assert(s3 == s2);
s1 = "A\u0460B\u0461d";
s2 = toLower(s1);
s3 = s1.dup;
assert(cmp(s2, "a\u0461b\u0461d") == 0);
assert(s2 !is s1);
toLowerInPlace(s3);
assert(s3 == s2);
s1 = "\u0130";
s2 = toLower(s1);
s3 = s1.dup;
assert(s2 == "i\u0307");
assert(s2 !is s1);
toLowerInPlace(s3);
assert(s3 == s2);
// Test on wchar and dchar strings.
assert(toLower("Some String"w) == "some string"w);
assert(toLower("Some String"d) == "some string"d);
}
/++
If $(D c) is a Unicode lowercase $(CHARACTER), then its uppercase equivalent
is returned. Otherwise $(D c) is returned.
Warning:
Certain alphabets like German and Greek have no 1:1
upper-lower mapping. Use overload of toUpper which takes full string instead.
+/
@safe pure nothrow
dchar toUpper(dchar c)
{
// optimize ASCII case
if(c < 0xAA)
{
if(c < 'a')
return c;
if(c <= 'z')
return c - 32;
return c;
}
size_t idx = toUpperIndex(c);
if(idx < MAX_SIMPLE_UPPER)
{
return toUpperTab(idx);
}
return c;
}
@trusted unittest
{
import std.string : format;
foreach(ch; 0..0x80)
assert(std.ascii.toUpper(ch) == toUpper(ch));
assert(toUpper('я') == 'Я');
assert(toUpper('δ') == 'Δ');
foreach(ch; unicode.lowerCase.byCodepoint)
{
dchar up = ch.toUpper();
assert(up == ch || isUpper(up), format("%s -> %s", ch, up));
}
}
/++
Returns a string which is identical to $(D s) except that all of its
characters are converted to uppercase (by preforming Unicode uppercase mapping).
If none of $(D s) characters were affected, then $(D s) itself is returned.
+/
S toUpper(S)(S s) @trusted pure
if(isSomeString!S)
{
return toCase!(UpperTriple)(s);
}
// overloads for the most common cases to reduce compile time
@safe pure /*TODO nothrow*/
{
string toUpper(string s)
{ return toUpper!string(s); }
wstring toUpper(wstring s)
{ return toUpper!wstring(s); }
dstring toUpper(dstring s)
{ return toUpper!dstring(s); }
}
unittest
{
string s1 = "FoL";
string s2;
char[] s3;
s2 = toUpper(s1);
s3 = s1.dup; toUpperInPlace(s3);
assert(s3 == s2, s3);
assert(cmp(s2, "FOL") == 0);
assert(s2 !is s1);
s1 = "a\u0100B\u0101d";
s2 = toUpper(s1);
s3 = s1.dup; toUpperInPlace(s3);
assert(s3 == s2);
assert(cmp(s2, "A\u0100B\u0100D") == 0);
assert(s2 !is s1);
s1 = "a\u0460B\u0461d";
s2 = toUpper(s1);
s3 = s1.dup; toUpperInPlace(s3);
assert(s3 == s2);
assert(cmp(s2, "A\u0460B\u0460D") == 0);
assert(s2 !is s1);
}
unittest
{
static void doTest(C)(const(C)[] s, const(C)[] trueUp, const(C)[] trueLow)
{
import std.string : format;
string diff = "src: %( %x %)\nres: %( %x %)\ntru: %( %x %)";
auto low = s.toLower() , up = s.toUpper();
auto lowInp = s.dup, upInp = s.dup;
lowInp.toLowerInPlace();
upInp.toUpperInPlace();
assert(low == trueLow, format(diff, low, trueLow));
assert(up == trueUp, format(diff, up, trueUp));
assert(lowInp == trueLow,
format(diff, cast(ubyte[])s, cast(ubyte[])lowInp, cast(ubyte[])trueLow));
assert(upInp == trueUp,
format(diff, cast(ubyte[])s, cast(ubyte[])upInp, cast(ubyte[])trueUp));
}
foreach(S; TypeTuple!(dstring, wstring, string))
{
S easy = "123";
S good = "abCФеж";
S awful = "\u0131\u023f\u2126";
S wicked = "\u0130\u1FE2";
auto options = [easy, good, awful, wicked];
S[] lower = ["123", "abcфеж", "\u0131\u023f\u03c9", "i\u0307\u1Fe2"];
S[] upper = ["123", "ABCФЕЖ", "I\u2c7e\u2126", "\u0130\u03A5\u0308\u0300"];
foreach(val; TypeTuple!(easy, good))
{
auto e = val.dup;
auto g = e;
e.toUpperInPlace();
assert(e is g);
e.toLowerInPlace();
assert(e is g);
}
foreach(i, v; options)
{
doTest(v, upper[i], lower[i]);
}
// a few combinatorial runs
foreach(i; 0..options.length)
foreach(j; i..options.length)
foreach(k; j..options.length)
{
auto sample = options[i] ~ options[j] ~ options[k];
auto sample2 = options[k] ~ options[j] ~ options[i];
doTest(sample, upper[i] ~ upper[j] ~ upper[k],
lower[i] ~ lower[j] ~ lower[k]);
doTest(sample2, upper[k] ~ upper[j] ~ upper[i],
lower[k] ~ lower[j] ~ lower[i]);
}
}
}
/++
Returns whether $(D c) is a Unicode alphabetic $(CHARACTER)
(general Unicode category: Alphabetic).
+/
@safe pure nothrow
bool isAlpha(dchar c)
{
// optimization
if(c < 0xAA)
{
size_t x = c - 'A';
if(x <= 'Z' - 'A')
return true;
else
{
x = c - 'a';
if(x <= 'z'-'a')
return true;
}
return false;
}
return alphaTrie[c];
}
@safe unittest
{
auto alpha = unicode("Alphabetic");
foreach(ch; alpha.byCodepoint)
assert(isAlpha(ch));
foreach(ch; 0..0x4000)
assert((ch in alpha) == isAlpha(ch));
}
/++
Returns whether $(D c) is a Unicode mark
(general Unicode category: Mn, Me, Mc).
+/
@safe pure nothrow
bool isMark(dchar c)
{
return markTrie[c];
}
@safe unittest
{
auto mark = unicode("Mark");
foreach(ch; mark.byCodepoint)
assert(isMark(ch));
foreach(ch; 0..0x4000)
assert((ch in mark) == isMark(ch));
}
/++
Returns whether $(D c) is a Unicode numerical $(CHARACTER)
(general Unicode category: Nd, Nl, No).
+/
@safe pure nothrow
bool isNumber(dchar c)
{
return numberTrie[c];
}
@safe unittest
{
auto n = unicode("N");
foreach(ch; n.byCodepoint)
assert(isNumber(ch));
foreach(ch; 0..0x4000)
assert((ch in n) == isNumber(ch));
}
/++
Returns whether $(D c) is a Unicode punctuation $(CHARACTER)
(general Unicode category: Pd, Ps, Pe, Pc, Po, Pi, Pf).
+/
@safe pure nothrow
bool isPunctuation(dchar c)
{
return punctuationTrie[c];
}
unittest
{
assert(isPunctuation('\u0021'));
assert(isPunctuation('\u0028'));
assert(isPunctuation('\u0029'));
assert(isPunctuation('\u002D'));
assert(isPunctuation('\u005F'));
assert(isPunctuation('\u00AB'));
assert(isPunctuation('\u00BB'));
foreach(ch; unicode("P").byCodepoint)
assert(isPunctuation(ch));
}
/++
Returns whether $(D c) is a Unicode symbol $(CHARACTER)
(general Unicode category: Sm, Sc, Sk, So).
+/
@safe pure nothrow
bool isSymbol(dchar c)
{
return symbolTrie[c];
}
unittest
{
import std.string;
assert(isSymbol('\u0024'));
assert(isSymbol('\u002B'));
assert(isSymbol('\u005E'));
assert(isSymbol('\u00A6'));
foreach(ch; unicode("S").byCodepoint)
assert(isSymbol(ch), format("%04x", ch));
}
/++
Returns whether $(D c) is a Unicode space $(CHARACTER)
(general Unicode category: Zs)
Note: This doesn't include '\n', '\r', \t' and other non-space $(CHARACTER).
For commonly used less strict semantics see $(LREF isWhite).
+/
@safe pure nothrow
bool isSpace(dchar c)
{
return isSpaceGen(c);
}
unittest
{
assert(isSpace('\u0020'));
auto space = unicode.Zs;
foreach(ch; space.byCodepoint)
assert(isSpace(ch));
foreach(ch; 0..0x1000)
assert(isSpace(ch) == space[ch]);
}
/++
Returns whether $(D c) is a Unicode graphical $(CHARACTER)
(general Unicode category: L, M, N, P, S, Zs).
+/
@safe pure nothrow
bool isGraphical(dchar c)
{
return graphicalTrie[c];
}
unittest
{
auto set = unicode("Graphical");
import std.string;
foreach(ch; set.byCodepoint)
assert(isGraphical(ch), format("%4x", ch));
foreach(ch; 0..0x4000)
assert((ch in set) == isGraphical(ch));
}
/++
Returns whether $(D c) is a Unicode control $(CHARACTER)
(general Unicode category: Cc).
+/
@safe pure nothrow
bool isControl(dchar c)
{
return isControlGen(c);
}
unittest
{
assert(isControl('\u0000'));
assert(isControl('\u0081'));
assert(!isControl('\u0100'));
auto cc = unicode.Cc;
foreach(ch; cc.byCodepoint)
assert(isControl(ch));
foreach(ch; 0..0x1000)
assert(isControl(ch) == cc[ch]);
}
/++
Returns whether $(D c) is a Unicode formatting $(CHARACTER)
(general Unicode category: Cf).
+/
@safe pure nothrow
bool isFormat(dchar c)
{
return isFormatGen(c);
}
unittest
{
assert(isFormat('\u00AD'));
foreach(ch; unicode("Format").byCodepoint)
assert(isFormat(ch));
}
// code points for private use, surrogates are not likely to change in near feature
// if need be they can be generated from unicode data as well
/++
Returns whether $(D c) is a Unicode Private Use $(CODEPOINT)
(general Unicode category: Co).
+/
@safe pure nothrow
bool isPrivateUse(dchar c)
{
return (0x00_E000 <= c && c <= 0x00_F8FF)
|| (0x0F_0000 <= c && c <= 0x0F_FFFD)
|| (0x10_0000 <= c && c <= 0x10_FFFD);
}
/++
Returns whether $(D c) is a Unicode surrogate $(CODEPOINT)
(general Unicode category: Cs).
+/
@safe pure nothrow
bool isSurrogate(dchar c)
{
return (0xD800 <= c && c <= 0xDFFF);
}
/++
Returns whether $(D c) is a Unicode high surrogate (lead surrogate).
+/
@safe pure nothrow
bool isSurrogateHi(dchar c)
{
return (0xD800 <= c && c <= 0xDBFF);
}
/++
Returns whether $(D c) is a Unicode low surrogate (trail surrogate).
+/
@safe pure nothrow
bool isSurrogateLo(dchar c)
{
return (0xDC00 <= c && c <= 0xDFFF);
}
/++
Returns whether $(D c) is a Unicode non-character i.e.
a $(CODEPOINT) with no assigned abstract character.
(general Unicode category: Cn)
+/
@safe pure nothrow
bool isNonCharacter(dchar c)
{
return nonCharacterTrie[c];
}
unittest
{
auto set = unicode("Cn");
foreach(ch; set.byCodepoint)
assert(isNonCharacter(ch));
}
private:
// load static data from pre-generated tables into usable datastructures
@safe auto asSet(const (ubyte)[] compressed)
{
return CodepointSet(decompressIntervals(compressed));
}
@safe pure nothrow auto asTrie(T...)(in TrieEntry!T e)
{
return const(CodepointTrie!T)(e.offsets, e.sizes, e.data);
}
@safe pure nothrow @property
{
// It's important to use auto return here, so that the compiler
// only runs semantic on the return type if the function gets
// used. Also these are functions rather than templates to not
// increase the object size of the caller.
auto lowerCaseTrie() { static immutable res = asTrie(lowerCaseTrieEntries); return res; }
auto upperCaseTrie() { static immutable res = asTrie(upperCaseTrieEntries); return res; }
auto simpleCaseTrie() { static immutable res = asTrie(simpleCaseTrieEntries); return res; }
auto fullCaseTrie() { static immutable res = asTrie(fullCaseTrieEntries); return res; }
auto alphaTrie() { static immutable res = asTrie(alphaTrieEntries); return res; }
auto markTrie() { static immutable res = asTrie(markTrieEntries); return res; }
auto numberTrie() { static immutable res = asTrie(numberTrieEntries); return res; }
auto punctuationTrie() { static immutable res = asTrie(punctuationTrieEntries); return res; }
auto symbolTrie() { static immutable res = asTrie(symbolTrieEntries); return res; }
auto graphicalTrie() { static immutable res = asTrie(graphicalTrieEntries); return res; }
auto nonCharacterTrie() { static immutable res = asTrie(nonCharacterTrieEntries); return res; }
//normalization quick-check tables
auto nfcQCTrie()
{
import std.internal.unicode_norm;
static immutable res = asTrie(nfcQCTrieEntries);
return res;
}
auto nfdQCTrie()
{
import std.internal.unicode_norm;
static immutable res = asTrie(nfdQCTrieEntries);
return res;
}
auto nfkcQCTrie()
{
import std.internal.unicode_norm;
static immutable res = asTrie(nfkcQCTrieEntries);
return res;
}
auto nfkdQCTrie()
{
import std.internal.unicode_norm;
static immutable res = asTrie(nfkdQCTrieEntries);
return res;
}
//grapheme breaking algorithm tables
auto mcTrie()
{
import std.internal.unicode_grapheme;
static immutable res = asTrie(mcTrieEntries);
return res;
}
auto graphemeExtendTrie()
{
import std.internal.unicode_grapheme;
static immutable res = asTrie(graphemeExtendTrieEntries);
return res;
}
auto hangLV()
{
import std.internal.unicode_grapheme;
static immutable res = asTrie(hangulLVTrieEntries);
return res;
}
auto hangLVT()
{
import std.internal.unicode_grapheme;
static immutable res = asTrie(hangulLVTTrieEntries);
return res;
}
// tables below are used for composition/decomposition
auto combiningClassTrie()
{
import std.internal.unicode_comp;
static immutable res = asTrie(combiningClassTrieEntries);
return res;
}
auto compatMappingTrie()
{
import std.internal.unicode_decomp;
static immutable res = asTrie(compatMappingTrieEntries);
return res;
}
auto canonMappingTrie()
{
import std.internal.unicode_decomp;
static immutable res = asTrie(canonMappingTrieEntries);
return res;
}
auto compositionJumpTrie()
{
import std.internal.unicode_comp;
static immutable res = asTrie(compositionJumpTrieEntries);
return res;
}
//case conversion tables
auto toUpperIndexTrie() { static immutable res = asTrie(toUpperIndexTrieEntries); return res; }
auto toLowerIndexTrie() { static immutable res = asTrie(toLowerIndexTrieEntries); return res; }
auto toTitleIndexTrie() { static immutable res = asTrie(toTitleIndexTrieEntries); return res; }
}
}// version(!std_uni_bootstrap)
| D |
/**
Utilties related to Discord Guild sharding.
*/
module dscord.util.sharding;
import dscord.types;
/// Returns the shard number a given snowflake is on (given the number of shards)
ushort shardNumber(Snowflake id, ushort numShards) {
return (id >> 22) % numShards;
}
| D |
module dwt.internal.mozilla.nsICookieManager;
import dwt.internal.mozilla.Common;
import dwt.internal.mozilla.nsID;
import dwt.internal.mozilla.nsISupports;
import dwt.internal.mozilla.nsISimpleEnumerator;
import dwt.internal.mozilla.nsStringAPI;
const char[] NS_ICOOKIEMANAGER_IID_STR = "aaab6710-0f2c-11d5-a53b-0010a401eb10";
const nsIID NS_ICOOKIEMANAGER_IID=
{
0xaaab6710, 0x0f2c, 0x11d5,
[ 0xa5, 0x3b, 0x00, 0x10, 0xa4, 0x01, 0xeb, 0x10 ]
};
interface nsICookieManager :
nsISupports
{
static const char[] IID_STR = NS_ICOOKIEMANAGER_IID_STR;
static const nsIID IID = NS_ICOOKIEMANAGER_IID;
extern(System):
nsresult RemoveAll();
nsresult GetEnumerator(nsISimpleEnumerator *aEnumerator);
nsresult Remove(nsACString * aDomain, nsACString * aName, nsACString * aPath, PRBool aBlocked);
}
| D |
/*
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
module derelict.purple.log;
import derelict.glib.gtypes;
import derelict.glib.glibconfig;
import derelict.glib.ghash;
import derelict.glib.glist;
import derelict.purple.conversation;
import derelict.purple.account;
import core.stdc.time;
import core.stdc.config;
import core.stdc.stdio;
extern (C):
alias _PurpleLog PurpleLog;
alias _PurpleLogLogger PurpleLogLogger;
alias _PurpleLogCommonLoggerData PurpleLogCommonLoggerData;
alias _PurpleLogSet PurpleLogSet;
alias _Anonymous_0 PurpleLogType;
alias _Anonymous_1 PurpleLogReadFlags;
alias void function (_GHashTable*, _PurpleLogSet*) PurpleLogSetCallback;
enum _Anonymous_0
{
PURPLE_LOG_IM = 0,
PURPLE_LOG_CHAT = 1,
PURPLE_LOG_SYSTEM = 2
}
enum _Anonymous_1
{
PURPLE_LOG_READ_NO_NEWLINE = 1
}
struct _PurpleLogLogger
{
char* name;
char* id;
void function (PurpleLog*) create;
gsize function (PurpleLog*, PurpleMessageFlags, const(char)*, time_t, const(char)*) write;
void function (PurpleLog*) finalize;
GList* function (PurpleLogType, const(char)*, PurpleAccount*) list;
char* function (PurpleLog*, PurpleLogReadFlags*) read;
int function (PurpleLog*) size;
int function (PurpleLogType, const(char)*, PurpleAccount*) total_size;
GList* function (PurpleAccount*) list_syslog;
void function (PurpleLogSetCallback, GHashTable*) get_log_sets;
gboolean function (PurpleLog*) remove;
gboolean function (PurpleLog*) is_deletable;
void function () _purple_reserved1;
void function () _purple_reserved2;
void function () _purple_reserved3;
void function () _purple_reserved4;
}
struct _PurpleLog
{
PurpleLogType type;
char* name;
PurpleAccount* account;
PurpleConversation* conv;
time_t time;
PurpleLogLogger* logger;
void* logger_data;
core.stdc.time.tm* tm;
}
struct _PurpleLogCommonLoggerData
{
char* path;
FILE* file;
void* extra_data;
}
struct _PurpleLogSet
{
PurpleLogType type;
char* name;
PurpleAccount* account;
gboolean buddy;
char* normalized_name;
}
version(Derelict_Link_Static)
{
extern( C ) nothrow
{
PurpleLog* purple_log_new(PurpleLogType type, const(char)* name, PurpleAccount* account, PurpleConversation* conv, time_t time, const(tm)* tm);
void purple_log_free(PurpleLog* log);
void purple_log_write(PurpleLog* log, PurpleMessageFlags type, const(char)* from, time_t time, const(char)* message);
char* purple_log_read(PurpleLog* log, PurpleLogReadFlags* flags);
GList* purple_log_get_logs(PurpleLogType type, const(char)* name, PurpleAccount* account);
GHashTable* purple_log_get_log_sets();
GList* purple_log_get_system_logs(PurpleAccount* account);
int purple_log_get_size(PurpleLog* log);
int purple_log_get_total_size(PurpleLogType type, const(char)* name, PurpleAccount* account);
int purple_log_get_activity_score(PurpleLogType type, const(char)* name, PurpleAccount* account);
gboolean purple_log_is_deletable(PurpleLog* log);
gboolean purple_log_delete(PurpleLog* log);
char* purple_log_get_log_dir(PurpleLogType type, const(char)* name, PurpleAccount* account);
gint purple_log_compare(gconstpointer y, gconstpointer z);
gint purple_log_set_compare(gconstpointer y, gconstpointer z);
void purple_log_set_free(PurpleLogSet* set);
void purple_log_common_writer(PurpleLog* log, const(char)* ext);
GList* purple_log_common_lister(PurpleLogType type, const(char)* name, PurpleAccount* account, const(char)* ext, PurpleLogLogger* logger);
int purple_log_common_total_sizer(PurpleLogType type, const(char)* name, PurpleAccount* account, const(char)* ext);
int purple_log_common_sizer(PurpleLog* log);
gboolean purple_log_common_deleter(PurpleLog* log);
gboolean purple_log_common_is_deletable(PurpleLog* log);
PurpleLogLogger* purple_log_logger_new(const(char)* id, const(char)* name, int functions, ...);
void purple_log_logger_free(PurpleLogLogger* logger);
void purple_log_logger_add(PurpleLogLogger* logger);
void purple_log_logger_remove(PurpleLogLogger* logger);
void purple_log_logger_set(PurpleLogLogger* logger);
PurpleLogLogger* purple_log_logger_get();
GList* purple_log_logger_get_options();
void purple_log_init();
void* purple_log_get_handle();
void purple_log_uninit();
}
}
else
{
extern( C ) nothrow
{
alias da_purple_log_new = PurpleLog* function(PurpleLogType type, const(char)* name, PurpleAccount* account, PurpleConversation* conv, time_t time, const(tm)* tm);
alias da_purple_log_free = void function(PurpleLog* log);
alias da_purple_log_write = void function(PurpleLog* log, PurpleMessageFlags type, const(char)* from, time_t time, const(char)* message);
alias da_purple_log_read = char* function(PurpleLog* log, PurpleLogReadFlags* flags);
alias da_purple_log_get_logs = GList* function(PurpleLogType type, const(char)* name, PurpleAccount* account);
alias da_purple_log_get_log_sets = GHashTable* function();
alias da_purple_log_get_system_logs = GList* function(PurpleAccount* account);
alias da_purple_log_get_size = int function(PurpleLog* log);
alias da_purple_log_get_total_size = int function(PurpleLogType type, const(char)* name, PurpleAccount* account);
alias da_purple_log_get_activity_score = int function(PurpleLogType type, const(char)* name, PurpleAccount* account);
alias da_purple_log_is_deletable = gboolean function(PurpleLog* log);
alias da_purple_log_delete = gboolean function(PurpleLog* log);
alias da_purple_log_get_log_dir = char* function(PurpleLogType type, const(char)* name, PurpleAccount* account);
alias da_purple_log_compare = gint function(gconstpointer y, gconstpointer z);
alias da_purple_log_set_compare = gint function(gconstpointer y, gconstpointer z);
alias da_purple_log_set_free = void function(PurpleLogSet* set);
alias da_purple_log_common_writer = void function(PurpleLog* log, const(char)* ext);
alias da_purple_log_common_lister = GList* function(PurpleLogType type, const(char)* name, PurpleAccount* account, const(char)* ext, PurpleLogLogger* logger);
alias da_purple_log_common_total_sizer = int function(PurpleLogType type, const(char)* name, PurpleAccount* account, const(char)* ext);
alias da_purple_log_common_sizer = int function(PurpleLog* log);
alias da_purple_log_common_deleter = gboolean function(PurpleLog* log);
alias da_purple_log_common_is_deletable = gboolean function(PurpleLog* log);
alias da_purple_log_logger_new = PurpleLogLogger* function(const(char)* id, const(char)* name, int functions, ...);
alias da_purple_log_logger_free = void function(PurpleLogLogger* logger);
alias da_purple_log_logger_add = void function(PurpleLogLogger* logger);
alias da_purple_log_logger_remove = void function(PurpleLogLogger* logger);
alias da_purple_log_logger_set = void function(PurpleLogLogger* logger);
alias da_purple_log_logger_get = PurpleLogLogger* function();
alias da_purple_log_logger_get_options = GList* function();
alias da_purple_log_init = void function();
alias da_purple_log_get_handle = void* function();
alias da_purple_log_uninit = void function();
}
__gshared
{
da_purple_log_new purple_log_new;
da_purple_log_free purple_log_free;
da_purple_log_write purple_log_write;
da_purple_log_read purple_log_read;
da_purple_log_get_logs purple_log_get_logs;
da_purple_log_get_log_sets purple_log_get_log_sets;
da_purple_log_get_system_logs purple_log_get_system_logs;
da_purple_log_get_size purple_log_get_size;
da_purple_log_get_total_size purple_log_get_total_size;
da_purple_log_get_activity_score purple_log_get_activity_score;
da_purple_log_is_deletable purple_log_is_deletable;
da_purple_log_delete purple_log_delete;
da_purple_log_get_log_dir purple_log_get_log_dir;
da_purple_log_compare purple_log_compare;
da_purple_log_set_compare purple_log_set_compare;
da_purple_log_set_free purple_log_set_free;
da_purple_log_common_writer purple_log_common_writer;
da_purple_log_common_lister purple_log_common_lister;
da_purple_log_common_total_sizer purple_log_common_total_sizer;
da_purple_log_common_sizer purple_log_common_sizer;
da_purple_log_common_deleter purple_log_common_deleter;
da_purple_log_common_is_deletable purple_log_common_is_deletable;
da_purple_log_logger_new purple_log_logger_new;
da_purple_log_logger_free purple_log_logger_free;
da_purple_log_logger_add purple_log_logger_add;
da_purple_log_logger_remove purple_log_logger_remove;
da_purple_log_logger_set purple_log_logger_set;
da_purple_log_logger_get purple_log_logger_get;
da_purple_log_logger_get_options purple_log_logger_get_options;
da_purple_log_init purple_log_init;
da_purple_log_get_handle purple_log_get_handle;
da_purple_log_uninit purple_log_uninit;
}
}
| D |
struct S1 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S2 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S3 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S4 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S5 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S6 { bool opEquals(T : typeof(this))(T) { return false; } ~this(){} }
struct S7 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S8 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S9 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S10 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S11 { bool opEquals(T : typeof(this))(T) const { return false; }
int opCmp(T : typeof(this))(T) const { return 0; }
size_t toHash() const nothrow @safe { return 0; } }
struct S12 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S13 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S14 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S15 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S16 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S17 { bool opEquals(T : typeof(this))(T) { return false; } }
struct S18 { bool opEquals(T : typeof(this))(T) { return false; } }
void fun()()
{
{ auto a = new S1[1]; }
{ auto p = new S2(); }
{ alias P = S3*; auto p = new P; }
{ S4[int] aa; auto b = (aa == aa); }
{ S5[] a; a.length = 10; }
{ S6[] a; delete a; }
{ S7[] a = []; }
{ S8[] a = [S8.init]; }
{ S9[int] aa = [1:S9.init]; }
{ auto ti = typeid(S10[int]); }
{ auto ti = typeid(int[S11]); }
{ auto ti = typeid(S12[]); }
{ auto ti = typeid(S13*); }
{ auto ti = typeid(S14[3]); }
{ auto ti = typeid(S15 function()); }
{ auto ti = typeid(S16 delegate()); }
{ auto ti = typeid(void function(S17)); } // TypeInfo_Function doesn't have parameter types
{ auto ti = typeid(void delegate(S18)); } // ditto
}
struct B12146
{
bool opCmp(ubyte val) { return false; }
}
| D |
instance DIA_Biff_DI_EXIT(C_Info)
{
npc = DJG_713_Biff_DI;
nr = 999;
condition = DIA_Biff_DI_EXIT_Condition;
information = DIA_Biff_DI_EXIT_Info;
permanent = TRUE;
description = Dialog_Ende;
};
func int DIA_Biff_DI_EXIT_Condition()
{
return TRUE;
};
func void DIA_Biff_DI_EXIT_Info()
{
AI_StopProcessInfos(self);
};
instance DIA_Biff_DI_HALLO(C_Info)
{
npc = DJG_713_Biff_DI;
nr = 10;
condition = DIA_Biff_DI_HALLO_Condition;
information = DIA_Biff_DI_HALLO_Info;
important = TRUE;
};
func int DIA_Biff_DI_HALLO_Condition()
{
if(Npc_IsInState(self,ZS_Talk) && (Npc_IsDead(UndeadDragon) == FALSE))
{
return TRUE;
};
};
func void DIA_Biff_DI_HALLO_Info()
{
AI_Output(self,other,"DIA_Biff_DI_HALLO_07_00"); //И? Где все те сокровища, что ты мне обещал?
if(Npc_KnowsInfo(other,DIA_Biff_DI_ORKS) == FALSE)
{
AI_Output(other,self,"DIA_Biff_DI_HALLO_15_01"); //Что я там говорил тебе раньше, в море?
};
AI_Output(other,self,"DIA_Biff_DI_HALLO_15_02"); //Сейчас твоя задача - охранять корабль.
AI_Output(other,self,"DIA_Biff_DI_HALLO_15_03"); //Мне не улыбается плыть назад.
AI_Output(self,other,"DIA_Biff_DI_HALLO_07_04"); //Черт. Если бы я знал это заранее, я бы лучше остался в Хоринисе.
AI_StopProcessInfos(self);
};
instance DIA_Biff_DI_perm(C_Info)
{
npc = DJG_713_Biff_DI;
nr = 5;
condition = DIA_Biff_DI_perm_Condition;
information = DIA_Biff_DI_perm_Info;
permanent = TRUE;
description = "На борту все спокойно?";
};
func int DIA_Biff_DI_perm_Condition()
{
if(Npc_KnowsInfo(other,DIA_Biff_DI_HALLO) && (Npc_IsDead(UndeadDragon) == FALSE))
{
return TRUE;
};
};
func void DIA_Biff_DI_perm_Info()
{
AI_Output(other,self,"DIA_Biff_DI_perm_15_00"); //На борту все спокойно?
AI_Output(self,other,"DIA_Biff_DI_perm_07_01"); //Да, да. Все тихо.
AI_StopProcessInfos(self);
};
instance DIA_Biff_DI_ORKS(C_Info)
{
npc = DJG_713_Biff_DI;
nr = 5;
condition = DIA_Biff_DI_ORKS_Condition;
information = DIA_Biff_DI_ORKS_Info;
important = TRUE;
};
func int DIA_Biff_DI_ORKS_Condition()
{
if((Npc_GetDistToWP(self,"DI_SHIP_03") < 1000) && (ORkSturmDI == TRUE) && (Npc_IsDead(UndeadDragon) == FALSE))
{
return TRUE;
};
};
func void DIA_Biff_DI_ORKS_Info()
{
AI_Output(self,other,"DIA_Biff_DI_ORKS_07_00"); //Эти мерзкие твари!
AI_Output(other,self,"DIA_Biff_DI_ORKS_15_01"); //Черт, что ты делаешь здесь? Ты должен был охранять корабль.
AI_Output(self,other,"DIA_Biff_DI_ORKS_07_02"); //Да никуда он не денется.
B_GivePlayerXP(XP_Ambient);
AI_StopProcessInfos(self);
Npc_ExchangeRoutine(self,"Start");
};
instance DIA_Biff_DI_UNDEADDRGDEAD(C_Info)
{
npc = DJG_713_Biff_DI;
nr = 4;
condition = DIA_Biff_DI_UNDEADDRGDEAD_Condition;
information = DIA_Biff_DI_UNDEADDRGDEAD_Info;
important = TRUE;
};
func int DIA_Biff_DI_UNDEADDRGDEAD_Condition()
{
if(Npc_IsDead(UndeadDragon))
{
return TRUE;
};
};
func void DIA_Biff_DI_UNDEADDRGDEAD_Info()
{
AI_Output(self,other,"DIA_Biff_DI_UNDEADDRGDEAD_07_00"); //Что, все кончено?
AI_Output(other,self,"DIA_Biff_DI_UNDEADDRGDEAD_15_01"); //Вроде бы да.
AI_Output(self,other,"DIA_Biff_DI_UNDEADDRGDEAD_07_02"); //И теперь, могу я...
AI_Output(other,self,"DIA_Biff_DI_UNDEADDRGDEAD_15_03"); //Ты можешь перевернуть весь остров, ели хочешь.
AI_Output(self,other,"DIA_Biff_DI_UNDEADDRGDEAD_07_04"); //Отлично.
AI_StopProcessInfos(self);
Npc_ExchangeRoutine(self,"PlunderTempel");
};
instance DIA_Biff_DI_plunder(C_Info)
{
npc = DJG_713_Biff_DI;
nr = 5;
condition = DIA_Biff_DI_plunder_Condition;
information = DIA_Biff_DI_plunder_Info;
important = TRUE;
};
func int DIA_Biff_DI_plunder_Condition()
{
if(Npc_IsInState(self,ZS_Talk) && Npc_KnowsInfo(other,DIA_Biff_DI_plunder) && Npc_IsDead(UndeadDragon))
{
return TRUE;
};
};
func void DIA_Biff_DI_plunder_Info()
{
AI_Output(self,other,"DIA_Biff_DI_plunder_07_00"); //Черт. Не сейчас.
AI_StopProcessInfos(self);
};
instance DIA_Biff_DI_PICKPOCKET(C_Info)
{
npc = DJG_713_Biff_DI;
nr = 900;
condition = DIA_Biff_DI_PICKPOCKET_Condition;
information = DIA_Biff_DI_PICKPOCKET_Info;
permanent = TRUE;
description = Pickpocket_100;
};
func int DIA_Biff_DI_PICKPOCKET_Condition()
{
return C_Beklauen(92,450);
};
func void DIA_Biff_DI_PICKPOCKET_Info()
{
Info_ClearChoices(DIA_Biff_DI_PICKPOCKET);
Info_AddChoice(DIA_Biff_DI_PICKPOCKET,Dialog_Back,DIA_Biff_DI_PICKPOCKET_BACK);
Info_AddChoice(DIA_Biff_DI_PICKPOCKET,DIALOG_PICKPOCKET,DIA_Biff_DI_PICKPOCKET_DoIt);
};
func void DIA_Biff_DI_PICKPOCKET_DoIt()
{
B_Beklauen();
Info_ClearChoices(DIA_Biff_DI_PICKPOCKET);
};
func void DIA_Biff_DI_PICKPOCKET_BACK()
{
Info_ClearChoices(DIA_Biff_DI_PICKPOCKET);
};
| D |
/**
License:
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
Authors:
aermicioi
**/
module aermicioi.aedi.test.storage.storage;
| D |
unittest {}
unittest {}
unittest { assert(false); }
| D |
module dopus.lister.actions.focusnextaction;
import dopus.lister.actions;
static this()
{
ListerActions.register!FocusNextAction;
}
class FocusNextAction : SimpleAction
{
this(Lister lister)
{
super("focusNext", null);
addOnActivate(delegate(Variant, SimpleAction) {
import std.stdio : writeln;
writeln("focusNext");
});
}
}
| D |
/Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/NotFound.swift.o : /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Data+Base64URL.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/NestedData.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Thread+Async.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Deprecated.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/NotFound.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/ReflectionDecodable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/Decodable+Reflectable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Reflectable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/LosslessDataConvertible.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/File.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/MediaType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/OptionalType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Process+Execute.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/HeaderValue.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/DirectoryConfig.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CaseInsensitiveString.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Future+Unwrap.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/FutureEncoder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CoreError.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/String+Utilities.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/DataCoders.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/ReflectionDecoders.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Data+Hex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/BasicKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/MySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentMySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/NotFound~partial.swiftmodule : /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Data+Base64URL.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/NestedData.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Thread+Async.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Deprecated.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/NotFound.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/ReflectionDecodable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/Decodable+Reflectable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Reflectable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/LosslessDataConvertible.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/File.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/MediaType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/OptionalType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Process+Execute.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/HeaderValue.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/DirectoryConfig.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CaseInsensitiveString.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Future+Unwrap.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/FutureEncoder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CoreError.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/String+Utilities.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/DataCoders.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/ReflectionDecoders.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Data+Hex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/BasicKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/MySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentMySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/NotFound~partial.swiftdoc : /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Data+Base64URL.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/NestedData.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Thread+Async.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Deprecated.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/NotFound.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/ReflectionDecodable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/Decodable+Reflectable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Reflectable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/LosslessDataConvertible.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/File.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/MediaType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/OptionalType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Process+Execute.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/HeaderValue.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/DirectoryConfig.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CaseInsensitiveString.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Future+Unwrap.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/FutureEncoder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CoreError.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/String+Utilities.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/DataCoders.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/ReflectionDecoders.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Data+Hex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/BasicKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/MySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentMySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
/Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/NotFound~partial.swiftsourceinfo : /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Data+Base64URL.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/NestedData.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Thread+Async.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Deprecated.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/NotFound.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/ReflectionDecodable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/Decodable+Reflectable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Reflectable.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/LosslessDataConvertible.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/File.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/MediaType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/OptionalType.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Process+Execute.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/HeaderValue.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/DirectoryConfig.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CaseInsensitiveString.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Future+Unwrap.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/FutureEncoder.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CoreError.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/String+Utilities.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/DataCoders.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/CodableReflection/ReflectionDecoders.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Exports.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/Data+Hex.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/core/Sources/Core/BasicKey.swift /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/XPC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/ObjectiveC.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Combine.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Dispatch.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Darwin.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Foundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreFoundation.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/CoreGraphics.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/Swift.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/IOKit.swiftmodule/x86_64-apple-macos.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx/prebuilt-modules/SwiftOnoneSupport.swiftmodule/x86_64-apple-macos.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.swiftmodule /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/cpp_magic.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/ifaddrs-android.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIODarwin/include/CNIODarwin.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOAtomics/include/CNIOAtomics.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio/Sources/CNIOLinux/include/CNIOLinux.h /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOSHA1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOHTTP1.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/MySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentMySQL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CCryptoOpenSSL.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIO.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/HTTP.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOTLS.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOZlib.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Async.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Command.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Service.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Console.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Core.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentSQLite.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOPriorityQueue.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Logging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Debugging.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Routing.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/SQLBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/FluentBenchmark.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/COperatingSystem.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Random.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/URLEncodedForm.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIODarwin.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Authentication.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Validation.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Crypto.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/App.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOHTTPParser.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Vapor.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOAtomics.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOConcurrencyHelpers.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Bits.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOFoundationCompat.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/WebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/NIOWebSocket.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/DatabaseKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/TemplateKit.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Fluent.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/Multipart.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/x86_64-apple-macosx/debug/CNIOLinux.build/module.modulemap /Users/panartem/Developer/Study/Microservices-vapor/TILAppAcronyms/.build/checkouts/swift-nio-zlib-support/module.modulemap /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/xpc/XPC.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/objc/ObjectiveC.apinotes /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/apinotes/Dispatch.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/Darwin.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreGraphics.framework/Headers/CoreGraphics.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/ApplicationServices.framework/Headers/ApplicationServices.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreText.framework/Headers/CoreText.apinotes /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Security.framework/Headers/Security.apinotes
| D |
import std.stdio, std.range, std.string, std.algorithm, std.array,
std.ascii, std.typecons;
struct Digit {
immutable char d;
this(in char d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = d_; }
this(in int d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = cast(char)d_; } // Required cast.
alias d this;
}
enum size_t sudokuUnitSide = 3;
enum size_t sudokuSide = sudokuUnitSide ^^ 2; // Sudoku grid side.
alias SudokuTable = Digit[sudokuSide ^^ 2];
Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem)
pure nothrow {
alias Tgrid = uint;
Tgrid[SudokuTable.length] grid = void;
problem[].map!(c => c - '0').copy(grid[]);
// DMD doesn't inline this function. Performance loss.
Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc {
return grid[y * sudokuSide + x];
}
// DMD doesn't inline this function. If you want to retain
// the same performance as the C++ entry and you use the DMD
// compiler then this function must be manually inlined.
bool checkValidity(in Tgrid val, in size_t x, in size_t y)
pure nothrow @safe @nogc {
/*static*/ foreach (immutable i; staticIota!(0, sudokuSide))
if (access(i, y) == val || access(x, i) == val)
return false;
immutable startX = (x / sudokuUnitSide) * sudokuUnitSide;
immutable startY = (y / sudokuUnitSide) * sudokuUnitSide;
/*static*/ foreach (immutable i; staticIota!(0, sudokuUnitSide))
/*static*/ foreach (immutable j; staticIota!(0, sudokuUnitSide))
if (access(startX + j, startY + i) == val)
return false;
return true;
}
bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc {
if (pos == SudokuTable.length)
return true;
if (grid[pos] > 0)
return canPlaceNumbers(pos + 1);
foreach (immutable n; 1 .. sudokuSide + 1)
if (checkValidity(n, pos % sudokuSide, pos / sudokuSide)) {
grid[pos] = n;
if (canPlaceNumbers(pos + 1))
return true;
grid[pos] = 0;
}
return false;
}
if (canPlaceNumbers) {
//return typeof(return)(grid[]
// .map!(c => Digit(c + '0'))
// .array);
immutable SudokuTable result = grid[]
.map!(c => Digit(c + '0'))
.array;
return typeof(return)(result);
} else
return typeof(return)();
}
string representSudoku(in ref SudokuTable sudo)
pure nothrow @safe out(result) {
assert(result.countchars("1-9") == sudo[].count!q{a != '0'});
assert(result.countchars(".") == sudo[].count!q{a == '0'});
} body {
static assert(sudo.length == 81,
"representSudoku works only with a 9x9 Sudoku.");
string result;
foreach (immutable i; 0 .. sudokuSide) {
foreach (immutable j; 0 .. sudokuSide) {
result ~= sudo[i * sudokuSide + j];
result ~= ' ';
if (j == 2 || j == 5)
result ~= "| ";
}
result ~= "\n";
if (i == 2 || i == 5)
result ~= "------+-------+------\n";
}
return result.replace("0", ".");
}
void main() {
enum ValidateCells(string s) = s.map!Digit.array;
immutable SudokuTable problem = ValidateCells!("
850002400
720000009
004000000
000107002
305000900
040000000
000080070
017000000
000036040".removechars(whitespace));
problem.representSudoku.writeln;
immutable solution = problem.sudokuSolver;
if (solution.isNull)
writeln("Unsolvable!");
else
solution.get.representSudoku.writeln;
}
| D |
/Users/NMB12/Documents/caregiverapp/DerivedData/ReMindr/Build/Intermediates/ReMindr.build/Debug-iphoneos/ReMindr.build/Objects-normal/arm64/ZoomTransitioningDelegate.o : /Users/NMB12/Documents/caregiverapp/ReMindr/CustomPointAnnotation.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddFavouriteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FavouriteCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PhotoCollectionViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PoliceStationDetailsViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PoliceWebDetailsViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PhotoCellCollectionViewCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PhotoCollectionAddPhotoHandler.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FavouritesTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Reminder.swift /Users/NMB12/Documents/caregiverapp/ReMindr/GeoSettingsViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FastestRouteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AppDelegate.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EmergencyContact.swift /Users/NMB12/Documents/caregiverapp/ReMindr/NotificationTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Photo.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddReminderViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddLocationViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Geofence.swift /Users/NMB12/Documents/caregiverapp/ReMindr/photoInfoViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PoliceStation.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PanicTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PanicTableViewCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddContactViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/LocationViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/DetailViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/MapViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/ViewFavouriteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EditFavouriteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FavouriteOnlyViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EmergencyContactsTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/ZoomTransitioningDelegate.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Reachability.swift /Users/NMB12/Documents/caregiverapp/ReMindr/GeofencingViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EmergencyTableViewCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Favourite.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Panic.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PanicMapViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.swiftmodule /Users/NMB12/Documents/caregiverapp/Pods/Firebase/Core/Sources/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/MapKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreLocation.swiftmodule /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIROptions.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRLoggerLevel.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRApp.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRAnalyticsConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FirebaseCore.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIROptions.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRApp.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalyticsConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FirebaseAuthVersion.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRUserInfo.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRUser.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRAuthCredential.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRAuthErrors.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRAuth.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRTwitterAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRGoogleAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRGitHubAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRFacebookAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIREmailPasswordAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FirebaseAuth.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRServerValue.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRTransactionResult.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRMutableData.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDataSnapshot.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDataEventType.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabaseQuery.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabaseReference.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabase.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FirebaseDatabase.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageTaskSnapshot.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageUploadTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageReference.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageMetadata.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageObservableTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageDownloadTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageConstants.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorage.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FirebaseStorage.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/Firebase/Core/Sources/Firebase.h /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreAudio.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreData.swiftmodule
/Users/NMB12/Documents/caregiverapp/DerivedData/ReMindr/Build/Intermediates/ReMindr.build/Debug-iphoneos/ReMindr.build/Objects-normal/arm64/ZoomTransitioningDelegate~partial.swiftmodule : /Users/NMB12/Documents/caregiverapp/ReMindr/CustomPointAnnotation.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddFavouriteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FavouriteCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PhotoCollectionViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PoliceStationDetailsViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PoliceWebDetailsViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PhotoCellCollectionViewCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PhotoCollectionAddPhotoHandler.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FavouritesTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Reminder.swift /Users/NMB12/Documents/caregiverapp/ReMindr/GeoSettingsViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FastestRouteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AppDelegate.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EmergencyContact.swift /Users/NMB12/Documents/caregiverapp/ReMindr/NotificationTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Photo.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddReminderViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddLocationViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Geofence.swift /Users/NMB12/Documents/caregiverapp/ReMindr/photoInfoViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PoliceStation.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PanicTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PanicTableViewCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddContactViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/LocationViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/DetailViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/MapViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/ViewFavouriteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EditFavouriteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FavouriteOnlyViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EmergencyContactsTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/ZoomTransitioningDelegate.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Reachability.swift /Users/NMB12/Documents/caregiverapp/ReMindr/GeofencingViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EmergencyTableViewCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Favourite.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Panic.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PanicMapViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.swiftmodule /Users/NMB12/Documents/caregiverapp/Pods/Firebase/Core/Sources/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/MapKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreLocation.swiftmodule /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIROptions.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRLoggerLevel.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRApp.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRAnalyticsConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FirebaseCore.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIROptions.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRApp.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalyticsConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FirebaseAuthVersion.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRUserInfo.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRUser.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRAuthCredential.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRAuthErrors.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRAuth.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRTwitterAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRGoogleAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRGitHubAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRFacebookAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIREmailPasswordAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FirebaseAuth.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRServerValue.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRTransactionResult.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRMutableData.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDataSnapshot.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDataEventType.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabaseQuery.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabaseReference.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabase.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FirebaseDatabase.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageTaskSnapshot.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageUploadTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageReference.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageMetadata.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageObservableTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageDownloadTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageConstants.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorage.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FirebaseStorage.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/Firebase/Core/Sources/Firebase.h /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreAudio.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreData.swiftmodule
/Users/NMB12/Documents/caregiverapp/DerivedData/ReMindr/Build/Intermediates/ReMindr.build/Debug-iphoneos/ReMindr.build/Objects-normal/arm64/ZoomTransitioningDelegate~partial.swiftdoc : /Users/NMB12/Documents/caregiverapp/ReMindr/CustomPointAnnotation.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddFavouriteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FavouriteCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PhotoCollectionViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PoliceStationDetailsViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PoliceWebDetailsViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PhotoCellCollectionViewCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PhotoCollectionAddPhotoHandler.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FavouritesTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Reminder.swift /Users/NMB12/Documents/caregiverapp/ReMindr/GeoSettingsViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FastestRouteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AppDelegate.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EmergencyContact.swift /Users/NMB12/Documents/caregiverapp/ReMindr/NotificationTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Photo.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddReminderViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddLocationViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Geofence.swift /Users/NMB12/Documents/caregiverapp/ReMindr/photoInfoViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PoliceStation.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PanicTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PanicTableViewCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/AddContactViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/LocationViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/DetailViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/MapViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/ViewFavouriteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EditFavouriteViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/FavouriteOnlyViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EmergencyContactsTableViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/ZoomTransitioningDelegate.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Reachability.swift /Users/NMB12/Documents/caregiverapp/ReMindr/GeofencingViewController.swift /Users/NMB12/Documents/caregiverapp/ReMindr/EmergencyTableViewCell.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Favourite.swift /Users/NMB12/Documents/caregiverapp/ReMindr/Panic.swift /Users/NMB12/Documents/caregiverapp/ReMindr/PanicMapViewController.swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Swift.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/SwiftOnoneSupport.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Foundation.swiftmodule /Users/NMB12/Documents/caregiverapp/Pods/Firebase/Core/Sources/module.modulemap /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Darwin.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/Dispatch.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/ObjectiveC.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreGraphics.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/MapKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/UIKit.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/QuartzCore.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreImage.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreLocation.swiftmodule /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIROptions.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRLoggerLevel.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRApp.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRAnalyticsConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FirebaseCore.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIROptions.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRApp.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalyticsConfiguration.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FirebaseAuthVersion.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRUserInfo.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRUser.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRAuthCredential.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRAuthErrors.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRAuth.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRTwitterAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRGoogleAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRGitHubAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIRFacebookAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FIREmailPasswordAuthProvider.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Headers/FirebaseAuth.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseAuth/Frameworks/FirebaseAuth.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRServerValue.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRTransactionResult.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRMutableData.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDataSnapshot.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDataEventType.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabaseQuery.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabaseReference.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabase.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FirebaseDatabase.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageTaskSnapshot.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageUploadTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageReference.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageMetadata.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageObservableTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageDownloadTask.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageConstants.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorage.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FirebaseStorage.h /Users/NMB12/Documents/caregiverapp/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Modules/module.modulemap /Users/NMB12/Documents/caregiverapp/Pods/Firebase/Core/Sources/Firebase.h /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/AVFoundation.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreMedia.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreAudio.swiftmodule /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/arm64/CoreData.swiftmodule
| D |
ZGELQF (F08AVF) Example Program Data
3 4 2 :Values of M, N and NRHS
( 0.28,-0.36) ( 0.50,-0.86) (-0.77,-0.48) ( 1.58, 0.66)
(-0.50,-1.10) (-1.21, 0.76) (-0.32,-0.24) (-0.27,-1.15)
( 0.36,-0.51) (-0.07, 1.33) (-0.75, 0.47) (-0.08, 1.01) :End of matrix A
(-1.35, 0.19) ( 4.83,-2.67)
( 9.41,-3.56) (-7.28, 3.34)
(-7.57, 6.93) ( 0.62, 4.53) :End of matrix B
| D |
// @ inheritance.d
import std.stdio;
interface Dog{
void Bark();
void Walk();
}
class Husky : Dog{
void Bark(){ writeln("Husky Bark!"); }
void Walk(){ writeln("Husky Walk!"); }
}
class GoldenRetriever : Dog{
void Bark(){ writeln("GoldenRetriever Bark!"); }
void Walk(){ writeln("GoldenRetriever Walk!"); }
}
void main(){
Dog dog1 = new Husky;
Dog dog2 = new GoldenRetriever;
Dog[] collection;
collection ~= dog1;
collection ~= dog2;
foreach(doggy ; collection){
doggy.Bark();
}
}
| D |
with respect to the outside
in outward appearance
| D |
void main() { runSolver(); }
void problem() {
auto T = scan!long;
auto subSolve(long N) {
auto ds = (9 * N).divisors;
foreach(k; 1..18) {
const dec = 10L ^^ k;
foreach(d; ds) {
const l = d - N;
if (l >= 1 && l < dec) return l;
}
}
return 0;
}
auto solve() {
foreach(_; 0..T) {
subSolve(scan!long).writeln;
}
}
outputForAtCoder(&solve);
}
// ----------------------------------------------
import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) { if (!m) return [[]]; if (s.empty) return []; return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
else static if (is(T == void)) fn();
else static if (is(T == string)) fn().writeln;
else static if (isInputRange!T) {
static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
else foreach(r; fn()) r.writeln;
}
else fn().writeln;
}
void runSolver() {
enum BORDER = "==================================";
debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
else problem();
}
enum YESNO = [true: "Yes", false: "No"];
// -----------------------------------------------
| D |
/Users/AyushArora/Documents/100_Days_of_Code/100_Days_of_Code/Rust/target/rls/debug/build/rand_chacha-8f12a30830111b58/build_script_build-8f12a30830111b58: /Users/AyushArora/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/build.rs
/Users/AyushArora/Documents/100_Days_of_Code/100_Days_of_Code/Rust/target/rls/debug/build/rand_chacha-8f12a30830111b58/build_script_build-8f12a30830111b58.d: /Users/AyushArora/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/build.rs
/Users/AyushArora/.cargo/registry/src/github.com-1ecc6299db9ec823/rand_chacha-0.1.1/build.rs:
| D |
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/target/debug/deps/aho_corasick-bfefb538d71f8e98.rmeta: /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/lib.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/ahocorasick.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/automaton.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/buffer.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/byte_frequencies.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/classes.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/dfa.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/error.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/nfa.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/mod.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/api.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/pattern.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/rabinkarp.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/mod.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/compile.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/runtime.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/vector.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/prefilter.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/state_id.rs
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/target/debug/deps/libaho_corasick-bfefb538d71f8e98.rlib: /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/lib.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/ahocorasick.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/automaton.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/buffer.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/byte_frequencies.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/classes.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/dfa.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/error.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/nfa.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/mod.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/api.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/pattern.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/rabinkarp.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/mod.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/compile.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/runtime.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/vector.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/prefilter.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/state_id.rs
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/target/debug/deps/aho_corasick-bfefb538d71f8e98.d: /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/lib.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/ahocorasick.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/automaton.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/buffer.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/byte_frequencies.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/classes.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/dfa.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/error.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/nfa.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/mod.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/api.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/pattern.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/rabinkarp.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/mod.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/compile.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/runtime.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/vector.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/prefilter.rs /run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/state_id.rs
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/lib.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/ahocorasick.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/automaton.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/buffer.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/byte_frequencies.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/classes.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/dfa.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/error.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/nfa.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/mod.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/api.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/pattern.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/rabinkarp.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/mod.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/compile.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/teddy/runtime.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/packed/vector.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/prefilter.rs:
/run/media/andreby/Docs/GithubCodes/learn_rust/actix-demo/~/.cargo/registry/src/github.com-1ecc6299db9ec823/aho-corasick-0.7.6/src/state_id.rs:
| D |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.