VirtualBox

source: vbox/trunk/include/VBox/com/string.h@ 34350

Last change on this file since 34350 was 34242, checked in by vboxsync, 14 years ago

com/string.h: Added Bstr::isNotEmpty().

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 17.8 KB
Line 
1/* $Id: string.h 34242 2010-11-22 14:27:48Z vboxsync $ */
2
3/** @file
4 * MS COM / XPCOM Abstraction Layer:
5 * Smart string classes declaration
6 */
7
8/*
9 * Copyright (C) 2006-2010 Oracle Corporation
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.virtualbox.org. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 *
19 * The contents of this file may alternatively be used under the terms
20 * of the Common Development and Distribution License Version 1.0
21 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
22 * VirtualBox OSE distribution, in which case the provisions of the
23 * CDDL are applicable instead of those of the GPL.
24 *
25 * You may elect to license modified versions of this file under the
26 * terms and conditions of either the GPL or the CDDL or both.
27 */
28
29#ifndef ___VBox_com_string_h
30#define ___VBox_com_string_h
31
32/* Make sure all the stdint.h macros are included - must come first! */
33#ifndef __STDC_LIMIT_MACROS
34# define __STDC_LIMIT_MACROS
35#endif
36#ifndef __STDC_CONSTANT_MACROS
37# define __STDC_CONSTANT_MACROS
38#endif
39
40#if defined(VBOX_WITH_XPCOM)
41# include <nsMemory.h>
42#endif
43
44#include "VBox/com/defs.h"
45#include "VBox/com/assert.h"
46
47#include <iprt/alloc.h>
48#include <iprt/cpp/ministring.h>
49
50namespace com
51{
52
53class Utf8Str;
54
55// global constant in glue/string.cpp that represents an empty BSTR
56extern const BSTR g_bstrEmpty;
57
58/**
59 * String class used universally in Main for COM-style Utf-16 strings.
60 * Unfortunately COM on Windows uses UTF-16 everywhere, requiring conversions
61 * back and forth since most of VirtualBox and our libraries use UTF-8.
62 *
63 * To make things more obscure, on Windows, a COM-style BSTR is not just a
64 * pointer to a null-terminated wide character array, but the four bytes
65 * (32 bits) BEFORE the memory that the pointer points to are a length
66 * DWORD. One must therefore avoid pointer arithmetic and always use
67 * SysAllocString and the like to deal with BSTR pointers, which manage
68 * that DWORD correctly.
69 *
70 * For platforms other than Windows, we provide our own versions of the
71 * Sys* functions in Main/xpcom/helpers.cpp which do NOT use length
72 * prefixes though to be compatible with how XPCOM allocates string
73 * parameters to public functions.
74 *
75 * The Bstr class hides all this handling behind a std::string-like interface
76 * and also provides automatic conversions to MiniString and Utf8Str instances.
77 *
78 * The one advantage of using the SysString* routines is that this makes it
79 * possible to use it as a type of member variables of COM/XPCOM components
80 * and pass their values to callers through component methods' output parameters
81 * using the #cloneTo() operation. Also, the class can adopt (take ownership of)
82 * string buffers returned in output parameters of COM methods using the
83 * #asOutParam() operation and correctly free them afterwards.
84 *
85 * Starting with VirtualBox 3.2, like Utf8Str, Bstr no longer differentiates
86 * between NULL strings and empty strings. In other words, Bstr("") and
87 * Bstr(NULL) behave the same. In both cases, Bstr allocates no memory,
88 * reports a zero length and zero allocated bytes for both, and returns an
89 * empty C wide string from raw().
90 */
91class Bstr
92{
93public:
94
95 Bstr()
96 : m_bstr(NULL)
97 { }
98
99 Bstr(const Bstr &that)
100 {
101 copyFrom((const OLECHAR *)that.m_bstr);
102 }
103
104 Bstr(CBSTR that)
105 {
106 copyFrom((const OLECHAR *)that);
107 }
108
109#if defined(VBOX_WITH_XPCOM)
110 Bstr(const wchar_t *that)
111 {
112 AssertCompile(sizeof(wchar_t) == sizeof(OLECHAR));
113 copyFrom((const OLECHAR *)that);
114 }
115#endif
116
117 Bstr(const iprt::MiniString &that)
118 {
119 copyFrom(that.c_str());
120 }
121
122 Bstr(const char *that)
123 {
124 copyFrom(that);
125 }
126
127 ~Bstr()
128 {
129 setNull();
130 }
131
132 Bstr& operator=(const Bstr &that)
133 {
134 cleanup();
135 copyFrom((const OLECHAR *)that.m_bstr);
136 return *this;
137 }
138
139 Bstr& operator=(CBSTR that)
140 {
141 cleanup();
142 copyFrom((const OLECHAR *)that);
143 return *this;
144 }
145
146#if defined(VBOX_WITH_XPCOM)
147 Bstr& operator=(const wchar_t *that)
148 {
149 cleanup();
150 copyFrom((const OLECHAR *)that);
151 return *this;
152 }
153#endif
154
155 Bstr& setNull()
156 {
157 cleanup();
158 return *this;
159 }
160
161 /** Case sensitivity selector. */
162 enum CaseSensitivity
163 {
164 CaseSensitive,
165 CaseInsensitive
166 };
167
168 /**
169 * Compares the member string to str.
170 * @param str
171 * @param cs Whether comparison should be case-sensitive.
172 * @return
173 */
174 int compare(CBSTR str, CaseSensitivity cs = CaseSensitive) const
175 {
176 if (cs == CaseSensitive)
177 return ::RTUtf16Cmp((PRTUTF16)m_bstr, (PRTUTF16)str);
178 return ::RTUtf16LocaleICmp((PRTUTF16)m_bstr, (PRTUTF16)str);
179 }
180
181 int compare(BSTR str, CaseSensitivity cs = CaseSensitive) const
182 {
183 return compare((CBSTR)str, cs);
184 }
185
186 int compare(const Bstr &that, CaseSensitivity cs = CaseSensitive) const
187 {
188 return compare(that.m_bstr, cs);
189 }
190
191 bool operator==(const Bstr &that) const { return !compare(that.m_bstr); }
192 bool operator!=(const Bstr &that) const { return !!compare(that.m_bstr); }
193 bool operator==(CBSTR that) const { return !compare(that); }
194 bool operator==(BSTR that) const { return !compare(that); }
195
196 bool operator!=(CBSTR that) const { return !!compare(that); }
197 bool operator!=(BSTR that) const { return !!compare(that); }
198 bool operator<(const Bstr &that) const { return compare(that.m_bstr) < 0; }
199 bool operator<(CBSTR that) const { return compare(that) < 0; }
200 bool operator<(BSTR that) const { return compare(that) < 0; }
201
202 /**
203 * Returns true if the member string has no length.
204 * This is true for instances created from both NULL and "" input strings.
205 *
206 * @note Always use this method to check if an instance is empty. Do not
207 * use length() because that may need to run through the entire string
208 * (Bstr does not cache string lengths).
209 */
210 bool isEmpty() const { return m_bstr == NULL || *m_bstr == 0; }
211
212 /**
213 * Returns true if the member string has a length of one or more.
214 *
215 * @returns true if not empty, false if empty (NULL or "").
216 */
217 bool isNotEmpty() const { return m_bstr != NULL && *m_bstr != 0; }
218
219 size_t length() const { return isEmpty() ? 0 : ::RTUtf16Len((PRTUTF16)m_bstr); }
220
221#if defined(VBOX_WITH_XPCOM)
222 /**
223 * Returns a pointer to the raw member UTF-16 string. If the member string is empty,
224 * returns a pointer to a global variable containing an empty BSTR with a proper zero
225 * length prefix so that Windows is happy.
226 */
227 CBSTR raw() const
228 {
229 if (m_bstr)
230 return m_bstr;
231
232 return g_bstrEmpty;
233 }
234#else
235 /**
236 * Windows-only hack, as the automatically generated headers use BSTR.
237 * So if we don't want to cast like crazy we have to be more loose than
238 * on XPCOM.
239 *
240 * Returns a pointer to the raw member UTF-16 string. If the member string is empty,
241 * returns a pointer to a global variable containing an empty BSTR with a proper zero
242 * length prefix so that Windows is happy.
243 */
244 BSTR raw() const
245 {
246 if (m_bstr)
247 return m_bstr;
248
249 return g_bstrEmpty;
250 }
251#endif
252
253 /**
254 * Returns a non-const raw pointer that allows to modify the string directly.
255 * As opposed to raw(), this DOES return NULL if the member string is empty
256 * because we cannot return a mutable pointer to the global variable with the
257 * empty string.
258 *
259 * @warning
260 * Be sure not to modify data beyond the allocated memory! The
261 * guaranteed size of the allocated memory is at least #length()
262 * bytes after creation and after every assignment operation.
263 */
264 BSTR mutableRaw() { return m_bstr; }
265
266 /**
267 * Intended to assign copies of instances to |BSTR| out parameters from
268 * within the interface method. Transfers the ownership of the duplicated
269 * string to the caller.
270 *
271 * If the member string is empty, this allocates an empty BSTR in *pstr
272 * (i.e. makes it point to a new buffer with a null byte).
273 */
274 void cloneTo(BSTR *pstr) const
275 {
276 if (pstr)
277 {
278 *pstr = ::SysAllocString((const OLECHAR *)raw()); // raw() returns a pointer to "" if empty
279#ifdef RT_EXCEPTIONS_ENABLED
280 if (!*pstr)
281 throw std::bad_alloc();
282#endif
283 }
284 }
285
286 /**
287 * Intended to assign instances to |BSTR| out parameters from within the
288 * interface method. Transfers the ownership of the original string to the
289 * caller and resets the instance to null.
290 *
291 * As opposed to cloneTo(), this method doesn't create a copy of the
292 * string.
293 *
294 * If the member string is empty, this allocates an empty BSTR in *pstr
295 * (i.e. makes it point to a new buffer with a null byte).
296 */
297 void detachTo(BSTR *pstr)
298 {
299 if (m_bstr)
300 *pstr = m_bstr;
301 else
302 {
303 // allocate null BSTR
304 *pstr = ::SysAllocString((const OLECHAR *)g_bstrEmpty);
305#ifdef RT_EXCEPTIONS_ENABLED
306 if (!*pstr)
307 throw std::bad_alloc();
308#endif
309 }
310 m_bstr = NULL;
311 }
312
313 /**
314 * Intended to pass instances as |BSTR| out parameters to methods.
315 * Takes the ownership of the returned data.
316 */
317 BSTR* asOutParam()
318 {
319 cleanup();
320 return &m_bstr;
321 }
322
323 /**
324 * Static immutable empty-string object. May be used for comparison purposes.
325 */
326 static const Bstr Empty;
327
328protected:
329
330 void cleanup()
331 {
332 if (m_bstr)
333 {
334 ::SysFreeString(m_bstr);
335 m_bstr = NULL;
336 }
337 }
338
339 /**
340 * Protected internal helper to copy a string. This ignores the previous object
341 * state, so either call this from a constructor or call cleanup() first.
342 *
343 * This variant copies from a zero-terminated UTF-16 string (which need not
344 * be a BSTR, i.e. need not have a length prefix).
345 *
346 * If the source is empty, this sets the member string to NULL.
347 * @param rs
348 */
349 void copyFrom(const OLECHAR *rs)
350 {
351 if (rs && *rs)
352 {
353 m_bstr = ::SysAllocString(rs);
354#ifdef RT_EXCEPTIONS_ENABLED
355 if (!m_bstr)
356 throw std::bad_alloc();
357#endif
358 }
359 else
360 m_bstr = NULL;
361 }
362
363 /**
364 * Protected internal helper to copy a string. This ignores the previous object
365 * state, so either call this from a constructor or call cleanup() first.
366 *
367 * This variant copies and converts from a zero-terminated UTF-8 string.
368 *
369 * If the source is empty, this sets the member string to NULL.
370 * @param rs
371 */
372 void copyFrom(const char *rs)
373 {
374 if (rs && *rs)
375 {
376 PRTUTF16 s = NULL;
377 ::RTStrToUtf16(rs, &s);
378#ifdef RT_EXCEPTIONS_ENABLED
379 if (!s)
380 throw std::bad_alloc();
381#endif
382 copyFrom((const OLECHAR *)s); // allocates BSTR from zero-terminated input string
383 ::RTUtf16Free(s);
384 }
385 else
386 m_bstr = NULL;
387 }
388
389 BSTR m_bstr;
390
391 friend class Utf8Str; /* to access our raw_copy() */
392};
393
394/* symmetric compare operators */
395inline bool operator==(CBSTR l, const Bstr &r) { return r.operator==(l); }
396inline bool operator!=(CBSTR l, const Bstr &r) { return r.operator!=(l); }
397inline bool operator==(BSTR l, const Bstr &r) { return r.operator==(l); }
398inline bool operator!=(BSTR l, const Bstr &r) { return r.operator!=(l); }
399
400
401////////////////////////////////////////////////////////////////////////////////
402
403/**
404 * String class used universally in Main for UTF-8 strings.
405 *
406 * This is based on iprt::MiniString, to which some functionality has been
407 * moved. Here we keep things that are specific to Main, such as conversions
408 * with UTF-16 strings (Bstr).
409 *
410 * Like iprt::MiniString, Utf8Str does not differentiate between NULL strings
411 * and empty strings. In other words, Utf8Str("") and Utf8Str(NULL)
412 * behave the same. In both cases, MiniString allocates no memory, reports
413 * a zero length and zero allocated bytes for both, and returns an empty
414 * C string from c_str().
415 */
416class Utf8Str : public iprt::MiniString
417{
418public:
419
420 Utf8Str() {}
421
422 Utf8Str(const MiniString &that)
423 : MiniString(that)
424 {}
425
426 Utf8Str(const char *that)
427 : MiniString(that)
428 {}
429
430 Utf8Str(const Bstr &that)
431 {
432 copyFrom(that.raw());
433 }
434
435 Utf8Str(CBSTR that)
436 {
437 copyFrom(that);
438 }
439
440 /**
441 * Constructs a new string given the format string and the list of the
442 * arguments for the format string.
443 *
444 * @param a_pszFormat Pointer to the format string (UTF-8),
445 * @see pg_rt_str_format.
446 * @param a_va Argument vector containing the arguments
447 * specified by the format string.
448 * @sa iprt::MiniString::printfV
449 */
450 Utf8Str(const char *a_pszFormat, va_list a_va)
451 : MiniString(a_pszFormat, a_va)
452 {
453 }
454
455 Utf8Str& operator=(const MiniString &that)
456 {
457 MiniString::operator=(that);
458 return *this;
459 }
460
461 Utf8Str& operator=(const char *that)
462 {
463 MiniString::operator=(that);
464 return *this;
465 }
466
467 Utf8Str& operator=(const Bstr &that)
468 {
469 cleanup();
470 copyFrom(that.raw());
471 return *this;
472 }
473
474 Utf8Str& operator=(CBSTR that)
475 {
476 cleanup();
477 copyFrom(that);
478 return *this;
479 }
480
481#if defined(VBOX_WITH_XPCOM)
482 /**
483 * Intended to assign instances to |char *| out parameters from within the
484 * interface method. Transfers the ownership of the duplicated string to the
485 * caller.
486 *
487 * This allocates a single 0 byte in the target if the member string is empty.
488 *
489 * This uses XPCOM memory allocation and thus only works on XPCOM. MSCOM doesn't
490 * like char* strings anyway.
491 */
492 void cloneTo(char **pstr) const;
493#endif
494
495 /**
496 * Intended to assign instances to |BSTR| out parameters from within the
497 * interface method. Transfers the ownership of the duplicated string to the
498 * caller.
499 */
500 void cloneTo(BSTR *pstr) const
501 {
502 if (pstr)
503 {
504 Bstr bstr(*this);
505 bstr.cloneTo(pstr);
506 }
507 }
508
509 /**
510 * Removes a trailing slash from the member string, if present.
511 * Calls RTPathStripTrailingSlash() without having to mess with mutableRaw().
512 */
513 Utf8Str& stripTrailingSlash();
514
515 /**
516 * Removes a trailing filename from the member string, if present.
517 * Calls RTPathStripFilename() without having to mess with mutableRaw().
518 */
519 Utf8Str& stripFilename();
520
521 /**
522 * Removes the path component from the member string, if present.
523 * Calls RTPathFilename() without having to mess with mutableRaw().
524 */
525 Utf8Str& stripPath();
526
527 /**
528 * Removes a trailing file name extension from the member string, if present.
529 * Calls RTPathStripExt() without having to mess with mutableRaw().
530 */
531 Utf8Str& stripExt();
532
533 /**
534 * Static immutable empty-string object. May be used for comparison purposes.
535 */
536 static const Utf8Str Empty;
537
538protected:
539
540 void copyFrom(CBSTR s);
541
542 friend class Bstr; /* to access our raw_copy() */
543};
544
545/**
546 * Class with iprt::MiniString::printf as constructor for your convenience.
547 *
548 * Constructing a Utf8Str string object from a format string and a variable
549 * number of arguments can easily be confused with the other Utf8Str
550 * constructures, thus this child class.
551 *
552 * The usage of this class is like the following:
553 * @code
554 Utf8StrFmt strName("program name = %s", argv[0]);
555 @endcode
556 */
557class Utf8StrFmt : public Utf8Str
558{
559public:
560
561 /**
562 * Constructs a new string given the format string and the list of the
563 * arguments for the format string.
564 *
565 * @param a_pszFormat Pointer to the format string (UTF-8),
566 * @see pg_rt_str_format.
567 * @param ... Ellipsis containing the arguments specified by
568 * the format string.
569 */
570 explicit Utf8StrFmt(const char *a_pszFormat, ...)
571 {
572 va_list va;
573 va_start(va, a_pszFormat);
574 printfV(a_pszFormat, va);
575 va_end(va);
576 }
577
578protected:
579 Utf8StrFmt()
580 { }
581
582private:
583};
584
585/**
586 * The BstrFmt class is a shortcut to <tt>Bstr(Utf8StrFmt(...))</tt>.
587 */
588class BstrFmt : public Bstr
589{
590public:
591
592 /**
593 * Constructs a new string given the format string and the list of the
594 * arguments for the format string.
595 *
596 * @param aFormat printf-like format string (in UTF-8 encoding).
597 * @param ... List of the arguments for the format string.
598 */
599 explicit BstrFmt(const char *aFormat, ...)
600 {
601 va_list args;
602 va_start(args, aFormat);
603 copyFrom(Utf8Str(aFormat, args).c_str());
604 va_end(args);
605 }
606};
607
608/**
609 * The BstrFmtVA class is a shortcut to <tt>Bstr(Utf8Str(format,va))</tt>.
610 */
611class BstrFmtVA : public Bstr
612{
613public:
614
615 /**
616 * Constructs a new string given the format string and the list of the
617 * arguments for the format string.
618 *
619 * @param aFormat printf-like format string (in UTF-8 encoding).
620 * @param aArgs List of arguments for the format string
621 */
622 BstrFmtVA(const char *aFormat, va_list aArgs)
623 {
624 copyFrom(Utf8Str(aFormat, aArgs).c_str());
625 }
626};
627
628} /* namespace com */
629
630#endif /* !___VBox_com_string_h */
631
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette