00001
00006 #include <iostream>
00007 #include <cstdlib>
00008 #include <cstring>
00009 #include <cassert>
00010
00011 #include "LightString.h"
00012
00016 #define DEBUG_STRING 0
00017
00018 LightString::LightString(char *kMemoryPointer, unsigned size) :
00019 size(size) {
00020 memoryPointer = (char*) malloc((size + 1) * sizeof(char));
00021 memcpy(memoryPointer, kMemoryPointer, size);
00022 memoryPointer[size] = '\0';
00023 refCount = (int*) malloc(sizeof(int));
00024 *refCount = 1;
00025 #if SYNCHRONIZE_LIGHT_STRING
00026 mutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
00027 pthread_mutex_init(mutex, NULL);
00028 #endif
00029 #if DEBUG_STRING
00030 printf("Tworze stringa: %s\n", memoryPointer);
00031 #endif
00032 }
00033
00034 LightString::LightString(const LightString & ls) {
00035 #if SYNCHRONIZE_LIGHT_STRING
00036 pthread_mutex_lock(ls.mutex);
00037 #endif
00038 memoryPointer = ls.memoryPointer;
00039 size = ls.size;
00040 refCount = ls.refCount;
00041 (*refCount)++;
00042 #if SYNCHRONIZE_LIGHT_STRING
00043 mutex = ls.mutex;
00044 pthread_mutex_unlock(ls.mutex);
00045 #endif
00046 #if DEBUG_STRING
00047 printf("Kopiuje stringa: %s\n", memoryPointer);
00048 #endif
00049 }
00050
00051 LightString::~LightString() {
00052 #if DEBUG_STRING
00053 printf("Usuwam stringa: %s ->%d\n", memoryPointer, *refCount - 1);
00054 if (*refCount == 1) {
00055 printf("Permanentnie!\n");
00056 }
00057 #endif
00058 #if SYNCHRONIZE_LIGHT_STRING
00059 pthread_mutex_lock(mutex);
00060 #endif
00061 if (!--(*refCount)) {
00062 free(memoryPointer);
00063 free(refCount);
00064 #if SYNCHRONIZE_LIGHT_STRING
00065 pthread_mutex_unlock(mutex);
00066 pthread_mutex_destroy(mutex);
00067 free(mutex);
00068 #endif
00069 return;
00070 }
00071 #if SYNCHRONIZE_LIGHT_STRING
00072 pthread_mutex_unlock(mutex);
00073 #endif
00074 }
00075
00076 const LightString& LightString::operator=(const LightString& ls) {
00077
00078 #if DEBUG_STRING
00079 printf("LightString\'s operator=?! Impossible!\n");
00080 #endif
00081 this->~LightString();
00082
00083 #if SYNCHRONIZE_LIGHT_STRING
00084 pthread_mutex_lock(ls.mutex);
00085 #endif
00086 memoryPointer = ls.memoryPointer;
00087 size = ls.size;
00088 refCount = ls.refCount;
00089 (*refCount)++;
00090 #if SYNCHRONIZE_LIGHT_STRING
00091 mutex = ls.mutex;
00092 pthread_mutex_unlock(ls.mutex);
00093 #endif
00094
00095 return *this;
00096 }
00097
00098 bool operator==(const LightString& ls1, const LightString& ls2) {
00099
00100 #if DEBUG_STRING
00101 printf("Porownuje: %s (%p) z %s (%p)\n", ls1.memoryPointer, ls1.memoryPointer,
00102 ls2.memoryPointer, ls2.memoryPointer);
00103 #endif
00104
00105 if (ls1.memoryPointer == ls2.memoryPointer) {
00106 return true;
00107 } else if (ls1.size != ls2.size) {
00108 return false;
00109 } else {
00110 return (memcmp(ls1.memoryPointer, ls2.memoryPointer, ls1.size) == 0);
00111 }
00112 }