From 0e09dfe1b2c2545ec0916fe38d8fe3068fee3859 Mon Sep 17 00:00:00 2001 From: Cr4sh Date: Sat, 14 Jan 2017 03:24:56 +0300 Subject: [PATCH] NE Alpha 38 --- UEFIDump/CMakeLists.txt | 8 +- UEFIDump/uefidump_main.cpp | 2 +- UEFIExtract/uefiextract_main.cpp | 2 +- UEFIFind/uefifind_main.cpp | 2 +- UEFITool/gotooffsetdialog.ui | 21 +- UEFITool/hexspinbox.cpp | 37 + UEFITool/hexspinbox.h | 36 + UEFITool/hexviewdialog.h | 2 +- UEFITool/qhexedit2/chunks.cpp | 323 +++ UEFITool/qhexedit2/chunks.h | 77 + UEFITool/qhexedit2/commands.cpp | 165 ++ UEFITool/qhexedit2/commands.h | 47 + UEFITool/qhexedit2/license.txt | 502 +++++ UEFITool/qhexedit2/qhexedit.cpp | 1085 +++++++++++ UEFITool/qhexedit2/qhexedit.h | 411 ++++ UEFITool/uefitool.cpp | 34 +- UEFITool/uefitool.pro | 14 +- common/bstrlib/LICENSE | 28 + common/bstrlib/bstrlib.c | 3137 ++++++++++++++++++++++++++++++ common/bstrlib/bstrlib.h | 321 +++ common/bstrlib/bstrwrap.cpp | 1721 ++++++++++++++++ common/bstrlib/bstrwrap.h | 449 +++++ common/treemodel.cpp | 2 +- common/ustring.h | 2 +- 24 files changed, 8383 insertions(+), 45 deletions(-) create mode 100644 UEFITool/hexspinbox.cpp create mode 100644 UEFITool/hexspinbox.h create mode 100644 UEFITool/qhexedit2/chunks.cpp create mode 100644 UEFITool/qhexedit2/chunks.h create mode 100644 UEFITool/qhexedit2/commands.cpp create mode 100644 UEFITool/qhexedit2/commands.h create mode 100644 UEFITool/qhexedit2/license.txt create mode 100644 UEFITool/qhexedit2/qhexedit.cpp create mode 100644 UEFITool/qhexedit2/qhexedit.h create mode 100644 common/bstrlib/LICENSE create mode 100644 common/bstrlib/bstrlib.c create mode 100644 common/bstrlib/bstrlib.h create mode 100644 common/bstrlib/bstrwrap.cpp create mode 100644 common/bstrlib/bstrwrap.h diff --git a/UEFIDump/CMakeLists.txt b/UEFIDump/CMakeLists.txt index 9054749..e15ab1d 100644 --- a/UEFIDump/CMakeLists.txt +++ b/UEFIDump/CMakeLists.txt @@ -18,8 +18,8 @@ SET(PROJECT_SOURCES ../common/LZMA/SDK/C/LzmaDec.c ../common/Tiano/EfiTianoDecompress.c ../common/ustring.cpp - ../bstrlib/bstrlib.c - ../bstrlib/bstrwrap.cpp + ../common/bstrlib/bstrlib.c + ../common/bstrlib/bstrwrap.cpp ) SET(PROJECT_HEADERS @@ -43,8 +43,8 @@ SET(PROJECT_HEADERS ../common/Tiano/EfiTianoDecompress.h ../common/ubytearray.h ../common/ustring.h - ../bstrlib/bstrlib.h - ../bstrlib/bstrwrap.h + ../common/bstrlib/bstrlib.h + ../common/bstrlib/bstrwrap.h ) ADD_DEFINITIONS(-DU_ENABLE_NVRAM_PARSING_SUPPORT) diff --git a/UEFIDump/uefidump_main.cpp b/UEFIDump/uefidump_main.cpp index 1c28c24..0445bb2 100644 --- a/UEFIDump/uefidump_main.cpp +++ b/UEFIDump/uefidump_main.cpp @@ -29,7 +29,7 @@ int main(int argc, char *argv[]) return (uefidumper.dump(buffer, UString(argv[1])) != U_SUCCESS); } - std::cout << "UEFIDump 0.1.3" << std::endl << std::endl + std::cout << "UEFIDump 0.1.4" << std::endl << std::endl << "Usage: UEFIDump imagefile" << std::endl; return 0; } diff --git a/UEFIExtract/uefiextract_main.cpp b/UEFIExtract/uefiextract_main.cpp index b88df0a..3c37fd2 100644 --- a/UEFIExtract/uefiextract_main.cpp +++ b/UEFIExtract/uefiextract_main.cpp @@ -121,7 +121,7 @@ int main(int argc, char *argv[]) } } // If parameters are different, show version and usage information - std::cout << "UEFIExtract 0.13.2" << std::endl << std::endl + std::cout << "UEFIExtract 0.13.3" << std::endl << std::endl << "Usage: UEFIExtract imagefile - generate report and dump only leaf tree items into .dump folder." << std::endl << " UEFIExtract imagefile all - generate report and dump all tree items." << std::endl << " UEFIExtract imagefile dump - only generate dump, no report needed." << std::endl diff --git a/UEFIFind/uefifind_main.cpp b/UEFIFind/uefifind_main.cpp index a6a991d..d14f679 100644 --- a/UEFIFind/uefifind_main.cpp +++ b/UEFIFind/uefifind_main.cpp @@ -148,7 +148,7 @@ int main(int argc, char *argv[]) return U_SUCCESS; } else { - std::cout << "UEFIFind 0.10.6" << std::endl << std::endl << + std::cout << "UEFIFind 0.10.7" << std::endl << std::endl << "Usage: UEFIFind {header | body | all} {list | count} pattern imagefile" << std::endl << " or UEFIFind file patternsfile imagefile" << std::endl; return U_INVALID_PARAMETER; diff --git a/UEFITool/gotooffsetdialog.ui b/UEFITool/gotooffsetdialog.ui index bad9d1c..7179183 100644 --- a/UEFITool/gotooffsetdialog.ui +++ b/UEFITool/gotooffsetdialog.ui @@ -61,25 +61,13 @@ - + 0 0 - - - - - 0x - - - 1000000000 - - - 16 - @@ -97,6 +85,13 @@ + + + HexSpinBox + QSpinBox +
hexspinbox.h
+
+
buttonBox diff --git a/UEFITool/hexspinbox.cpp b/UEFITool/hexspinbox.cpp new file mode 100644 index 0000000..44763a1 --- /dev/null +++ b/UEFITool/hexspinbox.cpp @@ -0,0 +1,37 @@ +/* hexspinbox.cpp + + Copyright (c) 2016, Nikolaj Schlej. All rights reserved. + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + + */ + +#include "hexspinbox.h" +#include + +HexSpinBox::HexSpinBox(QWidget *parent) : +QSpinBox(parent), validator(QRegExp("0x([0-9a-fA-F]){1,8}")) +{ + this->setRange(0, INT_MAX); + this->setPrefix("0x"); +} + +QValidator::State HexSpinBox::validate(QString &text, int &pos) const +{ + return validator.validate(text, pos); +} + +QString HexSpinBox::textFromValue(int val) const +{ + return QString::number(val, 16).toUpper(); +} + +int HexSpinBox::valueFromText(const QString &text) const +{ + return text.toInt(NULL, 16); +} diff --git a/UEFITool/hexspinbox.h b/UEFITool/hexspinbox.h new file mode 100644 index 0000000..1304e88 --- /dev/null +++ b/UEFITool/hexspinbox.h @@ -0,0 +1,36 @@ +/* hexspinbox.h + + Copyright (c) 2016, Nikolaj Schlej. All rights reserved. + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + + */ + +#ifndef HEXSPINBOX_H +#define HEXSPINBOX_H + +#include +#include + +class HexSpinBox : public QSpinBox +{ + Q_OBJECT + +public: + HexSpinBox(QWidget *parent = 0); + +protected: + QValidator::State validate(QString &text, int &pos) const; + int valueFromText(const QString &text) const; + QString textFromValue(int value) const; + +private: + QRegExpValidator validator; +}; + +#endif // HEXSPINBOX_H diff --git a/UEFITool/hexviewdialog.h b/UEFITool/hexviewdialog.h index a221a01..ad7d29b 100644 --- a/UEFITool/hexviewdialog.h +++ b/UEFITool/hexviewdialog.h @@ -16,7 +16,7 @@ #include #include "../common/treemodel.h" -#include "../qhexedit2/qhexedit.h" +#include "qhexedit2/qhexedit.h" #include "ui_hexviewdialog.h" class HexViewDialog : public QDialog diff --git a/UEFITool/qhexedit2/chunks.cpp b/UEFITool/qhexedit2/chunks.cpp new file mode 100644 index 0000000..a4e420b --- /dev/null +++ b/UEFITool/qhexedit2/chunks.cpp @@ -0,0 +1,323 @@ +#include "chunks.h" +#include + +#define NORMAL 0 +#define HIGHLIGHTED 1 + +#define BUFFER_SIZE 0x10000 +#define CHUNK_SIZE 0x1000 +#define READ_CHUNK_MASK Q_INT64_C(0xfffffffffffff000) + +// ***************************************** Constructors and file settings + +Chunks::Chunks(QObject *parent): QObject(parent) +{ + QBuffer *buf = new QBuffer(this); + setIODevice(*buf); +} + +Chunks::Chunks(QIODevice &ioDevice, QObject *parent): QObject(parent) +{ + setIODevice(ioDevice); +} + +bool Chunks::setIODevice(QIODevice &ioDevice) +{ + _ioDevice = &ioDevice; + bool ok = _ioDevice->open(QIODevice::ReadOnly); + if (ok) // Try to open IODevice + { + _size = _ioDevice->size(); + _ioDevice->close(); + } + else // Fallback is an empty buffer + { + QBuffer *buf = new QBuffer(this); + _ioDevice = buf; + _size = 0; + } + _chunks.clear(); + _pos = 0; + return ok; +} + + +// ***************************************** Getting data out of Chunks + +QByteArray Chunks::data(qint64 pos, qint64 maxSize, QByteArray *highlighted) +{ + qint64 ioDelta = 0; + int chunkIdx = 0; + + Chunk chunk; + QByteArray buffer; + + // Do some checks and some arrangements + if (highlighted) + highlighted->clear(); + + if (pos >= _size) + return buffer; + + if (maxSize < 0) + maxSize = _size; + else + if ((pos + maxSize) > _size) + maxSize = _size - pos; + + _ioDevice->open(QIODevice::ReadOnly); + + while (maxSize > 0) + { + chunk.absPos = LLONG_MAX; + bool chunksLoopOngoing = true; + while ((chunkIdx < _chunks.count()) && chunksLoopOngoing) + { + // In this section, we track changes before our required data and + // we take the editdet data, if availible. ioDelta is a difference + // counter to justify the read pointer to the original data, if + // data in between was deleted or inserted. + + chunk = _chunks[chunkIdx]; + if (chunk.absPos > pos) + chunksLoopOngoing = false; + else + { + chunkIdx += 1; + qint64 count; + qint64 chunkOfs = pos - chunk.absPos; + if (maxSize > ((qint64)chunk.data.size() - chunkOfs)) + { + count = (qint64)chunk.data.size() - chunkOfs; + ioDelta += CHUNK_SIZE - chunk.data.size(); + } + else + count = maxSize; + if (count > 0) + { + buffer += chunk.data.mid(chunkOfs, (int)count); + maxSize -= count; + pos += count; + if (highlighted) + *highlighted += chunk.dataChanged.mid(chunkOfs, (int)count); + } + } + } + + if ((maxSize > 0) && (pos < chunk.absPos)) + { + // In this section, we read data from the original source. This only will + // happen, whe no copied data is available + + qint64 byteCount; + QByteArray readBuffer; + if ((chunk.absPos - pos) > maxSize) + byteCount = maxSize; + else + byteCount = chunk.absPos - pos; + + maxSize -= byteCount; + _ioDevice->seek(pos + ioDelta); + readBuffer = _ioDevice->read(byteCount); + buffer += readBuffer; + if (highlighted) + *highlighted += QByteArray(readBuffer.size(), NORMAL); + pos += readBuffer.size(); + } + } + _ioDevice->close(); + return buffer; +} + +bool Chunks::write(QIODevice &iODevice, qint64 pos, qint64 count) +{ + if (count == -1) + count = _size; + bool ok = iODevice.open(QIODevice::WriteOnly); + if (ok) + { + for (qint64 idx=pos; idx < count; idx += BUFFER_SIZE) + { + QByteArray ba = data(idx, BUFFER_SIZE); + iODevice.write(ba); + } + iODevice.close(); + } + return ok; +} + + +// ***************************************** Set and get highlighting infos + +void Chunks::setDataChanged(qint64 pos, bool dataChanged) +{ + if ((pos < 0) || (pos >= _size)) + return; + int chunkIdx = getChunkIndex(pos); + qint64 posInBa = pos - _chunks[chunkIdx].absPos; + _chunks[chunkIdx].dataChanged[(int)posInBa] = char(dataChanged); +} + +bool Chunks::dataChanged(qint64 pos) +{ + QByteArray highlighted; + data(pos, 1, &highlighted); + return bool(highlighted.at(0)); +} + + +// ***************************************** Search API + +qint64 Chunks::indexOf(const QByteArray &ba, qint64 from) +{ + qint64 result = -1; + QByteArray buffer; + + for (qint64 pos=from; (pos < _size) && (result < 0); pos += BUFFER_SIZE) + { + buffer = data(pos, BUFFER_SIZE + ba.size() - 1); + int findPos = buffer.indexOf(ba); + if (findPos >= 0) + result = pos + (qint64)findPos; + } + return result; +} + +qint64 Chunks::lastIndexOf(const QByteArray &ba, qint64 from) +{ + qint64 result = -1; + QByteArray buffer; + + for (qint64 pos=from; (pos > 0) && (result < 0); pos -= BUFFER_SIZE) + { + qint64 sPos = pos - BUFFER_SIZE - (qint64)ba.size() + 1; + if (sPos < 0) + sPos = 0; + buffer = data(sPos, pos - sPos); + int findPos = buffer.lastIndexOf(ba); + if (findPos >= 0) + result = sPos + (qint64)findPos; + } + return result; +} + + +// ***************************************** Char manipulations + +bool Chunks::insert(qint64 pos, char b) +{ + if ((pos < 0) || (pos > _size)) + return false; + int chunkIdx; + if (pos == _size) + chunkIdx = getChunkIndex(pos-1); + else + chunkIdx = getChunkIndex(pos); + qint64 posInBa = pos - _chunks[chunkIdx].absPos; + _chunks[chunkIdx].data.insert(posInBa, b); + _chunks[chunkIdx].dataChanged.insert(posInBa, char(1)); + for (int idx=chunkIdx+1; idx < _chunks.size(); idx++) + _chunks[idx].absPos += 1; + _size += 1; + _pos = pos; + return true; +} + +bool Chunks::overwrite(qint64 pos, char b) +{ + if ((pos < 0) || (pos >= _size)) + return false; + int chunkIdx = getChunkIndex(pos); + qint64 posInBa = pos - _chunks[chunkIdx].absPos; + _chunks[chunkIdx].data[(int)posInBa] = b; + _chunks[chunkIdx].dataChanged[(int)posInBa] = char(1); + _pos = pos; + return true; +} + +bool Chunks::removeAt(qint64 pos) +{ + if ((pos < 0) || (pos >= _size)) + return false; + int chunkIdx = getChunkIndex(pos); + qint64 posInBa = pos - _chunks[chunkIdx].absPos; + _chunks[chunkIdx].data.remove(posInBa, 1); + _chunks[chunkIdx].dataChanged.remove(posInBa, 1); + for (int idx=chunkIdx+1; idx < _chunks.size(); idx++) + _chunks[idx].absPos -= 1; + _size -= 1; + _pos = pos; + return true; +} + + +// ***************************************** Utility functions + +char Chunks::operator[](qint64 pos) +{ + return data(pos, 1)[0]; +} + +qint64 Chunks::pos() +{ + return _pos; +} + +qint64 Chunks::size() +{ + return _size; +} + +int Chunks::getChunkIndex(qint64 absPos) +{ + // This routine checks, if there is already a copied chunk available. If os, it + // returns a reference to it. If there is no copied chunk available, original + // data will be copied into a new chunk. + + int foundIdx = -1; + int insertIdx = 0; + qint64 ioDelta = 0; + + + for (int idx=0; idx < _chunks.size(); idx++) + { + Chunk chunk = _chunks[idx]; + if ((absPos >= chunk.absPos) && (absPos < (chunk.absPos + chunk.data.size()))) + { + foundIdx = idx; + break; + } + if (absPos < chunk.absPos) + { + insertIdx = idx; + break; + } + ioDelta += chunk.data.size() - CHUNK_SIZE; + insertIdx = idx + 1; + } + + if (foundIdx == -1) + { + Chunk newChunk; + qint64 readAbsPos = absPos - ioDelta; + qint64 readPos = (readAbsPos & READ_CHUNK_MASK); + _ioDevice->open(QIODevice::ReadOnly); + _ioDevice->seek(readPos); + newChunk.data = _ioDevice->read(CHUNK_SIZE); + _ioDevice->close(); + newChunk.absPos = absPos - (readAbsPos - readPos); + newChunk.dataChanged = QByteArray(newChunk.data.size(), char(0)); + _chunks.insert(insertIdx, newChunk); + foundIdx = insertIdx; + } + return foundIdx; +} + + +#ifdef MODUL_TEST +int Chunks::chunkSize() +{ + return _chunks.size(); +} + +#endif diff --git a/UEFITool/qhexedit2/chunks.h b/UEFITool/qhexedit2/chunks.h new file mode 100644 index 0000000..43df76c --- /dev/null +++ b/UEFITool/qhexedit2/chunks.h @@ -0,0 +1,77 @@ +#ifndef CHUNKS_H +#define CHUNKS_H + +/** \cond docNever */ + +/*! The Chunks class is the storage backend for QHexEdit. + * + * When QHexEdit loads data, Chunks access them using a QIODevice interface. When the app uses + * a QByteArray interface, QBuffer is used to provide again a QIODevice like interface. No data + * will be changed, therefore Chunks opens the QIODevice in QIODevice::ReadOnly mode. After every + * access Chunks closes the QIODevice, that's why external applications can overwrite files while + * QHexEdit shows them. + * + * When the the user starts to edit the data, Chunks creates a local copy of a chunk of data (4 + * kilobytes) and notes all changes there. Parallel to that chunk, there is a second chunk, + * which keep track of which bytes are changed and which not. + * + */ + +#include + +struct Chunk +{ + QByteArray data; + QByteArray dataChanged; + qint64 absPos; +}; + +class Chunks: public QObject +{ +Q_OBJECT +public: + // Constructors and file settings + Chunks(QObject *parent); + Chunks(QIODevice &ioDevice, QObject *parent); + bool setIODevice(QIODevice &ioDevice); + + // Getting data out of Chunks + QByteArray data(qint64 pos=0, qint64 count=-1, QByteArray *highlighted=0); + bool write(QIODevice &iODevice, qint64 pos=0, qint64 count=-1); + + // Set and get highlighting infos + void setDataChanged(qint64 pos, bool dataChanged); + bool dataChanged(qint64 pos); + + // Search API + qint64 indexOf(const QByteArray &ba, qint64 from); + qint64 lastIndexOf(const QByteArray &ba, qint64 from); + + // Char manipulations + bool insert(qint64 pos, char b); + bool overwrite(qint64 pos, char b); + bool removeAt(qint64 pos); + + // Utility functions + char operator[](qint64 pos); + qint64 pos(); + qint64 size(); + + +private: + int getChunkIndex(qint64 absPos); + + QIODevice * _ioDevice; + qint64 _pos; + qint64 _size; + QList _chunks; + +#ifdef MODUL_TEST +public: + int chunkSize(); +#endif +}; + +/** \endcond docNever */ + +#endif // CHUNKS_H diff --git a/UEFITool/qhexedit2/commands.cpp b/UEFITool/qhexedit2/commands.cpp new file mode 100644 index 0000000..e9530d5 --- /dev/null +++ b/UEFITool/qhexedit2/commands.cpp @@ -0,0 +1,165 @@ +#include "commands.h" +#include + + +// Helper class to store single byte commands +class CharCommand : public QUndoCommand +{ +public: + enum CCmd {insert, removeAt, overwrite}; + + CharCommand(Chunks * chunks, CCmd cmd, qint64 charPos, char newChar, + QUndoCommand *parent=0); + + void undo(); + void redo(); + bool mergeWith(const QUndoCommand *command); + int id() const { return 1234; } + +private: + Chunks * _chunks; + qint64 _charPos; + bool _wasChanged; + char _newChar; + char _oldChar; + CCmd _cmd; +}; + +CharCommand::CharCommand(Chunks * chunks, CCmd cmd, qint64 charPos, char newChar, QUndoCommand *parent) + : QUndoCommand(parent) +{ + _chunks = chunks; + _charPos = charPos; + _newChar = newChar; + _cmd = cmd; +} + +bool CharCommand::mergeWith(const QUndoCommand *command) +{ + const CharCommand *nextCommand = static_cast(command); + bool result = false; + + if (_cmd != CharCommand::removeAt) + { + if (nextCommand->_cmd == overwrite) + if (nextCommand->_charPos == _charPos) + { + _newChar = nextCommand->_newChar; + result = true; + } + } + return result; +} + +void CharCommand::undo() +{ + switch (_cmd) + { + case insert: + _chunks->removeAt(_charPos); + break; + case overwrite: + _chunks->overwrite(_charPos, _oldChar); + _chunks->setDataChanged(_charPos, _wasChanged); + break; + case removeAt: + _chunks->insert(_charPos, _oldChar); + _chunks->setDataChanged(_charPos, _wasChanged); + break; + } +} + +void CharCommand::redo() +{ + switch (_cmd) + { + case insert: + _chunks->insert(_charPos, _newChar); + break; + case overwrite: + _oldChar = (*_chunks)[_charPos]; + _wasChanged = _chunks->dataChanged(_charPos); + _chunks->overwrite(_charPos, _newChar); + break; + case removeAt: + _oldChar = (*_chunks)[_charPos]; + _wasChanged = _chunks->dataChanged(_charPos); + _chunks->removeAt(_charPos); + break; + } +} + +UndoStack::UndoStack(Chunks * chunks, QObject * parent) + : QUndoStack(parent) +{ + _chunks = chunks; + _parent = parent; +} + +void UndoStack::insert(qint64 pos, char c) +{ + if ((pos >= 0) && (pos <= _chunks->size())) + { + QUndoCommand *cc = new CharCommand(_chunks, CharCommand::insert, pos, c); + this->push(cc); + } +} + +void UndoStack::insert(qint64 pos, const QByteArray &ba) +{ + if ((pos >= 0) && (pos <= _chunks->size())) + { + QString txt = QString(tr("Inserting %1 bytes")).arg(ba.size()); + beginMacro(txt); + for (int idx=0; idx < ba.size(); idx++) + { + QUndoCommand *cc = new CharCommand(_chunks, CharCommand::insert, pos + idx, ba.at(idx)); + this->push(cc); + } + endMacro(); + } +} + +void UndoStack::removeAt(qint64 pos, qint64 len) +{ + if ((pos >= 0) && (pos < _chunks->size())) + { + if (len==1) + { + QUndoCommand *cc = new CharCommand(_chunks, CharCommand::removeAt, pos, char(0)); + this->push(cc); + } + else + { + QString txt = QString(tr("Delete %1 chars")).arg(len); + beginMacro(txt); + for (qint64 cnt=0; cnt= 0) && (pos < _chunks->size())) + { + QUndoCommand *cc = new CharCommand(_chunks, CharCommand::overwrite, pos, c); + this->push(cc); + } +} + +void UndoStack::overwrite(qint64 pos, int len, const QByteArray &ba) +{ + if ((pos >= 0) && (pos < _chunks->size())) + { + QString txt = QString(tr("Overwrite %1 chars")).arg(len); + beginMacro(txt); + removeAt(pos, len); + insert(pos, ba); + endMacro(); + } +} diff --git a/UEFITool/qhexedit2/commands.h b/UEFITool/qhexedit2/commands.h new file mode 100644 index 0000000..9c34683 --- /dev/null +++ b/UEFITool/qhexedit2/commands.h @@ -0,0 +1,47 @@ +#ifndef COMMANDS_H +#define COMMANDS_H + +/** \cond docNever */ + +#include + +#include "chunks.h" + +/*! CharCommand is a class to provid undo/redo functionality in QHexEdit. +A QUndoCommand represents a single editing action on a document. CharCommand +is responsable for manipulations on single chars. It can insert. overwrite and +remove characters. A manipulation stores allways two actions +1. redo (or do) action +2. undo action. + +CharCommand also supports command compression via mergeWidht(). This allows +the user to execute a undo command contation e.g. 3 steps in a single command. +If you for example insert a new byt "34" this means for the editor doing 3 +steps: insert a "00", overwrite it with "03" and the overwrite it with "34". These +3 steps are combined into a single step, insert a "34". + +The byte array oriented commands are just put into a set of single byte commands, +which are pooled together with the macroBegin() and macroEnd() functionality of +Qt's QUndoStack. +*/ + +class UndoStack : public QUndoStack +{ + Q_OBJECT + +public: + UndoStack(Chunks *chunks, QObject * parent=0); + void insert(qint64 pos, char c); + void insert(qint64 pos, const QByteArray &ba); + void removeAt(qint64 pos, qint64 len=1); + void overwrite(qint64 pos, char c); + void overwrite(qint64 pos, int len, const QByteArray &ba); + +private: + Chunks * _chunks; + QObject * _parent; +}; + +/** \endcond docNever */ + +#endif // COMMANDS_H diff --git a/UEFITool/qhexedit2/license.txt b/UEFITool/qhexedit2/license.txt new file mode 100644 index 0000000..f166cc5 --- /dev/null +++ b/UEFITool/qhexedit2/license.txt @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! \ No newline at end of file diff --git a/UEFITool/qhexedit2/qhexedit.cpp b/UEFITool/qhexedit2/qhexedit.cpp new file mode 100644 index 0000000..e81189b --- /dev/null +++ b/UEFITool/qhexedit2/qhexedit.cpp @@ -0,0 +1,1085 @@ +#include +#include +#include +#include +#include + +#include "qhexedit.h" +#include + + +// ********************************************************************** Constructor, destructor + +QHexEdit::QHexEdit(QWidget *parent) : QAbstractScrollArea(parent) +{ + _addressArea = true; + _addressWidth = 4; + _asciiArea = true; + _overwriteMode = true; + _highlighting = true; + _readOnly = false; + _cursorPosition = 0; + _lastEventSize = 0; + _hexCharsInLine = 47; + _bytesPerLine = 16; + _editAreaIsAscii = false; + + _chunks = new Chunks(this); + _undoStack = new UndoStack(_chunks, this); +#ifdef Q_OS_WIN32 + setFont(QFont("Courier", 10)); +#else + setFont(QFont("Monospace", 10)); +#endif + setAddressAreaColor(this->palette().alternateBase().color()); + setHighlightingColor(QColor(0xff, 0xff, 0x99, 0xff)); + setSelectionColor(this->palette().highlight().color()); + + connect(&_cursorTimer, SIGNAL(timeout()), this, SLOT(updateCursor())); + connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(adjust())); + connect(horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(adjust())); + connect(_undoStack, SIGNAL(indexChanged(int)), this, SLOT(dataChangedPrivate(int))); + + _cursorTimer.setInterval(500); + _cursorTimer.start(); + + setAddressWidth(4); + setAddressArea(true); + setAsciiArea(true); + setOverwriteMode(true); + setHighlighting(true); + setReadOnly(false); + + init(); + +} + +QHexEdit::~QHexEdit() +{ +} + +// ********************************************************************** Properties + +void QHexEdit::setAddressArea(bool addressArea) +{ + _addressArea = addressArea; + adjust(); + setCursorPosition(_cursorPosition); + viewport()->update(); +} + +bool QHexEdit::addressArea() +{ + return _addressArea; +} + +void QHexEdit::setAddressAreaColor(const QColor &color) +{ + _addressAreaColor = color; + viewport()->update(); +} + +QColor QHexEdit::addressAreaColor() +{ + return _addressAreaColor; +} + +void QHexEdit::setAddressOffset(qint64 addressOffset) +{ + _addressOffset = addressOffset; + adjust(); + setCursorPosition(_cursorPosition); + viewport()->update(); +} + +qint64 QHexEdit::addressOffset() +{ + return _addressOffset; +} + +void QHexEdit::setAddressWidth(int addressWidth) +{ + _addressWidth = addressWidth; + adjust(); + setCursorPosition(_cursorPosition); + viewport()->update(); +} + +int QHexEdit::addressWidth() +{ + qint64 size = _chunks->size(); + int n = 1; + if (size > Q_INT64_C(0x100000000)){ n += 8; size /= Q_INT64_C(0x100000000);} + if (size > 0x10000){ n += 4; size /= 0x10000;} + if (size > 0x100){ n += 2; size /= 0x100;} + if (size > 0x10){ n += 1; size /= 0x10;} + + if (n > _addressWidth) + return n; + else + return _addressWidth; +} + +void QHexEdit::setAsciiArea(bool asciiArea) +{ + if (!asciiArea) + _editAreaIsAscii = false; + _asciiArea = asciiArea; + adjust(); + setCursorPosition(_cursorPosition); + viewport()->update(); +} + +bool QHexEdit::asciiArea() +{ + return _asciiArea; +} + +void QHexEdit::setBytesPerLine(int count) +{ + _bytesPerLine = count; + _hexCharsInLine = count * 3 - 1; + + adjust(); + setCursorPosition(_cursorPosition); + viewport()->update(); +} + +int QHexEdit::bytesPerLine() +{ + return _bytesPerLine; +} + +void QHexEdit::setCursorPosition(qint64 position) +{ + // 1. delete old cursor + _blink = false; + viewport()->update(_cursorRect); + + // 2. Check, if cursor in range? + if (position > (_chunks->size() * 2 - 1)) + position = _chunks->size() * 2 - (_overwriteMode ? 1 : 0); + + if (position < 0) + position = 0; + + // 3. Calc new position of cursor + _bPosCurrent = position / 2; + _pxCursorY = ((position / 2 - _bPosFirst) / _bytesPerLine + 1) * _pxCharHeight; + int x = (position % (2 * _bytesPerLine)); + if (_editAreaIsAscii) + { + _pxCursorX = x / 2 * _pxCharWidth + _pxPosAsciiX; + _cursorPosition = position & 0xFFFFFFFFFFFFFFFE; + } else { + _pxCursorX = (((x / 2) * 3) + (x % 2)) * _pxCharWidth + _pxPosHexX; + _cursorPosition = position; + } + + if (_overwriteMode) + _cursorRect = QRect(_pxCursorX - horizontalScrollBar()->value(), _pxCursorY + _pxCursorWidth, _pxCharWidth, _pxCursorWidth); + else + _cursorRect = QRect(_pxCursorX - horizontalScrollBar()->value(), _pxCursorY - _pxCharHeight + 4, _pxCursorWidth, _pxCharHeight); + + // 4. Immediately draw new cursor + _blink = true; + viewport()->update(_cursorRect); + emit currentAddressChanged(_bPosCurrent); +} + +qint64 QHexEdit::cursorPosition(QPoint pos) +{ + // Calc cursor position depending on a graphical position + qint64 result = -1; + int posX = pos.x() + horizontalScrollBar()->value(); + int posY = pos.y() - 3; + if ((posX >= _pxPosHexX) && (posX < (_pxPosHexX + (1 + _hexCharsInLine) * _pxCharWidth))) + { + _editAreaIsAscii = false; + int x = (posX - _pxPosHexX) / _pxCharWidth; + x = (x / 3) * 2 + x % 3; + int y = (posY / _pxCharHeight) * 2 * _bytesPerLine; + result = _bPosFirst * 2 + x + y; + } else + if (_asciiArea && (posX >= _pxPosAsciiX) && (posX < (_pxPosAsciiX + (1 + _bytesPerLine) * _pxCharWidth))) + { + _editAreaIsAscii = true; + int x = 2 * (posX - _pxPosAsciiX) / _pxCharWidth; + int y = (posY / _pxCharHeight) * 2 * _bytesPerLine; + result = _bPosFirst * 2 + x + y; + } + return result; +} + +qint64 QHexEdit::cursorPosition() +{ + return _cursorPosition; +} + +void QHexEdit::setData(const QByteArray &ba) +{ + _data = ba; + _bData.setData(_data); + setData(_bData); +} + +QByteArray QHexEdit::data() +{ + return _chunks->data(0, -1); +} + +void QHexEdit::setHighlighting(bool highlighting) +{ + _highlighting = highlighting; + viewport()->update(); +} + +bool QHexEdit::highlighting() +{ + return _highlighting; +} + +void QHexEdit::setHighlightingColor(const QColor &color) +{ + _brushHighlighted = QBrush(color); + _penHighlighted = QPen(viewport()->palette().color(QPalette::WindowText)); + viewport()->update(); +} + +QColor QHexEdit::highlightingColor() +{ + return _brushHighlighted.color(); +} + +void QHexEdit::setOverwriteMode(bool overwriteMode) +{ + _overwriteMode = overwriteMode; + emit overwriteModeChanged(overwriteMode); +} + +bool QHexEdit::overwriteMode() +{ + return _overwriteMode; +} + +void QHexEdit::setSelectionColor(const QColor &color) +{ + _brushSelection = QBrush(color); + _penSelection = QPen(Qt::white); + viewport()->update(); +} + +QColor QHexEdit::selectionColor() +{ + return _brushSelection.color(); +} + +bool QHexEdit::isReadOnly() +{ + return _readOnly; +} + +void QHexEdit::setReadOnly(bool readOnly) +{ + _readOnly = readOnly; +} + +bool QHexEdit::isUpperCase() +{ + return _upperCase; +} + +void QHexEdit::setUpperCase(bool upperCase) +{ + _upperCase = upperCase; +} + +// ********************************************************************** Access to data of qhexedit +bool QHexEdit::setData(QIODevice &iODevice) +{ + bool ok = _chunks->setIODevice(iODevice); + init(); + dataChangedPrivate(); + return ok; +} + +QByteArray QHexEdit::dataAt(qint64 pos, qint64 count) +{ + return _chunks->data(pos, count); +} + +bool QHexEdit::write(QIODevice &iODevice, qint64 pos, qint64 count) +{ + return _chunks->write(iODevice, pos, count); +} + +// ********************************************************************** Char handling +void QHexEdit::insert(qint64 index, char ch) +{ + _undoStack->insert(index, ch); + refresh(); +} + +void QHexEdit::remove(qint64 index, qint64 len) +{ + _undoStack->removeAt(index, len); + refresh(); +} + +void QHexEdit::replace(qint64 index, char ch) +{ + _undoStack->overwrite(index, ch); + refresh(); +} + +// ********************************************************************** ByteArray handling +void QHexEdit::insert(qint64 pos, const QByteArray &ba) +{ + _undoStack->insert(pos, ba); + refresh(); +} + +void QHexEdit::replace(qint64 pos, qint64 len, const QByteArray &ba) +{ + _undoStack->overwrite(pos, len, ba); + refresh(); +} + +// ********************************************************************** Utility functions +void QHexEdit::ensureVisible() +{ + if (_cursorPosition < (_bPosFirst * 2)) + verticalScrollBar()->setValue((int)(_cursorPosition / 2 / _bytesPerLine)); + if (_cursorPosition > ((_bPosFirst + (_rowsShown - 1)*_bytesPerLine) * 2)) + verticalScrollBar()->setValue((int)(_cursorPosition / 2 / _bytesPerLine) - _rowsShown + 1); + if (_pxCursorX < horizontalScrollBar()->value()) + horizontalScrollBar()->setValue(_pxCursorX); + if ((_pxCursorX + _pxCharWidth) > (horizontalScrollBar()->value() + viewport()->width())) + horizontalScrollBar()->setValue(_pxCursorX + _pxCharWidth - viewport()->width()); + viewport()->update(); +} + +qint64 QHexEdit::indexOf(const QByteArray &ba, qint64 from) +{ + qint64 pos = _chunks->indexOf(ba, from); + if (pos > -1) + { + qint64 curPos = pos*2; + setCursorPosition(curPos + ba.length()*2); + resetSelection(curPos); + setSelection(curPos + ba.length()*2); + ensureVisible(); + } + return pos; +} + +bool QHexEdit::isModified() +{ + return _modified; +} + +qint64 QHexEdit::lastIndexOf(const QByteArray &ba, qint64 from) +{ + qint64 pos = _chunks->lastIndexOf(ba, from); + if (pos > -1) + { + qint64 curPos = pos*2; + setCursorPosition(curPos - 1); + resetSelection(curPos); + setSelection(curPos + ba.length()*2); + ensureVisible(); + } + return pos; +} + +void QHexEdit::redo() +{ + _undoStack->redo(); + setCursorPosition(_chunks->pos()*(_editAreaIsAscii ? 1 : 2)); + refresh(); +} + +QString QHexEdit::selectionToReadableString() +{ + QByteArray ba = _chunks->data(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()); + return toReadable(ba); +} + +void QHexEdit::setFont(const QFont &font) +{ + QWidget::setFont(font); + _pxCharWidth = fontMetrics().width(QLatin1Char('2')); + _pxCharHeight = fontMetrics().height(); + _pxGapAdr = _pxCharWidth / 2; + _pxGapAdrHex = _pxCharWidth; + _pxGapHexAscii = 2 * _pxCharWidth; + _pxCursorWidth = _pxCharHeight / 7; + _pxSelectionSub = _pxCharHeight / 5; + viewport()->update(); +} + +QString QHexEdit::toReadableString() +{ + QByteArray ba = _chunks->data(); + return toReadable(ba); +} + +void QHexEdit::undo() +{ + _undoStack->undo(); + setCursorPosition(_chunks->pos()*(_editAreaIsAscii ? 1 : 2)); + refresh(); +} + +// ********************************************************************** Handle events +void QHexEdit::keyPressEvent(QKeyEvent *event) +{ + // Cursor movements + if (event->matches(QKeySequence::MoveToNextChar)) + { + qint64 pos = _cursorPosition + 1; + if (_editAreaIsAscii) + pos += 1; + setCursorPosition(pos); + resetSelection(pos); + } + if (event->matches(QKeySequence::MoveToPreviousChar)) + { + qint64 pos = _cursorPosition - 1; + if (_editAreaIsAscii) + pos -= 1; + setCursorPosition(pos); + resetSelection(pos); + } + if (event->matches(QKeySequence::MoveToEndOfLine)) + { + qint64 pos = _cursorPosition - (_cursorPosition % (2 * _bytesPerLine)) + (2 * _bytesPerLine) - 1; + setCursorPosition(pos); + resetSelection(_cursorPosition); + } + if (event->matches(QKeySequence::MoveToStartOfLine)) + { + qint64 pos = _cursorPosition - (_cursorPosition % (2 * _bytesPerLine)); + setCursorPosition(pos); + resetSelection(_cursorPosition); + } + if (event->matches(QKeySequence::MoveToPreviousLine)) + { + setCursorPosition(_cursorPosition - (2 * _bytesPerLine)); + resetSelection(_cursorPosition); + } + if (event->matches(QKeySequence::MoveToNextLine)) + { + setCursorPosition(_cursorPosition + (2 * _bytesPerLine)); + resetSelection(_cursorPosition); + } + if (event->matches(QKeySequence::MoveToNextPage)) + { + setCursorPosition(_cursorPosition + (((_rowsShown - 1) * 2 * _bytesPerLine))); + resetSelection(_cursorPosition); + } + if (event->matches(QKeySequence::MoveToPreviousPage)) + { + setCursorPosition(_cursorPosition - (((_rowsShown - 1) * 2 * _bytesPerLine))); + resetSelection(_cursorPosition); + } + if (event->matches(QKeySequence::MoveToEndOfDocument)) + { + setCursorPosition(_chunks->size() * 2 ); + resetSelection(_cursorPosition); + } + if (event->matches(QKeySequence::MoveToStartOfDocument)) + { + setCursorPosition(0); + resetSelection(_cursorPosition); + } + + // Select commands + if (event->matches(QKeySequence::SelectAll)) + { + resetSelection(0); + setSelection(2 * _chunks->size() + 1); + } + if (event->matches(QKeySequence::SelectNextChar)) + { + qint64 pos = _cursorPosition + 1; + if (_editAreaIsAscii) + pos += 1; + setCursorPosition(pos); + setSelection(pos); + } + if (event->matches(QKeySequence::SelectPreviousChar)) + { + qint64 pos = _cursorPosition - 1; + if (_editAreaIsAscii) + pos -= 1; + setSelection(pos); + setCursorPosition(pos); + } + if (event->matches(QKeySequence::SelectEndOfLine)) + { + qint64 pos = _cursorPosition - (_cursorPosition % (2 * _bytesPerLine)) + (2 * _bytesPerLine) - 1; + setCursorPosition(pos); + setSelection(pos); + } + if (event->matches(QKeySequence::SelectStartOfLine)) + { + qint64 pos = _cursorPosition - (_cursorPosition % (2 * _bytesPerLine)); + setCursorPosition(pos); + setSelection(pos); + } + if (event->matches(QKeySequence::SelectPreviousLine)) + { + qint64 pos = _cursorPosition - (2 * _bytesPerLine); + setCursorPosition(pos); + setSelection(pos); + } + if (event->matches(QKeySequence::SelectNextLine)) + { + qint64 pos = _cursorPosition + (2 * _bytesPerLine); + setCursorPosition(pos); + setSelection(pos); + } + if (event->matches(QKeySequence::SelectNextPage)) + { + qint64 pos = _cursorPosition + (((viewport()->height() / _pxCharHeight) - 1) * 2 * _bytesPerLine); + setCursorPosition(pos); + setSelection(pos); + } + if (event->matches(QKeySequence::SelectPreviousPage)) + { + qint64 pos = _cursorPosition - (((viewport()->height() / _pxCharHeight) - 1) * 2 * _bytesPerLine); + setCursorPosition(pos); + setSelection(pos); + } + if (event->matches(QKeySequence::SelectEndOfDocument)) + { + qint64 pos = _chunks->size() * 2; + setCursorPosition(pos); + setSelection(pos); + } + if (event->matches(QKeySequence::SelectStartOfDocument)) + { + qint64 pos = 0; + setCursorPosition(pos); + setSelection(pos); + } + + // Edit Commands + if (!_readOnly) + { + /* Cut */ + if (event->matches(QKeySequence::Cut)) + { + QByteArray ba = _chunks->data(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()).toHex(); + for (qint64 idx = 32; idx < ba.size(); idx +=33) + ba.insert(idx, "\n"); + QClipboard *clipboard = QApplication::clipboard(); + clipboard->setText(ba); + if (_overwriteMode) + { + qint64 len = getSelectionEnd() - getSelectionBegin(); + replace(getSelectionBegin(), (int)len, QByteArray((int)len, char(0))); + } + else + { + remove(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()); + } + setCursorPosition(2 * getSelectionBegin()); + resetSelection(2 * getSelectionBegin()); + } else + + /* Paste */ + if (event->matches(QKeySequence::Paste)) + { + QClipboard *clipboard = QApplication::clipboard(); + QByteArray ba = QByteArray().fromHex(clipboard->text().toLatin1()); + if (_overwriteMode) + { + ba = ba.left(std::min(ba.size(), (_chunks->size() - _bPosCurrent))); + replace(_bPosCurrent, ba.size(), ba); + } + else + insert(_bPosCurrent, ba); + setCursorPosition(_cursorPosition + 2 * ba.size()); + resetSelection(getSelectionBegin()); + } else + + /* Delete char */ + if (event->matches(QKeySequence::Delete)) + { + if (getSelectionBegin() != getSelectionEnd()) + { + _bPosCurrent = getSelectionBegin(); + if (_overwriteMode) + { + QByteArray ba = QByteArray(getSelectionEnd() - getSelectionBegin(), char(0)); + replace(_bPosCurrent, ba.size(), ba); + } + else + { + remove(_bPosCurrent, getSelectionEnd() - getSelectionBegin()); + } + } + else + { + if (_overwriteMode) + replace(_bPosCurrent, char(0)); + else + remove(_bPosCurrent, 1); + } + setCursorPosition(2 * _bPosCurrent); + resetSelection(2 * _bPosCurrent); + } else + + /* Backspace */ + if ((event->key() == Qt::Key_Backspace) && (event->modifiers() == Qt::NoModifier)) + { + if (getSelectionBegin() != getSelectionEnd()) + { + _bPosCurrent = getSelectionBegin(); + setCursorPosition(2 * _bPosCurrent); + if (_overwriteMode) + { + QByteArray ba = QByteArray(getSelectionEnd() - getSelectionBegin(), char(0)); + replace(_bPosCurrent, ba.size(), ba); + } + else + { + remove(_bPosCurrent, getSelectionEnd() - getSelectionBegin()); + } + resetSelection(2 * _bPosCurrent); + } + else + { + bool behindLastByte = false; + if ((_cursorPosition / 2) == _chunks->size()) + behindLastByte = true; + + _bPosCurrent -= 1; + if (_overwriteMode) + replace(_bPosCurrent, char(0)); + else + remove(_bPosCurrent, 1); + + if (!behindLastByte) + _bPosCurrent -= 1; + + setCursorPosition(2 * _bPosCurrent); + resetSelection(2 * _bPosCurrent); + } + } else + + /* undo */ + if (event->matches(QKeySequence::Undo)) + { + undo(); + } else + + /* redo */ + if (event->matches(QKeySequence::Redo)) + { + redo(); + } else + + if ((QApplication::keyboardModifiers() == Qt::NoModifier) || + (QApplication::keyboardModifiers() == Qt::KeypadModifier) || + (QApplication::keyboardModifiers() == Qt::ShiftModifier) || + (QApplication::keyboardModifiers() == (Qt::AltModifier | Qt::ControlModifier)) || + (QApplication::keyboardModifiers() == Qt::GroupSwitchModifier)) + { + /* Hex and ascii input */ + int key; + if (_editAreaIsAscii) + key = (uchar)event->text()[0].toLatin1(); + else + key = int(event->text()[0].toLower().toLatin1()); + + if ((((key >= '0' && key <= '9') || (key >= 'a' && key <= 'f')) && _editAreaIsAscii == false) + || (key >= ' ' && _editAreaIsAscii)) + { + if (getSelectionBegin() != getSelectionEnd()) + { + if (_overwriteMode) + { + qint64 len = getSelectionEnd() - getSelectionBegin(); + replace(getSelectionBegin(), (int)len, QByteArray((int)len, char(0))); + } else + { + remove(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()); + _bPosCurrent = getSelectionBegin(); + } + setCursorPosition(2 * _bPosCurrent); + resetSelection(2 * _bPosCurrent); + } + + // If insert mode, then insert a byte + if (_overwriteMode == false) + if ((_cursorPosition % 2) == 0) + insert(_bPosCurrent, char(0)); + + // Change content + if (_chunks->size() > 0) + { + char ch = key; + if (!_editAreaIsAscii){ + QByteArray hexValue = _chunks->data(_bPosCurrent, 1).toHex(); + if ((_cursorPosition % 2) == 0) + hexValue[0] = key; + else + hexValue[1] = key; + ch = QByteArray().fromHex(hexValue)[0]; + } + replace(_bPosCurrent, ch); + if (_editAreaIsAscii) + setCursorPosition(_cursorPosition + 2); + else + setCursorPosition(_cursorPosition + 1); + resetSelection(_cursorPosition); + } + } + } + } + + /* Copy */ + if (event->matches(QKeySequence::Copy)) + { + QByteArray ba = _chunks->data(getSelectionBegin(), getSelectionEnd() - getSelectionBegin()).toHex(); + for (qint64 idx = 32; idx < ba.size(); idx += 33) + ba.insert(idx, "\n"); + if(_upperCase) + ba = ba.toUpper(); + QClipboard *clipboard = QApplication::clipboard(); + clipboard->setText(ba); + } + + // Switch between insert/overwrite mode + if ((event->key() == Qt::Key_Insert) && (event->modifiers() == Qt::NoModifier)) + { + setOverwriteMode(!overwriteMode()); + setCursorPosition(_cursorPosition); + } + + // switch from hex to ascii edit + if (event->key() == Qt::Key_Tab && !_editAreaIsAscii){ + _editAreaIsAscii = true; + setCursorPosition(_cursorPosition); + } + + // switch from ascii to hex edit + if (event->key() == Qt::Key_Backtab && _editAreaIsAscii){ + _editAreaIsAscii = false; + setCursorPosition(_cursorPosition); + } + + refresh(); +} + +void QHexEdit::mouseMoveEvent(QMouseEvent * event) +{ + _blink = false; + viewport()->update(); + qint64 actPos = cursorPosition(event->pos()); + if (actPos >= 0) + { + setCursorPosition(actPos); + setSelection(actPos); + } +} + +void QHexEdit::mousePressEvent(QMouseEvent * event) +{ + _blink = false; + viewport()->update(); + qint64 cPos = cursorPosition(event->pos()); + if (cPos >= 0) + { + resetSelection(cPos); + setCursorPosition(cPos); + } +} + +void QHexEdit::paintEvent(QPaintEvent *event) +{ + QPainter painter(viewport()); + int pxOfsX = horizontalScrollBar()->value(); + + if (event->rect() != _cursorRect) + { + int pxPosStartY = _pxCharHeight; + + // draw some patterns if needed + painter.fillRect(event->rect(), viewport()->palette().color(QPalette::Base)); + if (_addressArea) + painter.fillRect(QRect(-pxOfsX, event->rect().top(), _pxPosHexX - _pxGapAdrHex/2, height()), _addressAreaColor); + if (_asciiArea) + { + int linePos = _pxPosAsciiX - (_pxGapHexAscii / 2); + painter.setPen(Qt::gray); + painter.drawLine(linePos - pxOfsX, event->rect().top(), linePos - pxOfsX, height()); + } + + painter.setPen(viewport()->palette().color(QPalette::WindowText)); + + // paint address area + if (_addressArea) + { + QString address; + for (int row=0, pxPosY = _pxCharHeight; row <= (_dataShown.size()/_bytesPerLine); row++, pxPosY +=_pxCharHeight) + { + address = QString("%1").arg(_bPosFirst + row*_bytesPerLine + _addressOffset, _addrDigits, 16, QChar('0')); + // upper or lower case + if (_upperCase) + address = address.toUpper(); + + painter.drawText(_pxPosAdrX - pxOfsX, pxPosY, address); + } + } + + // paint hex and ascii area + QPen colStandard = QPen(viewport()->palette().color(QPalette::WindowText)); + + painter.setBackgroundMode(Qt::TransparentMode); + + for (int row = 0, pxPosY = pxPosStartY; row <= _rowsShown; row++, pxPosY +=_pxCharHeight) + { + QByteArray hex; + int pxPosX = _pxPosHexX - pxOfsX; + int pxPosAsciiX2 = _pxPosAsciiX - pxOfsX; + qint64 bPosLine = row * _bytesPerLine; + for (int colIdx = 0; ((bPosLine + colIdx) < _dataShown.size() && (colIdx < _bytesPerLine)); colIdx++) + { + QColor c = viewport()->palette().color(QPalette::Base); + painter.setPen(colStandard); + + qint64 posBa = _bPosFirst + bPosLine + colIdx; + if ((getSelectionBegin() <= posBa) && (getSelectionEnd() > posBa)) + { + c = _brushSelection.color(); + painter.setPen(_penSelection); + } + else + { + if (_highlighting) + if (_markedShown.at((int)(posBa - _bPosFirst))) + { + c = _brushHighlighted.color(); + painter.setPen(_penHighlighted); + } + } + + // render hex value + QRect r; + if (colIdx == 0) + r.setRect(pxPosX, pxPosY - _pxCharHeight + _pxSelectionSub, 2*_pxCharWidth, _pxCharHeight); + else + r.setRect(pxPosX - _pxCharWidth, pxPosY - _pxCharHeight + _pxSelectionSub, 3*_pxCharWidth, _pxCharHeight); + painter.fillRect(r, c); + hex = _hexDataShown.mid((bPosLine + colIdx) * 2, 2); + + // upper or lower case + if (_upperCase) + hex = hex.toUpper(); + + painter.drawText(pxPosX, pxPosY, hex); + pxPosX += 3*_pxCharWidth; + + // render ascii value + if (_asciiArea) + { + int ch = (uchar)_dataShown.at(bPosLine + colIdx); + if ( ch < 0x20 ) + ch = '.'; + r.setRect(pxPosAsciiX2, pxPosY - _pxCharHeight + _pxSelectionSub, _pxCharWidth, _pxCharHeight); + painter.fillRect(r, c); + painter.drawText(pxPosAsciiX2, pxPosY, QChar(ch)); + pxPosAsciiX2 += _pxCharWidth; + } + } + } + painter.setBackgroundMode(Qt::TransparentMode); + painter.setPen(viewport()->palette().color(QPalette::WindowText)); + } + + // paint cursor + if (_blink && !_readOnly && hasFocus()) + painter.fillRect(_cursorRect, this->palette().color(QPalette::WindowText)); + else + painter.drawRect(QRect(_pxCursorX - pxOfsX, _pxCursorY - _pxCharHeight + 2, _pxCharWidth, _pxCharHeight - 1)); + + // emit event, if size has changed + if (_lastEventSize != _chunks->size()) + { + _lastEventSize = _chunks->size(); + emit currentSizeChanged(_lastEventSize); + } +} + +void QHexEdit::resizeEvent(QResizeEvent *) +{ + adjust(); +} + +bool QHexEdit::focusNextPrevChild(bool next) +{ + if (_addressArea) + { + if ((next && _editAreaIsAscii) || (!next && !_editAreaIsAscii)) + return QWidget::focusNextPrevChild(next); + else + return false; + } + else + { + return QWidget::focusNextPrevChild(next); + } +} + +// ********************************************************************** Handle selections +void QHexEdit::resetSelection() +{ + _bSelectionBegin = _bSelectionInit; + _bSelectionEnd = _bSelectionInit; +} + +void QHexEdit::resetSelection(qint64 pos) +{ + pos = pos / 2 ; + if (pos < 0) + pos = 0; + if (pos > _chunks->size()) + pos = _chunks->size(); + + _bSelectionInit = pos; + _bSelectionBegin = pos; + _bSelectionEnd = pos; +} + +void QHexEdit::setSelection(qint64 pos) +{ + pos = pos / 2; + if (pos < 0) + pos = 0; + if (pos > _chunks->size()) + pos = _chunks->size(); + + if (pos >= _bSelectionInit) + { + _bSelectionEnd = pos; + _bSelectionBegin = _bSelectionInit; + } + else + { + _bSelectionBegin = pos; + _bSelectionEnd = _bSelectionInit; + } +} + +int QHexEdit::getSelectionBegin() +{ + return _bSelectionBegin; +} + +int QHexEdit::getSelectionEnd() +{ + return _bSelectionEnd; +} + +// ********************************************************************** Private utility functions +void QHexEdit::init() +{ + _undoStack->clear(); + setAddressOffset(0); + resetSelection(0); + setCursorPosition(0); + verticalScrollBar()->setValue(0); + _modified = false; +} + +void QHexEdit::adjust() +{ + // recalc Graphics + if (_addressArea) + { + _addrDigits = addressWidth(); + _pxPosHexX = _pxGapAdr + _addrDigits*_pxCharWidth + _pxGapAdrHex; + } + else + _pxPosHexX = _pxGapAdrHex; + _pxPosAdrX = _pxGapAdr; + _pxPosAsciiX = _pxPosHexX + _hexCharsInLine * _pxCharWidth + _pxGapHexAscii; + + // set horizontalScrollBar() + int pxWidth = _pxPosAsciiX; + if (_asciiArea) + pxWidth += _bytesPerLine*_pxCharWidth; + horizontalScrollBar()->setRange(0, pxWidth - viewport()->width()); + horizontalScrollBar()->setPageStep(viewport()->width()); + + // set verticalScrollbar() + _rowsShown = ((viewport()->height()-4)/_pxCharHeight); + int lineCount = (int)(_chunks->size() / (qint64)_bytesPerLine) + 1; + verticalScrollBar()->setRange(0, lineCount - _rowsShown); + verticalScrollBar()->setPageStep(_rowsShown); + + int value = verticalScrollBar()->value(); + _bPosFirst = (qint64)value * _bytesPerLine; + _bPosLast = _bPosFirst + (qint64)(_rowsShown * _bytesPerLine) - 1; + if (_bPosLast >= _chunks->size()) + _bPosLast = _chunks->size() - 1; + readBuffers(); + setCursorPosition(_cursorPosition); +} + +void QHexEdit::dataChangedPrivate(int) +{ + _modified = _undoStack->index() != 0; + adjust(); + emit dataChanged(); +} + +void QHexEdit::refresh() +{ + ensureVisible(); + readBuffers(); +} + +void QHexEdit::readBuffers() +{ + _dataShown = _chunks->data(_bPosFirst, _bPosLast - _bPosFirst + _bytesPerLine + 1, &_markedShown); + _hexDataShown = QByteArray(_dataShown.toHex()); +} + +QString QHexEdit::toReadable(const QByteArray &ba) +{ + QString result; + + for (int i=0; i < ba.size(); i += 16) + { + QString addrStr = QString("%1").arg(_addressOffset + i, addressWidth(), 16, QChar('0')); + QString hexStr; + QString ascStr; + for (int j=0; j<16; j++) + { + if ((i + j) < ba.size()) + { + hexStr.append(" ").append(ba.mid(i+j, 1).toHex()); + char ch = ba[i + j]; + if ((ch < 0x20) || (ch > 0x7e)) + ch = '.'; + ascStr.append(QChar(ch)); + } + } + result += addrStr + " " + QString("%1").arg(hexStr, -48) + " " + QString("%1").arg(ascStr, -17) + "\n"; + } + return result; +} + +void QHexEdit::updateCursor() +{ + if (_blink) + _blink = false; + else + _blink = true; + viewport()->update(_cursorRect); +} diff --git a/UEFITool/qhexedit2/qhexedit.h b/UEFITool/qhexedit2/qhexedit.h new file mode 100644 index 0000000..76d8670 --- /dev/null +++ b/UEFITool/qhexedit2/qhexedit.h @@ -0,0 +1,411 @@ +#ifndef QHEXEDIT_H +#define QHEXEDIT_H + +#include +#include +#include + +#include "chunks.h" +#include "commands.h" + +#ifdef QHEXEDIT_EXPORTS +#define QHEXEDIT_API Q_DECL_EXPORT +#elif QHEXEDIT_IMPORTS +#define QHEXEDIT_API Q_DECL_IMPORT +#else +#define QHEXEDIT_API +#endif + +/** \mainpage +QHexEdit is a binary editor widget for Qt. + +\version Version 0.8.2 +\image html qhexedit.png +*/ + + +/** QHexEdit is a hex editor widget written in C++ for the Qt (Qt4, Qt5) framework. +It is a simple editor for binary data, just like QPlainTextEdit is for text +data. There are sip configuration files included, so it is easy to create +bindings for PyQt and you can use this widget also in python 2 and 3. + +QHexEdit takes the data of a QByteArray (setData()) and shows it. You can use +the mouse or the keyboard to navigate inside the widget. If you hit the keys +(0..9, a..f) you will change the data. Changed data is highlighted and can be +accessed via data(). + +Normaly QHexEdit works in the overwrite Mode. You can set overwriteMode(false) +and insert data. In this case the size of data() increases. It is also possible +to delete bytes (del or backspace), here the size of data decreases. + +You can select data with keyboard hits or mouse movements. The copy-key will +copy the selected data into the clipboard. The cut-key copies also but delets +it afterwards. In overwrite mode, the paste function overwrites the content of +the (does not change the length) data. In insert mode, clipboard data will be +inserted. The clipboard content is expected in ASCII Hex notation. Unknown +characters will be ignored. + +QHexEdit comes with undo/redo functionality. All changes can be undone, by +pressing the undo-key (usually ctr-z). They can also be redone afterwards. +The undo/redo framework is cleared, when setData() sets up a new +content for the editor. You can search data inside the content with indexOf() +and lastIndexOf(). The replace() function is to change located subdata. This +'replaced' data can also be undone by the undo/redo framework. + +QHexEdit is based on QIODevice, that's why QHexEdit can handle big amounts of +data. The size of edited data can be more then two gigabytes without any +restrictions. +*/ +class QHEXEDIT_API QHexEdit : public QAbstractScrollArea +{ + Q_OBJECT + + /*! Property address area switch the address area on or off. Set addressArea true + (show it), false (hide it). + */ + Q_PROPERTY(bool addressArea READ addressArea WRITE setAddressArea) + + /*! Property address area color sets (setAddressAreaColor()) the backgorund + color of address areas. You can also read the color (addressaAreaColor()). + */ + Q_PROPERTY(QColor addressAreaColor READ addressAreaColor WRITE setAddressAreaColor) + + /*! Property addressOffset is added to the Numbers of the Address Area. + A offset in the address area (left side) is sometimes usefull, whe you show + only a segment of a complete memory picture. With setAddressOffset() you set + this property - with addressOffset() you get the current value. + */ + Q_PROPERTY(qint64 addressOffset READ addressOffset WRITE setAddressOffset) + + /*! Set and get the minimum width of the address area, width in characters. + */ + Q_PROPERTY(int addressWidth READ addressWidth WRITE setAddressWidth) + + /*! Switch the ascii area on (true, show it) or off (false, hide it). + */ + Q_PROPERTY(bool asciiArea READ asciiArea WRITE setAsciiArea) + + /*! Set and get bytes number per line.*/ + Q_PROPERTY(int bytesPerLine READ bytesPerLine WRITE setBytesPerLine) + + /*! Porperty cursorPosition sets or gets the position of the editor cursor + in QHexEdit. Every byte in data has to cursor positions: the lower and upper + Nibble. Maximum cursor position is factor two of data.size(). + */ + Q_PROPERTY(qint64 cursorPosition READ cursorPosition WRITE setCursorPosition) + + /*! Property data holds the content of QHexEdit. Call setData() to set the + content of QHexEdit, data() returns the actual content. When calling setData() + with a QByteArray as argument, QHexEdit creates a internal copy of the data + If you want to edit big files please use setData(), based on QIODevice. + */ + Q_PROPERTY(QByteArray data READ data WRITE setData NOTIFY dataChanged) + + /*! Switch the highlighting feature on or of: true (show it), false (hide it). + */ + Q_PROPERTY(bool highlighting READ highlighting WRITE setHighlighting) + + /*! Property highlighting color sets (setHighlightingColor()) the backgorund + color of highlighted text areas. You can also read the color + (highlightingColor()). + */ + Q_PROPERTY(QColor highlightingColor READ highlightingColor WRITE setHighlightingColor) + + /*! Porperty overwrite mode sets (setOverwriteMode()) or gets (overwriteMode()) the mode + in which the editor works. In overwrite mode the user will overwrite existing data. The + size of data will be constant. In insert mode the size will grow, when inserting + new data. + */ + Q_PROPERTY(bool overwriteMode READ overwriteMode WRITE setOverwriteMode) + + /*! Property selection color sets (setSelectionColor()) the backgorund + color of selected text areas. You can also read the color + (selectionColor()). + */ + Q_PROPERTY(QColor selectionColor READ selectionColor WRITE setSelectionColor) + + /*! Property readOnly sets (setReadOnly()) or gets (isReadOnly) the mode + in which the editor works. In readonly mode the the user can only navigate + through the data and select data; modifying is not possible. This + property's default is false. + */ + Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) + + /*! Property upperCase sets (setUpperCase()) or gets (isUpperCase) the case of hex + data. Default is lowercase. + */ + Q_PROPERTY(bool upperCase READ isUpperCase WRITE setUpperCase) + + /*! Set the font of the widget. Please use fixed width fonts like Mono or Courier.*/ + Q_PROPERTY(QFont font READ font WRITE setFont) + +public: + /*! Creates an instance of QHexEdit. + \param parent Parent widget of QHexEdit. + */ + QHexEdit(QWidget *parent=0); + + // Access to data of qhexedit + + /*! Sets the data of QHexEdit. The QIODevice will be opend just before reading + and closed immediately afterwards. This is to allow other programs to rewrite + the file while editing it. + */ + bool setData(QIODevice &iODevice); + + /*! Gives back the data as a QByteArray starting at position \param pos and + delivering \param count bytes. + */ + QByteArray dataAt(qint64 pos, qint64 count=-1); + + /*! Gives back the data into a \param iODevice starting at position \param pos + and delivering \param count bytes. + */ + bool write(QIODevice &iODevice, qint64 pos=0, qint64 count=-1); + + + // Char handling + + /*! Inserts a char. + \param pos Index position, where to insert + \param ch Char, which is to insert + The char will be inserted and size of data grows. + */ + void insert(qint64 pos, char ch); + + /*! Removes len bytes from the content. + \param pos Index position, where to remove + \param len Amount of bytes to remove + */ + void remove(qint64 pos, qint64 len=1); + + /*! Replaces a char. + \param pos Index position, where to overwrite + \param ch Char, which is to insert + The char will be overwritten and size remains constant. + */ + void replace(qint64 pos, char ch); + + + // ByteArray handling + + /*! Inserts a byte array. + \param pos Index position, where to insert + \param ba QByteArray, which is to insert + The QByteArray will be inserted and size of data grows. + */ + void insert(qint64 pos, const QByteArray &ba); + + /*! Replaces \param len bytes with a byte array \param ba + \param pos Index position, where to overwrite + \param ba QByteArray, which is inserted + \param len count of bytes to overwrite + The data is overwritten and size of data may change. + */ + void replace(qint64 pos, qint64 len, const QByteArray &ba); + + + // Utility functioins + /*! Calc cursor position from graphics position + * \param point from where the cursor position should be calculated + * \return Cursor postioin + */ + qint64 cursorPosition(QPoint point); + + /*! Ensure the cursor to be visble + */ + void ensureVisible(); + + /*! Find first occurence of ba in QHexEdit data + * \param ba Data to find + * \param from Point where the search starts + * \return pos if fond, else -1 + */ + qint64 indexOf(const QByteArray &ba, qint64 from); + + /*! Returns if any changes where done on document + * \return true when document is modified else false + */ + bool isModified(); + + /*! Find last occurence of ba in QHexEdit data + * \param ba Data to find + * \param from Point where the search starts + * \return pos if fond, else -1 + */ + qint64 lastIndexOf(const QByteArray &ba, qint64 from); + + /*! Gives back a formatted image of the selected content of QHexEdit + */ + QString selectionToReadableString(); + + /*! Set Font of QHexEdit + * \param font + */ + void setFont(const QFont &font); + + /*! Gives back a formatted image of the content of QHexEdit + */ + QString toReadableString(); + + +public slots: + /*! Redoes the last operation. If there is no operation to redo, i.e. + there is no redo step in the undo/redo history, nothing happens. + */ + void redo(); + + /*! Undoes the last operation. If there is no operation to undo, i.e. + there is no undo step in the undo/redo history, nothing happens. + */ + void undo(); + +signals: + + /*! Contains the address, where the cursor is located. */ + void currentAddressChanged(qint64 address); + + /*! Contains the size of the data to edit. */ + void currentSizeChanged(qint64 size); + + /*! The signal is emitted every time, the data is changed. */ + void dataChanged(); + + /*! The signal is emitted every time, the overwrite mode is changed. */ + void overwriteModeChanged(bool state); + + +/*! \cond docNever */ +public: + ~QHexEdit(); + + // Properties + bool addressArea(); + void setAddressArea(bool addressArea); + + QColor addressAreaColor(); + void setAddressAreaColor(const QColor &color); + + qint64 addressOffset(); + void setAddressOffset(qint64 addressArea); + + int addressWidth(); + void setAddressWidth(int addressWidth); + + bool asciiArea(); + void setAsciiArea(bool asciiArea); + + int bytesPerLine(); + void setBytesPerLine(int count); + + qint64 cursorPosition(); + void setCursorPosition(qint64 position); + + QByteArray data(); + void setData(const QByteArray &ba); + + bool highlighting(); + void setHighlighting(bool mode); + + QColor highlightingColor(); + void setHighlightingColor(const QColor &color); + + bool overwriteMode(); + void setOverwriteMode(bool overwriteMode); + + bool isReadOnly(); + void setReadOnly(bool readOnly); + + bool isUpperCase(); + void setUpperCase(bool upperCase); + + QColor selectionColor(); + void setSelectionColor(const QColor &color); + +protected: + // Handle events + void keyPressEvent(QKeyEvent *event); + void mouseMoveEvent(QMouseEvent * event); + void mousePressEvent(QMouseEvent * event); + void paintEvent(QPaintEvent *event); + void resizeEvent(QResizeEvent *); + virtual bool focusNextPrevChild(bool next); +private: + // Handle selections + void resetSelection(qint64 pos); // set selectionStart and selectionEnd to pos + void resetSelection(); // set selectionEnd to selectionStart + void setSelection(qint64 pos); // set min (if below init) or max (if greater init) + int getSelectionBegin(); + int getSelectionEnd(); + + // Private utility functions + void init(); + void readBuffers(); + QString toReadable(const QByteArray &ba); + +private slots: + void adjust(); // recalc pixel positions + void dataChangedPrivate(int idx=0); // emit dataChanged() signal + void refresh(); // ensureVisible() and readBuffers() + void updateCursor(); // update blinking cursor + +private: + // Name convention: pixel positions start with _px + int _pxCharWidth, _pxCharHeight; // char dimensions (dpendend on font) + int _pxPosHexX; // X-Pos of HeaxArea + int _pxPosAdrX; // X-Pos of Address Area + int _pxPosAsciiX; // X-Pos of Ascii Area + int _pxGapAdr; // gap left from AddressArea + int _pxGapAdrHex; // gap between AddressArea and HexAerea + int _pxGapHexAscii; // gap between HexArea and AsciiArea + int _pxCursorWidth; // cursor width + int _pxSelectionSub; // offset selection rect + int _pxCursorX; // current cursor pos + int _pxCursorY; // current cursor pos + + // Name convention: absolute byte positions in chunks start with _b + qint64 _bSelectionBegin; // first position of Selection + qint64 _bSelectionEnd; // end of Selection + qint64 _bSelectionInit; // memory position of Selection + qint64 _bPosFirst; // position of first byte shown + qint64 _bPosLast; // position of last byte shown + qint64 _bPosCurrent; // current position + + // variables to store the property values + bool _addressArea; // left area of QHexEdit + QColor _addressAreaColor; + int _addressWidth; + bool _asciiArea; + qint64 _addressOffset; + int _bytesPerLine; + int _hexCharsInLine; + bool _highlighting; + bool _overwriteMode; + QBrush _brushSelection; + QPen _penSelection; + QBrush _brushHighlighted; + QPen _penHighlighted; + bool _readOnly; + bool _upperCase; + + // other variables + bool _editAreaIsAscii; // flag about the ascii mode edited + int _addrDigits; // real no of addressdigits, may be > addressWidth + bool _blink; // help get cursor blinking + QBuffer _bData; // buffer, when setup with QByteArray + Chunks *_chunks; // IODevice based access to data + QTimer _cursorTimer; // for blinking cursor + qint64 _cursorPosition; // absolute position of cursor, 1 Byte == 2 tics + QRect _cursorRect; // physical dimensions of cursor + QByteArray _data; // QHexEdit's data, when setup with QByteArray + QByteArray _dataShown; // data in the current View + QByteArray _hexDataShown; // data in view, transformed to hex + qint64 _lastEventSize; // size, which was emitted last time + QByteArray _markedShown; // marked data in view + bool _modified; // Is any data in editor modified? + int _rowsShown; // lines of text shown + UndoStack * _undoStack; // Stack to store edit actions for undo/redo + /*! \endcond docNever */ +}; + +#endif // QHEXEDIT_H diff --git a/UEFITool/uefitool.cpp b/UEFITool/uefitool.cpp index 87ad8a6..199e596 100644 --- a/UEFITool/uefitool.cpp +++ b/UEFITool/uefitool.cpp @@ -18,7 +18,7 @@ UEFITool::UEFITool(QWidget *parent) : QMainWindow(parent), ui(new Ui::UEFITool), -version(tr("NE Alpha 37")) +version(tr("NE Alpha 38")) { clipboard = QApplication::clipboard(); @@ -327,6 +327,8 @@ void UEFITool::bodyHexView() void UEFITool::goToOffset() { + goToOffsetDialog->ui->hexSpinBox->setFocus(); + goToOffsetDialog->ui->hexSpinBox->selectAll(); if (goToOffsetDialog->exec() != QDialog::Accepted) return; @@ -810,9 +812,7 @@ void UEFITool::openImageFile(QString path) delete ffsOps; ffsOps = new FfsOperations(model); - // Set max offset and enable goToOffset - // FIXME: doesn't work properly - //goToOffsetDialog->ui->hexSpinBox->setMaximum(buffer.size() - 1); + // Enable goToOffset ui->actionGoToOffset->setEnabled(true); // Enable or disable FIT tab @@ -905,7 +905,7 @@ void UEFITool::showParserMessages() std::pair msg; foreach (msg, messages) { QListWidgetItem* item = new QListWidgetItem(msg.first, NULL, 0); - item->setData(Qt::UserRole, msg.second); + item->setData(Qt::UserRole, QByteArray((const char*)&msg.second, sizeof(msg.second))); ui->parserMessagesListWidget->addItem(item); } @@ -923,7 +923,7 @@ void UEFITool::showFinderMessages() std::pair msg; foreach (msg, messages) { QListWidgetItem* item = new QListWidgetItem(msg.first, NULL, 0); - item->setData(Qt::UserRole, msg.second); + item->setData(Qt::UserRole, QByteArray((const char*)&msg.second, sizeof(msg.second)));; ui->finderMessagesListWidget->addItem(item); } @@ -941,7 +941,7 @@ void UEFITool::showBuilderMessages() std::pair msg; foreach (msg, messages) { QListWidgetItem* item = new QListWidgetItem(msg.first, NULL, 0); - item->setData(Qt::UserRole, msg.second); + item->setData(Qt::UserRole, QByteArray((const char*)&msg.second, sizeof(msg.second))); ui->builderMessagesListWidget->addItem(item); } @@ -951,19 +951,21 @@ void UEFITool::showBuilderMessages() void UEFITool::scrollTreeView(QListWidgetItem* item) { - QModelIndex index = item->data(Qt::UserRole).toModelIndex(); - if (index.isValid()) { - ui->structureTreeView->scrollTo(index, QAbstractItemView::PositionAtCenter); - ui->structureTreeView->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Rows | QItemSelectionModel::Clear); + QByteArray second = item->data(Qt::UserRole).toByteArray(); + QModelIndex *index = (QModelIndex *)second.data(); + if (index && index->isValid()) { + ui->structureTreeView->scrollTo(*index, QAbstractItemView::PositionAtCenter); + ui->structureTreeView->selectionModel()->select(*index, QItemSelectionModel::Select | QItemSelectionModel::Rows | QItemSelectionModel::Clear); } } void UEFITool::scrollTreeView(QTableWidgetItem* item) { - QModelIndex index = item->data(Qt::UserRole).toModelIndex(); - if (index.isValid()) { - ui->structureTreeView->scrollTo(index, QAbstractItemView::PositionAtCenter); - ui->structureTreeView->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Rows | QItemSelectionModel::Clear); + QByteArray second = item->data(Qt::UserRole).toByteArray(); + QModelIndex *index = (QModelIndex *)second.data(); + if (index && index->isValid()) { + ui->structureTreeView->scrollTo(*index, QAbstractItemView::PositionAtCenter); + ui->structureTreeView->selectionModel()->select(*index, QItemSelectionModel::Select | QItemSelectionModel::Rows | QItemSelectionModel::Clear); } } @@ -1069,7 +1071,7 @@ void UEFITool::showFitTable() for (size_t i = 0; i < fitTable.size(); i++) { for (UINT8 j = 0; j < 6; j++) { QTableWidgetItem* item = new QTableWidgetItem(fitTable[i].first[j]); - item->setData(Qt::UserRole, fitTable[i].second); + item->setData(Qt::UserRole, QByteArray((const char*)&fitTable[i].second, sizeof(fitTable[i].second))); ui->fitTableWidget->setItem((int)i, j, item); } } diff --git a/UEFITool/uefitool.pro b/UEFITool/uefitool.pro index fdc63e2..721d35c 100644 --- a/UEFITool/uefitool.pro +++ b/UEFITool/uefitool.pro @@ -11,6 +11,7 @@ HEADERS += uefitool.h \ gotooffsetdialog.h \ guidlineedit.h \ ffsfinder.h \ + hexspinbox.h \ ../common/nvram.h \ ../common/nvramparser.h \ ../common/meparser.h \ @@ -35,9 +36,9 @@ HEADERS += uefitool.h \ ../common/Tiano/EfiTianoCompress.h \ ../common/ustring.h \ ../common/ubytearray.h \ - ../qhexedit2/qhexedit.h \ - ../qhexedit2/chunks.h \ - ../qhexedit2/commands.h + qhexedit2/qhexedit.h \ + qhexedit2/chunks.h \ + qhexedit2/commands.h SOURCES += uefitool_main.cpp \ uefitool.cpp \ @@ -45,6 +46,7 @@ SOURCES += uefitool_main.cpp \ hexviewdialog.cpp \ guidlineedit.cpp \ ffsfinder.cpp \ + hexspinbox.cpp \ ../common/nvram.cpp \ ../common/nvramparser.cpp \ ../common/ffsops.cpp \ @@ -66,9 +68,9 @@ SOURCES += uefitool_main.cpp \ ../common/Tiano/EfiTianoCompress.c \ ../common/Tiano/EfiTianoCompressLegacy.c \ ../common/ustring.cpp \ - ../qhexedit2/qhexedit.cpp \ - ../qhexedit2/chunks.cpp \ - ../qhexedit2/commands.cpp + qhexedit2/qhexedit.cpp \ + qhexedit2/chunks.cpp \ + qhexedit2/commands.cpp FORMS += uefitool.ui \ searchdialog.ui \ diff --git a/common/bstrlib/LICENSE b/common/bstrlib/LICENSE new file mode 100644 index 0000000..28ab228 --- /dev/null +++ b/common/bstrlib/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014, Paul Hsieh +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of bstrlib nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/common/bstrlib/bstrlib.c b/common/bstrlib/bstrlib.c new file mode 100644 index 0000000..82fbc05 --- /dev/null +++ b/common/bstrlib/bstrlib.c @@ -0,0 +1,3137 @@ +/* + * This source file is part of the bstring string library. This code was + * written by Paul Hsieh in 2002-2015, and is covered by the BSD open source + * license and the GPL. Refer to the accompanying documentation for details + * on usage and license. + */ + +/* + * bstrlib.c + * + * This file is the core module for implementing the bstring functions. + */ + +#if defined (_MSC_VER) +# define _CRT_SECURE_NO_WARNINGS +#endif + +#include +#include +#include +#include +#include +#include +#include +#include "bstrlib.h" + +/* Optionally include a mechanism for debugging memory */ + +#if defined(MEMORY_DEBUG) || defined(BSTRLIB_MEMORY_DEBUG) +#include "memdbg.h" +#endif + +#ifndef bstr__alloc +#if defined (BSTRLIB_TEST_CANARY) +void* bstr__alloc (size_t sz) { + char* p = (char *) malloc (sz); + memset (p, 'X', sz); + return p; +} +#else +#define bstr__alloc(x) malloc (x) +#endif +#endif + +#ifndef bstr__free +#define bstr__free(p) free (p) +#endif + +#ifndef bstr__realloc +#define bstr__realloc(p,x) realloc ((p), (x)) +#endif + +#ifndef bstr__memcpy +#define bstr__memcpy(d,s,l) memcpy ((d), (s), (l)) +#endif + +#ifndef bstr__memmove +#define bstr__memmove(d,s,l) memmove ((d), (s), (l)) +#endif + +#ifndef bstr__memset +#define bstr__memset(d,c,l) memset ((d), (c), (l)) +#endif + +#ifndef bstr__memcmp +#define bstr__memcmp(d,c,l) memcmp ((d), (c), (l)) +#endif + +#ifndef bstr__memchr +#define bstr__memchr(s,c,l) memchr ((s), (c), (l)) +#endif + +/* Just a length safe wrapper for memmove. */ + +#define bBlockCopy(D,S,L) { if ((L) > 0) bstr__memmove ((D),(S),(L)); } + +/* Compute the snapped size for a given requested size. By snapping to powers + of 2 like this, repeated reallocations are avoided. */ +static int snapUpSize (int i) { + if (i < 8) { + i = 8; + } else { + unsigned int j; + j = (unsigned int) i; + + j |= (j >> 1); + j |= (j >> 2); + j |= (j >> 4); + j |= (j >> 8); /* Ok, since int >= 16 bits */ +#if (UINT_MAX != 0xffff) + j |= (j >> 16); /* For 32 bit int systems */ +#if (UINT_MAX > 0xffffffffUL) + j |= (j >> 32); /* For 64 bit int systems */ +#endif +#endif + /* Least power of two greater than i */ + j++; + if ((int) j >= i) i = (int) j; + } + return i; +} + +/* int balloc (bstring b, int len) + * + * Increase the size of the memory backing the bstring b to at least len. + */ +int balloc (bstring b, int olen) { + int len; + if (b == NULL || b->data == NULL || b->slen < 0 || b->mlen <= 0 || + b->mlen < b->slen || olen <= 0) { + return BSTR_ERR; + } + + if (olen >= b->mlen) { + unsigned char * x; + + if ((len = snapUpSize (olen)) <= b->mlen) return BSTR_OK; + + /* Assume probability of a non-moving realloc is 0.125 */ + if (7 * b->mlen < 8 * b->slen) { + + /* If slen is close to mlen in size then use realloc to reduce + the memory defragmentation */ + + reallocStrategy:; + + x = (unsigned char *) bstr__realloc (b->data, (size_t) len); + if (x == NULL) { + + /* Since we failed, try allocating the tighest possible + allocation */ + + len = olen; + x = (unsigned char *) bstr__realloc (b->data, (size_t) olen); + if (NULL == x) { + return BSTR_ERR; + } + } + } else { + + /* If slen is not close to mlen then avoid the penalty of copying + the extra bytes that are allocated, but not considered part of + the string */ + + if (NULL == (x = (unsigned char *) bstr__alloc ((size_t) len))) { + + /* Perhaps there is no available memory for the two + allocations to be in memory at once */ + + goto reallocStrategy; + + } else { + if (b->slen) bstr__memcpy ((char *) x, (char *) b->data, + (size_t) b->slen); + bstr__free (b->data); + } + } + b->data = x; + b->mlen = len; + b->data[b->slen] = (unsigned char) '\0'; + +#if defined (BSTRLIB_TEST_CANARY) + if (len > b->slen + 1) { + memchr (b->data + b->slen + 1, 'X', len - (b->slen + 1)); + } +#endif + } + + return BSTR_OK; +} + +/* int ballocmin (bstring b, int len) + * + * Set the size of the memory backing the bstring b to len or b->slen+1, + * whichever is larger. Note that repeated use of this function can degrade + * performance. + */ +int ballocmin (bstring b, int len) { + unsigned char * s; + + if (b == NULL || b->data == NULL) return BSTR_ERR; + if (b->slen >= INT_MAX || b->slen < 0) return BSTR_ERR; + if (b->mlen <= 0 || b->mlen < b->slen || len <= 0) { + return BSTR_ERR; + } + + if (len < b->slen + 1) len = b->slen + 1; + + if (len != b->mlen) { + s = (unsigned char *) bstr__realloc (b->data, (size_t) len); + if (NULL == s) return BSTR_ERR; + s[b->slen] = (unsigned char) '\0'; + b->data = s; + b->mlen = len; + } + + return BSTR_OK; +} + +/* bstring bfromcstr (const char * str) + * + * Create a bstring which contains the contents of the '\0' terminated char * + * buffer str. + */ +bstring bfromcstr (const char * str) { +bstring b; +int i; +size_t j; + + if (str == NULL) return NULL; + j = (strlen) (str); + i = snapUpSize ((int) (j + (2 - (j != 0)))); + if (i <= (int) j) return NULL; + + b = (bstring) bstr__alloc (sizeof (struct tagbstring)); + if (NULL == b) return NULL; + b->slen = (int) j; + if (NULL == (b->data = (unsigned char *) bstr__alloc (b->mlen = i))) { + bstr__free (b); + return NULL; + } + + bstr__memcpy (b->data, str, j+1); + return b; +} + +/* bstring bfromcstrrangealloc (int minl, int maxl, const char* str) + * + * Create a bstring which contains the contents of the '\0' terminated + * char* buffer str. The memory buffer backing the string is at least + * minl characters in length, but an attempt is made to allocate up to + * maxl characters. + */ +bstring bfromcstrrangealloc (int minl, int maxl, const char* str) { +bstring b; +int i; +size_t j; + + /* Bad parameters? */ + if (str == NULL) return NULL; + if (maxl < minl || minl < 0) return NULL; + + /* Adjust lengths */ + j = (strlen) (str); + if ((size_t) minl < (j+1)) minl = (int) (j+1); + if (maxl < minl) maxl = minl; + i = maxl; + + b = (bstring) bstr__alloc (sizeof (struct tagbstring)); + if (b == NULL) return NULL; + b->slen = (int) j; + + while (NULL == (b->data = (unsigned char *) bstr__alloc (b->mlen = i))) { + int k = (i >> 1) + (minl >> 1); + if (i == k || i < minl) { + bstr__free (b); + return NULL; + } + i = k; + } + + bstr__memcpy (b->data, str, j+1); + return b; +} + +/* bstring bfromcstralloc (int mlen, const char * str) + * + * Create a bstring which contains the contents of the '\0' terminated + * char* buffer str. The memory buffer backing the string is at least + * mlen characters in length. + */ +bstring bfromcstralloc (int mlen, const char * str) { + return bfromcstrrangealloc (mlen, mlen, str); +} + +/* bstring blk2bstr (const void * blk, int len) + * + * Create a bstring which contains the content of the block blk of length + * len. + */ +bstring blk2bstr (const void * blk, int len) { +bstring b; +int i; + + if (blk == NULL || len < 0) return NULL; + b = (bstring) bstr__alloc (sizeof (struct tagbstring)); + if (b == NULL) return NULL; + b->slen = len; + + i = len + (2 - (len != 0)); + i = snapUpSize (i); + + b->mlen = i; + + b->data = (unsigned char *) bstr__alloc ((size_t) b->mlen); + if (b->data == NULL) { + bstr__free (b); + return NULL; + } + + if (len > 0) bstr__memcpy (b->data, blk, (size_t) len); + b->data[len] = (unsigned char) '\0'; + + return b; +} + +/* char * bstr2cstr (const_bstring s, char z) + * + * Create a '\0' terminated char * buffer which is equal to the contents of + * the bstring s, except that any contained '\0' characters are converted + * to the character in z. This returned value should be freed with a + * bcstrfree () call, by the calling application. + */ +char * bstr2cstr (const_bstring b, char z) { +int i, l; +char * r; + + if (b == NULL || b->slen < 0 || b->data == NULL) return NULL; + l = b->slen; + r = (char *) bstr__alloc ((size_t) (l + 1)); + if (r == NULL) return r; + + for (i=0; i < l; i ++) { + r[i] = (char) ((b->data[i] == '\0') ? z : (char) (b->data[i])); + } + + r[l] = (unsigned char) '\0'; + + return r; +} + +/* int bcstrfree (char * s) + * + * Frees a C-string generated by bstr2cstr (). This is normally unnecessary + * since it just wraps a call to bstr__free (), however, if bstr__alloc () + * and bstr__free () have been redefined as a macros within the bstrlib + * module (via defining them in memdbg.h after defining + * BSTRLIB_MEMORY_DEBUG) with some difference in behaviour from the std + * library functions, then this allows a correct way of freeing the memory + * that allows higher level code to be independent from these macro + * redefinitions. + */ +int bcstrfree (char * s) { + if (s) { + bstr__free (s); + return BSTR_OK; + } + return BSTR_ERR; +} + +/* int bconcat (bstring b0, const_bstring b1) + * + * Concatenate the bstring b1 to the bstring b0. + */ +int bconcat (bstring b0, const_bstring b1) { +int len, d; +bstring aux = (bstring) b1; + + if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL) + return BSTR_ERR; + + d = b0->slen; + len = b1->slen; + if ((d | (b0->mlen - d) | len | (d + len)) < 0) return BSTR_ERR; + + if (b0->mlen <= d + len + 1) { + ptrdiff_t pd = b1->data - b0->data; + if (0 <= pd && pd < b0->mlen) { + if (NULL == (aux = bstrcpy (b1))) return BSTR_ERR; + } + if (balloc (b0, d + len + 1) != BSTR_OK) { + if (aux != b1) bdestroy (aux); + return BSTR_ERR; + } + } + + bBlockCopy (&b0->data[d], &aux->data[0], (size_t) len); + b0->data[d + len] = (unsigned char) '\0'; + b0->slen = d + len; + if (aux != b1) bdestroy (aux); + return BSTR_OK; +} + +/* int bconchar (bstring b, char c) + * + * Concatenate the single character c to the bstring b. + */ +int bconchar (bstring b, char c) { +int d; + + if (b == NULL) return BSTR_ERR; + d = b->slen; + if ((d | (b->mlen - d)) < 0 || balloc (b, d + 2) != BSTR_OK) + return BSTR_ERR; + b->data[d] = (unsigned char) c; + b->data[d + 1] = (unsigned char) '\0'; + b->slen++; + return BSTR_OK; +} + +/* int bcatcstr (bstring b, const char * s) + * + * Concatenate a char * string to a bstring. + */ +int bcatcstr (bstring b, const char * s) { +char * d; +int i, l; + + if (b == NULL || b->data == NULL || b->slen < 0 || b->mlen < b->slen + || b->mlen <= 0 || s == NULL) return BSTR_ERR; + + /* Optimistically concatenate directly */ + l = b->mlen - b->slen; + d = (char *) &b->data[b->slen]; + for (i=0; i < l; i++) { + if ((*d++ = *s++) == '\0') { + b->slen += i; + return BSTR_OK; + } + } + b->slen += i; + + /* Need to explicitely resize and concatenate tail */ + return bcatblk (b, (const void *) s, (int) strlen (s)); +} + +/* int bcatblk (bstring b, const void * s, int len) + * + * Concatenate a fixed length buffer to a bstring. + */ +int bcatblk (bstring b, const void * s, int len) { +int nl; + + if (b == NULL || b->data == NULL || b->slen < 0 || b->mlen < b->slen + || b->mlen <= 0 || s == NULL || len < 0) return BSTR_ERR; + + if (0 > (nl = b->slen + len)) return BSTR_ERR; /* Overflow? */ + if (b->mlen <= nl && 0 > balloc (b, nl + 1)) return BSTR_ERR; + + bBlockCopy (&b->data[b->slen], s, (size_t) len); + b->slen = nl; + b->data[nl] = (unsigned char) '\0'; + return BSTR_OK; +} + +/* bstring bstrcpy (const_bstring b) + * + * Create a copy of the bstring b. + */ +bstring bstrcpy (const_bstring b) { +bstring b0; +int i,j; + + /* Attempted to copy an invalid string? */ + if (b == NULL || b->slen < 0 || b->data == NULL) return NULL; + + b0 = (bstring) bstr__alloc (sizeof (struct tagbstring)); + if (b0 == NULL) { + /* Unable to allocate memory for string header */ + return NULL; + } + + i = b->slen; + j = snapUpSize (i + 1); + + b0->data = (unsigned char *) bstr__alloc (j); + if (b0->data == NULL) { + j = i + 1; + b0->data = (unsigned char *) bstr__alloc (j); + if (b0->data == NULL) { + /* Unable to allocate memory for string data */ + bstr__free (b0); + return NULL; + } + } + + b0->mlen = j; + b0->slen = i; + + if (i) bstr__memcpy ((char *) b0->data, (char *) b->data, i); + b0->data[b0->slen] = (unsigned char) '\0'; + + return b0; +} + +/* int bassign (bstring a, const_bstring b) + * + * Overwrite the string a with the contents of string b. + */ +int bassign (bstring a, const_bstring b) { + if (b == NULL || b->data == NULL || b->slen < 0) + return BSTR_ERR; + if (b->slen != 0) { + if (balloc (a, b->slen) != BSTR_OK) return BSTR_ERR; + bstr__memmove (a->data, b->data, b->slen); + } else { + if (a == NULL || a->data == NULL || a->mlen < a->slen || + a->slen < 0 || a->mlen == 0) + return BSTR_ERR; + } + a->data[b->slen] = (unsigned char) '\0'; + a->slen = b->slen; + return BSTR_OK; +} + +/* int bassignmidstr (bstring a, const_bstring b, int left, int len) + * + * Overwrite the string a with the middle of contents of string b + * starting from position left and running for a length len. left and + * len are clamped to the ends of b as with the function bmidstr. + */ +int bassignmidstr (bstring a, const_bstring b, int left, int len) { + if (b == NULL || b->data == NULL || b->slen < 0) + return BSTR_ERR; + + if (left < 0) { + len += left; + left = 0; + } + + if (len > b->slen - left) len = b->slen - left; + + if (a == NULL || a->data == NULL || a->mlen < a->slen || + a->slen < 0 || a->mlen == 0) + return BSTR_ERR; + + if (len > 0) { + if (balloc (a, len) != BSTR_OK) return BSTR_ERR; + bstr__memmove (a->data, b->data + left, len); + a->slen = len; + } else { + a->slen = 0; + } + a->data[a->slen] = (unsigned char) '\0'; + return BSTR_OK; +} + +/* int bassigncstr (bstring a, const char * str) + * + * Overwrite the string a with the contents of char * string str. Note that + * the bstring a must be a well defined and writable bstring. If an error + * occurs BSTR_ERR is returned however a may be partially overwritten. + */ +int bassigncstr (bstring a, const char * str) { +int i; +size_t len; + if (a == NULL || a->data == NULL || a->mlen < a->slen || + a->slen < 0 || a->mlen == 0 || NULL == str) + return BSTR_ERR; + + for (i=0; i < a->mlen; i++) { + if ('\0' == (a->data[i] = str[i])) { + a->slen = i; + return BSTR_OK; + } + } + + a->slen = i; + len = strlen (str + i); + if (len + 1 > (size_t) INT_MAX - i || + 0 > balloc (a, (int) (i + len + 1))) return BSTR_ERR; + bBlockCopy (a->data + i, str + i, (size_t) len + 1); + a->slen += (int) len; + return BSTR_OK; +} + +/* int bassignblk (bstring a, const void * s, int len) + * + * Overwrite the string a with the contents of the block (s, len). Note that + * the bstring a must be a well defined and writable bstring. If an error + * occurs BSTR_ERR is returned and a is not overwritten. + */ +int bassignblk (bstring a, const void * s, int len) { + if (a == NULL || a->data == NULL || a->mlen < a->slen || + a->slen < 0 || a->mlen == 0 || NULL == s || len < 0 || len >= INT_MAX) + return BSTR_ERR; + if (len + 1 > a->mlen && 0 > balloc (a, len + 1)) return BSTR_ERR; + bBlockCopy (a->data, s, (size_t) len); + a->data[len] = (unsigned char) '\0'; + a->slen = len; + return BSTR_OK; +} + +/* int btrunc (bstring b, int n) + * + * Truncate the bstring to at most n characters. + */ +int btrunc (bstring b, int n) { + if (n < 0 || b == NULL || b->data == NULL || b->mlen < b->slen || + b->slen < 0 || b->mlen <= 0) return BSTR_ERR; + if (b->slen > n) { + b->slen = n; + b->data[n] = (unsigned char) '\0'; + } + return BSTR_OK; +} + +#define upcase(c) (toupper ((unsigned char) c)) +#define downcase(c) (tolower ((unsigned char) c)) +#define wspace(c) (isspace ((unsigned char) c)) + +/* int btoupper (bstring b) + * + * Convert contents of bstring to upper case. + */ +int btoupper (bstring b) { +int i, len; + if (b == NULL || b->data == NULL || b->mlen < b->slen || + b->slen < 0 || b->mlen <= 0) return BSTR_ERR; + for (i=0, len = b->slen; i < len; i++) { + b->data[i] = (unsigned char) upcase (b->data[i]); + } + return BSTR_OK; +} + +/* int btolower (bstring b) + * + * Convert contents of bstring to lower case. + */ +int btolower (bstring b) { +int i, len; + if (b == NULL || b->data == NULL || b->mlen < b->slen || + b->slen < 0 || b->mlen <= 0) return BSTR_ERR; + for (i=0, len = b->slen; i < len; i++) { + b->data[i] = (unsigned char) downcase (b->data[i]); + } + return BSTR_OK; +} + +/* int bstricmp (const_bstring b0, const_bstring b1) + * + * Compare two strings without differentiating between case. The return + * value is the difference of the values of the characters where the two + * strings first differ after lower case transformation, otherwise 0 is + * returned indicating that the strings are equal. If the lengths are + * different, then a difference from 0 is given, but if the first extra + * character is '\0', then it is taken to be the value UCHAR_MAX+1. + */ +int bstricmp (const_bstring b0, const_bstring b1) { +int i, v, n; + + if (bdata (b0) == NULL || b0->slen < 0 || + bdata (b1) == NULL || b1->slen < 0) return SHRT_MIN; + if ((n = b0->slen) > b1->slen) n = b1->slen; + else if (b0->slen == b1->slen && b0->data == b1->data) return BSTR_OK; + + for (i = 0; i < n; i ++) { + v = (char) downcase (b0->data[i]) + - (char) downcase (b1->data[i]); + if (0 != v) return v; + } + + if (b0->slen > n) { + v = (char) downcase (b0->data[n]); + if (v) return v; + return UCHAR_MAX + 1; + } + if (b1->slen > n) { + v = - (char) downcase (b1->data[n]); + if (v) return v; + return - (int) (UCHAR_MAX + 1); + } + return BSTR_OK; +} + +/* int bstrnicmp (const_bstring b0, const_bstring b1, int n) + * + * Compare two strings without differentiating between case for at most n + * characters. If the position where the two strings first differ is + * before the nth position, the return value is the difference of the values + * of the characters, otherwise 0 is returned. If the lengths are different + * and less than n characters, then a difference from 0 is given, but if the + * first extra character is '\0', then it is taken to be the value + * UCHAR_MAX+1. + */ +int bstrnicmp (const_bstring b0, const_bstring b1, int n) { +int i, v, m; + + if (bdata (b0) == NULL || b0->slen < 0 || + bdata (b1) == NULL || b1->slen < 0 || n < 0) return SHRT_MIN; + m = n; + if (m > b0->slen) m = b0->slen; + if (m > b1->slen) m = b1->slen; + + if (b0->data != b1->data) { + for (i = 0; i < m; i ++) { + v = (char) downcase (b0->data[i]); + v -= (char) downcase (b1->data[i]); + if (v != 0) return b0->data[i] - b1->data[i]; + } + } + + if (n == m || b0->slen == b1->slen) return BSTR_OK; + + if (b0->slen > m) { + v = (char) downcase (b0->data[m]); + if (v) return v; + return UCHAR_MAX + 1; + } + + v = - (char) downcase (b1->data[m]); + if (v) return v; + return - (int) (UCHAR_MAX + 1); +} + +/* int biseqcaselessblk (const_bstring b, const void * blk, int len) + * + * Compare content of b and the array of bytes in blk for length len for + * equality without differentiating between character case. If the content + * differs other than in case, 0 is returned, if, ignoring case, the content + * is the same, 1 is returned, if there is an error, -1 is returned. If the + * length of the strings are different, this function is O(1). '\0' + * characters are not treated in any special way. + */ +int biseqcaselessblk (const_bstring b, const void * blk, int len) { +int i; + + if (bdata (b) == NULL || b->slen < 0 || + blk == NULL || len < 0) return BSTR_ERR; + if (b->slen != len) return 0; + if (len == 0 || b->data == blk) return 1; + for (i=0; i < len; i++) { + if (b->data[i] != ((unsigned char*)blk)[i]) { + unsigned char c = (unsigned char) downcase (b->data[i]); + if (c != (unsigned char) downcase (((unsigned char*)blk)[i])) + return 0; + } + } + return 1; +} + + +/* int biseqcaseless (const_bstring b0, const_bstring b1) + * + * Compare two strings for equality without differentiating between case. + * If the strings differ other than in case, 0 is returned, if the strings + * are the same, 1 is returned, if there is an error, -1 is returned. If + * the length of the strings are different, this function is O(1). '\0' + * termination characters are not treated in any special way. + */ +int biseqcaseless (const_bstring b0, const_bstring b1) { + if (NULL == b1) return BSTR_ERR; + return biseqcaselessblk (b0, b1->data, b1->slen); +} + +/* int bisstemeqcaselessblk (const_bstring b0, const void * blk, int len) + * + * Compare beginning of string b0 with a block of memory of length len + * without differentiating between case for equality. If the beginning of b0 + * differs from the memory block other than in case (or if b0 is too short), + * 0 is returned, if the strings are the same, 1 is returned, if there is an + * error, -1 is returned. '\0' characters are not treated in any special + * way. + */ +int bisstemeqcaselessblk (const_bstring b0, const void * blk, int len) { +int i; + + if (bdata (b0) == NULL || b0->slen < 0 || NULL == blk || len < 0) + return BSTR_ERR; + if (b0->slen < len) return BSTR_OK; + if (b0->data == (const unsigned char *) blk || len == 0) return 1; + + for (i = 0; i < len; i ++) { + if (b0->data[i] != ((const unsigned char *) blk)[i]) { + if (downcase (b0->data[i]) != + downcase (((const unsigned char *) blk)[i])) return 0; + } + } + return 1; +} + +/* + * int bltrimws (bstring b) + * + * Delete whitespace contiguous from the left end of the string. + */ +int bltrimws (bstring b) { +int i, len; + + if (b == NULL || b->data == NULL || b->mlen < b->slen || + b->slen < 0 || b->mlen <= 0) return BSTR_ERR; + + for (len = b->slen, i = 0; i < len; i++) { + if (!wspace (b->data[i])) { + return bdelete (b, 0, i); + } + } + + b->data[0] = (unsigned char) '\0'; + b->slen = 0; + return BSTR_OK; +} + +/* + * int brtrimws (bstring b) + * + * Delete whitespace contiguous from the right end of the string. + */ +int brtrimws (bstring b) { +int i; + + if (b == NULL || b->data == NULL || b->mlen < b->slen || + b->slen < 0 || b->mlen <= 0) return BSTR_ERR; + + for (i = b->slen - 1; i >= 0; i--) { + if (!wspace (b->data[i])) { + if (b->mlen > i) b->data[i+1] = (unsigned char) '\0'; + b->slen = i + 1; + return BSTR_OK; + } + } + + b->data[0] = (unsigned char) '\0'; + b->slen = 0; + return BSTR_OK; +} + +/* + * int btrimws (bstring b) + * + * Delete whitespace contiguous from both ends of the string. + */ +int btrimws (bstring b) { +int i, j; + + if (b == NULL || b->data == NULL || b->mlen < b->slen || + b->slen < 0 || b->mlen <= 0) return BSTR_ERR; + + for (i = b->slen - 1; i >= 0; i--) { + if (!wspace (b->data[i])) { + if (b->mlen > i) b->data[i+1] = (unsigned char) '\0'; + b->slen = i + 1; + for (j = 0; wspace (b->data[j]); j++) {} + return bdelete (b, 0, j); + } + } + + b->data[0] = (unsigned char) '\0'; + b->slen = 0; + return BSTR_OK; +} + +/* int biseqblk (const_bstring b, const void * blk, int len) + * + * Compare the string b with the character block blk of length len. If the + * content differs, 0 is returned, if the content is the same, 1 is returned, + * if there is an error, -1 is returned. If the length of the strings are + * different, this function is O(1). '\0' characters are not treated in any + * special way. + */ +int biseqblk (const_bstring b, const void * blk, int len) { + if (len < 0 || b == NULL || blk == NULL || b->data == NULL || b->slen < 0) + return BSTR_ERR; + if (b->slen != len) return 0; + if (len == 0 || b->data == blk) return 1; + return !bstr__memcmp (b->data, blk, len); +} + +/* int biseq (const_bstring b0, const_bstring b1) + * + * Compare the string b0 and b1. If the strings differ, 0 is returned, if + * the strings are the same, 1 is returned, if there is an error, -1 is + * returned. If the length of the strings are different, this function is + * O(1). '\0' termination characters are not treated in any special way. + */ +int biseq (const_bstring b0, const_bstring b1) { + if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL || + b0->slen < 0 || b1->slen < 0) return BSTR_ERR; + if (b0->slen != b1->slen) return BSTR_OK; + if (b0->data == b1->data || b0->slen == 0) return 1; + return !bstr__memcmp (b0->data, b1->data, b0->slen); +} + +/* int bisstemeqblk (const_bstring b0, const void * blk, int len) + * + * Compare beginning of string b0 with a block of memory of length len for + * equality. If the beginning of b0 differs from the memory block (or if b0 + * is too short), 0 is returned, if the strings are the same, 1 is returned, + * if there is an error, -1 is returned. '\0' characters are not treated in + * any special way. + */ +int bisstemeqblk (const_bstring b0, const void * blk, int len) { +int i; + + if (bdata (b0) == NULL || b0->slen < 0 || NULL == blk || len < 0) + return BSTR_ERR; + if (b0->slen < len) return BSTR_OK; + if (b0->data == (const unsigned char *) blk || len == 0) return 1; + + for (i = 0; i < len; i ++) { + if (b0->data[i] != ((const unsigned char *) blk)[i]) return BSTR_OK; + } + return 1; +} + +/* int biseqcstr (const_bstring b, const char *s) + * + * Compare the bstring b and char * string s. The C string s must be '\0' + * terminated at exactly the length of the bstring b, and the contents + * between the two must be identical with the bstring b with no '\0' + * characters for the two contents to be considered equal. This is + * equivalent to the condition that their current contents will be always be + * equal when comparing them in the same format after converting one or the + * other. If the strings are equal 1 is returned, if they are unequal 0 is + * returned and if there is a detectable error BSTR_ERR is returned. + */ +int biseqcstr (const_bstring b, const char * s) { +int i; + if (b == NULL || s == NULL || b->data == NULL || b->slen < 0) + return BSTR_ERR; + for (i=0; i < b->slen; i++) { + if (s[i] == '\0' || b->data[i] != (unsigned char) s[i]) + return BSTR_OK; + } + return s[i] == '\0'; +} + +/* int biseqcstrcaseless (const_bstring b, const char *s) + * + * Compare the bstring b and char * string s. The C string s must be '\0' + * terminated at exactly the length of the bstring b, and the contents + * between the two must be identical except for case with the bstring b with + * no '\0' characters for the two contents to be considered equal. This is + * equivalent to the condition that their current contents will be always be + * equal ignoring case when comparing them in the same format after + * converting one or the other. If the strings are equal, except for case, + * 1 is returned, if they are unequal regardless of case 0 is returned and + * if there is a detectable error BSTR_ERR is returned. + */ +int biseqcstrcaseless (const_bstring b, const char * s) { +int i; + if (b == NULL || s == NULL || b->data == NULL || b->slen < 0) + return BSTR_ERR; + for (i=0; i < b->slen; i++) { + if (s[i] == '\0' || + (b->data[i] != (unsigned char) s[i] && + downcase (b->data[i]) != (unsigned char) downcase (s[i]))) + return BSTR_OK; + } + return s[i] == '\0'; +} + +/* int bstrcmp (const_bstring b0, const_bstring b1) + * + * Compare the string b0 and b1. If there is an error, SHRT_MIN is returned, + * otherwise a value less than or greater than zero, indicating that the + * string pointed to by b0 is lexicographically less than or greater than + * the string pointed to by b1 is returned. If the the string lengths are + * unequal but the characters up until the length of the shorter are equal + * then a value less than, or greater than zero, indicating that the string + * pointed to by b0 is shorter or longer than the string pointed to by b1 is + * returned. 0 is returned if and only if the two strings are the same. If + * the length of the strings are different, this function is O(n). Like its + * standard C library counter part strcmp, the comparison does not proceed + * past any '\0' termination characters encountered. + */ +int bstrcmp (const_bstring b0, const_bstring b1) { +int i, v, n; + + if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL || + b0->slen < 0 || b1->slen < 0) return SHRT_MIN; + n = b0->slen; if (n > b1->slen) n = b1->slen; + if (b0->slen == b1->slen && (b0->data == b1->data || b0->slen == 0)) + return BSTR_OK; + + for (i = 0; i < n; i ++) { + v = ((char) b0->data[i]) - ((char) b1->data[i]); + if (v != 0) return v; + if (b0->data[i] == (unsigned char) '\0') return BSTR_OK; + } + + if (b0->slen > n) return 1; + if (b1->slen > n) return -1; + return BSTR_OK; +} + +/* int bstrncmp (const_bstring b0, const_bstring b1, int n) + * + * Compare the string b0 and b1 for at most n characters. If there is an + * error, SHRT_MIN is returned, otherwise a value is returned as if b0 and + * b1 were first truncated to at most n characters then bstrcmp was called + * with these new strings are paremeters. If the length of the strings are + * different, this function is O(n). Like its standard C library counter + * part strcmp, the comparison does not proceed past any '\0' termination + * characters encountered. + */ +int bstrncmp (const_bstring b0, const_bstring b1, int n) { +int i, v, m; + + if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL || + b0->slen < 0 || b1->slen < 0) return SHRT_MIN; + m = n; + if (m > b0->slen) m = b0->slen; + if (m > b1->slen) m = b1->slen; + + if (b0->data != b1->data) { + for (i = 0; i < m; i ++) { + v = ((char) b0->data[i]) - ((char) b1->data[i]); + if (v != 0) return v; + if (b0->data[i] == (unsigned char) '\0') return BSTR_OK; + } + } + + if (n == m || b0->slen == b1->slen) return BSTR_OK; + + if (b0->slen > m) return 1; + return -1; +} + +/* bstring bmidstr (const_bstring b, int left, int len) + * + * Create a bstring which is the substring of b starting from position left + * and running for a length len (clamped by the end of the bstring b.) If + * b is detectably invalid, then NULL is returned. The section described + * by (left, len) is clamped to the boundaries of b. + */ +bstring bmidstr (const_bstring b, int left, int len) { + + if (b == NULL || b->slen < 0 || b->data == NULL) return NULL; + + if (left < 0) { + len += left; + left = 0; + } + + if (len > b->slen - left) len = b->slen - left; + + if (len <= 0) return bfromcstr (""); + return blk2bstr (b->data + left, len); +} + +/* int bdelete (bstring b, int pos, int len) + * + * Removes characters from pos to pos+len-1 inclusive and shifts the tail of + * the bstring starting from pos+len to pos. len must be positive for this + * call to have any effect. The section of the string described by (pos, + * len) is clamped to boundaries of the bstring b. + */ +int bdelete (bstring b, int pos, int len) { + /* Clamp to left side of bstring */ + if (pos < 0) { + len += pos; + pos = 0; + } + + if (len < 0 || b == NULL || b->data == NULL || b->slen < 0 || + b->mlen < b->slen || b->mlen <= 0) + return BSTR_ERR; + if (len > 0 && pos < b->slen) { + if (pos + len >= b->slen) { + b->slen = pos; + } else { + bBlockCopy ((char *) (b->data + pos), + (char *) (b->data + pos + len), + b->slen - (pos+len)); + b->slen -= len; + } + b->data[b->slen] = (unsigned char) '\0'; + } + return BSTR_OK; +} + +/* int bdestroy (bstring b) + * + * Free up the bstring. Note that if b is detectably invalid or not writable + * then no action is performed and BSTR_ERR is returned. Like a freed memory + * allocation, dereferences, writes or any other action on b after it has + * been bdestroyed is undefined. + */ +int bdestroy (bstring b) { + if (b == NULL || b->slen < 0 || b->mlen <= 0 || b->mlen < b->slen || + b->data == NULL) + return BSTR_ERR; + + bstr__free (b->data); + + /* In case there is any stale usage, there is one more chance to + notice this error. */ + + b->slen = -1; + b->mlen = -__LINE__; + b->data = NULL; + + bstr__free (b); + return BSTR_OK; +} + +/* int binstr (const_bstring b1, int pos, const_bstring b2) + * + * Search for the bstring b2 in b1 starting from position pos, and searching + * forward. If it is found then return with the first position where it is + * found, otherwise return BSTR_ERR. Note that this is just a brute force + * string searcher that does not attempt clever things like the Boyer-Moore + * search algorithm. Because of this there are many degenerate cases where + * this can take much longer than it needs to. + */ +int binstr (const_bstring b1, int pos, const_bstring b2) { +int j, ii, ll, lf; +unsigned char * d0; +unsigned char c0; +register unsigned char * d1; +register unsigned char c1; +register int i; + + if (b1 == NULL || b1->data == NULL || b1->slen < 0 || + b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR; + if (b1->slen == pos) return (b2->slen == 0)?pos:BSTR_ERR; + if (b1->slen < pos || pos < 0) return BSTR_ERR; + if (b2->slen == 0) return pos; + + /* No space to find such a string? */ + if ((lf = b1->slen - b2->slen + 1) <= pos) return BSTR_ERR; + + /* An obvious alias case */ + if (b1->data == b2->data && pos == 0) return 0; + + i = pos; + + d0 = b2->data; + d1 = b1->data; + ll = b2->slen; + + /* Peel off the b2->slen == 1 case */ + c0 = d0[0]; + if (1 == ll) { + for (;i < lf; i++) if (c0 == d1[i]) return i; + return BSTR_ERR; + } + + c1 = c0; + j = 0; + lf = b1->slen - 1; + + ii = -1; + if (i < lf) do { + /* Unrolled current character test */ + if (c1 != d1[i]) { + if (c1 != d1[1+i]) { + i += 2; + continue; + } + i++; + } + + /* Take note if this is the start of a potential match */ + if (0 == j) ii = i; + + /* Shift the test character down by one */ + j++; + i++; + + /* If this isn't past the last character continue */ + if (j < ll) { + c1 = d0[j]; + continue; + } + + N0:; + + /* If no characters mismatched, then we matched */ + if (i == ii+j) return ii; + + /* Shift back to the beginning */ + i -= j; + j = 0; + c1 = c0; + } while (i < lf); + + /* Deal with last case if unrolling caused a misalignment */ + if (i == lf && ll == j+1 && c1 == d1[i]) goto N0; + + return BSTR_ERR; +} + +/* int binstrr (const_bstring b1, int pos, const_bstring b2) + * + * Search for the bstring b2 in b1 starting from position pos, and searching + * backward. If it is found then return with the first position where it is + * found, otherwise return BSTR_ERR. Note that this is just a brute force + * string searcher that does not attempt clever things like the Boyer-Moore + * search algorithm. Because of this there are many degenerate cases where + * this can take much longer than it needs to. + */ +int binstrr (const_bstring b1, int pos, const_bstring b2) { +int j, i, l; +unsigned char * d0, * d1; + + if (b1 == NULL || b1->data == NULL || b1->slen < 0 || + b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR; + if (b1->slen == pos && b2->slen == 0) return pos; + if (b1->slen < pos || pos < 0) return BSTR_ERR; + if (b2->slen == 0) return pos; + + /* Obvious alias case */ + if (b1->data == b2->data && pos == 0 && b2->slen <= b1->slen) return 0; + + i = pos; + if ((l = b1->slen - b2->slen) < 0) return BSTR_ERR; + + /* If no space to find such a string then snap back */ + if (l + 1 <= i) i = l; + j = 0; + + d0 = b2->data; + d1 = b1->data; + l = b2->slen; + + for (;;) { + if (d0[j] == d1[i + j]) { + j ++; + if (j >= l) return i; + } else { + i --; + if (i < 0) break; + j=0; + } + } + + return BSTR_ERR; +} + +/* int binstrcaseless (const_bstring b1, int pos, const_bstring b2) + * + * Search for the bstring b2 in b1 starting from position pos, and searching + * forward but without regard to case. If it is found then return with the + * first position where it is found, otherwise return BSTR_ERR. Note that + * this is just a brute force string searcher that does not attempt clever + * things like the Boyer-Moore search algorithm. Because of this there are + * many degenerate cases where this can take much longer than it needs to. + */ +int binstrcaseless (const_bstring b1, int pos, const_bstring b2) { +int j, i, l, ll; +unsigned char * d0, * d1; + + if (b1 == NULL || b1->data == NULL || b1->slen < 0 || + b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR; + if (b1->slen == pos) return (b2->slen == 0)?pos:BSTR_ERR; + if (b1->slen < pos || pos < 0) return BSTR_ERR; + if (b2->slen == 0) return pos; + + l = b1->slen - b2->slen + 1; + + /* No space to find such a string? */ + if (l <= pos) return BSTR_ERR; + + /* An obvious alias case */ + if (b1->data == b2->data && pos == 0) return BSTR_OK; + + i = pos; + j = 0; + + d0 = b2->data; + d1 = b1->data; + ll = b2->slen; + + for (;;) { + if (d0[j] == d1[i + j] || downcase (d0[j]) == downcase (d1[i + j])) { + j ++; + if (j >= ll) return i; + } else { + i ++; + if (i >= l) break; + j=0; + } + } + + return BSTR_ERR; +} + +/* int binstrrcaseless (const_bstring b1, int pos, const_bstring b2) + * + * Search for the bstring b2 in b1 starting from position pos, and searching + * backward but without regard to case. If it is found then return with the + * first position where it is found, otherwise return BSTR_ERR. Note that + * this is just a brute force string searcher that does not attempt clever + * things like the Boyer-Moore search algorithm. Because of this there are + * many degenerate cases where this can take much longer than it needs to. + */ +int binstrrcaseless (const_bstring b1, int pos, const_bstring b2) { +int j, i, l; +unsigned char * d0, * d1; + + if (b1 == NULL || b1->data == NULL || b1->slen < 0 || + b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR; + if (b1->slen == pos && b2->slen == 0) return pos; + if (b1->slen < pos || pos < 0) return BSTR_ERR; + if (b2->slen == 0) return pos; + + /* Obvious alias case */ + if (b1->data == b2->data && pos == 0 && b2->slen <= b1->slen) + return BSTR_OK; + + i = pos; + if ((l = b1->slen - b2->slen) < 0) return BSTR_ERR; + + /* If no space to find such a string then snap back */ + if (l + 1 <= i) i = l; + j = 0; + + d0 = b2->data; + d1 = b1->data; + l = b2->slen; + + for (;;) { + if (d0[j] == d1[i + j] || downcase (d0[j]) == downcase (d1[i + j])) { + j ++; + if (j >= l) return i; + } else { + i --; + if (i < 0) break; + j=0; + } + } + + return BSTR_ERR; +} + + +/* int bstrchrp (const_bstring b, int c, int pos) + * + * Search for the character c in b forwards from the position pos + * (inclusive). + */ +int bstrchrp (const_bstring b, int c, int pos) { +unsigned char * p; + + if (b == NULL || b->data == NULL || b->slen <= pos || pos < 0) + return BSTR_ERR; + p = (unsigned char *) bstr__memchr ((b->data + pos), (unsigned char) c, + (b->slen - pos)); + if (p) return (int) (p - b->data); + return BSTR_ERR; +} + +/* int bstrrchrp (const_bstring b, int c, int pos) + * + * Search for the character c in b backwards from the position pos in string + * (inclusive). + */ +int bstrrchrp (const_bstring b, int c, int pos) { +int i; + + if (b == NULL || b->data == NULL || b->slen <= pos || pos < 0) + return BSTR_ERR; + for (i=pos; i >= 0; i--) { + if (b->data[i] == (unsigned char) c) return i; + } + return BSTR_ERR; +} + +#if !defined (BSTRLIB_AGGRESSIVE_MEMORY_FOR_SPEED_TRADEOFF) +#define LONG_LOG_BITS_QTY (3) +#define LONG_BITS_QTY (1 << LONG_LOG_BITS_QTY) +#define LONG_TYPE unsigned char + +#define CFCLEN ((1 << CHAR_BIT) / LONG_BITS_QTY) +struct charField { LONG_TYPE content[CFCLEN]; }; +#define testInCharField(cf,c) ((cf)->content[(c) >> LONG_LOG_BITS_QTY] & \ + (((long)1) << ((c) & (LONG_BITS_QTY-1)))) +#define setInCharField(cf,idx) { \ + unsigned int c = (unsigned int) (idx); \ + (cf)->content[c >> LONG_LOG_BITS_QTY] |= \ + (LONG_TYPE) (1ul << (c & (LONG_BITS_QTY-1))); \ +} + +#else + +#define CFCLEN (1 << CHAR_BIT) +struct charField { unsigned char content[CFCLEN]; }; +#define testInCharField(cf,c) ((cf)->content[(unsigned char) (c)]) +#define setInCharField(cf,idx) (cf)->content[(unsigned int) (idx)] = ~0 + +#endif + +/* Convert a bstring to charField */ +static int buildCharField (struct charField * cf, const_bstring b) { +int i; + if (b == NULL || b->data == NULL || b->slen <= 0) return BSTR_ERR; + memset ((void *) cf->content, 0, sizeof (struct charField)); + for (i=0; i < b->slen; i++) { + setInCharField (cf, b->data[i]); + } + return BSTR_OK; +} + +static void invertCharField (struct charField * cf) { +int i; + for (i=0; i < CFCLEN; i++) cf->content[i] = ~cf->content[i]; +} + +/* Inner engine for binchr */ +static int binchrCF (const unsigned char * data, int len, int pos, + const struct charField * cf) { +int i; + for (i=pos; i < len; i++) { + unsigned char c = (unsigned char) data[i]; + if (testInCharField (cf, c)) return i; + } + return BSTR_ERR; +} + +/* int binchr (const_bstring b0, int pos, const_bstring b1); + * + * Search for the first position in b0 starting from pos or after, in which + * one of the characters in b1 is found and return it. If such a position + * does not exist in b0, then BSTR_ERR is returned. + */ +int binchr (const_bstring b0, int pos, const_bstring b1) { +struct charField chrs; + if (pos < 0 || b0 == NULL || b0->data == NULL || + b0->slen <= pos) return BSTR_ERR; + if (1 == b1->slen) return bstrchrp (b0, b1->data[0], pos); + if (0 > buildCharField (&chrs, b1)) return BSTR_ERR; + return binchrCF (b0->data, b0->slen, pos, &chrs); +} + +/* Inner engine for binchrr */ +static int binchrrCF (const unsigned char * data, int pos, + const struct charField * cf) { +int i; + for (i=pos; i >= 0; i--) { + unsigned int c = (unsigned int) data[i]; + if (testInCharField (cf, c)) return i; + } + return BSTR_ERR; +} + +/* int binchrr (const_bstring b0, int pos, const_bstring b1); + * + * Search for the last position in b0 no greater than pos, in which one of + * the characters in b1 is found and return it. If such a position does not + * exist in b0, then BSTR_ERR is returned. + */ +int binchrr (const_bstring b0, int pos, const_bstring b1) { +struct charField chrs; + if (pos < 0 || b0 == NULL || b0->data == NULL || b1 == NULL || + b0->slen < pos) return BSTR_ERR; + if (pos == b0->slen) pos--; + if (1 == b1->slen) return bstrrchrp (b0, b1->data[0], pos); + if (0 > buildCharField (&chrs, b1)) return BSTR_ERR; + return binchrrCF (b0->data, pos, &chrs); +} + +/* int bninchr (const_bstring b0, int pos, const_bstring b1); + * + * Search for the first position in b0 starting from pos or after, in which + * none of the characters in b1 is found and return it. If such a position + * does not exist in b0, then BSTR_ERR is returned. + */ +int bninchr (const_bstring b0, int pos, const_bstring b1) { +struct charField chrs; + if (pos < 0 || b0 == NULL || b0->data == NULL || + b0->slen <= pos) return BSTR_ERR; + if (buildCharField (&chrs, b1) < 0) return BSTR_ERR; + invertCharField (&chrs); + return binchrCF (b0->data, b0->slen, pos, &chrs); +} + +/* int bninchrr (const_bstring b0, int pos, const_bstring b1); + * + * Search for the last position in b0 no greater than pos, in which none of + * the characters in b1 is found and return it. If such a position does not + * exist in b0, then BSTR_ERR is returned. + */ +int bninchrr (const_bstring b0, int pos, const_bstring b1) { +struct charField chrs; + if (pos < 0 || b0 == NULL || b0->data == NULL || + b0->slen < pos) return BSTR_ERR; + if (pos == b0->slen) pos--; + if (buildCharField (&chrs, b1) < 0) return BSTR_ERR; + invertCharField (&chrs); + return binchrrCF (b0->data, pos, &chrs); +} + +/* int bsetstr (bstring b0, int pos, bstring b1, unsigned char fill) + * + * Overwrite the string b0 starting at position pos with the string b1. If + * the position pos is past the end of b0, then the character "fill" is + * appended as necessary to make up the gap between the end of b0 and pos. + * If b1 is NULL, it behaves as if it were a 0-length string. + */ +int bsetstr (bstring b0, int pos, const_bstring b1, unsigned char fill) { +int d, newlen; +ptrdiff_t pd; +bstring aux = (bstring) b1; + + if (pos < 0 || b0 == NULL || b0->slen < 0 || NULL == b0->data || + b0->mlen < b0->slen || b0->mlen <= 0) return BSTR_ERR; + if (b1 != NULL && (b1->slen < 0 || b1->data == NULL)) return BSTR_ERR; + + d = pos; + + /* Aliasing case */ + if (NULL != aux) { + if ((pd = (ptrdiff_t) (b1->data - b0->data)) >= 0 && + pd < (ptrdiff_t) b0->mlen) { + if (NULL == (aux = bstrcpy (b1))) return BSTR_ERR; + } + d += aux->slen; + } + + /* Increase memory size if necessary */ + if (balloc (b0, d + 1) != BSTR_OK) { + if (aux != b1) bdestroy (aux); + return BSTR_ERR; + } + + newlen = b0->slen; + + /* Fill in "fill" character as necessary */ + if (pos > newlen) { + bstr__memset (b0->data + b0->slen, (int) fill, + (size_t) (pos - b0->slen)); + newlen = pos; + } + + /* Copy b1 to position pos in b0. */ + if (aux != NULL) { + bBlockCopy ((char *) (b0->data + pos), (char *) aux->data, aux->slen); + if (aux != b1) bdestroy (aux); + } + + /* Indicate the potentially increased size of b0 */ + if (d > newlen) newlen = d; + + b0->slen = newlen; + b0->data[newlen] = (unsigned char) '\0'; + + return BSTR_OK; +} + +/* int binsertblk (bstring b, int pos, const void * blk, int len, + * unsigned char fill) + * + * Inserts the block of characters at blk with length len into b at position + * pos. If the position pos is past the end of b, then the character "fill" + * is appended as necessary to make up the gap between the end of b1 and pos. + * Unlike bsetstr, binsert does not allow b2 to be NULL. + */ +int binsertblk (bstring b, int pos, const void * blk, int len, + unsigned char fill) { +int d, l; +unsigned char* aux = (unsigned char*) blk; + + if (b == NULL || blk == NULL || pos < 0 || len < 0 || b->slen < 0 || + b->mlen <= 0 || b->mlen < b->slen) return BSTR_ERR; + + /* Compute the two possible end pointers */ + d = b->slen + len; + l = pos + len; + if ((d|l) < 0) return BSTR_ERR; /* Integer wrap around. */ + + /* Aliasing case */ + if (((size_t) ((unsigned char*) blk + len)) >= ((size_t) b->data) && + ((size_t) blk) < ((size_t) (b->data + b->mlen))) { + if (NULL == (aux = (unsigned char*) bstr__alloc (len))) + return BSTR_ERR; + bstr__memcpy (aux, blk, len); + } + + if (l > d) { + /* Inserting past the end of the string */ + if (balloc (b, l + 1) != BSTR_OK) { + if (aux != (unsigned char*) blk) bstr__free (aux); + return BSTR_ERR; + } + bstr__memset (b->data + b->slen, (int) fill, + (size_t) (pos - b->slen)); + b->slen = l; + } else { + /* Inserting in the middle of the string */ + if (balloc (b, d + 1) != BSTR_OK) { + if (aux != (unsigned char*) blk) bstr__free (aux); + return BSTR_ERR; + } + bBlockCopy (b->data + l, b->data + pos, d - l); + b->slen = d; + } + bBlockCopy (b->data + pos, aux, len); + b->data[b->slen] = (unsigned char) '\0'; + if (aux != (unsigned char*) blk) bstr__free (aux); + return BSTR_OK; +} + +/* int binsert (bstring b1, int pos, const_bstring b2, unsigned char fill) + * + * Inserts the string b2 into b1 at position pos. If the position pos is + * past the end of b1, then the character "fill" is appended as necessary to + * make up the gap between the end of b1 and pos. Unlike bsetstr, binsert + * does not allow b2 to be NULL. + */ +int binsert (bstring b1, int pos, const_bstring b2, unsigned char fill) { + if (NULL == b2 || (b2->mlen > 0 && b2->slen > b2->mlen)) return BSTR_ERR; + return binsertblk (b1, pos, b2->data, b2->slen, fill); +} + +/* int breplace (bstring b1, int pos, int len, bstring b2, + * unsigned char fill) + * + * Replace a section of a string from pos for a length len with the string + * b2. fill is used is pos > b1->slen. + */ +int breplace (bstring b1, int pos, int len, const_bstring b2, + unsigned char fill) { +int pl, ret; +ptrdiff_t pd; +bstring aux = (bstring) b2; + + if (pos < 0 || len < 0) return BSTR_ERR; + if (pos > INT_MAX - len) return BSTR_ERR; /* Overflow */ + pl = pos + len; + if (b1 == NULL || b2 == NULL || b1->data == NULL || b2->data == NULL || + b1->slen < 0 || b2->slen < 0 || b1->mlen < b1->slen || + b1->mlen <= 0) return BSTR_ERR; + + /* Straddles the end? */ + if (pl >= b1->slen) { + if ((ret = bsetstr (b1, pos, b2, fill)) < 0) return ret; + if (pos + b2->slen < b1->slen) { + b1->slen = pos + b2->slen; + b1->data[b1->slen] = (unsigned char) '\0'; + } + return ret; + } + + /* Aliasing case */ + if ((pd = (ptrdiff_t) (b2->data - b1->data)) >= 0 && + pd < (ptrdiff_t) b1->slen) { + if (NULL == (aux = bstrcpy (b2))) return BSTR_ERR; + } + + if (aux->slen > len) { + if (balloc (b1, b1->slen + aux->slen - len) != BSTR_OK) { + if (aux != b2) bdestroy (aux); + return BSTR_ERR; + } + } + + if (aux->slen != len) bstr__memmove (b1->data + pos + aux->slen, + b1->data + pos + len, + b1->slen - (pos + len)); + bstr__memcpy (b1->data + pos, aux->data, aux->slen); + b1->slen += aux->slen - len; + b1->data[b1->slen] = (unsigned char) '\0'; + if (aux != b2) bdestroy (aux); + return BSTR_OK; +} + +/* + * findreplaceengine is used to implement bfindreplace and + * bfindreplacecaseless. It works by breaking the three cases of + * expansion, reduction and replacement, and solving each of these + * in the most efficient way possible. + */ + +typedef int (*instr_fnptr) (const_bstring s1, int pos, const_bstring s2); + +#define INITIAL_STATIC_FIND_INDEX_COUNT 32 + +static int findreplaceengine (bstring b, const_bstring find, + const_bstring repl, int pos, + instr_fnptr instr) { +int i, ret, slen, mlen, delta, acc; +int * d; +int static_d[INITIAL_STATIC_FIND_INDEX_COUNT+1]; /* This +1 is for LINT. */ +ptrdiff_t pd; +bstring auxf = (bstring) find; +bstring auxr = (bstring) repl; + + if (b == NULL || b->data == NULL || find == NULL || + find->data == NULL || repl == NULL || repl->data == NULL || + pos < 0 || find->slen <= 0 || b->mlen <= 0 || b->slen > b->mlen || + b->slen < 0 || repl->slen < 0) return BSTR_ERR; + if (pos > b->slen - find->slen) return BSTR_OK; + + /* Alias with find string */ + pd = (ptrdiff_t) (find->data - b->data); + if ((ptrdiff_t) (pos - find->slen) < pd && pd < (ptrdiff_t) b->slen) { + if (NULL == (auxf = bstrcpy (find))) return BSTR_ERR; + } + + /* Alias with repl string */ + pd = (ptrdiff_t) (repl->data - b->data); + if ((ptrdiff_t) (pos - repl->slen) < pd && pd < (ptrdiff_t) b->slen) { + if (NULL == (auxr = bstrcpy (repl))) { + if (auxf != find) bdestroy (auxf); + return BSTR_ERR; + } + } + + delta = auxf->slen - auxr->slen; + + /* in-place replacement since find and replace strings are of equal + length */ + if (delta == 0) { + while ((pos = instr (b, pos, auxf)) >= 0) { + bstr__memcpy (b->data + pos, auxr->data, auxr->slen); + pos += auxf->slen; + } + if (auxf != find) bdestroy (auxf); + if (auxr != repl) bdestroy (auxr); + return BSTR_OK; + } + + /* shrinking replacement since auxf->slen > auxr->slen */ + if (delta > 0) { + acc = 0; + + while ((i = instr (b, pos, auxf)) >= 0) { + if (acc && i > pos) + bstr__memmove (b->data + pos - acc, b->data + pos, i - pos); + if (auxr->slen) + bstr__memcpy (b->data + i - acc, auxr->data, auxr->slen); + acc += delta; + pos = i + auxf->slen; + } + + if (acc) { + i = b->slen; + if (i > pos) + bstr__memmove (b->data + pos - acc, b->data + pos, i - pos); + b->slen -= acc; + b->data[b->slen] = (unsigned char) '\0'; + } + + if (auxf != find) bdestroy (auxf); + if (auxr != repl) bdestroy (auxr); + return BSTR_OK; + } + + /* expanding replacement since find->slen < repl->slen. Its a lot + more complicated. This works by first finding all the matches and + storing them to a growable array, then doing at most one resize of + the destination bstring and then performing the direct memory transfers + of the string segment pieces to form the final result. The growable + array of matches uses a deferred doubling reallocing strategy. What + this means is that it starts as a reasonably fixed sized auto array in + the hopes that many if not most cases will never need to grow this + array. But it switches as soon as the bounds of the array will be + exceeded. An extra find result is always appended to this array that + corresponds to the end of the destination string, so slen is checked + against mlen - 1 rather than mlen before resizing. + */ + + mlen = INITIAL_STATIC_FIND_INDEX_COUNT; + d = (int *) static_d; /* Avoid malloc for trivial/initial cases */ + acc = slen = 0; + + while ((pos = instr (b, pos, auxf)) >= 0) { + if (slen >= mlen - 1) { + int *t; + int sl; + /* Overflow */ + if (mlen > (INT_MAX / sizeof(int *)) / 2) { + ret = BSTR_ERR; + goto done; + } + mlen += mlen; + sl = sizeof (int *) * mlen; + if (static_d == d) d = NULL; /* static_d cannot be realloced */ + if (NULL == (t = (int *) bstr__realloc (d, sl))) { + ret = BSTR_ERR; + goto done; + } + if (NULL == d) bstr__memcpy (t, static_d, sizeof (static_d)); + d = t; + } + d[slen] = pos; + slen++; + acc -= delta; + pos += auxf->slen; + if (pos < 0 || acc < 0) { + ret = BSTR_ERR; + goto done; + } + } + + /* slen <= INITIAL_STATIC_INDEX_COUNT-1 or mlen-1 here. */ + d[slen] = b->slen; + + if (BSTR_OK == (ret = balloc (b, b->slen + acc + 1))) { + b->slen += acc; + for (i = slen-1; i >= 0; i--) { + int s, l; + s = d[i] + auxf->slen; + l = d[i+1] - s; /* d[slen] may be accessed here. */ + if (l) { + bstr__memmove (b->data + s + acc, b->data + s, l); + } + if (auxr->slen) { + bstr__memmove (b->data + s + acc - auxr->slen, + auxr->data, auxr->slen); + } + acc += delta; + } + b->data[b->slen] = (unsigned char) '\0'; + } + + done:; + if (static_d != d) bstr__free (d); + if (auxf != find) bdestroy (auxf); + if (auxr != repl) bdestroy (auxr); + return ret; +} + +/* int bfindreplace (bstring b, const_bstring find, const_bstring repl, + * int pos) + * + * Replace all occurrences of a find string with a replace string after a + * given point in a bstring. + */ +int bfindreplace (bstring b, const_bstring find, const_bstring repl, + int pos) { + return findreplaceengine (b, find, repl, pos, binstr); +} + +/* int bfindreplacecaseless (bstring b, const_bstring find, + * const_bstring repl, int pos) + * + * Replace all occurrences of a find string, ignoring case, with a replace + * string after a given point in a bstring. + */ +int bfindreplacecaseless (bstring b, const_bstring find, const_bstring repl, + int pos) { + return findreplaceengine (b, find, repl, pos, binstrcaseless); +} + +/* int binsertch (bstring b, int pos, int len, unsigned char fill) + * + * Inserts the character fill repeatedly into b at position pos for a + * length len. If the position pos is past the end of b, then the + * character "fill" is appended as necessary to make up the gap between the + * end of b and the position pos + len. + */ +int binsertch (bstring b, int pos, int len, unsigned char fill) { +int d, l, i; + + if (pos < 0 || b == NULL || b->slen < 0 || b->mlen < b->slen || + b->mlen <= 0 || len < 0) return BSTR_ERR; + + /* Compute the two possible end pointers */ + d = b->slen + len; + l = pos + len; + if ((d|l) < 0) return BSTR_ERR; + + if (l > d) { + /* Inserting past the end of the string */ + if (balloc (b, l + 1) != BSTR_OK) return BSTR_ERR; + pos = b->slen; + b->slen = l; + } else { + /* Inserting in the middle of the string */ + if (balloc (b, d + 1) != BSTR_OK) return BSTR_ERR; + for (i = d - 1; i >= l; i--) { + b->data[i] = b->data[i - len]; + } + b->slen = d; + } + + for (i=pos; i < l; i++) b->data[i] = fill; + b->data[b->slen] = (unsigned char) '\0'; + return BSTR_OK; +} + +/* int bpattern (bstring b, int len) + * + * Replicate the bstring, b in place, end to end repeatedly until it + * surpasses len characters, then chop the result to exactly len characters. + * This function operates in-place. The function will return with BSTR_ERR + * if b is NULL or of length 0, otherwise BSTR_OK is returned. + */ +int bpattern (bstring b, int len) { +int i, d; + + d = blength (b); + if (d <= 0 || len < 0 || balloc (b, len + 1) != BSTR_OK) return BSTR_ERR; + if (len > 0) { + if (d == 1) return bsetstr (b, len, NULL, b->data[0]); + for (i = d; i < len; i++) b->data[i] = b->data[i - d]; + } + b->data[len] = (unsigned char) '\0'; + b->slen = len; + return BSTR_OK; +} + +#define BS_BUFF_SZ (1024) + +/* int breada (bstring b, bNread readPtr, void * parm) + * + * Use a finite buffer fread-like function readPtr to concatenate to the + * bstring b the entire contents of file-like source data in a roughly + * efficient way. + */ +int breada (bstring b, bNread readPtr, void * parm) { +int i, l, n; + + if (b == NULL || b->mlen <= 0 || b->slen < 0 || b->mlen < b->slen || + readPtr == NULL) return BSTR_ERR; + + i = b->slen; + for (n=i+16; ; n += ((n < BS_BUFF_SZ) ? n : BS_BUFF_SZ)) { + if (BSTR_OK != balloc (b, n + 1)) return BSTR_ERR; + l = (int) readPtr ((void *) (b->data + i), 1, n - i, parm); + i += l; + b->slen = i; + if (i < n) break; + } + + b->data[i] = (unsigned char) '\0'; + return BSTR_OK; +} + +/* bstring bread (bNread readPtr, void * parm) + * + * Use a finite buffer fread-like function readPtr to create a bstring + * filled with the entire contents of file-like source data in a roughly + * efficient way. + */ +bstring bread (bNread readPtr, void * parm) { +bstring buff; + + if (0 > breada (buff = bfromcstr (""), readPtr, parm)) { + bdestroy (buff); + return NULL; + } + return buff; +} + +/* int bassigngets (bstring b, bNgetc getcPtr, void * parm, char terminator) + * + * Use an fgetc-like single character stream reading function (getcPtr) to + * obtain a sequence of characters which are concatenated to the end of the + * bstring b. The stream read is terminated by the passed in terminator + * parameter. + * + * If getcPtr returns with a negative number, or the terminator character + * (which is appended) is read, then the stream reading is halted and the + * function returns with a partial result in b. If there is an empty partial + * result, 1 is returned. If no characters are read, or there is some other + * detectable error, BSTR_ERR is returned. + */ +int bassigngets (bstring b, bNgetc getcPtr, void * parm, char terminator) { +int c, d, e; + + if (b == NULL || b->mlen <= 0 || b->slen < 0 || b->mlen < b->slen || + getcPtr == NULL) return BSTR_ERR; + d = 0; + e = b->mlen - 2; + + while ((c = getcPtr (parm)) >= 0) { + if (d > e) { + b->slen = d; + if (balloc (b, d + 2) != BSTR_OK) return BSTR_ERR; + e = b->mlen - 2; + } + b->data[d] = (unsigned char) c; + d++; + if (c == terminator) break; + } + + b->data[d] = (unsigned char) '\0'; + b->slen = d; + + return d == 0 && c < 0; +} + +/* int bgetsa (bstring b, bNgetc getcPtr, void * parm, char terminator) + * + * Use an fgetc-like single character stream reading function (getcPtr) to + * obtain a sequence of characters which are concatenated to the end of the + * bstring b. The stream read is terminated by the passed in terminator + * parameter. + * + * If getcPtr returns with a negative number, or the terminator character + * (which is appended) is read, then the stream reading is halted and the + * function returns with a partial result concatentated to b. If there is + * an empty partial result, 1 is returned. If no characters are read, or + * there is some other detectable error, BSTR_ERR is returned. + */ +int bgetsa (bstring b, bNgetc getcPtr, void * parm, char terminator) { +int c, d, e; + + if (b == NULL || b->mlen <= 0 || b->slen < 0 || b->mlen < b->slen || + getcPtr == NULL) return BSTR_ERR; + d = b->slen; + e = b->mlen - 2; + + while ((c = getcPtr (parm)) >= 0) { + if (d > e) { + b->slen = d; + if (balloc (b, d + 2) != BSTR_OK) return BSTR_ERR; + e = b->mlen - 2; + } + b->data[d] = (unsigned char) c; + d++; + if (c == terminator) break; + } + + b->data[d] = (unsigned char) '\0'; + b->slen = d; + + return d == 0 && c < 0; +} + +/* bstring bgets (bNgetc getcPtr, void * parm, char terminator) + * + * Use an fgetc-like single character stream reading function (getcPtr) to + * obtain a sequence of characters which are concatenated into a bstring. + * The stream read is terminated by the passed in terminator function. + * + * If getcPtr returns with a negative number, or the terminator character + * (which is appended) is read, then the stream reading is halted and the + * result obtained thus far is returned. If no characters are read, or + * there is some other detectable error, NULL is returned. + */ +bstring bgets (bNgetc getcPtr, void * parm, char terminator) { +bstring buff; + + if (0 > bgetsa (buff = bfromcstr (""), getcPtr, parm, terminator) || + 0 >= buff->slen) { + bdestroy (buff); + buff = NULL; + } + return buff; +} + +struct bStream { + bstring buff; /* Buffer for over-reads */ + void * parm; /* The stream handle for core stream */ + bNread readFnPtr; /* fread compatible fnptr for core stream */ + int isEOF; /* track file's EOF state */ + int maxBuffSz; +}; + +/* struct bStream * bsopen (bNread readPtr, void * parm) + * + * Wrap a given open stream (described by a fread compatible function + * pointer and stream handle) into an open bStream suitable for the bstring + * library streaming functions. + */ +struct bStream * bsopen (bNread readPtr, void * parm) { +struct bStream * s; + + if (readPtr == NULL) return NULL; + s = (struct bStream *) bstr__alloc (sizeof (struct bStream)); + if (s == NULL) return NULL; + s->parm = parm; + s->buff = bfromcstr (""); + s->readFnPtr = readPtr; + s->maxBuffSz = BS_BUFF_SZ; + s->isEOF = 0; + return s; +} + +/* int bsbufflength (struct bStream * s, int sz) + * + * Set the length of the buffer used by the bStream. If sz is zero, the + * length is not set. This function returns with the previous length. + */ +int bsbufflength (struct bStream * s, int sz) { +int oldSz; + if (s == NULL || sz < 0) return BSTR_ERR; + oldSz = s->maxBuffSz; + if (sz > 0) s->maxBuffSz = sz; + return oldSz; +} + +int bseof (const struct bStream * s) { + if (s == NULL || s->readFnPtr == NULL) return BSTR_ERR; + return s->isEOF && (s->buff->slen == 0); +} + +/* void * bsclose (struct bStream * s) + * + * Close the bStream, and return the handle to the stream that was originally + * used to open the given stream. + */ +void * bsclose (struct bStream * s) { +void * parm; + if (s == NULL) return NULL; + s->readFnPtr = NULL; + if (s->buff) bdestroy (s->buff); + s->buff = NULL; + parm = s->parm; + s->parm = NULL; + s->isEOF = 1; + bstr__free (s); + return parm; +} + +/* int bsreadlna (bstring r, struct bStream * s, char terminator) + * + * Read a bstring terminated by the terminator character or the end of the + * stream from the bStream (s) and return it into the parameter r. This + * function may read additional characters from the core stream that are not + * returned, but will be retained for subsequent read operations. + */ +int bsreadlna (bstring r, struct bStream * s, char terminator) { +int i, l, ret, rlo; +char * b; +struct tagbstring x; + + if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0 || + r->slen < 0 || r->mlen < r->slen) return BSTR_ERR; + l = s->buff->slen; + if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; + b = (char *) s->buff->data; + x.data = (unsigned char *) b; + + /* First check if the current buffer holds the terminator */ + b[l] = terminator; /* Set sentinel */ + for (i=0; b[i] != terminator; i++) ; + if (i < l) { + x.slen = i + 1; + ret = bconcat (r, &x); + s->buff->slen = l; + if (BSTR_OK == ret) bdelete (s->buff, 0, i + 1); + return BSTR_OK; + } + + rlo = r->slen; + + /* If not then just concatenate the entire buffer to the output */ + x.slen = l; + if (BSTR_OK != bconcat (r, &x)) return BSTR_ERR; + + /* Perform direct in-place reads into the destination to allow for + the minimum of data-copies */ + for (;;) { + if (BSTR_OK != balloc (r, r->slen + s->maxBuffSz + 1)) + return BSTR_ERR; + b = (char *) (r->data + r->slen); + l = (int) s->readFnPtr (b, 1, s->maxBuffSz, s->parm); + if (l <= 0) { + r->data[r->slen] = (unsigned char) '\0'; + s->buff->slen = 0; + s->isEOF = 1; + /* If nothing was read return with an error message */ + return BSTR_ERR & -(r->slen == rlo); + } + b[l] = terminator; /* Set sentinel */ + for (i=0; b[i] != terminator; i++) ; + if (i < l) break; + r->slen += l; + } + + /* Terminator found, push over-read back to buffer */ + i++; + r->slen += i; + s->buff->slen = l - i; + bstr__memcpy (s->buff->data, b + i, l - i); + r->data[r->slen] = (unsigned char) '\0'; + return BSTR_OK; +} + +/* int bsreadlnsa (bstring r, struct bStream * s, bstring term) + * + * Read a bstring terminated by any character in the term string or the end + * of the stream from the bStream (s) and return it into the parameter r. + * This function may read additional characters from the core stream that + * are not returned, but will be retained for subsequent read operations. + */ +int bsreadlnsa (bstring r, struct bStream * s, const_bstring term) { +int i, l, ret, rlo; +unsigned char * b; +struct tagbstring x; +struct charField cf; + + if (s == NULL || s->buff == NULL || r == NULL || term == NULL || + term->data == NULL || r->mlen <= 0 || r->slen < 0 || + r->mlen < r->slen) return BSTR_ERR; + if (term->slen == 1) return bsreadlna (r, s, term->data[0]); + if (term->slen < 1 || buildCharField (&cf, term)) return BSTR_ERR; + + l = s->buff->slen; + if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; + b = (unsigned char *) s->buff->data; + x.data = b; + + /* First check if the current buffer holds the terminator */ + b[l] = term->data[0]; /* Set sentinel */ + for (i=0; !testInCharField (&cf, b[i]); i++) ; + if (i < l) { + x.slen = i + 1; + ret = bconcat (r, &x); + s->buff->slen = l; + if (BSTR_OK == ret) bdelete (s->buff, 0, i + 1); + return BSTR_OK; + } + + rlo = r->slen; + + /* If not then just concatenate the entire buffer to the output */ + x.slen = l; + if (BSTR_OK != bconcat (r, &x)) return BSTR_ERR; + + /* Perform direct in-place reads into the destination to allow for + the minimum of data-copies */ + for (;;) { + if (BSTR_OK != balloc (r, r->slen + s->maxBuffSz + 1)) + return BSTR_ERR; + b = (unsigned char *) (r->data + r->slen); + l = (int) s->readFnPtr (b, 1, s->maxBuffSz, s->parm); + if (l <= 0) { + r->data[r->slen] = (unsigned char) '\0'; + s->buff->slen = 0; + s->isEOF = 1; + /* If nothing was read return with an error message */ + return BSTR_ERR & -(r->slen == rlo); + } + + b[l] = term->data[0]; /* Set sentinel */ + for (i=0; !testInCharField (&cf, b[i]); i++) ; + if (i < l) break; + r->slen += l; + } + + /* Terminator found, push over-read back to buffer */ + i++; + r->slen += i; + s->buff->slen = l - i; + bstr__memcpy (s->buff->data, b + i, l - i); + r->data[r->slen] = (unsigned char) '\0'; + return BSTR_OK; +} + +/* int bsreada (bstring r, struct bStream * s, int n) + * + * Read a bstring of length n (or, if it is fewer, as many bytes as is + * remaining) from the bStream. This function may read additional + * characters from the core stream that are not returned, but will be + * retained for subsequent read operations. This function will not read + * additional characters from the core stream beyond virtual stream pointer. + */ +int bsreada (bstring r, struct bStream * s, int n) { +int l, ret, orslen; +char * b; +struct tagbstring x; + + if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0 + || r->slen < 0 || r->mlen < r->slen || n <= 0) return BSTR_ERR; + + if (n > INT_MAX - r->slen) return BSTR_ERR; + n += r->slen; + + l = s->buff->slen; + + orslen = r->slen; + + if (0 == l) { + if (s->isEOF) return BSTR_ERR; + if (r->mlen > n) { + l = (int) s->readFnPtr (r->data + r->slen, 1, n - r->slen, + s->parm); + if (0 >= l || l > n - r->slen) { + s->isEOF = 1; + return BSTR_ERR; + } + r->slen += l; + r->data[r->slen] = (unsigned char) '\0'; + return 0; + } + } + + if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; + b = (char *) s->buff->data; + x.data = (unsigned char *) b; + + do { + if (l + r->slen >= n) { + x.slen = n - r->slen; + ret = bconcat (r, &x); + s->buff->slen = l; + if (BSTR_OK == ret) bdelete (s->buff, 0, x.slen); + return BSTR_ERR & -(r->slen == orslen); + } + + x.slen = l; + if (BSTR_OK != bconcat (r, &x)) break; + + l = n - r->slen; + if (l > s->maxBuffSz) l = s->maxBuffSz; + + l = (int) s->readFnPtr (b, 1, l, s->parm); + + } while (l > 0); + if (l < 0) l = 0; + if (l == 0) s->isEOF = 1; + s->buff->slen = l; + return BSTR_ERR & -(r->slen == orslen); +} + +/* int bsreadln (bstring r, struct bStream * s, char terminator) + * + * Read a bstring terminated by the terminator character or the end of the + * stream from the bStream (s) and return it into the parameter r. This + * function may read additional characters from the core stream that are not + * returned, but will be retained for subsequent read operations. + */ +int bsreadln (bstring r, struct bStream * s, char terminator) { + if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0) + return BSTR_ERR; + if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; + r->slen = 0; + return bsreadlna (r, s, terminator); +} + +/* int bsreadlns (bstring r, struct bStream * s, bstring term) + * + * Read a bstring terminated by any character in the term string or the end + * of the stream from the bStream (s) and return it into the parameter r. + * This function may read additional characters from the core stream that + * are not returned, but will be retained for subsequent read operations. + */ +int bsreadlns (bstring r, struct bStream * s, const_bstring term) { + if (s == NULL || s->buff == NULL || r == NULL || term == NULL + || term->data == NULL || r->mlen <= 0) return BSTR_ERR; + if (term->slen == 1) return bsreadln (r, s, term->data[0]); + if (term->slen < 1) return BSTR_ERR; + if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; + r->slen = 0; + return bsreadlnsa (r, s, term); +} + +/* int bsread (bstring r, struct bStream * s, int n) + * + * Read a bstring of length n (or, if it is fewer, as many bytes as is + * remaining) from the bStream. This function may read additional + * characters from the core stream that are not returned, but will be + * retained for subsequent read operations. This function will not read + * additional characters from the core stream beyond virtual stream pointer. + */ +int bsread (bstring r, struct bStream * s, int n) { + if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0 + || n <= 0) return BSTR_ERR; + if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; + r->slen = 0; + return bsreada (r, s, n); +} + +/* int bsunread (struct bStream * s, const_bstring b) + * + * Insert a bstring into the bStream at the current position. These + * characters will be read prior to those that actually come from the core + * stream. + */ +int bsunread (struct bStream * s, const_bstring b) { + if (s == NULL || s->buff == NULL) return BSTR_ERR; + return binsert (s->buff, 0, b, (unsigned char) '?'); +} + +/* int bspeek (bstring r, const struct bStream * s) + * + * Return the currently buffered characters from the bStream that will be + * read prior to reads from the core stream. + */ +int bspeek (bstring r, const struct bStream * s) { + if (s == NULL || s->buff == NULL) return BSTR_ERR; + return bassign (r, s->buff); +} + +/* bstring bjoinblk (const struct bstrList * bl, void * blk, int len); + * + * Join the entries of a bstrList into one bstring by sequentially + * concatenating them with the content from blk for length len in between. + * If there is an error NULL is returned, otherwise a bstring with the + * correct result is returned. + */ +bstring bjoinblk (const struct bstrList * bl, const void * blk, int len) { +bstring b; +unsigned char * p; +int i, c, v; + + if (bl == NULL || bl->qty < 0) return NULL; + if (len < 0) return NULL; + if (len > 0 && blk == NULL) return NULL; + if (bl->qty < 1) return bfromStatic (""); + + for (i = 0, c = 1; i < bl->qty; i++) { + v = bl->entry[i]->slen; + if (v < 0) return NULL; /* Invalid input */ + if (v > INT_MAX - c) return NULL; /* Overflow */ + c += v; + } + + b = (bstring) bstr__alloc (sizeof (struct tagbstring)); + if (len == 0) { + p = b->data = (unsigned char *) bstr__alloc (c); + if (p == NULL) { + bstr__free (b); + return NULL; + } + for (i = 0; i < bl->qty; i++) { + v = bl->entry[i]->slen; + bstr__memcpy (p, bl->entry[i]->data, v); + p += v; + } + } else { + v = (bl->qty - 1) * len; + if ((bl->qty > 512 || len > 127) && + v / len != bl->qty - 1) return NULL; /* Overflow */ + if (v > INT_MAX - c) return NULL; /* Overflow */ + c += v; + p = b->data = (unsigned char *) bstr__alloc (c); + if (p == NULL) { + bstr__free (b); + return NULL; + } + v = bl->entry[0]->slen; + bstr__memcpy (p, bl->entry[0]->data, v); + p += v; + for (i = 1; i < bl->qty; i++) { + bstr__memcpy (p, blk, len); + p += len; + v = bl->entry[i]->slen; + if (v) { + bstr__memcpy (p, bl->entry[i]->data, v); + p += v; + } + } + } + b->mlen = c; + b->slen = c-1; + b->data[c-1] = (unsigned char) '\0'; + return b; +} + +/* bstring bjoin (const struct bstrList * bl, const_bstring sep); + * + * Join the entries of a bstrList into one bstring by sequentially + * concatenating them with the sep string in between. If there is an error + * NULL is returned, otherwise a bstring with the correct result is returned. + */ +bstring bjoin (const struct bstrList * bl, const_bstring sep) { + if (sep != NULL && (sep->slen < 0 || sep->data == NULL)) return NULL; + return bjoinblk (bl, sep->data, sep->slen); +} + +#define BSSSC_BUFF_LEN (256) + +/* int bssplitscb (struct bStream * s, const_bstring splitStr, + * int (* cb) (void * parm, int ofs, const_bstring entry), + * void * parm) + * + * Iterate the set of disjoint sequential substrings read from a stream + * divided by any of the characters in splitStr. An empty splitStr causes + * the whole stream to be iterated once. + * + * Note: At the point of calling the cb function, the bStream pointer is + * pointed exactly at the position right after having read the split + * character. The cb function can act on the stream by causing the bStream + * pointer to move, and bssplitscb will continue by starting the next split + * at the position of the pointer after the return from cb. + * + * However, if the cb causes the bStream s to be destroyed then the cb must + * return with a negative value, otherwise bssplitscb will continue in an + * undefined manner. + */ +int bssplitscb (struct bStream * s, const_bstring splitStr, + int (* cb) (void * parm, int ofs, const_bstring entry), void * parm) { +struct charField chrs; +bstring buff; +int i, p, ret; + + if (cb == NULL || s == NULL || s->readFnPtr == NULL || + splitStr == NULL || splitStr->slen < 0) return BSTR_ERR; + + if (NULL == (buff = bfromcstr (""))) return BSTR_ERR; + + if (splitStr->slen == 0) { + while (bsreada (buff, s, BSSSC_BUFF_LEN) >= 0) ; + if ((ret = cb (parm, 0, buff)) > 0) + ret = 0; + } else { + buildCharField (&chrs, splitStr); + ret = p = i = 0; + for (;;) { + if (i >= buff->slen) { + bsreada (buff, s, BSSSC_BUFF_LEN); + if (i >= buff->slen) { + if (0 < (ret = cb (parm, p, buff))) ret = 0; + break; + } + } + if (testInCharField (&chrs, buff->data[i])) { + struct tagbstring t; + unsigned char c; + + blk2tbstr (t, buff->data + i + 1, buff->slen - (i + 1)); + if ((ret = bsunread (s, &t)) < 0) break; + buff->slen = i; + c = buff->data[i]; + buff->data[i] = (unsigned char) '\0'; + if ((ret = cb (parm, p, buff)) < 0) break; + buff->data[i] = c; + buff->slen = 0; + p += i + 1; + i = -1; + } + i++; + } + } + + bdestroy (buff); + return ret; +} + +/* int bssplitstrcb (struct bStream * s, const_bstring splitStr, + * int (* cb) (void * parm, int ofs, const_bstring entry), + * void * parm) + * + * Iterate the set of disjoint sequential substrings read from a stream + * divided by the entire substring splitStr. An empty splitStr causes + * each character of the stream to be iterated. + * + * Note: At the point of calling the cb function, the bStream pointer is + * pointed exactly at the position right after having read the split + * character. The cb function can act on the stream by causing the bStream + * pointer to move, and bssplitscb will continue by starting the next split + * at the position of the pointer after the return from cb. + * + * However, if the cb causes the bStream s to be destroyed then the cb must + * return with a negative value, otherwise bssplitscb will continue in an + * undefined manner. + */ +int bssplitstrcb (struct bStream * s, const_bstring splitStr, + int (* cb) (void * parm, int ofs, const_bstring entry), void * parm) { +bstring buff; +int i, p, ret; + + if (cb == NULL || s == NULL || s->readFnPtr == NULL + || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR; + + if (splitStr->slen == 1) return bssplitscb (s, splitStr, cb, parm); + + if (NULL == (buff = bfromcstr (""))) return BSTR_ERR; + + if (splitStr->slen == 0) { + for (i=0; bsreada (buff, s, BSSSC_BUFF_LEN) >= 0; i++) { + if ((ret = cb (parm, 0, buff)) < 0) { + bdestroy (buff); + return ret; + } + buff->slen = 0; + } + return BSTR_OK; + } else { + ret = p = i = 0; + for (i=p=0;;) { + if ((ret = binstr (buff, 0, splitStr)) >= 0) { + struct tagbstring t; + blk2tbstr (t, buff->data, ret); + i = ret + splitStr->slen; + if ((ret = cb (parm, p, &t)) < 0) break; + p += i; + bdelete (buff, 0, i); + } else { + bsreada (buff, s, BSSSC_BUFF_LEN); + if (bseof (s)) { + if ((ret = cb (parm, p, buff)) > 0) ret = 0; + break; + } + } + } + } + + bdestroy (buff); + return ret; +} + +/* int bstrListCreate (void) + * + * Create a bstrList. + */ +struct bstrList * bstrListCreate (void) { +struct bstrList * sl = + (struct bstrList *) bstr__alloc (sizeof (struct bstrList)); + if (sl) { + sl->entry = (bstring *) bstr__alloc (1*sizeof (bstring)); + if (!sl->entry) { + bstr__free (sl); + sl = NULL; + } else { + sl->qty = 0; + sl->mlen = 1; + } + } + return sl; +} + +/* int bstrListDestroy (struct bstrList * sl) + * + * Destroy a bstrList that has been created by bsplit, bsplits or + * bstrListCreate. + */ +int bstrListDestroy (struct bstrList * sl) { +int i; + if (sl == NULL || sl->qty < 0) return BSTR_ERR; + for (i=0; i < sl->qty; i++) { + if (sl->entry[i]) { + bdestroy (sl->entry[i]); + sl->entry[i] = NULL; + } + } + sl->qty = -1; + sl->mlen = -1; + bstr__free (sl->entry); + sl->entry = NULL; + bstr__free (sl); + return BSTR_OK; +} + +/* int bstrListAlloc (struct bstrList * sl, int msz) + * + * Ensure that there is memory for at least msz number of entries for the + * list. + */ +int bstrListAlloc (struct bstrList * sl, int msz) { +bstring * l; +int smsz; +size_t nsz; + if (!sl || msz <= 0 || !sl->entry || sl->qty < 0 || sl->mlen <= 0 || + sl->qty > sl->mlen) return BSTR_ERR; + if (sl->mlen >= msz) return BSTR_OK; + smsz = snapUpSize (msz); + nsz = ((size_t) smsz) * sizeof (bstring); + if (nsz < (size_t) smsz) return BSTR_ERR; + l = (bstring *) bstr__realloc (sl->entry, nsz); + if (!l) { + smsz = msz; + nsz = ((size_t) smsz) * sizeof (bstring); + l = (bstring *) bstr__realloc (sl->entry, nsz); + if (!l) return BSTR_ERR; + } + sl->mlen = smsz; + sl->entry = l; + return BSTR_OK; +} + +/* int bstrListAllocMin (struct bstrList * sl, int msz) + * + * Try to allocate the minimum amount of memory for the list to include at + * least msz entries or sl->qty whichever is greater. + */ +int bstrListAllocMin (struct bstrList * sl, int msz) { +bstring * l; +size_t nsz; + if (!sl || msz <= 0 || !sl->entry || sl->qty < 0 || sl->mlen <= 0 || + sl->qty > sl->mlen) return BSTR_ERR; + if (msz < sl->qty) msz = sl->qty; + if (sl->mlen == msz) return BSTR_OK; + nsz = ((size_t) msz) * sizeof (bstring); + if (nsz < (size_t) msz) return BSTR_ERR; + l = (bstring *) bstr__realloc (sl->entry, nsz); + if (!l) return BSTR_ERR; + sl->mlen = msz; + sl->entry = l; + return BSTR_OK; +} + +/* int bsplitcb (const_bstring str, unsigned char splitChar, int pos, + * int (* cb) (void * parm, int ofs, int len), void * parm) + * + * Iterate the set of disjoint sequential substrings over str divided by the + * character in splitChar. + * + * Note: Non-destructive modification of str from within the cb function + * while performing this split is not undefined. bsplitcb behaves in + * sequential lock step with calls to cb. I.e., after returning from a cb + * that return a non-negative integer, bsplitcb continues from the position + * 1 character after the last detected split character and it will halt + * immediately if the length of str falls below this point. However, if the + * cb function destroys str, then it *must* return with a negative value, + * otherwise bsplitcb will continue in an undefined manner. + */ +int bsplitcb (const_bstring str, unsigned char splitChar, int pos, + int (* cb) (void * parm, int ofs, int len), void * parm) { +int i, p, ret; + + if (cb == NULL || str == NULL || pos < 0 || pos > str->slen) + return BSTR_ERR; + + p = pos; + do { + for (i=p; i < str->slen; i++) { + if (str->data[i] == splitChar) break; + } + if ((ret = cb (parm, p, i - p)) < 0) return ret; + p = i + 1; + } while (p <= str->slen); + return BSTR_OK; +} + +/* int bsplitscb (const_bstring str, const_bstring splitStr, int pos, + * int (* cb) (void * parm, int ofs, int len), void * parm) + * + * Iterate the set of disjoint sequential substrings over str divided by any + * of the characters in splitStr. An empty splitStr causes the whole str to + * be iterated once. + * + * Note: Non-destructive modification of str from within the cb function + * while performing this split is not undefined. bsplitscb behaves in + * sequential lock step with calls to cb. I.e., after returning from a cb + * that return a non-negative integer, bsplitscb continues from the position + * 1 character after the last detected split character and it will halt + * immediately if the length of str falls below this point. However, if the + * cb function destroys str, then it *must* return with a negative value, + * otherwise bsplitscb will continue in an undefined manner. + */ +int bsplitscb (const_bstring str, const_bstring splitStr, int pos, + int (* cb) (void * parm, int ofs, int len), void * parm) { +struct charField chrs; +int i, p, ret; + + if (cb == NULL || str == NULL || pos < 0 || pos > str->slen + || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR; + if (splitStr->slen == 0) { + if ((ret = cb (parm, 0, str->slen)) > 0) ret = 0; + return ret; + } + + if (splitStr->slen == 1) + return bsplitcb (str, splitStr->data[0], pos, cb, parm); + + buildCharField (&chrs, splitStr); + + p = pos; + do { + for (i=p; i < str->slen; i++) { + if (testInCharField (&chrs, str->data[i])) break; + } + if ((ret = cb (parm, p, i - p)) < 0) return ret; + p = i + 1; + } while (p <= str->slen); + return BSTR_OK; +} + +/* int bsplitstrcb (const_bstring str, const_bstring splitStr, int pos, + * int (* cb) (void * parm, int ofs, int len), void * parm) + * + * Iterate the set of disjoint sequential substrings over str divided by the + * substring splitStr. An empty splitStr causes the whole str to be + * iterated once. + * + * Note: Non-destructive modification of str from within the cb function + * while performing this split is not undefined. bsplitstrcb behaves in + * sequential lock step with calls to cb. I.e., after returning from a cb + * that return a non-negative integer, bsplitscb continues from the position + * 1 character after the last detected split character and it will halt + * immediately if the length of str falls below this point. However, if the + * cb function destroys str, then it *must* return with a negative value, + * otherwise bsplitscb will continue in an undefined manner. + */ +int bsplitstrcb (const_bstring str, const_bstring splitStr, int pos, + int (* cb) (void * parm, int ofs, int len), void * parm) { +int i, p, ret; + + if (cb == NULL || str == NULL || pos < 0 || pos > str->slen + || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR; + + if (0 == splitStr->slen) { + for (i=pos; i < str->slen; i++) { + if ((ret = cb (parm, i, 1)) < 0) return ret; + } + return BSTR_OK; + } + + if (splitStr->slen == 1) + return bsplitcb (str, splitStr->data[0], pos, cb, parm); + + for (i=p=pos; i <= str->slen - splitStr->slen; i++) { + if (0 == bstr__memcmp (splitStr->data, str->data + i, + splitStr->slen)) { + if ((ret = cb (parm, p, i - p)) < 0) return ret; + i += splitStr->slen; + p = i; + } + } + if ((ret = cb (parm, p, str->slen - p)) < 0) return ret; + return BSTR_OK; +} + +struct genBstrList { + bstring b; + struct bstrList * bl; +}; + +static int bscb (void * parm, int ofs, int len) { +struct genBstrList * g = (struct genBstrList *) parm; + if (g->bl->qty >= g->bl->mlen) { + int mlen = g->bl->mlen * 2; + bstring * tbl; + + while (g->bl->qty >= mlen) { + if (mlen < g->bl->mlen) return BSTR_ERR; + mlen += mlen; + } + + tbl = (bstring *) bstr__realloc (g->bl->entry, + sizeof (bstring) * mlen); + if (tbl == NULL) return BSTR_ERR; + + g->bl->entry = tbl; + g->bl->mlen = mlen; + } + + g->bl->entry[g->bl->qty] = bmidstr (g->b, ofs, len); + g->bl->qty++; + return BSTR_OK; +} + +/* struct bstrList * bsplit (const_bstring str, unsigned char splitChar) + * + * Create an array of sequential substrings from str divided by the character + * splitChar. + */ +struct bstrList * bsplit (const_bstring str, unsigned char splitChar) { +struct genBstrList g; + + if (str == NULL || str->data == NULL || str->slen < 0) return NULL; + + g.bl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList)); + if (g.bl == NULL) return NULL; + g.bl->mlen = 4; + g.bl->entry = (bstring *) bstr__alloc (g.bl->mlen * sizeof (bstring)); + if (NULL == g.bl->entry) { + bstr__free (g.bl); + return NULL; + } + + g.b = (bstring) str; + g.bl->qty = 0; + if (bsplitcb (str, splitChar, 0, bscb, &g) < 0) { + bstrListDestroy (g.bl); + return NULL; + } + return g.bl; +} + +/* struct bstrList * bsplitstr (const_bstring str, const_bstring splitStr) + * + * Create an array of sequential substrings from str divided by the entire + * substring splitStr. + */ +struct bstrList * bsplitstr (const_bstring str, const_bstring splitStr) { +struct genBstrList g; + + if (str == NULL || str->data == NULL || str->slen < 0) return NULL; + + g.bl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList)); + if (g.bl == NULL) return NULL; + g.bl->mlen = 4; + g.bl->entry = (bstring *) bstr__alloc (g.bl->mlen * sizeof (bstring)); + if (NULL == g.bl->entry) { + bstr__free (g.bl); + return NULL; + } + + g.b = (bstring) str; + g.bl->qty = 0; + if (bsplitstrcb (str, splitStr, 0, bscb, &g) < 0) { + bstrListDestroy (g.bl); + return NULL; + } + return g.bl; +} + +/* struct bstrList * bsplits (const_bstring str, bstring splitStr) + * + * Create an array of sequential substrings from str divided by any of the + * characters in splitStr. An empty splitStr causes a single entry bstrList + * containing a copy of str to be returned. + */ +struct bstrList * bsplits (const_bstring str, const_bstring splitStr) { +struct genBstrList g; + + if ( str == NULL || str->slen < 0 || str->data == NULL || + splitStr == NULL || splitStr->slen < 0 || splitStr->data == NULL) + return NULL; + + g.bl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList)); + if (g.bl == NULL) return NULL; + g.bl->mlen = 4; + g.bl->entry = (bstring *) bstr__alloc (g.bl->mlen * sizeof (bstring)); + if (NULL == g.bl->entry) { + bstr__free (g.bl); + return NULL; + } + g.b = (bstring) str; + g.bl->qty = 0; + + if (bsplitscb (str, splitStr, 0, bscb, &g) < 0) { + bstrListDestroy (g.bl); + return NULL; + } + return g.bl; +} + +#if defined (__TURBOC__) && !defined (__BORLANDC__) +# ifndef BSTRLIB_NOVSNP +# define BSTRLIB_NOVSNP +# endif +#endif + +/* Give WATCOM C/C++, MSVC some latitude for their non-support of vsnprintf */ +#if defined(__WATCOMC__) || defined(_MSC_VER) +#define exvsnprintf(r,b,n,f,a) {r = _vsnprintf (b,n,f,a);} +#else +#ifdef BSTRLIB_NOVSNP +/* This is just a hack. If you are using a system without a vsnprintf, it is + not recommended that bformat be used at all. */ +#define exvsnprintf(r,b,n,f,a) {vsprintf (b,f,a); r = -1;} +#define START_VSNBUFF (256) +#else + +#if defined(__GNUC__) && !defined(__APPLE__) +/* Something is making gcc complain about this prototype not being here, so + I've just gone ahead and put it in. */ +extern int vsnprintf (char *buf, size_t count, const char *format, va_list arg); +#endif + +#define exvsnprintf(r,b,n,f,a) {r = vsnprintf (b,n,f,a);} +#endif +#endif + +#if !defined (BSTRLIB_NOVSNP) + +#ifndef START_VSNBUFF +#define START_VSNBUFF (16) +#endif + +/* On IRIX vsnprintf returns n-1 when the operation would overflow the target + buffer, WATCOM and MSVC both return -1, while C99 requires that the + returned value be exactly what the length would be if the buffer would be + large enough. This leads to the idea that if the return value is larger + than n, then changing n to the return value will reduce the number of + iterations required. */ + +/* int bformata (bstring b, const char * fmt, ...) + * + * After the first parameter, it takes the same parameters as printf (), but + * rather than outputting results to stdio, it appends the results to + * a bstring which contains what would have been output. Note that if there + * is an early generation of a '\0' character, the bstring will be truncated + * to this end point. + */ +int bformata (bstring b, const char * fmt, ...) { +va_list arglist; +bstring buff; +int n, r; + + if (b == NULL || fmt == NULL || b->data == NULL || b->mlen <= 0 + || b->slen < 0 || b->slen > b->mlen) return BSTR_ERR; + + /* Since the length is not determinable beforehand, a search is + performed using the truncating "vsnprintf" call (to avoid buffer + overflows) on increasing potential sizes for the output result. */ + + if ((n = (int) (2*strlen (fmt))) < START_VSNBUFF) n = START_VSNBUFF; + if (NULL == (buff = bfromcstralloc (n + 2, ""))) { + n = 1; + if (NULL == (buff = bfromcstralloc (n + 2, ""))) return BSTR_ERR; + } + + for (;;) { + va_start (arglist, fmt); + exvsnprintf (r, (char *) buff->data, n + 1, fmt, arglist); + va_end (arglist); + + buff->data[n] = (unsigned char) '\0'; + buff->slen = (int) (strlen) ((char *) buff->data); + + if (buff->slen < n) break; + + if (r > n) n = r; else n += n; + + if (BSTR_OK != balloc (buff, n + 2)) { + bdestroy (buff); + return BSTR_ERR; + } + } + + r = bconcat (b, buff); + bdestroy (buff); + return r; +} + +/* int bassignformat (bstring b, const char * fmt, ...) + * + * After the first parameter, it takes the same parameters as printf (), but + * rather than outputting results to stdio, it outputs the results to + * the bstring parameter b. Note that if there is an early generation of a + * '\0' character, the bstring will be truncated to this end point. + */ +int bassignformat (bstring b, const char * fmt, ...) { +va_list arglist; +bstring buff; +int n, r; + + if (b == NULL || fmt == NULL || b->data == NULL || b->mlen <= 0 + || b->slen < 0 || b->slen > b->mlen) return BSTR_ERR; + + /* Since the length is not determinable beforehand, a search is + performed using the truncating "vsnprintf" call (to avoid buffer + overflows) on increasing potential sizes for the output result. */ + + if ((n = (int) (2*strlen (fmt))) < START_VSNBUFF) n = START_VSNBUFF; + if (NULL == (buff = bfromcstralloc (n + 2, ""))) { + n = 1; + if (NULL == (buff = bfromcstralloc (n + 2, ""))) return BSTR_ERR; + } + + for (;;) { + va_start (arglist, fmt); + exvsnprintf (r, (char *) buff->data, n + 1, fmt, arglist); + va_end (arglist); + + buff->data[n] = (unsigned char) '\0'; + buff->slen = (int) (strlen) ((char *) buff->data); + + if (buff->slen < n) break; + + if (r > n) n = r; else n += n; + + if (BSTR_OK != balloc (buff, n + 2)) { + bdestroy (buff); + return BSTR_ERR; + } + } + + r = bassign (b, buff); + bdestroy (buff); + return r; +} + +/* bstring bformat (const char * fmt, ...) + * + * Takes the same parameters as printf (), but rather than outputting results + * to stdio, it forms a bstring which contains what would have been output. + * Note that if there is an early generation of a '\0' character, the + * bstring will be truncated to this end point. + */ +bstring bformat (const char * fmt, ...) { +va_list arglist; +bstring buff; +int n, r; + + if (fmt == NULL) return NULL; + + /* Since the length is not determinable beforehand, a search is + performed using the truncating "vsnprintf" call (to avoid buffer + overflows) on increasing potential sizes for the output result. */ + + if ((n = (int) (2*strlen (fmt))) < START_VSNBUFF) n = START_VSNBUFF; + if (NULL == (buff = bfromcstralloc (n + 2, ""))) { + n = 1; + if (NULL == (buff = bfromcstralloc (n + 2, ""))) return NULL; + } + + for (;;) { + va_start (arglist, fmt); + exvsnprintf (r, (char *) buff->data, n + 1, fmt, arglist); + va_end (arglist); + + buff->data[n] = (unsigned char) '\0'; + buff->slen = (int) (strlen) ((char *) buff->data); + + if (buff->slen < n) break; + + if (r > n) n = r; else n += n; + + if (BSTR_OK != balloc (buff, n + 2)) { + bdestroy (buff); + return NULL; + } + } + + return buff; +} + +/* int bvcformata (bstring b, int count, const char * fmt, va_list arglist) + * + * The bvcformata function formats data under control of the format control + * string fmt and attempts to append the result to b. The fmt parameter is + * the same as that of the printf function. The variable argument list is + * replaced with arglist, which has been initialized by the va_start macro. + * The size of the output is upper bounded by count. If the required output + * exceeds count, the string b is not augmented with any contents and a value + * below BSTR_ERR is returned. If a value below -count is returned then it + * is recommended that the negative of this value be used as an update to the + * count in a subsequent pass. On other errors, such as running out of + * memory, parameter errors or numeric wrap around BSTR_ERR is returned. + * BSTR_OK is returned when the output is successfully generated and + * appended to b. + * + * Note: There is no sanity checking of arglist, and this function is + * destructive of the contents of b from the b->slen point onward. If there + * is an early generation of a '\0' character, the bstring will be truncated + * to this end point. + */ +int bvcformata (bstring b, int count, const char * fmt, va_list arg) { +int n, r, l; + + if (b == NULL || fmt == NULL || count <= 0 || b->data == NULL + || b->mlen <= 0 || b->slen < 0 || b->slen > b->mlen) return BSTR_ERR; + + if (count > (n = b->slen + count) + 2) return BSTR_ERR; + if (BSTR_OK != balloc (b, n + 2)) return BSTR_ERR; + + exvsnprintf (r, (char *) b->data + b->slen, count + 2, fmt, arg); + b->data[b->slen + count + 2] = '\0'; + + /* Did the operation complete successfully within bounds? */ + + if (n >= (l = b->slen + (int) (strlen) ((char *) b->data + b->slen))) { + b->slen = l; + return BSTR_OK; + } + + /* Abort, since the buffer was not large enough. The return value + tries to help set what the retry length should be. */ + + b->data[b->slen] = '\0'; + if (r > count+1) { + l = r; + } else { + if (count > INT_MAX / 2) + l = INT_MAX; + else + l = count + count; + } + n = -l; + if (n > BSTR_ERR-1) n = BSTR_ERR-1; + return n; +} + +#endif diff --git a/common/bstrlib/bstrlib.h b/common/bstrlib/bstrlib.h new file mode 100644 index 0000000..57c8f89 --- /dev/null +++ b/common/bstrlib/bstrlib.h @@ -0,0 +1,321 @@ +/* + * This source file is part of the bstring string library. This code was + * written by Paul Hsieh in 2002-2015, and is covered by the BSD open source + * license and the GPL. Refer to the accompanying documentation for details + * on usage and license. + */ + +/* + * bstrlib.h + * + * This file is the interface for the core bstring functions. + */ + +#ifndef BSTRLIB_INCLUDE +#define BSTRLIB_INCLUDE + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + +#if !defined (BSTRLIB_VSNP_OK) && !defined (BSTRLIB_NOVSNP) +# if defined (__TURBOC__) && !defined (__BORLANDC__) +# define BSTRLIB_NOVSNP +# endif +#endif + +#define BSTR_ERR (-1) +#define BSTR_OK (0) +#define BSTR_BS_BUFF_LENGTH_GET (0) + +typedef struct tagbstring * bstring; +typedef const struct tagbstring * const_bstring; + +/* Version */ +#define BSTR_VER_MAJOR 1 +#define BSTR_VER_MINOR 0 +#define BSTR_VER_UPDATE 0 + +/* Copy functions */ +#define cstr2bstr bfromcstr +extern bstring bfromcstr (const char * str); +extern bstring bfromcstralloc (int mlen, const char * str); +extern bstring bfromcstrrangealloc (int minl, int maxl, const char* str); +extern bstring blk2bstr (const void * blk, int len); +extern char * bstr2cstr (const_bstring s, char z); +extern int bcstrfree (char * s); +extern bstring bstrcpy (const_bstring b1); +extern int bassign (bstring a, const_bstring b); +extern int bassignmidstr (bstring a, const_bstring b, int left, int len); +extern int bassigncstr (bstring a, const char * str); +extern int bassignblk (bstring a, const void * s, int len); + +/* Destroy function */ +extern int bdestroy (bstring b); + +/* Space allocation hinting functions */ +extern int balloc (bstring s, int len); +extern int ballocmin (bstring b, int len); + +/* Substring extraction */ +extern bstring bmidstr (const_bstring b, int left, int len); + +/* Various standard manipulations */ +extern int bconcat (bstring b0, const_bstring b1); +extern int bconchar (bstring b0, char c); +extern int bcatcstr (bstring b, const char * s); +extern int bcatblk (bstring b, const void * s, int len); +extern int binsert (bstring s1, int pos, const_bstring s2, unsigned char fill); +extern int binsertblk (bstring s1, int pos, const void * s2, int len, unsigned char fill); +extern int binsertch (bstring s1, int pos, int len, unsigned char fill); +extern int breplace (bstring b1, int pos, int len, const_bstring b2, unsigned char fill); +extern int bdelete (bstring s1, int pos, int len); +extern int bsetstr (bstring b0, int pos, const_bstring b1, unsigned char fill); +extern int btrunc (bstring b, int n); + +/* Scan/search functions */ +extern int bstricmp (const_bstring b0, const_bstring b1); +extern int bstrnicmp (const_bstring b0, const_bstring b1, int n); +extern int biseqcaseless (const_bstring b0, const_bstring b1); +extern int biseqcaselessblk (const_bstring b, const void * blk, int len); +extern int bisstemeqcaselessblk (const_bstring b0, const void * blk, int len); +extern int biseq (const_bstring b0, const_bstring b1); +extern int biseqblk (const_bstring b, const void * blk, int len); +extern int bisstemeqblk (const_bstring b0, const void * blk, int len); +extern int biseqcstr (const_bstring b, const char * s); +extern int biseqcstrcaseless (const_bstring b, const char * s); +extern int bstrcmp (const_bstring b0, const_bstring b1); +extern int bstrncmp (const_bstring b0, const_bstring b1, int n); +extern int binstr (const_bstring s1, int pos, const_bstring s2); +extern int binstrr (const_bstring s1, int pos, const_bstring s2); +extern int binstrcaseless (const_bstring s1, int pos, const_bstring s2); +extern int binstrrcaseless (const_bstring s1, int pos, const_bstring s2); +extern int bstrchrp (const_bstring b, int c, int pos); +extern int bstrrchrp (const_bstring b, int c, int pos); +#define bstrchr(b,c) bstrchrp ((b), (c), 0) +#define bstrrchr(b,c) bstrrchrp ((b), (c), blength(b)-1) +extern int binchr (const_bstring b0, int pos, const_bstring b1); +extern int binchrr (const_bstring b0, int pos, const_bstring b1); +extern int bninchr (const_bstring b0, int pos, const_bstring b1); +extern int bninchrr (const_bstring b0, int pos, const_bstring b1); +extern int bfindreplace (bstring b, const_bstring find, const_bstring repl, int pos); +extern int bfindreplacecaseless (bstring b, const_bstring find, const_bstring repl, int pos); + +/* List of string container functions */ +struct bstrList { + int qty, mlen; + bstring * entry; +}; +extern struct bstrList * bstrListCreate (void); +extern int bstrListDestroy (struct bstrList * sl); +extern int bstrListAlloc (struct bstrList * sl, int msz); +extern int bstrListAllocMin (struct bstrList * sl, int msz); + +/* String split and join functions */ +extern struct bstrList * bsplit (const_bstring str, unsigned char splitChar); +extern struct bstrList * bsplits (const_bstring str, const_bstring splitStr); +extern struct bstrList * bsplitstr (const_bstring str, const_bstring splitStr); +extern bstring bjoin (const struct bstrList * bl, const_bstring sep); +extern bstring bjoinblk (const struct bstrList * bl, const void * s, int len); +extern int bsplitcb (const_bstring str, unsigned char splitChar, int pos, + int (* cb) (void * parm, int ofs, int len), void * parm); +extern int bsplitscb (const_bstring str, const_bstring splitStr, int pos, + int (* cb) (void * parm, int ofs, int len), void * parm); +extern int bsplitstrcb (const_bstring str, const_bstring splitStr, int pos, + int (* cb) (void * parm, int ofs, int len), void * parm); + +/* Miscellaneous functions */ +extern int bpattern (bstring b, int len); +extern int btoupper (bstring b); +extern int btolower (bstring b); +extern int bltrimws (bstring b); +extern int brtrimws (bstring b); +extern int btrimws (bstring b); + +#if !defined (BSTRLIB_NOVSNP) +extern bstring bformat (const char * fmt, ...); +extern int bformata (bstring b, const char * fmt, ...); +extern int bassignformat (bstring b, const char * fmt, ...); +extern int bvcformata (bstring b, int count, const char * fmt, va_list arglist); + +#define bvformata(ret, b, fmt, lastarg) { \ +bstring bstrtmp_b = (b); \ +const char * bstrtmp_fmt = (fmt); \ +int bstrtmp_r = BSTR_ERR, bstrtmp_sz = 16; \ + for (;;) { \ + va_list bstrtmp_arglist; \ + va_start (bstrtmp_arglist, lastarg); \ + bstrtmp_r = bvcformata (bstrtmp_b, bstrtmp_sz, bstrtmp_fmt, bstrtmp_arglist); \ + va_end (bstrtmp_arglist); \ + if (bstrtmp_r >= 0) { /* Everything went ok */ \ + bstrtmp_r = BSTR_OK; \ + break; \ + } else if (-bstrtmp_r <= bstrtmp_sz) { /* A real error? */ \ + bstrtmp_r = BSTR_ERR; \ + break; \ + } \ + bstrtmp_sz = -bstrtmp_r; /* Doubled or target size */ \ + } \ + ret = bstrtmp_r; \ +} + +#endif + +typedef int (*bNgetc) (void *parm); +typedef size_t (* bNread) (void *buff, size_t elsize, size_t nelem, void *parm); + +/* Input functions */ +extern bstring bgets (bNgetc getcPtr, void * parm, char terminator); +extern bstring bread (bNread readPtr, void * parm); +extern int bgetsa (bstring b, bNgetc getcPtr, void * parm, char terminator); +extern int bassigngets (bstring b, bNgetc getcPtr, void * parm, char terminator); +extern int breada (bstring b, bNread readPtr, void * parm); + +/* Stream functions */ +extern struct bStream * bsopen (bNread readPtr, void * parm); +extern void * bsclose (struct bStream * s); +extern int bsbufflength (struct bStream * s, int sz); +extern int bsreadln (bstring b, struct bStream * s, char terminator); +extern int bsreadlns (bstring r, struct bStream * s, const_bstring term); +extern int bsread (bstring b, struct bStream * s, int n); +extern int bsreadlna (bstring b, struct bStream * s, char terminator); +extern int bsreadlnsa (bstring r, struct bStream * s, const_bstring term); +extern int bsreada (bstring b, struct bStream * s, int n); +extern int bsunread (struct bStream * s, const_bstring b); +extern int bspeek (bstring r, const struct bStream * s); +extern int bssplitscb (struct bStream * s, const_bstring splitStr, + int (* cb) (void * parm, int ofs, const_bstring entry), void * parm); +extern int bssplitstrcb (struct bStream * s, const_bstring splitStr, + int (* cb) (void * parm, int ofs, const_bstring entry), void * parm); +extern int bseof (const struct bStream * s); + +struct tagbstring { + int mlen; + int slen; + unsigned char * data; +}; + +/* Accessor macros */ +#define blengthe(b, e) (((b) == (void *)0 || (b)->slen < 0) ? (int)(e) : ((b)->slen)) +#define blength(b) (blengthe ((b), 0)) +#define bdataofse(b, o, e) (((b) == (void *)0 || (b)->data == (void*)0) ? (char *)(e) : ((char *)(b)->data) + (o)) +#define bdataofs(b, o) (bdataofse ((b), (o), (void *)0)) +#define bdatae(b, e) (bdataofse (b, 0, e)) +#define bdata(b) (bdataofs (b, 0)) +#define bchare(b, p, e) ((((unsigned)(p)) < (unsigned)blength(b)) ? ((b)->data[(p)]) : (e)) +#define bchar(b, p) bchare ((b), (p), '\0') + +/* Static constant string initialization macro */ +#define bsStaticMlen(q,m) {(m), (int) sizeof(q)-1, (unsigned char *) ("" q "")} +#if defined(_MSC_VER) +# define bsStatic(q) bsStaticMlen(q,-32) +#endif +#ifndef bsStatic +# define bsStatic(q) bsStaticMlen(q,-__LINE__) +#endif + +/* Static constant block parameter pair */ +#define bsStaticBlkParms(q) ((void *)("" q "")), ((int) sizeof(q)-1) + +#define bcatStatic(b,s) ((bcatblk)((b), bsStaticBlkParms(s))) +#define bfromStatic(s) ((blk2bstr)(bsStaticBlkParms(s))) +#define bassignStatic(b,s) ((bassignblk)((b), bsStaticBlkParms(s))) +#define binsertStatic(b,p,s,f) ((binsertblk)((b), (p), bsStaticBlkParms(s), (f))) +#define bjoinStatic(b,s) ((bjoinblk)((b), bsStaticBlkParms(s))) +#define biseqStatic(b,s) ((biseqblk)((b), bsStaticBlkParms(s))) +#define bisstemeqStatic(b,s) ((bisstemeqblk)((b), bsStaticBlkParms(s))) +#define biseqcaselessStatic(b,s) ((biseqcaselessblk)((b), bsStaticBlkParms(s))) +#define bisstemeqcaselessStatic(b,s) ((bisstemeqcaselessblk)((b), bsStaticBlkParms(s))) + +/* Reference building macros */ +#define cstr2tbstr btfromcstr +#define btfromcstr(t,s) { \ + (t).data = (unsigned char *) (s); \ + (t).slen = ((t).data) ? ((int) (strlen) ((char *)(t).data)) : 0; \ + (t).mlen = -1; \ +} +#define blk2tbstr(t,s,l) { \ + (t).data = (unsigned char *) (s); \ + (t).slen = l; \ + (t).mlen = -1; \ +} +#define btfromblk(t,s,l) blk2tbstr(t,s,l) +#define bmid2tbstr(t,b,p,l) { \ + const_bstring bstrtmp_s = (b); \ + if (bstrtmp_s && bstrtmp_s->data && bstrtmp_s->slen >= 0) { \ + int bstrtmp_left = (p); \ + int bstrtmp_len = (l); \ + if (bstrtmp_left < 0) { \ + bstrtmp_len += bstrtmp_left; \ + bstrtmp_left = 0; \ + } \ + if (bstrtmp_len > bstrtmp_s->slen - bstrtmp_left) \ + bstrtmp_len = bstrtmp_s->slen - bstrtmp_left; \ + if (bstrtmp_len <= 0) { \ + (t).data = (unsigned char *)""; \ + (t).slen = 0; \ + } else { \ + (t).data = bstrtmp_s->data + bstrtmp_left; \ + (t).slen = bstrtmp_len; \ + } \ + } else { \ + (t).data = (unsigned char *)""; \ + (t).slen = 0; \ + } \ + (t).mlen = -__LINE__; \ +} +#define btfromblkltrimws(t,s,l) { \ + int bstrtmp_idx = 0, bstrtmp_len = (l); \ + unsigned char * bstrtmp_s = (s); \ + if (bstrtmp_s && bstrtmp_len >= 0) { \ + for (; bstrtmp_idx < bstrtmp_len; bstrtmp_idx++) { \ + if (!isspace (bstrtmp_s[bstrtmp_idx])) break; \ + } \ + } \ + (t).data = bstrtmp_s + bstrtmp_idx; \ + (t).slen = bstrtmp_len - bstrtmp_idx; \ + (t).mlen = -__LINE__; \ +} +#define btfromblkrtrimws(t,s,l) { \ + int bstrtmp_len = (l) - 1; \ + unsigned char * bstrtmp_s = (s); \ + if (bstrtmp_s && bstrtmp_len >= 0) { \ + for (; bstrtmp_len >= 0; bstrtmp_len--) { \ + if (!isspace (bstrtmp_s[bstrtmp_len])) break; \ + } \ + } \ + (t).data = bstrtmp_s; \ + (t).slen = bstrtmp_len + 1; \ + (t).mlen = -__LINE__; \ +} +#define btfromblktrimws(t,s,l) { \ + int bstrtmp_idx = 0, bstrtmp_len = (l) - 1; \ + unsigned char * bstrtmp_s = (s); \ + if (bstrtmp_s && bstrtmp_len >= 0) { \ + for (; bstrtmp_idx <= bstrtmp_len; bstrtmp_idx++) { \ + if (!isspace (bstrtmp_s[bstrtmp_idx])) break; \ + } \ + for (; bstrtmp_len >= bstrtmp_idx; bstrtmp_len--) { \ + if (!isspace (bstrtmp_s[bstrtmp_len])) break; \ + } \ + } \ + (t).data = bstrtmp_s + bstrtmp_idx; \ + (t).slen = bstrtmp_len + 1 - bstrtmp_idx; \ + (t).mlen = -__LINE__; \ +} + +/* Write protection macros */ +#define bwriteprotect(t) { if ((t).mlen >= 0) (t).mlen = -1; } +#define bwriteallow(t) { if ((t).mlen == -1) (t).mlen = (t).slen + ((t).slen == 0); } +#define biswriteprotected(t) ((t).mlen <= 0) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/bstrlib/bstrwrap.cpp b/common/bstrlib/bstrwrap.cpp new file mode 100644 index 0000000..2ec38c1 --- /dev/null +++ b/common/bstrlib/bstrwrap.cpp @@ -0,0 +1,1721 @@ +/* + * This source file is part of the bstring string library. This code was + * written by Paul Hsieh in 2002-2015, and is covered by the BSD open source + * license and the GPL. Refer to the accompanying documentation for details + * on usage and license. + */ + +/* + * bstrwrap.c + * + * This file is the C++ wrapper for the bstring functions. + */ + +#if defined (_MSC_VER) +# define _CRT_SECURE_NO_WARNINGS +#endif + +#include +#include +#include +#include +#include +#include "bstrwrap.h" + +#if defined(MEMORY_DEBUG) || defined(BSTRLIB_MEMORY_DEBUG) +#include "memdbg.h" +#endif + +#ifndef bstr__alloc +#define bstr__alloc(x) malloc (x) +#endif + +#ifndef bstr__free +#define bstr__free(p) free (p) +#endif + +#ifndef bstr__realloc +#define bstr__realloc(p,x) realloc ((p), (x)) +#endif + +#ifndef bstr__memcpy +#define bstr__memcpy(d,s,l) memcpy ((d), (s), (l)) +#endif + +#ifndef bstr__memmove +#define bstr__memmove(d,s,l) memmove ((d), (s), (l)) +#endif + +#ifndef bstr__memset +#define bstr__memset(d,c,l) memset ((d), (c), (l)) +#endif + +#ifndef bstr__memcmp +#define bstr__memcmp(d,c,l) memcmp ((d), (c), (l)) +#endif + +#ifndef bstr__memchr +#define bstr__memchr(s,c,l) memchr ((s), (c), (l)) +#endif + +#if defined(BSTRLIB_CAN_USE_IOSTREAM) +#include +#endif + +namespace Bstrlib { + +// Constructors. + +CBString::CBString () { + slen = 0; + mlen = 8; + data = (unsigned char *) bstr__alloc (mlen); + if (!data) { + mlen = 0; + bstringThrow ("Failure in default constructor"); + } else { + data[0] = '\0'; + } +} + +CBString::CBString (const void * blk, int len) { + data = NULL; + if (len >= 0) { + mlen = len + 1; + slen = len; + data = (unsigned char *) bstr__alloc (mlen); + } + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in block constructor"); + } else { + if (slen > 0) bstr__memcpy (data, blk, slen); + data[slen] = '\0'; + } +} + +CBString::CBString (char c, int len) { + data = NULL; + if (len >= 0) { + mlen = len + 1; + slen = len; + data = (unsigned char *) bstr__alloc (mlen); + } + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in repeat(char) constructor"); + } else { + if (slen > 0) bstr__memset (data, c, slen); + data[slen] = '\0'; + } +} + +CBString::CBString (char c) { + mlen = 2; + slen = 1; + if (NULL == (data = (unsigned char *) bstr__alloc (mlen))) { + mlen = slen = 0; + bstringThrow ("Failure in (char) constructor"); + } else { + data[0] = (unsigned char) c; + data[1] = '\0'; + } +} + +CBString::CBString (unsigned char c) { + mlen = 2; + slen = 1; + if (NULL == (data = (unsigned char *) bstr__alloc (mlen))) { + mlen = slen = 0; + bstringThrow ("Failure in (char) constructor"); + } else { + data[0] = c; + data[1] = '\0'; + } +} + +CBString::CBString (const char *s) { + if (s) { + size_t sslen = strlen (s); + if (sslen >= INT_MAX) bstringThrow ("Failure in (char *) constructor, string too large") + slen = (int) sslen; + mlen = slen + 1; + if (NULL != (data = (unsigned char *) bstr__alloc (mlen))) { + bstr__memcpy (data, s, mlen); + return; + } + } + data = NULL; + bstringThrow ("Failure in (char *) constructor"); +} + +CBString::CBString (int len, const char *s) { + if (s) { + size_t sslen = strlen (s); + if (sslen >= INT_MAX) bstringThrow ("Failure in (char *) constructor, string too large") + slen = (int) sslen; + mlen = slen + 1; + if (mlen < len) mlen = len; + if (NULL != (data = (unsigned char *) bstr__alloc (mlen))) { + bstr__memcpy (data, s, slen + 1); + return; + } + } + data = NULL; + bstringThrow ("Failure in (int len, char *) constructor"); +} + +CBString::CBString (const CBString& b) { + slen = b.slen; + mlen = slen + 1; + data = NULL; + if (mlen > 0) data = (unsigned char *) bstr__alloc (mlen); + if (!data) { + bstringThrow ("Failure in (CBString) constructor"); + } else { + bstr__memcpy (data, b.data, slen); + data[slen] = '\0'; + } +} + +CBString::CBString (const tagbstring& x) { + slen = x.slen; + mlen = slen + 1; + data = NULL; + if (slen >= 0 && x.data != NULL) data = (unsigned char *) bstr__alloc (mlen); + if (!data) { + bstringThrow ("Failure in (tagbstring) constructor"); + } else { + bstr__memcpy (data, x.data, slen); + data[slen] = '\0'; + } +} + +// Destructor. + +CBString::~CBString () { + if (data != NULL) { + bstr__free (data); + data = NULL; + } + mlen = 0; + slen = -__LINE__; +} + +// = operator. + +const CBString& CBString::operator = (char c) { + if (mlen <= 0) bstringThrow ("Write protection error"); + if (2 >= mlen) alloc (2); + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in =(char) operator"); + } else { + slen = 1; + data[0] = (unsigned char) c; + data[1] = '\0'; + } + return *this; +} + +const CBString& CBString::operator = (unsigned char c) { + if (mlen <= 0) bstringThrow ("Write protection error"); + if (2 >= mlen) alloc (2); + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in =(char) operator"); + } else { + slen = 1; + data[0] = c; + data[1] = '\0'; + } + return *this; +} + +const CBString& CBString::operator = (const char *s) { +size_t tmpSlen; + + if (mlen <= 0) bstringThrow ("Write protection error"); + if (NULL == s) s = ""; + if ((tmpSlen = strlen (s)) >= (size_t) mlen) { + if (tmpSlen >= INT_MAX-1) bstringThrow ("Failure in =(const char *) operator, string too large"); + alloc ((int) tmpSlen); + } + + if (data) { + slen = (int) tmpSlen; + bstr__memcpy (data, s, tmpSlen + 1); + } else { + mlen = slen = 0; + bstringThrow ("Failure in =(const char *) operator"); + } + return *this; +} + +const CBString& CBString::operator = (const CBString& b) { + if (mlen <= 0) bstringThrow ("Write protection error"); + if (b.slen >= mlen) alloc (b.slen); + + slen = b.slen; + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in =(CBString) operator"); + } else { + bstr__memcpy (data, b.data, slen); + data[slen] = '\0'; + } + return *this; +} + +const CBString& CBString::operator = (const tagbstring& x) { + if (mlen <= 0) bstringThrow ("Write protection error"); + if (x.slen < 0) bstringThrow ("Failure in =(tagbstring) operator, badly formed tagbstring"); + if (x.slen >= mlen) alloc (x.slen); + + slen = x.slen; + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in =(tagbstring) operator"); + } else { + bstr__memcpy (data, x.data, slen); + data[slen] = '\0'; + } + return *this; +} + +const CBString& CBString::operator += (const CBString& b) { + if (BSTR_ERR == bconcat (this, (bstring) &b)) { + bstringThrow ("Failure in concatenate"); + } + return *this; +} + +const CBString& CBString::operator += (const char *s) { + char * d; + int i, l; + + if (mlen <= 0) bstringThrow ("Write protection error"); + + /* Optimistically concatenate directly */ + l = mlen - slen; + d = (char *) &data[slen]; + for (i=0; i < l; i++) { + if ((*d++ = *s++) == '\0') { + slen += i; + return *this; + } + } + slen += i; + + if (BSTR_ERR == bcatcstr (this, s)) { + bstringThrow ("Failure in concatenate"); + } + return *this; +} + +const CBString& CBString::operator += (char c) { + if (BSTR_ERR == bconchar (this, c)) { + bstringThrow ("Failure in concatenate"); + } + return *this; +} + +const CBString& CBString::operator += (unsigned char c) { + if (BSTR_ERR == bconchar (this, (char) c)) { + bstringThrow ("Failure in concatenate"); + } + return *this; +} + +const CBString& CBString::operator += (const tagbstring& x) { + if (mlen <= 0) bstringThrow ("Write protection error"); + if (x.slen < 0) bstringThrow ("Failure in +=(tagbstring) operator, badly formed tagbstring"); + alloc (x.slen + slen + 1); + + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in +=(tagbstring) operator"); + } else { + bstr__memcpy (data + slen, x.data, x.slen); + slen += x.slen; + data[slen] = '\0'; + } + return *this; +} + +const CBString CBString::operator + (char c) const { + CBString retval (*this); + retval += c; + return retval; +} + +const CBString CBString::operator + (unsigned char c) const { + CBString retval (*this); + retval += c; + return retval; +} + +const CBString CBString::operator + (const CBString& b) const { + CBString retval (*this); + retval += b; + return retval; +} + +const CBString CBString::operator + (const char *s) const { + if (s == NULL) bstringThrow ("Failure in + (char *) operator, NULL"); + CBString retval (*this); + retval += s; + return retval; +} + +const CBString CBString::operator + (const unsigned char *s) const { + if (s == NULL) bstringThrow ("Failure in + (unsigned char *) operator, NULL"); + CBString retval (*this); + retval += (const char *) s; + return retval; +} + +const CBString CBString::operator + (const tagbstring& x) const { + if (x.slen < 0) bstringThrow ("Failure in + (tagbstring) operator, badly formed tagbstring"); + CBString retval (*this); + retval += x; + return retval; +} + +bool CBString::operator == (const CBString& b) const { + int retval; + if (BSTR_ERR == (retval = biseq ((bstring)this, (bstring)&b))) { + bstringThrow ("Failure in compare (==)"); + } + return retval > 0; +} + +bool CBString::operator == (const char * s) const { + int retval; + if (NULL == s) { + bstringThrow ("Failure in compare (== NULL)"); + } + if (BSTR_ERR == (retval = biseqcstr ((bstring) this, s))) { + bstringThrow ("Failure in compare (==)"); + } + return retval > 0; +} + +bool CBString::operator == (const unsigned char * s) const { + int retval; + if (NULL == s) { + bstringThrow ("Failure in compare (== NULL)"); + } + if (BSTR_ERR == (retval = biseqcstr ((bstring) this, (const char *) s))) { + bstringThrow ("Failure in compare (==)"); + } + return retval > 0; +} + +bool CBString::operator != (const CBString& b) const { + return ! ((*this) == b); +} + +bool CBString::operator != (const char * s) const { + return ! ((*this) == s); +} + +bool CBString::operator != (const unsigned char * s) const { + return ! ((*this) == s); +} + +bool CBString::operator < (const CBString& b) const { + int retval; + if (SHRT_MIN == (retval = bstrcmp ((bstring) this, (bstring)&b))) { + bstringThrow ("Failure in compare (<)"); + } + return retval < 0; +} + +bool CBString::operator < (const char * s) const { + if (s == NULL) { + bstringThrow ("Failure in compare (<)"); + } + return strcmp ((const char *)this->data, s) < 0; +} + +bool CBString::operator < (const unsigned char * s) const { + if (s == NULL) { + bstringThrow ("Failure in compare (<)"); + } + return strcmp ((const char *)this->data, (const char *)s) < 0; +} + +bool CBString::operator <= (const CBString& b) const { + int retval; + if (SHRT_MIN == (retval = bstrcmp ((bstring) this, (bstring)&b))) { + bstringThrow ("Failure in compare (<=)"); + } + return retval <= 0; +} + +bool CBString::operator <= (const char * s) const { + if (s == NULL) { + bstringThrow ("Failure in compare (<=)"); + } + return strcmp ((const char *)this->data, s) <= 0; +} + +bool CBString::operator <= (const unsigned char * s) const { + if (s == NULL) { + bstringThrow ("Failure in compare (<=)"); + } + return strcmp ((const char *)this->data, (const char *)s) <= 0; +} + +bool CBString::operator > (const CBString& b) const { + return ! ((*this) <= b); +} + +bool CBString::operator > (const char * s) const { + return ! ((*this) <= s); +} + +bool CBString::operator > (const unsigned char * s) const { + return ! ((*this) <= s); +} + +bool CBString::operator >= (const CBString& b) const { + return ! ((*this) < b); +} + +bool CBString::operator >= (const char * s) const { + return ! ((*this) < s); +} + +bool CBString::operator >= (const unsigned char * s) const { + return ! ((*this) < s); +} + +CBString::operator double () const { +double d = 0; + if (1 != sscanf ((const char *)this->data, "%lf", &d)) { + bstringThrow ("Unable to convert to a double"); + } + return d; +} + +CBString::operator float () const { +float d = 0; + if (1 != sscanf ((const char *)this->data, "%f", &d)) { + bstringThrow ("Unable to convert to a float"); + } + return d; +} + +CBString::operator int () const { +int d = 0; + if (1 != sscanf ((const char *)this->data, "%d", &d)) { + bstringThrow ("Unable to convert to an int"); + } + return d; +} + +CBString::operator unsigned int () const { +unsigned int d = 0; + if (1 != sscanf ((const char *)this->data, "%u", &d)) { + bstringThrow ("Unable to convert to an unsigned int"); + } + return d; +} + +#ifdef __TURBOC__ +# ifndef BSTRLIB_NOVSNP +# define BSTRLIB_NOVSNP +# endif +#endif + +/* Give WATCOM C/C++, MSVC some latitude for their non-support of vsnprintf */ +#if defined(__WATCOMC__) || defined(_MSC_VER) +#define exvsnprintf(r,b,n,f,a) {r = _vsnprintf (b,n,f,a);} +#else +#ifdef BSTRLIB_NOVSNP +/* This is just a hack. If you are using a system without a vsnprintf, it is + not recommended that bformat be used at all. */ +#define exvsnprintf(r,b,n,f,a) {vsprintf (b,f,a); r = -1;} +#define START_VSNBUFF (256) +#else + +#if defined (__GNUC__) && !defined (__PPC__) +/* Something is making gcc complain about this prototype not being here, so + I've just gone ahead and put it in. */ +extern "C" { +extern int vsnprintf (char *buf, size_t count, const char *format, va_list arg); +} +#endif + +#define exvsnprintf(r,b,n,f,a) {r = vsnprintf (b,n,f,a);} +#endif +#endif + +#ifndef START_VSNBUFF +#define START_VSNBUFF (16) +#endif + +/* + * Yeah I'd like to just call a vformat function or something, but because of + * the ANSI specified brokeness of the va_* macros, it is actually not + * possible to do this correctly. + */ + +void CBString::format (const char * fmt, ...) { + bstring b; + va_list arglist; + int r, n; + + if (mlen <= 0) bstringThrow ("Write protection error"); + if (fmt == NULL) { + *this = ""; + bstringThrow ("CBString::format (NULL, ...) is erroneous."); + } else { + + if ((b = bfromcstr ("")) == NULL) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::format out of memory."); +#else + *this = ""; +#endif + } else { + if ((n = (int) (2 * (strlen) (fmt))) < START_VSNBUFF) n = START_VSNBUFF; + for (;;) { + if (BSTR_OK != balloc (b, n + 2)) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::format out of memory."); +#else + b = bformat (""); + break; +#endif + } + + va_start (arglist, fmt); + exvsnprintf (r, (char *) b->data, n + 1, fmt, arglist); + va_end (arglist); + + b->data[n] = '\0'; + b->slen = (int) (strlen) ((char *) b->data); + + if (b->slen < n) break; + if (r > n) n = r; else n += n; + } + *this = *b; + bdestroy (b); + } + } +} + +void CBString::formata (const char * fmt, ...) { + bstring b; + va_list arglist; + int r, n; + + if (mlen <= 0) bstringThrow ("Write protection error"); + if (fmt == NULL) { + *this += ""; + bstringThrow ("CBString::formata (NULL, ...) is erroneous."); + } else { + + if ((b = bfromcstr ("")) == NULL) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::format out of memory."); +#else + *this += ""; +#endif + } else { + if ((n = (int) (2 * (strlen) (fmt))) < START_VSNBUFF) n = START_VSNBUFF; + for (;;) { + if (BSTR_OK != balloc (b, n + 2)) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::format out of memory."); +#else + b = bformat (""); + break; +#endif + } + + va_start (arglist, fmt); + exvsnprintf (r, (char *) b->data, n + 1, fmt, arglist); + va_end (arglist); + + b->data[n] = '\0'; + b->slen = (int) (strlen) ((char *) b->data); + + if (b->slen < n) break; + if (r > n) n = r; else n += n; + } + *this += *b; + bdestroy (b); + } + } +} + +int CBString::caselessEqual (const CBString& b) const { +int ret; + if (BSTR_ERR == (ret = biseqcaseless ((bstring) this, (bstring) &b))) { + bstringThrow ("CBString::caselessEqual Unable to compare"); + } + return ret; +} + +int CBString::caselessCmp (const CBString& b) const { +int ret; + if (SHRT_MIN == (ret = bstricmp ((bstring) this, (bstring) &b))) { + bstringThrow ("CBString::caselessCmp Unable to compare"); + } + return ret; +} + +int CBString::find (const CBString& b, int pos) const { + return binstr ((bstring) this, pos, (bstring) &b); +} + +/* + int CBString::find (const char * b, int pos) const; + + Uses and unrolling and sliding paired indexes character matching. Since + the unrolling is the primary real world impact the true purpose of this + algorithm choice is maximize the effectiveness of the unrolling. The + idea is to scan until at least one match of the current indexed character + from each string, and then shift indexes of both down by and repeat until + the last character form b matches. When the last character from b + matches if the were no mismatches in previous strlen(b) characters then + we know we have a full match, otherwise shift both indexes back strlen(b) + characters and continue. + + In general, if there is any character in b that is not at all in this + CBString, then this algorithm is O(slen). The algorithm does not easily + degenerate into O(slen * strlen(b)) performance except in very uncommon + situations. Thus from a real world perspective, the overhead of + precomputing suffix shifts in the Boyer-Moore algorithm is avoided, while + delivering an unrolled matching inner loop most of the time. + */ + +int CBString::find (const char * b, int pos) const { +int ii, j; +unsigned char c0; +register int i, l; +register unsigned char cx; +register unsigned char * pdata; + + if (NULL == b) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::find NULL."); +#else + return BSTR_ERR; +#endif + } + + if ((unsigned int) pos > (unsigned int) slen) return BSTR_ERR; + if ('\0' == b[0]) return pos; + if (pos == slen) return BSTR_ERR; + if ('\0' == b[1]) return find (b[0], pos); + + cx = c0 = (unsigned char) b[0]; + l = slen - 1; + + pdata = data; + for (ii = -1, i = pos, j = 0; i < l;) { + /* Unrolled current character test */ + if (cx != pdata[i]) { + if (cx != pdata[1+i]) { + i += 2; + continue; + } + i++; + } + + /* Take note if this is the start of a potential match */ + if (0 == j) ii = i; + + /* Shift the test character down by one */ + j++; + i++; + + /* If this isn't past the last character continue */ + if ('\0' != (cx = b[j])) continue; + + N0:; + + /* If no characters mismatched, then we matched */ + if (i == ii+j) return ii; + + /* Shift back to the beginning */ + i -= j; + j = 0; + cx = c0; + } + + /* Deal with last case if unrolling caused a misalignment */ + if (i == l && cx == pdata[i] && '\0' == b[j+1]) goto N0; + + return BSTR_ERR; +} + +int CBString::caselessfind (const CBString& b, int pos) const { + return binstrcaseless ((bstring) this, pos, (bstring) &b); +} + +int CBString::caselessfind (const char * b, int pos) const { +struct tagbstring t; + + if (NULL == b) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::caselessfind NULL."); +#else + return BSTR_ERR; +#endif + } + + if ((unsigned int) pos > (unsigned int) slen) return BSTR_ERR; + if ('\0' == b[0]) return pos; + if (pos == slen) return BSTR_ERR; + + btfromcstr (t, b); + return binstrcaseless ((bstring) this, pos, (bstring) &t); +} + +int CBString::find (char c, int pos) const { + if (pos < 0) return BSTR_ERR; + for (;pos < slen; pos++) { + if (data[pos] == (unsigned char) c) return pos; + } + return BSTR_ERR; +} + +int CBString::reversefind (const CBString& b, int pos) const { + return binstrr ((bstring) this, pos, (bstring) &b); +} + +int CBString::reversefind (const char * b, int pos) const { +struct tagbstring t; + if (NULL == b) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::reversefind NULL."); +#else + return BSTR_ERR; +#endif + } + cstr2tbstr (t, b); + return binstrr ((bstring) this, pos, &t); +} + +int CBString::caselessreversefind (const CBString& b, int pos) const { + return binstrrcaseless ((bstring) this, pos, (bstring) &b); +} + +int CBString::caselessreversefind (const char * b, int pos) const { +struct tagbstring t; + + if (NULL == b) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::caselessreversefind NULL."); +#else + return BSTR_ERR; +#endif + } + + if ((unsigned int) pos > (unsigned int) slen) return BSTR_ERR; + if ('\0' == b[0]) return pos; + if (pos == slen) return BSTR_ERR; + + btfromcstr (t, b); + return binstrrcaseless ((bstring) this, pos, (bstring) &t); +} + +int CBString::reversefind (char c, int pos) const { + if (pos > slen) return BSTR_ERR; + if (pos == slen) pos--; + for (;pos >= 0; pos--) { + if (data[pos] == (unsigned char) c) return pos; + } + return BSTR_ERR; +} + +int CBString::findchr (const CBString& b, int pos) const { + return binchr ((bstring) this, pos, (bstring) &b); +} + +int CBString::findchr (const char * s, int pos) const { +struct tagbstring t; + if (NULL == s) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::findchr NULL."); +#else + return BSTR_ERR; +#endif + } + cstr2tbstr (t, s); + return binchr ((bstring) this, pos, (bstring) &t); +} + +int CBString::nfindchr (const CBString& b, int pos) const { + return bninchr ((bstring) this, pos, (bstring) &b); +} + +int CBString::nfindchr (const char * s, int pos) const { +struct tagbstring t; + if (NULL == s) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::nfindchr NULL."); +#else + return BSTR_ERR; +#endif + } + cstr2tbstr (t, s); + return bninchr ((bstring) this, pos, &t); +} + +int CBString::reversefindchr (const CBString& b, int pos) const { + return binchrr ((bstring) this, pos, (bstring) &b); +} + +int CBString::reversefindchr (const char * s, int pos) const { +struct tagbstring t; + if (NULL == s) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::reversefindchr NULL."); +#else + return BSTR_ERR; +#endif + } + cstr2tbstr (t, s); + return binchrr ((bstring) this, pos, &t); +} + +int CBString::nreversefindchr (const CBString& b, int pos) const { + return bninchrr ((bstring) this, pos, (bstring) &b); +} + +int CBString::nreversefindchr (const char * s, int pos) const { +struct tagbstring t; + if (NULL == s) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("CBString::nreversefindchr NULL."); +#else + return BSTR_ERR; +#endif + } + cstr2tbstr (t, s); + return bninchrr ((bstring) this, pos, &t); +} + +CBString CBString::midstr (int left, int len) const { +struct tagbstring t; + if (left < 0) { + len += left; + left = 0; + } + if (len > slen - left) len = slen - left; + if (len <= 0) return CBString (""); + blk2tbstr (t, data + left, len); + return CBString (t); +} + +void CBString::alloc (int len) { + if (BSTR_ERR == balloc ((bstring)this, len)) { + bstringThrow ("Failure in alloc"); + } +} + +void CBString::fill (int len, unsigned char cfill) { + slen = 0; + if (BSTR_ERR == bsetstr (this, len, NULL, cfill)) { + bstringThrow ("Failure in fill"); + } +} + +void CBString::setsubstr (int pos, const CBString& b, unsigned char cfill) { + if (BSTR_ERR == bsetstr (this, pos, (bstring) &b, cfill)) { + bstringThrow ("Failure in setsubstr"); + } +} + +void CBString::setsubstr (int pos, const char * s, unsigned char cfill) { +struct tagbstring t; + if (NULL == s) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("setsubstr NULL."); +#else + return; +#endif + } + cstr2tbstr (t, s); + if (BSTR_ERR == bsetstr (this, pos, &t, cfill)) { + bstringThrow ("Failure in setsubstr"); + } +} + +void CBString::insert (int pos, const CBString& b, unsigned char cfill) { + if (BSTR_ERR == binsert (this, pos, (bstring) &b, cfill)) { + bstringThrow ("Failure in insert"); + } +} + +void CBString::insert (int pos, const char * s, unsigned char cfill) { +struct tagbstring t; + if (NULL == s) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("insert NULL."); +#else + return; +#endif + } + cstr2tbstr (t, s); + if (BSTR_ERR == binsert (this, pos, &t, cfill)) { + bstringThrow ("Failure in insert"); + } +} + +void CBString::insertchrs (int pos, int len, unsigned char cfill) { + if (BSTR_ERR == binsertch (this, pos, len, cfill)) { + bstringThrow ("Failure in insertchrs"); + } +} + +void CBString::replace (int pos, int len, const CBString& b, unsigned char cfill) { + if (BSTR_ERR == breplace (this, pos, len, (bstring) &b, cfill)) { + bstringThrow ("Failure in replace"); + } +} + +void CBString::replace (int pos, int len, const char * s, unsigned char cfill) { +struct tagbstring t; +size_t q; + + if (mlen <= 0) bstringThrow ("Write protection error"); + if (NULL == s || (pos|len) < 0) { + bstringThrow ("Failure in replace"); + } else { + if (pos + len >= slen) { + cstr2tbstr (t, s); + if (BSTR_ERR == bsetstr (this, pos, &t, cfill)) { + bstringThrow ("Failure in replace"); + } else if (pos + t.slen < slen) { + slen = pos + t.slen; + data[slen] = '\0'; + } + } else { + + /* Aliasing case */ + if ((unsigned int) (data - (unsigned char *) s) < (unsigned int) slen) { + replace (pos, len, CBString(s), cfill); + return; + } + + if ((q = strlen (s)) > (size_t) len || len < 0) { + if (slen + q - len >= INT_MAX) bstringThrow ("Failure in replace, result too long."); + alloc ((int) (slen + q - len)); + if (NULL == data) return; + } + if ((int) q != len) bstr__memmove (data + pos + q, data + pos + len, slen - (pos + len)); + bstr__memcpy (data + pos, s, q); + slen += ((int) q) - len; + data[slen] = '\0'; + } + } +} + +void CBString::findreplace (const CBString& sfind, const CBString& repl, int pos) { + if (BSTR_ERR == bfindreplace (this, (bstring) &sfind, (bstring) &repl, pos)) { + bstringThrow ("Failure in findreplace"); + } +} + +void CBString::findreplace (const CBString& sfind, const char * repl, int pos) { +struct tagbstring t; + if (NULL == repl) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("findreplace NULL."); +#else + return; +#endif + } + cstr2tbstr (t, repl); + if (BSTR_ERR == bfindreplace (this, (bstring) &sfind, (bstring) &t, pos)) { + bstringThrow ("Failure in findreplace"); + } +} + +void CBString::findreplace (const char * sfind, const CBString& repl, int pos) { +struct tagbstring t; + if (NULL == sfind) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("findreplace NULL."); +#else + return; +#endif + } + cstr2tbstr (t, sfind); + if (BSTR_ERR == bfindreplace (this, (bstring) &t, (bstring) &repl, pos)) { + bstringThrow ("Failure in findreplace"); + } +} + +void CBString::findreplace (const char * sfind, const char * repl, int pos) { +struct tagbstring t, u; + if (NULL == repl || NULL == sfind) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("findreplace NULL."); +#else + return; +#endif + } + cstr2tbstr (t, sfind); + cstr2tbstr (u, repl); + if (BSTR_ERR == bfindreplace (this, (bstring) &t, (bstring) &u, pos)) { + bstringThrow ("Failure in findreplace"); + } +} + +void CBString::findreplacecaseless (const CBString& sfind, const CBString& repl, int pos) { + if (BSTR_ERR == bfindreplacecaseless (this, (bstring) &sfind, (bstring) &repl, pos)) { + bstringThrow ("Failure in findreplacecaseless"); + } +} + +void CBString::findreplacecaseless (const CBString& sfind, const char * repl, int pos) { +struct tagbstring t; + if (NULL == repl) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("findreplacecaseless NULL."); +#else + return; +#endif + } + cstr2tbstr (t, repl); + if (BSTR_ERR == bfindreplacecaseless (this, (bstring) &sfind, (bstring) &t, pos)) { + bstringThrow ("Failure in findreplacecaseless"); + } +} + +void CBString::findreplacecaseless (const char * sfind, const CBString& repl, int pos) { +struct tagbstring t; + if (NULL == sfind) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("findreplacecaseless NULL."); +#else + return; +#endif + } + cstr2tbstr (t, sfind); + if (BSTR_ERR == bfindreplacecaseless (this, (bstring) &t, (bstring) &repl, pos)) { + bstringThrow ("Failure in findreplacecaseless"); + } +} + +void CBString::findreplacecaseless (const char * sfind, const char * repl, int pos) { +struct tagbstring t, u; + if (NULL == repl || NULL == sfind) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("findreplacecaseless NULL."); +#else + return; +#endif + } + cstr2tbstr (t, sfind); + cstr2tbstr (u, repl); + if (BSTR_ERR == bfindreplacecaseless (this, (bstring) &t, (bstring) &u, pos)) { + bstringThrow ("Failure in findreplacecaseless"); + } +} + +void CBString::remove (int pos, int len) { + if (BSTR_ERR == bdelete (this, pos, len)) { + bstringThrow ("Failure in remove"); + } +} + +void CBString::trunc (int len) { + if (len < 0) { + bstringThrow ("Failure in trunc"); + } + if (len < slen) { + slen = len; + data[len] = '\0'; + } +} + +void CBString::ltrim (const CBString& b) { + int l = nfindchr (b, 0); + if (l == BSTR_ERR) l = slen; + remove (0, l); +} + +void CBString::rtrim (const CBString& b) { + int l = nreversefindchr (b, slen - 1); +#if BSTR_ERR != -1 + if (l == BSTR_ERR) l = -1; +#endif + slen = l + 1; + if (mlen > slen) data[slen] = '\0'; +} + +void CBString::toupper () { + if (BSTR_ERR == btoupper ((bstring) this)) { + bstringThrow ("Failure in toupper"); + } +} + +void CBString::tolower () { + if (BSTR_ERR == btolower ((bstring) this)) { + bstringThrow ("Failure in tolower"); + } +} + +void CBString::repeat (int count) { + count *= slen; + if (count == 0) { + trunc (0); + return; + } + if (count < 0 || BSTR_ERR == bpattern (this, count)) { + bstringThrow ("Failure in repeat"); + } +} + +int CBString::gets (bNgetc getcPtr, void * parm, char terminator) { + if (mlen <= 0) bstringThrow ("Write protection error"); + bstring b = bgets (getcPtr, parm, terminator); + if (b == NULL) { + slen = 0; + return -1; + } + *this = *b; + bdestroy (b); + return 0; +} + +int CBString::read (bNread readPtr, void * parm) { + if (mlen <= 0) bstringThrow ("Write protection error"); + bstring b = bread (readPtr, parm); + if (b == NULL) { + slen = 0; + return -1; + } + *this = *b; + bdestroy (b); + return 0; +} + +const CBString operator + (const char *a, const CBString& b) { + return CBString(a) + b; +} + +const CBString operator + (const unsigned char *a, const CBString& b) { + return CBString((const char *)a) + b; +} + +const CBString operator + (char c, const CBString& b) { + return CBString(c) + b; +} + +const CBString operator + (unsigned char c, const CBString& b) { + return CBString(c) + b; +} + +const CBString operator + (const tagbstring& x, const CBString& b) { + return CBString(x) + b; +} + +void CBString::writeprotect () { + if (mlen >= 0) mlen = -1; +} + +void CBString::writeallow () { + if (mlen == -1) mlen = slen + (slen == 0); + else if (mlen < 0) { + bstringThrow ("Cannot unprotect a constant"); + } +} + +#if defined(BSTRLIB_CAN_USE_STL) + +// Constructors. + +CBString::CBString (const CBStringList& l) { +int c; +size_t i; + + for (c=1, i=0; i < l.size(); i++) { + c += l.at(i).slen; + } + + mlen = c; + slen = 0; + data = (unsigned char *) bstr__alloc (c); + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in (CBStringList) constructor"); + } else { + for (i=0; i < l.size(); i++) { + *this += l.at(i); + } + } +} + +CBString::CBString (const struct CBStringList& l, const CBString& sep) { +int c, sl = sep.length (); +size_t i; + + for (c=1, i=0; i < l.size(); i++) { + c += l.at(i).slen + sl; + } + + mlen = c; + slen = 0; + data = (unsigned char *) bstr__alloc (mlen); + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in (CBStringList) constructor"); + } else { + for (i=0; i < l.size(); i++) { + if (i > 0) *this += sep; + *this += l.at(i); + } + } +} + +CBString::CBString (const struct CBStringList& l, char sep) { +int c; +size_t i; + + for (c=1, i=0; i < l.size(); i++) { + c += l.at(i).slen + 1; + } + + mlen = c; + slen = 0; + data = (unsigned char *) bstr__alloc (mlen); + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in (CBStringList) constructor"); + } else { + for (i=0; i < l.size(); i++) { + if (i > 0) *this += sep; + *this += l.at(i); + } + } +} + +CBString::CBString (const struct CBStringList& l, unsigned char sep) { +int c; +size_t i; + + for (c=1, i=0; i < l.size(); i++) { + c += l.at(i).slen + 1; + } + + mlen = c; + slen = 0; + data = (unsigned char *) bstr__alloc (mlen); + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in (CBStringList) constructor"); + } else { + for (i=0; i < l.size(); i++) { + if (i > 0) *this += sep; + *this += l.at(i); + } + } +} + +void CBString::join (const struct CBStringList& l) { +int c; +size_t i; + + if (mlen <= 0) { + bstringThrow ("Write protection error"); + } + + for (c=1, i=0; i < l.size(); i++) { + c += l.at(i).slen; + if (c < 0) bstringThrow ("Failure in (CBStringList) constructor, too long"); + } + + alloc (c); + slen = 0; + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in (CBStringList) constructor"); + } else { + for (i=0; i < l.size(); i++) { + *this += l.at(i); + } + } +} + +void CBString::join (const struct CBStringList& l, const CBString& sep) { +int c, sl = sep.length(); +size_t i; + + if (mlen <= 0) { + bstringThrow ("Write protection error"); + } + + for (c=1, i=0; i < l.size(); i++) { + c += l.at(i).slen + sl; + if (c < sl) bstringThrow ("Failure in (CBStringList) constructor, too long"); + } + + alloc (c); + slen = 0; + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in (CBStringList) constructor"); + } else { + for (i=0; i < l.size(); i++) { + if (i > 0) *this += sep; + *this += l.at(i); + } + } +} + + +void CBString::join (const struct CBStringList& l, char sep) { +int c; +size_t i; + + if (mlen <= 0) { + bstringThrow ("Write protection error"); + } + + for (c=1, i=0; i < l.size(); i++) { + c += l.at(i).slen + 1; + if (c <= 0) bstringThrow ("Failure in (CBStringList) constructor, too long"); + } + + alloc (c); + slen = 0; + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in (CBStringList) constructor"); + } else { + for (i=0; i < l.size(); i++) { + if (i > 0) *this += sep; + *this += l.at(i); + } + } +} + +void CBString::join (const struct CBStringList& l, unsigned char sep) { +int c; +size_t i; + + if (mlen <= 0) { + bstringThrow ("Write protection error"); + } + + for (c=1, i=0; i < l.size(); i++) { + c += l.at(i).slen + 1; + if (c <= 0) bstringThrow ("Failure in (CBStringList) constructor, too long"); + } + + alloc (c); + slen = 0; + if (!data) { + mlen = slen = 0; + bstringThrow ("Failure in (CBStringList) constructor"); + } else { + for (i=0; i < l.size(); i++) { + if (i > 0) *this += sep; + *this += l.at(i); + } + } +} + +// Split functions. + +void CBStringList::split (const CBString& b, unsigned char splitChar) { +int p, i; + + p = 0; + do { + for (i = p; i < b.length (); i++) { + if (b.character (i) == splitChar) break; + } + if (i >= p) this->push_back (CBString (&(b.data[p]), i - p)); + p = i + 1; + } while (p <= b.length ()); +} + +void CBStringList::split (const CBString& b, const CBString& s) { +struct { unsigned long content[(1 << CHAR_BIT) / 32]; } chrs; +unsigned char c; +int p, i; + + if (s.length() == 0) bstringThrow ("Null splitstring failure"); + if (s.length() == 1) { + this->split (b, s.character (0)); + } else { + + for (i=0; i < ((1 << CHAR_BIT) / 32); i++) chrs.content[i] = 0x0; + for (i=0; i < s.length(); i++) { + c = s.character (i); + chrs.content[c >> 5] |= ((long)1) << (c & 31); + } + + p = 0; + do { + for (i = p; i < b.length (); i++) { + c = b.character (i); + if (chrs.content[c >> 5] & ((long)1) << (c & 31)) break; + } + if (i >= p) this->push_back (CBString (&(b.data[p]), i - p)); + p = i + 1; + } while (p <= b.length ()); + } +} + +void CBStringList::splitstr (const CBString& b, const CBString& s) { +int p, i; + + if (s.length() == 1) { + this->split (b, s.character (0)); + } else if (s.length() == 0) { + for (i=0; i < b.length (); i++) { + this->push_back (CBString (b.data[i])); + } + } else { + for (p=0; (i = b.find (s, p)) >= 0; p = i + s.length ()) { + this->push_back (b.midstr (p, i - p)); + } + if (p <= b.length ()) { + this->push_back (b.midstr (p, b.length () - p)); + } + } +} + +static int streamSplitCb (void * parm, int ofs, const_bstring entry) { +CBStringList * r = (CBStringList *) parm; + + ofs = ofs; + r->push_back (CBString (*entry)); + return 0; +} + +void CBStringList::split (const CBStream& b, const CBString& s) { + if (0 > bssplitscb (b.m_s, (bstring) &s, streamSplitCb, + (void *) this)) { + bstringThrow ("Split bstream failure"); + } +} + +void CBStringList::split (const CBStream& b, unsigned char splitChar) { +CBString sc (splitChar); + if (0 > bssplitscb (b.m_s, (bstring) &sc, + streamSplitCb, (void *) this)) { + bstringThrow ("Split bstream failure"); + } +} + +void CBStringList::splitstr (const CBStream& b, const CBString& s) { + if (0 > bssplitstrcb (b.m_s, (bstring) &s, streamSplitCb, + (void *) this)) { + bstringThrow ("Split bstream failure"); + } +} + +#endif + +#if defined(BSTRLIB_CAN_USE_IOSTREAM) + +std::ostream& operator << (std::ostream& sout, CBString b) { + return sout.write ((const char *)b, b.length()); +} + +#include + +static int istreamGets (void * parm) { + char c = '\n'; + ((std::istream *)parm)->get(c); + if (isspace (c)) c = '\n'; + return c; +} + +std::istream& operator >> (std::istream& sin, CBString& b) { + do { + b.gets ((bNgetc) istreamGets, &sin, '\n'); + if (b.slen > 0 && b.data[b.slen-1] == '\n') b.slen--; + } while (b.slen == 0 && !sin.eof ()); + return sin; +} + +struct sgetc { + std::istream * sin; + char terminator; +}; + +static int istreamGetc (void * parm) { + char c = ((struct sgetc *)parm)->terminator; + ((struct sgetc *)parm)->sin->get(c); + return c; +} + +std::istream& getline (std::istream& sin, CBString& b, char terminator) { +struct sgetc parm; + parm.sin = &sin; + parm.terminator = terminator; + b.gets ((bNgetc) istreamGetc, &parm, terminator); + if (b.slen > 0 && b.data[b.slen-1] == terminator) b.slen--; + return sin; +} + +#endif + +CBStream::CBStream (bNread readPtr, void * parm) { + m_s = bsopen (readPtr, parm); +} + +CBStream::~CBStream () { + bsclose (m_s); +} + +int CBStream::buffLengthSet (int sz) { + if (sz <= 0) { + bstringThrow ("buffLengthSet parameter failure"); + } + return bsbufflength (m_s, sz); +} + +int CBStream::buffLengthGet () { + return bsbufflength (m_s, 0); +} + +CBString CBStream::readLine (char terminator) { + CBString ret(""); + if (0 > bsreadln ((bstring) &ret, m_s, terminator) && eof () < 0) { + bstringThrow ("Failed readLine"); + } + return ret; +} + +CBString CBStream::readLine (const CBString& terminator) { + CBString ret(""); + if (0 > bsreadlns ((bstring) &ret, m_s, (bstring) &terminator) && eof () < 0) { + bstringThrow ("Failed readLine"); + } + return ret; +} + +void CBStream::readLine (CBString& s, char terminator) { + if (0 > bsreadln ((bstring) &s, m_s, terminator) && eof () < 0) { + bstringThrow ("Failed readLine"); + } +} + +void CBStream::readLine (CBString& s, const CBString& terminator) { + if (0 > bsreadlns ((bstring) &s, m_s, (bstring) &terminator) && eof () < 0) { + bstringThrow ("Failed readLine"); + } +} + +void CBStream::readLineAppend (CBString& s, char terminator) { + if (0 > bsreadlna ((bstring) &s, m_s, terminator) && eof () < 0) { + bstringThrow ("Failed readLineAppend"); + } +} + +void CBStream::readLineAppend (CBString& s, const CBString& terminator) { + if (0 > bsreadlnsa ((bstring) &s, m_s, (bstring) &terminator) && eof () < 0) { + bstringThrow ("Failed readLineAppend"); + } +} + +#define BS_BUFF_SZ (1024) + +CBString CBStream::read () { + CBString ret(""); + while (!bseof (m_s)) { + if (0 > bsreada ((bstring) &ret, m_s, BS_BUFF_SZ) && eof () < 0) { + bstringThrow ("Failed read"); + } + } + return ret; +} + +CBString& CBStream::operator >> (CBString& s) { + while (!bseof (m_s)) { + if (0 > bsreada ((bstring) &s, m_s, BS_BUFF_SZ) && eof () < 0) { + bstringThrow ("Failed read"); + } + } + return s; +} + +CBString CBStream::read (int n) { + CBString ret(""); + if (0 > bsread ((bstring) &ret, m_s, n) && eof () < 0) { + bstringThrow ("Failed read"); + } + return ret; +} + +void CBStream::read (CBString& s) { + s.slen = 0; + while (!bseof (m_s)) { + if (0 > bsreada ((bstring) &s, m_s, BS_BUFF_SZ)) { + bstringThrow ("Failed read"); + } + } +} + +void CBStream::read (CBString& s, int n) { + if (0 > bsread ((bstring) &s, m_s, n)) { + bstringThrow ("Failed read"); + } +} + +void CBStream::readAppend (CBString& s) { + while (!bseof (m_s)) { + if (0 > bsreada ((bstring) &s, m_s, BS_BUFF_SZ)) { + bstringThrow ("Failed readAppend"); + } + } +} + +void CBStream::readAppend (CBString& s, int n) { + if (0 > bsreada ((bstring) &s, m_s, n)) { + bstringThrow ("Failed readAppend"); + } +} + +void CBStream::unread (const CBString& s) { + if (0 > bsunread (m_s, (bstring) &s)) { + bstringThrow ("Failed unread"); + } +} + +CBString CBStream::peek () const { + CBString ret (""); + if (0 > bspeek ((bstring) &ret, m_s)) { + bstringThrow ("Failed peek"); + } + return ret; +} + +void CBStream::peek (CBString& s) const { + s.slen = 0; + if (0 > bspeek ((bstring) &s, m_s)) { + bstringThrow ("Failed peek"); + } +} + +void CBStream::peekAppend (CBString& s) const { + if (0 > bspeek ((bstring) &s, m_s)) { + bstringThrow ("Failed peekAppend"); + } +} + +int CBStream::eof () const { + int ret = bseof (m_s); + if (0 > ret) { + bstringThrow ("Failed eof"); + } + return ret; +} + +} // namespace Bstrlib diff --git a/common/bstrlib/bstrwrap.h b/common/bstrlib/bstrwrap.h new file mode 100644 index 0000000..e672d4d --- /dev/null +++ b/common/bstrlib/bstrwrap.h @@ -0,0 +1,449 @@ +/* + * This source file is part of the bstring string library. This code was + * written by Paul Hsieh in 2002-2015, and is covered by the BSD open source + * license and the GPL. Refer to the accompanying documentation for details + * on usage and license. + */ + +/* + * bstrwrap.h + * + * This file is the C++ wrapper for the bstring functions. + */ + +#ifndef BSTRWRAP_INCLUDE +#define BSTRWRAP_INCLUDE + +/////////////////// Configuration defines ////////////////////////////// + +// WATCOM C/C++ has broken STL and std::iostream support. If you have +// ported over STLport, then you can #define BSTRLIB_CAN_USE_STL to use +// the CBStringList class. +#if defined(__WATCOMC__) +# if !defined (BSTRLIB_CAN_USE_STL) && !defined (BSTRLIB_CANNOT_USE_STL) +# define BSTRLIB_CANNOT_USE_STL +# endif +# if !defined (BSTRLIB_CAN_USE_IOSTREAM) && !defined (BSTRLIB_CANNOT_USE_IOSTREAM) +# define BSTRLIB_CANNOT_USE_IOSTREAM +# endif +#endif + +// By default it assumed that STL has been installed and works for your +// compiler. If this is not the case, then #define BSTRLIB_CANNOT_USE_STL +#if !defined (BSTRLIB_CANNOT_USE_STL) && !defined (BSTRLIB_CAN_USE_STL) +#define BSTRLIB_CAN_USE_STL +#endif + +// By default it assumed that std::iostream works well with your compiler. +// If this is not the case, then #define BSTRLIB_CAN_USE_IOSTREAM +#if !defined (BSTRLIB_CANNOT_USE_IOSTREAM) && !defined (BSTRLIB_CAN_USE_IOSTREAM) +#define BSTRLIB_CAN_USE_IOSTREAM +#endif + +// By default it is assumed that your compiler can deal with and has enabled +// exception handlling. If this is not the case then you will need to +// #define BSTRLIB_DOESNT_THROW_EXCEPTIONS +#if !defined (BSTRLIB_THROWS_EXCEPTIONS) && !defined (BSTRLIB_DOESNT_THROW_EXCEPTIONS) +#define BSTRLIB_THROWS_EXCEPTIONS +#endif + +//////////////////////////////////////////////////////////////////////// + +#include +#include "bstrlib.h" +#include "../ubytearray.h" + +#ifdef __cplusplus + +#if defined(BSTRLIB_CAN_USE_STL) + +#if defined(__WATCOMC__) +#pragma warning 604 10 +#pragma warning 595 10 +#pragma warning 594 10 +#pragma warning 549 10 +#endif + +#include +#include + +#if defined(__WATCOMC__) +#pragma warning 604 9 +#pragma warning 595 9 +#pragma warning 594 9 +#endif + +#endif + +namespace Bstrlib { + +#ifdef BSTRLIB_THROWS_EXCEPTIONS +#if defined(BSTRLIB_CAN_USE_STL) +struct CBStringException : public std::exception { +private: + std::string msg; +public: + CBStringException (const std::string inmsg) : msg(inmsg) {} + virtual ~CBStringException () throw () {} + virtual const char *what () const throw () { return msg.c_str(); } +}; +#else +struct CBStringException { +private: + char * msg; + int needToFree; +public: + CBStringException (const char * inmsg) : needToFree(0) { + if (inmsg) { + msg = (char *) malloc (1 + strlen (inmsg)); + if (NULL == msg) msg = "Out of memory"; + else { + strcpy (msg, inmsg); + needToFree = 1; + } + } else { + msg = "NULL exception message"; + } + } + virtual ~CBStringException () throw () { + if (needToFree) { + free (msg); + needToFree = 0; + msg = NULL; + } + } + virtual const char *what () const throw () { return msg; } +}; +#endif +#define bstringThrow(er) {\ + CBStringException bstr__cppwrapper_exception ("CBString::" er "");\ + throw bstr__cppwrapper_exception;\ +} +#else +#define bstringThrow(er) {} +#endif + +struct CBString; + +#ifdef _MSC_VER +#pragma warning(disable:4512) +#endif + +class CBCharWriteProtected { +friend struct CBString; + private: + const struct tagbstring& s; + unsigned int idx; + CBCharWriteProtected (const struct tagbstring& c, int i) : s(c), idx((unsigned int)i) { + if (idx >= (unsigned) s.slen) { + bstringThrow ("character index out of bounds"); + } + } + + public: + + inline char operator = (char c) { + if (s.mlen <= 0) { + bstringThrow ("Write protection error"); + } else { +#ifndef BSTRLIB_THROWS_EXCEPTIONS + if (idx >= (unsigned) s.slen) return '\0'; +#endif + s.data[idx] = (unsigned char) c; + } + return (char) s.data[idx]; + } + inline unsigned char operator = (unsigned char c) { + if (s.mlen <= 0) { + bstringThrow ("Write protection error"); + } else { +#ifndef BSTRLIB_THROWS_EXCEPTIONS + if (idx >= (unsigned) s.slen) return '\0'; +#endif + s.data[idx] = c; + } + return s.data[idx]; + } + inline operator unsigned char () const { +#ifndef BSTRLIB_THROWS_EXCEPTIONS + if (idx >= (unsigned) s.slen) return (unsigned char) '\0'; +#endif + return s.data[idx]; + } +}; + +struct CBString : public tagbstring { + + // Constructors + CBString (); + CBString (char c); + CBString (unsigned char c); + CBString (const char *s); + CBString (int len, const char *s); + CBString (const CBString& b); + CBString (const tagbstring& x); + CBString (char c, int len); + CBString (const void * blk, int len); + +#if defined(BSTRLIB_CAN_USE_STL) + CBString (const struct CBStringList& l); + CBString (const struct CBStringList& l, const CBString& sep); + CBString (const struct CBStringList& l, char sep); + CBString (const struct CBStringList& l, unsigned char sep); +#endif + + // Destructor +#if !defined(BSTRLIB_DONT_USE_VIRTUAL_DESTRUCTOR) + virtual +#endif + ~CBString (); + + // = operator + const CBString& operator = (char c); + const CBString& operator = (unsigned char c); + const CBString& operator = (const char *s); + const CBString& operator = (const CBString& b); + const CBString& operator = (const tagbstring& x); + + // += operator + const CBString& operator += (char c); + const CBString& operator += (unsigned char c); + const CBString& operator += (const char *s); + const CBString& operator += (const CBString& b); + const CBString& operator += (const tagbstring& x); + + // *= operator + inline const CBString& operator *= (int count) { + this->repeat (count); + return *this; + } + + // + operator + const CBString operator + (char c) const; + const CBString operator + (unsigned char c) const; + const CBString operator + (const unsigned char *s) const; + const CBString operator + (const char *s) const; + const CBString operator + (const CBString& b) const; + const CBString operator + (const tagbstring& x) const; + + // * operator + inline const CBString operator * (int count) const { + CBString retval (*this); + retval.repeat (count); + return retval; + } + + // Comparison operators + bool operator == (const CBString& b) const; + bool operator == (const char * s) const; + bool operator == (const unsigned char * s) const; + bool operator != (const CBString& b) const; + bool operator != (const char * s) const; + bool operator != (const unsigned char * s) const; + bool operator < (const CBString& b) const; + bool operator < (const char * s) const; + bool operator < (const unsigned char * s) const; + bool operator <= (const CBString& b) const; + bool operator <= (const char * s) const; + bool operator <= (const unsigned char * s) const; + bool operator > (const CBString& b) const; + bool operator > (const char * s) const; + bool operator > (const unsigned char * s) const; + bool operator >= (const CBString& b) const; + bool operator >= (const char * s) const; + bool operator >= (const unsigned char * s) const; + + // Casts + inline operator const char* () const { return (const char *)data; } + inline operator const unsigned char* () const { return (const unsigned char *)data; } + operator double () const; + operator float () const; + operator int () const; + operator unsigned int () const; + + // Accessors + inline int length () const {return slen;} + + inline unsigned char character (int i) const { + if (((unsigned) i) >= (unsigned) slen) { +#ifdef BSTRLIB_THROWS_EXCEPTIONS + bstringThrow ("character idx out of bounds"); +#else + return '\0'; +#endif + } + return data[i]; + } + inline unsigned char operator [] (int i) const { return character(i); } + + inline CBCharWriteProtected character (int i) { + return CBCharWriteProtected (*this, i); + } + inline CBCharWriteProtected operator [] (int i) { return character(i); } + + // Space allocation hint method. + void alloc (int length); + + // Search methods. + int caselessEqual (const CBString& b) const; + int caselessCmp (const CBString& b) const; + int find (const CBString& b, int pos = 0) const; + int find (const char * b, int pos = 0) const; + int caselessfind (const CBString& b, int pos = 0) const; + int caselessfind (const char * b, int pos = 0) const; + int find (char c, int pos = 0) const; + int reversefind (const CBString& b, int pos) const; + int reversefind (const char * b, int pos) const; + int caselessreversefind (const CBString& b, int pos) const; + int caselessreversefind (const char * b, int pos) const; + int reversefind (char c, int pos) const; + int findchr (const CBString& b, int pos = 0) const; + int findchr (const char * s, int pos = 0) const; + int reversefindchr (const CBString& b, int pos) const; + int reversefindchr (const char * s, int pos) const; + int nfindchr (const CBString& b, int pos = 0) const; + int nfindchr (const char * b, int pos = 0) const; + int nreversefindchr (const CBString& b, int pos) const; + int nreversefindchr (const char * b, int pos) const; + + // Search and substitute methods. + void findreplace (const CBString& find, const CBString& repl, int pos = 0); + void findreplace (const CBString& find, const char * repl, int pos = 0); + void findreplace (const char * find, const CBString& repl, int pos = 0); + void findreplace (const char * find, const char * repl, int pos = 0); + void findreplacecaseless (const CBString& find, const CBString& repl, int pos = 0); + void findreplacecaseless (const CBString& find, const char * repl, int pos = 0); + void findreplacecaseless (const char * find, const CBString& repl, int pos = 0); + void findreplacecaseless (const char * find, const char * repl, int pos = 0); + + // Extraction method. + CBString midstr (int left, int len) const; + + // Standard manipulation methods. + void setsubstr (int pos, const CBString& b, unsigned char fill = ' '); + void setsubstr (int pos, const char * b, unsigned char fill = ' '); + void insert (int pos, const CBString& b, unsigned char fill = ' '); + void insert (int pos, const char * b, unsigned char fill = ' '); + void insertchrs (int pos, int len, unsigned char fill = ' '); + void replace (int pos, int len, const CBString& b, unsigned char fill = ' '); + void replace (int pos, int len, const char * s, unsigned char fill = ' '); + void remove (int pos, int len); + void trunc (int len); + + // Miscellaneous methods. + void format (const char * fmt, ...); + void formata (const char * fmt, ...); + void fill (int length, unsigned char fill = ' '); + void repeat (int count); + void ltrim (const CBString& b = CBString (bsStaticBlkParms (" \t\v\f\r\n"))); + void rtrim (const CBString& b = CBString (bsStaticBlkParms (" \t\v\f\r\n"))); + inline void trim (const CBString& b = CBString (bsStaticBlkParms (" \t\v\f\r\n"))) { + rtrim (b); + ltrim (b); + } + void toupper (); + void tolower (); + + // Write protection methods. + void writeprotect (); + void writeallow (); + inline bool iswriteprotected () const { return mlen <= 0; } + + // Join methods. +#if defined(BSTRLIB_CAN_USE_STL) + void join (const struct CBStringList& l); + void join (const struct CBStringList& l, const CBString& sep); + void join (const struct CBStringList& l, char sep); + void join (const struct CBStringList& l, unsigned char sep); +#endif + + // CBStream methods + int gets (bNgetc getcPtr, void * parm, char terminator = '\n'); + int read (bNread readPtr, void * parm); + + // QString compatibility methods + CBString toLocal8Bit() const { return *this; } + bool isEmpty() const { return slen == 0; } + void clear() { *this = ""; } + CBString left(int len) const { return midstr(0, len); } + CBString mid(int pos, int len) const { return midstr(pos, len); } + static CBString fromUtf16(const unsigned short* str) { // Naive implementation assuming that only ASCII part of UCS2 is used + CBString msg; while (*str) { msg += *(char*)str; str++; } return msg; + } + CBString leftJustified(int length) { if (length > slen) { return *this + CBString(' ', length - slen); } return *this; } +}; +extern const CBString operator + (const char *a, const CBString& b); +extern const CBString operator + (const unsigned char *a, const CBString& b); +extern const CBString operator + (char c, const CBString& b); +extern const CBString operator + (unsigned char c, const CBString& b); +extern const CBString operator + (const tagbstring& x, const CBString& b); +inline const CBString operator * (int count, const CBString& b) { + CBString retval (b); + retval.repeat (count); + return retval; +} + +#if defined(BSTRLIB_CAN_USE_IOSTREAM) +extern std::ostream& operator << (std::ostream& sout, CBString b); +extern std::istream& operator >> (std::istream& sin, CBString& b); +extern std::istream& getline (std::istream& sin, CBString& b, char terminator='\n'); +#endif + +struct CBStream { +friend struct CBStringList; +private: + struct bStream * m_s; +public: + CBStream (bNread readPtr, void * parm); + ~CBStream (); + int buffLengthSet (int sz); + int buffLengthGet (); + int eof () const; + + CBString readLine (char terminator); + CBString readLine (const CBString& terminator); + void readLine (CBString& s, char terminator); + void readLine (CBString& s, const CBString& terminator); + void readLineAppend (CBString& s, char terminator); + void readLineAppend (CBString& s, const CBString& terminator); + + CBString read (); + CBString& operator >> (CBString& s); + + CBString read (int n); + void read (CBString& s); + void read (CBString& s, int n); + void readAppend (CBString& s); + void readAppend (CBString& s, int n); + + void unread (const CBString& s); + inline CBStream& operator << (const CBString& s) { + this->unread (s); + return *this; + } + + CBString peek () const; + void peek (CBString& s) const; + void peekAppend (CBString& s) const; +}; + +#if defined(BSTRLIB_CAN_USE_STL) +struct CBStringList : public std::vector { + // split a string into a vector of strings. + void split (const CBString& b, unsigned char splitChar); + void split (const CBString& b, const CBString& s); + void splitstr (const CBString& b, const CBString& s); + void split (const CBStream& b, unsigned char splitChar); + void split (const CBStream& b, const CBString& s); + void splitstr (const CBStream& b, const CBString& s); +}; +#endif + +} // namespace Bstrlib + +#if !defined (BSTRLIB_DONT_ASSUME_NAMESPACE) +using namespace Bstrlib; +#endif + +#endif +#endif diff --git a/common/treemodel.cpp b/common/treemodel.cpp index 021e240..1f69c28 100644 --- a/common/treemodel.cpp +++ b/common/treemodel.cpp @@ -473,7 +473,7 @@ UModelIndex TreeModel::addItem(const UINT32 offset, const UINT8 type, const UINT emit layoutChanged(); UModelIndex created = createIndex(newItem->row(), parentColumn, newItem); - setFixed(created, fixed); // Non-trivial logic requires additional call + setFixed(created, (bool)fixed); // Non-trivial logic requires additional call return created; } diff --git a/common/ustring.h b/common/ustring.h index f304db6..2882d80 100644 --- a/common/ustring.h +++ b/common/ustring.h @@ -21,7 +21,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. #else // Use Bstrlib #define BSTRLIB_DOESNT_THROW_EXCEPTIONS -#include "../bstrlib/bstrwrap.h" +#include "bstrlib/bstrwrap.h" #define UString CBString #endif // QT_CORE_LIB