diff --git a/src/brpc/policy/auto_concurrency_limiter.cpp b/src/brpc/policy/auto_concurrency_limiter.cpp index e9cce0fa43..0f70d9b043 100644 --- a/src/brpc/policy/auto_concurrency_limiter.cpp +++ b/src/brpc/policy/auto_concurrency_limiter.cpp @@ -97,7 +97,7 @@ AutoConcurrencyLimiter::AutoConcurrencyLimiter() } AutoConcurrencyLimiter* AutoConcurrencyLimiter::New(const AdaptiveMaxConcurrency&) const { - return new (std::nothrow) AutoConcurrencyLimiter; + return new AutoConcurrencyLimiter; } bool AutoConcurrencyLimiter::OnRequested(int current_concurrency, Controller*) { diff --git a/src/brpc/policy/baidu_rpc_protocol.cpp b/src/brpc/policy/baidu_rpc_protocol.cpp index 41ff97ee22..b74fb1805a 100644 --- a/src/brpc/policy/baidu_rpc_protocol.cpp +++ b/src/brpc/policy/baidu_rpc_protocol.cpp @@ -157,7 +157,7 @@ bool SerializeRpcMessage(const google::protobuf::Message& message, ok = serializer.SerializeTo(&stream); } else { const CompressHandler* handler = FindCompressHandler(compress_type); - if (NULL == handler) { + if (nullptr == handler) { return false; } ok = handler->Compress(serializer, buf); @@ -232,7 +232,7 @@ static bool SerializeResponse(const google::protobuf::Message& res, ContentType content_type = cntl.response_content_type(); CompressType compress_type = cntl.response_compress_type(); ChecksumType checksum_type = cntl.response_checksum_type(); - const butil::IOBuf* checksum_attachment = NULL; + const butil::IOBuf* checksum_attachment = nullptr; if (cntl.response_checksum_attachment()) { // See the same check in SerializeRpcRequest() for the rationale; // baidu_std never sets this flag itself but we defend anyway. @@ -289,8 +289,8 @@ void SendRpcResponse(int64_t correlation_id, Controller* cntl, } Socket* sock = accessor.get_sending_socket(); - const google::protobuf::Message* req = NULL == messages ? NULL : messages->Request(); - const google::protobuf::Message* res = NULL == messages ? NULL : messages->Response(); + const google::protobuf::Message* req = nullptr == messages ? nullptr : messages->Request(); + const google::protobuf::Message* res = nullptr == messages ? nullptr : messages->Response(); // Recycle resources at the end of this function. BRPC_SCOPE_EXIT { @@ -301,12 +301,12 @@ void SendRpcResponse(int64_t correlation_id, Controller* cntl, std::unique_ptr recycle_cntl(cntl); - if (NULL == messages) { + if (nullptr == messages) { return; } cntl->CallAfterRpcResp(req, res); - if (NULL == server->options().baidu_master_service) { + if (nullptr == server->options().baidu_master_service) { server->options().rpc_pb_message_factory->Return(messages); } else { BaiduProxyPBMessages::Return(static_cast(messages)); @@ -324,10 +324,10 @@ void SendRpcResponse(int64_t correlation_id, Controller* cntl, } bool append_body = false; butil::IOBuf res_body; - // `res' can be NULL here, in which case we don't serialize it + // `res' can be nullptr here, in which case we don't serialize it // If user calls `SetFailed' on Controller, we don't serialize // response either - if (res != NULL && !cntl->Failed()) { + if (res != nullptr && !cntl->Failed()) { append_body = SerializeResponse(*res, *cntl, res_body); } @@ -523,7 +523,7 @@ bool DeserializeRpcMessage(const butil::IOBuf& data, Controller& cntl, ok = deserializer.DeserializeFrom(&stream); } else { const CompressHandler* handler = FindCompressHandler(compress_type); - if (NULL == handler) { + if (nullptr == handler) { return false; } ok = handler->Decompress(data, &deserializer); @@ -607,13 +607,9 @@ void ProcessRpcRequest(InputMessageBase* msg_base) { sample->submit(start_parse_us); } - std::unique_ptr cntl(new (std::nothrow) Controller); - if (NULL == cntl.get()) { - LOG(WARNING) << "Fail to new Controller"; - return; - } + std::unique_ptr cntl(new Controller); - RpcPBMessages* messages = NULL; + RpcPBMessages* messages = nullptr; ServerPrivateAccessor server_accessor(server); ControllerPrivateAccessor accessor(cntl.get()); @@ -673,7 +669,7 @@ void ProcessRpcRequest(InputMessageBase* msg_base) { span->set_request_size(msg->payload.size() + msg->meta.size() + 12); } - MethodStatus* method_status = NULL; + MethodStatus* method_status = nullptr; do { if (!server->IsRunning()) { cntl->SetFailed(ELOGOFF, "Server is stopping"); @@ -703,9 +699,9 @@ void ProcessRpcRequest(InputMessageBase* msg_base) { } } - google::protobuf::Service* svc = NULL; - google::protobuf::MethodDescriptor* method = NULL; - if (NULL != server->options().baidu_master_service) { + google::protobuf::Service* svc = nullptr; + google::protobuf::MethodDescriptor* method = nullptr; + if (nullptr != server->options().baidu_master_service) { if (socket->is_overcrowded() && !server->options().ignore_eovercrowded && !server->options().baidu_master_service->ignore_eovercrowded()) { @@ -714,11 +710,7 @@ void ProcessRpcRequest(InputMessageBase* msg_base) { break; } svc = server->options().baidu_master_service; - auto sampled_request = new (std::nothrow) SampledRequest; - if (NULL == sampled_request) { - cntl->SetFailed(ENOMEM, "Fail to get sampled_request"); - break; - } + auto sampled_request = new SampledRequest; sampled_request->meta.set_service_name(request_meta.service_name()); sampled_request->meta.set_method_name(request_meta.method_name()); cntl->reset_sampled_request(sampled_request); @@ -753,7 +745,7 @@ void ProcessRpcRequest(InputMessageBase* msg_base) { if (svc_name.find('.') == butil::StringPiece::npos) { const Server::ServiceProperty* sp = server_accessor.FindServicePropertyByName(svc_name); - if (NULL == sp) { + if (nullptr == sp) { cntl->SetFailed(ENOSERVICE, "Fail to find service=%s", request_meta.service_name().c_str()); break; @@ -763,7 +755,7 @@ void ProcessRpcRequest(InputMessageBase* msg_base) { const Server::MethodProperty* mp = server_accessor.FindMethodPropertyByFullName( svc_name, request_meta.method_name()); - if (NULL == mp) { + if (nullptr == mp) { cntl->SetFailed(ENOMETHOD, "Fail to find method=%s/%s", request_meta.service_name().c_str(), request_meta.method_name().c_str()); @@ -772,7 +764,7 @@ void ProcessRpcRequest(InputMessageBase* msg_base) { BadMethodRequest breq; BadMethodResponse bres; breq.set_service_name(request_meta.service_name()); - mp->service->CallMethod(mp->method, cntl.get(), &breq, &bres, NULL); + mp->service->CallMethod(mp->method, cntl.get(), &breq, &bres, nullptr); break; } if (socket->is_overcrowded() && @@ -827,7 +819,7 @@ void ProcessRpcRequest(InputMessageBase* msg_base) { // it into the checksum now when the client asked us to. const butil::IOBuf* checksum_attachment = cntl->request_checksum_attachment() ? - &cntl->request_attachment() : NULL; + &cntl->request_attachment() : nullptr; if (!DeserializeRpcMessage(req_buf, *cntl, content_type, compress_type, checksum_type, messages->Request(), @@ -898,7 +890,7 @@ bool VerifyRpcRequest(const InputMessageBase* msg_base) { return false; } const Authenticator* auth = server->options().auth; - if (NULL == auth) { + if (nullptr == auth) { // Fast pass (no authentication) return true; } @@ -939,7 +931,7 @@ void ProcessRpcResponse(InputMessageBase* msg_base) { } const bthread_id_t cid = { static_cast(meta.correlation_id()) }; - Controller* cntl = NULL; + Controller* cntl = nullptr; StreamId remote_stream_id = meta.has_stream_settings() ? meta.stream_settings().stream_id(): INVALID_STREAM_ID; @@ -1016,7 +1008,7 @@ void ProcessRpcResponse(InputMessageBase* msg_base) { // it into the checksum now when the server told us to. const butil::IOBuf* checksum_attachment = cntl->response_checksum_attachment() ? - &cntl->response_attachment() : NULL; + &cntl->response_attachment() : nullptr; if (cntl->response()->GetDescriptor() == SerializedResponse::descriptor()) { ((SerializedResponse*)cntl->response())-> serialized_data().append(*res_buf_ptr); @@ -1044,7 +1036,7 @@ void ProcessRpcResponse(InputMessageBase* msg_base) { void SerializeRpcRequest(butil::IOBuf* request_buf, Controller* cntl, const google::protobuf::Message* request) { // Check sanity of request. - if (NULL == request) { + if (nullptr == request) { return cntl->SetFailed(EREQUEST, "`request' is NULL"); } if (request->GetDescriptor() == SerializedRequest::descriptor()) { @@ -1059,7 +1051,7 @@ void SerializeRpcRequest(butil::IOBuf* request_buf, Controller* cntl, ContentType content_type = cntl->request_content_type(); CompressType compress_type = cntl->request_compress_type(); ChecksumType checksum_type = cntl->request_checksum_type(); - const butil::IOBuf* checksum_attachment = NULL; + const butil::IOBuf* checksum_attachment = nullptr; if (cntl->request_checksum_attachment()) { // Progressive reading (HTTP-only feature) hands the attachment to // the user piece by piece as it arrives, so there's no single, @@ -1108,7 +1100,7 @@ void PackRpcRequest(butil::IOBuf* req_buf, if (cntl->request_checksum_attachment()) { meta.set_checksum_with_attachment(true); } - } else if (NULL != cntl->sampled_request()) { + } else if (nullptr != cntl->sampled_request()) { // Replaying. Keep service-name as the one seen by server. request_meta->set_service_name(cntl->sampled_request()->meta.service_name()); request_meta->set_method_name(cntl->sampled_request()->meta.method_name()); diff --git a/src/brpc/policy/consistent_hashing_load_balancer.cpp b/src/brpc/policy/consistent_hashing_load_balancer.cpp index d29ad55e3c..5ff1558f8b 100644 --- a/src/brpc/policy/consistent_hashing_load_balancer.cpp +++ b/src/brpc/policy/consistent_hashing_load_balancer.cpp @@ -193,7 +193,7 @@ size_t ConsistentHashingLoadBalancer::RemoveBatch( bool use_set = true; if (id_set.init(servers.size() * 2) == 0) { for (size_t i = 0; i < servers.size(); ++i) { - if (id_set.insert(servers[i]) == NULL) { + if (id_set.insert(servers[i]) == nullptr) { use_set = false; break; } @@ -205,7 +205,7 @@ size_t ConsistentHashingLoadBalancer::RemoveBatch( bg.clear(); for (size_t i = 0; i < fg.size(); ++i) { const bool removed = - use_set ? (id_set.seek(fg[i].server_sock) != NULL) + use_set ? (id_set.seek(fg[i].server_sock) != nullptr) : (std::find(servers.begin(), servers.end(), fg[i].server_sock) != servers.end()); if (!removed) { @@ -285,9 +285,8 @@ size_t ConsistentHashingLoadBalancer::RemoveServersInBatch( } LoadBalancer *ConsistentHashingLoadBalancer::New(const butil::StringPiece& params) const { - ConsistentHashingLoadBalancer* lb = - new (std::nothrow) ConsistentHashingLoadBalancer(_type); - if (lb && !lb->SetParameters(params)) { + ConsistentHashingLoadBalancer* lb = new ConsistentHashingLoadBalancer(_type); + if (!lb->SetParameters(params)) { delete lb; lb = nullptr; } diff --git a/src/brpc/policy/consul_naming_service.cpp b/src/brpc/policy/consul_naming_service.cpp index 70e0a46506..5bee4093aa 100644 --- a/src/brpc/policy/consul_naming_service.cpp +++ b/src/brpc/policy/consul_naming_service.cpp @@ -103,7 +103,7 @@ int ConsulNamingService::GetServers(const char* service_name, Controller cntl; cntl.http_request().uri() = consul_url; - _channel.CallMethod(NULL, &cntl, NULL, NULL, NULL); + _channel.CallMethod(nullptr, &cntl, nullptr, nullptr, nullptr); if (cntl.Failed()) { LOG(ERROR) << "Fail to access " << consul_url << ": " << cntl.ErrorText(); diff --git a/src/brpc/policy/couchbase_protocol.cpp b/src/brpc/policy/couchbase_protocol.cpp index 0ab79bfb90..8e59c4f6e2 100644 --- a/src/brpc/policy/couchbase_protocol.cpp +++ b/src/brpc/policy/couchbase_protocol.cpp @@ -84,7 +84,7 @@ ParseResult ParseCouchbaseMessage(butil::IOBuf* source, Socket* socket, bool /*read_eof*/, const void* /*arg*/) { while (1) { const uint8_t* p_cbmagic = (const uint8_t*)source->fetch1(); - if (NULL == p_cbmagic) { + if (nullptr == p_cbmagic) { return MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA); } if (*p_cbmagic != (uint8_t)CB_MAGIC_RESPONSE) { @@ -92,7 +92,7 @@ ParseResult ParseCouchbaseMessage(butil::IOBuf* source, Socket* socket, } char buf[24]; const uint8_t* p = (const uint8_t*)source->fetch(buf, sizeof(buf)); - if (NULL == p) { + if (nullptr == p) { return MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA); } const CouchbaseResponseHeader* header = (const CouchbaseResponseHeader*)p; @@ -118,7 +118,7 @@ ParseResult ParseCouchbaseMessage(butil::IOBuf* source, Socket* socket, } MostCommonMessage* msg = static_cast(socket->parsing_context()); - if (msg == NULL) { + if (msg == nullptr) { msg = MostCommonMessage::Get(); socket->reset_parsing_context(msg); } @@ -155,7 +155,7 @@ void ProcessCouchbaseResponse(InputMessageBase* msg_base) { static_cast(msg_base)); const bthread_id_t cid = msg->pi.id_wait; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -171,7 +171,7 @@ void ProcessCouchbaseResponse(InputMessageBase* msg_base) { span->set_start_parse_us(start_parse_us); } const int saved_error = cntl->ErrorCode(); - if (cntl->response() == NULL) { + if (cntl->response() == nullptr) { cntl->SetFailed(ERESPONSE, "response is NULL!"); } else if (cntl->response()->GetDescriptor() != CouchbaseOperations::CouchbaseResponse::descriptor()) { @@ -195,7 +195,7 @@ void ProcessCouchbaseResponse(InputMessageBase* msg_base) { void SerializeCouchbaseRequest(butil::IOBuf* buf, Controller* cntl, const google::protobuf::Message* request) { - if (request == NULL) { + if (request == nullptr) { return cntl->SetFailed(EREQUEST, "request is NULL"); } if (request->GetDescriptor() != diff --git a/src/brpc/policy/crc32c_checksum.cpp b/src/brpc/policy/crc32c_checksum.cpp index 7a3b8ef9d7..8af7fbe2ff 100644 --- a/src/brpc/policy/crc32c_checksum.cpp +++ b/src/brpc/policy/crc32c_checksum.cpp @@ -41,10 +41,10 @@ uint32_t ExtendCrc32c(uint32_t crc, const butil::IOBuf& buf) { } // Computes the crc32c over `in.buf', and over `in.attachment' as well when -// the caller opted in (ChecksumIn::attachment != NULL). +// the caller opted in (ChecksumIn::attachment != nullptr). uint32_t ComputeCrc32c(const ChecksumIn& in) { uint32_t crc = ExtendCrc32c(0, *in.buf); - if (in.attachment != NULL) { + if (in.attachment != nullptr) { crc = ExtendCrc32c(crc, *in.attachment); } return crc; diff --git a/src/brpc/policy/dh.cpp b/src/brpc/policy/dh.cpp index e56cf19eb7..cb66c9c2cb 100644 --- a/src/brpc/policy/dh.cpp +++ b/src/brpc/policy/dh.cpp @@ -25,9 +25,9 @@ namespace brpc { namespace policy { void DHWrapper::clear() { - if (_pdh != NULL) { + if (_pdh != nullptr) { DH_free(_pdh); - _pdh = NULL; + _pdh = nullptr; } } @@ -37,8 +37,8 @@ int DHWrapper::initialize(bool ensure_128bytes_public_key) { return -1; } if (ensure_128bytes_public_key) { - const BIGNUM* pub_key = NULL; - DH_get0_key(_pdh, &pub_key, NULL); + const BIGNUM* pub_key = nullptr; + DH_get0_key(_pdh, &pub_key, nullptr); int key_size = BN_num_bytes(pub_key); if (key_size != 128) { RPC_VLOG << "regenerate 128B key, current=" << key_size; @@ -52,8 +52,8 @@ int DHWrapper::initialize(bool ensure_128bytes_public_key) { } int DHWrapper::copy_public_key(char* pkey, int* pkey_size) const { - const BIGNUM* pub_key = NULL; - DH_get0_key(_pdh, &pub_key, NULL); + const BIGNUM* pub_key = nullptr; + DH_get0_key(_pdh, &pub_key, nullptr); // copy public key to bytes. // sometimes, the key_size is 127, seems ok. int key_size = BN_num_bytes(pub_key); @@ -75,7 +75,7 @@ int DHWrapper::copy_public_key(char* pkey, int* pkey_size) const { int DHWrapper::copy_shared_key(const void* ppkey, int ppkey_size, void* skey, int* skey_size) const { BIGNUM* ppk = BN_bin2bn((const unsigned char*)ppkey, ppkey_size, 0); - if (ppk == NULL) { + if (ppk == nullptr) { LOG(ERROR) << "Fail to BN_bin2bn"; return -1; } @@ -91,13 +91,13 @@ int DHWrapper::copy_shared_key(const void* ppkey, int ppkey_size, } int DHWrapper::do_initialize() { - BIGNUM* p = get_rfc2409_prime_1024(NULL); + BIGNUM* p = get_rfc2409_prime_1024(nullptr); if (!p) { return -1; } // See RFC 2409, Section 6 "Oakley Groups" // for the reason why 2 is used as generator. - BIGNUM* g = NULL; + BIGNUM* g = nullptr; BN_dec2bn(&g, "2"); if (!g) { BN_free(p); @@ -109,7 +109,7 @@ int DHWrapper::do_initialize() { BN_free(g); return -1; } - DH_set0_pqg(_pdh, p, NULL, g); + DH_set0_pqg(_pdh, p, nullptr, g); // Generate private and public key if (!DH_generate_key(_pdh)) { diff --git a/src/brpc/policy/dh.h b/src/brpc/policy/dh.h index 8b888ba304..bac804871a 100644 --- a/src/brpc/policy/dh.h +++ b/src/brpc/policy/dh.h @@ -28,7 +28,7 @@ namespace policy { // Diffie-Hellman key exchange class DHWrapper { public: - DHWrapper() : _pdh(NULL) {} + DHWrapper() : _pdh(nullptr) {} ~DHWrapper() { clear(); } // initialize dh, generate the public and private key. diff --git a/src/brpc/policy/discovery_naming_service.cpp b/src/brpc/policy/discovery_naming_service.cpp index b935bcfc49..2dca269eb4 100644 --- a/src/brpc/policy/discovery_naming_service.cpp +++ b/src/brpc/policy/discovery_naming_service.cpp @@ -47,7 +47,7 @@ DEFINE_int32(discovery_reregister_threshold, 3, "The renew error threshold beyon " which Register would be called again"); static pthread_once_t s_init_discovery_channel_once = PTHREAD_ONCE_INIT; -static Channel* s_discovery_channel = NULL; +static Channel* s_discovery_channel = nullptr; static int ListDiscoveryNodes(const char* discovery_api_addr, std::string* servers) { Channel api_channel; @@ -61,7 +61,7 @@ static int ListDiscoveryNodes(const char* discovery_api_addr, std::string* serve } Controller cntl; cntl.http_request().uri() = discovery_api_addr; - api_channel.CallMethod(NULL, &cntl, NULL, NULL, NULL); + api_channel.CallMethod(nullptr, &cntl, nullptr, nullptr, nullptr); if (cntl.Failed()) { LOG(FATAL) << "Fail to access " << cntl.http_request().uri() << ": " << cntl.ErrorText(); @@ -143,7 +143,7 @@ DiscoveryClient::DiscoveryClient() DiscoveryClient::~DiscoveryClient() { if (_registered.load(butil::memory_order_acquire)) { bthread_stop(_th); - bthread_join(_th, NULL); + bthread_join(_th, nullptr); DoCancel(); } } @@ -193,7 +193,7 @@ int DiscoveryClient::DoRenew() const { << "®ion=" << _params.region << "&zone=" << _params.zone; os.move_to(cntl.request_attachment()); - chan.CallMethod(NULL, &cntl, NULL, NULL, NULL); + chan.CallMethod(nullptr, &cntl, nullptr, nullptr, nullptr); if (cntl.Failed()) { LOG(ERROR) << "Fail to post /discovery/renew: " << cntl.ErrorText(); return -1; @@ -214,7 +214,7 @@ void* DiscoveryClient::PeriodicRenew(void* arg) { butil::fast_rand_less_than(FLAGS_discovery_renew_interval_s / 2); if (bthread_usleep(init_sleep_s * 1000000) != 0) { if (errno == ESTOP) { - return NULL; + return nullptr; } } @@ -237,7 +237,7 @@ void* DiscoveryClient::PeriodicRenew(void* arg) { consecutive_renew_error = 0; bthread_usleep(FLAGS_discovery_renew_interval_s * 1000000); } - return NULL; + return nullptr; } int DiscoveryClient::Register(const DiscoveryRegisterParam& params) { @@ -253,7 +253,7 @@ int DiscoveryClient::Register(const DiscoveryRegisterParam& params) { if (DoRegister() != 0) { return -1; } - if (bthread_start_background(&_th, NULL, PeriodicRenew, this) != 0) { + if (bthread_start_background(&_th, nullptr, PeriodicRenew, this) != 0) { LOG(ERROR) << "Fail to start background PeriodicRenew"; return -1; } @@ -262,7 +262,7 @@ int DiscoveryClient::Register(const DiscoveryRegisterParam& params) { int DiscoveryClient::DoRegister() { Channel* chan = GetOrNewDiscoveryChannel(); - if (NULL == chan) { + if (nullptr == chan) { LOG(ERROR) << "Fail to create discovery channel"; return -1; } @@ -289,7 +289,7 @@ int DiscoveryClient::DoRegister() { << "&version=" << _params.version << "&metadata=" << _params.metadata; os.move_to(cntl.request_attachment()); - chan->CallMethod(NULL, &cntl, NULL, NULL, NULL); + chan->CallMethod(nullptr, &cntl, nullptr, nullptr, nullptr); if (cntl.Failed()) { LOG(ERROR) << "Fail to register " << _params.appid << ": " << cntl.ErrorText(); return -1; @@ -327,7 +327,7 @@ int DiscoveryClient::DoCancel() const { << "®ion=" << _params.region << "&zone=" << _params.zone; os.move_to(cntl.request_attachment()); - chan.CallMethod(NULL, &cntl, NULL, NULL, NULL); + chan.CallMethod(nullptr, &cntl, nullptr, nullptr, nullptr); if (cntl.Failed()) { LOG(ERROR) << "Fail to post /discovery/cancel: " << cntl.ErrorText(); return -1; @@ -345,14 +345,14 @@ int DiscoveryClient::DoCancel() const { int DiscoveryNamingService::GetServers(const char* service_name, std::vector* servers) { - if (service_name == NULL || *service_name == '\0' || + if (service_name == nullptr || *service_name == '\0' || FLAGS_discovery_env.empty() || FLAGS_discovery_status.empty()) { LOG_ONCE(ERROR) << "Invalid parameters"; return -1; } Channel* chan = GetOrNewDiscoveryChannel(); - if (NULL == chan) { + if (nullptr == chan) { LOG(ERROR) << "Fail to create discovery channel"; return -1; } @@ -366,7 +366,7 @@ int DiscoveryNamingService::GetServers(const char* service_name, uri_str.append(FLAGS_discovery_zone); } cntl.http_request().uri() = uri_str; - chan->CallMethod(NULL, &cntl, NULL, NULL, NULL); + chan->CallMethod(nullptr, &cntl, nullptr, nullptr, nullptr); if (cntl.Failed()) { LOG(ERROR) << "Fail to get /discovery/fetchs: " << cntl.ErrorText(); return -1; diff --git a/src/brpc/policy/domain_naming_service.cpp b/src/brpc/policy/domain_naming_service.cpp index d93d799051..8c2632cd6e 100644 --- a/src/brpc/policy/domain_naming_service.cpp +++ b/src/brpc/policy/domain_naming_service.cpp @@ -57,7 +57,7 @@ int DomainNamingService::GetServers(const char* dns_name, int port = _default_port; if (dns_name[i] == ':') { ++i; - char* end = NULL; + char* end = nullptr; port = strtol(dns_name + i, &end, 10); if (end == dns_name + i) { LOG(ERROR) << "No port after colon in `" << dns_name << '\''; @@ -89,7 +89,7 @@ int DomainNamingService::GetServers(const char* dns_name, snprintf(portBuf, arraysize(portBuf), "%d", port); auto ret = getaddrinfo(buf, portBuf, &hints, &addrResult); if (!ret) { - for(auto rp = addrResult; rp != NULL; rp = rp->ai_next) { + for(auto rp = addrResult; rp != nullptr; rp = rp->ai_next) { butil::EndPoint point; auto ret = butil::sockaddr2endpoint((struct sockaddr_storage*)rp->ai_addr, rp->ai_addrlen, &point); if(!ret) { @@ -112,21 +112,21 @@ int DomainNamingService::GetServers(const char* dns_name, // returned hostent is TLS. Check following link for the ref: // https://lists.apple.com/archives/darwin-dev/2006/May/msg00008.html struct hostent* result = gethostbyname(buf); - if (result == NULL) { + if (result == nullptr) { LOG(WARNING) << "result of gethostbyname is NULL"; return -1; } #else - if (_aux_buf == NULL) { + if (_aux_buf == nullptr) { _aux_buf_len = 1024; _aux_buf.reset(new char[_aux_buf_len]); } int ret = 0; int error = 0; struct hostent ent; - struct hostent* result = NULL; + struct hostent* result = nullptr; do { - result = NULL; + result = nullptr; error = 0; ret = gethostbyname_r(buf, &ent, _aux_buf.get(), _aux_buf_len, &result, &error); @@ -144,7 +144,7 @@ int DomainNamingService::GetServers(const char* dns_name, << "' herror=`" << hstrerror(error) << '\''; return -1; } - if (result == NULL) { + if (result == nullptr) { LOG(WARNING) << "result of gethostbyname_r is NULL"; return -1; } @@ -153,7 +153,7 @@ int DomainNamingService::GetServers(const char* dns_name, //TODO add protocols other than IPv4 supports butil::EndPoint point; point.port = port; - for (int i = 0; result->h_addr_list[i] != NULL; ++i) { + for (int i = 0; result->h_addr_list[i] != nullptr; ++i) { if (result->h_addrtype == AF_INET) { // Only fetch IPv4 addresses bcopy(result->h_addr_list[i], &point.ip, result->h_length); diff --git a/src/brpc/policy/dynpart_load_balancer.cpp b/src/brpc/policy/dynpart_load_balancer.cpp index ad3cbbcbff..24a2570423 100644 --- a/src/brpc/policy/dynpart_load_balancer.cpp +++ b/src/brpc/policy/dynpart_load_balancer.cpp @@ -155,7 +155,7 @@ int DynPartLoadBalancer::SelectServer(const SelectIn& in, SelectOut* out) { } DynPartLoadBalancer* DynPartLoadBalancer::New(const butil::StringPiece&) const { - return new (std::nothrow) DynPartLoadBalancer; + return new DynPartLoadBalancer; } void DynPartLoadBalancer::Destroy() { diff --git a/src/brpc/policy/esp_protocol.cpp b/src/brpc/policy/esp_protocol.cpp index ee8464b85e..1341a998f8 100644 --- a/src/brpc/policy/esp_protocol.cpp +++ b/src/brpc/policy/esp_protocol.cpp @@ -67,14 +67,14 @@ void SerializeEspRequest( Controller* cntl, const google::protobuf::Message* req_base) { - if (req_base == NULL) { + if (req_base == nullptr) { return cntl->SetFailed(EREQUEST, "request is NULL"); } ControllerPrivateAccessor accessor(cntl); if (req_base->GetDescriptor() != EspMessage::descriptor()) { return cntl->SetFailed(EINVAL, "Type of request must be EspMessage"); } - if (cntl->response() != NULL && + if (cntl->response() != nullptr && cntl->response()->GetDescriptor() != EspMessage::descriptor()) { return cntl->SetFailed(EINVAL, "Type of response must be EspMessage"); } @@ -105,7 +105,7 @@ void PackEspRequest(butil::IOBuf* packet_buf, span->set_request_size(request.length()); } - if (auth != NULL) { + if (auth != nullptr) { std::string auth_str; auth->GenerateCredential(&auth_str); //means first request in this connect, need to special head @@ -121,7 +121,7 @@ void ProcessEspResponse(InputMessageBase* msg_base) { // Fetch correlation id that we saved before in `PackEspRequest' const CallId cid = { static_cast(msg->socket()->correlation_id()) }; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -140,7 +140,7 @@ void ProcessEspResponse(InputMessageBase* msg_base) { EspMessage* response = (EspMessage*)cntl->response(); const int saved_error = cntl->ErrorCode(); - if (response != NULL) { + if (response != nullptr) { msg->meta.copy_to(&response->head, sizeof(EspHead)); msg->payload.swap(response->body); if (response->head.msg != 0) { diff --git a/src/brpc/policy/file_naming_service.cpp b/src/brpc/policy/file_naming_service.cpp index df49673f0f..4ecdd89632 100644 --- a/src/brpc/policy/file_naming_service.cpp +++ b/src/brpc/policy/file_naming_service.cpp @@ -38,7 +38,7 @@ bool SplitIntoServerAndTag(const butil::StringPiece& line, return false; } const char* const addr_start = line.data() + i; - const char* tag_start = NULL; + const char* tag_start = nullptr; ssize_t tag_size = 0; for (; i < line.size() && !isspace(line[i]); ++i) {} if (server_addr) { @@ -69,7 +69,7 @@ bool SplitIntoServerAndTag(const butil::StringPiece& line, int FileNamingService::GetServers(const char *service_name, std::vector* servers) { servers->clear(); - char* line = NULL; + char* line = nullptr; size_t line_len = 0; ssize_t nr = 0; // Sort/unique the inserted vector is faster, but may have a different order diff --git a/src/brpc/policy/giano_authenticator.cpp b/src/brpc/policy/giano_authenticator.cpp index d74f1063c9..7961f0fa76 100644 --- a/src/brpc/policy/giano_authenticator.cpp +++ b/src/brpc/policy/giano_authenticator.cpp @@ -27,29 +27,27 @@ namespace policy { GianoAuthenticator::GianoAuthenticator(const baas::CredentialGenerator* gen, const baas::CredentialVerifier* ver) { if (gen) { - _generator = new(std::nothrow) baas::CredentialGenerator(*gen); - CHECK(_generator); + _generator = new baas::CredentialGenerator(*gen); } else { - _generator = NULL; + _generator = nullptr; } if (ver) { - _verifier = new(std::nothrow) baas::CredentialVerifier(*ver); - CHECK(_verifier); + _verifier = new baas::CredentialVerifier(*ver); } else { - _verifier = NULL; + _verifier = nullptr; } } GianoAuthenticator::~GianoAuthenticator() { delete _generator; - _generator = NULL; + _generator = nullptr; delete _verifier; - _verifier = NULL; + _verifier = nullptr; } int GianoAuthenticator::GenerateCredential(std::string* auth_str) const { - if (NULL == _generator) { + if (nullptr == _generator) { LOG(FATAL) << "CredentialGenerator is NULL"; return -1; } @@ -62,7 +60,7 @@ int GianoAuthenticator::VerifyCredential( const std::string& auth_str, const butil::EndPoint& client_addr, AuthContext* out_ctx) const { - if (NULL == _verifier) { + if (nullptr == _verifier) { LOG(FATAL) << "CredentialVerifier is NULL"; return -1; } @@ -75,7 +73,7 @@ int GianoAuthenticator::VerifyCredential( << baas::sdk::GetReturnCodeMessage(rc); return -1; } - if (out_ctx != NULL) { + if (out_ctx != nullptr) { out_ctx->set_user(ctx.user()); out_ctx->set_group(ctx.group()); out_ctx->set_roles(ctx.roles()); diff --git a/src/brpc/policy/giano_authenticator.h b/src/brpc/policy/giano_authenticator.h index d2b9acbd2f..362497789d 100644 --- a/src/brpc/policy/giano_authenticator.h +++ b/src/brpc/policy/giano_authenticator.h @@ -29,7 +29,7 @@ namespace policy { class GianoAuthenticator: public Authenticator { public: - // Either `gen' or `ver' can be NULL (but not at the same time), + // Either `gen' or `ver' can be nullptr (but not at the same time), // in which case it can only verify/generate credential data explicit GianoAuthenticator(const baas::CredentialGenerator* gen, const baas::CredentialVerifier* ver); diff --git a/src/brpc/policy/gzip_compress.cpp b/src/brpc/policy/gzip_compress.cpp index e8c77a5563..73a6f02f42 100644 --- a/src/brpc/policy/gzip_compress.cpp +++ b/src/brpc/policy/gzip_compress.cpp @@ -64,7 +64,7 @@ static bool Compress(const google::protobuf::Message& msg, butil::IOBuf* buf, LOG(WARNING) << "Fail to serialize input message=" << msg.GetDescriptor()->full_name() << ", format=" << Format2CStr(format) << " : " - << (NULL == gzip.ZlibErrorMessage() ? "" : gzip.ZlibErrorMessage()); + << (nullptr == gzip.ZlibErrorMessage() ? "" : gzip.ZlibErrorMessage()); } return ok && gzip.Close(); } @@ -83,7 +83,7 @@ static bool Decompress(const butil::IOBuf& data, google::protobuf::Message* msg, LOG(WARNING) << "Fail to deserialize input message=" << msg->GetDescriptor()->full_name() << ", format=" << Format2CStr(format) << " : " - << (NULL == gzip.ZlibErrorMessage() ? "" : gzip.ZlibErrorMessage()); + << (nullptr == gzip.ZlibErrorMessage() ? "" : gzip.ZlibErrorMessage()); } return ok; } @@ -105,9 +105,9 @@ bool GzipCompress(const butil::IOBuf& msg, butil::IOBuf* buf, } google::protobuf::io::GzipOutputStream out(&wrapper, gzip_opt); butil::IOBufAsZeroCopyInputStream in(msg); - const void* data_in = NULL; + const void* data_in = nullptr; int size_in = 0; - void* data_out = NULL; + void* data_out = nullptr; int size_out = 0; while (1) { if (size_out == 0 && !out.Next(&data_out, &size_out)) { @@ -141,9 +141,9 @@ inline bool GzipDecompressBase( butil::IOBufAsZeroCopyInputStream wrapper(data); google::protobuf::io::GzipInputStream in(&wrapper, format); butil::IOBufAsZeroCopyOutputStream out(msg); - const void* data_in = NULL; + const void* data_in = nullptr; int size_in = 0; - void* data_out = NULL; + void* data_out = nullptr; int size_out = 0; while (1) { if (size_out == 0 && !out.Next(&data_out, &size_out)) { diff --git a/src/brpc/policy/http2_rpc_protocol.cpp b/src/brpc/policy/http2_rpc_protocol.cpp index eb0e35317d..af9ed0b151 100644 --- a/src/brpc/policy/http2_rpc_protocol.cpp +++ b/src/brpc/policy/http2_rpc_protocol.cpp @@ -318,7 +318,7 @@ void InitFrameHandlers() { inline H2Context::FrameHandler FindFrameHandler(H2FrameType type) { pthread_once(&s_frame_handlers_init_once, InitFrameHandlers); if (type < 0 || type > H2_FRAME_TYPE_MAX) { - return NULL; + return nullptr; } return s_frame_handlers[type]; } @@ -382,11 +382,11 @@ size_t H2Context::VolatilePendingStreamSize() const { } H2StreamContext* H2Context::RemoveStreamAndDeferWU(int stream_id) { - H2StreamContext* sctx = NULL; + H2StreamContext* sctx = nullptr; { std::unique_lock mu(_stream_mutex); if (!_pending_streams.erase(stream_id, &sctx)) { - return NULL; + return nullptr; } CHECK_GE(_pending_data_size, sctx->_pending_data.size()); _pending_data_size -= sctx->_pending_data.size(); @@ -436,7 +436,7 @@ H2StreamContext* H2Context::FindStream(int stream_id) { if (psctx) { return *psctx; } - return NULL; + return nullptr; } int H2Context::TryToInsertStream(int stream_id, H2StreamContext* ctx) { @@ -445,7 +445,7 @@ int H2Context::TryToInsertStream(int stream_id, H2StreamContext* ctx) { return 1; } H2StreamContext*& sctx = _pending_streams[stream_id]; - if (sctx == NULL) { + if (sctx == nullptr) { // Synchronize creation with SETTINGS_INITIAL_WINDOW_SIZE updates. ctx->_remote_window_left.store(_remote_settings.stream_window_size, butil::memory_order_relaxed); @@ -481,7 +481,7 @@ ParseResult H2Context::ConsumeFrameHead( return MakeParseError(PARSE_ERROR_ABSOLUTELY_WRONG); } frame_head->stream_id = static_cast(stream_id); - return MakeMessage(NULL); + return MakeMessage(nullptr); } ParseResult H2Context::Consume( @@ -509,7 +509,7 @@ ParseResult H2Context::Consume( } else { _conn_state = H2_CONNECTION_READY; } - return MakeMessage(NULL); + return MakeMessage(nullptr); } else if (_conn_state == H2_CONNECTION_READY) { H2FrameHead frame_head; ParseResult res = ConsumeFrameHead(it, &frame_head); @@ -517,7 +517,7 @@ ParseResult H2Context::Consume( return res; } H2Context::FrameHandler handler = FindFrameHandler(frame_head.type); - if (handler == NULL) { + if (handler == nullptr) { LOG(ERROR) << "Invalid frame type=" << (int)frame_head.type; return MakeParseError(PARSE_ERROR_ABSOLUTELY_WRONG); } @@ -538,14 +538,14 @@ ParseResult H2Context::Consume( if (sctx) { if (is_server_side()) { delete sctx; - return MakeMessage(NULL); + return MakeMessage(nullptr); } else { sctx->header().set_status_code( H2ErrorToStatusCode(h2_res.error())); return MakeMessage(sctx); } } - return MakeMessage(NULL); + return MakeMessage(nullptr); } else { // send GOAWAY char goawaybuf[FRAME_HEAD_SIZE + 8]; SerializeFrameHead(goawaybuf, 8, H2_FRAME_GOAWAY, 0, 0); @@ -555,7 +555,7 @@ ParseResult H2Context::Consume( LOG(WARNING) << "Fail to send GOAWAY to " << *_socket; return MakeParseError(PARSE_ERROR_ABSOLUTELY_WRONG); } - return MakeMessage(NULL); + return MakeMessage(nullptr); } } else { return MakeParseError(PARSE_ERROR_NO_RESOURCE); @@ -594,7 +594,7 @@ H2ParseResult H2Context::OnHeaders( return MakeH2Error(H2_FRAME_SIZE_ERROR); } frag_size -= pad_length; - H2StreamContext* sctx = NULL; + H2StreamContext* sctx = nullptr; if (is_server_side() && frame_head.stream_id > _last_received_stream_id) { // new stream if ((frame_head.stream_id & 1) == 0) { @@ -616,14 +616,14 @@ H2ParseResult H2Context::OnHeaders( } } else { sctx = FindStream(frame_head.stream_id); - if (sctx == NULL) { + if (sctx == nullptr) { if (is_client_side()) { RPC_VLOG << "Fail to find stream_id=" << frame_head.stream_id; // Ignore the message without closing the socket. H2StreamContext tmp_sctx(false); tmp_sctx.Init(this, frame_head.stream_id); tmp_sctx.OnHeaders(it, frame_head, frag_size, pad_length); - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } else { LOG(ERROR) << "Fail to find stream_id=" << frame_head.stream_id; return MakeH2Error(H2_PROTOCOL_ERROR); @@ -662,27 +662,27 @@ H2ParseResult H2StreamContext::OnHeaders( if (frame_head.flags & H2_FLAGS_END_STREAM) { return OnEndStream(); } - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } else { if (frame_head.flags & H2_FLAGS_END_STREAM) { // Delay calling OnEndStream() in OnContinuation() _stream_ended = true; } - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } } H2ParseResult H2Context::OnContinuation( butil::IOBufBytesIterator& it, const H2FrameHead& frame_head) { H2StreamContext* sctx = FindStream(frame_head.stream_id); - if (sctx == NULL) { + if (sctx == nullptr) { if (is_client_side()) { RPC_VLOG << "Fail to find stream_id=" << frame_head.stream_id; // Ignore the message without closing the socket. H2StreamContext tmp_sctx(false); tmp_sctx.Init(this, frame_head.stream_id); tmp_sctx.OnContinuation(it, frame_head); - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } else { LOG(ERROR) << "Fail to find stream_id=" << frame_head.stream_id; return MakeH2Error(H2_PROTOCOL_ERROR); @@ -713,7 +713,7 @@ H2ParseResult H2StreamContext::OnContinuation( return OnEndStream(); } } - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } H2ParseResult H2Context::OnData( @@ -734,7 +734,7 @@ H2ParseResult H2Context::OnData( } frag_size -= pad_length; H2StreamContext* sctx = FindStream(frame_head.stream_id); - if (sctx == NULL) { + if (sctx == nullptr) { // If a DATA frame is received whose stream is not in "open" or "half-closed (local)" state, // the recipient MUST respond with a stream error (Section 5.4.2) of type STREAM_CLOSED. // Ignore the message without closing the socket. @@ -802,7 +802,7 @@ H2ParseResult H2StreamContext::OnData( if (frame_head.flags & H2_FLAGS_END_STREAM) { return OnEndStream(); } - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } H2ParseResult H2Context::OnResetStream( @@ -813,9 +813,9 @@ H2ParseResult H2Context::OnResetStream( } const H2Error h2_error = static_cast(LoadUint32(it)); H2StreamContext* sctx = FindStream(frame_head.stream_id); - if (sctx == NULL) { + if (sctx == nullptr) { RPC_VLOG << "Fail to find stream_id=" << frame_head.stream_id; - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } return sctx->OnResetStream(h2_error, frame_head); } @@ -835,7 +835,7 @@ H2ParseResult H2StreamContext::OnResetStream( } #endif H2StreamContext* sctx = _conn_ctx->RemoveStreamAndDeferWU(stream_id()); - if (sctx == NULL) { + if (sctx == nullptr) { LOG(ERROR) << "Fail to find stream_id=" << stream_id(); return MakeH2Error(H2_PROTOCOL_ERROR); } @@ -845,7 +845,7 @@ H2ParseResult H2StreamContext::OnResetStream( } else { // No need to process the request. delete sctx; - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } } @@ -862,9 +862,9 @@ H2ParseResult H2StreamContext::OnEndStream() { } #endif H2StreamContext* sctx = _conn_ctx->RemoveStreamAndDeferWU(stream_id()); - if (sctx == NULL) { + if (sctx == nullptr) { RPC_VLOG << "Fail to find stream_id=" << stream_id(); - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } CHECK_EQ(sctx, this); @@ -890,7 +890,7 @@ H2ParseResult H2Context::OnSettings( return MakeH2Error(H2_PROTOCOL_ERROR); } _local_settings = _unack_local_settings; - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } int64_t window_diff = 0; { @@ -926,7 +926,7 @@ H2ParseResult H2Context::OnSettings( if (window_diff > 0 && !FlushPendingData(0)) { return MakeH2Error(H2_PROTOCOL_ERROR); } - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } H2ParseResult H2Context::OnPriority( @@ -952,7 +952,7 @@ H2ParseResult H2Context::OnPing( return MakeH2Error(H2_PROTOCOL_ERROR); } if (frame_head.flags & H2_FLAGS_ACK) { - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } char pongbuf[FRAME_HEAD_SIZE + 8]; @@ -962,12 +962,12 @@ H2ParseResult H2Context::OnPing( LOG(WARNING) << "Fail to send ack of PING to " << *_socket; return MakeH2Error(H2_PROTOCOL_ERROR); } - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } static void* ProcessHttpResponseWrapper(void* void_arg) { ProcessHttpResponse(static_cast(void_arg)); - return NULL; + return nullptr; } H2ParseResult H2Context::OnGoAway( @@ -999,7 +999,7 @@ H2ParseResult H2Context::OnGoAway( std::vector goaway_streams; RemoveGoAwayStreams(last_stream_id, &goaway_streams); if (goaway_streams.empty()) { - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } for (size_t i = 0; i < goaway_streams.size(); ++i) { H2StreamContext* sctx = goaway_streams[i]; @@ -1017,7 +1017,7 @@ H2ParseResult H2Context::OnGoAway( return MakeH2Message(goaway_streams[0]); } else { // server serves requests on-demand, ignoring GOAWAY is OK. - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } } @@ -1043,7 +1043,7 @@ H2ParseResult H2Context::OnWindowUpdate( if (!FlushPendingData(0)) { return MakeH2Error(H2_PROTOCOL_ERROR); } - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } else { { std::unique_lock mu(_stream_mutex); @@ -1062,7 +1062,7 @@ H2ParseResult H2Context::OnWindowUpdate( if (!FlushPendingData(frame_head.stream_id)) { return MakeH2Error(H2_PROTOCOL_ERROR); } - return MakeH2Message(NULL); + return MakeH2Message(nullptr); } } @@ -1147,7 +1147,7 @@ ParseResult ParseH2Message(butil::IOBuf *source, Socket *socket, bvar::ScopedTimer > tm(g_parse_time); #endif H2Context* ctx = static_cast(socket->parsing_context()); - if (ctx == NULL) { + if (ctx == nullptr) { if (read_eof || source->empty()) { return MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA); } @@ -1167,7 +1167,7 @@ ParseResult ParseH2Message(butil::IOBuf *source, Socket *socket, ParseResult res = ctx->Consume(it, socket); if (res.is_ok()) { last_bytes_left = it.bytes_left(); - if (res.message() == NULL) { + if (res.message() == nullptr) { // no message to process, continue parsing. continue; } @@ -1190,7 +1190,7 @@ inline void H2Context::ClearAbandonedStreams() { _abandoned_streams.pop_back(); mu.unlock(); H2StreamContext* sctx = RemoveStreamAndDeferWU(stream_id); - if (sctx != NULL) { + if (sctx != nullptr) { delete sctx; } mu.lock(); @@ -1199,7 +1199,7 @@ inline void H2Context::ClearAbandonedStreams() { H2StreamContext::H2StreamContext(bool read_body_progressively) : HttpContext(read_body_progressively) - , _conn_ctx(NULL) + , _conn_ctx(nullptr) #if defined(BRPC_H2_STREAM_STATE) , _state(H2_STREAM_IDLE) #endif @@ -1283,7 +1283,7 @@ int H2StreamContext::ConsumeHeaders(butil::IOBufBytesIterator& it) { h.uri().set_scheme(pair.value); } else if (strcmp(name + 2, /*:s*/"tatus") == 0) { matched = true; - char* endptr = NULL; + char* endptr = nullptr; const int sc = strtol(pair.value.c_str(), &endptr, 10); if (*endptr != '\0') { LOG(ERROR) << "Invalid status=" << pair.value; @@ -1308,7 +1308,7 @@ int H2StreamContext::ConsumeHeaders(butil::IOBufBytesIterator& it) { if (FLAGS_http_verbose) { butil::IOBufBuilder* vs = this->_vmsgbuilder.get(); - if (vs == NULL) { + if (vs == nullptr) { vs = new butil::IOBufBuilder; this->_vmsgbuilder.reset(vs); if (_conn_ctx->is_server_side()) { @@ -1637,7 +1637,7 @@ void H2UnsentRequest::DestroyStreamUserData(SocketUniquePtr& sending_sock, if (sending_sock != nullptr && error_code != 0) { CHECK_EQ(cntl, _cntl); std::unique_lock mu(_mutex); - _cntl = NULL; + _cntl = nullptr; if (_stream_id != 0) { H2Context* ctx = static_cast(sending_sock->parsing_context()); ctx->ClearPendingData(_stream_id); @@ -1658,15 +1658,15 @@ H2UnsentRequest::AppendAndDestroySelf(butil::IOBuf* out, Socket* socket) { bvar::ScopedTimer > tm(g_append_request_time); #endif RemoveRefOnQuit deref_self(this); - if (socket == NULL) { + if (socket == nullptr) { return butil::Status::OK(); } H2Context* ctx = static_cast(socket->parsing_context()); // Create a http2 stream and store correlation_id in. - if (ctx == NULL) { + if (ctx == nullptr) { CHECK(socket->CreatedByConnect()); - ctx = new H2Context(socket, NULL); + ctx = new H2Context(socket, nullptr); if (ctx->Init() != 0) { delete ctx; return butil::Status(EINTERNAL, "Fail to init H2Context"); @@ -1687,7 +1687,7 @@ H2UnsentRequest::AppendAndDestroySelf(butil::IOBuf* out, Socket* socket) { // Although the critical section looks huge, it should rarely be contended // since timeout of RPC is much larger than the delay of sending. std::unique_lock mu(_mutex); - if (_cntl == NULL) { + if (_cntl == nullptr) { return butil::Status(ECANCELED, "The RPC was already failed"); } @@ -1754,7 +1754,7 @@ size_t H2UnsentRequest::EstimatedByteSize() { sz += _list[i].name.size() + _list[i].value.size() + 1; } std::unique_lock mu(_mutex); - if (_cntl == NULL) { + if (_cntl == nullptr) { return 0; } if (_cntl->has_http_request()) { @@ -1774,7 +1774,7 @@ void H2UnsentRequest::Print(std::ostream& os) const { os << "> " << _list[i].name << " = " << _list[i].value << '\n'; } std::unique_lock mu(_mutex); - if (_cntl == NULL) { + if (_cntl == nullptr) { return; } if (_cntl->has_http_request()) { @@ -1846,7 +1846,7 @@ H2UnsentResponse::AppendAndDestroySelf(butil::IOBuf* out, Socket* socket) { bvar::ScopedTimer > tm(g_append_response_time); #endif DestroyingPtr destroy_self(this); - if (socket == NULL) { + if (socket == nullptr) { return butil::Status::OK(); } H2Context* ctx = static_cast(socket->parsing_context()); @@ -1946,7 +1946,7 @@ void PackH2Request(butil::IOBuf*, ControllerPrivateAccessor accessor(cntl); HttpHeader* header = &cntl->http_request(); - if (auth != NULL && header->GetHeader("Authorization") == NULL) { + if (auth != nullptr && header->GetHeader("Authorization") == nullptr) { std::string auth_data; if (auth->GenerateCredential(&auth_data) != 0) { return cntl->SetFailed(EREQUEST, "Fail to GenerateCredential"); @@ -1975,13 +1975,13 @@ StreamUserData* H2GlobalStreamCreator::OnCreatingStream( SocketUniquePtr* inout, Controller* cntl) { if ((*inout)->GetAgentSocket(inout, IsH2SocketValid) != 0) { cntl->SetFailed(EINTERNAL, "Fail to create agent socket"); - return NULL; + return nullptr; } H2UnsentRequest* h2_req = H2UnsentRequest::New(cntl); if (!h2_req) { cntl->SetFailed(ENOMEM, "Fail to create H2UnsentRequest"); - return NULL; + return nullptr; } return h2_req; } diff --git a/src/brpc/policy/http2_rpc_protocol.h b/src/brpc/policy/http2_rpc_protocol.h index 27055ae9a5..022f978c85 100644 --- a/src/brpc/policy/http2_rpc_protocol.h +++ b/src/brpc/policy/http2_rpc_protocol.h @@ -38,7 +38,7 @@ class H2StreamContext; class H2ParseResult { public: explicit H2ParseResult(H2Error err, int stream_id) - : _msg(NULL), _err(err), _stream_id(stream_id) {} + : _msg(nullptr), _err(err), _stream_id(stream_id) {} explicit H2ParseResult(H2StreamContext* msg) : _msg(msg), _err(H2_NO_ERROR), _stream_id(0) {} @@ -48,7 +48,7 @@ class H2ParseResult { bool is_ok() const { return error() == H2_NO_ERROR; } int stream_id() const { return _stream_id; } - // definitely NULL when result is failed. + // definitely nullptr when result is failed. H2StreamContext* message() const { return _msg; } private: @@ -318,7 +318,7 @@ class H2Context : public Destroyable, public Describable { butil::IOBufBytesIterator&, const H2FrameHead&); // main_socket: the socket owns this object as parsing_context - // server: NULL means client-side + // server: nullptr means client-side H2Context(Socket* main_socket, const Server* server); ~H2Context() override; // Must be called before usage. diff --git a/src/brpc/policy/http_rpc_protocol.cpp b/src/brpc/policy/http_rpc_protocol.cpp index 8cbe06980f..ca1d30d1fa 100644 --- a/src/brpc/policy/http_rpc_protocol.cpp +++ b/src/brpc/policy/http_rpc_protocol.cpp @@ -89,7 +89,7 @@ static bool GetUserAddressFromHeaderImpl(const HttpHeader& headers, butil::EndPoint* user_addr) { const std::string* user_addr_str = headers.GetHeader(FLAGS_http_header_of_user_ip); - if (user_addr_str == NULL) { + if (user_addr_str == nullptr) { return false; } //TODO add protocols other than IPv4 supports. @@ -161,7 +161,7 @@ CommonStrings::CommonStrings() , DEFAULT_PATH("/") {} -static CommonStrings* common = NULL; +static CommonStrings* common = nullptr; static pthread_once_t g_common_strings_once = PTHREAD_ONCE_INIT; static void CreateCommonStrings() { common = new CommonStrings; @@ -363,7 +363,7 @@ void ProcessHttpResponse(InputMessageBase* msg) { return; } const bthread_id_t cid = { cid_value }; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -397,7 +397,7 @@ void ProcessHttpResponse(InputMessageBase* msg) { if (!is_http2) { // If header has "Connection: close", close the connection. const std::string* conn_cmd = res_header->GetHeader(common->CONNECTION); - if (conn_cmd != NULL && 0 == strcasecmp(conn_cmd->c_str(), "close")) { + if (conn_cmd != nullptr && 0 == strcasecmp(conn_cmd->c_str(), "close")) { // Server asked to close the connection. if (imsg_guard->read_body_progressively()) { // Close the socket when reading completes. @@ -414,7 +414,7 @@ void ProcessHttpResponse(InputMessageBase* msg) { const std::string* grpc_status = res_header->GetHeader(common->GRPC_STATUS); if (grpc_status) { // TODO: More strict parsing - GrpcStatus status = (GrpcStatus)strtol(grpc_status->data(), NULL, 10); + GrpcStatus status = (GrpcStatus)strtol(grpc_status->data(), nullptr, 10); if (status != GRPC_OK) { const std::string* grpc_message = res_header->GetHeader(common->GRPC_MESSAGE); @@ -451,7 +451,7 @@ void ProcessHttpResponse(InputMessageBase* msg) { static_cast(res_header->status_code()), res_header->reason_phrase(), (int)body_str.size(), body_str.c_str()); - } else if (cntl->response() != NULL && + } else if (cntl->response() != nullptr && cntl->response()->GetDescriptor()->field_count() != 0) { cntl->SetFailed(ERESPONSE, "A protobuf response can't be parsed" " from progressively-read HTTP body"); @@ -481,13 +481,13 @@ void ProcessHttpResponse(InputMessageBase* msg) { // set the returned error code to controller. Otherwise, // set EHTTP to controller uniformly. const std::string* error_code_ptr = res_header->GetHeader(common->ERROR_CODE); - int error_code = error_code_ptr ? strtol(error_code_ptr->data(), NULL, 10) : 0; + int error_code = error_code_ptr ? strtol(error_code_ptr->data(), nullptr, 10) : 0; if (FLAGS_use_http_error_code && error_code != 0) { cntl->SetFailed(error_code, "%s", err.c_str()); } else { cntl->SetFailed(EHTTP, "%s", err.c_str()); } - if (cntl->response() == NULL || + if (cntl->response() == nullptr || cntl->response()->GetDescriptor()->field_count() == 0) { // A http call. Http users may need the body(containing a html, // json etc) even if the http call was failed. This is different @@ -497,18 +497,18 @@ void ProcessHttpResponse(InputMessageBase* msg) { } break; } - if (cntl->response() == NULL || + if (cntl->response() == nullptr || cntl->response()->GetDescriptor()->field_count() == 0) { // a http call, content is the "real response". cntl->response_attachment().swap(res_body); break; } - const std::string* encoding = NULL; + const std::string* encoding = nullptr; if (is_grpc) { if (grpc_compressed) { encoding = res_header->GetHeader(common->GRPC_ENCODING); - if (encoding == NULL) { + if (encoding == nullptr) { cntl->SetFailed(ERESPONSE, "Fail to find header `grpc-encoding' " "in compressed gRPC response"); break; @@ -517,7 +517,7 @@ void ProcessHttpResponse(InputMessageBase* msg) { } else { encoding = res_header->GetHeader(common->CONTENT_ENCODING); } - if (encoding != NULL && *encoding == common->GZIP) { + if (encoding != nullptr && *encoding == common->GZIP) { TRACEPRINTF("Decompressing response=%lu", (unsigned long)res_body.size()); butil::IOBuf uncompressed; @@ -581,8 +581,8 @@ void SerializeHttpRequest(butil::IOBuf* /*not used*/, hreq.set_content_type(param); } } - if (pbreq != NULL) { - // If request is not NULL, message body will be serialized proto/json, + if (pbreq != nullptr) { + // If request is not nullptr, message body will be serialized proto/json, if (!pbreq->IsInitialized()) { return cntl->SetFailed( EREQUEST, "Missing required fields in request: %s", @@ -657,7 +657,7 @@ void SerializeHttpRequest(butil::IOBuf* /*not used*/, if (request_size >= (size_t)FLAGS_http_body_compress_threshold) { TRACEPRINTF("Compressing request=%lu", (unsigned long)request_size); butil::IOBuf compressed; - if (GzipCompress(cntl->request_attachment(), &compressed, NULL)) { + if (GzipCompress(cntl->request_attachment(), &compressed, nullptr)) { cntl->request_attachment().swap(compressed); if (is_grpc) { grpc_compressed = true; @@ -684,7 +684,7 @@ void SerializeHttpRequest(butil::IOBuf* /*not used*/, // HTTP before 1.1 needs to set keep-alive explicitly. if (hreq.before_http_1_1() && cntl->connection_type() != CONNECTION_TYPE_SHORT && - hreq.GetHeader(common->CONNECTION) == NULL) { + hreq.GetHeader(common->CONNECTION) == nullptr) { hreq.SetHeader(common->CONNECTION, common->KEEP_ALIVE); } } else { @@ -706,9 +706,9 @@ void SerializeHttpRequest(butil::IOBuf* /*not used*/, } // Set url to /ServiceName/MethodName when we're about to call protobuf - // services (indicated by non-NULL method). + // services (indicated by non-nullptr method). const google::protobuf::MethodDescriptor* method = cntl->method(); - if (method != NULL) { + if (method != nullptr) { hreq.set_method(HTTP_METHOD_POST); std::string path; path.reserve(2 + method->service()->full_name().size() @@ -742,7 +742,7 @@ void PackHttpRequest(butil::IOBuf* buf, } ControllerPrivateAccessor accessor(cntl); HttpHeader* header = &cntl->http_request(); - if (auth != NULL && header->GetHeader(common->AUTHORIZATION) == NULL) { + if (auth != nullptr && header->GetHeader(common->AUTHORIZATION) == nullptr) { std::string auth_data; if (auth->GenerateCredential(&auth_data) != 0) { return cntl->SetFailed(EREQUEST, "Fail to GenerateCredential"); @@ -775,11 +775,11 @@ class HttpResponseSender { friend class HttpResponseSenderAsDone; public: HttpResponseSender() - : HttpResponseSender(NULL) {} + : HttpResponseSender(nullptr) {} explicit HttpResponseSender(Controller* cntl/*own*/) : _cntl(cntl) - , _messages(NULL) - , _method_status(NULL) + , _messages(nullptr) + , _method_status(nullptr) , _received_us(0) , _h2_stream_id(-1) {} @@ -789,8 +789,8 @@ friend class HttpResponseSenderAsDone; , _method_status(s._method_status) , _received_us(s._received_us) , _h2_stream_id(s._h2_stream_id) { - s._messages = NULL; - s._method_status = NULL; + s._messages = nullptr; + s._method_status = nullptr; s._received_us = 0; s._h2_stream_id = -1; } @@ -813,7 +813,7 @@ class HttpResponseSenderAsDone : public google::protobuf::Closure { public: explicit HttpResponseSenderAsDone(HttpResponseSender* s) : _sender(std::move(*s)) {} void Run() override { - if (NULL != _sender._messages) { + if (nullptr != _sender._messages) { _sender._cntl->CallAfterRpcResp(_sender._messages->Request(), _sender._messages->Response()); } @@ -827,12 +827,12 @@ class HttpResponseSenderAsDone : public google::protobuf::Closure { HttpResponseSender::~HttpResponseSender() { // Return messages to factory at the end. BRPC_SCOPE_EXIT { - if (NULL != _messages) { + if (nullptr != _messages) { _cntl->server()->options().rpc_pb_message_factory->Return(_messages); } }; Controller* cntl = _cntl.get(); - if (cntl == NULL) { + if (cntl == nullptr) { return; } ControllerPrivateAccessor accessor(cntl); @@ -842,7 +842,7 @@ HttpResponseSender::~HttpResponseSender() { } ConcurrencyRemover concurrency_remover(_method_status, cntl, _received_us); Socket* socket = accessor.get_sending_socket(); - const google::protobuf::Message* res = NULL != _messages ? _messages->Response() : NULL; + const google::protobuf::Message* res = nullptr != _messages ? _messages->Response() : nullptr; if (cntl->IsCloseConnection()) { socket->SetFailed(); @@ -871,7 +871,7 @@ HttpResponseSender::~HttpResponseSender() { // Convert response to json/proto if needed. // Notice: Not check res->IsInitialized() which should be checked in the // conversion function. - if (res != NULL && + if (res != nullptr && cntl->response_attachment().empty() && // ^ user did not fill the body yet. res->GetDescriptor()->field_count() > 0 && @@ -912,16 +912,16 @@ HttpResponseSender::~HttpResponseSender() { // after receiving the response. if (!is_http2) { const std::string* res_conn = res_header->GetHeader(common->CONNECTION); - if (res_conn == NULL || strcasecmp(res_conn->c_str(), "close") != 0) { + if (res_conn == nullptr || strcasecmp(res_conn->c_str(), "close") != 0) { const std::string* req_conn = req_header->GetHeader(common->CONNECTION); if (req_header->before_http_1_1()) { - if (req_conn != NULL && + if (req_conn != nullptr && strcasecmp(req_conn->c_str(), "keep-alive") == 0) { res_header->SetHeader(common->CONNECTION, common->KEEP_ALIVE); } } else { - if (req_conn != NULL && + if (req_conn != nullptr && strcasecmp(req_conn->c_str(), "close") == 0) { res_header->SetHeader(common->CONNECTION, common->CLOSE); } @@ -974,7 +974,7 @@ HttpResponseSender::~HttpResponseSender() { && (is_http2 || SupportGzip(cntl))) { TRACEPRINTF("Compressing response=%lu", (unsigned long)response_size); butil::IOBuf tmpbuf; - if (GzipCompress(cntl->response_attachment(), &tmpbuf, NULL)) { + if (GzipCompress(cntl->response_attachment(), &tmpbuf, nullptr)) { cntl->response_attachment().swap(tmpbuf); if (is_grpc) { grpc_compressed = true; @@ -1012,7 +1012,7 @@ HttpResponseSender::~HttpResponseSender() { } SocketMessagePtr h2_response( H2UnsentResponse::New(cntl, _h2_stream_id, is_grpc)); - if (h2_response == NULL) { + if (h2_response == nullptr) { LOG(ERROR) << "Fail to make http2 response"; errno = EINVAL; rc = -1; @@ -1026,7 +1026,7 @@ HttpResponseSender::~HttpResponseSender() { rc = socket->Write(h2_response, &wopt); } } else { - butil::IOBuf* content = NULL; + butil::IOBuf* content = nullptr; if (cntl->Failed() || !cntl->has_progressive_writer()) { content = &cntl->response_attachment(); } @@ -1063,7 +1063,7 @@ HttpResponseSender::~HttpResponseSender() { static void FillUnresolvedPath(std::string* unresolved_path, const std::string& uri_path, butil::StringSplitter& splitter) { - if (unresolved_path == NULL) { + if (unresolved_path == nullptr) { return; } if (!splitter) { @@ -1077,7 +1077,7 @@ static void FillUnresolvedPath(std::string* unresolved_path, unresolved_path->clear(); for (butil::StringSplitter slash_sp( splitter.field(), splitter.field() + path_len, '/'); - slash_sp != NULL; ++slash_sp) { + slash_sp != nullptr; ++slash_sp) { if (!unresolved_path->empty()) { unresolved_path->push_back('/'); } @@ -1091,7 +1091,7 @@ FindMethodPropertyByURIImpl(const std::string& uri_path, const Server* server, ServerPrivateAccessor wrapper(server); butil::StringSplitter splitter(uri_path.c_str(), '/'); // Show index page for empty URI - if (NULL == splitter) { + if (nullptr == splitter) { return wrapper.FindMethodPropertyByFullName( IndexService::descriptor()->full_name(), common->DEFAULT_METHOD); } @@ -1102,9 +1102,9 @@ FindMethodPropertyByURIImpl(const std::string& uri_path, const Server* server, (full_service_name ? wrapper.FindServicePropertyByFullName(service_name) : wrapper.FindServicePropertyByName(service_name)); - if (NULL == sp) { + if (nullptr == sp) { // normal for urls matching _global_restful_map - return NULL; + return nullptr; } // Find restful methods by uri. if (sp->restful_map) { @@ -1123,9 +1123,9 @@ FindMethodPropertyByURIImpl(const std::string& uri_path, const Server* server, } // Regard URI as [service_name]/[method_name] - const Server::MethodProperty* mp = NULL; + const Server::MethodProperty* mp = nullptr; butil::StringPiece method_name; - if (++splitter != NULL) { + if (++splitter != nullptr) { method_name.set(splitter.field(), splitter.length()); // Copy splitter rather than modifying it directly since it's used // in later branches. @@ -1151,7 +1151,7 @@ FindMethodPropertyByURIImpl(const std::string& uri_path, const Server* server, } // Called an existing service w/o default_method with an unknown method. - return NULL; + return nullptr; } // Used in UT, don't be static @@ -1160,11 +1160,11 @@ FindMethodPropertyByURI(const std::string& uri_path, const Server* server, std::string* unresolved_path) { const Server::MethodProperty* mp = FindMethodPropertyByURIImpl(uri_path, server, unresolved_path); - if (mp != NULL) { - if (mp->http_url != NULL && !mp->params.allow_default_url) { + if (mp != nullptr) { + if (mp->http_url != nullptr && !mp->params.allow_default_url) { // the restful method is accessed from its // default url (SERVICE/METHOD) which should be rejected. - return NULL; + return nullptr; } return mp; } @@ -1176,14 +1176,14 @@ FindMethodPropertyByURI(const std::string& uri_path, const Server* server, return accessor.global_restful_map()->FindMethodProperty( uri_path, unresolved_path); } - return NULL; + return nullptr; } ParseResult ParseHttpMessage(butil::IOBuf *source, Socket *socket, bool read_eof, const void* arg) { HttpContext* http_imsg = static_cast(socket->parsing_context()); - if (http_imsg == NULL) { + if (http_imsg == nullptr) { if (read_eof || source->empty()) { // 1. read_eof: Read EOF after intact HTTP messages, a common case. // Notice that errors except NOT_ENOUGH_DATA can't be returned @@ -1194,13 +1194,8 @@ ParseResult ParseHttpMessage(butil::IOBuf *source, Socket *socket, // source is likely to be empty. return MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA); } - http_imsg = new (std::nothrow) HttpContext( - socket->is_read_progressive(), - socket->http_request_method()); - if (http_imsg == NULL) { - LOG(FATAL) << "Fail to new HttpContext"; - return MakeParseError(PARSE_ERROR_NO_RESOURCE); - } + http_imsg = new HttpContext(socket->is_read_progressive(), + socket->http_request_method()); // Parsing http is costly, parsing an incomplete http message from the // beginning repeatedly should be avoided, otherwise the cost may reach // O(n^2) in the worst case. Save incomplete http messages in sockets @@ -1211,7 +1206,7 @@ ParseResult ParseHttpMessage(butil::IOBuf *source, Socket *socket, ssize_t rc = 0; if (read_eof) { // Send EOF to HttpContext, check comments in http_message.h - rc = http_imsg->ParseFromArray(NULL, 0); + rc = http_imsg->ParseFromArray(nullptr, 0); } else { // Empty `source' is sliently ignored and 0 is returned, check // comments in http_message.h @@ -1227,7 +1222,7 @@ ParseResult ParseHttpMessage(butil::IOBuf *source, Socket *socket, HttpHeader header; header.set_status_code(HTTP_STATUS_REQUEST_ENTITY_TOO_LARGE); header.SetHeader("Connection", "close"); - MakeRawHttpResponse(&resp, &header, NULL); + MakeRawHttpResponse(&resp, &header, nullptr); Socket::WriteOptions wopt; wopt.ignore_eovercrowded = true; socket->Write(&resp, &wopt); @@ -1248,7 +1243,7 @@ ParseResult ParseHttpMessage(butil::IOBuf *source, Socket *socket, // be called from ProcessHttpXXX http_imsg->RemoveOneRefForStage2(); socket->OnProgressiveReadCompleted(); - return MakeMessage(NULL); + return MakeMessage(nullptr); } else { return MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA); } @@ -1287,7 +1282,7 @@ ParseResult ParseHttpMessage(butil::IOBuf *source, Socket *socket, butil::IOBuf resp; HttpHeader header; header.set_status_code(HTTP_STATUS_CONTINUE); - MakeRawHttpResponse(&resp, &header, NULL); + MakeRawHttpResponse(&resp, &header, nullptr); Socket::WriteOptions wopt; wopt.ignore_eovercrowded = true; socket->Write(&resp, &wopt); @@ -1319,7 +1314,7 @@ ParseResult ParseHttpMessage(butil::IOBuf *source, Socket *socket, // internal fd from epoll thus we can still get EPOLLIN and read // in more data. If the second read happens, parsing_context() // should return the same InputMessage that we see now because we - // don't reset_parsing_context(NULL) in this branch, and following + // don't reset_parsing_context(nullptr) in this branch, and following // ParseFromXXX should return -1 immediately because of the non-zero // parser.http_errno, and ReleaseAdditionalReference() here should // return -1 to prevent us from sending another 400. @@ -1337,7 +1332,7 @@ ParseResult ParseHttpMessage(butil::IOBuf *source, Socket *socket, butil::IOBuf resp; HttpHeader header; header.set_status_code(HTTP_STATUS_BAD_REQUEST); - MakeRawHttpResponse(&resp, &header, NULL); + MakeRawHttpResponse(&resp, &header, nullptr); Socket::WriteOptions wopt; wopt.ignore_eovercrowded = true; socket->Write(&resp, &wopt); @@ -1398,13 +1393,13 @@ bool VerifyHttpRequest(const InputMessageBase* msg) { HttpContext* http_request = (HttpContext*)msg; const Authenticator* auth = server->options().auth; - if (NULL == auth) { + if (nullptr == auth) { // Fast pass return true; } const Server::MethodProperty* mp = FindMethodPropertyByURI( - http_request->header().uri().path(), server, NULL); - if (mp != NULL && mp->is_builtin_service && + http_request->header().uri().path(), server, nullptr); + if (mp != nullptr && mp->is_builtin_service && mp->service->GetDescriptor() != BadMethodService::descriptor()) { // Builtin services on internal_port doesn't need authentication // Builtin services on the public listener must pass authentication @@ -1416,7 +1411,7 @@ bool VerifyHttpRequest(const InputMessageBase* msg) { const std::string *authorization = http_request->header().GetHeader(common->AUTHORIZATION); - if (authorization == NULL) { + if (authorization == nullptr) { SendUnauthorizedResponse(auth->GetUnauthorizedErrorText(), socket, msg); return false; } @@ -1451,11 +1446,7 @@ void ProcessHttpRequest(InputMessageBase *msg) { const Server* server = static_cast(msg->arg()); ScopedNonServiceError non_service_error(server); - Controller* cntl = new (std::nothrow) Controller; - if (NULL == cntl) { - LOG(FATAL) << "Fail to new Controller"; - return; - } + Controller* cntl = new Controller; HttpResponseSender resp_sender(cntl); resp_sender.set_received_us(msg->received_us()); @@ -1490,7 +1481,7 @@ void ProcessHttpRequest(InputMessageBase *msg) { // atoi/atol/atoll don't support 64-bit integer and can't be used. const std::string* log_id_str = req_header.GetHeader(common->LOG_ID); if (log_id_str) { - char* logid_end = NULL; + char* logid_end = nullptr; errno = 0; uint64_t logid = strtoull(log_id_str->c_str(), &logid_end, 10); if (*logid_end || errno) { @@ -1518,18 +1509,18 @@ void ProcessHttpRequest(InputMessageBase *msg) { if (IsTraceable(trace_id_str)) { uint64_t trace_id = 0; if (trace_id_str) { - trace_id = strtoull(trace_id_str->c_str(), NULL, 10); + trace_id = strtoull(trace_id_str->c_str(), nullptr, 10); } uint64_t span_id = 0; const std::string* span_id_str = req_header.GetHeader("x-bd-span-id"); if (span_id_str) { - span_id = strtoull(span_id_str->c_str(), NULL, 10); + span_id = strtoull(span_id_str->c_str(), nullptr, 10); } uint64_t parent_span_id = 0; const std::string* parent_span_id_str = req_header.GetHeader("x-bd-parent-span-id"); if (parent_span_id_str) { - parent_span_id = strtoull(parent_span_id_str->c_str(), NULL, 10); + parent_span_id = strtoull(parent_span_id_str->c_str(), nullptr, 10); } span = Span::CreateServerSpan( path, trace_id, span_id, parent_span_id, msg->base_real_us()); @@ -1552,7 +1543,7 @@ void ProcessHttpRequest(InputMessageBase *msg) { google::protobuf::Service* svc = server->options().http_master_service; const google::protobuf::MethodDescriptor* md = svc->GetDescriptor()->FindMethodByName(common->DEFAULT_METHOD); - if (md == NULL) { + if (md == nullptr) { cntl->SetFailed(ENOMETHOD, "No default_method in http_master_service"); return; } @@ -1565,12 +1556,12 @@ void ProcessHttpRequest(InputMessageBase *msg) { span->AsParent(); } // `cntl', `req' and `res' will be deleted inside `done' - return svc->CallMethod(md, cntl, NULL, NULL, done); + return svc->CallMethod(md, cntl, nullptr, nullptr, done); } const Server::MethodProperty* const mp = FindMethodPropertyByURI(path, server, &req_header._unresolved_path); - if (NULL == mp) { + if (nullptr == mp) { if (security_mode) { std::string escape_path; WebEscape(path, &escape_path); @@ -1584,7 +1575,7 @@ void ProcessHttpRequest(InputMessageBase *msg) { BadMethodResponse bres; butil::StringSplitter split(path.c_str(), '/'); breq.set_service_name(std::string(split.field(), split.length())); - mp->service->CallMethod(mp->method, cntl, &breq, &bres, NULL); + mp->service->CallMethod(mp->method, cntl, &breq, &bres, nullptr); return; } // Switch to service-specific error. @@ -1667,7 +1658,7 @@ void ProcessHttpRequest(InputMessageBase *msg) { bool is_grpc_ct = false; const HttpContentType content_type = ParseContentType(req_header.content_type(), &is_grpc_ct); - const std::string* encoding = NULL; + const std::string* encoding = nullptr; if (is_http2 && is_grpc_ct) { bool grpc_compressed = false; if (!RemoveGrpcPrefix(&req_body, &grpc_compressed)) { @@ -1676,7 +1667,7 @@ void ProcessHttpRequest(InputMessageBase *msg) { } if (grpc_compressed) { encoding = req_header.GetHeader(common->GRPC_ENCODING); - if (encoding == NULL) { + if (encoding == nullptr) { cntl->SetFailed( EREQUEST, "Fail to find header `grpc-encoding'" " in compressed gRPC request"); @@ -1692,7 +1683,7 @@ void ProcessHttpRequest(InputMessageBase *msg) { } else { // http or h2 but not grpc encoding = req_header.GetHeader(common->CONTENT_ENCODING); } - if (encoding != NULL && *encoding == common->GZIP) { + if (encoding != nullptr && *encoding == common->GZIP) { TRACEPRINTF("Decompressing request=%lu", (unsigned long)req_body.size()); butil::IOBuf uncompressed; @@ -1801,14 +1792,14 @@ const std::string& GetHttpMethodName( } void HttpContext::CheckProgressiveRead(const void* arg, Socket *socket) { - if (arg == NULL || !((Server *)arg)->has_progressive_read_method()) { - // arg == NULL indicates not in server-end + if (arg == nullptr || !((Server *)arg)->has_progressive_read_method()) { + // arg == nullptr indicates not in server-end return; } const Server::MethodProperty *const sp = FindMethodPropertyByURI( header().uri().path(), (Server *)arg, const_cast(&header().unresolved_path())); - if (sp != NULL && sp->params.enable_progressive_read) { + if (sp != nullptr && sp->params.enable_progressive_read) { set_read_body_progressively(true); socket->read_will_be_progressive(CONNECTION_TYPE_SHORT); } diff --git a/src/brpc/policy/hulu_pbrpc_protocol.cpp b/src/brpc/policy/hulu_pbrpc_protocol.cpp index f69804851f..cb397a49b2 100644 --- a/src/brpc/policy/hulu_pbrpc_protocol.cpp +++ b/src/brpc/policy/hulu_pbrpc_protocol.cpp @@ -247,11 +247,11 @@ static void SendHuluResponse(int64_t correlation_id, bool append_body = false; butil::IOBuf res_body_buf; - // `res' can be NULL here, in which case we don't serialize it + // `res' can be nullptr here, in which case we don't serialize it // If user calls `SetFailed' on Controller, we don't serialize // response either CompressType type = cntl->response_compress_type(); - if (res != NULL && !cntl->Failed()) { + if (res != nullptr && !cntl->Failed()) { if (!res->IsInitialized()) { cntl->SetFailed( ERESPONSE, "Missing required fields in response: %s", @@ -373,11 +373,7 @@ void ProcessHuluRequest(InputMessageBase* msg_base) { sample->submit(start_parse_us); } - std::unique_ptr cntl(new (std::nothrow) HuluController()); - if (NULL == cntl.get()) { - LOG(WARNING) << "Fail to new Controller"; - return; - } + std::unique_ptr cntl(new HuluController()); std::unique_ptr req; std::unique_ptr res; @@ -428,7 +424,7 @@ void ProcessHuluRequest(InputMessageBase* msg_base) { span->set_request_size(msg->payload.size() + msg->meta.size() + 12); } - MethodStatus* method_status = NULL; + MethodStatus* method_status = nullptr; do { if (!server->IsRunning()) { cntl->SetFailed(ELOGOFF, "Server is stopping"); @@ -449,7 +445,7 @@ void ProcessHuluRequest(InputMessageBase* msg_base) { const Server::MethodProperty *sp = server_accessor.FindMethodPropertyByNameAndIndex( meta.service_name(), meta.method_index()); - if (NULL == sp) { + if (nullptr == sp) { cntl->SetFailed(ENOMETHOD, "Fail to find method=%d of service=%s", meta.method_index(), meta.service_name().c_str()); break; @@ -458,7 +454,7 @@ void ProcessHuluRequest(InputMessageBase* msg_base) { BadMethodRequest breq; BadMethodResponse bres; breq.set_service_name(meta.service_name()); - sp->service->CallMethod(sp->method, cntl.get(), &breq, &bres, NULL); + sp->service->CallMethod(sp->method, cntl.get(), &breq, &bres, nullptr); break; } if (socket->is_overcrowded() && @@ -562,7 +558,7 @@ bool VerifyHuluRequest(const InputMessageBase* msg_base) { return false; } const Authenticator* auth = server->options().auth; - if (NULL == auth) { + if (nullptr == auth) { // Fast pass (no authentication) return true; } @@ -603,7 +599,7 @@ void ProcessHuluResponse(InputMessageBase* msg_base) { } const bthread_id_t cid = { static_cast(meta.correlation_id()) }; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -670,7 +666,7 @@ void PackHuluRequest(butil::IOBuf* req_buf, const butil::IOBuf& req_body, const Authenticator* auth) { HuluRpcRequestMeta meta; - if (auth != NULL && auth->GenerateCredential( + if (auth != nullptr && auth->GenerateCredential( meta.mutable_credential_data()) != 0) { return cntl->SetFailed(EREQUEST, "Fail to generate credential"); } @@ -691,7 +687,7 @@ void PackHuluRequest(butil::IOBuf* req_buf, } HuluController* hulu_controller = dynamic_cast(cntl); - if (hulu_controller != NULL) { + if (hulu_controller != nullptr) { if (hulu_controller->request_source_addr() != 0) { meta.set_user_defined_source_addr( hulu_controller->request_source_addr()); diff --git a/src/brpc/policy/list_naming_service.cpp b/src/brpc/policy/list_naming_service.cpp index 3a8ba45e0b..d5eb639e32 100644 --- a/src/brpc/policy/list_naming_service.cpp +++ b/src/brpc/policy/list_naming_service.cpp @@ -45,7 +45,7 @@ int ParseServerList(const char* service_name, LOG(FATAL) << "Param[service_name] is NULL"; return -1; } - for (butil::StringSplitter sp(service_name, ','); sp != NULL; ++sp) { + for (butil::StringSplitter sp(service_name, ','); sp != nullptr; ++sp) { line.assign(sp.field(), sp.length()); butil::StringPiece addr; butil::StringPiece tag; diff --git a/src/brpc/policy/locality_aware_load_balancer.cpp b/src/brpc/policy/locality_aware_load_balancer.cpp index beea51690e..81729d781e 100644 --- a/src/brpc/policy/locality_aware_load_balancer.cpp +++ b/src/brpc/policy/locality_aware_load_balancer.cpp @@ -55,12 +55,12 @@ bool LocalityAwareLoadBalancer::Add(Servers& bg, const Servers& fg, if (bg.weight_tree.capacity() < INITIAL_WEIGHT_TREE_SIZE) { bg.weight_tree.reserve(INITIAL_WEIGHT_TREE_SIZE); } - if (bg.server_map.seek(id) != NULL) { + if (bg.server_map.seek(id) != nullptr) { // The id duplicates. return false; } const size_t* pindex = fg.server_map.seek(id); - if (pindex == NULL) { + if (pindex == nullptr) { // Both fg and bg do not have the id. We create and insert a new Weight // structure. Later when we modify the other buffer(current fg), just // copy the pointer. @@ -106,7 +106,7 @@ bool LocalityAwareLoadBalancer::Add(Servers& bg, const Servers& fg, bool LocalityAwareLoadBalancer::Remove( Servers& bg, SocketId id, LocalityAwareLoadBalancer* lb) { size_t* pindex = bg.server_map.seek(id); - if (NULL == pindex) { + if (nullptr == pindex) { // The id does not exist. return false; } @@ -362,7 +362,7 @@ void LocalityAwareLoadBalancer::Feedback(const CallInfo& info) { return; } const size_t* pindex = s->server_map.seek(info.server_id); - if (NULL == pindex) { + if (nullptr == pindex) { return; } const size_t index = *pindex; @@ -470,9 +470,9 @@ int64_t LocalityAwareLoadBalancer::Weight::Update( return ResetWeight(index, end_time_us); } -LocalityAwareLoadBalancer* LocalityAwareLoadBalancer::New( - const butil::StringPiece&) const { - return new (std::nothrow) LocalityAwareLoadBalancer; +LocalityAwareLoadBalancer* +LocalityAwareLoadBalancer::New(const butil::StringPiece&) const { + return new LocalityAwareLoadBalancer; } void LocalityAwareLoadBalancer::Destroy() { diff --git a/src/brpc/policy/memcache_binary_protocol.cpp b/src/brpc/policy/memcache_binary_protocol.cpp index e3174be588..dcb435b059 100644 --- a/src/brpc/policy/memcache_binary_protocol.cpp +++ b/src/brpc/policy/memcache_binary_protocol.cpp @@ -78,7 +78,7 @@ ParseResult ParseMemcacheMessage(butil::IOBuf* source, Socket* socket, bool /*read_eof*/, const void */*arg*/) { while (1) { const uint8_t* p_mcmagic = (const uint8_t*)source->fetch1(); - if (NULL == p_mcmagic) { + if (nullptr == p_mcmagic) { return MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA); } if (*p_mcmagic != (uint8_t)MC_MAGIC_RESPONSE) { @@ -86,7 +86,7 @@ ParseResult ParseMemcacheMessage(butil::IOBuf* source, } char buf[24]; const uint8_t* p = (const uint8_t*)source->fetch(buf, sizeof(buf)); - if (NULL == p) { + if (nullptr == p) { return MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA); } const MemcacheResponseHeader* header = (const MemcacheResponseHeader*)p; @@ -112,7 +112,7 @@ ParseResult ParseMemcacheMessage(butil::IOBuf* source, } MostCommonMessage* msg = static_cast(socket->parsing_context()); - if (msg == NULL) { + if (msg == nullptr) { msg = MostCommonMessage::Get(); socket->reset_parsing_context(msg); } @@ -159,7 +159,7 @@ void ProcessMemcacheResponse(InputMessageBase* msg_base) { DestroyingPtr msg(static_cast(msg_base)); const bthread_id_t cid = msg->pi.id_wait; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -175,7 +175,7 @@ void ProcessMemcacheResponse(InputMessageBase* msg_base) { span->set_start_parse_us(start_parse_us); } const int saved_error = cntl->ErrorCode(); - if (cntl->response() == NULL) { + if (cntl->response() == nullptr) { cntl->SetFailed(ERESPONSE, "response is NULL!"); } else if (cntl->response()->GetDescriptor() != MemcacheResponse::descriptor()) { cntl->SetFailed(ERESPONSE, "Must be MemcacheResponse"); @@ -197,7 +197,7 @@ void ProcessMemcacheResponse(InputMessageBase* msg_base) { void SerializeMemcacheRequest(butil::IOBuf* buf, Controller* cntl, const google::protobuf::Message* request) { - if (request == NULL) { + if (request == nullptr) { return cntl->SetFailed(EREQUEST, "request is NULL"); } if (request->GetDescriptor() != MemcacheRequest::descriptor()) { diff --git a/src/brpc/policy/mongo_protocol.cpp b/src/brpc/policy/mongo_protocol.cpp index ee416421d8..cae64b5b06 100644 --- a/src/brpc/policy/mongo_protocol.cpp +++ b/src/brpc/policy/mongo_protocol.cpp @@ -46,7 +46,7 @@ namespace policy { struct SendMongoResponse : public google::protobuf::Closure { SendMongoResponse(const Server *server) : - status(NULL), + status(nullptr), received_us(0L), server(server) {} ~SendMongoResponse(); @@ -113,22 +113,22 @@ void SendMongoResponse::Run() { ParseResult ParseMongoMessage(butil::IOBuf* source, Socket* socket, bool /*read_eof*/, const void *arg) { const Server* server = static_cast(arg); - // arg may be NULL when the parser is invoked outside of a full Server + // arg may be nullptr when the parser is invoked outside of a full Server // context (e.g. during protocol probing or fuzz testing). Without this // guard, server->options() dereferences a null pointer and crashes. - if (NULL == server) { + if (nullptr == server) { LOG(FATAL) << "Failed creating server"; return MakeParseError(PARSE_ERROR_TRY_OTHERS); } const MongoServiceAdaptor* adaptor = server->options().mongo_service_adaptor; - if (NULL == adaptor) { + if (nullptr == adaptor) { // The server does not enable mongo adaptor. return MakeParseError(PARSE_ERROR_TRY_OTHERS); } char buf[sizeof(mongo_head_t)]; const char *p = (const char *)source->fetch(buf, sizeof(buf)); - if (NULL == p) { + if (nullptr == p) { return MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA); } mongo_head_t header = *(const mongo_head_t*)p; @@ -153,9 +153,9 @@ ParseResult ParseMongoMessage(butil::IOBuf* source, // socket::_input_message, and created at the first time when msg // comes over the socket. Destroyable *socket_context_msg = socket->parsing_context(); - if (NULL == socket_context_msg) { + if (nullptr == socket_context_msg) { MongoContext *context = adaptor->CreateSocketContext(); - if (NULL == context) { + if (nullptr == context) { return MakeParseError(PARSE_ERROR_NO_RESOURCE); } socket_context_msg = new MongoContextMessage(context); @@ -203,7 +203,7 @@ void ProcessMongoRequest(InputMessageBase* msg_base) { MongoContextMessage *context_msg = dynamic_cast(socket->parsing_context()); - if (NULL == context_msg) { + if (nullptr == context_msg) { LOG(WARNING) << "socket context wasn't set correctly"; return; } @@ -245,7 +245,7 @@ void ProcessMongoRequest(InputMessageBase* msg_base) { break; } - if (NULL == mp || + if (nullptr == mp || mp->service->GetDescriptor() == BadMethodService::descriptor()) { mongo_done->cntl.SetFailed(ENOMETHOD, "Fail to find default_method"); break; diff --git a/src/brpc/policy/mysql/mysql.cpp b/src/brpc/policy/mysql/mysql.cpp index 154f7398d3..8d49d06639 100644 --- a/src/brpc/policy/mysql/mysql.cpp +++ b/src/brpc/policy/mysql/mysql.cpp @@ -91,17 +91,17 @@ void MysqlRequest::SharedCtor() { _has_error = false; _cached_size_ = 0; _has_command = false; - _tx = NULL; - _stmt = NULL; + _tx = nullptr; + _stmt = nullptr; _param_index = 0; } MysqlRequest::~MysqlRequest() { SharedDtor(); - if (_stmt != NULL) { + if (_stmt != nullptr) { delete _stmt; } - _stmt = NULL; + _stmt = nullptr; } void MysqlRequest::SharedDtor() { @@ -115,10 +115,10 @@ void MysqlRequest::Clear() { _has_error = false; _buf.clear(); _has_command = false; - _tx = NULL; + _tx = nullptr; if (_stmt) { delete _stmt; - _stmt = NULL; + _stmt = nullptr; } _param_index = 0; } @@ -141,11 +141,11 @@ void MysqlRequest::MergeFrom(const MysqlRequest& from) { // _tx is a non-owning pointer (never deleted by MysqlRequest): shallow copy. _tx = from._tx; // _stmt is owned (deleted in the dtor): deep-copy to avoid double free. - if (_stmt != NULL) { + if (_stmt != nullptr) { delete _stmt; - _stmt = NULL; + _stmt = nullptr; } - if (from._stmt != NULL) { + if (from._stmt != nullptr) { _stmt = new MysqlStatementStub(*from._stmt); } } @@ -196,7 +196,7 @@ bool MysqlRequest::AddParam(int8_t p) { if (_has_error) { return false; } - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(int8_t): no prepared statement bound to request"; _has_error = true; return false; @@ -212,7 +212,7 @@ bool MysqlRequest::AddParam(int8_t p) { } } bool MysqlRequest::AddParam(uint8_t p) { - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(uint8_t): no prepared statement bound to request"; _has_error = true; return false; @@ -229,7 +229,7 @@ bool MysqlRequest::AddParam(uint8_t p) { } } bool MysqlRequest::AddParam(int16_t p) { - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(int16_t): no prepared statement bound to request"; _has_error = true; return false; @@ -245,7 +245,7 @@ bool MysqlRequest::AddParam(int16_t p) { } } bool MysqlRequest::AddParam(uint16_t p) { - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(uint16_t): no prepared statement bound to request"; _has_error = true; return false; @@ -262,7 +262,7 @@ bool MysqlRequest::AddParam(uint16_t p) { } } bool MysqlRequest::AddParam(int32_t p) { - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(int32_t): no prepared statement bound to request"; _has_error = true; return false; @@ -278,7 +278,7 @@ bool MysqlRequest::AddParam(int32_t p) { } } bool MysqlRequest::AddParam(uint32_t p) { - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(uint32_t): no prepared statement bound to request"; _has_error = true; return false; @@ -295,7 +295,7 @@ bool MysqlRequest::AddParam(uint32_t p) { } } bool MysqlRequest::AddParam(int64_t p) { - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(int64_t): no prepared statement bound to request"; _has_error = true; return false; @@ -312,7 +312,7 @@ bool MysqlRequest::AddParam(int64_t p) { } } bool MysqlRequest::AddParam(uint64_t p) { - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(uint64_t): no prepared statement bound to request"; _has_error = true; return false; @@ -329,7 +329,7 @@ bool MysqlRequest::AddParam(uint64_t p) { } } bool MysqlRequest::AddParam(float p) { - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(float): no prepared statement bound to request"; _has_error = true; return false; @@ -345,7 +345,7 @@ bool MysqlRequest::AddParam(float p) { } } bool MysqlRequest::AddParam(double p) { - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(double): no prepared statement bound to request"; _has_error = true; return false; @@ -361,7 +361,7 @@ bool MysqlRequest::AddParam(double p) { } } bool MysqlRequest::AddParam(const butil::StringPiece& p) { - if (_stmt == NULL || _stmt->stmt() == NULL) { + if (_stmt == nullptr || _stmt->stmt() == nullptr) { LOG(WARNING) << "MysqlRequest::AddParam(StringPiece): no prepared statement bound to request"; _has_error = true; return false; @@ -473,7 +473,7 @@ ParseError MysqlResponse::ConsumePartialIOBuf(butil::IOBuf& buf, if (_other_replies.size() < reply_size()) { MysqlReply* replies = (MysqlReply*)_arena.allocate(sizeof(MysqlReply) * (replies_size - 1)); - if (replies == NULL) { + if (replies == nullptr) { LOG(ERROR) << "Fail to allocate MysqlReply[" << replies_size - 1 << "]"; return PARSE_ERROR_ABSOLUTELY_WRONG; } diff --git a/src/brpc/policy/mysql/mysql.h b/src/brpc/policy/mysql/mysql.h index d55086e713..9ff8d72c42 100644 --- a/src/brpc/policy/mysql/mysql.h +++ b/src/brpc/policy/mysql/mysql.h @@ -42,7 +42,7 @@ namespace brpc { // MysqlRequest request; // request.Query("select * from table"); // MysqlResponse response; -// channel.CallMethod(NULL, &controller, &request, &response, NULL/*done*/); +// channel.CallMethod(nullptr, &controller, &request, &response, nullptr/*done*/); // if (!cntl.Failed()) { // LOG(INFO) << response.reply(0); // } diff --git a/src/brpc/policy/mysql/mysql_auth_packet.cpp b/src/brpc/policy/mysql/mysql_auth_packet.cpp index 1e1395a696..0c3af4b8b3 100644 --- a/src/brpc/policy/mysql/mysql_auth_packet.cpp +++ b/src/brpc/policy/mysql/mysql_auth_packet.cpp @@ -43,7 +43,7 @@ size_t DecodeLengthEncodedInt(const butil::StringPiece& buf, uint64_t* out, return 1; } if (first == 0xfb) { - // 0xFB is the lenenc NULL marker, not a length prefix. Report NULL + // 0xFB is the lenenc nullptr marker, not a length prefix. Report nullptr // (one byte consumed) instead of folding it into the failure path. if (is_null != nullptr) { *is_null = true; @@ -126,7 +126,7 @@ size_t DecodeLengthEncodedString(const butil::StringPiece& buf, return 0; } if (len_is_null) { - // Leading 0xFB: the string itself is NULL. Only the marker byte is + // Leading 0xFB: the string itself is nullptr. Only the marker byte is // consumed; there is no payload to read. if (is_null != nullptr) { *is_null = true; diff --git a/src/brpc/policy/mysql/mysql_auth_packet.h b/src/brpc/policy/mysql/mysql_auth_packet.h index dcefa3c772..d3be6507f7 100644 --- a/src/brpc/policy/mysql/mysql_auth_packet.h +++ b/src/brpc/policy/mysql/mysql_auth_packet.h @@ -52,17 +52,17 @@ static const uint32_t kMaxPayloadLen = (1u << 24) - 1; // On success stores the value in *out and returns the number of bytes // consumed (1, 3, 4, or 9). // -// 0xFB is the protocol's NULL marker (a NULL column value in a result +// 0xFB is the protocol's nullptr marker (a nullptr column value in a result // row), NOT an ordinary integer: when |buf| begins with 0xFB the value is -// NULL, *out is set to 0, *is_null (when non-NULL) is set to true, and 1 -// (the single byte consumed) is returned. For every non-NULL result +// nullptr, *out is set to 0, *is_null (when non-nullptr) is set to true, and 1 +// (the single byte consumed) is returned. For every non-nullptr result // *is_null is set to false. // // Returns 0 on failure: an empty buffer, a truncated multi-byte value, or // the reserved 0xFF marker. On failure *out is set to 0 and *is_null -// (when non-NULL) to false, so a caller that forgets to check the return -// value never reads an uninitialized result. |is_null| may be NULL when -// the caller does not need to distinguish NULL from 0. +// (when non-nullptr) to false, so a caller that forgets to check the return +// value never reads an uninitialized result. |is_null| may be nullptr when +// the caller does not need to distinguish nullptr from 0. size_t DecodeLengthEncodedInt(const butil::StringPiece& buf, uint64_t* out, bool* is_null = nullptr); @@ -70,11 +70,11 @@ size_t DecodeLengthEncodedInt(const butil::StringPiece& buf, uint64_t* out, void EncodeLengthEncodedInt(uint64_t value, std::string* out); // Decodes a length-encoded string into |out_value| and returns the -// number of bytes consumed. A leading 0xFB encodes the protocol NULL -// value: when present *out_value is cleared, *is_null (when non-NULL) is -// set to true, and 1 (the marker byte) is returned. For a non-NULL +// number of bytes consumed. A leading 0xFB encodes the protocol nullptr +// value: when present *out_value is cleared, *is_null (when non-nullptr) is +// set to true, and 1 (the marker byte) is returned. For a non-nullptr // string *is_null is set to false. Returns 0 if the leading lenenc-int -// is invalid or the declared payload is truncated. |is_null| may be NULL. +// is invalid or the declared payload is truncated. |is_null| may be nullptr. size_t DecodeLengthEncodedString(const butil::StringPiece& buf, std::string* out_value, bool* is_null = nullptr); diff --git a/src/brpc/policy/mysql/mysql_command.cpp b/src/brpc/policy/mysql/mysql_command.cpp index a4ecf9df35..fa48abbbc4 100644 --- a/src/brpc/policy/mysql/mysql_command.cpp +++ b/src/brpc/policy/mysql/mysql_command.cpp @@ -74,7 +74,7 @@ butil::Status MakePacket(butil::IOBuf* outbuf, const H& head, const F& func, con butil::Status MysqlMakeCommand(butil::IOBuf* outbuf, const MysqlCommandType type, const butil::StringPiece& command) { - if (outbuf == NULL || command.size() == 0) { + if (outbuf == nullptr || command.size() == 0) { return butil::Status(EINVAL, "[MysqlMakeCommand] Param[outbuf] or [stmt] is NULL"); } auto func = @@ -200,7 +200,7 @@ butil::Status MysqlMakeExecuteData(MysqlStatementStub* stmt, break; case MYSQL_FIELD_TYPE_STRING: { const butil::StringPiece* p = (butil::StringPiece*)value; - if (p == NULL || p->data() == NULL) { + if (p == nullptr || p->data() == nullptr) { param_types.types[index + index] = MYSQL_FIELD_TYPE_NULL; param_types.types[index + index + 1] = 0x00; null_mask.mask[index / 8] |= 1 << (index & 7); diff --git a/src/brpc/policy/mysql/mysql_protocol.cpp b/src/brpc/policy/mysql/mysql_protocol.cpp index c82f1a2670..7155406286 100644 --- a/src/brpc/policy/mysql/mysql_protocol.cpp +++ b/src/brpc/policy/mysql/mysql_protocol.cpp @@ -108,12 +108,12 @@ bool PackRequest(butil::IOBuf* buf, const butil::IOBuf& request) { if (accessor.pipelined_count() == MYSQL_PREPARED_STATEMENT) { Socket* sock = accessor.get_sending_socket(); - if (sock == NULL) { + if (sock == nullptr) { LOG(ERROR) << "[MYSQL PACK] get sending socket with NULL"; return false; } auto stub = static_cast(accessor.session_data()); - if (stub == NULL) { + if (stub == nullptr) { LOG(ERROR) << "[MYSQL PACK] get prepare statement with NULL"; return false; } @@ -145,7 +145,7 @@ bool PackRequest(butil::IOBuf* buf, ParseError HandleAuthentication(const InputResponse* msg, const Socket* socket, PipelinedInfo* pi) { const bthread_id_t cid = pi->id_wait; - Controller* cntl = NULL; + Controller* cntl = nullptr; if (bthread_id_lock(cid, (void**)&cntl) != 0) { LOG(ERROR) << "[MYSQL PARSE] fail to lock controller"; return PARSE_ERROR_ABSOLUTELY_WRONG; @@ -153,7 +153,7 @@ ParseError HandleAuthentication(const InputResponse* msg, const Socket* socket, ParseError parseCode = PARSE_OK; const AuthContext* ctx = socket->auth_context(); - if (ctx == NULL) { + if (ctx == nullptr) { parseCode = PARSE_ERROR_ABSOLUTELY_WRONG; LOG(ERROR) << "[MYSQL PARSE] auth context is null"; goto END_OF_AUTH; @@ -286,7 +286,7 @@ ParseError HandlePrepareStatement(const InputResponse* msg, } const MysqlReply::PrepareOk& ok = msg->response.reply(0).prepare_ok(); const bthread_id_t cid = pi->id_wait; - Controller* cntl = NULL; + Controller* cntl = nullptr; if (bthread_id_lock(cid, (void**)&cntl) != 0) { LOG(ERROR) << "[MYSQL PARSE] fail to lock controller"; return PARSE_ERROR_ABSOLUTELY_WRONG; @@ -294,16 +294,16 @@ ParseError HandlePrepareStatement(const InputResponse* msg, ParseError parseCode = PARSE_OK; butil::IOBuf buf; butil::Status st; - MysqlStatementStub* stub = NULL; - MysqlStatement* stmt = NULL; + MysqlStatementStub* stub = nullptr; + MysqlStatement* stmt = nullptr; stub = static_cast(ControllerPrivateAccessor(cntl).session_data()); - if (stub == NULL) { + if (stub == nullptr) { LOG(ERROR) << "[MYSQL PACK] get prepare statement with NULL"; parseCode = PARSE_ERROR_ABSOLUTELY_WRONG; goto END_OF_PREPARE; } stmt = stub->stmt(); - if (stmt == NULL || stmt->param_count() != ok.param_count()) { + if (stmt == nullptr || stmt->param_count() != ok.param_count()) { LOG(ERROR) << "[MYSQL PACK] stmt can't be NULL"; parseCode = PARSE_ERROR_ABSOLUTELY_WRONG; goto END_OF_PREPARE; @@ -356,7 +356,7 @@ ParseResult ParseMysqlMessage(butil::IOBuf* source, } InputResponse* msg = static_cast(socket->parsing_context()); - if (msg == NULL) { + if (msg == nullptr) { msg = new InputResponse; socket->reset_parsing_context(msg); } @@ -413,7 +413,7 @@ void ProcessMysqlResponse(InputMessageBase* msg_base) { DestroyingPtr msg(static_cast(msg_base)); const bthread_id_t cid = msg->id_wait; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -431,7 +431,7 @@ void ProcessMysqlResponse(InputMessageBase* msg_base) { span->set_start_parse_us(start_parse_us); } const int saved_error = cntl->ErrorCode(); - if (cntl->response() != NULL) { + if (cntl->response() != nullptr) { if (cntl->response()->GetDescriptor() != MysqlResponse::descriptor()) { LOG(ERROR) << "[MYSQL PROCESS] response message is not a MysqlResponse"; cntl->SetFailed(ERESPONSE, "Must be MysqlResponse"); @@ -450,7 +450,7 @@ void ProcessMysqlResponse(InputMessageBase* msg_base) { void SerializeMysqlRequest(butil::IOBuf* buf, Controller* cntl, const google::protobuf::Message* request) { - if (request == NULL) { + if (request == nullptr) { LOG(ERROR) << "[MYSQL SERIALIZE] request is NULL"; return cntl->SetFailed(EREQUEST, "request is NULL"); } @@ -473,11 +473,11 @@ void SerializeMysqlRequest(butil::IOBuf* buf, accessor.set_mysql_statement_type(MYSQL_NORMAL_STATEMENT); auto tx = rr->tx(); - if (tx != NULL) { + if (tx != nullptr) { accessor.use_bind_sock(tx->GetSocketId()); } auto st = rr->stmt(); - if (st != NULL) { + if (st != nullptr) { accessor.set_session_data(rr->stmt()); accessor.set_mysql_statement_type(MYSQL_PREPARED_STATEMENT); } @@ -496,12 +496,12 @@ void PackMysqlRequest(butil::IOBuf* buf, ControllerPrivateAccessor accessor(cntl); if (auth) { const MysqlAuthenticator* my_auth(dynamic_cast(auth)); - if (my_auth == NULL) { + if (my_auth == nullptr) { LOG(ERROR) << "[MYSQL PACK] there is not MysqlAuthenticator"; return; } Socket* sock = accessor.get_sending_socket(); - if (sock == NULL) { + if (sock == nullptr) { LOG(ERROR) << "[MYSQL PACK] get sending socket with NULL"; return; } diff --git a/src/brpc/policy/mysql/mysql_reply.cpp b/src/brpc/policy/mysql/mysql_reply.cpp index 46778f2e64..80b222f3f2 100644 --- a/src/brpc/policy/mysql/mysql_reply.cpp +++ b/src/brpc/policy/mysql/mysql_reply.cpp @@ -40,9 +40,9 @@ namespace brpc { template inline bool my_alloc_check(butil::Arena* arena, const size_t n, Type*& pointer) { - if (pointer == NULL) { + if (pointer == nullptr) { pointer = (Type*)arena->allocate(sizeof(Type) * n); - if (pointer == NULL) { + if (pointer == nullptr) { LOG(ERROR) << "my_alloc_check: arena failed to allocate " << (sizeof(Type) * n) << " bytes (n=" << n << ")"; return false; @@ -56,9 +56,9 @@ inline bool my_alloc_check(butil::Arena* arena, const size_t n, Type*& pointer) template <> inline bool my_alloc_check(butil::Arena* arena, const size_t n, char*& pointer) { - if (pointer == NULL) { + if (pointer == nullptr) { pointer = (char*)arena->allocate(sizeof(char) * n); - if (pointer == NULL) { + if (pointer == nullptr) { LOG(ERROR) << "my_alloc_check: arena failed to allocate " << n << " char bytes"; return false; } @@ -120,7 +120,7 @@ const char* MysqlRspTypeToString(MysqlRspType type) { inline bool is_full_package(const butil::IOBuf& buf) { uint8_t header[4]; const uint8_t* p = (const uint8_t*)buf.fetch(header, sizeof(header)); - if (p == NULL) { + if (p == nullptr) { return false; } uint32_t payload_size = mysql_uint3korr(p); @@ -133,7 +133,7 @@ inline bool is_full_package(const butil::IOBuf& buf) { inline bool is_an_eof(const butil::IOBuf& buf) { uint8_t tmp[5]; const uint8_t* p = (const uint8_t*)buf.fetch(tmp, sizeof(tmp)); - if (p == NULL) { + if (p == nullptr) { return false; } uint8_t type = p[4]; @@ -222,7 +222,7 @@ ParseError MysqlReply::ConsumePartialIOBuf(butil::IOBuf& buf, // never coalesced. uint8_t status[4 + 2]; const uint8_t* sp = (const uint8_t*)buf.fetch(status, sizeof(status)); - const bool fast_auth_success = (sp != NULL && sp[5] == 0x03); + const bool fast_auth_success = (sp != nullptr && sp[5] == 0x03); if (fast_auth_success) { // Determine, WITHOUT consuming anything, whether the OK packet // that follows the fast-auth marker is also fully buffered. @@ -455,7 +455,7 @@ ParseError MysqlReply::Auth::Parse(butil::IOBuf& buf, butil::Arena* arena) { { butil::IOBuf version; buf.cut_until(&version, delim); - char* d = NULL; + char* d = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, version.size(), d)); version.copy_to(d); _version.set(d, version.size()); @@ -468,7 +468,7 @@ ParseError MysqlReply::Auth::Parse(butil::IOBuf& buf, butil::Arena* arena) { { butil::IOBuf salt; buf.cut_until(&salt, delim); - char* d = NULL; + char* d = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, salt.size(), d)); salt.copy_to(d); _salt.set(d, salt.size()); @@ -494,7 +494,7 @@ ParseError MysqlReply::Auth::Parse(butil::IOBuf& buf, butil::Arena* arena) { { butil::IOBuf salt2; buf.cut_until(&salt2, delim); - char* d = NULL; + char* d = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, salt2.size(), d)); salt2.copy_to(d); _salt2.set(d, salt2.size()); @@ -505,7 +505,7 @@ ParseError MysqlReply::Auth::Parse(butil::IOBuf& buf, butil::Arena* arena) { << " exceeds remaining buffer size " << buf.size(); return PARSE_ERROR_ABSOLUTELY_WRONG; } - char* d = NULL; + char* d = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, _auth_plugin_length, d)); buf.cutn(d, _auth_plugin_length); _auth_plugin.set(d, _auth_plugin_length); @@ -529,12 +529,12 @@ ParseError MysqlReply::AuthMoreData::Parse(butil::IOBuf& buf, butil::Arena* aren buf.pop_front(1); const int64_t len = (int64_t)header.payload_size - 1; if (len > 0) { - char* d = NULL; + char* d = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, d)); buf.cutn(d, len); _data.set(d, len); } else { - _data.set(NULL, 0); + _data.set(nullptr, 0); } set_parsed(); return PARSE_OK; @@ -552,7 +552,7 @@ ParseError MysqlReply::ResultSetHeader::Parse(butil::IOBuf& buf) { old_size = buf.size(); _column_count = parse_encode_length(buf); // Guard against an absurd/malicious column count driving unbounded - // allocations downstream (per-column arrays and the row NULL-bitmap). + // allocations downstream (per-column arrays and the row nullptr-bitmap). // MySQL's hard limit is 4096 columns per table; 65535 is a generous cap // that no legitimate result set exceeds. if (_column_count > 65535) { @@ -587,7 +587,7 @@ ParseError MysqlReply::Column::Parse(butil::IOBuf& buf, butil::Arena* arena) { << " exceeds remaining buffer size " << buf.size(); return PARSE_ERROR_ABSOLUTELY_WRONG; } - char* catalog = NULL; + char* catalog = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, catalog)); buf.cutn(catalog, len); _catalog.set(catalog, len); @@ -598,7 +598,7 @@ ParseError MysqlReply::Column::Parse(butil::IOBuf& buf, butil::Arena* arena) { << " exceeds remaining buffer size " << buf.size(); return PARSE_ERROR_ABSOLUTELY_WRONG; } - char* database = NULL; + char* database = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, database)); buf.cutn(database, len); _database.set(database, len); @@ -609,7 +609,7 @@ ParseError MysqlReply::Column::Parse(butil::IOBuf& buf, butil::Arena* arena) { << " exceeds remaining buffer size " << buf.size(); return PARSE_ERROR_ABSOLUTELY_WRONG; } - char* table = NULL; + char* table = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, table)); buf.cutn(table, len); _table.set(table, len); @@ -620,7 +620,7 @@ ParseError MysqlReply::Column::Parse(butil::IOBuf& buf, butil::Arena* arena) { << " exceeds remaining buffer size " << buf.size(); return PARSE_ERROR_ABSOLUTELY_WRONG; } - char* origin_table = NULL; + char* origin_table = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, origin_table)); buf.cutn(origin_table, len); _origin_table.set(origin_table, len); @@ -631,7 +631,7 @@ ParseError MysqlReply::Column::Parse(butil::IOBuf& buf, butil::Arena* arena) { << " exceeds remaining buffer size " << buf.size(); return PARSE_ERROR_ABSOLUTELY_WRONG; } - char* name = NULL; + char* name = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, name)); buf.cutn(name, len); _name.set(name, len); @@ -642,7 +642,7 @@ ParseError MysqlReply::Column::Parse(butil::IOBuf& buf, butil::Arena* arena) { << " exceeds remaining buffer size " << buf.size(); return PARSE_ERROR_ABSOLUTELY_WRONG; } - char* origin_name = NULL; + char* origin_name = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, origin_name)); buf.cutn(origin_name, len); _origin_name.set(origin_name, len); @@ -698,7 +698,7 @@ ParseError MysqlReply::Ok::Parse(butil::IOBuf& buf, butil::Arena* arena) { new_size = buf.size(); if (old_size - new_size < header.payload_size) { const int64_t len = header.payload_size - (old_size - new_size); - char* msg = NULL; + char* msg = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, msg)); buf.cutn(msg, len); _msg.set(msg, len); @@ -746,7 +746,7 @@ ParseError MysqlReply::Error::Parse(butil::IOBuf& buf, butil::Arena* arena) { } buf.pop_front(1); // '#' // 5 byte server status - char* status = NULL; + char* status = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, 5, status)); buf.cutn(status, 5); _status.set(status, 5); @@ -760,7 +760,7 @@ ParseError MysqlReply::Error::Parse(butil::IOBuf& buf, butil::Arena* arena) { return PARSE_ERROR_ABSOLUTELY_WRONG; } uint64_t len = header.payload_size - 9; - char* msg = NULL; + char* msg = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, msg)); buf.cutn(msg, len); _msg.set(msg, len); @@ -793,12 +793,12 @@ ParseError MysqlReply::Row::Parse(butil::IOBuf& buf, << unsigned(hdr) << ", expected 0x00"; return PARSE_ERROR_ABSOLUTELY_WRONG; } - // NULL-bitmap, [(column-count + 7 + 2) / 8 bytes]. Allocate from the + // nullptr-bitmap, [(column-count + 7 + 2) / 8 bytes]. Allocate from the // arena instead of a stack VLA: column_count is attacker-controlled // (length-encoded in the result-set header), so a large value would // otherwise be an unbounded stack allocation / stack overflow. const uint64_t size = ((column_count + 7 + 2) >> 3); - uint8_t* null_mask = NULL; + uint8_t* null_mask = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, (size_t)size, null_mask)); for (uint64_t i = 0; i < size; ++i) { null_mask[i] = 0; @@ -849,39 +849,39 @@ ParseError MysqlReply::Field::Parse(butil::IOBuf& buf, break; case MYSQL_FIELD_TYPE_TINY: if (column->_flag & MYSQL_UNSIGNED_FLAG) { - _data.tiny = strtoul(str.to_string().c_str(), NULL, 10); + _data.tiny = strtoul(str.to_string().c_str(), nullptr, 10); } else { - _data.stiny = strtol(str.to_string().c_str(), NULL, 10); + _data.stiny = strtol(str.to_string().c_str(), nullptr, 10); } break; case MYSQL_FIELD_TYPE_SHORT: case MYSQL_FIELD_TYPE_YEAR: if (column->_flag & MYSQL_UNSIGNED_FLAG) { - _data.small = strtoul(str.to_string().c_str(), NULL, 10); + _data.small = strtoul(str.to_string().c_str(), nullptr, 10); } else { - _data.ssmall = strtol(str.to_string().c_str(), NULL, 10); + _data.ssmall = strtol(str.to_string().c_str(), nullptr, 10); } break; case MYSQL_FIELD_TYPE_INT24: case MYSQL_FIELD_TYPE_LONG: if (column->_flag & MYSQL_UNSIGNED_FLAG) { - _data.integer = strtoul(str.to_string().c_str(), NULL, 10); + _data.integer = strtoul(str.to_string().c_str(), nullptr, 10); } else { - _data.sinteger = strtol(str.to_string().c_str(), NULL, 10); + _data.sinteger = strtol(str.to_string().c_str(), nullptr, 10); } break; case MYSQL_FIELD_TYPE_LONGLONG: if (column->_flag & MYSQL_UNSIGNED_FLAG) { - _data.bigint = strtoul(str.to_string().c_str(), NULL, 10); + _data.bigint = strtoul(str.to_string().c_str(), nullptr, 10); } else { - _data.sbigint = strtol(str.to_string().c_str(), NULL, 10); + _data.sbigint = strtol(str.to_string().c_str(), nullptr, 10); } break; case MYSQL_FIELD_TYPE_FLOAT: - _data.float32 = strtof(str.to_string().c_str(), NULL); + _data.float32 = strtof(str.to_string().c_str(), nullptr); break; case MYSQL_FIELD_TYPE_DOUBLE: - _data.float64 = strtod(str.to_string().c_str(), NULL); + _data.float64 = strtod(str.to_string().c_str(), nullptr); break; case MYSQL_FIELD_TYPE_DECIMAL: case MYSQL_FIELD_TYPE_NEWDECIMAL: @@ -902,7 +902,7 @@ ParseError MysqlReply::Field::Parse(butil::IOBuf& buf, case MYSQL_FIELD_TYPE_NEWDATE: case MYSQL_FIELD_TYPE_TIMESTAMP: case MYSQL_FIELD_TYPE_DATETIME: { - char* d = NULL; + char* d = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, d)); str.copy_to(d); _data.str.set(d, len); @@ -1017,7 +1017,7 @@ ParseError MysqlReply::Field::Parse(butil::IOBuf& buf, << " exceeds remaining buffer size " << buf.size(); return PARSE_ERROR_ABSOLUTELY_WRONG; } - char* d = NULL; + char* d = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, len, d)); buf.cutn(d, len); _data.str.set(d, len); @@ -1053,8 +1053,8 @@ ParseError MysqlReply::Field::ParseBinaryTime(butil::IOBuf& buf, const uint64_t len = parse_encode_length(buf); // A length of 0, 8 or 12 are the only legal binary TIME encodings. Anything // else is a malformed packet -- reject it rather than reading past the value. - // NOTE: len == 0 is NOT a NULL value (NULL is signalled by the row - // NULL-bitmap, handled by the caller before we are reached); it is the zero + // NOTE: len == 0 is NOT a nullptr value (nullptr is signalled by the row + // nullptr-bitmap, handled by the caller before we are reached); it is the zero // TIME value "00:00:00" with no field bytes on the wire. if (len != 0 && len != 8 && len != 12) { LOG(ERROR) << "invalid TIME packet length " << len; @@ -1089,7 +1089,7 @@ ParseError MysqlReply::Field::ParseBinaryTime(butil::IOBuf& buf, } size_t i = 0; - char* d = NULL; + char* d = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, dstlen + 2, d)); d[dstlen] = '\0'; d[dstlen + 1] = '\0'; @@ -1178,8 +1178,8 @@ ParseError MysqlReply::Field::ParseBinaryDataTime(butil::IOBuf& buf, const uint64_t len = parse_encode_length(buf); // A length of 0, 4, 7 or 11 are the only legal binary DATE/DATETIME/ // TIMESTAMP encodings. Reject anything else rather than over-reading. - // NOTE: len == 0 is NOT a NULL value (NULL is signalled by the row - // NULL-bitmap, handled by the caller before we are reached); it is the zero + // NOTE: len == 0 is NOT a nullptr value (nullptr is signalled by the row + // nullptr-bitmap, handled by the caller before we are reached); it is the zero // value "0000-00-00 00:00:00" (or "0000-00-00" for DATE) with no field // bytes on the wire. if (len != 0 && len != 4 && len != 7 && len != 11) { @@ -1224,7 +1224,7 @@ ParseError MysqlReply::Field::ParseBinaryDataTime(butil::IOBuf& buf, } size_t i = 0; - char* d = NULL; + char* d = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, dstlen, d)); // Read only the fields present for this `len`; absent fields are 0. // len == 0 -> no bytes (all-zero value). @@ -1392,8 +1392,8 @@ ParseError MysqlReply::ResultSet::Parse(butil::IOBuf& buf, butil::Arena* arena, break; } // allocate memory for row and fields - Row* row = NULL; - Field* fields = NULL; + Row* row = nullptr; + Field* fields = nullptr; MY_ALLOC_CHECK(my_alloc_check(arena, 1, row)); MY_ALLOC_CHECK(my_alloc_check(arena, _header._column_count, fields)); row->_fields = fields; diff --git a/src/brpc/policy/mysql/mysql_reply.h b/src/brpc/policy/mysql/mysql_reply.h index 2cb90528fa..14bf0dbd26 100644 --- a/src/brpc/policy/mysql/mysql_reply.h +++ b/src/brpc/policy/mysql/mysql_reply.h @@ -298,7 +298,7 @@ class MysqlReply { float float32; double float64; butil::StringPiece str; - } _data = {.str = NULL}; + } _data = {.str = nullptr}; MysqlFieldType _type; bool _unsigned; bool _is_nil; @@ -374,7 +374,7 @@ class MysqlReply { }; // Mysql result set struct ResultSet : private CheckParsed { - ResultSet() : _columns(NULL), _row_count(0) { + ResultSet() : _columns(nullptr), _row_count(0) { _cur = _first = _last = &_dummy; } ParseError Parse(butil::IOBuf& buf, butil::Arena* arena, bool binary); @@ -589,7 +589,7 @@ inline uint8_t MysqlReply::AuthMoreData::seq() const { return _seq; } // mysql prepared statement ok -inline MysqlReply::PrepareOk::PrepareOk() : _params(NULL), _columns(NULL) {} +inline MysqlReply::PrepareOk::PrepareOk() : _params(nullptr), _columns(nullptr) {} inline uint32_t MysqlReply::PrepareOk::stmt_id() const { CHECK(_header._stmt_id > 0) << "stmt id is wrong"; return _header._stmt_id; @@ -691,7 +691,7 @@ inline uint8_t MysqlReply::Column::decimal() const { return _decimal; } // mysql reply row -inline MysqlReply::Row::Row() : _fields(NULL), _field_count(0), _next(NULL) {} +inline MysqlReply::Row::Row() : _fields(nullptr), _field_count(0), _next(nullptr) {} inline uint64_t MysqlReply::Row::field_count() const { return _field_count; } diff --git a/src/brpc/policy/mysql/mysql_statement.cpp b/src/brpc/policy/mysql/mysql_statement.cpp index 5f41088ab8..d4018c8ed8 100644 --- a/src/brpc/policy/mysql/mysql_statement.cpp +++ b/src/brpc/policy/mysql/mysql_statement.cpp @@ -46,7 +46,7 @@ uint32_t MysqlStatement::StatementId(SocketId socket_id) const { return 0; } const MysqlStatementId* p = ptr->seek(socket_id); - if (p == NULL) { + if (p == nullptr) { LOG(WARNING) << "MysqlStatement::StatementId: no prepared statement id " "cached for socket_id=" << socket_id << " (statement not found / not prepared on this " diff --git a/src/brpc/policy/mysql/mysql_statement_inl.h b/src/brpc/policy/mysql/mysql_statement_inl.h index 3e1323c87a..9dbf07f52e 100644 --- a/src/brpc/policy/mysql/mysql_statement_inl.h +++ b/src/brpc/policy/mysql/mysql_statement_inl.h @@ -45,7 +45,7 @@ inline size_t my_init_kv(MysqlStatementKVMap& m) { inline size_t my_update_kv(MysqlStatementKVMap& m, SocketId key, MysqlStatementId value) { MysqlStatementId* p = m.seek(key); - if (p == NULL) { + if (p == nullptr) { m.insert(key, value); } else { *p = value; diff --git a/src/brpc/policy/mysql/mysql_transaction.cpp b/src/brpc/policy/mysql/mysql_transaction.cpp index 58871dd952..267ba00961 100644 --- a/src/brpc/policy/mysql/mysql_transaction.cpp +++ b/src/brpc/policy/mysql/mysql_transaction.cpp @@ -36,14 +36,14 @@ SocketId MysqlTransaction::GetSocketId() const { bool MysqlTransaction::DoneTransaction(const char* command) { bool rc = false; MysqlRequest request(this); - if (_socket == NULL) { // must already commit or rollback, return true. + if (_socket == nullptr) { // must already commit or rollback, return true. return true; } else if (!request.Query(command)) { LOG(ERROR) << "Fail to query command" << command; } else { MysqlResponse response; Controller cntl; - _channel.CallMethod(NULL, &cntl, &request, &response, NULL); + _channel.CallMethod(nullptr, &cntl, &request, &response, nullptr); if (!cntl.Failed()) { if (response.reply(0).is_ok()) { rc = true; @@ -67,7 +67,7 @@ MysqlTransactionUniquePtr NewMysqlTransaction(Channel& channel, if (channel.options().connection_type == CONNECTION_TYPE_SINGLE) { LOG(ERROR) << "mysql transaction can't use connection type 'single'"; - return NULL; + return nullptr; } std::stringstream ss; // repeatable read is mysql default isolation level, so ignore it. @@ -85,21 +85,21 @@ MysqlTransactionUniquePtr NewMysqlTransaction(Channel& channel, MysqlRequest request; if (!request.Query(ss.str())) { LOG(ERROR) << "Fail to query command" << ss.str(); - return NULL; + return nullptr; } MysqlTransactionUniquePtr tx; MysqlResponse response; Controller cntl; ControllerPrivateAccessor(&cntl).set_bind_sock_action(BIND_SOCK_RESERVE); - channel.CallMethod(NULL, &cntl, &request, &response, NULL); + channel.CallMethod(nullptr, &cntl, &request, &response, nullptr); if (!cntl.Failed()) { // repeatable read isolation send one reply, other isolation has two reply if ((opts.isolation_level == MysqlIsoRepeatableRead && response.reply(0).is_ok()) || (response.reply(0).is_ok() && response.reply(1).is_ok())) { SocketUniquePtr socket; ControllerPrivateAccessor(&cntl).get_bind_sock(&socket); - if (socket == NULL) { + if (socket == nullptr) { LOG(ERROR) << "Fail create mysql transaction, get bind socket failed"; } else { tx.reset(new MysqlTransaction(channel, socket, cntl.connection_type())); @@ -111,7 +111,7 @@ MysqlTransactionUniquePtr NewMysqlTransaction(Channel& channel, // ref (which would leak the pooled connection). SocketUniquePtr socket; ControllerPrivateAccessor(&cntl).get_bind_sock(&socket); - if (socket != NULL && cntl.connection_type() == CONNECTION_TYPE_POOLED) { + if (socket != nullptr && cntl.connection_type() == CONNECTION_TYPE_POOLED) { socket->ReturnToPool(); } LOG(ERROR) << "Fail create mysql transaction, " << response; diff --git a/src/brpc/policy/nacos_naming_service.cpp b/src/brpc/policy/nacos_naming_service.cpp index c4cc46b225..95c3e4d537 100644 --- a/src/brpc/policy/nacos_naming_service.cpp +++ b/src/brpc/policy/nacos_naming_service.cpp @@ -97,7 +97,7 @@ int NacosNamingService::RefreshAccessToken(const char *service_name) { auto iter_ttl = doc.FindMember("tokenTtl"); if (iter_ttl != doc.MemberEnd() && iter_ttl->value.IsInt()) { - _token_expire_time = time(NULL) + iter_ttl->value.GetInt() - 10; + _token_expire_time = time(nullptr) + iter_ttl->value.GetInt() - 10; } else { _token_expire_time = 0; } @@ -257,7 +257,7 @@ int NacosNamingService::GetServers(const char *service_name, !FLAGS_nacos_username.empty() && !FLAGS_nacos_password.empty(); const bool has_invalid_access_token = _access_token.empty() || - (0 < _token_expire_time && _token_expire_time <= time(NULL)); + (0 < _token_expire_time && _token_expire_time <= time(nullptr)); bool token_changed = false; if (authentiction_enabled && has_invalid_access_token) { diff --git a/src/brpc/policy/nova_pbrpc_protocol.cpp b/src/brpc/policy/nova_pbrpc_protocol.cpp index a1d88f2562..224da322d1 100644 --- a/src/brpc/policy/nova_pbrpc_protocol.cpp +++ b/src/brpc/policy/nova_pbrpc_protocol.cpp @@ -112,7 +112,7 @@ void ProcessNovaResponse(InputMessageBase* msg_base) { // Fetch correlation id that we saved before in `PackNovaRequest' const bthread_id_t cid = { static_cast(socket->correlation_id()) }; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -131,7 +131,7 @@ void ProcessNovaResponse(InputMessageBase* msg_base) { // Fetch compress flag from nshead char buf[sizeof(nshead_t)]; const char *p = (const char *)msg->meta.fetch(buf, sizeof(buf)); - if (NULL == p) { + if (nullptr == p) { LOG(WARNING) << "Fail to fetch nshead from client=" << socket->remote_side(); return; diff --git a/src/brpc/policy/nshead_mcpack_protocol.cpp b/src/brpc/policy/nshead_mcpack_protocol.cpp index 8ba49f936e..d242808f65 100644 --- a/src/brpc/policy/nshead_mcpack_protocol.cpp +++ b/src/brpc/policy/nshead_mcpack_protocol.cpp @@ -82,7 +82,7 @@ void NsheadMcpackAdaptor::SerializeResponseToIOBuf( type = COMPRESS_TYPE_NONE; } - if (pb_res == NULL) { + if (pb_res == nullptr) { cntl->CloseConnection("response was not created yet"); return; } @@ -103,7 +103,7 @@ void ProcessNsheadMcpackResponse(InputMessageBase* msg_base) { // Fetch correlation id that we saved before in `PackNsheadMcpackRequest' const bthread_id_t cid = { static_cast(socket->correlation_id()) }; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -120,7 +120,7 @@ void ProcessNsheadMcpackResponse(InputMessageBase* msg_base) { } const int saved_error = cntl->ErrorCode(); google::protobuf::Message* res = cntl->response(); - if (res == NULL) { + if (res == nullptr) { // silently ignore response. return; } diff --git a/src/brpc/policy/nshead_protocol.cpp b/src/brpc/policy/nshead_protocol.cpp index 82f696e3c2..72fc89947d 100644 --- a/src/brpc/policy/nshead_protocol.cpp +++ b/src/brpc/policy/nshead_protocol.cpp @@ -42,7 +42,7 @@ void bthread_assign_data(void* data); namespace brpc { NsheadClosure::NsheadClosure(void* additional_space) - : _server(NULL) + : _server(nullptr) , _received_us(0) , _do_respond(true) , _additional_space(additional_space) { @@ -231,7 +231,7 @@ void ProcessNsheadRequest(InputMessageBase* msg_base) { const nshead_t *req_head = (const nshead_t *)p; NsheadService* service = server->options().nshead_service; - if (service == NULL) { + if (service == nullptr) { LOG_EVERY_SECOND(WARNING) << "Received nshead request however the server does not set" " ServerOptions.nshead_service, close the connection."; @@ -261,7 +261,7 @@ void ProcessNsheadRequest(InputMessageBase* msg_base) { CHECK(method_status->OnRequested()); } - void* sub_space = NULL; + void* sub_space = nullptr; if (service->_additional_space) { sub_space = (char*)space + sizeof(NsheadClosure); } @@ -359,7 +359,7 @@ void ProcessNsheadResponse(InputMessageBase* msg_base) { // Fetch correlation id that we saved before in `PackNsheadRequest' const CallId cid = { static_cast(msg->socket()->correlation_id()) }; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -377,7 +377,7 @@ void ProcessNsheadResponse(InputMessageBase* msg_base) { // MUST be NsheadMessage (checked in SerializeNsheadRequest) NsheadMessage* response = (NsheadMessage*)cntl->response(); const int saved_error = cntl->ErrorCode(); - if (response != NULL) { + if (response != nullptr) { msg->meta.copy_to(&response->head, sizeof(nshead_t)); msg->payload.swap(response->body); } // else just ignore the response. @@ -399,13 +399,13 @@ bool VerifyNsheadRequest(const InputMessageBase* msg_base) { void SerializeNsheadRequest(butil::IOBuf* request_buf, Controller* cntl, const google::protobuf::Message* req_base) { - if (req_base == NULL) { + if (req_base == nullptr) { return cntl->SetFailed(EREQUEST, "request is NULL"); } if (req_base->GetDescriptor() != NsheadMessage::descriptor()) { return cntl->SetFailed(EINVAL, "Type of request must be NsheadMessage"); } - if (cntl->response() != NULL && + if (cntl->response() != nullptr && cntl->response()->GetDescriptor() != NsheadMessage::descriptor()) { return cntl->SetFailed(EINVAL, "Type of response must be NsheadMessage"); } diff --git a/src/brpc/policy/p2c_ewma_load_balancer.cpp b/src/brpc/policy/p2c_ewma_load_balancer.cpp index 2b3f5bb594..bd71d34fdf 100644 --- a/src/brpc/policy/p2c_ewma_load_balancer.cpp +++ b/src/brpc/policy/p2c_ewma_load_balancer.cpp @@ -72,12 +72,12 @@ bool P2CEwmaLoadBalancer::Add(Servers& bg, const Servers& fg, if (bg.server_list.capacity() < 128) { bg.server_list.reserve(128); } - if (bg.server_map.seek(id.id) != NULL) { + if (bg.server_map.seek(id.id) != nullptr) { return false; } - ServerInfo info = { id.id, WeightOfTag(id.tag), NULL }; + ServerInfo info = { id.id, WeightOfTag(id.tag), nullptr }; const size_t* pindex = fg.server_map.seek(id.id); - if (pindex == NULL) { + if (pindex == nullptr) { // Both buffers do not have the server. Create the stat structure // which will be shared by both buffers. info.stat = std::make_shared(); @@ -92,7 +92,7 @@ bool P2CEwmaLoadBalancer::Add(Servers& bg, const Servers& fg, bool P2CEwmaLoadBalancer::Remove(Servers& bg, const ServerId& id) { size_t* pindex = bg.server_map.seek(id.id); - if (pindex == NULL) { + if (pindex == nullptr) { return false; } const size_t index = *pindex; @@ -181,7 +181,7 @@ int P2CEwmaLoadBalancer::SelectServer(const SelectIn& in, SelectOut* out) { const int64_t now_us = in.begin_time_us > 0 ? in.begin_time_us : butil::gettimeofday_us(); - const ServerInfo* best = NULL; + const ServerInfo* best = nullptr; double best_score = 0; SocketUniquePtr best_ptr; // Score the server at `index' and keep it if it beats the current best. @@ -196,7 +196,7 @@ int P2CEwmaLoadBalancer::SelectServer(const SelectIn& in, SelectOut* out) { return; } const double score = Score(info, now_us); - if (best == NULL || score < best_score) { + if (best == nullptr || score < best_score) { best = &info; best_score = score; best_ptr.swap(ptr); @@ -233,7 +233,7 @@ int P2CEwmaLoadBalancer::SelectServer(const SelectIn& in, SelectOut* out) { chosen[nchosen++] = index; consider(index); } - if (best == NULL) { + if (best == nullptr) { // All sampled servers were excluded or unavailable, fall back // to scoring the whole list before violating exclusion below. for (size_t i = 0; i < n; ++i) { @@ -242,7 +242,7 @@ int P2CEwmaLoadBalancer::SelectServer(const SelectIn& in, SelectOut* out) { } } - if (best == NULL) { + if (best == nullptr) { // Always take last chance: all servers are excluded, send to any // available one as rr/random do. for (size_t i = 0; i < n; ++i) { @@ -251,7 +251,7 @@ int P2CEwmaLoadBalancer::SelectServer(const SelectIn& in, SelectOut* out) { break; } } - if (best == NULL) { + if (best == nullptr) { return EHOSTDOWN; } } @@ -269,7 +269,7 @@ void P2CEwmaLoadBalancer::Feedback(const CallInfo& info) { return; } const size_t* pindex = s->server_map.seek(info.server_id); - if (pindex == NULL) { + if (pindex == nullptr) { // The server was removed after selection, its stat is gone with it. return; } @@ -317,10 +317,10 @@ void P2CEwmaLoadBalancer::Feedback(const CallInfo& info) { P2CEwmaLoadBalancer* P2CEwmaLoadBalancer::New( const butil::StringPiece& params) const { - P2CEwmaLoadBalancer* lb = new (std::nothrow) P2CEwmaLoadBalancer; - if (lb != NULL && !lb->SetParameters(params)) { + P2CEwmaLoadBalancer* lb = new P2CEwmaLoadBalancer; + if (!lb->SetParameters(params)) { delete lb; - lb = NULL; + lb = nullptr; } return lb; } diff --git a/src/brpc/policy/public_pbrpc_protocol.cpp b/src/brpc/policy/public_pbrpc_protocol.cpp index a4298a15da..111a863e91 100644 --- a/src/brpc/policy/public_pbrpc_protocol.cpp +++ b/src/brpc/policy/public_pbrpc_protocol.cpp @@ -74,7 +74,7 @@ void PublicPbrpcServiceAdaptor::ParseNsheadMeta( const RequestBody& body = pbreq.requestbody(0); const Server::MethodProperty *sp = ServerPrivateAccessor(&svr) .FindMethodPropertyByNameAndIndex(body.service(), body.method_id()); - if (NULL == sp) { + if (nullptr == sp) { cntl->SetFailed(ENOMETHOD, "Fail to find method by service=%s method_id=%u", body.service().c_str(), body.method_id()); return; @@ -165,7 +165,7 @@ void ProcessPublicPbrpcResponse(InputMessageBase* msg_base) { const ResponseHead& head = pbres.responsehead(); const ResponseBody& body = pbres.responsebody(0); const bthread_id_t cid = { static_cast(body.id()) }; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -241,7 +241,7 @@ void PackPublicPbrpcRequest(butil::IOBuf* buf, head->set_connection(!short_connection); head->set_charset(CHARSET); char time_buf[128]; - time_t now = time(NULL); + time_t now = time(nullptr); strftime(time_buf, sizeof(time_buf), TIME_FORMAT, localtime(&now)); head->set_create_time(time_buf); if (controller->has_log_id()) { diff --git a/src/brpc/policy/randomized_load_balancer.cpp b/src/brpc/policy/randomized_load_balancer.cpp index 4ff43d753f..a76eaa91b6 100644 --- a/src/brpc/policy/randomized_load_balancer.cpp +++ b/src/brpc/policy/randomized_load_balancer.cpp @@ -134,10 +134,10 @@ int RandomizedLoadBalancer::SelectServer(const SelectIn& in, SelectOut* out) { RandomizedLoadBalancer* RandomizedLoadBalancer::New( const butil::StringPiece& params) const { - RandomizedLoadBalancer* lb = new (std::nothrow) RandomizedLoadBalancer; - if (lb && !lb->SetParameters(params)) { + RandomizedLoadBalancer* lb = new RandomizedLoadBalancer; + if (!lb->SetParameters(params)) { delete lb; - lb = NULL; + lb = nullptr; } return lb; } diff --git a/src/brpc/policy/redis_protocol.cpp b/src/brpc/policy/redis_protocol.cpp index 7dc5b5b8f3..3009d7b7aa 100644 --- a/src/brpc/policy/redis_protocol.cpp +++ b/src/brpc/policy/redis_protocol.cpp @@ -64,7 +64,7 @@ int ConsumeCommand(RedisConnContext* ctx, if (ctx->transaction_handler) { result = ctx->transaction_handler->Run(ctx, args, &output, flush_batched); if (result == REDIS_CMD_HANDLED) { - ctx->transaction_handler.reset(NULL); + ctx->transaction_handler.reset(nullptr); } else if (result == REDIS_CMD_BATCHED) { LOG(ERROR) << "BATCHED should not be returned by a transaction handler."; return -1; @@ -126,7 +126,7 @@ ParseResult ParseRedisMessage(butil::IOBuf* source, Socket* socket, return MakeParseError(PARSE_ERROR_TRY_OTHERS); } RedisConnContext* ctx = static_cast(socket->parsing_context()); - if (ctx == NULL) { + if (ctx == nullptr) { ctx = new RedisConnContext(rs); socket->reset_parsing_context(ctx); } @@ -182,7 +182,7 @@ ParseResult ParseRedisMessage(butil::IOBuf* source, Socket* socket, do { InputResponse* msg = static_cast(socket->parsing_context()); - if (msg == NULL) { + if (msg == nullptr) { msg = new InputResponse; socket->reset_parsing_context(msg); } @@ -228,7 +228,7 @@ void ProcessRedisResponse(InputMessageBase* msg_base) { DestroyingPtr msg(static_cast(msg_base)); const bthread_id_t cid = msg->id_wait; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -244,7 +244,7 @@ void ProcessRedisResponse(InputMessageBase* msg_base) { span->set_start_parse_us(start_parse_us); } const int saved_error = cntl->ErrorCode(); - if (cntl->response() != NULL) { + if (cntl->response() != nullptr) { if (cntl->response()->GetDescriptor() != RedisResponse::descriptor()) { cntl->SetFailed(ERESPONSE, "Must be RedisResponse"); } else { @@ -273,7 +273,7 @@ void ProcessRedisRequest(InputMessageBase* msg_base) { } void SerializeRedisRequest(butil::IOBuf* buf, Controller* cntl, const google::protobuf::Message* request) { - if (request == NULL) { + if (request == nullptr) { return cntl->SetFailed(EREQUEST, "request is NULL"); } if (request->GetDescriptor() != RedisRequest::descriptor()) { @@ -310,7 +310,7 @@ void PackRedisRequest(butil::IOBuf* buf, buf->append(auth_str); const RedisAuthenticator* redis_auth = dynamic_cast(auth); - if (redis_auth == NULL) { + if (redis_auth == nullptr) { return cntl->SetFailed(EREQUEST, "Fail to generate credential"); } ControllerPrivateAccessor(cntl).set_auth_flags( diff --git a/src/brpc/policy/remote_file_naming_service.cpp b/src/brpc/policy/remote_file_naming_service.cpp index c5aeac9e75..b2e929544b 100644 --- a/src/brpc/policy/remote_file_naming_service.cpp +++ b/src/brpc/policy/remote_file_naming_service.cpp @@ -61,7 +61,7 @@ int RemoteFileNamingService::GetServers(const char *service_name_cstr, std::vector* servers) { servers->clear(); - if (_channel == NULL) { + if (_channel == nullptr) { butil::StringPiece tmpname(service_name_cstr); size_t pos = tmpname.find("://"); butil::StringPiece proto; @@ -105,7 +105,7 @@ int RemoteFileNamingService::GetServers(const char *service_name_cstr, Controller cntl; cntl.http_request().uri() = _path; - _channel->CallMethod(NULL, &cntl, NULL, NULL, NULL); + _channel->CallMethod(nullptr, &cntl, nullptr, nullptr, nullptr); if (cntl.Failed()) { LOG(WARNING) << "Fail to access " << _server_addr << _path << ": " << cntl.ErrorText(); diff --git a/src/brpc/policy/round_robin_load_balancer.cpp b/src/brpc/policy/round_robin_load_balancer.cpp index cf67624085..c219808b6a 100644 --- a/src/brpc/policy/round_robin_load_balancer.cpp +++ b/src/brpc/policy/round_robin_load_balancer.cpp @@ -134,10 +134,10 @@ int RoundRobinLoadBalancer::SelectServer(const SelectIn& in, SelectOut* out) { RoundRobinLoadBalancer* RoundRobinLoadBalancer::New( const butil::StringPiece& params) const { - RoundRobinLoadBalancer* lb = new (std::nothrow) RoundRobinLoadBalancer; - if (lb && !lb->SetParameters(params)) { + RoundRobinLoadBalancer* lb = new RoundRobinLoadBalancer; + if (!lb->SetParameters(params)) { delete lb; - lb = NULL; + lb = nullptr; } return lb; } diff --git a/src/brpc/policy/rtmp_protocol.cpp b/src/brpc/policy/rtmp_protocol.cpp index c5ece81ae1..2b50c6a3f0 100644 --- a/src/brpc/policy/rtmp_protocol.cpp +++ b/src/brpc/policy/rtmp_protocol.cpp @@ -106,7 +106,7 @@ static const size_t MAGIC_NUMBER_SIZE = 4; /* magic number */ // ========== The handshaking described in RTMP spec ========== // The random data for handshaking -static butil::IOBuf* s_rtmp_handshake_server_random = NULL; +static butil::IOBuf* s_rtmp_handshake_server_random = nullptr; static pthread_once_t s_sr_once = PTHREAD_ONCE_INIT; static void InitRtmpHandshakeServerRandom() { char buf[1528]; @@ -121,7 +121,7 @@ static const butil::IOBuf& GetRtmpHandshakeServerRandom() { return *s_rtmp_handshake_server_random; } -static butil::IOBuf* s_rtmp_handshake_client_random = NULL; +static butil::IOBuf* s_rtmp_handshake_client_random = nullptr; static pthread_once_t s_cr_once = PTHREAD_ONCE_INIT; static void InitRtmpHandshakeClientRandom() { char buf[1528]; @@ -147,16 +147,16 @@ namespace adobe_hs { // Modified from code in SRS2 (src/protocol/srs_rtmp_handshake.cpp:94) int openssl_HMACsha256(const void* key, int key_size, const void* data, int data_size, void* digest) { - if (NULL == EVP_sha256) { + if (nullptr == EVP_sha256) { LOG_ONCE(ERROR) << "Fail to find EVP_sha256, fall back to simple handshaking"; return -1; } unsigned int digest_size = 0; unsigned char* temp_digest = (unsigned char*)digest; - if (key == NULL) { + if (key == nullptr) { // NOTE: first parameter of EVP_Digest in older openssl is void*. if (EVP_Digest(const_cast(data), data_size, temp_digest, - &digest_size, EVP_sha256(), NULL) < 0) { + &digest_size, EVP_sha256(), nullptr) < 0) { LOG(ERROR) << "Fail to EVP_Digest"; return -1; } @@ -165,7 +165,7 @@ int openssl_HMACsha256(const void* key, int key_size, // inconsistent in different version of openssl. if (HMAC(EVP_sha256(), key, key_size, (const unsigned char*) data, data_size, - temp_digest, &digest_size) == NULL) { + temp_digest, &digest_size) == nullptr) { LOG(ERROR) << "Fail to HMAC"; return -1; } @@ -431,7 +431,7 @@ bool C1S1Base::ComputeDigestBase(const void* key, int key_size, bool C1::Generate(C1S1Schema schema) { _schema = schema; - time = ::time(NULL); + time = ::time(nullptr); version = FP_VERSION; key_blk.Generate(); digest_blk.Generate(); @@ -473,7 +473,7 @@ bool C1::Load(const void* buf) { bool S1::Generate(const C1& c1) { _schema = c1.schema(); - time = ::time(NULL); + time = ::time(nullptr); version = FMS_VERSION; key_blk.Generate(); digest_blk.Generate(); @@ -710,7 +710,7 @@ RtmpUnsentMessage* MakeUnsentControlMessage( RtmpContext::RtmpContext(const RtmpClientOptions* copt, const Server* server) : _state(RtmpContext::STATE_UNINITIALIZED) - , _s1_digest(NULL) + , _s1_digest(nullptr) , _chunk_size_out(RTMP_INITIAL_CHUNK_SIZE) , _chunk_size_in(RTMP_INITIAL_CHUNK_SIZE) , _window_ack_size(RTMP_DEFAULT_WINDOW_ACK_SIZE) @@ -719,12 +719,12 @@ RtmpContext::RtmpContext(const RtmpClientOptions* copt, const Server* server) , _cs_id_allocator(RTMP_CONTROL_CHUNK_STREAM_ID + 1) , _ms_id_allocator(RTMP_CONTROL_MESSAGE_STREAM_ID + 1) , _client_options(copt) - , _on_connect(NULL) - , _on_connect_arg(NULL) + , _on_connect(nullptr) + , _on_connect_arg(nullptr) , _only_check_simple_s0s1(false) , _create_stream_with_play_or_publish(false) , _server(server) - , _service(NULL) + , _service(nullptr) , _trans_id_allocator(2) , _simplified_rtmp(false) { if (server) { @@ -771,13 +771,13 @@ RtmpContext::~RtmpContext() { for (size_t i = 0; i < RTMP_CHUNK_ARRAY_1ST_SIZE; ++i) { SubChunkArray* p = _cstream_ctx[i].load(butil::memory_order_relaxed); if (p) { - _cstream_ctx[i].store(NULL, butil::memory_order_relaxed); + _cstream_ctx[i].store(nullptr, butil::memory_order_relaxed); delete p; } } free(_s1_digest); - _s1_digest = NULL; + _s1_digest = nullptr; } void RtmpContext::Destroy() { @@ -787,13 +787,13 @@ void RtmpContext::Destroy() { butil::Status RtmpUnsentMessage::AppendAndDestroySelf(butil::IOBuf* out, Socket* s) { std::unique_ptr destroy_self(this); - if (s == NULL) { // abandoned + if (s == nullptr) { // abandoned RPC_VLOG << "Socket=NULL"; return butil::Status::OK(); } RtmpContext* ctx = static_cast(s->parsing_context()); RtmpChunkStream* cstream = ctx->GetChunkStream(chunk_stream_id); - if (cstream == NULL) { + if (cstream == nullptr) { s->SetFailed(EINVAL, "Invalid chunk_stream_id=%u", chunk_stream_id); return butil::Status(EINVAL, "Invalid chunk_stream_id=%u", chunk_stream_id); } @@ -820,7 +820,7 @@ RtmpContext::SubChunkArray::~SubChunkArray() { for (size_t i = 0; i < RTMP_CHUNK_ARRAY_2ND_SIZE; ++i) { RtmpChunkStream* stream = ptrs[i].load(butil::memory_order_relaxed); if (stream) { - ptrs[i].store(NULL, butil::memory_order_relaxed); + ptrs[i].store(nullptr, butil::memory_order_relaxed); delete stream; } } @@ -829,15 +829,15 @@ RtmpContext::SubChunkArray::~SubChunkArray() { RtmpChunkStream* RtmpContext::GetChunkStream(uint32_t cs_id) { if (cs_id > RTMP_MAX_CHUNK_STREAM_ID) { LOG(ERROR) << "Invalid chunk_stream_id=" << cs_id; - return NULL; + return nullptr; } const uint32_t index1 = cs_id / RTMP_CHUNK_ARRAY_2ND_SIZE; SubChunkArray* sub_array = _cstream_ctx[index1].load(butil::memory_order_consume); - if (sub_array == NULL) { + if (sub_array == nullptr) { // Optimistic creation. sub_array = new SubChunkArray; - SubChunkArray* expected = NULL; + SubChunkArray* expected = nullptr; if (!_cstream_ctx[index1].compare_exchange_strong( expected, sub_array, butil::memory_order_acq_rel)) { delete sub_array; @@ -847,10 +847,10 @@ RtmpChunkStream* RtmpContext::GetChunkStream(uint32_t cs_id) { const uint32_t index2 = cs_id - index1 * RTMP_CHUNK_ARRAY_2ND_SIZE; RtmpChunkStream* cstream = sub_array->ptrs[index2].load(butil::memory_order_consume); - if (cstream == NULL) { + if (cstream == nullptr) { // Optimistic creation. cstream = new RtmpChunkStream(this, cs_id); - RtmpChunkStream* expected = NULL; + RtmpChunkStream* expected = nullptr; if (!sub_array->ptrs[index2].compare_exchange_strong( expected, cstream, butil::memory_order_acq_rel)) { delete cstream; @@ -868,19 +868,19 @@ void RtmpContext::ClearChunkStream(uint32_t cs_id) { const uint32_t index1 = cs_id / RTMP_CHUNK_ARRAY_2ND_SIZE; SubChunkArray* sub_array = _cstream_ctx[index1].load(butil::memory_order_consume); - if (sub_array == NULL) { + if (sub_array == nullptr) { LOG(ERROR) << "chunk_stream_id=" << cs_id << " does not exist"; return; } const uint32_t index2 = cs_id - index1 * RTMP_CHUNK_ARRAY_2ND_SIZE; RtmpChunkStream* cstream = sub_array->ptrs[index2].load(butil::memory_order_consume); - if (cstream == NULL) { + if (cstream == nullptr) { LOG(ERROR) << "chunk_stream_id=" << cs_id << " does not exist"; return; } delete sub_array->ptrs[index2].exchange( - NULL, butil::memory_order_acquire); + nullptr, butil::memory_order_acquire); } void RtmpContext::AllocateChunkStreamId(uint32_t* chunk_stream_id) { @@ -921,7 +921,7 @@ bool RtmpContext::FindMessageStream( uint32_t stream_id, butil::intrusive_ptr* stream) { BAIDU_SCOPED_LOCK(_stream_mutex); MessageStreamInfo* info = _mstream_map.seek(stream_id); - if (info == NULL || info->stream == NULL) { + if (info == nullptr || info->stream == nullptr) { return false; } *stream = info->stream; @@ -939,7 +939,7 @@ bool RtmpContext::AddClientStream(RtmpStreamBase* stream) { { std::unique_lock mu(_stream_mutex); MessageStreamInfo& info = _mstream_map[stream_id]; - if (info.stream != NULL) { + if (info.stream != nullptr) { mu.unlock(); LOG(ERROR) << "stream_id=" << stream_id << " is already used"; return false; @@ -959,7 +959,7 @@ bool RtmpContext::AddServerStream(RtmpStreamBase* stream) { return false; } MessageStreamInfo& info = _mstream_map[stream_id]; - if (info.stream != NULL) { + if (info.stream != nullptr) { mu.unlock(); LOG(ERROR) << "stream_id=" << stream_id << " is already used"; return false; @@ -972,7 +972,7 @@ bool RtmpContext::AddServerStream(RtmpStreamBase* stream) { } bool RtmpContext::RemoveMessageStream(RtmpStreamBase* stream) { - if (stream == NULL) { + if (stream == nullptr) { LOG(FATAL) << "Param[stream] is NULL"; return false; } @@ -987,7 +987,7 @@ bool RtmpContext::RemoveMessageStream(RtmpStreamBase* stream) { { std::unique_lock mu(_stream_mutex); MessageStreamInfo* info = _mstream_map.seek(stream_id); - if (info == NULL) { + if (info == nullptr) { mu.unlock(); return false; } @@ -1026,7 +1026,7 @@ bool RtmpContext::AddTransaction(uint32_t* out_transaction_id, continue; } step *= 2; // 1,2,4,8,16,32,64,128,256,512,1024 - if (_trans_map.seek(transaction_id) == NULL) { + if (_trans_map.seek(transaction_id) == nullptr) { _trans_map[transaction_id] = handler; *out_transaction_id = transaction_id; return true; @@ -1037,11 +1037,11 @@ bool RtmpContext::AddTransaction(uint32_t* out_transaction_id, RtmpTransactionHandler* RtmpContext::RemoveTransaction(uint32_t transaction_id) { - RtmpTransactionHandler* handler = NULL; + RtmpTransactionHandler* handler = nullptr; { BAIDU_SCOPED_LOCK(_trans_mutex); RtmpTransactionHandler** phandler = _trans_map.seek(transaction_id); - if (phandler != NULL) { + if (phandler != nullptr) { handler = *phandler; _trans_map.erase(transaction_id); } @@ -1209,7 +1209,7 @@ ParseResult RtmpContext::WaitForC0C1orSimpleRtmp(butil::IOBuf* source, Socket* s s1.Save(buf); tmp.append(buf, RTMP_HANDSHAKE_SIZE1); _s1_digest = malloc(adobe_hs::DigestBlock::DIGEST_SIZE); - if (_s1_digest == NULL) { + if (_s1_digest == nullptr) { LOG(ERROR) << "Fail to malloc"; return MakeParseError(PARSE_ERROR_NO_RESOURCE); } @@ -1329,7 +1329,7 @@ ParseResult RtmpContext::WaitForS2(butil::IOBuf* source, Socket* socket) { ParseResult RtmpContext::OnChunks(butil::IOBuf* source, Socket* socket) { // Parse basic header. const char* p = (const char*)source->fetch1(); - if (NULL == p) { + if (nullptr == p) { return MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA); } const uint8_t first_byte = *p; @@ -1357,7 +1357,7 @@ ParseResult RtmpContext::OnChunks(butil::IOBuf* source, Socket* socket) { } // else 1-byte basic header, keep cs_id as it is. RtmpBasicHeader bh = { cs_id, fmt, basic_header_len }; RtmpChunkStream* cstream = GetChunkStream(cs_id); - if (cstream == NULL) { + if (cstream == nullptr) { LOG(ERROR) << "Invalid chunk_stream_id=" << cs_id; return MakeParseError(PARSE_ERROR_NO_RESOURCE); } @@ -1400,14 +1400,14 @@ RtmpChunkStream::WriteParams::WriteParams() , last_timestamp_delta(0) { } -MethodStatus* g_client_msg_status = NULL; +MethodStatus* g_client_msg_status = nullptr; static pthread_once_t g_client_msg_status_once = PTHREAD_ONCE_INIT; static void InitClientMessageStatus() { g_client_msg_status = new MethodStatus; g_client_msg_status->Expose("rtmp_client_in"); } -MethodStatus* g_server_msg_status = NULL; +MethodStatus* g_server_msg_status = nullptr; static pthread_once_t g_server_msg_status_once = PTHREAD_ONCE_INIT; static void InitServerMessageStatus() { g_server_msg_status = new MethodStatus; @@ -1619,8 +1619,8 @@ ParseResult RtmpChunkStream::Feed(const RtmpBasicHeader& bh, AddChunk(); if (_r.left_message_length == 0) { - MethodStatus* st = NULL; - if (ctx->service() != NULL) { + MethodStatus* st = nullptr; + if (ctx->service() != nullptr) { pthread_once(&g_server_msg_status_once, InitServerMessageStatus); st = g_server_msg_status; } else { @@ -1643,7 +1643,7 @@ ParseResult RtmpChunkStream::Feed(const RtmpBasicHeader& bh, } else { _r.first_chunk_of_message = false; } - return MakeMessage(NULL); + return MakeMessage(nullptr); } int RtmpChunkStream::SerializeMessage(butil::IOBuf* buf, @@ -1746,26 +1746,26 @@ static const RtmpChunkStream::MessageHandler s_msg_handlers[] = { &RtmpChunkStream::OnUserControlMessage, // 4 &RtmpChunkStream::OnWindowAckSize,// 5 &RtmpChunkStream::OnSetPeerBandwidth, // 6 - NULL, //7 + nullptr, //7 &RtmpChunkStream::OnAudioMessage, // 8 &RtmpChunkStream::OnVideoMessage, // 9 - NULL, // 10 - NULL, // 11 - NULL, // 12 - NULL, // 13 - NULL, // 14 + nullptr, // 10 + nullptr, // 11 + nullptr, // 12 + nullptr, // 13 + nullptr, // 14 &RtmpChunkStream::OnDataMessageAMF3, // 15 &RtmpChunkStream::OnSharedObjectMessageAMF3, // 16 &RtmpChunkStream::OnCommandMessageAMF3, // 17 &RtmpChunkStream::OnDataMessageAMF0, // 18 &RtmpChunkStream::OnSharedObjectMessageAMF0, // 19 &RtmpChunkStream::OnCommandMessageAMF0, // 20 - NULL, // 21 + nullptr, // 21 &RtmpChunkStream::OnAggregateMessage, // 22 }; typedef butil::FlatMap CommandHandlerMap; -static CommandHandlerMap* s_cmd_handlers = NULL; +static CommandHandlerMap* s_cmd_handlers = nullptr; static pthread_once_t s_cmd_handlers_init_once = PTHREAD_ONCE_INIT; static void InitCommandHandlers() { // Dispatch commands based on "Command Name". @@ -1817,7 +1817,7 @@ bool RtmpChunkStream::OnMessage(const RtmpBasicHeader& bh, return false; } MessageHandler handler = s_msg_handlers[index]; - if (handler == NULL) { + if (handler == nullptr) { RTMP_ERROR(socket, mh) << "Unknown message_type=" << (int)mh.message_type; return false; } @@ -1967,7 +1967,7 @@ bool RtmpChunkStream::OnStreamBegin(const RtmpMessageHeader& mh, const butil::StringPiece& event_data, Socket* socket) { RtmpService* service = connection_context()->service(); - if (service != NULL) { + if (service != nullptr) { RTMP_ERROR(socket, mh) << "Server should not receive `StreamBegin'"; return false; } @@ -1984,7 +1984,7 @@ bool RtmpChunkStream::OnStreamEOF(const RtmpMessageHeader& mh, const butil::StringPiece& event_data, Socket* socket) { RtmpService* service = connection_context()->service(); - if (service != NULL) { + if (service != nullptr) { RTMP_ERROR(socket, mh) << "Server should not receive `StreamEOF'"; return false; } @@ -2001,7 +2001,7 @@ bool RtmpChunkStream::OnStreamDry(const RtmpMessageHeader& mh, const butil::StringPiece& event_data, Socket* socket) { RtmpService* service = connection_context()->service(); - if (service != NULL) { + if (service != nullptr) { RTMP_ERROR(socket, mh) << "Server should not receive `StreamDry'"; return false; } @@ -2018,7 +2018,7 @@ bool RtmpChunkStream::OnStreamIsRecorded(const RtmpMessageHeader& mh, const butil::StringPiece& event_data, Socket* socket) { RtmpService* service = connection_context()->service(); - if (service != NULL) { + if (service != nullptr) { RTMP_ERROR(socket, mh) << "Server should not receive `StreamIsRecorded'"; return false; } @@ -2035,7 +2035,7 @@ bool RtmpChunkStream::OnSetBufferLength(const RtmpMessageHeader& mh, const butil::StringPiece& event_data, Socket* socket) { RtmpService* service = connection_context()->service(); - if (service == NULL) { + if (service == nullptr) { RTMP_ERROR(socket, mh) << "Client should not receive `SetBufferLength'"; return false; } @@ -2066,7 +2066,7 @@ bool RtmpChunkStream::OnPingRequest(const RtmpMessageHeader& mh, const butil::StringPiece& event_data, Socket* socket) { RtmpService* service = connection_context()->service(); - if (service != NULL) { + if (service != nullptr) { RTMP_ERROR(socket, mh) << "Server should not receive `PingRequest'"; return false; } @@ -2093,7 +2093,7 @@ bool RtmpChunkStream::OnPingResponse(const RtmpMessageHeader& mh, const butil::StringPiece& event_data, Socket* socket) { RtmpService* service = connection_context()->service(); - if (service == NULL) { + if (service == nullptr) { RTMP_ERROR(socket, mh) << "Client should not receive `PingResponse'"; return false; } @@ -2287,7 +2287,7 @@ bool RtmpChunkStream::OnCommandMessageAMF0( pthread_once(&s_cmd_handlers_init_once, InitCommandHandlers); RtmpChunkStream::CommandHandler* phandler = s_cmd_handlers->seek(command_name); - if (phandler == NULL) { + if (phandler == nullptr) { RTMP_ERROR(socket, mh) << "Unknown command_name=" << command_name; return false; } @@ -2356,7 +2356,7 @@ bool RtmpChunkStream::OnConnect(const RtmpMessageHeader& mh, << "] connect{" << req->ShortDebugString() << '}'; TemporaryArrayBuilder, 5> msgs; - char* p = NULL; + char* p = nullptr; // WindowAckSize // TODO(gejun): seems not effective to ffplay. char wasbuf[4]; @@ -2465,10 +2465,10 @@ bool RtmpChunkStream::OnBWDone(const RtmpMessageHeader& mh, } void RtmpContext::OnConnected(int error_code) { - if (_on_connect != NULL) { + if (_on_connect != nullptr) { void (*saved_on_connect)(int, void*) = _on_connect; void* saved_arg = _on_connect_arg; - _on_connect = NULL; + _on_connect = nullptr; saved_on_connect(error_code, saved_arg); } } @@ -2507,7 +2507,7 @@ bool RtmpChunkStream::OnResult(const RtmpMessageHeader& mh, } RtmpContext* ctx = static_cast(socket->parsing_context()); RtmpTransactionHandler* handler = ctx->RemoveTransaction(transaction_id); - if (handler == NULL) { + if (handler == nullptr) { RTMP_WARNING(socket, mh) << "Unknown _result.TransactionId=" << transaction_id; return false; @@ -2537,7 +2537,7 @@ bool RtmpChunkStream::OnError(const RtmpMessageHeader& mh, } RtmpContext* ctx = static_cast(socket->parsing_context()); RtmpTransactionHandler* handler = ctx->RemoveTransaction(transaction_id); - if (handler == NULL) { + if (handler == nullptr) { RTMP_WARNING(socket, mh) << "Unknown _error.TransactionId=" << transaction_id; return false; @@ -2582,7 +2582,7 @@ bool RtmpChunkStream::OnCreateStream(const RtmpMessageHeader& mh, AMFInputStream* istream, Socket* socket) { RtmpService* service = connection_context()->service(); - if (service == NULL) { + if (service == nullptr) { RTMP_ERROR(socket, mh) << "Client should not receive `createStream'"; return false; } @@ -2600,16 +2600,16 @@ bool RtmpChunkStream::OnCreateStream(const RtmpMessageHeader& mh, return false; } const AMFField* cmd_name_field = cmd_obj.Find("CommandName"); - if (cmd_name_field != NULL && cmd_name_field->IsString()) { + if (cmd_name_field != nullptr && cmd_name_field->IsString()) { is_publish = (cmd_name_field->AsString() == "publish"); } const AMFField* stream_name_field = cmd_obj.Find("StreamName"); - if (stream_name_field != NULL && stream_name_field->IsString()) { + if (stream_name_field != nullptr && stream_name_field->IsString()) { stream_name_field->AsString().CopyToString(&stream_name); } if (is_publish) { const AMFField* publish_type_field = cmd_obj.Find("PublishType"); - if (publish_type_field != NULL && publish_type_field->IsString()) { + if (publish_type_field != nullptr && publish_type_field->IsString()) { Str2RtmpPublishType(publish_type_field->AsString(), &publish_type); } } @@ -2619,10 +2619,10 @@ bool RtmpChunkStream::OnCreateStream(const RtmpMessageHeader& mh, butil::intrusive_ptr stream( service->NewStream(connection_context()->_connect_req)); if (connection_context()->_connect_req.stream_multiplexing() && - stream != NULL) { + stream != nullptr) { stream->_client_supports_stream_multiplexing = true; } - if (NULL == stream) { + if (nullptr == stream) { error_text = "Fail to create stream"; LOG(ERROR) << error_text; } else { @@ -3419,26 +3419,26 @@ bool RtmpChunkStream::OnPause(const RtmpMessageHeader& mh, inline ParseResult IsPossiblyRtmp(const butil::IOBuf* source) { const char* p = (const char*)source->fetch1(); - if (p == NULL) { + if (p == nullptr) { return MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA); } if (*p != RTMP_DEFAULT_VERSION) { return MakeParseError(PARSE_ERROR_TRY_OTHERS); } - return MakeMessage(NULL); + return MakeMessage(nullptr); } ParseResult ParseRtmpMessage(butil::IOBuf* source, Socket *socket, bool read_eof, const void* arg) { RtmpContext* rtmp_ctx = static_cast(socket->parsing_context()); - if (rtmp_ctx == NULL) { - if (arg == NULL) { + if (rtmp_ctx == nullptr) { + if (arg == nullptr) { // We are probably parsing another client-side protocol. return MakeParseError(PARSE_ERROR_TRY_OTHERS); } const Server* server = static_cast(arg); RtmpService* service = server->options().rtmp_service; - if (service == NULL) { + if (service == nullptr) { // Validating RTMP protocol only checks the first byte, which // is very easy to be confused with other protocols. Currently // if rtmp_service is not set, the protocol is skipped w/o any @@ -3454,11 +3454,7 @@ ParseResult ParseRtmpMessage(butil::IOBuf* source, Socket *socket, bool read_eof if (!r.is_ok()) { return r; } - rtmp_ctx = new (std::nothrow) RtmpContext(NULL, server); - if (rtmp_ctx == NULL) { - LOG(FATAL) << "Fail to new RtmpContext"; - return MakeParseError(PARSE_ERROR_NO_RESOURCE); - } + rtmp_ctx = new RtmpContext(nullptr, server); socket->reset_parsing_context(rtmp_ctx); // We don't need to customize app_connect at server-side. } @@ -3491,7 +3487,7 @@ void OnServerStreamCreated::Run(bool error, std::unique_ptr delete_self(this); // End the createStream call. RtmpContext* ctx = static_cast(socket->parsing_context()); - if (ctx == NULL) { + if (ctx == nullptr) { LOG(FATAL) << "RtmpContext must be created"; return; } @@ -3500,7 +3496,7 @@ void OnServerStreamCreated::Run(bool error, const int64_t received_us = start_parse_us; const int64_t base_realtime = butil::gettimeofday_us() - received_us; const bthread_id_t cid = _call_id; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -3517,7 +3513,7 @@ void OnServerStreamCreated::Run(bool error, break; } const AMFField* field = cmd_obj.Find("PlayOrPublishAccepted"); - if (field != NULL && field->IsBool() && field->AsBool()) { + if (field != nullptr && field->IsBool() && field->AsBool()) { _stream->_created_stream_with_play_or_publish = true; } if (error) { @@ -3565,12 +3561,12 @@ void OnServerStreamCreated::Cancel() { butil::Status RtmpCreateStreamMessage::AppendAndDestroySelf(butil::IOBuf* out, Socket* s) { std::unique_ptr destroy_self(this); - if (s == NULL) { // abandoned + if (s == nullptr) { // abandoned return butil::Status::OK(); } // Serialize createStream command RtmpContext* ctx = static_cast(socket->parsing_context()); - if (ctx == NULL) { + if (ctx == nullptr) { return butil::Status(EINVAL, "RtmpContext of %s is not created", socket->description().c_str()); } @@ -3611,7 +3607,7 @@ RtmpCreateStreamMessage::AppendAndDestroySelf(butil::IOBuf* out, Socket* s) { CHECK(ostream.good()); } RtmpChunkStream* cstream = ctx->GetChunkStream(RTMP_CONTROL_CHUNK_STREAM_ID); - if (cstream == NULL) { + if (cstream == nullptr) { socket->SetFailed(EINVAL, "Invalid chunk_stream_id=%u", RTMP_CONTROL_CHUNK_STREAM_ID); return butil::Status(EINVAL, "Invalid chunk_stream_id=%u", @@ -3631,7 +3627,7 @@ RtmpCreateStreamMessage::AppendAndDestroySelf(butil::IOBuf* out, Socket* s) { void PackRtmpRequest(butil::IOBuf* /*buf*/, SocketMessage** user_message, uint64_t /*correlation_id*/, - const google::protobuf::MethodDescriptor* /*NULL*/, + const google::protobuf::MethodDescriptor* /*nullptr*/, Controller* cntl, const butil::IOBuf& /*request*/, const Authenticator*) { @@ -3639,7 +3635,7 @@ void PackRtmpRequest(butil::IOBuf* /*buf*/, ControllerPrivateAccessor accessor(cntl); Socket* s = accessor.get_sending_socket(); RtmpContext* ctx = static_cast(s->parsing_context()); - if (ctx == NULL) { + if (ctx == nullptr) { cntl->SetFailed(EINVAL, "RtmpContext of %s is not created", s->description().c_str()); return; @@ -3675,7 +3671,7 @@ void PackRtmpRequest(butil::IOBuf* /*buf*/, void SerializeRtmpRequest(butil::IOBuf* /*buf*/, Controller* /*cntl*/, - const google::protobuf::Message* /*NULL*/) { + const google::protobuf::Message* /*nullptr*/) { } } // namespace policy diff --git a/src/brpc/policy/rtmp_protocol.h b/src/brpc/policy/rtmp_protocol.h index b5572c2f18..2ed9fd3c2e 100644 --- a/src/brpc/policy/rtmp_protocol.h +++ b/src/brpc/policy/rtmp_protocol.h @@ -169,12 +169,12 @@ class RtmpUnsentMessage : public SocketMessage { // if this field is non-zero. uint32_t new_chunk_size; butil::IOBuf body; - // If next is not NULL, next->AppendAndDestroySelf() will be called + // If next is not nullptr, next->AppendAndDestroySelf() will be called // recursively. For implementing batched messages. SocketMessagePtr next; public: RtmpUnsentMessage() - : chunk_stream_id(0) , new_chunk_size(0), next(NULL) {} + : chunk_stream_id(0) , new_chunk_size(0), next(nullptr) {} // @SocketMessage butil::Status AppendAndDestroySelf(butil::IOBuf* out, Socket*); }; @@ -255,7 +255,7 @@ friend class RtmpUnsentMessage; // Get literal form of the state. static const char* state2str(State); - // One of copt/service must be NULL, indicating this context belongs + // One of copt/service must be nullptr, indicating this context belongs // to a server-side or client-side socket. RtmpContext(const RtmpClientOptions* copt, const Server* server); ~RtmpContext(); @@ -272,8 +272,8 @@ friend class RtmpUnsentMessage; const Server* server() const { return _server; } RtmpService* service() const { return _service; } - bool is_server_side() const { return service() != NULL; } - bool is_client_side() const { return service() == NULL; } + bool is_server_side() const { return service() != nullptr; } + bool is_client_side() const { return service() == nullptr; } // XXXMessageStream may be called from multiple threads(currently not), // so they're protected by _stream_mutex @@ -325,7 +325,7 @@ friend class RtmpUnsentMessage; } // Called when the RTMP connection is established. void OnConnected(int error_code); - bool unconnected() const { return _on_connect != NULL; } + bool unconnected() const { return _on_connect != nullptr; } void only_check_simple_s0s1() { _only_check_simple_s0s1 = true; } bool can_stream_be_created_with_play_or_publish() const diff --git a/src/brpc/policy/sofa_pbrpc_protocol.cpp b/src/brpc/policy/sofa_pbrpc_protocol.cpp index 328ae4aa38..6b663c19f9 100644 --- a/src/brpc/policy/sofa_pbrpc_protocol.cpp +++ b/src/brpc/policy/sofa_pbrpc_protocol.cpp @@ -237,11 +237,11 @@ static void SendSofaResponse(int64_t correlation_id, bool append_body = false; butil::IOBuf res_body; - // `res' can be NULL here, in which case we don't serialize it + // `res' can be nullptr here, in which case we don't serialize it // If user calls `SetFailed' on Controller, we don't serialize // response either CompressType type = cntl->response_compress_type(); - if (res != NULL && !cntl->Failed()) { + if (res != nullptr && !cntl->Failed()) { if (!res->IsInitialized()) { cntl->SetFailed( ERESPONSE, "Missing required fields in response: %s", @@ -345,11 +345,7 @@ void ProcessSofaRequest(InputMessageBase* msg_base) { sample->submit(start_parse_us); } - std::unique_ptr cntl(new (std::nothrow) Controller); - if (NULL == cntl.get()) { - LOG(WARNING) << "Fail to new Controller"; - return; - } + std::unique_ptr cntl(new Controller); std::unique_ptr req; std::unique_ptr res; @@ -388,7 +384,7 @@ void ProcessSofaRequest(InputMessageBase* msg_base) { span->set_request_size(msg->meta.size() + msg->payload.size() + 24); } - MethodStatus* method_status = NULL; + MethodStatus* method_status = nullptr; do { if (!server->IsRunning()) { cntl->SetFailed(ELOGOFF, "Server is stopping"); @@ -409,7 +405,7 @@ void ProcessSofaRequest(InputMessageBase* msg_base) { const Server::MethodProperty *sp = server_accessor.FindMethodPropertyByFullName(meta.method()); - if (NULL == sp) { + if (nullptr == sp) { cntl->SetFailed(ENOMETHOD, "Fail to find method=%s", meta.method().c_str()); break; @@ -509,7 +505,7 @@ void ProcessSofaResponse(InputMessageBase* msg_base) { } const bthread_id_t cid = { static_cast(meta.sequence_id()) }; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) diff --git a/src/brpc/policy/streaming_rpc_protocol.cpp b/src/brpc/policy/streaming_rpc_protocol.cpp index 429d2bc282..bdad1f2385 100644 --- a/src/brpc/policy/streaming_rpc_protocol.cpp +++ b/src/brpc/policy/streaming_rpc_protocol.cpp @@ -53,7 +53,7 @@ void PackStreamMessage(butil::IOBuf* out, out->append(head, ARRAY_SIZE(head)); butil::IOBufAsZeroCopyOutputStream wrapper(out); CHECK(fm.SerializeToZeroCopyStream(&wrapper)); - if (data != NULL) { + if (data != nullptr) { out->append(*data); } } @@ -120,7 +120,7 @@ ParseResult ParseStreamingMessage(butil::IOBuf* source, } while (0); // Hack input messenger - return MakeMessage(NULL); + return MakeMessage(nullptr); } void ProcessStreamingMessage(InputMessageBase* /*msg*/) { @@ -128,12 +128,12 @@ void ProcessStreamingMessage(InputMessageBase* /*msg*/) { } void SendStreamRst(Socket* sock, int64_t remote_stream_id) { - CHECK(sock != NULL); + CHECK(sock != nullptr); StreamFrameMeta fm; fm.set_stream_id(remote_stream_id); fm.set_frame_type(FRAME_TYPE_RST); butil::IOBuf out; - PackStreamMessage(&out, fm, NULL); + PackStreamMessage(&out, fm, nullptr); Socket::WriteOptions wopt; wopt.ignore_eovercrowded = true; sock->Write(&out, &wopt); @@ -141,13 +141,13 @@ void SendStreamRst(Socket* sock, int64_t remote_stream_id) { void SendStreamClose(Socket* sock, int64_t remote_stream_id, int64_t source_stream_id) { - CHECK(sock != NULL); + CHECK(sock != nullptr); StreamFrameMeta fm; fm.set_stream_id(remote_stream_id); fm.set_source_stream_id(source_stream_id); fm.set_frame_type(FRAME_TYPE_CLOSE); butil::IOBuf out; - PackStreamMessage(&out, fm, NULL); + PackStreamMessage(&out, fm, nullptr); Socket::WriteOptions wopt; wopt.ignore_eovercrowded = true; sock->Write(&out, &wopt); @@ -156,7 +156,7 @@ void SendStreamClose(Socket* sock, int64_t remote_stream_id, int SendStreamData(Socket* sock, const butil::IOBuf* data, int64_t remote_stream_id, int64_t source_stream_id, bthread_id_t response_id) { - CHECK(sock != NULL); + CHECK(sock != nullptr); StreamFrameMeta fm; fm.set_stream_id(remote_stream_id); fm.set_source_stream_id(source_stream_id); diff --git a/src/brpc/policy/thrift_protocol.cpp b/src/brpc/policy/thrift_protocol.cpp index 2b5739ea3e..dce6bc3899 100755 --- a/src/brpc/policy/thrift_protocol.cpp +++ b/src/brpc/policy/thrift_protocol.cpp @@ -249,7 +249,7 @@ void ThriftClosure::DoRun() { } Socket* sock = accessor.get_sending_socket(); MethodStatus* method_status = (server->options().thrift_service ? - server->options().thrift_service->_status : NULL); + server->options().thrift_service->_status : nullptr); ConcurrencyRemover concurrency_remover(method_status, &_controller, _received_us); if (!method_status) { // Judge errors belongings. @@ -492,7 +492,7 @@ void ProcessThriftRequest(InputMessageBase* msg_base) { cntl->set_log_id(seq_id); // Pass seq_id by log_id ThriftService* service = server->options().thrift_service; - if (service == NULL) { + if (service == nullptr) { LOG_EVERY_SECOND(ERROR) << "Received thrift request however the server does not set" " ServerOptions.thrift_service, close the connection."; @@ -575,7 +575,7 @@ void ProcessThriftResponse(InputMessageBase* msg_base) { // Fetch correlation id that we saved before in `PacThriftRequest' const CallId cid = { static_cast(msg->socket()->correlation_id()) }; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -656,13 +656,13 @@ bool VerifyThriftRequest(const InputMessageBase* msg_base) { void SerializeThriftRequest(butil::IOBuf* request_buf, Controller* cntl, const google::protobuf::Message* req_base) { - if (req_base == NULL) { + if (req_base == nullptr) { return cntl->SetFailed(EREQUEST, "request is NULL"); } if (req_base->GetDescriptor() != ThriftFramedMessage::descriptor()) { return cntl->SetFailed(EINVAL, "Type of request must be ThriftFramedMessage"); } - if (cntl->response() != NULL && + if (cntl->response() != nullptr && cntl->response()->GetDescriptor() != ThriftFramedMessage::descriptor()) { return cntl->SetFailed(EINVAL, "Type of response must be ThriftFramedMessage"); } diff --git a/src/brpc/policy/timeout_concurrency_limiter.cpp b/src/brpc/policy/timeout_concurrency_limiter.cpp index 21aad33fc1..5ef37fdb5f 100644 --- a/src/brpc/policy/timeout_concurrency_limiter.cpp +++ b/src/brpc/policy/timeout_concurrency_limiter.cpp @@ -67,8 +67,8 @@ TimeoutConcurrencyLimiter::TimeoutConcurrencyLimiter( TimeoutConcurrencyLimiter *TimeoutConcurrencyLimiter::New( const AdaptiveMaxConcurrency &amc) const { - return new (std::nothrow) - TimeoutConcurrencyLimiter(static_cast(amc)); + return new TimeoutConcurrencyLimiter( + static_cast(amc)); } bool TimeoutConcurrencyLimiter::OnRequested(int current_concurrency, diff --git a/src/brpc/policy/ubrpc2pb_protocol.cpp b/src/brpc/policy/ubrpc2pb_protocol.cpp index 2f5194c880..c3c598f0cc 100644 --- a/src/brpc/policy/ubrpc2pb_protocol.cpp +++ b/src/brpc/policy/ubrpc2pb_protocol.cpp @@ -55,7 +55,7 @@ void UbrpcAdaptor::ParseNsheadMeta( } mcpack2pb::ObjectIterator it1(&stream, request.body.size() - stream.popped_bytes()); bool found_content = false; - for (; it1 != NULL; ++it1) { + for (; it1 != nullptr; ++it1) { if (it1->name == "content") { found_content = true; break; @@ -72,7 +72,7 @@ void UbrpcAdaptor::ParseNsheadMeta( } mcpack2pb::ArrayIterator it2(it1->value); - if (it2 == NULL) { + if (it2 == nullptr) { cntl->SetFailed(EREQUEST, "Fail to parse request.content as array"); return; } @@ -81,7 +81,7 @@ void UbrpcAdaptor::ParseNsheadMeta( bool has_params = false; size_t user_req_offset = 0; size_t user_req_size = 0; - for (mcpack2pb::ObjectIterator it3(*it2); it3 != NULL; ++it3) { + for (mcpack2pb::ObjectIterator it3(*it2); it3 != nullptr; ++it3) { if (it3->name == "service_name") { if (it3->value.type() != mcpack2pb::FIELD_STRING) { cntl->SetFailed(EREQUEST, "Expect request.content[0].service_name" @@ -120,7 +120,7 @@ void UbrpcAdaptor::ParseNsheadMeta( user_req_size = it3->value.size(); const size_t stream_end = stream.popped_bytes() + it3->value.size(); mcpack2pb::ObjectIterator it4(it3->value); - if (it4 == NULL || it4.field_count() == 0) { + if (it4 == nullptr || it4.field_count() == 0) { cntl->SetFailed(EREQUEST, "Nothing in request.content[0].params"); return; } @@ -173,7 +173,7 @@ void UbrpcAdaptor::ParseRequestFromIOBuf( Controller* cntl, google::protobuf::Message* pb_req) const { const std::string msg_name = butil::EnsureString(pb_req->GetDescriptor()->full_name()); mcpack2pb::MessageHandler handler = mcpack2pb::find_message_handler(msg_name); - if (handler.parse_body == NULL) { + if (handler.parse_body == nullptr) { return cntl->SetFailed(EREQUEST, "Fail to find parser of %s", msg_name.c_str()); } @@ -216,7 +216,7 @@ void UbrpcAdaptor::SerializeResponseToIOBuf( type = COMPRESS_TYPE_NONE; } - if (pb_res == NULL || cntl->Failed()) { + if (pb_res == nullptr || cntl->Failed()) { if (!cntl->Failed()) { cntl->SetFailed(ERESPONSE, "response was not created yet"); } @@ -231,7 +231,7 @@ void UbrpcAdaptor::SerializeResponseToIOBuf( const std::string msg_name = butil::EnsureString(pb_res->GetDescriptor()->full_name()); mcpack2pb::MessageHandler handler = mcpack2pb::find_message_handler(msg_name); - if (handler.serialize_body == NULL) { + if (handler.serialize_body == nullptr) { cntl->SetFailed(ERESPONSE, "Fail to find serializer of %s", msg_name.c_str()); return AppendError(meta, cntl, raw_res->body); @@ -254,7 +254,7 @@ void UbrpcAdaptor::SerializeResponseToIOBuf( } sr.begin_object("result_params"); const char* const response_name = cntl->idl_names().response_name; - if (response_name != NULL && *response_name) { + if (response_name != nullptr && *response_name) { sr.begin_object(response_name); handler.serialize_body(*pb_res, sr, _format); sr.end_object(); @@ -277,13 +277,13 @@ void UbrpcAdaptor::SerializeResponseToIOBuf( static void ParseResponse(Controller* cntl, butil::IOBuf& buf, google::protobuf::Message* res) { - if (res == NULL) { + if (res == nullptr) { // silently ignore response. return; } const std::string msg_name = butil::EnsureString(res->GetDescriptor()->full_name()); mcpack2pb::MessageHandler handler = mcpack2pb::find_message_handler(msg_name); - if (handler.parse_body == NULL) { + if (handler.parse_body == nullptr) { return cntl->SetFailed(ERESPONSE, "Fail to find parser of %s", msg_name.c_str()); } @@ -295,7 +295,7 @@ static void ParseResponse(Controller* cntl, butil::IOBuf& buf, } mcpack2pb::ObjectIterator it1(&stream, buf.size() - stream.popped_bytes()); bool found_content = false; - for (; it1 != NULL; ++it1) { + for (; it1 != nullptr; ++it1) { if (it1->name == "content") { found_content = true; break; @@ -311,7 +311,7 @@ static void ParseResponse(Controller* cntl, butil::IOBuf& buf, return; } mcpack2pb::ArrayIterator it2(it1->value); - if (it2 == NULL) { + if (it2 == nullptr) { cntl->SetFailed("Fail to parse response.content as array"); return; } @@ -319,7 +319,7 @@ static void ParseResponse(Controller* cntl, butil::IOBuf& buf, size_t user_res_offset = 0; size_t user_res_size = 0; const char* response_name = "result_params"; - for (mcpack2pb::ObjectIterator it3(*it2); it3 != NULL; ++it3) { + for (mcpack2pb::ObjectIterator it3(*it2); it3 != nullptr; ++it3) { if (it3->name == "error") { if (it3->value.type() != mcpack2pb::FIELD_OBJECT) { cntl->SetFailed(ERESPONSE, "Expect response.content[0].error" @@ -329,7 +329,7 @@ static void ParseResponse(Controller* cntl, butil::IOBuf& buf, } int32_t code = 0; std::string msg; - for (mcpack2pb::ObjectIterator it4(it3->value); it4 != NULL; ++it4) { + for (mcpack2pb::ObjectIterator it4(it3->value); it4 != nullptr; ++it4) { if (it4->name == "code") { if (!mcpack2pb::is_primitive(it4->value.type()) || !mcpack2pb::is_integral( @@ -390,10 +390,10 @@ static void ParseResponse(Controller* cntl, butil::IOBuf& buf, user_res_size = it3->value.size(); const size_t stream_end = stream.popped_bytes() + it3->value.size(); const char* const expname = cntl->idl_names().response_name; - if (expname != NULL && *expname) { + if (expname != nullptr && *expname) { mcpack2pb::ObjectIterator it4(it3->value); bool found_response_name = false; - for (; it4 != NULL; ++it4) { + for (; it4 != nullptr; ++it4) { if (it4->name == expname) { found_response_name = true; break; @@ -446,7 +446,7 @@ void ProcessUbrpcResponse(InputMessageBase* msg_base) { // Fetch correlation id that we saved before in `PackUbrpcRequest' const bthread_id_t cid = { static_cast(socket->correlation_id()) }; - Controller* cntl = NULL; + Controller* cntl = nullptr; const int rc = bthread_id_lock(cid, (void**)&cntl); if (rc != 0) { LOG_IF(ERROR, rc != EINVAL && rc != EPERM) @@ -478,12 +478,12 @@ static void SerializeUbrpcRequest(butil::IOBuf* buf, Controller* cntl, return cntl->SetFailed( EREQUEST, "ubrpc protocol doesn't support compression"); } - if (cntl->method() == NULL) { + if (cntl->method() == nullptr) { return cntl->SetFailed(ENOMETHOD, "method is NULL"); } const std::string msg_name = butil::EnsureString(request->GetDescriptor()->full_name()); mcpack2pb::MessageHandler handler = mcpack2pb::find_message_handler(msg_name); - if (handler.serialize_body == NULL) { + if (handler.serialize_body == nullptr) { return cntl->SetFailed(EREQUEST, "Fail to find serializer of %s", msg_name.c_str()); } @@ -506,7 +506,7 @@ static void SerializeUbrpcRequest(butil::IOBuf* buf, Controller* cntl, sr.add_string("method", butil::EnsureString(cntl->method()->name())); sr.begin_object("params"); const char* const request_name = cntl->idl_names().request_name; - if (request_name != NULL && *request_name) { + if (request_name != nullptr && *request_name) { sr.begin_object(request_name); handler.serialize_body(*request, sr, format); sr.end_object(); diff --git a/src/brpc/policy/weighted_randomized_load_balancer.cpp b/src/brpc/policy/weighted_randomized_load_balancer.cpp index d2786ed8bf..0f9a339a05 100644 --- a/src/brpc/policy/weighted_randomized_load_balancer.cpp +++ b/src/brpc/policy/weighted_randomized_load_balancer.cpp @@ -155,7 +155,7 @@ int WeightedRandomizedLoadBalancer::SelectServer(const SelectIn& in, SelectOut* for (size_t i = 0; i < n; ++i) { offset = (offset + stride) % n; SocketId id = s->server_list[offset].id; - if (NULL != random_traversed.seek(id)) { + if (nullptr != random_traversed.seek(id)) { continue; } if (IsServerAvailable(id, out->ptr)) { @@ -170,12 +170,12 @@ int WeightedRandomizedLoadBalancer::SelectServer(const SelectIn& in, SelectOut* // Returns EHOSTDOWN, if no available server is found // after traversing the whole server list. // Otherwise, returns 0 with a available excluded server. - return NULL == out->ptr ? EHOSTDOWN : 0; + return nullptr == out->ptr ? EHOSTDOWN : 0; } LoadBalancer* WeightedRandomizedLoadBalancer::New( const butil::StringPiece&) const { - return new (std::nothrow) WeightedRandomizedLoadBalancer; + return new WeightedRandomizedLoadBalancer; } void WeightedRandomizedLoadBalancer::Destroy() { diff --git a/src/brpc/policy/weighted_round_robin_load_balancer.cpp b/src/brpc/policy/weighted_round_robin_load_balancer.cpp index 44d8a957b3..f52bf2990b 100644 --- a/src/brpc/policy/weighted_round_robin_load_balancer.cpp +++ b/src/brpc/policy/weighted_round_robin_load_balancer.cpp @@ -246,7 +246,7 @@ SocketId WeightedRoundRobinLoadBalancer::GetServerInNextStride( LoadBalancer* WeightedRoundRobinLoadBalancer::New( const butil::StringPiece&) const { - return new (std::nothrow) WeightedRoundRobinLoadBalancer; + return new WeightedRoundRobinLoadBalancer; } void WeightedRoundRobinLoadBalancer::Destroy() {