summaryrefslogtreecommitdiff
path: root/zen/osx_string.h
blob: ce8b10628f77067b7367b01b80863f9bbac6d19a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// **************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under *
// * GNU General Public License: http://www.gnu.org/licenses/gpl.html       *
// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved        *
// **************************************************************************

#ifndef OSX_STRING_1873641732143214324
#define OSX_STRING_1873641732143214324

#include <zen/zstring.h>
#include <CoreFoundation/CoreFoundation.h> //CFString

namespace osx
{
Zstring cfStringToZstring(const CFStringRef& cfStr);

CFStringRef        createCFString       (const char* utf8Str); //returns nullptr on error
CFMutableStringRef createMutableCFString(const char* utf8Str); //pass ownership! => ZEN_ON_SCOPE_EXIT(::CFRelease(utf8Str));













//################# implementation #####################
inline
Zstring cfStringToZstring(const CFStringRef& cfStr)
{
    if (cfStr)
    {
        //perf: try to get away cheap:
        if (const char* utf8Str = ::CFStringGetCStringPtr(cfStr, kCFStringEncodingUTF8))
            return utf8Str;

        CFIndex length = ::CFStringGetLength(cfStr);
        if (length > 0)
        {
            CFIndex bufferSize = ::CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
            Zstring buffer;
            buffer.resize(bufferSize);

            if (::CFStringGetCString(cfStr, &*buffer.begin(), bufferSize, kCFStringEncodingUTF8))
            {
                buffer.resize(zen::strLength(&*buffer.begin())); //caveat: memory consumption of returned string!
                return buffer;
            }
        }
    }
    return Zstring();
}


inline
CFStringRef createCFString(const char* utf8Str)
{
    //don't bother with CFStringCreateWithBytes: it's slightly slower, despite passing length info
    return ::CFStringCreateWithCString(nullptr,                //CFAllocatorRef alloc,
                                       utf8Str,                //const char *cStr,
                                       kCFStringEncodingUTF8); //CFStringEncoding encoding
}


inline
CFMutableStringRef createMutableCFString(const char* utf8Str)
{
    if (CFMutableStringRef strRef = ::CFStringCreateMutable(NULL, 0))
    {
        ::CFStringAppendCString(strRef, utf8Str, kCFStringEncodingUTF8);
        return strRef;
    }
    return nullptr;
}
}

#endif //OSX_STRING_1873641732143214324
bgstack15