Index.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. //
  2. // System.Data.Common.Key.cs
  3. //
  4. // Author:
  5. // Boris Kirzner <[email protected]>
  6. // Konstantin Triger ([email protected])
  7. //
  8. /*
  9. * Copyright (c) 2002-2004 Mainsoft Corporation.
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a
  12. * copy of this software and associated documentation files (the "Software"),
  13. * to deal in the Software without restriction, including without limitation
  14. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  15. * and/or sell copies of the Software, and to permit persons to whom the
  16. * Software is furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  26. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  27. * DEALINGS IN THE SOFTWARE.
  28. */
  29. using System;
  30. using System.Collections;
  31. using System.Text;
  32. namespace System.Data.Common
  33. {
  34. enum IndexDuplicatesState { Unknown, True, False };
  35. /// <summary>
  36. /// Summary description for Index.
  37. /// </summary>
  38. internal class Index
  39. {
  40. #region Fields
  41. int[] _array;
  42. int _size;
  43. Key _key;
  44. int _refCount = 0;
  45. IndexDuplicatesState _hasDuplicates;
  46. #endregion // Fields
  47. #region Constructors
  48. internal Index(Key key)
  49. {
  50. _key = key;
  51. Reset();
  52. RebuildIndex ();
  53. }
  54. #endregion // Constructors
  55. #region Properties
  56. internal Key Key
  57. {
  58. get {
  59. return _key;
  60. }
  61. }
  62. internal int Size
  63. {
  64. get {
  65. EnsureArray();
  66. return _size;
  67. }
  68. }
  69. internal int RefCount
  70. {
  71. get {
  72. return _refCount;
  73. }
  74. }
  75. internal int IndexToRecord(int index){
  76. return index < 0 ? index : Array[index];
  77. }
  78. private int[] Array
  79. {
  80. get {
  81. EnsureArray();
  82. return _array;
  83. }
  84. }
  85. internal bool HasDuplicates
  86. {
  87. get {
  88. if (_array == null || _hasDuplicates == IndexDuplicatesState.Unknown) {
  89. EnsureArray();
  90. if (_hasDuplicates == IndexDuplicatesState.Unknown) {
  91. // check for duplicates
  92. _hasDuplicates = IndexDuplicatesState.False;
  93. for(int i = 0; i < Size - 1; i++) {
  94. if (Key.CompareRecords(Array[i],Array[i+1]) == 0) {
  95. _hasDuplicates = IndexDuplicatesState.True;
  96. break;
  97. }
  98. }
  99. }
  100. }
  101. return (_hasDuplicates == IndexDuplicatesState.True);
  102. }
  103. }
  104. #endregion // Properties
  105. #region Methods
  106. internal int[] Duplicates {
  107. get {
  108. if (!HasDuplicates)
  109. return null;
  110. ArrayList dups = new ArrayList();
  111. bool inRange = false;
  112. for(int i = 0; i < Size - 1; i++) {
  113. if (Key.CompareRecords(Array[i],Array[i+1]) == 0){
  114. if (!inRange) {
  115. dups.Add(Array[i]);
  116. inRange = true;
  117. }
  118. dups.Add(Array[i+1]);
  119. }
  120. else
  121. inRange = false;
  122. }
  123. return (int[])dups.ToArray(typeof(int));
  124. }
  125. }
  126. private void EnsureArray()
  127. {
  128. if (_array == null) {
  129. RebuildIndex();
  130. }
  131. }
  132. internal int[] GetAll()
  133. {
  134. return Array;
  135. }
  136. internal void Reset()
  137. {
  138. _array = null;
  139. }
  140. private void RebuildIndex()
  141. {
  142. // consider better capacity approximation
  143. _array = new int[Key.Table.RecordCache.CurrentCapacity];
  144. _size = 0;
  145. foreach(DataRow row in Key.Table.Rows) {
  146. int record = Key.GetRecord(row);
  147. if (record != -1) {
  148. _array[_size++] = record;
  149. }
  150. }
  151. _hasDuplicates = IndexDuplicatesState.False;
  152. // Note : MergeSort may update hasDuplicates to True
  153. Sort();
  154. }
  155. private void Sort()
  156. {
  157. //QuickSort(Array,0,Size-1);
  158. MergeSort(Array,Size);
  159. }
  160. /*
  161. * Returns record number of the record equal to the key values supplied
  162. * in the meaning of index key, or -1 if no equal record found.
  163. */
  164. internal int Find(object[] keys)
  165. {
  166. int index = FindIndex(keys);
  167. return IndexToRecord(index);
  168. }
  169. /*
  170. * Returns record index (location) of the record equal to the key values supplied
  171. * in the meaning of index key, or -1 if no equal record found.
  172. */
  173. internal int FindIndex(object[] keys)
  174. {
  175. if (keys == null || keys.Length != Key.Columns.Length) {
  176. throw new ArgumentException("Expecting " + Key.Columns.Length + " value(s) for the key being indexed, " +
  177. "but received " + ((keys == null) ? 0 : keys.Length) + " value(s).");
  178. }
  179. int tmp = Key.Table.RecordCache.NewRecord();
  180. try {
  181. // init key values for temporal record
  182. for(int i = 0; i < Key.Columns.Length; i++) {
  183. Key.Columns[i].DataContainer[tmp] = keys[i];
  184. }
  185. return FindIndex(tmp);
  186. }
  187. // catch(FormatException) {
  188. // return -1;
  189. // }
  190. // catch(InvalidCastException) {
  191. // return -1;
  192. // }
  193. finally {
  194. Key.Table.RecordCache.DisposeRecord(tmp);
  195. }
  196. }
  197. /*
  198. * Returns record number of the record equal to the record supplied
  199. * in the meaning of index key, or -1 if no equal record found.
  200. */
  201. internal int Find(int record)
  202. {
  203. int index = FindIndex(record);
  204. return IndexToRecord(index);
  205. }
  206. /*
  207. * Returns array of record numbers of the records equal equal to the key values supplied
  208. * in the meaning of index key, or -1 if no equal record found.
  209. */
  210. internal int[] FindAll(object[] keys)
  211. {
  212. int[] indexes = FindAllIndexes(keys);
  213. IndexesToRecords(indexes);
  214. return indexes;
  215. }
  216. /*
  217. * Returns array of indexes of the records inside the index equal equal to the key values supplied
  218. * in the meaning of index key, or -1 if no equal record found.
  219. */
  220. internal int[] FindAllIndexes(object[] keys)
  221. {
  222. if (keys == null || keys.Length != Key.Columns.Length) {
  223. throw new ArgumentException("Expecting " + Key.Columns.Length + " value(s) for the key being indexed," +
  224. "but received " + ((keys == null) ? 0 : keys.Length) + " value(s).");
  225. }
  226. int tmp = Key.Table.RecordCache.NewRecord();
  227. try {
  228. // init key values for temporal record
  229. for(int i = 0; i < Key.Columns.Length; i++) {
  230. Key.Columns[i].DataContainer[tmp] = keys[i];
  231. }
  232. return FindAllIndexes(tmp);
  233. }
  234. catch(FormatException) {
  235. return new int[0];
  236. }
  237. catch(InvalidCastException) {
  238. return new int[0];
  239. }
  240. finally {
  241. Key.Table.RecordCache.DisposeRecord(tmp);
  242. }
  243. }
  244. /*
  245. * Returns array of record numbers of the records equal to the record supplied
  246. * in the meaning of index key, or empty list if no equal records found.
  247. */
  248. internal int[] FindAll(int record)
  249. {
  250. int[] indexes = FindAllIndexes(record);
  251. IndexesToRecords(indexes);
  252. return indexes;
  253. }
  254. /*
  255. * Returns array of indexes of the records inside the index that equal to the record supplied
  256. * in the meaning of index key, or empty list if no equal records found.
  257. */
  258. internal int[] FindAllIndexes(int record)
  259. {
  260. int index = FindIndex(record);
  261. if (index == -1) {
  262. return new int[0];
  263. }
  264. int startIndex = index++;
  265. int endIndex = index;
  266. for(;startIndex >= 0 && Key.CompareRecords(Array[startIndex],record) == 0;startIndex--);
  267. for(;endIndex < Size && Key.CompareRecords(Array[endIndex],record) == 0;endIndex++);
  268. int length = endIndex - startIndex - 1;
  269. int[] indexes = new int[length];
  270. for(int i = 0; i < length; i++) {
  271. indexes[i] = ++startIndex;
  272. }
  273. return indexes;
  274. }
  275. /*
  276. * Returns index inside the array where record number of the record equal to the record supplied
  277. * in the meaning of index key is sored, or -1 if no equal record found.
  278. */
  279. private int FindIndex(int record)
  280. {
  281. if (Size == 0) {
  282. return -1;
  283. }
  284. return BinarySearch(Array,0,Size - 1,record);
  285. }
  286. /*
  287. * Finds exact location of the record specified
  288. */
  289. private int FindIndexExact(int record)
  290. {
  291. int index = System.Array.BinarySearch(Array,record);
  292. return (index > 0) ? index : -1;
  293. }
  294. /*
  295. * Returns array of records from the indexes (locations) inside the index
  296. */
  297. private void IndexesToRecords(int[] indexes)
  298. {
  299. for(int i = 0; i < indexes.Length; i++) {
  300. indexes[i] = Array[indexes[i]];
  301. }
  302. }
  303. internal void Delete(DataRow row)
  304. {
  305. int oldRecord = Key.GetRecord(row);
  306. Delete(oldRecord);
  307. }
  308. internal void Delete(int oldRecord)
  309. {
  310. if (oldRecord == -1)
  311. return;
  312. int index = FindIndex(oldRecord);
  313. if (index != -1) {
  314. if ((_hasDuplicates == IndexDuplicatesState.True)) {
  315. int c1 = 1;
  316. int c2 = 1;
  317. if (index > 0) {
  318. c1 = Key.CompareRecords(Array[index - 1],oldRecord);
  319. }
  320. if (index < Size - 1) {
  321. c2 = Key.CompareRecords(Array[index + 1],oldRecord);
  322. }
  323. if (c1 == 0 ^ c2 == 0) {
  324. _hasDuplicates = IndexDuplicatesState.Unknown;
  325. }
  326. }
  327. Remove(index);
  328. }
  329. }
  330. private void Remove(int index)
  331. {
  332. if (Size > 1) {
  333. System.Array.Copy(Array,index+1,Array,index,Size - index - 1);
  334. }
  335. _size--;
  336. }
  337. internal void Update(DataRow row,int newRecord)
  338. {
  339. int oldRecord = Key.GetRecord(row);
  340. if (oldRecord == -1 || Size == 0) {
  341. Add(row,newRecord);
  342. return;
  343. }
  344. int oldIdx = FindIndex(oldRecord);
  345. if( oldIdx == -1 || Key.Table.RecordCache[Array[oldIdx]] != row ) {
  346. Add(row,newRecord);
  347. return;
  348. }
  349. int newIdx = -1;
  350. int compare = Key.CompareRecords(Array[oldIdx],newRecord);
  351. int start,end;
  352. int c1 = 1;
  353. int c2 = 1;
  354. if (compare == 0) {
  355. if (Array[oldIdx] == newRecord) {
  356. // we deal with the same record that didn't change
  357. // in the context of current index.
  358. // so , do nothing.
  359. return;
  360. }
  361. }
  362. else {
  363. if ((_hasDuplicates == IndexDuplicatesState.True)) {
  364. if (oldIdx > 0) {
  365. c1 = Key.CompareRecords(Array[oldIdx - 1],newRecord);
  366. }
  367. if (oldIdx < Size - 1) {
  368. c2 = Key.CompareRecords(Array[oldIdx + 1],newRecord);
  369. }
  370. if ((c1 == 0 ^ c2 == 0) && compare != 0) {
  371. _hasDuplicates = IndexDuplicatesState.Unknown;
  372. }
  373. }
  374. }
  375. if ((oldIdx == 0 && compare > 0) || (oldIdx == (Size - 1) && compare < 0) || (compare == 0)) {
  376. // no need to switch cells
  377. newIdx = oldIdx;
  378. }
  379. else {
  380. if (compare < 0) {
  381. // search after the old place
  382. start = oldIdx + 1;
  383. end = Size - 1;
  384. }
  385. else {
  386. // search before the old palce
  387. start = 0;
  388. end = oldIdx - 1;
  389. }
  390. newIdx = LazyBinarySearch(Array,start,end,newRecord);
  391. if (oldIdx < newIdx) {
  392. System.Array.Copy(Array,oldIdx + 1,Array,oldIdx,newIdx - oldIdx);
  393. }
  394. else if (oldIdx > newIdx){
  395. System.Array.Copy(Array,newIdx,Array,newIdx + 1,oldIdx - newIdx);
  396. }
  397. }
  398. Array[newIdx] = newRecord;
  399. if (compare != 0) {
  400. if (!(_hasDuplicates == IndexDuplicatesState.True)) {
  401. if (newIdx > 0) {
  402. c1 = Key.CompareRecords(Array[newIdx - 1],newRecord);
  403. }
  404. if (newIdx < Size - 1) {
  405. c2 = Key.CompareRecords(Array[newIdx + 1],newRecord);
  406. }
  407. if (c1 == 0 || c2 == 0) {
  408. _hasDuplicates = IndexDuplicatesState.True;
  409. }
  410. }
  411. }
  412. }
  413. private void Add(DataRow row,int newRecord)
  414. {
  415. int newIdx;
  416. if (!Key.CanContain (newRecord))
  417. return;
  418. if (Size == 0) {
  419. newIdx = 0;
  420. }
  421. else {
  422. newIdx = LazyBinarySearch(Array,0,Size - 1,newRecord);
  423. // if newl value is greater - insert afer old value
  424. // else - insert before old value
  425. if (Key.CompareRecords(Array[newIdx],newRecord) < 0) {
  426. newIdx++;
  427. }
  428. }
  429. Insert(newIdx,newRecord);
  430. int c1 = 1;
  431. int c2 = 1;
  432. if (!(_hasDuplicates == IndexDuplicatesState.True)) {
  433. if (newIdx > 0) {
  434. c1 = Key.CompareRecords(Array[newIdx - 1],newRecord);
  435. }
  436. if (newIdx < Size - 1) {
  437. c2 = Key.CompareRecords(Array[newIdx + 1],newRecord);
  438. }
  439. if (c1 == 0 || c2 == 0) {
  440. _hasDuplicates = IndexDuplicatesState.True;
  441. }
  442. }
  443. }
  444. private void Insert(int index,int r)
  445. {
  446. if (Array.Length == Size) {
  447. int[] tmp = (Size == 0) ? new int[16] : new int[Size << 1];
  448. System.Array.Copy(Array,0,tmp,0,index);
  449. tmp[index] = r;
  450. System.Array.Copy(Array,index,tmp,index + 1,Size - index);
  451. _array = tmp;
  452. }
  453. else {
  454. System.Array.Copy(Array,index,Array,index + 1,Size - index);
  455. Array[index] = r;
  456. }
  457. _size++;
  458. }
  459. private void MergeSort(int[] to, int length)
  460. {
  461. int[] from = new int[length];
  462. System.Array.Copy(to, 0, from, 0, from.Length);
  463. MergeSort(from, to, 0, from.Length);
  464. }
  465. private void MergeSort(int[] from, int[] to,int p, int r)
  466. {
  467. int q = (p + r) >> 1;
  468. if (q == p) {
  469. return;
  470. }
  471. MergeSort(to, from, p, q);
  472. MergeSort(to, from, q, r);
  473. // merge
  474. for (int middle = q, current = p;;) {
  475. int res = Key.CompareRecords(from[p],from[q]);
  476. if (res > 0) {
  477. to[current++] = from[q++];
  478. if (q == r) {
  479. while( p < middle) {
  480. to[current++] = from[p++];
  481. }
  482. break;
  483. }
  484. }
  485. else {
  486. if (res == 0) {
  487. _hasDuplicates = IndexDuplicatesState.True;
  488. }
  489. to[current++] = from[p++];
  490. if (p == middle) {
  491. while( q < r) {
  492. to[current++] = from[q++];
  493. }
  494. break;
  495. }
  496. }
  497. }
  498. }
  499. private void QuickSort(int[] a,int p,int r)
  500. {
  501. if (p < r) {
  502. int q = Partition(a,p,r);
  503. QuickSort(a,p,q);
  504. QuickSort(a,q+1,r);
  505. }
  506. }
  507. private int Partition(int[] a,int p,int r)
  508. {
  509. int x = a[p];
  510. int i = p - 1;
  511. int j = r + 1;
  512. while(true) {
  513. // decrement upper limit while values are greater then border value
  514. do {
  515. j--;
  516. }
  517. while(Key.CompareRecords(a[j],x) > 0); //while(a[j] > x);
  518. do {
  519. i++;
  520. }
  521. while(Key.CompareRecords(a[i],x) < 0); //while(a[i] < x);
  522. if (i<j) {
  523. int tmp = a[j];
  524. a[j] = a[i];
  525. a[i] = tmp;
  526. }
  527. else {
  528. return j;
  529. }
  530. }
  531. }
  532. private int BinarySearch(int[] a, int p, int r,int b)
  533. {
  534. int i = LazyBinarySearch(a,p,r,b);
  535. return (Key.CompareRecords(a[i],b) == 0) ? i : -1;
  536. }
  537. // Lazy binary search only returns the cell number the search finished in,
  538. // but does not checks that the correct value was actually found
  539. private int LazyBinarySearch(int[] a, int p, int r,int b)
  540. {
  541. if ( p == r ) {
  542. return p;
  543. }
  544. int q = (p+r) >> 1;
  545. int compare = Key.CompareRecords(a[q],b);
  546. if (compare < 0) { // if (a[q] < b) {
  547. return LazyBinarySearch(a,q+1,r,b);
  548. }
  549. else if (compare > 0) { // a[q] > b
  550. return LazyBinarySearch(a,p,q,b);
  551. }
  552. else { // a[q] == b
  553. return q;
  554. }
  555. }
  556. internal void AddRef()
  557. {
  558. _refCount++;
  559. }
  560. internal void RemoveRef()
  561. {
  562. _refCount--;
  563. }
  564. /*
  565. // Prints indexes. For debugging.
  566. internal void Print ()
  567. {
  568. for (int i=0; i < Size; i++) {
  569. Console.Write ("Index {0} record {1}: ", i, Array [i]);
  570. for (int j=0; j < Key.Table.Columns.Count; j++) {
  571. DataColumn col = Key.Table.Columns [j];
  572. if (Array [i] >= 0)
  573. Console.Write ("{0,15} ", col [Array [i]]);
  574. }
  575. Console.WriteLine ();
  576. }
  577. }
  578. */
  579. #endregion // Methods
  580. }
  581. }