Index.cs 16 KB

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