DFortune

Unix fortune-cookie parser written in D
git clone git://xatko.vsos.ethz.ch/DFortune.git
Log | Files | Refs

commit 5c88e98b24e58012c8f7baca7afd3f89a99881fe
parent 92d0a0e386d1f5b06f9182b28922513d1e61e00d
Author: Dominik Schmidt <das1993@hotmail.com>
Date:   Sun,  9 Aug 2015 16:36:39 +0200

Do boundary-management properly

Diffstat:
dfortune.d | 25++++++++++++++++++-------
1 file changed, 18 insertions(+), 7 deletions(-)

diff --git a/dfortune.d b/dfortune.d @@ -81,6 +81,9 @@ class Fortune : RandomAccessFinite!(Cookie){ if(i>header.numstr){ throw new RangeError("Range violation"); } + if(i==header.numstr){ + return cast(uint)content.size; + } table.seek(Header.getOffset()+(i+1)*4-1); ubyte b[uint.sizeof]; table.rawRead(b); @@ -92,6 +95,9 @@ class Fortune : RandomAccessFinite!(Cookie){ assert(table.isOpen && content.isOpen, "Fortunes must be opened before reading"); } body{ + if(pos==end){ + return ""; + } content.seek(pos); ubyte buf[]=new ubyte[end-pos]; content.rawRead(buf); @@ -113,13 +119,18 @@ class Fortune : RandomAccessFinite!(Cookie){ } public string read(uint i){ - uint pos=getOffset(i); - uint end=getOffset(i+1)-3; //-3 to exclude \n%\n - return sliceFile(pos,end); + Cookie c=getCookie(i); + return sliceFile(c.pos,c.pos+c.size); } public Cookie getCookie(uint i){ + if(i>=header.numstr){ + throw new RangeError("Range violation"); + } uint pos=getOffset(i); - uint end=getOffset(i+1)-3; //-3 to exclude \n%\n + uint end=getOffset(i+1)-1; //-1 to exclude \n + if(end>pos+2){ + end-=2; //to exclude the following %\n + } return Cookie(pos, end-pos); } public string read(in ref Cookie c){ @@ -144,7 +155,7 @@ class Fortune : RandomAccessFinite!(Cookie){ return c; } @property size_t length() const{ - return header.numstr-pos; + return end-pos+1; } Fortune opSlice(size_t a, size_t b){ Fortune c=clone(); @@ -178,7 +189,7 @@ class Fortune : RandomAccessFinite!(Cookie){ return getCookie(pos); } @property bool empty() const{ - return (pos>end); + return (length==0); } @property Cookie front(){ return moveFront(); @@ -229,7 +240,7 @@ struct Fortunes{ void add(Fortune f){ fortunes~=f; - end+=f.length-1; + end+=f.length; } alias chooseRandom=Fortune.chooseRandom; auto @property strings(){