Hashtable.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. //
  2. // System.Collections.Hashtable
  3. //
  4. // Author:
  5. // Sergey Chaban ([email protected])
  6. //
  7. using System;
  8. using System.Collections;
  9. // TODO: 1. Interfaces to implement: ISerializable and IDeserializationCallback;
  10. // Synchronized wrapper (it's really easy but requires at least
  11. // System.Threading.Monitor to be present, maybe just a stub for now).
  12. // 2. Meaningfull error messages for all exceptions.
  13. namespace System.Collections {
  14. public class Hashtable : IDictionary, ICollection,
  15. IEnumerable, ICloneable {
  16. internal struct slot {
  17. internal Object key;
  18. internal Object value;
  19. // Hashcode. Chains are also marked through this.
  20. internal int hashMix;
  21. }
  22. //
  23. // Private data
  24. //
  25. private readonly static int CHAIN_MARKER=~Int32.MaxValue;
  26. private readonly static int ALLOC_GRAIN=0x2F;
  27. // Used as indicator for the removed parts of a chain.
  28. private readonly static Object REMOVED_MARKER=new Object();
  29. private int inUse;
  30. private int modificationCount;
  31. private float loadFactor;
  32. private slot[] table;
  33. private int threshold;
  34. private IHashCodeProvider m_hcp;
  35. private IComparer m_comparer;
  36. public static int[] primeTbl={};
  37. // Class constructor
  38. static Hashtable() {
  39. // NOTE: Precalculate primes table.
  40. // This precalculated table of primes is intended
  41. // to speed-up allocations/resize for relatively
  42. // small tables.
  43. // I'm not sure whether it's a good idea or not.
  44. // Also I am in doubt as for the quality of this
  45. // particular implementation, probably the increment
  46. // shouldn't be linear? Consider this as a hack
  47. // or as a placeholder for future improvements.
  48. int size=0x2000/ALLOC_GRAIN;
  49. primeTbl=new int[size];
  50. for (int x=53,i=0;i<size;x+=ALLOC_GRAIN,i++) {
  51. primeTbl[i]=CalcPrime(x);
  52. }
  53. }
  54. //
  55. // Constructors
  56. //
  57. public Hashtable() : this(0,1.0f) {}
  58. public Hashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) {
  59. if (capacity<0)
  60. throw new ArgumentOutOfRangeException("negative capacity");
  61. if (loadFactor<0.1 || loadFactor>1)
  62. throw new ArgumentOutOfRangeException("load factor");
  63. if (capacity==0) ++capacity;
  64. this.loadFactor=0.75f*loadFactor;
  65. int size=(int)(capacity/this.loadFactor);
  66. size=ToPrime(size);
  67. this.SetTable(new slot[size]);
  68. this.hcp=hcp;
  69. this.comparer=comparer;
  70. this.inUse=0;
  71. this.modificationCount=0;
  72. }
  73. public Hashtable(int capacity, float loadFactor) :
  74. this(capacity,loadFactor,null,null) {}
  75. public Hashtable(int capacity) : this(capacity,1.0f) {}
  76. public Hashtable(int capacity,
  77. IHashCodeProvider hcp,
  78. IComparer comparer
  79. ) : this(capacity,1.0f,hcp,comparer) {}
  80. public Hashtable(IDictionary d, float loadFactor,
  81. IHashCodeProvider hcp,IComparer comparer)
  82. : this(d!=null?d.Count:0,
  83. loadFactor,hcp,comparer) {
  84. if (d==null)
  85. throw new ArgumentNullException("dictionary");
  86. IDictionaryEnumerator it=d.GetEnumerator();
  87. while (it.MoveNext()) {
  88. Add(it.Key,it.Value);
  89. }
  90. }
  91. public Hashtable(IDictionary d, float loadFactor)
  92. : this(d,loadFactor,null,null) {}
  93. public Hashtable(IDictionary d) : this(d,1.0f) {}
  94. public Hashtable(IDictionary d, IHashCodeProvider hcp,IComparer comparer)
  95. : this(d,1.0f,hcp,comparer) {}
  96. public Hashtable(IHashCodeProvider hcp,IComparer comparer)
  97. : this(1,1.0f,hcp,comparer) {}
  98. //
  99. // Properties
  100. //
  101. protected IComparer comparer {
  102. set {
  103. m_comparer=value;
  104. }
  105. get {
  106. return m_comparer;
  107. }
  108. }
  109. protected IHashCodeProvider hcp {
  110. set {
  111. m_hcp=value;
  112. }
  113. get {
  114. return m_hcp;
  115. }
  116. }
  117. // ICollection
  118. public virtual int Count {
  119. get {
  120. return inUse;
  121. }
  122. }
  123. public virtual bool IsSynchronized {
  124. get {
  125. return false;
  126. }
  127. }
  128. public virtual Object SyncRoot {
  129. get {
  130. return this;
  131. }
  132. }
  133. // IDictionary
  134. public virtual bool IsFixedSize {
  135. get {
  136. return false;
  137. }
  138. }
  139. public virtual bool IsReadOnly {
  140. get {
  141. return false;
  142. }
  143. }
  144. public virtual ICollection Keys {
  145. get {
  146. return new HashKeys(this);
  147. }
  148. }
  149. public virtual ICollection Values {
  150. get {
  151. return new HashValues(this);
  152. }
  153. }
  154. public virtual Object this[Object key] {
  155. get {
  156. return GetImpl(key);
  157. }
  158. set {
  159. PutImpl(key,value,true);
  160. }
  161. }
  162. //
  163. // Interface methods
  164. //
  165. // IEnumerable
  166. IEnumerator IEnumerable.GetEnumerator() {
  167. return new Enumerator(this,EnumeratorMode.KEY_MODE);
  168. }
  169. // ICollection
  170. public virtual void CopyTo(Array array, int arrayIndex) {
  171. IDictionaryEnumerator it=GetEnumerator();
  172. int i=arrayIndex;
  173. while (it.MoveNext()) {
  174. array.SetValue(it.Entry,i++);
  175. }
  176. }
  177. // IDictionary
  178. public virtual void Add(Object key, Object value) {
  179. PutImpl(key,value,false);
  180. }
  181. public virtual void Clear() {
  182. for (int i=0;i<table.Length;i++) {
  183. table[i].key=null;
  184. table[i].value=null;
  185. table[i].hashMix=0;
  186. }
  187. }
  188. public virtual bool Contains(Object key) {
  189. return (Find(key)>=0);
  190. }
  191. public virtual IDictionaryEnumerator GetEnumerator() {
  192. return new Enumerator(this,EnumeratorMode.KEY_MODE);
  193. }
  194. public virtual void Remove(Object key) {
  195. int i=Find(key);
  196. slot[] table=this.table;
  197. if (i>=0) {
  198. int h=table[i].hashMix;
  199. h&=CHAIN_MARKER;
  200. table[i].hashMix=h;
  201. table[i].key=(h!=0)
  202. ? REMOVED_MARKER
  203. : null;
  204. table[i].value=null;
  205. --inUse;
  206. ++modificationCount;
  207. }
  208. }
  209. public virtual bool ContainsKey(object key) {
  210. return Contains(key);
  211. }
  212. public virtual bool ContainsValue(object value) {
  213. int size=this.table.Length;
  214. slot[] table=this.table;
  215. for (int i=0;i<size;i++) {
  216. slot entry=table[i];
  217. if (entry.key!=null
  218. && entry.key!=REMOVED_MARKER
  219. && value.Equals(entry.value)) {
  220. return true;
  221. }
  222. }
  223. return false;
  224. }
  225. // ICloneable
  226. public virtual object Clone() {
  227. Hashtable ht=new Hashtable(Count, hcp, comparer);
  228. ht.modificationCount=this.modificationCount;
  229. ht.inUse=this.inUse;
  230. ht.AdjustThreshold();
  231. // FIXME: maybe it's faster to simply
  232. // copy the back-end array?
  233. IDictionaryEnumerator it=GetEnumerator();
  234. while (it.MoveNext()) {
  235. ht[it.Key]=it.Value;
  236. }
  237. return ht;
  238. }
  239. // TODO: public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {}
  240. // TODO: public virtual void OnDeserialization(object sender);
  241. public override string ToString() {
  242. // FIXME: What's it supposed to do?
  243. // Maybe print out some internals here? Anyway.
  244. return "mono::System.Collections.Hashtable";
  245. }
  246. /// <summary>
  247. /// Returns a synchronized (thread-safe)
  248. /// wrapper for the Hashtable.
  249. /// </summary>
  250. public static Hashtable Synchronized(Hashtable table) {
  251. // TODO: implement
  252. return null;
  253. }
  254. //
  255. // Protected instance methods
  256. //
  257. /// <summary>Returns the hash code for the specified key.</summary>
  258. protected virtual int GetHash(Object key) {
  259. IHashCodeProvider hcp=this.hcp;
  260. return (hcp!=null)
  261. ? hcp.GetHashCode()
  262. : key.GetHashCode();
  263. }
  264. /// <summary>
  265. /// Compares a specific Object with a specific key
  266. /// in the Hashtable.
  267. /// </summary>
  268. protected virtual bool KeyEquals(Object item,Object key) {
  269. IComparer c=this.comparer;
  270. if (c!=null)
  271. return (c.Compare(item,key)==0);
  272. else
  273. return item.Equals(key);
  274. }
  275. //
  276. // Private instance methods
  277. //
  278. private void AdjustThreshold() {
  279. int size=table.Length;
  280. threshold=(int)(size*loadFactor);
  281. if (this.threshold>=size) threshold=size-1;
  282. }
  283. private void SetTable(slot[] table) {
  284. if (table==null)
  285. throw new ArgumentNullException("table");
  286. this.table=table;
  287. AdjustThreshold();
  288. }
  289. private Object GetImpl(Object key) {
  290. int i=Find(key);
  291. if (i>=0)
  292. return table[i].value;
  293. else
  294. return null;
  295. }
  296. private int Find(Object key) {
  297. if (key==null)
  298. throw new ArgumentNullException("null key");
  299. uint size=(uint)this.table.Length;
  300. int h=this.GetHash(key) & Int32.MaxValue;
  301. uint spot=(uint)h;
  302. uint step=(uint)((h>>5)+1)%(size-1)+1;
  303. slot[] table=this.table;
  304. for (int i=0;i<size;i++) {
  305. int indx=(int)(spot%size);
  306. slot entry=table[indx];
  307. Object k=entry.key;
  308. if (k==null) return -1;
  309. if ((entry.hashMix & Int32.MaxValue)==h
  310. && this.KeyEquals(key,k)) {
  311. return indx;
  312. }
  313. if ((entry.hashMix & CHAIN_MARKER)==0)
  314. return -1;
  315. spot+=step;
  316. }
  317. return -1;
  318. }
  319. private void Rehash() {
  320. int oldSize=this.table.Length;
  321. // From the SDK docs:
  322. // Hashtable is automatically increased
  323. // to the smallest prime number that is larger
  324. // than twice the current number of Hashtable buckets
  325. uint newSize=(uint)ToPrime((oldSize<<1)|1);
  326. slot[] newTable=new slot[newSize];
  327. slot[] table=this.table;
  328. for (int i=0;i<oldSize;i++) {
  329. slot s=table[i];
  330. if (s.key!=null) {
  331. int h=s.hashMix & Int32.MaxValue;
  332. uint spot=(uint)h;
  333. uint step=((uint)(h>>5)+1)%(newSize-1)+1;
  334. for (uint j=spot%newSize;;spot+=step,j=spot%newSize) {
  335. // No check for REMOVED_MARKER here,
  336. // because the table is just allocated.
  337. if (newTable[j].key==null) {
  338. newTable[j].key=s.key;
  339. newTable[j].value=s.value;
  340. newTable[j].hashMix|=h;
  341. break;
  342. } else {
  343. newTable[j].hashMix|=CHAIN_MARKER;
  344. }
  345. }
  346. }
  347. }
  348. ++this.modificationCount;
  349. this.SetTable(newTable);
  350. }
  351. private void PutImpl(Object key,Object value,bool overwrite) {
  352. if (key==null)
  353. throw new ArgumentNullException("null key");
  354. uint size=(uint)this.table.Length;
  355. if (this.inUse>=this.threshold) {
  356. this.Rehash();
  357. size=(uint)this.table.Length;
  358. }
  359. int h=this.GetHash(key) & Int32.MaxValue;
  360. uint spot=(uint)h;
  361. uint step=(uint)((spot>>5)+1)%(size-1)+1;
  362. slot[] table=this.table;
  363. slot entry;
  364. int freeIndx=-1;
  365. for (int i=0;i<size;i++) {
  366. int indx=(int)(spot%size);
  367. entry=table[indx];
  368. if (freeIndx==-1
  369. && entry.key==REMOVED_MARKER
  370. && (entry.hashMix & CHAIN_MARKER)!=0) freeIndx=indx;
  371. if (entry.key==null ||
  372. (entry.key==REMOVED_MARKER
  373. && (entry.hashMix & CHAIN_MARKER)!=0)) {
  374. if (freeIndx==-1) freeIndx=indx;
  375. break;
  376. }
  377. if ((entry.hashMix & Int32.MaxValue)==h
  378. && KeyEquals(key,entry.key)) {
  379. if (overwrite) {
  380. table[indx].value=value;
  381. ++this.modificationCount;
  382. } else {
  383. // Handle Add():
  384. // An entry with the same key already exists in the Hashtable.
  385. throw new ArgumentException("Key duplication");
  386. }
  387. return;
  388. }
  389. if (freeIndx==-1) {
  390. table[indx].hashMix|=CHAIN_MARKER;
  391. }
  392. spot+=step;
  393. }
  394. if (freeIndx!=-1) {
  395. table[freeIndx].key=key;
  396. table[freeIndx].value=value;
  397. table[freeIndx].hashMix|=h;
  398. ++this.inUse;
  399. ++this.modificationCount;
  400. }
  401. }
  402. private void CopyToArray(Array arr,int i,
  403. EnumeratorMode mode) {
  404. IEnumerator it=new Enumerator(this,mode);
  405. while (it.MoveNext()) {
  406. arr.SetValue(it.Current,i++);
  407. }
  408. }
  409. //
  410. // Private static methods
  411. //
  412. private static bool TestPrime(int x) {
  413. if ((x & 1)!=0) {
  414. for (int n=3;n<(int)Math.Sqrt(x);n+=2) {
  415. if (x%n==0) return false;
  416. }
  417. return true;
  418. }
  419. // There is only one even prime - 2.
  420. return (x==2);
  421. }
  422. private static int CalcPrime(int x) {
  423. for (int i=(x&(~1))-1;i<Int32.MaxValue;i+=2) {
  424. if (TestPrime(i)) return i;
  425. }
  426. return x;
  427. }
  428. private static int ToPrime(int x) {
  429. for (int i=x/ALLOC_GRAIN;i<primeTbl.Length;i++) {
  430. if (x<=primeTbl[i]) return primeTbl[i];
  431. }
  432. return CalcPrime(x);
  433. }
  434. //
  435. // Inner classes
  436. //
  437. public enum EnumeratorMode : int {KEY_MODE=0,VALUE_MODE};
  438. protected sealed class Enumerator : IDictionaryEnumerator, IEnumerator {
  439. private Hashtable host;
  440. private int stamp;
  441. private int pos;
  442. private int size;
  443. private EnumeratorMode mode;
  444. private Object currentKey;
  445. private Object currentValue;
  446. private readonly static string xstr="Hashtable.Enumerator: snapshot out of sync.";
  447. public Enumerator(Hashtable host,EnumeratorMode mode) {
  448. this.host=host;
  449. stamp=host.modificationCount;
  450. size=host.table.Length;
  451. this.mode=mode;
  452. Reset();
  453. }
  454. public Enumerator(Hashtable host)
  455. : this(host,EnumeratorMode.KEY_MODE) {}
  456. private void FailFast() {
  457. if (host.modificationCount!=stamp) {
  458. throw new InvalidOperationException(xstr);
  459. }
  460. }
  461. public void Reset() {
  462. FailFast();
  463. pos=-1;
  464. currentKey=null;
  465. currentValue=null;
  466. }
  467. public bool MoveNext() {
  468. FailFast();
  469. if (pos<size) while (++pos<size) {
  470. slot entry=host.table[pos];
  471. if (entry.key!=null && entry.key!=REMOVED_MARKER) {
  472. currentKey=entry.key;
  473. currentValue=entry.value;
  474. return true;
  475. }
  476. }
  477. currentKey=null;
  478. currentValue=null;
  479. return false;
  480. }
  481. public DictionaryEntry Entry {
  482. get {
  483. FailFast();
  484. return new DictionaryEntry(currentKey,currentValue);
  485. }
  486. }
  487. public Object Key {
  488. get {
  489. FailFast();
  490. return currentKey;
  491. }
  492. }
  493. public Object Value {
  494. get {
  495. FailFast();
  496. return currentValue;
  497. }
  498. }
  499. public Object Current {
  500. get {
  501. FailFast();
  502. return (mode==EnumeratorMode.KEY_MODE)
  503. ? currentKey
  504. : currentValue;
  505. }
  506. }
  507. }
  508. protected class HashKeys : ICollection, IEnumerable {
  509. private Hashtable host;
  510. private int count;
  511. public HashKeys(Hashtable host) {
  512. if (host==null)
  513. throw new ArgumentNullException();
  514. this.host=host;
  515. this.count=host.Count;
  516. }
  517. // ICollection
  518. public virtual int Count {
  519. get {return count;}
  520. }
  521. public virtual bool IsSynchronized {
  522. get {return host.IsSynchronized;}
  523. }
  524. public virtual Object SyncRoot {
  525. get {return host.SyncRoot;}
  526. }
  527. public virtual void CopyTo(Array array, int arrayIndex) {
  528. host.CopyToArray(array,arrayIndex,EnumeratorMode.KEY_MODE);
  529. }
  530. // IEnumerable
  531. public virtual IEnumerator GetEnumerator() {
  532. return new Hashtable.Enumerator(host,EnumeratorMode.KEY_MODE);
  533. }
  534. }
  535. protected class HashValues : ICollection, IEnumerable {
  536. private Hashtable host;
  537. private int count;
  538. public HashValues(Hashtable host) {
  539. if (host==null)
  540. throw new ArgumentNullException();
  541. this.host=host;
  542. this.count=host.Count;
  543. }
  544. // ICollection
  545. public virtual int Count {
  546. get {return count;}
  547. }
  548. public virtual bool IsSynchronized {
  549. get {return host.IsSynchronized;}
  550. }
  551. public virtual Object SyncRoot {
  552. get {return host.SyncRoot;}
  553. }
  554. public virtual void CopyTo(Array array, int arrayIndex) {
  555. host.CopyToArray(array,arrayIndex,EnumeratorMode.VALUE_MODE);
  556. }
  557. // IEnumerable
  558. public virtual IEnumerator GetEnumerator() {
  559. return new Hashtable.Enumerator(host,EnumeratorMode.VALUE_MODE);
  560. }
  561. }
  562. }
  563. }