/*
 *  UtilitySupport.h
 *  Keychain
 *
 *  Created by Wade Tregaskis on Fri Jan 24 2003.
 *  Copyright (c) 2003 Wade Tregaskis. All rights reserved.
 *
 */

#include <Security/Security.h>
#include <Foundation/NSString.h>

static inline  CSSM_DATA_PTR constDataFromNSString(NSString *string) {
    CSSM_DATA *result = NULL;

    if (string) {
        result = malloc(sizeof(CSSM_DATA));
#ifndef MAC_OS_X_VERSION_10_5
        result->Length = [string cStringLength];
        result->Data = (uint8 *)[string cString];
#else
		result->Length = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
		result->Data = (uint8 *)[string cStringUsingEncoding:NSUTF8StringEncoding];
#endif
    }

    return result;
}

static inline CSSM_DATA* dataFromNSString(NSString *string) {
    CSSM_DATA *result = NULL;

    if (string) {
        result = malloc(sizeof(CSSM_DATA));

#ifndef MAC_OS_X_VERSION_10_5
       result->Length = [string cStringLength];
        result->Data = malloc(result->Length + 1);
        [string getCString:(char *)(result->Data)];
#else
		result->Length = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
        result->Data = malloc(result->Length + 1);
		[string getCString:(char *)result->Data maxLength:sizeof(result->Data) encoding:NSUTF8StringEncoding];
#endif
    }
    
    return result;
}

static inline  CSSM_DATA_PTR constDataFromNSData(NSData *data) {
    CSSM_DATA *result = NULL;

    if (data) {
        result = malloc(sizeof(CSSM_DATA));

        result->Length = [data length];
        result->Data = (uint8 *)[data bytes];
    }

    return result;
}

static inline CSSM_DATA* dataFromNSData(NSData *data) {
    CSSM_DATA *result = NULL;

    if (data) {
        result = malloc(sizeof(CSSM_DATA));

        result->Length = [data length];
        result->Data = malloc(result->Length);
        [data getBytes:result->Data];
    }
    
    return result;
}

static inline NSString* NSStringFromData(const CSSM_DATA *data) {
    if (data) {
#ifndef MAC_OS_X_VERSION_10_5
        return [NSString stringWithCString:(const char *)data->Data length:data->Length];
#else
		return [NSString stringWithCString:(const char *)data->Data encoding:NSUTF8StringEncoding];
#endif
    } else {
        return nil;
    }
}

static inline NSData* NSDataFromData(const CSSM_DATA *data) {
    if (data) {
        return [NSData dataWithBytes:data->Data length:data->Length];
    } else {
        return nil;
    }
}

static inline BOOL OIDsAreEqual(const CSSM_OID *a, const CSSM_OID *b) {
    if (a->Length != b->Length) {
        return NO;
    } else {
        return (memcmp(a->Data, b->Data, a->Length) == 0);
    }
}
