소스 검색

2008-02-24 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com>

	Rewritten itos and uitos using template. llitos and ullitos are
	replaced with itos and uitos respectively.
	* src/Util.{h, cc}
	* test/UtilTest.cc
Tatsuhiro Tsujikawa 17 년 전
부모
커밋
5a4d691aed

+ 7 - 0
ChangeLog

@@ -1,3 +1,10 @@
+2008-02-24  Tatsuhiro Tsujikawa  <tujikawa at rednoah dot com>
+
+	Rewritten itos and uitos using template. llitos and ullitos are
+	replaced with itos and uitos respectively.
+	* src/Util.{h, cc}
+	* test/UtilTest.cc
+
 2008-02-24  Tatsuhiro Tsujikawa  <tujikawa at rednoah dot com>
 
 	Fixed the bug that DH key exchange sometimes fails due to bad handling

+ 1 - 1
src/DHTMessageTracker.cc

@@ -88,7 +88,7 @@ DHTMessageTracker::messageArrived(const Dictionary* d,
       SharedHandle<DHTMessage> message = _factory->createResponseMessage(entry->getMessageType(),
 								 d, targetNode);
       int64_t rtt = entry->getElapsedMillis();
-      _logger->debug("RTT is %s", Util::llitos(rtt).c_str());
+      _logger->debug("RTT is %s", Util::itos(rtt).c_str());
       targetNode->updateRTT(rtt);
       SharedHandle<DHTMessageCallback> callback = entry->getCallback();
       return std::pair<SharedHandle<DHTMessage>, SharedHandle<DHTMessageCallback> >(message, callback);

+ 1 - 1
src/DHTQueryMessage.cc

@@ -68,7 +68,7 @@ std::string DHTQueryMessage::toString() const
   return "dht query "+getMessageType()+
     " TransactionID="+Util::toHex(_transactionID)+
     " Remote:"+
-    _remoteNode->getIPAddress()+":"+Util::itos(_remoteNode->getPort())+
+    _remoteNode->getIPAddress()+":"+Util::uitos(_remoteNode->getPort())+
     ", id="+Util::toHex(_remoteNode->getID(), DHT_ID_LENGTH)+
     ", "+toStringOptional();
 }

+ 1 - 1
src/DHTResponseMessage.cc

@@ -67,7 +67,7 @@ std::string DHTResponseMessage::toString() const
   return "dht response "+getMessageType()+
     " TransactionID="+Util::toHex(_transactionID)+
     " Remote:"+
-    _remoteNode->getIPAddress()+":"+Util::itos(_remoteNode->getPort())+
+    _remoteNode->getIPAddress()+":"+Util::uitos(_remoteNode->getPort())+
     ", id="+Util::toHex(_remoteNode->getID(), DHT_ID_LENGTH)+
     ", "+toStringOptional();
 }

+ 3 - 3
src/DefaultBtAnnounce.cc

@@ -143,9 +143,9 @@ std::string DefaultBtAnnounce::getAnnounceUrl() {
     "info_hash="+Util::torrentUrlencode(btContext->getInfoHash(),
 					btContext->getInfoHashLength())+"&"+
     "peer_id="+Util::torrentUrlencode(btContext->getPeerId(), 20)+"&"+
-    "uploaded="+Util::llitos(stat.getSessionUploadLength())+"&"+
-    "downloaded="+Util::llitos(stat.getSessionDownloadLength())+"&"+
-    "left="+Util::llitos(left)+"&"+
+    "uploaded="+Util::itos(stat.getSessionUploadLength())+"&"+
+    "downloaded="+Util::itos(stat.getSessionDownloadLength())+"&"+
+    "left="+Util::itos(left)+"&"+
     "compact=1"+"&"+
     "key="+key+"&"+
     "numwant="+Util::itos(numWant)+"&"+

+ 2 - 2
src/DefaultBtProgressInfoFile.cc

@@ -206,8 +206,8 @@ void DefaultBtProgressInfoFile::load()
     in.read(reinterpret_cast<char*>(&totalLength), sizeof(totalLength));
     if(totalLength != _dctx->getTotalLength()) {
       throw new DlAbortEx("total length mismatch. expected: %s, actual: %s",
-			  Util::llitos(_dctx->getTotalLength()).c_str(),
-			  Util::llitos(totalLength).c_str());
+			  Util::itos(_dctx->getTotalLength()).c_str(),
+			  Util::itos(totalLength).c_str());
     }
     int64_t uploadLength;
     in.read(reinterpret_cast<char*>(&uploadLength), sizeof(uploadLength));

+ 1 - 1
src/DownloadCommand.cc

@@ -200,7 +200,7 @@ void DownloadCommand::validatePieceHash(const SegmentHandle& segment)
     } else {
       logger->info(EX_INVALID_CHUNK_CHECKSUM,
 		   segment->getIndex(),
-		   Util::llitos(segment->getPosition(), true).c_str(),
+		   Util::itos(segment->getPosition(), true).c_str(),
 		   expectedPieceHash.c_str(),
 		   actualPieceHash.c_str());
       segment->clear();

+ 1 - 1
src/FileAllocationCommand.cc

@@ -59,7 +59,7 @@ bool FileAllocationCommand::executeInternal()
   if(_fileAllocationEntry->finished()) {
     logger->debug(MSG_ALLOCATION_COMPLETED,
 		  _timer.difference(),
-		  Util::llitos(_requestGroup->getTotalLength(), true).c_str());
+		  Util::itos(_requestGroup->getTotalLength(), true).c_str());
     _e->_fileAllocationMan->markCurrentFileAllocationEntryDone();
     
     _e->addCommand(_fileAllocationEntry->prepareForNextAction(_e));

+ 1 - 1
src/FtpConnection.cc

@@ -128,7 +128,7 @@ SocketHandle FtpConnection::sendPort() const
 
 void FtpConnection::sendRest(const SegmentHandle& segment) const
 {
-  std::string request = "REST "+Util::llitos(segment->getPositionToWrite())+"\r\n";
+  std::string request = "REST "+Util::itos(segment->getPositionToWrite())+"\r\n";
   logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
   socket->writeData(request);
 }

+ 1 - 1
src/FtpNegotiationCommand.cc

@@ -215,7 +215,7 @@ bool FtpNegotiationCommand::recvSize() {
     throw new DlAbortEx(EX_BAD_STATUS, status);
   }
   if(size == INT64_MAX || size < 0) {
-    throw new DlAbortEx(EX_TOO_LARGE_FILE, Util::llitos(size, true).c_str());
+    throw new DlAbortEx(EX_TOO_LARGE_FILE, Util::itos(size, true).c_str());
   }
   if(_requestGroup->getPieceStorage().isNull()) {
     SingleFileDownloadContextHandle dctx = _requestGroup->getDownloadContext();

+ 2 - 2
src/HandshakeExtensionMessage.cc

@@ -65,7 +65,7 @@ std::string HandshakeExtensionMessage::getBencodedData()
     dic->put("v", v);
   }
   if(_tcpPort > 0) {
-    std::string portStr = Util::itos(_tcpPort);
+    std::string portStr = Util::uitos(_tcpPort);
     Data* p = new Data(portStr, true);
     dic->put("p", p);
   }
@@ -89,7 +89,7 @@ std::string HandshakeExtensionMessage::toString() const
     s += " client="+Util::urlencode(_clientVersion);
   }
   if(_tcpPort > 0) {
-    s += ", tcpPort="+Util::itos(_tcpPort);
+    s += ", tcpPort="+Util::uitos(_tcpPort);
   }
   for(std::map<std::string, uint8_t>::const_iterator itr = _extensions.begin();
       itr != _extensions.end(); ++itr) {

+ 3 - 3
src/HttpRequest.cc

@@ -128,7 +128,7 @@ bool HttpRequest::isRangeSatisfied(const RangeHandle& range) const
 
 std::string HttpRequest::getHostText(const std::string& host, int32_t port) const
 {
-  return  host+(port == 80 || port == 443 ? "" : ":"+Util::llitos(port));
+  return  host+(port == 80 || port == 443 ? "" : ":"+Util::itos(port));
 }
 
 std::string HttpRequest::createRequest() const
@@ -156,10 +156,10 @@ std::string HttpRequest::createRequest() const
   }
   if(!segment.isNull() && segment->getLength() > 0 &&
      (request->isKeepAlive() || getStartByte() > 0)) {
-    requestLine += "Range: bytes="+Util::llitos(getStartByte());
+    requestLine += "Range: bytes="+Util::itos(getStartByte());
     requestLine += "-";
     if(request->isKeepAlive()) {
-      requestLine += Util::llitos(getEndByte());
+      requestLine += Util::itos(getEndByte());
     }
     requestLine += "\r\n";
   }

+ 6 - 6
src/HttpResponse.cc

@@ -80,12 +80,12 @@ void HttpResponse::validateResponse() const
       RangeHandle responseRange = httpHeader->getRange();
       if(!httpRequest->isRangeSatisfied(responseRange)) {
 	throw new DlAbortEx(EX_INVALID_RANGE_HEADER,
-			    Util::llitos(httpRequest->getStartByte(), true).c_str(),
-			    Util::llitos(httpRequest->getEndByte(), true).c_str(),
-			    Util::llitos(httpRequest->getEntityLength(), true).c_str(),
-			    Util::llitos(responseRange->getStartByte(), true).c_str(),
-			    Util::llitos(responseRange->getEndByte(), true).c_str(),
-			    Util::llitos(responseRange->getEntityLength(), true).c_str());
+			    Util::itos(httpRequest->getStartByte(), true).c_str(),
+			    Util::itos(httpRequest->getEndByte(), true).c_str(),
+			    Util::itos(httpRequest->getEntityLength(), true).c_str(),
+			    Util::itos(responseRange->getStartByte(), true).c_str(),
+			    Util::itos(responseRange->getEndByte(), true).c_str(),
+			    Util::itos(responseRange->getEntityLength(), true).c_str());
       }
     }
   }

+ 1 - 1
src/IteratableChunkChecksumValidator.cc

@@ -87,7 +87,7 @@ void IteratableChunkChecksumValidator::validateChunk()
     } else {
       _logger->info(EX_INVALID_CHUNK_CHECKSUM,
 		    _currentIndex,
-		    Util::llitos(getCurrentOffset(), true).c_str(),
+		    Util::itos(getCurrentOffset(), true).c_str(),
 		    _dctx->getPieceHashes()[_currentIndex].c_str(),
 		    actualChecksum.c_str());
       _bitfield->unsetBit(_currentIndex);

+ 2 - 2
src/MultiDiskAdaptor.cc

@@ -201,7 +201,7 @@ void MultiDiskAdaptor::writeData(const unsigned char* data, int32_t len,
     }
   }
   if(!writing) {
-    throw new DlAbortEx(EX_FILE_OFFSET_OUT_OF_RANGE, Util::llitos(offset, true).c_str());
+    throw new DlAbortEx(EX_FILE_OFFSET_OUT_OF_RANGE, Util::itos(offset, true).c_str());
   }
 }
 
@@ -244,7 +244,7 @@ int32_t MultiDiskAdaptor::readData(unsigned char* data, int32_t len, int64_t off
     }
   }
   if(!reading) {
-    throw new DlAbortEx(EX_FILE_OFFSET_OUT_OF_RANGE, Util::llitos(offset, true).c_str());
+    throw new DlAbortEx(EX_FILE_OFFSET_OUT_OF_RANGE, Util::itos(offset, true).c_str());
   }
   return totalReadLength;
 }

+ 5 - 5
src/OptionHandlerImpl.h

@@ -89,7 +89,7 @@ public:
       int32_t v = seq.next();
       if(v < _min || _max < v) {
 	std::string msg = _optName+" "+_("must be between %s and %s.");
-	throw new FatalException(msg.c_str(), Util::llitos(_min).c_str(), Util::llitos(_max).c_str());
+	throw new FatalException(msg.c_str(), Util::itos(_min).c_str(), Util::itos(_max).c_str());
       }
       option->put(_optName, optarg);
     }
@@ -114,18 +114,18 @@ public:
   void parseArg(Option* option, int64_t number)
   {
     if((_min == -1 || _min <= number) && (_max ==  -1 || number <= _max)) {
-      option->put(_optName, Util::llitos(number));
+      option->put(_optName, Util::itos(number));
     } else {
       std::string msg = _optName+" ";
       if(_min == -1 && _max != -1) {
 	msg += _("must be smaller than or equal to %s.");
-	throw new FatalException(msg.c_str(), Util::llitos(_max).c_str());
+	throw new FatalException(msg.c_str(), Util::itos(_max).c_str());
       } else if(_min != -1 && _max != -1) {
 	msg += _("must be between %s and %s.");
-	throw new FatalException(msg.c_str(), Util::llitos(_min).c_str(), Util::llitos(_max).c_str());
+	throw new FatalException(msg.c_str(), Util::itos(_min).c_str(), Util::itos(_max).c_str());
       } else if(_min != -1 && _max == -1) {
 	msg += _("must be greater than or equal to %s.");
-	throw new FatalException(msg.c_str(), Util::llitos(_min).c_str());
+	throw new FatalException(msg.c_str(), Util::itos(_min).c_str());
       } else {
 	msg += _("must be a number.");
 	throw new FatalException(msg.c_str());

+ 1 - 1
src/Peer.cc

@@ -53,7 +53,7 @@ Peer::Peer(std::string ipaddr, uint16_t port):
   _res(0)
 {
   resetStatus();
-  std::string idSeed = ipaddr+":"+Util::itos(port);
+  std::string idSeed = ipaddr+":"+Util::uitos(port);
 #ifdef ENABLE_MESSAGE_DIGEST
   id = MessageDigestHelper::digestString("sha1", idSeed);
 #else

+ 4 - 4
src/RequestGroup.cc

@@ -360,8 +360,8 @@ void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoF
 	if(getTotalLength() < outfile.size()) {
 	  throw new DlAbortEx(EX_FILE_LENGTH_MISMATCH_BETWEEN_LOCAL_AND_REMOTE,
 			      getFilePath().c_str(),
-			      Util::llitos(outfile.size()).c_str(),
-			      Util::llitos(getTotalLength()).c_str());
+			      Util::itos(outfile.size()).c_str(),
+			      Util::itos(getTotalLength()).c_str());
 	}
 	_pieceStorage->getDiskAdaptor()->openExistingFile();
 	_pieceStorage->markPiecesDone(outfile.size());
@@ -514,8 +514,8 @@ void RequestGroup::validateTotalLength(int64_t expectedTotalLength,
   }
   if(expectedTotalLength != actualTotalLength) {
     throw new DlAbortEx(EX_SIZE_MISMATCH,
-			Util::llitos(expectedTotalLength, true).c_str(),
-			Util::llitos(actualTotalLength, true).c_str());
+			Util::itos(expectedTotalLength, true).c_str(),
+			Util::itos(actualTotalLength, true).c_str());
   }
 }
 

+ 2 - 70
src/Util.cc

@@ -59,74 +59,6 @@
 
 namespace aria2 {
 
-template<typename T>
-std::string uint2str(T value, bool comma)
-{
-  std::string str;
-  if(value == 0) {
-    str = "0";
-    return str;
-  }
-  int32_t count = 0;
-  while(value) {
-    ++count;
-    char digit = value%10+'0';
-    str.insert(str.begin(), digit);
-    value /= 10;
-    if(comma && count > 3 && count%3 == 1) {
-      str.insert(str.begin()+1, ',');
-    }
-  }
-  return str;
-}
-
-template<typename T>
-std::string int2str(T value, bool comma)
-{
-  bool flag = false;
-  if(value < 0) {
-    flag = true;
-    value = -value;
-  }
-  std::string str = uint2str<T>(value, comma);
-  if(flag) {
-    str.insert(str.begin(), '-');
-  }
-  return str;
-}
-
-
-
-std::string Util::uitos(uint16_t value, bool comma)
-{
-  return uint2str<uint16_t>(value, comma);
-}
-
-std::string Util::itos(int16_t value, bool comma)
-{
-  return int2str<int16_t>(value, comma);
-}
-
-std::string Util::uitos(uint32_t value, bool comma)
-{
-  return uint2str<uint32_t>(value, comma);
-}
-
-std::string Util::itos(int32_t value, bool comma)
-{
-  return int2str<int32_t>(value, comma);
-}
-
-std::string Util::ullitos(uint64_t value, bool comma)
-{
-  return uint2str<uint64_t>(value, comma);
-}
-
-std::string Util::llitos(int64_t value, bool comma)
-{
-  return int2str<int64_t>(value, comma);
-}
-
 std::string Util::trim(const std::string& src, const std::string& trimCharset)
 {
   std::string::size_type sp = src.find_first_not_of(trimCharset);
@@ -674,7 +606,7 @@ int64_t Util::getRealSize(const std::string& sizeWithUnit)
 std::string Util::abbrevSize(int64_t size)
 {
   if(size < 1024) {
-    return Util::llitos(size, true);
+    return Util::itos(size, true);
   }
   char units[] = { 'K', 'M' };
   int32_t numUnit = sizeof(units)/sizeof(char);
@@ -685,7 +617,7 @@ std::string Util::abbrevSize(int64_t size)
     r = size&0x3ff;
     size >>= 10;
   }
-  return Util::llitos(size, true)+"."+Util::itos(r*10/1024)+units[i]+"i";
+  return Util::itos(size, true)+"."+Util::itos(r*10/1024)+units[i]+"i";
 }
 
 time_t Util::httpGMT(const std::string& httpStdTime)

+ 35 - 6
src/Util.h

@@ -66,12 +66,41 @@ public:
   static std::pair<std::string, std::string>
   split(const std::string& src, const std::string& delims);
 
-  static std::string llitos(int64_t value, bool comma = false);
-  static std::string ullitos(uint64_t value, bool comma = false);
-  static std::string itos(int32_t value, bool comma = false);
-  static std::string uitos(uint32_t value, bool comma = false);
-  static std::string itos(int16_t value, bool comma = false);
-  static std::string uitos(uint16_t value, bool comma = false);
+  template<typename T>
+  static std::string uitos(T value, bool comma = false)
+  {
+    std::string str;
+    if(value == 0) {
+      str = "0";
+      return str;
+    }
+    int32_t count = 0;
+    while(value) {
+      ++count;
+      char digit = value%10+'0';
+      str.insert(str.begin(), digit);
+      value /= 10;
+      if(comma && count > 3 && count%3 == 1) {
+	str.insert(str.begin()+1, ',');
+      }
+    }
+    return str;
+  }
+
+  template<typename T>
+  static std::string itos(T value, bool comma = false)
+  {
+    bool flag = false;
+    if(value < 0) {
+      flag = true;
+      value = -value;
+    }
+    std::string str = uitos(value, comma);
+    if(flag) {
+      str.insert(str.begin(), '-');
+    }
+    return str;
+  }
 
   /**
    * Computes difference in micro-seconds between tv1 and tv2,

+ 48 - 0
test/UtilTest.cc

@@ -41,6 +41,8 @@ class UtilTest:public CppUnit::TestFixture {
   CPPUNIT_TEST(testParseInt);
   CPPUNIT_TEST(testParseLLInt);
   CPPUNIT_TEST(testToString_binaryStream);
+  CPPUNIT_TEST(testItos);
+  CPPUNIT_TEST(testUitos);
   CPPUNIT_TEST_SUITE_END();
 private:
 
@@ -75,6 +77,8 @@ public:
   void testParseInt();
   void testParseLLInt();
   void testToString_binaryStream();
+  void testItos();
+  void testUitos();
 };
 
 
@@ -597,4 +601,48 @@ void UtilTest::testToString_binaryStream()
   CPPUNIT_ASSERT_EQUAL(data, readData);
 }
 
+void UtilTest::testItos()
+{
+  {
+    int32_t i = 0;
+    CPPUNIT_ASSERT_EQUAL(std::string("0"), Util::itos(i));
+  }
+  {
+    int32_t i = 100;
+    CPPUNIT_ASSERT_EQUAL(std::string("100"), Util::itos(i, true));
+  }
+  {
+    int32_t i = 100;
+    CPPUNIT_ASSERT_EQUAL(std::string("100"), Util::itos(i));
+  }
+  {
+    int32_t i = 12345;
+    CPPUNIT_ASSERT_EQUAL(std::string("12,345"), Util::itos(i, true));
+  }
+  {
+    int32_t i = 12345;
+    CPPUNIT_ASSERT_EQUAL(std::string("12345"), Util::itos(i));
+  }
+  {
+    int32_t i = -12345;
+    CPPUNIT_ASSERT_EQUAL(std::string("-12,345"), Util::itos(i, true));
+  }
+  {
+    int64_t i = INT64_MAX;
+    CPPUNIT_ASSERT_EQUAL(std::string("9,223,372,036,854,775,807"), Util::itos(i, true));
+  }  
+}
+
+void UtilTest::testUitos()
+{
+  {
+    uint16_t i = 12345;
+    CPPUNIT_ASSERT_EQUAL(std::string("12345"), Util::uitos(i));
+  }
+  {
+    int16_t i = -12345;
+    CPPUNIT_ASSERT_EQUAL(std::string("/.-,+"), Util::uitos(i));
+  }
+}
+
 } // namespace aria2