Skip to content

Commit

Permalink
Use endian-aware read/write for length of string. (rdkit#8105)
Browse files Browse the repository at this point in the history
* Use endian-aware read/write for length of string.

* Re-run clang-format.

---------

Co-authored-by: David Cosgrove <[email protected]>
  • Loading branch information
DavidACosgrove and David Cosgrove authored Dec 18, 2024
1 parent ce35b3c commit e589f17
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions Code/RDGeneral/StreamOps.h
Original file line number Diff line number Diff line change
Expand Up @@ -88,18 +88,22 @@ inline T EndianSwapBytes(T value) {

return SwapBytes<T, sizeof(T)>(value);
}

template <EEndian from, EEndian to>
inline char EndianSwapBytes(char value) {
return value;
}

template <EEndian from, EEndian to>
inline unsigned char EndianSwapBytes(unsigned char value) {
return value;
}

template <EEndian from, EEndian to>
inline signed char EndianSwapBytes(signed char value) {
return value;
}

// --------------------------------------

//! Packs an integer and outputs it to a stream
Expand Down Expand Up @@ -265,8 +269,8 @@ void streamWrite(std::ostream &ss, const T &val) {

//! special case for string
inline void streamWrite(std::ostream &ss, const std::string &what) {
unsigned int l = rdcast<unsigned int>(what.length());
ss.write((const char *)&l, sizeof(l));
unsigned int l = static_cast<unsigned int>(what.length());
streamWrite(ss, l);
ss.write(what.c_str(), sizeof(char) * l);
};

Expand Down Expand Up @@ -299,10 +303,7 @@ void streamRead(std::istream &ss, T &obj, int version) {
inline void streamRead(std::istream &ss, std::string &what, int version) {
RDUNUSED_PARAM(version);
unsigned int l;
ss.read((char *)&l, sizeof(l));
if (ss.fail()) {
throw std::runtime_error("failed to read from stream");
}
streamRead(ss, l);
auto buff = std::make_unique<char[]>(l);
ss.read(buff.get(), sizeof(char) * l);
if (ss.fail()) {
Expand Down Expand Up @@ -342,6 +343,7 @@ inline std::string getLine(std::istream *inStream) {
}
return res;
}

//! grabs the next line from an instream and returns it.
inline std::string getLine(std::istream &inStream) {
return getLine(&inStream);
Expand Down Expand Up @@ -370,10 +372,15 @@ const unsigned char EndTag = 0xFF;
class CustomPropHandler {
public:
virtual ~CustomPropHandler() {}

virtual const char *getPropName() const = 0;

virtual bool canSerialize(const RDValue &value) const = 0;

virtual bool read(std::istream &ss, RDValue &value) const = 0;

virtual bool write(std::ostream &ss, const RDValue &value) const = 0;

virtual CustomPropHandler *clone() const = 0;
};

Expand Down Expand Up @@ -642,7 +649,6 @@ inline unsigned int streamReadProps(std::istream &ss, RDProps &props,

return static_cast<unsigned int>(count);
}

} // namespace RDKit

#endif

0 comments on commit e589f17

Please sign in to comment.