StringOperations.cpp (1082B)
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* This Source Code Form is subject to the terms of the Mozilla Public 3 * License, v. 2.0. If a copy of the MPL was not distributed with this 4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 5 6 #include "StringOperations.h" 7 8 static unsigned long djbHash(const char *Str) { 9 unsigned long Hash = 5381; 10 11 for (const char *P = Str; *P; P++) { 12 // Hash * 33 + c 13 Hash = ((Hash << 5) + Hash) + *P; 14 } 15 16 return Hash; 17 } 18 19 // This doesn't actually return a hex string of |hash|, but it 20 // does... something. It doesn't really matter what. 21 static void hashToString(unsigned long Hash, char *Buffer) { 22 const char Table[] = {"0123456789abcdef"}; 23 char *P = Buffer; 24 while (Hash) { 25 *P = Table[Hash & 0xf]; 26 Hash >>= 4; 27 P++; 28 } 29 30 *P = 0; 31 } 32 33 std::string hash(const std::string &Str) { 34 static char HashStr[41]; 35 unsigned long H = djbHash(Str.c_str()); 36 hashToString(H, HashStr); 37 return std::string(HashStr); 38 } 39 40 std::string toString(int N) { return stringFormat("%d", N); }