| 1 | // Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. |
| 2 | |
| 3 | namespace WixToolset.Dtf.Compression.Cab |
| 4 | { |
| 5 | using System; |
| 6 | using System.Collections.Generic; |
| 7 | |
| 8 | /// <summary> |
| 9 | /// Generic class for managing allocations of integer handles |
| 10 | /// for objects of a certain type. |
| 11 | /// </summary> |
| 12 | /// <typeparam name="T">The type of objects the handles refer to.</typeparam> |
| 13 | internal sealed class HandleManager<T> where T : class |
| 14 | { |
| 15 | /// <summary> |
| 16 | /// Auto-resizing list of objects for which handles have been allocated. |
| 17 | /// Each handle is just an index into this list. When a handle is freed, |
| 18 | /// the list item at that index is set to null. |
| 19 | /// </summary> |
| 20 | private List<T> handles; |
| 21 | |
| 22 | /// <summary> |
| 23 | /// Creates a new HandleManager instance. |
| 24 | /// </summary> |
| 25 | public HandleManager() |
| 26 | { |
| 27 | this.handles = new List<T>(); |
| 28 | } |
| 29 | |
| 30 | /// <summary> |
| 31 | /// Gets the object of a handle, or null if the handle is invalid. |
| 32 | /// </summary> |
| 33 | /// <param name="handle">The integer handle previously allocated |
| 34 | /// for the desired object.</param> |
| 35 | /// <returns>The object for which the handle was allocated.</returns> |
| 36 | public T this[int handle] |
| 37 | { |
| 38 | get |
| 39 | { |
| 40 | if (handle > 0 && handle <= this.handles.Count) |
| 41 | { |
| 42 | return this.handles[handle - 1]; |
| 43 | } |
| 44 | else |
| 45 | { |
| 46 | return null; |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | /// <summary> |
| 52 | /// Allocates a new handle for an object. |
| 53 | /// </summary> |
| 54 | /// <param name="obj">Object that the handle will refer to.</param> |
| 55 | /// <returns>New handle that can be later used to retrieve the object.</returns> |
| 56 | public int AllocHandle(T obj) |
| 57 | { |
| 58 | this.handles.Add(obj); |
| 59 | int handle = this.handles.Count; |
| 60 | return handle; |
| 61 | } |
| 62 | |
| 63 | /// <summary> |
| 64 | /// Frees a handle that was previously allocated. Afterward the handle |
| 65 | /// will be invalid and the object it referred to can no longer retrieved. |
| 66 | /// </summary> |
| 67 | /// <param name="handle">Handle to be freed.</param> |
| 68 | public void FreeHandle(int handle) |
| 69 | { |
| 70 | if (handle > 0 && handle <= this.handles.Count) |
| 71 | { |
| 72 | this.handles[handle - 1] = null; |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | } |