1 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 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 http://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 16 #ifndef TENSORFLOW_COMPILER_XLA_SERVICE_NAME_UNIQUER_H_ 17 #define TENSORFLOW_COMPILER_XLA_SERVICE_NAME_UNIQUER_H_ 18 19 #include <string> 20 #include <unordered_map> 21 22 #include "tensorflow/compiler/xla/types.h" 23 #include "tensorflow/core/lib/core/stringpiece.h" 24 #include "tensorflow/core/platform/macros.h" 25 26 namespace xla { 27 28 // Simple stateful class that helps generate "unique" names. To use it, simply 29 // call GetUniqueName as many times as needed. The names returned by 30 // GetUniqueName are guaranteed to be distinct for this instance of the class. 31 // Note that the names will be sanitized to match regexp 32 // "[a-zA-Z_][a-zA-Z0-9_.-]*". 33 class NameUniquer { 34 public: 35 // The separator must contain allowed characters only: "[a-zA-Z0-9_.-]". 36 explicit NameUniquer(const string& separator = "__"); 37 38 // Get a sanitized unique name in a string, with an optional prefix for 39 // convenience. 40 string GetUniqueName(tensorflow::StringPiece prefix = ""); 41 42 // Sanitizes and returns the name. Unallowed characters will be replaced with 43 // '_'. The result will match the regexp "[a-zA-Z_][a-zA-Z0-9_.-]*". 44 static string GetSanitizedName(const string& name); 45 46 private: 47 // The string to use to separate the prefix of the name from the uniquing 48 // integer value. 49 string separator_; 50 51 // Map from name prefix to the number of names generated using that prefix 52 // so far. 53 std::unordered_map<string, int64> generated_names_; 54 55 TF_DISALLOW_COPY_AND_ASSIGN(NameUniquer); 56 }; 57 58 } // namespace xla 59 60 #endif // TENSORFLOW_COMPILER_XLA_SERVICE_NAME_UNIQUER_H_ 61