Panda3D
nameUniquifier.cxx
Go to the documentation of this file.
1 /**
2  * PANDA 3D SOFTWARE
3  * Copyright (c) Carnegie Mellon University. All rights reserved.
4  *
5  * All use of this software is subject to the terms of the revised BSD
6  * license. You should have received a copy of this license along
7  * with this source code in a file named "LICENSE."
8  *
9  * @file nameUniquifier.cxx
10  * @author drose
11  * @date 2000-02-16
12  */
13 
14 #include "nameUniquifier.h"
15 
16 #include "pnotify.h"
17 
18 #include <stdio.h>
19 
20 using std::string;
21 
22 
23 /**
24  * Creates a new NameUniquifier.
25  *
26  * The separator string is used to separate the original name (or supplied
27  * prefix) and the generated number when a name must be generated.
28  *
29  * If the original name is empty, the empty string is used, followed by the
30  * generated number.
31  */
33 NameUniquifier(const string &separator,
34  const string &empty) :
35  _separator(separator),
36  _empty(empty)
37 {
38  _counter = 0;
39 
40  if (_empty.empty()) {
41  _empty = _separator;
42  }
43 }
44 
45 /**
46  *
47  */
48 NameUniquifier::
49 ~NameUniquifier() {
50 }
51 
52 /**
53  * The actual implementation of the two flavors of add_name().
54  *
55  * If name is nonempty and so far unique, returns it unchanged.
56  *
57  * Otherwise, generates and returns a new name according to the following
58  * rules:
59  *
60  * If the prefix is empty, the new name is the NameUniquifier's "empty" string
61  * followed by a number, or the "separator" string if the "empty" string is
62  * empty.
63  *
64  * If the prefix is nonempty, the new name is the prefix, followed by the
65  * NameUniquifier's "separator" string, followed by a number.
66  */
67 string NameUniquifier::
68 add_name_body(const string &name, const string &prefix) {
69  if (!name.empty()) {
70  if (_names.insert(name).second) {
71  // The name was successfully inserted into the set; therefore, it's
72  // unique. Return it.
73  return name;
74  }
75  }
76 
77  // The name was not successfully inserted; there must be another one
78  // already. Make up a new one.
79 
80  // Keep trying to make up names until we make one that's unique.
81  string temp_name;
82  do {
83  static const int max_len = 16;
84  char num_str[max_len];
85  sprintf(num_str, "%d", ++_counter);
86  nassertr((int)strlen(num_str) <= max_len, "");
87 
88  if (prefix.empty()) {
89  temp_name = _empty + num_str;
90  } else {
91  temp_name = prefix + _separator + num_str;
92  }
93  } while (!_names.insert(temp_name).second);
94 
95  return temp_name;
96 }
PANDA 3D SOFTWARE Copyright (c) Carnegie Mellon University.
PANDA 3D SOFTWARE Copyright (c) Carnegie Mellon University.
NameUniquifier(const std::string &separator=std::string(), const std::string &empty=std::string())
Creates a new NameUniquifier.