aboutsummaryrefslogtreecommitdiff
path: root/src/common/Utilities/Util.cpp
blob: 9322cad14acad198dd5a95a94165f81f0ab62ec2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
/*
 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "Util.h"
#include "Common.h"
#include "Containers.h"
#include "IpAddress.h"
#include "StringFormat.h"
#include <utf8.h>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <cctype>
#include <cstdarg>
#include <ctime>

#if TRINITY_COMPILER == TRINITY_COMPILER_GNU
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
#endif

Tokenizer::Tokenizer(const std::string &src, const char sep, uint32 vectorReserve /*= 0*/, bool keepEmptyStrings /*= true*/)
{
    m_str = new char[src.length() + 1];
    memcpy(m_str, src.c_str(), src.length() + 1);

    if (vectorReserve)
        m_storage.reserve(vectorReserve);

    char* posold = m_str;
    char* posnew = m_str;

    for (;;)
    {
        if (*posnew == sep)
        {
            if (keepEmptyStrings || posold != posnew)
                m_storage.push_back(posold);

            posold = posnew + 1;
            *posnew = '\0';
        }
        else if (*posnew == '\0')
        {
            // Hack like, but the old code accepted these kind of broken strings,
            // so changing it would break other things
            if (posold != posnew)
                m_storage.push_back(posold);

            break;
        }

        ++posnew;
    }
}

#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
struct tm* localtime_r(time_t const* time, struct tm *result)
{
    localtime_s(result, time);
    return result;
}
#endif

tm TimeBreakdown(time_t time)
{
    tm timeLocal;
    localtime_r(&time, &timeLocal);
    return timeLocal;
}

time_t LocalTimeToUTCTime(time_t time)
{
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
    return time + _timezone;
#else
    return time + timezone;
#endif
}

time_t GetLocalHourTimestamp(time_t time, uint8 hour, bool onlyAfterTime)
{
    tm timeLocal = TimeBreakdown(time);
    timeLocal.tm_hour = 0;
    timeLocal.tm_min = 0;
    timeLocal.tm_sec = 0;
    time_t midnightLocal = mktime(&timeLocal);
    time_t hourLocal = midnightLocal + hour * HOUR;

    if (onlyAfterTime && hourLocal <= time)
        hourLocal += DAY;

    return hourLocal;
}

std::string secsToTimeString(uint64 timeInSecs, TimeFormat timeFormat, bool hoursOnly)
{
    uint64 secs    = timeInSecs % MINUTE;
    uint64 minutes = timeInSecs % HOUR / MINUTE;
    uint64 hours   = timeInSecs % DAY  / HOUR;
    uint64 days    = timeInSecs / DAY;

    if (timeFormat == TimeFormat::Numeric)
    {
        if (days)
            return Trinity::StringFormat("%u:%02u:%02u:%02u", days, hours, minutes, secs);
        else if (hours)
            return Trinity::StringFormat("%u:%02u:%02u", hours, minutes, secs);
        else if (minutes)
            return Trinity::StringFormat("%u:%02u", minutes, secs);
        else
            return Trinity::StringFormat("0:%02u", secs);
    }

    std::ostringstream ss;
    if (days)
    {
        ss << days;
        switch (timeFormat)
        {
            case TimeFormat::ShortText:
                ss << "d";
                break;
            case TimeFormat::FullText:
                if (days == 1)
                    ss << " Day ";
                else
                    ss << " Days ";
                break;
            default:
                return "<Unknown time format>";
        }
    }

    if (hours || hoursOnly)
    {
        ss << hours;
        switch (timeFormat)
        {
            case TimeFormat::ShortText:
                ss << "h";
                break;
            case TimeFormat::FullText:
                if (hours <= 1)
                    ss << " Hour ";
                else
                    ss << " Hours ";
                break;
            default:
                return "<Unknown time format>";
        }
    }
    if (!hoursOnly)
    {
        if (minutes)
        {
            ss << minutes;
            switch (timeFormat)
            {
                case TimeFormat::ShortText:
                    ss << "m";
                    break;
                case TimeFormat::FullText:
                    if (minutes == 1)
                        ss << " Minute ";
                    else
                        ss << " Minutes ";
                    break;
                default:
                    return "<Unknown time format>";
            }
        }

        if (secs || (!days && !hours && !minutes))
        {
            ss << secs;
            switch (timeFormat)
            {
                case TimeFormat::ShortText:
                    ss << "s";
                    break;
                case TimeFormat::FullText:
                    if (secs <= 1)
                        ss << " Second.";
                    else
                        ss << " Seconds.";
                    break;
                default:
                    return "<Unknown time format>";
            }
        }
    }

    return ss.str();
}

int64 MoneyStringToMoney(std::string const& moneyString)
{
    int64 money = 0;

    if (!(std::count(moneyString.begin(), moneyString.end(), 'g') == 1 ||
        std::count(moneyString.begin(), moneyString.end(), 's') == 1 ||
        std::count(moneyString.begin(), moneyString.end(), 'c') == 1))
        return 0; // Bad format

    Tokenizer tokens(moneyString, ' ');
    for (Tokenizer::const_iterator itr = tokens.begin(); itr != tokens.end(); ++itr)
    {
        std::string tokenString(*itr);
        size_t gCount = std::count(tokenString.begin(), tokenString.end(), 'g');
        size_t sCount = std::count(tokenString.begin(), tokenString.end(), 's');
        size_t cCount = std::count(tokenString.begin(), tokenString.end(), 'c');
        if (gCount + sCount + cCount != 1)
            return 0;

        uint64 amount = strtoull(*itr, nullptr, 10);
        if (gCount == 1)
            money += amount * 100 * 100;
        else if (sCount == 1)
            money += amount * 100;
        else if (cCount == 1)
            money += amount;
    }

    return money;
}

uint32 TimeStringToSecs(std::string const& timestring)
{
    uint32 secs       = 0;
    uint32 buffer     = 0;
    uint32 multiplier = 0;

    for (std::string::const_iterator itr = timestring.begin(); itr != timestring.end(); ++itr)
    {
        if (isdigit(*itr))
        {
            buffer *= 10;
            buffer += *itr - '0';
        }
        else
        {
            switch (*itr)
            {
                case 'd': multiplier = DAY;     break;
                case 'h': multiplier = HOUR;    break;
                case 'm': multiplier = MINUTE;  break;
                case 's': multiplier = 1;       break;
                default : return 0;                         //bad format
            }
            buffer *= multiplier;
            secs += buffer;
            buffer = 0;
        }
    }

    return secs;
}

std::string TimeToTimestampStr(time_t t)
{
    tm aTm;
    localtime_r(&t, &aTm);
    //       YYYY   year
    //       MM     month (2 digits 01-12)
    //       DD     day (2 digits 01-31)
    //       HH     hour (2 digits 00-23)
    //       MM     minutes (2 digits 00-59)
    //       SS     seconds (2 digits 00-59)
    return Trinity::StringFormat("%04d-%02d-%02d_%02d-%02d-%02d", aTm.tm_year + 1900, aTm.tm_mon + 1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec);
}

std::string TimeToHumanReadable(time_t t)
{
    tm time;
    localtime_r(&t, &time);
    char buf[30];
    strftime(buf, 30, "%c", &time);
    return std::string(buf);
}

/// Check if the string is a valid ip address representation
bool IsIPAddress(char const* ipaddress)
{
    if (!ipaddress)
        return false;

    boost::system::error_code error;
    Trinity::Net::make_address(ipaddress, error);
    return !error;
}

/// create PID file
uint32 CreatePIDFile(std::string const& filename)
{
    FILE* pid_file = fopen(filename.c_str(), "w");
    if (pid_file == nullptr)
        return 0;

    uint32 pid = GetPID();

    fprintf(pid_file, "%u", pid);
    fclose(pid_file);

    return pid;
}

uint32 GetPID()
{
#ifdef _WIN32
    DWORD pid = GetCurrentProcessId();
#else
    pid_t pid = getpid();
#endif

    return uint32(pid);
}

size_t utf8length(std::string& utf8str)
{
    try
    {
        return utf8::distance(utf8str.c_str(), utf8str.c_str()+utf8str.size());
    }
    catch (std::exception const&)
    {
        utf8str.clear();
        return 0;
    }
}

void utf8truncate(std::string& utf8str, size_t len)
{
    try
    {
        size_t wlen = utf8::distance(utf8str.c_str(), utf8str.c_str()+utf8str.size());
        if (wlen <= len)
            return;

        std::wstring wstr;
        wstr.resize(wlen);
        utf8::utf8to16(utf8str.c_str(), utf8str.c_str()+utf8str.size(), &wstr[0]);
        wstr.resize(len);
        char* oend = utf8::utf16to8(wstr.c_str(), wstr.c_str()+wstr.size(), &utf8str[0]);
        utf8str.resize(oend-(&utf8str[0]));                 // remove unused tail
    }
    catch (std::exception const&)
    {
        utf8str.clear();
    }
}

bool Utf8toWStr(char const* utf8str, size_t csize, wchar_t* wstr, size_t& wsize)
{
    try
    {
        Trinity::CheckedBufferOutputIterator<wchar_t> out(wstr, wsize);
        out = utf8::utf8to16(utf8str, utf8str+csize, out);
        wsize -= out.remaining(); // remaining unused space
        wstr[wsize] = L'\0';
    }
    catch (std::exception const&)
    {
        // Replace the converted string with an error message if there is enough space
        // Otherwise just return an empty string
        wchar_t const* errorMessage = L"An error occurred converting string from UTF-8 to WStr";
        size_t errorMessageLength = wcslen(errorMessage);
        if (wsize >= errorMessageLength)
        {
            wcscpy(wstr, errorMessage);
            wsize = wcslen(wstr);
        }
        else if (wsize > 0)
        {
            wstr[0] = L'\0';
            wsize = 0;
        }
        else
            wsize = 0;

        return false;
    }

    return true;
}

bool Utf8toWStr(const std::string& utf8str, std::wstring& wstr)
{
    wstr.clear();
    try
    {
        utf8::utf8to16(utf8str.c_str(), utf8str.c_str()+utf8str.size(), std::back_inserter(wstr));
    }
    catch (std::exception const&)
    {
        wstr.clear();
        return false;
    }

    return true;
}

bool WStrToUtf8(wchar_t* wstr, size_t size, std::string& utf8str)
{
    try
    {
        std::string utf8str2;
        utf8str2.resize(size*4);                            // allocate for most long case

        if (size)
        {
            char* oend = utf8::utf16to8(wstr, wstr+size, &utf8str2[0]);
            utf8str2.resize(oend-(&utf8str2[0]));               // remove unused tail
        }
        utf8str = utf8str2;
    }
    catch (std::exception const&)
    {
        utf8str.clear();
        return false;
    }

    return true;
}

bool WStrToUtf8(std::wstring const& wstr, std::string& utf8str)
{
    try
    {
        std::string utf8str2;
        utf8str2.resize(wstr.size()*4);                     // allocate for most long case

        if (wstr.size())
        {
            char* oend = utf8::utf16to8(wstr.c_str(), wstr.c_str()+wstr.size(), &utf8str2[0]);
            utf8str2.resize(oend-(&utf8str2[0]));                // remove unused tail
        }
        utf8str = utf8str2;
    }
    catch (std::exception const&)
    {
        utf8str.clear();
        return false;
    }

    return true;
}

std::wstring wstrCaseAccentInsensitiveParse(std::wstring const& wstr, LocaleConstant locale)
{
    std::wstring result;
    result.reserve(wstr.length() * 2);

    switch (locale)
    {
        case LOCALE_frFR:
            for (wchar_t wchar : wstr)
            {
                wchar = wcharToLower(wchar);
                switch (wchar)
                {
                    case 0x00A0:                             // NO-BREAK SPACE
                        result += L' ';
                        break;
                    case 0x00AB:                             // LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
                    case 0x00BB:                             // RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
                        result += L'"';
                        break;
                    case 0x00E7:                             // LATIN SMALL LETTER C WITH CEDILLA
                        result += L'c';
                        break;
                    case 0x00E8:                             // LATIN SMALL LETTER E WITH GRAVE
                    case 0x00E9:                             // LATIN SMALL LETTER E WITH ACUTE
                    case 0x00EA:                             // LATIN SMALL LETTER E WITH CIRCUMFLEX
                    case 0x00EB:                             // LATIN SMALL LETTER E WITH DIAERESIS
                        result += L'e';
                        break;
                    case 0x00EE:                             // LATIN SMALL LETTER I WITH CIRCUMFLEX
                    case 0x00EF:                             // LATIN SMALL LETTER I WITH DIAERESIS
                        result += L'i';
                        break;
                    case 0x00F2:                             // LATIN SMALL LETTER O WITH GRAVE
                    case 0x00F3:                             // LATIN SMALL LETTER O WITH ACUTE
                    case 0x00F4:                             // LATIN SMALL LETTER O WITH CIRCUMFLEX
                    case 0x00F6:                             // LATIN SMALL LETTER O WITH DIAERESIS
                        result += L'o';
                        break;
                    case 0x00F9:                             // LATIN SMALL LETTER U WITH GRAVE
                    case 0x00FA:                             // LATIN SMALL LETTER U WITH ACUTE
                    case 0x00FB:                             // LATIN SMALL LETTER U WITH CIRCUMFLEX
                    case 0x00FC:                             // LATIN SMALL LETTER U WITH DIAERESIS
                        result += L'u';
                        break;
                    case 0x0153:                             // LATIN SMALL LIGATURE OE
                        result += L'o';
                        result += L'e';
                        break;
                    case 0x2013:                             // EN DASH
                        result += L'-';
                        break;
                    case 0x2018:                             // LEFT SINGLE QUOTATION MARK
                    case 0x2019:                             // RIGHT SINGLE QUOTATION MARK
                        result += L'\'';
                        break;
                    default:
                        result += wchar;
                        break;
                }
            }
            break;
        case LOCALE_deDE:
            for (wchar_t wchar : wstr)
            {
                wchar = wcharToLower(wchar);
                if (wchar == 0x00DF)                         // LATIN SMALL LETTER SHARP S
                {
                    result += L's';
                    result += L's';
                }
                else
                    result += wchar;
            }
            break;
        case LOCALE_esES:
        case LOCALE_esMX:
        case LOCALE_itIT:
            for (wchar_t wchar : wstr)
            {
                wchar = wcharToLower(wchar);
                switch (wchar)
                {
                    case 0x00E1:                             // LATIN SMALL LETTER A WITH ACUTE
                        result += L'a';
                        break;
                    case 0x00E9:                             // LATIN SMALL LETTER E WITH ACUTE
                        result += L'e';
                        break;
                    case 0x00ED:                             // LATIN SMALL LETTER I WITH ACUTE
                        result += L'i';
                        break;
                    case 0x00F1:                             // LATIN SMALL LETTER N WITH TILDE
                        result += L'n';
                        break;
                    case 0x00F3:                             // LATIN SMALL LETTER O WITH ACUTE
                        result += L'o';
                        break;
                    case 0x00FA:                             // LATIN SMALL LETTER U WITH ACUTE
                    case 0x00FC:                             // LATIN SMALL LETTER U WITH DIAERESIS
                        result += L'u';
                        break;
                    default:
                        result += wchar;
                        break;
                }
            }
            break;
        case LOCALE_ruRU:
            for (wchar_t wchar : wstr)
            {
                wchar = wcharToLower(wchar);
                switch (wchar)
                {
                    case 0x451:                              // CYRILLIC SMALL LETTER IO
                        result += wchar_t(0x435);
                        break;
                    case 0x2013:                             // EN DASH
                        result += L'-';
                        break;
                    default:
                        result += wchar;
                        break;
                }
            }
            break;
        case LOCALE_ptBR:
            for (wchar_t wchar : wstr)
            {
                wchar = wcharToLower(wchar);
                switch (wchar)
                {
                    case 0x00E0:                             // LATIN SMALL LETTER A WITH GRAVE
                    case 0x00E1:                             // LATIN SMALL LETTER A WITH ACUTE
                    case 0x00E2:                             // LATIN SMALL LETTER A WITH CIRCUMFLEX
                    case 0x00E3:                             // LATIN SMALL LETTER A WITH TILDE
                    case 0x00E4:                             // LATIN SMALL LETTER A WITH DIAERESIS
                        result += L'a';
                        break;
                    case 0x00E7:                             // LATIN SMALL LETTER C WITH CEDILLA
                        result += L'c';
                        break;
                    case 0x00E8:                             // LATIN SMALL LETTER E WITH GRAVE
                    case 0x00E9:                             // LATIN SMALL LETTER E WITH ACUTE
                    case 0x00EA:                             // LATIN SMALL LETTER E WITH CIRCUMFLEX
                    case 0x00EB:                             // LATIN SMALL LETTER E WITH DIAERESIS
                        result += L'e';
                        break;
                    case 0x00EC:                             // LATIN SMALL LETTER I WITH GRAVE
                    case 0x00ED:                             // LATIN SMALL LETTER I WITH ACUTE
                    case 0x00EE:                             // LATIN SMALL LETTER I WITH CIRCUMFLEX
                    case 0x00EF:                             // LATIN SMALL LETTER I WITH DIAERESIS
                        result += L'i';
                        break;
                    case 0x00F1:                             // LATIN SMALL LETTER N WITH TILDE
                        result += L'n';
                        break;
                    case 0x00F2:                             // LATIN SMALL LETTER O WITH GRAVE
                    case 0x00F3:                             // LATIN SMALL LETTER O WITH ACUTE
                    case 0x00F4:                             // LATIN SMALL LETTER O WITH CIRCUMFLEX
                    case 0x00F5:                             // LATIN SMALL LETTER O WITH TILDE
                    case 0x00F6:                             // LATIN SMALL LETTER O WITH DIAERESIS
                        result += L'o';
                        break;
                    case 0x00F9:                             // LATIN SMALL LETTER U WITH GRAVE
                    case 0x00FA:                             // LATIN SMALL LETTER U WITH ACUTE
                    case 0x00FB:                             // LATIN SMALL LETTER U WITH CIRCUMFLEX
                    case 0x00FC:                             // LATIN SMALL LETTER U WITH DIAERESIS
                        result += L'u';
                        break;
                    default:
                        result += wchar;
                        break;
                }
            }
            break;
        default:
            result = wstr;
            wstrToLower(result);
            break;
    }

    return result;
}

void wstrToUpper(std::wstring& str)
{
    std::transform(str.begin(), str.end(), str.begin(), wcharToUpper);
}

void wstrToLower(std::wstring& str)
{
    std::transform(str.begin(), str.end(), str.begin(), wcharToLower);
}

std::wstring GetMainPartOfName(std::wstring const& wname, uint32 declension)
{
    // supported only Cyrillic cases
    if (wname.empty() || !isCyrillicCharacter(wname[0]) || declension > 5)
        return wname;

    // Important: end length must be <= MAX_INTERNAL_PLAYER_NAME-MAX_PLAYER_NAME (3 currently)
    static std::wstring const a_End    = { wchar_t(0x0430), wchar_t(0x0000) };
    static std::wstring const o_End    = { wchar_t(0x043E), wchar_t(0x0000) };
    static std::wstring const ya_End   = { wchar_t(0x044F), wchar_t(0x0000) };
    static std::wstring const ie_End   = { wchar_t(0x0435), wchar_t(0x0000) };
    static std::wstring const i_End    = { wchar_t(0x0438), wchar_t(0x0000) };
    static std::wstring const yeru_End = { wchar_t(0x044B), wchar_t(0x0000) };
    static std::wstring const u_End    = { wchar_t(0x0443), wchar_t(0x0000) };
    static std::wstring const yu_End   = { wchar_t(0x044E), wchar_t(0x0000) };
    static std::wstring const oj_End   = { wchar_t(0x043E), wchar_t(0x0439), wchar_t(0x0000) };
    static std::wstring const ie_j_End = { wchar_t(0x0435), wchar_t(0x0439), wchar_t(0x0000) };
    static std::wstring const io_j_End = { wchar_t(0x0451), wchar_t(0x0439), wchar_t(0x0000) };
    static std::wstring const o_m_End  = { wchar_t(0x043E), wchar_t(0x043C), wchar_t(0x0000) };
    static std::wstring const io_m_End = { wchar_t(0x0451), wchar_t(0x043C), wchar_t(0x0000) };
    static std::wstring const ie_m_End = { wchar_t(0x0435), wchar_t(0x043C), wchar_t(0x0000) };
    static std::wstring const soft_End = { wchar_t(0x044C), wchar_t(0x0000) };
    static std::wstring const j_End    = { wchar_t(0x0439), wchar_t(0x0000) };

    static std::array<std::array<std::wstring const*, 7>, 6> const dropEnds = {{
        { &a_End,  &o_End,    &ya_End,   &ie_End,  &soft_End, &j_End,    nullptr },
        { &a_End,  &ya_End,   &yeru_End, &i_End,   nullptr,   nullptr,   nullptr },
        { &ie_End, &u_End,    &yu_End,   &i_End,   nullptr,   nullptr,   nullptr },
        { &u_End,  &yu_End,   &o_End,    &ie_End,  &soft_End, &ya_End,   &a_End  },
        { &oj_End, &io_j_End, &ie_j_End, &o_m_End, &io_m_End, &ie_m_End, &yu_End },
        { &ie_End, &i_End,    nullptr,   nullptr,  nullptr,   nullptr,   nullptr }
    }};

    std::size_t const thisLen = wname.length();
    std::array<std::wstring const*, 7> const& endings = dropEnds[declension];
    for (auto itr = endings.begin(), end = endings.end(); (itr != end) && *itr; ++itr)
    {
        std::wstring const& ending = **itr;
        std::size_t const endLen = ending.length();
        if (!(endLen <= thisLen))
            continue;

        if (wname.substr(thisLen-endLen, thisLen) == ending)
            return wname.substr(0, thisLen-endLen);
    }

    return wname;
}

bool utf8ToConsole(const std::string& utf8str, std::string& conStr)
{
#if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS
    std::wstring wstr;
    if (!Utf8toWStr(utf8str, wstr))
        return false;

    conStr.resize(wstr.size());
    CharToOemBuffW(&wstr[0], &conStr[0], uint32(wstr.size()));
#else
    // not implemented yet
    conStr = utf8str;
#endif

    return true;
}

bool consoleToUtf8(const std::string& conStr, std::string& utf8str)
{
#if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS
    std::wstring wstr;
    wstr.resize(conStr.size());
    OemToCharBuffW(&conStr[0], &wstr[0], uint32(conStr.size()));

    return WStrToUtf8(wstr, utf8str);
#else
    // not implemented yet
    utf8str = conStr;
    return true;
#endif
}

bool Utf8FitTo(const std::string& str, std::wstring const& search)
{
    std::wstring temp;

    if (!Utf8toWStr(str, temp))
        return false;

    // converting to lower case
    wstrToLower(temp);

    if (temp.find(search) == std::wstring::npos)
        return false;

    return true;
}

void utf8printf(FILE* out, const char *str, ...)
{
    va_list ap;
    va_start(ap, str);
    vutf8printf(out, str, &ap);
    va_end(ap);
}

void vutf8printf(FILE* out, const char *str, va_list* ap)
{
#if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS
    char temp_buf[32 * 1024];
    wchar_t wtemp_buf[32 * 1024];

    size_t temp_len = vsnprintf(temp_buf, 32 * 1024, str, *ap);
    //vsnprintf returns -1 if the buffer is too small
    if (temp_len == size_t(-1))
        temp_len = 32*1024-1;

    size_t wtemp_len = 32*1024-1;
    Utf8toWStr(temp_buf, temp_len, wtemp_buf, wtemp_len);

    CharToOemBuffW(&wtemp_buf[0], &temp_buf[0], uint32(wtemp_len + 1));
    fprintf(out, "%s", temp_buf);
#else
    vfprintf(out, str, *ap);
#endif
}

bool Utf8ToUpperOnlyLatin(std::string& utf8String)
{
    std::wstring wstr;
    if (!Utf8toWStr(utf8String, wstr))
        return false;

    std::transform(wstr.begin(), wstr.end(), wstr.begin(), wcharToUpperOnlyLatin);

    return WStrToUtf8(wstr, utf8String);
}

std::string ByteArrayToHexStr(uint8 const* bytes, size_t arrayLen, bool reverse /* = false */)
{
    int32 init = 0;
    int32 end = arrayLen;
    int8 op = 1;

    if (reverse)
    {
        init = arrayLen - 1;
        end = -1;
        op = -1;
    }

    std::ostringstream ss;
    for (int32 i = init; i != end; i += op)
    {
        char buffer[4];
        sprintf(buffer, "%02X", bytes[i]);
        ss << buffer;
    }

    return ss.str();
}

void HexStrToByteArray(std::string const& str, uint8* out, bool reverse /*= false*/)
{
    // string must have even number of characters
    if (str.length() & 1)
        return;

    int32 init = 0;
    int32 end = int32(str.length());
    int8 op = 1;

    if (reverse)
    {
        init = int32(str.length() - 2);
        end = -2;
        op = -1;
    }

    uint32 j = 0;
    for (int32 i = init; i != end; i += 2 * op)
    {
        char buffer[3] = { str[i], str[i + 1], '\0' };
        out[j++] = uint8(strtoul(buffer, nullptr, 16));
    }
}

bool StringToBool(std::string const& str)
{
    std::string lowerStr = str;
    std::transform(str.begin(), str.end(), lowerStr.begin(), [](char c) { return char(::tolower(c)); });
    return lowerStr == "1" || lowerStr == "true" || lowerStr == "yes";
}

bool StringContainsStringI(std::string const& haystack, std::string const& needle)
{
    return haystack.end() !=
        std::search(haystack.begin(), haystack.end(), needle.begin(), needle.end(), [](char c1, char c2) { return std::toupper(c1) == std::toupper(c2); });
}

float DegToRad(float degrees)
{
    return degrees * (2.f * float(M_PI) / 360.f);
}