From 77d4369b52642d44c38968545d71d68581929bad Mon Sep 17 00:00:00 2001 From: chenBright Date: Mon, 17 Aug 2026 00:02:15 +0800 Subject: [PATCH] Refactor NULL with nullptr in brpc --- src/brpc/acceptor.cpp | 10 +- src/brpc/acceptor.h | 2 +- src/brpc/adaptive_max_concurrency.cpp | 2 +- src/brpc/amf.cpp | 22 +- src/brpc/amf.h | 4 +- src/brpc/amf_inl.h | 6 +- src/brpc/backup_request_policy.cpp | 10 +- src/brpc/backup_request_policy.h | 2 +- src/brpc/baidu_master_service.cpp | 10 +- src/brpc/channel.cpp | 57 ++-- src/brpc/channel.h | 30 +- src/brpc/checksum.cpp | 22 +- src/brpc/checksum.h | 6 +- src/brpc/closure_guard.h | 12 +- src/brpc/compress.cpp | 22 +- src/brpc/compress.h | 6 +- src/brpc/controller.cpp | 196 +++++++------ src/brpc/controller.h | 32 +-- src/brpc/couchbase.cpp | 28 +- src/brpc/data_factory.h | 2 +- src/brpc/details/naming_service_thread.cpp | 14 +- src/brpc/event_dispatcher.cpp | 8 +- src/brpc/event_dispatcher.h | 4 +- src/brpc/event_dispatcher_epoll.cpp | 10 +- src/brpc/event_dispatcher_kqueue.cpp | 30 +- src/brpc/excluded_servers.h | 8 +- src/brpc/extension_inl.h | 10 +- src/brpc/global.cpp | 103 ++++--- src/brpc/grpc.cpp | 2 +- src/brpc/http_header.cpp | 10 +- src/brpc/http_header.h | 2 +- src/brpc/http_method.cpp | 2 +- src/brpc/http_status_code.cpp | 2 +- src/brpc/http_status_code.h | 2 +- src/brpc/input_messenger.cpp | 54 ++-- src/brpc/input_messenger.h | 6 +- src/brpc/kvmap.h | 2 +- src/brpc/load_balancer.cpp | 10 +- src/brpc/memcache.cpp | 14 +- src/brpc/memcache.h | 4 +- src/brpc/nshead_message.cpp | 2 +- src/brpc/nshead_pb_service_adaptor.cpp | 4 +- src/brpc/nshead_pb_service_adaptor.h | 2 +- src/brpc/nshead_service.cpp | 6 +- src/brpc/nshead_service.h | 2 +- src/brpc/parallel_channel.cpp | 66 ++--- src/brpc/parallel_channel.h | 10 +- src/brpc/parse_result.h | 8 +- src/brpc/partition_channel.cpp | 70 ++--- src/brpc/partition_channel.h | 4 +- src/brpc/periodic_task.cpp | 6 +- src/brpc/policy/auto_concurrency_limiter.cpp | 2 +- src/brpc/progressive_attachment.cpp | 6 +- src/brpc/progressive_reader.h | 2 +- src/brpc/protocol.cpp | 6 +- src/brpc/protocol.h | 6 +- src/brpc/rdma_transport.cpp | 16 +- src/brpc/rdma_transport.h | 4 +- src/brpc/redis.cpp | 12 +- src/brpc/redis.h | 4 +- src/brpc/redis_cluster.cpp | 60 ++-- src/brpc/redis_cluster.h | 2 +- src/brpc/redis_command.cpp | 30 +- src/brpc/redis_reply.cpp | 16 +- src/brpc/redis_reply.h | 4 +- src/brpc/restful.cpp | 14 +- src/brpc/restful.h | 2 +- src/brpc/retry_policy.cpp | 2 +- src/brpc/rpc_dump.cpp | 26 +- src/brpc/rpc_dump.h | 12 +- src/brpc/rpc_pb_message_factory.cpp | 6 +- src/brpc/rpc_pb_message_factory.h | 8 +- src/brpc/rtmp.cpp | 118 ++++---- src/brpc/rtmp.h | 8 +- src/brpc/selective_channel.cpp | 46 ++- src/brpc/selective_channel.h | 2 +- src/brpc/server.cpp | 282 +++++++++---------- src/brpc/server.h | 54 ++-- src/brpc/server_id.cpp | 2 +- src/brpc/simple_data_pool.cpp | 18 +- src/brpc/socket.cpp | 232 ++++++++------- src/brpc/socket.h | 42 +-- src/brpc/socket_inl.h | 12 +- src/brpc/socket_map.cpp | 30 +- src/brpc/socket_map.h | 10 +- src/brpc/socket_message.h | 4 +- src/brpc/span.cpp | 55 ++-- src/brpc/span.h | 4 +- src/brpc/stream.cpp | 90 +++--- src/brpc/stream.h | 14 +- src/brpc/stream_creator.h | 2 +- src/brpc/stream_impl.h | 4 +- src/brpc/tcp_transport.cpp | 2 +- src/brpc/thrift_message.cpp | 4 +- src/brpc/thrift_message.h | 8 +- src/brpc/thrift_service.cpp | 4 +- src/brpc/traceprintf.h | 2 +- src/brpc/trackme.cpp | 28 +- src/brpc/transport.h | 6 +- src/brpc/ts.cpp | 32 +-- src/brpc/ubshm_transport.cpp | 16 +- src/brpc/ubshm_transport.h | 4 +- src/brpc/uri.h | 4 +- src/brpc/versioned_ref_with_id.h | 8 +- 104 files changed, 1114 insertions(+), 1231 deletions(-) diff --git a/src/brpc/acceptor.cpp b/src/brpc/acceptor.cpp index f9c22a6848..8333a17127 100644 --- a/src/brpc/acceptor.cpp +++ b/src/brpc/acceptor.cpp @@ -39,7 +39,7 @@ Acceptor::Acceptor(bthread_keytable_pool_t* pool) , _acception_id(0) , _empty_cond(&_map_mutex) , _force_ssl(false) - , _ssl_ctx(NULL) + , _ssl_ctx(nullptr) , _socket_mode(SOCKET_MODE_TCP) , _bthread_tag(BTHREAD_TAG_DEFAULT) { } @@ -120,7 +120,7 @@ void* Acceptor::CloseIdleConnections(void* arg) { } } } - return NULL; + return nullptr; } void Acceptor::StopAccept(int /*closewait_ms*/) { @@ -190,7 +190,7 @@ void Acceptor::Join() { // Join the bthread outside lock. if (saved_idle_timeout_sec > 0) { bthread_stop(saved_close_idle_tid); - bthread_join(saved_close_idle_tid, NULL); + bthread_join(saved_close_idle_tid, nullptr); } { @@ -207,7 +207,7 @@ size_t Acceptor::ConnectionCount() const { void Acceptor::ListConnections(std::vector* conn_list, size_t max_copied) { - if (conn_list == NULL) { + if (conn_list == nullptr) { LOG(FATAL) << "Param[conn_list] is NULL"; return; } @@ -270,7 +270,7 @@ void Acceptor::OnNewConnectionsUntilEAGAIN(Socket* acception) { } Acceptor* am = dynamic_cast(acception->user()); - if (NULL == am) { + if (nullptr == am) { LOG(FATAL) << "Impossible! acception->user() MUST be Acceptor"; acception->SetFailed(EINVAL, "Impossible! acception->user() MUST be Acceptor"); return; diff --git a/src/brpc/acceptor.h b/src/brpc/acceptor.h index 77942beca2..2f138b30ea 100644 --- a/src/brpc/acceptor.h +++ b/src/brpc/acceptor.h @@ -45,7 +45,7 @@ friend class Server; }; public: - explicit Acceptor(bthread_keytable_pool_t* pool = NULL); + explicit Acceptor(bthread_keytable_pool_t* pool = nullptr); ~Acceptor(); // [thread-safe] Accept connections from `listened_fd'. Ownership of diff --git a/src/brpc/adaptive_max_concurrency.cpp b/src/brpc/adaptive_max_concurrency.cpp index 6a5977bcf4..a43bdaf755 100644 --- a/src/brpc/adaptive_max_concurrency.cpp +++ b/src/brpc/adaptive_max_concurrency.cpp @@ -47,7 +47,7 @@ AdaptiveMaxConcurrency::AdaptiveMaxConcurrency( inline bool CompareStringPieceWithoutCase( const butil::StringPiece& s1, const char* s2) { - DCHECK(s2 != NULL); + DCHECK(s2 != nullptr); if (std::strlen(s2) != s1.size()) { return false; } diff --git a/src/brpc/amf.cpp b/src/brpc/amf.cpp index 219199c78f..3cd44d3728 100644 --- a/src/brpc/amf.cpp +++ b/src/brpc/amf.cpp @@ -147,13 +147,13 @@ void AMFField::SlowerClear() { break; case AMF_MARKER_STRICT_ARRAY: delete _arr; - _arr = NULL; + _arr = nullptr; break; case AMF_MARKER_STRING: case AMF_MARKER_LONG_STRING: if (!_is_shortstr) { free(_str); - _str = NULL; + _str = nullptr; } _strsize = 0; _is_shortstr = false; @@ -161,7 +161,7 @@ void AMFField::SlowerClear() { case AMF_MARKER_OBJECT: case AMF_MARKER_ECMA_ARRAY: delete _obj; - _obj = NULL; + _obj = nullptr; break; } _type = AMF_MARKER_UNDEFINED; @@ -173,7 +173,7 @@ const AMFField* AMFObject::Find(const char* name) const { if (it != _fields.end()) { return &it->second; } - return NULL; + return nullptr; } void AMFField::SetString(const butil::StringPiece& str) { @@ -433,7 +433,7 @@ static bool ReadAMFObjectField(AMFInputStream* stream, if (!CheckAMFDepth(depth)) { return false; } - const google::protobuf::Reflection* reflection = NULL; + const google::protobuf::Reflection* reflection = nullptr; if (field) { reflection = message->GetReflection(); } @@ -570,7 +570,7 @@ static bool ReadAMFObjectBody(google::protobuf::Message* message, break; } const google::protobuf::FieldDescriptor* field = desc->FindFieldByName(name); - RPC_VLOG_IF(field == NULL) << "Unknown field=" << desc->full_name() + RPC_VLOG_IF(field == nullptr) << "Unknown field=" << desc->full_name() << "." << name; if (!ReadAMFObjectField(stream, message, field, depth)) { return false; @@ -598,7 +598,7 @@ static bool SkipAMFObjectBody(AMFInputStream* stream, int depth) { } break; } - if (!ReadAMFObjectField(stream, NULL, NULL, depth)) { + if (!ReadAMFObjectField(stream, nullptr, nullptr, depth)) { return false; } } @@ -627,7 +627,7 @@ static bool ReadAMFEcmaArrayBody(google::protobuf::Message* message, return false; } const google::protobuf::FieldDescriptor* field = desc->FindFieldByName(name); - RPC_VLOG_IF(field == NULL) << "Unknown field=" << desc->full_name() + RPC_VLOG_IF(field == nullptr) << "Unknown field=" << desc->full_name() << "." << name; if (!ReadAMFObjectField(stream, message, field, depth)) { return false; @@ -651,7 +651,7 @@ bool ReadAMFObject(google::protobuf::Message* msg, AMFInputStream* stream) { return false; } } else if ((AMFMarker)marker != AMF_MARKER_NULL) { - // Notice that NULL is treated as an object w/o any fields. + // Notice that nullptr is treated as an object w/o any fields. LOG(ERROR) << "Expected object/null, actually " << marker2str(marker); return false; } @@ -826,7 +826,7 @@ bool ReadAMFObject(AMFObject* obj, AMFInputStream* stream) { return false; } } else if ((AMFMarker)marker != AMF_MARKER_NULL) { - // NOTE: NULL is treated as an object w/o any fields. + // NOTE: nullptr is treated as an object w/o any fields. LOG(ERROR) << "Expected object/null, actually " << marker2str(marker); return false; } @@ -952,7 +952,7 @@ bool ReadAMFArray(AMFArray* arr, AMFInputStream* stream) { return false; } } else if ((AMFMarker)marker != AMF_MARKER_NULL) { - // NOTE: NULL is treated as an array w/o any items. + // NOTE: nullptr is treated as an array w/o any items. LOG(ERROR) << "Expected array/null, actually " << marker2str(marker); return false; } diff --git a/src/brpc/amf.h b/src/brpc/amf.h index e9777e818e..0344794ef0 100644 --- a/src/brpc/amf.h +++ b/src/brpc/amf.h @@ -37,7 +37,7 @@ class AMFInputStream { AMFInputStream(google::protobuf::io::ZeroCopyInputStream* stream) : _good(true) , _size(0) - , _data(NULL) + , _data(nullptr) , _zc_stream(stream) , _popped_bytes(0) {} @@ -81,7 +81,7 @@ class AMFOutputStream { AMFOutputStream(google::protobuf::io::ZeroCopyOutputStream* stream) : _good(true) , _size(0) - , _data(NULL) + , _data(nullptr) , _zc_stream(stream) , _pushed_bytes(0) {} diff --git a/src/brpc/amf_inl.h b/src/brpc/amf_inl.h index d9d3a56cce..159bfdb408 100644 --- a/src/brpc/amf_inl.h +++ b/src/brpc/amf_inl.h @@ -40,7 +40,7 @@ inline size_t AMFInputStream::cutn(void* out, size_t n) { n -= _size; } } while (_zc_stream->Next(&_data, &_size)); - _data = NULL; + _data = nullptr; _size = 0; _popped_bytes += saved_n - n; return saved_n - n; @@ -127,7 +127,7 @@ inline void AMFOutputStream::putn(const void* data, int n) { data = (const char*)data + _size; n -= _size; } while (_zc_stream->Next(&_data, &_size)); - _data = NULL; + _data = nullptr; _size = 0; _pushed_bytes += (saved_n - n); if (n) { @@ -145,7 +145,7 @@ inline void AMFOutputStream::put_u8(uint8_t val) { return; } } while (_zc_stream->Next(&_data, &_size)); - _data = NULL; + _data = nullptr; _size = 0; set_bad(); } diff --git a/src/brpc/backup_request_policy.cpp b/src/brpc/backup_request_policy.cpp index 851537b3df..8784b0720f 100644 --- a/src/brpc/backup_request_policy.cpp +++ b/src/brpc/backup_request_policy.cpp @@ -144,22 +144,22 @@ BackupRequestPolicy* CreateRateLimitedBackupPolicy( if (options.backup_request_ms < -1) { LOG(ERROR) << "Invalid backup_request_ms=" << options.backup_request_ms << ", must be >= -1 (-1 means inherit from ChannelOptions)"; - return NULL; + return nullptr; } if (options.max_backup_ratio <= 0 || options.max_backup_ratio > 1.0) { LOG(ERROR) << "Invalid max_backup_ratio=" << options.max_backup_ratio << ", must be in (0, 1]"; - return NULL; + return nullptr; } if (options.window_size_seconds < 1 || options.window_size_seconds > 3600) { LOG(ERROR) << "Invalid window_size_seconds=" << options.window_size_seconds << ", must be in [1, 3600]"; - return NULL; + return nullptr; } if (options.update_interval_seconds < 1) { LOG(ERROR) << "Invalid update_interval_seconds=" << options.update_interval_seconds << ", must be >= 1"; - return NULL; + return nullptr; } if (options.update_interval_seconds > options.window_size_seconds) { LOG(WARNING) << "update_interval_seconds=" << options.update_interval_seconds @@ -167,7 +167,7 @@ BackupRequestPolicy* CreateRateLimitedBackupPolicy( << "; the ratio window will rarely refresh within its own period"; } // Plain new (without std::nothrow): brpc follows the project-wide convention - // of letting OOM throw/abort rather than returning NULL. NULL return from + // of letting OOM throw/abort rather than returning nullptr. nullptr return from // this factory already signals invalid parameters, not allocation failure. return new RateLimitedBackupPolicy( options.backup_request_ms, options.max_backup_ratio, diff --git a/src/brpc/backup_request_policy.h b/src/brpc/backup_request_policy.h index 13da2a59ba..70d74e3a01 100644 --- a/src/brpc/backup_request_policy.h +++ b/src/brpc/backup_request_policy.h @@ -70,7 +70,7 @@ struct RateLimitedBackupPolicyOptions { // NOTE: Backup decisions are counted immediately at DoBackup() time for // fast feedback. Total RPCs are counted on completion (OnRPCEnd). During // latency spikes the ratio may temporarily lag until RPCs complete. -// Returns NULL on invalid parameters. +// Returns nullptr on invalid parameters. // The caller owns the returned pointer. BackupRequestPolicy* CreateRateLimitedBackupPolicy( const RateLimitedBackupPolicyOptions& options); diff --git a/src/brpc/baidu_master_service.cpp b/src/brpc/baidu_master_service.cpp index b1b0fa0dbf..a32c8e52da 100644 --- a/src/brpc/baidu_master_service.cpp +++ b/src/brpc/baidu_master_service.cpp @@ -22,13 +22,12 @@ namespace brpc { BaiduMasterService::BaiduMasterService() - : _status(new (std::nothrow) MethodStatus), _ignore_eovercrowded(false) { - LOG_IF(FATAL, NULL == _status) << "Fail to new MethodStatus"; -} + : _status(new MethodStatus) + , _ignore_eovercrowded(false) {} BaiduMasterService::~BaiduMasterService() { delete _status; - _status = NULL; + _status = nullptr; } void BaiduMasterService::Describe(std::ostream &os, @@ -37,9 +36,6 @@ void BaiduMasterService::Describe(std::ostream &os, } void BaiduMasterService::Expose(const butil::StringPiece& prefix) { - if (NULL == _status) { - return; - } std::string s; const std::string& cached_name = butil::class_name_str(*this); s.reserve(prefix.size() + 1 + cached_name.size()); diff --git a/src/brpc/channel.cpp b/src/brpc/channel.cpp index 83fc37b077..01d8637564 100644 --- a/src/brpc/channel.cpp +++ b/src/brpc/channel.cpp @@ -64,10 +64,10 @@ ChannelOptions::ChannelOptions() , succeed_without_server(true) , log_succeed_without_server(true) , socket_mode(SOCKET_MODE_TCP) - , auth(NULL) - , backup_request_policy(NULL) - , retry_policy(NULL) - , ns_filter(NULL) + , auth(nullptr) + , backup_request_policy(nullptr) + , retry_policy(nullptr) + , ns_filter(nullptr) {} ChannelSSLOptions* ChannelOptions::mutable_ssl_options() { @@ -78,7 +78,7 @@ ChannelSSLOptions* ChannelOptions::mutable_ssl_options() { } static ChannelSignature ComputeChannelSignature(const ChannelOptions& opt) { - if (opt.auth == NULL && + if (opt.auth == nullptr && !opt.has_ssl_options() && opt.client_host.empty() && opt.device_name.empty() && @@ -167,9 +167,9 @@ static ChannelSignature ComputeChannelSignature(const ChannelOptions& opt) { Channel::Channel(ProfilerLinker) : _server_id(INVALID_SOCKET_ID) - , _serialize_request(NULL) - , _pack_request(NULL) - , _get_method_name(NULL) + , _serialize_request(nullptr) + , _pack_request(nullptr) + , _get_method_name(nullptr) , _preferred_index(-1) { } @@ -186,7 +186,7 @@ int Channel::InitChannelOptions(const ChannelOptions* options) { _options = *options; } const Protocol* protocol = FindProtocol(_options.protocol); - if (NULL == protocol || !protocol->support_client()) { + if (nullptr == protocol || !protocol->support_client()) { LOG(ERROR) << "Channel does not support the protocol"; return -1; } @@ -238,7 +238,7 @@ int Channel::InitChannelOptions(const ChannelOptions* options) { } if (_options.protocol == PROTOCOL_ESP) { - if (_options.auth == NULL) { + if (_options.auth == nullptr) { _options.auth = policy::global_esp_authenticator(); } } @@ -258,11 +258,11 @@ int Channel::Init(const char* server_addr_and_port, butil::EndPoint point; const AdaptiveProtocolType& ptype = (options ? options->protocol : _options.protocol); const Protocol* protocol = FindProtocol(ptype); - if (protocol == NULL || !protocol->support_client()) { + if (protocol == nullptr || !protocol->support_client()) { LOG(ERROR) << "Channel does not support the protocol"; return -1; } - if (protocol->parse_server_address != NULL) { + if (protocol->parse_server_address != nullptr) { if (!protocol->parse_server_address(&point, server_addr_and_port)) { LOG(ERROR) << "Fail to parse address=`" << server_addr_and_port << '\''; return -1; @@ -291,11 +291,11 @@ int Channel::Init(const char* server_addr, int port, butil::EndPoint point; const AdaptiveProtocolType& ptype = (options ? options->protocol : _options.protocol); const Protocol* protocol = FindProtocol(ptype); - if (protocol == NULL || !protocol->support_client()) { + if (protocol == nullptr || !protocol->support_client()) { LOG(ERROR) << "Channel does not support the protocol"; return -1; } - if (protocol->parse_server_address != NULL) { + if (protocol->parse_server_address != nullptr) { if (!protocol->parse_server_address(&point, server_addr)) { LOG(ERROR) << "Fail to parse address=`" << server_addr << '\''; return -1; @@ -324,7 +324,7 @@ static int CreateSocketSSLContext(const ChannelOptions& options, (*ssl_ctx)->sni_name = options.ssl_options().sni_name; (*ssl_ctx)->alpn_protocols = options.ssl_options().alpn_protocols; } else { - (*ssl_ctx) = NULL; + (*ssl_ctx) = nullptr; } return 0; } @@ -362,7 +362,7 @@ int Channel::InitSingle(const butil::EndPoint& server_addr_and_port, if (InitChannelOptions(options) != 0) { return -1; } - int* port_out = raw_port == -1 ? &raw_port: NULL; + int* port_out = raw_port == -1 ? &raw_port: nullptr; ParseURL(raw_server_address, &_scheme, &_service_name, port_out); const std::string host = _service_name; if (raw_port != -1) { @@ -406,7 +406,7 @@ int Channel::InitSingle(const butil::EndPoint& server_addr_and_port, int Channel::Init(const char* ns_url, const char* lb_name, const ChannelOptions* options) { - if (lb_name == NULL || *lb_name == '\0') { + if (lb_name == nullptr || *lb_name == '\0') { // Treat ns_url as server_addr_and_port return Init(ns_url, options); } @@ -430,12 +430,7 @@ int Channel::Init(const char* ns_url, LOG(ERROR) << "Invalid client host=`" << _options.client_host << '\''; return -1; } - std::unique_ptr lb(new (std::nothrow) - LoadBalancerWithNaming); - if (NULL == lb) { - LOG(FATAL) << "Fail to new LoadBalancerWithNaming"; - return -1; - } + std::unique_ptr lb(new LoadBalancerWithNaming); GetNamingServiceThreadOptions ns_opt; ns_opt.succeed_without_server = _options.succeed_without_server; ns_opt.log_succeed_without_server = _options.log_succeed_without_server; @@ -502,7 +497,7 @@ void Channel::CallMethod(const google::protobuf::MethodDescriptor* method, } const CallId correlation_id = cntl->call_id(); const int rc = bthread_id_lock_and_reset_range( - correlation_id, NULL, 2 + cntl->max_retry()); + correlation_id, nullptr, 2 + cntl->max_retry()); if (rc != 0) { CHECK_EQ(EINVAL, rc); if (!cntl->FailedInline()) { @@ -526,7 +521,7 @@ void Channel::CallMethod(const google::protobuf::MethodDescriptor* method, } cntl->set_used_by_rpc(); - if (cntl->_sender == NULL && IsTraceable(Span::tls_parent().get())) { + if (cntl->_sender == nullptr && IsTraceable(Span::tls_parent().get())) { const int64_t start_send_us = butil::cpuwide_time_us(); std::string method_name; if (_get_method_name) { @@ -557,7 +552,7 @@ void Channel::CallMethod(const google::protobuf::MethodDescriptor* method, // one in ChannelOptions cntl->_connect_timeout_ms = _options.connect_timeout_ms; if (cntl->backup_request_ms() == UNSET_MAGIC_NUM && - NULL == cntl->_backup_request_policy) { + nullptr == cntl->_backup_request_policy) { cntl->set_backup_request_ms(_options.backup_request_ms); cntl->_backup_request_policy = _options.backup_request_policy; } @@ -588,7 +583,7 @@ void Channel::CallMethod(const google::protobuf::MethodDescriptor* method, return cntl->HandleSendFailed(); } if (FLAGS_usercode_in_pthread && - done != NULL && + done != nullptr && TooManyUserCode()) { cntl->SetFailed(ELIMIT, "Too many user code to run when " "-usercode_in_pthread is on"); @@ -599,7 +594,7 @@ void Channel::CallMethod(const google::protobuf::MethodDescriptor* method, // Currently we cannot handle retry and backup request correctly cntl->set_max_retry(0); cntl->set_backup_request_ms(-1); - cntl->_backup_request_policy = NULL; + cntl->_backup_request_policy = nullptr; } if (cntl->backup_request_ms() >= 0 && @@ -642,7 +637,7 @@ void Channel::CallMethod(const google::protobuf::MethodDescriptor* method, } cntl->IssueRPC(start_send_real_us); - if (done == NULL) { + if (done == nullptr) { // MUST wait for response when sending synchronous RPC. It will // be woken up by callback when RPC finishes (succeeds or still // fails after retry) @@ -667,7 +662,7 @@ int Channel::Weight() { } int Channel::CheckHealth() { - if (_lb == NULL) { + if (_lb == nullptr) { SocketUniquePtr ptr; if (Socket::Address(_server_id, &ptr) == 0 && ptr->IsAvailable()) { return 0; @@ -675,7 +670,7 @@ int Channel::CheckHealth() { return -1; } else { SocketUniquePtr tmp_sock; - LoadBalancer::SelectIn sel_in = { 0, false, true, 0, NULL }; + LoadBalancer::SelectIn sel_in = { 0, false, true, 0, nullptr }; LoadBalancer::SelectOut sel_out(&tmp_sock); return _lb->SelectServer(sel_in, &sel_out); } diff --git a/src/brpc/channel.h b/src/brpc/channel.h index 28a17ac8ea..d13ae52df6 100644 --- a/src/brpc/channel.h +++ b/src/brpc/channel.h @@ -102,7 +102,7 @@ struct ChannelOptions { bool log_succeed_without_server; // SSL related options. Refer to `ChannelSSLOptions' for details - bool has_ssl_options() const { return _ssl_options != NULL; } + bool has_ssl_options() const { return _ssl_options != nullptr; } const ChannelSSLOptions& ssl_options() const { return *_ssl_options; } ChannelSSLOptions* mutable_ssl_options(); @@ -110,10 +110,10 @@ struct ChannelOptions { // Default: SOCKET_MODE_TCP SocketMode socket_mode; - // Turn on authentication for this channel if `auth' is not NULL. + // Turn on authentication for this channel if `auth' is not nullptr. // Note `auth' will not be deleted by channel and must remain valid when // the channel is being used. - // Default: NULL + // Default: nullptr const Authenticator* auth; // Customize the backup request time and whether to send backup request. @@ -122,14 +122,14 @@ struct ChannelOptions { // Controller.set_backup_request_policy(). // This object is NOT owned by channel and should remain valid during // channel's lifetime. - // Default: NULL + // Default: nullptr BackupRequestPolicy* backup_request_policy; // Customize the error code that should be retried. The interface is // defined in src/brpc/retry_policy.h // This object is NOT owned by channel and should remain valid when // channel is used. - // Default: NULL + // Default: nullptr const RetryPolicy* retry_policy; // Filter ServerNodes (i.e. based on `tag' field of `ServerNode') @@ -137,7 +137,7 @@ struct ChannelOptions { // in src/brpc/naming_service_filter.h // This object is NOT owned by channel and should remain valid when // channel is used. - // Default: NULL + // Default: nullptr const NamingServiceFilter* ns_filter; // Channels with same connection_group share connections. @@ -172,9 +172,9 @@ struct ChannelOptions { // instead construct a stub Service wrapping it. // Example: // brpc::Channel channel; -// channel.Init("bns://rdev.matrix.all", "rr", NULL/*default options*/); +// channel.Init("bns://rdev.matrix.all", "rr", nullptr/*default options*/); // MyService_Stub stub(&channel); -// stub.MyMethod(&controller, &request, &response, NULL); +// stub.MyMethod(&controller, &request, &response, nullptr); class Channel : public ChannelBase { friend class Controller; friend class SelectiveChannel; @@ -185,7 +185,7 @@ friend class SelectiveChannel; DISALLOW_COPY_AND_ASSIGN(Channel); // Connect this channel to a single server whose address is given by the - // first parameter. Use default options if `options' is NULL. + // first parameter. Use default options if `options' is nullptr. int Init(butil::EndPoint server_addr_and_port, const ChannelOptions* options); int Init(const char* server_addr_and_port, const ChannelOptions* options); int Init(const char* server_addr, int port, const ChannelOptions* options); @@ -193,7 +193,7 @@ friend class SelectiveChannel; // Connect this channel to a group of servers whose addresses can be // accessed via `naming_service_url' according to its protocol. Use the // method specified by `load_balancer_name' to distribute traffic to - // servers. Use default options if `options' is NULL. + // servers. Use default options if `options' is nullptr. // Supported naming service("protocol://service_name"): // bns:// # Baidu Naming Service // file:// # load addresses from the file @@ -206,8 +206,8 @@ friend class SelectiveChannel; // wrr # weighted round robin // la # locality aware // c_murmurhash/c_md5 # consistent hashing with murmurhash3/md5 - // "" or NULL # treat `naming_service_url' as `server_addr_and_port' - // # Init(xxx, "", options) and Init(xxx, NULL, options) + // "" or nullptr # treat `naming_service_url' as `server_addr_and_port' + // # Init(xxx, "", options) and Init(xxx, nullptr, options) // # are exactly same with Init(xxx, options) int Init(const char* naming_service_url, const char* load_balancer_name, @@ -215,7 +215,7 @@ friend class SelectiveChannel; // Call `method' of the remote service with `request' as input, and // `response' as output. `controller' contains options and extra data. - // If `done' is not NULL, this method returns after request was sent + // If `done' is not nullptr, this method returns after request was sent // and `done->Run()' will be called when the call finishes, otherwise // caller blocks until the call finishes. void CallMethod(const google::protobuf::MethodDescriptor* method, @@ -235,12 +235,12 @@ friend class SelectiveChannel; int CheckHealth(); protected: - bool SingleServer() const { return _lb.get() == NULL; } + bool SingleServer() const { return _lb.get() == nullptr; } // Pick a server using `lb' and then send RPC. Wait for response when // sending synchronous RPC. // NOTE: DO NOT directly use `controller' after this call when - // sending asynchronous RPC (controller->_done != NULL) since + // sending asynchronous RPC (controller->_done != nullptr) since // user callback `done' could be called when it returns and // therefore destroy the `controller' inside `done' static void CallMethodImpl(Controller* controller, SharedLoadBalancer* lb); diff --git a/src/brpc/checksum.cpp b/src/brpc/checksum.cpp index 85d04d852a..13fae81d4c 100644 --- a/src/brpc/checksum.cpp +++ b/src/brpc/checksum.cpp @@ -23,10 +23,10 @@ namespace brpc { static const int MAX_HANDLER_SIZE = 1024; -static ChecksumHandler s_handler_map[MAX_HANDLER_SIZE] = {{NULL, NULL, NULL}}; +static ChecksumHandler s_handler_map[MAX_HANDLER_SIZE] = {{nullptr, nullptr, nullptr}}; int RegisterChecksumHandler(ChecksumType type, ChecksumHandler handler) { - if (NULL == handler.Compute) { + if (nullptr == handler.Compute) { LOG(FATAL) << "Invalid parameter: handler function is NULL"; return -1; } @@ -35,7 +35,7 @@ int RegisterChecksumHandler(ChecksumType type, ChecksumHandler handler) { LOG(FATAL) << "ChecksumType=" << type << " is out of range"; return -1; } - if (s_handler_map[index].Compute != NULL) { + if (s_handler_map[index].Compute != nullptr) { LOG(FATAL) << "ChecksumType=" << type << " was registered"; return -1; } @@ -44,15 +44,15 @@ int RegisterChecksumHandler(ChecksumType type, ChecksumHandler handler) { } // Find ChecksumHandler by type. -// Returns NULL if not found +// Returns nullptr if not found inline const ChecksumHandler* FindChecksumHandler(ChecksumType type) { int index = type; if (index < 0 || index >= MAX_HANDLER_SIZE) { LOG(ERROR) << "ChecksumType=" << type << " is out of range"; - return NULL; + return nullptr; } - if (NULL == s_handler_map[index].Compute) { - return NULL; + if (nullptr == s_handler_map[index].Compute) { + return nullptr; } return &s_handler_map[index]; } @@ -62,13 +62,13 @@ const char* ChecksumTypeToCStr(ChecksumType type) { return "none"; } const ChecksumHandler* handler = FindChecksumHandler(type); - return (handler != NULL ? handler->name : "unknown"); + return (handler != nullptr ? handler->name : "unknown"); } void ListChecksumHandler(std::vector* vec) { vec->clear(); for (int i = 0; i < MAX_HANDLER_SIZE; ++i) { - if (s_handler_map[i].Compute != NULL) { + if (s_handler_map[i].Compute != nullptr) { vec->push_back(s_handler_map[i]); } } @@ -80,7 +80,7 @@ void ComputeDataChecksum(const ChecksumIn& in, ChecksumType checksum_type) { return; } const ChecksumHandler* handler = FindChecksumHandler(checksum_type); - if (NULL != handler) { + if (nullptr != handler) { handler->Compute(in); } } @@ -91,7 +91,7 @@ bool VerifyDataChecksum(const ChecksumIn& in, ChecksumType checksum_type) { return true; } const ChecksumHandler* handler = FindChecksumHandler(checksum_type); - if (NULL != handler) { + if (nullptr != handler) { return handler->Verify(in); } return true; diff --git a/src/brpc/checksum.h b/src/brpc/checksum.h index 854b578a25..75d15dcb6a 100644 --- a/src/brpc/checksum.h +++ b/src/brpc/checksum.h @@ -26,14 +26,14 @@ namespace brpc { struct ChecksumIn { ChecksumIn(const butil::IOBuf* buf, Controller* cntl, - const butil::IOBuf* attachment = NULL) + const butil::IOBuf* attachment = nullptr) : buf(buf), cntl(cntl), attachment(attachment) {} const butil::IOBuf* buf; Controller* cntl; - // Attachment to fold into the checksum in addition to `buf', or NULL if + // Attachment to fold into the checksum in addition to `buf', or nullptr if // the checksum should cover `buf' only (the default, pre-existing - // behavior). When non-NULL, implementations must extend the checksum + // behavior). When non-nullptr, implementations must extend the checksum // with `buf' first and `attachment' second, so that both sides of the // RPC (which independently decide whether to pass an attachment here // based on Controller::request/response_checksum_attachment()) compute diff --git a/src/brpc/closure_guard.h b/src/brpc/closure_guard.h index c1405b5a35..ec5b05f3d3 100644 --- a/src/brpc/closure_guard.h +++ b/src/brpc/closure_guard.h @@ -28,19 +28,19 @@ namespace brpc { // RAII: Call Run() of the closure on destruction. class ClosureGuard { public: - ClosureGuard() : _done(NULL) {} + ClosureGuard() : _done(nullptr) {} // Constructed with a closure which will be Run() inside dtor. explicit ClosureGuard(google::protobuf::Closure* done) : _done(done) {} - // Run internal closure if it's not NULL. + // Run internal closure if it's not nullptr. ~ClosureGuard() { if (_done) { _done->Run(); } } - // Run internal closure if it's not NULL and set it to `done'. + // Run internal closure if it's not nullptr and set it to `done'. void reset(google::protobuf::Closure* done) { if (_done) { _done->Run(); @@ -48,15 +48,15 @@ class ClosureGuard { _done = done; } - // Return and set internal closure to NULL. + // Return and set internal closure to nullptr. google::protobuf::Closure* release() { google::protobuf::Closure* const prev_done = _done; - _done = NULL; + _done = nullptr; return prev_done; } // True if no closure inside. - bool empty() const { return _done == NULL; } + bool empty() const { return _done == nullptr; } // Exchange closure with another guard. void swap(ClosureGuard& other) { std::swap(_done, other._done); } diff --git a/src/brpc/compress.cpp b/src/brpc/compress.cpp index 36e55c7cdc..9f9939c9f3 100644 --- a/src/brpc/compress.cpp +++ b/src/brpc/compress.cpp @@ -25,11 +25,11 @@ namespace brpc { static const int MAX_HANDLER_SIZE = 1024; -static CompressHandler s_handler_map[MAX_HANDLER_SIZE] = { { NULL, NULL, NULL } }; +static CompressHandler s_handler_map[MAX_HANDLER_SIZE] = { { nullptr, nullptr, nullptr } }; int RegisterCompressHandler(CompressType type, CompressHandler handler) { - if (NULL == handler.Compress || NULL == handler.Decompress) { + if (nullptr == handler.Compress || nullptr == handler.Decompress) { LOG(FATAL) << "Invalid parameter: handler function is NULL"; return -1; } @@ -38,7 +38,7 @@ int RegisterCompressHandler(CompressType type, LOG(FATAL) << "CompressType=" << type << " is out of range"; return -1; } - if (s_handler_map[index].Compress != NULL) { + if (s_handler_map[index].Compress != nullptr) { LOG(FATAL) << "CompressType=" << type << " was registered"; return -1; } @@ -47,15 +47,15 @@ int RegisterCompressHandler(CompressType type, } // Find CompressHandler by type. -// Returns NULL if not found +// Returns nullptr if not found const CompressHandler* FindCompressHandler(CompressType type) { int index = type; if (index < 0 || index >= MAX_HANDLER_SIZE) { LOG(ERROR) << "CompressType=" << type << " is out of range"; - return NULL; + return nullptr; } - if (NULL == s_handler_map[index].Compress) { - return NULL; + if (nullptr == s_handler_map[index].Compress) { + return nullptr; } return &s_handler_map[index]; } @@ -65,13 +65,13 @@ const char* CompressTypeToCStr(CompressType type) { return "none"; } const CompressHandler* handler = FindCompressHandler(type); - return (handler != NULL ? handler->name : "unknown"); + return (handler != nullptr ? handler->name : "unknown"); } void ListCompressHandler(std::vector* vec) { vec->clear(); for (int i = 0; i < MAX_HANDLER_SIZE; ++i) { - if (s_handler_map[i].Compress != NULL) { + if (s_handler_map[i].Compress != nullptr) { vec->push_back(s_handler_map[i]); } } @@ -84,7 +84,7 @@ bool ParseFromCompressedData(const butil::IOBuf& data, return ParsePbFromIOBuf(msg, data); } const CompressHandler* handler = FindCompressHandler(compress_type); - if (NULL == handler) { + if (nullptr == handler) { return false; } @@ -101,7 +101,7 @@ bool SerializeAsCompressedData(const google::protobuf::Message& msg, return msg.SerializeToZeroCopyStream(&wrapper); } const CompressHandler* handler = FindCompressHandler(compress_type); - if (NULL == handler) { + if (nullptr == handler) { return false; } diff --git a/src/brpc/compress.h b/src/brpc/compress.h index 4529959873..a6c61648e3 100644 --- a/src/brpc/compress.h +++ b/src/brpc/compress.h @@ -33,7 +33,7 @@ class Serializer : public NonreflectableMessage { public: using Callback = std::function; - Serializer() :Serializer(NULL) {} + Serializer() :Serializer(nullptr) {} explicit Serializer(Callback callback) :_callback(std::move(callback)) { @@ -100,7 +100,7 @@ class Deserializer : public NonreflectableMessage { public: using Callback = std::function; - Deserializer() :Deserializer(NULL) {} + Deserializer() :Deserializer(nullptr) {} explicit Deserializer(Callback callback) : _callback(std::move(callback)) { SharedCtor(); @@ -175,7 +175,7 @@ struct CompressHandler { // Returns 0 on success, -1 otherwise int RegisterCompressHandler(CompressType type, CompressHandler handler); -// Returns CompressHandler pointer of `type' if registered, NULL otherwise. +// Returns CompressHandler pointer of `type' if registered, nullptr otherwise. const CompressHandler* FindCompressHandler(CompressType type); // Returns the `name' of the CompressType if registered diff --git a/src/brpc/controller.cpp b/src/brpc/controller.cpp index 8a8410beb9..062d62f031 100644 --- a/src/brpc/controller.cpp +++ b/src/brpc/controller.cpp @@ -114,7 +114,7 @@ static void PrintRevision(std::ostream& os, void*) { #endif } static bvar::PassiveStatus s_rpc_revision( - "rpc_revision", PrintRevision, NULL); + "rpc_revision", PrintRevision, nullptr); static const int RETRY_AVOIDANCE = 8; @@ -128,7 +128,7 @@ const Controller* GetSubControllerOfSelectiveChannel( DECLARE_bool(usercode_in_pthread); DECLARE_bool(usercode_in_coroutine); static const int MAX_RETRY_COUNT = 1000; -static bvar::Adder* g_ncontroller = NULL; +static bvar::Adder* g_ncontroller = nullptr; static pthread_once_t s_create_vars_once = PTHREAD_ONCE_INIT; @@ -174,7 +174,7 @@ class IgnoreAllRead : public ProgressiveReader { void OnEndOfMessage(const butil::Status&) {} }; -static IgnoreAllRead* s_ignore_all_read = NULL; +static IgnoreAllRead* s_ignore_all_read = nullptr; static pthread_once_t s_ignore_all_read_once = PTHREAD_ONCE_INIT; static void CreateIgnoreAllRead() { s_ignore_all_read = new IgnoreAllRead; } @@ -206,7 +206,7 @@ void Controller::ResetNonPods() { DestroyParallelChannelDone(_done); } delete _sender; - _lb.reset(NULL); + _lb.reset(nullptr); _current_call.Reset(); ExcludedServers::Destroy(_accessed); _request_buf.clear(); @@ -218,9 +218,9 @@ void Controller::ResetNonPods() { _response_attachment.clear(); if (_wpa) { _wpa->MarkRPCAsDone(Failed()); - _wpa.reset(NULL); + _wpa.reset(nullptr); } - if (_rpa != NULL) { + if (_rpa != nullptr) { if (!has_progressive_reader()) { // Never called ReadProgressiveAttachmentBy (successfully), the data // is probably being buffered and a full buffer may block parse @@ -229,14 +229,14 @@ void Controller::ResetNonPods() { pthread_once(&s_ignore_all_read_once, CreateIgnoreAllRead); _rpa->ReadProgressiveAttachmentBy(s_ignore_all_read); } - _rpa.reset(NULL); + _rpa.reset(nullptr); } delete _remote_stream_settings; _bind_sock.reset(); _thrift_method_name.clear(); _after_rpc_resp_fn = nullptr; - CHECK(_unfinished_call == NULL); + CHECK(_unfinished_call == nullptr); } void Controller::ResetPods() { @@ -247,19 +247,19 @@ void Controller::ResetPods() { set_pb_bytes_to_base64(true); #endif _error_code = 0; - _session_local_data = NULL; - _server = NULL; + _session_local_data = nullptr; + _server = nullptr; _oncancel_id = INVALID_BTHREAD_ID; - _auth_context = NULL; - _sampled_request = NULL; + _auth_context = nullptr; + _sampled_request = nullptr; _request_protocol = PROTOCOL_UNKNOWN; _max_retry = UNSET_MAGIC_NUM; - _retry_policy = NULL; + _retry_policy = nullptr; _correlation_id = INVALID_BTHREAD_ID; _connection_type = CONNECTION_TYPE_UNKNOWN; _timeout_ms = UNSET_MAGIC_NUM; _backup_request_ms = UNSET_MAGIC_NUM; - _backup_request_policy = NULL; + _backup_request_policy = nullptr; _connect_timeout_ms = UNSET_MAGIC_NUM; _real_timeout_ms = UNSET_MAGIC_NUM; _deadline_us = -1; @@ -276,29 +276,29 @@ void Controller::ResetPods() { _pipelined_count = 0; _inheritable.Reset(); _pchan_sub_count = 0; - _response = NULL; - _done = NULL; - _sender = NULL; + _response = nullptr; + _done = nullptr; + _sender = nullptr; _request_code = 0; _single_server_id = INVALID_SOCKET_ID; - _unfinished_call = NULL; - _stream_creator = NULL; - _accessed = NULL; - _pack_request = NULL; - _method = NULL; - _auth = NULL; + _unfinished_call = nullptr; + _stream_creator = nullptr; + _accessed = nullptr; + _pack_request = nullptr; + _method = nullptr; + _auth = nullptr; _idl_names = idl_single_req_single_res; _idl_result = IDL_VOID_RESULT; - _http_request = NULL; - _http_response = NULL; - _request_user_fields = NULL; - _response_user_fields = NULL; + _http_request = nullptr; + _http_response = nullptr; + _request_user_fields = nullptr; + _response_user_fields = nullptr; _request_content_type = CONTENT_TYPE_PB; _response_content_type = CONTENT_TYPE_PB; _request_streams.clear(); _response_streams.clear(); - _remote_stream_settings = NULL; - _session_data = NULL; + _remote_stream_settings = nullptr; + _session_data = nullptr; _auth_flags = 0; _rpc_received_us = 0; } @@ -318,11 +318,11 @@ Controller::Call::Call(Controller::Call* rhs) // will behave incorrectly. rhs->need_feedback = false; rhs->peer_id = INVALID_SOCKET_ID; - rhs->stream_user_data = NULL; + rhs->stream_user_data = nullptr; } Controller::Call::~Call() { - CHECK(sending_sock.get() == NULL); + CHECK(sending_sock.get() == nullptr); } void Controller::Call::Reset() { @@ -331,9 +331,9 @@ void Controller::Call::Reset() { enable_circuit_breaker = false; peer_id = INVALID_SOCKET_ID; begin_time_us = 0; - sending_sock.reset(NULL); + sending_sock.reset(nullptr); bind_sock_action = BIND_SOCK_NONE; - stream_user_data = NULL; + stream_user_data = nullptr; } void Controller::set_timeout_ms(int64_t timeout_ms) { @@ -357,7 +357,7 @@ void Controller::set_backup_request_ms(int64_t timeout_ms) { int64_t Controller::backup_request_ms() const { int timeout_ms = _backup_request_ms; - if (NULL != _backup_request_policy) { + if (nullptr != _backup_request_policy) { const int32_t policy_ms = _backup_request_policy->GetBackupRequestMs(this); // -1 is the designated sentinel: the policy defers to the channel-level // backup_request_ms (set from ChannelOptions). Any other negative value @@ -410,7 +410,7 @@ void Controller::StartCancel() { static const char HEX_ALPHA[] = "0123456789ABCDEF"; void Controller::AppendServerIdentiy() { - if (_server == NULL) { + if (_server == nullptr) { return; } if (is_security_mode()) { @@ -441,7 +441,7 @@ inline void UpdateResponseHeader(Controller* cntl) { cntl->http_response().set_status_code( ErrorCodeToStatusCode(cntl->ErrorCode())); } // else assume that status code is already set along with EHTTP. - if (cntl->server() != NULL) { + if (cntl->server() != nullptr) { // Override HTTP body at server-side to conduct error text // to the client. // The client-side should preserve body which may be a piece @@ -539,7 +539,7 @@ class RunOnCancelThread { static void* RunThis(void* arg) { ((RunOnCancelThread*)arg)->Run(); - return NULL; + return nullptr; } void Run() { @@ -567,12 +567,12 @@ int Controller::RunOnCancel(bthread_id_t id, void* data, int error_code) { RunOnCancelThread* arg = new RunOnCancelThread( static_cast(data), id); bthread_t th; - CHECK_EQ(0, bthread_start_urgent(&th, NULL, RunOnCancelThread::RunThis, arg)); + CHECK_EQ(0, bthread_start_urgent(&th, nullptr, RunOnCancelThread::RunThis, arg)); return 0; } void Controller::NotifyOnCancel(google::protobuf::Closure* callback) { - if (NULL == callback) { + if (nullptr == callback) { LOG(WARNING) << "Parameter `callback' is NLLL"; return; } @@ -621,7 +621,7 @@ void Controller::OnVersionedRPCReturned(const CompletionInfo& info, // Complete failed backup request. _unfinished_call->OnComplete(this, _error_code, info.responded, false); delete _unfinished_call; - _unfinished_call = NULL; + _unfinished_call = nullptr; } // Ignore all non-backup requests and failed backup requests. _error_code = saved_error; @@ -640,12 +640,12 @@ void Controller::OnVersionedRPCReturned(const CompletionInfo& info, return; } - if ((!_error_code && _retry_policy == NULL) || + if ((!_error_code && _retry_policy == nullptr) || _current_call.nretry >= _max_retry) { goto END_OF_RPC; } if (_error_code == EBACKUPREQUEST) { - if (NULL != _backup_request_policy && !_backup_request_policy->DoBackup(this)) { + if (nullptr != _backup_request_policy && !_backup_request_policy->DoBackup(this)) { // No need to do backup request. _error_code = saved_error; CHECK_EQ(0, bthread_id_unlock(info.id)); @@ -665,10 +665,10 @@ void Controller::OnVersionedRPCReturned(const CompletionInfo& info, goto END_OF_RPC; } if (!SingleServer()) { - if (_accessed == NULL) { + if (_accessed == nullptr) { _accessed = ExcludedServers::Create( std::min(_max_retry, RETRY_AVOIDANCE)); - if (NULL == _accessed) { + if (nullptr == _accessed) { SetFailed(ENOMEM, "Fail to create ExcludedServers"); goto END_OF_RPC; } @@ -676,12 +676,8 @@ void Controller::OnVersionedRPCReturned(const CompletionInfo& info, _accessed->Add(_current_call.peer_id); } // _current_call does not end yet. - CHECK(_unfinished_call == NULL); // only one backup request now. - _unfinished_call = new (std::nothrow) Call(&_current_call); - if (_unfinished_call == NULL) { - SetFailed(ENOMEM, "Fail to new Call"); - goto END_OF_RPC; - } + CHECK(_unfinished_call == nullptr); // only one backup request now. + _unfinished_call = new Call(&_current_call); ++_current_call.nretry; add_flag(FLAGS_BACKUP_REQUEST); return IssueRPC(butil::gettimeofday_us()); @@ -693,10 +689,10 @@ void Controller::OnVersionedRPCReturned(const CompletionInfo& info, // * ERPCTIMEDOUT/ECANCELED are not retrying error by default. CHECK_EQ(current_id(), info.id) << "error_code=" << _error_code; if (!SingleServer()) { - if (_accessed == NULL) { + if (_accessed == nullptr) { _accessed = ExcludedServers::Create( std::min(_max_retry, RETRY_AVOIDANCE)); - if (NULL == _accessed) { + if (nullptr == _accessed) { SetFailed(ENOMEM, "Fail to create ExcludedServers"); goto END_OF_RPC; } @@ -757,7 +753,7 @@ void Controller::OnVersionedRPCReturned(const CompletionInfo& info, // FLAGS_DESTROY_CID_IN_DONE to true must be aware of // -usercode_in_pthread and avoid deadlock by their own (TBR) - if ((FLAGS_usercode_in_pthread || _done != NULL/*Note[_done]*/) && + if ((FLAGS_usercode_in_pthread || _done != nullptr/*Note[_done]*/) && !has_flag(FLAGS_DESTROY_CID_IN_DONE)/*Note[cid]*/) { bthread_id_about_to_destroy(info.id); } @@ -773,7 +769,7 @@ void Controller::OnVersionedRPCReturned(const CompletionInfo& info, EndRPC(info); } } else { - if (_done != NULL/*Note[_done]*/ && + if (_done != nullptr/*Note[_done]*/ && !has_flag(FLAGS_DESTROY_CID_IN_DONE)/*Note[cid]*/) { bthread_id_about_to_destroy(info.id); } @@ -784,7 +780,7 @@ void Controller::OnVersionedRPCReturned(const CompletionInfo& info, void* Controller::RunEndRPC(void* arg) { Controller* c = static_cast(arg); c->EndRPC(c->_tmp_completion_info); - return NULL; + return nullptr; } inline bool does_error_affect_main_socket(int error_code) { @@ -805,10 +801,10 @@ void Controller::Call::OnComplete( Controller* c, int error_code/*note*/, bool responded, bool end_of_rpc) { if (stream_user_data) { stream_user_data->DestroyStreamUserData(sending_sock, c, error_code, end_of_rpc); - stream_user_data = NULL; + stream_user_data = nullptr; } - if (sending_sock != NULL) { + if (sending_sock != nullptr) { if (error_code != 0) { sending_sock->AddRecentError(); } @@ -826,9 +822,9 @@ void Controller::Call::OnComplete( // Set main socket to be failed for connection refusal of streams. // "single" streams are often maintained in a separate SocketMap and // different from the main socket as well. - if (c->_stream_creator != NULL && + if (c->_stream_creator != nullptr && does_error_affect_main_socket(error_code) && - (sending_sock == NULL || sending_sock->id() != peer_id)) { + (sending_sock == nullptr || sending_sock->id() != peer_id)) { Socket::SetFailed(peer_id); } break; @@ -838,7 +834,7 @@ void Controller::Call::OnComplete( // Otherwise in-flight responses may come back in future and break the // assumption that one pooled connection cannot have more than one // message at the same time. - if (sending_sock != NULL && (error_code == 0 || responded)) { + if (sending_sock != nullptr && (error_code == 0 || responded)) { if (bind_sock_action == BIND_SOCK_RESERVE) { // Reserve this socket on the controller for a following RPC // (used by mysql transactions for connection affinity). @@ -860,14 +856,14 @@ void Controller::Call::OnComplete( } // fall through case CONNECTION_TYPE_SHORT: - if (sending_sock != NULL) { + if (sending_sock != nullptr) { // Check the comment in CONNECTION_TYPE_POOLED branch. if (bind_sock_action == BIND_SOCK_RESERVE) { c->_bind_sock.reset(sending_sock.release()); } else if (bind_sock_action == BIND_SOCK_USE) { // Socket is owned by the binder; do not fail it. } else if (!sending_sock->is_read_progressive()) { - if (c->_stream_creator == NULL) { + if (c->_stream_creator == nullptr) { sending_sock->SetFailed(); } } else { @@ -902,7 +898,7 @@ void Controller::Call::OnComplete( } // Release the `Socket' we used to send/receive data - sending_sock.reset(NULL); + sending_sock.reset(nullptr); } void Controller::EndRPC(const CompletionInfo& info) { @@ -915,12 +911,12 @@ void Controller::EndRPC(const CompletionInfo& info) { // End _current_call and _unfinished_call. if (info.id == current_id() || info.id == _correlation_id) { - if (_current_call.sending_sock != NULL) { + if (_current_call.sending_sock != nullptr) { _remote_side = _current_call.sending_sock->remote_side(); _local_side = _current_call.sending_sock->local_side(); } - if (_unfinished_call != NULL) { + if (_unfinished_call != nullptr) { // When _current_call is successful, mark _unfinished_call as // EBACKUPREQUEST, we can't use 0 because the server possibly // never respond, we can't use ERPCTIMEDOUT because _current_call @@ -931,7 +927,7 @@ void Controller::EndRPC(const CompletionInfo& info) { const int err = (_error_code == 0 ? EBACKUPREQUEST : _error_code); _unfinished_call->OnComplete(this, err, false, false); delete _unfinished_call; - _unfinished_call = NULL; + _unfinished_call = nullptr; } // TODO: Replace this with stream_creator. HandleStreamConnection(_current_call.sending_sock.get()); @@ -944,7 +940,7 @@ void Controller::EndRPC(const CompletionInfo& info) { // (which gets punished in LALB) for _current_call because _current_call // is sent after _unfinished_call, it's just normal that _current_call // does not respond before _unfinished_call. - if (_unfinished_call == NULL) { + if (_unfinished_call == nullptr) { CHECK(false) << "A previous non-backup request responded, cid=" << info.id << " current_cid=" << current_id() << " initial_cid=" << _correlation_id @@ -952,8 +948,8 @@ void Controller::EndRPC(const CompletionInfo& info) { << " sending_sock=" << _current_call.sending_sock.get(); } _current_call.OnComplete(this, ECANCELED, false, false); - if (_unfinished_call != NULL) { - if (_unfinished_call->sending_sock != NULL) { + if (_unfinished_call != nullptr) { + if (_unfinished_call->sending_sock != nullptr) { _remote_side = _unfinished_call->sending_sock->remote_side(); _local_side = _unfinished_call->sending_sock->local_side(); } @@ -968,12 +964,12 @@ void Controller::EndRPC(const CompletionInfo& info) { } delete _unfinished_call; - _unfinished_call = NULL; + _unfinished_call = nullptr; } } if (_stream_creator) { _stream_creator->DestroyStreamCreator(this); - _stream_creator = NULL; + _stream_creator = nullptr; } // Clear _error_text when the call succeeded, otherwise a successful // call with non-empty ErrorText may confuse user. @@ -1034,7 +1030,7 @@ void Controller::EndRPC(const CompletionInfo& info) { void Controller::OnRPCEnd(int64_t end_time_us) { _end_time_us = end_time_us; - if (NULL != _backup_request_policy) { + if (nullptr != _backup_request_policy) { _backup_request_policy->OnRPCEnd(this); } } @@ -1083,7 +1079,7 @@ void Controller::HandleSendFailed() { // same stack of CallMethod, the code is deadlocked. // We don't need to run the callback in new thread in a sync call since // the created thread needs to be joined anyway before end of CallMethod. - const bool new_bthread = (_done != NULL && !is_done_allowed_to_run_in_place()); + const bool new_bthread = (_done != nullptr && !is_done_allowed_to_run_in_place()); OnVersionedRPCReturned(info, new_bthread, _error_code); } @@ -1186,7 +1182,7 @@ void Controller::IssueRPC(int64_t start_realtime_us) { } // Handle connection type if (_connection_type == CONNECTION_TYPE_SINGLE || - _stream_creator != NULL) { // let user decides the sending_sock + _stream_creator != nullptr) { // let user decides the sending_sock // in the callback(according to connection_type) directly _current_call.sending_sock.reset(tmp_sock.release()); // TODO(gejun): Setting preferred index of single-connected socket @@ -1223,7 +1219,7 @@ void Controller::IssueRPC(int64_t start_realtime_us) { _current_call.sending_sock->set_preferred_index(_preferred_index); // Set preferred_index of main_socket as well to make it easier to // debug and observe from /connections. - // tmp_sock is NULL on the BIND_SOCK_USE path. + // tmp_sock is nullptr on the BIND_SOCK_USE path. if (tmp_sock && tmp_sock->preferred_index() < 0) { tmp_sock->set_preferred_index(_preferred_index); } @@ -1239,8 +1235,8 @@ void Controller::IssueRPC(int64_t start_realtime_us) { } // Handle authentication - const Authenticator* using_auth = NULL; - if (_auth != NULL) { + const Authenticator* using_auth = nullptr; + if (_auth != nullptr) { // Only one thread will be the winner and get the right to pack // authentication information, others wait until the request // is sent. @@ -1255,7 +1251,7 @@ void Controller::IssueRPC(int64_t start_realtime_us) { } // Make request butil::IOBuf packet; - SocketMessage* user_packet = NULL; + SocketMessage* user_packet = nullptr; _pack_request(&packet, &user_packet, cid.value, _method, this, _request_buf, using_auth); // TODO: PackRequest may accept SocketMessagePtr<>? @@ -1270,7 +1266,7 @@ void Controller::IssueRPC(int64_t start_realtime_us) { } timespec connect_abstime; - timespec* pabstime = NULL; + timespec* pabstime = nullptr; if (_connect_timeout_ms > 0) { if (_deadline_us >= 0) { connect_abstime = butil::microseconds_to_timespec( @@ -1319,7 +1315,7 @@ void Controller::IssueRPC(int64_t start_realtime_us) { } void Controller::set_auth_context(const AuthContext* ctx) { - if (_auth_context != NULL) { + if (_auth_context != nullptr) { LOG(FATAL) << "Impossible! This function is supposed to be called " "only once when verification succeeds in server side"; return; @@ -1366,13 +1362,13 @@ int Controller::HandleSocketFailed(bthread_id_t id, void* data, int error_code, std::unique_ptr args(static_cast(p)); CompletionInfo info = { args->id, false }; args->cntl->OnVersionedRPCReturned(info, true, args->error); - return NULL; + return nullptr; }; auto* args = new OnVersionedRPCReturnedArgs{ id, cntl, saved_error }; bthread_t tid; // RetryPolicy may block current bthread, so start a new bthread to run OnVersionedRPCReturned - if (!cntl->_retry_policy || bthread_start_background(&tid, NULL, func, args) != 0) { + if (!cntl->_retry_policy || bthread_start_background(&tid, nullptr, func, args) != 0) { func(args); } return 0; @@ -1437,13 +1433,13 @@ int Controller::sub_count() const { } const Controller* Controller::sub(int index) const { - if (_pchan_sub_count > 0 && _done != NULL) { + if (_pchan_sub_count > 0 && _done != nullptr) { return GetSubControllerOfParallelChannel(_done, index); } - if (_sender != NULL) { + if (_sender != nullptr) { return GetSubControllerOfSelectiveChannel(_sender, index); } - return NULL; + return nullptr; } uint64_t Controller::trace_id() const { @@ -1471,7 +1467,7 @@ void* Controller::session_local_data() { return _session_local_data; } } - return NULL; + return nullptr; } void Controller::HandleStreamConnection(Socket *host_socket) { @@ -1482,7 +1478,7 @@ void Controller::HandleStreamConnection(Socket *host_socket) { size_t stream_num = _request_streams.size(); std::vector ptrs(stream_num); if (!FailedInline()) { - if (_remote_stream_settings == NULL) { + if (_remote_stream_settings == nullptr) { if (!FailedInline()) { SetFailed(EREQUEST, "The server didn't accept the stream"); } @@ -1501,7 +1497,7 @@ void Controller::HandleStreamConnection(Socket *host_socket) { if (FailedInline()) { Stream::SetFailed(_request_streams, _error_code, "%s", _error_text.c_str()); - if (_remote_stream_settings != NULL) { + if (_remote_stream_settings != nullptr) { policy::SendStreamRst(host_socket, _remote_stream_settings->stream_id()); for (int i = 0; i < _remote_stream_settings->extra_stream_ids().size(); ++i) { @@ -1555,7 +1551,7 @@ void Controller::reset_sampled_request(SampledRequest* req) { SampledRequest* Controller::release_sampled_request() { SampledRequest* saved_sampled_request = _sampled_request; - _sampled_request = NULL; + _sampled_request = nullptr; return saved_sampled_request; } @@ -1571,15 +1567,15 @@ butil::intrusive_ptr Controller::CreateProgressiveAttachment(StopStyle stop_style) { if (has_progressive_writer()) { LOG(ERROR) << "One controller can only have one ProgressiveAttachment"; - return NULL; + return nullptr; } if (_request_protocol != PROTOCOL_HTTP) { LOG(ERROR) << "Only http supports ProgressiveAttachment now"; - return NULL; + return nullptr; } - if (_current_call.sending_sock == NULL) { + if (_current_call.sending_sock == nullptr) { LOG(ERROR) << "sending_sock is NULL"; - return NULL; + return nullptr; } SocketUniquePtr httpsock; _current_call.sending_sock->ReAddress(&httpsock); @@ -1593,7 +1589,7 @@ Controller::CreateProgressiveAttachment(StopStyle stop_style) { } void Controller::ReadProgressiveAttachmentBy(ProgressiveReader* r) { - if (r == NULL) { + if (r == nullptr) { LOG(FATAL) << "Param[r] is NULL"; return; } @@ -1603,7 +1599,7 @@ void Controller::ReadProgressiveAttachmentBy(ProgressiveReader* r) { "controller without calling " "response_will_be_read_progressively() before")); } - if (_rpa == NULL) { + if (_rpa == nullptr) { return r->OnEndOfMessage( butil::Status(EINVAL, "ReadableProgressiveAttachment is NULL")); } @@ -1622,12 +1618,12 @@ void Controller::set_mongo_session_data(MongoContext* data) { bool Controller::is_ssl() const { Socket* s = _current_call.sending_sock.get(); - return s != NULL && s->is_ssl(); + return s != nullptr && s->is_ssl(); } x509_st* Controller::get_peer_certificate() const { Socket* s = _current_call.sending_sock.get(); - return s ? s->GetPeerCertificate() : NULL; + return s ? s->GetPeerCertificate() : nullptr; } int Controller::GetSockOption(int level, int optname, void* optval, socklen_t* optlen) { @@ -1654,9 +1650,9 @@ typedef sighandler_t SignalHandler; #endif static volatile bool s_signal_quit = false; -static SignalHandler s_prev_sigint_handler = NULL; -static SignalHandler s_prev_sigterm_handler = NULL; -static SignalHandler s_prev_sighup_handler = NULL; +static SignalHandler s_prev_sigint_handler = nullptr; +static SignalHandler s_prev_sigterm_handler = nullptr; +static SignalHandler s_prev_sighup_handler = nullptr; static void quit_handler(int signo) { s_signal_quit = true; diff --git a/src/brpc/controller.h b/src/brpc/controller.h index 564c0875e1..90215e476c 100644 --- a/src/brpc/controller.h +++ b/src/brpc/controller.h @@ -292,7 +292,7 @@ friend void policy::ProcessThriftRequest(InputMessageBase*); // Mutable header of http request. HttpHeader& http_request() { - if (_http_request == NULL) { + if (_http_request == nullptr) { _http_request = new HttpHeader; } return *_http_request; @@ -300,7 +300,7 @@ friend void policy::ProcessThriftRequest(InputMessageBase*); bool has_http_request() const { return _http_request; } HttpHeader* release_http_request() { HttpHeader* const tmp = _http_request; - _http_request = NULL; + _http_request = nullptr; return tmp; } @@ -327,18 +327,18 @@ friend void policy::ProcessThriftRequest(InputMessageBase*); butil::IOBuf& request_attachment() { return _request_attachment; } ConnectionType connection_type() const { return _connection_type; } - // Get the called method. May-be NULL for non-pb services. + // Get the called method. May-be nullptr for non-pb services. const google::protobuf::MethodDescriptor* method() const { return _method; } // Get the controllers for accessing sub channels in combo channels. // Ordinary channel: - // sub_count() is 0 and sub() is always NULL. + // sub_count() is 0 and sub() is always nullptr. // ParallelChannel/PartitionChannel: // sub_count() is #sub-channels and sub(i) is the controller for // accessing i-th sub channel inside ParallelChannel, if i is outside - // [0, sub_count() - 1], sub(i) is NULL. - // NOTE: You must test sub() against NULL, ALWAYS. Even if i is inside - // range, sub(i) can still be NULL: + // [0, sub_count() - 1], sub(i) is nullptr. + // NOTE: You must test sub() against nullptr, ALWAYS. Even if i is inside + // range, sub(i) can still be nullptr: // * the rpc call may fail and terminate before accessing the sub channel // * the sub channel was skipped // SelectiveChannel/DynamicPartitionChannel: @@ -457,7 +457,7 @@ friend void policy::ProcessThriftRequest(InputMessageBase*); // NotifyOnCancel() must be called no more than once per request. void NotifyOnCancel(google::protobuf::Closure* callback) override; - // Returns the authenticated result. NULL if there is no authentication + // Returns the authenticated result. nullptr if there is no authentication const AuthContext* auth_context() const { return _auth_context; } // Whether the underlying channel is using SSL @@ -468,7 +468,7 @@ friend void policy::ProcessThriftRequest(InputMessageBase*); // Mutable header of http response. HttpHeader& http_response() { - if (_http_response == NULL) { + if (_http_response == nullptr) { _http_response = new HttpHeader; } return *_http_response; @@ -476,7 +476,7 @@ friend void policy::ProcessThriftRequest(InputMessageBase*); bool has_http_response() const { return _http_response; } HttpHeader* release_http_response() { HttpHeader* const tmp = _http_response; - _http_response = NULL; + _http_response = nullptr; return tmp; } @@ -501,7 +501,7 @@ friend void policy::ProcessThriftRequest(InputMessageBase*); butil::intrusive_ptr CreateProgressiveAttachment(StopStyle stop_style = WAIT_FOR_STOP); - bool has_progressive_writer() const { return _wpa != NULL; } + bool has_progressive_writer() const { return _wpa != nullptr; } // Set compression method for response. void set_response_compress_type(CompressType t) { _response_compress_type = t; } @@ -536,12 +536,12 @@ friend void policy::ProcessThriftRequest(InputMessageBase*); bool is_security_mode() const { return has_flag(FLAGS_SECURITY_MODE); } // The server running this RPC session. - // Always NULL at client-side. + // Always nullptr at client-side. const Server* server() const { return _server; } // Get the data attached to current RPC session. The data is created by // ServerOptions.session_local_data_factory and reused between different - // RPC. If factory is NULL, this method returns NULL. + // RPC. If factory is nullptr, this method returns nullptr. void* session_local_data(); // Get the data attached to a mongo session(practically a socket). @@ -609,10 +609,10 @@ friend void policy::ProcessThriftRequest(InputMessageBase*); bool request_checksum_attachment() const { return has_flag(FLAGS_REQUEST_CHECKSUM_WITH_ATTACHMENT); } bool response_checksum_attachment() const { return has_flag(FLAGS_RESPONSE_CHECKSUM_WITH_ATTACHMENT); } const HttpHeader& http_request() const - { return _http_request != NULL ? *_http_request : DefaultHttpHeader(); } + { return _http_request != nullptr ? *_http_request : DefaultHttpHeader(); } const HttpHeader& http_response() const - { return _http_response != NULL ? *_http_response : DefaultHttpHeader(); } + { return _http_response != nullptr ? *_http_response : DefaultHttpHeader(); } const butil::IOBuf& request_attachment() const { return _request_attachment; } const butil::IOBuf& response_attachment() const { return _response_attachment; } @@ -636,7 +636,7 @@ friend void policy::ProcessThriftRequest(InputMessageBase*); LogPrefixDummy LogPrefix() const { return LogPrefixDummy(this); } // Return true if the remote side creates a stream. - bool has_remote_stream() { return _remote_stream_settings != NULL; } + bool has_remote_stream() { return _remote_stream_settings != nullptr; } // The id to cancel RPC call or join response. CallId call_id(); diff --git a/src/brpc/couchbase.cpp b/src/brpc/couchbase.cpp index 7e622b1e65..fd26107a41 100644 --- a/src/brpc/couchbase.cpp +++ b/src/brpc/couchbase.cpp @@ -259,8 +259,8 @@ bool CouchbaseManifestManager::refreshCollectionManifest( CouchbaseOperations::CouchbaseResponse temp_get_manifest_response; brpc::Controller temp_cntl; temp_get_manifest_request.getCollectionManifest(); - channel->CallMethod(NULL, &temp_cntl, &temp_get_manifest_request, - &temp_get_manifest_response, NULL); + channel->CallMethod(nullptr, &temp_cntl, &temp_get_manifest_request, + &temp_get_manifest_response, nullptr); if (temp_cntl.Failed()) { DEBUG_PRINT("Failed to get collection manifest: bRPC controller error " << temp_cntl.ErrorText()); @@ -1068,7 +1068,7 @@ bool CouchbaseOperations::CouchbaseResponse::popGet(std::string* value, // MUST NOT have key // MUST NOT have value bool CouchbaseOperations::CouchbaseResponse::popDelete() { - return popStore(policy::CB_BINARY_DELETE, NULL); + return popStore(policy::CB_BINARY_DELETE, nullptr); } struct StoreHeaderWithExtras { @@ -1891,7 +1891,7 @@ bool sendRequest(CouchbaseOperations::operation_type op_type, const std::string& // that indicates the collectionID is not found return false; } - channel->CallMethod(NULL, &cntl, request, response, NULL); + channel->CallMethod(nullptr, &cntl, request, response, nullptr); if (cntl.Failed()) { DEBUG_PRINT("Failed to perform operation on key: " << key << " to Couchbase: " << cntl.ErrorText()); @@ -1944,7 +1944,7 @@ bool sendRequest(CouchbaseOperations::operation_type op_type, const std::string& // indicates the collectionID is not found return false; } - channel->CallMethod(NULL, &cntl, request, response, NULL); + channel->CallMethod(nullptr, &cntl, request, response, nullptr); if (cntl.Failed()) { DEBUG_PRINT("Failed to perform operation on key: " << key << " to Couchbase: " << cntl.ErrorText()); @@ -2055,7 +2055,7 @@ bool sendRequest(CouchbaseOperations::operation_type op_type, const std::string& "Unsupported operation type in response pop"; return false; } - channel->CallMethod(NULL, &cntl, request, response, NULL); + channel->CallMethod(nullptr, &cntl, request, response, nullptr); if (cntl.Failed()) { DEBUG_PRINT("Failed to perform operation on key: " << key << " to Couchbase: " << cntl.ErrorText()); @@ -2254,7 +2254,7 @@ CouchbaseOperations::Result CouchbaseOperations::authenticateAll( result.success = false; return result; } - new_channel->CallMethod(NULL, &cntl, &request, &response, NULL); + new_channel->CallMethod(nullptr, &cntl, &request, &response, nullptr); if (cntl.Failed()) { DEBUG_PRINT("Failed to access Couchbase: " << cntl.ErrorText()); delete new_channel; @@ -2311,7 +2311,7 @@ CouchbaseOperations::Result CouchbaseOperations::selectBucket( result.value = ""; return result; } - channel_->CallMethod(NULL, &cntl, &request, &response, NULL); + channel_->CallMethod(nullptr, &cntl, &request, &response, nullptr); if (cntl.Failed()) { DEBUG_PRINT("Failed to select bucket: " << bucket_name << " from Couchbase: " << cntl.ErrorText()); @@ -2320,7 +2320,7 @@ CouchbaseOperations::Result CouchbaseOperations::selectBucket( result.error_message = cntl.ErrorText(); return result; } - if (response.popSelectBucket(NULL) == false) { + if (response.popSelectBucket(nullptr) == false) { result.success = false; result.value = ""; result.error_message = response.lastError(); @@ -2402,7 +2402,7 @@ CouchbaseOperations::Result CouchbaseOperations::version() { result.value = ""; return result; } - channel_->CallMethod(NULL, &cntl, &request, &response, NULL); + channel_->CallMethod(nullptr, &cntl, &request, &response, nullptr); if (cntl.Failed()) { DEBUG_PRINT("Failed to get version from Couchbase: " << cntl.ErrorText()); result.success = false; @@ -2514,8 +2514,8 @@ std::vector CouchbaseOperations::executePipeline() } brpc::Controller cntl; - channel_->CallMethod(NULL, &cntl, &pipeline_request_couchbase_req, - &pipeline_response_couchbase_resp, NULL); + channel_->CallMethod(nullptr, &cntl, &pipeline_request_couchbase_req, + &pipeline_response_couchbase_resp, nullptr); if (cntl.Failed()) { DEBUG_PRINT("Pipeline execution failed: " << cntl.ErrorText()); @@ -2560,7 +2560,7 @@ std::vector CouchbaseOperations::executePipeline() break; } case UPSERT: { - if (response->popUpsert(NULL) == false) { + if (response->popUpsert(nullptr) == false) { result.success = false; result.value = ""; result.error_message = response->lastError(); @@ -2573,7 +2573,7 @@ std::vector CouchbaseOperations::executePipeline() break; } case ADD: { - if (response->popAdd(NULL) == false) { + if (response->popAdd(nullptr) == false) { result.success = false; result.value = ""; result.error_message = response->lastError(); diff --git a/src/brpc/data_factory.h b/src/brpc/data_factory.h index 5733073a03..86890af054 100644 --- a/src/brpc/data_factory.h +++ b/src/brpc/data_factory.h @@ -31,7 +31,7 @@ class DataFactory { virtual ~DataFactory() {} // Implement this method to create a piece of data - // Returns the data, NULL on error. + // Returns the data, nullptr on error. virtual void* CreateData() const = 0; // Implement this method to destroy data created by Create(). diff --git a/src/brpc/details/naming_service_thread.cpp b/src/brpc/details/naming_service_thread.cpp index 7eb005e8f0..50c7519e33 100644 --- a/src/brpc/details/naming_service_thread.cpp +++ b/src/brpc/details/naming_service_thread.cpp @@ -434,12 +434,7 @@ int GetNamingServiceThread( { std::unique_lock mu(g_nsthread_map_mutex); if (g_nsthread_map == NULL) { - g_nsthread_map = new (std::nothrow) NamingServiceMap; - if (NULL == g_nsthread_map) { - mu.unlock(); - LOG(ERROR) << "Fail to new g_nsthread_map"; - return -1; - } + g_nsthread_map = new NamingServiceMap; if (g_nsthread_map->init(64) != 0) { LOG(WARNING) << "Fail to init g_nsthread_map"; } @@ -459,12 +454,7 @@ int GetNamingServiceThread( } } if (ptr == NULL) { - NamingServiceThread* thr = new (std::nothrow) NamingServiceThread; - if (thr == NULL) { - mu.unlock(); - LOG(ERROR) << "Fail to new NamingServiceThread"; - return -1; - } + NamingServiceThread* thr = new NamingServiceThread; ptr = thr; nsthread.reset(ptr); new_thread = true; diff --git a/src/brpc/event_dispatcher.cpp b/src/brpc/event_dispatcher.cpp index 15152fc8f7..9a61c90c5f 100644 --- a/src/brpc/event_dispatcher.cpp +++ b/src/brpc/event_dispatcher.cpp @@ -39,9 +39,9 @@ DEFINE_bool(usercode_in_pthread, false, DEFINE_bool(usercode_in_coroutine, false, "User's callback are run in coroutine, no bthread or pthread blocking call"); -static EventDispatcher* g_edisp = NULL; -static bvar::LatencyRecorder* g_edisp_read_lantency = NULL; -static bvar::LatencyRecorder* g_edisp_write_lantency = NULL; +static EventDispatcher* g_edisp = nullptr; +static bvar::LatencyRecorder* g_edisp_read_lantency = nullptr; +static bvar::LatencyRecorder* g_edisp_write_lantency = nullptr; static pthread_once_t g_edisp_once = PTHREAD_ONCE_INIT; bool EventDispatcherUnsched() { @@ -100,7 +100,7 @@ int IOEventData::OnCreated(const IOEventDataOptions& options) { } void IOEventData::BeforeRecycled() { - _options = { NULL, NULL, NULL }; + _options = { nullptr, nullptr, nullptr }; } } // namespace brpc diff --git a/src/brpc/event_dispatcher.h b/src/brpc/event_dispatcher.h index d95243ac2d..33f3537ebb 100644 --- a/src/brpc/event_dispatcher.h +++ b/src/brpc/event_dispatcher.h @@ -63,7 +63,7 @@ class IOEventData : public VersionedRefWithId { public: explicit IOEventData(Forbidden f) : VersionedRefWithId(f) - , _options{ NULL, NULL, NULL } {} + , _options{ nullptr, nullptr, nullptr } {} DISALLOW_COPY_AND_ASSIGN(IOEventData); @@ -103,7 +103,7 @@ template friend class IOEvent; virtual ~EventDispatcher(); // Start this dispatcher in a bthread. - // Use |*thread_attr| (if it's not NULL) as the attribute to + // Use |*thread_attr| (if it's not nullptr) as the attribute to // create bthreads running user callbacks. // Returns 0 on success, -1 otherwise. virtual int Start(const bthread_attr_t* thread_attr); diff --git a/src/brpc/event_dispatcher_epoll.cpp b/src/brpc/event_dispatcher_epoll.cpp index 31f60aace3..e57ab90267 100644 --- a/src/brpc/event_dispatcher_epoll.cpp +++ b/src/brpc/event_dispatcher_epoll.cpp @@ -101,14 +101,14 @@ void EventDispatcher::Stop() { _stop = true; if (_event_dispatcher_fd >= 0) { - epoll_event evt = { EPOLLOUT, { NULL } }; + epoll_event evt = { EPOLLOUT, { nullptr } }; epoll_ctl(_event_dispatcher_fd, EPOLL_CTL_ADD, _wakeup_fds[1], &evt); } } void EventDispatcher::Join() { if (_tid) { - bthread_join(_tid, NULL); + bthread_join(_tid, nullptr); _tid = 0; } } @@ -152,7 +152,7 @@ int EventDispatcher::UnregisterEvent(IOEventDataId event_data_id, #endif return epoll_ctl(_event_dispatcher_fd, EPOLL_CTL_MOD, fd, &evt); } else { - return epoll_ctl(_event_dispatcher_fd, EPOLL_CTL_DEL, fd, NULL); + return epoll_ctl(_event_dispatcher_fd, EPOLL_CTL_DEL, fd, nullptr); } return -1; } @@ -182,7 +182,7 @@ int EventDispatcher::RemoveConsumer(int fd) { // from epoll again! If the fd was level-triggered and there's data left, // epoll_wait will keep returning events of the fd continuously, making // program abnormal. - if (epoll_ctl(_event_dispatcher_fd, EPOLL_CTL_DEL, fd, NULL) < 0) { + if (epoll_ctl(_event_dispatcher_fd, EPOLL_CTL_DEL, fd, nullptr) < 0) { PLOG(WARNING) << "Fail to remove fd=" << fd << " from epfd=" << _event_dispatcher_fd; return -1; } @@ -197,7 +197,7 @@ void* EventDispatcher::RunThis(void* arg) { meta->priority_index = ed->_priority_index; } ed->Run(); - return NULL; + return nullptr; } void EventDispatcher::Run() { diff --git a/src/brpc/event_dispatcher_kqueue.cpp b/src/brpc/event_dispatcher_kqueue.cpp index f73e62004f..111c21fbf2 100644 --- a/src/brpc/event_dispatcher_kqueue.cpp +++ b/src/brpc/event_dispatcher_kqueue.cpp @@ -104,14 +104,14 @@ void EventDispatcher::Stop() { if (_event_dispatcher_fd >= 0) { struct kevent kqueue_event; EV_SET(&kqueue_event, _wakeup_fds[1], EVFILT_WRITE, EV_ADD | EV_ENABLE, - 0, 0, NULL); - kevent(_event_dispatcher_fd, &kqueue_event, 1, NULL, 0, NULL); + 0, 0, nullptr); + kevent(_event_dispatcher_fd, &kqueue_event, 1, nullptr, 0, nullptr); } } void EventDispatcher::Join() { if (_tid) { - bthread_join(_tid, NULL); + bthread_join(_tid, nullptr); _tid = 0; } } @@ -127,13 +127,13 @@ int EventDispatcher::RegisterEvent(IOEventDataId event_data_id, //TODO(zhujiashun): add EV_EOF EV_SET(&evt, fd, EVFILT_WRITE, EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, (void*)event_data_id); - if (kevent(_event_dispatcher_fd, &evt, 1, NULL, 0, NULL) < 0) { + if (kevent(_event_dispatcher_fd, &evt, 1, nullptr, 0, nullptr) < 0) { return -1; } if (pollin) { EV_SET(&evt, fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, (void*)event_data_id); - if (kevent(_event_dispatcher_fd, &evt, 1, NULL, 0, NULL) < 0) { + if (kevent(_event_dispatcher_fd, &evt, 1, nullptr, 0, nullptr) < 0) { return -1; } } @@ -143,14 +143,14 @@ int EventDispatcher::RegisterEvent(IOEventDataId event_data_id, int EventDispatcher::UnregisterEvent(IOEventDataId event_data_id, int fd, bool pollin) { struct kevent evt; - EV_SET(&evt, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); - if (kevent(_event_dispatcher_fd, &evt, 1, NULL, 0, NULL) < 0) { + EV_SET(&evt, fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr); + if (kevent(_event_dispatcher_fd, &evt, 1, nullptr, 0, nullptr) < 0) { return -1; } if (pollin) { EV_SET(&evt, fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, (void*)event_data_id); - return kevent(_event_dispatcher_fd, &evt, 1, NULL, 0, NULL); + return kevent(_event_dispatcher_fd, &evt, 1, nullptr, 0, nullptr); } return 0; } @@ -163,7 +163,7 @@ int EventDispatcher::AddConsumer(IOEventDataId event_data_id, int fd) { struct kevent evt; EV_SET(&evt, fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_CLEAR, 0, 0, (void*)event_data_id); - return kevent(_event_dispatcher_fd, &evt, 1, NULL, 0, NULL); + return kevent(_event_dispatcher_fd, &evt, 1, nullptr, 0, nullptr); } int EventDispatcher::RemoveConsumer(int fd) { @@ -178,22 +178,22 @@ int EventDispatcher::RemoveConsumer(int fd) { // kevent will keep returning events of the fd continuously, making // program abnormal. struct kevent evt; - EV_SET(&evt, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); - kevent(_event_dispatcher_fd, &evt, 1, NULL, 0, NULL); - EV_SET(&evt, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); - kevent(_event_dispatcher_fd, &evt, 1, NULL, 0, NULL); + EV_SET(&evt, fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr); + kevent(_event_dispatcher_fd, &evt, 1, nullptr, 0, nullptr); + EV_SET(&evt, fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr); + kevent(_event_dispatcher_fd, &evt, 1, nullptr, 0, nullptr); return 0; } void* EventDispatcher::RunThis(void* arg) { ((EventDispatcher*)arg)->Run(); - return NULL; + return nullptr; } void EventDispatcher::Run() { while (!_stop) { struct kevent e[32]; - int n = kevent(_event_dispatcher_fd, NULL, 0, e, ARRAY_SIZE(e), NULL); + int n = kevent(_event_dispatcher_fd, nullptr, 0, e, ARRAY_SIZE(e), nullptr); if (_stop) { // EV_SET/kevent should have some sort of memory fencing // guaranteeing that we(after kevent) see _stop set before diff --git a/src/brpc/excluded_servers.h b/src/brpc/excluded_servers.h index ad095f4b3d..d06e3e3b96 100644 --- a/src/brpc/excluded_servers.h +++ b/src/brpc/excluded_servers.h @@ -42,7 +42,7 @@ class ExcludedServers { // True if the server shall be excluded. bool IsExcluded(SocketId id) const; static bool IsExcluded(const ExcludedServers* s, SocketId id) { - return s != NULL && s->IsExcluded(id); + return s != nullptr && s->IsExcluded(id); } // #servers inside. @@ -65,8 +65,8 @@ class ExcludedServers { inline ExcludedServers* ExcludedServers::Create(int cap) { void *space = malloc( offsetof(ExcludedServers, _space) + sizeof(SocketId) * cap); - if (NULL == space) { - return NULL; + if (nullptr == space) { + return nullptr; } return new (space) ExcludedServers(cap); } @@ -81,7 +81,7 @@ inline void ExcludedServers::Destroy(ExcludedServers* ptr) { inline void ExcludedServers::Add(SocketId id) { BAIDU_SCOPED_LOCK(_mutex); const SocketId* last_id = _l.bottom(); - if (last_id == NULL || *last_id != id) { + if (last_id == nullptr || *last_id != id) { _l.elim_push(id); } } diff --git a/src/brpc/extension_inl.h b/src/brpc/extension_inl.h index 8a081c7fb1..4852f3da8c 100644 --- a/src/brpc/extension_inl.h +++ b/src/brpc/extension_inl.h @@ -31,12 +31,12 @@ Extension* Extension::instance() { template int Extension::Register(const std::string& name, T* instance) { - if (NULL == instance) { + if (nullptr == instance) { LOG(ERROR) << "instance to \"" << name << "\" is NULL"; return -1; } BAIDU_SCOPED_LOCK(_map_mutex); - if (_instance_map.seek(name) != NULL) { + if (_instance_map.seek(name) != nullptr) { LOG(ERROR) << "\"" << name << "\" was registered"; return -1; } @@ -54,15 +54,15 @@ int Extension::RegisterOrDie(const std::string& name, T* instance) { template T* Extension::Find(const char* name) { - if (NULL == name) { - return NULL; + if (nullptr == name) { + return nullptr; } BAIDU_SCOPED_LOCK(_map_mutex); T** p = _instance_map.seek(name); if (p) { return *p; } - return NULL; + return nullptr; } template diff --git a/src/brpc/global.cpp b/src/brpc/global.cpp index 04a56282ea..812a79a183 100644 --- a/src/brpc/global.cpp +++ b/src/brpc/global.cpp @@ -171,7 +171,7 @@ struct GlobalExtensions { }; static pthread_once_t register_extensions_once = PTHREAD_ONCE_INIT; -static GlobalExtensions* g_ext = NULL; +static GlobalExtensions* g_ext = nullptr; static long ReadPortOfDummyServer(const char* filename) { butil::fd_guard fd(open(filename, O_RDONLY)); @@ -189,7 +189,7 @@ static long ReadPortOfDummyServer(const char* filename) { port_str[std::min((size_t)nr, sizeof(port_str)-1)] = '\0'; const char* p = port_str; for (; isspace(*p); ++p) {} - char* endptr = NULL; + char* endptr = nullptr; const long port = strtol(p, &endptr, 10); for (; isspace(*endptr); ++endptr) {} if (*endptr != '\0') { @@ -231,25 +231,25 @@ static void* GlobalUpdate(void*) { ANNOTATE_MEMORY_LEAK_DISABLE(); // Expose variables. bvar::PassiveStatus var_iobuf_block_count( - "iobuf_block_count", GetIOBufBlockCount, NULL); + "iobuf_block_count", GetIOBufBlockCount, nullptr); bvar::PassiveStatus var_iobuf_block_count_hit_tls_threshold( "iobuf_block_count_hit_tls_threshold", - GetIOBufBlockCountHitTLSThreshold, NULL); + GetIOBufBlockCountHitTLSThreshold, nullptr); bvar::PassiveStatus var_iobuf_new_bigview_count( - GetIOBufNewBigViewCount, NULL); + GetIOBufNewBigViewCount, nullptr); bvar::PerSecond > var_iobuf_new_bigview_second( "iobuf_newbigview_second", &var_iobuf_new_bigview_count); bvar::PassiveStatus var_iobuf_block_memory( - "iobuf_block_memory", GetIOBufBlockMemory, NULL); + "iobuf_block_memory", GetIOBufBlockMemory, nullptr); bvar::PassiveStatus var_running_server_count( - "rpc_server_count", GetRunningServerCount, NULL); + "rpc_server_count", GetRunningServerCount, nullptr); butil::FileWatcher fw; const int fw_rc = fw.init_from_not_exist(DUMMY_SERVER_PORT_FILE); ANNOTATE_MEMORY_LEAK_ENABLE(); if (fw_rc < 0) { LOG(FATAL) << "Fail to init FileWatcher on `" << DUMMY_SERVER_PORT_FILE << "'"; - return NULL; + return nullptr; } std::vector conns; @@ -309,7 +309,7 @@ static void* GlobalUpdate(void*) { // 1.7 and 2.5, which means making the static member function weak // in details/tcmalloc_extension.cpp is probably not correct, however // it does work for heap profilers. - if (MallocExtension_ReleaseFreeMemory != NULL) { + if (MallocExtension_ReleaseFreeMemory != nullptr) { MallocExtension_ReleaseFreeMemory(); } else { #if defined(OS_LINUX) @@ -319,7 +319,7 @@ static void* GlobalUpdate(void*) { } } } - return NULL; + return nullptr; } #if GOOGLE_PROTOBUF_VERSION < 3022000 @@ -353,8 +353,8 @@ static void GlobalInitializeOrDieImpl() { // Ignore SIGPIPE. struct sigaction oldact; - if (sigaction(SIGPIPE, NULL, &oldact) != 0 || - (oldact.sa_handler == NULL && oldact.sa_sigaction == NULL)) { + if (sigaction(SIGPIPE, nullptr, &oldact) != 0 || + (oldact.sa_handler == nullptr && oldact.sa_sigaction == nullptr)) { CHECK(SIG_ERR != signal(SIGPIPE, SIG_IGN)); } @@ -385,10 +385,7 @@ static void GlobalInitializeOrDieImpl() { InitCommonStrings(); // Leave memory of these extensions to process's clean up. - g_ext = new(std::nothrow) GlobalExtensions(); - if (NULL == g_ext) { - exit(1); - } + g_ext = new GlobalExtensions(); // Naming Services #ifdef BAIDU_INTERNAL NamingServiceExtension()->RegisterOrDie("bns", &g_ext->bns); @@ -439,9 +436,9 @@ static void GlobalInitializeOrDieImpl() { // Protocols Protocol rdma_handshake_protocol = { - ParseRdmaHandshake, NULL, NULL, - ProcessRdmaHandshake, NULL, - NULL, NULL, NULL, + ParseRdmaHandshake, nullptr, nullptr, + ProcessRdmaHandshake, nullptr, + nullptr, nullptr, nullptr, CONNECTION_TYPE_ALL, "rdma_handshake" }; if (RegisterProtocol(PROTOCOL_RDMA_HANDSHAKE, rdma_handshake_protocol) != 0) { exit(1); @@ -450,16 +447,16 @@ static void GlobalInitializeOrDieImpl() { Protocol baidu_protocol = { ParseRpcMessage, SerializeRpcRequest, PackRpcRequest, ProcessRpcRequest, ProcessRpcResponse, - VerifyRpcRequest, NULL, NULL, + VerifyRpcRequest, nullptr, nullptr, CONNECTION_TYPE_ALL, "baidu_std" }; if (RegisterProtocol(PROTOCOL_BAIDU_STD, baidu_protocol) != 0) { exit(1); } Protocol streaming_protocol = { ParseStreamingMessage, - NULL, NULL, ProcessStreamingMessage, + nullptr, nullptr, ProcessStreamingMessage, ProcessStreamingMessage, - NULL, NULL, NULL, + nullptr, nullptr, nullptr, CONNECTION_TYPE_SINGLE, "streaming_rpc" }; if (RegisterProtocol(PROTOCOL_STREAMING_RPC, streaming_protocol) != 0) { @@ -491,7 +488,7 @@ static void GlobalInitializeOrDieImpl() { Protocol hulu_protocol = { ParseHuluMessage, SerializeRequestDefault, PackHuluRequest, ProcessHuluRequest, ProcessHuluResponse, - VerifyHuluRequest, NULL, NULL, + VerifyHuluRequest, nullptr, nullptr, CONNECTION_TYPE_ALL, "hulu_pbrpc" }; if (RegisterProtocol(PROTOCOL_HULU_PBRPC, hulu_protocol) != 0) { exit(1); @@ -500,8 +497,8 @@ static void GlobalInitializeOrDieImpl() { // Only valid at client side Protocol nova_protocol = { ParseNsheadMessage, SerializeNovaRequest, PackNovaRequest, - NULL, ProcessNovaResponse, - NULL, NULL, NULL, + nullptr, ProcessNovaResponse, + nullptr, nullptr, nullptr, CONNECTION_TYPE_POOLED_AND_SHORT, "nova_pbrpc" }; if (RegisterProtocol(PROTOCOL_NOVA_PBRPC, nova_protocol) != 0) { exit(1); @@ -511,8 +508,8 @@ static void GlobalInitializeOrDieImpl() { Protocol public_pbrpc_protocol = { ParseNsheadMessage, SerializePublicPbrpcRequest, PackPublicPbrpcRequest, - NULL, ProcessPublicPbrpcResponse, - NULL, NULL, NULL, + nullptr, ProcessPublicPbrpcResponse, + nullptr, nullptr, nullptr, // public_pbrpc server implementation // doesn't support full duplex CONNECTION_TYPE_POOLED_AND_SHORT, @@ -524,7 +521,7 @@ static void GlobalInitializeOrDieImpl() { Protocol sofa_protocol = { ParseSofaMessage, SerializeRequestDefault, PackSofaRequest, ProcessSofaRequest, ProcessSofaResponse, - VerifySofaRequest, NULL, NULL, + VerifySofaRequest, nullptr, nullptr, CONNECTION_TYPE_ALL, "sofa_pbrpc" }; if (RegisterProtocol(PROTOCOL_SOFA_PBRPC, sofa_protocol) != 0) { exit(1); @@ -536,7 +533,7 @@ static void GlobalInitializeOrDieImpl() { Protocol nshead_protocol = { ParseNsheadMessage, SerializeNsheadRequest, PackNsheadRequest, ProcessNsheadRequest, ProcessNsheadResponse, - VerifyNsheadRequest, NULL, NULL, + VerifyNsheadRequest, nullptr, nullptr, CONNECTION_TYPE_POOLED_AND_SHORT, "nshead" }; if (RegisterProtocol(PROTOCOL_NSHEAD, nshead_protocol) != 0) { exit(1); @@ -545,8 +542,8 @@ static void GlobalInitializeOrDieImpl() { Protocol mc_binary_protocol = { ParseMemcacheMessage, SerializeMemcacheRequest, PackMemcacheRequest, - NULL, ProcessMemcacheResponse, - NULL, NULL, GetMemcacheMethodName, + nullptr, ProcessMemcacheResponse, + nullptr, nullptr, GetMemcacheMethodName, CONNECTION_TYPE_ALL, "memcache" }; if (RegisterProtocol(PROTOCOL_MEMCACHE, mc_binary_protocol) != 0) { exit(1); @@ -555,8 +552,8 @@ static void GlobalInitializeOrDieImpl() { Protocol couchbase_protocol = { ParseCouchbaseMessage, SerializeCouchbaseRequest, PackCouchbaseRequest, - NULL, ProcessCouchbaseResponse, - NULL, NULL, GetCouchbaseMethodName, + nullptr, ProcessCouchbaseResponse, + nullptr, nullptr, GetCouchbaseMethodName, CONNECTION_TYPE_ALL, "couchbase" }; if (RegisterProtocol(PROTOCOL_COUCHBASE, couchbase_protocol) != 0) { exit(1); @@ -566,16 +563,16 @@ static void GlobalInitializeOrDieImpl() { SerializeRedisRequest, PackRedisRequest, ProcessRedisRequest, ProcessRedisResponse, - NULL, NULL, GetRedisMethodName, + nullptr, nullptr, GetRedisMethodName, CONNECTION_TYPE_ALL, "redis" }; if (RegisterProtocol(PROTOCOL_REDIS, redis_protocol) != 0) { exit(1); } Protocol mongo_protocol = { ParseMongoMessage, - NULL, NULL, - ProcessMongoRequest, NULL, - NULL, NULL, NULL, + nullptr, nullptr, + ProcessMongoRequest, nullptr, + nullptr, nullptr, nullptr, CONNECTION_TYPE_POOLED, "mongo" }; if (RegisterProtocol(PROTOCOL_MONGO, mongo_protocol) != 0) { exit(1); @@ -587,7 +584,7 @@ static void GlobalInitializeOrDieImpl() { policy::ParseThriftMessage, policy::SerializeThriftRequest, policy::PackThriftRequest, policy::ProcessThriftRequest, policy::ProcessThriftResponse, - policy::VerifyThriftRequest, NULL, NULL, + policy::VerifyThriftRequest, nullptr, nullptr, CONNECTION_TYPE_POOLED_AND_SHORT, "thrift" }; if (RegisterProtocol(PROTOCOL_THRIFT, thrift_binary_protocol) != 0) { exit(1); @@ -598,8 +595,8 @@ static void GlobalInitializeOrDieImpl() { Protocol ubrpc_compack_protocol = { ParseNsheadMessage, SerializeUbrpcCompackRequest, PackUbrpcRequest, - NULL, ProcessUbrpcResponse, - NULL, NULL, NULL, + nullptr, ProcessUbrpcResponse, + nullptr, nullptr, nullptr, CONNECTION_TYPE_POOLED_AND_SHORT, "ubrpc_compack" }; if (RegisterProtocol(PROTOCOL_UBRPC_COMPACK, ubrpc_compack_protocol) != 0) { exit(1); @@ -607,8 +604,8 @@ static void GlobalInitializeOrDieImpl() { Protocol ubrpc_mcpack2_protocol = { ParseNsheadMessage, SerializeUbrpcMcpack2Request, PackUbrpcRequest, - NULL, ProcessUbrpcResponse, - NULL, NULL, NULL, + nullptr, ProcessUbrpcResponse, + nullptr, nullptr, nullptr, CONNECTION_TYPE_POOLED_AND_SHORT, "ubrpc_mcpack2" }; if (RegisterProtocol(PROTOCOL_UBRPC_MCPACK2, ubrpc_mcpack2_protocol) != 0) { exit(1); @@ -618,8 +615,8 @@ static void GlobalInitializeOrDieImpl() { Protocol nshead_mcpack_protocol = { ParseNsheadMessage, SerializeNsheadMcpackRequest, PackNsheadMcpackRequest, - NULL, ProcessNsheadMcpackResponse, - NULL, NULL, NULL, + nullptr, ProcessNsheadMcpackResponse, + nullptr, nullptr, nullptr, CONNECTION_TYPE_POOLED_AND_SHORT, "nshead_mcpack" }; if (RegisterProtocol(PROTOCOL_NSHEAD_MCPACK, nshead_mcpack_protocol) != 0) { exit(1); @@ -629,7 +626,7 @@ static void GlobalInitializeOrDieImpl() { ParseRtmpMessage, SerializeRtmpRequest, PackRtmpRequest, ProcessRtmpMessage, ProcessRtmpMessage, - NULL, NULL, NULL, + nullptr, nullptr, nullptr, (ConnectionType)(CONNECTION_TYPE_SINGLE|CONNECTION_TYPE_SHORT), "rtmp" }; if (RegisterProtocol(PROTOCOL_RTMP, rtmp_protocol) != 0) { @@ -639,8 +636,8 @@ static void GlobalInitializeOrDieImpl() { Protocol esp_protocol = { ParseEspMessage, SerializeEspRequest, PackEspRequest, - NULL, ProcessEspResponse, - NULL, NULL, NULL, + nullptr, ProcessEspResponse, + nullptr, nullptr, nullptr, CONNECTION_TYPE_POOLED_AND_SHORT, "esp"}; if (RegisterProtocol(PROTOCOL_ESP, esp_protocol) != 0) { exit(1); @@ -649,10 +646,10 @@ static void GlobalInitializeOrDieImpl() { Protocol mysql_protocol = {ParseMysqlMessage, SerializeMysqlRequest, PackMysqlRequest, - NULL, + nullptr, ProcessMysqlResponse, - NULL, - NULL, + nullptr, + nullptr, GetMysqlMethodName, CONNECTION_TYPE_POOLED_AND_SHORT, "mysql"}; @@ -669,8 +666,8 @@ static void GlobalInitializeOrDieImpl() { handler.parse = protocols[i].parse; handler.process = protocols[i].process_response; // No need to verify at client side - handler.verify = NULL; - handler.arg = NULL; + handler.verify = nullptr; + handler.arg = nullptr; handler.name = protocols[i].name; if (get_or_new_client_side_messenger()->AddHandler(handler) != 0) { exit(1); @@ -695,7 +692,7 @@ static void GlobalInitializeOrDieImpl() { bthread_t th; bthread_attr_t attr = BTHREAD_ATTR_NORMAL; bthread_attr_set_name(&attr, "GlobalUpdate"); - CHECK(bthread_start_background(&th, &attr, GlobalUpdate, NULL) == 0) + CHECK(bthread_start_background(&th, &attr, GlobalUpdate, nullptr) == 0) << "Fail to start GlobalUpdate"; } diff --git a/src/brpc/grpc.cpp b/src/brpc/grpc.cpp index 87f98c028d..bde72a2f2a 100644 --- a/src/brpc/grpc.cpp +++ b/src/brpc/grpc.cpp @@ -173,7 +173,7 @@ int64_t ConvertGrpcTimeoutToUS(const std::string* grpc_timeout) { if (!grpc_timeout || grpc_timeout->empty()) { return -1; } - char* endptr = NULL; + char* endptr = nullptr; int64_t timeout_value = (int64_t)strtol(grpc_timeout->data(), &endptr, 10); // Only the format that the digit number is equal to (timeout header size - 1) // is valid. Otherwise the format is not valid and is treated as no deadline. diff --git a/src/brpc/http_header.cpp b/src/brpc/http_header.cpp index 9cc82b7bdb..6ef074712e 100644 --- a/src/brpc/http_header.cpp +++ b/src/brpc/http_header.cpp @@ -30,7 +30,7 @@ HttpHeader::HttpHeader() : _status_code(HTTP_STATUS_OK) , _method(HTTP_METHOD_GET) , _version(1, 1) - , _first_set_cookie(NULL) { + , _first_set_cookie(nullptr) { // NOTE: don't forget to clear the field in Clear() as well. } @@ -92,7 +92,7 @@ void HttpHeader::RemoveHeader(const char* key) { } else { _headers.erase(key); if (IsSetCookie(key)) { - _first_set_cookie = NULL; + _first_set_cookie = nullptr; } } } @@ -130,12 +130,12 @@ std::string& HttpHeader::GetOrAddHeader(const std::string& key) { bool is_set_cookie = IsSetCookie(key); // Only returns the first Set-Cookie header field for compatibility. - if (is_set_cookie && NULL != _first_set_cookie) { + if (is_set_cookie && nullptr != _first_set_cookie) { return *_first_set_cookie; } std::string* val = _headers.seek(key); - if (NULL == val) { + if (nullptr == val) { val = _headers.insert({ key, "" }); if (is_set_cookie) { _first_set_cookie = val; @@ -146,7 +146,7 @@ std::string& HttpHeader::GetOrAddHeader(const std::string& key) { std::string& HttpHeader::AddHeader(const std::string& key) { std::string* val = _headers.insert({ key, "" }); - if (IsSetCookie(key) && NULL == _first_set_cookie) { + if (IsSetCookie(key) && nullptr == _first_set_cookie) { _first_set_cookie = val; } return *val; diff --git a/src/brpc/http_header.h b/src/brpc/http_header.h index 39b2fa9b0b..58b92ecb19 100644 --- a/src/brpc/http_header.h +++ b/src/brpc/http_header.h @@ -78,7 +78,7 @@ class HttpHeader { // https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 // Namely, GetHeader("log-id"), GetHeader("Log-Id"), GetHeader("LOG-ID") // point to the same value. - // Return pointer to the value, NULL on not found. + // Return pointer to the value, nullptr on not found. // NOTE: If the key is "Content-Type", `GetHeader("Content-Type")' // (case-insensitive) is equal to `content_type()'. const std::string* GetHeader(const char* key) const; diff --git a/src/brpc/http_method.cpp b/src/brpc/http_method.cpp index c66ed33dc2..0d5cbf98a4 100644 --- a/src/brpc/http_method.cpp +++ b/src/brpc/http_method.cpp @@ -59,7 +59,7 @@ static HttpMethodPair g_method_pairs[] = { { HTTP_METHOD_MKCALENDAR , "MKCALENDAR" }, }; -static const char* g_method2str_map[64] = { NULL }; +static const char* g_method2str_map[64] = { nullptr }; static pthread_once_t g_init_maps_once = PTHREAD_ONCE_INIT; static uint8_t g_first_char_index[26] = { 0 }; diff --git a/src/brpc/http_status_code.cpp b/src/brpc/http_status_code.cpp index cd3a7c249b..01f132b78b 100644 --- a/src/brpc/http_status_code.cpp +++ b/src/brpc/http_status_code.cpp @@ -104,7 +104,7 @@ static BAIDU_THREAD_LOCAL char tls_phrase_cache[64]; const char *HttpReasonPhrase(int status_code) { pthread_once(&init_reason_phrases_once, InitReasonPhrases); - const char* desc = NULL; + const char* desc = nullptr; if (status_code >= 0 && status_code < (int)ARRAY_SIZE(phrases) && (desc = phrases[status_code])) { diff --git a/src/brpc/http_status_code.h b/src/brpc/http_status_code.h index 3dedfeeced..b196946a86 100644 --- a/src/brpc/http_status_code.h +++ b/src/brpc/http_status_code.h @@ -71,7 +71,7 @@ namespace brpc { // Return the reason phrase of a given status_code. // "Unknown status code (|status_code|)" will be returned if the status_code is // unknown -// This function is thread-safe and NULL is never supposed to be returned +// This function is thread-safe and nullptr is never supposed to be returned // // NOTICE: the memory referenced by the pointer returned before might be reused // when this function is called again, so please DON'T try to cache the return diff --git a/src/brpc/input_messenger.cpp b/src/brpc/input_messenger.cpp index 1e42f92351..81154be134 100644 --- a/src/brpc/input_messenger.cpp +++ b/src/brpc/input_messenger.cpp @@ -33,7 +33,7 @@ namespace brpc { -InputMessenger* g_messenger = NULL; +InputMessenger* g_messenger = nullptr; static pthread_once_t g_messenger_init = PTHREAD_ONCE_INIT; static void InitClientSideMessenger() { g_messenger = new InputMessenger; @@ -87,7 +87,7 @@ ParseResult InputMessenger::CutInputMessage( // Try preferred handler first. The preferred_index is set on last // selection or by client. if (preferred >= 0 && preferred <= max_index - && _handlers[preferred].parse != NULL) { + && _handlers[preferred].parse != nullptr) { int cur_index = preferred; do { ParseResult result = @@ -132,12 +132,12 @@ ParseResult InputMessenger::CutInputMessage( // Clear context before trying next protocol which probably has // an incompatible context with the current one. if (m->parsing_context()) { - m->reset_parsing_context(NULL); + m->reset_parsing_context(nullptr); } m->set_preferred_index(-1); } for (int i = 0; i <= max_index; ++i) { - if (i == preferred || _handlers[i].parse == NULL) { + if (i == preferred || _handlers[i].parse == nullptr) { // Don't try preferred handler(already tried) or invalid handler continue; } @@ -160,7 +160,7 @@ ParseResult InputMessenger::CutInputMessage( // Clear context before trying next protocol which definitely has // an incompatible context with the current one. if (m->parsing_context()) { - m->reset_parsing_context(NULL); + m->reset_parsing_context(nullptr); } // Try other protocols. } @@ -170,7 +170,7 @@ ParseResult InputMessenger::CutInputMessage( void* ProcessInputMessage(void* void_arg) { InputMessageBase* msg = static_cast(void_arg); msg->_process(msg); - return NULL; + return nullptr; } struct RunLastMessage { @@ -249,7 +249,7 @@ int InputMessenger::ProcessNewMessage( } m->_last_msg_size = 0; - if (pr.message() == NULL) { // the Process() step can be skipped. + if (pr.message() == nullptr) { // the Process() step can be skipped. continue; } pr.message()->_received_us = received_us; @@ -259,7 +259,7 @@ int InputMessenger::ProcessNewMessage( // ownership to last_msg DestroyingPtr msg(pr.message()); m->_transport->QueueMessage(last_msg, &num_bthread_created, false); - if (_handlers[index].process == NULL) { + if (_handlers[index].process == nullptr) { LOG(ERROR) << "process of index=" << index << " is NULL"; continue; } @@ -268,7 +268,7 @@ int InputMessenger::ProcessNewMessage( msg->_process = _handlers[index].process; msg->_arg = _handlers[index].arg; - if (_handlers[index].verify != NULL) { + if (_handlers[index].verify != nullptr) { int auth_error = 0; if (0 == m->FightAuthentication(&auth_error)) { // Get the right to authenticate @@ -378,7 +378,7 @@ void InputMessenger::OnNewMessages(Socket* m) { } InputMessenger::InputMessenger(size_t capacity) - : _handlers(NULL) + : _handlers(nullptr) , _max_index(-1) , _non_protocol(false) , _capacity(capacity) { @@ -386,24 +386,20 @@ InputMessenger::InputMessenger(size_t capacity) InputMessenger::~InputMessenger() { delete[] _handlers; - _handlers = NULL; + _handlers = nullptr; _max_index.store(-1, butil::memory_order_relaxed); _capacity = 0; } int InputMessenger::AddHandler(const InputMessageHandler& handler) { - if (handler.parse == NULL || handler.process == NULL - || handler.name == NULL) { + if (handler.parse == nullptr || handler.process == nullptr + || handler.name == nullptr) { CHECK(false) << "Invalid argument"; return -1; } BAIDU_SCOPED_LOCK(_add_handler_mutex); - if (NULL == _handlers) { - _handlers = new (std::nothrow) InputMessageHandler[_capacity]; - if (NULL == _handlers) { - LOG(FATAL) << "Fail to new array of InputMessageHandler"; - return -1; - } + if (nullptr == _handlers) { + _handlers = new InputMessageHandler[_capacity]; memset(_handlers, 0, sizeof(*_handlers) * _capacity); _non_protocol = false; } @@ -421,7 +417,7 @@ int InputMessenger::AddHandler(const InputMessageHandler& handler) { LOG(FATAL) << "Can't add more handlers than " << _capacity; return -1; } - if (_handlers[index].parse == NULL) { + if (_handlers[index].parse == nullptr) { // The same protocol might be added more than twice _handlers[index] = handler; } else if (_handlers[index].parse != handler.parse @@ -437,18 +433,14 @@ int InputMessenger::AddHandler(const InputMessageHandler& handler) { } int InputMessenger::AddNonProtocolHandler(const InputMessageHandler& handler) { - if (handler.parse == NULL || handler.process == NULL - || handler.name == NULL) { + if (handler.parse == nullptr || handler.process == nullptr + || handler.name == nullptr) { CHECK(false) << "Invalid argument"; return -1; } BAIDU_SCOPED_LOCK(_add_handler_mutex); - if (NULL == _handlers) { - _handlers = new (std::nothrow) InputMessageHandler[_capacity]; - if (NULL == _handlers) { - LOG(FATAL) << "Fail to new array of InputMessageHandler"; - return -1; - } + if (nullptr == _handlers) { + _handlers = new InputMessageHandler[_capacity]; memset(_handlers, 0, sizeof(*_handlers) * _capacity); _non_protocol = true; } @@ -513,7 +505,7 @@ int InputMessenger::Create(SocketOptions options, SocketId* id) { int InputMessenger::FindProtocolIndex(const char* name) const { for (size_t i = 0; i < _capacity; ++i) { - if (_handlers[i].parse != NULL + if (_handlers[i].parse != nullptr && strcmp(name, _handlers[i].name) == 0) { return i; } @@ -523,7 +515,7 @@ int InputMessenger::FindProtocolIndex(const char* name) const { int InputMessenger::FindProtocolIndex(ProtocolType type) const { const Protocol* proto = FindProtocol(type); - if (NULL == proto) { + if (nullptr == proto) { return -1; } return FindProtocolIndex(proto->name); @@ -531,7 +523,7 @@ int InputMessenger::FindProtocolIndex(ProtocolType type) const { } const char* InputMessenger::NameOfProtocol(int n) const { - if (n < 0 || (size_t)n >= _capacity || _handlers[n].parse == NULL) { + if (n < 0 || (size_t)n >= _capacity || _handlers[n].parse == nullptr) { return "unknown"; // use lowercase to be consistent with valid names. } return _handlers[n].name; diff --git a/src/brpc/input_messenger.h b/src/brpc/input_messenger.h index e82ecd4a66..d056263e2e 100644 --- a/src/brpc/input_messenger.h +++ b/src/brpc/input_messenger.h @@ -61,7 +61,7 @@ struct InputMessageHandler { Process process; // The callback to verify authentication of this socket. Only called - // on the first message that a socket receives. Can be NULL when + // on the first message that a socket receives. Can be nullptr when // authentication is not needed or this is the client side. // Returns true on successful authentication. typedef bool (*Verify)(const InputMessageBase* msg); @@ -76,12 +76,12 @@ struct InputMessageHandler { class InputMessageClosure { public: - InputMessageClosure() : _msg(NULL) { } + InputMessageClosure() : _msg(nullptr) { } ~InputMessageClosure() noexcept(false); InputMessageBase* release() { InputMessageBase* m = _msg; - _msg = NULL; + _msg = nullptr; return m; } diff --git a/src/brpc/kvmap.h b/src/brpc/kvmap.h index 489ed2e62d..9cb755b72a 100644 --- a/src/brpc/kvmap.h +++ b/src/brpc/kvmap.h @@ -37,7 +37,7 @@ class KVMap { void Clear() { _entries.clear(); } // Get value of a key(case-sensitive) - // Return pointer to the value, NULL on not found. + // Return pointer to the value, nullptr on not found. const std::string* Get(const char* key) const { return _entries.seek(key); } const std::string* Get(const std::string& key) const { return _entries.seek(key); diff --git a/src/brpc/load_balancer.cpp b/src/brpc/load_balancer.cpp index 2532d9efad..0544a48367 100644 --- a/src/brpc/load_balancer.cpp +++ b/src/brpc/load_balancer.cpp @@ -65,7 +65,7 @@ void SharedLoadBalancer::ExposeLB() { } SharedLoadBalancer::SharedLoadBalancer() - : _lb(NULL) + : _lb(nullptr) , _weight_sum(0) , _exposed(false) , _st(DescribeLB, this) { @@ -75,7 +75,7 @@ SharedLoadBalancer::~SharedLoadBalancer() { _st.hide(); if (_lb) { _lb->Destroy(); - _lb = NULL; + _lb = nullptr; } } @@ -87,12 +87,12 @@ int SharedLoadBalancer::Init(const char* lb_protocol) { return -1; } const LoadBalancer* lb = LoadBalancerExtension()->Find(lb_name.c_str()); - if (lb == NULL) { + if (lb == nullptr) { LOG(FATAL) << "Fail to find LoadBalancer by `" << lb_name << "'"; return -1; } _lb = lb->New(lb_params); - if (_lb == NULL) { + if (_lb == nullptr) { LOG(FATAL) << "Fail to new LoadBalancer"; return -1; } @@ -104,7 +104,7 @@ int SharedLoadBalancer::Init(const char* lb_protocol) { void SharedLoadBalancer::Describe(std::ostream& os, const DescribeOptions& options) { - if (_lb == NULL) { + if (_lb == nullptr) { os << "lb=NULL"; } else { _lb->Describe(os, options); diff --git a/src/brpc/memcache.cpp b/src/brpc/memcache.cpp index 8d01e7bfee..8c6857992f 100644 --- a/src/brpc/memcache.cpp +++ b/src/brpc/memcache.cpp @@ -65,7 +65,7 @@ bool MemcacheRequest::MergePartialFromCodedStream( // simple approach just making it work. butil::IOBuf tmp; - const void* data = NULL; + const void* data = nullptr; int size = 0; while (input->GetDirectBufferPointer(&data, &size)) { tmp.append(data, size); @@ -77,7 +77,7 @@ bool MemcacheRequest::MergePartialFromCodedStream( char aux_buf[sizeof(policy::MemcacheRequestHeader)]; const policy::MemcacheRequestHeader* header = (const policy::MemcacheRequestHeader*)tmp.fetch(aux_buf, sizeof(aux_buf)); - if (header == NULL) { + if (header == nullptr) { return false; } if (header->magic != (uint8_t)policy::MC_MAGIC_REQUEST) { @@ -100,7 +100,7 @@ void MemcacheRequest::SerializeWithCachedSizes( // simple approach just making it work. butil::IOBufAsZeroCopyInputStream wrapper(_buf); - const void* data = NULL; + const void* data = nullptr; int size = 0; while (wrapper.Next(&data, &size)) { output->WriteRaw(data, size); @@ -172,7 +172,7 @@ bool MemcacheResponse::MergePartialFromCodedStream( LOG(WARNING) << "You're not supposed to parse a MemcacheResponse"; // simple approach just making it work. - const void* data = NULL; + const void* data = nullptr; int size = 0; while (input->GetDirectBufferPointer(&data, &size)) { _buf.append(data, size); @@ -187,7 +187,7 @@ void MemcacheResponse::SerializeWithCachedSizes( // simple approach just making it work. butil::IOBufAsZeroCopyInputStream wrapper(_buf); - const void* data = NULL; + const void* data = nullptr; int size = 0; while (wrapper.Next(&data, &size)) { output->WriteRaw(data, size); @@ -423,10 +423,10 @@ bool MemcacheResponse::PopGet( // MUST NOT have key // MUST NOT have value bool MemcacheResponse::PopDelete() { - return PopStore(policy::MC_BINARY_DELETE, NULL); + return PopStore(policy::MC_BINARY_DELETE, nullptr); } bool MemcacheResponse::PopFlush() { - return PopStore(policy::MC_BINARY_FLUSH, NULL); + return PopStore(policy::MC_BINARY_FLUSH, nullptr); } struct StoreHeaderWithExtras { diff --git a/src/brpc/memcache.h b/src/brpc/memcache.h index daedd49861..261de3f84c 100644 --- a/src/brpc/memcache.h +++ b/src/brpc/memcache.h @@ -39,7 +39,7 @@ namespace brpc { // ... // MemcacheResponse response; // // 2 GET and 1 SET are sent to the server together. -// channel.CallMethod(&controller, &request, &response, NULL/*done*/); +// channel.CallMethod(&controller, &request, &response, nullptr/*done*/); class MemcacheRequest : public NonreflectableMessage { public: MemcacheRequest(); @@ -127,7 +127,7 @@ class MemcacheRequest : public NonreflectableMessage { // of operations in corresponding MemcacheRequest. // Example: // MemcacheResponse response; -// channel.CallMethod(&controller, &request, &response, NULL/*done*/); +// channel.CallMethod(&controller, &request, &response, nullptr/*done*/); // ... // if (!response.PopGet(&my_value1, &flags1, &cas1)) { // LOG(FATAL) << "Fail to pop GET: " << response.LastError(); diff --git a/src/brpc/nshead_message.cpp b/src/brpc/nshead_message.cpp index 46081c702a..ba2285d3d1 100644 --- a/src/brpc/nshead_message.cpp +++ b/src/brpc/nshead_message.cpp @@ -56,7 +56,7 @@ size_t NsheadMessage::ByteSizeLong() const { void NsheadMessage::MergeFrom(const ::google::protobuf::Message& from) { CHECK_NE(&from, this); const NsheadMessage* source = dynamic_cast(&from); - if (source == NULL) { + if (source == nullptr) { LOG(ERROR) << "Can only merge from NsheadMessage"; return; } else { diff --git a/src/brpc/nshead_pb_service_adaptor.cpp b/src/brpc/nshead_pb_service_adaptor.cpp index 889f957540..956e150844 100644 --- a/src/brpc/nshead_pb_service_adaptor.cpp +++ b/src/brpc/nshead_pb_service_adaptor.cpp @@ -66,7 +66,7 @@ SendNsheadPbResponse::SendNsheadPbResponse( , cntl(cntl2) , ns_res(ns_res2) , done(done2) - , status(NULL) { + , status(nullptr) { } void SendNsheadPbResponse::Run() { @@ -116,7 +116,7 @@ void NsheadPbServiceAdaptor::ProcessNsheadRequest( ServerPrivateAccessor server_accessor(&server); const Server::MethodProperty *sp = server_accessor .FindMethodPropertyByFullName(meta->full_method_name()); - if (NULL == sp || + if (nullptr == sp || sp->service->GetDescriptor() == BadMethodService::descriptor()) { controller->SetFailed(ENOMETHOD, "Fail to find method=%s", meta->full_method_name().c_str()); diff --git a/src/brpc/nshead_pb_service_adaptor.h b/src/brpc/nshead_pb_service_adaptor.h index 8fa1e8244c..3bb04dc34c 100644 --- a/src/brpc/nshead_pb_service_adaptor.h +++ b/src/brpc/nshead_pb_service_adaptor.h @@ -73,7 +73,7 @@ class NsheadPbServiceAdaptor : public NsheadService { // meta: was set by ParseNsheadMeta() // controller: If something goes wrong, call controller->SetFailed() // pb_res: the pb response that returned by pb method. [NOTE] `pb_res' - // can be NULL or uninitialized when RPC failed (indicated by + // can be nullptr or uninitialized when RPC failed (indicated by // Controller::Failed()), in which case you may put error // information into `nshead_res'. // nshead_res: the nshead response that will be sent back to client. diff --git a/src/brpc/nshead_service.cpp b/src/brpc/nshead_service.cpp index 0371baaefd..04ad60210a 100644 --- a/src/brpc/nshead_service.cpp +++ b/src/brpc/nshead_service.cpp @@ -30,7 +30,7 @@ NsheadService::NsheadService() : _additional_space(0) { } NsheadService::NsheadService(const NsheadServiceOptions& options) - : _status(NULL), _additional_space(options.additional_space) { + : _status(nullptr), _additional_space(options.additional_space) { if (options.generate_status) { _status = new MethodStatus; } @@ -38,7 +38,7 @@ NsheadService::NsheadService(const NsheadServiceOptions& options) NsheadService::~NsheadService() { delete _status; - _status = NULL; + _status = nullptr; } void NsheadService::Describe(std::ostream &os, const DescribeOptions&) const { @@ -47,7 +47,7 @@ void NsheadService::Describe(std::ostream &os, const DescribeOptions&) const { void NsheadService::Expose(const butil::StringPiece& prefix) { _cached_name = butil::class_name_str(*this); - if (_status == NULL) { + if (_status == nullptr) { return; } std::string s; diff --git a/src/brpc/nshead_service.h b/src/brpc/nshead_service.h index 49ff9d79ce..149beca196 100644 --- a/src/brpc/nshead_service.h +++ b/src/brpc/nshead_service.h @@ -47,7 +47,7 @@ class NsheadClosure : public google::protobuf::Closure { // The space required by subclass at NsheadServiceOptions. subclass may // utilizes this feature to save the cost of allocating closure separately. - // If subclass does not require space, this return value is NULL. + // If subclass does not require space, this return value is nullptr. void* additional_space() { return _additional_space; } int64_t received_us() const { return _received_us; } diff --git a/src/brpc/parallel_channel.cpp b/src/brpc/parallel_channel.cpp index de2b86f1c4..5ae115c0bb 100644 --- a/src/brpc/parallel_channel.cpp +++ b/src/brpc/parallel_channel.cpp @@ -34,7 +34,7 @@ struct Memory { int size; void* ptr; }; -static __thread Memory tls_cached_pchan_mem = { 0, NULL }; +static __thread Memory tls_cached_pchan_mem = { 0, nullptr }; #endif class ParallelChannelDone : public google::protobuf::Closure { @@ -59,7 +59,7 @@ class ParallelChannelDone : public google::protobuf::Closure { public: class SubDone : public google::protobuf::Closure { public: - SubDone() : shared_data(NULL) { + SubDone() : shared_data(nullptr) { } ~SubDone() override { @@ -102,7 +102,7 @@ class ParallelChannelDone : public google::protobuf::Closure { if (ndone != nchan) { req_size += sizeof(int) * nchan; } - void* mem = NULL; + void* mem = nullptr; int memsize = 0; #ifdef BRPC_CACHE_PCHAN_MEM Memory pchan_mem = tls_cached_pchan_mem; @@ -110,20 +110,20 @@ class ParallelChannelDone : public google::protobuf::Closure { mem = pchan_mem.ptr; memsize = pchan_mem.size; pchan_mem.size = 0; - pchan_mem.ptr = NULL; + pchan_mem.ptr = nullptr; tls_cached_pchan_mem = pchan_mem; } else { mem = malloc(req_size); memsize = req_size; - if (BAIDU_UNLIKELY(NULL == mem)) { - return NULL; + if (BAIDU_UNLIKELY(nullptr == mem)) { + return nullptr; } } #else mem = malloc(req_size); memsize = req_size; - if (BAIDU_UNLIKELY(NULL == mem)) { - return NULL; + if (BAIDU_UNLIKELY(nullptr == mem)) { + return nullptr; } #endif auto d = new (mem) ParallelChannelDone( @@ -156,7 +156,7 @@ class ParallelChannelDone : public google::protobuf::Closure { } static void Destroy(ParallelChannelDone* d) { - if (d != NULL) { + if (d != nullptr) { for (int i = 0; i < d->_ndone; ++i) { d->sub_done(i)->~SubDone(); } @@ -189,12 +189,12 @@ class ParallelChannelDone : public google::protobuf::Closure { } else { CHECK(ECANCELED == ec || ERPCTIMEDOUT == ec) << "ec=" << ec; } - OnSubDoneRun(NULL); + OnSubDoneRun(nullptr); } static void* RunOnComplete(void* arg) { static_cast(arg)->OnComplete(); - return NULL; + return nullptr; } // For otherwhere to know if they're in the same thread. @@ -213,7 +213,7 @@ class ParallelChannelDone : public google::protobuf::Closure { } void OnSubDoneRun(SubDone* fin) { - if (fin != NULL) { + if (fin != nullptr) { // [ called from SubDone::Run() ] int error_code = fin->cntl.ErrorCode(); @@ -287,7 +287,7 @@ class ParallelChannelDone : public google::protobuf::Closure { } butil::atomic_thread_fence(butil::memory_order_acquire); - if (fin != NULL && + if (fin != nullptr && !_cntl->is_done_allowed_to_run_in_place() && IsSameThreadAsCallMethod()) { // A sub channel's CallMethod calls a subdone directly, create a @@ -321,7 +321,7 @@ class ParallelChannelDone : public google::protobuf::Closure { SubDone* sd = sub_done(i); google::protobuf::Message* sub_res = sd->cntl._response; if (!sd->cntl.FailedInline()) { // successful calls only. - if (sd->merger == NULL) { + if (sd->merger == nullptr) { try { _cntl->_response->MergeFrom(*sub_res); } catch (const std::exception& e) { @@ -413,7 +413,7 @@ class ParallelChannelDone : public google::protobuf::Closure { } int sub_channel_size() const { return _nchan; } - // Different from sub_done(), sub_channel_controller returns NULL for + // Different from sub_done(), sub_channel_controller returns nullptr for // invalid accesses and never crashes. const Controller* sub_channel_controller(int i) const { if (i >= 0 && i < _nchan) { @@ -425,7 +425,7 @@ class ParallelChannelDone : public google::protobuf::Closure { return &sub_done(offset)->cntl; } } - return NULL; + return nullptr; } private: @@ -460,7 +460,7 @@ const Controller* GetSubControllerOfParallelChannel( } int ParallelChannel::Init(const ParallelChannelOptions* options) { - if (options != NULL) { + if (options != nullptr) { _options = *options; } return 0; @@ -470,7 +470,7 @@ int ParallelChannel::AddChannel(ChannelBase* sub_channel, ChannelOwnership ownership, CallMapper* call_mapper, ResponseMerger* merger) { - if (NULL == sub_channel) { + if (nullptr == sub_channel) { LOG(ERROR) << "Param[sub_channel] is NULL"; return -1; } @@ -490,7 +490,7 @@ int ParallelChannel::AddChannel(ChannelBase* sub_channel, ChannelOwnership ownership, const butil::intrusive_ptr& call_mapper, const butil::intrusive_ptr& merger) { - if (NULL == sub_channel) { + if (nullptr == sub_channel) { LOG(ERROR) << "Param[sub_channel] is NULL"; return -1; } @@ -569,12 +569,12 @@ void* ParallelChannel::RunDoneAndDestroy(void* arg) { Controller* c = static_cast(arg); // Move done out from the controller. google::protobuf::Closure* done = c->_done; - c->_done = NULL; + c->_done = nullptr; // Save call_id from the controller which may be deleted after Run(). const bthread_id_t cid = c->call_id(); done->Run(); CHECK_EQ(0, bthread_id_unlock_and_destroy(cid)); - return NULL; + return nullptr; } void ParallelChannel::CallMethod( @@ -590,7 +590,7 @@ void ParallelChannel::CallMethod( cntl->_pchan_sub_count = nchan; const CallId cid = cntl->call_id(); - const int rc = bthread_id_lock(cid, NULL); + const int rc = bthread_id_lock(cid, nullptr); if (rc != 0) { CHECK_EQ(EINVAL, rc); if (!cntl->FailedInline()) { @@ -608,7 +608,7 @@ void ParallelChannel::CallMethod( } cntl->set_used_by_rpc(); - ParallelChannelDone* d = NULL; + ParallelChannelDone* d = nullptr; int ndone = nchan; int fail_limit = 1; int success_limit = 1; @@ -619,8 +619,8 @@ void ParallelChannel::CallMethod( // The call_id is cancelled before RPC. goto FAIL; } - // we don't support http whose response is NULL. - if (response == NULL) { + // we don't support http whose response is nullptr. + if (response == nullptr) { cntl->SetFailed(EINVAL, "response must be non-NULL"); goto FAIL; } @@ -631,7 +631,7 @@ void ParallelChannel::CallMethod( for (int i = 0; i < nchan; ++i) { SubChan& sub_chan = _chans[i]; - if (sub_chan.call_mapper != NULL) { + if (sub_chan.call_mapper != nullptr) { aps[i] = sub_chan.call_mapper->Map(i, nchan, method, request, response); // Test is_skip first because it implies is_bad. if (aps[i].is_skip()) { @@ -643,7 +643,7 @@ void ParallelChannel::CallMethod( } } else { google::protobuf::Message* cur_res = response->New(); - if (cur_res == NULL) { + if (cur_res == nullptr) { cntl->SetFailed(ENOMEM, "Fail to new response"); goto FAIL; } @@ -681,7 +681,7 @@ void ParallelChannel::CallMethod( d = ParallelChannelDone::Create( fail_limit, success_limit, ndone, aps, nchan, cntl, done); - if (NULL == d) { + if (nullptr == d) { cntl->SetFailed(ENOMEM, "Fail to new ParallelChannelDone"); goto FAIL; } @@ -728,7 +728,7 @@ void ParallelChannel::CallMethod( for (int i = 0, j = 0; i < nchan; ++i) { if (!aps[i].is_skip()) { ParallelChannelDone::SubDone* sd = d->sub_done(j++); - if (NULL != _chans[i].call_mapper) { + if (nullptr != _chans[i].call_mapper) { _chans[i].call_mapper->MapController(i, nchan, cntl, &sd->cntl); } else { // Forward the attachment to each sub call. @@ -749,7 +749,7 @@ void ParallelChannel::CallMethod( // Destroy()-ed) because we may need to check requests for debugging // purposes. } - if (done == NULL) { + if (done == nullptr) { Join(cid); cntl->OnRPCEnd(butil::gettimeofday_us()); } @@ -758,8 +758,8 @@ void ParallelChannel::CallMethod( FAIL: // The RPC was failed after locking call_id and before calling sub channels. if (d) { - // Set the _done to NULL to make sure cntl->sub(any_index) is NULL. - cntl->_done = NULL; + // Set the _done to nullptr to make sure cntl->sub(any_index) is nullptr. + cntl->_done = nullptr; ParallelChannelDone::Destroy(d); } if (done) { @@ -772,7 +772,7 @@ void ParallelChannel::CallMethod( if (bthread_start_background(&bh, &attr, RunDoneAndDestroy, cntl) == 0) { return; } - cntl->_done = NULL; + cntl->_done = nullptr; LOG(FATAL) << "Fail to start bthread"; } done->Run(); diff --git a/src/brpc/parallel_channel.h b/src/brpc/parallel_channel.h index 292213c1ad..03f2f44669 100644 --- a/src/brpc/parallel_channel.h +++ b/src/brpc/parallel_channel.h @@ -46,7 +46,7 @@ struct SubCall { , flags(flags2) { } - SubCall() : method(NULL), request(NULL), response(NULL), flags(0) { } + SubCall() : method(nullptr), request(nullptr), response(nullptr), flags(0) { } // Returning this makes the call to ParallelChannel fail immediately. static SubCall Bad() { return SubCall(); } @@ -60,7 +60,7 @@ struct SubCall { // True if this object is constructed by Bad(). bool is_bad() const { - return request == NULL || response == NULL; + return request == nullptr || response == nullptr; } // True if this object is constructed by Skip(). @@ -213,11 +213,11 @@ friend class Controller; // is OWNS_CHANNEL. // A sub channel can be added multiple times. If it's added with // brpc::OWNS_CHANNEL, it will be deleted for only once. - // If call_mapper is NULL: + // If call_mapper is nullptr: // - Every sub_channel will get the same `request' to ParallelChannel // - responses of sub channels are New()-ed from the `response' to // ParallelChannel. - // If response_merger is NULL: + // If response_merger is nullptr: // - responses of sub channels will be merged to the `response' to // ParalleChannel by google::protobuf::Message::MergeFrom(). // `call_mapper' and `response_merger' are always deleted in dtor. @@ -243,7 +243,7 @@ friend class Controller; // Call `method' of the remote service with `request' as input, and // `response' as output. `controller' contains options and extra data. - // If `done' is not NULL, this method returns after request was sent + // If `done' is not nullptr, this method returns after request was sent // and `done->Run()' will be called when the call finishes, otherwise // caller blocks until the call finishes. void CallMethod(const google::protobuf::MethodDescriptor* method, diff --git a/src/brpc/parse_result.h b/src/brpc/parse_result.h index d916acc5ad..5a2be5dc6f 100644 --- a/src/brpc/parse_result.h +++ b/src/brpc/parse_result.h @@ -51,13 +51,13 @@ class ParseResult { public: // Create a failed parsing result. explicit ParseResult(ParseError err) - : _msg(NULL), _err(err), _user_desc(NULL) {} + : _msg(nullptr), _err(err), _user_desc(nullptr) {} // The `user_desc' must be string constant or always valid. explicit ParseResult(ParseError err, const char* user_desc) - : _msg(NULL), _err(err), _user_desc(user_desc) {} + : _msg(nullptr), _err(err), _user_desc(user_desc) {} // Create a successful parsing result. explicit ParseResult(InputMessageBase* msg) - : _msg(msg), _err(PARSE_OK), _user_desc(NULL) {} + : _msg(msg), _err(PARSE_OK), _user_desc(nullptr) {} // Return PARSE_OK when the result is successful. ParseError error() const { return _err; } @@ -65,7 +65,7 @@ class ParseResult { { return _user_desc ? _user_desc : ParseErrorToString(_err); } bool is_ok() const { return error() == PARSE_OK; } - // definitely NULL when result is failed. + // definitely nullptr when result is failed. InputMessageBase* message() const { return _msg; } private: diff --git a/src/brpc/partition_channel.cpp b/src/brpc/partition_channel.cpp index f6a37bc223..80633af231 100644 --- a/src/brpc/partition_channel.cpp +++ b/src/brpc/partition_channel.cpp @@ -46,7 +46,7 @@ class PartitionChannelBase : public ParallelChannel, size_t RemoveServersInBatch(const std::vector& servers); private: - bool initialized() const { return _parser != NULL; } + bool initialized() const { return _parser != nullptr; } void PartitionServersIntoTemps(const std::vector& servers); void OnAddedServers(const std::vector& servers); void OnRemovedServers(const std::vector& servers); @@ -61,13 +61,13 @@ class PartitionChannelBase : public ParallelChannel, }; PartitionChannelBase::PartitionChannelBase() - : _subs(NULL) - , _parser(NULL) { + : _subs(nullptr) + , _parser(nullptr) { } PartitionChannelBase::~PartitionChannelBase() { delete [] _subs; - _subs = NULL; + _subs = nullptr; } int PartitionChannelBase::Init(int num_partition_kinds, @@ -78,7 +78,7 @@ int PartitionChannelBase::Init(int num_partition_kinds, LOG(ERROR) << "Parameter[num_partition_kinds] must be positive"; return -1; } - if (NULL == partition_parser) { + if (nullptr == partition_parser) { LOG(ERROR) << "Parameter[partition_parser] must be non-NULL"; return -1; } @@ -88,11 +88,7 @@ int PartitionChannelBase::Init(int num_partition_kinds, } options.succeed_without_server = true; options.log_succeed_without_server = false; - _subs = new (std::nothrow) SubChannel[num_partition_kinds]; - if (NULL == _subs) { - LOG(ERROR) << "Fail to new Channels[" << num_partition_kinds << "]"; - return -1; - } + _subs = new SubChannel[num_partition_kinds]; for (int i = 0; i < num_partition_kinds; ++i) { if (_subs[i].Init("list://", load_balancer_name, &options) != 0) { LOG(ERROR) << "Fail to init sub channel[" << i << "]"; @@ -191,8 +187,8 @@ PartitionChannelOptions::PartitionChannelOptions() } PartitionChannel::PartitionChannel() - : _pchan(NULL) - , _parser(NULL) { + : _pchan(nullptr) + , _parser(nullptr) { } PartitionChannel::~PartitionChannel() { @@ -203,9 +199,9 @@ PartitionChannel::~PartitionChannel() { _nsthread_ptr.reset(); } delete _pchan; - _pchan = NULL; + _pchan = nullptr; delete _parser; - _parser = NULL; + _parser = nullptr; } int PartitionChannel::Init(int num_partition_kinds, @@ -219,7 +215,7 @@ int PartitionChannel::Init(int num_partition_kinds, LOG(ERROR) << "Parameter[num_partition_kinds] must be positive"; return -1; } - if (NULL == partition_parser) { + if (nullptr == partition_parser) { LOG(ERROR) << "Parameter[partition_parser] must be non-NULL"; return -1; } @@ -231,18 +227,14 @@ int PartitionChannel::Init(int num_partition_kinds, LOG(ERROR) << "Fail to get NamingServiceThread"; return -1; } - _pchan = new (std::nothrow) PartitionChannelBase; - if (NULL == _pchan) { - LOG(ERROR) << "Fail to new PartitionChannelBase"; - return -1; - } + _pchan = new PartitionChannelBase; if (_pchan->Init(num_partition_kinds, partition_parser, load_balancer_name, options_in) != 0) { LOG(ERROR) << "Fail to init PartitionChannelBase"; return -1; } if (_nsthread_ptr->AddWatcher( - _pchan, (options_in ? options_in->ns_filter : NULL)) != 0) { + _pchan, (options_in ? options_in->ns_filter : nullptr)) != 0) { LOG(ERROR) << "Fail to add PartitionChannelBase as watcher"; return -1; } @@ -257,7 +249,7 @@ void PartitionChannel::CallMethod( const google::protobuf::Message* request, google::protobuf::Message* response, google::protobuf::Closure* done) { - if (_pchan != NULL) { + if (_pchan != nullptr) { _pchan->CallMethod(method, controller, request, response, done); } else { Controller* cntl = static_cast(controller); @@ -276,7 +268,7 @@ int PartitionChannel::partition_count() const { } int PartitionChannel::CheckHealth() { - if (_pchan == NULL) { + if (_pchan == nullptr) { return -1; } return static_cast(_pchan)->CheckHealth(); @@ -308,13 +300,9 @@ class DynamicPartitionChannel::Partitioner : public NamingServiceWatcher { continue; } SubPartitionChannel** ppchan = _part_chan_map.seek(part.num_partition_kinds); - SubPartitionChannel* pchan = NULL; - if (ppchan == NULL) { - pchan = new (std::nothrow) SubPartitionChannel; - if (pchan == NULL) { - LOG(ERROR) << "Fail to new SubPartitionChannel"; - continue; - } + SubPartitionChannel* pchan = nullptr; + if (ppchan == nullptr) { + pchan = new SubPartitionChannel; if (pchan->Init(part.num_partition_kinds, _parser, _load_balancer_name.c_str(), &_options) != 0) { LOG(ERROR) << "Fail to init SubPartitionChannel=#" @@ -382,8 +370,8 @@ class DynamicPartitionChannel::Partitioner : public NamingServiceWatcher { } Partitioner() - : _schan(NULL) - , _parser(NULL) + : _schan(nullptr) + , _parser(nullptr) {} ~Partitioner() { @@ -420,8 +408,8 @@ class DynamicPartitionChannel::Partitioner : public NamingServiceWatcher { }; DynamicPartitionChannel::DynamicPartitionChannel() - : _partitioner(NULL) - , _parser(NULL) { + : _partitioner(nullptr) + , _parser(nullptr) { } DynamicPartitionChannel::~DynamicPartitionChannel() { @@ -432,9 +420,9 @@ DynamicPartitionChannel::~DynamicPartitionChannel() { _nsthread_ptr.reset(); } delete _partitioner; - _partitioner = NULL; + _partitioner = nullptr; delete _parser; - _parser = NULL; + _parser = nullptr; } int DynamicPartitionChannel::Init( @@ -443,7 +431,7 @@ int DynamicPartitionChannel::Init( const char* load_balancer_name, const PartitionChannelOptions* options_in) { GlobalInitializeOrDie(); - if (NULL == partition_parser) { + if (nullptr == partition_parser) { LOG(ERROR) << "Parameter[partition_parser] must be non-NULL"; return -1; } @@ -459,18 +447,14 @@ int DynamicPartitionChannel::Init( LOG(ERROR) << "Fail to init _schan"; return -1; } - _partitioner = new (std::nothrow) Partitioner; - if (NULL == _partitioner) { - LOG(ERROR) << "Fail to new Partitioner"; - return -1; - } + _partitioner = new Partitioner; if (_partitioner->Init(&_schan, partition_parser, load_balancer_name, options_in) != 0) { LOG(ERROR) << "Fail to init Partitioner"; return -1; } if (_nsthread_ptr->AddWatcher( - _partitioner, (options_in ? options_in->ns_filter : NULL)) != 0) { + _partitioner, (options_in ? options_in->ns_filter : nullptr)) != 0) { LOG(ERROR) << "Fail to add Partitioner as watcher"; return -1; } diff --git a/src/brpc/partition_channel.h b/src/brpc/partition_channel.h index f2421b8e8a..4b07732fcf 100644 --- a/src/brpc/partition_channel.h +++ b/src/brpc/partition_channel.h @@ -116,7 +116,7 @@ class PartitionChannel : public ChannelBase { int partition_count() const; private: - bool initialized() const { return _parser != NULL; } + bool initialized() const { return _parser != nullptr; } int CheckHealth(); @@ -154,7 +154,7 @@ class DynamicPartitionChannel : public ChannelBase { google::protobuf::Closure* done); private: - bool initialized() const { return _parser != NULL; } + bool initialized() const { return _parser != nullptr; } int CheckHealth() { return static_cast(&_schan)->CheckHealth(); diff --git a/src/brpc/periodic_task.cpp b/src/brpc/periodic_task.cpp index 3ba9c0ec59..097bc9fdb9 100644 --- a/src/brpc/periodic_task.cpp +++ b/src/brpc/periodic_task.cpp @@ -30,10 +30,10 @@ static void* PeriodicTaskThread(void* arg) { timespec abstime; if (!task->OnTriggeringTask(&abstime)) { // end task->OnDestroyingTask(); - return NULL; + return nullptr; } PeriodicTaskManager::StartTaskAt(task, abstime); - return NULL; + return nullptr; } static void RunPeriodicTaskThread(void* arg) { @@ -50,7 +50,7 @@ static void RunPeriodicTaskThread(void* arg) { } void PeriodicTaskManager::StartTaskAt(PeriodicTask* task, const timespec& abstime) { - if (task == NULL) { + if (task == nullptr) { LOG(ERROR) << "Param[task] is NULL"; return; } 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/progressive_attachment.cpp b/src/brpc/progressive_attachment.cpp index 0f8a3a37f1..233b8b3025 100644 --- a/src/brpc/progressive_attachment.cpp +++ b/src/brpc/progressive_attachment.cpp @@ -150,7 +150,7 @@ int ProgressiveAttachment::Write(const butil::IOBuf& data) { } int ProgressiveAttachment::Write(const void* data, size_t n) { - if (data == NULL || n == 0) { + if (data == nullptr || n == 0) { LOG_EVERY_SECOND(WARNING) << "Write an empty chunk. To suppress this warning, check emptiness" " of the chunk before calling ProgressiveAttachment.Write()"; @@ -239,7 +239,7 @@ static int RunOnFailed(bthread_id_t id, void* data, int) { } void ProgressiveAttachment::NotifyOnStopped(google::protobuf::Closure* done) { - if (done == NULL) { + if (done == nullptr) { LOG(ERROR) << "Param[done] is NULL"; return; } @@ -247,7 +247,7 @@ void ProgressiveAttachment::NotifyOnStopped(google::protobuf::Closure* done) { LOG(ERROR) << "NotifyOnStopped() can only be called once"; return done->Run(); } - if (_httpsock == NULL) { + if (_httpsock == nullptr) { return done->Run(); } const int rc = bthread_id_create(&_notify_id, done, RunOnFailed); diff --git a/src/brpc/progressive_reader.h b/src/brpc/progressive_reader.h index 6f54ae68a7..870664e25b 100644 --- a/src/brpc/progressive_reader.h +++ b/src/brpc/progressive_reader.h @@ -29,7 +29,7 @@ namespace brpc { // Client-side usage: // cntl.response_will_be_read_progressively(); // before RPC // ... -// channel.CallMethod(NULL, &cntl, NULL, NULL, NULL/*done*/); +// channel.CallMethod(nullptr, &cntl, nullptr, nullptr, nullptr/*done*/); // ... // cntl.ReadProgressiveAttachmentBy(new MyProgressiveReader); // after RPC // ... diff --git a/src/brpc/protocol.cpp b/src/brpc/protocol.cpp index 9bb1fde315..298f3fcfa2 100644 --- a/src/brpc/protocol.cpp +++ b/src/brpc/protocol.cpp @@ -101,13 +101,13 @@ const Protocol* FindProtocol(ProtocolType type) { const size_t index = type; if (index >= MAX_PROTOCOL_SIZE) { LOG(ERROR) << "ProtocolType=" << type << " is out of range"; - return NULL; + return nullptr; } ProtocolEntry* const protocol_map = get_protocol_map(); if (protocol_map[index].valid.load(butil::memory_order_acquire)) { return &protocol_map[index].protocol; } - return NULL; + return nullptr; } void ListProtocols(std::vector* vec) { @@ -193,7 +193,7 @@ const char* ProtocolTypeToString(ProtocolType type) { GlobalInitializeOrDie(); const Protocol* p = FindProtocol(type); - if (p != NULL) { + if (p != nullptr) { return p->name; } return "unknown"; diff --git a/src/brpc/protocol.h b/src/brpc/protocol.h index 0492d0b5f7..1d6612b978 100644 --- a/src/brpc/protocol.h +++ b/src/brpc/protocol.h @@ -107,7 +107,7 @@ struct Protocol { // [Required by client] // The callback to pack `request_buf' into `iobuf_out' or `user_message_out' // Called before sending each request (including retries). - // Remember to pack authentication information when `auth' is not NULL. + // Remember to pack authentication information when `auth' is not nullptr. // Call cntl->SetFailed() on error. typedef void (*PackRequest)( butil::IOBuf* iobuf_out, @@ -139,7 +139,7 @@ struct Protocol { // [Required by authenticating server] // The callback to verify authentication of this socket. Only called - // on the first message that a socket receives. Can be NULL when + // on the first message that a socket receives. Can be nullptr when // authentication is not needed or this is the client side. // Returns true on successful authentication. typedef bool (*Verify)(const InputMessageBase* msg); @@ -187,7 +187,7 @@ int RegisterProtocol(ProtocolType type, const Protocol& protocol); // [thread-safe] // Find the protocol registered with key=`type'. -// Returns NULL on not found. +// Returns nullptr on not found. const Protocol* FindProtocol(ProtocolType type); // [thread-safe] diff --git a/src/brpc/rdma_transport.cpp b/src/brpc/rdma_transport.cpp index b172e47f34..ee5151c3a5 100644 --- a/src/brpc/rdma_transport.cpp +++ b/src/brpc/rdma_transport.cpp @@ -31,15 +31,9 @@ DECLARE_bool(usercode_in_pthread); extern SocketVarsCollector *g_vars; void RdmaTransport::Init(Socket *socket, const SocketOptions &options) { - CHECK(_rdma_ep == NULL); + CHECK(_rdma_ep == nullptr); if (options.socket_mode == SOCKET_MODE_RDMA) { - _rdma_ep = new(std::nothrow)rdma::RdmaEndpoint(socket); - if (!_rdma_ep) { - const int saved_errno = errno; - PLOG(ERROR) << "Fail to create RdmaEndpoint"; - socket->SetFailed( - saved_errno, "Fail to create RdmaEndpoint: %s", berror(saved_errno)); - } + _rdma_ep = new rdma::RdmaEndpoint(socket); _rdma_state = RDMA_UNKNOWN; } else { _rdma_state = RDMA_OFF; @@ -48,7 +42,7 @@ void RdmaTransport::Init(Socket *socket, const SocketOptions &options) { _socket = socket; _default_connect = options.app_connect; _on_edge_trigger = options.on_edge_triggered_events; - if (options.need_on_edge_trigger && _on_edge_trigger == NULL) { + if (options.need_on_edge_trigger && _on_edge_trigger == nullptr) { // Server-side RDMA sockets drive the handshake through the standard // InputMessenger path (ParseRdmaHandshake), so they use OnNewMessages // just like TCP sockets. Only client-side sockets, whose handshake @@ -67,7 +61,7 @@ void RdmaTransport::Init(Socket *socket, const SocketOptions &options) { void RdmaTransport::Release() { if (_rdma_ep) { delete _rdma_ep; - _rdma_ep = NULL; + _rdma_ep = nullptr; _rdma_state = RDMA_UNKNOWN; } } @@ -112,7 +106,7 @@ int RdmaTransport::WaitEpollOut(butil::atomic *_epollout_butex, bool pollin, const timespec duetime) { if (_rdma_state == RDMA_ON) { const int expected_val = _epollout_butex->load(butil::memory_order_acquire); - CHECK(_rdma_ep != NULL); + CHECK(_rdma_ep != nullptr); if (!_rdma_ep->IsWritable()) { g_vars->nwaitepollout << 1; if (bthread::butex_wait(_epollout_butex, expected_val, &duetime) < 0) { diff --git a/src/brpc/rdma_transport.h b/src/brpc/rdma_transport.h index 0ac8a25324..1d78fbb430 100644 --- a/src/brpc/rdma_transport.h +++ b/src/brpc/rdma_transport.h @@ -42,7 +42,7 @@ friend class rdma::RdmaHandshakeServerV3; void QueueMessage(InputMessageClosure& inputMsg, int* num_bthread_created, bool last_msg) override; void Debug(std::ostream &os) override; rdma::RdmaEndpoint* GetRdmaEp() { - CHECK(_rdma_ep != NULL); + CHECK(_rdma_ep != nullptr); return _rdma_ep; } static int ContextInitOrDie(bool serverOrNot, const void* _options); @@ -57,7 +57,7 @@ friend class rdma::RdmaHandshakeServerV3; RDMA_UNKNOWN }; // The RdmaEndpoint - rdma::RdmaEndpoint* _rdma_ep = NULL; + rdma::RdmaEndpoint* _rdma_ep = nullptr; // Should use RDMA or not RdmaState _rdma_state; std::shared_ptr _tcp_transport; diff --git a/src/brpc/redis.cpp b/src/brpc/redis.cpp index b9c5363f3e..d4a2108b16 100644 --- a/src/brpc/redis.cpp +++ b/src/brpc/redis.cpp @@ -207,7 +207,7 @@ RedisResponse::RedisResponse(const RedisResponse& from) } void RedisResponse::SharedCtor() { - _other_replies = NULL; + _other_replies = nullptr; _cached_size_ = 0; _nreply = 0; } @@ -225,7 +225,7 @@ void RedisResponse::SetCachedSize(int size) const { void RedisResponse::Clear() { _first_reply.Reset(); - _other_replies = NULL; + _other_replies = nullptr; _arena.clear(); _nreply = 0; _cached_size_ = 0; @@ -303,10 +303,10 @@ ParseError RedisResponse::ConsumePartialIOBuf(butil::IOBuf& buf, int reply_count ++_nreply; } if (reply_count > 1) { - if (_other_replies == NULL) { + if (_other_replies == nullptr) { _other_replies = (RedisReply*)_arena.allocate( sizeof(RedisReply) * (reply_count - 1)); - if (_other_replies == NULL) { + if (_other_replies == nullptr) { LOG(ERROR) << "Fail to allocate RedisReply[" << reply_count -1 << "]"; return PARSE_ERROR_ABSOLUTELY_WRONG; } @@ -362,12 +362,12 @@ RedisCommandHandler* RedisService::FindCommandHandler(const butil::StringPiece& if (it != _command_map.end()) { return it->second; } - return NULL; + return nullptr; } RedisCommandHandler* RedisCommandHandler::NewTransactionHandler() { LOG(ERROR) << "NewTransactionHandler is not implemented"; - return NULL; + return nullptr; } // ========== impl of RedisConnContext ========== diff --git a/src/brpc/redis.h b/src/brpc/redis.h index c140baf34b..6a57715ddc 100644 --- a/src/brpc/redis.h +++ b/src/brpc/redis.h @@ -40,7 +40,7 @@ namespace brpc { // RedisRequest request; // request.AddCommand("PING"); // RedisResponse response; -// channel.CallMethod(&controller, &request, &response, NULL/*done*/); +// channel.CallMethod(&controller, &request, &response, nullptr/*done*/); // if (!cntl.Failed()) { // LOG(INFO) << response.reply(0); // } @@ -152,7 +152,7 @@ class RedisResponse : public NonreflectableMessage { if (index < reply_size()) { return (index == 0 ? _first_reply : _other_replies[index - 1]); } - static RedisReply redis_nil(NULL); + static RedisReply redis_nil(nullptr); return redis_nil; } diff --git a/src/brpc/redis_cluster.cpp b/src/brpc/redis_cluster.cpp index f2531c95ac..c2c1ed6bb1 100644 --- a/src/brpc/redis_cluster.cpp +++ b/src/brpc/redis_cluster.cpp @@ -175,7 +175,7 @@ RedisClusterChannel::RedisClusterChannel() RedisClusterChannel::~RedisClusterChannel() { _stop_refresh.store(true); if (_refresh_started) { - bthread_join(_refresh_tid, NULL); + bthread_join(_refresh_tid, nullptr); } } @@ -205,7 +205,7 @@ int RedisClusterChannel::Init(const std::string& seed_nodes, } for (size_t i = 0; i < seeds.size(); ++i) { - if (GetOrCreateChannel(seeds[i]) == NULL) { + if (GetOrCreateChannel(seeds[i]) == nullptr) { LOG(WARNING) << "Fail to init seed channel=" << seeds[i]; } } @@ -217,7 +217,7 @@ int RedisClusterChannel::Init(const std::string& seed_nodes, if (_options.enable_periodic_refresh && _options.refresh_interval_s > 0) { _stop_refresh.store(false); - if (bthread_start_background(&_refresh_tid, NULL, + if (bthread_start_background(&_refresh_tid, nullptr, RedisClusterChannel::RunPeriodicRefresh, this) == 0) { _refresh_started = true; @@ -235,7 +235,7 @@ void RedisClusterChannel::CallMethod( google::protobuf::Message* response_base, google::protobuf::Closure* done) { Controller* cntl = static_cast(controller_base); - if (cntl == NULL) { + if (cntl == nullptr) { LOG(ERROR) << "controller is NULL"; if (done) { done->Run(); @@ -243,7 +243,7 @@ void RedisClusterChannel::CallMethod( return; } - if (request_base == NULL || + if (request_base == nullptr || request_base->GetDescriptor() != RedisRequest::descriptor()) { cntl->SetFailed(EREQUEST, "request must be RedisRequest"); if (done) { @@ -251,7 +251,7 @@ void RedisClusterChannel::CallMethod( } return; } - if (response_base == NULL || + if (response_base == nullptr || response_base->GetDescriptor() != RedisResponse::descriptor()) { cntl->SetFailed(ERESPONSE, "response must be RedisResponse"); if (done) { @@ -263,17 +263,12 @@ void RedisClusterChannel::CallMethod( const RedisRequest* request = static_cast(request_base); RedisResponse* response = static_cast(response_base); - if (done == NULL) { + if (done == nullptr) { CallMethodImpl(cntl, *request, response); return; } - AsyncCall* ac = new (std::nothrow) AsyncCall; - if (ac == NULL) { - cntl->SetFailed(ENOMEM, "Fail to allocate async context"); - done->Run(); - return; - } + AsyncCall* ac = new AsyncCall; ac->self = this; ac->cntl = cntl; ac->request = request; @@ -281,7 +276,7 @@ void RedisClusterChannel::CallMethod( ac->done = done; bthread_t tid; - if (bthread_start_background(&tid, NULL, RedisClusterChannel::RunAsyncCall, ac) != 0) { + if (bthread_start_background(&tid, nullptr, RedisClusterChannel::RunAsyncCall, ac) != 0) { delete ac; CallMethodImpl(cntl, *request, response); done->Run(); @@ -380,7 +375,7 @@ bool RedisClusterChannel::ExecuteCommand(const ParsedCommand& cmd, } SingleCommandResult result; - if (!ExecuteSingleCommand(cmd.args, NULL, &result, cntl)) { + if (!ExecuteSingleCommand(cmd.args, nullptr, &result, cntl)) { return false; } encoded_reply->swap(result.encoded_reply); @@ -398,7 +393,7 @@ bool RedisClusterChannel::ExecuteSingleCommand(const std::vector& a std::string endpoint; int key_slot = -1; - if (forced_endpoint != NULL) { + if (forced_endpoint != nullptr) { endpoint = *forced_endpoint; } else if (!IsNoKeyCommand(args[0]) && args.size() >= 2) { if (!PickEndpointForKey(args[1], &endpoint, &key_slot)) { @@ -478,7 +473,7 @@ bool RedisClusterChannel::ExecuteMGet(const ParsedCommand& cmd, sub_args.push_back("get"); sub_args.push_back(cmd.args[i]); SingleCommandResult sub_result; - if (!ExecuteSingleCommand(sub_args, NULL, &sub_result, cntl)) { + if (!ExecuteSingleCommand(sub_args, nullptr, &sub_result, cntl)) { return false; } values.push_back(sub_result.encoded_reply); @@ -507,7 +502,7 @@ bool RedisClusterChannel::ExecuteMSet(const ParsedCommand& cmd, sub_args.push_back(cmd.args[i + 1]); SingleCommandResult sub_result; - if (!ExecuteSingleCommand(sub_args, NULL, &sub_result, cntl)) { + if (!ExecuteSingleCommand(sub_args, nullptr, &sub_result, cntl)) { return false; } if (sub_result.is_error || !sub_result.is_status_ok) { @@ -536,7 +531,7 @@ bool RedisClusterChannel::ExecuteIntegerAggregate(const ParsedCommand& cmd, sub_args.push_back(cmd.args[i]); SingleCommandResult sub_result; - if (!ExecuteSingleCommand(sub_args, NULL, &sub_result, cntl)) { + if (!ExecuteSingleCommand(sub_args, nullptr, &sub_result, cntl)) { return false; } if (sub_result.is_error) { @@ -596,7 +591,7 @@ bool RedisClusterChannel::ExecuteEvalLike(const ParsedCommand& cmd, SingleCommandResult result; if (!ExecuteSingleCommand(cmd.args, - numkeys > 0 ? &forced_endpoint : NULL, + numkeys > 0 ? &forced_endpoint : nullptr, &result, cntl)) { return false; @@ -622,7 +617,7 @@ bool RedisClusterChannel::PickEndpointForKey(const std::string& key, return false; } *endpoint = mapped; - if (slot != NULL) { + if (slot != nullptr) { *slot = key_slot; } return true; @@ -655,7 +650,7 @@ bool RedisClusterChannel::SendToEndpoint(const std::string& endpoint, redirect->endpoint.clear(); Channel* channel = GetOrCreateChannel(endpoint); - if (channel == NULL) { + if (channel == nullptr) { cntl->SetFailed(EHOSTDOWN, "Fail to get channel for %s", endpoint.c_str()); return false; } @@ -687,7 +682,7 @@ bool RedisClusterChannel::SendToEndpoint(const std::string& endpoint, if (cntl->timeout_ms() > 0) { sub_cntl.set_timeout_ms(cntl->timeout_ms()); } - channel->CallMethod(NULL, &sub_cntl, &request, &response, NULL); + channel->CallMethod(nullptr, &sub_cntl, &request, &response, nullptr); if (sub_cntl.Failed()) { cntl->SetFailed(sub_cntl.ErrorCode(), "Redis cluster sub-request to %s failed: %s", @@ -750,7 +745,7 @@ bool RedisClusterChannel::RefreshTopology() { bool RedisClusterChannel::RefreshTopologyFromEndpoint(const std::string& endpoint) { Channel* channel = GetOrCreateChannel(endpoint); - if (channel == NULL) { + if (channel == nullptr) { return false; } @@ -784,7 +779,7 @@ bool RedisClusterChannel::FetchAndParseClusterSlots( RedisResponse response; Controller cntl; cntl.set_timeout_ms(_options.topology_refresh_timeout_ms); - channel->CallMethod(NULL, &cntl, &request, &response, NULL); + channel->CallMethod(nullptr, &cntl, &request, &response, nullptr); if (cntl.Failed()) { return false; } @@ -854,7 +849,7 @@ bool RedisClusterChannel::FetchAndParseClusterNodes( RedisResponse response; Controller cntl; cntl.set_timeout_ms(_options.topology_refresh_timeout_ms); - channel->CallMethod(NULL, &cntl, &request, &response, NULL); + channel->CallMethod(nullptr, &cntl, &request, &response, nullptr); if (cntl.Failed()) { return false; } @@ -978,14 +973,11 @@ Channel* RedisClusterChannel::GetOrCreateChannel(const std::string& endpoint) { } } - std::unique_ptr new_channel(new (std::nothrow) Channel); - if (!new_channel) { - return NULL; - } + std::unique_ptr new_channel(new Channel); ChannelOptions options = _options.channel_options; options.protocol = brpc::PROTOCOL_REDIS; if (new_channel->Init(endpoint.c_str(), &options) != 0) { - return NULL; + return nullptr; } BAIDU_SCOPED_LOCK(_mutex); @@ -1156,7 +1148,7 @@ bool RedisClusterChannel::ParseInt(const std::string& s, int64_t* out) { if (s.empty()) { return false; } - char* end = NULL; + char* end = nullptr; errno = 0; const long long value = strtoll(s.c_str(), &end, 10); if (errno != 0 || end != s.c_str() + s.size()) { @@ -1187,14 +1179,14 @@ void* RedisClusterChannel::RunPeriodicRefresh(void* arg) { } self->RefreshTopology(); } - return NULL; + return nullptr; } void* RedisClusterChannel::RunAsyncCall(void* arg) { std::unique_ptr ac(static_cast(arg)); ac->self->CallMethodImpl(ac->cntl, *ac->request, ac->response); ac->done->Run(); - return NULL; + return nullptr; } int RedisClusterChannel::CheckHealth() { diff --git a/src/brpc/redis_cluster.h b/src/brpc/redis_cluster.h index 1250a8e386..d8b99701a9 100644 --- a/src/brpc/redis_cluster.h +++ b/src/brpc/redis_cluster.h @@ -54,7 +54,7 @@ class RedisClusterChannel : public ChannelBase { DISALLOW_COPY_AND_ASSIGN(RedisClusterChannel); int Init(const std::string& seed_nodes, - const RedisClusterChannelOptions* options = NULL); + const RedisClusterChannelOptions* options = nullptr); void CallMethod(const google::protobuf::MethodDescriptor* method, google::protobuf::RpcController* controller, diff --git a/src/brpc/redis_command.cpp b/src/brpc/redis_command.cpp index ccc646145e..a833cb54a0 100644 --- a/src/brpc/redis_command.cpp +++ b/src/brpc/redis_command.cpp @@ -100,7 +100,7 @@ static void FlushComponent(std::string* out, std::string* compbuf, int* ncomp) { // compatibility with hiredis. butil::Status RedisCommandFormatV(butil::IOBuf* outbuf, const char* fmt, va_list ap) { - if (outbuf == NULL || fmt == NULL) { + if (outbuf == nullptr || fmt == nullptr) { return butil::Status(EINVAL, "Param[outbuf] or [fmt] is NULL"); } const size_t fmt_len = strlen(fmt); @@ -181,7 +181,7 @@ RedisCommandFormatV(butil::IOBuf* outbuf, const char* fmt, va_list ap) { va_list _cpy; /* Flags */ - while (*_p != '\0' && strchr(flags,*_p) != NULL) _p++; + while (*_p != '\0' && strchr(flags,*_p) != nullptr) _p++; /* Field width */ while (*_p != '\0' && isdigit(*_p)) _p++; @@ -196,13 +196,13 @@ RedisCommandFormatV(butil::IOBuf* outbuf, const char* fmt, va_list ap) { va_copy(_cpy, ap); /* Integer conversion (without modifiers) */ - if (strchr(intfmts,*_p) != NULL) { + if (strchr(intfmts,*_p) != nullptr) { va_arg(ap,int); goto fmt_valid; } /* Double conversion (without modifiers) */ - if (strchr("eEfFgGaA",*_p) != NULL) { + if (strchr("eEfFgGaA",*_p) != nullptr) { va_arg(ap,double); goto fmt_valid; } @@ -210,7 +210,7 @@ RedisCommandFormatV(butil::IOBuf* outbuf, const char* fmt, va_list ap) { /* Size: char */ if (_p[0] == 'h' && _p[1] == 'h') { _p += 2; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { + if (*_p != '\0' && strchr(intfmts,*_p) != nullptr) { va_arg(ap,int); /* char gets promoted to int */ goto fmt_valid; } @@ -220,7 +220,7 @@ RedisCommandFormatV(butil::IOBuf* outbuf, const char* fmt, va_list ap) { /* Size: short */ if (_p[0] == 'h') { _p += 1; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { + if (*_p != '\0' && strchr(intfmts,*_p) != nullptr) { va_arg(ap,int); /* short gets promoted to int */ goto fmt_valid; } @@ -230,7 +230,7 @@ RedisCommandFormatV(butil::IOBuf* outbuf, const char* fmt, va_list ap) { /* Size: long long */ if (_p[0] == 'l' && _p[1] == 'l') { _p += 2; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { + if (*_p != '\0' && strchr(intfmts,*_p) != nullptr) { va_arg(ap,long long); goto fmt_valid; } @@ -240,7 +240,7 @@ RedisCommandFormatV(butil::IOBuf* outbuf, const char* fmt, va_list ap) { /* Size: long */ if (_p[0] == 'l') { _p += 1; - if (*_p != '\0' && strchr(intfmts,*_p) != NULL) { + if (*_p != '\0' && strchr(intfmts,*_p) != nullptr) { va_arg(ap,long); goto fmt_valid; } @@ -305,7 +305,7 @@ butil::Status RedisCommandFormat(butil::IOBuf* buf, const char* fmt, ...) { butil::Status RedisCommandNoFormat(butil::IOBuf* outbuf, const butil::StringPiece& cmd) { - if (outbuf == NULL || cmd == NULL) { + if (outbuf == nullptr || cmd == nullptr) { return butil::Status(EINVAL, "Param[outbuf] or [cmd] is NULL"); } const size_t cmd_len = cmd.size(); @@ -370,7 +370,7 @@ RedisCommandNoFormat(butil::IOBuf* outbuf, const butil::StringPiece& cmd) { butil::Status RedisCommandByComponents(butil::IOBuf* output, const butil::StringPiece* components, size_t ncomponents) { - if (output == NULL) { + if (output == nullptr) { return butil::Status(EINVAL, "Param[output] is NULL"); } AppendHeader(*output, '*', ncomponents); @@ -415,7 +415,7 @@ RedisCommandConsumeState RedisCommandParser::ConsumeImpl(butil::IOBuf& buf, butil::Arena* arena, ParseError* err) { const auto pfc = static_cast(buf.fetch1()); - if (pfc == NULL) { + if (pfc == nullptr) { *err = PARSE_ERROR_NOT_ENOUGH_DATA; return CONSUME_STATE_ERROR; } @@ -472,8 +472,8 @@ RedisCommandConsumeState RedisCommandParser::ConsumeImpl(butil::IOBuf& buf, } const size_t buf_size = crlf_pos; const auto copy_str = static_cast(arena->allocate(buf_size + 1)); - // arena->allocate() may return NULL on allocation failure - if (copy_str == NULL) { + // arena->allocate() may return nullptr on allocation failure + if (copy_str == nullptr) { LOG(FATAL) << "Arena failed allocation"; *err = PARSE_ERROR_ABSOLUTELY_WRONG; return CONSUME_STATE_ERROR; @@ -536,7 +536,7 @@ RedisCommandConsumeState RedisCommandParser::ConsumeImpl(butil::IOBuf& buf, *err = PARSE_ERROR_NOT_ENOUGH_DATA; return CONSUME_STATE_ERROR; } - char* endptr = NULL; + char* endptr = nullptr; int64_t value = strtoll(intbuf + 1/*skip fc*/, &endptr, 10); if (endptr != intbuf + crlf_pos) { LOG(ERROR) << '`' << intbuf + 1 << "' is not a valid 64-bit decimal"; @@ -592,7 +592,7 @@ RedisCommandConsumeState RedisCommandParser::ConsumeImpl(butil::IOBuf& buf, buf.pop_front(crlf_pos + 2/*CRLF*/); char* d = (char*)arena->allocate((len/8 + 1) * 8); // Guard against allocation failure - if (d == NULL) { + if (d == nullptr) { LOG(FATAL) << "Arena failed allocation"; *err = PARSE_ERROR_ABSOLUTELY_WRONG; return CONSUME_STATE_ERROR; diff --git a/src/brpc/redis_reply.cpp b/src/brpc/redis_reply.cpp index 14c76f4841..e36f56747b 100644 --- a/src/brpc/redis_reply.cpp +++ b/src/brpc/redis_reply.cpp @@ -123,7 +123,7 @@ ParseError RedisReply::ConsumePartialIOBuf(butil::IOBuf& buf, int depth) { // Notice that all branches returning PARSE_ERROR_NOT_ENOUGH_DATA must not change `buf'. const char* pfc = (const char*)buf.fetch1(); - if (pfc == NULL) { + if (pfc == nullptr) { return PARSE_ERROR_NOT_ENOUGH_DATA; } const char fc = *pfc; // first character @@ -149,7 +149,7 @@ ParseError RedisReply::ConsumePartialIOBuf(butil::IOBuf& buf, int depth) { return PARSE_OK; } char* d = (char*)_arena->allocate((len/8 + 1)*8); - if (d == NULL) { + if (d == nullptr) { LOG(FATAL) << "Fail to allocate string[" << len << "]"; return PARSE_ERROR_ABSOLUTELY_WRONG; } @@ -169,7 +169,7 @@ ParseError RedisReply::ConsumePartialIOBuf(butil::IOBuf& buf, int depth) { if (crlf_pos == butil::StringPiece::npos) { // not enough data return PARSE_ERROR_NOT_ENOUGH_DATA; } - char* endptr = NULL; + char* endptr = nullptr; int64_t value = strtoll(intbuf + 1/*skip fc*/, &endptr, 10); if (endptr != intbuf + crlf_pos) { LOG(ERROR) << '`' << intbuf + 1 << "' is not a valid 64-bit decimal"; @@ -209,7 +209,7 @@ ParseError RedisReply::ConsumePartialIOBuf(butil::IOBuf& buf, int depth) { _data.short_str[len] = '\0'; } else { char* d = (char*)_arena->allocate((len/8 + 1)*8); - if (d == NULL) { + if (d == nullptr) { LOG(FATAL) << "Fail to allocate string[" << len << "]"; return PARSE_ERROR_ABSOLUTELY_WRONG; } @@ -241,7 +241,7 @@ ParseError RedisReply::ConsumePartialIOBuf(butil::IOBuf& buf, int depth) { _type = REDIS_REPLY_ARRAY; _length = 0; _data.array.last_index = -1; - _data.array.replies = NULL; + _data.array.replies = nullptr; return PARSE_OK; } int64_t max_count = FLAGS_redis_max_allocation_size / sizeof(RedisReply); @@ -252,7 +252,7 @@ ParseError RedisReply::ConsumePartialIOBuf(butil::IOBuf& buf, int depth) { } // FIXME(gejun): Call allocate_aligned instead. RedisReply* subs = (RedisReply*)_arena->allocate(sizeof(RedisReply) * count); - if (subs == NULL) { + if (subs == nullptr) { LOG(FATAL) << "Fail to allocate RedisReply[" << count << "]"; return PARSE_ERROR_ABSOLUTELY_WRONG; } @@ -378,7 +378,7 @@ void RedisReply::CopyFromDifferentArena(const RedisReply& other) { switch (_type) { case REDIS_REPLY_ARRAY: { RedisReply* subs = (RedisReply*)_arena->allocate(sizeof(RedisReply) * _length); - if (subs == NULL) { + if (subs == nullptr) { LOG(FATAL) << "Fail to allocate RedisReply[" << _length << "]"; return; } @@ -413,7 +413,7 @@ void RedisReply::CopyFromDifferentArena(const RedisReply& other) { memcpy(_data.short_str, other._data.short_str, _length + 1); } else { char* d = (char*)_arena->allocate((_length/8 + 1)*8); - if (d == NULL) { + if (d == nullptr) { LOG(FATAL) << "Fail to allocate string[" << _length << "]"; return; } diff --git a/src/brpc/redis_reply.h b/src/brpc/redis_reply.h index 13114be11a..4efb5b7195 100644 --- a/src/brpc/redis_reply.h +++ b/src/brpc/redis_reply.h @@ -176,7 +176,7 @@ inline void RedisReply::Reset() { _type = REDIS_REPLY_NIL; _length = 0; _data.array.last_index = -1; - _data.array.replies = NULL; + _data.array.replies = nullptr; // _arena should not be reset because further memory allocation needs it. } @@ -310,7 +310,7 @@ inline const RedisReply& RedisReply::operator[](size_t index) const { if (is_array() && index < (size_t)_length) { return _data.array.replies[index]; } - static RedisReply redis_nil(NULL); + static RedisReply redis_nil(nullptr); return redis_nil; } diff --git a/src/brpc/restful.cpp b/src/brpc/restful.cpp index 36b31e9dd7..c22c824879 100644 --- a/src/brpc/restful.cpp +++ b/src/brpc/restful.cpp @@ -195,7 +195,7 @@ bool ParseRestfulPath(butil::StringPiece path, bool ParseRestfulMappings(const butil::StringPiece& mappings, std::vector* list) { - if (list == NULL) { + if (list == nullptr) { LOG(ERROR) << "Param[list] is NULL"; return false; } @@ -262,13 +262,13 @@ bool RestfulMap::AddMethod(const RestfulMethodPath& path, const Server::MethodProperty::OpaqueParams& params, const std::string& method_name, MethodStatus* status) { - if (service == NULL) { + if (service == nullptr) { LOG(ERROR) << "Param[service] is NULL"; return false; } const google::protobuf::MethodDescriptor* md = service->GetDescriptor()->FindMethodByName(method_name); - if (md == NULL) { + if (md == nullptr) { LOG(ERROR) << service->GetDescriptor()->full_name() << " has no method called `" << method_name << '\''; return false; @@ -405,14 +405,14 @@ RestfulMap::FindMethodProperty(const butil::StringPiece& method_path, std::string* unresolved_path) const { if (_sorted_paths.empty()) { LOG(ERROR) << "_sorted_paths is empty, method_path=" << method_path; - return NULL; + return nullptr; } const std::string full_path = NormalizeSlashes(method_path); butil::StringPiece sub_path = full_path; PathList::const_iterator last_find_pos = _sorted_paths.end(); do { if (last_find_pos == _sorted_paths.begin()) { - return NULL; + return nullptr; } // Note: stop trying places that we already visited or skipped. PathList::const_iterator it = @@ -475,7 +475,7 @@ RestfulMap::FindMethodProperty(const butil::StringPiece& method_path, << "Hit beginning, sub_path=" << sub_path << " full_path=" << full_path << " candidate=" << DebugPrinter(rpath); - return NULL; + return nullptr; } // Matched with prefix but postfix or wildcard, moving forward --it; @@ -500,7 +500,7 @@ RestfulMap::FindMethodProperty(const butil::StringPiece& method_path, } while (RemoveLastComponent(&sub_path)); // ^^^^^^^^ // sub_path can be / to match patterns like "*.flv => M" whose prefix is / - return NULL; + return nullptr; } } // namespace brpc diff --git a/src/brpc/restful.h b/src/brpc/restful.h index ceab4918d4..d0e85c1ab5 100644 --- a/src/brpc/restful.h +++ b/src/brpc/restful.h @@ -69,7 +69,7 @@ class RestfulMap { virtual ~RestfulMap(); // Map `path' to the method denoted by `method_name' in `service'. - // Returns MethodStatus of the method on success, NULL otherwise. + // Returns MethodStatus of the method on success, nullptr otherwise. bool AddMethod(const RestfulMethodPath& path, google::protobuf::Service* service, const Server::MethodProperty::OpaqueParams& params, diff --git a/src/brpc/retry_policy.cpp b/src/brpc/retry_policy.cpp index 3120b3c854..6f0e0750d5 100644 --- a/src/brpc/retry_policy.cpp +++ b/src/brpc/retry_policy.cpp @@ -45,7 +45,7 @@ bool RpcRetryPolicy::DoRetry(const Controller* controller) const { // NOTE(gejun): g_default_policy can't be deleted on process's exit because // client-side may still retry and use the policy at exit static pthread_once_t g_default_policy_once = PTHREAD_ONCE_INIT; -static RpcRetryPolicy* g_default_policy = NULL; +static RpcRetryPolicy* g_default_policy = nullptr; static void init_default_policy() { g_default_policy = new RpcRetryPolicy; } diff --git a/src/brpc/rpc_dump.cpp b/src/brpc/rpc_dump.cpp index 4686713cd2..a9dca57ca9 100644 --- a/src/brpc/rpc_dump.cpp +++ b/src/brpc/rpc_dump.cpp @@ -116,7 +116,7 @@ class RpcDumpContext { }; bvar::CollectorSpeedLimit g_rpc_dump_sl = BVAR_COLLECTOR_SPEED_LIMIT_INITIALIZER; -static RpcDumpContext* g_rpc_dump_ctx = NULL; +static RpcDumpContext* g_rpc_dump_ctx = nullptr; void SampledRequest::dump_and_destroy(size_t round) { static bvar::DisplaySamplingRatio sampling_ratio_var( @@ -124,7 +124,7 @@ void SampledRequest::dump_and_destroy(size_t round) { // Safe to modify g_rpc_dump_ctx w/o locking. RpcDumpContext* rpc_dump_ctx = g_rpc_dump_ctx; - if (rpc_dump_ctx == NULL) { + if (rpc_dump_ctx == nullptr) { rpc_dump_ctx = new RpcDumpContext; g_rpc_dump_ctx = rpc_dump_ctx; } @@ -259,7 +259,7 @@ bool RpcDumpContext::Serialize(butil::IOBuf& buf, SampledRequest* sample) { SampleIterator::SampleIterator(const butil::StringPiece& dir) : _cur_fd(-1) - , _enum(NULL) + , _enum(nullptr) , _dir(std::string(dir.data(), dir.size())) { } @@ -269,7 +269,7 @@ SampleIterator::~SampleIterator() { _cur_fd = -1; } delete _enum; - _enum = NULL; + _enum = nullptr; } SampledRequest* SampleIterator::Next() { @@ -307,13 +307,13 @@ SampledRequest* SampleIterator::Next() { _cur_fd = -1; } - if (_enum == NULL) { + if (_enum == nullptr) { _enum = new butil::FileEnumerator( _dir, false, butil::FileEnumerator::FILES); } butil::FilePath filename = _enum->Next(); if (filename.empty()) { - return NULL; + return nullptr; } _cur_fd = open(filename.value().c_str(), O_RDONLY); } @@ -322,13 +322,13 @@ SampledRequest* SampleIterator::Next() { SampledRequest* SampleIterator::Pop(butil::IOBuf& buf, bool* format_error) { char backing_buf[12]; const char* p = (const char*)buf.fetch(backing_buf, sizeof(backing_buf)); - if (NULL == p) { // buf.length() < sizeof(backing_buf) - return NULL; + if (nullptr == p) { // buf.length() < sizeof(backing_buf) + return nullptr; } if (*(const uint32_t*)p != *(const uint32_t*)"PRPC") { LOG(ERROR) << "Unmatched magic string"; *format_error = true; - return NULL; + return nullptr; } uint32_t body_size; uint32_t meta_size; @@ -336,15 +336,15 @@ SampledRequest* SampleIterator::Pop(butil::IOBuf& buf, bool* format_error) { if (body_size > FLAGS_max_body_size) { LOG(ERROR) << "Too big body=" << body_size; *format_error = true; - return NULL; + return nullptr; } else if (buf.length() < sizeof(backing_buf) + body_size) { - return NULL; + return nullptr; } if (meta_size > body_size) { LOG(ERROR) << "meta_size=" << meta_size << " is bigger than body_size=" << body_size; *format_error = true; - return NULL; + return nullptr; } buf.pop_front(sizeof(backing_buf)); butil::IOBuf meta_buf; @@ -353,7 +353,7 @@ SampledRequest* SampleIterator::Pop(butil::IOBuf& buf, bool* format_error) { if (!ParsePbFromIOBuf(&req->meta, meta_buf)) { LOG(ERROR) << "Fail to parse RpcDumpMeta"; *format_error = true; - return NULL; + return nullptr; } buf.cutn(&req->request, body_size - meta_size); return req.release(); diff --git a/src/brpc/rpc_dump.h b/src/brpc/rpc_dump.h index 09bb6f14be..ae101512f7 100644 --- a/src/brpc/rpc_dump.h +++ b/src/brpc/rpc_dump.h @@ -61,21 +61,21 @@ class SampledRequest : public bvar::Collected { } }; -// If this function returns non-NULL, the caller must fill the returned +// If this function returns non-nullptr, the caller must fill the returned // object and submit it for later dumping by calling SubmitSample(). If -// the caller ignores non-NULL return value, the object is leaked. +// the caller ignores non-nullptr return value, the object is leaked. inline SampledRequest* AskToBeSampled() { extern bvar::CollectorSpeedLimit g_rpc_dump_sl; if (!FLAGS_rpc_dump || !bvar::is_collectable(&g_rpc_dump_sl)) { - return NULL; + return nullptr; } - return new (std::nothrow) SampledRequest; + return new SampledRequest; } // Read samples from dumped files in a directory. // Example: // SampleIterator it("./rpc_dump_echo_server"); -// for (SampledRequest* req = it->Next(); req != NULL; req = it->Next()) { +// for (SampledRequest* req = it->Next(); req != nullptr; req = it->Next()) { // ... // } class SampleIterator { @@ -85,7 +85,7 @@ class SampleIterator { // Read a sample. Order of samples are not guaranteed to be same with // the order that they're stored in dumped files. - // Returns the sample which should be deleted by caller. NULL means + // Returns the sample which should be deleted by caller. nullptr means // all dumped files are read. SampledRequest* Next(); diff --git a/src/brpc/rpc_pb_message_factory.cpp b/src/brpc/rpc_pb_message_factory.cpp index 27e2457e05..caed04dda7 100644 --- a/src/brpc/rpc_pb_message_factory.cpp +++ b/src/brpc/rpc_pb_message_factory.cpp @@ -20,7 +20,7 @@ namespace brpc { struct DefaultRpcPBMessages : public RpcPBMessages { - DefaultRpcPBMessages() : request(NULL), response(NULL) {} + DefaultRpcPBMessages() : request(nullptr), response(nullptr) {} ::google::protobuf::Message* Request() override { return request; } ::google::protobuf::Message* Response() override { return response; } @@ -42,8 +42,8 @@ void DefaultRpcPBMessageFactory::Return(RpcPBMessages* messages) { auto default_messages = static_cast(messages); delete default_messages->request; delete default_messages->response; - default_messages->request = NULL; - default_messages->response = NULL; + default_messages->request = nullptr; + default_messages->response = nullptr; butil::return_object(default_messages); } diff --git a/src/brpc/rpc_pb_message_factory.h b/src/brpc/rpc_pb_message_factory.h index 20d27a0fcb..7e3c865f6e 100644 --- a/src/brpc/rpc_pb_message_factory.h +++ b/src/brpc/rpc_pb_message_factory.h @@ -79,8 +79,8 @@ struct ArenaRpcPBMessages : public RpcPBMessages { explicit ArenaRpcPBMessages(ArenaOptionsWrapper options_wrapper) : arena(options_wrapper.options) - , request(NULL) - , response(NULL) {} + , request(nullptr) + , response(nullptr) {} ::google::protobuf::Message* Request() override { return request; } ::google::protobuf::Message* Response() override { return response; } @@ -111,8 +111,8 @@ class ArenaRpcPBMessageFactory : public RpcPBMessageFactory { void Return(RpcPBMessages* messages) override { auto arena_messages = static_cast(messages); - arena_messages->request = NULL; - arena_messages->response = NULL; + arena_messages->request = nullptr; + arena_messages->response = nullptr; arena_messages->arena.Reset(); butil::return_object(arena_messages); } diff --git a/src/brpc/rtmp.cpp b/src/brpc/rtmp.cpp index 31681239f4..b897aed759 100644 --- a/src/brpc/rtmp.cpp +++ b/src/brpc/rtmp.cpp @@ -191,7 +191,7 @@ butil::Status FlvReader::ReadHeader() { // { 'F', 'L', 'V', 0x01, 0x05, 0, 0, 0, 0x09 }. char header_buf[9 + 4/* PreviousTagSize0 */]; const char* p = (const char*)_buf->fetch(header_buf, sizeof(header_buf)); - if (p == NULL) { + if (p == nullptr) { return butil::Status(EAGAIN, "Fail to read, not enough data"); } const char flv_header_signature[3] = { 'F', 'L', 'V' }; @@ -211,7 +211,7 @@ butil::Status FlvReader::PeekMessageType(FlvTagType* type_out) { return st; } const char* p = (const char*)_buf->fetch1(); - if (p == NULL) { + if (p == nullptr) { return butil::Status(EAGAIN, "Fail to read, not enough data"); } FlvTagType type = (FlvTagType)*p; @@ -228,7 +228,7 @@ butil::Status FlvReader::PeekMessageType(FlvTagType* type_out) { butil::Status FlvReader::Read(RtmpVideoMessage* msg) { char tags[11]; const unsigned char* p = (const unsigned char*)_buf->fetch(tags, sizeof(tags)); - if (p == NULL) { + if (p == nullptr) { return butil::Status(EAGAIN, "Fail to read, not enough data"); } if (*p != FLV_TAG_VIDEO) { @@ -262,7 +262,7 @@ butil::Status FlvReader::Read(RtmpVideoMessage* msg) { butil::Status FlvReader::Read(RtmpAudioMessage* msg) { char tags[11]; const unsigned char* p = (const unsigned char*)_buf->fetch(tags, sizeof(tags)); - if (p == NULL) { + if (p == nullptr) { return butil::Status(EAGAIN, "Fail to read, not enough data"); } if (*p != FLV_TAG_AUDIO) { @@ -297,7 +297,7 @@ butil::Status FlvReader::Read(RtmpAudioMessage* msg) { butil::Status FlvReader::Read(RtmpMetaData* msg, std::string* name) { char tags[11]; const unsigned char* p = (const unsigned char*)_buf->fetch(tags, sizeof(tags)); - if (p == NULL) { + if (p == nullptr) { return butil::Status(EAGAIN, "Fail to read, not enough data"); } if (*p != FLV_TAG_SCRIPT_DATA) { @@ -430,7 +430,7 @@ butil::Status RtmpAACMessage::Create(const RtmpAudioMessage& msg) { FlvAudioCodec2Str(msg.codec)); } const uint8_t* p = (const uint8_t*)msg.data.fetch1(); - if (p == NULL) { + if (p == nullptr) { return butil::Status(EINVAL, "Not enough data in AudioMessage"); } if (*p > FLV_AAC_PACKET_RAW) { @@ -481,7 +481,7 @@ bool RtmpAudioMessage::IsAACSequenceHeader() const { return false; } const uint8_t* p = (const uint8_t*)data.fetch1(); - if (p == NULL) { + if (p == nullptr) { return false; } return *p == FLV_AAC_PACKET_SEQUENCE_HEADER; @@ -494,7 +494,7 @@ butil::Status RtmpAVCMessage::Create(const RtmpVideoMessage& msg) { } uint8_t buf[4]; const uint8_t* p = (const uint8_t*)msg.data.fetch(buf, sizeof(buf)); - if (p == NULL) { + if (p == nullptr) { return butil::Status(EINVAL, "Not enough data in VideoMessage"); } if (*p > FLV_AVC_PACKET_END_OF_SEQUENCE) { @@ -513,7 +513,7 @@ bool RtmpVideoMessage::IsAVCSequenceHeader() const { return false; } const uint8_t* p = (const uint8_t*)data.fetch1(); - if (p == NULL) { + if (p == nullptr) { return false; } return *p == FLV_AVC_PACKET_SEQUENCE_HEADER; @@ -524,7 +524,7 @@ bool RtmpVideoMessage::IsHEVCSequenceHeader() const { return false; } const uint8_t* p = (const uint8_t*)data.fetch1(); - if (p == NULL) { + if (p == nullptr) { return false; } return *p == FLV_AVC_PACKET_SEQUENCE_HEADER; @@ -828,7 +828,7 @@ butil::Status AVCDecoderConfigurationRecord::ParseSPS( static bool find_avc_annexb_nalu_start_code(const butil::IOBuf& buf, size_t* start_code_length) { size_t consecutive_zero_count = 0; - for (butil::IOBufBytesIterator it(buf); it != NULL; ++it) { + for (butil::IOBufBytesIterator it(buf); it != nullptr; ++it) { char c = *it; if (c == 0) { ++consecutive_zero_count; @@ -852,7 +852,7 @@ static void find_avc_annexb_nalu_stop_code(const butil::IOBuf& buf, size_t* stop_code_length) { size_t nalu_length = 0; size_t consecutive_zero_count = 0; - for (butil::IOBufBytesIterator it(buf); it != NULL; ++it) { + for (butil::IOBufBytesIterator it(buf); it != nullptr; ++it) { unsigned char c = (unsigned char)*it; if (c > 1) { // most frequent ++nalu_length; @@ -1052,7 +1052,7 @@ void RtmpConnect::StartConnect( RPC_VLOG << "Establish rtmp-level connection on " << *s; policy::RtmpContext* ctx = static_cast(s->parsing_context()); - if (ctx == NULL) { + if (ctx == nullptr) { LOG(FATAL) << "RtmpContext of " << *s << " is NULL"; return done(EINVAL, data); } @@ -1086,7 +1086,7 @@ void RtmpConnect::StartConnect( void RtmpConnect::StopConnect(Socket* s) { policy::RtmpContext* ctx = static_cast(s->parsing_context()); - if (ctx == NULL) { + if (ctx == nullptr) { LOG(FATAL) << "RtmpContext of " << *s << " is NULL"; } else { ctx->OnConnected(EFAILEDSOCKET); @@ -1102,7 +1102,7 @@ class RtmpSocketCreator : public SocketCreator { int CreateSocket(const SocketOptions& opt, SocketId* id) override { SocketOptions sock_opt = opt; sock_opt.app_connect = std::make_shared(); - sock_opt.initial_parsing_context = new policy::RtmpContext(&_connect_options, NULL); + sock_opt.initial_parsing_context = new policy::RtmpContext(&_connect_options, nullptr); return get_client_side_messenger()->Create(sock_opt, id); } @@ -1114,7 +1114,7 @@ int RtmpClientImpl::CreateSocket(const butil::EndPoint& pt, SocketId* id) { SocketOptions sock_opt; sock_opt.remote_side = pt; sock_opt.app_connect = std::make_shared(); - sock_opt.initial_parsing_context = new policy::RtmpContext(&_connect_options, NULL); + sock_opt.initial_parsing_context = new policy::RtmpContext(&_connect_options, nullptr); return get_client_side_messenger()->Create(sock_opt, id); } @@ -1195,11 +1195,7 @@ const RtmpClientOptions& RtmpClient::options() const { int RtmpClient::Init(butil::EndPoint server_addr_and_port, const RtmpClientOptions& options) { - butil::intrusive_ptr tmp(new (std::nothrow) RtmpClientImpl); - if (tmp == NULL) { - LOG(FATAL) << "Fail to new RtmpClientImpl"; - return -1; - } + butil::intrusive_ptr tmp(new RtmpClientImpl); if (tmp->Init(server_addr_and_port, options) != 0) { return -1; } @@ -1209,11 +1205,7 @@ int RtmpClient::Init(butil::EndPoint server_addr_and_port, int RtmpClient::Init(const char* server_addr_and_port, const RtmpClientOptions& options) { - butil::intrusive_ptr tmp(new (std::nothrow) RtmpClientImpl); - if (tmp == NULL) { - LOG(FATAL) << "Fail to new RtmpClientImpl"; - return -1; - } + butil::intrusive_ptr tmp(new RtmpClientImpl); if (tmp->Init(server_addr_and_port, options) != 0) { return -1; } @@ -1223,11 +1215,7 @@ int RtmpClient::Init(const char* server_addr_and_port, int RtmpClient::Init(const char* server_addr, int port, const RtmpClientOptions& options) { - butil::intrusive_ptr tmp(new (std::nothrow) RtmpClientImpl); - if (tmp == NULL) { - LOG(FATAL) << "Fail to new RtmpClientImpl"; - return -1; - } + butil::intrusive_ptr tmp(new RtmpClientImpl); if (tmp->Init(server_addr, port, options) != 0) { return -1; } @@ -1238,11 +1226,7 @@ int RtmpClient::Init(const char* server_addr, int port, int RtmpClient::Init(const char* naming_service_url, const char* load_balancer_name, const RtmpClientOptions& options) { - butil::intrusive_ptr tmp(new (std::nothrow) RtmpClientImpl); - if (tmp == NULL) { - LOG(FATAL) << "Fail to new RtmpClientImpl"; - return -1; - } + butil::intrusive_ptr tmp(new RtmpClientImpl); if (tmp->Init(naming_service_url, load_balancer_name, options) != 0) { return -1; } @@ -1250,7 +1234,7 @@ int RtmpClient::Init(const char* naming_service_url, return 0; } -bool RtmpClient::initialized() const { return _impl != NULL; } +bool RtmpClient::initialized() const { return _impl != nullptr; } RtmpStreamBase::RtmpStreamBase(bool is_client) : _is_client(is_client) @@ -1274,7 +1258,7 @@ void RtmpStreamBase::Destroy() { int RtmpStreamBase::SendMessage(uint32_t timestamp, uint8_t message_type, const butil::IOBuf& body) { - if (_rtmpsock == NULL) { + if (_rtmpsock == nullptr) { errno = EPERM; return -1; } @@ -1295,7 +1279,7 @@ int RtmpStreamBase::SendMessage(uint32_t timestamp, int RtmpStreamBase::SendControlMessage( uint8_t message_type, const void* body, size_t size) { - if (_rtmpsock == NULL) { + if (_rtmpsock == nullptr) { errno = EPERM; return -1; } @@ -1342,7 +1326,7 @@ int RtmpStreamBase::SendSharedObjectMessage(const RtmpSharedObjectMessage&) { } int RtmpStreamBase::SendAudioMessage(const RtmpAudioMessage& msg) { - if (_rtmpsock == NULL) { + if (_rtmpsock == nullptr) { errno = EPERM; return -1; } @@ -1373,7 +1357,7 @@ int RtmpStreamBase::SendAudioMessage(const RtmpAudioMessage& msg) { } int RtmpStreamBase::SendAACMessage(const RtmpAACMessage& msg) { - if (_rtmpsock == NULL) { + if (_rtmpsock == nullptr) { errno = EPERM; return -1; } @@ -1410,7 +1394,7 @@ int RtmpStreamBase::SendUserMessage(void*) { } int RtmpStreamBase::SendVideoMessage(const RtmpVideoMessage& msg) { - if (_rtmpsock == NULL) { + if (_rtmpsock == nullptr) { errno = EPERM; return -1; } @@ -1443,7 +1427,7 @@ int RtmpStreamBase::SendVideoMessage(const RtmpVideoMessage& msg) { } int RtmpStreamBase::SendAVCMessage(const RtmpAVCMessage& msg) { - if (_rtmpsock == NULL) { + if (_rtmpsock == nullptr) { errno = EPERM; return -1; } @@ -1708,20 +1692,20 @@ StreamUserData* RtmpClientStream::OnCreatingStream( std::unique_lock mu(_state_mutex); if (_state == STATE_ERROR || _state == STATE_DESTROYING) { cntl->SetFailed(EINVAL, "Fail to replace socket for stream, _state is error or destroying"); - return NULL; + return nullptr; } } SocketId esid; if (cntl->connection_type() == CONNECTION_TYPE_SHORT) { if (_client_impl->CreateSocket((*inout)->remote_side(), &esid) != 0) { cntl->SetFailed(EINVAL, "Fail to create RTMP socket"); - return NULL; + return nullptr; } } else { if (_client_impl->socket_map().Insert( SocketMapKey((*inout)->remote_side()), &esid) != 0) { cntl->SetFailed(EINVAL, "Fail to get the RTMP socket"); - return NULL; + return nullptr; } } SocketUniquePtr tmp_ptr; @@ -1729,7 +1713,7 @@ StreamUserData* RtmpClientStream::OnCreatingStream( cntl->SetFailed(EFAILEDSOCKET, "Fail to address RTMP SocketId=%" PRIu64 " from SocketMap of RtmpClient=%p", esid, _client_impl.get()); - return NULL; + return nullptr; } RPC_VLOG << "Replace Socket For Stream, RTMP socketId=" << esid << ", main socketId=" << (*inout)->id(); @@ -1796,8 +1780,8 @@ void RtmpClientStream::DestroyStreamUserData(SocketUniquePtr& sending_sock, void RtmpClientStream::DestroyStreamCreator(Controller* cntl) { if (cntl->Failed()) { - if (_rtmpsock != NULL && - // ^ If sending_sock is NULL, the RPC fails before _pack_request + if (_rtmpsock != nullptr && + // ^ If sending_sock is nullptr, the RPC fails before _pack_request // which calls AddTransaction, in another word, RemoveTransaction // is not needed. cntl->ErrorCode() != ERTMPCREATESTREAM) { @@ -1807,7 +1791,7 @@ void RtmpClientStream::DestroyStreamCreator(Controller* cntl) { const uint32_t transaction_id = cntl->log_id(); policy::RtmpContext* rtmp_ctx = static_cast(_rtmpsock->parsing_context()); - if (rtmp_ctx == NULL) { + if (rtmp_ctx == nullptr) { LOG(FATAL) << "RtmpContext must be created"; } else { policy::RtmpTransactionHandler* handler = @@ -1856,7 +1840,7 @@ void RtmpClientStream::DestroyStreamCreator(Controller* cntl) { } void RtmpClientStream::OnStopInternal() { - if (_rtmpsock == NULL) { + if (_rtmpsock == nullptr) { return CallOnStop(); } @@ -1907,7 +1891,7 @@ void RtmpClientStream::OnStopInternal() { } policy::RtmpContext* ctx = static_cast(_rtmpsock->parsing_context()); - if (ctx != NULL) { + if (ctx != nullptr) { if (!ctx->RemoveMessageStream(this)) { // The stream is not registered yet. Is this normal? LOG(ERROR) << "Fail to remove stream_id=" << _message_stream_id; @@ -1931,7 +1915,7 @@ RtmpPlayOptions::RtmpPlayOptions() } int RtmpClientStream::Play(const RtmpPlayOptions& opt) { - if (_rtmpsock == NULL) { + if (_rtmpsock == nullptr) { errno = EPERM; return -1; } @@ -1940,7 +1924,7 @@ int RtmpClientStream::Play(const RtmpPlayOptions& opt) { errno = EINVAL; return -1; } - if (_client_impl == NULL) { + if (_client_impl == nullptr) { LOG(ERROR) << "The client stream is not created yet"; errno = EPERM; return -1; @@ -2145,7 +2129,7 @@ void OnClientStreamCreated::Run() { void RtmpClientStream::Init(const RtmpClient* client, const RtmpClientStreamOptions& options) { - if (client->_impl == NULL) { + if (client->_impl == nullptr) { LOG(FATAL) << "RtmpClient is not initialized"; return OnStopInternal(); } @@ -2195,14 +2179,14 @@ void RtmpClientStream::Init(const RtmpClient* client, return done->CancelBeforeCallMethod(); } } - _client_impl->_chan.CallMethod(NULL, &done->cntl, NULL, res, done); + _client_impl->_chan.CallMethod(nullptr, &done->cntl, nullptr, res, done); if (options.wait_until_play_or_publish_is_sent) { Join(call_id); } } std::string RtmpClientStream::rtmp_url() const { - if (_client_impl == NULL) { + if (_client_impl == nullptr) { return std::string(); } butil::StringPiece tcurl = _client_impl->options().tcUrl; @@ -2235,14 +2219,14 @@ RtmpRetryingClientStream::RtmpRetryingClientStream() , _last_creation_time_us(0) , _last_retry_start_time_us(0) , _create_timer_id(0) - , _sub_stream_creator(NULL) { + , _sub_stream_creator(nullptr) { get_rtmp_bvars()->retrying_client_stream_count << 1; _self_ref.reset(this); } RtmpRetryingClientStream::~RtmpRetryingClientStream() { delete _sub_stream_creator; - _sub_stream_creator = NULL; + _sub_stream_creator = nullptr; get_rtmp_bvars()->retrying_client_stream_count << -1; } @@ -2262,7 +2246,7 @@ void RtmpRetryingClientStream::Destroy() { } // Make sure _self_ref is released before quiting this function. - // Notice that _self_ref.reset(NULL) is wrong because it may destructs + // Notice that _self_ref.reset(nullptr) is wrong because it may destructs // this object immediately. butil::intrusive_ptr self_ref; _self_ref.swap(self_ref); @@ -2270,7 +2254,7 @@ void RtmpRetryingClientStream::Destroy() { butil::intrusive_ptr old_sub_stream; { BAIDU_SCOPED_LOCK(_stream_mutex); - // swap instead of reset(NULL) to make the stream destructed + // swap instead of reset(nullptr) to make the stream destructed // outside _stream_mutex. _using_sub_stream.swap(old_sub_stream); } @@ -2291,7 +2275,7 @@ void RtmpRetryingClientStream::Destroy() { void RtmpRetryingClientStream::Init( SubStreamCreator* sub_stream_creator, const RtmpRetryingClientStreamOptions& options) { - if (sub_stream_creator == NULL) { + if (sub_stream_creator == nullptr) { LOG(ERROR) << "sub_stream_creator is NULL"; return CallOnStopIfNeeded(); } @@ -2395,7 +2379,7 @@ void RtmpRetryingClientStream::OnSubStreamStop(RtmpStreamBase* sub_stream) { _using_sub_stream.swap(removed_sub_stream); } } - if (removed_sub_stream == NULL || + if (removed_sub_stream == nullptr || _destroying.load(butil::memory_order_relaxed) || _called_on_stop.load(butil::memory_order_relaxed)) { return; @@ -2635,7 +2619,7 @@ int RtmpServerStream::OnPause(bool pause, double offset_ms) { void RtmpServerStream::OnSetBufferLength(uint32_t /*buffer_length_ms*/) {} int RtmpServerStream::SendStopMessage(const butil::StringPiece& error_desc) { - if (_rtmpsock == NULL) { + if (_rtmpsock == nullptr) { errno = EINVAL; return -1; } @@ -2715,12 +2699,12 @@ int RtmpServerStream::RunOnFailed(bthread_id_t id, void* data, int) { } void RtmpServerStream::OnStopInternal() { - if (_rtmpsock == NULL) { + if (_rtmpsock == nullptr) { return CallOnStop(); } policy::RtmpContext* ctx = static_cast(_rtmpsock->parsing_context()); - if (ctx == NULL) { + if (ctx == nullptr) { LOG(FATAL) << _rtmpsock->remote_side() << ": RtmpContext of " << *_rtmpsock << " is NULL"; return CallOnStop(); @@ -2859,7 +2843,7 @@ void ParseRtmpURL(const butil::StringPiece& rtmp_url_in, return SplitVHostFromApp(rtmp_url, app, vhost); } SplitVHostFromApp(rtmp_url.substr(0, slash2_pos), app, vhost); - if (stream_name != NULL) { + if (stream_name != nullptr) { // Remove duplicated slashes. for (++slash2_pos; slash2_pos < rtmp_url.size() && rtmp_url[slash2_pos] == '/'; ++slash2_pos); diff --git a/src/brpc/rtmp.h b/src/brpc/rtmp.h index eb1b41805d..986d7539db 100644 --- a/src/brpc/rtmp.h +++ b/src/brpc/rtmp.h @@ -351,7 +351,7 @@ class AVCNaluIterator { DISALLOW_COPY_AND_ASSIGN(AVCNaluIterator); bool next_as_annexb(); bool next_as_ibmf(); - void set_end() { _data = NULL; } + void set_end() { _data = nullptr; } butil::IOBuf* _data; butil::IOBuf _cur_nalu; AVCNaluFormat* _format; @@ -568,9 +568,9 @@ class RtmpStreamBase : public SharedObject virtual int SendStopMessage(const butil::StringPiece& error_description); // // Call user's procedure at server-side. - // // request == NULL : send AMF null as the parameter. - // // response == NULL : response is not needed. - // // done == NULL : synchronous call, asynchronous otherwise. + // // request == nullptr : send AMF null as the parameter. + // // response == nullptr : response is not needed. + // // done == nullptr : synchronous call, asynchronous otherwise. // void Call(Controller* cntl, // const butil::StringPiece& procedure_name, // const google::protobuf::Message* request, diff --git a/src/brpc/selective_channel.cpp b/src/brpc/selective_channel.cpp index 287b0a1600..c53ac13b33 100644 --- a/src/brpc/selective_channel.cpp +++ b/src/brpc/selective_channel.cpp @@ -104,7 +104,7 @@ class SubDone; class Sender; struct Resource { - Resource() : response(NULL), sub_done(NULL) {} + Resource() : response(nullptr), sub_done(nullptr) {} google::protobuf::Message* response; SubDone* sub_done; @@ -177,7 +177,7 @@ int ChannelBalancer::Init(const char* lb_name) { int ChannelBalancer::AddChannel(ChannelBase* sub_channel, const SelectiveChannel::SubChannelOptions& subopt, SelectiveChannel::ChannelHandle* handle) { - if (NULL == sub_channel) { + if (nullptr == sub_channel) { LOG(ERROR) << "Parameter[sub_channel] is NULL"; return -1; } @@ -186,11 +186,7 @@ int ChannelBalancer::AddChannel(ChannelBase* sub_channel, LOG(ERROR) << "Duplicated sub_channel=" << sub_channel; return -1; } - SubChannel* sub_chan = new (std::nothrow) SubChannel; - if (sub_chan == NULL) { - LOG(FATAL) << "Fail to to new SubChannel"; - return -1; - } + SubChannel* sub_chan = new SubChannel; sub_chan->chan = sub_channel; sub_chan->ownership = subopt.ownership; SocketId sock_id; @@ -312,7 +308,7 @@ int Sender::IssueRPC(int64_t start_realtime_us) { _main_cntl->_current_call.need_feedback = false; ChannelBalancer* balancer = static_cast(_lb.get()); - if (balancer == NULL) { + if (balancer == nullptr) { _main_cntl->SetFailed(ECANCELED, "SelectiveChannel balancer is unavailable"); return -1; @@ -332,7 +328,7 @@ int Sender::IssueRPC(int64_t start_realtime_us) { _main_cntl->_current_call.peer_id = sel_out.fake_sock->id(); Resource r = PopFree(); - if (r.sub_done == NULL) { + if (r.sub_done == nullptr) { CHECK(false) << "Impossible!"; _main_cntl->SetFailed("Impossible happens"); return -1; @@ -365,7 +361,7 @@ int Sender::IssueRPC(int64_t start_realtime_us) { } void SubDone::Run() { - Controller* main_cntl = NULL; + Controller* main_cntl = nullptr; const int rc = bthread_id_lock(_cid, (void**)&main_cntl); if (rc != 0) { // _cid must be valid because schan does not dtor before cancelling @@ -426,7 +422,7 @@ void Sender::Run() { } void Sender::Clear() { - if (_main_cntl == NULL) { + if (_main_cntl == nullptr) { return; } for (int i = 0; i < _nalloc; ++i) { @@ -437,8 +433,8 @@ void Sender::Clear() { _alloc_resources[i] = Resource(); } const CallId cid = _main_cntl->call_id(); - _main_cntl = NULL; - _lb.reset(NULL); + _main_cntl = nullptr; + _lb.reset(nullptr); if (_user_done) { _user_done->Run(); } @@ -468,7 +464,7 @@ inline Resource Sender::PopFree() { r.response->Clear(); Controller& sub_cntl = r.sub_done->_cntl; ExcludedServers* saved_accessed = sub_cntl._accessed; - sub_cntl._accessed = NULL; + sub_cntl._accessed = nullptr; sub_cntl.Reset(); sub_cntl._accessed = saved_accessed; return r; @@ -491,7 +487,7 @@ inline bool Sender::PushFree(const Resource& r) { inline const Controller* Sender::SubController(int index) const { if (index != 0) { - return NULL; + return nullptr; } for (int i = 0; i < _nfree; ++i) { if (!_free_resources[i].sub_done->_cntl.Failed()) { @@ -501,7 +497,7 @@ inline const Controller* Sender::SubController(int index) const { if (_nfree != 0) { return &_free_resources[_nfree - 1].sub_done->_cntl; } - return NULL; + return nullptr; } } // namespace schan @@ -526,11 +522,7 @@ int SelectiveChannel::Init(const char* lb_name, const ChannelOptions* options) { LOG(ERROR) << "Already initialized"; return -1; } - schan::ChannelBalancer* lb = new (std::nothrow) schan::ChannelBalancer; - if (NULL == lb) { - LOG(FATAL) << "Fail to new ChannelBalancer"; - return -1; - } + schan::ChannelBalancer* lb = new schan::ChannelBalancer; if (lb->Init(lb_name) != 0) { LOG(ERROR) << "Fail to init lb"; delete lb; @@ -543,14 +535,14 @@ int SelectiveChannel::Init(const char* lb_name, const ChannelOptions* options) { // Modify some fields to be consistent with behavior of schan. _chan._options.connection_type = CONNECTION_TYPE_UNKNOWN; _chan._options.succeed_without_server = true; - _chan._options.auth = NULL; + _chan._options.auth = nullptr; } _chan._options.protocol = PROTOCOL_UNKNOWN; return 0; } bool SelectiveChannel::initialized() const { - return _chan._lb != NULL; + return _chan._lb != nullptr; } int SelectiveChannel::AddChannel(ChannelBase* sub_channel, @@ -558,7 +550,7 @@ int SelectiveChannel::AddChannel(ChannelBase* sub_channel, ChannelHandle* handle) { schan::ChannelBalancer* lb = static_cast(_chan._lb.get()); - if (lb == NULL) { + if (lb == nullptr) { LOG(ERROR) << "You must call Init() to initialize a SelectiveChannel"; return -1; } @@ -568,7 +560,7 @@ int SelectiveChannel::AddChannel(ChannelBase* sub_channel, void SelectiveChannel::RemoveAndDestroyChannel(const ChannelHandle& handle) { schan::ChannelBalancer* lb = static_cast(_chan._lb.get()); - if (lb == NULL) { + if (lb == nullptr) { LOG(ERROR) << "You must call Init() to initialize a SelectiveChannel"; return; } @@ -598,7 +590,7 @@ void SelectiveChannel::CallMethod( cntl->add_flag(Controller::FLAGS_DESTROY_CID_IN_DONE); const CallId cid = cntl->call_id(); _chan.CallMethod(method, cntl, request, response, sndr); - if (user_done == NULL) { + if (user_done == nullptr) { Join(cid); cntl->OnRPCEnd(butil::gettimeofday_us()); } @@ -616,7 +608,7 @@ int SelectiveChannel::CheckHealth() { void SelectiveChannel::Describe( std::ostream& os, const DescribeOptions& options) const { os << "SelectiveChannel["; - if (_chan._lb != NULL) { + if (_chan._lb != nullptr) { _chan._lb->Describe(os, options); } else { os << "uninitialized"; diff --git a/src/brpc/selective_channel.h b/src/brpc/selective_channel.h index fd8fb9cf9d..a728ac5edf 100644 --- a/src/brpc/selective_channel.h +++ b/src/brpc/selective_channel.h @@ -66,7 +66,7 @@ class SelectiveChannel : public ChannelBase/*non-copyable*/ { // You MUST initialize a schan before using it. `load_balancer_name' is the // name of load balancing algorithm which is listed in brpc/channel.h - // if `options' is NULL, use default options. + // if `options' is nullptr, use default options. int Init(const char* load_balancer_name, const ChannelOptions* options); // Add a sub channel, which will be deleted along with schan or explicitly diff --git a/src/brpc/server.cpp b/src/brpc/server.cpp index 230c228416..0852cfc105 100644 --- a/src/brpc/server.cpp +++ b/src/brpc/server.cpp @@ -128,33 +128,33 @@ const int s_ncore = sysconf(_SC_NPROCESSORS_ONLN); ServerOptions::ServerOptions() : idle_timeout_sec(-1) - , nshead_service(NULL) - , thrift_service(NULL) - , mongo_service_adaptor(NULL) - , auth(NULL) + , nshead_service(nullptr) + , thrift_service(nullptr) + , mongo_service_adaptor(nullptr) + , auth(nullptr) , server_owns_auth(false) - , interceptor(NULL) + , interceptor(nullptr) , server_owns_interceptor(false) , num_threads(8) , max_concurrency(0) - , session_local_data_factory(NULL) + , session_local_data_factory(nullptr) , reserved_session_local_data(0) - , thread_local_data_factory(NULL) + , thread_local_data_factory(nullptr) , reserved_thread_local_data(0) - , bthread_init_fn(NULL) - , bthread_init_args(NULL) + , bthread_init_fn(nullptr) + , bthread_init_args(nullptr) , bthread_init_count(0) , internal_port(-1) , has_builtin_services(true) , force_ssl(false) , socket_mode(SOCKET_MODE_TCP) - , baidu_master_service(NULL) - , http_master_service(NULL) - , health_reporter(NULL) - , rtmp_service(NULL) - , redis_service(NULL) + , baidu_master_service(nullptr) + , http_master_service(nullptr) + , health_reporter(nullptr) + , rtmp_service(nullptr) + , redis_service(nullptr) , bthread_tag(BTHREAD_TAG_DEFAULT) - , rpc_pb_message_factory(NULL) + , rpc_pb_message_factory(nullptr) , ignore_eovercrowded(false) { if (s_ncore > 0) { num_threads = s_ncore + 1; @@ -179,10 +179,10 @@ Server::MethodProperty::OpaqueParams::OpaqueParams() Server::MethodProperty::MethodProperty() : is_builtin_service(false) , own_method_status(false) - , http_url(NULL) - , service(NULL) - , method(NULL) - , status(NULL) + , http_url(nullptr) + , service(nullptr) + , method(nullptr) + , status(nullptr) , ignore_eovercrowded(false) { } @@ -256,22 +256,22 @@ static void PrintEnabledProfilers(std::ostream& os, void*) { } static bvar::PassiveStatus s_lb_st( - "rpc_load_balancer", PrintSupportedLB, NULL); + "rpc_load_balancer", PrintSupportedLB, nullptr); static bvar::PassiveStatus s_ns_st( - "rpc_naming_service", PrintSupportedNS, NULL); + "rpc_naming_service", PrintSupportedNS, nullptr); static bvar::PassiveStatus s_proto_st( - "rpc_protocols", PrintSupportedProtocols, NULL); + "rpc_protocols", PrintSupportedProtocols, nullptr); static bvar::PassiveStatus s_comp_st( - "rpc_compressions", PrintSupportedCompressions, NULL); + "rpc_compressions", PrintSupportedCompressions, nullptr); static bvar::PassiveStatus s_cksum_st( - "rpc_checksums", PrintSupportedChecksums, NULL); + "rpc_checksums", PrintSupportedChecksums, nullptr); static bvar::PassiveStatus s_prof_st( - "rpc_profilers", PrintEnabledProfilers, NULL); + "rpc_profilers", PrintEnabledProfilers, nullptr); static int32_t GetConnectionCount(void* arg) { ServerStatistics ss; @@ -385,7 +385,7 @@ void* Server::UpdateDerivedVars(void* arg) { consecutive_nosleep = 0; if (bthread_usleep(sleep_us) < 0) { PLOG_IF(ERROR, errno != ESTOP) << "Fail to sleep"; - return NULL; + return nullptr; } } last_time = butil::cpuwide_time_us(); @@ -424,20 +424,20 @@ const std::string Server::ServiceProperty::service_name() const { } Server::Server(ProfilerLinker) - : _session_local_data_pool(NULL) + : _session_local_data_pool(nullptr) , _status(UNINITIALIZED) , _builtin_service_count(0) , _virtual_service_count(0) , _failed_to_set_max_concurrency_of_method(false) , _failed_to_set_ignore_eovercrowded(false) - , _am(NULL) - , _internal_am(NULL) - , _first_service(NULL) - , _tab_info_list(NULL) - , _global_restful_map(NULL) + , _am(nullptr) + , _internal_am(nullptr) + , _first_service(nullptr) + , _tab_info_list(nullptr) + , _global_restful_map(nullptr) , _last_start_time(0) , _derivative_thread(INVALID_BTHREAD) - , _keytable_pool(NULL) + , _keytable_pool(nullptr) , _eps_bvar(&_nerror_bvar) , _concurrency(0) , _concurrency_bvar(cast_no_barrier_int, &_concurrency) @@ -452,50 +452,50 @@ Server::~Server() { ClearServices(); FreeSSLContexts(); delete _session_local_data_pool; - _session_local_data_pool = NULL; + _session_local_data_pool = nullptr; delete _options.nshead_service; - _options.nshead_service = NULL; + _options.nshead_service = nullptr; #ifdef ENABLE_THRIFT_FRAMED_PROTOCOL delete _options.thrift_service; - _options.thrift_service = NULL; + _options.thrift_service = nullptr; #endif delete _options.baidu_master_service; - _options.baidu_master_service = NULL; + _options.baidu_master_service = nullptr; delete _options.http_master_service; - _options.http_master_service = NULL; + _options.http_master_service = nullptr; delete _options.rpc_pb_message_factory; - _options.rpc_pb_message_factory = NULL; + _options.rpc_pb_message_factory = nullptr; delete _am; - _am = NULL; + _am = nullptr; delete _internal_am; - _internal_am = NULL; + _internal_am = nullptr; delete _tab_info_list; - _tab_info_list = NULL; + _tab_info_list = nullptr; delete _global_restful_map; - _global_restful_map = NULL; + _global_restful_map = nullptr; if (!_options.pid_file.empty()) { unlink(_options.pid_file.c_str()); } if (_options.server_owns_auth) { delete _options.auth; - _options.auth = NULL; + _options.auth = nullptr; } if (_options.server_owns_interceptor) { delete _options.interceptor; - _options.interceptor = NULL; + _options.interceptor = nullptr; } delete _options.redis_service; - _options.redis_service = NULL; + _options.redis_service = nullptr; } int Server::AddBuiltinServices() { @@ -626,16 +626,12 @@ Acceptor* Server::BuildAcceptor() { whitelist.insert(protocol); } const bool has_whitelist = !whitelist.empty(); - Acceptor* acceptor = new (std::nothrow) Acceptor(_keytable_pool); - if (NULL == acceptor) { - LOG(ERROR) << "Fail to new Acceptor"; - return NULL; - } + Acceptor* acceptor = new Acceptor(_keytable_pool); InputMessageHandler handler; std::vector protocols; ListProtocols(&protocols); for (size_t i = 0; i < protocols.size(); ++i) { - if (protocols[i].process_request == NULL) { + if (protocols[i].process_request == nullptr) { // The protocol does not support server-side. continue; } @@ -657,7 +653,7 @@ Acceptor* Server::BuildAcceptor() { LOG(ERROR) << "Fail to add handler into Acceptor(" << acceptor << ')'; delete acceptor; - return NULL; + return nullptr; } } if (!whitelist.empty()) { @@ -670,7 +666,7 @@ Acceptor* Server::BuildAcceptor() { err << '\''; delete acceptor; LOG(ERROR) << err.str(); - return NULL; + return nullptr; } return acceptor; } @@ -721,8 +717,8 @@ static void DestroyServerTLS(void* data, const void* void_factory) { } struct BthreadInitArgs { - bool (*bthread_init_fn)(void* args); // default: NULL (do nothing) - void* bthread_init_args; // default: NULL + bool (*bthread_init_fn)(void* args); // default: nullptr (do nothing) + void* bthread_init_args; // default: nullptr bool result; bool done; bool stop; @@ -736,12 +732,12 @@ static void* BthreadInitEntry(void* void_args) { while (!args->stop) { bthread_usleep(1000); } - return NULL; + return nullptr; } struct RevertServerStatus { inline void operator()(Server* s) const { - if (s != NULL) { + if (s != nullptr) { s->Stop(0); s->Join(); } @@ -760,17 +756,17 @@ static int get_port_from_fd(int fd) { bool Server::CreateConcurrencyLimiter(const AdaptiveMaxConcurrency& amc, ConcurrencyLimiter** out) { if (amc.type() == AdaptiveMaxConcurrency::UNLIMITED()) { - *out = NULL; + *out = nullptr; return true; } const ConcurrencyLimiter* cl = ConcurrencyLimiterExtension()->Find(amc.type().c_str()); - if (cl == NULL) { + if (cl == nullptr) { LOG(ERROR) << "Fail to find ConcurrencyLimiter by `" << amc.value() << "'"; return false; } ConcurrencyLimiter* cl_copy = cl->New(amc); - if (cl_copy == NULL) { + if (cl_copy == nullptr) { LOG(ERROR) << "Fail to new ConcurrencyLimiter"; return false; } @@ -787,7 +783,7 @@ inline void copy_and_fill_server_options(ServerOptions& dst, const ServerOptions #define FREE_PTR_IF_NOT_REUSED(ptr) \ if (dst.ptr != src.ptr) { \ delete dst.ptr; \ - dst.ptr = NULL; \ + dst.ptr = nullptr; \ } if (&dst != &src) { @@ -898,7 +894,7 @@ int Server::StartInternal(const butil::EndPoint& endpoint, _options.http_master_service->GetDescriptor(); const google::protobuf::MethodDescriptor* md = sd->FindMethodByName("default_method"); - if (md == NULL) { + if (md == nullptr) { LOG(ERROR) << "http_master_service must have a method named `default_method'"; return -1; } @@ -919,13 +915,9 @@ int Server::StartInternal(const butil::EndPoint& endpoint, // stopped more than once. Reuse or delete previous resources! if (_options.session_local_data_factory) { - if (_session_local_data_pool == NULL) { + if (_session_local_data_pool == nullptr) { _session_local_data_pool = - new (std::nothrow) SimpleDataPool(_options.session_local_data_factory); - if (NULL == _session_local_data_pool) { - LOG(ERROR) << "Fail to new SimpleDataPool"; - return -1; - } + new SimpleDataPool(_options.session_local_data_factory); } else { _session_local_data_pool->Reset(_options.session_local_data_factory); } @@ -943,7 +935,7 @@ int Server::StartInternal(const butil::EndPoint& endpoint, if (bthread_keytable_pool_init(_keytable_pool) != 0) { LOG(ERROR) << "Fail to init _keytable_pool"; delete _keytable_pool; - _keytable_pool = NULL; + _keytable_pool = nullptr; return -1; } } @@ -967,7 +959,7 @@ int Server::StartInternal(const butil::EndPoint& endpoint, } if (_options.bthread_init_count != 0 && - _options.bthread_init_fn != NULL) { + _options.bthread_init_fn != nullptr) { // Create some special bthreads to call the init functions. The // bthreads will not quit until all bthreads finish the init function. BthreadInitArgs* init_args @@ -998,7 +990,7 @@ int Server::StartInternal(const butil::EndPoint& endpoint, init_args[i].stop = true; } for (size_t i = 0; i < ncreated; ++i) { - bthread_join(init_args[i].th, NULL); + bthread_join(init_args[i].th, nullptr); } size_t num_failed_result = 0; for (size_t i = 0; i < ncreated; ++i) { @@ -1090,13 +1082,13 @@ int Server::StartInternal(const butil::EndPoint& endpoint, for (MethodMap::iterator it = _method_map.begin(); it != _method_map.end(); ++it) { if (it->second.is_builtin_service) { - it->second.status->SetConcurrencyLimiter(NULL); + it->second.status->SetConcurrencyLimiter(nullptr); } else { const AdaptiveMaxConcurrency* amc = &it->second.max_concurrency; if (amc->type() == AdaptiveMaxConcurrency::UNLIMITED()) { amc = &_options.method_max_concurrency; } - ConcurrencyLimiter* cl = NULL; + ConcurrencyLimiter* cl = nullptr; if (!CreateConcurrencyLimiter(*amc, &cl)) { LOG(ERROR) << "Fail to create ConcurrencyLimiter for method"; return -1; @@ -1153,9 +1145,9 @@ int Server::StartInternal(const butil::EndPoint& endpoint, return -1; } } - if (_am == NULL) { + if (_am == nullptr) { _am = BuildAcceptor(); - if (NULL == _am) { + if (nullptr == _am) { LOG(ERROR) << "Fail to build acceptor"; return -1; } @@ -1204,9 +1196,9 @@ int Server::StartInternal(const butil::EndPoint& endpoint, LOG(ERROR) << "Fail to listen " << internal_point << " (internal)"; return -1; } - if (NULL == _internal_am) { + if (nullptr == _internal_am) { _internal_am = BuildAcceptor(); - if (NULL == _internal_am) { + if (nullptr == _internal_am) { LOG(ERROR) << "Fail to build internal acceptor"; return -1; } @@ -1336,7 +1328,7 @@ int Server::Join() { if (_session_local_data_pool) { // We can't delete the pool right here because there's a bvar watching // this pool in _derivative_thread which does not quit yet. - _session_local_data_pool->Reset(NULL); + _session_local_data_pool->Reset(nullptr); } if (_keytable_pool) { @@ -1349,7 +1341,7 @@ int Server::Join() { // still-running bthreads (created by the server). The memory is // leaked but servers are unlikely to be started/stopped frequently, // the leak is acceptable in most scenarios. - _keytable_pool = NULL; + _keytable_pool = nullptr; } // Delete tls_key as well since we don't need it anymore. @@ -1363,7 +1355,7 @@ int Server::Join() { // between Add/RemoveService after Join() and the thread. if (_derivative_thread != INVALID_BTHREAD) { bthread_stop(_derivative_thread); - bthread_join(_derivative_thread, NULL); + bthread_join(_derivative_thread, nullptr); _derivative_thread = INVALID_BTHREAD; } @@ -1375,7 +1367,7 @@ int Server::Join() { int Server::AddServiceInternal(google::protobuf::Service* service, bool is_builtin_service, const ServiceOptions& svc_opt) { - if (NULL == service) { + if (nullptr == service) { LOG(ERROR) << "Parameter[service] is NULL!"; return -1; } @@ -1396,12 +1388,12 @@ int Server::AddServiceInternal(google::protobuf::Service* service, return -1; } - if (_fullname_service_map.seek(sd->full_name()) != NULL) { + if (_fullname_service_map.seek(sd->full_name()) != nullptr) { LOG(ERROR) << "service=" << sd->full_name() << " already exists"; return -1; } ServiceProperty* old_ss = _service_map.seek(sd->name()); - if (old_ss != NULL) { + if (old_ss != nullptr) { // names conflict. LOG(ERROR) << "Conflict service name between " << sd->full_name() << " and " @@ -1441,7 +1433,7 @@ int Server::AddServiceInternal(google::protobuf::Service* service, full_name_wo_ns.append(sd->name()); full_name_wo_ns.push_back('.'); full_name_wo_ns.append(md->name()); - if (_method_map.seek(full_name_wo_ns) == NULL) { + if (_method_map.seek(full_name_wo_ns) == nullptr) { _method_map[full_name_wo_ns] = mp2; } else { LOG(ERROR) << '`' << full_name_wo_ns << "' already exists"; @@ -1452,13 +1444,13 @@ int Server::AddServiceInternal(google::protobuf::Service* service, } const ServiceProperty ss = { - is_builtin_service, svc_opt.ownership, service, NULL }; + is_builtin_service, svc_opt.ownership, service, nullptr }; _fullname_service_map[butil::EnsureString(sd->full_name())] = ss; _service_map[butil::EnsureString(sd->name())] = ss; if (is_builtin_service) { ++_builtin_service_count; } else { - if (_first_service == NULL) { + if (_first_service == nullptr) { _first_service = service; } } @@ -1498,7 +1490,7 @@ int Server::AddServiceInternal(google::protobuf::Service* service, const std::string full_method_name = butil::EnsureString(sd->full_name()) + "." + mappings[i].method_name; MethodProperty* mp = _method_map.seek(full_method_name); - if (mp == NULL) { + if (mp == nullptr) { LOG(ERROR) << "Unknown method=`" << full_method_name << '\''; RemoveService(service); return -1; @@ -1506,7 +1498,7 @@ int Server::AddServiceInternal(google::protobuf::Service* service, const std::string& svc_name = mappings[i].path.service_name; if (svc_name.empty()) { - if (_global_restful_map == NULL) { + if (_global_restful_map == nullptr) { _global_restful_map = new RestfulMap(""); } MethodProperty::OpaqueParams params; @@ -1523,7 +1515,7 @@ int Server::AddServiceInternal(google::protobuf::Service* service, RemoveService(service); return -1; } - if (mp->http_url == NULL) { + if (mp->http_url == nullptr) { mp->http_url = new std::string(mappings[i].path.to_string()); } else { if (!mp->http_url->empty()) { @@ -1536,14 +1528,14 @@ int Server::AddServiceInternal(google::protobuf::Service* service, ServiceProperty* sp = _fullname_service_map.seek(svc_name); ServiceProperty* sp2 = _service_map.seek(svc_name); if (((!!sp) != (!!sp2)) || - (sp != NULL && sp->service != sp2->service)) { + (sp != nullptr && sp->service != sp2->service)) { LOG(ERROR) << "Impossible: _fullname_service and _service_map are" " inconsistent before inserting " << svc_name; RemoveService(service); return -1; } - RestfulMap* m = NULL; - if (sp == NULL) { + RestfulMap* m = nullptr; + if (sp == nullptr) { m = new RestfulMap(mappings[i].path.service_name); } else { m = sp->restful_map; @@ -1559,13 +1551,13 @@ int Server::AddServiceInternal(google::protobuf::Service* service, LOG(ERROR) << "Fail to map `" << mappings[i].path << "' to `" << sd->full_name() << '.' << mappings[i].method_name << '\''; - if (sp == NULL) { + if (sp == nullptr) { delete m; } RemoveService(service); return -1; } - if (mp->http_url == NULL) { + if (mp->http_url == nullptr) { mp->http_url = new std::string(mappings[i].path.to_string()); } else { if (!mp->http_url->empty()) { @@ -1573,9 +1565,9 @@ int Server::AddServiceInternal(google::protobuf::Service* service, } mp->http_url->append(mappings[i].path.to_string()); } - if (sp == NULL) { + if (sp == nullptr) { ServiceProperty ss = - { false, SERVER_DOESNT_OWN_SERVICE, NULL, m }; + { false, SERVER_DOESNT_OWN_SERVICE, nullptr, m }; _fullname_service_map[svc_name] = ss; _service_map[svc_name] = ss; ++_virtual_service_count; @@ -1584,7 +1576,7 @@ int Server::AddServiceInternal(google::protobuf::Service* service, } if (tabbed) { - if (_tab_info_list == NULL) { + if (_tab_info_list == nullptr) { _tab_info_list = new TabInfoList; } const size_t last_size = _tab_info_list->size(); @@ -1670,7 +1662,7 @@ void Server::RemoveMethodsOf(google::protobuf::Service* service) { full_name_wo_ns.append(md->name()); _method_map.erase(full_name_wo_ns); } - if (mp == NULL) { + if (mp == nullptr) { LOG(ERROR) << "Fail to find method=" << md->full_name(); continue; } @@ -1681,13 +1673,13 @@ void Server::RemoveMethodsOf(google::protobuf::Service* service) { path.trim_spaces(); butil::StringSplitter slash_sp( path.data(), path.data() + path.size(), '/'); - if (slash_sp == NULL) { + if (slash_sp == nullptr) { LOG(ERROR) << "Invalid http_url=" << *mp->http_url; break; } butil::StringPiece v_svc_name(slash_sp.field(), slash_sp.length()); const ServiceProperty* vsp = FindServicePropertyByName(v_svc_name); - if (vsp == NULL) { + if (vsp == nullptr) { if (_global_restful_map) { std::string path_str; path.CopyToString(&path_str); @@ -1717,7 +1709,7 @@ void Server::RemoveMethodsOf(google::protobuf::Service* service) { } int Server::RemoveService(google::protobuf::Service* service) { - if (NULL == service) { + if (nullptr == service) { LOG(ERROR) << "Parameter[service] is NULL"; return -1; } @@ -1730,7 +1722,7 @@ int Server::RemoveService(google::protobuf::Service* service) { const google::protobuf::ServiceDescriptor* sd = service->GetDescriptor(); ServiceProperty* ss = _fullname_service_map.seek(butil::EnsureString(sd->full_name())); - if (ss == NULL) { + if (ss == nullptr) { RPC_VLOG << "Fail to find service=" << sd->full_name(); return -1; } @@ -1747,7 +1739,7 @@ int Server::RemoveService(google::protobuf::Service* service) { --_builtin_service_count; } else { if (_first_service == service) { - _first_service = NULL; + _first_service = nullptr; } } return 0; @@ -1779,19 +1771,19 @@ void Server::ClearServices() { _method_map.clear(); _builtin_service_count = 0; _virtual_service_count = 0; - _first_service = NULL; + _first_service = nullptr; } google::protobuf::Service* Server::FindServiceByFullName( const butil::StringPiece& full_name) const { ServiceProperty* ss = _fullname_service_map.seek(full_name); - return (ss ? ss->service : NULL); + return (ss ? ss->service : nullptr); } google::protobuf::Service* Server::FindServiceByName( const butil::StringPiece& name) const { ServiceProperty* ss = _service_map.seek(name); - return (ss ? ss->service : NULL); + return (ss ? ss->service : nullptr); } void Server::GetStat(ServerStatistics* stat) const { @@ -1911,17 +1903,17 @@ void Server::RunUntilAskedToQuit() { void* thread_local_data() { const Server::ThreadLocalOptions* tl_options = static_cast(bthread_get_assigned_data()); - if (tl_options == NULL) { // not in server threads. - return NULL; + if (tl_options == nullptr) { // not in server threads. + return nullptr; } - if (BAIDU_UNLIKELY(tl_options->thread_local_data_factory == NULL)) { + if (BAIDU_UNLIKELY(tl_options->thread_local_data_factory == nullptr)) { CHECK(false) << "The protocol impl. may not set tls correctly"; - return NULL; + return nullptr; } void* data = bthread_getspecific(tl_options->tls_key); - if (data == NULL) { + if (data == nullptr) { data = tl_options->thread_local_data_factory->CreateData(); - if (data != NULL) { + if (data != nullptr) { CHECK_EQ(0, bthread_setspecific(tl_options->tls_key, data)); } } @@ -1953,16 +1945,16 @@ void Server::PrintTabsBody(std::ostream& os, } static pthread_mutex_t g_dummy_server_mutex = PTHREAD_MUTEX_INITIALIZER; -static Server* g_dummy_server = NULL; +static Server* g_dummy_server = nullptr; int StartDummyServerAt(int port, ProfilerLinker) { if (port < 0 || port >= 65536) { LOG(ERROR) << "Invalid port=" << port; return -1; } - if (g_dummy_server == NULL) { // (1) + if (g_dummy_server == nullptr) { // (1) BAIDU_SCOPED_LOCK(g_dummy_server_mutex); - if (g_dummy_server == NULL) { + if (g_dummy_server == nullptr) { Server* dummy_server = new Server; dummy_server->set_version(butil::string_printf( "DummyServerOf(%s)", GetProgramName())); @@ -1986,7 +1978,7 @@ int StartDummyServerAt(int port, ProfilerLinker) { } bool IsDummyServerRunning() { - return g_dummy_server != NULL; + return g_dummy_server != nullptr; } const Server::MethodProperty* @@ -2019,12 +2011,12 @@ const Server::MethodProperty* Server::FindMethodPropertyByNameAndIndex(const butil::StringPiece& service_name, int method_index) const { const Server::ServiceProperty* sp = FindServicePropertyByName(service_name); - if (NULL == sp) { - return NULL; + if (nullptr == sp) { + return nullptr; } const google::protobuf::ServiceDescriptor* sd = sp->service->GetDescriptor(); if (method_index < 0 || method_index >= sd->method_count()) { - return NULL; + return nullptr; } const google::protobuf::MethodDescriptor* method = sd->method(method_index); return FindMethodPropertyByFullName(method->full_name()); @@ -2047,7 +2039,7 @@ int Server::AddCertificate(const CertInfo& cert) { } std::string cert_key(cert.certificate); cert_key.append(cert.private_key); - if (_ssl_ctx_map.seek(cert_key) != NULL) { + if (_ssl_ctx_map.seek(cert_key) != nullptr) { LOG(WARNING) << cert << " already exists"; return 0; } @@ -2058,7 +2050,7 @@ int Server::AddCertificate(const CertInfo& cert) { SSL_CTX* raw_ctx = CreateServerSSLContext( cert.certificate, cert.private_key, _options.ssl_options(), &_raw_alpns, &ssl_ctx.filters); - if (raw_ctx == NULL) { + if (raw_ctx == nullptr) { return -1; } ssl_ctx.ctx->raw_ctx = raw_ctx; @@ -2079,14 +2071,14 @@ int Server::AddCertificate(const CertInfo& cert) { bool Server::AddCertMapping(CertMaps& bg, const SSLContext& ssl_ctx) { for (size_t i = 0; i < ssl_ctx.filters.size(); ++i) { const char* hostname = ssl_ctx.filters[i].c_str(); - CertMap* cmap = NULL; + CertMap* cmap = nullptr; if (strncmp(hostname, "*.", 2) == 0) { cmap = &(bg.wildcard_cert_map); hostname += 2; } else { cmap = &(bg.cert_map); } - if (cmap->seek(hostname) == NULL) { + if (cmap->seek(hostname) == nullptr) { cmap->insert(hostname, ssl_ctx.ctx); } else { LOG(WARNING) << "Duplicate certificate hostname=" << hostname; @@ -2103,7 +2095,7 @@ int Server::RemoveCertificate(const CertInfo& cert) { std::string cert_key(cert.certificate); cert_key.append(cert.private_key); SSLContext* ssl_ctx = _ssl_ctx_map.seek(cert_key); - if (ssl_ctx == NULL) { + if (ssl_ctx == nullptr) { LOG(WARNING) << cert << " doesn't exist"; return 0; } @@ -2125,7 +2117,7 @@ int Server::RemoveCertificate(const CertInfo& cert) { bool Server::RemoveCertMapping(CertMaps& bg, const SSLContext& ssl_ctx) { for (size_t i = 0; i < ssl_ctx.filters.size(); ++i) { const char* hostname = ssl_ctx.filters[i].c_str(); - CertMap* cmap = NULL; + CertMap* cmap = nullptr; if (strncmp(hostname, "*.", 2) == 0) { cmap = &(bg.wildcard_cert_map); hostname += 2; @@ -2133,7 +2125,7 @@ bool Server::RemoveCertMapping(CertMaps& bg, const SSLContext& ssl_ctx) { cmap = &(bg.cert_map); } std::shared_ptr* ctx = cmap->seek(hostname); - if (ctx != NULL && *ctx == ssl_ctx.ctx) { + if (ctx != nullptr && *ctx == ssl_ctx.ctx) { cmap->erase(hostname); } } @@ -2161,7 +2153,7 @@ int Server::ResetCertificates(const std::vector& certs) { for (size_t i = 0; i < certs.size(); ++i) { std::string cert_key(certs[i].certificate); cert_key.append(certs[i].private_key); - if (tmp_map.seek(cert_key) != NULL) { + if (tmp_map.seek(cert_key) != nullptr) { LOG(WARNING) << certs[i] << " already exists"; return 0; } @@ -2172,7 +2164,7 @@ int Server::ResetCertificates(const std::vector& certs) { ssl_ctx.ctx->raw_ctx = CreateServerSSLContext( certs[i].certificate, certs[i].private_key, _options.ssl_options(), &_raw_alpns, &ssl_ctx.filters); - if (ssl_ctx.ctx->raw_ctx == NULL) { + if (ssl_ctx.ctx->raw_ctx == nullptr) { return -1; } @@ -2200,14 +2192,14 @@ bool Server::ResetCertMappings(CertMaps& bg, const SSLContextMap& ctx_map) { const SSLContext& ssl_ctx = it->second; for (size_t i = 0; i < ssl_ctx.filters.size(); ++i) { const char* hostname = ssl_ctx.filters[i].c_str(); - CertMap* cmap = NULL; + CertMap* cmap = nullptr; if (strncmp(hostname, "*.", 2) == 0) { cmap = &(bg.wildcard_cert_map); hostname += 2; } else { cmap = &(bg.cert_map); } - if (cmap->seek(hostname) == NULL) { + if (cmap->seek(hostname) == nullptr) { cmap->insert(hostname, ssl_ctx.ctx); } else { LOG(WARNING) << "Duplicate certificate hostname=" << hostname; @@ -2220,7 +2212,7 @@ bool Server::ResetCertMappings(CertMaps& bg, const SSLContextMap& ctx_map) { void Server::FreeSSLContexts() { _ssl_ctx_map.clear(); _reload_cert_maps.Modify(ClearCertMapping); - _default_ssl_ctx = NULL; + _default_ssl_ctx = nullptr; } bool Server::ClearCertMapping(CertMaps& bg) { @@ -2240,7 +2232,7 @@ int Server::ResetMaxConcurrency(int max_concurrency) { } AdaptiveMaxConcurrency& Server::MaxConcurrencyOf(MethodProperty* mp) { - if (mp->status == NULL) { + if (mp->status == nullptr) { LOG(ERROR) << "method=" << mp->method->full_name() << " does not support max_concurrency"; _failed_to_set_max_concurrency_of_method = true; @@ -2250,7 +2242,7 @@ AdaptiveMaxConcurrency& Server::MaxConcurrencyOf(MethodProperty* mp) { } int Server::MaxConcurrencyOf(const MethodProperty* mp) const { - if (mp == NULL || mp->status == NULL) { + if (mp == nullptr || mp->status == nullptr) { return 0; } return mp->max_concurrency; @@ -2259,28 +2251,28 @@ int Server::MaxConcurrencyOf(const MethodProperty* mp) const { AdaptiveMaxConcurrency& Server::MaxConcurrencyOf(const butil::StringPiece& full_method_name) { do { if (full_method_name == butil::class_name_str()) { - if (NULL == options().nshead_service) { + if (nullptr == options().nshead_service) { break; } return options().nshead_service->_max_concurrency; } #ifdef ENABLE_THRIFT_FRAMED_PROTOCOL if (full_method_name == butil::class_name_str()) { - if (NULL == options().thrift_service) { + if (nullptr == options().thrift_service) { break; } return options().thrift_service->_max_concurrency; } #endif if (full_method_name == butil::class_name_str()) { - if (NULL == options().baidu_master_service) { + if (nullptr == options().baidu_master_service) { break; } return options().baidu_master_service->_max_concurrency; } MethodProperty* mp = _method_map.seek(full_method_name); - if (mp == NULL) { + if (mp == nullptr) { break; } return MaxConcurrencyOf(mp); @@ -2300,7 +2292,7 @@ AdaptiveMaxConcurrency& Server::MaxConcurrencyOf(const butil::StringPiece& full_ const butil::StringPiece& method_name) { MethodProperty* mp = const_cast( FindMethodPropertyByFullName(full_service_name, method_name)); - if (mp == NULL) { + if (mp == nullptr) { LOG(ERROR) << "Fail to find method=" << full_service_name << '/' << method_name; _failed_to_set_max_concurrency_of_method = true; @@ -2327,7 +2319,7 @@ int Server::MaxConcurrencyOf(google::protobuf::Service* service, bool& Server::IgnoreEovercrowdedOf(const butil::StringPiece& full_method_name) { MethodProperty* mp = _method_map.seek(full_method_name); - if (mp == NULL) { + if (mp == nullptr) { LOG(ERROR) << "Fail to find method=" << full_method_name; _failed_to_set_ignore_eovercrowded = true; return g_default_ignore_eovercrowded; @@ -2336,7 +2328,7 @@ bool& Server::IgnoreEovercrowdedOf(const butil::StringPiece& full_method_name) { LOG(WARNING) << "IgnoreEovercrowdedOf is only allowd before Server started"; return g_default_ignore_eovercrowded; } - if (mp->status == NULL) { + if (mp->status == nullptr) { LOG(ERROR) << "method=" << mp->method->full_name() << " does not support ignore_eovercrowded"; _failed_to_set_ignore_eovercrowded = true; @@ -2351,7 +2343,7 @@ bool Server::IgnoreEovercrowdedOf(const butil::StringPiece& full_method_name) co LOG(WARNING) << "IgnoreEovercrowdedOf is only allowd before Server started"; return g_default_ignore_eovercrowded; } - if (mp == NULL || mp->status == NULL) { + if (mp == nullptr || mp->status == nullptr) { return false; } return mp->ignore_eovercrowded; @@ -2383,7 +2375,7 @@ int Server::SSLSwitchCTXByHostname(struct ssl_st* ssl, Server* server = reinterpret_cast(se); const char* hostname = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); bool strict_sni = server->_options.ssl_options().strict_sni; - if (hostname == NULL) { + if (hostname == nullptr) { return strict_sni ? SSL_TLSEXT_ERR_ALERT_FATAL : SSL_TLSEXT_ERR_NOACK; } @@ -2393,7 +2385,7 @@ int Server::SSLSwitchCTXByHostname(struct ssl_st* ssl, } std::shared_ptr* pctx = s->cert_map.seek(hostname); - if (pctx == NULL) { + if (pctx == nullptr) { const char* dot = hostname; for (; *dot != '\0'; ++dot) { if (*dot == '.') { @@ -2405,7 +2397,7 @@ int Server::SSLSwitchCTXByHostname(struct ssl_st* ssl, pctx = s->wildcard_cert_map.seek(dot); } } - if (pctx == NULL) { + if (pctx == nullptr) { if (strict_sni) { return SSL_TLSEXT_ERR_ALERT_FATAL; } diff --git a/src/brpc/server.h b/src/brpc/server.h index 4fbe304fde..30846f750d 100644 --- a/src/brpc/server.h +++ b/src/brpc/server.h @@ -74,12 +74,12 @@ struct ServerOptions { // Process requests in format of nshead_t + blob. // Owned by Server and deleted in server's destructor. - // Default: NULL + // Default: nullptr NsheadService* nshead_service; // Process requests in format of thrift_binary_head_t + blob. // Owned by Server and deleted in server's destructor. - // Default: NULL + // Default: nullptr ThriftService* thrift_service; // Adaptor for Mongo protocol, check src/brpc/mongo_service_adaptor.h for details @@ -87,8 +87,8 @@ struct ServerOptions { // and must remain valid when server is running. const MongoServiceAdaptor* mongo_service_adaptor; - // Turn on authentication for all services if `auth' is not NULL. - // Default: NULL + // Turn on authentication for all services if `auth' is not nullptr. + // Default: nullptr const Authenticator* auth; // false: `auth' is not owned by server and must be valid when server is running. @@ -96,8 +96,8 @@ struct ServerOptions { // Default: false bool server_owns_auth; - // Turn on request interception if `interceptor' is not NULL. - // Default: NULL + // Turn on request interception if `interceptor' is not nullptr. + // Default: nullptr const Interceptor* interceptor; // false: `interceptor' is not owned by server and must be valid when server is running. @@ -158,9 +158,9 @@ struct ServerOptions { // session-local data or thread-local data is definitely not a good design. // The factory to create/destroy data attached to each RPC session. - // If this option is NULL, Controller::session_local_data() is always NULL. + // If this option is nullptr, Controller::session_local_data() is always nullptr. // NOT owned by Server and must be valid when Server is running. - // Default: NULL + // Default: nullptr const DataFactory* session_local_data_factory; // Prepare so many session-local data before server starts, so that calls @@ -173,9 +173,9 @@ struct ServerOptions { // The factory to create/destroy data attached to each searching thread // in server. - // If this option is NULL, brpc::thread_local_data() is always NULL. + // If this option is nullptr, brpc::thread_local_data() is always nullptr. // NOT owned by Server and must be valid when Server is running. - // Default: NULL + // Default: nullptr const DataFactory* thread_local_data_factory; // Prepare so many thread-local data before server starts, so that calls @@ -190,8 +190,8 @@ struct ServerOptions { // bthreads before server runs, mainly for initializing bthread locals. // You have to set both `bthread_init_fn' and `bthread_init_count' to // enable the feature. - bool (*bthread_init_fn)(void* args); // default: NULL (do nothing) - void* bthread_init_args; // default: NULL + bool (*bthread_init_fn)(void* args); // default: nullptr (do nothing) + void* bthread_init_args; // default: nullptr size_t bthread_init_count; // default: 0 // Provide builtin services at this port rather than the port to Start(). @@ -217,7 +217,7 @@ struct ServerOptions { bool security_mode() const { return internal_port >= 0 || !has_builtin_services; } // SSL related options. Refer to `ServerSSLOptions' for details - bool has_ssl_options() const { return _ssl_options != NULL; } + bool has_ssl_options() const { return _ssl_options != nullptr; } const ServerSSLOptions& ssl_options() const { return *_ssl_options; } ServerSSLOptions* mutable_ssl_options(); @@ -255,7 +255,7 @@ struct ServerOptions { HealthReporter* health_reporter; // For processing RTMP connections. Read src/brpc/rtmp.h for details. - // Default: NULL (rtmp support disabled) + // Default: nullptr (rtmp support disabled) RtmpService* rtmp_service; // Only enable these protocols, separated by spaces. @@ -268,7 +268,7 @@ struct ServerOptions { // For processing Redis connections. Read src/brpc/redis.h for details. // Owned by Server and deleted in server's destructor. - // Default: NULL (disabled) + // Default: nullptr (disabled) RedisService* redis_service; // Optional info name for composing server bvar prefix. Read ServerPrefix() method for details; @@ -383,7 +383,7 @@ class Server { bool is_builtin_service; ServiceOwnership ownership; // `service' and `restful_map' are mutual exclusive, they can't be - // both non-NULL. If `restful_map' is not NULL, the URL should be + // both non-nullptr. If `restful_map' is not nullptr, the URL should be // further matched by it. google::protobuf::Service* service; RestfulMap* restful_map; @@ -411,7 +411,7 @@ class Server { OpaqueParams(); }; OpaqueParams params; - // NULL if service of the method was never added as restful. + // nullptr if service of the method was never added as restful. // "@path1 @path2 ..." if the method was mapped from paths. std::string* http_url; google::protobuf::Service* service; @@ -435,7 +435,7 @@ class Server { ThreadLocalOptions() : tls_key(INVALID_BTHREAD_KEY) - , thread_local_data_factory(NULL) {} + , thread_local_data_factory(nullptr) {} }; public: @@ -445,7 +445,7 @@ class Server { // A set of functions to start this server. // Returns 0 on success, -1 otherwise and errno is set appropriately. // Notes: - // * Default options are taken if `opt' is NULL. + // * Default options are taken if `opt' is nullptr. // * A server can be started more than once if the server is completely // stopped by Stop() and Join(). // * port can be 0, which makes kernel to choose a port dynamically. @@ -520,14 +520,14 @@ class Server { int ResetCertificates(const std::vector& certs); // Find a service by its ServiceDescriptor::full_name(). - // Returns the registered service pointer, NULL on not found. + // Returns the registered service pointer, nullptr on not found. // Notice that for performance concerns, this function does not lock service // list internally thus races with AddService()/RemoveService(). google::protobuf::Service* FindServiceByFullName(const butil::StringPiece& full_name) const; // Find a service by its ServiceDescriptor::name(). - // Returns the registered service pointer, NULL on not found. + // Returns the registered service pointer, nullptr on not found. // Notice that for performance concerns, this function does not lock service // list internally thus races with AddService()/RemoveService(). google::protobuf::Service* @@ -550,7 +550,7 @@ class Server { // Return the first service added to this server. If a service was once // returned by first_service() and then removed, first_service() will - // always be NULL. + // always be nullptr. // This is useful for some production lines whose protocol does not // contain a service name, in which case this service works as the // default service. @@ -715,12 +715,12 @@ friend class Controller; template int SetServiceMaxConcurrency(T* service) { - if (NULL != service && NULL != service->_status) { + if (nullptr != service && nullptr != service->_status) { const AdaptiveMaxConcurrency* amc = &service->_max_concurrency; if (amc->type() == AdaptiveMaxConcurrency::UNLIMITED()) { amc = &_options.method_max_concurrency; } - ConcurrencyLimiter* cl = NULL; + ConcurrencyLimiter* cl = nullptr; if (!CreateConcurrencyLimiter(*amc, &cl)) { LOG(ERROR) << "Fail to create ConcurrencyLimiter for method"; return -1; @@ -755,7 +755,7 @@ friend class Controller; // uses service->name() to designate an RPC service ServiceMap _service_map; - // The only non-builtin service in _service_map, otherwise NULL. + // The only non-builtin service in _service_map, otherwise nullptr. google::protobuf::Service* _first_service; // Store TabInfo of services inheriting Tabbed. @@ -799,8 +799,8 @@ friend class Controller; // Get the data attached to current searching thread. The data is created by // ServerOptions.thread_local_data_factory and reused between different threads. -// If ServerOptions.thread_local_data_factory is NULL, return NULL. -// If this function is not called inside a server thread, return NULL. +// If ServerOptions.thread_local_data_factory is nullptr, return nullptr. +// If this function is not called inside a server thread, return nullptr. void* thread_local_data(); // Test if a dummy server was already started. diff --git a/src/brpc/server_id.cpp b/src/brpc/server_id.cpp index d745d6c5ba..19c3411623 100644 --- a/src/brpc/server_id.cpp +++ b/src/brpc/server_id.cpp @@ -37,7 +37,7 @@ bool ServerId2SocketIdMapper::AddServer(const ServerId& server) { bool ServerId2SocketIdMapper::RemoveServer(const ServerId& server) { int* nref = _nref_map.seek(server.id); - if (nref == NULL) { + if (nref == nullptr) { LOG(ERROR) << "Unexist SocketId=" << server.id; return false; } diff --git a/src/brpc/simple_data_pool.cpp b/src/brpc/simple_data_pool.cpp index fe1d32489c..23e4bc7df4 100644 --- a/src/brpc/simple_data_pool.cpp +++ b/src/brpc/simple_data_pool.cpp @@ -24,18 +24,18 @@ SimpleDataPool::SimpleDataPool(const DataFactory* factory) : _capacity(0) , _size(0) , _ncreated(0) - , _pool(NULL) + , _pool(nullptr) , _factory(factory) { } SimpleDataPool::~SimpleDataPool() { - Reset(NULL); + Reset(nullptr); } void SimpleDataPool::Reset(const DataFactory* factory) { unsigned saved_size = 0; - void** saved_pool = NULL; - const DataFactory* saved_factory = NULL; + void** saved_pool = nullptr; + const DataFactory* saved_factory = nullptr; { BAIDU_SCOPED_LOCK(_mutex); saved_size = _size; @@ -44,7 +44,7 @@ void SimpleDataPool::Reset(const DataFactory* factory) { _capacity = 0; _size = 0; _ncreated.store(0, butil::memory_order_relaxed); - _pool = NULL; + _pool = nullptr; _factory = factory; } if (saved_pool) { @@ -68,7 +68,7 @@ void SimpleDataPool::Reserve(unsigned n) { // Resize. const unsigned new_cap = std::max(_capacity * 3 / 2, n); void** new_pool = (void**)malloc(new_cap * sizeof(void*)); - if (NULL == new_pool) { + if (nullptr == new_pool) { return; } if (_pool) { @@ -81,7 +81,7 @@ void SimpleDataPool::Reserve(unsigned n) { for (; i < n; ++i) { void* data = _factory->CreateData(); - if (data == NULL) { + if (data == nullptr) { break; } _ncreated.fetch_add(1, butil::memory_order_relaxed); @@ -104,7 +104,7 @@ void* SimpleDataPool::Borrow() { } void SimpleDataPool::Return(void* data) { - if (data == NULL) { + if (data == nullptr) { return; } if (!_factory->ResetData(data)) { @@ -114,7 +114,7 @@ void SimpleDataPool::Return(void* data) { if (_capacity == _size) { const unsigned new_cap = (_capacity <= 1 ? 128 : (_capacity * 3 / 2)); void** new_pool = (void**)malloc(new_cap * sizeof(void*)); - if (NULL == new_pool) { + if (nullptr == new_pool) { mu.unlock(); return _factory->DestroyData(data); } diff --git a/src/brpc/socket.cpp b/src/brpc/socket.cpp index 95a7c6f43f..38727571ba 100644 --- a/src/brpc/socket.cpp +++ b/src/brpc/socket.cpp @@ -208,30 +208,27 @@ class Socket::SharedPart : public SharedObject { }; Socket::SharedPart::SharedPart(SocketId creator_socket_id2) - : socket_pool(NULL) + : socket_pool(nullptr) , creator_socket_id(creator_socket_id2) , num_continuous_connect_timeouts(0) , in_size(0) , in_num_messages(0) , out_size(0) , out_num_messages(0) - , extended_stat(NULL) + , extended_stat(nullptr) , recent_error_count(0) { } Socket::SharedPart::~SharedPart() { delete extended_stat; - extended_stat = NULL; - delete socket_pool.exchange(NULL, butil::memory_order_relaxed); + extended_stat = nullptr; + delete socket_pool.exchange(nullptr, butil::memory_order_relaxed); } void Socket::SharedPart::UpdateStatsEverySecond(int64_t now_ms) { ExtendedSocketStat* stat = extended_stat; - if (stat == NULL) { - stat = new (std::nothrow) ExtendedSocketStat; - if (stat == NULL) { - return; - } + if (stat == nullptr) { + stat = new ExtendedSocketStat; extended_stat = stat; } @@ -284,7 +281,7 @@ void Socket::SharedPart::UpdateStatsEverySecond(int64_t now_ms) { } } -SocketVarsCollector* g_vars = NULL; +SocketVarsCollector* g_vars = nullptr; static pthread_once_t s_create_vars_once = PTHREAD_ONCE_INIT; static void CreateVars() { @@ -371,9 +368,9 @@ struct BAIDU_CACHELINE_ALIGNMENT Socket::WriteRequest { butil::IOBuf dummy_buf; // We don't care about the return value since the request // is already failed. - (void)msg->AppendAndDestroySelf(&dummy_buf, NULL); + (void)msg->AppendAndDestroySelf(&dummy_buf, nullptr); } - set_pipelined_count_and_user_message(0, NULL, 0); + set_pipelined_count_and_user_message(0, nullptr, 0); return true; } return false; @@ -428,7 +425,7 @@ Socket::WriteRequest* const Socket::WriteRequest::UNCONNECTED = class Socket::EpollOutRequest : public SocketUser { public: EpollOutRequest() : fd(-1), timer_id(0) - , on_epollout_event(NULL), data(NULL) {} + , on_epollout_event(nullptr), data(nullptr) {} ~EpollOutRequest() override { // Remove the timer at last inside destructor to avoid @@ -455,32 +452,32 @@ static const uint64_t AUTH_FLAG = (1ul << 32); Socket::Socket(Forbidden f) // must be even because Address() relies on evenness of version : VersionedRefWithId(f) - , _shared_part(NULL) + , _shared_part(nullptr) , _nevent(0) - , _keytable_pool(NULL) + , _keytable_pool(nullptr) , _fd(-1) , _tos(0) , _reset_fd_real_us(-1) , _fd_version(0) - , _on_edge_triggered_events(NULL) + , _on_edge_triggered_events(nullptr) , _need_on_edge_trigger(false) - , _user(NULL) - , _conn(NULL) + , _user(nullptr) + , _conn(nullptr) , _preferred_index(-1) , _hc_count(0) , _last_msg_size(0) , _avg_msg_size(0) , _last_readtime_us(0) - , _parsing_context(NULL) + , _parsing_context(nullptr) , _correlation_id(0) , _health_check_interval_s(-1) , _is_hc_related_ref_held(false) , _ninprocess(1) , _auth_flag_error(0) , _auth_id(INVALID_BTHREAD_ID) - , _auth_context(NULL) + , _auth_context(nullptr) , _ssl_state(SSL_UNKNOWN) - , _ssl_session(NULL) + , _ssl_session(nullptr) , _socket_mode(SOCKET_MODE_TCP) , _connection_type_for_progressive_read(CONNECTION_TYPE_UNKNOWN) , _controller_released_socket(false) @@ -488,19 +485,19 @@ Socket::Socket(Forbidden f) , _fail_me_at_server_stop(false) , _logoff_flag(false) , _error_code(0) - , _pipeline_q(NULL) + , _pipeline_q(nullptr) , _last_writetime_us(0) , _unwritten_bytes(0) - , _epollout_butex(NULL) - , _write_head(NULL) + , _epollout_butex(nullptr) + , _write_head(nullptr) , _is_write_shutdown(false) - , _stream_set(NULL) + , _stream_set(nullptr) , _total_streams_unconsumed_size(0) , _ninflight_app_health_check(0) , _tcp_user_timeout_ms(-1) , _http_request_method(HTTP_METHOD_GET) { CreateVarsOnce(); - pthread_mutex_init(&_id_wait_list_mutex, NULL); + pthread_mutex_init(&_id_wait_list_mutex, nullptr); _epollout_butex = bthread::butex_create_checked >(); } @@ -541,7 +538,7 @@ void Socket::ReturnFailedWriteRequest(Socket::WriteRequest* p, int error_code, Socket::WriteRequest* Socket::ReleaseWriteRequestsExceptLast( Socket::WriteRequest* req, int error_code, const std::string& error_text) { WriteRequest* p = req; - while (p->next != NULL) { + while (p->next != nullptr) { WriteRequest* const saved_next = p->next; ReturnFailedWriteRequest(p, error_code, error_text); p = saved_next; @@ -569,7 +566,7 @@ void Socket::ReleaseAllFailedWriteRequests(Socket::WriteRequest* req) { CancelUnwrittenBytes(req->data.size()); } req->data.clear(); // MUST, otherwise IsWriteComplete is false - } while (!IsWriteComplete(req, true, NULL)); + } while (!IsWriteComplete(req, true, nullptr)); ReturnFailedWriteRequest(req, error_code, error_text); } @@ -736,11 +733,11 @@ int Socket::OnCreated(const SocketOptions& options) { // start build the transport _socket_mode = options.socket_mode; _transport = TransportFactory::CreateTransport(options.socket_mode); - CHECK(NULL != _transport); + CHECK(nullptr != _transport); _transport->Init(this, options); g_vars->nsocket << 1; - CHECK(NULL == _shared_part.load(butil::memory_order_relaxed)); + CHECK(nullptr == _shared_part.load(butil::memory_order_relaxed)); _nevent.store(0, butil::memory_order_relaxed); _keytable_pool = options.keytable_pool; _tos = 0; @@ -764,7 +761,7 @@ int Socket::OnCreated(const SocketOptions& options) { _is_hc_related_ref_held = false; _ninprocess.store(1, butil::memory_order_relaxed); _auth_flag_error.store(0, butil::memory_order_relaxed); - const int rc2 = bthread_id_create(&_auth_id, NULL, NULL); + const int rc2 = bthread_id_create(&_auth_id, nullptr, nullptr); if (rc2) { LOG(ERROR) << "Fail to create auth_id: " << berror(rc2); SetFailed(rc2, "Fail to create auth_id: %s", berror(rc2)); @@ -772,8 +769,8 @@ int Socket::OnCreated(const SocketOptions& options) { } _force_ssl = options.force_ssl; // Disable SSL check if there is no SSL context - _ssl_state = (options.initial_ssl_ctx == NULL ? SSL_OFF : SSL_UNKNOWN); - _ssl_session = NULL; + _ssl_state = (options.initial_ssl_ctx == nullptr ? SSL_OFF : SSL_UNKNOWN); + _ssl_session = nullptr; _ssl_ctx = options.initial_ssl_ctx; _connection_type_for_progressive_read = CONNECTION_TYPE_UNKNOWN; _controller_released_socket.store(false, butil::memory_order_relaxed); @@ -796,12 +793,12 @@ int Socket::OnCreated(const SocketOptions& options) { _unwritten_bytes.store(0, butil::memory_order_relaxed); _keepalive_options = options.keepalive_options; _tcp_user_timeout_ms = options.tcp_user_timeout_ms; - CHECK(NULL == _write_head.load(butil::memory_order_relaxed)); + CHECK(nullptr == _write_head.load(butil::memory_order_relaxed)); _is_write_shutdown = false; int fd = options.fd; if (!ValidFileDescriptor(fd) && options.connect_on_create) { // Connect on create. - fd = DoConnect(options.connect_abstime, NULL, NULL); + fd = DoConnect(options.connect_abstime, nullptr, nullptr); if (fd < 0) { PLOG(ERROR) << "Fail to connect to " << options.remote_side; int error_code = errno != 0 ? errno : EHOSTDOWN; @@ -835,15 +832,15 @@ void Socket::BeforeRecycled() { } if (_conn) { SocketConnection* const saved_conn = _conn; - _conn = NULL; + _conn = nullptr; saved_conn->BeforeRecycle(this); } if (_user) { SocketUser* const saved_user = _user; - _user = NULL; + _user = nullptr; saved_user->BeforeRecycle(this); } - SharedPart* sp = _shared_part.exchange(NULL, butil::memory_order_acquire); + SharedPart* sp = _shared_part.exchange(nullptr, butil::memory_order_acquire); if (sp) { sp->RemoveRefManually(); } @@ -863,7 +860,7 @@ void Socket::BeforeRecycled() { } } _transport->Release(); - reset_parsing_context(NULL); + reset_parsing_context(nullptr); _read_buf.clear(); _auth_flag_error.store(0, butil::memory_order_relaxed); @@ -873,19 +870,19 @@ void Socket::BeforeRecycled() { if (_ssl_session) { SSL_free(_ssl_session); - _ssl_session = NULL; + _ssl_session = nullptr; } - _ssl_ctx = NULL; + _ssl_ctx = nullptr; delete _pipeline_q; - _pipeline_q = NULL; + _pipeline_q = nullptr; delete _auth_context; - _auth_context = NULL; + _auth_context = nullptr; delete _stream_set; - _stream_set = NULL; + _stream_set = nullptr; const SocketId asid = _agent_socket_id.load(butil::memory_order_relaxed); if (asid != INVALID_SOCKET_ID) { @@ -920,12 +917,12 @@ void Socket::OnFailed(int error_code, const std::string& error_text) { &_id_wait_list, error_code, error_text, &_id_wait_list_mutex)); ResetAllStreams(error_code, error_text); - // _app_connect shouldn't be set to NULL in SetFailed otherwise + // _app_connect shouldn't be set to nullptr in SetFailed otherwise // HC is always not supported. // FIXME: Design a better interface for AppConnect // if (_app_connect) { // AppConnect* const saved_app_connect = _app_connect; - // _app_connect = NULL; + // _app_connect = nullptr; // saved_app_connect->StopConnect(this); // } } @@ -1019,20 +1016,20 @@ int Socket::WaitAndReset(int32_t expected_nref) { _local_side = butil::EndPoint(); if (_ssl_session) { SSL_free(_ssl_session); - _ssl_session = NULL; + _ssl_session = nullptr; } _ssl_state = SSL_UNKNOWN; _nevent.store(0, butil::memory_order_relaxed); // parsing_context is very likely to be associated with the fd, // removing it is a safer choice and required by http2. - reset_parsing_context(NULL); + reset_parsing_context(nullptr); // Must clear _read_buf otehrwise even if the connections is recovered, // the kept old data is likely to make parsing fail. _read_buf.clear(); _ninprocess.store(1, butil::memory_order_relaxed); _auth_flag_error.store(0, butil::memory_order_relaxed); bthread_id_error(_auth_id, 0); - const int rc = bthread_id_create(&_auth_id, NULL, NULL); + const int rc = bthread_id_create(&_auth_id, nullptr, nullptr); if (rc != 0) { LOG(FATAL) << "Fail to create _auth_id, " << berror(rc); return -1; @@ -1108,12 +1105,12 @@ int Socket::ReleaseReferenceIfIdle(int idle_seconds) { int Socket::SetFailed() { - return SetFailed(EFAILEDSOCKET, NULL); + return SetFailed(EFAILEDSOCKET, nullptr); } int Socket::SetFailed(int error_code, const char* error_fmt, ...) { std::string error_text; - if (error_fmt != NULL) { + if (error_fmt != nullptr) { va_list ap; va_start(ap, error_fmt); butil::string_vprintf(&error_text, error_fmt, ap); @@ -1128,7 +1125,7 @@ int Socket::SetFailed(SocketId id) { return -1; } - return ptr->SetFailed(EFAILEDSOCKET, NULL); + return ptr->SetFailed(EFAILEDSOCKET, nullptr); } void Socket::NotifyOnFailed(bthread_id_t id) { @@ -1151,7 +1148,7 @@ void Socket::NotifyOnFailed(bthread_id_t id) { int Socket::Status(SocketId id, int32_t* nref) { const butil::ResourceId slot = SlotOfVRefId(id); Socket* const m = address_resource(slot); - if (m != NULL) { + if (m != nullptr) { const uint64_t vref = m->versioned_ref(); if (VersionOfVRef(vref) == VersionOfVRefId(id)) { if (nref) { @@ -1171,7 +1168,7 @@ int Socket::Status(SocketId id, int32_t* nref) { // Check if there're new requests appended. // If yes, point old_head to reversed new requests and return false; // If no: -// old_head is fully written, set _write_head to NULL and return true; +// old_head is fully written, set _write_head to nullptr and return true; // old_head is not written yet, keep _write_head unchanged and return false; // `old_head' is last new_head got from this function or (in another word) // tail of current writing list. @@ -1179,10 +1176,10 @@ int Socket::Status(SocketId id, int32_t* nref) { bool Socket::IsWriteComplete(Socket::WriteRequest* old_head, bool singular_node, Socket::WriteRequest** new_tail) { - CHECK(NULL == old_head->next); - // Try to set _write_head to NULL to mark that the write is done. + CHECK(nullptr == old_head->next); + // Try to set _write_head to nullptr to mark that the write is done. WriteRequest* new_head = old_head; - WriteRequest* desired = NULL; + WriteRequest* desired = nullptr; bool return_when_no_more = true; if (!old_head->data.empty() || !singular_node) { desired = old_head; @@ -1203,7 +1200,7 @@ bool Socket::IsWriteComplete(Socket::WriteRequest* old_head, // Someone added new requests. // Reverse the list until old_head. - WriteRequest* tail = NULL; + WriteRequest* tail = nullptr; WriteRequest* p = new_head; do { while (p->next == WriteRequest::UNCONNECTED) { @@ -1214,7 +1211,7 @@ bool Socket::IsWriteComplete(Socket::WriteRequest* old_head, p->next = tail; tail = p; p = saved_next; - CHECK(p != NULL); + CHECK(p != nullptr); } while (p != old_head); // Link old list with new list. @@ -1311,11 +1308,7 @@ int Socket::Connect(const timespec* abstime, return -1; } if (on_connect) { - EpollOutRequest* req = new(std::nothrow) EpollOutRequest; - if (req == NULL) { - LOG(FATAL) << "Fail to new EpollOutRequest"; - return -1; - } + EpollOutRequest* req = new EpollOutRequest; req->fd = sockfd; req->timer_id = 0; req->on_epollout_event = on_connect; @@ -1449,7 +1442,7 @@ int Socket::OnOutputEvent(void* user_data, uint32_t, } EpollOutRequest* req = dynamic_cast(s->user()); - if (req != NULL) { + if (req != nullptr) { return s->HandleEpollOutRequest(0, req); } @@ -1467,7 +1460,7 @@ void Socket::HandleEpollOutTimeout(void* arg) { return; } EpollOutRequest* req = dynamic_cast(s->user()); - if (req == NULL) { + if (req == nullptr) { LOG(FATAL) << "Impossible! SocketUser MUST be EpollOutRequest here"; return; } @@ -1529,7 +1522,7 @@ void Socket::AfterAppConnected(int err, void* data) { static void* RunClosure(void* arg) { google::protobuf::Closure* done = (google::protobuf::Closure*)arg; done->Run(); - return NULL; + return nullptr; } int Socket::KeepWriteIfConnected(int fd, int err, void* data) { @@ -1559,7 +1552,7 @@ void Socket::CheckConnectedAndKeepWrite(int fd, int err, void* data) { butil::fd_guard sockfd(fd); WriteRequest* req = static_cast(data); Socket* s = req->get_socket(); - if (NULL == s->_conn) { + if (nullptr == s->_conn) { CHECK_GE(sockfd, 0); } if (err == 0 && s->CheckConnected(sockfd) == 0 @@ -1615,7 +1608,7 @@ int Socket::ConductError(bthread_id_t id_wait) { X509* Socket::GetPeerCertificate() const { if (ssl_state() != SSL_CONNECTED) { - return NULL; + return nullptr; } BAIDU_SCOPED_LOCK(_ssl_session_mutex); return SSL_get_peer_certificate(_ssl_session); @@ -1655,7 +1648,7 @@ int Socket::Write(butil::IOBuf* data, const WriteOptions* options_in) { req->data.swap(*data); // Set `req->next' to UNCONNECTED so that the KeepWrite thread will - // wait until it points to a valid WriteRequest or NULL. + // wait until it points to a valid WriteRequest or nullptr. req->next = WriteRequest::UNCONNECTED; req->id_wait = opt.id_wait; req->clear_and_set_control_bits(opt.notify_on_success, opt.shutdown_write); @@ -1692,7 +1685,7 @@ int Socket::Write(SocketMessagePtr<>& msg, const WriteOptions* options_in) { } // Set `req->next' to UNCONNECTED so that the KeepWrite thread will - // wait until it points to a valid WriteRequest or NULL. + // wait until it points to a valid WriteRequest or nullptr. req->next = WriteRequest::UNCONNECTED; req->id_wait = opt.id_wait; req->clear_and_set_control_bits(opt.notify_on_success, opt.shutdown_write); @@ -1705,7 +1698,7 @@ int Socket::StartWrite(WriteRequest* req, const WriteOptions& opt) { // Release fence makes sure the thread getting request sees *req WriteRequest* const prev_head = _write_head.exchange(req, butil::memory_order_release); - if (prev_head != NULL) { + if (prev_head != nullptr) { // Someone is writing to the fd. The KeepWrite thread may spin // until req->next to be non-UNCONNECTED. This process is not // lock-free, but the duration is so short(1~2 instructions, @@ -1724,7 +1717,7 @@ int Socket::StartWrite(WriteRequest* req, const WriteOptions& opt) { int ret = 0; // We've got the right to write. - req->next = NULL; + req->next = nullptr; // Fast fail when write has been shutdown. if (_is_write_shutdown) { @@ -1776,7 +1769,7 @@ int Socket::StartWrite(WriteRequest* req, const WriteOptions& opt) { } else { AddOutputBytes(nw); } - if (IsWriteComplete(req, true, NULL)) { + if (IsWriteComplete(req, true, nullptr)) { ReturnSuccessfulWriteRequest(req); return 0; } @@ -1808,13 +1801,13 @@ void* Socket::KeepWrite(void* void_arg) { SocketUniquePtr s(req->get_socket()); // When error occurs, spin until there's no more requests instead of - // returning directly otherwise _write_head is permantly non-NULL which + // returning directly otherwise _write_head is permantly non-nullptr which // makes later Write() abnormal. - WriteRequest* cur_tail = NULL; + WriteRequest* cur_tail = nullptr; do { // req was written, skip it. bool need_shutdown = false; - if (req->next != NULL && req->data.empty()) { + if (req->next != nullptr && req->data.empty()) { WriteRequest* const saved_req = req; need_shutdown = req->need_shutdown_write(); req = req->next; @@ -1838,7 +1831,7 @@ void* Socket::KeepWrite(void* void_arg) { s->AddOutputBytes(nw); } // Release WriteRequest until non-empty data, last request or shutdown write. - while (req->next != NULL && req->data.empty()) { + while (req->next != nullptr && req->data.empty()) { WriteRequest* const saved_req = req; need_shutdown = req->need_shutdown_write(); req = req->next; @@ -1869,8 +1862,8 @@ void* Socket::KeepWrite(void* void_arg) { break; } } - if (NULL == cur_tail) { - for (cur_tail = req; cur_tail->next != NULL; + if (nullptr == cur_tail) { + for (cur_tail = req; cur_tail->next != nullptr; cur_tail = cur_tail->next); } // Return when there's no more WriteRequests and req is completely @@ -1878,20 +1871,20 @@ void* Socket::KeepWrite(void* void_arg) { if (s->IsWriteComplete(cur_tail, (req == cur_tail), &cur_tail)) { CHECK_EQ(cur_tail, req); s->ReturnSuccessfulWriteRequest(req); - return NULL; + return nullptr; } } while (1); // Error occurred, release all requests until no new requests. s->ReleaseAllFailedWriteRequests(req); - return NULL; + return nullptr; } ssize_t Socket::DoWrite(WriteRequest* req) { // Group butil::IOBuf in the list into a batch array. butil::IOBuf* data_list[DATA_LIST_MAX]; size_t ndata = 0; - for (WriteRequest* p = req; p != NULL && ndata < DATA_LIST_MAX; + for (WriteRequest* p = req; p != nullptr && ndata < DATA_LIST_MAX; p = p->next) { data_list[ndata++] = &p->data; if (p->need_shutdown_write()) { @@ -1952,7 +1945,7 @@ ssize_t Socket::DoWrite(WriteRequest* req) { } int Socket::SSLHandshake(int fd, bool server_mode) { - if (_ssl_ctx == NULL) { + if (_ssl_ctx == nullptr) { if (server_mode) { LOG(ERROR) << "Lack SSL configuration to handle SSL request"; return -1; @@ -1966,7 +1959,7 @@ int Socket::SSLHandshake(int fd, bool server_mode) { SSL_free(_ssl_session); } _ssl_session = CreateSSLSession(_ssl_ctx->raw_ctx, id(), fd, server_mode); - if (_ssl_session == NULL) { + if (_ssl_session == nullptr) { LOG(ERROR) << "Fail to CreateSSLSession"; return -1; } @@ -1986,7 +1979,7 @@ int Socket::SSLHandshake(int fd, bool server_mode) { // remain ESTABLISHED indefinitely. const int handshake_timeout_ms = FLAGS_ssl_handshake_timeout_ms; timespec abstime_storage; - const timespec* abstime = NULL; + const timespec* abstime = nullptr; if (handshake_timeout_ms > 0) { abstime_storage = butil::milliseconds_from_now(handshake_timeout_ms); abstime = &abstime_storage; @@ -2185,7 +2178,7 @@ int Socket::FightAuthentication(int* auth_error) { *auth_error = (int32_t)(flag_error & 0xFFFFFFFFul); return EINVAL; } - if (0 == bthread_id_trylock(_auth_id, NULL)) { + if (0 == bthread_id_trylock(_auth_id, nullptr)) { // Winner return 0; } else { @@ -2214,13 +2207,12 @@ void Socket::SetAuthentication(int error_code) { } AuthContext* Socket::mutable_auth_context() { - if (_auth_context != NULL) { + if (_auth_context != nullptr) { LOG(FATAL) << "Impossible! This function is supposed to be called " "only once when verification succeeds in server side"; - return NULL; + return nullptr; } - _auth_context = new(std::nothrow) AuthContext(); - CHECK(_auth_context); + _auth_context = new AuthContext(); return _auth_context; } @@ -2232,7 +2224,7 @@ int Socket::OnInputEvent(void* user_data, uint32_t events, return -1; } if (!s->_transport->HasOnEdgeTrigger()) { - // Callback can be NULL when receiving error epoll events + // Callback can be nullptr when receiving error epoll events // (Added into epoll by `WaitConnected') return 0; } @@ -2294,7 +2286,7 @@ ObjectPtr ShowObject(const T* obj) { return ObjectPtr(obj); } template std::ostream& operator<<(std::ostream& os, const ObjectPtr& obj) { - if (obj._obj != NULL) { + if (obj._obj != nullptr) { os << '(' << butil::class_name_str(*obj._obj) << "*)"; } return os << obj._obj; @@ -2379,7 +2371,7 @@ void Socket::DebugSocket(std::ostream& os, SocketId id) { << "\nthis_id=" << ptr->id() << "\npreferred_index=" << preferred_index; InputMessenger* messenger = dynamic_cast(ptr->user()); - if (messenger != NULL) { + if (messenger != nullptr) { os << " (" << messenger->NameOfProtocol(preferred_index) << ')'; } const int64_t cpuwide_now = butil::cpuwide_time_us(); @@ -2581,7 +2573,7 @@ int Socket::CheckHealth() { } const timespec duetime = butil::milliseconds_from_now(_hc_option.health_check_timeout_ms); - const int connected_fd = Connect(&duetime, NULL, NULL); + const int connected_fd = Connect(&duetime, nullptr, nullptr); if (connected_fd >= 0) { ::close(connected_fd); return 0; @@ -2595,7 +2587,7 @@ int Socket::AddStream(StreamId stream_id) { _stream_mutex.unlock(); return -1; } - if (_stream_set == NULL) { + if (_stream_set == nullptr) { _stream_set = new std::set(); } _stream_set->insert(stream_id); @@ -2605,7 +2597,7 @@ int Socket::AddStream(StreamId stream_id) { int Socket::RemoveStream(StreamId stream_id) { _stream_mutex.lock(); - if (_stream_set == NULL) { + if (_stream_set == nullptr) { _stream_mutex.unlock(); CHECK(false) << "AddStream was not called"; return -1; @@ -2619,7 +2611,7 @@ void Socket::ResetAllStreams(int error_code, const std::string& error_text) { DCHECK(Failed()); std::set saved_stream_set; _stream_mutex.lock(); - if (_stream_set != NULL) { + if (_stream_set != nullptr) { // Not delete _stream_set because there are likely more streams added // after reviving if the Socket is still in use, or it is to be deleted in // BeforeRecycled() @@ -2752,10 +2744,10 @@ inline void SocketPool::ListSockets(std::vector* out, size_t max_count Socket::SharedPart* Socket::GetOrNewSharedPartSlower() { // Create _shared_part optimistically. SharedPart* shared_part = GetSharedPart(); - if (shared_part == NULL) { + if (shared_part == nullptr) { shared_part = new SharedPart(id()); shared_part->AddRefManually(); - SharedPart* expected = NULL; + SharedPart* expected = nullptr; if (!_shared_part.compare_exchange_strong( expected, shared_part, butil::memory_order_acq_rel)) { shared_part->RemoveRefManually(); @@ -2777,18 +2769,18 @@ void Socket::ShareStats(Socket* main_socket) { } int Socket::GetPooledSocket(SocketUniquePtr* pooled_socket) { - if (pooled_socket == NULL) { + if (pooled_socket == nullptr) { LOG(ERROR) << "pooled_socket is NULL"; return -1; } SharedPart* main_sp = GetOrNewSharedPart(); - if (main_sp == NULL) { + if (main_sp == nullptr) { LOG(ERROR) << "_shared_part is NULL"; return -1; } // Create socket_pool optimistically. SocketPool* socket_pool = main_sp->socket_pool.load(butil::memory_order_consume); - if (socket_pool == NULL) { + if (socket_pool == nullptr) { SocketOptions opt; opt.remote_side = remote_side(); opt.local_side = butil::EndPoint(local_side().ip, 0); @@ -2800,7 +2792,7 @@ int Socket::GetPooledSocket(SocketUniquePtr* pooled_socket) { opt.app_connect = _app_connect; opt.socket_mode = _socket_mode; socket_pool = new SocketPool(opt); - SocketPool* expected = NULL; + SocketPool* expected = nullptr; if (!main_sp->socket_pool.compare_exchange_strong( expected, socket_pool, butil::memory_order_acq_rel)) { delete socket_pool; @@ -2812,7 +2804,7 @@ int Socket::GetPooledSocket(SocketUniquePtr* pooled_socket) { return -1; } (*pooled_socket)->ShareStats(this); - CHECK((*pooled_socket)->parsing_context() == NULL) + CHECK((*pooled_socket)->parsing_context() == nullptr) << "context=" << (*pooled_socket)->parsing_context() << " is not NULL when " << *(*pooled_socket) << " is got from" " SocketPool, the protocol implementation is buggy"; @@ -2820,20 +2812,20 @@ int Socket::GetPooledSocket(SocketUniquePtr* pooled_socket) { } int Socket::ReturnToPool() { - SharedPart* sp = _shared_part.exchange(NULL, butil::memory_order_acquire); - if (sp == NULL) { + SharedPart* sp = _shared_part.exchange(nullptr, butil::memory_order_acquire); + if (sp == nullptr) { LOG(ERROR) << "_shared_part is NULL"; SetFailed(EINVAL, "_shared_part is NULL"); return -1; } SocketPool* pool = sp->socket_pool.load(butil::memory_order_consume); - if (pool == NULL) { + if (pool == nullptr) { LOG(ERROR) << "_shared_part->socket_pool is NULL"; SetFailed(EINVAL, "_shared_part->socket_pool is NULL"); sp->RemoveRefManually(); return -1; } - CHECK(parsing_context() == NULL) + CHECK(parsing_context() == nullptr) << "context=" << parsing_context() << " is not released when " << *this << " is returned to SocketPool, the protocol " "implementation is buggy"; @@ -2853,8 +2845,8 @@ int Socket::ReturnToPool() { bool Socket::HasSocketPool() const { SharedPart* sp = GetSharedPart(); - if (sp != NULL) { - return sp->socket_pool.load(butil::memory_order_consume) != NULL; + if (sp != nullptr) { + return sp->socket_pool.load(butil::memory_order_consume) != nullptr; } return false; } @@ -2862,11 +2854,11 @@ bool Socket::HasSocketPool() const { void Socket::ListPooledSockets(std::vector* out, size_t max_count) { out->clear(); SharedPart* sp = GetSharedPart(); - if (sp == NULL) { + if (sp == nullptr) { return; } SocketPool* pool = sp->socket_pool.load(butil::memory_order_consume); - if (pool == NULL) { + if (pool == nullptr) { return; } pool->ListSockets(out, max_count); @@ -2874,11 +2866,11 @@ void Socket::ListPooledSockets(std::vector* out, size_t max_count) { bool Socket::GetPooledSocketStats(int* numfree, int* numinflight) { SharedPart* sp = GetSharedPart(); - if (sp == NULL) { + if (sp == nullptr) { return false; } SocketPool* pool = sp->socket_pool.load(butil::memory_order_consume); - if (pool == NULL) { + if (pool == nullptr) { return false; } *numfree = pool->_numfree.load(butil::memory_order_relaxed); @@ -2887,7 +2879,7 @@ bool Socket::GetPooledSocketStats(int* numfree, int* numinflight) { } int Socket::GetShortSocket(SocketUniquePtr* short_socket) { - if (short_socket == NULL) { + if (short_socket == nullptr) { LOG(ERROR) << "short_socket is NULL"; return -1; } @@ -2915,7 +2907,7 @@ int Socket::GetAgentSocket(SocketUniquePtr* out, bool (*checkfn)(Socket*)) { SocketUniquePtr tmp_sock; do { if (Address(id, &tmp_sock) == 0) { - if (checkfn == NULL || checkfn(tmp_sock.get())) { + if (checkfn == nullptr || checkfn(tmp_sock.get())) { out->swap(tmp_sock); return 0; } @@ -2926,7 +2918,7 @@ int Socket::GetAgentSocket(SocketUniquePtr* out, bool (*checkfn)(Socket*)) { LOG(ERROR) << "Fail to get short socket from " << *this; return -1; } - if (checkfn == NULL || checkfn(tmp_sock.get())) { + if (checkfn == nullptr || checkfn(tmp_sock.get())) { break; } tmp_sock->ReleaseAdditionalReference(); @@ -2955,7 +2947,7 @@ void Socket::GetStat(SocketStat* s) const { BAIDU_CASSERT(sizeof(WriteRequest) == 64, sizeof_write_request_is_64); SharedPart* sp = GetSharedPart(); - if (sp != NULL && sp->extended_stat != NULL) { + if (sp != nullptr && sp->extended_stat != nullptr) { *s = *sp->extended_stat; } else { memset(s, 0, sizeof(*s)); @@ -3007,7 +2999,7 @@ void Socket::OnProgressiveReadCompleted() { } SocketSSLContext::SocketSSLContext() - : raw_ctx(NULL) + : raw_ctx(nullptr) {} SocketSSLContext::~SocketSSLContext() { diff --git a/src/brpc/socket.h b/src/brpc/socket.h index 3bc90918d9..6d321f8bc3 100644 --- a/src/brpc/socket.h +++ b/src/brpc/socket.h @@ -270,19 +270,19 @@ struct SocketOptions { // Default: false, means that a connection will be established // on first write. bool connect_on_create{false}; - // Default: NULL, means no timeout. - const timespec* connect_abstime{NULL}; - SocketUser* user{NULL}; + // Default: nullptr, means no timeout. + const timespec* connect_abstime{nullptr}; + SocketUser* user{nullptr}; // When *edge-triggered* events happen on the file descriptor, callback // `on_edge_triggered_events' will be called. Inside the callback, user // shall read fd() in non-blocking mode until all data has been read // or EAGAIN is met, otherwise the callback will not be called again // until new data arrives. The callback will not be called from more than // one thread at any time. - void (*on_edge_triggered_events)(Socket*){NULL}; + void (*on_edge_triggered_events)(Socket*){nullptr}; // Indicates that this socket requires an edge-triggered event handler even - // if `on_edge_triggered_events` is left as NULL by the caller. When this - // flag is true and `on_edge_triggered_events` is NULL, the underlying + // if `on_edge_triggered_events` is left as nullptr by the caller. When this + // flag is true and `on_edge_triggered_events` is nullptr, the underlying // transport-specific implementation (e.g. a transport subclass) is allowed // to install a suitable default `on_edge_triggered_events` callback on // behalf of the user. Typical usage is by transports/protocols that rely @@ -294,11 +294,11 @@ struct SocketOptions { bool force_ssl{false}; std::shared_ptr initial_ssl_ctx; SocketMode socket_mode{SOCKET_MODE_TCP}; - bthread_keytable_pool_t* keytable_pool{NULL}; - SocketConnection* conn{NULL}; + bthread_keytable_pool_t* keytable_pool{nullptr}; + SocketConnection* conn{nullptr}; std::shared_ptr app_connect; // The created socket will set parsing_context with this value. - Destroyable* initial_parsing_context{NULL}; + Destroyable* initial_parsing_context{nullptr}; // Socket keepalive related options. // Refer to `SocketKeepaliveOptions' for details. @@ -383,8 +383,8 @@ friend class TransportFactory; bool notify_on_success; // If no connection exists, a connection will be established to - // remote_side() regarding deadline `abstime'. NULL means no timeout. - // Default: NULL + // remote_side() regarding deadline `abstime'. nullptr means no timeout. + // Default: nullptr const timespec* abstime; // Will be queued to implement positional correspondence with responses @@ -419,7 +419,7 @@ friend class TransportFactory; WriteOptions() : id_wait(INVALID_BTHREAD_ID) , notify_on_success(false) - , abstime(NULL) + , abstime(nullptr) , pipelined_count(0) , auth_flags(0) , ignore_eovercrowded(false) @@ -430,11 +430,11 @@ friend class TransportFactory; // True if write of socket is shutdown. bool IsWriteShutdown() const { return _is_write_shutdown; } - int Write(butil::IOBuf *msg, const WriteOptions* options = NULL); + int Write(butil::IOBuf *msg, const WriteOptions* options = nullptr); // Write an user-defined message. `msg' is released when Write() is // successful and *may* remain unchanged otherwise. - int Write(SocketMessagePtr<>& msg, const WriteOptions* options = NULL); + int Write(SocketMessagePtr<>& msg, const WriteOptions* options = nullptr); // The file descriptor int fd() const { return _fd.load(butil::memory_order_relaxed); } @@ -480,8 +480,8 @@ friend class TransportFactory; Destroyable* release_parsing_context(); Destroyable* parsing_context() const { return _parsing_context.load(butil::memory_order_consume); } - // Try to set _parsing_context to *ctx when _parsing_context is NULL. - // If _parsing_context is NULL, the set is successful and true is returned. + // Try to set _parsing_context to *ctx when _parsing_context is nullptr. + // If _parsing_context is nullptr, the set is successful and true is returned. // Otherwise, *ctx is Destroy()-ed and replaced with the value of // _parsing_context, and false is returned. This process is thread-safe. template bool initialize_parsing_context(T** ctx); @@ -495,7 +495,7 @@ friend class TransportFactory; static int Create(const SocketOptions& options, SocketId* id); // Mark this Socket or the Socket associated with `id' as failed. - // Any later Address() of the identifier shall return NULL unless the + // Any later Address() of the identifier shall return nullptr unless the // Socket was revivied by StartHealthCheck. The Socket is NOT recycled // after calling this function, instead it will be recycled when no one // references it. Internal fields of the Socket are still accessible @@ -629,7 +629,7 @@ friend class TransportFactory; // Get and persist a socket connecting to the same place as this socket. // If an agent socket was already created and persisted, it's returned // directly (provided other constraints are satisfied) - // If `checkfn' is not NULL, and the checking result on the socket that + // If `checkfn' is not nullptr, and the checking result on the socket that // would be returned is false, the socket is abandoned and the getting // process is restarted. // For example, http2 connections may run out of stream_id after long time @@ -709,7 +709,7 @@ friend class TransportFactory; // reference on created. void HoldHCRelatedRef(); - static int Status(SocketId, int32_t* nref = NULL); // for unit-test. + static int Status(SocketId, int32_t* nref = nullptr); // for unit-test. // Perform SSL handshake after TCP connection has been established. // Create SSL session inside and block (in bthread) until handshake @@ -737,7 +737,7 @@ friend class TransportFactory; int WaitEpollOut(int fd, bool pollin, const timespec* abstime); // [Not thread-safe] Establish a tcp connection to `remote_side()' - // If `on_connect' is NULL, this function blocks current thread + // If `on_connect' is nullptr, this function blocks current thread // until connected/timeout. Otherwise, it returns immediately after // starting a connection request and `on_connect' will be called // when connecting completes (whether it succeeds or not) @@ -1003,7 +1003,7 @@ friend class TransportFactory; // Socket keepalive related options. // Refer to `SocketKeepaliveOptions' for details. - // non-NULL means that keepalive is on. + // non-nullptr means that keepalive is on. std::shared_ptr _keepalive_options; // Only linux supports TCP_USER_TIMEOUT. diff --git a/src/brpc/socket_inl.h b/src/brpc/socket_inl.h index ea8a392ef2..fe6bf76b47 100644 --- a/src/brpc/socket_inl.h +++ b/src/brpc/socket_inl.h @@ -88,12 +88,12 @@ inline void Socket::reset_parsing_context(Destroyable* new_context) { } inline Destroyable* Socket::release_parsing_context() { - return _parsing_context.exchange(NULL, butil::memory_order_acquire); + return _parsing_context.exchange(nullptr, butil::memory_order_acquire); } template bool Socket::initialize_parsing_context(T** ctx) { - Destroyable* expected = NULL; + Destroyable* expected = nullptr; if (_parsing_context.compare_exchange_strong( expected, *ctx, butil::memory_order_acq_rel, butil::memory_order_acquire)) { @@ -108,7 +108,7 @@ bool Socket::initialize_parsing_context(T** ctx) { // NOTE: Push/Pop may be called from different threads simultaneously. inline void Socket::PushPipelinedInfo(const PipelinedInfo& pi) { BAIDU_SCOPED_LOCK(_pipeline_mutex); - if (_pipeline_q == NULL) { + if (_pipeline_q == nullptr) { _pipeline_q = new std::deque; } _pipeline_q->push_back(pi); @@ -116,7 +116,7 @@ inline void Socket::PushPipelinedInfo(const PipelinedInfo& pi) { inline bool Socket::PopPipelinedInfo(PipelinedInfo* info) { BAIDU_SCOPED_LOCK(_pipeline_mutex); - if (_pipeline_q != NULL && !_pipeline_q->empty()) { + if (_pipeline_q != nullptr && !_pipeline_q->empty()) { *info = _pipeline_q->front(); _pipeline_q->pop_front(); return true; @@ -126,7 +126,7 @@ inline bool Socket::PopPipelinedInfo(PipelinedInfo* info) { inline void Socket::GivebackPipelinedInfo(const PipelinedInfo& pi) { BAIDU_SCOPED_LOCK(_pipeline_mutex); - if (_pipeline_q != NULL) { + if (_pipeline_q != nullptr) { _pipeline_q->push_front(pi); } } @@ -141,7 +141,7 @@ inline Socket::SharedPart* Socket::GetSharedPart() const { inline Socket::SharedPart* Socket::GetOrNewSharedPart() { SharedPart* shared_part = GetSharedPart(); - if (shared_part != NULL) { // most cases + if (shared_part != nullptr) { // most cases return shared_part; } return GetOrNewSharedPartSlower(); diff --git a/src/brpc/socket_map.cpp b/src/brpc/socket_map.cpp index 1562e0a3b9..852231097c 100644 --- a/src/brpc/socket_map.cpp +++ b/src/brpc/socket_map.cpp @@ -62,7 +62,7 @@ DEFINE_bool(reserve_one_idle_socket, false, "Reserve one idle socket for pooled connections when idle_timeout_second > 0"); static pthread_once_t g_socket_map_init = PTHREAD_ONCE_INIT; -static butil::static_atomic g_socket_map = BUTIL_STATIC_ATOMIC_INIT(NULL); +static butil::static_atomic g_socket_map = BUTIL_STATIC_ATOMIC_INIT(nullptr); class GlobalSocketCreator : public SocketCreator { public: @@ -88,7 +88,7 @@ static void CreateClientSideSocketMap() { } SocketMap* get_client_side_socket_map() { - // The consume fence makes sure that we see a NULL or a fully initialized + // The consume fence makes sure that we see a nullptr or a fully initialized // SocketMap. return g_socket_map.load(butil::memory_order_consume); } @@ -134,18 +134,18 @@ void SocketMapList(std::vector* ids) { // ========== SocketMap impl. ============ SocketMapOptions::SocketMapOptions() - : socket_creator(NULL) + : socket_creator(nullptr) , suggested_map_size(1024) - , idle_timeout_second_dynamic(NULL) + , idle_timeout_second_dynamic(nullptr) , idle_timeout_second(0) - , defer_close_second_dynamic(NULL) + , defer_close_second_dynamic(nullptr) , defer_close_second(0) - , defer_close_respect_idle_dynamic(NULL) { + , defer_close_respect_idle_dynamic(nullptr) { } SocketMap::SocketMap() : _exposed_in_bvar(false) - , _this_map_bvar(NULL) + , _this_map_bvar(nullptr) , _has_close_idle_thread(false) { } @@ -153,7 +153,7 @@ SocketMap::~SocketMap() { RPC_VLOG << "Destroying SocketMap=" << this; if (_has_close_idle_thread) { bthread_stop(_close_idle_thread); - bthread_join(_close_idle_thread, NULL); + bthread_join(_close_idle_thread, nullptr); } if (!_map.empty()) { std::ostringstream err; @@ -176,19 +176,19 @@ SocketMap::~SocketMap() { } delete _this_map_bvar; - _this_map_bvar = NULL; + _this_map_bvar = nullptr; delete _options.socket_creator; - _options.socket_creator = NULL; + _options.socket_creator = nullptr; } int SocketMap::Init(const SocketMapOptions& options) { - if (_options.socket_creator != NULL) { + if (_options.socket_creator != nullptr) { LOG(ERROR) << "Already initialized"; return -1; } _options = options; - if (_options.socket_creator == NULL) { + if (_options.socket_creator == nullptr) { LOG(ERROR) << "SocketOptions.socket_creator must be set"; return -1; } @@ -196,7 +196,7 @@ int SocketMap::Init(const SocketMapOptions& options) { LOG(ERROR) << "Fail to init _map"; return -1; } - if (_options.idle_timeout_second_dynamic != NULL || + if (_options.idle_timeout_second_dynamic != nullptr || _options.idle_timeout_second > 0) { bthread_attr_t attr = BTHREAD_ATTR_NORMAL; bthread_attr_set_name(&attr, "RunWatchConnections"); @@ -252,7 +252,7 @@ int SocketMap::Insert(const SocketMapKey& key, SocketId* id, // removing and inserting it again. But this would make error branches // below have to remove the entry before returning, which is // error-prone. We prefer code maintainability here. - sc = NULL; + sc = nullptr; } SocketId tmp_id; opt.remote_side = key.peer.addr; @@ -381,7 +381,7 @@ void SocketMap::ListOrphans(int64_t defer_us, std::vector* out) { void* SocketMap::RunWatchConnections(void* arg) { static_cast(arg)->WatchConnections(); - return NULL; + return nullptr; } void SocketMap::WatchConnections() { diff --git a/src/brpc/socket_map.h b/src/brpc/socket_map.h index c4dc5c28f3..234d67536c 100644 --- a/src/brpc/socket_map.h +++ b/src/brpc/socket_map.h @@ -132,7 +132,7 @@ struct SocketMapOptions { SocketMapOptions(); // For creating sockets by need. Owned and deleted by SocketMap. - // Default: NULL (must be set by user). + // Default: nullptr (must be set by user). SocketCreator* socket_creator; // Initial size of the map (proper size reduces number of resizes) @@ -141,7 +141,7 @@ struct SocketMapOptions { // Pooled connections without data transmission for so many seconds will // be closed. No effect for non-positive values. - // If idle_timeout_second_dynamic is not NULL, use the dereferenced value + // If idle_timeout_second_dynamic is not nullptr, use the dereferenced value // each time instead of idle_timeout_second. // Default: 0 (disabled) const int* idle_timeout_second_dynamic; @@ -149,7 +149,7 @@ struct SocketMapOptions { // Defer close of connections for so many seconds even if the connection // is not used by anyone. Close immediately for non-positive values. - // If defer_close_second_dynamic is not NULL, use the dereferenced value + // If defer_close_second_dynamic is not nullptr, use the dereferenced value // each time instead of defer_close_second. // Default: 0 (disabled) const int* defer_close_second_dynamic; @@ -158,9 +158,9 @@ struct SocketMapOptions { // When defer_close_second > 0 and this flag is true, close a connection // immediately when the last reference is removed and the socket has already // been idle for longer than defer_close_second. - // If defer_close_respect_idle_dynamic is not NULL, use the dereferenced + // If defer_close_respect_idle_dynamic is not nullptr, use the dereferenced // value each time. - // Default: NULL (treated as false) + // Default: nullptr (treated as false) const bool* defer_close_respect_idle_dynamic; }; diff --git a/src/brpc/socket_message.h b/src/brpc/socket_message.h index 32ecfd7733..869d299eba 100644 --- a/src/brpc/socket_message.h +++ b/src/brpc/socket_message.h @@ -39,7 +39,7 @@ class SocketMessage { // Params: // out - The buffer to be generated, being empty initially, could // remain empty after being called. - // sock - the socket to write. NULL when the message will be abandoned + // sock - the socket to write. nullptr when the message will be abandoned // If the status returned is an error, WriteOptions.id_wait (if absent) // will be signaled with the error. Other messages are not affected. virtual butil::Status AppendAndDestroySelf(butil::IOBuf* out, Socket* sock) = 0; @@ -53,7 +53,7 @@ struct SocketMessageDeleter { void operator()(SocketMessage* msg) const { butil::IOBuf dummy_buf; // We don't care about the return value since the message is abandoned - (void)msg->AppendAndDestroySelf(&dummy_buf, NULL); + (void)msg->AppendAndDestroySelf(&dummy_buf, nullptr); } }; } diff --git a/src/brpc/span.cpp b/src/brpc/span.cpp index d5807121d7..304ba5d2be 100644 --- a/src/brpc/span.cpp +++ b/src/brpc/span.cpp @@ -41,14 +41,14 @@ namespace brpc { // Callback for creating a new bthread span when creating a new bthread. // This is called by bthread layer when BTHREAD_INHERIT_SPAN flag is set. -// Returns a heap-allocated weak_ptr* as void*, or NULL if span creation fails. +// Returns a heap-allocated weak_ptr* as void*, or nullptr if span creation fails. void* CreateBthreadSpanAsVoid() { const int64_t received_us = butil::cpuwide_time_us(); const int64_t base_realtime = butil::gettimeofday_us() - received_us; std::shared_ptr span = Span::CreateBthreadSpan("Bthread", base_realtime); if (!span) { - return NULL; + return nullptr; } return new std::weak_ptr(span); } @@ -111,7 +111,7 @@ bool HasTlsParentSpan() { void SpanDeleter::operator()(Span* r) const { - if (r == NULL) { + if (r == nullptr) { return; } @@ -202,7 +202,7 @@ Span::~Span() { std::shared_ptr Span::CreateClientSpan(const std::string& full_method_name, int64_t base_real_us) { Span* span_raw = butil::get_object(Forbidden()); - if (__builtin_expect(span_raw == NULL, 0)) { + if (__builtin_expect(span_raw == nullptr, 0)) { return nullptr; } std::shared_ptr span(span_raw, SpanDeleter()); @@ -245,7 +245,7 @@ std::shared_ptr Span::CreateBthreadSpan(const std::string& full_method_nam int64_t base_real_us) { std::shared_ptr parent = Span::tls_parent(); Span* span_raw = butil::get_object(Forbidden()); - if (__builtin_expect(span_raw == NULL, 0)) { + if (__builtin_expect(span_raw == nullptr, 0)) { return nullptr; } std::shared_ptr span(span_raw, SpanDeleter()); @@ -296,7 +296,7 @@ std::shared_ptr Span::CreateServerSpan( uint64_t trace_id, uint64_t span_id, uint64_t parent_span_id, int64_t base_real_us) { Span* span_raw = butil::get_object(Forbidden()); - if (__builtin_expect(span_raw == NULL, 0)) { + if (__builtin_expect(span_raw == nullptr, 0)) { return nullptr; } std::shared_ptr span(span_raw, SpanDeleter()); @@ -419,7 +419,7 @@ SpanInfoExtractor::SpanInfoExtractor(const char* info) bool SpanInfoExtractor::PopAnnotation( int64_t before_this_time, int64_t* time, std::string* annotation) { - for (; _sp != NULL; ++_sp) { + for (; _sp != nullptr; ++_sp) { butil::StringSplitter sp_time(_sp.field(), _sp.field() + _sp.length(), ' '); if (sp_time) { char* endptr; @@ -473,7 +473,7 @@ class SpanDB : public SharedObject { std::string id_db_name; std::string time_db_name; - SpanDB() : id_db(NULL), time_db(NULL) { } + SpanDB() : id_db(nullptr), time_db(nullptr) { } static SpanDB* Open(); leveldb::Status Index(std::shared_ptr span, std::string* value_buf); leveldb::Status RemoveSpansBefore(int64_t tm); @@ -487,7 +487,7 @@ class SpanDB : public SharedObject { } ~SpanDB() { - if (id_db == NULL && time_db == NULL) { + if (id_db == nullptr && time_db == nullptr) { return; } delete id_db; @@ -508,7 +508,7 @@ static int64_t g_last_delete_tm = 0; static pthread_mutex_t g_span_db_mutex = PTHREAD_MUTEX_INITIALIZER; static bool g_span_ending = false; // don't open span again if this var is true. // Can't use intrusive_ptr which has ctor/dtor issues. -static SpanDB* g_span_db = NULL; +static SpanDB* g_span_db = nullptr; bool has_span_db() { return !!g_span_db; } bvar::CollectorSpeedLimit g_span_sl = BVAR_COLLECTOR_SPEED_LIMIT_INITIALIZER; static bvar::DisplaySamplingRatio s_display_sampling_ratio( @@ -533,7 +533,7 @@ class SpanPreprocessor : public bvar::CollectorPreprocessor { std::sort(list.begin(), list.end(), SpanEarlier()); } }; -static SpanPreprocessor* g_span_prep = NULL; +static SpanPreprocessor* g_span_prep = nullptr; bvar::CollectorSpeedLimit* Span::speed_limit() { return &g_span_sl; @@ -544,7 +544,7 @@ bvar::CollectorPreprocessor* Span::preprocessor() { } static void ResetSpanDB(SpanDB* db) { - SpanDB* old_db = NULL; + SpanDB* old_db = nullptr; { BAIDU_SCOPED_LOCK(g_span_db_mutex); old_db = g_span_db; @@ -560,7 +560,7 @@ static void ResetSpanDB(SpanDB* db) { static void RemoveSpanDB() { g_span_ending = true; - ResetSpanDB(NULL); + ResetSpanDB(nullptr); } static void StartSpanIndexing() { @@ -578,7 +578,7 @@ static int StartIndexingIfNeeded() { inline int GetSpanDB(butil::intrusive_ptr* db) { BAIDU_SCOPED_LOCK(g_span_db_mutex); - if (g_span_db != NULL) { + if (g_span_db != nullptr) { *db = g_span_db; return 0; } @@ -661,14 +661,14 @@ SpanDB* SpanDB::Open() { if (!butil::CreateDirectoryAndGetError(dir, &error)) { LOG(ERROR) << "Fail to create directory=`" << dir.value() << ", " << error; - return NULL; + return nullptr; } local.id_db_name.append("/id.db"); st = leveldb::DB::Open(options, local.id_db_name.c_str(), &local.id_db); if (!st.ok()) { LOG(ERROR) << "Fail to open id_db: " << st.ToString(); - return NULL; + return nullptr; } local.time_db_name.append(FLAGS_rpcz_database_dir); @@ -677,12 +677,9 @@ SpanDB* SpanDB::Open() { st = leveldb::DB::Open(options, local.time_db_name.c_str(), &local.time_db); if (!st.ok()) { LOG(ERROR) << "Fail to open time_db: " << st.ToString(); - return NULL; - } - SpanDB* db = new (std::nothrow) SpanDB; - if (NULL == db) { - return NULL; + return nullptr; } + SpanDB* db = new SpanDB; LOG(INFO) << "Opened " << local.id_db_name << " and " << local.time_db_name; Swap(local, *db); @@ -807,7 +804,7 @@ leveldb::Status SpanDB::Index(std::shared_ptr span, std::string* val // NOTE: may take more than 100ms leveldb::Status SpanDB::RemoveSpansBefore(int64_t tm) { - if (id_db == NULL || time_db == NULL) { + if (id_db == nullptr || time_db == nullptr) { return leveldb::Status::InvalidArgument(leveldb::Slice("NULL param")); } leveldb::Status rc; @@ -860,7 +857,7 @@ void Span::dump_to_db() { return; } SpanDB* db2 = SpanDB::Open(); - if (db2 == NULL) { + if (db2 == nullptr) { LOG(WARNING) << "Fail to open SpanDB"; return; } @@ -872,7 +869,7 @@ void Span::dump_to_db() { if (!st.ok()) { LOG(WARNING) << st.ToString(); if (st.IsNotFound() || st.IsIOError() || st.IsCorruption()) { - ResetSpanDB(NULL); + ResetSpanDB(nullptr); return; } } @@ -886,7 +883,7 @@ void Span::dump_to_db() { if (!st.ok()) { LOG(ERROR) << st.ToString(); if (st.IsNotFound() || st.IsIOError() || st.IsCorruption()) { - ResetSpanDB(NULL); + ResetSpanDB(nullptr); return; } } @@ -924,7 +921,7 @@ bvar::CollectorSpeedLimit* SpanContainer::speed_limit() { if (_span) { return _span->speed_limit(); } - return NULL; + return nullptr; } // ===================================== @@ -1007,7 +1004,7 @@ void ListSpans(int64_t starting_realtime, size_t max_scan, } brief.Clear(); if (brief.ParseFromArray(it->value().data(), it->value().size())) { - if (NULL == filter || filter->Keep(brief)) { + if (nullptr == filter || filter->Keep(brief)) { out->push_back(brief); } // We increase the count no matter filter passed or not to avoid @@ -1026,7 +1023,7 @@ void DescribeSpanDB(std::ostream& os) { return; } - if (db->id_db != NULL) { + if (db->id_db != nullptr) { std::string val; if (db->id_db->GetProperty(leveldb::Slice("leveldb.stats"), &val)) { os << "[ " << db->id_db_name << " ]\n" << val; @@ -1036,7 +1033,7 @@ void DescribeSpanDB(std::ostream& os) { } } os << '\n'; - if (db->time_db != NULL) { + if (db->time_db != nullptr) { std::string val; if (db->time_db->GetProperty(leveldb::Slice("leveldb.stats"), &val)) { os << "[ " << db->time_db_name << " ]\n" << val; diff --git a/src/brpc/span.h b/src/brpc/span.h index c6b3306cdd..e62357e7b9 100644 --- a/src/brpc/span.h +++ b/src/brpc/span.h @@ -295,7 +295,7 @@ class SpanInfoExtractor { void AnnotateSpan(const char* fmt, ...); // Add an annotation to the given span. -// If the span is NULL, this function does nothing. +// If the span is nullptr, this function does nothing. void AnnotateSpanEx(std::shared_ptr span, const char* fmt, ...); @@ -314,7 +314,7 @@ int FindSpan(uint64_t trace_id, uint64_t span_id, RpczSpan* span); void FindSpans(uint64_t trace_id, std::deque* out); // Put at most `max_scan' spans before `before_this_time' into `out'. -// If filter is not NULL, only push spans that make SpanFilter::Keep() +// If filter is not nullptr, only push spans that make SpanFilter::Keep() // true. void ListSpans(int64_t before_this_time, size_t max_scan, std::deque* out, SpanFilter* filter); diff --git a/src/brpc/stream.cpp b/src/brpc/stream.cpp index c799f2ffe1..8f5ef3c50b 100644 --- a/src/brpc/stream.cpp +++ b/src/brpc/stream.cpp @@ -44,7 +44,7 @@ const static butil::IOBuf *TIMEOUT_TASK = (butil::IOBuf*)-1L; Stream::Stream(Forbidden f) : VersionedRefWithId(f) - , _host_socket(NULL) + , _host_socket(nullptr) , _connected(false) , _error_code(0) , _produced(0) @@ -54,20 +54,20 @@ Stream::Stream(Forbidden f) , _local_consumed(0) , _atomic_local_consumed(0) , _parse_rpc_response(false) - , _pending_buf(NULL) + , _pending_buf(nullptr) , _start_idle_timer_us(0) , _idle_timer(0) { - CHECK_EQ(0, bthread_mutex_init(&_connect_mutex, NULL)); - CHECK_EQ(0, bthread_mutex_init(&_congestion_control_mutex, NULL)); + CHECK_EQ(0, bthread_mutex_init(&_connect_mutex, nullptr)); + CHECK_EQ(0, bthread_mutex_init(&_congestion_control_mutex, nullptr)); } Stream::~Stream() { // Clear pending buffer - if (_pending_buf != NULL) { + if (_pending_buf != nullptr) { delete _pending_buf; - _pending_buf = NULL; + _pending_buf = nullptr; } - CHECK(_host_socket == NULL); + CHECK(_host_socket == nullptr); bthread_mutex_destroy(&_connect_mutex); bthread_mutex_destroy(&_congestion_control_mutex); } @@ -82,7 +82,7 @@ int Stream::Create(const StreamOptions &options, int Stream::OnCreated(const StreamOptions& options, const StreamSettings* remote_settings, bool parse_rpc_response) { - _host_socket = NULL; + _host_socket = nullptr; _connected.store(false, butil::memory_order_relaxed); _options = options; _error_code = 0; @@ -94,7 +94,7 @@ int Stream::OnCreated(const StreamOptions& options, _local_consumed = 0; _atomic_local_consumed.store(0, butil::memory_order_relaxed); _parse_rpc_response = parse_rpc_response; - _pending_buf = NULL; + _pending_buf = nullptr; _start_idle_timer_us = 0; _idle_timer = 0; _remote_settings.Clear(); @@ -109,7 +109,7 @@ int Stream::OnCreated(const StreamOptions& options, _cur_buf_size = _options.min_buf_size; } - if (remote_settings != NULL) { + if (remote_settings != nullptr) { _remote_settings.MergeFrom(*remote_settings); } @@ -150,11 +150,11 @@ void Stream::OnFailed(int error_code, const std::string& error_text) { BAIDU_SCOPED_LOCK(_connect_mutex); if (connected) { RPC_VLOG << "Send close frame"; - CHECK(_host_socket != NULL); + CHECK(_host_socket != nullptr); policy::SendStreamClose( _host_socket, _remote_settings.stream_id(), id()); } - if (_host_socket != NULL) { + if (_host_socket != nullptr) { if (FLAGS_socket_max_streams_unconsumed_bytes > 0) { BAIDU_SCOPED_LOCK(_congestion_control_mutex); if (_socket_unconsumed_size != 0) { @@ -173,22 +173,22 @@ void Stream::OnFailed(int error_code, const std::string& error_text) { } void Stream::BeforeRecycled() { - if (_pending_buf != NULL) { + if (_pending_buf != nullptr) { delete _pending_buf; - _pending_buf = NULL; + _pending_buf = nullptr; } _pending_writes.clear(); bthread_id_list_destroy(&_writable_wait_list); - if (_host_socket != NULL) { + if (_host_socket != nullptr) { DereferenceSocket(_host_socket); - _host_socket = NULL; + _host_socket = nullptr; } } std::string Stream::OnDescription() const { BAIDU_SCOPED_LOCK(_connect_mutex); - if (_host_socket != NULL) { + if (_host_socket != nullptr) { return _host_socket->description(); } else { return "host_socket=NULL"; @@ -197,7 +197,7 @@ std::string Stream::OnDescription() const { int Stream::WritePacked(const butil::IOBuf& data, const StreamWriteOptions* options) { - if (_host_socket == NULL) { + if (_host_socket == nullptr) { CHECK(false) << "Not connected"; errno = EBADF; return -1; @@ -212,7 +212,7 @@ int Stream::WritePacked(const butil::IOBuf& data, } Socket::WriteOptions wopt; - wopt.write_in_background = options != NULL && options->write_in_background; + wopt.write_in_background = options != nullptr && options->write_in_background; // Pack the whole message (splitting large data into multiple STRM frames) // into a SINGLE IOBuf, then hand it to Socket::Write in one shot. @@ -341,7 +341,7 @@ void Stream::SetRemoteConsumed(size_t new_remote_consumed) { } const bool was_full = _produced >= _remote_consumed + _cur_buf_size; - if (FLAGS_socket_max_streams_unconsumed_bytes > 0 && _host_socket != NULL) { + if (FLAGS_socket_max_streams_unconsumed_bytes > 0 && _host_socket != nullptr) { const size_t consumed_delta = new_remote_consumed - _remote_consumed; const size_t accounted_delta = std::min(consumed_delta, _socket_unconsumed_size); @@ -387,7 +387,7 @@ void* Stream::RunOnWritable(void* arg) { WritableMeta *wm = (WritableMeta*)arg; wm->on_writable(wm->id, wm->arg, wm->error_code); delete wm; - return NULL; + return nullptr; } int Stream::TriggerOnWritable(bthread_id_t id, void *data, int error_code) { @@ -436,8 +436,8 @@ void Stream::Wait(void (*on_writable)(StreamId, void*, int), void* arg, if (join_id) { *join_id = wait_id; } - CHECK_EQ(0, bthread_id_lock(wait_id, NULL)); - if (due_time != NULL) { + CHECK_EQ(0, bthread_id_lock(wait_id, nullptr)); + if (due_time != nullptr) { wm->has_timer = true; const int rc = bthread_timer_add(&wm->timer, *due_time, OnTimedOut, @@ -462,7 +462,7 @@ void Stream::Wait(void (*on_writable)(StreamId, void*, int), void* arg, void Stream::Wait(void (*on_writable)(StreamId, void *, int), void *arg, const timespec* due_time) { - return Wait(on_writable, arg, due_time, true, NULL); + return Wait(on_writable, arg, due_time, true, nullptr); } void OnWritable(StreamId, void *arg, int error_code) { @@ -480,7 +480,7 @@ int Stream::Wait(const timespec* due_time) { } void Stream::SetConnected() { - return SetConnected(NULL); + return SetConnected(nullptr); } void Stream::SetConnected(const StreamSettings* remote_settings) { @@ -497,8 +497,8 @@ void Stream::SetConnected(const StreamSettings* remote_settings) { bthread_mutex_unlock(&_connect_mutex); return; } - CHECK(_host_socket != NULL); - if (remote_settings != NULL) { + CHECK(_host_socket != nullptr); + if (remote_settings != nullptr) { CHECK(!_remote_settings.IsInitialized()); _remote_settings.MergeFrom(*remote_settings); } else { @@ -567,7 +567,7 @@ void Stream::SetConnected(const StreamSettings* remote_settings) { } bthread_mutex_unlock(&_connect_mutex); - if (remote_settings == NULL) { + if (remote_settings == nullptr) { // Start the timer at server-side // Client-side timer would triggered in Consume after received the first // message which is the very RPC response @@ -599,7 +599,7 @@ int Stream::OnReceived(const StreamFrameMeta& fm, butil::IOBuf *buf, Socket* soc CHECK(buf->empty()); break; case FRAME_TYPE_DATA: - if (_pending_buf != NULL) { + if (_pending_buf != nullptr) { _pending_buf->append(*buf); buf->clear(); } else { @@ -608,7 +608,7 @@ int Stream::OnReceived(const StreamFrameMeta& fm, butil::IOBuf *buf, Socket* soc } if (!fm.has_continuation()) { butil::IOBuf* tmp = _pending_buf; - _pending_buf = NULL; + _pending_buf = nullptr; int rc = bthread::execution_queue_execute(_consumer_queue, tmp); if (rc != 0) { CHECK(false) << "Fail to push into channel"; @@ -644,7 +644,7 @@ class MessageBatcher { {} ~MessageBatcher() { flush(); } void flush() { - if (_size > 0 && _s->_options.handler != NULL) { + if (_size > 0 && _s->_options.handler != nullptr) { _s->_options.handler->on_received_messages( _s->id(), _storage, _size); } @@ -678,7 +678,7 @@ int Stream::Consume(void *meta, bthread::TaskIterator& iter) { // user callbacks, then release the reference held by the queue (which // was added in OnCreated). This may recycle the instance via // BeforeRecycled(), so do not touch `s' afterwards. - if (s->_options.handler != NULL) { + if (s->_options.handler != nullptr) { int error_code; std::string error_text; { @@ -712,7 +712,7 @@ int Stream::Consume(void *meta, bthread::TaskIterator& iter) { } } } - if (s->_options.handler != NULL) { + if (s->_options.handler != nullptr) { if (has_timeout_task && mb.total_length() == 0) { s->_options.handler->on_idle_timeout(s->id()); } @@ -748,7 +748,7 @@ void Stream::SendFeedback(int64_t _consumed_bytes) { fm.set_source_stream_id(id()); fm.mutable_feedback()->set_consumed_size(_consumed_bytes); butil::IOBuf out; - policy::PackStreamMessage(&out, fm, NULL); + policy::PackStreamMessage(&out, fm, nullptr); WriteToHostSocket(&out); } @@ -757,7 +757,7 @@ int Stream::SetHostSocket(Socket* host_socket) { if (Failed()) { return -1; } - if (_host_socket != NULL) { + if (_host_socket != nullptr) { return 0; } @@ -775,7 +775,7 @@ int Stream::SetHostSocket(Socket* host_socket) { void Stream::FillSettings(StreamSettings *settings) { settings->set_stream_id(id()); settings->set_need_feedback(_cur_buf_size > 0); - settings->set_writable(_options.handler != NULL); + settings->set_writable(_options.handler != nullptr); } void OnIdleTimeout(void *arg) { @@ -855,16 +855,16 @@ int Stream::SetFailed(const StreamIds& ids, int error_code, const char* reason_f void Stream::HandleRpcResponse(butil::IOBuf* response_buffer) { CHECK(!_remote_settings.IsInitialized()); - CHECK(_host_socket != NULL); + CHECK(_host_socket != nullptr); std::unique_ptr buf_guard(response_buffer); - ParseResult pr = policy::ParseRpcMessage(response_buffer, NULL, true, NULL); + ParseResult pr = policy::ParseRpcMessage(response_buffer, nullptr, true, nullptr); if (!pr.is_ok()) { CHECK(false); Close(EPROTO, "Fail to parse rpc response message"); return; } InputMessageBase* msg = pr.message(); - if (msg == NULL) { + if (msg == nullptr) { CHECK(false); Close(ENOMEM, "Message is NULL"); return; @@ -873,7 +873,7 @@ void Stream::HandleRpcResponse(butil::IOBuf* response_buffer) { _host_socket->ReAddress(&msg->_socket); msg->_received_us = butil::gettimeofday_us(); msg->_base_real_us = butil::gettimeofday_us(); - msg->_arg = NULL; // ProcessRpcResponse() don't need arg + msg->_arg = nullptr; // ProcessRpcResponse() don't need arg policy::ProcessRpcResponse(msg); } @@ -930,7 +930,7 @@ int StreamClose(StreamId stream_id) { int StreamCreate(StreamId *request_stream, Controller &cntl, const StreamOptions* options) { - if (request_stream == NULL) { + if (request_stream == nullptr) { LOG(ERROR) << "request_stream is NULL"; return -1; } @@ -954,13 +954,13 @@ int StreamCreate(StreamIds& request_streams, int request_stream_size, Controller return -1; } StreamOptions opt; - if (options != NULL) { + if (options != nullptr) { opt = *options; } for (auto i = 0; i < request_stream_size; ++i) { StreamId stream_id; bool parse_rpc_response = (i == 0); // Only the first stream need parse rpc - if (Stream::Create(opt, NULL, &stream_id, parse_rpc_response) != 0) { + if (Stream::Create(opt, nullptr, &stream_id, parse_rpc_response) != 0) { // Close already created streams Stream::SetFailed(request_streams, 0 , "Fail to create stream at %d index", i); LOG(ERROR) << "Fail to create stream"; @@ -974,7 +974,7 @@ int StreamCreate(StreamIds& request_streams, int request_stream_size, Controller int StreamAccept(StreamId* response_stream, Controller &cntl, const StreamOptions* options) { - if (response_stream == NULL) { + if (response_stream == nullptr) { LOG(ERROR) << "response_stream is NULL"; return -1; } @@ -1010,7 +1010,7 @@ int StreamAccept(StreamIds& response_streams, Controller& cntl, return -1; } StreamOptions opt; - if (options != NULL) { + if (options != nullptr) { opt = *options; } StreamId stream_id; diff --git a/src/brpc/stream.h b/src/brpc/stream.h index 73e7aff52f..febc4cde76 100644 --- a/src/brpc/stream.h +++ b/src/brpc/stream.h @@ -59,7 +59,7 @@ struct StreamOptions { , max_buf_size(2 * 1024 * 1024) , idle_timeout_ms(-1) , messages_in_batch(128) - , handler(NULL) + , handler(nullptr) {} // stream max buffer size limit in [min_buf_size, max_buf_size] @@ -82,9 +82,9 @@ struct StreamOptions { // default: 128 size_t messages_in_batch; - // Handle input message, if handler is NULL, the remote side is not allowed to + // Handle input message, if handler is nullptr, the remote side is not allowed to // write any message, who will get EBADF on writting - // default: NULL + // default: nullptr StreamInputHandler* handler; }; @@ -102,7 +102,7 @@ struct StreamWriteOptions { // [Called at the client side] // Create a stream at client-side along with the |cntl|, which will be connected // when receiving the response with a stream from server-side. If |options| is -// NULL, the stream will be created with default options +// nullptr, the stream will be created with default options // Return 0 on success, -1 otherwise int StreamCreate(StreamId* request_stream, Controller &cntl, const StreamOptions* options); @@ -110,7 +110,7 @@ int StreamCreate(StreamId* request_stream, Controller &cntl, // [Called at the client side for creating multiple streams] // Create streams at client-side along with the |cntl|, which will be connected // when receiving the response with streams from server-side. If |options| is -// NULL, the stream will be created with default options +// nullptr, the stream will be created with default options // Return 0 on success, -1 otherwise int StreamCreate(StreamIds& request_streams, int request_stream_size, Controller& cntl, const StreamOptions* options); @@ -136,13 +136,13 @@ int StreamAccept(StreamIds& response_stream, Controller& cntl, // which the remote side hasn't consumed yet excceeds the number. // - EINVAL: |stream_id| is invalied or has been closed int StreamWrite(StreamId stream_id, const butil::IOBuf& message, - const StreamWriteOptions* options = NULL); + const StreamWriteOptions* options = nullptr); // Write util the pending buffer size is less than |max_buf_size| or orrur // occurs // Returns 0 on success, errno otherwise // Errno: -// - ETIMEDOUT: when |due_time| is not NULL and time expired this +// - ETIMEDOUT: when |due_time| is not nullptr and time expired this // - EINVAL: the stream was close during waiting int StreamWait(StreamId stream_id, const timespec* due_time); diff --git a/src/brpc/stream_creator.h b/src/brpc/stream_creator.h index 1bc2f0724a..d8a1f44b44 100644 --- a/src/brpc/stream_creator.h +++ b/src/brpc/stream_creator.h @@ -67,7 +67,7 @@ class StreamUserData { // of StreamCreator has returned a valid StreamUserData pointer. // Params: // sending_sock: The socket chosen by OnCreatingStream(), if an error - // happens during choosing, the enclosed socket is NULL. + // happens during choosing, the enclosed socket is nullptr. // cntl: contexts of the RPC. // error_code: Use this instead of cntl->ErrorCode(). // end_of_rpc: true if the RPC is about to destroyed. diff --git a/src/brpc/stream_impl.h b/src/brpc/stream_impl.h index f9ae065dab..06e5044859 100644 --- a/src/brpc/stream_impl.h +++ b/src/brpc/stream_impl.h @@ -45,7 +45,7 @@ class BAIDU_CACHELINE_ALIGNMENT Stream : public VersionedRefWithId { // Write `msg' into this stream. Returns 0 on success, 1 when the stream is // full, -1 on error. int AppendIfNotFull(const butil::IOBuf& msg, - const StreamWriteOptions* options = NULL); + const StreamWriteOptions* options = nullptr); static int Create(const StreamOptions& options, const StreamSettings* remote_settings, StreamId *id, bool parse_rpc_response = true); @@ -128,7 +128,7 @@ friend class VersionedRefWithId; PendingWrite() = default; explicit PendingWrite(const butil::IOBuf& d, const StreamWriteOptions* opts) : data(d) { - if (opts != NULL) { + if (opts != nullptr) { options = *opts; } } diff --git a/src/brpc/tcp_transport.cpp b/src/brpc/tcp_transport.cpp index 27e6ae87be..98fea81674 100644 --- a/src/brpc/tcp_transport.cpp +++ b/src/brpc/tcp_transport.cpp @@ -28,7 +28,7 @@ void TcpTransport::Init(Socket* socket, const SocketOptions& options) { _socket = socket; _default_connect = options.app_connect; _on_edge_trigger = options.on_edge_triggered_events; - if (options.need_on_edge_trigger && _on_edge_trigger == NULL) { + if (options.need_on_edge_trigger && _on_edge_trigger == nullptr) { _on_edge_trigger = InputMessenger::OnNewMessages; } } diff --git a/src/brpc/thrift_message.cpp b/src/brpc/thrift_message.cpp index 9265ed9685..d9309c3474 100644 --- a/src/brpc/thrift_message.cpp +++ b/src/brpc/thrift_message.cpp @@ -49,7 +49,7 @@ void ThriftFramedMessage::Clear() { if (_own_raw_instance) { delete _raw_instance; _own_raw_instance = false; - _raw_instance = NULL; + _raw_instance = nullptr; } } @@ -88,7 +88,7 @@ void ThriftStub::CallMethod(const char* method_name, ThriftFramedMessage* res, ::google::protobuf::Closure* done) { cntl->_thrift_method_name.assign(method_name); - _channel->CallMethod(NULL, cntl, req, res, done); + _channel->CallMethod(nullptr, cntl, req, res, done); } } // namespace brpc diff --git a/src/brpc/thrift_message.h b/src/brpc/thrift_message.h index e31c941968..1502f35f1b 100644 --- a/src/brpc/thrift_message.h +++ b/src/brpc/thrift_message.h @@ -127,7 +127,7 @@ namespace details { template class ThriftMessageWrapper final : public ThriftMessageBase { public: - ThriftMessageWrapper() : msg_ptr(NULL) {} + ThriftMessageWrapper() : msg_ptr(nullptr) {} ThriftMessageWrapper(T* msg2) : msg_ptr(msg2) {} virtual ~ThriftMessageWrapper() {} // NOTE: "T::" makes the function call work around vtable @@ -204,20 +204,20 @@ void ThriftStub::CallMethod(const char* method_name, ThriftFramedMessage request; request._raw_instance = &raw_request_wrapper; - if (done == NULL) { + if (done == nullptr) { // response is guaranteed to be unused after a synchronous RPC, no // need to allocate it on heap. ThriftFramedMessage response; details::ThriftMessageWrapper raw_response_wrapper(raw_response); response._raw_instance = &raw_response_wrapper; - _channel->CallMethod(NULL, cntl, &request, &response, NULL); + _channel->CallMethod(nullptr, cntl, &request, &response, nullptr); } else { // Let the new_done own the response and release it after Run(). details::ThriftDoneWrapper* new_done = new details::ThriftDoneWrapper(done); new_done->raw_response_wrapper.msg_ptr = raw_response; new_done->response._raw_instance = &new_done->raw_response_wrapper; - _channel->CallMethod(NULL, cntl, &request, &new_done->response, new_done); + _channel->CallMethod(nullptr, cntl, &request, &new_done->response, new_done); } } diff --git a/src/brpc/thrift_service.cpp b/src/brpc/thrift_service.cpp index 24b2439024..1ed1450b07 100644 --- a/src/brpc/thrift_service.cpp +++ b/src/brpc/thrift_service.cpp @@ -28,7 +28,7 @@ ThriftService::ThriftService() { ThriftService::~ThriftService() { delete _status; - _status = NULL; + _status = nullptr; } void ThriftService::Describe(std::ostream &os, const DescribeOptions&) const { @@ -36,7 +36,7 @@ void ThriftService::Describe(std::ostream &os, const DescribeOptions&) const { } void ThriftService::Expose(const butil::StringPiece& prefix) { - if (_status == NULL) { + if (_status == nullptr) { return; } std::string s; diff --git a/src/brpc/traceprintf.h b/src/brpc/traceprintf.h index 47a8dcf33a..f1fd305b53 100644 --- a/src/brpc/traceprintf.h +++ b/src/brpc/traceprintf.h @@ -52,7 +52,7 @@ void AnnotateSpanEx(std::shared_ptr span, const char* fmt, ...); // Use this macro to print log to a specific span. -// If span_ptr is NULL, arguments to this macro is NOT evaluated. +// If span_ptr is nullptr, arguments to this macro is NOT evaluated. #define TRACEPRINTF_SPAN(span_ptr, fmt, args...) \ do { \ if ((span_ptr)) { \ diff --git a/src/brpc/trackme.cpp b/src/brpc/trackme.cpp index 4decc35269..b006ebc891 100644 --- a/src/brpc/trackme.cpp +++ b/src/brpc/trackme.cpp @@ -45,9 +45,9 @@ static int32_t s_trackme_interval = TRACKME_MIN_INTERVAL; // Protecting global vars on trackme static pthread_mutex_t s_trackme_mutex = PTHREAD_MUTEX_INITIALIZER; // For contacting with trackme_server. -static Channel* s_trackme_chan = NULL; +static Channel* s_trackme_chan = nullptr; // Any server address in this process. -static std::string* s_trackme_addr = NULL; +static std::string* s_trackme_addr = nullptr; // Information of bugs. // Notice that this structure may be a combination of all affected bugs. @@ -63,7 +63,7 @@ struct BugInfo { }; // If a bug was shown, its info was stored in this var as well so that we // can avoid showing the same bug repeatly. -static BugInfo* g_bug_info = NULL; +static BugInfo* g_bug_info = nullptr; // The timestamp(microseconds) that we sent TrackMeRequest. static int64_t s_trackme_last_time = 0; @@ -81,14 +81,14 @@ const int64_t g_rpc_version = 0; int ReadJPaasHostPort(int container_port) { const uid_t uid = getuid(); struct passwd* pw = getpwuid(uid); - if (pw == NULL) { + if (pw == nullptr) { RPC_VLOG << "Fail to get password file entry of uid=" << uid; return -1; } char JPAAS_LOG_PATH[64]; snprintf(JPAAS_LOG_PATH, sizeof(JPAAS_LOG_PATH), "%s/jpaas_run/logs/env.log", pw->pw_dir); - char* line = NULL; + char* line = nullptr; size_t line_len = 0; ssize_t nr = 0; butil::ScopedFILE fp(fopen(JPAAS_LOG_PATH, "r")); @@ -105,7 +105,7 @@ int ReadJPaasHostPort(int container_port) { --nr; } if (nr > prefix_len && memcmp(line, prefix, prefix_len) == 0) { - host_port = strtol(line + prefix_len, NULL, 10); + host_port = strtol(line + prefix_len, nullptr, 10); break; } } @@ -117,7 +117,7 @@ int ReadJPaasHostPort(int container_port) { // Called in server.cpp void SetTrackMeAddress(butil::EndPoint pt) { BAIDU_SCOPED_LOCK(s_trackme_mutex); - if (s_trackme_addr == NULL) { + if (s_trackme_addr == nullptr) { // JPAAS has NAT capabilities, read its log to figure out the open port // accessible from outside. const int jpaas_port = ReadJPaasHostPort(pt.port); @@ -140,12 +140,12 @@ static void HandleTrackMeResponse(Controller* cntl, TrackMeResponse* res) { bool already_reported = false; { BAIDU_SCOPED_LOCK(s_trackme_mutex); - if (g_bug_info != NULL && *g_bug_info == cur_info) { + if (g_bug_info != nullptr && *g_bug_info == cur_info) { // we've shown the bug. already_reported = true; } else { // save the bug. - if (g_bug_info == NULL) { + if (g_bug_info == nullptr) { g_bug_info = new BugInfo(cur_info); } else { *g_bug_info = cur_info; @@ -187,15 +187,11 @@ static void HandleTrackMeResponse(Controller* cntl, TrackMeResponse* res) { } static void TrackMeNow(std::unique_lock& mu) { - if (s_trackme_addr == NULL) { + if (s_trackme_addr == nullptr) { return; } - if (s_trackme_chan == NULL) { - Channel* chan = new (std::nothrow) Channel; - if (chan == NULL) { - LOG(FATAL) << "Fail to new trackme channel"; - return; - } + if (s_trackme_chan == nullptr) { + Channel* chan = new Channel; ChannelOptions opt; // keep #connections on server-side low opt.connection_type = CONNECTION_TYPE_SHORT; diff --git a/src/brpc/transport.h b/src/brpc/transport.h index a2cb868b89..edef24879c 100644 --- a/src/brpc/transport.h +++ b/src/brpc/transport.h @@ -31,13 +31,13 @@ class Transport { SocketUniquePtr s(static_cast(arg)); const OnEdgeTrigger on_edge_trigger = s->_transport->GetOnEdgeTrigger(); on_edge_trigger(s.get()); - return NULL; + return nullptr; } static void* ProcessInputMessage(void* void_arg) { InputMessageBase* msg = static_cast(void_arg); msg->_process(msg); - return NULL; + return nullptr; } virtual ~Transport() = default; virtual void Init(Socket* socket, const SocketOptions& options) = 0; @@ -52,7 +52,7 @@ class Transport { virtual void Debug(std::ostream &os) = 0; bool HasOnEdgeTrigger() { - return _on_edge_trigger != NULL; + return _on_edge_trigger != nullptr; } OnEdgeTrigger GetOnEdgeTrigger() { return _on_edge_trigger; diff --git a/src/brpc/ts.cpp b/src/brpc/ts.cpp index ebefe538ff..804aa32900 100644 --- a/src/brpc/ts.cpp +++ b/src/brpc/ts.cpp @@ -230,7 +230,7 @@ TsChannel* TsChannelGroup::get(TsPid pid) { // if (it != _pids.end()) { // return &it->second; // } - // return NULL; + // return nullptr; } TsChannel* TsChannelGroup::set(TsPid pid) { @@ -251,8 +251,8 @@ TsPacket::TsPacket(TsChannelGroup* g) , _transport_scrambling_control(TS_SCRAMBLED_DISABLED) , _adaptation_field_control(TS_AF_RESERVED) , _continuity_counter(0) - , _adaptation_field(NULL) - , _payload(NULL) + , _adaptation_field(nullptr) + , _payload(nullptr) , _tschan_group(g) { } @@ -263,9 +263,9 @@ TsPacket::~TsPacket() { void TsPacket::Reset() { delete _payload; - _payload = NULL; + _payload = nullptr; delete _adaptation_field; - _adaptation_field = NULL; + _adaptation_field = nullptr; _transport_error_indicator = 0; _payload_unit_start_indicator = 0; _transport_priority = 0; @@ -273,12 +273,12 @@ void TsPacket::Reset() { _transport_scrambling_control = TS_SCRAMBLED_DISABLED; _adaptation_field_control = TS_AF_RESERVED; _continuity_counter = 0; - _payload = NULL; + _payload = nullptr; _modified = false; } TsAdaptationField* TsPacket::CreateAdaptationField() { - if (_adaptation_field != NULL) { + if (_adaptation_field != nullptr) { LOG(ERROR) << "_adaptation_field is not NULL"; return _adaptation_field; } @@ -345,7 +345,7 @@ int TsPacket::Encode(void* data) const { } void TsPacket::AddPadding(size_t num_stuffings) { - const bool no_af_before = (_adaptation_field == NULL); + const bool no_af_before = (_adaptation_field == nullptr); TsAdaptationField* af = mutable_adaptation_field(); if (no_af_before) { const size_t sz = af->ByteSize(); @@ -487,7 +487,7 @@ TsAdaptationField::TsAdaptationField() , original_program_clock_reference_extension(0) , splice_countdown(0) , transport_private_data_length(0) - , transport_private_data(NULL) + , transport_private_data(nullptr) , adaptation_field_extension_length(0) , ltw_flag(0) , piecewise_rate_flag(0) @@ -611,9 +611,9 @@ TsPayload::~TsPayload() {} TsPayloadPES::TsPayloadPES(const TsPacket* p) : TsPayload(p) { _PES_header_data_length = -1; - PES_private_data = NULL; - pack_field = NULL; - PES_extension_field = NULL; + PES_private_data = nullptr; + pack_field = nullptr; + PES_extension_field = nullptr; nb_stuffings = 0; nb_bytes = 0; nb_paddings = 0; @@ -889,7 +889,7 @@ TsPayloadPMTESInfo::TsPayloadPMTESInfo(TsStream st, TsPid epid) : stream_type(st) , elementary_PID(epid) , ES_info_length(0) - , ES_info(NULL) { + , ES_info(nullptr) { } TsPayloadPMTESInfo::~TsPayloadPMTESInfo() { @@ -923,7 +923,7 @@ int TsPayloadPMTESInfo::Encode(void* data) const { TsPayloadPMT::TsPayloadPMT(const TsPacket* p) : TsPayloadPSI(p) , program_info_length(0) - , program_info_desc(NULL) { + , program_info_desc(nullptr) { } TsPayloadPMT::~TsPayloadPMT() { @@ -1281,7 +1281,7 @@ butil::Status TsWriter::Write(const RtmpVideoMessage& msg) { butil::IOBuf nalus; bool has_idr = false; for (AVCNaluIterator it(&avc_msg.data, _avc_seq_header.length_size_minus1, - &_nalu_format); it != NULL; ++it) { + &_nalu_format); it != nullptr; ++it) { // ignore SPS/PPS/AUD switch (it.nalu_type()) { case AVC_NALU_IDR: @@ -1414,7 +1414,7 @@ butil::Status TsWriter::EncodePES(TsMessage* msg, TsStream sid, TsPid pid, } TsChannel* channel = _tschan_group.get(pid); - if (channel == NULL) { + if (channel == nullptr) { return butil::Status(EINVAL, "Fail to get channel on pid=%d", (int)pid); } diff --git a/src/brpc/ubshm_transport.cpp b/src/brpc/ubshm_transport.cpp index fec1a4b646..df4eb36bed 100644 --- a/src/brpc/ubshm_transport.cpp +++ b/src/brpc/ubshm_transport.cpp @@ -29,15 +29,9 @@ DECLARE_bool(usercode_in_pthread); extern SocketVarsCollector *g_vars; void UBShmTransport::Init(Socket *socket, const SocketOptions &options) { - CHECK(_ub_ep == NULL); + CHECK(_ub_ep == nullptr); if (options.socket_mode == SOCKET_MODE_UBRING) { - _ub_ep = new(std::nothrow)ubring::UBShmEndpoint(socket); - if (!_ub_ep) { - const int saved_errno = errno; - PLOG(ERROR) << "Fail to create UBShmEndpoint"; - socket->SetFailed( - saved_errno, "Fail to create UBShmEndpoint: %s", berror(saved_errno)); - } + _ub_ep = new ubring::UBShmEndpoint(socket); _ub_state = UB_UNKNOWN; } else { _ub_state = UB_OFF; @@ -46,7 +40,7 @@ void UBShmTransport::Init(Socket *socket, const SocketOptions &options) { _socket = socket; _default_connect = options.app_connect; _on_edge_trigger = options.on_edge_triggered_events; - if (options.need_on_edge_trigger && _on_edge_trigger == NULL) { + if (options.need_on_edge_trigger && _on_edge_trigger == nullptr) { _on_edge_trigger = ubring::UBShmEndpoint::OnNewDataFromTcp; } _tcp_transport = std::make_shared(); @@ -56,7 +50,7 @@ void UBShmTransport::Init(Socket *socket, const SocketOptions &options) { void UBShmTransport::Release() { if (_ub_ep) { delete _ub_ep; - _ub_ep = NULL; + _ub_ep = nullptr; _ub_state = UB_UNKNOWN; } } @@ -98,7 +92,7 @@ int UBShmTransport::WaitEpollOut(butil::atomic *_epollout_butex, if (_ub_state == UB_ON) { // LOG(INFO) << "mwj pollin1=" << pollin; const int expected_val = _epollout_butex->load(butil::memory_order_acquire); - CHECK(_ub_ep != NULL); + CHECK(_ub_ep != nullptr); if (!_ub_ep->IsWritable()) { g_vars->nwaitepollout << 1; _ub_ep->PollerRegisterEpollOut(pollin); diff --git a/src/brpc/ubshm_transport.h b/src/brpc/ubshm_transport.h index 13943d763e..b3d1e7c518 100644 --- a/src/brpc/ubshm_transport.h +++ b/src/brpc/ubshm_transport.h @@ -39,7 +39,7 @@ friend class ubring::UBConnect; void QueueMessage(InputMessageClosure& inputMsg, int* num_bthread_created, bool last_msg) override; void Debug(std::ostream &os) override; ubring::UBShmEndpoint* GetUBShmEp() { - CHECK(_ub_ep != NULL); + CHECK(_ub_ep != nullptr); return _ub_ep; } static int ContextInitOrDie(bool serverOrNot, const void* _options); @@ -54,7 +54,7 @@ friend class ubring::UBConnect; UB_UNKNOWN }; // The UBShmEndpoint - ubring::UBShmEndpoint* _ub_ep = NULL; + ubring::UBShmEndpoint* _ub_ep = nullptr; // Should use UB or not UBState _ub_state; std::shared_ptr _tcp_transport; diff --git a/src/brpc/uri.h b/src/brpc/uri.h index f8d551ca3c..7edac4002d 100644 --- a/src/brpc/uri.h +++ b/src/brpc/uri.h @@ -103,7 +103,7 @@ class URI { void SetH2Path(const std::string& path) { SetH2Path(path.c_str()); } // Get the value of a CASE-SENSITIVE key. - // Returns pointer to the value, NULL when the key does not exist. + // Returns pointer to the value, nullptr when the key does not exist. const std::string* GetQuery(const char* key) const { return get_query_map().seek(key); } const std::string* GetQuery(const std::string& key) const @@ -157,7 +157,7 @@ friend class HttpMessage; mutable QueryMap _query_map; }; -// Parse host/port/scheme from `url' if the corresponding parameter is not NULL. +// Parse host/port/scheme from `url' if the corresponding parameter is not nullptr. // Returns 0 on success, -1 otherwise. int ParseURL(const char* url, std::string* scheme, std::string* host, int* port); diff --git a/src/brpc/versioned_ref_with_id.h b/src/brpc/versioned_ref_with_id.h index 3793e2185e..b7213c3492 100644 --- a/src/brpc/versioned_ref_with_id.h +++ b/src/brpc/versioned_ref_with_id.h @@ -279,7 +279,7 @@ class VersionedRefWithId { // Mark this VersionedRefWithId or the VersionedRefWithId associated // with `id' as failed. - // Any later Address() of the identifier shall return NULL. The + // Any later Address() of the identifier shall return nullptr. The // VersionedRefWithId is NOT recycled after calling this function, // instead it will be recycled when no one references it. Internal // fields of the object are still accessible after calling this @@ -401,7 +401,7 @@ template int VersionedRefWithId::Create(VRefId* id, Args&&... args) { resource_id_t slot; T* const t = butil::get_resource(&slot, Forbidden()); - if (t == NULL) { + if (t == nullptr) { LOG(FATAL) << "Fail to get_resource<" << butil::class_name() << ">"; return -1; @@ -446,7 +446,7 @@ int VersionedRefWithId::AddressImpl( VRefId id, bool failed_as_well, VersionedRefWithIdUniquePtr* ptr) { const resource_id_t slot = SlotOfVRefId(id); T* const t = address_resource(slot); - if (__builtin_expect(t != NULL, 1)) { + if (__builtin_expect(t != nullptr, 1)) { // acquire fence makes sure this thread sees latest changes before // Dereference() or Revive(). VersionedRefWithId* const vref_with_id = t; @@ -528,7 +528,7 @@ int VersionedRefWithId::SetFailedImpl(Args&&... args) { if (VersionOfVRef(vref) != id_ver) { return -1; } - // Try to set version=id_ver+1 (to make later address() return NULL), + // Try to set version=id_ver+1 (to make later address() return nullptr), // retry on fail. if (_versioned_ref.compare_exchange_strong( vref, MakeVRef(id_ver + 1, NRefOfVRef(vref)),