File size: 11,073 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ReSharper disable UnusedMember.Global
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
namespace System.Management.Automation
{
internal static class ArrayOps
{
internal static object AddObjectArray(object[] lhs, object rhs)
{
int newIdx = lhs.Length;
Array.Resize(ref lhs, newIdx + 1);
lhs[newIdx] = rhs;
return lhs;
}
internal static object[] SlicingIndex(object target, object[] indexes, Func<object, object, object> indexer)
{
var result = new object[indexes.Length];
int j = 0;
foreach (object t in indexes)
{
var value = indexer(target, t);
if (value != AutomationNull.Value)
{
result[j++] = value;
}
}
if (j != indexes.Length)
{
var shortResult = new object[j];
Array.Copy(result, shortResult, j);
return shortResult;
}
return result;
}
/// <summary>
/// Efficiently multiplies collection by integer.
/// </summary>
/// <param name="array">Collection to multiply.</param>
/// <param name="times">Number of times the collection is to be multiplied/copied.</param>
/// <returns>Collection multiplied by integer.</returns>
internal static T[] Multiply<T>(T[] array, uint times)
{
Diagnostics.Assert(array != null, "Caller should verify the arguments for array multiplication");
if (times == 1)
{
return array;
}
if (times == 0 || array.Length == 0)
{
#pragma warning disable CA1825 // Avoid zero-length array allocations
// Don't use Array.Empty<T>(); always return a new instance.
return new T[0];
#pragma warning restore CA1825 // Avoid zero-length array allocations
}
var context = LocalPipeline.GetExecutionContextFromTLS();
if (context != null &&
context.LanguageMode == PSLanguageMode.RestrictedLanguage && (array.Length * times) > 1024)
{
throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException),
null, "ArrayMultiplyToolongInDataSection", ParserStrings.ArrayMultiplyToolongInDataSection, 1024);
}
var uncheckedLength = array.Length * times;
int elements = -1;
try
{
elements = checked((int)uncheckedLength);
}
catch (OverflowException)
{
LanguagePrimitives.ThrowInvalidCastException(uncheckedLength, typeof(int));
}
// Make the minimum number of calls to Array.Copy by doubling the array up to
// the most significant bit in times, then do one final Array.Copy to get the
// remaining copies.
T[] result = new T[elements];
int resultLength = array.Length;
Array.Copy(array, 0, result, 0, resultLength);
times >>= 1;
while (times != 0)
{
Array.Copy(result, 0, result, resultLength, resultLength);
resultLength *= 2;
times >>= 1;
}
if (result.Length != resultLength)
{
Array.Copy(result, 0, result, resultLength, (result.Length - resultLength));
}
return result;
}
internal static object GetMDArrayValue(Array array, int[] indexes, bool slicing)
{
if (array.Rank != indexes.Length)
{
ReportIndexingError(array, indexes, null);
}
for (int i = 0; i < indexes.Length; ++i)
{
int ub = array.GetUpperBound(i);
int lb = array.GetLowerBound(i);
if (indexes[i] < lb)
{
indexes[i] = indexes[i] + ub + 1;
}
if (indexes[i] < lb || indexes[i] > ub)
{
// In strict mode, don't return, fall through and let Array.GetValue raise an exception.
var context = LocalPipeline.GetExecutionContextFromTLS();
if (context != null && !context.IsStrictVersion(3))
{
// If we're slicing, return AutomationNull.Value to signal no result)
return slicing ? AutomationNull.Value : null;
}
}
}
// All indexes have been validated, so this won't raise an exception.
return array.GetValue(indexes);
}
internal static object GetMDArrayValueOrSlice(Array array, object indexes)
{
Exception whyFailed = null;
int[] indexArray = null;
try
{
indexArray = (int[])LanguagePrimitives.ConvertTo(indexes, typeof(int[]), NumberFormatInfo.InvariantInfo);
}
catch (InvalidCastException ice)
{
// Ignore an exception here as we may actually be looking at an array of arrays
// which could still be ok. Save the exception as we may use it later...
whyFailed = ice;
}
if (indexArray != null)
{
if (indexArray.Length != array.Rank)
{
// rank failed to match so error...
ReportIndexingError(array, indexes, null);
}
return GetMDArrayValue(array, indexArray, false);
}
var indexList = new List<int[]>();
var ie = LanguagePrimitives.GetEnumerator(indexes);
while (EnumerableOps.MoveNext(null, ie))
{
var currentIndex = EnumerableOps.Current(ie);
try
{
indexArray = LanguagePrimitives.ConvertTo<int[]>(currentIndex);
}
catch (InvalidCastException)
{
indexArray = null;
}
if (indexArray == null || indexArray.Length != array.Rank)
{
if (whyFailed != null)
{
// If the first fails, report the original exception and all indices
ReportIndexingError(array, indexes, whyFailed);
Diagnostics.Assert(false, "ReportIndexingError must throw");
}
// If the second or subsequent index fails, report the failure for just that index
ReportIndexingError(array, currentIndex, null);
Diagnostics.Assert(false, "ReportIndexingError must throw");
}
// Only use whyFailed the first time through, otherwise
whyFailed = null;
indexList.Add(indexArray);
}
// Optimistically assume all indices are valid so the result array is the same size.
// If that turns out to be wrong, we'll just copy the elements produced.
var result = new object[indexList.Count];
int j = 0;
foreach (var i in indexList)
{
var value = GetMDArrayValue(array, i, true);
if (value != AutomationNull.Value)
{
result[j++] = value;
}
}
if (j != indexList.Count)
{
var shortResult = new object[j];
Array.Copy(result, shortResult, j);
return shortResult;
}
return result;
}
private static void ReportIndexingError(Array array, object index, Exception reason)
{
// Convert this index into something printable (we hope)...
string msgString = IndexStringMessage(index);
if (reason == null)
{
throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), null,
"NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, array.Rank, msgString);
}
throw InterpreterError.NewInterpreterExceptionWithInnerException(index, typeof(RuntimeException), null,
"NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, reason, array.Rank, msgString);
}
internal static string IndexStringMessage(object index)
{
// Convert this index into something printable (we hope)...
string msgString = PSObject.ToString(null, index, ",", null, null, true, true);
if (msgString.Length > 20)
msgString = string.Concat(msgString.AsSpan(0, 20), " ...");
return msgString;
}
internal static object SetMDArrayValue(Array array, int[] indexes, object value)
{
if (array.Rank != indexes.Length)
{
ReportIndexingError(array, indexes, null);
}
for (int i = 0; i < indexes.Length; ++i)
{
int ub = array.GetUpperBound(i);
int lb = array.GetLowerBound(i);
if (indexes[i] < lb)
{
indexes[i] = indexes[i] + ub + 1;
}
}
array.SetValue(value, indexes);
return value;
}
internal static object GetNonIndexable(object target, object[] indices)
{
// We want to allow:
// $x[0]
// and
// $x[-1]
// to be the same as
// $x
// But disallow anything else:
// if in the strict mode, throw exception
// otherwise, return AutomationNull.Value to signal no result
if (indices.Length == 1)
{
var index = indices[0];
if (index != null && (LanguagePrimitives.Equals(0, index) || LanguagePrimitives.Equals(-1, index)))
{
return target;
}
}
var context = LocalPipeline.GetExecutionContextFromTLS();
if (context == null || !context.IsStrictVersion(2))
{
return AutomationNull.Value;
}
throw InterpreterError.NewInterpreterException(target, typeof(RuntimeException), null, "CannotIndex",
ParserStrings.CannotIndex, target.GetType());
}
}
}
|