Cobs.cpp

Go to the documentation of this file.
00001 /*
00002 
00003 Copyright (C) 2005-2007 by Peter Dimov.
00004 
00005 This file is part of Calitko (http://www.calitko.org).
00006 
00007 Calitko is free software; you can redistribute it and/or modify
00008 it under the terms of the GNU General Public License as published by
00009 the Free Software Foundation; either version 2 of the License, or
00010 (at your option) any later version.
00011 
00012 Calitko is distributed in the hope that it will be useful,
00013 but WITHOUT ANY WARRANTY; without even the implied warranty of
00014 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015 GNU General Public License for more details.
00016 
00017 You should have received a copy of the GNU General Public License
00018 along with Calitko; if not, write to the Free Software
00019 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
00020 
00021 */
00022 
00023 #include "Qt.h"
00024 #include "Cobs.h"
00025 
00027 QByteArray Utils::Encodings::Cobs::encode (const QByteArray &rawData)
00028 {
00029 #define FinishBlock(X)  (*code_ptr = (X), code_ptr = dst++, code = 0x01)
00030 
00031     int maximalEncodedLength = rawData.length() + rawData.length() / 254 + 1;
00032     QByteArray encodedData;
00033     encodedData.resize (maximalEncodedLength);
00034 
00035     uchar *dst = reinterpret_cast <uchar *> (encodedData.data());
00036     const uchar *ptr = reinterpret_cast <const uchar*> (rawData.data());
00037     const uchar *end = ptr + rawData.length();
00038     uchar *code_ptr = dst++;
00039     uchar code = 0x01;
00040 
00041     while (ptr < end) {
00042         if (*ptr == 0)
00043             FinishBlock (code);
00044         else {
00045             *dst++ = *ptr;
00046             code++;
00047             if (code == 0xFF)
00048                 FinishBlock (code);
00049         }
00050         ptr++;
00051     }
00052     FinishBlock (code);
00053 
00054     encodedData.resize (code_ptr - reinterpret_cast <uchar *> (encodedData.data()));
00055     return encodedData;
00056 
00057 #undef FinishBlock
00058 }
00059 
00061 QByteArray Utils::Encodings::Cobs::decode (const QByteArray &rawData)
00062 {
00063     QByteArray decodedData;
00064     decodedData.resize (rawData.length());
00065 
00066     uchar *dst = reinterpret_cast <uchar *> (decodedData.data());
00067     const uchar *ptr = reinterpret_cast <const uchar *> (rawData.data());
00068     const uchar *end = ptr + rawData.length();
00069 
00070     while (ptr < end) {
00071         int code = *ptr++;
00072         for (int i = 1; i < code; i++)
00073             *dst++ = *ptr++;
00074         if (code < 0xFF)
00075             *dst++ = 0;
00076     };
00077 
00078     decodedData.resize (dst - 1 - reinterpret_cast <uchar *> (decodedData.data()));
00079     return decodedData;
00080 }