File indexing completed on 2024-05-05 17:57:58

0001 /*
0002     This file is part of the Okteta Core library, made within the KDE community.
0003 
0004     SPDX-FileCopyrightText: 2004, 2011 Friedrich W. H. Kossebau <kossebau@kde.org>
0005 
0006     SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
0007 */
0008 
0009 #include "binarybytecodec.hpp"
0010 
0011 // Qt
0012 #include <QString>
0013 
0014 namespace Okteta {
0015 static constexpr Byte binaryDigitsFilledLimit = 128;
0016 
0017 unsigned int BinaryByteCodec::encodingWidth() const { return 8; }
0018 Byte BinaryByteCodec::digitsFilledLimit() const { return binaryDigitsFilledLimit; }
0019 
0020 void BinaryByteCodec::encode(QString* digits, unsigned int pos, Byte byte) const
0021 {
0022     const int minSizeNeeded = pos + 8;
0023     if (digits->size() < minSizeNeeded) {
0024         digits->resize(minSizeNeeded);
0025     }
0026 
0027     for (Byte mask = 1 << 7; mask > 0; mask >>= 1) {
0028         (*digits)[pos++] = QLatin1Char((byte & mask) ? '1' : '0');
0029     }
0030 }
0031 
0032 void BinaryByteCodec::encodeShort(QString* digits, unsigned int pos, Byte byte) const
0033 {
0034     int encodingLength = 8;
0035     Byte mask = 1 << 7;
0036     // find first set bit, at last break on LSB
0037     for (; mask > 1; mask >>= 1, --encodingLength) {
0038         if (byte & mask) {
0039             break;
0040         }
0041     }
0042 
0043     const int minSizeNeeded = pos + encodingLength;
0044     if (digits->size() < minSizeNeeded) {
0045         digits->resize(minSizeNeeded);
0046     }
0047 
0048     // now set the
0049     for (; mask > 0; mask >>= 1) {
0050         (*digits)[pos++] = QLatin1Char((byte & mask) ? '1' : '0');
0051     }
0052 }
0053 
0054 bool BinaryByteCodec::isValidDigit(unsigned char digit) const
0055 {
0056     return digit == '0' || digit == '1';
0057 }
0058 
0059 bool BinaryByteCodec::turnToValue(unsigned char* digit) const
0060 {
0061     if (isValidDigit(*digit)) {
0062         *digit -= '0';
0063         return true;
0064     }
0065     return false;
0066 }
0067 
0068 bool BinaryByteCodec::appendDigit(Byte* byte, unsigned char digit) const
0069 {
0070     if (turnToValue(&digit)) {
0071         Byte _byte = *byte;
0072         if (_byte < binaryDigitsFilledLimit) {
0073             _byte <<= 1;
0074             _byte += digit;
0075             *byte = _byte;
0076             return true;
0077         }
0078     }
0079     return false;
0080 }
0081 
0082 void BinaryByteCodec::removeLastDigit(Byte* byte) const
0083 {
0084     *byte >>= 1;
0085 }
0086 
0087 }