--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Iconv.cpp Wed Nov 20 14:56:41 2019 +0100
@@ -0,0 +1,82 @@
+/**
+ * Relational pipes (library)
+ * Copyright © 2019 František Kučera (Frantovo.cz, GlobalCode.info)
+ *
+ * This program 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;
+ * version 3 of the License or (at your option)
+ * - GNU General Public License as published by the Free Software Foundation;
+ * version 2 of the License.
+ *
+ * This program 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "../include/relpipe/common/text/Iconv.h"
+
+namespace relpipe {
+namespace common {
+namespace text {
+
+class Iconv::IconvInternal {
+public:
+ static const size_t BUFFER_SIZE_MINIMUM;
+ static const size_t BUFFER_SIZE_DEFAULT;
+ const size_t bufferSize;
+ iconv_t cd;
+
+ IconvInternal(std::string to, std::string from, const size_t bufferSize) : bufferSize(std::max(bufferSize, BUFFER_SIZE_MINIMUM)) {
+ cd = iconv_open(to.c_str(), from.c_str());
+ if (errno) throw std::string("iconv_open() error: ") + strerror(errno); // TODO: custom exception
+ }
+
+ virtual ~IconvInternal() {
+ iconv_close(cd);
+ }
+
+};
+
+const size_t Iconv::IconvInternal::BUFFER_SIZE_MINIMUM = 2; // TODO: enough?
+const size_t Iconv::IconvInternal::BUFFER_SIZE_DEFAULT = 20;
+
+Iconv::Iconv(std::string to, std::string from) : Iconv(to, from, IconvInternal::BUFFER_SIZE_DEFAULT) {
+}
+
+Iconv::Iconv(std::string to, std::string from, size_t bufferSize) {
+ internal = new Iconv::IconvInternal(to, from, bufferSize);
+
+}
+
+Iconv::~Iconv() {
+ delete internal;
+}
+
+std::string Iconv::convert(std::string originalText) {
+ std::stringstream result;
+ size_t inBytesLeft = originalText.size();
+ size_t outBytesLeft = internal->bufferSize;
+ char outBuffer[internal->bufferSize];
+ char* outBuf = (char*) outBuffer;
+ char* inBuf = (char*) originalText.c_str();
+
+ do {
+ size_t nconv = iconv(internal->cd, &inBuf, &inBytesLeft, &outBuf, &outBytesLeft);
+ if (nconv < 0) throw std::string("iconv() error: ") + strerror(errno); // TODO: custom exception
+ // TODO: throw exception if locale is not initialized and platform default "" is used (avoid infinite loop)
+ result.write(outBuffer, internal->bufferSize - outBytesLeft);
+ outBytesLeft = internal->bufferSize;
+ outBuf = (char*) outBuffer;
+ } while (inBytesLeft > 0);
+
+ return result.str();
+}
+
+}
+}
+}