Skip to content

Commit

Permalink
Optimize fiopen by reducing jumps
Browse files Browse the repository at this point in the history
  • Loading branch information
AreaZR committed Oct 3, 2021
1 parent dc888f7 commit e47687f
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions stl/src/fiopen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ FILE* _Xfsopen(_In_z_ const wchar_t* filename, _In_ int mode, _In_ int prot) {

template <class CharT>
FILE* _Xfiopen(const CharT* filename, ios_base::openmode mode, int prot) {
static const int valid[] = {
static const ios_base::openmode valid[] = {
// valid combinations of open flags
ios_base::in,
ios_base::out,
Expand All @@ -44,6 +44,10 @@ FILE* _Xfiopen(const CharT* filename, ios_base::openmode mode, int prot) {
0,
};

if (mode == 0) {
return nullptr; // no valid mode
}

FILE* fp = nullptr;
ios_base::openmode atendflag = mode & ios_base::ate;
ios_base::openmode norepflag = mode & ios_base::_Noreplace;
Expand All @@ -59,12 +63,14 @@ FILE* _Xfiopen(const CharT* filename, ios_base::openmode mode, int prot) {
mode &= ~(ios_base::ate | ios_base::_Nocreate | ios_base::_Noreplace);

int n = 0;
while (valid[n] != 0 && valid[n] != mode) { // look for a valid mode
++n;
}

if (valid[n] == 0) {
return nullptr; // no valid mode
for (;; ++n) { // look for a valid mode
if (valid[n] == mode) {
break;
}

if (valid[n] == 0) {
return nullptr; // no valid mode
}
}

if (norepflag && (mode & (ios_base::out | ios_base::app))
Expand All @@ -81,12 +87,12 @@ FILE* _Xfiopen(const CharT* filename, ios_base::openmode mode, int prot) {
return nullptr; // open failed
}

if (!atendflag || fseek(fp, 0, SEEK_END) == 0) {
return fp; // no need to seek to end, or seek succeeded
if (atendflag && fseek(fp, 0, SEEK_END) != 0) {
fclose(fp); // can't position at end
return nullptr;
}

fclose(fp); // can't position at end
return nullptr;
return fp; // no need to seek to end, or seek succeeded
}

_CRTIMP2_PURE FILE* __CLRCALL_PURE_OR_CDECL _Fiopen(
Expand Down

0 comments on commit e47687f

Please sign in to comment.