Use CFStringGetCStringPtr if possible to avoid wasting memory
authorAlexandra Ellwood <lxs@mit.edu>
Fri, 24 Oct 2008 00:58:38 +0000 (00:58 +0000)
committerAlexandra Ellwood <lxs@mit.edu>
Fri, 24 Oct 2008 00:58:38 +0000 (00:58 +0000)
since CFStringGetMaximumSizeForEncoding is wasteful for UTF8.

ticket: new

git-svn-id: svn://anonsvn.mit.edu/krb5/trunk@20914 dc483132-0cff-0310-8789-dd5450dbe970

src/kim/lib/mac/kim_os_string.c

index 5999021d7a76506932d5c48cf5a9c4e21be1094a..96573eec9e9100c0f7012db64b97cede19b6c53f 100644 (file)
@@ -101,21 +101,34 @@ kim_error kim_os_string_create_from_cfstring (kim_string  *out_string,
     if (!err && !in_cfstring) { err = check_error (KIM_NULL_PARAMETER_ERR); }
     
     if (!err) {
-        length = CFStringGetMaximumSizeForEncoding (CFStringGetLength (in_cfstring), 
-                                                    kCFStringEncodingUTF8) + 1;
+        char *ptr = NULL;
         
-        string = (char *) calloc (length, sizeof (char));
-        if (!string) { err = check_error (KIM_OUT_OF_MEMORY_ERR); }
+        /* check if in_cfstring is a C string internally so we can 
+         * avoid using CFStringGetMaximumSizeForEncoding which is wasteful */
+        ptr = (char *) CFStringGetCStringPtr(in_cfstring, 
+                                             kCFStringEncodingUTF8);
+        if (ptr) {
+            string = strdup (ptr);
+            if (!string) { err = check_error (KIM_OUT_OF_MEMORY_ERR); }
+
+        } else {
+            length = CFStringGetMaximumSizeForEncoding (CFStringGetLength (in_cfstring), 
+                                                        kCFStringEncodingUTF8) + 1;
+            
+            string = (char *) calloc (length, sizeof (char));
+            if (!string) { err = check_error (KIM_OUT_OF_MEMORY_ERR); }
+        
+            if (!err) {
+                if (!CFStringGetCString (in_cfstring, 
+                                         (char *) string, 
+                                         length, 
+                                         kCFStringEncodingUTF8)) {
+                    err = KIM_OUT_OF_MEMORY_ERR;
+                }        
+            }        
+        }
     }
     
-    if (!err) {
-        if (!CFStringGetCString (in_cfstring, 
-                                 (char *) string, 
-                                 length, 
-                                 kCFStringEncodingUTF8)) {
-            err = KIM_OUT_OF_MEMORY_ERR;
-        }        
-    }
     
     if (!err) {
         *out_string = string;