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.

IndexPageCache.java 45KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501
  1. /*
  2. Copyright (c) 2008 Health Market Science, Inc.
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  14. USA
  15. You can contact Health Market Science at info@healthmarketscience.com
  16. or at the following address:
  17. Health Market Science
  18. 2700 Horizon Drive
  19. Suite 200
  20. King of Prussia, PA 19406
  21. */
  22. package com.healthmarketscience.jackcess;
  23. import java.io.IOException;
  24. import java.lang.ref.Reference;
  25. import java.lang.ref.SoftReference;
  26. import java.util.AbstractList;
  27. import java.util.ArrayList;
  28. import java.util.Collections;
  29. import java.util.HashMap;
  30. import java.util.Iterator;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.RandomAccess;
  34. import static com.healthmarketscience.jackcess.IndexData.*;
  35. /**
  36. * Manager of the index pages for a BigIndex.
  37. * @author James Ahlborn
  38. */
  39. public class IndexPageCache
  40. {
  41. private enum UpdateType {
  42. ADD, REMOVE, REPLACE;
  43. }
  44. /** the index whose pages this cache is managing */
  45. private final BigIndexData _indexData;
  46. /** the root page for the index */
  47. private DataPageMain _rootPage;
  48. /** the currently loaded pages for this index, pageNumber -> page */
  49. private final Map<Integer, DataPageMain> _dataPages =
  50. new HashMap<Integer, DataPageMain>();
  51. /** the currently modified index pages */
  52. private final List<CacheDataPage> _modifiedPages =
  53. new ArrayList<CacheDataPage>();
  54. public IndexPageCache(BigIndexData indexData) {
  55. _indexData = indexData;
  56. }
  57. public BigIndexData getIndexData() {
  58. return _indexData;
  59. }
  60. public PageChannel getPageChannel() {
  61. return getIndexData().getPageChannel();
  62. }
  63. /**
  64. * Sets the root page for this index, must be called before normal usage.
  65. *
  66. * @param pageNumber the root page number
  67. */
  68. public void setRootPageNumber(int pageNumber) throws IOException {
  69. _rootPage = getDataPage(pageNumber);
  70. // root page has no parent
  71. _rootPage.initParentPage(INVALID_INDEX_PAGE_NUMBER, false);
  72. }
  73. /**
  74. * Writes any outstanding changes for this index to the file.
  75. */
  76. public void write()
  77. throws IOException
  78. {
  79. // first discard any empty pages
  80. handleEmptyPages();
  81. // next, handle any necessary page splitting
  82. preparePagesForWriting();
  83. // finally, write all the modified pages (which are not being deleted)
  84. writeDataPages();
  85. }
  86. /**
  87. * Handles any modified pages which are empty as the first pass during a
  88. * {@link #write} call. All empty pages are removed from the _modifiedPages
  89. * collection by this method.
  90. */
  91. private void handleEmptyPages() throws IOException
  92. {
  93. for(Iterator<CacheDataPage> iter = _modifiedPages.iterator();
  94. iter.hasNext(); ) {
  95. CacheDataPage cacheDataPage = iter.next();
  96. if(cacheDataPage._extra._entryView.isEmpty()) {
  97. if(!cacheDataPage._main.isRoot()) {
  98. deleteDataPage(cacheDataPage);
  99. } else {
  100. writeDataPage(cacheDataPage);
  101. }
  102. iter.remove();
  103. }
  104. }
  105. }
  106. /**
  107. * Prepares any non-empty modified pages for writing as the second pass
  108. * during a {@link #write} call. Updates entry prefixes, promotes/demotes
  109. * tail pages, and splits pages as needed.
  110. */
  111. private void preparePagesForWriting() throws IOException
  112. {
  113. boolean splitPages = false;
  114. int maxPageEntrySize = getIndexData().getMaxPageEntrySize();
  115. // we need to continue looping through all the pages until we do not split
  116. // any pages (because a split may cascade up the tree)
  117. do {
  118. splitPages = false;
  119. // we might be adding to this list while iterating, so we can't use an
  120. // iterator
  121. for(int i = 0; i < _modifiedPages.size(); ++i) {
  122. CacheDataPage cacheDataPage = _modifiedPages.get(i);
  123. if(!cacheDataPage.isLeaf()) {
  124. // see if we need to update any child tail status
  125. DataPageMain dpMain = cacheDataPage._main;
  126. int size = cacheDataPage._extra._entryView.size();
  127. if(dpMain.hasChildTail()) {
  128. if(size == 1) {
  129. demoteTail(cacheDataPage);
  130. }
  131. } else {
  132. if(size > 1) {
  133. promoteTail(cacheDataPage);
  134. }
  135. }
  136. }
  137. // look for pages with more entries than can fit on a page
  138. if(cacheDataPage.getTotalEntrySize() > maxPageEntrySize) {
  139. // make sure the prefix is up-to-date (this may have gotten
  140. // discarded by one of the update entry methods)
  141. cacheDataPage._extra.updateEntryPrefix();
  142. // now, see if the page will fit when compressed
  143. if(cacheDataPage.getCompressedEntrySize() > maxPageEntrySize) {
  144. // need to split this page
  145. splitPages = true;
  146. splitDataPage(cacheDataPage);
  147. }
  148. }
  149. }
  150. } while(splitPages);
  151. }
  152. /**
  153. * Writes any non-empty modified pages as the last pass during a
  154. * {@link #write} call. Clears the _modifiedPages collection when finised.
  155. */
  156. private void writeDataPages() throws IOException
  157. {
  158. for(CacheDataPage cacheDataPage : _modifiedPages) {
  159. if(cacheDataPage._extra._entryView.isEmpty()) {
  160. throw new IllegalStateException("Unexpected empty page " +
  161. cacheDataPage);
  162. }
  163. writeDataPage(cacheDataPage);
  164. }
  165. _modifiedPages.clear();
  166. }
  167. /**
  168. * Returns a CacheDataPage for the given page number, may be {@code null} if
  169. * the given page number is invalid. Loads the given page if necessary.
  170. */
  171. public CacheDataPage getCacheDataPage(Integer pageNumber)
  172. throws IOException
  173. {
  174. DataPageMain main = getDataPage(pageNumber);
  175. return((main != null) ? new CacheDataPage(main) : null);
  176. }
  177. /**
  178. * Returns a DataPageMain for the given page number, may be {@code null} if
  179. * the given page number is invalid. Loads the given page if necessary.
  180. */
  181. private DataPageMain getDataPage(Integer pageNumber)
  182. throws IOException
  183. {
  184. DataPageMain dataPage = _dataPages.get(pageNumber);
  185. if((dataPage == null) && (pageNumber > INVALID_INDEX_PAGE_NUMBER)) {
  186. dataPage = readDataPage(pageNumber)._main;
  187. _dataPages.put(pageNumber, dataPage);
  188. }
  189. return dataPage;
  190. }
  191. /**
  192. * Writes the given index page to the file.
  193. */
  194. private void writeDataPage(CacheDataPage cacheDataPage)
  195. throws IOException
  196. {
  197. getIndexData().writeDataPage(cacheDataPage);
  198. // lastly, mark the page as no longer modified
  199. cacheDataPage._extra._modified = false;
  200. }
  201. /**
  202. * Deletes the given index page from the file (clears the page).
  203. */
  204. private void deleteDataPage(CacheDataPage cacheDataPage)
  205. throws IOException
  206. {
  207. // free this database page
  208. getPageChannel().deallocatePage(cacheDataPage._main._pageNumber);
  209. // discard from our cache
  210. _dataPages.remove(cacheDataPage._main._pageNumber);
  211. // lastly, mark the page as no longer modified
  212. cacheDataPage._extra._modified = false;
  213. }
  214. /**
  215. * Reads the given index page from the file.
  216. */
  217. private CacheDataPage readDataPage(Integer pageNumber)
  218. throws IOException
  219. {
  220. DataPageMain dataPage = new DataPageMain(pageNumber);
  221. DataPageExtra extra = new DataPageExtra();
  222. CacheDataPage cacheDataPage = new CacheDataPage(dataPage, extra);
  223. getIndexData().readDataPage(cacheDataPage);
  224. // associate the extra info with the main data page
  225. dataPage.setExtra(extra);
  226. return cacheDataPage;
  227. }
  228. /**
  229. * Removes the entry with the given index from the given page.
  230. *
  231. * @param cacheDataPage the page from which to remove the entry
  232. * @param entryIdx the index of the entry to remove
  233. */
  234. private void removeEntry(CacheDataPage cacheDataPage, int entryIdx)
  235. throws IOException
  236. {
  237. updateEntry(cacheDataPage, entryIdx, null, UpdateType.REMOVE);
  238. }
  239. /**
  240. * Adds the entry to the given page at the given index.
  241. *
  242. * @param cacheDataPage the page to which to add the entry
  243. * @param entryIdx the index at which to add the entry
  244. * @param newEntry the entry to add
  245. */
  246. private void addEntry(CacheDataPage cacheDataPage,
  247. int entryIdx,
  248. Entry newEntry)
  249. throws IOException
  250. {
  251. updateEntry(cacheDataPage, entryIdx, newEntry, UpdateType.ADD);
  252. }
  253. /**
  254. * Updates the entries on the given page according to the given updateType.
  255. *
  256. * @param cacheDataPage the page to update
  257. * @param entryIdx the index at which to add/remove/replace the entry
  258. * @param newEntry the entry to add/replace
  259. * @param upType the type of update to make
  260. */
  261. private void updateEntry(CacheDataPage cacheDataPage,
  262. int entryIdx,
  263. Entry newEntry,
  264. UpdateType upType)
  265. throws IOException
  266. {
  267. DataPageMain dpMain = cacheDataPage._main;
  268. DataPageExtra dpExtra = cacheDataPage._extra;
  269. if(newEntry != null) {
  270. validateEntryForPage(dpMain, newEntry);
  271. }
  272. // note, it's slightly ucky, but we need to load the parent page before we
  273. // start mucking with our entries because our parent may use our entries.
  274. CacheDataPage parentDataPage = (!dpMain.isRoot() ?
  275. new CacheDataPage(dpMain.getParentPage()) :
  276. null);
  277. Entry oldLastEntry = dpExtra._entryView.getLast();
  278. Entry oldEntry = null;
  279. int entrySizeDiff = 0;
  280. switch(upType) {
  281. case ADD:
  282. dpExtra._entryView.add(entryIdx, newEntry);
  283. entrySizeDiff += newEntry.size();
  284. break;
  285. case REPLACE:
  286. oldEntry = dpExtra._entryView.set(entryIdx, newEntry);
  287. entrySizeDiff += newEntry.size() - oldEntry.size();
  288. break;
  289. case REMOVE: {
  290. oldEntry = dpExtra._entryView.remove(entryIdx);
  291. entrySizeDiff -= oldEntry.size();
  292. break;
  293. }
  294. default:
  295. throw new RuntimeException("unknown update type " + upType);
  296. }
  297. boolean updateLast = (oldLastEntry != dpExtra._entryView.getLast());
  298. // child tail entry updates do not modify the page
  299. if(!updateLast || !dpMain.hasChildTail()) {
  300. dpExtra._totalEntrySize += entrySizeDiff;
  301. setModified(cacheDataPage);
  302. // for now, just clear the prefix, we'll fix it later
  303. dpExtra._entryPrefix = EMPTY_PREFIX;
  304. }
  305. if(dpExtra._entryView.isEmpty()) {
  306. // this page is dead
  307. removeDataPage(parentDataPage, cacheDataPage, oldLastEntry);
  308. return;
  309. }
  310. // determine if we need to update our parent page
  311. if(!updateLast || dpMain.isRoot()) {
  312. // no parent
  313. return;
  314. }
  315. // the update to the last entry needs to be propagated to our parent
  316. replaceParentEntry(parentDataPage, cacheDataPage, oldLastEntry);
  317. }
  318. /**
  319. * Removes an index page which has become empty. If this page is the root
  320. * page, just clears it.
  321. *
  322. * @param parentDataPage the parent of the removed page
  323. * @param cacheDataPage the page to remove
  324. * @param oldLastEntry the last entry for this page (before it was removed)
  325. */
  326. private void removeDataPage(CacheDataPage parentDataPage,
  327. CacheDataPage cacheDataPage,
  328. Entry oldLastEntry)
  329. throws IOException
  330. {
  331. DataPageMain dpMain = cacheDataPage._main;
  332. DataPageExtra dpExtra = cacheDataPage._extra;
  333. if(dpMain.hasChildTail()) {
  334. throw new IllegalStateException("Still has child tail?");
  335. }
  336. if(dpExtra._totalEntrySize != 0) {
  337. throw new IllegalStateException("Empty page but size is not 0? " +
  338. dpExtra._totalEntrySize + ", " +
  339. cacheDataPage);
  340. }
  341. if(dpMain.isRoot()) {
  342. // clear out this page (we don't actually remove it)
  343. dpExtra._entryPrefix = EMPTY_PREFIX;
  344. // when the root page becomes empty, it becomes a leaf page again
  345. dpMain._leaf = true;
  346. return;
  347. }
  348. // remove this page from its parent page
  349. updateParentEntry(parentDataPage, cacheDataPage, oldLastEntry, null,
  350. UpdateType.REMOVE);
  351. // remove this page from any next/prev pages
  352. removeFromPeers(cacheDataPage);
  353. }
  354. /**
  355. * Removes a now empty index page from its next and previous peers.
  356. *
  357. * @param cacheDataPage the page to remove
  358. */
  359. private void removeFromPeers(CacheDataPage cacheDataPage)
  360. throws IOException
  361. {
  362. DataPageMain dpMain = cacheDataPage._main;
  363. Integer prevPageNumber = dpMain._prevPageNumber;
  364. Integer nextPageNumber = dpMain._nextPageNumber;
  365. DataPageMain prevMain = dpMain.getPrevPage();
  366. if(prevMain != null) {
  367. setModified(new CacheDataPage(prevMain));
  368. prevMain._nextPageNumber = nextPageNumber;
  369. }
  370. DataPageMain nextMain = dpMain.getNextPage();
  371. if(nextMain != null) {
  372. setModified(new CacheDataPage(nextMain));
  373. nextMain._prevPageNumber = prevPageNumber;
  374. }
  375. }
  376. /**
  377. * Adds an entry for the given child page to the given parent page.
  378. *
  379. * @param parentDataPage the parent page to which to add the entry
  380. * @param childDataPage the child from which to get the entry to add
  381. */
  382. private void addParentEntry(CacheDataPage parentDataPage,
  383. CacheDataPage childDataPage)
  384. throws IOException
  385. {
  386. DataPageExtra childExtra = childDataPage._extra;
  387. updateParentEntry(parentDataPage, childDataPage, null,
  388. childExtra._entryView.getLast(), UpdateType.ADD);
  389. }
  390. /**
  391. * Replaces the entry for the given child page in the given parent page.
  392. *
  393. * @param parentDataPage the parent page in which to replace the entry
  394. * @param childDataPage the child for which the entry is being replaced
  395. * @param oldEntry the old child entry for the child page
  396. */
  397. private void replaceParentEntry(CacheDataPage parentDataPage,
  398. CacheDataPage childDataPage,
  399. Entry oldEntry)
  400. throws IOException
  401. {
  402. DataPageExtra childExtra = childDataPage._extra;
  403. updateParentEntry(parentDataPage, childDataPage, oldEntry,
  404. childExtra._entryView.getLast(), UpdateType.REPLACE);
  405. }
  406. /**
  407. * Updates the entry for the given child page in the given parent page
  408. * according to the given updateType.
  409. *
  410. * @param parentDataPage the parent page in which to update the entry
  411. * @param childDataPage the child for which the entry is being updated
  412. * @param oldEntry the old child entry to remove/replace
  413. * @param newEntry the new child entry to replace/add
  414. * @param upType the type of update to make
  415. */
  416. private void updateParentEntry(CacheDataPage parentDataPage,
  417. CacheDataPage childDataPage,
  418. Entry oldEntry, Entry newEntry,
  419. UpdateType upType)
  420. throws IOException
  421. {
  422. DataPageMain childMain = childDataPage._main;
  423. DataPageExtra parentExtra = parentDataPage._extra;
  424. if(childMain.isTail() && (upType != UpdateType.REMOVE)) {
  425. // for add or replace, update the child tail info before updating the
  426. // parent entries
  427. updateParentTail(parentDataPage, childDataPage, upType);
  428. }
  429. if(oldEntry != null) {
  430. oldEntry = oldEntry.asNodeEntry(childMain._pageNumber);
  431. }
  432. if(newEntry != null) {
  433. newEntry = newEntry.asNodeEntry(childMain._pageNumber);
  434. }
  435. boolean expectFound = true;
  436. int idx = 0;
  437. switch(upType) {
  438. case ADD:
  439. expectFound = false;
  440. idx = parentExtra._entryView.find(newEntry);
  441. break;
  442. case REPLACE:
  443. case REMOVE:
  444. idx = parentExtra._entryView.find(oldEntry);
  445. break;
  446. default:
  447. throw new RuntimeException("unknown update type " + upType);
  448. }
  449. if(idx < 0) {
  450. if(expectFound) {
  451. throw new IllegalStateException(
  452. "Could not find child entry in parent; childEntry " + oldEntry +
  453. "; parent " + parentDataPage);
  454. }
  455. idx = missingIndexToInsertionPoint(idx);
  456. } else {
  457. if(!expectFound) {
  458. throw new IllegalStateException(
  459. "Unexpectedly found child entry in parent; childEntry " +
  460. newEntry + "; parent " + parentDataPage);
  461. }
  462. }
  463. updateEntry(parentDataPage, idx, newEntry, upType);
  464. if(childMain.isTail() && (upType == UpdateType.REMOVE)) {
  465. // for remove, update the child tail info after updating the parent
  466. // entries
  467. updateParentTail(parentDataPage, childDataPage, upType);
  468. }
  469. }
  470. /**
  471. * Updates the child tail info in the given parent page according to the
  472. * given updateType.
  473. *
  474. * @param parentDataPage the parent page in which to update the child tail
  475. * @param childDataPage the child to add/replace
  476. * @param upType the type of update to make
  477. */
  478. private void updateParentTail(CacheDataPage parentDataPage,
  479. CacheDataPage childDataPage,
  480. UpdateType upType)
  481. throws IOException
  482. {
  483. DataPageMain parentMain = parentDataPage._main;
  484. int newChildTailPageNumber =
  485. ((upType == UpdateType.REMOVE) ?
  486. INVALID_INDEX_PAGE_NUMBER :
  487. childDataPage._main._pageNumber);
  488. if(!parentMain.isChildTailPageNumber(newChildTailPageNumber)) {
  489. setModified(parentDataPage);
  490. parentMain._childTailPageNumber = newChildTailPageNumber;
  491. }
  492. }
  493. /**
  494. * Verifies that the given entry type (node/leaf) is valid for the given
  495. * page (node/leaf).
  496. *
  497. * @param dpMain the page to which the entry will be added
  498. * @param entry the entry being added
  499. * @throws IllegalStateException if the entry type does not match the page
  500. * type
  501. */
  502. private void validateEntryForPage(DataPageMain dpMain, Entry entry) {
  503. if(dpMain._leaf != entry.isLeafEntry()) {
  504. throw new IllegalStateException(
  505. "Trying to update page with wrong entry type; pageLeaf " +
  506. dpMain._leaf + ", entryLeaf " + entry.isLeafEntry());
  507. }
  508. }
  509. /**
  510. * Splits an index page which has too many entries on it.
  511. *
  512. * @param origDataPage the page to split
  513. */
  514. private void splitDataPage(CacheDataPage origDataPage)
  515. throws IOException
  516. {
  517. DataPageMain origMain = origDataPage._main;
  518. DataPageExtra origExtra = origDataPage._extra;
  519. setModified(origDataPage);
  520. int numEntries = origExtra._entries.size();
  521. if(numEntries < 2) {
  522. throw new IllegalStateException(
  523. "Cannot split page with less than 2 entries " + origDataPage);
  524. }
  525. if(origMain.isRoot()) {
  526. // we can't split the root page directly, so we need to put another page
  527. // between the root page and its sub-pages, and then split that page.
  528. CacheDataPage newDataPage = nestRootDataPage(origDataPage);
  529. // now, split this new page instead
  530. origDataPage = newDataPage;
  531. origMain = newDataPage._main;
  532. origExtra = newDataPage._extra;
  533. }
  534. // note, it's slightly ucky, but we need to load the parent page before we
  535. // start mucking with our entries because our parent may use our entries.
  536. DataPageMain parentMain = origMain.getParentPage();
  537. CacheDataPage parentDataPage = new CacheDataPage(parentMain);
  538. // note, there are many, many ways this could be improved/tweaked. for
  539. // now, we just want it to be functional...
  540. // so, we will naively move half the entries from one page to a new page.
  541. CacheDataPage newDataPage = allocateNewCacheDataPage(
  542. parentMain._pageNumber, origMain._leaf);
  543. DataPageMain newMain = newDataPage._main;
  544. DataPageExtra newExtra = newDataPage._extra;
  545. List<Entry> headEntries =
  546. origExtra._entries.subList(0, ((numEntries + 1) / 2));
  547. // move first half of the entries from old page to new page (so we do not
  548. // need to muck with any tail entries)
  549. for(Entry headEntry : headEntries) {
  550. newExtra._totalEntrySize += headEntry.size();
  551. newExtra._entries.add(headEntry);
  552. }
  553. newExtra.setEntryView(newMain);
  554. // remove the moved entries from the old page
  555. headEntries.clear();
  556. origExtra._entryPrefix = EMPTY_PREFIX;
  557. origExtra._totalEntrySize -= newExtra._totalEntrySize;
  558. // insert this new page between the old page and any previous page
  559. addToPeersBefore(newDataPage, origDataPage);
  560. if(!newMain._leaf) {
  561. // reparent the children pages of the new page
  562. reparentChildren(newDataPage);
  563. // if the children of this page are also node pages, then the next/prev
  564. // links should not cross parent boundaries (the leaf pages are linked
  565. // from beginning to end, but child node pages are only linked within
  566. // the same parent)
  567. DataPageMain childMain = newMain.getChildPage(
  568. newExtra._entryView.getLast());
  569. if(!childMain._leaf) {
  570. separateFromNextPeer(new CacheDataPage(childMain));
  571. }
  572. }
  573. // lastly, we need to add the new page to the parent page's entries
  574. addParentEntry(parentDataPage, newDataPage);
  575. }
  576. /**
  577. * Copies the current root page info into a new page and nests this page
  578. * under the root page. This must be done when the root page needs to be
  579. * split.
  580. *
  581. * @param rootDataPage the root data page
  582. *
  583. * @return the newly created page nested under the root page
  584. */
  585. private CacheDataPage nestRootDataPage(CacheDataPage rootDataPage)
  586. throws IOException
  587. {
  588. DataPageMain rootMain = rootDataPage._main;
  589. DataPageExtra rootExtra = rootDataPage._extra;
  590. if(!rootMain.isRoot()) {
  591. throw new IllegalArgumentException("should be called with root, duh");
  592. }
  593. CacheDataPage newDataPage =
  594. allocateNewCacheDataPage(rootMain._pageNumber, rootMain._leaf);
  595. DataPageMain newMain = newDataPage._main;
  596. DataPageExtra newExtra = newDataPage._extra;
  597. // move entries to new page
  598. newMain._childTailPageNumber = rootMain._childTailPageNumber;
  599. newExtra._entries = rootExtra._entries;
  600. newExtra._entryPrefix = rootExtra._entryPrefix;
  601. newExtra._totalEntrySize = rootExtra._totalEntrySize;
  602. newExtra.setEntryView(newMain);
  603. if(!newMain._leaf) {
  604. // we need to re-parent all the child pages
  605. reparentChildren(newDataPage);
  606. }
  607. // clear the root page
  608. rootMain._leaf = false;
  609. rootMain._childTailPageNumber = INVALID_INDEX_PAGE_NUMBER;
  610. rootExtra._entries = new ArrayList<Entry>();
  611. rootExtra._entryPrefix = EMPTY_PREFIX;
  612. rootExtra._totalEntrySize = 0;
  613. rootExtra.setEntryView(rootMain);
  614. // add the new page as the first child of the root page
  615. addParentEntry(rootDataPage, newDataPage);
  616. return newDataPage;
  617. }
  618. /**
  619. * Allocates a new index page with the given parent page and type.
  620. *
  621. * @param parentPageNumber the parent page for the new page
  622. * @param isLeaf whether or not the new page is a leaf page
  623. *
  624. * @return the newly created page
  625. */
  626. private CacheDataPage allocateNewCacheDataPage(Integer parentPageNumber,
  627. boolean isLeaf)
  628. throws IOException
  629. {
  630. DataPageMain dpMain = new DataPageMain(getPageChannel().allocateNewPage());
  631. DataPageExtra dpExtra = new DataPageExtra();
  632. dpMain.initParentPage(parentPageNumber, false);
  633. dpMain._leaf = isLeaf;
  634. dpMain._prevPageNumber = INVALID_INDEX_PAGE_NUMBER;
  635. dpMain._nextPageNumber = INVALID_INDEX_PAGE_NUMBER;
  636. dpMain._childTailPageNumber = INVALID_INDEX_PAGE_NUMBER;
  637. dpExtra._entries = new ArrayList<Entry>();
  638. dpExtra._entryPrefix = EMPTY_PREFIX;
  639. dpMain.setExtra(dpExtra);
  640. // add to our page cache
  641. _dataPages.put(dpMain._pageNumber, dpMain);
  642. // update owned pages cache
  643. _indexData.addOwnedPage(dpMain._pageNumber);
  644. // needs to be written out
  645. CacheDataPage cacheDataPage = new CacheDataPage(dpMain, dpExtra);
  646. setModified(cacheDataPage);
  647. return cacheDataPage;
  648. }
  649. /**
  650. * Inserts the new page as a peer between the given original page and any
  651. * previous peer page.
  652. *
  653. * @param newDataPage the new index page
  654. * @param origDataPage the current index page
  655. */
  656. private void addToPeersBefore(CacheDataPage newDataPage,
  657. CacheDataPage origDataPage)
  658. throws IOException
  659. {
  660. DataPageMain origMain = origDataPage._main;
  661. DataPageMain newMain = newDataPage._main;
  662. DataPageMain prevMain = origMain.getPrevPage();
  663. newMain._nextPageNumber = origMain._pageNumber;
  664. newMain._prevPageNumber = origMain._prevPageNumber;
  665. origMain._prevPageNumber = newMain._pageNumber;
  666. if(prevMain != null) {
  667. setModified(new CacheDataPage(prevMain));
  668. prevMain._nextPageNumber = newMain._pageNumber;
  669. }
  670. }
  671. /**
  672. * Separates the given index page from any next peer page.
  673. *
  674. * @param cacheDataPage the index page to be separated
  675. */
  676. private void separateFromNextPeer(CacheDataPage cacheDataPage)
  677. throws IOException
  678. {
  679. DataPageMain dpMain = cacheDataPage._main;
  680. setModified(cacheDataPage);
  681. DataPageMain nextMain = dpMain.getNextPage();
  682. setModified(new CacheDataPage(nextMain));
  683. nextMain._prevPageNumber = INVALID_INDEX_PAGE_NUMBER;
  684. dpMain._nextPageNumber = INVALID_INDEX_PAGE_NUMBER;
  685. }
  686. /**
  687. * Sets the parent info for the children of the given page to the given
  688. * page.
  689. *
  690. * @param cacheDataPage the page whose children need to be updated
  691. */
  692. private void reparentChildren(CacheDataPage cacheDataPage)
  693. throws IOException
  694. {
  695. DataPageMain dpMain = cacheDataPage._main;
  696. DataPageExtra dpExtra = cacheDataPage._extra;
  697. // note, the "parent" page number is not actually persisted, so we do not
  698. // need to mark any updated pages as modified. for the same reason, we
  699. // don't need to load the pages if not already loaded
  700. for(Entry entry : dpExtra._entryView) {
  701. Integer childPageNumber = entry.getSubPageNumber();
  702. DataPageMain childMain = _dataPages.get(childPageNumber);
  703. if(childMain != null) {
  704. childMain.setParentPage(dpMain._pageNumber,
  705. dpMain.isChildTailPageNumber(childPageNumber));
  706. }
  707. }
  708. }
  709. /**
  710. * Makes the tail entry of the given page a normal entry on that page, done
  711. * when there is only one entry left on a page, and it is the tail.
  712. *
  713. * @param cacheDataPage the page whose tail must be updated
  714. */
  715. private void demoteTail(CacheDataPage cacheDataPage)
  716. throws IOException
  717. {
  718. // there's only one entry on the page, and it's the tail. make it a
  719. // normal entry
  720. DataPageMain dpMain = cacheDataPage._main;
  721. DataPageExtra dpExtra = cacheDataPage._extra;
  722. setModified(cacheDataPage);
  723. DataPageMain tailMain = dpMain.getChildTailPage();
  724. CacheDataPage tailDataPage = new CacheDataPage(tailMain);
  725. // move the tail entry to the last normal entry
  726. updateParentTail(cacheDataPage, tailDataPage, UpdateType.REMOVE);
  727. Entry tailEntry = dpExtra._entryView.demoteTail();
  728. dpExtra._totalEntrySize += tailEntry.size();
  729. dpExtra._entryPrefix = EMPTY_PREFIX;
  730. tailMain.setParentPage(dpMain._pageNumber, false);
  731. }
  732. /**
  733. * Makes the last normal entry of the given page the tail entry on that
  734. * page, done when there are multiple entries on a page and no tail entry.
  735. *
  736. * @param cacheDataPage the page whose tail must be updated
  737. */
  738. private void promoteTail(CacheDataPage cacheDataPage)
  739. throws IOException
  740. {
  741. // there's not tail currently on this page, make last entry a tail
  742. DataPageMain dpMain = cacheDataPage._main;
  743. DataPageExtra dpExtra = cacheDataPage._extra;
  744. setModified(cacheDataPage);
  745. DataPageMain lastMain = dpMain.getChildPage(dpExtra._entryView.getLast());
  746. CacheDataPage lastDataPage = new CacheDataPage(lastMain);
  747. // move the "last" normal entry to the tail entry
  748. updateParentTail(cacheDataPage, lastDataPage, UpdateType.ADD);
  749. Entry lastEntry = dpExtra._entryView.promoteTail();
  750. dpExtra._totalEntrySize -= lastEntry.size();
  751. dpExtra._entryPrefix = EMPTY_PREFIX;
  752. lastMain.setParentPage(dpMain._pageNumber, true);
  753. }
  754. /**
  755. * Finds the index page on which the given entry does or should reside.
  756. *
  757. * @param e the entry to find
  758. */
  759. public CacheDataPage findCacheDataPage(Entry e)
  760. throws IOException
  761. {
  762. DataPageMain curPage = _rootPage;
  763. while(true) {
  764. if(curPage._leaf) {
  765. // nowhere to go from here
  766. return new CacheDataPage(curPage);
  767. }
  768. DataPageExtra extra = curPage.getExtra();
  769. // need to descend
  770. int idx = extra._entryView.find(e);
  771. if(idx < 0) {
  772. idx = missingIndexToInsertionPoint(idx);
  773. if(idx == extra._entryView.size()) {
  774. // just move to last child page
  775. --idx;
  776. }
  777. }
  778. Entry nodeEntry = extra._entryView.get(idx);
  779. curPage = curPage.getChildPage(nodeEntry);
  780. }
  781. }
  782. /**
  783. * Marks the given index page as modified and saves it for writing, if
  784. * necessary (if the page is already marked, does nothing).
  785. *
  786. * @param cacheDataPage the modified index page
  787. */
  788. private void setModified(CacheDataPage cacheDataPage)
  789. {
  790. if(!cacheDataPage._extra._modified) {
  791. _modifiedPages.add(cacheDataPage);
  792. cacheDataPage._extra._modified = true;
  793. }
  794. }
  795. /**
  796. * Finds the valid entry prefix given the first/last entries on an index
  797. * page.
  798. *
  799. * @param e1 the first entry on the page
  800. * @param e2 the last entry on the page
  801. *
  802. * @return a valid entry prefix for the page
  803. */
  804. private static byte[] findCommonPrefix(Entry e1, Entry e2)
  805. {
  806. byte[] b1 = e1.getEntryBytes();
  807. byte[] b2 = e2.getEntryBytes();
  808. int maxLen = b1.length;
  809. byte[] prefix = b1;
  810. if(b1.length > b2.length) {
  811. maxLen = b2.length;
  812. prefix = b2;
  813. }
  814. int len = 0;
  815. while((len < maxLen) && (b1[len] == b2[len])) {
  816. ++len;
  817. }
  818. if(len < prefix.length) {
  819. if(len == 0) {
  820. return EMPTY_PREFIX;
  821. }
  822. // need new prefix
  823. prefix = ByteUtil.copyOf(prefix, len);
  824. }
  825. return prefix;
  826. }
  827. /**
  828. * Used by unit tests to validate the internal status of the index.
  829. */
  830. void validate() throws IOException {
  831. for(DataPageMain dpMain : _dataPages.values()) {
  832. DataPageExtra dpExtra = dpMain.getExtra();
  833. validateEntries(dpExtra);
  834. validateChildren(dpMain, dpExtra);
  835. validatePeers(dpMain);
  836. }
  837. }
  838. /**
  839. * Validates the entries for an index page
  840. *
  841. * @param dpExtra the entries to validate
  842. */
  843. private void validateEntries(DataPageExtra dpExtra) throws IOException {
  844. int entrySize = 0;
  845. Entry prevEntry = IndexData.FIRST_ENTRY;
  846. for(Entry e : dpExtra._entries) {
  847. entrySize += e.size();
  848. if(prevEntry.compareTo(e) >= 0) {
  849. throw new IOException("Unexpected order in index entries, " +
  850. prevEntry + " >= " + e);
  851. }
  852. prevEntry = e;
  853. }
  854. if(entrySize != dpExtra._totalEntrySize) {
  855. throw new IllegalStateException("Expected size " + entrySize +
  856. " but was " + dpExtra._totalEntrySize);
  857. }
  858. }
  859. /**
  860. * Validates the children for an index page
  861. *
  862. * @param dpMain the index page
  863. * @param dpExtra the child entries to validate
  864. */
  865. private void validateChildren(DataPageMain dpMain,
  866. DataPageExtra dpExtra) throws IOException {
  867. int childTailPageNumber = dpMain._childTailPageNumber;
  868. if(dpMain._leaf) {
  869. if(childTailPageNumber != INVALID_INDEX_PAGE_NUMBER) {
  870. throw new IllegalStateException("Leaf page has tail " + dpMain);
  871. }
  872. return;
  873. }
  874. if((dpExtra._entryView.size() == 1) && dpMain.hasChildTail()) {
  875. throw new IllegalStateException("Single child is tail " + dpMain);
  876. }
  877. for(Entry e : dpExtra._entryView) {
  878. validateEntryForPage(dpMain, e);
  879. Integer subPageNumber = e.getSubPageNumber();
  880. DataPageMain childMain = _dataPages.get(subPageNumber);
  881. if(childMain != null) {
  882. if(childMain._parentPageNumber != null) {
  883. if((int)childMain._parentPageNumber != dpMain._pageNumber) {
  884. throw new IllegalStateException("Child's parent is incorrect " +
  885. childMain);
  886. }
  887. boolean expectTail = ((int)subPageNumber == childTailPageNumber);
  888. if(expectTail != childMain._tail) {
  889. throw new IllegalStateException("Child tail status incorrect " +
  890. childMain);
  891. }
  892. }
  893. Entry lastEntry = childMain.getExtra()._entryView.getLast();
  894. if(e.compareTo(lastEntry) != 0) {
  895. throw new IllegalStateException("Invalid entry " + e +
  896. " but child is " + lastEntry);
  897. }
  898. }
  899. }
  900. }
  901. /**
  902. * Validates the peer pages for an index page.
  903. *
  904. * @param dpMain the index page
  905. */
  906. private void validatePeers(DataPageMain dpMain) throws IOException {
  907. DataPageMain prevMain = _dataPages.get(dpMain._prevPageNumber);
  908. if(prevMain != null) {
  909. if((int)prevMain._nextPageNumber != dpMain._pageNumber) {
  910. throw new IllegalStateException("Prev page " + prevMain +
  911. " does not ref " + dpMain);
  912. }
  913. validatePeerStatus(dpMain, prevMain);
  914. }
  915. DataPageMain nextMain = _dataPages.get(dpMain._nextPageNumber);
  916. if(nextMain != null) {
  917. if((int)nextMain._prevPageNumber != dpMain._pageNumber) {
  918. throw new IllegalStateException("Next page " + nextMain +
  919. " does not ref " + dpMain);
  920. }
  921. validatePeerStatus(dpMain, nextMain);
  922. }
  923. }
  924. /**
  925. * Validates the given peer page against the given index page
  926. *
  927. * @param dpMain the index page
  928. * @param peerMain the peer index page
  929. */
  930. private void validatePeerStatus(DataPageMain dpMain, DataPageMain peerMain)
  931. throws IOException
  932. {
  933. if(dpMain._leaf != peerMain._leaf) {
  934. throw new IllegalStateException("Mismatched peer status " +
  935. dpMain._leaf + " " + peerMain._leaf);
  936. }
  937. if(!dpMain._leaf) {
  938. if((dpMain._parentPageNumber != null) &&
  939. (peerMain._parentPageNumber != null) &&
  940. ((int)dpMain._parentPageNumber != (int)peerMain._parentPageNumber)) {
  941. throw new IllegalStateException("Mismatched node parents " +
  942. dpMain._parentPageNumber + " " +
  943. peerMain._parentPageNumber);
  944. }
  945. }
  946. }
  947. /**
  948. * Dumps the given index page to a StringBuilder
  949. *
  950. * @param rtn the StringBuilder to update
  951. * @param dpMain the index page to dump
  952. */
  953. private void dumpPage(StringBuilder rtn, DataPageMain dpMain) {
  954. try {
  955. CacheDataPage cacheDataPage = new CacheDataPage(dpMain);
  956. rtn.append(cacheDataPage).append("\n");
  957. if(!dpMain._leaf) {
  958. for(Entry e : cacheDataPage._extra._entryView) {
  959. DataPageMain childMain = dpMain.getChildPage(e);
  960. dumpPage(rtn, childMain);
  961. }
  962. }
  963. } catch(IOException e) {
  964. rtn.append("Page[" + dpMain._pageNumber + "]: " + e);
  965. }
  966. }
  967. @Override
  968. public String toString() {
  969. if(_rootPage == null) {
  970. return "Cache: (uninitialized)";
  971. }
  972. StringBuilder rtn = new StringBuilder("Cache: \n");
  973. dumpPage(rtn, _rootPage);
  974. return rtn.toString();
  975. }
  976. /**
  977. * Keeps track of the main info for an index page.
  978. */
  979. private class DataPageMain
  980. {
  981. public final int _pageNumber;
  982. public Integer _prevPageNumber;
  983. public Integer _nextPageNumber;
  984. public Integer _childTailPageNumber;
  985. public Integer _parentPageNumber;
  986. public boolean _leaf;
  987. public boolean _tail;
  988. private Reference<DataPageExtra> _extra;
  989. private DataPageMain(int pageNumber) {
  990. _pageNumber = pageNumber;
  991. }
  992. public IndexPageCache getCache() {
  993. return IndexPageCache.this;
  994. }
  995. public boolean isRoot() {
  996. return(this == _rootPage);
  997. }
  998. public boolean isTail() throws IOException
  999. {
  1000. resolveParent();
  1001. return _tail;
  1002. }
  1003. public boolean hasChildTail() {
  1004. return((int)_childTailPageNumber != INVALID_INDEX_PAGE_NUMBER);
  1005. }
  1006. public boolean isChildTailPageNumber(int pageNumber) {
  1007. return((int)_childTailPageNumber == pageNumber);
  1008. }
  1009. public DataPageMain getParentPage() throws IOException
  1010. {
  1011. resolveParent();
  1012. return IndexPageCache.this.getDataPage(_parentPageNumber);
  1013. }
  1014. public void initParentPage(Integer parentPageNumber, boolean isTail) {
  1015. // only set if not already set
  1016. if(_parentPageNumber == null) {
  1017. setParentPage(parentPageNumber, isTail);
  1018. }
  1019. }
  1020. public void setParentPage(Integer parentPageNumber, boolean isTail) {
  1021. _parentPageNumber = parentPageNumber;
  1022. _tail = isTail;
  1023. }
  1024. public DataPageMain getPrevPage() throws IOException
  1025. {
  1026. return IndexPageCache.this.getDataPage(_prevPageNumber);
  1027. }
  1028. public DataPageMain getNextPage() throws IOException
  1029. {
  1030. return IndexPageCache.this.getDataPage(_nextPageNumber);
  1031. }
  1032. public DataPageMain getChildPage(Entry e) throws IOException
  1033. {
  1034. Integer childPageNumber = e.getSubPageNumber();
  1035. return getChildPage(childPageNumber,
  1036. isChildTailPageNumber(childPageNumber));
  1037. }
  1038. public DataPageMain getChildTailPage() throws IOException
  1039. {
  1040. return getChildPage(_childTailPageNumber, true);
  1041. }
  1042. /**
  1043. * Returns a child page for the given page number, updating its parent
  1044. * info if necessary.
  1045. */
  1046. private DataPageMain getChildPage(Integer childPageNumber, boolean isTail)
  1047. throws IOException
  1048. {
  1049. DataPageMain child = getDataPage(childPageNumber);
  1050. if(child != null) {
  1051. // set the parent info for this child (if necessary)
  1052. child.initParentPage(_pageNumber, isTail);
  1053. }
  1054. return child;
  1055. }
  1056. public DataPageExtra getExtra() throws IOException
  1057. {
  1058. DataPageExtra extra = _extra.get();
  1059. if(extra == null) {
  1060. extra = readDataPage(_pageNumber)._extra;
  1061. setExtra(extra);
  1062. }
  1063. return extra;
  1064. }
  1065. public void setExtra(DataPageExtra extra) throws IOException
  1066. {
  1067. extra.setEntryView(this);
  1068. _extra = new SoftReference<DataPageExtra>(extra);
  1069. }
  1070. private void resolveParent() throws IOException {
  1071. if(_parentPageNumber == null) {
  1072. // the act of searching for the last entry should resolve any parent
  1073. // pages along the path
  1074. findCacheDataPage(getExtra()._entryView.getLast());
  1075. if(_parentPageNumber == null) {
  1076. throw new IllegalStateException("Parent was not resolved");
  1077. }
  1078. }
  1079. }
  1080. @Override
  1081. public String toString() {
  1082. return (_leaf ? "Leaf" : "Node") + "DPMain[" + _pageNumber +
  1083. "] " + _prevPageNumber + ", " + _nextPageNumber + ", (" +
  1084. _childTailPageNumber + ")";
  1085. }
  1086. }
  1087. /**
  1088. * Keeps track of the extra info for an index page. This info (if
  1089. * unmodified) may be re-read from disk as necessary.
  1090. */
  1091. private static class DataPageExtra
  1092. {
  1093. /** sorted collection of index entries. this is kept in a list instead of
  1094. a SortedSet because the SortedSet has lame traversal utilities */
  1095. public List<Entry> _entries;
  1096. public EntryListView _entryView;
  1097. public byte[] _entryPrefix;
  1098. public int _totalEntrySize;
  1099. public boolean _modified;
  1100. private DataPageExtra()
  1101. {
  1102. }
  1103. public void setEntryView(DataPageMain main) throws IOException {
  1104. _entryView = new EntryListView(main, this);
  1105. }
  1106. public void updateEntryPrefix() {
  1107. if(_entryPrefix.length == 0) {
  1108. // prefix is only related to *real* entries, tail not included
  1109. _entryPrefix = findCommonPrefix(_entries.get(0),
  1110. _entries.get(_entries.size() - 1));
  1111. }
  1112. }
  1113. @Override
  1114. public String toString() {
  1115. return "DPExtra: " + _entryView;
  1116. }
  1117. }
  1118. /**
  1119. * IndexPageCache implementation of an Index {@link DataPage}.
  1120. */
  1121. public static final class CacheDataPage
  1122. extends IndexData.DataPage
  1123. {
  1124. public final DataPageMain _main;
  1125. public final DataPageExtra _extra;
  1126. private CacheDataPage(DataPageMain dataPage) throws IOException {
  1127. this(dataPage, dataPage.getExtra());
  1128. }
  1129. private CacheDataPage(DataPageMain dataPage, DataPageExtra extra) {
  1130. _main = dataPage;
  1131. _extra = extra;
  1132. }
  1133. @Override
  1134. public int getPageNumber() {
  1135. return _main._pageNumber;
  1136. }
  1137. @Override
  1138. public boolean isLeaf() {
  1139. return _main._leaf;
  1140. }
  1141. @Override
  1142. public void setLeaf(boolean isLeaf) {
  1143. _main._leaf = isLeaf;
  1144. }
  1145. @Override
  1146. public int getPrevPageNumber() {
  1147. return _main._prevPageNumber;
  1148. }
  1149. @Override
  1150. public void setPrevPageNumber(int pageNumber) {
  1151. _main._prevPageNumber = pageNumber;
  1152. }
  1153. @Override
  1154. public int getNextPageNumber() {
  1155. return _main._nextPageNumber;
  1156. }
  1157. @Override
  1158. public void setNextPageNumber(int pageNumber) {
  1159. _main._nextPageNumber = pageNumber;
  1160. }
  1161. @Override
  1162. public int getChildTailPageNumber() {
  1163. return _main._childTailPageNumber;
  1164. }
  1165. @Override
  1166. public void setChildTailPageNumber(int pageNumber) {
  1167. _main._childTailPageNumber = pageNumber;
  1168. }
  1169. @Override
  1170. public int getTotalEntrySize() {
  1171. return _extra._totalEntrySize;
  1172. }
  1173. @Override
  1174. public void setTotalEntrySize(int totalSize) {
  1175. _extra._totalEntrySize = totalSize;
  1176. }
  1177. @Override
  1178. public byte[] getEntryPrefix() {
  1179. return _extra._entryPrefix;
  1180. }
  1181. @Override
  1182. public void setEntryPrefix(byte[] entryPrefix) {
  1183. _extra._entryPrefix = entryPrefix;
  1184. }
  1185. @Override
  1186. public List<Entry> getEntries() {
  1187. return _extra._entries;
  1188. }
  1189. @Override
  1190. public void setEntries(List<Entry> entries) {
  1191. _extra._entries = entries;
  1192. }
  1193. @Override
  1194. public void addEntry(int idx, Entry entry) throws IOException {
  1195. _main.getCache().addEntry(this, idx, entry);
  1196. }
  1197. @Override
  1198. public void removeEntry(int idx) throws IOException {
  1199. _main.getCache().removeEntry(this, idx);
  1200. }
  1201. }
  1202. /**
  1203. * A view of an index page's entries which combines the normal entries and
  1204. * tail entry into one collection.
  1205. */
  1206. private static class EntryListView extends AbstractList<Entry>
  1207. implements RandomAccess
  1208. {
  1209. private final DataPageExtra _extra;
  1210. private Entry _childTailEntry;
  1211. private EntryListView(DataPageMain main, DataPageExtra extra)
  1212. throws IOException
  1213. {
  1214. if(main.hasChildTail()) {
  1215. _childTailEntry = main.getChildTailPage().getExtra()._entryView
  1216. .getLast().asNodeEntry(main._childTailPageNumber);
  1217. }
  1218. _extra = extra;
  1219. }
  1220. private List<Entry> getEntries() {
  1221. return _extra._entries;
  1222. }
  1223. @Override
  1224. public int size() {
  1225. int size = getEntries().size();
  1226. if(hasChildTail()) {
  1227. ++size;
  1228. }
  1229. return size;
  1230. }
  1231. @Override
  1232. public Entry get(int idx) {
  1233. return (isCurrentChildTailIndex(idx) ?
  1234. _childTailEntry :
  1235. getEntries().get(idx));
  1236. }
  1237. @Override
  1238. public Entry set(int idx, Entry newEntry) {
  1239. return (isCurrentChildTailIndex(idx) ?
  1240. setChildTailEntry(newEntry) :
  1241. getEntries().set(idx, newEntry));
  1242. }
  1243. @Override
  1244. public void add(int idx, Entry newEntry) {
  1245. // note, we will never add to the "tail" entry, that will always be
  1246. // handled through promoteTail
  1247. getEntries().add(idx, newEntry);
  1248. }
  1249. @Override
  1250. public Entry remove(int idx) {
  1251. return (isCurrentChildTailIndex(idx) ?
  1252. setChildTailEntry(null) :
  1253. getEntries().remove(idx));
  1254. }
  1255. public Entry setChildTailEntry(Entry newEntry) {
  1256. Entry old = _childTailEntry;
  1257. _childTailEntry = newEntry;
  1258. return old;
  1259. }
  1260. public Entry getChildTailEntry() {
  1261. return _childTailEntry;
  1262. }
  1263. private boolean hasChildTail() {
  1264. return(_childTailEntry != null);
  1265. }
  1266. private boolean isCurrentChildTailIndex(int idx) {
  1267. return(idx == getEntries().size());
  1268. }
  1269. public Entry getLast() {
  1270. return(hasChildTail() ? _childTailEntry :
  1271. (!getEntries().isEmpty() ?
  1272. getEntries().get(getEntries().size() - 1) : null));
  1273. }
  1274. public Entry demoteTail() {
  1275. Entry tail = _childTailEntry;
  1276. _childTailEntry = null;
  1277. getEntries().add(tail);
  1278. return tail;
  1279. }
  1280. public Entry promoteTail() {
  1281. Entry last = getEntries().remove(getEntries().size() - 1);
  1282. _childTailEntry = last;
  1283. return last;
  1284. }
  1285. public int find(Entry e) {
  1286. return Collections.binarySearch(this, e);
  1287. }
  1288. }
  1289. }