[vlc-commits] include/vlc_charset: Add FromCFString for darwin

Marvin Scholz git at videolan.org
Sat Oct 20 20:06:07 CEST 2018


vlc | branch: master | Marvin Scholz <epirat07 at gmail.com> | Mon Oct  8 10:51:33 2018 +0200| [f4b57268547f27172966cc7d850f797acaaa77d3] | committer: Marvin Scholz

include/vlc_charset: Add FromCFString for darwin

This is a helper function to obtain the copy of a char* from a
CFStringRef.

> http://git.videolan.org/gitweb.cgi/vlc.git/?a=commit;h=f4b57268547f27172966cc7d850f797acaaa77d3
---

 include/vlc_charset.h | 44 ++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 44 insertions(+)

diff --git a/include/vlc_charset.h b/include/vlc_charset.h
index 3c03b97a16..a2412c5d2f 100644
--- a/include/vlc_charset.h
+++ b/include/vlc_charset.h
@@ -145,6 +145,50 @@ VLC_API char * vlc_strcasestr(const char *, const char *) VLC_USED;
 VLC_API char * FromCharset( const char *charset, const void *data, size_t data_size ) VLC_USED;
 VLC_API void * ToCharset( const char *charset, const char *in, size_t *outsize ) VLC_USED;
 
+#ifdef __APPLE__
+# include <CoreFoundation/CoreFoundation.h>
+
+/* Obtains a copy of the contents of a CFString in specified encoding.
+ * Returns char* (must be freed by caller) or NULL on failure.
+ */
+VLC_USED static inline char *FromCFString(const CFStringRef cfString,
+    const CFStringEncoding cfStringEncoding)
+{
+    // Try the quick way to obtain the buffer
+    const char *tmpBuffer = CFStringGetCStringPtr(cfString, cfStringEncoding);
+
+    if (tmpBuffer != NULL) {
+       return strdup(tmpBuffer);
+    }
+
+    // The quick way did not work, try the long way
+    CFIndex length = CFStringGetLength(cfString);
+    CFIndex maxSize =
+        CFStringGetMaximumSizeForEncoding(length, cfStringEncoding);
+
+    // If result would exceed LONG_MAX, kCFNotFound is returned
+    if (unlikely(maxSize == kCFNotFound)) {
+        return NULL;
+    }
+
+    // Account for the null terminator
+    maxSize++;
+
+    char *buffer = (char *)malloc(maxSize);
+
+    if (unlikely(buffer == NULL)) {
+        return NULL;
+    }
+
+    // Copy CFString in requested encoding to buffer
+    Boolean success = CFStringGetCString(cfString, buffer, maxSize, cfStringEncoding);
+
+    if (!success)
+        FREENULL(buffer);
+    return buffer;
+}
+#endif
+
 #ifdef _WIN32
 VLC_USED
 static inline char *FromWide (const wchar_t *wide)



More information about the vlc-commits mailing list