Skip to content

Commit

Permalink
If function find(keyword) fails to locate specified keyword in the he…
Browse files Browse the repository at this point in the history
…ader of the numpy file it returns -1. This indicates problems with header and therefore should be caught properly by raising runtime error.
  • Loading branch information
chaloz committed Nov 8, 2015
1 parent 814b38e commit 64f6670
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions cnpy.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,18 @@ void cnpy::parse_npy_header(FILE* fp, unsigned int& word_size, unsigned int*& sh
int loc1, loc2;

//fortran order
loc1 = header.find("fortran_order")+16;
loc1 = header.find("fortran_order");
if (loc1 < 0)
throw std::runtime_error("parse_npy_header: failed to find header keyword: 'fortran_order'");
loc1 += 16;
fortran_order = (header.substr(loc1,5) == "True" ? true : false);

//shape
loc1 = header.find("(");
loc2 = header.find(")");
if (loc1 < 0 || loc2 < 0)
throw std::runtime_error("parse_npy_header: failed to find header keyword: '(' or ')'");

std::string str_shape = header.substr(loc1+1,loc2-loc1-1);
if(str_shape[str_shape.size()-1] == ',') ndims = 1;
else ndims = std::count(str_shape.begin(),str_shape.end(),',')+1;
Expand All @@ -87,7 +93,10 @@ void cnpy::parse_npy_header(FILE* fp, unsigned int& word_size, unsigned int*& sh
//endian, word size, data type
//byte order code | stands for not applicable.
//not sure when this applies except for byte array
loc1 = header.find("descr")+9;
loc1 = header.find("descr");
if (loc1 < 0)
throw std::runtime_error("parse_npy_header: failed to find header keyword: 'descr'");
loc1 += 9;
bool littleEndian = (header[loc1] == '<' || header[loc1] == '|' ? true : false);
assert(littleEndian);

Expand Down

0 comments on commit 64f6670

Please sign in to comment.