1 // Copyright 2021 The Abseil Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef ABSL_STRINGS_INTERNAL_CORDZ_UPDATE_SCOPE_H_ 16 #define ABSL_STRINGS_INTERNAL_CORDZ_UPDATE_SCOPE_H_ 17 18 #include "absl/base/config.h" 19 #include "absl/base/optimization.h" 20 #include "absl/base/thread_annotations.h" 21 #include "absl/strings/internal/cord_internal.h" 22 #include "absl/strings/internal/cordz_info.h" 23 #include "absl/strings/internal/cordz_update_tracker.h" 24 25 namespace absl { 26 ABSL_NAMESPACE_BEGIN 27 namespace cord_internal { 28 29 // CordzUpdateScope scopes an update to the provided CordzInfo. 30 // The class invokes `info->Lock(method)` and `info->Unlock()` to guard 31 // cordrep updates. This class does nothing if `info` is null. 32 // See also the 'Lock`, `Unlock` and `SetCordRep` methods in `CordzInfo`. 33 class ABSL_SCOPED_LOCKABLE CordzUpdateScope { 34 public: CordzUpdateScope(CordzInfo * info,CordzUpdateTracker::MethodIdentifier method)35 CordzUpdateScope(CordzInfo* info, CordzUpdateTracker::MethodIdentifier method) 36 ABSL_EXCLUSIVE_LOCK_FUNCTION(info) 37 : info_(info) { 38 if (ABSL_PREDICT_FALSE(info_)) { 39 info->Lock(method); 40 } 41 } 42 43 // CordzUpdateScope can not be copied or assigned to. 44 CordzUpdateScope(CordzUpdateScope&& rhs) = delete; 45 CordzUpdateScope(const CordzUpdateScope&) = delete; 46 CordzUpdateScope& operator=(CordzUpdateScope&& rhs) = delete; 47 CordzUpdateScope& operator=(const CordzUpdateScope&) = delete; 48 ABSL_UNLOCK_FUNCTION()49 ~CordzUpdateScope() ABSL_UNLOCK_FUNCTION() { 50 if (ABSL_PREDICT_FALSE(info_)) { 51 info_->Unlock(); 52 } 53 } 54 SetCordRep(CordRep * rep)55 void SetCordRep(CordRep* rep) const { 56 if (ABSL_PREDICT_FALSE(info_)) { 57 info_->SetCordRep(rep); 58 } 59 } 60 info()61 CordzInfo* info() const { return info_; } 62 63 private: 64 CordzInfo* info_; 65 }; 66 67 } // namespace cord_internal 68 ABSL_NAMESPACE_END 69 } // namespace absl 70 71 #endif // ABSL_STRINGS_INTERNAL_CORDZ_UPDATE_SCOPE_H_ 72