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 "decimalbytecodec.hpp"
0010 
0011 // Qt
0012 #include <QString>
0013 
0014 namespace Okteta {
0015 
0016 unsigned int DecimalByteCodec::encodingWidth() const { return 3; }
0017 Byte DecimalByteCodec::digitsFilledLimit() const { return 26; }
0018 
0019 void DecimalByteCodec::encode(QString* digits, unsigned int pos, Byte byte) const
0020 {
0021     const int minSizeNeeded = pos + 3;
0022     if (digits->size() < minSizeNeeded) {
0023         digits->resize(minSizeNeeded);
0024     }
0025 
0026     unsigned char digitValue = byte / 100;
0027     (*digits)[pos++] = QLatin1Char('0' + digitValue);
0028     byte -= digitValue * 100;
0029     digitValue = byte / 10;
0030     (*digits)[pos++] = QLatin1Char('0' + digitValue);
0031     byte -= digitValue * 10;
0032     (*digits)[pos] = QLatin1Char('0' + byte);
0033 }
0034 
0035 void DecimalByteCodec::encodeShort(QString* digits, unsigned int pos, Byte byte) const
0036 {
0037     const int encodingLength = (byte > 99) ? 3 : (byte > 9) ? 2 : 1;
0038     const int minSizeNeeded = pos + encodingLength;
0039     if (digits->size() < minSizeNeeded) {
0040         digits->resize(minSizeNeeded);
0041     }
0042 
0043     const unsigned char firstDigitValue = byte / 100;
0044     if (firstDigitValue > 0) {
0045         (*digits)[pos++] = QLatin1Char('0' + firstDigitValue);
0046         byte -= firstDigitValue * 100;
0047     }
0048     const unsigned char secondDigitValue = byte / 10;
0049     if (secondDigitValue > 0 || firstDigitValue > 0) {
0050         (*digits)[pos++] = QLatin1Char('0' + secondDigitValue);
0051         byte -= secondDigitValue * 10;
0052     }
0053     (*digits)[pos] = QLatin1Char('0' + byte);
0054 }
0055 
0056 bool DecimalByteCodec::isValidDigit(unsigned char digit) const
0057 {
0058     return ('0' <= digit && digit <= '9');
0059 }
0060 
0061 bool DecimalByteCodec::turnToValue(unsigned char* digit) const
0062 {
0063     if (isValidDigit(*digit)) {
0064         *digit -= '0';
0065         return true;
0066     }
0067     return false;
0068 }
0069 
0070 bool DecimalByteCodec::appendDigit(Byte* byte, unsigned char digit) const
0071 {
0072     if (turnToValue(&digit)) {
0073         Byte _byte = *byte;
0074         if (_byte < 25 ||
0075             (_byte == 25 && digit < 6)) {
0076             _byte *= 10;
0077             _byte += digit;
0078             *byte = _byte;
0079             return true;
0080         }
0081     }
0082     return false;
0083 }
0084 
0085 void DecimalByteCodec::removeLastDigit(Byte* byte) const
0086 {
0087     *byte /= 10;
0088 }
0089 
0090 }