KiCad PCB EDA Suite
Loading...
Searching...
No Matches
kiid.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2020 Ian McInerney <[email protected]>
5 * Copyright (C) 2007-2014 Jean-Pierre Charras, jp.charras at wanadoo.fr
6 * Copyright The KiCad Developers, see AUTHORS.TXT for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, you may find one here:
20 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
21 * or you may search the http://www.gnu.org website for the version 2 license,
22 * or you may write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 */
25
26#include <kiid.h>
27
28#include <boost/random/mersenne_twister.hpp>
29#include <boost/uuid/uuid_generators.hpp>
30#include <boost/uuid/uuid_io.hpp>
31
32#if BOOST_VERSION >= 106700
33#include <boost/uuid/entropy_error.hpp>
34#endif
35
36#include <json_common.h>
37
38#include <cctype>
39#include <mutex>
40#include <utility>
41#include <stdlib.h>
42
43#include <wx/log.h>
44
45// boost:mt19937 is not thread-safe
46static std::mutex rng_mutex;
47
48// Static rng and generators are used because the overhead of constant seeding is expensive
49// We rely on the default non-arg constructor of basic_random_generator to provide a random seed.
50// We use a separate rng object for cases where we want to control the basic_random_generator
51// initial seed by calling SeedGenerator from unit tests and other special cases.
52static boost::mt19937 rng;
53static boost::uuids::basic_random_generator<boost::mt19937> randomGenerator;
54
55// These don't have the same performance penalty, but we might as well be consistent
56static boost::uuids::string_generator stringGenerator;
57static boost::uuids::nil_generator nilGenerator;
58
59
60// Global nil reference
62
63
64// When true, always create nil uuids for performance, when valid ones aren't needed.
65// Thread-local to prevent background library loading from affecting other threads.
66static thread_local bool g_createNilUuids = false;
67
68
69// For static initialization
71{
72 static KIID nil( 0 );
73 return nil;
74}
75
76
78{
79#if BOOST_VERSION >= 106700
80 try
81 {
82#endif
83
85 {
87 }
88 else
89 {
90 std::lock_guard<std::mutex> lock( rng_mutex );
92 }
93
94#if BOOST_VERSION >= 106700
95 }
96 catch( const boost::uuids::entropy_error& )
97 {
98 wxLogFatalError( "A Boost UUID entropy exception was thrown in %s:%s.",
99 __FILE__, __FUNCTION__ );
100 }
101#endif
102}
103
104
105KIID::KIID( int null ) :
107{
108 wxASSERT( null == 0 );
109}
110
111
112KIID::KIID( const std::string& aString ) :
113 m_uuid()
114{
115 if( !aString.empty() && aString.length() <= 8
116 && std::all_of( aString.begin(), aString.end(),
117 []( unsigned char c )
118 {
119 return std::isxdigit( c );
120 } ) )
121 {
122 // A legacy-timestamp-based UUID has only the last 4 octets filled in.
123 // Convert them individually to avoid stepping in the little-endian/big-endian
124 // doo-doo.
125 for( int i = 0; i < 4; i++ )
126 {
127 int start = static_cast<int>( aString.length() ) - 8 + i * 2;
128 int end = start + 2;
129
130 start = std::max( 0, start );
131 int len = std::max( 0, end - start );
132
133 std::string octet = aString.substr( start, len );
134 m_uuid.data[i + 12] = strtol( octet.data(), nullptr, 16 );
135 }
136 }
137 else
138 {
139 try
140 {
141 m_uuid = stringGenerator( aString );
142 }
143 catch( ... )
144 {
145 // Failed to parse string representation; best we can do is assign a new
146 // random one.
147#if BOOST_VERSION >= 106700
148 try
149 {
150#endif
151
152 m_uuid = randomGenerator();
153
154#if BOOST_VERSION >= 106700
155 }
156 catch( const boost::uuids::entropy_error& )
157 {
158 wxLogFatalError( "A Boost UUID entropy exception was thrown in %s:%s.",
159 __FILE__, __FUNCTION__ );
160 }
161#endif
162 }
163 }
164}
165
166
167KIID::KIID( const char* aString ) :
168 KIID( std::string( aString ) )
169{
170}
171
172
173KIID::KIID( const wxString& aString ) :
174 KIID( std::string( aString.ToUTF8() ) )
175{
176}
177
178
179bool KIID::SniffTest( const wxString& aCandidate )
180{
181 static wxString niluuidStr = niluuid.AsString();
182
183 if( aCandidate.Length() != niluuidStr.Length() )
184 return false;
185
186 for( wxChar c : aCandidate )
187 {
188 if( c >= '0' && c <= '9' )
189 continue;
190
191 if( c >= 'a' && c <= 'f' )
192 continue;
193
194 if( c >= 'A' && c <= 'F' )
195 continue;
196
197 if( c == '-' )
198 continue;
199
200 return false;
201 }
202
203 return true;
204}
205
206
208{
209 m_uuid.data[12] = static_cast<uint8_t>( aTimestamp >> 24 );
210 m_uuid.data[13] = static_cast<uint8_t>( aTimestamp >> 16 );
211 m_uuid.data[14] = static_cast<uint8_t>( aTimestamp >> 8 );
212 m_uuid.data[15] = static_cast<uint8_t>( aTimestamp );
213}
214
215
217{
218 return !m_uuid.data[8] && !m_uuid.data[9] && !m_uuid.data[10] && !m_uuid.data[11];
219}
220
221
223{
224 timestamp_t ret = 0;
225
226 ret |= m_uuid.data[12] << 24;
227 ret |= m_uuid.data[13] << 16;
228 ret |= m_uuid.data[14] << 8;
229 ret |= m_uuid.data[15];
230
231 return ret;
232}
233
234
235size_t KIID::Hash() const
236{
237 return boost::uuids::hash_value( m_uuid );
238}
239
240
241void KIID::Clone( const KIID& aUUID )
242{
243 m_uuid = aUUID.m_uuid;
244}
245
246
247wxString KIID::AsString() const
248{
249 return boost::uuids::to_string( m_uuid );
250}
251
252
253std::string KIID::AsStdString() const
254{
255 return boost::uuids::to_string( m_uuid );
256}
257
258
260{
261 return wxString::Format( "%8.8lX", (unsigned long) AsLegacyTimestamp() );
262}
263
264
266{
267 if( !IsLegacyTimestamp() )
268 return;
269
271}
272
273
275{
276 // This obviously destroys uniform distribution, but it can be useful when a
277 // deterministic replacement for a duplicate ID is required.
278
279 for( int i = 15; i >= 0; --i )
280 {
281 m_uuid.data[i]++;
282
283 if( m_uuid.data[i] != 0 )
284 break;
285 }
286}
287
288
289KIID KIID::Combine( const KIID& aFirst, const KIID& aSecond )
290{
291 KIID result( 0 );
292
293 for( int i = 0; i < 16; ++i )
294 result.m_uuid.data[i] = aFirst.m_uuid.data[i] ^ aSecond.m_uuid.data[i];
295
296 return result;
297}
298
299
300void KIID::CreateNilUuids( bool aNil )
301{
302 g_createNilUuids = aNil;
303}
304
305
306void KIID::SeedGenerator( unsigned int aSeed )
307{
308 rng.seed( aSeed );
309 randomGenerator = boost::uuids::basic_random_generator<boost::mt19937>( rng );
310}
311
312
313KIID_PATH::KIID_PATH( const wxString& aString )
314{
315 for( const wxString& pathStep : wxSplit( aString, '/' ) )
316 {
317 if( !pathStep.empty() )
318 emplace_back( KIID( pathStep ) );
319 }
320}
321
322
324{
325 KIID_PATH copy = *this;
326 clear();
327
328 if( aPath.size() > copy.size() )
329 return false; // this path is not contained within aPath
330
331 for( size_t i = 0; i < aPath.size(); ++i )
332 {
333 if( copy.at( i ) != aPath.at( i ) )
334 {
335 *this = copy;
336 return false; // this path is not contained within aPath
337 }
338 }
339
340 for( size_t i = aPath.size(); i < copy.size(); ++i )
341 push_back( copy.at( i ) );
342
343 return true;
344}
345
346
347bool KIID_PATH::EndsWith( const KIID_PATH& aPath ) const
348{
349 if( aPath.size() > size() )
350 return false; // this path can not end aPath
351
352 KIID_PATH copyThis = *this;
353 KIID_PATH copyThat = aPath;
354
355 while( !copyThat.empty() )
356 {
357 if( *std::prev( copyThis.end() ) != *std::prev( copyThat.end() ) )
358 return false;
359
360 copyThis.pop_back();
361 copyThat.pop_back();
362 }
363
364 return true;
365}
366
367
368wxString KIID_PATH::AsString() const
369{
370 wxString path;
371
372 for( const KIID& pathStep : *this )
373 path += '/' + pathStep.AsString();
374
375 return path;
376}
377
378
379void to_json( nlohmann::json& aJson, const KIID& aKIID )
380{
381 aJson = aKIID.AsString().ToUTF8();
382}
383
384
385void from_json( const nlohmann::json& aJson, KIID& aKIID )
386{
387 aKIID = KIID( aJson.get<std::string>() );
388}
bool EndsWith(const KIID_PATH &aPath) const
Test if aPath from the last path towards the first path.
Definition kiid.cpp:347
bool MakeRelativeTo(const KIID_PATH &aPath)
Definition kiid.cpp:323
KIID_PATH()
Definition kiid.h:154
wxString AsString() const
Definition kiid.cpp:368
Definition kiid.h:49
KIID()
Definition kiid.cpp:77
static void SeedGenerator(unsigned int aSeed)
Re-initialize the UUID generator with a given seed (for testing or QA purposes)
Definition kiid.cpp:306
size_t Hash() const
Definition kiid.cpp:235
wxString AsString() const
Definition kiid.cpp:247
static KIID Combine(const KIID &aFirst, const KIID &aSecond)
Creates a deterministic KIID from two input KIIDs by XORing their underlying UUIDs.
Definition kiid.cpp:289
boost::uuids::uuid m_uuid
Definition kiid.h:140
void Increment()
Generates a deterministic replacement for a given ID.
Definition kiid.cpp:274
std::string AsStdString() const
Definition kiid.cpp:253
wxString AsLegacyTimestampString() const
Definition kiid.cpp:259
timestamp_t AsLegacyTimestamp() const
Definition kiid.cpp:222
static void CreateNilUuids(bool aNil=true)
A performance optimization which disables/enables the generation of pseudo-random UUIDs.
Definition kiid.cpp:300
static bool SniffTest(const wxString &aCandidate)
Returns true if a string has the correct formatting to be a KIID.
Definition kiid.cpp:179
void Clone(const KIID &aUUID)
Definition kiid.cpp:241
bool IsLegacyTimestamp() const
Definition kiid.cpp:216
void ConvertTimestampToUuid()
Change an existing time stamp based UUID into a true UUID.
Definition kiid.cpp:265
static boost::uuids::nil_generator nilGenerator
Definition kiid.cpp:57
KIID & NilUuid()
Definition kiid.cpp:70
static std::mutex rng_mutex
Definition kiid.cpp:46
static boost::mt19937 rng
Definition kiid.cpp:52
void from_json(const nlohmann::json &aJson, KIID &aKIID)
Definition kiid.cpp:385
static boost::uuids::string_generator stringGenerator
Definition kiid.cpp:56
static boost::uuids::basic_random_generator< boost::mt19937 > randomGenerator
Definition kiid.cpp:53
static thread_local bool g_createNilUuids
Definition kiid.cpp:66
void to_json(nlohmann::json &aJson, const KIID &aKIID)
Definition kiid.cpp:379
KIID niluuid(0)
KICOMMON_API KIID niluuid
uint32_t timestamp_t
timestamp_t is our type to represent unique IDs for all kinds of elements; historically simply the ti...
Definition kiid.h:46
STL namespace.
std::string path
wxString result
Test unit parsing edge cases and error handling.