1. /*
  2. * Copyright 1999-2004 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /*
  17. * $Id: FastStringBuffer.java,v 1.25 2004/02/17 04:21:14 minchau Exp $
  18. */
  19. package com.sun.org.apache.xml.internal.utils;
  20. /**
  21. * Bare-bones, unsafe, fast string buffer. No thread-safety, no
  22. * parameter range checking, exposed fields. Note that in typical
  23. * applications, thread-safety of a StringBuffer is a somewhat
  24. * dubious concept in any case.
  25. * <p>
  26. * Note that Stree and DTM used a single FastStringBuffer as a string pool,
  27. * by recording start and length indices within this single buffer. This
  28. * minimizes heap overhead, but of course requires more work when retrieving
  29. * the data.
  30. * <p>
  31. * FastStringBuffer operates as a "chunked buffer". Doing so
  32. * reduces the need to recopy existing information when an append
  33. * exceeds the space available; we just allocate another chunk and
  34. * flow across to it. (The array of chunks may need to grow,
  35. * admittedly, but that's a much smaller object.) Some excess
  36. * recopying may arise when we extract Strings which cross chunk
  37. * boundaries; larger chunks make that less frequent.
  38. * <p>
  39. * The size values are parameterized, to allow tuning this code. In
  40. * theory, Result Tree Fragments might want to be tuned differently
  41. * from the main document's text.
  42. * <p>
  43. * %REVIEW% An experiment in self-tuning is
  44. * included in the code (using nested FastStringBuffers to achieve
  45. * variation in chunk sizes), but this implementation has proven to
  46. * be problematic when data may be being copied from the FSB into itself.
  47. * We should either re-architect that to make this safe (if possible)
  48. * or remove that code and clean up for performance/maintainability reasons.
  49. * <p>
  50. */
  51. public class FastStringBuffer
  52. {
  53. // If nonzero, forces the inial chunk size.
  54. /**/static final int DEBUG_FORCE_INIT_BITS=0;
  55. // %BUG% %REVIEW% *****PROBLEM SUSPECTED: If data from an FSB is being copied
  56. // back into the same FSB (variable set from previous variable, for example)
  57. // and blocksize changes in mid-copy... there's risk of severe malfunction in
  58. // the read process, due to how the resizing code re-jiggers storage. Arggh.
  59. // If we want to retain the variable-size-block feature, we need to reconsider
  60. // that issue. For now, I have forced us into fixed-size mode.
  61. static boolean DEBUG_FORCE_FIXED_CHUNKSIZE=true;
  62. /** Manifest constant: Suppress leading whitespace.
  63. * This should be used when normalize-to-SAX is called for the first chunk of a
  64. * multi-chunk output, or one following unsuppressed whitespace in a previous
  65. * chunk.
  66. * @see sendNormalizedSAXcharacters(char[],int,int,org.xml.sax.ContentHandler,int)
  67. */
  68. public static final int SUPPRESS_LEADING_WS=0x01;
  69. /** Manifest constant: Suppress trailing whitespace.
  70. * This should be used when normalize-to-SAX is called for the last chunk of a
  71. * multi-chunk output; it may have to be or'ed with SUPPRESS_LEADING_WS.
  72. */
  73. public static final int SUPPRESS_TRAILING_WS=0x02;
  74. /** Manifest constant: Suppress both leading and trailing whitespace.
  75. * This should be used when normalize-to-SAX is called for a complete string.
  76. * (I'm not wild about the name of this one. Ideas welcome.)
  77. * @see sendNormalizedSAXcharacters(char[],int,int,org.xml.sax.ContentHandler,int)
  78. */
  79. public static final int SUPPRESS_BOTH
  80. = SUPPRESS_LEADING_WS | SUPPRESS_TRAILING_WS;
  81. /** Manifest constant: Carry trailing whitespace of one chunk as leading
  82. * whitespace of the next chunk. Used internally; I don't see any reason
  83. * to make it public right now.
  84. */
  85. private static final int CARRY_WS=0x04;
  86. /**
  87. * Field m_chunkBits sets our chunking strategy, by saying how many
  88. * bits of index can be used within a single chunk before flowing over
  89. * to the next chunk. For example, if m_chunkbits is set to 15, each
  90. * chunk can contain up to 2^15 (32K) characters
  91. */
  92. int m_chunkBits = 15;
  93. /**
  94. * Field m_maxChunkBits affects our chunk-growth strategy, by saying what
  95. * the largest permissible chunk size is in this particular FastStringBuffer
  96. * hierarchy.
  97. */
  98. int m_maxChunkBits = 15;
  99. /**
  100. * Field m_rechunkBits affects our chunk-growth strategy, by saying how
  101. * many chunks should be allocated at one size before we encapsulate them
  102. * into the first chunk of the next size up. For example, if m_rechunkBits
  103. * is set to 3, then after 8 chunks at a given size we will rebundle
  104. * them as the first element of a FastStringBuffer using a chunk size
  105. * 8 times larger (chunkBits shifted left three bits).
  106. */
  107. int m_rebundleBits = 2;
  108. /**
  109. * Field m_chunkSize establishes the maximum size of one chunk of the array
  110. * as 2**chunkbits characters.
  111. * (Which may also be the minimum size if we aren't tuning for storage)
  112. */
  113. int m_chunkSize; // =1<<(m_chunkBits-1);
  114. /**
  115. * Field m_chunkMask is m_chunkSize-1 -- in other words, m_chunkBits
  116. * worth of low-order '1' bits, useful for shift-and-mask addressing
  117. * within the chunks.
  118. */
  119. int m_chunkMask; // =m_chunkSize-1;
  120. /**
  121. * Field m_array holds the string buffer's text contents, using an
  122. * array-of-arrays. Note that this array, and the arrays it contains, may be
  123. * reallocated when necessary in order to allow the buffer to grow;
  124. * references to them should be considered to be invalidated after any
  125. * append. However, the only time these arrays are directly exposed
  126. * is in the sendSAXcharacters call.
  127. */
  128. char[][] m_array;
  129. /**
  130. * Field m_lastChunk is an index into m_array[], pointing to the last
  131. * chunk of the Chunked Array currently in use. Note that additional
  132. * chunks may actually be allocated, eg if the FastStringBuffer had
  133. * previously been truncated or if someone issued an ensureSpace request.
  134. * <p>
  135. * The insertion point for append operations is addressed by the combination
  136. * of m_lastChunk and m_firstFree.
  137. */
  138. int m_lastChunk = 0;
  139. /**
  140. * Field m_firstFree is an index into m_array[m_lastChunk][], pointing to
  141. * the first character in the Chunked Array which is not part of the
  142. * FastStringBuffer's current content. Since m_array[][] is zero-based,
  143. * the length of that content can be calculated as
  144. * (m_lastChunk<<m_chunkBits) + m_firstFree
  145. */
  146. int m_firstFree = 0;
  147. /**
  148. * Field m_innerFSB, when non-null, is a FastStringBuffer whose total
  149. * length equals m_chunkSize, and which replaces m_array[0]. This allows
  150. * building a hierarchy of FastStringBuffers, where early appends use
  151. * a smaller chunkSize (for less wasted memory overhead) but later
  152. * ones use a larger chunkSize (for less heap activity overhead).
  153. */
  154. FastStringBuffer m_innerFSB = null;
  155. /**
  156. * Construct a FastStringBuffer, with allocation policy as per parameters.
  157. * <p>
  158. * For coding convenience, I've expressed both allocation sizes in terms of
  159. * a number of bits. That's needed for the final size of a chunk,
  160. * to permit fast and efficient shift-and-mask addressing. It's less critical
  161. * for the inital size, and may be reconsidered.
  162. * <p>
  163. * An alternative would be to accept integer sizes and round to powers of two;
  164. * that really doesn't seem to buy us much, if anything.
  165. *
  166. * @param initChunkBits Length in characters of the initial allocation
  167. * of a chunk, expressed in log-base-2. (That is, 10 means allocate 1024
  168. * characters.) Later chunks will use larger allocation units, to trade off
  169. * allocation speed of large document against storage efficiency of small
  170. * ones.
  171. * @param maxChunkBits Number of character-offset bits that should be used for
  172. * addressing within a chunk. Maximum length of a chunk is 2^chunkBits
  173. * characters.
  174. * @param rebundleBits Number of character-offset bits that addressing should
  175. * advance before we attempt to take a step from initChunkBits to maxChunkBits
  176. */
  177. public FastStringBuffer(int initChunkBits, int maxChunkBits,
  178. int rebundleBits)
  179. {
  180. if(DEBUG_FORCE_INIT_BITS!=0) initChunkBits=DEBUG_FORCE_INIT_BITS;
  181. // %REVIEW%
  182. // Should this force to larger value, or smaller? Smaller less efficient, but if
  183. // someone requested variable mode it's because they care about storage space.
  184. // On the other hand, given the other changes I'm making, odds are that we should
  185. // adopt the larger size. Dither, dither, dither... This is just stopgap workaround
  186. // anyway; we need a permanant solution.
  187. //
  188. if(DEBUG_FORCE_FIXED_CHUNKSIZE) maxChunkBits=initChunkBits;
  189. //if(DEBUG_FORCE_FIXED_CHUNKSIZE) initChunkBits=maxChunkBits;
  190. m_array = new char[16][];
  191. // Don't bite off more than we're prepared to swallow!
  192. if (initChunkBits > maxChunkBits)
  193. initChunkBits = maxChunkBits;
  194. m_chunkBits = initChunkBits;
  195. m_maxChunkBits = maxChunkBits;
  196. m_rebundleBits = rebundleBits;
  197. m_chunkSize = 1 << (initChunkBits);
  198. m_chunkMask = m_chunkSize - 1;
  199. m_array[0] = new char[m_chunkSize];
  200. }
  201. /**
  202. * Construct a FastStringBuffer, using a default rebundleBits value.
  203. *
  204. * NEEDSDOC @param initChunkBits
  205. * NEEDSDOC @param maxChunkBits
  206. */
  207. public FastStringBuffer(int initChunkBits, int maxChunkBits)
  208. {
  209. this(initChunkBits, maxChunkBits, 2);
  210. }
  211. /**
  212. * Construct a FastStringBuffer, using default maxChunkBits and
  213. * rebundleBits values.
  214. * <p>
  215. * ISSUE: Should this call assert initial size, or fixed size?
  216. * Now configured as initial, with a default for fixed.
  217. *
  218. * @param
  219. *
  220. * NEEDSDOC @param initChunkBits
  221. */
  222. public FastStringBuffer(int initChunkBits)
  223. {
  224. this(initChunkBits, 15, 2);
  225. }
  226. /**
  227. * Construct a FastStringBuffer, using a default allocation policy.
  228. */
  229. public FastStringBuffer()
  230. {
  231. // 10 bits is 1K. 15 bits is 32K. Remember that these are character
  232. // counts, so actual memory allocation unit is doubled for UTF-16 chars.
  233. //
  234. // For reference: In the original FastStringBuffer, we simply
  235. // overallocated by blocksize (default 1KB) on each buffer-growth.
  236. this(10, 15, 2);
  237. }
  238. /**
  239. * Get the length of the list. Synonym for length().
  240. *
  241. * @return the number of characters in the FastStringBuffer's content.
  242. */
  243. public final int size()
  244. {
  245. return (m_lastChunk << m_chunkBits) + m_firstFree;
  246. }
  247. /**
  248. * Get the length of the list. Synonym for size().
  249. *
  250. * @return the number of characters in the FastStringBuffer's content.
  251. */
  252. public final int length()
  253. {
  254. return (m_lastChunk << m_chunkBits) + m_firstFree;
  255. }
  256. /**
  257. * Discard the content of the FastStringBuffer, and most of the memory
  258. * that was allocated by it, restoring the initial state. Note that this
  259. * may eventually be different from setLength(0), which see.
  260. */
  261. public final void reset()
  262. {
  263. m_lastChunk = 0;
  264. m_firstFree = 0;
  265. // Recover the original chunk size
  266. FastStringBuffer innermost = this;
  267. while (innermost.m_innerFSB != null)
  268. {
  269. innermost = innermost.m_innerFSB;
  270. }
  271. m_chunkBits = innermost.m_chunkBits;
  272. m_chunkSize = innermost.m_chunkSize;
  273. m_chunkMask = innermost.m_chunkMask;
  274. // Discard the hierarchy
  275. m_innerFSB = null;
  276. m_array = new char[16][0];
  277. m_array[0] = new char[m_chunkSize];
  278. }
  279. /**
  280. * Directly set how much of the FastStringBuffer's storage is to be
  281. * considered part of its content. This is a fast but hazardous
  282. * operation. It is not protected against negative values, or values
  283. * greater than the amount of storage currently available... and even
  284. * if additional storage does exist, its contents are unpredictable.
  285. * The only safe use for our setLength() is to truncate the FastStringBuffer
  286. * to a shorter string.
  287. *
  288. * @param l New length. If l<0 or l>=getLength(), this operation will
  289. * not report an error but future operations will almost certainly fail.
  290. */
  291. public final void setLength(int l)
  292. {
  293. m_lastChunk = l >>> m_chunkBits;
  294. if (m_lastChunk == 0 && m_innerFSB != null)
  295. {
  296. // Replace this FSB with the appropriate inner FSB, truncated
  297. m_innerFSB.setLength(l, this);
  298. }
  299. else
  300. {
  301. m_firstFree = l & m_chunkMask;
  302. // There's an edge case if l is an exact multiple of m_chunkBits, which risks leaving
  303. // us pointing at the start of a chunk which has not yet been allocated. Rather than
  304. // pay the cost of dealing with that in the append loops (more scattered and more
  305. // inner-loop), we correct it here by moving to the safe side of that
  306. // line -- as we would have left the indexes had we appended up to that point.
  307. if(m_firstFree==0 && m_lastChunk>0)
  308. {
  309. --m_lastChunk;
  310. m_firstFree=m_chunkSize;
  311. }
  312. }
  313. }
  314. /**
  315. * Subroutine for the public setLength() method. Deals with the fact
  316. * that truncation may require restoring one of the innerFSBs
  317. *
  318. * NEEDSDOC @param l
  319. * NEEDSDOC @param rootFSB
  320. */
  321. private final void setLength(int l, FastStringBuffer rootFSB)
  322. {
  323. m_lastChunk = l >>> m_chunkBits;
  324. if (m_lastChunk == 0 && m_innerFSB != null)
  325. {
  326. m_innerFSB.setLength(l, rootFSB);
  327. }
  328. else
  329. {
  330. // Undo encapsulation -- pop the innerFSB data back up to root.
  331. // Inefficient, but attempts to keep the code simple.
  332. rootFSB.m_chunkBits = m_chunkBits;
  333. rootFSB.m_maxChunkBits = m_maxChunkBits;
  334. rootFSB.m_rebundleBits = m_rebundleBits;
  335. rootFSB.m_chunkSize = m_chunkSize;
  336. rootFSB.m_chunkMask = m_chunkMask;
  337. rootFSB.m_array = m_array;
  338. rootFSB.m_innerFSB = m_innerFSB;
  339. rootFSB.m_lastChunk = m_lastChunk;
  340. // Finally, truncate this sucker.
  341. rootFSB.m_firstFree = l & m_chunkMask;
  342. }
  343. }
  344. /**
  345. * Note that this operation has been somewhat deoptimized by the shift to a
  346. * chunked array, as there is no factory method to produce a String object
  347. * directly from an array of arrays and hence a double copy is needed.
  348. * By using ensureCapacity we hope to minimize the heap overhead of building
  349. * the intermediate StringBuffer.
  350. * <p>
  351. * (It really is a pity that Java didn't design String as a final subclass
  352. * of MutableString, rather than having StringBuffer be a separate hierarchy.
  353. * We'd avoid a <strong>lot</strong> of double-buffering.)
  354. *
  355. * @return the contents of the FastStringBuffer as a standard Java string.
  356. */
  357. public final String toString()
  358. {
  359. int length = (m_lastChunk << m_chunkBits) + m_firstFree;
  360. return getString(new StringBuffer(length), 0, 0, length).toString();
  361. }
  362. /**
  363. * Append a single character onto the FastStringBuffer, growing the
  364. * storage if necessary.
  365. * <p>
  366. * NOTE THAT after calling append(), previously obtained
  367. * references to m_array[][] may no longer be valid....
  368. * though in fact they should be in this instance.
  369. *
  370. * @param value character to be appended.
  371. */
  372. public final void append(char value)
  373. {
  374. char[] chunk;
  375. // We may have preallocated chunks. If so, all but last should
  376. // be at full size.
  377. boolean lastchunk = (m_lastChunk + 1 == m_array.length);
  378. if (m_firstFree < m_chunkSize) // Simplified test single-character-fits
  379. chunk = m_array[m_lastChunk];
  380. else
  381. {
  382. // Extend array?
  383. int i = m_array.length;
  384. if (m_lastChunk + 1 == i)
  385. {
  386. char[][] newarray = new char[i + 16][];
  387. System.arraycopy(m_array, 0, newarray, 0, i);
  388. m_array = newarray;
  389. }
  390. // Advance one chunk
  391. chunk = m_array[++m_lastChunk];
  392. if (chunk == null)
  393. {
  394. // Hierarchical encapsulation
  395. if (m_lastChunk == 1 << m_rebundleBits
  396. && m_chunkBits < m_maxChunkBits)
  397. {
  398. // Should do all the work of both encapsulating
  399. // existing data and establishing new sizes/offsets
  400. m_innerFSB = new FastStringBuffer(this);
  401. }
  402. // Add a chunk.
  403. chunk = m_array[m_lastChunk] = new char[m_chunkSize];
  404. }
  405. m_firstFree = 0;
  406. }
  407. // Space exists in the chunk. Append the character.
  408. chunk[m_firstFree++] = value;
  409. }
  410. /**
  411. * Append the contents of a String onto the FastStringBuffer,
  412. * growing the storage if necessary.
  413. * <p>
  414. * NOTE THAT after calling append(), previously obtained
  415. * references to m_array[] may no longer be valid.
  416. *
  417. * @param value String whose contents are to be appended.
  418. */
  419. public final void append(String value)
  420. {
  421. if (value == null)
  422. return;
  423. int strlen = value.length();
  424. if (0 == strlen)
  425. return;
  426. int copyfrom = 0;
  427. char[] chunk = m_array[m_lastChunk];
  428. int available = m_chunkSize - m_firstFree;
  429. // Repeat while data remains to be copied
  430. while (strlen > 0)
  431. {
  432. // Copy what fits
  433. if (available > strlen)
  434. available = strlen;
  435. value.getChars(copyfrom, copyfrom + available, m_array[m_lastChunk],
  436. m_firstFree);
  437. strlen -= available;
  438. copyfrom += available;
  439. // If there's more left, allocate another chunk and continue
  440. if (strlen > 0)
  441. {
  442. // Extend array?
  443. int i = m_array.length;
  444. if (m_lastChunk + 1 == i)
  445. {
  446. char[][] newarray = new char[i + 16][];
  447. System.arraycopy(m_array, 0, newarray, 0, i);
  448. m_array = newarray;
  449. }
  450. // Advance one chunk
  451. chunk = m_array[++m_lastChunk];
  452. if (chunk == null)
  453. {
  454. // Hierarchical encapsulation
  455. if (m_lastChunk == 1 << m_rebundleBits
  456. && m_chunkBits < m_maxChunkBits)
  457. {
  458. // Should do all the work of both encapsulating
  459. // existing data and establishing new sizes/offsets
  460. m_innerFSB = new FastStringBuffer(this);
  461. }
  462. // Add a chunk.
  463. chunk = m_array[m_lastChunk] = new char[m_chunkSize];
  464. }
  465. available = m_chunkSize;
  466. m_firstFree = 0;
  467. }
  468. }
  469. // Adjust the insert point in the last chunk, when we've reached it.
  470. m_firstFree += available;
  471. }
  472. /**
  473. * Append the contents of a StringBuffer onto the FastStringBuffer,
  474. * growing the storage if necessary.
  475. * <p>
  476. * NOTE THAT after calling append(), previously obtained
  477. * references to m_array[] may no longer be valid.
  478. *
  479. * @param value StringBuffer whose contents are to be appended.
  480. */
  481. public final void append(StringBuffer value)
  482. {
  483. if (value == null)
  484. return;
  485. int strlen = value.length();
  486. if (0 == strlen)
  487. return;
  488. int copyfrom = 0;
  489. char[] chunk = m_array[m_lastChunk];
  490. int available = m_chunkSize - m_firstFree;
  491. // Repeat while data remains to be copied
  492. while (strlen > 0)
  493. {
  494. // Copy what fits
  495. if (available > strlen)
  496. available = strlen;
  497. value.getChars(copyfrom, copyfrom + available, m_array[m_lastChunk],
  498. m_firstFree);
  499. strlen -= available;
  500. copyfrom += available;
  501. // If there's more left, allocate another chunk and continue
  502. if (strlen > 0)
  503. {
  504. // Extend array?
  505. int i = m_array.length;
  506. if (m_lastChunk + 1 == i)
  507. {
  508. char[][] newarray = new char[i + 16][];
  509. System.arraycopy(m_array, 0, newarray, 0, i);
  510. m_array = newarray;
  511. }
  512. // Advance one chunk
  513. chunk = m_array[++m_lastChunk];
  514. if (chunk == null)
  515. {
  516. // Hierarchical encapsulation
  517. if (m_lastChunk == 1 << m_rebundleBits
  518. && m_chunkBits < m_maxChunkBits)
  519. {
  520. // Should do all the work of both encapsulating
  521. // existing data and establishing new sizes/offsets
  522. m_innerFSB = new FastStringBuffer(this);
  523. }
  524. // Add a chunk.
  525. chunk = m_array[m_lastChunk] = new char[m_chunkSize];
  526. }
  527. available = m_chunkSize;
  528. m_firstFree = 0;
  529. }
  530. }
  531. // Adjust the insert point in the last chunk, when we've reached it.
  532. m_firstFree += available;
  533. }
  534. /**
  535. * Append part of the contents of a Character Array onto the
  536. * FastStringBuffer, growing the storage if necessary.
  537. * <p>
  538. * NOTE THAT after calling append(), previously obtained
  539. * references to m_array[] may no longer be valid.
  540. *
  541. * @param chars character array from which data is to be copied
  542. * @param start offset in chars of first character to be copied,
  543. * zero-based.
  544. * @param length number of characters to be copied
  545. */
  546. public final void append(char[] chars, int start, int length)
  547. {
  548. int strlen = length;
  549. if (0 == strlen)
  550. return;
  551. int copyfrom = start;
  552. char[] chunk = m_array[m_lastChunk];
  553. int available = m_chunkSize - m_firstFree;
  554. // Repeat while data remains to be copied
  555. while (strlen > 0)
  556. {
  557. // Copy what fits
  558. if (available > strlen)
  559. available = strlen;
  560. System.arraycopy(chars, copyfrom, m_array[m_lastChunk], m_firstFree,
  561. available);
  562. strlen -= available;
  563. copyfrom += available;
  564. // If there's more left, allocate another chunk and continue
  565. if (strlen > 0)
  566. {
  567. // Extend array?
  568. int i = m_array.length;
  569. if (m_lastChunk + 1 == i)
  570. {
  571. char[][] newarray = new char[i + 16][];
  572. System.arraycopy(m_array, 0, newarray, 0, i);
  573. m_array = newarray;
  574. }
  575. // Advance one chunk
  576. chunk = m_array[++m_lastChunk];
  577. if (chunk == null)
  578. {
  579. // Hierarchical encapsulation
  580. if (m_lastChunk == 1 << m_rebundleBits
  581. && m_chunkBits < m_maxChunkBits)
  582. {
  583. // Should do all the work of both encapsulating
  584. // existing data and establishing new sizes/offsets
  585. m_innerFSB = new FastStringBuffer(this);
  586. }
  587. // Add a chunk.
  588. chunk = m_array[m_lastChunk] = new char[m_chunkSize];
  589. }
  590. available = m_chunkSize;
  591. m_firstFree = 0;
  592. }
  593. }
  594. // Adjust the insert point in the last chunk, when we've reached it.
  595. m_firstFree += available;
  596. }
  597. /**
  598. * Append the contents of another FastStringBuffer onto
  599. * this FastStringBuffer, growing the storage if necessary.
  600. * <p>
  601. * NOTE THAT after calling append(), previously obtained
  602. * references to m_array[] may no longer be valid.
  603. *
  604. * @param value FastStringBuffer whose contents are
  605. * to be appended.
  606. */
  607. public final void append(FastStringBuffer value)
  608. {
  609. // Complicating factor here is that the two buffers may use
  610. // different chunk sizes, and even if they're the same we're
  611. // probably on a different alignment due to previously appended
  612. // data. We have to work through the source in bite-sized chunks.
  613. if (value == null)
  614. return;
  615. int strlen = value.length();
  616. if (0 == strlen)
  617. return;
  618. int copyfrom = 0;
  619. char[] chunk = m_array[m_lastChunk];
  620. int available = m_chunkSize - m_firstFree;
  621. // Repeat while data remains to be copied
  622. while (strlen > 0)
  623. {
  624. // Copy what fits
  625. if (available > strlen)
  626. available = strlen;
  627. int sourcechunk = (copyfrom + value.m_chunkSize - 1)
  628. >>> value.m_chunkBits;
  629. int sourcecolumn = copyfrom & value.m_chunkMask;
  630. int runlength = value.m_chunkSize - sourcecolumn;
  631. if (runlength > available)
  632. runlength = available;
  633. System.arraycopy(value.m_array[sourcechunk], sourcecolumn,
  634. m_array[m_lastChunk], m_firstFree, runlength);
  635. if (runlength != available)
  636. System.arraycopy(value.m_array[sourcechunk + 1], 0,
  637. m_array[m_lastChunk], m_firstFree + runlength,
  638. available - runlength);
  639. strlen -= available;
  640. copyfrom += available;
  641. // If there's more left, allocate another chunk and continue
  642. if (strlen > 0)
  643. {
  644. // Extend array?
  645. int i = m_array.length;
  646. if (m_lastChunk + 1 == i)
  647. {
  648. char[][] newarray = new char[i + 16][];
  649. System.arraycopy(m_array, 0, newarray, 0, i);
  650. m_array = newarray;
  651. }
  652. // Advance one chunk
  653. chunk = m_array[++m_lastChunk];
  654. if (chunk == null)
  655. {
  656. // Hierarchical encapsulation
  657. if (m_lastChunk == 1 << m_rebundleBits
  658. && m_chunkBits < m_maxChunkBits)
  659. {
  660. // Should do all the work of both encapsulating
  661. // existing data and establishing new sizes/offsets
  662. m_innerFSB = new FastStringBuffer(this);
  663. }
  664. // Add a chunk.
  665. chunk = m_array[m_lastChunk] = new char[m_chunkSize];
  666. }
  667. available = m_chunkSize;
  668. m_firstFree = 0;
  669. }
  670. }
  671. // Adjust the insert point in the last chunk, when we've reached it.
  672. m_firstFree += available;
  673. }
  674. /**
  675. * @return true if the specified range of characters are all whitespace,
  676. * as defined by XMLCharacterRecognizer.
  677. * <p>
  678. * CURRENTLY DOES NOT CHECK FOR OUT-OF-RANGE.
  679. *
  680. * @param start Offset of first character in the range.
  681. * @param length Number of characters to send.
  682. */
  683. public boolean isWhitespace(int start, int length)
  684. {
  685. int sourcechunk = start >>> m_chunkBits;
  686. int sourcecolumn = start & m_chunkMask;
  687. int available = m_chunkSize - sourcecolumn;
  688. boolean chunkOK;
  689. while (length > 0)
  690. {
  691. int runlength = (length <= available) ? length : available;
  692. if (sourcechunk == 0 && m_innerFSB != null)
  693. chunkOK = m_innerFSB.isWhitespace(sourcecolumn, runlength);
  694. else
  695. chunkOK = com.sun.org.apache.xml.internal.utils.XMLCharacterRecognizer.isWhiteSpace(
  696. m_array[sourcechunk], sourcecolumn, runlength);
  697. if (!chunkOK)
  698. return false;
  699. length -= runlength;
  700. ++sourcechunk;
  701. sourcecolumn = 0;
  702. available = m_chunkSize;
  703. }
  704. return true;
  705. }
  706. /**
  707. * @param start Offset of first character in the range.
  708. * @param length Number of characters to send.
  709. * @return a new String object initialized from the specified range of
  710. * characters.
  711. */
  712. public String getString(int start, int length)
  713. {
  714. int startColumn = start & m_chunkMask;
  715. int startChunk = start >>> m_chunkBits;
  716. if (startColumn + length < m_chunkMask && m_innerFSB == null) {
  717. return getOneChunkString(startChunk, startColumn, length);
  718. }
  719. return getString(new StringBuffer(length), startChunk, startColumn,
  720. length).toString();
  721. }
  722. protected String getOneChunkString(int startChunk, int startColumn,
  723. int length) {
  724. return new String(m_array[startChunk], startColumn, length);
  725. }
  726. /**
  727. * @param sb StringBuffer to be appended to
  728. * @param start Offset of first character in the range.
  729. * @param length Number of characters to send.
  730. * @return sb with the requested text appended to it
  731. */
  732. StringBuffer getString(StringBuffer sb, int start, int length)
  733. {
  734. return getString(sb, start >>> m_chunkBits, start & m_chunkMask, length);
  735. }
  736. /**
  737. * Internal support for toString() and getString().
  738. * PLEASE NOTE SIGNATURE CHANGE from earlier versions; it now appends into
  739. * and returns a StringBuffer supplied by the caller. This simplifies
  740. * m_innerFSB support.
  741. * <p>
  742. * Note that this operation has been somewhat deoptimized by the shift to a
  743. * chunked array, as there is no factory method to produce a String object
  744. * directly from an array of arrays and hence a double copy is needed.
  745. * By presetting length we hope to minimize the heap overhead of building
  746. * the intermediate StringBuffer.
  747. * <p>
  748. * (It really is a pity that Java didn't design String as a final subclass
  749. * of MutableString, rather than having StringBuffer be a separate hierarchy.
  750. * We'd avoid a <strong>lot</strong> of double-buffering.)
  751. *
  752. *
  753. * @param sb
  754. * @param startChunk
  755. * @param startColumn
  756. * @param length
  757. *
  758. * @return the contents of the FastStringBuffer as a standard Java string.
  759. */
  760. StringBuffer getString(StringBuffer sb, int startChunk, int startColumn,
  761. int length)
  762. {
  763. int stop = (startChunk << m_chunkBits) + startColumn + length;
  764. int stopChunk = stop >>> m_chunkBits;
  765. int stopColumn = stop & m_chunkMask;
  766. // Factored out
  767. //StringBuffer sb=new StringBuffer(length);
  768. for (int i = startChunk; i < stopChunk; ++i)
  769. {
  770. if (i == 0 && m_innerFSB != null)
  771. m_innerFSB.getString(sb, startColumn, m_chunkSize - startColumn);
  772. else
  773. sb.append(m_array[i], startColumn, m_chunkSize - startColumn);
  774. startColumn = 0; // after first chunk
  775. }
  776. if (stopChunk == 0 && m_innerFSB != null)
  777. m_innerFSB.getString(sb, startColumn, stopColumn - startColumn);
  778. else if (stopColumn > startColumn)
  779. sb.append(m_array[stopChunk], startColumn, stopColumn - startColumn);
  780. return sb;
  781. }
  782. /**
  783. * Get a single character from the string buffer.
  784. *
  785. *
  786. * @param pos character position requested.
  787. * @return A character from the requested position.
  788. */
  789. public char charAt(int pos)
  790. {
  791. int startChunk = pos >>> m_chunkBits;
  792. if (startChunk == 0 && m_innerFSB != null)
  793. return m_innerFSB.charAt(pos & m_chunkMask);
  794. else
  795. return m_array[startChunk][pos & m_chunkMask];
  796. }
  797. /**
  798. * Sends the specified range of characters as one or more SAX characters()
  799. * events.
  800. * Note that the buffer reference passed to the ContentHandler may be
  801. * invalidated if the FastStringBuffer is edited; it's the user's
  802. * responsibility to manage access to the FastStringBuffer to prevent this
  803. * problem from arising.
  804. * <p>
  805. * Note too that there is no promise that the output will be sent as a
  806. * single call. As is always true in SAX, one logical string may be split
  807. * across multiple blocks of memory and hence delivered as several
  808. * successive events.
  809. *
  810. * @param ch SAX ContentHandler object to receive the event.
  811. * @param start Offset of first character in the range.
  812. * @param length Number of characters to send.
  813. * @exception org.xml.sax.SAXException may be thrown by handler's
  814. * characters() method.
  815. */
  816. public void sendSAXcharacters(
  817. org.xml.sax.ContentHandler ch, int start, int length)
  818. throws org.xml.sax.SAXException
  819. {
  820. int startChunk = start >>> m_chunkBits;
  821. int startColumn = start & m_chunkMask;
  822. if (startColumn + length < m_chunkMask && m_innerFSB == null) {
  823. ch.characters(m_array[startChunk], startColumn, length);
  824. return;
  825. }
  826. int stop = start + length;
  827. int stopChunk = stop >>> m_chunkBits;
  828. int stopColumn = stop & m_chunkMask;
  829. for (int i = startChunk; i < stopChunk; ++i)
  830. {
  831. if (i == 0 && m_innerFSB != null)
  832. m_innerFSB.sendSAXcharacters(ch, startColumn,
  833. m_chunkSize - startColumn);
  834. else
  835. ch.characters(m_array[i], startColumn, m_chunkSize - startColumn);
  836. startColumn = 0; // after first chunk
  837. }
  838. // Last, or only, chunk
  839. if (stopChunk == 0 && m_innerFSB != null)
  840. m_innerFSB.sendSAXcharacters(ch, startColumn, stopColumn - startColumn);
  841. else if (stopColumn > startColumn)
  842. {
  843. ch.characters(m_array[stopChunk], startColumn,
  844. stopColumn - startColumn);
  845. }
  846. }
  847. /**
  848. * Sends the specified range of characters as one or more SAX characters()
  849. * events, normalizing the characters according to XSLT rules.
  850. *
  851. * @param ch SAX ContentHandler object to receive the event.
  852. * @param start Offset of first character in the range.
  853. * @param length Number of characters to send.
  854. * @return normalization status to apply to next chunk (because we may
  855. * have been called recursively to process an inner FSB):
  856. * <dl>
  857. * <dt>0</dt>
  858. * <dd>if this output did not end in retained whitespace, and thus whitespace
  859. * at the start of the following chunk (if any) should be converted to a
  860. * single space.
  861. * <dt>SUPPRESS_LEADING_WS</dt>
  862. * <dd>if this output ended in retained whitespace, and thus whitespace
  863. * at the start of the following chunk (if any) should be completely
  864. * suppressed.</dd>
  865. * </dd>
  866. * </dl>
  867. * @exception org.xml.sax.SAXException may be thrown by handler's
  868. * characters() method.
  869. */
  870. public int sendNormalizedSAXcharacters(
  871. org.xml.sax.ContentHandler ch, int start, int length)
  872. throws org.xml.sax.SAXException
  873. {
  874. // This call always starts at the beginning of the
  875. // string being written out, either because it was called directly or
  876. // because it was an m_innerFSB recursion. This is important since
  877. // it gives us a well-known initial state for this flag:
  878. int stateForNextChunk=SUPPRESS_LEADING_WS;
  879. int stop = start + length;
  880. int startChunk = start >>> m_chunkBits;
  881. int startColumn = start & m_chunkMask;
  882. int stopChunk = stop >>> m_chunkBits;
  883. int stopColumn = stop & m_chunkMask;
  884. for (int i = startChunk; i < stopChunk; ++i)
  885. {
  886. if (i == 0 && m_innerFSB != null)
  887. stateForNextChunk=
  888. m_innerFSB.sendNormalizedSAXcharacters(ch, startColumn,
  889. m_chunkSize - startColumn);
  890. else
  891. stateForNextChunk=
  892. sendNormalizedSAXcharacters(m_array[i], startColumn,
  893. m_chunkSize - startColumn,
  894. ch,stateForNextChunk);
  895. startColumn = 0; // after first chunk
  896. }
  897. // Last, or only, chunk
  898. if (stopChunk == 0 && m_innerFSB != null)
  899. stateForNextChunk= // %REVIEW% Is this update really needed?
  900. m_innerFSB.sendNormalizedSAXcharacters(ch, startColumn, stopColumn - startColumn);
  901. else if (stopColumn > startColumn)
  902. {
  903. stateForNextChunk= // %REVIEW% Is this update really needed?
  904. sendNormalizedSAXcharacters(m_array[stopChunk],
  905. startColumn, stopColumn - startColumn,
  906. ch, stateForNextChunk | SUPPRESS_TRAILING_WS);
  907. }
  908. return stateForNextChunk;
  909. }
  910. static final char[] SINGLE_SPACE = {' '};
  911. /**
  912. * Internal method to directly normalize and dispatch the character array.
  913. * This version is aware of the fact that it may be called several times
  914. * in succession if the data is made up of multiple "chunks", and thus
  915. * must actively manage the handling of leading and trailing whitespace.
  916. *
  917. * Note: The recursion is due to the possible recursion of inner FSBs.
  918. *
  919. * @param ch The characters from the XML document.
  920. * @param start The start position in the array.
  921. * @param length The number of characters to read from the array.
  922. * @param handler SAX ContentHandler object to receive the event.
  923. * @param edgeTreatmentFlags How leading/trailing spaces should be handled.
  924. * This is a bitfield contining two flags, bitwise-ORed together:
  925. * <dl>
  926. * <dt>SUPPRESS_LEADING_WS</dt>
  927. * <dd>When false, causes leading whitespace to be converted to a single
  928. * space; when true, causes it to be discarded entirely.
  929. * Should be set TRUE for the first chunk, and (in multi-chunk output)
  930. * whenever the previous chunk ended in retained whitespace.</dd>
  931. * <dt>SUPPRESS_TRAILING_WS</dt>
  932. * <dd>When false, causes trailing whitespace to be converted to a single
  933. * space; when true, causes it to be discarded entirely.
  934. * Should be set TRUE for the last or only chunk.
  935. * </dd>
  936. * </dl>
  937. * @return normalization status, as in the edgeTreatmentFlags parameter:
  938. * <dl>
  939. * <dt>0</dt>
  940. * <dd>if this output did not end in retained whitespace, and thus whitespace
  941. * at the start of the following chunk (if any) should be converted to a
  942. * single space.
  943. * <dt>SUPPRESS_LEADING_WS</dt>
  944. * <dd>if this output ended in retained whitespace, and thus whitespace
  945. * at the start of the following chunk (if any) should be completely
  946. * suppressed.</dd>
  947. * </dd>
  948. * </dl>
  949. *
  950. *
  951. * @exception org.xml.sax.SAXException Any SAX exception, possibly
  952. * wrapping another exception.
  953. */
  954. static int sendNormalizedSAXcharacters(char ch[],
  955. int start, int length,
  956. org.xml.sax.ContentHandler handler,
  957. int edgeTreatmentFlags)
  958. throws org.xml.sax.SAXException
  959. {
  960. boolean processingLeadingWhitespace =
  961. ((edgeTreatmentFlags & SUPPRESS_LEADING_WS) != 0);
  962. boolean seenWhitespace = ((edgeTreatmentFlags & CARRY_WS) != 0);
  963. boolean suppressTrailingWhitespace =
  964. ((edgeTreatmentFlags & SUPPRESS_TRAILING_WS) != 0);
  965. int currPos = start;
  966. int limit = start+length;
  967. // Strip any leading spaces first, if required
  968. if (processingLeadingWhitespace) {
  969. for (; currPos < limit
  970. && XMLCharacterRecognizer.isWhiteSpace(ch[currPos]);
  971. currPos++) { }
  972. // If we've only encountered leading spaces, the
  973. // current state remains unchanged
  974. if (currPos == limit) {
  975. return edgeTreatmentFlags;
  976. }
  977. }
  978. // If we get here, there are no more leading spaces to strip
  979. while (currPos < limit) {
  980. int startNonWhitespace = currPos;
  981. // Grab a chunk of non-whitespace characters
  982. for (; currPos < limit
  983. && !XMLCharacterRecognizer.isWhiteSpace(ch[currPos]);
  984. currPos++) { }
  985. // Non-whitespace seen - emit them, along with a single
  986. // space for any preceding whitespace characters
  987. if (startNonWhitespace != currPos) {
  988. if (seenWhitespace) {
  989. handler.characters(SINGLE_SPACE, 0, 1);
  990. seenWhitespace = false;
  991. }
  992. handler.characters(ch, startNonWhitespace,
  993. currPos - startNonWhitespace);
  994. }
  995. int startWhitespace = currPos;
  996. // Consume any whitespace characters
  997. for (; currPos < limit
  998. && XMLCharacterRecognizer.isWhiteSpace(ch[currPos]);
  999. currPos++) { }
  1000. if (startWhitespace != currPos) {
  1001. seenWhitespace = true;
  1002. }
  1003. }
  1004. return (seenWhitespace ? CARRY_WS : 0)
  1005. | (edgeTreatmentFlags & SUPPRESS_TRAILING_WS);
  1006. }
  1007. /**
  1008. * Directly normalize and dispatch the character array.
  1009. *
  1010. * @param ch The characters from the XML document.
  1011. * @param start The start position in the array.
  1012. * @param length The number of characters to read from the array.
  1013. * @param handler SAX ContentHandler object to receive the event.
  1014. * @exception org.xml.sax.SAXException Any SAX exception, possibly
  1015. * wrapping another exception.
  1016. */
  1017. public static void sendNormalizedSAXcharacters(char ch[],
  1018. int start, int length,
  1019. org.xml.sax.ContentHandler handler)
  1020. throws org.xml.sax.SAXException
  1021. {
  1022. sendNormalizedSAXcharacters(ch, start, length,
  1023. handler, SUPPRESS_BOTH);
  1024. }
  1025. /**
  1026. * Sends the specified range of characters as sax Comment.
  1027. * <p>
  1028. * Note that, unlike sendSAXcharacters, this has to be done as a single
  1029. * call to LexicalHandler#comment.
  1030. *
  1031. * @param ch SAX LexicalHandler object to receive the event.
  1032. * @param start Offset of first character in the range.
  1033. * @param length Number of characters to send.
  1034. * @exception org.xml.sax.SAXException may be thrown by handler's
  1035. * characters() method.
  1036. */
  1037. public void sendSAXComment(
  1038. org.xml.sax.ext.LexicalHandler ch, int start, int length)
  1039. throws org.xml.sax.SAXException
  1040. {
  1041. // %OPT% Do it this way for now...
  1042. String comment = getString(start, length);
  1043. ch.comment(comment.toCharArray(), 0, length);
  1044. }
  1045. /**
  1046. * Copies characters from this string into the destination character
  1047. * array.
  1048. *
  1049. * @param srcBegin index of the first character in the string
  1050. * to copy.
  1051. * @param srcEnd index after the last character in the string
  1052. * to copy.
  1053. * @param dst the destination array.
  1054. * @param dstBegin the start offset in the destination array.
  1055. * @exception IndexOutOfBoundsException If any of the following
  1056. * is true:
  1057. * <ul><li><code>srcBegin</code> is negative.
  1058. * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
  1059. * <li><code>srcEnd</code> is greater than the length of this
  1060. * string
  1061. * <li><code>dstBegin</code> is negative
  1062. * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
  1063. * <code>dst.length</code></ul>
  1064. * @exception NullPointerException if <code>dst</code> is <code>null</code>
  1065. */
  1066. private void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
  1067. {
  1068. // %TBD% Joe needs to write this function. Make public when implemented.
  1069. }
  1070. /**
  1071. * Encapsulation c'tor. After this is called, the source FastStringBuffer
  1072. * will be reset to use the new object as its m_innerFSB, and will have
  1073. * had its chunk size reset appropriately. IT SHOULD NEVER BE CALLED
  1074. * EXCEPT WHEN source.length()==1<<(source.m_chunkBits+source.m_rebundleBits)
  1075. *
  1076. * NEEDSDOC @param source
  1077. */
  1078. private FastStringBuffer(FastStringBuffer source)
  1079. {
  1080. // Copy existing information into new encapsulation
  1081. m_chunkBits = source.m_chunkBits;
  1082. m_maxChunkBits = source.m_maxChunkBits;
  1083. m_rebundleBits = source.m_rebundleBits;
  1084. m_chunkSize = source.m_chunkSize;
  1085. m_chunkMask = source.m_chunkMask;
  1086. m_array = source.m_array;
  1087. m_innerFSB = source.m_innerFSB;
  1088. // These have to be adjusted because we're calling just at the time
  1089. // when we would be about to allocate another chunk
  1090. m_lastChunk = source.m_lastChunk - 1;
  1091. m_firstFree = source.m_chunkSize;
  1092. // Establish capsule as the Inner FSB, reset chunk sizes/addressing
  1093. source.m_array = new char[16][];
  1094. source.m_innerFSB = this;
  1095. // Since we encapsulated just as we were about to append another
  1096. // chunk, return ready to create the chunk after the innerFSB
  1097. // -- 1, not 0.
  1098. source.m_lastChunk = 1;
  1099. source.m_firstFree = 0;
  1100. source.m_chunkBits += m_rebundleBits;
  1101. source.m_chunkSize = 1 << (source.m_chunkBits);
  1102. source.m_chunkMask = source.m_chunkSize - 1;
  1103. }
  1104. }