commit ba39ede8dab54dc27331cdd3cc14b12b1efd717d
parent 02806a0d5621de1aad0c0d20bfae2fb7f1e89602
Author: Dominik Schmidt <das1993@hotmail.com>
Date: Sun, 9 Aug 2015 11:22:39 +0200
Provide an aggregate-struct for multiple fortunes.
Just adds multiple fortunes into an array, and bundles them into one range.
Diffstat:
dfortune.d | | | 93 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 93 insertions(+), 0 deletions(-)
diff --git a/dfortune.d b/dfortune.d
@@ -173,3 +173,96 @@ class Fortune : RandomAccessFinite!(string){
return clone();
}
}
+
+struct Fortunes{
+ Fortune fortunes[];
+ size_t pos,end;
+
+ void add(Fortune f){
+ fortunes~=f;
+ end+=f.length-1;
+ }
+ alias chooseRandom=Fortune.chooseRandom;
+ void add(string f){
+ Fortune n=new Fortune(f);
+ n.initialize();
+ add(n);
+ }
+ void add(T)(T r) if(isInputRange!(T) && (is(ElementType!(T)==string) || is(ElementType!(T)==Fortune) )){
+ while(!r.empty){
+ add(r.moveFront());
+ r.popFront();
+ }
+ }
+ string opIndex(size_t i){
+ foreach(Fortune f; fortunes.save){
+ if(i>=f.length){
+ i-=f.length;
+ }
+ else{
+ return f.readFortune(cast(uint)i);
+ }
+ }
+ assert(0);
+ }
+ @property size_t length(){
+ size_t size;
+ foreach(Fortune f; fortunes)
+ size+=f.length;
+ return size;
+ }
+ @property string front(){
+ return opIndex(pos);
+ }
+ @property string back(){
+ return opIndex(end);
+ }
+ string moveAt(size_t i){
+ pos=i;
+ return opIndex(pos);
+ }
+ Fortunes opSlice(size_t a, size_t b){
+ return Fortunes(fortunes, a, b);
+ }
+ @property Fortunes save(){
+ return Fortunes(fortunes, pos, end);
+ }
+ string moveFront(){
+ return front();
+ }
+ string moveBack(){
+ return back();
+ }
+ void popBack(){
+ end--;
+ }
+ int opApply(int delegate(string)f){
+ int ret;
+ while(!empty()){
+ ret=f(moveFront());
+ popFront();
+ if(ret){
+ break;
+ }
+ }
+ return ret;
+ }
+ int opApply(int delegate(size_t,string)f){
+ int ret;
+ size_t i;
+ while(!empty()){
+ ret=f(i++,moveFront());
+ popFront();
+ if(ret){
+ break;
+ }
+ }
+ return ret;
+ }
+ @property bool empty() const{
+ return (pos>end);
+ }
+ void popFront(){
+ pos++;
+ }
+}