diff options
| author | Tatsuhiro Tsujikawa <tatsuhiro.t@gmail.com> | 2013-07-11 21:09:51 +0900 |
|---|---|---|
| committer | Tatsuhiro Tsujikawa <tatsuhiro.t@gmail.com> | 2013-07-11 21:09:51 +0900 |
| commit | 7c06b903f3493db95fcf4bd42cccc59e3b4d0692 (patch) | |
| tree | f10a85795bb086e0b257a0e6c6c5ffb05f28f344 | |
| parent | 7a57ecc5f814dc305e5e4b9bd960d69b43870c0e (diff) | |
Use std::unique_ptr for ValueBase object hierarchy
77 files changed, 1242 insertions, 1265 deletions
diff --git a/src/BtPostDownloadHandler.cc b/src/BtPostDownloadHandler.cc index 05d09f2e..0b2e73ea 100644 --- a/src/BtPostDownloadHandler.cc +++ b/src/BtPostDownloadHandler.cc @@ -71,7 +71,7 @@ void BtPostDownloadHandler::getNextRequestGroups { A2_LOG_INFO(fmt("Generating RequestGroups for Torrent file %s", requestGroup->getFirstFilePath().c_str())); - std::shared_ptr<ValueBase> torrent; + std::unique_ptr<ValueBase> torrent; if(requestGroup->inMemoryDownload()) { auto& dw = static_cast<AbstractSingleDiskAdaptor*> (requestGroup->getPieceStorage()->getDiskAdaptor().get()) @@ -104,7 +104,7 @@ void BtPostDownloadHandler::getNextRequestGroups createRequestGroupForBitTorrent(newRgs, requestGroup->getOption(), std::vector<std::string>(), "", - torrent); + torrent.get()); requestGroup->followedBy(newRgs.begin(), newRgs.end()); std::shared_ptr<MetadataInfo> mi = createMetadataInfoFromFirstFileEntry(requestGroup->getGroupId(), diff --git a/src/DHTAnnouncePeerMessage.cc b/src/DHTAnnouncePeerMessage.cc index 07f69517..ef4c84fe 100644 --- a/src/DHTAnnouncePeerMessage.cc +++ b/src/DHTAnnouncePeerMessage.cc @@ -86,7 +86,7 @@ void DHTAnnouncePeerMessage::doReceivedAction() (getRemoteNode(), getTransactionID())); } -std::shared_ptr<Dict> DHTAnnouncePeerMessage::getArgument() +std::unique_ptr<Dict> DHTAnnouncePeerMessage::getArgument() { auto aDict = Dict::g(); aDict->put(DHTMessage::ID, String::g(getLocalNode()->getID(), DHT_ID_LENGTH)); diff --git a/src/DHTAnnouncePeerMessage.h b/src/DHTAnnouncePeerMessage.h index b8045a26..84100a62 100644 --- a/src/DHTAnnouncePeerMessage.h +++ b/src/DHTAnnouncePeerMessage.h @@ -67,7 +67,7 @@ public: virtual void doReceivedAction() CXX11_OVERRIDE; - virtual std::shared_ptr<Dict> getArgument() CXX11_OVERRIDE; + virtual std::unique_ptr<Dict> getArgument() CXX11_OVERRIDE; virtual const std::string& getMessageType() const CXX11_OVERRIDE; diff --git a/src/DHTAnnouncePeerReplyMessage.cc b/src/DHTAnnouncePeerReplyMessage.cc index 3b094eb5..b4f0f852 100644 --- a/src/DHTAnnouncePeerReplyMessage.cc +++ b/src/DHTAnnouncePeerReplyMessage.cc @@ -50,9 +50,9 @@ DHTAnnouncePeerReplyMessage::~DHTAnnouncePeerReplyMessage() {} void DHTAnnouncePeerReplyMessage::doReceivedAction() {} -std::shared_ptr<Dict> DHTAnnouncePeerReplyMessage::getResponse() +std::unique_ptr<Dict> DHTAnnouncePeerReplyMessage::getResponse() { - std::shared_ptr<Dict> rDict = Dict::g(); + auto rDict = Dict::g(); rDict->put(DHTMessage::ID, String::g(getLocalNode()->getID(), DHT_ID_LENGTH)); return rDict; } diff --git a/src/DHTAnnouncePeerReplyMessage.h b/src/DHTAnnouncePeerReplyMessage.h index 99dbe7ca..70cab67a 100644 --- a/src/DHTAnnouncePeerReplyMessage.h +++ b/src/DHTAnnouncePeerReplyMessage.h @@ -49,7 +49,7 @@ public: virtual void doReceivedAction() CXX11_OVERRIDE; - virtual std::shared_ptr<Dict> getResponse() CXX11_OVERRIDE; + virtual std::unique_ptr<Dict> getResponse() CXX11_OVERRIDE; virtual const std::string& getMessageType() const CXX11_OVERRIDE; diff --git a/src/DHTFindNodeMessage.cc b/src/DHTFindNodeMessage.cc index 1d0c0d78..69ea7fb2 100644 --- a/src/DHTFindNodeMessage.cc +++ b/src/DHTFindNodeMessage.cc @@ -69,7 +69,7 @@ void DHTFindNodeMessage::doReceivedAction() (getRemoteNode(), std::move(nodes), getTransactionID())); } -std::shared_ptr<Dict> DHTFindNodeMessage::getArgument() +std::unique_ptr<Dict> DHTFindNodeMessage::getArgument() { auto aDict = Dict::g(); aDict->put(DHTMessage::ID, String::g(getLocalNode()->getID(), DHT_ID_LENGTH)); diff --git a/src/DHTFindNodeMessage.h b/src/DHTFindNodeMessage.h index 4101b74b..10f4263a 100644 --- a/src/DHTFindNodeMessage.h +++ b/src/DHTFindNodeMessage.h @@ -53,7 +53,7 @@ public: virtual void doReceivedAction() CXX11_OVERRIDE; - virtual std::shared_ptr<Dict> getArgument() CXX11_OVERRIDE; + virtual std::unique_ptr<Dict> getArgument() CXX11_OVERRIDE; virtual const std::string& getMessageType() const CXX11_OVERRIDE; diff --git a/src/DHTFindNodeReplyMessage.cc b/src/DHTFindNodeReplyMessage.cc index 8f2fcda7..45eded94 100644 --- a/src/DHTFindNodeReplyMessage.cc +++ b/src/DHTFindNodeReplyMessage.cc @@ -71,7 +71,7 @@ void DHTFindNodeReplyMessage::doReceivedAction() } } -std::shared_ptr<Dict> DHTFindNodeReplyMessage::getResponse() +std::unique_ptr<Dict> DHTFindNodeReplyMessage::getResponse() { auto aDict = Dict::g(); aDict->put(DHTMessage::ID, String::g(getLocalNode()->getID(), DHT_ID_LENGTH)); diff --git a/src/DHTFindNodeReplyMessage.h b/src/DHTFindNodeReplyMessage.h index 7f0b57b2..cee8c731 100644 --- a/src/DHTFindNodeReplyMessage.h +++ b/src/DHTFindNodeReplyMessage.h @@ -55,7 +55,7 @@ public: virtual void doReceivedAction() CXX11_OVERRIDE; - virtual std::shared_ptr<Dict> getResponse() CXX11_OVERRIDE; + virtual std::unique_ptr<Dict> getResponse() CXX11_OVERRIDE; virtual const std::string& getMessageType() const CXX11_OVERRIDE; diff --git a/src/DHTGetPeersMessage.cc b/src/DHTGetPeersMessage.cc index 13abd754..42a380fa 100644 --- a/src/DHTGetPeersMessage.cc +++ b/src/DHTGetPeersMessage.cc @@ -80,7 +80,7 @@ void DHTGetPeersMessage::doReceivedAction() getTransactionID())); } -std::shared_ptr<Dict> DHTGetPeersMessage::getArgument() +std::unique_ptr<Dict> DHTGetPeersMessage::getArgument() { auto aDict = Dict::g(); aDict->put(DHTMessage::ID, String::g(getLocalNode()->getID(), DHT_ID_LENGTH)); diff --git a/src/DHTGetPeersMessage.h b/src/DHTGetPeersMessage.h index 66fce078..a35e6e47 100644 --- a/src/DHTGetPeersMessage.h +++ b/src/DHTGetPeersMessage.h @@ -61,7 +61,7 @@ public: virtual void doReceivedAction() CXX11_OVERRIDE; - virtual std::shared_ptr<Dict> getArgument() CXX11_OVERRIDE; + virtual std::unique_ptr<Dict> getArgument() CXX11_OVERRIDE; virtual const std::string& getMessageType() const CXX11_OVERRIDE; diff --git a/src/DHTGetPeersReplyMessage.cc b/src/DHTGetPeersReplyMessage.cc index c88fd5cb..1366696a 100644 --- a/src/DHTGetPeersReplyMessage.cc +++ b/src/DHTGetPeersReplyMessage.cc @@ -75,7 +75,7 @@ void DHTGetPeersReplyMessage::doReceivedAction() // Returned peers and nodes are handled in DHTPeerLookupTask. } -std::shared_ptr<Dict> DHTGetPeersReplyMessage::getResponse() +std::unique_ptr<Dict> DHTGetPeersReplyMessage::getResponse() { auto rDict = Dict::g(); rDict->put(DHTMessage::ID, String::g(getLocalNode()->getID(), DHT_ID_LENGTH)); @@ -136,7 +136,7 @@ std::shared_ptr<Dict> DHTGetPeersReplyMessage::getResponse() valuesList->append(String::g(compact, compactlen)); } } - rDict->put(VALUES, valuesList); + rDict->put(VALUES, std::move(valuesList)); } return rDict; } diff --git a/src/DHTGetPeersReplyMessage.h b/src/DHTGetPeersReplyMessage.h index 3b2c5a99..739bd9ed 100644 --- a/src/DHTGetPeersReplyMessage.h +++ b/src/DHTGetPeersReplyMessage.h @@ -65,7 +65,7 @@ public: virtual void doReceivedAction() CXX11_OVERRIDE; - virtual std::shared_ptr<Dict> getResponse() CXX11_OVERRIDE; + virtual std::unique_ptr<Dict> getResponse() CXX11_OVERRIDE; virtual const std::string& getMessageType() const CXX11_OVERRIDE; diff --git a/src/DHTPingMessage.cc b/src/DHTPingMessage.cc index bf7d97b5..6f718b74 100644 --- a/src/DHTPingMessage.cc +++ b/src/DHTPingMessage.cc @@ -57,7 +57,7 @@ void DHTPingMessage::doReceivedAction() (getRemoteNode(), getLocalNode()->getID(), getTransactionID())); } -std::shared_ptr<Dict> DHTPingMessage::getArgument() +std::unique_ptr<Dict> DHTPingMessage::getArgument() { auto aDict = Dict::g(); aDict->put(DHTMessage::ID, String::g(getLocalNode()->getID(), DHT_ID_LENGTH)); diff --git a/src/DHTPingMessage.h b/src/DHTPingMessage.h index b5be6b3d..e96f5d9d 100644 --- a/src/DHTPingMessage.h +++ b/src/DHTPingMessage.h @@ -48,7 +48,7 @@ public: virtual void doReceivedAction() CXX11_OVERRIDE; - virtual std::shared_ptr<Dict> getArgument() CXX11_OVERRIDE; + virtual std::unique_ptr<Dict> getArgument() CXX11_OVERRIDE; virtual const std::string& getMessageType() const CXX11_OVERRIDE; diff --git a/src/DHTPingReplyMessage.cc b/src/DHTPingReplyMessage.cc index a7b3129c..38630dac 100644 --- a/src/DHTPingReplyMessage.cc +++ b/src/DHTPingReplyMessage.cc @@ -55,7 +55,7 @@ DHTPingReplyMessage::DHTPingReplyMessage void DHTPingReplyMessage::doReceivedAction() {} -std::shared_ptr<Dict> DHTPingReplyMessage::getResponse() +std::unique_ptr<Dict> DHTPingReplyMessage::getResponse() { auto rDict = Dict::g(); rDict->put(DHTMessage::ID, String::g(id_, DHT_ID_LENGTH)); diff --git a/src/DHTPingReplyMessage.h b/src/DHTPingReplyMessage.h index 71494e94..0169315f 100644 --- a/src/DHTPingReplyMessage.h +++ b/src/DHTPingReplyMessage.h @@ -51,7 +51,7 @@ public: virtual void doReceivedAction() CXX11_OVERRIDE; - virtual std::shared_ptr<Dict> getResponse() CXX11_OVERRIDE; + virtual std::unique_ptr<Dict> getResponse() CXX11_OVERRIDE; virtual const std::string& getMessageType() const CXX11_OVERRIDE; diff --git a/src/DHTQueryMessage.h b/src/DHTQueryMessage.h index e85067a1..bb8e1a92 100644 --- a/src/DHTQueryMessage.h +++ b/src/DHTQueryMessage.h @@ -55,7 +55,7 @@ public: virtual void fillMessage(Dict* msgDict) CXX11_OVERRIDE; - virtual std::shared_ptr<Dict> getArgument() = 0; + virtual std::unique_ptr<Dict> getArgument() = 0; virtual bool isReply() const CXX11_OVERRIDE; diff --git a/src/DHTResponseMessage.h b/src/DHTResponseMessage.h index 495fff2c..f42c3be0 100644 --- a/src/DHTResponseMessage.h +++ b/src/DHTResponseMessage.h @@ -57,7 +57,7 @@ public: virtual void fillMessage(Dict* msgDict) CXX11_OVERRIDE; - virtual std::shared_ptr<Dict> getResponse() = 0; + virtual std::unique_ptr<Dict> getResponse() = 0; virtual bool isReply() const CXX11_OVERRIDE; diff --git a/src/DefaultBtAnnounce.cc b/src/DefaultBtAnnounce.cc index b7f22c2e..af1630ca 100644 --- a/src/DefaultBtAnnounce.cc +++ b/src/DefaultBtAnnounce.cc @@ -283,8 +283,7 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse, size_t trackerResponseLength) { A2_LOG_DEBUG("Now processing tracker response."); - std::shared_ptr<ValueBase> decodedValue = - bencode2::decode(trackerResponse, trackerResponseLength); + auto decodedValue = bencode2::decode(trackerResponse, trackerResponseLength); const Dict* dict = downcast<Dict>(decodedValue); if(!dict) { throw DL_ABORT_EX(MSG_NULL_TRACKER_RESPONSE); @@ -327,7 +326,7 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse, incomplete_ = incomp->i(); A2_LOG_DEBUG(fmt("Incomplete:%d", incomplete_)); } - const std::shared_ptr<ValueBase>& peerData = dict->get(BtAnnounce::PEERS); + auto peerData = dict->get(BtAnnounce::PEERS); if(!peerData) { A2_LOG_INFO(MSG_NO_PEER_LIST_RECEIVED); } else { @@ -337,7 +336,7 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse, peerStorage_->addPeer(peers); } } - const std::shared_ptr<ValueBase>& peer6Data = dict->get(BtAnnounce::PEERS6); + auto peer6Data = dict->get(BtAnnounce::PEERS6); if(!peer6Data) { A2_LOG_INFO("No peers6 received."); } else { diff --git a/src/GenericParser.h b/src/GenericParser.h index 1870328a..60f4e86d 100644 --- a/src/GenericParser.h +++ b/src/GenericParser.h @@ -45,7 +45,7 @@ template<typename Parser, typename ParserStateMachine> class GenericParser { public: GenericParser() - : parser_(&psm_) + : parser_{&psm_} {} ~GenericParser() diff --git a/src/HandshakeExtensionMessage.cc b/src/HandshakeExtensionMessage.cc index b31ef418..c4944219 100644 --- a/src/HandshakeExtensionMessage.cc +++ b/src/HandshakeExtensionMessage.cc @@ -64,14 +64,14 @@ std::string HandshakeExtensionMessage::getPayload() if(tcpPort_ > 0) { dict.put("p", Integer::g(tcpPort_)); } - std::shared_ptr<Dict> extDict = Dict::g(); + auto extDict = Dict::g(); for(int i = 0; i < ExtensionMessageRegistry::MAX_EXTENSION; ++i) { int id = extreg_.getExtensionMessageID(i); if(id) { extDict->put(strBtExtension(i), Integer::g(id)); } } - dict.put("m", extDict); + dict.put("m", std::move(extDict)); if(metadataSize_) { dict.put("metadata_size", Integer::g(metadataSize_)); } diff --git a/src/HttpServerBodyCommand.cc b/src/HttpServerBodyCommand.cc index 13e327be..67d660db 100644 --- a/src/HttpServerBodyCommand.cc +++ b/src/HttpServerBodyCommand.cc @@ -226,10 +226,9 @@ bool HttpServerBodyCommand::execute() addHttpServerResponseCommand(); return true; } - std::shared_ptr<rpc::RpcMethod> method = - rpc::RpcMethodFactory::create(req.methodName); + auto method = rpc::RpcMethodFactory::create(req.methodName); A2_LOG_INFO(fmt("Executing RPC method %s", req.methodName.c_str())); - rpc::RpcResponse res = method->execute(req, e_); + rpc::RpcResponse res = method->execute(std::move(req), e_); bool gzip = httpServer_->supportsGZip(); std::string responseData = rpc::toXml(res, gzip); httpServer_->feedResponse(std::move(responseData), "text/xml"); @@ -243,7 +242,7 @@ bool HttpServerBodyCommand::execute() case RPC_TYPE_JSON: case RPC_TYPE_JSONP: { std::string callback; - std::shared_ptr<ValueBase> json; + std::unique_ptr<ValueBase> json; ssize_t error = 0; if(httpServer_->getRequestType() == RPC_TYPE_JSONP) { json::JsonGetParam param = json::decodeGetParams(query); @@ -272,22 +271,20 @@ bool HttpServerBodyCommand::execute() sendJsonRpcResponse(res, callback); return true; } - const Dict* jsondict = downcast<Dict>(json); + Dict* jsondict = downcast<Dict>(json); if(jsondict) { rpc::RpcResponse res = rpc::processJsonRpcRequest(jsondict, e_); sendJsonRpcResponse(res, callback); } else { - const List* jsonlist = downcast<List>(json); + List* jsonlist = downcast<List>(json); if(jsonlist) { // This is batch call std::vector<rpc::RpcResponse> results; for(List::ValueType::const_iterator i = jsonlist->begin(), eoi = jsonlist->end(); i != eoi; ++i) { - const Dict* jsondict = downcast<Dict>(*i); + Dict* jsondict = downcast<Dict>(*i); if(jsondict) { - rpc::RpcResponse r = - rpc::processJsonRpcRequest(jsondict, e_); - results.push_back(r); + results.push_back(rpc::processJsonRpcRequest(jsondict, e_)); } } sendJsonRpcBatchResponse(results, callback); diff --git a/src/HttpServerBodyCommand.h b/src/HttpServerBodyCommand.h index a3086353..7817c048 100644 --- a/src/HttpServerBodyCommand.h +++ b/src/HttpServerBodyCommand.h @@ -57,12 +57,6 @@ private: Timer timeoutTimer_; bool writeCheck_; - void sendJsonRpcErrorResponse - (const std::string& httpStatus, - int code, - const std::string& message, - const std::shared_ptr<ValueBase>& id, - const std::string& callback); void sendJsonRpcResponse (const rpc::RpcResponse& res, const std::string& callback); diff --git a/src/RpcMethod.cc b/src/RpcMethod.cc index 892ba87d..dc90bb1a 100644 --- a/src/RpcMethod.cc +++ b/src/RpcMethod.cc @@ -59,23 +59,22 @@ RpcMethod::RpcMethod() RpcMethod::~RpcMethod() {} -std::shared_ptr<ValueBase> RpcMethod::createErrorResponse +std::unique_ptr<ValueBase> RpcMethod::createErrorResponse (const Exception& e, const RpcRequest& req) { - std::shared_ptr<Dict> params = Dict::g(); + auto params = Dict::g(); params->put((req.jsonRpc ? "code" : "faultCode"), Integer::g(1)); params->put((req.jsonRpc ? "message" : "faultString"), std::string(e.what())); - return params; + return std::move(params); } -RpcResponse RpcMethod::execute -(const RpcRequest& req, DownloadEngine* e) +RpcResponse RpcMethod::execute(RpcRequest req, DownloadEngine* e) { try { - return RpcResponse(0, process(req, e), req.id); + return RpcResponse(0, process(req, e), std::move(req.id)); } catch(RecoverableException& ex) { A2_LOG_DEBUG_EX(EX_EXCEPTION_CAUGHT, ex); - return RpcResponse(1, createErrorResponse(ex, req), req.id); + return RpcResponse(1, createErrorResponse(ex, req), std::move(req.id)); } } diff --git a/src/RpcMethod.h b/src/RpcMethod.h index 7f610731..a710aab4 100644 --- a/src/RpcMethod.h +++ b/src/RpcMethod.h @@ -69,7 +69,7 @@ protected: // Subclass must implement this function to fulfil RpcRequest req. // The return value of this method is used as a return value of RPC // request. - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) = 0; void gatherRequestOption(Option* option, const Dict* optionsDict); @@ -81,7 +81,7 @@ protected: void gatherChangeableGlobalOption(Option* option, const Dict* optionDict); - std::shared_ptr<ValueBase> createErrorResponse + std::unique_ptr<ValueBase> createErrorResponse (const Exception& e, const RpcRequest& req); const std::shared_ptr<OptionParser>& getOptionParser() const @@ -95,7 +95,7 @@ public: // Do work to fulfill RpcRequest req and returns its result as // RpcResponse. This method delegates to process() method. - RpcResponse execute(const RpcRequest& req, DownloadEngine* e); + RpcResponse execute(RpcRequest req, DownloadEngine* e); }; } // namespace rpc diff --git a/src/RpcMethodImpl.cc b/src/RpcMethodImpl.cc index 53ddf1ea..1edccd63 100644 --- a/src/RpcMethodImpl.cc +++ b/src/RpcMethodImpl.cc @@ -83,17 +83,17 @@ namespace aria2 { namespace rpc { namespace { -const std::shared_ptr<String> VLB_TRUE = String::g("true"); -const std::shared_ptr<String> VLB_FALSE = String::g("false"); -const std::shared_ptr<String> VLB_OK = String::g("OK"); -const std::shared_ptr<String> VLB_ACTIVE = String::g("active"); -const std::shared_ptr<String> VLB_WAITING = String::g("waiting"); -const std::shared_ptr<String> VLB_PAUSED = String::g("paused"); -const std::shared_ptr<String> VLB_REMOVED = String::g("removed"); -const std::shared_ptr<String> VLB_ERROR = String::g("error"); -const std::shared_ptr<String> VLB_COMPLETE = String::g("complete"); -const std::shared_ptr<String> VLB_USED = String::g("used"); -const std::shared_ptr<String> VLB_ZERO = String::g("0"); +const char VLB_TRUE[] = "true"; +const char VLB_FALSE[] = "false"; +const char VLB_OK[] = "OK"; +const char VLB_ACTIVE[] = "active"; +const char VLB_WAITING[] = "waiting"; +const char VLB_PAUSED[] = "paused"; +const char VLB_REMOVED[] = "removed"; +const char VLB_ERROR[] = "error"; +const char VLB_COMPLETE[] = "complete"; +const char VLB_USED[] = "used"; +const char VLB_ZERO[] = "0"; const std::string KEY_GID = "gid"; const std::string KEY_ERROR_CODE = "errorCode"; @@ -145,14 +145,21 @@ const std::string KEY_NUM_ACTIVE = "numActive"; } // namespace namespace { -std::shared_ptr<ValueBase> createGIDResponse(a2_gid_t gid) +std::unique_ptr<ValueBase> createGIDResponse(a2_gid_t gid) { return String::g(GroupId::toHex(gid)); } } // namespace namespace { -std::shared_ptr<ValueBase> +std::unique_ptr<ValueBase> createOKResponse() +{ + return String::g("OK"); +} +} // namespace + +namespace { +std::unique_ptr<ValueBase> addRequestGroup(const std::shared_ptr<RequestGroup>& group, DownloadEngine* e, bool posGiven, int pos) @@ -216,7 +223,7 @@ void extractUris(OutputIterator out, const List* src) } } // namespace -std::shared_ptr<ValueBase> AddUriRpcMethod::process +std::unique_ptr<ValueBase> AddUriRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const List* urisParam = checkRequiredParam<List>(req, 0); @@ -229,13 +236,13 @@ std::shared_ptr<ValueBase> AddUriRpcMethod::process throw DL_ABORT_EX("URI is not provided."); } - std::shared_ptr<Option> requestOption(new Option(*e->getOption())); + auto requestOption = std::make_shared<Option>(*e->getOption()); gatherRequestOption(requestOption.get(), optsParam); bool posGiven = checkPosParam(posParam); size_t pos = posGiven ? posParam->i() : 0; - std::vector<std::shared_ptr<RequestGroup> > result; + std::vector<std::shared_ptr<RequestGroup>> result; createRequestGroupForUri(result, requestOption, uris, /* ignoreForceSeq = */ true, /* ignoreLocalPath = */ true); @@ -260,7 +267,7 @@ std::string getHexSha1(const std::string& s) #endif // ENABLE_MESSAGE_DIGEST #ifdef ENABLE_BITTORRENT -std::shared_ptr<ValueBase> AddTorrentRpcMethod::process +std::unique_ptr<ValueBase> AddTorrentRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* torrentParam = checkRequiredParam<String>(req, 0); @@ -268,7 +275,7 @@ std::shared_ptr<ValueBase> AddTorrentRpcMethod::process const Dict* optsParam = checkParam<Dict>(req, 2); const Integer* posParam = checkParam<Integer>(req, 3); - std::shared_ptr<String> tempTorrentParam; + std::unique_ptr<String> tempTorrentParam; if(req.jsonRpc) { tempTorrentParam = String::g (base64::decode(torrentParam->s().begin(), @@ -278,7 +285,7 @@ std::shared_ptr<ValueBase> AddTorrentRpcMethod::process std::vector<std::string> uris; extractUris(std::back_inserter(uris), urisParam); - std::shared_ptr<Option> requestOption(new Option(*e->getOption())); + auto requestOption = std::make_shared<Option>(*e->getOption()); gatherRequestOption(requestOption.get(), optsParam); bool posGiven = checkPosParam(posParam); @@ -300,7 +307,7 @@ std::shared_ptr<ValueBase> AddTorrentRpcMethod::process filename.clear(); } } - std::vector<std::shared_ptr<RequestGroup> > result; + std::vector<std::shared_ptr<RequestGroup>> result; createRequestGroupForBitTorrent(result, requestOption, uris, filename, torrentParam->s()); @@ -313,27 +320,27 @@ std::shared_ptr<ValueBase> AddTorrentRpcMethod::process #endif // ENABLE_BITTORRENT #ifdef ENABLE_METALINK -std::shared_ptr<ValueBase> AddMetalinkRpcMethod::process +std::unique_ptr<ValueBase> AddMetalinkRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* metalinkParam = checkRequiredParam<String>(req, 0); const Dict* optsParam = checkParam<Dict>(req, 1); const Integer* posParam = checkParam<Integer>(req, 2); - std::shared_ptr<String> tempMetalinkParam; + std::unique_ptr<String> tempMetalinkParam; if(req.jsonRpc) { tempMetalinkParam = String::g (base64::decode(metalinkParam->s().begin(), metalinkParam->s().end())); metalinkParam = tempMetalinkParam.get(); } - std::shared_ptr<Option> requestOption(new Option(*e->getOption())); + auto requestOption = std::make_shared<Option>(*e->getOption()); gatherRequestOption(requestOption.get(), optsParam); bool posGiven = checkPosParam(posParam); size_t pos = posGiven ? posParam->i() : 0; - std::vector<std::shared_ptr<RequestGroup> > result; + std::vector<std::shared_ptr<RequestGroup>> result; #ifdef ENABLE_MESSAGE_DIGEST std::string filename; if(requestOption->getAsBool(PREF_RPC_SAVE_UPLOAD_METADATA)) { @@ -361,30 +368,29 @@ std::shared_ptr<ValueBase> AddMetalinkRpcMethod::process #else // !ENABLE_MESSAGE_DIGEST createRequestGroupForMetalink(result, requestOption, metalinkParam->s()); #endif // !ENABLE_MESSAGE_DIGEST - std::shared_ptr<List> gids = List::g(); + auto gids = List::g(); if(!result.empty()) { if(posGiven) { e->getRequestGroupMan()->insertReservedGroup(pos, result); } else { e->getRequestGroupMan()->addReservedGroup(result); } - for(std::vector<std::shared_ptr<RequestGroup> >::const_iterator i = - result.begin(), eoi = result.end(); i != eoi; ++i) { - gids->append(GroupId::toHex((*i)->getGID())); + for(auto& i : result) { + gids->append(GroupId::toHex(i->getGID())); } } - return gids; + return std::move(gids); } #endif // ENABLE_METALINK namespace { -std::shared_ptr<ValueBase> removeDownload +std::unique_ptr<ValueBase> removeDownload (const RpcRequest& req, DownloadEngine* e, bool forceRemove) { const String* gidParam = checkRequiredParam<String>(req, 0); a2_gid_t gid = str2Gid(gidParam); - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); + auto group = e->getRequestGroupMan()->findGroup(gid); if(group) { if(group->getState() == RequestGroup::STATE_ACTIVE) { if(forceRemove) { @@ -409,26 +415,26 @@ std::shared_ptr<ValueBase> removeDownload } } // namespace -std::shared_ptr<ValueBase> RemoveRpcMethod::process +std::unique_ptr<ValueBase> RemoveRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { return removeDownload(req, e, false); } -std::shared_ptr<ValueBase> ForceRemoveRpcMethod::process +std::unique_ptr<ValueBase> ForceRemoveRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { return removeDownload(req, e, true); } namespace { -std::shared_ptr<ValueBase> pauseDownload +std::unique_ptr<ValueBase> pauseDownload (const RpcRequest& req, DownloadEngine* e, bool forcePause) { const String* gidParam = checkRequiredParam<String>(req, 0); a2_gid_t gid = str2Gid(gidParam); - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); + auto group = e->getRequestGroupMan()->findGroup(gid); if(group) { bool reserved = group->getState() == RequestGroup::STATE_WAITING; if(pauseRequestGroup(group, reserved, forcePause)) { @@ -441,13 +447,13 @@ std::shared_ptr<ValueBase> pauseDownload } } // namespace -std::shared_ptr<ValueBase> PauseRpcMethod::process +std::unique_ptr<ValueBase> PauseRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { return pauseDownload(req, e, false); } -std::shared_ptr<ValueBase> ForcePauseRpcMethod::process +std::unique_ptr<ValueBase> ForcePauseRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { return pauseDownload(req, e, true); @@ -465,38 +471,37 @@ void pauseRequestGroups } // namespace namespace { -std::shared_ptr<ValueBase> pauseAllDownloads +std::unique_ptr<ValueBase> pauseAllDownloads (const RpcRequest& req, DownloadEngine* e, bool forcePause) { - const RequestGroupList& groups = e->getRequestGroupMan()->getRequestGroups(); + auto& groups = e->getRequestGroupMan()->getRequestGroups(); pauseRequestGroups(groups.begin(), groups.end(), false, forcePause); - const RequestGroupList& reservedGroups = - e->getRequestGroupMan()->getReservedGroups(); + auto& reservedGroups = e->getRequestGroupMan()->getReservedGroups(); pauseRequestGroups(reservedGroups.begin(), reservedGroups.end(), true, forcePause); - return VLB_OK; + return createOKResponse(); } } // namespace -std::shared_ptr<ValueBase> PauseAllRpcMethod::process +std::unique_ptr<ValueBase> PauseAllRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { return pauseAllDownloads(req, e, false); } -std::shared_ptr<ValueBase> ForcePauseAllRpcMethod::process +std::unique_ptr<ValueBase> ForcePauseAllRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { return pauseAllDownloads(req, e, true); } -std::shared_ptr<ValueBase> UnpauseRpcMethod::process +std::unique_ptr<ValueBase> UnpauseRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); a2_gid_t gid = str2Gid(gidParam); - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); + auto group = e->getRequestGroupMan()->findGroup(gid); if(!group || group->getState() != RequestGroup::STATE_WAITING || !group->isPauseRequested()) { @@ -509,46 +514,44 @@ std::shared_ptr<ValueBase> UnpauseRpcMethod::process return createGIDResponse(gid); } -std::shared_ptr<ValueBase> UnpauseAllRpcMethod::process +std::unique_ptr<ValueBase> UnpauseAllRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { - const RequestGroupList& groups = - e->getRequestGroupMan()->getReservedGroups(); - for(RequestGroupList::const_iterator i = groups.begin(), - eoi = groups.end(); i != eoi; ++i) { - (*i)->setPauseRequested(false); + auto& groups = e->getRequestGroupMan()->getReservedGroups(); + for(auto& group : groups) { + group->setPauseRequested(false); } e->getRequestGroupMan()->requestQueueCheck(); - return VLB_OK; + return createOKResponse(); } namespace { template<typename InputIterator> void createUriEntry -(const std::shared_ptr<List>& uriList, +(List* uriList, InputIterator first, InputIterator last, - const std::shared_ptr<String>& status) + const std::string& status) { for(; first != last; ++first) { - std::shared_ptr<Dict> entry = Dict::g(); + auto entry = Dict::g(); entry->put(KEY_URI, *first); entry->put(KEY_STATUS, status); - uriList->append(entry); + uriList->append(std::move(entry)); } } } // namespace namespace { void createUriEntry -(const std::shared_ptr<List>& uriList, const std::shared_ptr<FileEntry>& file) +(List* uriList, const std::shared_ptr<FileEntry>& file) { createUriEntry(uriList, - file->getSpentUris().begin(), - file->getSpentUris().end(), + std::begin(file->getSpentUris()), + std::end(file->getSpentUris()), VLB_USED); createUriEntry(uriList, - file->getRemainingUris().begin(), - file->getRemainingUris().end(), + std::begin(file->getRemainingUris()), + std::end(file->getRemainingUris()), VLB_WAITING); } } // namespace @@ -556,13 +559,13 @@ void createUriEntry namespace { template<typename InputIterator> void createFileEntry -(const std::shared_ptr<List>& files, +(List* files, InputIterator first, InputIterator last, const BitfieldMan* bf) { size_t index = 1; for(; first != last; ++first, ++index) { - std::shared_ptr<Dict> entry = Dict::g(); + auto entry = Dict::g(); entry->put(KEY_INDEX, util::uitos(index)); entry->put(KEY_PATH, (*first)->getPath()); entry->put(KEY_SELECTED, (*first)->isRequested()?VLB_TRUE:VLB_FALSE); @@ -571,10 +574,10 @@ void createFileEntry ((*first)->getOffset(), (*first)->getLength()); entry->put(KEY_COMPLETED_LENGTH, util::itos(completedLength)); - std::shared_ptr<List> uriList = List::g(); - createUriEntry(uriList, *first); - entry->put(KEY_URIS, uriList); - files->append(entry); + auto uriList = List::g(); + createUriEntry(uriList.get(), *first); + entry->put(KEY_URIS, std::move(uriList)); + files->append(std::move(entry)); } } } // namespace @@ -582,7 +585,7 @@ void createFileEntry namespace { template<typename InputIterator> void createFileEntry -(const std::shared_ptr<List>& files, +(List* files, InputIterator first, InputIterator last, int64_t totalLength, int32_t pieceLength, @@ -598,7 +601,7 @@ void createFileEntry namespace { template<typename InputIterator> void createFileEntry -(const std::shared_ptr<List>& files, +(List* files, InputIterator first, InputIterator last, int64_t totalLength, int32_t pieceLength, @@ -621,11 +624,11 @@ bool requested_key } // namespace void gatherProgressCommon -(const std::shared_ptr<Dict>& entryDict, +(Dict* entryDict, const std::shared_ptr<RequestGroup>& group, const std::vector<std::string>& keys) { - const std::shared_ptr<PieceStorage>& ps = group->getPieceStorage(); + auto& ps = group->getPieceStorage(); if(requested_key(keys, KEY_GID)) { entryDict->put(KEY_GID, GroupId::toHex(group->getGID()).c_str()); } @@ -660,7 +663,7 @@ void gatherProgressCommon } } } - const std::shared_ptr<DownloadContext>& dctx = group->getDownloadContext(); + auto& dctx = group->getDownloadContext(); if(requested_key(keys, KEY_PIECE_LENGTH)) { entryDict->put(KEY_PIECE_LENGTH, util::itos(dctx->getPieceLength())); } @@ -669,13 +672,12 @@ void gatherProgressCommon } if(requested_key(keys, KEY_FOLLOWED_BY)) { if(!group->followedBy().empty()) { - std::shared_ptr<List> list = List::g(); + auto list = List::g(); // The element is GID. - for(std::vector<a2_gid_t>::const_iterator i = group->followedBy().begin(), - eoi = group->followedBy().end(); i != eoi; ++i) { - list->append(GroupId::toHex(*i)); + for(auto& gid : group->followedBy()) { + list->append(GroupId::toHex(gid)); } - entryDict->put(KEY_FOLLOWED_BY, list); + entryDict->put(KEY_FOLLOWED_BY, std::move(list)); } } if(requested_key(keys, KEY_BELONGS_TO)) { @@ -684,11 +686,12 @@ void gatherProgressCommon } } if(requested_key(keys, KEY_FILES)) { - std::shared_ptr<List> files = List::g(); + auto files = List::g(); createFileEntry - (files, dctx->getFileEntries().begin(), dctx->getFileEntries().end(), + (files.get(), + std::begin(dctx->getFileEntries()), std::end(dctx->getFileEntries()), dctx->getTotalLength(), dctx->getPieceLength(), ps); - entryDict->put(KEY_FILES, files); + entryDict->put(KEY_FILES, std::move(files)); } if(requested_key(keys, KEY_DIR)) { entryDict->put(KEY_DIR, group->getOption()->get(PREF_DIR)); @@ -697,7 +700,7 @@ void gatherProgressCommon #ifdef ENABLE_BITTORRENT void gatherBitTorrentMetadata -(const std::shared_ptr<Dict>& btDict, TorrentAttribute* torrentAttrs) +(Dict* btDict, TorrentAttribute* torrentAttrs) { if(!torrentAttrs->comment.empty()) { btDict->put(KEY_COMMENT, torrentAttrs->comment); @@ -708,28 +711,25 @@ void gatherBitTorrentMetadata if(torrentAttrs->mode) { btDict->put(KEY_MODE, bittorrent::getModeString(torrentAttrs->mode)); } - std::shared_ptr<List> destAnnounceList = List::g(); - for(std::vector<std::vector<std::string> >::const_iterator l = - torrentAttrs->announceList.begin(), - eoi = torrentAttrs->announceList.end(); l != eoi; ++l) { - std::shared_ptr<List> destAnnounceTier = List::g(); - for(std::vector<std::string>::const_iterator t = (*l).begin(), - eoi2 = (*l).end(); t != eoi2; ++t) { - destAnnounceTier->append(*t); + auto destAnnounceList = List::g(); + for(auto& annlist : torrentAttrs->announceList) { + auto destAnnounceTier = List::g(); + for(auto& ann : annlist) { + destAnnounceTier->append(ann); } - destAnnounceList->append(destAnnounceTier); + destAnnounceList->append(std::move(destAnnounceTier)); } - btDict->put(KEY_ANNOUNCE_LIST, destAnnounceList); + btDict->put(KEY_ANNOUNCE_LIST, std::move(destAnnounceList)); if(!torrentAttrs->metadata.empty()) { - std::shared_ptr<Dict> infoDict = Dict::g(); + auto infoDict = Dict::g(); infoDict->put(KEY_NAME, torrentAttrs->name); - btDict->put(KEY_INFO, infoDict); + btDict->put(KEY_INFO, std::move(infoDict)); } } namespace { void gatherProgressBitTorrent -(const std::shared_ptr<Dict>& entryDict, +(Dict* entryDict, TorrentAttribute* torrentAttrs, BtObject* btObject, const std::vector<std::string>& keys) @@ -738,17 +738,17 @@ void gatherProgressBitTorrent entryDict->put(KEY_INFO_HASH, util::toHex(torrentAttrs->infoHash)); } if(requested_key(keys, KEY_BITTORRENT)) { - std::shared_ptr<Dict> btDict = Dict::g(); - gatherBitTorrentMetadata(btDict, torrentAttrs); - entryDict->put(KEY_BITTORRENT, btDict); + auto btDict = Dict::g(); + gatherBitTorrentMetadata(btDict.get(), torrentAttrs); + entryDict->put(KEY_BITTORRENT, std::move(btDict)); } if(requested_key(keys, KEY_NUM_SEEDERS)) { if(!btObject) { entryDict->put(KEY_NUM_SEEDERS, VLB_ZERO); } else { - const std::shared_ptr<PeerStorage>& peerStorage = btObject->peerStorage; + auto& peerStorage = btObject->peerStorage; assert(peerStorage); - const PeerSet& peers = peerStorage->getUsedPeers(); + auto& peers = peerStorage->getUsedPeers(); entryDict->put(KEY_NUM_SEEDERS, util::uitos(countSeeder(peers.begin(), peers.end()))); } @@ -758,33 +758,32 @@ void gatherProgressBitTorrent namespace { void gatherPeer -(const std::shared_ptr<List>& peers, const std::shared_ptr<PeerStorage>& ps) +(List* peers, const std::shared_ptr<PeerStorage>& ps) { - const PeerSet& usedPeers = ps->getUsedPeers(); - for(PeerSet::const_iterator i = usedPeers.begin(), eoi = usedPeers.end(); - i != eoi; ++i) { - if(!(*i)->isActive()) { + auto& usedPeers = ps->getUsedPeers(); + for(auto& peer : usedPeers) { + if(!peer->isActive()) { continue; } - std::shared_ptr<Dict> peerEntry = Dict::g(); - peerEntry->put(KEY_PEER_ID, util::torrentPercentEncode((*i)->getPeerId(), + auto peerEntry = Dict::g(); + peerEntry->put(KEY_PEER_ID, util::torrentPercentEncode(peer->getPeerId(), PEER_ID_LENGTH)); - peerEntry->put(KEY_IP, (*i)->getIPAddress()); - if((*i)->isIncomingPeer()) { + peerEntry->put(KEY_IP, peer->getIPAddress()); + if(peer->isIncomingPeer()) { peerEntry->put(KEY_PORT, VLB_ZERO); } else { - peerEntry->put(KEY_PORT, util::uitos((*i)->getPort())); + peerEntry->put(KEY_PORT, util::uitos(peer->getPort())); } peerEntry->put(KEY_BITFIELD, - util::toHex((*i)->getBitfield(), (*i)->getBitfieldLength())); - peerEntry->put(KEY_AM_CHOKING, (*i)->amChoking()?VLB_TRUE:VLB_FALSE); - peerEntry->put(KEY_PEER_CHOKING, (*i)->peerChoking()?VLB_TRUE:VLB_FALSE); + util::toHex(peer->getBitfield(), peer->getBitfieldLength())); + peerEntry->put(KEY_AM_CHOKING, peer->amChoking()?VLB_TRUE:VLB_FALSE); + peerEntry->put(KEY_PEER_CHOKING, peer->peerChoking()?VLB_TRUE:VLB_FALSE); peerEntry->put(KEY_DOWNLOAD_SPEED, - util::itos((*i)->calculateDownloadSpeed())); + util::itos(peer->calculateDownloadSpeed())); peerEntry->put(KEY_UPLOAD_SPEED, - util::itos((*i)->calculateUploadSpeed())); - peerEntry->put(KEY_SEEDER, (*i)->isSeeder()?VLB_TRUE:VLB_FALSE); - peers->append(peerEntry); + util::itos(peer->calculateUploadSpeed())); + peerEntry->put(KEY_SEEDER, peer->isSeeder()?VLB_TRUE:VLB_FALSE); + peers->append(std::move(peerEntry)); } } } // namespace @@ -792,7 +791,7 @@ void gatherPeer namespace { void gatherProgress -(const std::shared_ptr<Dict>& entryDict, +(Dict* entryDict, const std::shared_ptr<RequestGroup>& group, DownloadEngine* e, const std::vector<std::string>& keys) @@ -811,7 +810,7 @@ void gatherProgress } // namespace void gatherStoppedDownload -(const std::shared_ptr<Dict>& entryDict, const std::shared_ptr<DownloadResult>& ds, +(Dict* entryDict, const std::shared_ptr<DownloadResult>& ds, const std::vector<std::string>& keys) { if(requested_key(keys, KEY_GID)) { @@ -831,13 +830,12 @@ void gatherStoppedDownload } if(requested_key(keys, KEY_FOLLOWED_BY)) { if(!ds->followedBy.empty()) { - std::shared_ptr<List> list = List::g(); + auto list = List::g(); // The element is GID. - for(std::vector<a2_gid_t>::const_iterator i = ds->followedBy.begin(), - eoi = ds->followedBy.end(); i != eoi; ++i) { - list->append(GroupId::toHex(*i)); + for(auto gid : ds->followedBy) { + list->append(GroupId::toHex(gid)); } - entryDict->put(KEY_FOLLOWED_BY, list); + entryDict->put(KEY_FOLLOWED_BY, std::move(list)); } } if(requested_key(keys, KEY_BELONGS_TO)) { @@ -846,10 +844,11 @@ void gatherStoppedDownload } } if(requested_key(keys, KEY_FILES)) { - std::shared_ptr<List> files = List::g(); - createFileEntry(files, ds->fileEntries.begin(), ds->fileEntries.end(), + auto files = List::g(); + createFileEntry(files.get(), + std::begin(ds->fileEntries), std::end(ds->fileEntries), ds->totalLength, ds->pieceLength, ds->bitfield); - entryDict->put(KEY_FILES, files); + entryDict->put(KEY_FILES, std::move(files)); } if(requested_key(keys, KEY_TOTAL_LENGTH)) { entryDict->put(KEY_TOTAL_LENGTH, util::itos(ds->totalLength)); @@ -893,79 +892,80 @@ void gatherStoppedDownload } } -std::shared_ptr<ValueBase> GetFilesRpcMethod::process +std::unique_ptr<ValueBase> GetFilesRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); a2_gid_t gid = str2Gid(gidParam); - std::shared_ptr<List> files = List::g(); - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); + auto files = List::g(); + auto group = e->getRequestGroupMan()->findGroup(gid); if(!group) { - std::shared_ptr<DownloadResult> dr = - e->getRequestGroupMan()->findDownloadResult(gid); + auto dr = e->getRequestGroupMan()->findDownloadResult(gid); if(!dr) { throw DL_ABORT_EX(fmt("No file data is available for GID#%s", GroupId::toHex(gid).c_str())); } else { - createFileEntry(files, dr->fileEntries.begin(), dr->fileEntries.end(), + createFileEntry(files.get(), + std::begin(dr->fileEntries), + std::end(dr->fileEntries), dr->totalLength, dr->pieceLength, dr->bitfield); } } else { - const std::shared_ptr<PieceStorage>& ps = group->getPieceStorage(); - const std::shared_ptr<DownloadContext>& dctx = group->getDownloadContext(); - createFileEntry(files, - group->getDownloadContext()->getFileEntries().begin(), - group->getDownloadContext()->getFileEntries().end(), + auto& dctx = group->getDownloadContext(); + createFileEntry(files.get(), + std::begin(group->getDownloadContext()->getFileEntries()), + std::end(group->getDownloadContext()->getFileEntries()), dctx->getTotalLength(), dctx->getPieceLength(), - ps); + group->getPieceStorage()); } - return files; + return std::move(files); } -std::shared_ptr<ValueBase> GetUrisRpcMethod::process +std::unique_ptr<ValueBase> GetUrisRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); a2_gid_t gid = str2Gid(gidParam); - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); + auto group = e->getRequestGroupMan()->findGroup(gid); if(!group) { throw DL_ABORT_EX(fmt("No URI data is available for GID#%s", GroupId::toHex(gid).c_str())); } - std::shared_ptr<List> uriList = List::g(); + auto uriList = List::g(); // TODO Current implementation just returns first FileEntry's URIs. if(!group->getDownloadContext()->getFileEntries().empty()) { - createUriEntry(uriList, group->getDownloadContext()->getFirstFileEntry()); + createUriEntry(uriList.get(), + group->getDownloadContext()->getFirstFileEntry()); } - return uriList; + return std::move(uriList); } #ifdef ENABLE_BITTORRENT -std::shared_ptr<ValueBase> GetPeersRpcMethod::process +std::unique_ptr<ValueBase> GetPeersRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); a2_gid_t gid = str2Gid(gidParam); - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); + auto group = e->getRequestGroupMan()->findGroup(gid); if(!group) { throw DL_ABORT_EX(fmt("No peer data is available for GID#%s", GroupId::toHex(gid).c_str())); } - std::shared_ptr<List> peers = List::g(); + auto peers = List::g(); auto btObject = e->getBtRegistry()->get(group->getGID()); if(btObject) { assert(btObject->peerStorage); - gatherPeer(peers, btObject->peerStorage); + gatherPeer(peers.get(), btObject->peerStorage); } - return peers; + return std::move(peers); } #endif // ENABLE_BITTORRENT -std::shared_ptr<ValueBase> TellStatusRpcMethod::process +std::unique_ptr<ValueBase> TellStatusRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); @@ -975,17 +975,15 @@ std::shared_ptr<ValueBase> TellStatusRpcMethod::process std::vector<std::string> keys; toStringList(std::back_inserter(keys), keysParam); - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); - - std::shared_ptr<Dict> entryDict = Dict::g(); + auto group = e->getRequestGroupMan()->findGroup(gid); + auto entryDict = Dict::g(); if(!group) { - std::shared_ptr<DownloadResult> ds = - e->getRequestGroupMan()->findDownloadResult(gid); + auto ds = e->getRequestGroupMan()->findDownloadResult(gid); if(!ds) { throw DL_ABORT_EX(fmt("No such download for GID#%s", GroupId::toHex(gid).c_str())); } - gatherStoppedDownload(entryDict, ds, keys); + gatherStoppedDownload(entryDict.get(), ds, keys); } else { if(requested_key(keys, KEY_STATUS)) { if(group->getState() == RequestGroup::STATE_ACTIVE) { @@ -998,29 +996,28 @@ std::shared_ptr<ValueBase> TellStatusRpcMethod::process } } } - gatherProgress(entryDict, group, e, keys); + gatherProgress(entryDict.get(), group, e, keys); } - return entryDict; + return std::move(entryDict); } -std::shared_ptr<ValueBase> TellActiveRpcMethod::process +std::unique_ptr<ValueBase> TellActiveRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const List* keysParam = checkParam<List>(req, 0); std::vector<std::string> keys; toStringList(std::back_inserter(keys), keysParam); - std::shared_ptr<List> list = List::g(); - const RequestGroupList& groups = e->getRequestGroupMan()->getRequestGroups(); - for(RequestGroupList::const_iterator i = groups.begin(), - eoi = groups.end(); i != eoi; ++i) { - std::shared_ptr<Dict> entryDict = Dict::g(); - if(requested_key(keys, KEY_STATUS)) { + auto list = List::g(); + bool statusReq = requested_key(keys, KEY_STATUS); + for(auto& group : e->getRequestGroupMan()->getRequestGroups()) { + auto entryDict = Dict::g(); + if(statusReq) { entryDict->put(KEY_STATUS, VLB_ACTIVE); } - gatherProgress(entryDict, *i, e, keys); - list->append(entryDict); + gatherProgress(entryDict.get(), group, e, keys); + list->append(std::move(entryDict)); } - return list; + return std::move(list); } const RequestGroupList& @@ -1030,7 +1027,7 @@ TellWaitingRpcMethod::getItems(DownloadEngine* e) const } void TellWaitingRpcMethod::createEntry -(const std::shared_ptr<Dict>& entryDict, +(Dict* entryDict, const std::shared_ptr<RequestGroup>& item, DownloadEngine* e, const std::vector<std::string>& keys) const @@ -1052,7 +1049,7 @@ TellStoppedRpcMethod::getItems(DownloadEngine* e) const } void TellStoppedRpcMethod::createEntry -(const std::shared_ptr<Dict>& entryDict, +(Dict* entryDict, const std::shared_ptr<DownloadResult>& item, DownloadEngine* e, const std::vector<std::string>& keys) const @@ -1060,14 +1057,14 @@ void TellStoppedRpcMethod::createEntry gatherStoppedDownload(entryDict, item, keys); } -std::shared_ptr<ValueBase> PurgeDownloadResultRpcMethod::process +std::unique_ptr<ValueBase> PurgeDownloadResultRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { e->getRequestGroupMan()->purgeDownloadResult(); - return VLB_OK; + return createOKResponse(); } -std::shared_ptr<ValueBase> RemoveDownloadResultRpcMethod::process +std::unique_ptr<ValueBase> RemoveDownloadResultRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); @@ -1077,17 +1074,17 @@ std::shared_ptr<ValueBase> RemoveDownloadResultRpcMethod::process throw DL_ABORT_EX(fmt("Could not remove download result of GID#%s", GroupId::toHex(gid).c_str())); } - return VLB_OK; + return createOKResponse(); } -std::shared_ptr<ValueBase> ChangeOptionRpcMethod::process +std::unique_ptr<ValueBase> ChangeOptionRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); const Dict* optsParam = checkRequiredParam<Dict>(req, 1); a2_gid_t gid = str2Gid(gidParam); - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); + auto group = e->getRequestGroupMan()->findGroup(gid); Option option; if(group) { if(group->getState() == RequestGroup::STATE_ACTIVE) { @@ -1100,10 +1097,10 @@ std::shared_ptr<ValueBase> ChangeOptionRpcMethod::process throw DL_ABORT_EX(fmt("Cannot change option for GID#%s", GroupId::toHex(gid).c_str())); } - return VLB_OK; + return createOKResponse(); } -std::shared_ptr<ValueBase> ChangeGlobalOptionRpcMethod::process +std::unique_ptr<ValueBase> ChangeGlobalOptionRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const Dict* optsParam = checkRequiredParam<Dict>(req, 0); @@ -1111,28 +1108,28 @@ std::shared_ptr<ValueBase> ChangeGlobalOptionRpcMethod::process Option option; gatherChangeableGlobalOption(&option, optsParam); changeGlobalOption(option, e); - return VLB_OK; + return createOKResponse(); } -std::shared_ptr<ValueBase> GetVersionRpcMethod::process +std::unique_ptr<ValueBase> GetVersionRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { - std::shared_ptr<Dict> result = Dict::g(); + auto result = Dict::g(); result->put(KEY_VERSION, PACKAGE_VERSION); - std::shared_ptr<List> featureList = List::g(); + auto featureList = List::g(); for(int feat = 0; feat < MAX_FEATURE; ++feat) { const char* name = strSupportedFeature(feat); if(name) { featureList->append(name); } } - result->put(KEY_ENABLED_FEATURES, featureList); - return result; + result->put(KEY_ENABLED_FEATURES, std::move(featureList)); + return std::move(result); } namespace { void pushRequestOption -(const std::shared_ptr<Dict>& dict, +(Dict* dict, const std::shared_ptr<Option>& option, const std::shared_ptr<OptionParser>& oparser) { @@ -1146,32 +1143,31 @@ void pushRequestOption } } // namespace -std::shared_ptr<ValueBase> GetOptionRpcMethod::process +std::unique_ptr<ValueBase> GetOptionRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); a2_gid_t gid = str2Gid(gidParam); - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); - std::shared_ptr<Dict> result = Dict::g(); + auto group = e->getRequestGroupMan()->findGroup(gid); + auto result = Dict::g(); if(!group) { - std::shared_ptr<DownloadResult> dr = - e->getRequestGroupMan()->findDownloadResult(gid); + auto dr = e->getRequestGroupMan()->findDownloadResult(gid); if(!dr) { throw DL_ABORT_EX(fmt("Cannot get option for GID#%s", GroupId::toHex(gid).c_str())); } - pushRequestOption(result, dr->option, getOptionParser()); + pushRequestOption(result.get(), dr->option, getOptionParser()); } else { - pushRequestOption(result, group->getOption(), getOptionParser()); + pushRequestOption(result.get(), group->getOption(), getOptionParser()); } - return result; + return std::move(result); } -std::shared_ptr<ValueBase> GetGlobalOptionRpcMethod::process +std::unique_ptr<ValueBase> GetGlobalOptionRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { - std::shared_ptr<Dict> result = Dict::g(); + auto result = Dict::g(); for(size_t i = 0, len = e->getOption()->getTable().size(); i < len; ++i) { const Pref* pref = option::i2p(i); if(!e->getOption()->defined(pref)) { @@ -1182,10 +1178,10 @@ std::shared_ptr<ValueBase> GetGlobalOptionRpcMethod::process result->put(pref->k, e->getOption()->get(pref)); } } - return result; + return std::move(result); } -std::shared_ptr<ValueBase> ChangePositionRpcMethod::process +std::unique_ptr<ValueBase> ChangePositionRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); @@ -1207,59 +1203,52 @@ std::shared_ptr<ValueBase> ChangePositionRpcMethod::process } size_t destPos = e->getRequestGroupMan()->changeReservedGroupPosition(gid, pos, how); - std::shared_ptr<Integer> result = Integer::g(destPos); - return result; + return Integer::g(destPos); } -std::shared_ptr<ValueBase> GetSessionInfoRpcMethod::process +std::unique_ptr<ValueBase> GetSessionInfoRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { - std::shared_ptr<Dict> result = Dict::g(); + auto result = Dict::g(); result->put(KEY_SESSION_ID, util::toHex(e->getSessionId())); - return result; + return std::move(result); } -std::shared_ptr<ValueBase> GetServersRpcMethod::process +std::unique_ptr<ValueBase> GetServersRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); a2_gid_t gid = str2Gid(gidParam); - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); + auto group = e->getRequestGroupMan()->findGroup(gid); if(!group || group->getState() != RequestGroup::STATE_ACTIVE) { throw DL_ABORT_EX(fmt("No active download for GID#%s", GroupId::toHex(gid).c_str())); } - const std::shared_ptr<DownloadContext>& dctx = group->getDownloadContext(); - const std::vector<std::shared_ptr<FileEntry> >& files = dctx->getFileEntries(); - std::shared_ptr<List> result = List::g(); + auto result = List::g(); size_t index = 1; - for(std::vector<std::shared_ptr<FileEntry> >::const_iterator fi = files.begin(), - eoi = files.end(); fi != eoi; ++fi, ++index) { - std::shared_ptr<Dict> fileEntry = Dict::g(); - fileEntry->put(KEY_INDEX, util::uitos(index)); - std::shared_ptr<List> servers = List::g(); - const FileEntry::InFlightRequestSet& requests = - (*fi)->getInFlightRequests(); - for(FileEntry::InFlightRequestSet::iterator ri =requests.begin(), - eoi = requests.end(); ri != eoi; ++ri) { - std::shared_ptr<PeerStat> ps = (*ri)->getPeerStat(); + for(auto& fe : group->getDownloadContext()->getFileEntries()) { + auto fileEntry = Dict::g(); + fileEntry->put(KEY_INDEX, util::uitos(index++)); + auto servers = List::g(); + for(auto& req : fe->getInFlightRequests()) { + auto ps = req->getPeerStat(); if(ps) { - std::shared_ptr<Dict> serverEntry = Dict::g(); - serverEntry->put(KEY_URI, (*ri)->getUri()); - serverEntry->put(KEY_CURRENT_URI, (*ri)->getCurrentUri()); + auto serverEntry = Dict::g(); + serverEntry->put(KEY_URI, req->getUri()); + serverEntry->put(KEY_CURRENT_URI, req->getCurrentUri()); serverEntry->put(KEY_DOWNLOAD_SPEED, util::itos(ps->calculateDownloadSpeed())); - servers->append(serverEntry); + servers->append(std::move(serverEntry)); } } - fileEntry->put(KEY_SERVERS, servers); - result->append(fileEntry); + fileEntry->put(KEY_SERVERS, std::move(servers)); + result->append(std::move(fileEntry)); } - return result; + return std::move(result); } -std::shared_ptr<ValueBase> ChangeUriRpcMethod::process +std::unique_ptr<ValueBase> ChangeUriRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const String* gidParam = checkRequiredParam<String>(req, 0); @@ -1272,20 +1261,19 @@ std::shared_ptr<ValueBase> ChangeUriRpcMethod::process bool posGiven = checkPosParam(posParam); size_t pos = posGiven ? posParam->i() : 0; size_t index = indexParam->i()-1; - std::shared_ptr<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid); + auto group = e->getRequestGroupMan()->findGroup(gid); if(!group) { throw DL_ABORT_EX(fmt("Cannot remove URIs from GID#%s", GroupId::toHex(gid).c_str())); } - const std::shared_ptr<DownloadContext>& dctx = group->getDownloadContext(); - const std::vector<std::shared_ptr<FileEntry> >& files = dctx->getFileEntries(); + auto& files = group->getDownloadContext()->getFileEntries(); if(files.size() <= index) { throw DL_ABORT_EX(fmt("fileIndex is out of range")); } - std::shared_ptr<FileEntry> s = files[index]; + auto& s = files[index]; size_t delcount = 0; - for(List::ValueType::const_iterator i = delUrisParam->begin(), - eoi = delUrisParam->end(); i != eoi; ++i) { + for(auto i = delUrisParam->begin(), eoi = delUrisParam->end(); + i != eoi; ++i) { const String* uri = downcast<String>(*i); if(uri && s->removeUri(uri->s())) { ++delcount; @@ -1293,8 +1281,8 @@ std::shared_ptr<ValueBase> ChangeUriRpcMethod::process } size_t addcount = 0; if(posGiven) { - for(List::ValueType::const_iterator i = addUrisParam->begin(), - eoi = addUrisParam->end(); i != eoi; ++i) { + for(auto i = addUrisParam->begin(), eoi = addUrisParam->end(); + i != eoi; ++i) { const String* uri = downcast<String>(*i); if(uri && s->insertUri(uri->s(), pos)) { ++addcount; @@ -1302,8 +1290,8 @@ std::shared_ptr<ValueBase> ChangeUriRpcMethod::process } } } else { - for(List::ValueType::const_iterator i = addUrisParam->begin(), - eoi = addUrisParam->end(); i != eoi; ++i) { + for(auto i = addUrisParam->begin(), eoi = addUrisParam->end(); + i != eoi; ++i) { const String* uri = downcast<String>(*i); if(uri && s->addUri(uri->s())) { ++addcount; @@ -1316,14 +1304,14 @@ std::shared_ptr<ValueBase> ChangeUriRpcMethod::process e->addCommand(std::move(commands)); group->getSegmentMan()->recognizeSegmentFor(s); } - std::shared_ptr<List> res = List::g(); + auto res = List::g(); res->append(Integer::g(delcount)); res->append(Integer::g(addcount)); - return res; + return std::move(res); } namespace { -std::shared_ptr<ValueBase> goingShutdown +std::unique_ptr<ValueBase> goingShutdown (const RpcRequest& req, DownloadEngine* e, bool forceHalt) { // Schedule shutdown after 3seconds to give time to client to @@ -1331,44 +1319,43 @@ std::shared_ptr<ValueBase> goingShutdown e->addRoutineCommand(make_unique<TimedHaltCommand> (e->newCUID(), e, 3, forceHalt)); A2_LOG_INFO("Scheduled shutdown in 3 seconds."); - return VLB_OK; + return createOKResponse(); } } // namespace -std::shared_ptr<ValueBase> ShutdownRpcMethod::process +std::unique_ptr<ValueBase> ShutdownRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { return goingShutdown(req, e, false); } -std::shared_ptr<ValueBase> ForceShutdownRpcMethod::process +std::unique_ptr<ValueBase> ForceShutdownRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { return goingShutdown(req, e, true); } -std::shared_ptr<ValueBase> GetGlobalStatRpcMethod::process +std::unique_ptr<ValueBase> GetGlobalStatRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { auto& rgman = e->getRequestGroupMan(); - TransferStat ts = rgman->calculateStat(); - std::shared_ptr<Dict> res = Dict::g(); + auto ts = rgman->calculateStat(); + auto res = Dict::g(); res->put(KEY_DOWNLOAD_SPEED, util::itos(ts.downloadSpeed)); res->put(KEY_UPLOAD_SPEED, util::itos(ts.uploadSpeed)); res->put(KEY_NUM_WAITING, util::uitos(rgman->getReservedGroups().size())); res->put(KEY_NUM_STOPPED, util::uitos(rgman->getDownloadResults().size())); res->put(KEY_NUM_ACTIVE, util::uitos(rgman->getRequestGroups().size())); - return res; + return std::move(res); } -std::shared_ptr<ValueBase> SystemMulticallRpcMethod::process +std::unique_ptr<ValueBase> SystemMulticallRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { const List* methodSpecs = checkRequiredParam<List>(req, 0); - std::shared_ptr<List> list = List::g(); - for(List::ValueType::const_iterator i = methodSpecs->begin(), - eoi = methodSpecs->end(); i != eoi; ++i) { - const Dict* methodDict = downcast<Dict>(*i); + auto list = List::g(); + for(auto i = methodSpecs->begin(), eoi = methodSpecs->end(); i != eoi; ++i) { + Dict* methodDict = downcast<Dict>(*i); if(!methodDict) { list->append(createErrorResponse (DL_ABORT_EX("system.multicall expected struct."), req)); @@ -1385,29 +1372,30 @@ std::shared_ptr<ValueBase> SystemMulticallRpcMethod::process (DL_ABORT_EX("Recursive system.multicall forbidden."), req)); continue; } - const std::shared_ptr<ValueBase>& tempParamsList = methodDict->get(KEY_PARAMS); - std::shared_ptr<List> paramsList; + // TODO what if params missing? + auto tempParamsList = methodDict->get(KEY_PARAMS); + std::unique_ptr<List> paramsList; if(downcast<List>(tempParamsList)) { - paramsList = std::static_pointer_cast<List>(tempParamsList); + paramsList.reset(static_cast<List*>(methodDict->popValue(KEY_PARAMS) + .release())); } else { paramsList = List::g(); } - std::shared_ptr<RpcMethod> method = RpcMethodFactory::create(methodName->s()); - RpcRequest innerReq(methodName->s(), paramsList); - innerReq.jsonRpc = req.jsonRpc; - RpcResponse res = method->execute(innerReq, e); + auto method = RpcMethodFactory::create(methodName->s()); + RpcResponse res = method->execute + ({methodName->s(), std::move(paramsList), nullptr, req.jsonRpc}, e); if(res.code == 0) { - std::shared_ptr<List> l = List::g(); - l->append(res.param); - list->append(l); + auto l = List::g(); + l->append(std::move(res.param)); + list->append(std::move(l)); } else { - list->append(res.param); + list->append(std::move(res.param)); } } - return list; + return std::move(list); } -std::shared_ptr<ValueBase> NoSuchMethodRpcMethod::process +std::unique_ptr<ValueBase> NoSuchMethodRpcMethod::process (const RpcRequest& req, DownloadEngine* e) { throw DL_ABORT_EX(fmt("No such method: %s", req.methodName.c_str())); diff --git a/src/RpcMethodImpl.h b/src/RpcMethodImpl.h index fa39e6fd..fdc5b045 100644 --- a/src/RpcMethodImpl.h +++ b/src/RpcMethodImpl.h @@ -127,7 +127,7 @@ void toStringList(OutputIterator out, const List* src) class AddUriRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -138,7 +138,7 @@ public: class RemoveRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -149,7 +149,7 @@ public: class ForceRemoveRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -160,7 +160,7 @@ public: class PauseRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -171,7 +171,7 @@ public: class ForcePauseRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -182,7 +182,7 @@ public: class PauseAllRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -193,7 +193,7 @@ public: class ForcePauseAllRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -204,7 +204,7 @@ public: class UnpauseRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -215,7 +215,7 @@ public: class UnpauseAllRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -227,7 +227,7 @@ public: #ifdef ENABLE_BITTORRENT class AddTorrentRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -240,7 +240,7 @@ public: #ifdef ENABLE_METALINK class AddMetalinkRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -252,7 +252,7 @@ public: class PurgeDownloadResultRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -263,7 +263,7 @@ public: class RemoveDownloadResultRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -274,7 +274,7 @@ public: class GetUrisRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -285,7 +285,7 @@ public: class GetFilesRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -297,7 +297,7 @@ public: #ifdef ENABLE_BITTORRENT class GetPeersRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -309,7 +309,7 @@ public: class GetServersRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -320,7 +320,7 @@ public: class TellStatusRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -331,7 +331,7 @@ public: class TellActiveRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -376,7 +376,7 @@ private: protected: typedef IndexedList<a2_gid_t, std::shared_ptr<T> > ItemListType; - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE { const Integer* offsetParam = checkRequiredParam<Integer>(req, 0); @@ -388,25 +388,24 @@ protected: std::vector<std::string> keys; toStringList(std::back_inserter(keys), keysParam); const ItemListType& items = getItems(e); - std::pair<typename ItemListType::const_iterator, - typename ItemListType::const_iterator> range = - getPaginationRange(offset, num, items.begin(), items.end()); - std::shared_ptr<List> list = List::g(); + auto range = getPaginationRange(offset, num, + std::begin(items), std::end(items)); + auto list = List::g(); for(; range.first != range.second; ++range.first) { - std::shared_ptr<Dict> entryDict = Dict::g(); - createEntry(entryDict, *range.first, e, keys); - list->append(entryDict); + auto entryDict = Dict::g(); + createEntry(entryDict.get(), *range.first, e, keys); + list->append(std::move(entryDict)); } if(offset < 0) { std::reverse(list->begin(), list->end()); } - return list; + return std::move(list); } virtual const ItemListType& getItems(DownloadEngine* e) const = 0; virtual void createEntry - (const std::shared_ptr<Dict>& entryDict, + (Dict* entryDict, const std::shared_ptr<T>& item, DownloadEngine* e, const std::vector<std::string>& keys) const = 0; @@ -419,7 +418,7 @@ protected: CXX11_OVERRIDE; virtual void createEntry - (const std::shared_ptr<Dict>& entryDict, + (Dict* entryDict, const std::shared_ptr<RequestGroup>& item, DownloadEngine* e, const std::vector<std::string>& keys) const CXX11_OVERRIDE; @@ -437,7 +436,7 @@ protected: CXX11_OVERRIDE; virtual void createEntry - (const std::shared_ptr<Dict>& entryDict, + (Dict* entryDict, const std::shared_ptr<DownloadResult>& item, DownloadEngine* e, const std::vector<std::string>& keys) const CXX11_OVERRIDE; @@ -450,7 +449,7 @@ public: class ChangeOptionRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -461,7 +460,7 @@ public: class ChangeGlobalOptionRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -472,7 +471,7 @@ public: class GetVersionRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -483,7 +482,7 @@ public: class GetOptionRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -494,7 +493,7 @@ public: class GetGlobalOptionRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -505,7 +504,7 @@ public: class ChangePositionRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -516,7 +515,7 @@ public: class ChangeUriRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -527,7 +526,7 @@ public: class GetSessionInfoRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -538,7 +537,7 @@ public: class ShutdownRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -549,7 +548,7 @@ public: class GetGlobalStatRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -560,7 +559,7 @@ public: class ForceShutdownRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -571,7 +570,7 @@ public: class SystemMulticallRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; public: static const char* getMethodName() @@ -582,26 +581,25 @@ public: class NoSuchMethodRpcMethod:public RpcMethod { protected: - virtual std::shared_ptr<ValueBase> process + virtual std::unique_ptr<ValueBase> process (const RpcRequest& req, DownloadEngine* e) CXX11_OVERRIDE; }; // Helper function to store data to entryDict from ds. This function // is used by tellStatus method. void gatherStoppedDownload -(const std::shared_ptr<Dict>& entryDict, const std::shared_ptr<DownloadResult>& ds, +(Dict* entryDict, const std::shared_ptr<DownloadResult>& ds, const std::vector<std::string>& keys); // Helper function to store data to entryDict from group. This // function is used by tellStatus/tellActive/tellWaiting method void gatherProgressCommon -(const std::shared_ptr<Dict>& entryDict, const std::shared_ptr<RequestGroup>& group, +(Dict* entryDict, const std::shared_ptr<RequestGroup>& group, const std::vector<std::string>& keys); #ifdef ENABLE_BITTORRENT // Helper function to store BitTorrent metadata from torrentAttrs. -void gatherBitTorrentMetadata -(const std::shared_ptr<Dict>& btDict, TorrentAttribute* torrentAttrs); +void gatherBitTorrentMetadata(Dict* btDict, TorrentAttribute* torrentAttrs); #endif // ENABLE_BITTORRENT } // namespace rpc diff --git a/src/RpcRequest.cc b/src/RpcRequest.cc index 1ed1c1db..c9b531f7 100644 --- a/src/RpcRequest.cc +++ b/src/RpcRequest.cc @@ -39,35 +39,23 @@ namespace aria2 { namespace rpc { RpcRequest::RpcRequest() - : jsonRpc(false) + : jsonRpc{false} {} -RpcRequest::RpcRequest(const std::string& methodName, - const std::shared_ptr<List>& params) - : methodName(methodName), params(params), jsonRpc(false) +RpcRequest::RpcRequest(std::string methodName, + std::unique_ptr<List> params) + : methodName{std::move(methodName)}, params{std::move(params)}, + jsonRpc{false} {} -RpcRequest::RpcRequest(const std::string& methodName, - const std::shared_ptr<List>& params, - const std::shared_ptr<ValueBase>& id) - : methodName(methodName), params(params), id(id), jsonRpc(false) +RpcRequest::RpcRequest(std::string methodName, + std::unique_ptr<List> params, + std::unique_ptr<ValueBase> id, + bool jsonRpc) + : methodName{std::move(methodName)}, params{std::move(params)}, + id{std::move(id)}, jsonRpc{jsonRpc} {} -RpcRequest::RpcRequest(const RpcRequest& c) - : methodName(c.methodName), params(c.params), id(c.id), jsonRpc(c.jsonRpc) -{} - -RpcRequest::~RpcRequest() {} - -RpcRequest& RpcRequest::operator=(const RpcRequest& c) -{ - if(this != &c) { - methodName = c.methodName; - params = c.params; - } - return *this; -} - } // namespace rpc } // namespace aria2 diff --git a/src/RpcRequest.h b/src/RpcRequest.h index 85b75a50..87169c2d 100644 --- a/src/RpcRequest.h +++ b/src/RpcRequest.h @@ -47,24 +47,19 @@ namespace rpc { struct RpcRequest { std::string methodName; - std::shared_ptr<List> params; - std::shared_ptr<ValueBase> id; + std::unique_ptr<List> params; + std::unique_ptr<ValueBase> id; bool jsonRpc; RpcRequest(); - RpcRequest(const std::string& methodName, - const std::shared_ptr<List>& params); + RpcRequest(std::string methodName, + std::unique_ptr<List> params); - RpcRequest(const std::string& methodName, - const std::shared_ptr<List>& params, - const std::shared_ptr<ValueBase>& id); - - ~RpcRequest(); - - RpcRequest(const RpcRequest& c); - - RpcRequest& operator=(const RpcRequest& c); + RpcRequest(std::string methodName, + std::unique_ptr<List> params, + std::unique_ptr<ValueBase> id, + bool jsonRpc = false); }; } // namespace rpc diff --git a/src/RpcResponse.cc b/src/RpcResponse.cc index a3c16655..9360fb2a 100644 --- a/src/RpcResponse.cc +++ b/src/RpcResponse.cc @@ -49,7 +49,7 @@ namespace rpc { namespace { template<typename OutputStream> -void encodeValue(const std::shared_ptr<ValueBase>& value, OutputStream& o) +void encodeValue(const ValueBase* value, OutputStream& o) { class XmlValueBaseVisitor:public ValueBaseVisitor { private: @@ -104,7 +104,7 @@ void encodeValue(const std::shared_ptr<ValueBase>& value, OutputStream& o) namespace { template<typename OutputStream> std::string encodeAll -(OutputStream& o, int code, const std::shared_ptr<ValueBase>& param) +(OutputStream& o, int code, const ValueBase* param) { o << "<?xml version=\"1.0\"?>" << "<methodResponse>"; if(code == 0) { @@ -123,41 +123,24 @@ std::string encodeAll RpcResponse::RpcResponse (int code, - const std::shared_ptr<ValueBase>& param, - const std::shared_ptr<ValueBase>& id) - : code(code), param(param), id(id) + std::unique_ptr<ValueBase> param, + std::unique_ptr<ValueBase> id) + : code{code}, param{std::move(param)}, id{std::move(id)} {} -RpcResponse::RpcResponse(const RpcResponse& c) - : code(c.code), - param(c.param), - id(c.id) -{} - -RpcResponse::~RpcResponse() {} - -RpcResponse& RpcResponse::operator=(const RpcResponse& c) -{ - if(this != &c) { - code = c.code; - param = c.param; - } - return *this; -} - std::string toXml(const RpcResponse& res, bool gzip) { if(gzip) { #ifdef HAVE_ZLIB GZipEncoder o; o.init(); - return encodeAll(o, res.code, res.param); + return encodeAll(o, res.code, res.param.get()); #else // !HAVE_ZLIB abort(); #endif // !HAVE_ZLIB } else { std::stringstream o; - return encodeAll(o, res.code, res.param); + return encodeAll(o, res.code, res.param.get()); } } @@ -166,22 +149,23 @@ template<typename OutputStream> OutputStream& encodeJsonAll (OutputStream& o, int code, - const std::shared_ptr<ValueBase>& param, - const std::shared_ptr<ValueBase>& id, + const ValueBase* param, + const ValueBase* id, const std::string& callback = A2STR::NIL) { if(!callback.empty()) { o << callback << "("; } - std::shared_ptr<Dict> dict = Dict::g(); - dict->put("jsonrpc", "2.0"); - dict->put("id", id); + o << "{\"id\":"; + json::encode(o, id); + o << ",\"jsonrpc\":\"2.0\","; if(code == 0) { - dict->put("result", param); + o << "\"result\":"; } else { - dict->put("error", param); + o << "\"error\":"; } - json::encode(o, dict); + json::encode(o, param); + o << "}"; if(!callback.empty()) { o << ")"; } @@ -196,13 +180,15 @@ std::string toJson #ifdef HAVE_ZLIB GZipEncoder o; o.init(); - return encodeJsonAll(o, res.code, res.param, res.id, callback).str(); + return encodeJsonAll(o, res.code, res.param.get(), res.id.get(), + callback).str(); #else // !HAVE_ZLIB abort(); #endif // !HAVE_ZLIB } else { std::stringstream o; - return encodeJsonAll(o, res.code, res.param, res.id, callback).str(); + return encodeJsonAll(o, res.code, res.param.get(), res.id.get(), + callback).str(); } } @@ -218,12 +204,12 @@ OutputStream& encodeJsonBatchAll } o << "["; if(!results.empty()) { - encodeJsonAll(o, results[0].code, results[0].param, results[0].id); + encodeJsonAll(o, results[0].code, results[0].param.get(), + results[0].id.get()); } - for(std::vector<RpcResponse>::const_iterator i = results.begin()+1, - eoi = results.end(); i != eoi; ++i) { + for(auto i = std::begin(results)+1, eoi = std::end(results); i != eoi; ++i) { o << ","; - encodeJsonAll(o, (*i).code, (*i).param, (*i).id); + encodeJsonAll(o, (*i).code, (*i).param.get(), (*i).id.get()); } o << "]"; if(!callback.empty()) { diff --git a/src/RpcResponse.h b/src/RpcResponse.h index aaa401ea..1d90d0e7 100644 --- a/src/RpcResponse.h +++ b/src/RpcResponse.h @@ -49,21 +49,13 @@ namespace rpc { struct RpcResponse { // 0 for success, non-zero for error int code; - - std::shared_ptr<ValueBase> param; - - std::shared_ptr<ValueBase> id; + std::unique_ptr<ValueBase> param; + std::unique_ptr<ValueBase> id; RpcResponse (int code, - const std::shared_ptr<ValueBase>& param, - const std::shared_ptr<ValueBase>& id); - - RpcResponse(const RpcResponse& c); - - ~RpcResponse(); - - RpcResponse& operator=(const RpcResponse& c); + std::unique_ptr<ValueBase> param, + std::unique_ptr<ValueBase> id); }; std::string toXml(const RpcResponse& response, bool gzip = false); diff --git a/src/ValueBase.cc b/src/ValueBase.cc index b8c4e6db..d8a3afdf 100644 --- a/src/ValueBase.cc +++ b/src/ValueBase.cc @@ -36,39 +36,49 @@ namespace aria2 { -const std::shared_ptr<ValueBase> ValueBase::none; +String::String(const ValueType& string):str_{string} {} +String::String(ValueType&& string):str_{std::move(string)} {} -String::String(const ValueType& string):str_(string) {} +String::String(const char* cstring):str_{cstring} {} -String::String(const char* cstring):str_(cstring) {} +String::String(const char* data, size_t length) + : str_{&data[0], &data[length]} + {} -String::String(const char* data, size_t length):str_(&data[0], &data[length]) {} - -String::String(const unsigned char* data, size_t length): - str_(&data[0], &data[length]) {} +String::String(const unsigned char* data, size_t length) + : str_{&data[0], &data[length]} + {} String::String() {} -String::~String() {} - const String::ValueType& String::s() const { return str_; } +String::ValueType String::popValue() const +{ + return std::move(str_); +} + const unsigned char* String::uc() const { return reinterpret_cast<const unsigned char*>(str_.data()); } -std::shared_ptr<String> String::g(const ValueType& string) +std::unique_ptr<String> String::g(const ValueType& string) { - return std::shared_ptr<String>(new String(string)); + return make_unique<String>(string); } -std::shared_ptr<String> String::g(const unsigned char* data, size_t length) +std::unique_ptr<String> String::g(ValueType&& string) { - return std::shared_ptr<String>(new String(data, length)); + return make_unique<String>(std::move(string)); +} + +std::unique_ptr<String> String::g(const unsigned char* data, size_t length) +{ + return make_unique<String>(data, length); } void String::accept(ValueBaseVisitor& v) const @@ -76,20 +86,18 @@ void String::accept(ValueBaseVisitor& v) const v.visit(*this); } -Integer::Integer(ValueType integer):integer_(integer) {} - -Integer::Integer():integer_(0) {} +Integer::Integer(ValueType integer) : integer_{integer} {} -Integer::~Integer() {} +Integer::Integer() : integer_{0} {} Integer::ValueType Integer::i() const { return integer_; } -std::shared_ptr<Integer> Integer::g(ValueType integer) +std::unique_ptr<Integer> Integer::g(ValueType integer) { - return std::shared_ptr<Integer>(new Integer(integer)); + return make_unique<Integer>(integer); } void Integer::accept(ValueBaseVisitor& v) const @@ -97,17 +105,16 @@ void Integer::accept(ValueBaseVisitor& v) const v.visit(*this); } -const std::shared_ptr<Bool> Bool::trueValue_(new Bool(true)); -const std::shared_ptr<Bool> Bool::falseValue_(new Bool(false)); +Bool::Bool(bool val):val_{val} {} -std::shared_ptr<Bool> Bool::gTrue() +std::unique_ptr<Bool> Bool::gTrue() { - return trueValue_; + return make_unique<Bool>(true); } -std::shared_ptr<Bool> Bool::gFalse() +std::unique_ptr<Bool> Bool::gFalse() { - return falseValue_; + return make_unique<Bool>(false); } bool Bool::val() const @@ -120,13 +127,11 @@ void Bool::accept(ValueBaseVisitor& v) const v.visit(*this); } -Bool::Bool(bool val):val_(val) {} - -const std::shared_ptr<Null> Null::nullValue_(new Null()); +Null::Null() {} -std::shared_ptr<Null> Null::g() +std::unique_ptr<Null> Null::g() { - return nullValue_; + return make_unique<Null>(); } void Null::accept(ValueBaseVisitor& v) const @@ -134,41 +139,37 @@ void Null::accept(ValueBaseVisitor& v) const v.visit(*this); } -Null::Null() {} - List::List() {} -List::~List() {} - -const std::shared_ptr<ValueBase>& List::get(size_t index) const +ValueBase* List::get(size_t index) const { - return list_[index]; + return list_[index].get(); } -void List::set(size_t index, const std::shared_ptr<ValueBase>& v) +void List::set(size_t index, std::unique_ptr<ValueBase> v) { - list_[index] = v; + list_[index] = std::move(v); } -void List::append(const std::shared_ptr<ValueBase>& v) +void List::append(std::unique_ptr<ValueBase> v) { - list_.push_back(v); + list_.push_back(std::move(v)); } -void List::append(const String::ValueType& string) +void List::append(String::ValueType string) { - list_.push_back(String::g(string)); + list_.push_back(String::g(std::move(string))); } -List& List::operator<<(const std::shared_ptr<ValueBase>& v) +List& List::operator<<(std::unique_ptr<ValueBase> v) { - list_.push_back(v); + list_.push_back(std::move(v)); return *this; } -const std::shared_ptr<ValueBase>& List::operator[](size_t index) const +ValueBase* List::operator[](size_t index) const { - return list_[index]; + return list_[index].get(); } List::ValueType::iterator List::begin() @@ -191,6 +192,16 @@ List::ValueType::const_iterator List::end() const return list_.end(); } +List::ValueType::const_iterator List::cbegin() const +{ + return list_.cbegin(); +} + +List::ValueType::const_iterator List::cend() const +{ + return list_.cend(); +} + size_t List::size() const { return list_.size(); @@ -201,9 +212,9 @@ bool List::empty() const return list_.empty(); } -std::shared_ptr<List> List::g() +std::unique_ptr<List> List::g() { - return std::shared_ptr<List>(new List()); + return make_unique<List>(); } void List::accept(ValueBaseVisitor& v) const @@ -213,55 +224,38 @@ void List::accept(ValueBaseVisitor& v) const Dict::Dict() {} -Dict::~Dict() {} - -void Dict::put(const std::string& key, const std::shared_ptr<ValueBase>& vlb) +void Dict::put(std::string key, std::unique_ptr<ValueBase> vlb) { - ValueType::value_type p = std::make_pair(key, vlb); - std::pair<ValueType::iterator, bool> r = dict_.insert(p); + auto p = std::make_pair(std::move(key), std::move(vlb)); + auto r = dict_.insert(std::move(p)); if(!r.second) { - (*r.first).second = vlb; + (*r.first).second = std::move(vlb); } } -void Dict::put(const std::string& key, const String::ValueType& string) +void Dict::put(std::string key, String::ValueType string) { - put(key, String::g(string)); + put(std::move(key), String::g(std::move(string))); } -const std::shared_ptr<ValueBase>& Dict::get(const std::string& key) const +ValueBase* Dict::get(const std::string& key) const { - ValueType::const_iterator itr = dict_.find(key); - if(itr == dict_.end()) { - return ValueBase::none; + auto itr = dict_.find(key); + if(itr == std::end(dict_)) { + return nullptr; } else { - return (*itr).second; + return (*itr).second.get(); } } -std::shared_ptr<ValueBase>& Dict::get(const std::string& key) -{ - ValueType::iterator itr = dict_.find(key); - if(itr == dict_.end()) { - return dict_[key]; - } else { - return (*itr).second; - } -} - -std::shared_ptr<ValueBase>& Dict::operator[](const std::string& key) -{ - return get(key); -} - -const std::shared_ptr<ValueBase>& Dict::operator[](const std::string& key) const +ValueBase* Dict::operator[](const std::string& key) const { return get(key); } bool Dict::containsKey(const std::string& key) const { - return dict_.count(key) == 1; + return dict_.count(key); } void Dict::removeKey(const std::string& key) @@ -269,6 +263,18 @@ void Dict::removeKey(const std::string& key) dict_.erase(key); } +std::unique_ptr<ValueBase> Dict::popValue(const std::string& key) +{ + auto i = dict_.find(key); + if(i == std::end(dict_)) { + return nullptr; + } else { + auto res = std::move((*i).second); + dict_.erase(i); + return res; + } +} + Dict::ValueType::iterator Dict::begin() { return dict_.begin(); @@ -289,6 +295,16 @@ Dict::ValueType::const_iterator Dict::end() const return dict_.end(); } +Dict::ValueType::const_iterator Dict::cbegin() const +{ + return dict_.cbegin(); +} + +Dict::ValueType::const_iterator Dict::cend() const +{ + return dict_.cend(); +} + size_t Dict::size() const { return dict_.size(); @@ -299,10 +315,11 @@ bool Dict::empty() const return dict_.empty(); } -std::shared_ptr<Dict> Dict::g() +std::unique_ptr<Dict> Dict::g() { - return std::shared_ptr<Dict>(new Dict()); + return make_unique<Dict>(); } + void Dict::accept(ValueBaseVisitor& v) const { v.visit(*this); diff --git a/src/ValueBase.h b/src/ValueBase.h index 115c1616..e65699c1 100644 --- a/src/ValueBase.h +++ b/src/ValueBase.h @@ -42,6 +42,8 @@ #include <map> #include <memory> +#include "a2functional.h" + namespace aria2 { class ValueBaseVisitor; @@ -51,8 +53,6 @@ public: virtual ~ValueBase() {} virtual void accept(ValueBaseVisitor& visitor) const = 0; - - static const std::shared_ptr<ValueBase> none; }; class String; @@ -78,6 +78,7 @@ public: typedef std::string ValueType; String(const ValueType& string); + String(ValueType&& string); explicit String(const char* cstring); @@ -92,26 +93,27 @@ public: String(); - ~String(); - // Don't allow copying - String(const String&); - String& operator=(const String&); + String(const String&) = delete; + String& operator=(const String&) = delete; const ValueType& s() const; + ValueType popValue() const; + // Returns std::string.data() casted to unsigned char*. // Use s().size() to get length. const unsigned char* uc() const; - static std::shared_ptr<String> g(const ValueType& string); + static std::unique_ptr<String> g(const ValueType& string); + static std::unique_ptr<String> g(ValueType&& string); - static std::shared_ptr<String> g(const unsigned char* data, size_t length); + static std::unique_ptr<String> g(const unsigned char* data, size_t length); template<typename InputIterator> - static std::shared_ptr<String> g(InputIterator first, InputIterator last) + static std::unique_ptr<String> g(InputIterator first, InputIterator last) { - return std::shared_ptr<String>(new String(first, last)); + return make_unique<String>(first, last); } virtual void accept(ValueBaseVisitor& visitor) const CXX11_OVERRIDE; @@ -127,16 +129,14 @@ public: Integer(); - ~Integer(); - // Don't allow copying - Integer(const Integer&); - Integer& operator=(const Integer&); + Integer(const Integer&) = delete; + Integer& operator=(const Integer&) = delete; // Returns Integer. ValueType i() const; - static std::shared_ptr<Integer> g(ValueType integer); + static std::unique_ptr<Integer> g(ValueType integer); virtual void accept(ValueBaseVisitor& visitor) const CXX11_OVERRIDE; private: @@ -145,61 +145,56 @@ private: class Bool:public ValueBase { public: - static std::shared_ptr<Bool> gTrue(); - static std::shared_ptr<Bool> gFalse(); + static std::unique_ptr<Bool> gTrue(); + static std::unique_ptr<Bool> gFalse(); + Bool(bool val); bool val() const; virtual void accept(ValueBaseVisitor& visitor) const CXX11_OVERRIDE; private: - Bool(bool val); // Don't allow copying - Bool(const Bool&); - Bool& operator=(const Bool&); + Bool(const Bool&) = delete; + Bool& operator=(const Bool&) = delete; bool val_; - static const std::shared_ptr<Bool> trueValue_; - static const std::shared_ptr<Bool> falseValue_; }; class Null:public ValueBase { public: - static std::shared_ptr<Null> g(); + static std::unique_ptr<Null> g(); + Null(); virtual void accept(ValueBaseVisitor& visitor) const CXX11_OVERRIDE; private: - Null(); // Don't allow copying Null(const Null&); Null& operator=(const Null&); - static const std::shared_ptr<Null> nullValue_; }; class List:public ValueBase { public: - typedef std::vector<std::shared_ptr<ValueBase> > ValueType; + typedef std::vector<std::unique_ptr<ValueBase>> ValueType; List(); - ~List(); - // Don't allow copying - List(const List&); - List& operator=(const List&); + List(const List&) = delete; + List& operator=(const List&) = delete; // Appends given v to list. - void append(const std::shared_ptr<ValueBase>& v); + void append(std::unique_ptr<ValueBase> v); // Appeding string is so common that we provide shortcut function. - void append(const String::ValueType& string); + void append(String::ValueType string); // Alias for append() - List& operator<<(const std::shared_ptr<ValueBase>& v); + List& operator<<(std::unique_ptr<ValueBase> v); // Returns the object at given index. - const std::shared_ptr<ValueBase>& get(size_t index) const; + ValueBase* get(size_t index) const; // Set the object at given index. - void set(size_t index, const std::shared_ptr<ValueBase>& v); + void set(size_t index, std::unique_ptr<ValueBase> v); // Returns the const reference of the object at the given index. - const std::shared_ptr<ValueBase>& operator[](size_t index) const; + ValueBase* operator[](size_t index) const; // Returns a read/write iterator that points to the first object in // list. @@ -217,13 +212,21 @@ public: // past the last object in list. ValueType::const_iterator end() const; + // Returns a read/write read-only iterator that points to the first + // object in list. + ValueType::const_iterator cbegin() const; + + // Returns a read/write read-only iterator that points to the one + // past the last object in list. + ValueType::const_iterator cend() const; + // Returns size of list. size_t size() const; // Returns true if size of list is 0. bool empty() const; - static std::shared_ptr<List> g(); + static std::unique_ptr<List> g(); virtual void accept(ValueBaseVisitor& visitor) const CXX11_OVERRIDE; private: @@ -232,34 +235,24 @@ private: class Dict:public ValueBase { public: - typedef std::map<std::string, std::shared_ptr<ValueBase> > ValueType; + typedef std::map<std::string, std::unique_ptr<ValueBase>> ValueType; Dict(); - ~Dict(); - // Don't allow copying - Dict(const Dict&); - Dict& operator=(const Dict&); + Dict(const Dict&) = delete; + Dict& operator=(const Dict&) = delete; - void put(const std::string& key, const std::shared_ptr<ValueBase>& vlb); + void put(std::string key, std::unique_ptr<ValueBase> vlb); // Putting string is so common that we provide shortcut function. - void put(const std::string& key, const String::ValueType& string); + void put(std::string key, String::ValueType string); - const std::shared_ptr<ValueBase>& get(const std::string& key) const; - - std::shared_ptr<ValueBase>& get(const std::string& key); + ValueBase* get(const std::string& key) const; // Returns the reference to object associated with given key. If - // the key is not found, new pair with that key is created using - // default values, which is then returned. In other words, this is - // the same behavior of std::map's operator[]. - std::shared_ptr<ValueBase>& operator[](const std::string& key); - - // Returns the const reference to ojbect associated with given key. - // If the key is not found, ValueBase::none is returned. - const std::shared_ptr<ValueBase>& operator[](const std::string& key) const; + // the key is not found, nullptr is returned. + ValueBase* operator[](const std::string& key) const; // Returns true if the given key is found in dict. bool containsKey(const std::string& key) const; @@ -267,6 +260,9 @@ public: // Removes specified key from dict. void removeKey(const std::string& key); + // Removes specified key from dict and return its associated value. + std::unique_ptr<ValueBase> popValue(const std::string& key); + // Returns a read/write iterator that points to the first pair in // the dict. ValueType::iterator begin(); @@ -283,13 +279,21 @@ public: // the last pair in the dict. ValueType::const_iterator end() const; + // Returns a read/write read-only iterator that points to the first + // pair in the dict. + ValueType::const_iterator cbegin() const; + + // Returns a read/write read-only iterator that points to one past + // the last pair in the dict. + ValueType::const_iterator cend() const; + // Returns size of Dict. size_t size() const; // Returns true if size of Dict is 0. bool empty() const; - static std::shared_ptr<Dict> g(); + static std::unique_ptr<Dict> g(); virtual void accept(ValueBaseVisitor& visitor) const CXX11_OVERRIDE; private: @@ -310,7 +314,7 @@ public: template<typename T> class DowncastValueBaseVisitor:public EmptyDowncastValueBaseVisitor { public: - DowncastValueBaseVisitor():result_(0) {} + DowncastValueBaseVisitor() : result_{nullptr} {} virtual void visit(const T& t) CXX11_OVERRIDE { diff --git a/src/ValueBaseDiskWriter.h b/src/ValueBaseDiskWriter.h index c44389ab..311bb31c 100644 --- a/src/ValueBaseDiskWriter.h +++ b/src/ValueBaseDiskWriter.h @@ -94,7 +94,7 @@ public: return parser_.parseFinal(0, 0); } - std::shared_ptr<ValueBase> getResult() const + std::unique_ptr<ValueBase> getResult() { return psm_.getResult(); } diff --git a/src/ValueBaseStructParserStateMachine.cc b/src/ValueBaseStructParserStateMachine.cc index 4f63ed14..705ce014 100644 --- a/src/ValueBaseStructParserStateMachine.cc +++ b/src/ValueBaseStructParserStateMachine.cc @@ -65,22 +65,20 @@ NullValueBaseStructParserState* nullState = new NullValueBaseStructParserState(); } // namespace -const std::shared_ptr<ValueBase>& +std::unique_ptr<ValueBase> ValueBaseStructParserStateMachine::noResult() { - return ValueBase::none; + return nullptr; } ValueBaseStructParserStateMachine::ValueBaseStructParserStateMachine() - : ctrl_(new rpc::XmlRpcRequestParserController()) + : ctrl_{make_unique<rpc::XmlRpcRequestParserController>()} { stateStack_.push(valueState); } ValueBaseStructParserStateMachine::~ValueBaseStructParserStateMachine() -{ - delete ctrl_; -} +{} void ValueBaseStructParserStateMachine::reset() { @@ -102,10 +100,9 @@ void ValueBaseStructParserStateMachine::endElement(int elementType) stateStack_.pop(); } -std::shared_ptr<ValueBase> -ValueBaseStructParserStateMachine::getResult() const +std::unique_ptr<ValueBase> ValueBaseStructParserStateMachine::getResult() { - return getCurrentFrameValue(); + return popCurrentFrameValue(); } void ValueBaseStructParserStateMachine::charactersCallback @@ -159,21 +156,26 @@ void ValueBaseStructParserStateMachine::pushFrame() } void ValueBaseStructParserStateMachine::setCurrentFrameValue -(const std::shared_ptr<ValueBase>& value) +(std::unique_ptr<ValueBase> value) { - ctrl_->setCurrentFrameValue(value); + ctrl_->setCurrentFrameValue(std::move(value)); } -const std::shared_ptr<ValueBase>& +const std::unique_ptr<ValueBase>& ValueBaseStructParserStateMachine::getCurrentFrameValue() const { return ctrl_->getCurrentFrameValue(); } -void ValueBaseStructParserStateMachine::setCurrentFrameName -(const std::string& name) +std::unique_ptr<ValueBase> +ValueBaseStructParserStateMachine::popCurrentFrameValue() +{ + return ctrl_->popCurrentFrameValue(); +} + +void ValueBaseStructParserStateMachine::setCurrentFrameName(std::string name) { - ctrl_->setCurrentFrameName(name); + ctrl_->setCurrentFrameName(std::move(name)); } void ValueBaseStructParserStateMachine::pushDictState() diff --git a/src/ValueBaseStructParserStateMachine.h b/src/ValueBaseStructParserStateMachine.h index 38834438..a4b0c513 100644 --- a/src/ValueBaseStructParserStateMachine.h +++ b/src/ValueBaseStructParserStateMachine.h @@ -55,8 +55,8 @@ class ValueBaseStructParserState; // value holder. class ValueBaseStructParserStateMachine : public StructParserStateMachine { public: - typedef std::shared_ptr<ValueBase> ResultType; - static const std::shared_ptr<ValueBase>& noResult(); + typedef std::unique_ptr<ValueBase> ResultType; + static std::unique_ptr<ValueBase> noResult(); struct NumberData { int64_t number; @@ -82,7 +82,7 @@ public: CXX11_OVERRIDE; virtual void boolCallback(bool bval) CXX11_OVERRIDE; - std::shared_ptr<ValueBase> getResult() const; + std::unique_ptr<ValueBase> getResult(); virtual void reset() CXX11_OVERRIDE; @@ -93,9 +93,10 @@ public: void popArrayFrame(); void popDictFrame(); void pushFrame(); - void setCurrentFrameValue(const std::shared_ptr<ValueBase>& value); - const std::shared_ptr<ValueBase>& getCurrentFrameValue() const; - void setCurrentFrameName(const std::string& name); + void setCurrentFrameValue(std::unique_ptr<ValueBase> value); + const std::unique_ptr<ValueBase>& getCurrentFrameValue() const; + std::unique_ptr<ValueBase> popCurrentFrameValue(); + void setCurrentFrameName(std::string name); void pushDictState(); void pushDictKeyState(); @@ -107,7 +108,7 @@ public: void pushBoolState(); void pushNullState(); private: - rpc::XmlRpcRequestParserController* ctrl_; + std::unique_ptr<rpc::XmlRpcRequestParserController> ctrl_; std::stack<ValueBaseStructParserState*> stateStack_; SessionData sessionData_; }; diff --git a/src/WebSocketSession.cc b/src/WebSocketSession.cc index 6baa70bd..2e3d28a2 100644 --- a/src/WebSocketSession.cc +++ b/src/WebSocketSession.cc @@ -160,7 +160,7 @@ void onMsgRecvCallback(wslay_event_context_ptr wsctx, if(!wslay_is_ctrl_frame(arg->opcode)) { // TODO Only process text frame ssize_t error = 0; - std::shared_ptr<ValueBase> json = wsSession->parseFinal(0, 0, error); + auto json = wsSession->parseFinal(0, 0, error); if(error < 0) { A2_LOG_INFO("Failed to parse JSON-RPC request"); RpcResponse res @@ -168,23 +168,22 @@ void onMsgRecvCallback(wslay_event_context_ptr wsctx, addResponse(wsSession, res); return; } - const Dict* jsondict = downcast<Dict>(json); + Dict* jsondict = downcast<Dict>(json); if(jsondict) { RpcResponse res = processJsonRpcRequest(jsondict, wsSession->getDownloadEngine()); addResponse(wsSession, res); } else { - const List* jsonlist = downcast<List>(json); + List* jsonlist = downcast<List>(json); if(jsonlist) { // This is batch call std::vector<RpcResponse> results; for(List::ValueType::const_iterator i = jsonlist->begin(), eoi = jsonlist->end(); i != eoi; ++i) { - const Dict* jsondict = downcast<Dict>(*i); + Dict* jsondict = downcast<Dict>(*i); if(jsondict) { - RpcResponse r = processJsonRpcRequest - (jsondict, wsSession->getDownloadEngine()); - results.push_back(r); + results.push_back(processJsonRpcRequest + (jsondict, wsSession->getDownloadEngine())); } } addResponse(wsSession, results); @@ -292,10 +291,10 @@ ssize_t WebSocketSession::parseUpdate(const uint8_t* data, size_t len) return parser_.parseUpdate(reinterpret_cast<const char*>(data), len); } -std::shared_ptr<ValueBase> WebSocketSession::parseFinal +std::unique_ptr<ValueBase> WebSocketSession::parseFinal (const uint8_t* data, size_t len, ssize_t& error) { - std::shared_ptr<ValueBase> res = + auto res = parser_.parseFinal(reinterpret_cast<const char*>(data), len, error); receivedLength_ = 0; return res; diff --git a/src/WebSocketSession.h b/src/WebSocketSession.h index 4cd21fb9..05957460 100644 --- a/src/WebSocketSession.h +++ b/src/WebSocketSession.h @@ -86,8 +86,8 @@ public: // |error| will be the number of bytes processed if this function // succeeds, or negative error code. Whether success or failure, // this function resets parser state and receivedLength_. - std::shared_ptr<ValueBase> parseFinal(const uint8_t* data, size_t len, - ssize_t& error); + std::unique_ptr<ValueBase> parseFinal(const uint8_t* data, size_t len, + ssize_t& error); const std::shared_ptr<SocketCore>& getSocket() const { diff --git a/src/WebSocketSessionMan.cc b/src/WebSocketSessionMan.cc index edc961f0..1dab1201 100644 --- a/src/WebSocketSessionMan.cc +++ b/src/WebSocketSessionMan.cc @@ -68,15 +68,15 @@ void WebSocketSessionMan::removeSession void WebSocketSessionMan::addNotification (const std::string& method, const RequestGroup* group) { - std::shared_ptr<Dict> dict = Dict::g(); + auto dict = Dict::g(); dict->put("jsonrpc", "2.0"); dict->put("method", method); - std::shared_ptr<Dict> eventSpec = Dict::g(); + auto eventSpec = Dict::g(); eventSpec->put("gid", GroupId::toHex((group->getGID()))); - std::shared_ptr<List> params = List::g(); - params->append(eventSpec); - dict->put("params", params); - std::string msg = json::encode(dict); + auto params = List::g(); + params->append(std::move(eventSpec)); + dict->put("params", std::move(params)); + std::string msg = json::encode(dict.get()); for(WebSocketSessions::const_iterator i = sessions_.begin(), eoi = sessions_.end(); i != eoi; ++i) { (*i)->addTextMessage(msg); diff --git a/src/XmlRpcDiskWriter.cc b/src/XmlRpcDiskWriter.cc index 9aabd3cc..bfa8a92c 100644 --- a/src/XmlRpcDiskWriter.cc +++ b/src/XmlRpcDiskWriter.cc @@ -65,15 +65,15 @@ int XmlRpcDiskWriter::finalize() return parser_.parseFinal(0, 0); } -RpcRequest XmlRpcDiskWriter::getResult() const +RpcRequest XmlRpcDiskWriter::getResult() { - std::shared_ptr<List> params; + std::unique_ptr<List> params; if(downcast<List>(psm_.getCurrentFrameValue())) { - params = std::static_pointer_cast<List>(psm_.getCurrentFrameValue()); + params.reset(static_cast<List*>(psm_.popCurrentFrameValue().release())); } else { params = List::g(); } - return RpcRequest(psm_.getMethodName(), params); + return RpcRequest{psm_.getMethodName(), std::move(params)}; } int XmlRpcDiskWriter::reset() diff --git a/src/XmlRpcDiskWriter.h b/src/XmlRpcDiskWriter.h index b40cdc55..8eee3cad 100644 --- a/src/XmlRpcDiskWriter.h +++ b/src/XmlRpcDiskWriter.h @@ -83,7 +83,7 @@ public: } int finalize(); - RpcRequest getResult() const; + RpcRequest getResult(); int reset(); private: XmlRpcRequestParserStateMachine psm_; diff --git a/src/XmlRpcRequestParserController.cc b/src/XmlRpcRequestParserController.cc index 3401a4cd..067df858 100644 --- a/src/XmlRpcRequestParserController.cc +++ b/src/XmlRpcRequestParserController.cc @@ -42,7 +42,7 @@ namespace rpc { void XmlRpcRequestParserController::pushFrame() { - frameStack_.push(currentFrame_); + frameStack_.push(std::move(currentFrame_)); currentFrame_ = StateFrame(); } @@ -50,48 +50,54 @@ void XmlRpcRequestParserController::popStructFrame() { assert(!frameStack_.empty()); - StateFrame parentFrame = frameStack_.top(); + StateFrame parentFrame = std::move(frameStack_.top()); Dict* dict = downcast<Dict>(parentFrame.value_); assert(dict); frameStack_.pop(); if(currentFrame_.validMember()) { - dict->put(currentFrame_.name_, currentFrame_.value_); + dict->put(std::move(currentFrame_.name_), std::move(currentFrame_.value_)); } - currentFrame_ = parentFrame; + currentFrame_ = std::move(parentFrame); } void XmlRpcRequestParserController::popArrayFrame() { assert(!frameStack_.empty()); - StateFrame parentFrame = frameStack_.top(); + StateFrame parentFrame = std::move(frameStack_.top()); List* list = downcast<List>(parentFrame.value_); assert(list); frameStack_.pop(); if(currentFrame_.value_) { - list->append(currentFrame_.value_); + list->append(std::move(currentFrame_.value_)); } - currentFrame_ = parentFrame; + currentFrame_ = std::move(parentFrame); } void XmlRpcRequestParserController::setCurrentFrameValue -(const std::shared_ptr<ValueBase>& value) +(std::unique_ptr<ValueBase> value) { - currentFrame_.value_ = value; + currentFrame_.value_ = std::move(value); } void XmlRpcRequestParserController::setCurrentFrameName -(const std::string& name) +(std::string name) { - currentFrame_.name_ = name; + currentFrame_.name_ = std::move(name); } -const std::shared_ptr<ValueBase>& +const std::unique_ptr<ValueBase>& XmlRpcRequestParserController::getCurrentFrameValue() const { return currentFrame_.value_; } +std::unique_ptr<ValueBase> +XmlRpcRequestParserController::popCurrentFrameValue() +{ + return std::move(currentFrame_.value_); +} + void XmlRpcRequestParserController::reset() { while(!frameStack_.empty()) { @@ -101,6 +107,11 @@ void XmlRpcRequestParserController::reset() methodName_.clear(); } +void XmlRpcRequestParserController::setMethodName(std::string methodName) +{ + methodName_ = std::move(methodName); +} + } // namespace rpc } // namespace aria2 diff --git a/src/XmlRpcRequestParserController.h b/src/XmlRpcRequestParserController.h index 36fa86f0..2cb3eb64 100644 --- a/src/XmlRpcRequestParserController.h +++ b/src/XmlRpcRequestParserController.h @@ -50,7 +50,7 @@ class XmlRpcRequestParserController { private: struct StateFrame { - std::shared_ptr<ValueBase> value_; + std::unique_ptr<ValueBase> value_; std::string name_; bool validMember() const @@ -81,16 +81,15 @@ public: // to p and currentFrame_ = p; void popArrayFrame(); - void setCurrentFrameValue(const std::shared_ptr<ValueBase>& value); + void setCurrentFrameValue(std::unique_ptr<ValueBase> value); - void setCurrentFrameName(const std::string& name); + void setCurrentFrameName(std::string name); - const std::shared_ptr<ValueBase>& getCurrentFrameValue() const; + const std::unique_ptr<ValueBase>& getCurrentFrameValue() const; - void setMethodName(const std::string& methodName) - { - methodName_ = methodName; - } + std::unique_ptr<ValueBase> popCurrentFrameValue(); + + void setMethodName(std::string methodName); const std::string& getMethodName() const { return methodName_; } diff --git a/src/XmlRpcRequestParserStateMachine.cc b/src/XmlRpcRequestParserStateMachine.cc index 22b90246..73917a49 100644 --- a/src/XmlRpcRequestParserStateMachine.cc +++ b/src/XmlRpcRequestParserStateMachine.cc @@ -166,17 +166,23 @@ void XmlRpcRequestParserStateMachine::pushFrame() } void XmlRpcRequestParserStateMachine::setCurrentFrameValue -(const std::shared_ptr<ValueBase>& value) +(std::unique_ptr<ValueBase> value) { - controller_->setCurrentFrameValue(value); + controller_->setCurrentFrameValue(std::move(value)); } -const std::shared_ptr<ValueBase>& +const std::unique_ptr<ValueBase>& XmlRpcRequestParserStateMachine::getCurrentFrameValue() const { return controller_->getCurrentFrameValue(); } +std::unique_ptr<ValueBase> +XmlRpcRequestParserStateMachine::popCurrentFrameValue() +{ + return controller_->popCurrentFrameValue(); +} + void XmlRpcRequestParserStateMachine::setCurrentFrameName (const std::string& name) { diff --git a/src/XmlRpcRequestParserStateMachine.h b/src/XmlRpcRequestParserStateMachine.h index 2fb423c4..cbc0f419 100644 --- a/src/XmlRpcRequestParserStateMachine.h +++ b/src/XmlRpcRequestParserStateMachine.h @@ -77,8 +77,9 @@ public: void popArrayFrame(); void popStructFrame(); void pushFrame(); - void setCurrentFrameValue(const std::shared_ptr<ValueBase>& value); - const std::shared_ptr<ValueBase>& getCurrentFrameValue() const; + void setCurrentFrameValue(std::unique_ptr<ValueBase> value); + const std::unique_ptr<ValueBase>& getCurrentFrameValue() const; + std::unique_ptr<ValueBase> popCurrentFrameValue(); void setCurrentFrameName(const std::string& name); void pushUnknownElementState(); diff --git a/src/bencode2.cc b/src/bencode2.cc index 81b14403..8c3dab16 100644 --- a/src/bencode2.cc +++ b/src/bencode2.cc @@ -47,25 +47,25 @@ namespace aria2 { namespace bencode2 { -std::shared_ptr<ValueBase> decode(const unsigned char* data, size_t len) +std::unique_ptr<ValueBase> decode(const unsigned char* data, size_t len) { size_t end; return decode(data, len, end); } -std::shared_ptr<ValueBase> decode(const std::string& data) +std::unique_ptr<ValueBase> decode(const std::string& data) { size_t end; return decode(reinterpret_cast<const unsigned char*>(data.c_str()), data.size(), end); } -std::shared_ptr<ValueBase> decode(const unsigned char* data, size_t len, - size_t& end) +std::unique_ptr<ValueBase> decode(const unsigned char* data, size_t len, + size_t& end) { ssize_t error; bittorrent::ValueBaseBencodeParser parser; - std::shared_ptr<ValueBase> res = + auto res = parser.parseFinal(reinterpret_cast<const char*>(data), len, error); if(error < 0) { throw DL_ABORT_EX2(fmt("Bencode decoding failed: error=%d", @@ -130,11 +130,6 @@ std::string encode(const ValueBase* vlb) return visitor.getResult(); } -std::string encode(const std::shared_ptr<ValueBase>& vlb) -{ - return encode(vlb.get()); -} - } // namespace bencode2 } // namespace aria2 diff --git a/src/bencode2.h b/src/bencode2.h index e3896a3e..96e33b24 100644 --- a/src/bencode2.h +++ b/src/bencode2.h @@ -46,21 +46,19 @@ namespace aria2 { namespace bencode2 { // Decode the data whose length is len. -std::shared_ptr<ValueBase> decode(const unsigned char* data, size_t len); +std::unique_ptr<ValueBase> decode(const unsigned char* data, size_t len); -std::shared_ptr<ValueBase> decode(const std::string& data); +std::unique_ptr<ValueBase> decode(const std::string& data); // Decode the data whose length is len. After decode is done // successfully, return the bencoded string length in end. -std::shared_ptr<ValueBase> decode(const unsigned char* data, size_t len, - size_t& end); +std::unique_ptr<ValueBase> decode(const unsigned char* data, size_t len, + size_t& end); -std::shared_ptr<ValueBase> decodeFromFile(const std::string& filename); +std::unique_ptr<ValueBase> decodeFromFile(const std::string& filename); std::string encode(const ValueBase* vlb); -std::string encode(const std::shared_ptr<ValueBase>& vlb); - } // namespace bencode2 } // namespace aria2 diff --git a/src/bittorrent_helper.cc b/src/bittorrent_helper.cc index 238d2c0e..3deba170 100644 --- a/src/bittorrent_helper.cc +++ b/src/bittorrent_helper.cc @@ -406,7 +406,7 @@ void extractNodes(TorrentAttribute* torrent, const ValueBase* nodesListSrc) namespace { void processRootDictionary (const std::shared_ptr<DownloadContext>& ctx, - const std::shared_ptr<ValueBase>& root, + const ValueBase* root, const std::shared_ptr<Option>& option, const std::string& defaultName, const std::string& overrideName, @@ -422,7 +422,7 @@ void processRootDictionary throw DL_ABORT_EX2(fmt(MSG_MISSING_BT_INFO, C_INFO.c_str()), error_code::BITTORRENT_PARSE_ERROR); } - std::unique_ptr<TorrentAttribute> torrent(new TorrentAttribute()); + auto torrent = make_unique<TorrentAttribute>(); // retrieve infoHash std::string encodedInfoDict = bencode2::encode(infoDict); @@ -475,7 +475,7 @@ void processRootDictionary // This implemantation obeys HTTP-Seeding specification: // see http://www.getright.com/seedtorrent.html std::vector<std::string> urlList; - extractUrlList(torrent.get(), urlList, rootDict->get(C_URL_LIST).get()); + extractUrlList(torrent.get(), urlList, rootDict->get(C_URL_LIST)); urlList.insert(urlList.end(), uris.begin(), uris.end()); std::sort(urlList.begin(), urlList.end()); urlList.erase(std::unique(urlList.begin(), urlList.end()), urlList.end()); @@ -490,7 +490,7 @@ void processRootDictionary // retrieve announce extractAnnounce(torrent.get(), rootDict); // retrieve nodes - extractNodes(torrent.get(), rootDict->get(C_NODES).get()); + extractNodes(torrent.get(), rootDict->get(C_NODES)); const Integer* creationDate = downcast<Integer>(rootDict->get(C_CREATION_DATE)); if(creationDate) { @@ -521,7 +521,7 @@ void load(const std::string& torrentFile, { ValueBaseBencodeParser parser; processRootDictionary(ctx, - parseFile(parser, torrentFile), + parseFile(parser, torrentFile).get(), option, torrentFile, overrideName, @@ -536,7 +536,7 @@ void load(const std::string& torrentFile, { ValueBaseBencodeParser parser; processRootDictionary(ctx, - parseFile(parser, torrentFile), + parseFile(parser, torrentFile).get(), option, torrentFile, overrideName, @@ -551,7 +551,7 @@ void loadFromMemory(const unsigned char* content, const std::string& overrideName) { processRootDictionary(ctx, - bencode2::decode(content, length), + bencode2::decode(content, length).get(), option, defaultName, overrideName, @@ -567,7 +567,7 @@ void loadFromMemory(const unsigned char* content, const std::string& overrideName) { processRootDictionary(ctx, - bencode2::decode(content, length), + bencode2::decode(content, length).get(), option, defaultName, overrideName, @@ -582,7 +582,7 @@ void loadFromMemory(const std::string& context, { processRootDictionary (ctx, - bencode2::decode(context), + bencode2::decode(context).get(), option, defaultName, overrideName, std::vector<std::string>()); @@ -597,13 +597,13 @@ void loadFromMemory(const std::string& context, { processRootDictionary (ctx, - bencode2::decode(context), + bencode2::decode(context).get(), option, defaultName, overrideName, uris); } -void loadFromMemory(const std::shared_ptr<ValueBase>& torrent, +void loadFromMemory(const ValueBase* torrent, const std::shared_ptr<DownloadContext>& ctx, const std::shared_ptr<Option>& option, const std::vector<std::string>& uris, @@ -905,7 +905,7 @@ void assertID std::unique_ptr<TorrentAttribute> parseMagnet(const std::string& magnet) { - std::shared_ptr<Dict> r = magnet::parse(magnet); + auto r = magnet::parse(magnet); if(!r) { throw DL_ABORT_EX2("Bad BitTorrent Magnet URI.", error_code::MAGNET_PARSE_ERROR); @@ -917,8 +917,8 @@ std::unique_ptr<TorrentAttribute> parseMagnet(const std::string& magnet) } auto attrs = make_unique<TorrentAttribute>(); std::string infoHash; - for(List::ValueType::const_iterator xtiter = xts->begin(), - eoi = xts->end(); xtiter != eoi && infoHash.empty(); ++xtiter) { + for(auto xtiter = xts->begin(), eoi = xts->end(); + xtiter != eoi && infoHash.empty(); ++xtiter) { const String* xt = downcast<String>(*xtiter); if(util::startsWith(xt->s(), "urn:btih:")) { size_t size = xt->s().end()-xt->s().begin()-9; @@ -942,8 +942,7 @@ std::unique_ptr<TorrentAttribute> parseMagnet(const std::string& magnet) } const List* trs = downcast<List>(r->get("tr")); if(trs) { - for(List::ValueType::const_iterator i = trs->begin(), eoi = trs->end(); - i != eoi; ++i) { + for(auto i = trs->begin(), eoi = trs->end(); i != eoi; ++i) { std::vector<std::string> tier; tier.push_back(util::encodeNonUtf8(downcast<String>(*i)->s())); attrs->announceList.push_back(tier); @@ -974,16 +973,14 @@ std::string metadata2Torrent std::string torrent = "d"; List announceList; - for(std::vector<std::vector<std::string> >::const_iterator tierIter = - attrs->announceList.begin(), + for(auto tierIter = attrs->announceList.begin(), eoi = attrs->announceList.end(); tierIter != eoi; ++tierIter) { - std::shared_ptr<List> tier = List::g(); - for(std::vector<std::string>::const_iterator uriIter = (*tierIter).begin(), - eoi2 = (*tierIter).end(); uriIter != eoi2; ++uriIter) { - tier->append(String::g(*uriIter)); + auto tier = List::g(); + for(auto& uri : *tierIter) { + tier->append(uri); } if(!tier->empty()) { - announceList.append(tier); + announceList.append(std::move(tier)); } } if(!announceList.empty()) { diff --git a/src/bittorrent_helper.h b/src/bittorrent_helper.h index d6d93400..1587e065 100644 --- a/src/bittorrent_helper.h +++ b/src/bittorrent_helper.h @@ -101,7 +101,7 @@ void loadFromMemory(const std::string& context, const std::string& defaultName, const std::string& overrideName = ""); -void loadFromMemory(const std::shared_ptr<ValueBase>& torrent, +void loadFromMemory(const ValueBase* torrent, const std::shared_ptr<DownloadContext>& ctx, const std::shared_ptr<Option>& option, const std::vector<std::string>& uris, @@ -328,13 +328,6 @@ void extractPeer(const ValueBase* peerData, int family, OutputIterator dest) } } -template<typename OutputIterator> -void extractPeer -(const std::shared_ptr<ValueBase>& peerData, int family, OutputIterator dest) -{ - return extractPeer(peerData.get(), family, dest); -} - int getCompactLength(int family); // Returns textual representation of the |mode|. diff --git a/src/download_helper.cc b/src/download_helper.cc index a6ba4aea..f38f8fa4 100644 --- a/src/download_helper.cc +++ b/src/download_helper.cc @@ -185,7 +185,7 @@ std::shared_ptr<RequestGroup> createBtRequestGroup(const std::string& metaInfoUri, const std::shared_ptr<Option>& optionTemplate, const std::vector<std::string>& auxUris, - const std::shared_ptr<ValueBase>& torrent, + const ValueBase* torrent, bool adjustAnnounceUri = true) { auto option = util::copy(optionTemplate); @@ -264,7 +264,7 @@ void createRequestGroupForBitTorrent const std::string& torrentData, bool adjustAnnounceUri) { - std::shared_ptr<ValueBase> torrent; + std::unique_ptr<ValueBase> torrent; bittorrent::ValueBaseBencodeParser parser; if(torrentData.empty()) { torrent = parseFile(parser, metaInfoUri); @@ -277,7 +277,8 @@ void createRequestGroupForBitTorrent throw DL_ABORT_EX2("Bencode decoding failed", error_code::BENCODE_PARSE_ERROR); } - createRequestGroupForBitTorrent(result, option, uris, metaInfoUri, torrent); + createRequestGroupForBitTorrent(result, option, uris, metaInfoUri, + torrent.get()); } void createRequestGroupForBitTorrent @@ -285,7 +286,7 @@ void createRequestGroupForBitTorrent const std::shared_ptr<Option>& option, const std::vector<std::string>& uris, const std::string& metaInfoUri, - const std::shared_ptr<ValueBase>& torrent, + const ValueBase* torrent, bool adjustAnnounceUri) { std::vector<std::string> nargs; @@ -369,7 +370,7 @@ public: error_code::BENCODE_PARSE_ERROR); } requestGroups_.push_back - (createBtRequestGroup(uri, option_, {}, torrent)); + (createBtRequestGroup(uri, option_, {}, torrent.get())); } catch(RecoverableException& e) { if(throwOnError_) { throw; diff --git a/src/download_helper.h b/src/download_helper.h index ae6ce55b..2e098319 100644 --- a/src/download_helper.h +++ b/src/download_helper.h @@ -76,7 +76,7 @@ void createRequestGroupForBitTorrent const std::shared_ptr<Option>& option, const std::vector<std::string>& uris, const std::string& metaInfoUri, - const std::shared_ptr<ValueBase>& torrent, + const ValueBase* torrent, bool adjustAnnounceUri = true); #endif // ENABLE_BITTORRENT diff --git a/src/json.cc b/src/json.cc index 131b9755..f2481f7f 100644 --- a/src/json.cc +++ b/src/json.cc @@ -85,10 +85,10 @@ std::string jsonEscape(const std::string& s) } // Serializes JSON object or array. -std::string encode(const std::shared_ptr<ValueBase>& json) +std::string encode(const ValueBase* json) { std::ostringstream out; - return encode(out, json.get()).str(); + return encode(out, json).str(); } JsonGetParam::JsonGetParam @@ -47,7 +47,7 @@ std::string jsonEscape(const std::string& s); template<typename OutputStream> OutputStream& encode(OutputStream& out, const ValueBase* vlb) { - class JsonValueBaseVisitor:public ValueBaseVisitor { + class JsonValueBaseVisitor : public ValueBaseVisitor { public: JsonValueBaseVisitor(OutputStream& out):out_(out) {} @@ -74,11 +74,11 @@ OutputStream& encode(OutputStream& out, const ValueBase* vlb) virtual void visit(const List& list) CXX11_OVERRIDE { out_ << "["; - List::ValueType::const_iterator i = list.begin(); if(!list.empty()) { + auto i = list.begin(); (*i)->accept(*this); ++i; - for(List::ValueType::const_iterator eoi = list.end(); i != eoi; ++i){ + for(auto eoi = list.end(); i != eoi; ++i){ out_ << ","; (*i)->accept(*this); } @@ -89,13 +89,13 @@ OutputStream& encode(OutputStream& out, const ValueBase* vlb) virtual void visit(const Dict& dict) CXX11_OVERRIDE { out_ << "{"; - Dict::ValueType::const_iterator i = dict.begin(); if(!dict.empty()) { + auto i = dict.begin(); encodeString((*i).first); out_ << ":"; (*i).second->accept(*this); ++i; - for(Dict::ValueType::const_iterator eoi = dict.end(); i != eoi; ++i){ + for(auto eoi = dict.end(); i != eoi; ++i){ out_ << ","; encodeString((*i).first); out_ << ":"; @@ -107,8 +107,7 @@ OutputStream& encode(OutputStream& out, const ValueBase* vlb) private: void encodeString(const std::string& s) { - std::string t = jsonEscape(s); - out_ << "\"" << t << "\""; + out_ << "\"" << jsonEscape(s) << "\""; } OutputStream& out_; }; @@ -117,14 +116,8 @@ OutputStream& encode(OutputStream& out, const ValueBase* vlb) return out; } -template<typename OutputStream> -OutputStream& encode(OutputStream& out, const std::shared_ptr<ValueBase>& vlb) -{ - return encode(out, vlb.get()); -} - // Serializes JSON object or array. -std::string encode(const std::shared_ptr<ValueBase>& json); +std::string encode(const ValueBase* json); struct JsonGetParam { std::string request; diff --git a/src/magnet.cc b/src/magnet.cc index f2e5e89a..96fbf2f4 100644 --- a/src/magnet.cc +++ b/src/magnet.cc @@ -40,13 +40,12 @@ namespace aria2 { namespace magnet { -std::shared_ptr<Dict> parse(const std::string& magnet) +std::unique_ptr<Dict> parse(const std::string& magnet) { - std::shared_ptr<Dict> dict; if(!util::startsWith(magnet, "magnet:?")) { - return dict; + return nullptr; } - dict.reset(new Dict()); + auto dict = Dict::g(); std::vector<Scip> queries; util::splitIter(magnet.begin()+8, magnet.end(), std::back_inserter(queries), '&'); @@ -59,9 +58,9 @@ std::shared_ptr<Dict> parse(const std::string& magnet) if(l) { l->append(String::g(value)); } else { - std::shared_ptr<List> l = List::g(); + auto l = List::g(); l->append(String::g(value)); - dict->put(name, l); + dict->put(name, std::move(l)); } } return dict; diff --git a/src/magnet.h b/src/magnet.h index 4cb34246..cce03dbc 100644 --- a/src/magnet.h +++ b/src/magnet.h @@ -42,12 +42,11 @@ namespace aria2 { namespace magnet { -// Parses Magnet URI magnet and stores parameters in -// std::shared_ptr<Dict>. Because same parameter name can appear more -// than once, the value associated with a key is std::shared_ptr<List>. A -// parameter value is stored in a list. If parsing operation failed, -// std::shared_ptr<Dict>() is returned. -std::shared_ptr<Dict> parse(const std::string& magnet); +// Parses Magnet URI magnet and returns the result. Because same +// parameter name can appear more than once, the value associated with +// a key is std::unique_ptr<List>. A parameter value is stored in a +// list. If parsing operation failed, nullptr is returned. +std::unique_ptr<Dict> parse(const std::string& magnet); } // namespace magnet diff --git a/src/rpc_helper.cc b/src/rpc_helper.cc index 8b372908..3b953e15 100644 --- a/src/rpc_helper.cc +++ b/src/rpc_helper.cc @@ -56,59 +56,59 @@ RpcRequest xmlParseMemory(const char* xml, size_t size) if(xml::XmlParser(&psm).parseFinal(xml, size) < 0) { throw DL_ABORT_EX(MSG_CANNOT_PARSE_XML_RPC_REQUEST); } - std::shared_ptr<List> params; + std::unique_ptr<List> params; if(downcast<List>(psm.getCurrentFrameValue())) { - params = std::static_pointer_cast<List>(psm.getCurrentFrameValue()); + params.reset(static_cast<List*>(psm.popCurrentFrameValue().release())); } else { params = List::g(); } - return RpcRequest(psm.getMethodName(), params); + return {psm.getMethodName(), std::move(params)}; } #endif // ENABLE_XML_RPC RpcResponse createJsonRpcErrorResponse(int code, const std::string& msg, - const std::shared_ptr<ValueBase>& id) + std::unique_ptr<ValueBase> id) { - std::shared_ptr<Dict> params = Dict::g(); + auto params = Dict::g(); params->put("code", Integer::g(code)); params->put("message", msg); - rpc::RpcResponse res(code, params, id); - return res; + return rpc::RpcResponse{code, std::move(params), std::move(id)}; } -RpcResponse processJsonRpcRequest(const Dict* jsondict, DownloadEngine* e) +RpcResponse processJsonRpcRequest(Dict* jsondict, DownloadEngine* e) { - std::shared_ptr<ValueBase> id = jsondict->get("id"); + auto id = jsondict->popValue("id"); if(!id) { return createJsonRpcErrorResponse(-32600, "Invalid Request.", Null::g()); } const String* methodName = downcast<String>(jsondict->get("method")); if(!methodName) { - return createJsonRpcErrorResponse(-32600, "Invalid Request.", id); + return createJsonRpcErrorResponse(-32600, "Invalid Request.", + std::move(id)); } - std::shared_ptr<List> params; - const std::shared_ptr<ValueBase>& tempParams = jsondict->get("params"); + std::unique_ptr<List> params; + auto tempParams = jsondict->popValue("params"); if(downcast<List>(tempParams)) { - params = std::static_pointer_cast<List>(tempParams); + params.reset(static_cast<List*>(tempParams.release())); } else if(!tempParams) { params = List::g(); } else { // TODO No support for Named params - return createJsonRpcErrorResponse(-32602, "Invalid params.", id); + return createJsonRpcErrorResponse(-32602, "Invalid params.", + std::move(id)); } - rpc::RpcRequest req(methodName->s(), params, id); - req.jsonRpc = true; - std::shared_ptr<rpc::RpcMethod> method; + std::shared_ptr<RpcMethod> method; try { - method = rpc::RpcMethodFactory::create(req.methodName); + method = rpc::RpcMethodFactory::create(methodName->s()); } catch(RecoverableException& e) { A2_LOG_INFO_EX(EX_EXCEPTION_CAUGHT, e); - return createJsonRpcErrorResponse(-32601, "Method not found.", id); + return createJsonRpcErrorResponse(-32601, "Method not found.", + std::move(id)); } - A2_LOG_INFO(fmt("Executing RPC method %s", req.methodName.c_str())); - rpc::RpcResponse res = method->execute(req, e); - return res; + A2_LOG_INFO(fmt("Executing RPC method %s", methodName->s().c_str())); + return method->execute({methodName->s(), std::move(params), + std::move(id), true}, e); } } // namespace rpc diff --git a/src/rpc_helper.h b/src/rpc_helper.h index 50e4595e..a1658af6 100644 --- a/src/rpc_helper.h +++ b/src/rpc_helper.h @@ -60,10 +60,10 @@ RpcRequest xmlParseMemory(const char* xml, size_t size); // |msg| is the error message. The |id| is the id of the request . RpcResponse createJsonRpcErrorResponse(int code, const std::string& msg, - const std::shared_ptr<ValueBase>& id); + std::unique_ptr<ValueBase> id); // Processes JSON-RPC request |jsondict| and returns the result. -RpcResponse processJsonRpcRequest(const Dict* jsondict, DownloadEngine* e); +RpcResponse processJsonRpcRequest(Dict* jsondict, DownloadEngine* e); } // namespace rpc diff --git a/test/Bencode2Test.cc b/test/Bencode2Test.cc index e412110e..de6a2642 100644 --- a/test/Bencode2Test.cc +++ b/test/Bencode2Test.cc @@ -23,14 +23,14 @@ void Bencode2Test::testEncode() { { Dict dict; - dict["name"] = String::g("aria2"); - dict["loc"] = Integer::g(80000); - std::shared_ptr<List> files = List::g(); + dict.put("name", String::g("aria2")); + dict.put("loc", Integer::g(80000)); + auto files = List::g(); files->append(String::g("aria2c")); - dict["files"] = files; - std::shared_ptr<Dict> attrs = Dict::g(); + dict.put("files", std::move(files)); + auto attrs = Dict::g(); attrs->put("license", String::g("GPL")); - dict["attrs"] = attrs; + dict.put("attrs", std::move(attrs)); CPPUNIT_ASSERT_EQUAL(std::string("d" "5:attrsd7:license3:GPLe" diff --git a/test/BittorrentHelperTest.cc b/test/BittorrentHelperTest.cc index 263bef89..2562c933 100644 --- a/test/BittorrentHelperTest.cc +++ b/test/BittorrentHelperTest.cc @@ -412,25 +412,25 @@ void BittorrentHelperTest::testGetFileEntries_singleFileUrlListEndsWithSlash() { void BittorrentHelperTest::testLoadFromMemory_multiFileNonUtf8Path() { - std::shared_ptr<List> path = List::g(); + auto path = List::g(); path->append("path"); path->append(fromHex("90a28a")+"E"); - std::shared_ptr<Dict> file = Dict::g(); + auto file = Dict::g(); file->put("length", Integer::g(1024)); - file->put("path", path); - std::shared_ptr<List> files = List::g(); - files->append(file); - std::shared_ptr<Dict> info = Dict::g(); - info->put("files", files); + file->put("path", std::move(path)); + auto files = List::g(); + files->append(std::move(file)); + auto info = Dict::g(); + info->put("files", std::move(files)); info->put("piece length", Integer::g(1024)); info->put("pieces", "01234567890123456789"); info->put("name", fromHex("1b")+"$B%O%m!<"+fromHex("1b")+"(B"); Dict dict; - dict.put("info", info); - std::shared_ptr<DownloadContext> dctx(new DownloadContext()); + dict.put("info", std::move(info)); + auto dctx = std::make_shared<DownloadContext>(); loadFromMemory(bencode2::encode(&dict), dctx, option_, "default"); - const std::shared_ptr<FileEntry>& fe = dctx->getFirstFileEntry(); + auto& fe = dctx->getFirstFileEntry(); CPPUNIT_ASSERT_EQUAL (std::string("./%1B%24B%25O%25m%21%3C%1B%28B/path/%90%A2%8AE"), fe->getPath()); @@ -440,14 +440,14 @@ void BittorrentHelperTest::testLoadFromMemory_multiFileNonUtf8Path() void BittorrentHelperTest::testLoadFromMemory_singleFileNonUtf8Path() { - std::shared_ptr<Dict> info = Dict::g(); + auto info = Dict::g(); info->put("piece length", Integer::g(1024)); info->put("pieces", "01234567890123456789"); info->put("name", fromHex("90a28a")+"E"); info->put("length", Integer::g(1024)); Dict dict; - dict.put("info", info); - std::shared_ptr<DownloadContext> dctx(new DownloadContext()); + dict.put("info", std::move(info)); + auto dctx = std::make_shared<DownloadContext>(); loadFromMemory(bencode2::encode(&dict), dctx, option_, "default"); const std::shared_ptr<FileEntry>& fe = dctx->getFirstFileEntry(); @@ -740,11 +740,11 @@ void BittorrentHelperTest::testCheckBitfield() } void BittorrentHelperTest::testMetadata() { - std::shared_ptr<DownloadContext> dctx(new DownloadContext()); + auto dctx = std::make_shared<DownloadContext>(); load(A2_TEST_DIR"/test.torrent", dctx, option_); std::string torrentData = readFile(A2_TEST_DIR"/test.torrent"); - std::shared_ptr<ValueBase> tr = bencode2::decode(torrentData); - std::shared_ptr<ValueBase> infoDic = downcast<Dict>(tr)->get("info"); + auto tr = bencode2::decode(torrentData); + auto infoDic = downcast<Dict>(tr)->get("info"); std::string metadata = bencode2::encode(infoDic); auto attrs = getTorrentAttrs(dctx); CPPUNIT_ASSERT(metadata == attrs->metadata); @@ -827,9 +827,9 @@ void BittorrentHelperTest::testExtractPeerFromString() std::string hextext = "100210354527354678541237324732171ae1"; hextext += "20010db8bd0501d2288a1fc0000110ee1ae2"; std::string peersstr = "36:"+fromHex(hextext); - std::shared_ptr<ValueBase> str = bencode2::decode(peersstr); - std::deque<std::shared_ptr<Peer> > peers; - extractPeer(str, AF_INET6, std::back_inserter(peers)); + auto str = bencode2::decode(peersstr); + std::deque<std::shared_ptr<Peer>> peers; + extractPeer(str.get(), AF_INET6, std::back_inserter(peers)); CPPUNIT_ASSERT_EQUAL((size_t)2, peers.size()); CPPUNIT_ASSERT_EQUAL(std::string("1002:1035:4527:3546:7854:1237:3247:3217"), peers[0]->getIPAddress()); @@ -843,7 +843,7 @@ void BittorrentHelperTest::testExtractPeerFromString() peersstr = "12:"+fromHex(hextext); str = bencode2::decode(peersstr); peers.clear(); - extractPeer(str, AF_INET, std::back_inserter(peers)); + extractPeer(str.get(), AF_INET, std::back_inserter(peers)); CPPUNIT_ASSERT_EQUAL((size_t)2, peers.size()); CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.1"), peers[0]->getIPAddress()); CPPUNIT_ASSERT_EQUAL((uint16_t)6881, peers[0]->getPort()); @@ -857,12 +857,12 @@ void BittorrentHelperTest::testExtractPeerFromList() "d5:peersld2:ip11:192.168.0.17:peer id20:aria2-00000000000000" "4:porti2006eeee"; - std::shared_ptr<ValueBase> dict = bencode2::decode(peersString); + auto dict = bencode2::decode(peersString); - std::deque<std::shared_ptr<Peer> > peers; + std::deque<std::shared_ptr<Peer>> peers; extractPeer(downcast<Dict>(dict)->get("peers"), AF_INET, std::back_inserter(peers)); CPPUNIT_ASSERT_EQUAL((size_t)1, peers.size()); - std::shared_ptr<Peer> peer = *peers.begin(); + auto& peer = *peers.begin(); CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.1"), peer->getIPAddress()); CPPUNIT_ASSERT_EQUAL((uint16_t)2006, peer->getPort()); } @@ -874,12 +874,12 @@ void BittorrentHelperTest::testExtract2PeersFromList() "4:porti65535eed2:ip11:192.168.0.27:peer id20:aria2-00000000000000" "4:porti2007eeee"; - std::shared_ptr<ValueBase> dict = bencode2::decode(peersString); + auto dict = bencode2::decode(peersString); - std::deque<std::shared_ptr<Peer> > peers; + std::deque<std::shared_ptr<Peer>> peers; extractPeer(downcast<Dict>(dict)->get("peers"), AF_INET, std::back_inserter(peers)); CPPUNIT_ASSERT_EQUAL((size_t)2, peers.size()); - std::shared_ptr<Peer> peer = *peers.begin(); + auto& peer = *peers.begin(); CPPUNIT_ASSERT_EQUAL(std::string("192.168.0.1"), peer->getIPAddress()); CPPUNIT_ASSERT_EQUAL((uint16_t)65535, peer->getPort()); diff --git a/test/DHTAnnouncePeerMessageTest.cc b/test/DHTAnnouncePeerMessageTest.cc index f93c7f79..34d5857f 100644 --- a/test/DHTAnnouncePeerMessageTest.cc +++ b/test/DHTAnnouncePeerMessageTest.cc @@ -76,7 +76,7 @@ void DHTAnnouncePeerMessageTest::testGetBencodedMessage() aDict->put("info_hash", String::g(infoHash, DHT_ID_LENGTH)); aDict->put("port", Integer::g(port)); aDict->put("token", token); - dict.put("a", aDict); + dict.put("a", std::move(aDict)); CPPUNIT_ASSERT_EQUAL(util::percentEncode(bencode2::encode(&dict)), util::percentEncode(msgbody)); diff --git a/test/DHTAnnouncePeerReplyMessageTest.cc b/test/DHTAnnouncePeerReplyMessageTest.cc index 16c049e7..c287f1c5 100644 --- a/test/DHTAnnouncePeerReplyMessageTest.cc +++ b/test/DHTAnnouncePeerReplyMessageTest.cc @@ -42,9 +42,9 @@ void DHTAnnouncePeerReplyMessageTest::testGetBencodedMessage() dict.put("t", transactionID); dict.put("v", "A200"); dict.put("y", "r"); - std::shared_ptr<Dict> rDict = Dict::g(); + auto rDict = Dict::g(); rDict->put("id", String::g(localNode->getID(), DHT_ID_LENGTH)); - dict.put("r", rDict); + dict.put("r", std::move(rDict)); CPPUNIT_ASSERT_EQUAL(bencode2::encode(&dict), msgbody); } diff --git a/test/DHTFindNodeMessageTest.cc b/test/DHTFindNodeMessageTest.cc index 0a86ef67..2cd13a10 100644 --- a/test/DHTFindNodeMessageTest.cc +++ b/test/DHTFindNodeMessageTest.cc @@ -74,7 +74,7 @@ void DHTFindNodeMessageTest::testGetBencodedMessage() auto aDict = Dict::g(); aDict->put("id", String::g(localNode_->getID(), DHT_ID_LENGTH)); aDict->put("target", String::g(targetNode->getID(), DHT_ID_LENGTH)); - dict.put("a", aDict); + dict.put("a", std::move(aDict)); CPPUNIT_ASSERT_EQUAL(bencode2::encode(&dict), msgbody); } diff --git a/test/DHTFindNodeReplyMessageTest.cc b/test/DHTFindNodeReplyMessageTest.cc index cdb715c9..a69f4b13 100644 --- a/test/DHTFindNodeReplyMessageTest.cc +++ b/test/DHTFindNodeReplyMessageTest.cc @@ -64,10 +64,10 @@ void DHTFindNodeReplyMessageTest::testGetBencodedMessage() dict.put("t", transactionID); dict.put("v", "A200"); dict.put("y", "r"); - std::shared_ptr<Dict> rDict = Dict::g(); + auto rDict = Dict::g(); rDict->put("id", String::g(localNode->getID(), DHT_ID_LENGTH)); rDict->put("nodes", compactNodeInfo); - dict.put("r", rDict); + dict.put("r", std::move(rDict)); CPPUNIT_ASSERT_EQUAL(bencode2::encode(&dict), msgbody); } @@ -106,10 +106,10 @@ void DHTFindNodeReplyMessageTest::testGetBencodedMessage6() dict.put("t", transactionID); dict.put("v", "A200"); dict.put("y", "r"); - std::shared_ptr<Dict> rDict = Dict::g(); + auto rDict = Dict::g(); rDict->put("id", String::g(localNode->getID(), DHT_ID_LENGTH)); rDict->put("nodes6", compactNodeInfo); - dict.put("r", rDict); + dict.put("r", std::move(rDict)); CPPUNIT_ASSERT_EQUAL(bencode2::encode(&dict), msgbody); } diff --git a/test/DHTGetPeersMessageTest.cc b/test/DHTGetPeersMessageTest.cc index e1310904..98842c92 100644 --- a/test/DHTGetPeersMessageTest.cc +++ b/test/DHTGetPeersMessageTest.cc @@ -81,7 +81,7 @@ void DHTGetPeersMessageTest::testGetBencodedMessage() auto aDict = Dict::g(); aDict->put("id", String::g(localNode_->getID(), DHT_ID_LENGTH)); aDict->put("info_hash", String::g(infoHash, DHT_ID_LENGTH)); - dict.put("a", aDict); + dict.put("a", std::move(aDict)); CPPUNIT_ASSERT_EQUAL(util::percentEncode(bencode2::encode(&dict)), util::percentEncode(msgbody)); diff --git a/test/DHTGetPeersReplyMessageTest.cc b/test/DHTGetPeersReplyMessageTest.cc index ebafbbe6..dd77317f 100644 --- a/test/DHTGetPeersReplyMessageTest.cc +++ b/test/DHTGetPeersReplyMessageTest.cc @@ -49,10 +49,9 @@ void DHTGetPeersReplyMessageTest::testGetBencodedMessage() dict.put("t", transactionID); dict.put("v", "A200"); dict.put("y", "r"); - std::shared_ptr<Dict> rDict = Dict::g(); + auto rDict = Dict::g(); rDict->put("id", String::g(localNode->getID(), DHT_ID_LENGTH)); rDict->put("token", token); - dict.put("r", rDict); { std::string compactNodeInfo; std::shared_ptr<DHTNode> nodes[8]; @@ -74,10 +73,11 @@ void DHTGetPeersReplyMessageTest::testGetBencodedMessage() (std::vector<std::shared_ptr<DHTNode> >(&nodes[0], &nodes[DHTBucket::K])); rDict->put("nodes", compactNodeInfo); - std::vector<std::shared_ptr<Peer> > peers; - std::shared_ptr<List> valuesList = List::g(); + std::vector<std::shared_ptr<Peer>> peers; + auto valuesList = List::g(); for(size_t i = 0; i < 4; ++i) { - std::shared_ptr<Peer> peer(new Peer("192.168.0."+util::uitos(i+1), 6881+i)); + auto peer = std::make_shared<Peer>("192.168.0."+util::uitos(i+1), + 6881+i); unsigned char buffer[COMPACT_LEN_IPV6]; CPPUNIT_ASSERT_EQUAL (COMPACT_LEN_IPV4, @@ -87,7 +87,8 @@ void DHTGetPeersReplyMessageTest::testGetBencodedMessage() peers.push_back(peer); } msg.setValues(peers); - rDict->put("values", valuesList); + rDict->put("values", std::move(valuesList)); + dict.put("r", std::move(rDict)); std::string msgbody = msg.getBencodedMessage(); CPPUNIT_ASSERT_EQUAL(util::percentEncode(bencode2::encode(&dict)), @@ -113,10 +114,9 @@ void DHTGetPeersReplyMessageTest::testGetBencodedMessage6() dict.put("t", transactionID); dict.put("v", "A200"); dict.put("y", "r"); - std::shared_ptr<Dict> rDict = Dict::g(); + auto rDict = Dict::g(); rDict->put("id", String::g(localNode->getID(), DHT_ID_LENGTH)); rDict->put("token", token); - dict.put("r", rDict); { std::string compactNodeInfo; std::shared_ptr<DHTNode> nodes[8]; @@ -138,9 +138,9 @@ void DHTGetPeersReplyMessageTest::testGetBencodedMessage6() rDict->put("nodes6", compactNodeInfo); std::vector<std::shared_ptr<Peer> > peers; - std::shared_ptr<List> valuesList = List::g(); + auto valuesList = List::g(); for(size_t i = 0; i < 4; ++i) { - std::shared_ptr<Peer> peer(new Peer("2001::100"+util::uitos(i+1), 6881+i)); + auto peer = std::make_shared<Peer>("2001::100"+util::uitos(i+1), 6881+i); unsigned char buffer[COMPACT_LEN_IPV6]; CPPUNIT_ASSERT_EQUAL (COMPACT_LEN_IPV6, @@ -150,7 +150,8 @@ void DHTGetPeersReplyMessageTest::testGetBencodedMessage6() peers.push_back(peer); } msg.setValues(peers); - rDict->put("values", valuesList); + rDict->put("values", std::move(valuesList)); + dict.put("r", std::move(rDict)); std::string msgbody = msg.getBencodedMessage(); CPPUNIT_ASSERT_EQUAL(util::percentEncode(bencode2::encode(&dict)), diff --git a/test/DHTMessageFactoryImplTest.cc b/test/DHTMessageFactoryImplTest.cc index e286a9b9..cbdf257b 100644 --- a/test/DHTMessageFactoryImplTest.cc +++ b/test/DHTMessageFactoryImplTest.cc @@ -98,7 +98,7 @@ void DHTMessageFactoryImplTest::testCreatePingMessage() dict.put("q", "ping"); auto aDict = Dict::g(); aDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH)); - dict.put("a", aDict); + dict.put("a", std::move(aDict)); auto r = factory->createQueryMessage(&dict, "192.168.0.1", 6881); auto m = dynamic_cast<DHTPingMessage*>(r.get()); @@ -116,7 +116,7 @@ void DHTMessageFactoryImplTest::testCreatePingReplyMessage() dict.put("y", "r"); auto rDict = Dict::g(); rDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH)); - dict.put("r", rDict); + dict.put("r", std::move(rDict)); auto r = factory->createResponseMessage("ping", &dict, remoteNode_->getIPAddress(), @@ -140,7 +140,7 @@ void DHTMessageFactoryImplTest::testCreateFindNodeMessage() unsigned char targetNodeID[DHT_ID_LENGTH]; memset(targetNodeID, 0x11, DHT_ID_LENGTH); aDict->put("target", String::g(targetNodeID, DHT_ID_LENGTH)); - dict.put("a", aDict); + dict.put("a", std::move(aDict)); auto r = factory->createQueryMessage(&dict, "192.168.0.1", 6881); auto m = dynamic_cast<DHTFindNodeMessage*>(r.get()); @@ -178,7 +178,7 @@ void DHTMessageFactoryImplTest::testCreateFindNodeReplyMessage() std::string(&buf[0], &buf[COMPACT_LEN_IPV4]); } rDict->put("nodes", compactNodeInfo); - dict.put("r", rDict); + dict.put("r", std::move(rDict)); auto r = factory->createResponseMessage("find_node", &dict, remoteNode_->getIPAddress(), @@ -225,7 +225,7 @@ void DHTMessageFactoryImplTest::testCreateFindNodeReplyMessage6() std::string(&buf[0], &buf[COMPACT_LEN_IPV6]); } rDict->put("nodes6", compactNodeInfo); - dict.put("r", rDict); + dict.put("r", std::move(rDict)); auto r = factory->createResponseMessage("find_node", &dict, remoteNode_->getIPAddress(), @@ -255,7 +255,7 @@ void DHTMessageFactoryImplTest::testCreateGetPeersMessage() unsigned char infoHash[DHT_ID_LENGTH]; memset(infoHash, 0x11, DHT_ID_LENGTH); aDict->put("info_hash", String::g(infoHash, DHT_ID_LENGTH)); - dict.put("a", aDict); + dict.put("a", std::move(aDict)); auto r = factory->createQueryMessage(&dict, "192.168.0.1", 6881); auto m = dynamic_cast<DHTGetPeersMessage*>(r.get()); @@ -295,7 +295,7 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage() rDict->put("nodes", compactNodeInfo); std::deque<std::shared_ptr<Peer> > peers; - std::shared_ptr<List> valuesList = List::g(); + auto valuesList = List::g(); for(size_t i = 0; i < 4; ++i) { auto peer = std::make_shared<Peer>("192.168.0."+util::uitos(i+1), 6881+i); @@ -307,10 +307,9 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage() valuesList->append(String::g(buffer, COMPACT_LEN_IPV4)); peers.push_back(peer); } - rDict->put("values", valuesList); - + rDict->put("values", std::move(valuesList)); rDict->put("token", "token"); - dict.put("r", rDict); + dict.put("r", std::move(rDict)); auto r = factory->createResponseMessage("get_peers", &dict, remoteNode_->getIPAddress(), @@ -377,10 +376,9 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage6() valuesList->append(String::g(buffer, COMPACT_LEN_IPV6)); peers.push_back(peer); } - rDict->put("values", valuesList); - + rDict->put("values", std::move(valuesList)); rDict->put("token", "token"); - dict.put("r", rDict); + dict.put("r", std::move(rDict)); auto r = factory->createResponseMessage("get_peers", &dict, remoteNode_->getIPAddress(), @@ -422,7 +420,7 @@ void DHTMessageFactoryImplTest::testCreateAnnouncePeerMessage() uint16_t port = 6881; aDict->put("port", Integer::g(port)); aDict->put("token", token); - dict.put("a", aDict); + dict.put("a", std::move(aDict)); remoteNode_->setPort(6882); @@ -449,7 +447,7 @@ void DHTMessageFactoryImplTest::testCreateAnnouncePeerReplyMessage() dict.put("y", "r"); auto rDict = Dict::g(); rDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH)); - dict.put("r", rDict); + dict.put("r", std::move(rDict)); auto r = factory->createResponseMessage("announce_peer", &dict, remoteNode_->getIPAddress(), @@ -470,7 +468,7 @@ void DHTMessageFactoryImplTest::testReceivedErrorMessage() auto list = List::g(); list->append(Integer::g(404)); list->append("Not found"); - dict.put("e", list); + dict.put("e", std::move(list)); try { factory->createResponseMessage("announce_peer", &dict, diff --git a/test/DHTPingMessageTest.cc b/test/DHTPingMessageTest.cc index 35f79211..fce2db37 100644 --- a/test/DHTPingMessageTest.cc +++ b/test/DHTPingMessageTest.cc @@ -69,7 +69,7 @@ void DHTPingMessageTest::testGetBencodedMessage() dict.put("q", "ping"); auto aDict = Dict::g(); aDict->put("id", String::g(localNode_->getID(), DHT_ID_LENGTH)); - dict.put("a", aDict); + dict.put("a", std::move(aDict)); CPPUNIT_ASSERT_EQUAL(bencode2::encode(&dict), msgbody); } diff --git a/test/DHTPingReplyMessageTest.cc b/test/DHTPingReplyMessageTest.cc index 3c4a6238..4dc6d48c 100644 --- a/test/DHTPingReplyMessageTest.cc +++ b/test/DHTPingReplyMessageTest.cc @@ -45,9 +45,9 @@ void DHTPingReplyMessageTest::testGetBencodedMessage() dict.put("t", transactionID); dict.put("v", "A200"); dict.put("y", "r"); - std::shared_ptr<Dict> rDict = Dict::g(); + auto rDict = Dict::g(); rDict->put("id", String::g(id, DHT_ID_LENGTH)); - dict.put("r", rDict); + dict.put("r", std::move(rDict)); CPPUNIT_ASSERT_EQUAL(bencode2::encode(&dict), msgbody); } diff --git a/test/DefaultBtAnnounceTest.cc b/test/DefaultBtAnnounceTest.cc index 63abbd6a..b0047dd5 100644 --- a/test/DefaultBtAnnounceTest.cc +++ b/test/DefaultBtAnnounceTest.cc @@ -103,10 +103,10 @@ CPPUNIT_TEST_SUITE_REGISTRATION(DefaultBtAnnounceTest); namespace { template<typename InputIterator> -std::shared_ptr<List> createAnnounceTier +std::unique_ptr<List> createAnnounceTier (InputIterator first, InputIterator last) { - std::shared_ptr<List> announceTier = List::g(); + auto announceTier = List::g(); for(; first != last; ++first) { announceTier->append(String::g(*first)); } @@ -115,9 +115,9 @@ std::shared_ptr<List> createAnnounceTier } // namespace namespace { -std::shared_ptr<List> createAnnounceTier(const std::string& uri) +std::unique_ptr<List> createAnnounceTier(const std::string& uri) { - std::shared_ptr<List> announceTier = List::g(); + auto announceTier = List::g(); announceTier->append(String::g(uri)); return announceTier; } @@ -125,19 +125,19 @@ std::shared_ptr<List> createAnnounceTier(const std::string& uri) namespace { void setAnnounceList(const std::shared_ptr<DownloadContext>& dctx, - const std::shared_ptr<List>& announceList) + const List* announceList) { - std::vector<std::vector<std::string> > dest; - for(List::ValueType::const_iterator tierIter = announceList->begin(), - eoi = announceList->end(); tierIter != eoi; ++tierIter) { + std::vector<std::vector<std::string>> dest; + for(auto tierIter = announceList->begin(), eoi = announceList->end(); + tierIter != eoi; ++tierIter) { std::vector<std::string> ntier; const List* tier = downcast<List>(*tierIter); - for(List::ValueType::const_iterator uriIter = tier->begin(), - eoi2 = tier->end(); uriIter != eoi2; ++uriIter) { + for(auto uriIter = tier->begin(), eoi2 = tier->end(); uriIter != eoi2; + ++uriIter) { const String* uri = downcast<String>(*uriIter); ntier.push_back(uri->s()); } - dest.push_back(ntier); + dest.push_back(std::move(ntier)); } bittorrent::getTorrentAttrs(dctx)->announceList.swap(dest); } @@ -145,11 +145,11 @@ void setAnnounceList(const std::shared_ptr<DownloadContext>& dctx, void DefaultBtAnnounceTest::testNoMoreAnnounce() { - std::shared_ptr<List> announceList = List::g(); + auto announceList = List::g(); announceList->append(createAnnounceTier("http://localhost/announce")); announceList->append(createAnnounceTier("http://backup/announce")); - setAnnounceList(dctx_, announceList); + setAnnounceList(dctx_, announceList.get()); DefaultBtAnnounce btAnnounce(dctx_.get(), option_); btAnnounce.setPieceStorage(pieceStorage_); @@ -195,10 +195,9 @@ void DefaultBtAnnounceTest::testNoMoreAnnounce() void DefaultBtAnnounceTest::testGetAnnounceUrl() { - - std::shared_ptr<List> announceList = List::g(); + auto announceList = List::g(); announceList->append(createAnnounceTier("http://localhost/announce")); - setAnnounceList(dctx_, announceList); + setAnnounceList(dctx_, announceList.get()); DefaultBtAnnounce btAnnounce(dctx_.get(), option_); btAnnounce.setPieceStorage(pieceStorage_); @@ -253,9 +252,9 @@ void DefaultBtAnnounceTest::testGetAnnounceUrl() void DefaultBtAnnounceTest::testGetAnnounceUrl_withQuery() { - std::shared_ptr<List> announceList = List::g(); + auto announceList = List::g(); announceList->append(createAnnounceTier("http://localhost/announce?k=v")); - setAnnounceList(dctx_, announceList); + setAnnounceList(dctx_, announceList.get()); DefaultBtAnnounce btAnnounce(dctx_.get(), option_); btAnnounce.setPieceStorage(pieceStorage_); @@ -276,9 +275,9 @@ void DefaultBtAnnounceTest::testGetAnnounceUrl_withQuery() void DefaultBtAnnounceTest::testGetAnnounceUrl_externalIP() { - std::shared_ptr<List> announceList = List::g(); + auto announceList = List::g(); announceList->append(createAnnounceTier("http://localhost/announce")); - setAnnounceList(dctx_, announceList); + setAnnounceList(dctx_, announceList.get()); option_->put(PREF_BT_EXTERNAL_IP, "192.168.1.1"); DefaultBtAnnounce btAnnounce(dctx_.get(), option_); @@ -307,10 +306,10 @@ void DefaultBtAnnounceTest::testGetAnnounceUrl_externalIP() void DefaultBtAnnounceTest::testIsAllAnnounceFailed() { - std::shared_ptr<List> announceList = List::g(); + auto announceList = List::g(); announceList->append(createAnnounceTier("http://localhost/announce")); announceList->append(createAnnounceTier("http://backup/announce")); - setAnnounceList(dctx_, announceList); + setAnnounceList(dctx_, announceList.get()); DefaultBtAnnounce btAnnounce(dctx_.get(), option_); btAnnounce.setPieceStorage(pieceStorage_); @@ -341,9 +340,9 @@ void DefaultBtAnnounceTest::testURLOrderInStoppedEvent() const char* urls[] = { "http://localhost1/announce", "http://localhost2/announce" }; - std::shared_ptr<List> announceList = List::g(); + auto announceList = List::g(); announceList->append(createAnnounceTier(std::begin(urls), std::end(urls))); - setAnnounceList(dctx_, announceList); + setAnnounceList(dctx_, announceList.get()); DefaultBtAnnounce btAnnounce(dctx_.get(), option_); btAnnounce.setPieceStorage(pieceStorage_); @@ -372,9 +371,9 @@ void DefaultBtAnnounceTest::testURLOrderInCompletedEvent() const char* urls[] = { "http://localhost1/announce", "http://localhost2/announce" }; - std::shared_ptr<List> announceList = List::g(); + auto announceList = List::g(); announceList->append(createAnnounceTier(std::begin(urls), std::end(urls))); - setAnnounceList(dctx_, announceList); + setAnnounceList(dctx_, announceList.get()); DefaultBtAnnounce btAnnounce(dctx_.get(), option_); btAnnounce.setPieceStorage(pieceStorage_); diff --git a/test/JsonTest.cc b/test/JsonTest.cc index db3391a9..1fa19794 100644 --- a/test/JsonTest.cc +++ b/test/JsonTest.cc @@ -27,43 +27,43 @@ CPPUNIT_TEST_SUITE_REGISTRATION( JsonTest ); void JsonTest::testEncode() { { - std::shared_ptr<Dict> dict = Dict::g(); + auto dict = Dict::g(); dict->put("name", String::g("aria2")); dict->put("loc", Integer::g(80000)); - std::shared_ptr<List> files = List::g(); + auto files = List::g(); files->append(String::g("aria2c")); - dict->put("files", files); - std::shared_ptr<Dict> attrs = Dict::g(); + dict->put("files", std::move(files)); + auto attrs = Dict::g(); attrs->put("license", String::g("GPL")); - dict->put("attrs", attrs); + dict->put("attrs", std::move(attrs)); CPPUNIT_ASSERT_EQUAL(std::string("{\"attrs\":{\"license\":\"GPL\"}," "\"files\":[\"aria2c\"]," "\"loc\":80000," "\"name\":\"aria2\"}"), - json::encode(dict)); + json::encode(dict.get())); } { - std::shared_ptr<List> list = List::g(); + auto list = List::g(); list->append("\"\\/\b\f\n\r\t"); CPPUNIT_ASSERT_EQUAL(std::string("[\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"]"), - json::encode(list)); + json::encode(list.get())); } { - std::shared_ptr<List> list = List::g(); + auto list = List::g(); std::string s; s += 0x1Fu; list->append(s); CPPUNIT_ASSERT_EQUAL(std::string("[\"\\u001F\"]"), - json::encode(list)); + json::encode(list.get())); } { - std::shared_ptr<List> list = List::g(); + auto list = List::g(); list->append(Bool::gTrue()); list->append(Bool::gFalse()); list->append(Null::g()); CPPUNIT_ASSERT_EQUAL(std::string("[true,false,null]"), - json::encode(list)); + json::encode(list.get())); } } diff --git a/test/MagnetTest.cc b/test/MagnetTest.cc index 486de66e..645a73ec 100644 --- a/test/MagnetTest.cc +++ b/test/MagnetTest.cc @@ -21,7 +21,7 @@ public: CPPUNIT_TEST_SUITE_REGISTRATION(MagnetTest); namespace { -const std::string& nthStr(const std::shared_ptr<ValueBase>& v, size_t index) +const std::string& nthStr(const ValueBase* v, size_t index) { return downcast<String>(downcast<List>(v)->get(index))->s(); } @@ -29,7 +29,7 @@ const std::string& nthStr(const std::shared_ptr<ValueBase>& v, size_t index) void MagnetTest::testParse() { - std::shared_ptr<Dict> r = parse + auto r = parse ("magnet:?xt=urn:btih:248d0a1cd08284299de78d5c1ed359bb46717d8c&dn=aria2" "&tr=http%3A%2F%2Ftracker1&tr=http://tracker2"); CPPUNIT_ASSERT_EQUAL diff --git a/test/MockDHTMessage.h b/test/MockDHTMessage.h index ec464572..2bff5bde 100644 --- a/test/MockDHTMessage.h +++ b/test/MockDHTMessage.h @@ -80,7 +80,7 @@ public: virtual std::string toString() const CXX11_OVERRIDE { return "MockDHTMessage"; } - virtual std::shared_ptr<Dict> getArgument() CXX11_OVERRIDE + virtual std::unique_ptr<Dict> getArgument() CXX11_OVERRIDE { return Dict::g(); } }; @@ -115,7 +115,7 @@ public: virtual std::string toString() const CXX11_OVERRIDE { return "MockDHTMessage"; } - virtual std::shared_ptr<Dict> getResponse() CXX11_OVERRIDE + virtual std::unique_ptr<Dict> getResponse() CXX11_OVERRIDE { return Dict::g(); } virtual void accept(DHTMessageCallback* callback) CXX11_OVERRIDE {} diff --git a/test/RpcMethodTest.cc b/test/RpcMethodTest.cc index 0e6e0f05..902a1c3a 100644 --- a/test/RpcMethodTest.cc +++ b/test/RpcMethodTest.cc @@ -152,15 +152,22 @@ std::string getString(const Dict* dict, const std::string& key) } } // namespace +namespace { +RpcRequest createReq(std::string methodName) +{ + return {std::move(methodName), List::g()}; +} +} // namespace + void RpcMethodTest::testAddUri() { AddUriRpcMethod m; - RpcRequest req(AddUriRpcMethod::getMethodName(), List::g()); - std::shared_ptr<List> urisParam = List::g(); - urisParam->append("http://localhost/"); - req.params->append(urisParam); { - RpcResponse res = m.execute(req, e_.get()); + auto req = createReq(AddUriRpcMethod::getMethodName()); + auto urisParam = List::g(); + urisParam->append("http://localhost/"); + req.params->append(std::move(urisParam)); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); const RequestGroupList& rgs = e_->getRequestGroupMan()->getReservedGroups(); @@ -169,12 +176,16 @@ void RpcMethodTest::testAddUri() (*rgs.begin())->getDownloadContext()-> getFirstFileEntry()->getRemainingUris().front()); } - // with options - std::shared_ptr<Dict> opt = Dict::g(); - opt->put(PREF_DIR->k, "/sink"); - req.params->append(opt); { - RpcResponse res = m.execute(req, e_.get()); + auto req = createReq(AddUriRpcMethod::getMethodName()); + auto urisParam = List::g(); + urisParam->append("http://localhost/"); + req.params->append(std::move(urisParam)); + // with options + auto opt = Dict::g(); + opt->put(PREF_DIR->k, "/sink"); + req.params->append(std::move(opt)); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); a2_gid_t gid; CPPUNIT_ASSERT_EQUAL(0, GroupId::toNumericId @@ -189,53 +200,52 @@ void RpcMethodTest::testAddUri() void RpcMethodTest::testAddUri_withoutUri() { AddUriRpcMethod m; - RpcRequest req(AddUriRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(createReq(AddUriRpcMethod::getMethodName()), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testAddUri_notUri() { AddUriRpcMethod m; - RpcRequest req(AddUriRpcMethod::getMethodName(), List::g()); - std::shared_ptr<List> urisParam = List::g(); + auto req = createReq(AddUriRpcMethod::getMethodName()); + auto urisParam = List::g(); urisParam->append("not uri"); - req.params->append(urisParam); - RpcResponse res = m.execute(req, e_.get()); + req.params->append(std::move(urisParam)); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testAddUri_withBadOption() { AddUriRpcMethod m; - RpcRequest req(AddUriRpcMethod::getMethodName(), List::g()); - std::shared_ptr<List> urisParam = List::g(); + auto req = createReq(AddUriRpcMethod::getMethodName()); + auto urisParam = List::g(); urisParam->append("http://localhost"); - req.params->append(urisParam); - std::shared_ptr<Dict> opt = Dict::g(); + req.params->append(std::move(urisParam)); + auto opt = Dict::g(); opt->put(PREF_FILE_ALLOCATION->k, "badvalue"); - req.params->append(opt); - RpcResponse res = m.execute(req, e_.get()); + req.params->append(std::move(opt)); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testAddUri_withPosition() { AddUriRpcMethod m; - RpcRequest req1(AddUriRpcMethod::getMethodName(), List::g()); - std::shared_ptr<List> urisParam1 = List::g(); + auto req1 = createReq(AddUriRpcMethod::getMethodName()); + auto urisParam1 = List::g(); urisParam1->append("http://uri1"); - req1.params->append(urisParam1); - RpcResponse res1 = m.execute(req1, e_.get()); + req1.params->append(std::move(urisParam1)); + auto res1 = m.execute(std::move(req1), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res1.code); - RpcRequest req2(AddUriRpcMethod::getMethodName(), List::g()); - std::shared_ptr<List> urisParam2 = List::g(); + auto req2 = createReq(AddUriRpcMethod::getMethodName()); + auto urisParam2 = List::g(); urisParam2->append("http://uri2"); - req2.params->append(urisParam2); + req2.params->append(std::move(urisParam2)); req2.params->append(Dict::g()); req2.params->append(Integer::g(0)); - m.execute(req2, e_.get()); + m.execute(std::move(req2), e_.get()); std::string uri = getReservedGroup(e_->getRequestGroupMan().get(), 0)-> @@ -247,30 +257,37 @@ void RpcMethodTest::testAddUri_withPosition() void RpcMethodTest::testAddUri_withBadPosition() { AddUriRpcMethod m; - RpcRequest req(AddUriRpcMethod::getMethodName(), List::g()); - std::shared_ptr<List> urisParam = List::g(); + auto req = createReq(AddUriRpcMethod::getMethodName()); + auto urisParam = List::g(); urisParam->append("http://localhost/"); - req.params->append(urisParam); + req.params->append(std::move(urisParam)); req.params->append(Dict::g()); req.params->append(Integer::g(-1)); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } #ifdef ENABLE_BITTORRENT +namespace { +RpcRequest createAddTorrentReq() +{ + auto req = createReq(AddTorrentRpcMethod::getMethodName()); + req.params->append(readFile(A2_TEST_DIR"/single.torrent")); + auto uris = List::g(); + uris->append("http://localhost/aria2-0.8.2.tar.bz2"); + req.params->append(std::move(uris)); + return req; +} +} // namespace + void RpcMethodTest::testAddTorrent() { File(e_->getOption()->get(PREF_DIR)+ "/0a3893293e27ac0490424c06de4d09242215f0a6.torrent").remove(); AddTorrentRpcMethod m; - RpcRequest req(AddTorrentRpcMethod::getMethodName(), List::g()); - req.params->append(readFile(A2_TEST_DIR"/single.torrent")); - std::shared_ptr<List> uris = List::g(); - uris->append("http://localhost/aria2-0.8.2.tar.bz2"); - req.params->append(uris); { // Saving upload metadata is disabled by option. - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(createAddTorrentReq(), e_.get()); CPPUNIT_ASSERT (!File(e_->getOption()->get(PREF_DIR)+ "/0a3893293e27ac0490424c06de4d09242215f0a6.torrent").exists()); @@ -280,7 +297,7 @@ void RpcMethodTest::testAddTorrent() } e_->getOption()->put(PREF_RPC_SAVE_UPLOAD_METADATA, A2_V_TRUE); { - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(createAddTorrentReq(), e_.get()); CPPUNIT_ASSERT (File(e_->getOption()->get(PREF_DIR)+ "/0a3893293e27ac0490424c06de4d09242215f0a6.torrent").exists()); @@ -300,15 +317,17 @@ void RpcMethodTest::testAddTorrent() group->getDownloadContext()->getFirstFileEntry()-> getRemainingUris()[0]); } - // with options - std::string dir = A2_TEST_OUT_DIR"/aria2_RpcMethodTest_testAddTorrent"; - File(dir).mkdirs(); - std::shared_ptr<Dict> opt = Dict::g(); - opt->put(PREF_DIR->k, dir); - File(dir+"/0a3893293e27ac0490424c06de4d09242215f0a6.torrent").remove(); - req.params->append(opt); { - RpcResponse res = m.execute(req, e_.get()); + auto req = createAddTorrentReq(); + // with options + std::string dir = A2_TEST_OUT_DIR"/aria2_RpcMethodTest_testAddTorrent"; + File(dir).mkdirs(); + auto opt = Dict::g(); + opt->put(PREF_DIR->k, dir); + File(dir+"/0a3893293e27ac0490424c06de4d09242215f0a6.torrent").remove(); + req.params->append(std::move(opt)); + + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); a2_gid_t gid; CPPUNIT_ASSERT_EQUAL(0, GroupId::toNumericId @@ -325,36 +344,36 @@ void RpcMethodTest::testAddTorrent() void RpcMethodTest::testAddTorrent_withoutTorrent() { AddTorrentRpcMethod m; - RpcRequest req(AddTorrentRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(createReq(AddTorrentRpcMethod::getMethodName()), + e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testAddTorrent_notBase64Torrent() { AddTorrentRpcMethod m; - RpcRequest req(AddTorrentRpcMethod::getMethodName(), List::g()); + auto req = createReq(AddTorrentRpcMethod::getMethodName()); req.params->append("not torrent"); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testAddTorrent_withPosition() { AddTorrentRpcMethod m; - RpcRequest req1(AddTorrentRpcMethod::getMethodName(), List::g()); + auto req1 = createReq(AddTorrentRpcMethod::getMethodName()); req1.params->append(readFile(A2_TEST_DIR"/test.torrent")); req1.params->append(List::g()); req1.params->append(Dict::g()); - RpcResponse res1 = m.execute(req1, e_.get()); + auto res1 = m.execute(std::move(req1), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res1.code); - RpcRequest req2(AddTorrentRpcMethod::getMethodName(), List::g()); + auto req2 = createReq(AddTorrentRpcMethod::getMethodName()); req2.params->append(readFile(A2_TEST_DIR"/single.torrent")); req2.params->append(List::g()); req2.params->append(Dict::g()); req2.params->append(Integer::g(0)); - m.execute(req2, e_.get()); + m.execute(std::move(req2), e_.get()); CPPUNIT_ASSERT_EQUAL((size_t)1, getReservedGroup(e_->getRequestGroupMan().get(), 0)-> @@ -364,16 +383,23 @@ void RpcMethodTest::testAddTorrent_withPosition() #endif // ENABLE_BITTORRENT #ifdef ENABLE_METALINK +namespace { +RpcRequest createAddMetalinkReq() +{ + auto req = createReq(AddMetalinkRpcMethod::getMethodName()); + req.params->append(readFile(A2_TEST_DIR"/2files.metalink")); + return req; +} +} // namespace + void RpcMethodTest::testAddMetalink() { File(e_->getOption()->get(PREF_DIR)+ "/c908634fbc257fd56f0114912c2772aeeb4064f4.meta4").remove(); AddMetalinkRpcMethod m; - RpcRequest req(AddMetalinkRpcMethod::getMethodName(), List::g()); - req.params->append(readFile(A2_TEST_DIR"/2files.metalink")); { // Saving upload metadata is disabled by option. - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(createAddMetalinkReq(), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); const List* resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)2, resParams->size()); @@ -390,7 +416,7 @@ void RpcMethodTest::testAddMetalink() } e_->getOption()->put(PREF_RPC_SAVE_UPLOAD_METADATA, A2_V_TRUE); { - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(createAddMetalinkReq(), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); const List* resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)2, resParams->size()); @@ -416,15 +442,17 @@ void RpcMethodTest::testAddMetalink() CPPUNIT_ASSERT_EQUAL(e_->getOption()->get(PREF_DIR)+"/aria2-5.0.0.deb", deb->getFirstFilePath()); } - // with options - std::string dir = A2_TEST_OUT_DIR"/aria2_RpcMethodTest_testAddMetalink"; - File(dir).mkdirs(); - std::shared_ptr<Dict> opt = Dict::g(); - opt->put(PREF_DIR->k, dir); - File(dir+"/c908634fbc257fd56f0114912c2772aeeb4064f4.meta4").remove(); - req.params->append(opt); { - RpcResponse res = m.execute(req, e_.get()); + auto req = createAddMetalinkReq(); + // with options + std::string dir = A2_TEST_OUT_DIR"/aria2_RpcMethodTest_testAddMetalink"; + File(dir).mkdirs(); + auto opt = Dict::g(); + opt->put(PREF_DIR->k, dir); + File(dir+"/c908634fbc257fd56f0114912c2772aeeb4064f4.meta4").remove(); + req.params->append(std::move(opt)); + + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); const List* resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)2, resParams->size()); @@ -446,36 +474,36 @@ void RpcMethodTest::testAddMetalink() void RpcMethodTest::testAddMetalink_withoutMetalink() { AddMetalinkRpcMethod m; - RpcRequest req(AddMetalinkRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(createReq(AddMetalinkRpcMethod::getMethodName()), + e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testAddMetalink_notBase64Metalink() { AddMetalinkRpcMethod m; - RpcRequest req(AddMetalinkRpcMethod::getMethodName(), List::g()); + auto req = createReq(AddMetalinkRpcMethod::getMethodName()); req.params->append("not metalink"); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testAddMetalink_withPosition() { AddUriRpcMethod m1; - RpcRequest req1(AddUriRpcMethod::getMethodName(), List::g()); - std::shared_ptr<List> urisParam1 = List::g(); + auto req1 = createReq(AddUriRpcMethod::getMethodName()); + auto urisParam1 = List::g(); urisParam1->append("http://uri"); - req1.params->append(urisParam1); - RpcResponse res1 = m1.execute(req1, e_.get()); + req1.params->append(std::move(urisParam1)); + auto res1 = m1.execute(std::move(req1), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res1.code); AddMetalinkRpcMethod m2; - RpcRequest req2("ari2.addMetalink", List::g()); + auto req2 = createReq(AddMetalinkRpcMethod::getMethodName()); req2.params->append(readFile(A2_TEST_DIR"/2files.metalink")); req2.params->append(Dict::g()); req2.params->append(Integer::g(0)); - RpcResponse res2 = m2.execute(req2, e_.get()); + auto res2 = m2.execute(std::move(req2), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res2.code); CPPUNIT_ASSERT_EQUAL(e_->getOption()->get(PREF_DIR)+"/aria2-5.0.0.tar.bz2", @@ -487,48 +515,45 @@ void RpcMethodTest::testAddMetalink_withPosition() void RpcMethodTest::testGetOption() { - std::shared_ptr<RequestGroup> group(new RequestGroup(GroupId::create(), - option_)); + auto group = std::make_shared<RequestGroup>(GroupId::create(), option_); group->getOption()->put(PREF_DIR, "alpha"); e_->getRequestGroupMan()->addReservedGroup(group); - std::shared_ptr<DownloadResult> dr = createDownloadResult(error_code::FINISHED, - "http://host/fin"); + auto dr = createDownloadResult(error_code::FINISHED, "http://host/fin"); dr->option->put(PREF_DIR, "bravo"); e_->getRequestGroupMan()->addDownloadResult(dr); GetOptionRpcMethod m; - RpcRequest req(GetOptionRpcMethod::getMethodName(), List::g()); + auto req = createReq(GetOptionRpcMethod::getMethodName()); req.params->append(GroupId::toHex(group->getGID())); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); const Dict* resopt = downcast<Dict>(res.param); CPPUNIT_ASSERT_EQUAL(std::string("alpha"), downcast<String>(resopt->get(PREF_DIR->k))->s()); - req.params = List::g(); + req = createReq(GetOptionRpcMethod::getMethodName()); req.params->append(dr->gid->toHex()); - res = m.execute(req, e_.get()); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resopt = downcast<Dict>(res.param); CPPUNIT_ASSERT_EQUAL(std::string("bravo"), downcast<String>(resopt->get(PREF_DIR->k))->s()); // Invalid GID - req.params = List::g(); + req = createReq(GetOptionRpcMethod::getMethodName()); req.params->append(GroupId::create()->toHex()); - res = m.execute(req, e_.get()); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testChangeOption() { - std::shared_ptr<RequestGroup> group(new RequestGroup(GroupId::create(), - option_)); + auto group = std::make_shared<RequestGroup>(GroupId::create(), option_); e_->getRequestGroupMan()->addReservedGroup(group); ChangeOptionRpcMethod m; - RpcRequest req(ChangeOptionRpcMethod::getMethodName(), List::g()); + auto req = createReq(ChangeOptionRpcMethod::getMethodName()); req.params->append(GroupId::toHex(group->getGID())); - std::shared_ptr<Dict> opt = Dict::g(); + auto opt = Dict::g(); opt->put(PREF_MAX_DOWNLOAD_LIMIT->k, "100K"); #ifdef ENABLE_BITTORRENT opt->put(PREF_BT_MAX_PEERS->k, "100"); @@ -541,10 +566,10 @@ void RpcMethodTest::testChangeOption() e_->getBtRegistry()->put(group->getGID(), std::move(btObject)); } #endif // ENABLE_BITTORRENT - req.params->append(opt); - RpcResponse res = m.execute(req, e_.get()); + req.params->append(std::move(opt)); + auto res = m.execute(std::move(req), e_.get()); - std::shared_ptr<Option> option = group->getOption(); + auto option = group->getOption(); CPPUNIT_ASSERT_EQUAL(0, res.code); CPPUNIT_ASSERT_EQUAL(100*1024, @@ -569,33 +594,31 @@ void RpcMethodTest::testChangeOption() void RpcMethodTest::testChangeOption_withBadOption() { - std::shared_ptr<RequestGroup> group(new RequestGroup(GroupId::create(), - option_)); + auto group = std::make_shared<RequestGroup>(GroupId::create(), option_); e_->getRequestGroupMan()->addReservedGroup(group); ChangeOptionRpcMethod m; - RpcRequest req(ChangeOptionRpcMethod::getMethodName(), List::g()); + auto req = createReq(ChangeOptionRpcMethod::getMethodName()); req.params->append(GroupId::toHex(group->getGID())); - std::shared_ptr<Dict> opt = Dict::g(); + auto opt = Dict::g(); opt->put(PREF_MAX_DOWNLOAD_LIMIT->k, "badvalue"); - req.params->append(opt); - RpcResponse res = m.execute(req, e_.get()); + req.params->append(std::move(opt)); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testChangeOption_withNotAllowedOption() { - std::shared_ptr<RequestGroup> group(new RequestGroup(GroupId::create(), - option_)); + auto group = std::make_shared<RequestGroup>(GroupId::create(), option_); e_->getRequestGroupMan()->addReservedGroup(group); ChangeOptionRpcMethod m; - RpcRequest req(ChangeOptionRpcMethod::getMethodName(), List::g()); + auto req = createReq(ChangeOptionRpcMethod::getMethodName()); req.params->append(GroupId::toHex(group->getGID())); - std::shared_ptr<Dict> opt = Dict::g(); + auto opt = Dict::g(); opt->put(PREF_MAX_OVERALL_DOWNLOAD_LIMIT->k, "100K"); - req.params->append(opt); - RpcResponse res = m.execute(req, e_.get()); + req.params->append(std::move(opt)); + auto res = m.execute(std::move(req), e_.get()); // The unacceptable options are just ignored. CPPUNIT_ASSERT_EQUAL(0, res.code); } @@ -603,23 +626,22 @@ void RpcMethodTest::testChangeOption_withNotAllowedOption() void RpcMethodTest::testChangeOption_withoutGid() { ChangeOptionRpcMethod m; - RpcRequest req(ChangeOptionRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute + (createReq(ChangeOptionRpcMethod::getMethodName()), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testChangeGlobalOption() { ChangeGlobalOptionRpcMethod m; - RpcRequest req - (ChangeGlobalOptionRpcMethod::getMethodName(), List::g()); - std::shared_ptr<Dict> opt = Dict::g(); + auto req = createReq(ChangeGlobalOptionRpcMethod::getMethodName()); + auto opt = Dict::g(); opt->put(PREF_MAX_OVERALL_DOWNLOAD_LIMIT->k, "100K"); #ifdef ENABLE_BITTORRENT opt->put(PREF_MAX_OVERALL_UPLOAD_LIMIT->k, "50K"); #endif // ENABLE_BITTORRENT - req.params->append(opt); - RpcResponse res = m.execute(req, e_.get()); + req.params->append(std::move(opt)); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); CPPUNIT_ASSERT_EQUAL @@ -639,24 +661,22 @@ void RpcMethodTest::testChangeGlobalOption() void RpcMethodTest::testChangeGlobalOption_withBadOption() { ChangeGlobalOptionRpcMethod m; - RpcRequest req - (ChangeGlobalOptionRpcMethod::getMethodName(), List::g()); - std::shared_ptr<Dict> opt = Dict::g(); + auto req = createReq(ChangeGlobalOptionRpcMethod::getMethodName()); + auto opt = Dict::g(); opt->put(PREF_MAX_OVERALL_DOWNLOAD_LIMIT->k, "badvalue"); - req.params->append(opt); - RpcResponse res = m.execute(req, e_.get()); + req.params->append(std::move(opt)); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testChangeGlobalOption_withNotAllowedOption() { ChangeGlobalOptionRpcMethod m; - RpcRequest req - (ChangeGlobalOptionRpcMethod::getMethodName(), List::g()); - std::shared_ptr<Dict> opt = Dict::g(); + auto req = createReq(ChangeGlobalOptionRpcMethod::getMethodName()); + auto opt = Dict::g(); opt->put(PREF_ENABLE_RPC->k, "100K"); - req.params->append(opt); - RpcResponse res = m.execute(req, e_.get()); + req.params->append(std::move(opt)); + auto res = m.execute(std::move(req), e_.get()); // The unacceptable options are just ignored. CPPUNIT_ASSERT_EQUAL(0, res.code); } @@ -664,8 +684,7 @@ void RpcMethodTest::testChangeGlobalOption_withNotAllowedOption() void RpcMethodTest::testNoSuchMethod() { NoSuchMethodRpcMethod m; - RpcRequest req("make.hamburger", List::g()); - RpcResponse res = m.execute(req, 0); + auto res = m.execute(createReq("make.hamburger"), 0); CPPUNIT_ASSERT_EQUAL(1, res.code); CPPUNIT_ASSERT_EQUAL(std::string("No such method: make.hamburger"), getString(downcast<Dict>(res.param), "faultString")); @@ -674,8 +693,8 @@ void RpcMethodTest::testNoSuchMethod() void RpcMethodTest::testTellStatus_withoutGid() { TellStatusRpcMethod m; - RpcRequest req(TellStatusRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute + (createReq(TellStatusRpcMethod::getMethodName()), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } @@ -683,11 +702,11 @@ namespace { void addUri(const std::string& uri, const std::shared_ptr<DownloadEngine>& e) { AddUriRpcMethod m; - RpcRequest req(AddUriRpcMethod::getMethodName(), List::g()); - std::shared_ptr<List> urisParam = List::g(); + auto req = createReq(AddUriRpcMethod::getMethodName()); + auto urisParam = List::g(); urisParam->append(uri); - req.params->append(urisParam); - CPPUNIT_ASSERT_EQUAL(0, m.execute(req, e.get()).code); + req.params->append(std::move(urisParam)); + CPPUNIT_ASSERT_EQUAL(0, m.execute(std::move(req), e.get()).code); } } // namespace @@ -697,9 +716,9 @@ void addTorrent (const std::string& torrentFile, const std::shared_ptr<DownloadEngine>& e) { AddTorrentRpcMethod m; - RpcRequest req(AddTorrentRpcMethod::getMethodName(), List::g()); + auto req = createReq(AddTorrentRpcMethod::getMethodName()); req.params->append(readFile(torrentFile)); - RpcResponse res = m.execute(req, e.get()); + auto res = m.execute(std::move(req), e.get()); } } // namespace #endif // ENABLE_BITTORRENT @@ -716,10 +735,10 @@ void RpcMethodTest::testTellWaiting() #endif // !ENABLE_BITTORRENT auto& rgman = e_->getRequestGroupMan(); TellWaitingRpcMethod m; - RpcRequest req(TellWaitingRpcMethod::getMethodName(), List::g()); + auto req = createReq(TellWaitingRpcMethod::getMethodName()); req.params->append(Integer::g(1)); req.params->append(Integer::g(2)); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); const List* resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)2, resParams->size()); @@ -730,56 +749,60 @@ void RpcMethodTest::testTellWaiting() ->getGID()), getString(downcast<Dict>(resParams->get(1)), "gid")); // waiting.size() == offset+num - req = RpcRequest(TellWaitingRpcMethod::getMethodName(), List::g()); + req = createReq(TellWaitingRpcMethod::getMethodName()); req.params->append(Integer::g(1)); req.params->append(Integer::g(3)); - res = m.execute(req, e_.get()); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)3, resParams->size()); // waiting.size() < offset+num - req = RpcRequest(TellWaitingRpcMethod::getMethodName(), List::g()); + req = createReq(TellWaitingRpcMethod::getMethodName()); req.params->append(Integer::g(1)); req.params->append(Integer::g(4)); - res = m.execute(req, e_.get()); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)3, resParams->size()); // offset = INT32_MAX - req.params->set(0, Integer::g(INT32_MAX)); - req.params->set(1, Integer::g(1)); - res = m.execute(req, e_.get()); + req = createReq(TellWaitingRpcMethod::getMethodName()); + req.params->append(Integer::g(INT32_MAX)); + req.params->append(Integer::g(1)); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)0, resParams->size()); // num = INT32_MAX - req.params->set(0, Integer::g(1)); - req.params->set(1, Integer::g(INT32_MAX)); - res = m.execute(req, e_.get()); + req = createReq(TellWaitingRpcMethod::getMethodName()); + req.params->append(Integer::g(1)); + req.params->append(Integer::g(INT32_MAX)); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)3, resParams->size()); // offset=INT32_MAX and num = INT32_MAX - req.params->set(0, Integer::g(INT32_MAX)); - req.params->set(1, Integer::g(INT32_MAX)); - res = m.execute(req, e_.get()); + req = createReq(TellWaitingRpcMethod::getMethodName()); + req.params->append(Integer::g(INT32_MAX)); + req.params->append(Integer::g(INT32_MAX)); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)0, resParams->size()); // offset=INT32_MIN and num = INT32_MAX - req.params->set(0, Integer::g(INT32_MIN)); - req.params->set(1, Integer::g(INT32_MAX)); - res = m.execute(req, e_.get()); + req = createReq(TellWaitingRpcMethod::getMethodName()); + req.params->append(Integer::g(INT32_MIN)); + req.params->append(Integer::g(INT32_MAX)); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)0, resParams->size()); // negative offset - req = RpcRequest(TellWaitingRpcMethod::getMethodName(), List::g()); + req = createReq(TellWaitingRpcMethod::getMethodName()); req.params->append(Integer::g(-1)); req.params->append(Integer::g(2)); - res = m.execute(req, e_.get()); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)2, resParams->size()); @@ -790,20 +813,26 @@ void RpcMethodTest::testTellWaiting() 2)->getGID()), getString(downcast<Dict>(resParams->get(1)), "gid")); // negative offset and size < num - req.params->set(1, Integer::g(100)); - res = m.execute(req, e_.get()); + req = RpcRequest(TellWaitingRpcMethod::getMethodName(), List::g()); + req.params->append(Integer::g(-1)); + req.params->append(Integer::g(100)); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)4, resParams->size()); // nagative offset and normalized offset < 0 - req.params->set(0, Integer::g(-5)); - res = m.execute(req, e_.get()); + req = RpcRequest(TellWaitingRpcMethod::getMethodName(), List::g()); + req.params->append(Integer::g(-5)); + req.params->append(Integer::g(100)); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)0, resParams->size()); // nagative offset and normalized offset == 0 - req.params->set(0, Integer::g(-4)); - res = m.execute(req, e_.get()); + req = RpcRequest(TellWaitingRpcMethod::getMethodName(), List::g()); + req.params->append(Integer::g(-4)); + req.params->append(Integer::g(100)); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)1, resParams->size()); @@ -812,24 +841,23 @@ void RpcMethodTest::testTellWaiting() void RpcMethodTest::testTellWaiting_fail() { TellWaitingRpcMethod m; - RpcRequest req(TellWaitingRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(createReq(TellWaitingRpcMethod::getMethodName()), + e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } void RpcMethodTest::testGetVersion() { GetVersionRpcMethod m; - RpcRequest req(GetVersionRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(createReq(GetVersionRpcMethod::getMethodName()), + e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); const Dict* resParams = downcast<Dict>(res.param); CPPUNIT_ASSERT_EQUAL(std::string(PACKAGE_VERSION), getString(resParams, "version")); const List* featureList = downcast<List>(resParams->get("enabledFeatures")); std::string features; - for(List::ValueType::const_iterator i = featureList->begin(); - i != featureList->end(); ++i) { + for(auto i = featureList->begin(); i != featureList->end(); ++i) { const String* s = downcast<String>(*i); features += s->s(); features += ", "; @@ -839,11 +867,11 @@ void RpcMethodTest::testGetVersion() void RpcMethodTest::testGatherStoppedDownload() { - std::vector<std::shared_ptr<FileEntry> > fileEntries; + std::vector<std::shared_ptr<FileEntry>> fileEntries; std::vector<a2_gid_t> followedBy; followedBy.push_back(3); followedBy.push_back(4); - std::shared_ptr<DownloadResult> d(new DownloadResult()); + auto d = std::make_shared<DownloadResult>(); d->gid = GroupId::create(); d->fileEntries = fileEntries; d->inMemoryDownload = false; @@ -852,9 +880,9 @@ void RpcMethodTest::testGatherStoppedDownload() d->result = error_code::FINISHED; d->followedBy = followedBy; d->belongsTo = 2; - std::shared_ptr<Dict> entry = Dict::g(); + auto entry = Dict::g(); std::vector<std::string> keys; - gatherStoppedDownload(entry, d, keys); + gatherStoppedDownload(entry.get(), d, keys); const List* followedByRes = downcast<List>(entry->get("followedBy")); CPPUNIT_ASSERT_EQUAL(GroupId::toHex(3), @@ -867,33 +895,32 @@ void RpcMethodTest::testGatherStoppedDownload() keys.push_back("gid"); entry = Dict::g(); - gatherStoppedDownload(entry, d, keys); + gatherStoppedDownload(entry.get(), d, keys); CPPUNIT_ASSERT_EQUAL((size_t)1, entry->size()); CPPUNIT_ASSERT(entry->containsKey("gid")); } void RpcMethodTest::testGatherProgressCommon() { - std::shared_ptr<DownloadContext> dctx(new DownloadContext(0, 0,"aria2.tar.bz2")); + auto dctx = std::make_shared<DownloadContext>(0, 0,"aria2.tar.bz2"); std::string uris[] = { "http://localhost/aria2.tar.bz2" }; dctx->getFirstFileEntry()->addUris(std::begin(uris), std::end(uris)); - std::shared_ptr<RequestGroup> group(new RequestGroup(GroupId::create(), - util::copy(option_))); + auto group = std::make_shared<RequestGroup>(GroupId::create(), + util::copy(option_)); group->setDownloadContext(dctx); - std::vector<std::shared_ptr<RequestGroup> > followedBy; + std::vector<std::shared_ptr<RequestGroup>> followedBy; for(int i = 0; i < 2; ++i) { - followedBy.push_back(std::shared_ptr<RequestGroup> - (new RequestGroup(GroupId::create(), - util::copy(option_)))); + followedBy.push_back(std::make_shared<RequestGroup>(GroupId::create(), + util::copy(option_))); } group->followedBy(followedBy.begin(), followedBy.end()); - std::shared_ptr<GroupId> parent = GroupId::create(); + auto parent = GroupId::create(); group->belongsTo(parent->getNumericId()); - std::shared_ptr<Dict> entry = Dict::g(); + auto entry = Dict::g(); std::vector<std::string> keys; - gatherProgressCommon(entry, group, keys); + gatherProgressCommon(entry.get(), group, keys); const List* followedByRes = downcast<List>(entry->get("followedBy")); CPPUNIT_ASSERT_EQUAL(GroupId::toHex(followedBy[0]->getGID()), @@ -918,7 +945,7 @@ void RpcMethodTest::testGatherProgressCommon() keys.push_back("gid"); entry = Dict::g(); - gatherProgressCommon(entry, group, keys); + gatherProgressCommon(entry.get(), group, keys); CPPUNIT_ASSERT_EQUAL((size_t)1, entry->size()); CPPUNIT_ASSERT(entry->containsKey("gid")); @@ -928,12 +955,12 @@ void RpcMethodTest::testGatherProgressCommon() #ifdef ENABLE_BITTORRENT void RpcMethodTest::testGatherBitTorrentMetadata() { - std::shared_ptr<Option> option(new Option()); + auto option = std::make_shared<Option>(); option->put(PREF_DIR, "."); - std::shared_ptr<DownloadContext> dctx(new DownloadContext()); + auto dctx = std::make_shared<DownloadContext>(); bittorrent::load(A2_TEST_DIR"/test.torrent", dctx, option); - std::shared_ptr<Dict> btDict = Dict::g(); - gatherBitTorrentMetadata(btDict, bittorrent::getTorrentAttrs(dctx)); + auto btDict = Dict::g(); + gatherBitTorrentMetadata(btDict.get(), bittorrent::getTorrentAttrs(dctx)); CPPUNIT_ASSERT_EQUAL(std::string("REDNOAH.COM RULES"), downcast<String>(btDict->get("comment"))->s()); CPPUNIT_ASSERT_EQUAL((int64_t)1123456789, @@ -961,7 +988,7 @@ void RpcMethodTest::testGatherBitTorrentMetadata() modBtAttrs->mode = BT_FILE_MODE_NONE; modBtAttrs->metadata.clear(); btDict = Dict::g(); - gatherBitTorrentMetadata(btDict, modBtAttrs); + gatherBitTorrentMetadata(btDict.get(), modBtAttrs); CPPUNIT_ASSERT(!btDict->containsKey("comment")); CPPUNIT_ASSERT(!btDict->containsKey("creationDate")); CPPUNIT_ASSERT(!btDict->containsKey("mode")); @@ -973,19 +1000,17 @@ void RpcMethodTest::testGatherBitTorrentMetadata() void RpcMethodTest::testChangePosition() { e_->getRequestGroupMan()->addReservedGroup - (std::shared_ptr<RequestGroup>(new RequestGroup(GroupId::create(), - util::copy(option_)))); + (std::make_shared<RequestGroup>(GroupId::create(), util::copy(option_))); e_->getRequestGroupMan()->addReservedGroup - (std::shared_ptr<RequestGroup>(new RequestGroup(GroupId::create(), - util::copy(option_)))); + (std::make_shared<RequestGroup>(GroupId::create(), util::copy(option_))); a2_gid_t gid = getReservedGroup(e_->getRequestGroupMan().get(), 0)->getGID(); ChangePositionRpcMethod m; - RpcRequest req(ChangePositionRpcMethod::getMethodName(), List::g()); + auto req = createReq(ChangePositionRpcMethod::getMethodName()); req.params->append(GroupId::toHex(gid)); req.params->append(Integer::g(1)); req.params->append("POS_SET"); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); CPPUNIT_ASSERT_EQUAL((int64_t)1, downcast<Integer>(res.param)->i()); CPPUNIT_ASSERT_EQUAL @@ -995,16 +1020,34 @@ void RpcMethodTest::testChangePosition() void RpcMethodTest::testChangePosition_fail() { ChangePositionRpcMethod m; - RpcRequest req(ChangePositionRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute + (createReq(ChangePositionRpcMethod::getMethodName()), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); + auto req = createReq(ChangePositionRpcMethod::getMethodName()); req.params->append("1"); req.params->append(Integer::g(2)); req.params->append("bad keyword"); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } +namespace { +RpcRequest createChangeUriReq(a2_gid_t gid, size_t fileIndex) +{ + auto req = createReq(ChangeUriRpcMethod::getMethodName()); + + req.params->append(GroupId::toHex(gid)); // GID + req.params->append(Integer::g(fileIndex)); // index of FileEntry + auto removeuris = List::g(); + removeuris->append("http://example.org/mustremove1"); + removeuris->append("http://example.org/mustremove2"); + removeuris->append("http://example.org/notexist"); + req.params->append(std::move(removeuris)); + return req; +} +} // namespace + void RpcMethodTest::testChangeUri() { std::shared_ptr<FileEntry> files[3]; @@ -1014,29 +1057,21 @@ void RpcMethodTest::testChangeUri() files[1]->addUri("http://example.org/aria2.tar.bz2"); files[1]->addUri("http://example.org/mustremove1"); files[1]->addUri("http://example.org/mustremove2"); - std::shared_ptr<DownloadContext> dctx(new DownloadContext()); + auto dctx = std::make_shared<DownloadContext>(); dctx->setFileEntries(&files[0], &files[3]); - std::shared_ptr<RequestGroup> group(new RequestGroup(GroupId::create(), - option_)); + auto group = std::make_shared<RequestGroup>(GroupId::create(), option_); group->setDownloadContext(dctx); e_->getRequestGroupMan()->addReservedGroup(group); ChangeUriRpcMethod m; - RpcRequest req(ChangeUriRpcMethod::getMethodName(), List::g()); - req.params->append(GroupId::toHex(group->getGID())); // GID - req.params->append(Integer::g(2)); // index of FileEntry - std::shared_ptr<List> removeuris = List::g(); - removeuris->append("http://example.org/mustremove1"); - removeuris->append("http://example.org/mustremove2"); - removeuris->append("http://example.org/notexist"); - req.params->append(removeuris); - std::shared_ptr<List> adduris = List::g(); + auto req = createChangeUriReq(group->getGID(), 2); + auto adduris = List::g(); adduris->append("http://example.org/added1"); adduris->append("http://example.org/added2"); adduris->append("baduri"); adduris->append("http://example.org/added3"); - req.params->append(adduris); - RpcResponse res = m.execute(req, e_.get()); + req.params->append(std::move(adduris)); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); CPPUNIT_ASSERT_EQUAL((int64_t)2, downcast<Integer>(downcast<List>(res.param)->get(0))->i()); CPPUNIT_ASSERT_EQUAL((int64_t)3, downcast<Integer>(downcast<List>(res.param)->get(1))->i()); @@ -1049,14 +1084,15 @@ void RpcMethodTest::testChangeUri() CPPUNIT_ASSERT_EQUAL(std::string("http://example.org/added2"), uris[2]); CPPUNIT_ASSERT_EQUAL(std::string("http://example.org/added3"), uris[3]); + req = createChangeUriReq(group->getGID(), 2); // Change adduris adduris = List::g(); adduris->append("http://example.org/added1-1"); adduris->append("http://example.org/added1-2"); - req.params->set(3, adduris); + req.params->append(std::move(adduris)); // Set position parameter req.params->append(Integer::g(2)); - res = m.execute(req, e_.get()); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); CPPUNIT_ASSERT_EQUAL((int64_t)0, downcast<Integer>(downcast<List>(res.param)->get(0))->i()); CPPUNIT_ASSERT_EQUAL((int64_t)2, downcast<Integer>(downcast<List>(res.param)->get(1))->i()); @@ -1066,10 +1102,14 @@ void RpcMethodTest::testChangeUri() CPPUNIT_ASSERT_EQUAL(std::string("http://example.org/added1-2"), uris[3]); // Change index of FileEntry - req.params->set(1, Integer::g(1)); + req = createChangeUriReq(group->getGID(), 1); + adduris = List::g(); + adduris->append("http://example.org/added1-1"); + adduris->append("http://example.org/added1-2"); + req.params->append(std::move(adduris)); // Set position far beyond the size of uris in FileEntry. - req.params->set(4, Integer::g(1000)); - res = m.execute(req, e_.get()); + req.params->append(Integer::g(1000)); + res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); CPPUNIT_ASSERT_EQUAL((int64_t)0, downcast<Integer>(downcast<List>(res.param)->get(0))->i()); CPPUNIT_ASSERT_EQUAL((int64_t)2, downcast<Integer>(downcast<List>(res.param)->get(1))->i()); @@ -1079,61 +1119,67 @@ void RpcMethodTest::testChangeUri() CPPUNIT_ASSERT_EQUAL(std::string("http://example.org/added1-2"), uris[1]); } +namespace { +RpcRequest createChangeUriEmptyReq(a2_gid_t gid, size_t fileIndex) +{ + auto req = createReq(ChangeUriRpcMethod::getMethodName()); + + req.params->append(GroupId::toHex(gid)); // GID + req.params->append(Integer::g(fileIndex)); // index of FileEntry + req.params->append(List::g()); // remove uris + req.params->append(List::g()); // append uris + return req; +} +} // namespace + void RpcMethodTest::testChangeUri_fail() { std::shared_ptr<FileEntry> files[3]; for(int i = 0; i < 3; ++i) { - files[i].reset(new FileEntry()); + files[i] = std::make_shared<FileEntry>(); } - std::shared_ptr<DownloadContext> dctx(new DownloadContext()); + auto dctx = std::make_shared<DownloadContext>(); dctx->setFileEntries(&files[0], &files[3]); - std::shared_ptr<RequestGroup> group(new RequestGroup(GroupId::create(), - option_)); + auto group = std::make_shared<RequestGroup>(GroupId::create(), option_); group->setDownloadContext(dctx); e_->getRequestGroupMan()->addReservedGroup(group); ChangeUriRpcMethod m; - RpcRequest req(ChangeUriRpcMethod::getMethodName(), List::g()); - req.params->append(GroupId::toHex(group->getGID())); // GID - req.params->append(Integer::g(1)); // index of FileEntry - std::shared_ptr<List> removeuris = List::g(); - req.params->append(removeuris); - std::shared_ptr<List> adduris = List::g(); - req.params->append(adduris); - RpcResponse res = m.execute(req, e_.get()); + auto req = createChangeUriEmptyReq(group->getGID(), 1); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); - req.params->set(1, Integer::g(0)); - res = m.execute(req, e_.get()); + req = createChangeUriEmptyReq(group->getGID(), 0); + res = m.execute(std::move(req), e_.get()); // RPC request fails because 2nd argument is less than 1. CPPUNIT_ASSERT_EQUAL(1, res.code); - req.params->set(1, Integer::g(1)); - req.params->set(0, String::g(GroupId::create()->toHex())); - res = m.execute(req, e_.get()); + req = createChangeUriEmptyReq(GroupId::create()->getNumericId(), 1); + res = m.execute(std::move(req), e_.get()); // RPC request fails because the given GID does not exist. CPPUNIT_ASSERT_EQUAL(1, res.code); - req.params->set(0, String::g(GroupId::toHex(group->getGID()))); - req.params->set(1, Integer::g(4)); - res = m.execute(req, e_.get()); + req = createChangeUriEmptyReq(group->getGID(), 4); + res = m.execute(std::move(req), e_.get()); // RPC request fails because FileEntry#3 does not exist. CPPUNIT_ASSERT_EQUAL(1, res.code); + req = createChangeUriEmptyReq(group->getGID(), 1); req.params->set(1, String::g("0")); - res = m.execute(req, e_.get()); + res = m.execute(std::move(req), e_.get()); // RPC request fails because index of FileEntry is string. CPPUNIT_ASSERT_EQUAL(1, res.code); - req.params->set(1, Integer::g(1)); + req = createChangeUriEmptyReq(group->getGID(), 1); req.params->set(2, String::g("http://url")); - res = m.execute(req, e_.get()); + res = m.execute(std::move(req), e_.get()); // RPC request fails because 3rd param is not list. CPPUNIT_ASSERT_EQUAL(1, res.code); + req = createChangeUriEmptyReq(group->getGID(), 1); req.params->set(2, List::g()); req.params->set(3, String::g("http://url")); - res = m.execute(req, e_.get()); + res = m.execute(std::move(req), e_.get()); // RPC request fails because 4th param is not list. CPPUNIT_ASSERT_EQUAL(1, res.code); } @@ -1141,8 +1187,8 @@ void RpcMethodTest::testChangeUri_fail() void RpcMethodTest::testGetSessionInfo() { GetSessionInfoRpcMethod m; - RpcRequest req(GetSessionInfoRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute + (createReq(GetSessionInfoRpcMethod::getMethodName()), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); CPPUNIT_ASSERT_EQUAL(util::toHex(e_->getSessionId()), getString(downcast<Dict>(res.param), "sessionId")); @@ -1156,30 +1202,30 @@ void RpcMethodTest::testPause() "http://url3", }; option_->put(PREF_FORCE_SEQUENTIAL, A2_V_TRUE); - std::vector<std::shared_ptr<RequestGroup> > groups; + std::vector<std::shared_ptr<RequestGroup>> groups; createRequestGroupForUri(groups, option_, uris); CPPUNIT_ASSERT_EQUAL((size_t)3, groups.size()); e_->getRequestGroupMan()->addReservedGroup(groups); { PauseRpcMethod m; - RpcRequest req(PauseRpcMethod::getMethodName(), List::g()); + auto req = createReq(PauseRpcMethod::getMethodName()); req.params->append(GroupId::toHex(groups[0]->getGID())); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); } CPPUNIT_ASSERT(groups[0]->isPauseRequested()); { UnpauseRpcMethod m; - RpcRequest req(UnpauseRpcMethod::getMethodName(), List::g()); + auto req = createReq(UnpauseRpcMethod::getMethodName()); req.params->append(GroupId::toHex(groups[0]->getGID())); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); } CPPUNIT_ASSERT(!groups[0]->isPauseRequested()); { PauseAllRpcMethod m; - RpcRequest req(PauseAllRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto req = createReq(PauseAllRpcMethod::getMethodName()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); } for(size_t i = 0; i < groups.size(); ++i) { @@ -1187,8 +1233,8 @@ void RpcMethodTest::testPause() } { UnpauseAllRpcMethod m; - RpcRequest req(UnpauseAllRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto req = createReq(UnpauseAllRpcMethod::getMethodName()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); } for(size_t i = 0; i < groups.size(); ++i) { @@ -1196,8 +1242,8 @@ void RpcMethodTest::testPause() } { ForcePauseAllRpcMethod m; - RpcRequest req(ForcePauseAllRpcMethod::getMethodName(), List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto req = createReq(ForcePauseAllRpcMethod::getMethodName()); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); } for(size_t i = 0; i < groups.size(); ++i) { @@ -1208,47 +1254,47 @@ void RpcMethodTest::testPause() void RpcMethodTest::testSystemMulticall() { SystemMulticallRpcMethod m; - RpcRequest req("system.multicall", List::g()); - std::shared_ptr<List> reqparams = List::g(); - req.params->append(reqparams); + auto req = createReq("system.multicall"); + auto reqparams = List::g(); for(int i = 0; i < 2; ++i) { - std::shared_ptr<Dict> dict = Dict::g(); + auto dict = Dict::g(); dict->put("methodName", AddUriRpcMethod::getMethodName()); - std::shared_ptr<List> params = List::g(); - std::shared_ptr<List> urisParam = List::g(); + auto params = List::g(); + auto urisParam = List::g(); urisParam->append("http://localhost/"+util::itos(i)); - params->append(urisParam); - dict->put("params", params); - reqparams->append(dict); + params->append(std::move(urisParam)); + dict->put("params", std::move(params)); + reqparams->append(std::move(dict)); } { - std::shared_ptr<Dict> dict = Dict::g(); + auto dict = Dict::g(); dict->put("methodName", "not exists"); dict->put("params", List::g()); - reqparams->append(dict); + reqparams->append(std::move(dict)); } { reqparams->append("not struct"); } { - std::shared_ptr<Dict> dict = Dict::g(); + auto dict = Dict::g(); dict->put("methodName", "system.multicall"); dict->put("params", List::g()); - reqparams->append(dict); + reqparams->append(std::move(dict)); } { // missing params - std::shared_ptr<Dict> dict = Dict::g(); + auto dict = Dict::g(); dict->put("methodName", GetVersionRpcMethod::getMethodName()); - reqparams->append(dict); + reqparams->append(std::move(dict)); } { - std::shared_ptr<Dict> dict = Dict::g(); + auto dict = Dict::g(); dict->put("methodName", GetVersionRpcMethod::getMethodName()); dict->put("params", List::g()); - reqparams->append(dict); + reqparams->append(std::move(dict)); } - RpcResponse res = m.execute(req, e_.get()); + req.params->append(std::move(reqparams)); + auto res = m.execute(std::move(req), e_.get()); CPPUNIT_ASSERT_EQUAL(0, res.code); const List* resParams = downcast<List>(res.param); CPPUNIT_ASSERT_EQUAL((size_t)7, resParams->size()); @@ -1278,8 +1324,7 @@ void RpcMethodTest::testSystemMulticall() void RpcMethodTest::testSystemMulticall_fail() { SystemMulticallRpcMethod m; - RpcRequest req("system.multicall", List::g()); - RpcResponse res = m.execute(req, e_.get()); + auto res = m.execute(createReq("system.multicall"), e_.get()); CPPUNIT_ASSERT_EQUAL(1, res.code); } diff --git a/test/RpcResponseTest.cc b/test/RpcResponseTest.cc index 6e4eb191..7838d075 100644 --- a/test/RpcResponseTest.cc +++ b/test/RpcResponseTest.cc @@ -26,18 +26,17 @@ void RpcResponseTest::testToJson() { std::vector<RpcResponse> results; { - std::shared_ptr<List> param = List::g(); + auto param = List::g(); param->append(Integer::g(1)); - std::shared_ptr<String> id = String::g("9"); - RpcResponse res(0, param, id); - results.push_back(res); - std::string s = toJson(res, "", false); + RpcResponse res(0, std::move(param), String::g("9")); + results.push_back(std::move(res)); + std::string s = toJson(results.back(), "", false); CPPUNIT_ASSERT_EQUAL(std::string("{\"id\":\"9\"," "\"jsonrpc\":\"2.0\"," "\"result\":[1]}"), s); // with callback - s = toJson(res, "cb", false); + s = toJson(results.back(), "cb", false); CPPUNIT_ASSERT_EQUAL(std::string("cb({\"id\":\"9\"," "\"jsonrpc\":\"2.0\"," "\"result\":[1]})"), @@ -45,24 +44,24 @@ void RpcResponseTest::testToJson() } { // error response - std::shared_ptr<Dict> param = Dict::g(); + auto param = Dict::g(); param->put("code", Integer::g(1)); param->put("message", "HELLO ERROR"); - RpcResponse res(1, param, Null::g()); - results.push_back(res); - std::string s = toJson(res, "", false); - CPPUNIT_ASSERT_EQUAL(std::string("{\"error\":{\"code\":1," - "\"message\":\"HELLO ERROR\"}," - "\"id\":null," - "\"jsonrpc\":\"2.0\"" + RpcResponse res(1, std::move(param), Null::g()); + results.push_back(std::move(res)); + std::string s = toJson(results.back(), "", false); + CPPUNIT_ASSERT_EQUAL(std::string("{\"id\":null," + "\"jsonrpc\":\"2.0\"," + "\"error\":{\"code\":1," + "\"message\":\"HELLO ERROR\"}" "}"), s); // with callback - s = toJson(res, "cb", false); - CPPUNIT_ASSERT_EQUAL(std::string("cb({\"error\":{\"code\":1," - "\"message\":\"HELLO ERROR\"}," - "\"id\":null," - "\"jsonrpc\":\"2.0\"" + s = toJson(results.back(), "cb", false); + CPPUNIT_ASSERT_EQUAL(std::string("cb({\"id\":null," + "\"jsonrpc\":\"2.0\"," + "\"error\":{\"code\":1," + "\"message\":\"HELLO ERROR\"}" "})"), s); } @@ -73,10 +72,10 @@ void RpcResponseTest::testToJson() "{\"id\":\"9\"," "\"jsonrpc\":\"2.0\"," "\"result\":[1]}," - "{\"error\":{\"code\":1," - "\"message\":\"HELLO ERROR\"}," - "\"id\":null," - "\"jsonrpc\":\"2.0\"" + "{\"id\":null," + "\"jsonrpc\":\"2.0\"," + "\"error\":{\"code\":1," + "\"message\":\"HELLO ERROR\"}" "}" "]"), s); @@ -86,10 +85,10 @@ void RpcResponseTest::testToJson() "{\"id\":\"9\"," "\"jsonrpc\":\"2.0\"," "\"result\":[1]}," - "{\"error\":{\"code\":1," - "\"message\":\"HELLO ERROR\"}," - "\"id\":null," - "\"jsonrpc\":\"2.0\"" + "{\"id\":null," + "\"jsonrpc\":\"2.0\"," + "\"error\":{\"code\":1," + "\"message\":\"HELLO ERROR\"}" "}" "])"), s); @@ -99,10 +98,10 @@ void RpcResponseTest::testToJson() #ifdef ENABLE_XML_RPC void RpcResponseTest::testToXml() { - std::shared_ptr<Dict> param = Dict::g(); + auto param = Dict::g(); param->put("faultCode", Integer::g(1)); param->put("faultString", "No such method: make.hamburger"); - RpcResponse res(1, param, Null::g()); + RpcResponse res(1, std::move(param), Null::g()); std::string s = toXml(res, false); CPPUNIT_ASSERT_EQUAL (std::string("<?xml version=\"1.0\"?>" diff --git a/test/ValueBaseJsonParserTest.cc b/test/ValueBaseJsonParserTest.cc index 6a094d16..a51cea02 100644 --- a/test/ValueBaseJsonParserTest.cc +++ b/test/ValueBaseJsonParserTest.cc @@ -30,102 +30,91 @@ void ValueBaseJsonParserTest::testParseUpdate() { // empty object std::string src = "{}"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const Dict* dict = downcast<Dict>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto dict = downcast<Dict>(r); CPPUNIT_ASSERT(dict); } { // empty object std::string src = "{ }"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const Dict* dict = downcast<Dict>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto dict = downcast<Dict>(r); CPPUNIT_ASSERT(dict); } { // empty array std::string src = "[]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); } { // empty array std::string src = "[ ]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); } { // empty string std::string src = "[\"\"]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); - const String* s = downcast<String>(list->get(0)); + auto s = downcast<String>(list->get(0)); CPPUNIT_ASSERT_EQUAL(std::string(), s->s()); } { // string std::string src = "[\"foobar\"]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); - const String* s = downcast<String>(list->get(0)); + auto s = downcast<String>(list->get(0)); CPPUNIT_ASSERT_EQUAL(std::string("foobar"), s->s()); } { // string with escape std::string src = "[\"\\\\foo\\\"\\\"bar\"]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); - const String* s = downcast<String>(list->get(0)); + auto s = downcast<String>(list->get(0)); CPPUNIT_ASSERT_EQUAL(std::string("\\foo\"\"bar"), s->s()); } { // string with escape std::string src = "[\"foo\\\"\"]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); - const String* s = downcast<String>(list->get(0)); + auto s = downcast<String>(list->get(0)); CPPUNIT_ASSERT_EQUAL(std::string("foo\""), s->s()); } { // string: utf-8 1 to 3 bytes. std::string src = "[\"\\u0024\\u00A2\\u20AC\"]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); - const String* s = downcast<String>(list->get(0)); + auto s = downcast<String>(list->get(0)); CPPUNIT_ASSERT_EQUAL(std::string("$¢€"), s->s()); } { // string: utf-8 4 bytes std::string src = "[\"\\uD852\\uDF62\"]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); - const String* s = downcast<String>(list->get(0)); + auto s = downcast<String>(list->get(0)); const unsigned char arr[] = { 0xF0u, 0xA4u, 0xADu, 0xA2u }; CPPUNIT_ASSERT_EQUAL(std::string(std::begin(arr), std::end(arr)), s->s()); } { // null std::string src = "[null]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); const Null* s = downcast<Null>(list->get(0)); CPPUNIT_ASSERT(s); @@ -133,9 +122,8 @@ void ValueBaseJsonParserTest::testParseUpdate() { // true, false std::string src = "[true, false]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); const Bool* trueValue = downcast<Bool>(list->get(0)); CPPUNIT_ASSERT(trueValue); @@ -147,38 +135,35 @@ void ValueBaseJsonParserTest::testParseUpdate() { // object: 1 member std::string src = "{\"foo\":[\"bar\"]}"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); + auto r = parser.parseFinal(src.c_str(), src.size(), error); const Dict* dict = downcast<Dict>(r); CPPUNIT_ASSERT(dict); - const List* list = downcast<List>(dict->get("foo")); + auto list = downcast<List>(dict->get("foo")); CPPUNIT_ASSERT(list); - const String* s = downcast<String>(list->get(0)); + auto s = downcast<String>(list->get(0)); CPPUNIT_ASSERT_EQUAL(std::string("bar"), s->s()); } { // object: 2 members // TODO ValueBaseJsonParser does not allow empty dict key std::string src = "{\"foo\":[\"bar\"], \"alpha\" : \"bravo\"}"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); + auto r = parser.parseFinal(src.c_str(), src.size(), error); const Dict* dict = downcast<Dict>(r); CPPUNIT_ASSERT(dict); - const List* list = downcast<List>(dict->get("foo")); + auto list = downcast<List>(dict->get("foo")); CPPUNIT_ASSERT(list); - const String* s = downcast<String>(list->get(0)); + auto s = downcast<String>(list->get(0)); CPPUNIT_ASSERT_EQUAL(std::string("bar"), s->s()); - const String* str = downcast<String>(dict->get("alpha")); + auto str = downcast<String>(dict->get("alpha")); CPPUNIT_ASSERT_EQUAL(std::string("bravo"), str->s()); } { // array: 2 values std::string src = "[\"foo\", {}]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); - const String* s = downcast<String>(list->get(0)); + auto s = downcast<String>(list->get(0)); CPPUNIT_ASSERT_EQUAL(std::string("foo"), s->s()); const Dict* dict = downcast<Dict>(list->get(1)); CPPUNIT_ASSERT(dict); @@ -186,9 +171,8 @@ void ValueBaseJsonParserTest::testParseUpdate() { // Number: currently we ignore frac and exp std::string src = "[0,-1,1.2,-1.2e-10,-1e10]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); const Integer* i = downcast<Integer>(list->get(0)); CPPUNIT_ASSERT_EQUAL((Integer::ValueType)0, i->i()); @@ -204,28 +188,25 @@ void ValueBaseJsonParserTest::testParseUpdate() { // escape chars: ", \, /, \b, \f, \n, \r, \t std::string src = "[\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); - const String* s = downcast<String>(list->get(0)); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); + auto s = downcast<String>(list->get(0)); CPPUNIT_ASSERT_EQUAL(std::string("\"\\/\b\f\n\r\t"), s->s()); } { // string: literal + escaped chars. std::string src = "[\"foo\\u0024b\\u00A2\\u20ACbaz\"]"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); - const String* s = downcast<String>(list->get(0)); + auto s = downcast<String>(list->get(0)); CPPUNIT_ASSERT_EQUAL(std::string("foo$b¢€baz"), s->s()); } { // ignore garbage at the end of the input. std::string src = "[]trail"; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); - const List* list = downcast<List>(r); + auto r = parser.parseFinal(src.c_str(), src.size(), error); + auto list = downcast<List>(r); CPPUNIT_ASSERT(list); CPPUNIT_ASSERT_EQUAL((ssize_t)2, error); } @@ -236,8 +217,7 @@ void checkDecodeError(const std::string& src) { json::ValueBaseJsonParser parser; ssize_t error; - std::shared_ptr<ValueBase> r = parser.parseFinal(src.c_str(), src.size(), - error); + auto r = parser.parseFinal(src.c_str(), src.size(), error); CPPUNIT_ASSERT(!r); CPPUNIT_ASSERT(error < 0); } diff --git a/test/ValueBaseTest.cc b/test/ValueBaseTest.cc index 6edeb02b..56609667 100644 --- a/test/ValueBaseTest.cc +++ b/test/ValueBaseTest.cc @@ -87,8 +87,8 @@ void ValueBaseTest::testDict() Dict dict; CPPUNIT_ASSERT(dict.empty()); - dict["ki"] = Integer::g(7); - dict["ks"] = String::g("abc"); + dict.put("ki", Integer::g(7)); + dict.put("ks", String::g("abc")); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), dict.size()); CPPUNIT_ASSERT(dict.containsKey("ki")); @@ -98,27 +98,31 @@ void ValueBaseTest::testDict() CPPUNIT_ASSERT_EQUAL(std::string("abc"), downcast<String>(dict["ks"])->s()); - CPPUNIT_ASSERT(!dict["kn"]); // This adds kn key with default value. - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), dict.size()); - CPPUNIT_ASSERT(dict.containsKey("kn")); + CPPUNIT_ASSERT(!dict["kn"]); // This does not adds kn key + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), dict.size()); - const Dict& ref = dict; + auto& ref = dict; ref["kn2"]; // This doesn't add kn2 key. - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), ref.size()); + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), ref.size()); CPPUNIT_ASSERT(!ref.containsKey("kn2")); - dict.removeKey("kn"); - CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), dict.size()); - CPPUNIT_ASSERT(!dict.containsKey("kn")); + dict.removeKey("ks"); + CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), dict.size()); + CPPUNIT_ASSERT(!dict.containsKey("ks")); + + auto ki = dict.popValue("ki"); + CPPUNIT_ASSERT_EQUAL(Integer::ValueType{7}, downcast<Integer>(ki)->i()); + CPPUNIT_ASSERT(dict.empty()); + CPPUNIT_ASSERT(!dict.containsKey("ki")); } void ValueBaseTest::testDictIter() { Dict dict; - dict["alpha2"] = String::g("alpha2"); - dict["charlie"] = String::g("charlie"); - dict["bravo"] = String::g("bravo"); - dict["alpha"] = String::g("alpha"); + dict.put("alpha2", String::g("alpha2")); + dict.put("charlie", String::g("charlie")); + dict.put("bravo", String::g("bravo")); + dict.put("alpha", String::g("alpha")); Dict::ValueType::iterator i = dict.begin(); CPPUNIT_ASSERT_EQUAL(std::string("alpha"), (*i++).first); |
