Line data Source code
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 "nsString.h"
7 : #include "nsISupports.h"
8 : #include "nsILocale.h"
9 : #include "nsLocale.h"
10 : #include "nsMemory.h"
11 : #include "nsCRT.h"
12 :
13 : #define LOCALE_HASH_SIZE 0xFF
14 :
15 :
16 : /* nsILocale */
17 0 : NS_IMPL_ISUPPORTS(nsLocale, nsILocale)
18 :
19 0 : nsLocale::nsLocale(void)
20 0 : : fHashtable(nullptr), fCategoryCount(0)
21 : {
22 0 : fHashtable = PL_NewHashTable(LOCALE_HASH_SIZE,&nsLocale::Hash_HashFunction,
23 : &nsLocale::Hash_CompareNSString,
24 : &nsLocale::Hash_CompareNSString,
25 : nullptr, nullptr);
26 0 : NS_ASSERTION(fHashtable, "nsLocale: failed to allocate PR_Hashtable");
27 0 : }
28 :
29 0 : nsLocale::~nsLocale(void)
30 : {
31 : // enumerate all the entries with a delete function to
32 : // safely delete all the keys and values
33 0 : PL_HashTableEnumerateEntries(fHashtable, &nsLocale::Hash_EnumerateDelete,
34 0 : nullptr);
35 :
36 0 : PL_HashTableDestroy(fHashtable);
37 0 : }
38 :
39 : NS_IMETHODIMP
40 0 : nsLocale::GetCategory(const nsAString& category, nsAString& result)
41 : {
42 : const char16_t *value = (const char16_t*)
43 0 : PL_HashTableLookup(fHashtable, PromiseFlatString(category).get());
44 :
45 0 : if (value)
46 : {
47 0 : result.Assign(value);
48 0 : return NS_OK;
49 : }
50 :
51 0 : return NS_ERROR_FAILURE;
52 : }
53 :
54 : NS_IMETHODIMP
55 0 : nsLocale::AddCategory(const nsAString &category, const nsAString &value)
56 : {
57 0 : char16_t* newKey = ToNewUnicode(category);
58 0 : if (!newKey)
59 0 : return NS_ERROR_OUT_OF_MEMORY;
60 :
61 0 : char16_t* newValue = ToNewUnicode(value);
62 0 : if (!newValue) {
63 0 : free(newKey);
64 0 : return NS_ERROR_OUT_OF_MEMORY;
65 : }
66 :
67 0 : if (!PL_HashTableAdd(fHashtable, newKey, newValue)) {
68 0 : free(newKey);
69 0 : free(newValue);
70 0 : return NS_ERROR_OUT_OF_MEMORY;
71 : }
72 :
73 0 : return NS_OK;
74 : }
75 :
76 :
77 : PLHashNumber
78 0 : nsLocale::Hash_HashFunction(const void* key)
79 : {
80 0 : const char16_t* ptr = (const char16_t *) key;
81 : PLHashNumber hash;
82 :
83 0 : hash = (PLHashNumber)0;
84 :
85 0 : while (*ptr)
86 0 : hash += (PLHashNumber) *ptr++;
87 :
88 0 : return hash;
89 : }
90 :
91 :
92 : int
93 0 : nsLocale::Hash_CompareNSString(const void* s1, const void* s2)
94 : {
95 0 : return !nsCRT::strcmp((const char16_t *) s1, (const char16_t *) s2);
96 : }
97 :
98 :
99 : int
100 0 : nsLocale::Hash_EnumerateDelete(PLHashEntry *he, int hashIndex, void *arg)
101 : {
102 : // delete an entry
103 0 : free((char16_t *)he->key);
104 0 : free((char16_t *)he->value);
105 :
106 0 : return (HT_ENUMERATE_NEXT | HT_ENUMERATE_REMOVE);
107 : }
108 :
|