Last active
August 29, 2015 14:09
-
-
Save sturgle/372a94c73a154965142a to your computer and use it in GitHub Desktop.
use readM to implement readN
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
using namespace std; | |
// ******************** m reader mocker ********************* | |
string inputstr; | |
void initInputStr() { | |
string line; | |
stringstream ss; | |
while (getline(cin, line)) { | |
ss << line << endl; | |
} | |
inputstr = ss.str(); | |
} | |
class MBufReader { | |
public: | |
static const int M = 43; | |
int cur; | |
int readM(char buf[]) { | |
int i = 0; | |
while (i < M && cur < inputstr.size()) { | |
buf[i] = inputstr[cur]; | |
i++; | |
cur++; | |
} | |
return i; | |
} | |
MBufReader() { | |
reinit(); | |
} | |
void reinit() { | |
cur = 0; | |
} | |
}; | |
MBufReader mrb; | |
// ******************** real code ********************* | |
class NBufReader { | |
public: | |
int mcur; | |
int msize; | |
char mbuf[MBufReader::M]; | |
int readN_Naive(char buf[], int n) { | |
int ncur = 0; | |
while(ncur < n) { | |
if (mcur < msize) { | |
buf[ncur] = mbuf[mcur]; | |
ncur++; | |
mcur++; | |
} else { | |
msize = mrb.readM(mbuf); | |
mcur = 0; | |
if (msize == 0) return ncur; | |
} | |
} | |
return ncur; | |
} | |
int readN(char buf[], int n) { | |
int ncur = 0; | |
while(ncur < n) { | |
if (mcur < msize) { | |
buf[ncur] = mbuf[mcur]; | |
ncur++; | |
mcur++; | |
} else if (n - ncur >= MBufReader::M) { | |
int nread = mrb.readM(buf + ncur); | |
if (nread == 0) return ncur; | |
ncur += nread; | |
} else { | |
msize = mrb.readM(mbuf); | |
mcur = 0; | |
if (msize == 0) return ncur; | |
} | |
} | |
return ncur; | |
} | |
NBufReader() { | |
mcur = 0; | |
msize = 0; | |
} | |
}; | |
// ******************** testing ********************* | |
int main() { | |
initInputStr(); | |
const int N = 83; | |
char buf[100000]; | |
for (int N = 23; N < 197; N++) { | |
mrb.reinit(); | |
stringstream ss; | |
NBufReader br; | |
int n = 0; | |
while ((n = br.readN(buf, N)) != 0) { | |
for (int i = 0; i < n; i++) { | |
ss << buf[i]; | |
} | |
} | |
if (ss.str() == inputstr) { | |
cout << "N size " << N << " correct!" << endl; | |
} else { | |
cout << "N size " << N << " wrong!" << endl; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment