/[pcsx2_0.9.7]/trunk/common/src/Utilities/FastFormatString.cpp
ViewVC logotype

Contents of /trunk/common/src/Utilities/FastFormatString.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 280 - (show annotations) (download)
Thu Dec 23 12:02:12 2010 UTC (9 years, 1 month ago) by william
File size: 10538 byte(s)
re-commit (had local access denied errors when committing)
1 /* PCSX2 - PS2 Emulator for PCs
2 * Copyright (C) 2002-2010 PCSX2 Dev Team
3 *
4 * PCSX2 is free software: you can redistribute it and/or modify it under the terms
5 * of the GNU Lesser General Public License as published by the Free Software Found-
6 * ation, either version 3 of the License, or (at your option) any later version.
7 *
8 * PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
10 * PURPOSE. See the GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License along with PCSX2.
13 * If not, see <http://www.gnu.org/licenses/>.
14 */
15
16 #include "PrecompiledHeader.h"
17 #include "Threading.h"
18
19 #include "TlsVariable.inl"
20 #include "SafeArray.inl"
21
22 using namespace Threading;
23
24 // Implement some very commonly used SafeArray types here
25 // (done here for lack of a better place)
26
27 template class SafeArray<char>;
28 template class SafeArray<wchar_t>;
29 template class SafeArray<u8>;
30
31 template class SafeAlignedArray<char,16>;
32 template class SafeAlignedArray<wchar_t,16>;
33 template class SafeAlignedArray<u8,16>;
34
35 // Sanity check: truncate strings if they exceed 512k in length. Anything like that
36 // is either a bug or really horrible code that needs to be stopped before it causes
37 // system deadlock.
38 static const int MaxFormattedStringLength = 0x80000;
39
40 typedef ScopedAlignedAlloc<char,16> CharBufferType;
41
42 // --------------------------------------------------------------------------------------
43 // FastFormatBuffers
44 // --------------------------------------------------------------------------------------
45 // This class provides a series of pre-allocated thread-local buffers for use by string
46 // formatting tools. These buffers are handed out in round-robin style and require *no*
47 // thread sync objects and avoid multi-thread contention completely -- allowing multiple
48 // threads to format complicated strings concurrently with maximum efficiency.
49 //
50 class FastFormatBuffers
51 {
52 DeclareNoncopyableObject(FastFormatBuffers);
53
54 protected:
55 typedef char CharType;
56 typedef CharBufferType BufferType;
57
58 static const uint BufferCount = 6;
59
60 BufferType m_buffers[BufferCount];
61 uint m_curslot;
62
63 public:
64 FastFormatBuffers()
65 {
66 // This protects against potential recursive calls to our formatter, by forcing those
67 // calls to use a dynamic buffer for formatting.
68 m_curslot = BufferCount;
69
70 for (uint i=0; i<BufferCount; ++i)
71 {
72 m_buffers[i].Alloc(512);
73 }
74
75 m_curslot = 0;
76 }
77
78 virtual ~FastFormatBuffers() throw()
79 {
80 pxAssumeDev(m_curslot==0,
81 wxsFormat(L"Dangling %s formatting buffer detected!",
82 (sizeof(CharType)==1) ? L"UTF8/Ascii" : L"Wide-char"
83 )
84 );
85 }
86
87 bool HasFreeBuffer() const
88 {
89 return m_curslot < BufferCount-1;
90 }
91
92 BufferType& GrabBuffer()
93 {
94 ++m_curslot;
95 pxAssume(m_curslot < BufferCount);
96 return m_buffers[m_curslot];
97 }
98
99 void ReleaseBuffer()
100 {
101 --m_curslot;
102 pxAssume(m_curslot < BufferCount);
103 }
104
105 BufferType& operator[](uint i)
106 {
107 IndexBoundsAssume( ((sizeof(CharType)==1) ? L"Ascii Formatting Buffer" : L"Unicode Formatting Buffer"), i, BufferCount );
108 return m_buffers[i];
109 }
110 };
111
112 // --------------------------------------------------------------------------------------
113 // GlobalBufferManager
114 // --------------------------------------------------------------------------------------
115 // This local-scope class is needed in order to safely deal with C++ initializing and destroying
116 // global objects in arbitrary order. The initbit is updated by the object when constructed and
117 // destroyed; code using this class provides its own statically-initialized boolean (which MUST
118 // default to false!) and then sets the boolean to true to indicate the object is ready for use.
119 //
120 template< typename T >
121 class GlobalBufferManager
122 {
123 public:
124 bool& initbit;
125 T instance;
126
127 GlobalBufferManager( bool& globalBoolean )
128 : initbit( globalBoolean )
129 {
130 initbit = true;
131 }
132
133 ~GlobalBufferManager() throw()
134 {
135 initbit = false;
136 instance.Dispose();
137 }
138
139 T& Get()
140 {
141 return instance;
142 }
143
144 operator T&()
145 {
146 return instance;
147 }
148 };
149
150 static bool buffer_is_avail = false;
151 static GlobalBufferManager< BaseTlsVariable< FastFormatBuffers > > m_buffer_tls(buffer_is_avail);
152
153 //static __ri void format_that_ascii_mess( SafeArray<char>& buffer, uint writepos, const char* fmt, va_list argptr )
154 static __ri void format_that_ascii_mess( CharBufferType& buffer, uint writepos, const char* fmt, va_list argptr )
155 {
156 while( true )
157 {
158 int size = buffer.GetLength();
159 int len = vsnprintf(buffer.GetPtr(writepos), size-writepos, fmt, argptr);
160
161 // some implementations of vsnprintf() don't NUL terminate
162 // the string if there is not enough space for it so
163 // always do it manually
164 buffer[size-1] = '\0';
165
166 if (size >= MaxFormattedStringLength) break;
167
168 // vsnprintf() may return either -1 (traditional Unix behavior) or the
169 // total number of characters which would have been written if the
170 // buffer were large enough (newer standards such as Unix98)
171
172 if (len < 0)
173 len = size + (size/4);
174
175 len += writepos;
176 if (len < size) break;
177 buffer.Resize( len + 128 );
178 };
179
180 // performing an assertion or log of a truncated string is unsafe, so let's not; even
181 // though it'd be kinda nice if we did.
182 }
183
184 // returns the length of the formatted string, in characters (wxChars).
185 static __ri uint format_that_unicode_mess( CharBufferType& buffer, uint writepos, const wxChar* fmt, va_list argptr)
186 {
187 while( true )
188 {
189 int size = buffer.GetLength() / sizeof(wxChar);
190 int len = wxVsnprintf((wxChar*)buffer.GetPtr(writepos*sizeof(wxChar)), size-writepos, fmt, argptr);
191
192 // some implementations of vsnprintf() don't NUL terminate
193 // the string if there is not enough space for it so
194 // always do it manually
195 ((wxChar*)buffer.GetPtr())[size-1] = L'\0';
196
197 if( size >= MaxFormattedStringLength ) return size-1;
198
199 // vsnprintf() may return either -1 (traditional Unix behavior) or the
200 // total number of characters which would have been written if the
201 // buffer were large enough (newer standards such as Unix98)
202
203 if (len < 0)
204 len = size + (size/4);
205
206 len += writepos;
207 if (len < size) return len;
208 buffer.Resize( (len + 128) * sizeof(wxChar) );
209 };
210
211 // performing an assertion or log of a truncated string is unsafe, so let's not; even
212 // though it'd be kinda nice if we did.
213
214 pxAssume( false );
215 return 0; // unreachable.
216 }
217
218 CharBufferType* GetFormatBuffer( bool& deleteDest )
219 {
220 deleteDest = false;
221 if (buffer_is_avail)
222 {
223 if (m_buffer_tls.Get()->HasFreeBuffer())
224 return &m_buffer_tls.Get()->GrabBuffer();
225 }
226
227 deleteDest = true;
228
229 return new CharBufferType(2048);
230 }
231
232 // --------------------------------------------------------------------------------------
233 // FastFormatUnicode (implementations)
234 // --------------------------------------------------------------------------------------
235 // [TODO] This class should actually be renamed to FastFormatNative or FastFormatString, and
236 // adopted to properly support 1-byte wxChar types (mostly requiring some changes to the
237 // WriteV functions). The current implementation is fine for wx2.8, which always defaults
238 // to wide-varieties of wxChar -- but wx3.0 will use UTF8 for linux distros, which will break
239 // this class nicely in its current state. --air
240
241 FastFormatUnicode::FastFormatUnicode()
242 {
243 m_dest = GetFormatBuffer(m_deleteDest);
244 Clear();
245 }
246
247 FastFormatUnicode::~FastFormatUnicode() throw()
248 {
249 if (m_deleteDest)
250 delete m_dest;
251 else
252 m_buffer_tls.Get()->ReleaseBuffer();
253 }
254
255 void FastFormatUnicode::Clear()
256 {
257 m_Length = 0;
258 ((wxChar*)m_dest->GetPtr())[0] = 0;
259 }
260
261 FastFormatUnicode& FastFormatUnicode::WriteV( const char* fmt, va_list argptr )
262 {
263 wxString converted( fromUTF8(FastFormatAscii().WriteV( fmt, argptr )) );
264
265 const uint inspos = m_Length;
266 const uint convLen = converted.Length();
267 m_dest->MakeRoomFor((inspos + convLen + 64) * sizeof(wxChar));
268 memcpy_fast( &((wxChar*)m_dest->GetPtr())[inspos], converted, (convLen+1)*sizeof(wxChar) );
269 m_Length += convLen;
270
271 return *this;
272 }
273
274 FastFormatUnicode& FastFormatUnicode::WriteV( const wxChar* fmt, va_list argptr )
275 {
276 m_Length = format_that_unicode_mess( *m_dest, m_Length, fmt, argptr );
277 return *this;
278 }
279
280 FastFormatUnicode& FastFormatUnicode::Write( const char* fmt, ... )
281 {
282 va_list list;
283 va_start(list, fmt);
284 WriteV(fmt,list);
285 va_end(list);
286 return *this;
287 }
288
289 FastFormatUnicode& FastFormatUnicode::Write( const wxChar* fmt, ... )
290 {
291 va_list list;
292 va_start(list, fmt);
293 WriteV(fmt,list);
294 va_end(list);
295 return *this;
296 }
297
298 bool FastFormatUnicode::IsEmpty() const
299 {
300 return ((wxChar&)(*m_dest)[0]) == 0;
301 }
302
303 FastFormatUnicode& FastFormatUnicode::ToUpper()
304 {
305 wxChar* ch = (wxChar*)m_dest->GetPtr();
306 for ( uint i=0; i<m_Length; ++i, ++ch )
307 *ch = (wxChar)wxToupper(*ch);
308
309 return *this;
310 }
311
312 FastFormatUnicode& FastFormatUnicode::ToLower()
313 {
314 wxChar* ch = (wxChar*)m_dest->GetPtr();
315 for ( uint i=0; i<m_Length; ++i, ++ch )
316 *ch = (wxChar)wxTolower(*ch);
317
318 return *this;
319 }
320
321 FastFormatUnicode& FastFormatUnicode::operator+=(const char* psz )
322 {
323 Write( L"%s", fromUTF8(psz).c_str() );
324 return *this;
325 }
326
327 wxString& operator+=(wxString& str1, const FastFormatUnicode& str2)
328 {
329 str1.Append(str2.c_str(), str2.Length());
330 return str1;
331 }
332
333 wxString operator+(const wxString& str1, const FastFormatUnicode& str2)
334 {
335 wxString s = str1;
336 s += str2;
337
338 return s;
339 }
340
341 wxString operator+(const wxChar* str1, const FastFormatUnicode& str2)
342 {
343 wxString s = str1;
344 s += str2;
345
346 return s;
347 }
348
349
350 // --------------------------------------------------------------------------------------
351 // FastFormatAscii (implementations)
352 // --------------------------------------------------------------------------------------
353 FastFormatAscii::FastFormatAscii()
354 {
355 m_dest = GetFormatBuffer(m_deleteDest);
356 Clear();
357 }
358
359 FastFormatAscii::~FastFormatAscii() throw()
360 {
361 if (m_deleteDest)
362 delete m_dest;
363 else
364 m_buffer_tls.Get()->ReleaseBuffer();
365 }
366
367 void FastFormatAscii::Clear()
368 {
369 m_dest->GetPtr()[0] = 0;
370 }
371
372 const wxString FastFormatAscii::GetString() const
373 {
374 return fromAscii(m_dest->GetPtr());
375 }
376
377 FastFormatAscii& FastFormatAscii::WriteV( const char* fmt, va_list argptr )
378 {
379 format_that_ascii_mess( *m_dest, strlen(m_dest->GetPtr()), fmt, argptr );
380 return *this;
381 }
382
383 FastFormatAscii& FastFormatAscii::Write( const char* fmt, ... )
384 {
385 va_list list;
386 va_start(list, fmt);
387 WriteV(fmt,list);
388 va_end(list);
389 return *this;
390 }
391
392
393 bool FastFormatAscii::IsEmpty() const
394 {
395 return (*m_dest)[0] == 0;
396 }

  ViewVC Help
Powered by ViewVC 1.1.22