File indexing completed on 2021-12-21 13:28:00

0001 /**
0002  * Copyright (C) 2003 Maksim Orlovich <maksim.orlovich@kdemail.net>
0003  *
0004  * This program is free software; you can redistribute it and/or modify it under
0005  * the terms of the GNU General Public License as published by the Free Software
0006  * Foundation; either version 2 of the License, or (at your option) any later
0007  * version.
0008  *
0009  * This program is distributed in the hope that it will be useful, but WITHOUT ANY
0010  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
0011  * PARTICULAR PURPOSE. See the GNU General Public License for more details.
0012  *
0013  * You should have received a copy of the GNU General Public License along with
0014  * this program.  If not, see <http://www.gnu.org/licenses/>.
0015  */
0016 #include "stringshare.h"
0017 
0018 #include <QHash>
0019 
0020 const int SIZE = 5003;
0021 
0022 StringShare::Data* StringShare::s_data = 0;
0023 
0024 /**
0025  * We store the strings in a simple direct-mapped (i.e. no collision handling,
0026  * just replace) hash, which contain strings or null objects. This costs only
0027  * 4 bytes per slot on 32-bit archs, so with the default constant size we only
0028  * really use 40K or so.
0029  *
0030  * The end result is that many strings end up pointing to the same underlying data
0031  * object, instead of each one having its own little copy.
0032  *
0033  * More importantly, the way the tryShare function is coded ensures that
0034  * most-recently inserted text stays in the cache, which gives a better chance
0035  * of continuing to share data. (Even if something old ("foo") that was shared
0036  * gets kicked out, all the other "foo"s will still be sharing each other's
0037  * data.
0038  */
0039 
0040 struct StringShare::Data
0041 {
0042     QString  qstringHash [SIZE];
0043 };
0044 
0045 StringShare::Data* StringShare::data()
0046 {
0047     if (!s_data)
0048         s_data = new Data;
0049     return s_data;
0050 }
0051 
0052 QString StringShare::tryShare(const QString& in)
0053 {
0054     uint index = qHash(in) % SIZE;
0055 
0056     Data* dat = data();
0057     if (dat->qstringHash[index] == in) //Match
0058         return dat->qstringHash[index];
0059     else
0060     {
0061         //Else replace whatever was there before
0062         dat->qstringHash[index] = in;
0063         return in;
0064     }
0065 }
0066 
0067 // vim: set et sw=4 tw=0 sta: