PageRenderTime 25ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Common/SharpZipLib/Zip/ZipExtraData.cs

http://tsanie-shellextension.googlecode.com/
C# | 984 lines | 554 code | 106 blank | 324 comment | 64 complexity | c3922d77c6746802b32d1ae2aa4f6aad MD5 | raw file
  1. //
  2. // ZipExtraData.cs
  3. //
  4. // Copyright 2004-2007 John Reilly
  5. //
  6. // This program is free software; you can redistribute it and/or
  7. // modify it under the terms of the GNU General Public License
  8. // as published by the Free Software Foundation; either version 2
  9. // of the License, or (at your option) any later version.
  10. //
  11. // This program is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with this program; if not, write to the Free Software
  18. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. //
  20. // Linking this library statically or dynamically with other modules is
  21. // making a combined work based on this library. Thus, the terms and
  22. // conditions of the GNU General Public License cover the whole
  23. // combination.
  24. //
  25. // As a special exception, the copyright holders of this library give you
  26. // permission to link this library with independent modules to produce an
  27. // executable, regardless of the license terms of these independent
  28. // modules, and to copy and distribute the resulting executable under
  29. // terms of your choice, provided that you also meet, for each linked
  30. // independent module, the terms and conditions of the license of that
  31. // module. An independent module is a module which is not derived from
  32. // or based on this library. If you modify this library, you may extend
  33. // this exception to your version of the library, but you are not
  34. // obligated to do so. If you do not wish to do so, delete this
  35. // exception statement from your version.
  36. using System;
  37. using System.Collections;
  38. using System.IO;
  39. namespace SharpZipLib.Zip
  40. {
  41. // TODO: Sort out wether tagged data is useful and what a good implementation might look like.
  42. // Its just a sketch of an idea at the moment.
  43. /// <summary>
  44. /// ExtraData tagged value interface.
  45. /// </summary>
  46. public interface ITaggedData
  47. {
  48. /// <summary>
  49. /// Get the ID for this tagged data value.
  50. /// </summary>
  51. short TagID { get; }
  52. /// <summary>
  53. /// Set the contents of this instance from the data passed.
  54. /// </summary>
  55. /// <param name="data">The data to extract contents from.</param>
  56. /// <param name="offset">The offset to begin extracting data from.</param>
  57. /// <param name="count">The number of bytes to extract.</param>
  58. void SetData(byte[] data, int offset, int count);
  59. /// <summary>
  60. /// Get the data representing this instance.
  61. /// </summary>
  62. /// <returns>Returns the data for this instance.</returns>
  63. byte[] GetData();
  64. }
  65. /// <summary>
  66. /// A raw binary tagged value
  67. /// </summary>
  68. public class RawTaggedData : ITaggedData
  69. {
  70. /// <summary>
  71. /// Initialise a new instance.
  72. /// </summary>
  73. /// <param name="tag">The tag ID.</param>
  74. public RawTaggedData(short tag)
  75. {
  76. tag_ = tag;
  77. }
  78. #region ITaggedData Members
  79. /// <summary>
  80. /// Get the ID for this tagged data value.
  81. /// </summary>
  82. public short TagID
  83. {
  84. get { return tag_; }
  85. set { tag_ = value; }
  86. }
  87. /// <summary>
  88. /// Set the data from the raw values provided.
  89. /// </summary>
  90. /// <param name="data">The raw data to extract values from.</param>
  91. /// <param name="offset">The index to start extracting values from.</param>
  92. /// <param name="count">The number of bytes available.</param>
  93. public void SetData(byte[] data, int offset, int count)
  94. {
  95. if( data==null )
  96. {
  97. throw new ArgumentNullException("data");
  98. }
  99. data_=new byte[count];
  100. Array.Copy(data, offset, data_, 0, count);
  101. }
  102. /// <summary>
  103. /// Get the binary data representing this instance.
  104. /// </summary>
  105. /// <returns>The raw binary data representing this instance.</returns>
  106. public byte[] GetData()
  107. {
  108. return data_;
  109. }
  110. #endregion
  111. /// <summary>
  112. /// Get /set the binary data representing this instance.
  113. /// </summary>
  114. /// <returns>The raw binary data representing this instance.</returns>
  115. public byte[] Data
  116. {
  117. get { return data_; }
  118. set { data_=value; }
  119. }
  120. #region Instance Fields
  121. /// <summary>
  122. /// The tag ID for this instance.
  123. /// </summary>
  124. protected short tag_;
  125. byte[] data_;
  126. #endregion
  127. }
  128. /// <summary>
  129. /// Class representing extended unix date time values.
  130. /// </summary>
  131. public class ExtendedUnixData : ITaggedData
  132. {
  133. /// <summary>
  134. /// Flags indicate which values are included in this instance.
  135. /// </summary>
  136. [Flags]
  137. public enum Flags : byte
  138. {
  139. /// <summary>
  140. /// The modification time is included
  141. /// </summary>
  142. ModificationTime = 0x01,
  143. /// <summary>
  144. /// The access time is included
  145. /// </summary>
  146. AccessTime = 0x02,
  147. /// <summary>
  148. /// The create time is included.
  149. /// </summary>
  150. CreateTime = 0x04,
  151. }
  152. #region ITaggedData Members
  153. /// <summary>
  154. /// Get the ID
  155. /// </summary>
  156. public short TagID
  157. {
  158. get { return 0x5455; }
  159. }
  160. /// <summary>
  161. /// Set the data from the raw values provided.
  162. /// </summary>
  163. /// <param name="data">The raw data to extract values from.</param>
  164. /// <param name="index">The index to start extracting values from.</param>
  165. /// <param name="count">The number of bytes available.</param>
  166. public void SetData(byte[] data, int index, int count)
  167. {
  168. using (MemoryStream ms = new MemoryStream(data, index, count, false))
  169. using (ZipHelperStream helperStream = new ZipHelperStream(ms))
  170. {
  171. // bit 0 if set, modification time is present
  172. // bit 1 if set, access time is present
  173. // bit 2 if set, creation time is present
  174. flags_ = (Flags)helperStream.ReadByte();
  175. if (((flags_ & Flags.ModificationTime) != 0) && (count >= 5))
  176. {
  177. int iTime = helperStream.ReadLEInt();
  178. modificationTime_ = (new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
  179. new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
  180. }
  181. if ((flags_ & Flags.AccessTime) != 0)
  182. {
  183. int iTime = helperStream.ReadLEInt();
  184. lastAccessTime_ = (new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
  185. new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
  186. }
  187. if ((flags_ & Flags.CreateTime) != 0)
  188. {
  189. int iTime = helperStream.ReadLEInt();
  190. createTime_ = (new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
  191. new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
  192. }
  193. }
  194. }
  195. /// <summary>
  196. /// Get the binary data representing this instance.
  197. /// </summary>
  198. /// <returns>The raw binary data representing this instance.</returns>
  199. public byte[] GetData()
  200. {
  201. using (MemoryStream ms = new MemoryStream())
  202. using (ZipHelperStream helperStream = new ZipHelperStream(ms))
  203. {
  204. helperStream.IsStreamOwner = false;
  205. helperStream.WriteByte((byte)flags_); // Flags
  206. if ( (flags_ & Flags.ModificationTime) != 0) {
  207. TimeSpan span = modificationTime_.ToUniversalTime() - new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
  208. int seconds = (int)span.TotalSeconds;
  209. helperStream.WriteLEInt(seconds);
  210. }
  211. if ( (flags_ & Flags.AccessTime) != 0) {
  212. TimeSpan span = lastAccessTime_.ToUniversalTime() - new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
  213. int seconds = (int)span.TotalSeconds;
  214. helperStream.WriteLEInt(seconds);
  215. }
  216. if ( (flags_ & Flags.CreateTime) != 0) {
  217. TimeSpan span = createTime_.ToUniversalTime() - new System.DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
  218. int seconds = (int)span.TotalSeconds;
  219. helperStream.WriteLEInt(seconds);
  220. }
  221. return ms.ToArray();
  222. }
  223. }
  224. #endregion
  225. /// <summary>
  226. /// Test a <see cref="DateTime"> value to see if is valid and can be represented here.</see>
  227. /// </summary>
  228. /// <param name="value">The <see cref="DateTime">value</see> to test.</param>
  229. /// <returns>Returns true if the value is valid and can be represented; false if not.</returns>
  230. /// <remarks>The standard Unix time is a signed integer data type, directly encoding the Unix time number,
  231. /// which is the number of seconds since 1970-01-01.
  232. /// Being 32 bits means the values here cover a range of about 136 years.
  233. /// The minimum representable time is 1901-12-13 20:45:52,
  234. /// and the maximum representable time is 2038-01-19 03:14:07.
  235. /// </remarks>
  236. public static bool IsValidValue(DateTime value)
  237. {
  238. return (( value >= new DateTime(1901, 12, 13, 20, 45, 52)) ||
  239. ( value <= new DateTime(2038, 1, 19, 03, 14, 07) ));
  240. }
  241. /// <summary>
  242. /// Get /set the Modification Time
  243. /// </summary>
  244. /// <exception cref="ArgumentOutOfRangeException"></exception>
  245. /// <seealso cref="IsValidValue"></seealso>
  246. public DateTime ModificationTime
  247. {
  248. get { return modificationTime_; }
  249. set
  250. {
  251. if ( !IsValidValue(value) ) {
  252. throw new ArgumentOutOfRangeException("value");
  253. }
  254. flags_ |= Flags.ModificationTime;
  255. modificationTime_=value;
  256. }
  257. }
  258. /// <summary>
  259. /// Get / set the Access Time
  260. /// </summary>
  261. /// <exception cref="ArgumentOutOfRangeException"></exception>
  262. /// <seealso cref="IsValidValue"></seealso>
  263. public DateTime AccessTime
  264. {
  265. get { return lastAccessTime_; }
  266. set {
  267. if ( !IsValidValue(value) ) {
  268. throw new ArgumentOutOfRangeException("value");
  269. }
  270. flags_ |= Flags.AccessTime;
  271. lastAccessTime_=value;
  272. }
  273. }
  274. /// <summary>
  275. /// Get / Set the Create Time
  276. /// </summary>
  277. /// <exception cref="ArgumentOutOfRangeException"></exception>
  278. /// <seealso cref="IsValidValue"></seealso>
  279. public DateTime CreateTime
  280. {
  281. get { return createTime_; }
  282. set {
  283. if ( !IsValidValue(value) ) {
  284. throw new ArgumentOutOfRangeException("value");
  285. }
  286. flags_ |= Flags.CreateTime;
  287. createTime_=value;
  288. }
  289. }
  290. /// <summary>
  291. /// Get/set the <see cref="Flags">values</see> to include.
  292. /// </summary>
  293. Flags Include
  294. {
  295. get { return flags_; }
  296. set { flags_ = value; }
  297. }
  298. #region Instance Fields
  299. Flags flags_;
  300. DateTime modificationTime_ = new DateTime(1970,1,1);
  301. DateTime lastAccessTime_ = new DateTime(1970, 1, 1);
  302. DateTime createTime_ = new DateTime(1970, 1, 1);
  303. #endregion
  304. }
  305. /// <summary>
  306. /// Class handling NT date time values.
  307. /// </summary>
  308. public class NTTaggedData : ITaggedData
  309. {
  310. /// <summary>
  311. /// Get the ID for this tagged data value.
  312. /// </summary>
  313. public short TagID
  314. {
  315. get { return 10; }
  316. }
  317. /// <summary>
  318. /// Set the data from the raw values provided.
  319. /// </summary>
  320. /// <param name="data">The raw data to extract values from.</param>
  321. /// <param name="index">The index to start extracting values from.</param>
  322. /// <param name="count">The number of bytes available.</param>
  323. public void SetData(byte[] data, int index, int count)
  324. {
  325. using (MemoryStream ms = new MemoryStream(data, index, count, false))
  326. using (ZipHelperStream helperStream = new ZipHelperStream(ms))
  327. {
  328. helperStream.ReadLEInt(); // Reserved
  329. while (helperStream.Position < helperStream.Length)
  330. {
  331. int ntfsTag = helperStream.ReadLEShort();
  332. int ntfsLength = helperStream.ReadLEShort();
  333. if (ntfsTag == 1)
  334. {
  335. if (ntfsLength >= 24)
  336. {
  337. long lastModificationTicks = helperStream.ReadLELong();
  338. lastModificationTime_ = DateTime.FromFileTime(lastModificationTicks);
  339. long lastAccessTicks = helperStream.ReadLELong();
  340. lastAccessTime_ = DateTime.FromFileTime(lastAccessTicks);
  341. long createTimeTicks = helperStream.ReadLELong();
  342. createTime_ = DateTime.FromFileTime(createTimeTicks);
  343. }
  344. break;
  345. }
  346. else
  347. {
  348. // An unknown NTFS tag so simply skip it.
  349. helperStream.Seek(ntfsLength, SeekOrigin.Current);
  350. }
  351. }
  352. }
  353. }
  354. /// <summary>
  355. /// Get the binary data representing this instance.
  356. /// </summary>
  357. /// <returns>The raw binary data representing this instance.</returns>
  358. public byte[] GetData()
  359. {
  360. using (MemoryStream ms = new MemoryStream())
  361. using (ZipHelperStream helperStream = new ZipHelperStream(ms))
  362. {
  363. helperStream.IsStreamOwner = false;
  364. helperStream.WriteLEInt(0); // Reserved
  365. helperStream.WriteLEShort(1); // Tag
  366. helperStream.WriteLEShort(24); // Length = 3 x 8.
  367. helperStream.WriteLELong(lastModificationTime_.ToFileTime());
  368. helperStream.WriteLELong(lastAccessTime_.ToFileTime());
  369. helperStream.WriteLELong(createTime_.ToFileTime());
  370. return ms.ToArray();
  371. }
  372. }
  373. /// <summary>
  374. /// Test a <see cref="DateTime"> valuie to see if is valid and can be represented here.</see>
  375. /// </summary>
  376. /// <param name="value">The <see cref="DateTime">value</see> to test.</param>
  377. /// <returns>Returns true if the value is valid and can be represented; false if not.</returns>
  378. /// <remarks>
  379. /// NTFS filetimes are 64-bit unsigned integers, stored in Intel
  380. /// (least significant byte first) byte order. They determine the
  381. /// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch",
  382. /// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit
  383. /// </remarks>
  384. public static bool IsValidValue(DateTime value)
  385. {
  386. bool result = true;
  387. try
  388. {
  389. value.ToFileTimeUtc();
  390. }
  391. catch
  392. {
  393. result = false;
  394. }
  395. return result;
  396. }
  397. /// <summary>
  398. /// Get/set the <see cref="DateTime">last modification time</see>.
  399. /// </summary>
  400. public DateTime LastModificationTime
  401. {
  402. get { return lastModificationTime_; }
  403. set {
  404. if (! IsValidValue(value))
  405. {
  406. throw new ArgumentOutOfRangeException("value");
  407. }
  408. lastModificationTime_ = value;
  409. }
  410. }
  411. /// <summary>
  412. /// Get /set the <see cref="DateTime">create time</see>
  413. /// </summary>
  414. public DateTime CreateTime
  415. {
  416. get { return createTime_; }
  417. set {
  418. if ( !IsValidValue(value)) {
  419. throw new ArgumentOutOfRangeException("value");
  420. }
  421. createTime_ = value;
  422. }
  423. }
  424. /// <summary>
  425. /// Get /set the <see cref="DateTime">last access time</see>.
  426. /// </summary>
  427. public DateTime LastAccessTime
  428. {
  429. get { return lastAccessTime_; }
  430. set {
  431. if (!IsValidValue(value)) {
  432. throw new ArgumentOutOfRangeException("value");
  433. }
  434. lastAccessTime_ = value;
  435. }
  436. }
  437. #region Instance Fields
  438. DateTime lastAccessTime_ = DateTime.FromFileTime(0);
  439. DateTime lastModificationTime_ = DateTime.FromFileTime(0);
  440. DateTime createTime_ = DateTime.FromFileTime(0);
  441. #endregion
  442. }
  443. /// <summary>
  444. /// A factory that creates <see cref="ITaggedData">tagged data</see> instances.
  445. /// </summary>
  446. interface ITaggedDataFactory
  447. {
  448. /// <summary>
  449. /// Get data for a specific tag value.
  450. /// </summary>
  451. /// <param name="tag">The tag ID to find.</param>
  452. /// <param name="data">The data to search.</param>
  453. /// <param name="offset">The offset to begin extracting data from.</param>
  454. /// <param name="count">The number of bytes to extract.</param>
  455. /// <returns>The located <see cref="ITaggedData">value found</see>, or null if not found.</returns>
  456. ITaggedData Create(short tag, byte[] data, int offset, int count);
  457. }
  458. ///
  459. /// <summary>
  460. /// A class to handle the extra data field for Zip entries
  461. /// </summary>
  462. /// <remarks>
  463. /// Extra data contains 0 or more values each prefixed by a header tag and length.
  464. /// They contain zero or more bytes of actual data.
  465. /// The data is held internally using a copy on write strategy. This is more efficient but
  466. /// means that for extra data created by passing in data can have the values modified by the caller
  467. /// in some circumstances.
  468. /// </remarks>
  469. sealed public class ZipExtraData : IDisposable
  470. {
  471. #region Constructors
  472. /// <summary>
  473. /// Initialise a default instance.
  474. /// </summary>
  475. public ZipExtraData()
  476. {
  477. Clear();
  478. }
  479. /// <summary>
  480. /// Initialise with known extra data.
  481. /// </summary>
  482. /// <param name="data">The extra data.</param>
  483. public ZipExtraData(byte[] data)
  484. {
  485. if ( data == null )
  486. {
  487. data_ = new byte[0];
  488. }
  489. else
  490. {
  491. data_ = data;
  492. }
  493. }
  494. #endregion
  495. /// <summary>
  496. /// Get the raw extra data value
  497. /// </summary>
  498. /// <returns>Returns the raw byte[] extra data this instance represents.</returns>
  499. public byte[] GetEntryData()
  500. {
  501. if ( Length > ushort.MaxValue ) {
  502. throw new ZipException("Data exceeds maximum length");
  503. }
  504. return (byte[])data_.Clone();
  505. }
  506. /// <summary>
  507. /// Clear the stored data.
  508. /// </summary>
  509. public void Clear()
  510. {
  511. if ( (data_ == null) || (data_.Length != 0) ) {
  512. data_ = new byte[0];
  513. }
  514. }
  515. /// <summary>
  516. /// Gets the current extra data length.
  517. /// </summary>
  518. public int Length
  519. {
  520. get { return data_.Length; }
  521. }
  522. /// <summary>
  523. /// Get a read-only <see cref="Stream"/> for the associated tag.
  524. /// </summary>
  525. /// <param name="tag">The tag to locate data for.</param>
  526. /// <returns>Returns a <see cref="Stream"/> containing tag data or null if no tag was found.</returns>
  527. public Stream GetStreamForTag(int tag)
  528. {
  529. Stream result = null;
  530. if ( Find(tag) ) {
  531. result = new MemoryStream(data_, index_, readValueLength_, false);
  532. }
  533. return result;
  534. }
  535. /// <summary>
  536. /// Get the <see cref="ITaggedData">tagged data</see> for a tag.
  537. /// </summary>
  538. /// <param name="tag">The tag to search for.</param>
  539. /// <returns>Returns a <see cref="ITaggedData">tagged value</see> or null if none found.</returns>
  540. private ITaggedData GetData(short tag)
  541. {
  542. ITaggedData result = null;
  543. if (Find(tag))
  544. {
  545. result = Create(tag, data_, readValueStart_, readValueLength_);
  546. }
  547. return result;
  548. }
  549. static ITaggedData Create(short tag, byte[] data, int offset, int count)
  550. {
  551. ITaggedData result = null;
  552. switch ( tag )
  553. {
  554. case 0x000A:
  555. result = new NTTaggedData();
  556. break;
  557. case 0x5455:
  558. result = new ExtendedUnixData();
  559. break;
  560. default:
  561. result = new RawTaggedData(tag);
  562. break;
  563. }
  564. result.SetData(data, offset, count);
  565. return result;
  566. }
  567. /// <summary>
  568. /// Get the length of the last value found by <see cref="Find"/>
  569. /// </summary>
  570. /// <remarks>This is only valid if <see cref="Find"/> has previously returned true.</remarks>
  571. public int ValueLength
  572. {
  573. get { return readValueLength_; }
  574. }
  575. /// <summary>
  576. /// Get the index for the current read value.
  577. /// </summary>
  578. /// <remarks>This is only valid if <see cref="Find"/> has previously returned true.
  579. /// Initially the result will be the index of the first byte of actual data. The value is updated after calls to
  580. /// <see cref="ReadInt"/>, <see cref="ReadShort"/> and <see cref="ReadLong"/>. </remarks>
  581. public int CurrentReadIndex
  582. {
  583. get { return index_; }
  584. }
  585. /// <summary>
  586. /// Get the number of bytes remaining to be read for the current value;
  587. /// </summary>
  588. public int UnreadCount
  589. {
  590. get
  591. {
  592. if ((readValueStart_ > data_.Length) ||
  593. (readValueStart_ < 4) ) {
  594. throw new ZipException("Find must be called before calling a Read method");
  595. }
  596. return readValueStart_ + readValueLength_ - index_;
  597. }
  598. }
  599. /// <summary>
  600. /// Find an extra data value
  601. /// </summary>
  602. /// <param name="headerID">The identifier for the value to find.</param>
  603. /// <returns>Returns true if the value was found; false otherwise.</returns>
  604. public bool Find(int headerID)
  605. {
  606. readValueStart_ = data_.Length;
  607. readValueLength_ = 0;
  608. index_ = 0;
  609. int localLength = readValueStart_;
  610. int localTag = headerID - 1;
  611. // Trailing bytes that cant make up an entry (as there arent enough
  612. // bytes for a tag and length) are ignored!
  613. while ( (localTag != headerID) && (index_ < data_.Length - 3) ) {
  614. localTag = ReadShortInternal();
  615. localLength = ReadShortInternal();
  616. if ( localTag != headerID ) {
  617. index_ += localLength;
  618. }
  619. }
  620. bool result = (localTag == headerID) && ((index_ + localLength) <= data_.Length);
  621. if ( result ) {
  622. readValueStart_ = index_;
  623. readValueLength_ = localLength;
  624. }
  625. return result;
  626. }
  627. /// <summary>
  628. /// Add a new entry to extra data.
  629. /// </summary>
  630. /// <param name="taggedData">The <see cref="ITaggedData"/> value to add.</param>
  631. public void AddEntry(ITaggedData taggedData)
  632. {
  633. if (taggedData == null)
  634. {
  635. throw new ArgumentNullException("taggedData");
  636. }
  637. AddEntry(taggedData.TagID, taggedData.GetData());
  638. }
  639. /// <summary>
  640. /// Add a new entry to extra data
  641. /// </summary>
  642. /// <param name="headerID">The ID for this entry.</param>
  643. /// <param name="fieldData">The data to add.</param>
  644. /// <remarks>If the ID already exists its contents are replaced.</remarks>
  645. public void AddEntry(int headerID, byte[] fieldData)
  646. {
  647. if ( (headerID > ushort.MaxValue) || (headerID < 0)) {
  648. throw new ArgumentOutOfRangeException("headerID");
  649. }
  650. int addLength = (fieldData == null) ? 0 : fieldData.Length;
  651. if ( addLength > ushort.MaxValue ) {
  652. #if NETCF_1_0
  653. throw new ArgumentOutOfRangeException("fieldData");
  654. #else
  655. throw new ArgumentOutOfRangeException("fieldData", "exceeds maximum length");
  656. #endif
  657. }
  658. // Test for new length before adjusting data.
  659. int newLength = data_.Length + addLength + 4;
  660. if ( Find(headerID) )
  661. {
  662. newLength -= (ValueLength + 4);
  663. }
  664. if ( newLength > ushort.MaxValue ) {
  665. throw new ZipException("Data exceeds maximum length");
  666. }
  667. Delete(headerID);
  668. byte[] newData = new byte[newLength];
  669. data_.CopyTo(newData, 0);
  670. int index = data_.Length;
  671. data_ = newData;
  672. SetShort(ref index, headerID);
  673. SetShort(ref index, addLength);
  674. if ( fieldData != null ) {
  675. fieldData.CopyTo(newData, index);
  676. }
  677. }
  678. /// <summary>
  679. /// Start adding a new entry.
  680. /// </summary>
  681. /// <remarks>Add data using <see cref="AddData(byte[])"/>, <see cref="AddLeShort"/>, <see cref="AddLeInt"/>, or <see cref="AddLeLong"/>.
  682. /// The new entry is completed and actually added by calling <see cref="AddNewEntry"/></remarks>
  683. /// <seealso cref="AddEntry(ITaggedData)"/>
  684. public void StartNewEntry()
  685. {
  686. newEntry_ = new MemoryStream();
  687. }
  688. /// <summary>
  689. /// Add entry data added since <see cref="StartNewEntry"/> using the ID passed.
  690. /// </summary>
  691. /// <param name="headerID">The identifier to use for this entry.</param>
  692. public void AddNewEntry(int headerID)
  693. {
  694. byte[] newData = newEntry_.ToArray();
  695. newEntry_ = null;
  696. AddEntry(headerID, newData);
  697. }
  698. /// <summary>
  699. /// Add a byte of data to the pending new entry.
  700. /// </summary>
  701. /// <param name="data">The byte to add.</param>
  702. /// <seealso cref="StartNewEntry"/>
  703. public void AddData(byte data)
  704. {
  705. newEntry_.WriteByte(data);
  706. }
  707. /// <summary>
  708. /// Add data to a pending new entry.
  709. /// </summary>
  710. /// <param name="data">The data to add.</param>
  711. /// <seealso cref="StartNewEntry"/>
  712. public void AddData(byte[] data)
  713. {
  714. if ( data == null ) {
  715. throw new ArgumentNullException("data");
  716. }
  717. newEntry_.Write(data, 0, data.Length);
  718. }
  719. /// <summary>
  720. /// Add a short value in little endian order to the pending new entry.
  721. /// </summary>
  722. /// <param name="toAdd">The data to add.</param>
  723. /// <seealso cref="StartNewEntry"/>
  724. public void AddLeShort(int toAdd)
  725. {
  726. unchecked {
  727. newEntry_.WriteByte(( byte )toAdd);
  728. newEntry_.WriteByte(( byte )(toAdd >> 8));
  729. }
  730. }
  731. /// <summary>
  732. /// Add an integer value in little endian order to the pending new entry.
  733. /// </summary>
  734. /// <param name="toAdd">The data to add.</param>
  735. /// <seealso cref="StartNewEntry"/>
  736. public void AddLeInt(int toAdd)
  737. {
  738. unchecked {
  739. AddLeShort(( short )toAdd);
  740. AddLeShort(( short )(toAdd >> 16));
  741. }
  742. }
  743. /// <summary>
  744. /// Add a long value in little endian order to the pending new entry.
  745. /// </summary>
  746. /// <param name="toAdd">The data to add.</param>
  747. /// <seealso cref="StartNewEntry"/>
  748. public void AddLeLong(long toAdd)
  749. {
  750. unchecked {
  751. AddLeInt(( int )(toAdd & 0xffffffff));
  752. AddLeInt(( int )(toAdd >> 32));
  753. }
  754. }
  755. /// <summary>
  756. /// Delete an extra data field.
  757. /// </summary>
  758. /// <param name="headerID">The identifier of the field to delete.</param>
  759. /// <returns>Returns true if the field was found and deleted.</returns>
  760. public bool Delete(int headerID)
  761. {
  762. bool result = false;
  763. if ( Find(headerID) ) {
  764. result = true;
  765. int trueStart = readValueStart_ - 4;
  766. byte[] newData = new byte[data_.Length - (ValueLength + 4)];
  767. Array.Copy(data_, 0, newData, 0, trueStart);
  768. int trueEnd = trueStart + ValueLength + 4;
  769. Array.Copy(data_, trueEnd, newData, trueStart, data_.Length - trueEnd);
  770. data_ = newData;
  771. }
  772. return result;
  773. }
  774. #region Reading Support
  775. /// <summary>
  776. /// Read a long in little endian form from the last <see cref="Find">found</see> data value
  777. /// </summary>
  778. /// <returns>Returns the long value read.</returns>
  779. public long ReadLong()
  780. {
  781. ReadCheck(8);
  782. return (ReadInt() & 0xffffffff) | ((( long )ReadInt()) << 32);
  783. }
  784. /// <summary>
  785. /// Read an integer in little endian form from the last <see cref="Find">found</see> data value.
  786. /// </summary>
  787. /// <returns>Returns the integer read.</returns>
  788. public int ReadInt()
  789. {
  790. ReadCheck(4);
  791. int result = data_[index_] + (data_[index_ + 1] << 8) +
  792. (data_[index_ + 2] << 16) + (data_[index_ + 3] << 24);
  793. index_ += 4;
  794. return result;
  795. }
  796. /// <summary>
  797. /// Read a short value in little endian form from the last <see cref="Find">found</see> data value.
  798. /// </summary>
  799. /// <returns>Returns the short value read.</returns>
  800. public int ReadShort()
  801. {
  802. ReadCheck(2);
  803. int result = data_[index_] + (data_[index_ + 1] << 8);
  804. index_ += 2;
  805. return result;
  806. }
  807. /// <summary>
  808. /// Read a byte from an extra data
  809. /// </summary>
  810. /// <returns>The byte value read or -1 if the end of data has been reached.</returns>
  811. public int ReadByte()
  812. {
  813. int result = -1;
  814. if ( (index_ < data_.Length) && (readValueStart_ + readValueLength_ > index_) ) {
  815. result = data_[index_];
  816. index_ += 1;
  817. }
  818. return result;
  819. }
  820. /// <summary>
  821. /// Skip data during reading.
  822. /// </summary>
  823. /// <param name="amount">The number of bytes to skip.</param>
  824. public void Skip(int amount)
  825. {
  826. ReadCheck(amount);
  827. index_ += amount;
  828. }
  829. void ReadCheck(int length)
  830. {
  831. if ((readValueStart_ > data_.Length) ||
  832. (readValueStart_ < 4) ) {
  833. throw new ZipException("Find must be called before calling a Read method");
  834. }
  835. if (index_ > readValueStart_ + readValueLength_ - length ) {
  836. throw new ZipException("End of extra data");
  837. }
  838. }
  839. /// <summary>
  840. /// Internal form of <see cref="ReadShort"/> that reads data at any location.
  841. /// </summary>
  842. /// <returns>Returns the short value read.</returns>
  843. int ReadShortInternal()
  844. {
  845. if ( index_ > data_.Length - 2) {
  846. throw new ZipException("End of extra data");
  847. }
  848. int result = data_[index_] + (data_[index_ + 1] << 8);
  849. index_ += 2;
  850. return result;
  851. }
  852. void SetShort(ref int index, int source)
  853. {
  854. data_[index] = (byte)source;
  855. data_[index + 1] = (byte)(source >> 8);
  856. index += 2;
  857. }
  858. #endregion
  859. #region IDisposable Members
  860. /// <summary>
  861. /// Dispose of this instance.
  862. /// </summary>
  863. public void Dispose()
  864. {
  865. if ( newEntry_ != null ) {
  866. newEntry_.Close();
  867. }
  868. }
  869. #endregion
  870. #region Instance Fields
  871. int index_;
  872. int readValueStart_;
  873. int readValueLength_;
  874. MemoryStream newEntry_;
  875. byte[] data_;
  876. #endregion
  877. }
  878. }