OSDN Git Service

Lazy<T> class: Destroy the wrapped T object when the Lazy<T> instance gets destroyed.
[mutilities/MUtilities.git] / src / Global.cpp
index f4e365f..36b6baf 100644 (file)
@@ -1,6 +1,6 @@
 ///////////////////////////////////////////////////////////////////////////////
 // MuldeR's Utilities for Qt
-// Copyright (C) 2004-2016 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2018 LoRd_MuldeR <MuldeR2@GMX.de>
 //
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 //Per-thread init flag
 static QThreadStorage<bool> g_srand_flag;
 
+//32-Bit wrapper for qrand()
+#define QRAND() ((static_cast<quint32>(qrand()) & 0xFFFF) | (static_cast<quint32>(qrand()) << 16U))
+
 //Robert Jenkins' 96 bit Mix Function
-static quint32 mix_function(const quint32 x, const quint32 y, const quint32 z)
+static quint32 mix_function(quint32 a, quint32 b, quint32 c)
 {
-       quint32 a = x;
-       quint32 b = y;
-       quint32 c = z;
-       
        a=a-b;  a=a-c;  a=a^(c >> 13);
        b=b-c;  b=b-a;  b=b^(a <<  8); 
        c=c-a;  c=c-b;  c=c^(b >> 13);
@@ -86,24 +85,30 @@ static quint32 mix_function(const quint32 x, const quint32 y, const quint32 z)
 static void seed_rand(void)
 {
        QDateTime build(MUtils::Version::lib_build_date(), MUtils::Version::lib_build_time());
-       const quint32 seed = mix_function(MUtils::OS::process_id(), MUtils::OS::thread_id(), build.toMSecsSinceEpoch());
-       qsrand(mix_function(clock(), time(NULL), seed));
+       const quint32 seed_0 = mix_function(MUtils::OS::process_id(), MUtils::OS::thread_id(), build.toMSecsSinceEpoch());
+       qsrand(mix_function(clock(), time(NULL), seed_0));
 }
 
 static quint32 rand_fallback(void)
 {
-       Q_ASSERT(RAND_MAX >= 0xFFF);
+       Q_ASSERT(RAND_MAX >= 0x7FFF);
+
        if (!(g_srand_flag.hasLocalData() && g_srand_flag.localData()))
        {
                seed_rand();
                g_srand_flag.setLocalData(true);
        }
-       quint32 rnd = 0x32288EA3;
-       for (size_t i = 0; i < 3; i++)
+
+       quint32 rnd_val = mix_function(0x32288EA3, clock(), time(NULL));
+
+       for (size_t i = 0; i < 42; i++)
        {
-               rnd = (rnd << 12) ^ qrand();
+               rnd_val = mix_function(rnd_val, QRAND(), QRAND());
+               rnd_val = mix_function(QRAND(), rnd_val, QRAND());
+               rnd_val = mix_function(QRAND(), QRAND(), rnd_val);
        }
-       return rnd;
+
+       return rnd_val;
 }
 
 quint32 MUtils::next_rand_u32(void)
@@ -393,58 +398,39 @@ static const QFile::Permissions FILE_PERMISSIONS_NONE = QFile::ReadOther | QFile
 bool MUtils::remove_file(const QString &fileName)
 {
        QFileInfo fileInfo(fileName);
-       if(!(fileInfo.exists() && fileInfo.isFile()))
-       {
-               return true;
-       }
 
-       for(int i = 0; i < 32; i++)
+       for(size_t round = 0; round < 13; ++round)
        {
-               QFile file(fileName);
-               file.setPermissions(FILE_PERMISSIONS_NONE);
-               if((!(fileInfo.exists() && fileInfo.isFile())) || file.remove())
+               if (round > 0)
                {
-                       return true;
+                       MUtils::OS::sleep_ms(round);
+                       fileInfo.refresh();
                }
-               MUtils::OS::sleep_ms(1);
-               fileInfo.refresh();
-       }
-
-       qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
-       return false;
-}
-
-static bool remove_directory_helper(const QDir &folder)
-{
-       if(!folder.exists())
-       {
-               return true;
-       }
-       const QString dirName = folder.dirName();
-       if(!dirName.isEmpty())
-       {
-               QDir parent(folder);
-               if(parent.cdUp())
+               if (fileInfo.exists())
                {
-                       QFile::setPermissions(folder.absolutePath(), FILE_PERMISSIONS_NONE);
-                       if(parent.rmdir(dirName))
+                       QFile file(fileName);
+                       if (round > 0)
                        {
-                               return true;
+                               file.setPermissions(FILE_PERMISSIONS_NONE);
                        }
+                       file.remove();
+                       fileInfo.refresh();
+               }
+               if (!fileInfo.exists())
+               {
+                       return true; /*success*/
                }
        }
+
+       qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
        return false;
 }
 
 bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
 {
-       QDir folder(folderPath);
-       if(!folder.exists())
-       {
-               return true;
-       }
+       const QDir folder(folderPath);
 
-       if(recursive)
+       if(recursive && folder.exists())
        {
                const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
                for(QFileInfoList::ConstIterator iter = entryList.constBegin(); iter != entryList.constEnd(); iter++)
@@ -453,21 +439,37 @@ bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
                        {
                                remove_directory(iter->canonicalFilePath(), true);
                        }
-                       else if(iter->isFile())
+                       else
                        {
                                remove_file(iter->canonicalFilePath());
                        }
                }
        }
 
-       for(int i = 0; i < 32; i++)
+       for(size_t round = 0; round < 13; ++round)
        {
-               if(remove_directory_helper(folder))
+               if(round > 0)
                {
-                       return true;
+                       MUtils::OS::sleep_ms(round);
+                       folder.refresh();
+               }
+               if (folder.exists())
+               {
+                       QDir parent = folder;
+                       if (parent.cdUp())
+                       {
+                               if (round > 0)
+                               {
+                                       QFile::setPermissions(folder.absolutePath(), FILE_PERMISSIONS_NONE);
+                               }
+                               parent.rmdir(folder.dirName());
+                               folder.refresh();
+                       }
+               }
+               if (!folder.exists())
+               {
+                       return true; /*success*/
                }
-               MUtils::OS::sleep_ms(1);
-               folder.refresh();
        }
        
        qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
@@ -561,7 +563,52 @@ void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
 // CLEAN FILE PATH
 ///////////////////////////////////////////////////////////////////////////////
 
-QString MUtils::clean_file_name(const QString &name)
+static QMutex                                              g_clean_file_name_mutex;
+static QScopedPointer<const QList<QPair<QRegExp,QString>>> g_clean_file_name_regex;
+
+static void clean_file_name_make_pretty(QString &str)
+{
+       static const struct { const char *p; const char *r; } PATTERN[] =
+       {
+               { "^\\s*\"([^\"]*)\"\\s*$",    "\\1"                         },  //Remove straight double quotes around the whole string
+               { "\"([^\"]*)\"",              "\xE2\x80\x9C\\1\xE2\x80\x9D" },  //Replace remaining pairs of straight double quotes with opening/closing double quote
+               { "^[\\\\/:]+([^\\\\/:]+.*)$", "\\1"                         },  //Remove leading slash, backslash and colon characters
+               { "^(.*[^\\\\/:]+)[\\\\/:]+$", "\\1"                         },  //Remove trailing slash, backslash and colon characters
+               { "(\\s*[\\\\/:]\\s*)+",       " - "                         },  //Replace any slash, backslash or colon character that appears in the middle
+               { NULL, NULL }
+       };
+
+       QMutexLocker locker(&g_clean_file_name_mutex);
+
+       if (g_clean_file_name_regex.isNull())
+       {
+               QScopedPointer<QList<QPair<QRegExp, QString>>> list(new QList<QPair<QRegExp, QString>>());
+               for (size_t i = 0; PATTERN[i].p; ++i)
+               {
+                       list->append(qMakePair(QRegExp(QString::fromUtf8(PATTERN[i].p), Qt::CaseInsensitive), PATTERN[i].r ? QString::fromUtf8(PATTERN[i].r) : QString()));
+               }
+               g_clean_file_name_regex.reset(list.take());
+       }
+
+       bool keepOnGoing = !str.isEmpty();
+       while(keepOnGoing)
+       {
+               const QString prev = str;
+               keepOnGoing = false;
+               for (QList<QPair<QRegExp, QString>>::ConstIterator iter = g_clean_file_name_regex->constBegin(); iter != g_clean_file_name_regex->constEnd(); ++iter)
+               {
+                       str.replace(iter->first, iter->second);
+                       if (str.compare(prev))
+                       {
+                               str = str.simplified();
+                               keepOnGoing = !str.isEmpty();
+                               break;
+                       }
+               }
+       }
+}
+
+QString MUtils::clean_file_name(const QString &name, const bool &pretty)
 {
        static const QLatin1Char REPLACEMENT_CHAR('_');
        static const char FILENAME_ILLEGAL_CHARS[] = "<>:\"/\\|?*";
@@ -573,11 +620,9 @@ QString MUtils::clean_file_name(const QString &name)
        };
 
        QString result(name);
-       if (result.contains(QLatin1Char('"')))
+       if (pretty)
        {
-               QRegExp quoted("\"(.+)\"");
-               quoted.setMinimal(true);
-               result.replace(quoted, "``\\1ยดยด");
+               clean_file_name_make_pretty(result);
        }
 
        for(QString::Iterator iter = result.begin(); iter != result.end(); iter++)
@@ -630,7 +675,7 @@ static QPair<QString,QString> clean_file_path_get_prefix(const QString path)
        return qMakePair(QString(), posixPath);
 }
 
-QString MUtils::clean_file_path(const QString &path)
+QString MUtils::clean_file_path(const QString &path, const bool &pretty)
 {
        const QPair<QString, QString> prefix = clean_file_path_get_prefix(path);
 
@@ -641,7 +686,7 @@ QString MUtils::clean_file_path(const QString &path)
                {
                        continue; //handle case "c:\"
                }
-               parts[i] = MUtils::clean_file_name(parts[i]);
+               parts[i] = MUtils::clean_file_name(parts[i], pretty);
        }
 
        const QString cleanPath = parts.join(QLatin1String("/"));
@@ -654,23 +699,70 @@ QString MUtils::clean_file_path(const QString &path)
 
 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 &value)
 {
-       return regexp_parse_uint32(regexp, &value, 1);
+       return regexp_parse_uint32(regexp, &value, 1U, 1U);
+}
+
+bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 &value)
+{
+       return regexp_parse_int32(regexp, &value, 1U, 1U);
+}
+
+bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 &value, const size_t &offset)
+{
+       return regexp_parse_uint32(regexp, &value, offset, 1U);
+}
+
+bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 &value, const size_t &offset)
+{
+       return regexp_parse_int32(regexp, &value, offset, 1U);
 }
 
 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &count)
 {
+       return regexp_parse_uint32(regexp, values, 1U, count);
+}
+
+bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 *values, const size_t &count)
+{
+       return regexp_parse_int32(regexp, values, 1U, count);
+}
+
+bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &offset, const size_t &count)
+{
        const QStringList caps = regexp.capturedTexts();
-       
-       if(caps.isEmpty() || (quint32(caps.count()) <= count))
+
+       if (caps.isEmpty() || (quint32(caps.count()) <= count))
        {
                return false;
        }
 
-       for(size_t i = 0; i < count; i++)
+       for (size_t i = 0; i < count; i++)
        {
                bool ok = false;
-               values[i] = caps[i+1].toUInt(&ok);
-               if(!ok)
+               values[i] = caps[offset+i].toUInt(&ok);
+               if (!ok)
+               {
+                       return false;
+               }
+       }
+
+       return true;
+}
+
+bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 *values, const size_t &offset, const size_t &count)
+{
+       const QStringList caps = regexp.capturedTexts();
+
+       if (caps.isEmpty() || (quint32(caps.count()) <= count))
+       {
+               return false;
+       }
+
+       for (size_t i = 0; i < count; i++)
+       {
+               bool ok = false;
+               values[i] = caps[offset+i].toInt(&ok);
+               if (!ok)
                {
                        return false;
                }
@@ -712,6 +804,25 @@ QStringList MUtils::available_codepages(const bool &noAliases)
 }
 
 ///////////////////////////////////////////////////////////////////////////////
+// FP MATH SUPPORT
+///////////////////////////////////////////////////////////////////////////////
+
+MUtils::fp_parts_t MUtils::break_fp(const double value)
+{
+       fp_parts_t result = { };
+       if (_finite(value))
+       {
+               result.parts[1] = modf(value, &result.parts[0]);
+       }
+       else
+       {
+               result.parts[0] = std::numeric_limits<double>::quiet_NaN();
+               result.parts[1] = std::numeric_limits<double>::quiet_NaN();
+       }
+       return result;
+}
+
+///////////////////////////////////////////////////////////////////////////////
 // SELF-TEST
 ///////////////////////////////////////////////////////////////////////////////