You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.5 KiB

4 years ago
  1. #if MYSQL_6_10
  2. // Copyright ?2004, 2016 Oracle and/or its affiliates. All rights reserved.
  3. //
  4. // MySQL Connector/NET is licensed under the terms of the GPLv2
  5. // <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
  6. // MySQL Connectors. There are special exceptions to the terms and
  7. // conditions of the GPLv2 as it is applied to this software, see the
  8. // FLOSS License Exception
  9. // <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
  10. //
  11. // This program is free software; you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published
  13. // by the Free Software Foundation; version 2 of the License.
  14. //
  15. // This program is distributed in the hope that it will be useful, but
  16. // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  17. // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  18. // for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License along
  21. // with this program; if not, write to the Free Software Foundation, Inc.,
  22. // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  23. using System.Collections.Generic;
  24. namespace Externals.MySql.Data.Common
  25. {
  26. internal class Cache<TKeyType, TValueType>
  27. {
  28. private readonly int _capacity;
  29. private readonly Queue<TKeyType> _keyQ;
  30. private readonly Dictionary<TKeyType, TValueType> _contents;
  31. public Cache(int initialCapacity, int capacity)
  32. {
  33. _capacity = capacity;
  34. _contents = new Dictionary<TKeyType, TValueType>(initialCapacity);
  35. if (capacity > 0)
  36. _keyQ = new Queue<TKeyType>(initialCapacity);
  37. }
  38. public TValueType this[TKeyType key]
  39. {
  40. get
  41. {
  42. TValueType val;
  43. if (_contents.TryGetValue(key, out val))
  44. return val;
  45. else
  46. return default(TValueType);
  47. }
  48. set { InternalAdd(key, value); }
  49. }
  50. public void Add(TKeyType key, TValueType value)
  51. {
  52. InternalAdd(key, value);
  53. }
  54. private void InternalAdd(TKeyType key, TValueType value)
  55. {
  56. if (!_contents.ContainsKey(key))
  57. {
  58. if (_capacity > 0)
  59. {
  60. _keyQ.Enqueue(key);
  61. if (_keyQ.Count > _capacity)
  62. _contents.Remove(_keyQ.Dequeue());
  63. }
  64. }
  65. _contents[key] = value;
  66. }
  67. }
  68. }
  69. #endif