Example #1
0
 public static string CodeRepresentation(Array a)
 {
     StringBuilder ret = new StringBuilder();
     ret.Append(a.GetType().FullName);
     ret.Append("(");
     switch (a.Rank) {
         case 1: {
                 for (int i = 0; i < a.Length; i++) {
                     if (i > 0) ret.Append(", ");
                     ret.Append(Ops.StringRepr(a.GetValue(i + a.GetLowerBound(0))));
                 }
             }
             break;
         case 2: {
                 int imax = a.GetLength(0);
                 int jmax = a.GetLength(1);
                 for (int i = 0; i < imax; i++) {
                     ret.Append("\n");
                     for (int j = 0; j < jmax; j++) {
                         if (j > 0) ret.Append(", ");
                         ret.Append(Ops.StringRepr(a.GetValue(i + a.GetLowerBound(0), j + a.GetLowerBound(1))));
                     }
                 }
             }
             break;
         default:
             ret.Append(" Multi-dimensional array ");
             break;
     }
     ret.Append(")");
     return ret.ToString();
 }
Example #2
0
        public static string ArrayToDescriptor(Array array, 
            TypeRegistry treg,
            Type type = null,
            string th = null)
        {
            if (type==null)
                 type = array.GetType();

              if (array.LongLength>MAX_ELM_COUNT)
                throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_ELM_ERROR.Args(array.LongLength, MAX_ELM_COUNT));

              if (type==typeof(object[]))//special case for object[], because this type is very often used in Glue and other places
               return "$1|"+array.Length.ToString();

              if (th==null)
                 th = treg.GetTypeHandle(type);

               var ar = array.Rank;
               if (ar>MAX_DIM_COUNT)
                throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_DIMS_ERROR.Args(ar, MAX_DIM_COUNT));

               var descr = new StringBuilder(th);
               descr.Append('|');//separator char

               for(int i=0; i<ar; i++)
               {
                  descr.Append(array.GetLowerBound(i));
                  descr.Append('~');
                  descr.Append(array.GetUpperBound(i));
                  if (i<ar-1)
                   descr.Append(',');
               }

              return descr.ToString();
        }
Example #3
0
        //-------------------------------------------------------------------//
        /// <summary>
        ///     Converts COM like 2dim array where one dimension is of length 1 to regular array.
        /// </summary>
        /// <param name="a">COM array</param>
        /// <returns>regular array</returns>
        public static object[] Com2DArray2Array(Array a)
        {
            if (a == null)
                return null;

            object[] converted = null;
            switch (a.Rank)
            {
                case 1:
                    converted = new object[a.GetLength(0)];
                    for (var i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++)
                    {
                        converted[i] = a.GetValue(i);
                    }
                    break;
                case 2:
                {
                    var d1 = a.GetLength(0);
                    var d2 = a.GetLength(1);
                    var len = (d1 > d2) ? d1 : d2;
                    converted = new object[len];
                    var dim = (d1 > d2) ? 0 : 1;
                    for (var i = a.GetLowerBound(dim); i <= a.GetUpperBound(dim); i++)
                    {
                        converted[i - a.GetLowerBound(dim)] = a.GetValue((d1 == 1 ? a.GetLowerBound(0) : i),
                            (d2 == 1 ? a.GetLowerBound(1) : i));
                    }
                }
                    break;
            }

            return converted;
        }
Example #4
0
           public static string ArrayToDescriptor(Array array, Type type, VarIntStr typeHandle)
           {
              if (array.LongLength>MAX_ELM_COUNT)
                throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_ELM_ERROR.Args(array.LongLength, MAX_ELM_COUNT)); 
              
              if (type==typeof(object[]))//special case for object[], because this type is very often used in Glue and other places
               return "$2|"+array.Length.ToString();


              var th = typeHandle.StringValue ?? 
                      ( typeHandle.IntValue < TypeRegistry.STR_HNDL_POOL.Length ? 
                                TypeRegistry.STR_HNDL_POOL[typeHandle.IntValue] : 
                                '$'+typeHandle.IntValue.ToString() 
                      );

               var ar = array.Rank;
               if (ar>MAX_DIM_COUNT)
                throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_DIMS_ERROR.Args(ar, MAX_DIM_COUNT));


               var descr = new StringBuilder();
               descr.Append( th );
               descr.Append('|');//separator char

               for(int i=0; i<ar; i++)
               {
                  descr.Append(array.GetLowerBound(i));
                  descr.Append('~');
                  descr.Append(array.GetUpperBound(i));
                  if (i<ar-1)
                   descr.Append(',');
               }
                      
              return descr.ToString();
           }
Example #5
0
        /// <summary>
        /// Modifies the specified array by applying the specified function to each element.
        /// </summary>
        /// <param name="a"></param>
        /// <param name="func">object delegate(object o){}</param>
        /// <returns></returns>
        public static void ForEach(Array a, ForEachFunction func)
        {
            long[] ix = new long[a.Rank];
            //Init index
            for (int i = 0; i < ix.Length; i++) ix[i] = a.GetLowerBound(i);

            //Loop through all items
            for (long i = 0; i < a.LongLength; i++)
            {
                a.SetValue(func(a.GetValue(ix)), ix);

                //Increment ix, the index
                for (int j = 0; j < ix.Length; j++)
                {
                    if (ix[j] < a.GetUpperBound(j))
                    {
                        ix[j]++;
                        break; //We're done incrementing.
                    }
                    else
                    {
                        //Ok, reset this one and increment the next.
                        ix[j] = a.GetLowerBound(j);
                        //If this is the last dimension, assert
                        //that we are at the last element
                        if (j == ix.Length - 1)
                        {
                            if (i < a.LongLength - 1) throw new Exception();
                        }
                        continue;
                    }
                }
            }
            return;
        }
 public void CopyTo(Array array, int index)
 {
     if (this.isDisposed)
     {
         throw new ObjectDisposedException(name);
     }
     if (array == null)
     {
         throw new ArgumentNullException("array");
     }
     if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0)))
     {
         throw new ArgumentOutOfRangeException("index");
     }
     int num = array.Length - index;
     int num2 = 0;
     ArrayList list = new ArrayList();
     ManagementObjectEnumerator enumerator = this.GetEnumerator();
     while (enumerator.MoveNext())
     {
         ManagementBaseObject current = enumerator.Current;
         list.Add(current);
         num2++;
         if (num2 > num)
         {
             throw new ArgumentException(null, "index");
         }
     }
     list.CopyTo(array, index);
 }
Example #7
0
 /// <summary>
 /// Asserts that each element in the first array is equal to its corresponding element in the second array.
 /// </summary>
 public static void AssertAllArrayElementsAreEqual(Array first, Array second, IComparer comparer = null)
 {
     Assert.True(first.Length == second.Length, "The two arrays are not even the same size.");
     for (int g = first.GetLowerBound(0); g < first.GetUpperBound(0); g++)
     {
         AssertArrayElementsAreEqual(first, second, g, comparer);
     }
 }
Example #8
0
 private static void ArrayRankInfo(String name, Array a) {
    Console.WriteLine("Number of dimensions in \"{0}\" array (of type {1}): ",
       name, a.GetType().ToString(), a.Rank);
    for (int r = 0; r < a.Rank; r++) {
       Console.WriteLine("Rank: {0}, LowerBound = {1},  UpperBound = {2}",
          r, a.GetLowerBound(r), a.GetUpperBound(r));
    }
    Console.WriteLine();
 }
 /// <summary>
 /// The following implementation is based on 
 /// stackoverflow.com/questions/9914230/iterate-through-an-array-of-arbitrary-dimension/9914326#9914326
 /// </summary>
 /// <param name="array"></param>
 /// <returns></returns>
 public int[] determineFirstIndicesArray(Array array)
 {
     int spaceDimension = array.Rank;
     int[] firstIndicesArray = new int[spaceDimension];
     for (int dimIdx = 0; dimIdx < spaceDimension; dimIdx++)
     {
         firstIndicesArray[dimIdx] = array.GetLowerBound(dimIdx);
     }
     return firstIndicesArray;
 }
Example #10
0
 /// <summary>
 /// Инициализирующий конструктор.
 /// </summary>
 /// <param name="arr">Массив, индексы которого перебираются.</param>
 public ArrayIndexEnumerator(Array arr)
 {
  rank = arr.Rank;
  az = new int[rank, 2];
  index = new int[rank];
  for(int a = 0; a < rank; a++)
  {
   az[a, 0] = arr.GetLowerBound(a);
   index[a] = az[a, 0];
   az[a, 1] = arr.GetUpperBound(a);
  }
  index[rank-1]--;
 }
 /// <summary>
 /// The following implementation is based on 
 /// stackoverflow.com/questions/9914230/iterate-through-an-array-of-arbitrary-dimension/9914326#9914326
 /// </summary>
 /// <param name="array"></param>
 /// <param name="previousIndicesArray"></param>
 /// <returns></returns>
 public int[] determineNextIndicesArray(Array array, int[] previousIndicesArray)
 {
     int spaceDimension = array.Rank;
     int[] nextIndicesArray = new int[spaceDimension];
     previousIndicesArray.CopyTo(nextIndicesArray, 0);
     for (int dimIdx = spaceDimension - 1; dimIdx >= 0; --dimIdx)
     {
         nextIndicesArray[dimIdx]++;
         if (nextIndicesArray[dimIdx] <= array.GetUpperBound(dimIdx))
             return nextIndicesArray;
         nextIndicesArray[dimIdx] = array.GetLowerBound(dimIdx);
     }
     return null;
 }
Example #12
0
        /// <summary>
        /// Convert a list into a human-readable string representation. The 
        /// representation used is: (0 to 2) {1, 2, 3}
        /// </summary>
        /// <param name="data">The array to process</param>
        /// <returns>A string containing the array data.</returns>
        public static string ASCIIfy(Array data)
        {
            if ( data == null )
                return "()";

            StringBuilder sb = new StringBuilder("(");

            sb.Append( String.Format( ResStrings.GetString( "ArrayLimits" ),
                                   data.GetLowerBound( 0 ),
                                   data.GetUpperBound( 0 ) ) );
            sb.Append( ASCIIfy((IList)data) );
            sb.Append( ")" );

            return sb.ToString();
        }
Example #13
0
        private static void SetupLoopData(Array arr, out int rank, out int[] dimensions, out int[] lowerBounds,
                                          out int[] upperBounds)
        {
            rank = arr.Rank;
            dimensions = new int[rank];
            lowerBounds = new int[rank];
            upperBounds = new int[rank];

            for (int dimension = 0; dimension < rank; dimension++)
            {
                lowerBounds[dimension] = arr.GetLowerBound(dimension);
                upperBounds[dimension] = arr.GetUpperBound(dimension);

                //setup start values
                dimensions[dimension] = lowerBounds[dimension];
            }
        }
 public void CopyTo(Array array, int index)
 {
     IWbemQualifierSetFreeThreaded typeQualifierSet;
     if (array == null)
     {
         throw new ArgumentNullException("array");
     }
     if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0)))
     {
         throw new ArgumentOutOfRangeException("index");
     }
     string[] pNames = null;
     try
     {
         typeQualifierSet = this.GetTypeQualifierSet();
     }
     catch (ManagementException exception)
     {
         if ((this.qualifierSetType != QualifierType.PropertyQualifier) || (exception.ErrorCode != ManagementStatus.SystemProperty))
         {
             throw;
         }
         return;
     }
     int errorCode = typeQualifierSet.GetNames_(0, out pNames);
     if (errorCode < 0)
     {
         if ((errorCode & 0xfffff000L) == 0x80041000L)
         {
             ManagementException.ThrowWithExtendedInfo((ManagementStatus) errorCode);
         }
         else
         {
             Marshal.ThrowExceptionForHR(errorCode);
         }
     }
     if ((index + pNames.Length) > array.Length)
     {
         throw new ArgumentException(null, "index");
     }
     foreach (string str in pNames)
     {
         array.SetValue(new QualifierData(this.parent, this.propertyOrMethodName, str, this.qualifierSetType), index++);
     }
 }
Example #15
0
        private static bool TryGetRankDiff(Array x, Array y, out RankDiff rankDiff)
        {
            if (x.Length != y.Length || x.Rank != y.Rank)
            {
                rankDiff = new RankDiff(x, y);
                return true;
            }

            for (var i = 0; i < x.Rank; i++)
            {
                if (x.GetLowerBound(i) != y.GetLowerBound(i) ||
                    x.GetUpperBound(i) != y.GetUpperBound(i))
                {
                    rankDiff = new RankDiff(x, y);
                    return true;
                }
            }

            rankDiff = null;
            return false;
        }
        internal void CopyTo(Array array, int arrayIndex)
        {
            if (array == null)
                throw new ArgumentNullException("array");

            // ICollection expects the destination array to be single-dimensional.
            if (array.Rank != 1)
                throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));

            int destLB = array.GetLowerBound(0);

            int srcLen = Count();
            int destLen = array.GetLength(0);

            if (arrayIndex < destLB)
                throw new ArgumentOutOfRangeException("arrayIndex");

            // Does the dimension in question have sufficient space to copy the expected number of entries?
            // We perform this check before valid index check to ensure the exception message is in sync with
            // the following snippet that uses regular framework code:
            //
            // ArrayList list = new ArrayList();
            // list.Add(1);
            // Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { -1 });
            // list.CopyTo(items, 0);

            if(srcLen > (destLen - (arrayIndex - destLB)))
                throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection"));

            if(arrayIndex - destLB > destLen)
                throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds"));

            // We need to verify the index as we;
            IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);

            for (uint i = 0; i < srcLen; i++)
            {
                array.SetValue(_this.GetAt(i), i + arrayIndex);
            }
        }
Example #17
0
 // Reverses all elements of the given array. Following a call to this
 // method, an element previously located at index i will now be
 // located at index length - i - 1, where length is the
 // length of the array.
 // 
 /// <include file='doc\Array.uex' path='docs/doc[@for="Array.Reverse"]/*' />
 public static void Reverse(Array array) {
     if (array==null)
         throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Array"));
     Reverse(array, array.GetLowerBound(0), array.Length);
 }
		static bool IsSingleDimensionalZeroBasedArray(Array a)
		{
			return a != null && a.Rank == 1 && a.GetLowerBound(0) == 0;
		}
Example #19
0
        /// <summary>
        /// Append all array data to the binary stream.
        /// </summary>
        private void WriteBinaryArrayData(NpgsqlNativeTypeInfo TypeInfo, Array nativeData, NativeToBackendTypeConverterOptions options, MemoryStream dst, int dimensionOffset, int[] dimensionOffsets)
        {
            int dimensionLength = nativeData.GetLength(dimensionOffset);
            int dimensionLBound = nativeData.GetLowerBound(dimensionOffset);

            if (dimensionOffset < nativeData.Rank - 1)
            {
                // Drill down recursively until we hit a single dimension array.
                for (int i = dimensionLBound ; i < dimensionLBound + dimensionLength ; i++)
                {
                    dimensionOffsets[dimensionOffset] = i;

                    WriteBinaryArrayData(TypeInfo, nativeData, options, dst, dimensionOffset + 1, dimensionOffsets);
                }
            }
            else
            {
                // Write the individual array elements to the output stream.
                for (int i = dimensionLBound ; i < dimensionLBound + dimensionLength ; i++)
                {
                    object elementNative;

                    dimensionOffsets[dimensionOffset] = i;
                    elementNative = nativeData.GetValue(dimensionOffsets);

                    if (elementNative == null || elementNative == DBNull.Value)
                    {
                        // Write length identifier -1 indicating NULL value.
                        dst.WriteInt32(-1);
                    }
                    else
                    {
                        byte[] elementBinary;

                        elementBinary = (byte[])_elementConverter.ConvertToBackend(elementNative, true, options);

                        // Write lenght identifier.
                        dst.WriteInt32(elementBinary.Length);
                        // Write element data.
                        dst.Write(elementBinary, 0, elementBinary.Length);
                    }
                }
            }
        }
        public override string FormatArrayTypeName(Type arrayType, Array arrayOpt, ObjectFormattingOptions options)
        {
            StringBuilder sb = new StringBuilder();

            // print the inner-most element type first:
            Type elementType = arrayType.GetElementType();
            while (elementType.IsArray)
            {
                elementType = elementType.GetElementType();
            }

            sb.Append(FormatTypeName(elementType, options));

            // print all components of a jagged array:
            Type type = arrayType;
            do
            {
                if (arrayOpt != null)
                {
                    sb.Append('[');

                    int rank = type.GetArrayRank();

                    bool anyNonzeroLowerBound = false;
                    for (int i = 0; i < rank; i++)
                    {
                        if (arrayOpt.GetLowerBound(i) > 0)
                        {
                            anyNonzeroLowerBound = true;
                            break;
                        }
                    }

                    for (int i = 0; i < rank; i++)
                    {
                        int lowerBound = arrayOpt.GetLowerBound(i);
                        int length = arrayOpt.GetLength(i);

                        if (i > 0)
                        {
                            sb.Append(", ");
                        }

                        if (anyNonzeroLowerBound)
                        {
                            AppendArrayBound(sb, lowerBound, options.UseHexadecimalNumbers);
                            sb.Append("..");
                            AppendArrayBound(sb, length + lowerBound, options.UseHexadecimalNumbers);
                        }
                        else
                        {
                            AppendArrayBound(sb, length, options.UseHexadecimalNumbers);
                        }
                    }

                    sb.Append(']');
                    arrayOpt = null;
                }
                else
                {
                    AppendArrayRank(sb, type);
                }

                type = type.GetElementType();
            }
            while (type.IsArray);

            return sb.ToString();
        }
Example #21
0
 private static void WriteArray(MemoryStream stream, Array a, int[] indices, Hashtable ht, ref int hv, Encoding encoding)
 {
     int n = indices.Length;
     int dimension = n - 1;
     int[] temp = new int[n + 1];
     indices.CopyTo(temp, 0);
     int len = a.GetLength(dimension);
     byte[] alen = Encoding.ASCII.GetBytes(len.ToString());
     int lb = a.GetLowerBound(dimension);
     int ub = a.GetUpperBound(dimension);
     stream.WriteByte(__a);
     stream.WriteByte(__Colon);
     stream.Write(alen, 0, alen.Length);
     stream.WriteByte(__Colon);
     stream.WriteByte(__LeftB);
     for (int i = lb; i <= ub; i++)
     {
         WriteInteger(stream, Encoding.ASCII.GetBytes(i.ToString()));
         if (a.Rank == n)
         {
             indices[n - 1] = i;
             Serialize(stream, a.GetValue(indices), ht, ref hv, encoding);
         }
         else
         {
             temp[n - 1] = i;
             WriteArray(stream, a, temp, ht, ref hv, encoding);
         }
     }
     stream.WriteByte(__RightB);
 }
Example #22
0
 private static void WriteArray(MemoryStream stream, Array a, Hashtable ht, ref int hv, Encoding encoding)
 {
     if (a.Rank == 1)
     {
         int len = a.GetLength(0);
         byte[] alen = Encoding.ASCII.GetBytes(len.ToString());
         int lb = a.GetLowerBound(0);
         int ub = a.GetUpperBound(0);
         stream.WriteByte(__a);
         stream.WriteByte(__Colon);
         stream.Write(alen, 0, alen.Length);
         stream.WriteByte(__Colon);
         stream.WriteByte(__LeftB);
         for (int i = lb; i <= ub; i++)
         {
             WriteInteger(stream, Encoding.ASCII.GetBytes(i.ToString()));
             Serialize(stream, a.GetValue(i), ht, ref hv, encoding);
         }
         stream.WriteByte(__RightB);
     }
     else
     {
         WriteArray(stream, a, new int[] { 0 }, ht, ref hv, encoding);
     }
 }
Example #23
0
        /// <summary>
        /// Formats an array type name (vector or multidimensional).
        /// </summary>
        public virtual string FormatArrayTypeName(Type arrayType, Array arrayOpt, CommonTypeNameFormatterOptions options)
        {
            if (arrayType == null)
            {
                throw new ArgumentNullException(nameof(arrayType));
            }

            StringBuilder sb = new StringBuilder();

            // print the inner-most element type first:
            Type elementType = arrayType.GetElementType();
            while (elementType.IsArray)
            {
                elementType = elementType.GetElementType();
            }

            sb.Append(FormatTypeName(elementType, options));

            // print all components of a jagged array:
            Type type = arrayType;
            do
            {
                if (arrayOpt != null)
                {
                    sb.Append(ArrayOpening);

                    int rank = type.GetArrayRank();

                    bool anyNonzeroLowerBound = false;
                    for (int i = 0; i < rank; i++)
                    {
                        if (arrayOpt.GetLowerBound(i) > 0)
                        {
                            anyNonzeroLowerBound = true;
                            break;
                        }
                    }

                    for (int i = 0; i < rank; i++)
                    {
                        int lowerBound = arrayOpt.GetLowerBound(i);
                        int length = arrayOpt.GetLength(i);

                        if (i > 0)
                        {
                            sb.Append(", ");
                        }

                        if (anyNonzeroLowerBound)
                        {
                            AppendArrayBound(sb, lowerBound, options.ArrayBoundRadix);
                            sb.Append("..");
                            AppendArrayBound(sb, length + lowerBound, options.ArrayBoundRadix);
                        }
                        else
                        {
                            AppendArrayBound(sb, length, options.ArrayBoundRadix);
                        }
                    }

                    sb.Append(ArrayClosing);
                    arrayOpt = null;
                }
                else
                {
                    AppendArrayRank(sb, type);
                }

                type = type.GetElementType();
            }
            while (type.IsArray);

            return sb.ToString();
        }
            private void FormatMultidimensionalArray(Builder result, Array array, bool inline)
            {
                Debug.Assert(array.Rank > 1);

                if (array.Length == 0)
                {
                    result.AppendCollectionItemSeparator(isFirst: true, inline: true);
                    result.AppendGroupOpening();
                    result.AppendGroupClosing(inline: true);
                    return;
                }

                int[] indices = new int[array.Rank];
                for (int i = array.Rank - 1; i >= 0; i--)
                {
                    indices[i] = array.GetLowerBound(i);
                }

                int nesting = 0;
                int flatIndex = 0;
                while (true)
                {
                    // increment indices (lower index overflows to higher):
                    int i = indices.Length - 1;
                    while (indices[i] > array.GetUpperBound(i))
                    {
                        indices[i] = array.GetLowerBound(i);
                        result.AppendGroupClosing(inline: inline || nesting != 1);
                        nesting--;

                        i--;
                        if (i < 0)
                        {
                            return;
                        }

                        indices[i]++;
                    }

                    result.AppendCollectionItemSeparator(isFirst: flatIndex == 0, inline: inline || nesting != 1);

                    i = indices.Length - 1;
                    while (i >= 0 && indices[i] == array.GetLowerBound(i))
                    {
                        result.AppendGroupOpening();
                        nesting++;

                        // array isn't empty, so there is always an element following this separator
                        result.AppendCollectionItemSeparator(isFirst: true, inline: inline || nesting != 1);

                        i--;
                    }

                    string name;
                    FormatObjectRecursive(result, array.GetValue(indices), quoteStrings: true, memberFormat: MemberDisplayFormat.InlineValue, name: out name);

                    indices[indices.Length - 1]++;
                    flatIndex++;
                }
            }
Example #25
0
 private void WriteArray(Array array, Hashtable objectContainer, ref Int32 objectID)
 {
     if (array.Rank > 1) {
         throw new RankException("Only single dimension arrays are supported here.");
     }
     stream.WriteByte(PHPSerializationTag.AssocArray);
     stream.WriteByte(PHPSerializationTag.Colon);
     WriteNumber(array.GetLength(0));
     stream.WriteByte(PHPSerializationTag.Colon);
     stream.WriteByte(PHPSerializationTag.LeftB);
     Int32 lowerBound = array.GetLowerBound(0);
     Int32 upperBound = array.GetUpperBound(0);
     for (Int32 i = lowerBound; i <= upperBound; i++) {
         WriteInteger(i);
         Serialize(array.GetValue(i), objectContainer, ref objectID);
     }
     stream.WriteByte(PHPSerializationTag.RightB);
 }
Example #26
0
        // Sorts the elements in a section of two arrays based on the keys in the
        // first array. Elements in the keys array specify the sort keys for
        // corresponding elements in the items array. The sort compares the
        // keys to each other using the given IComparer interface. If
        // comparer is null, the elements are compared to each other using
        // the IComparable interface, which in that case must be implemented
        // by all elements of the given section of the keys array.
        // 
        /// <include file='doc\Array.uex' path='docs/doc[@for="Array.Sort7"]/*' />
        public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) {
            if (keys==null)
                throw new ArgumentNullException("keys");
            if (keys.Rank != 1 || (items != null && items.Rank != 1))
                throw new RankException(Environment.GetResourceString("Rank_MultiDimNotSupported"));
            if (items != null && keys.GetLowerBound(0) != items.GetLowerBound(0))
                throw new ArgumentException(Environment.GetResourceString("Arg_LowerBoundsMustMatch"));
            if (index < keys.GetLowerBound(0) || length < 0)
                throw new ArgumentOutOfRangeException((length<0 ? "length" : "index"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
            if (keys.Length - (index+keys.GetLowerBound(0)) < length || (items != null && index > items.Length - length))
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));


            
            if (length > 1) {
                if (comparer == Comparer.Default || comparer == null) {
                    int r = TrySZSort(keys, items, index, index + length - 1);
                    if (r != 0)
                        return;
                }

                Object[] objKeys = keys as Object[];
                Object[] objItems = null;
                if (objKeys != null)
                    objItems = items as Object[];
                if (objKeys != null && (items==null || objItems != null)) {
                    SorterObjectArray sorter = new SorterObjectArray(objKeys, objItems, comparer);
                    sorter.QuickSort(index, index + length - 1);
                }
                else {
                    SorterGenericArray sorter = new SorterGenericArray(keys, items, comparer);
                    sorter.QuickSort(index, index + length - 1);
                }
            }
        }
Example #27
0
 // Sorts the elements of two arrays based on the keys in the first array.
 // Elements in the keys array specify the sort keys for
 // corresponding elements in the items array. The sort compares the
 // keys to each other using the given IComparer interface. If
 // comparer is null, the elements are compared to each other using
 // the IComparable interface, which in that case must be implemented
 // by all elements of the keys array.
 // 
 /// <include file='doc\Array.uex' path='docs/doc[@for="Array.Sort5"]/*' />
 public static void Sort(Array keys, Array items, IComparer comparer) {
     if (keys==null)
         throw new ArgumentNullException("keys");
     Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer);
 }
Example #28
0
 // Sorts the elements of an array. The sort compares the elements to each
 // other using the given IComparer interface. If comparer is
 // null, the elements are compared to each other using the
 // IComparable interface, which in that case must be implemented by
 // all elements of the array.
 // 
 /// <include file='doc\Array.uex' path='docs/doc[@for="Array.Sort4"]/*' />
 public static void Sort(Array array, IComparer comparer) {
     if (array==null)
         throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Array"));
     Sort(array, null, array.GetLowerBound(0), array.Length, comparer);
 }
Example #29
0
        // Reverses the elements in a range of an array. Following a call to this
        // method, an element in the range given by index and count
        // which was previously located at index i will now be located at
        // index index + (index + count - i - 1).
        // 
        /// <include file='doc\Array.uex' path='docs/doc[@for="Array.Reverse1"]/*' />
        public static void Reverse(Array array, int index, int length) {
            if (array==null) 
                throw new ArgumentNullException("array");
            if (index < array.GetLowerBound(0) || length < 0)
                throw new ArgumentOutOfRangeException((index<0 ? "index" : "length"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
            if (array.Length - (index - array.GetLowerBound(0)) < length)
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
            if (array.Rank != 1)
                throw new RankException(Environment.GetResourceString("Rank_MultiDimNotSupported"));

            bool r = TrySZReverse(array, index, length);
            if (r)
                return;

            int i = index;
            int j = index + length - 1;
            Object[] objArray = array as Object[];
            if (objArray!=null) {
                while (i < j) {
                    Object temp = objArray[i];
                    objArray[i] = objArray[j];
                    objArray[j] = temp;
                    i++;
                    j--;
                }
            }
            else {
                while (i < j) {
                    Object temp = array.GetValue(i);
                    array.SetValue(array.GetValue(j), i);
                    array.SetValue(temp, j);
                    i++;
                    j--;
                }
            }
        }
Example #30
0
        // Returns the index of the last occurrence of a given value in a range of
        // an array. The array is searched backwards, starting at index
        // startIndex and counting uptocount elements. The elements of
        // the array are compared to the given value using the Object.Equals
        // method.
        // 
        /// <include file='doc\Array.uex' path='docs/doc[@for="Array.LastIndexOf2"]/*' />
        public static int LastIndexOf(Array array, Object value, int startIndex, int count) {
            if (array==null)
                throw new ArgumentNullException("array");
            if (array.Length == 0) {
                return -1;
            }
            int lb = array.GetLowerBound(0);
            if (startIndex < lb || startIndex >= array.Length + lb)
                throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
            if (count < 0)
                throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
            if (count > startIndex - lb + 1)
                throw new ArgumentOutOfRangeException("endIndex", Environment.GetResourceString("ArgumentOutOfRange_EndIndexStartIndex"));
            if (array.Rank != 1)
                throw new RankException(Environment.GetResourceString("Rank_MultiDimNotSupported"));

            // Try calling a quick native method to handle primitive types.
            int retVal;
            int r = TrySZLastIndexOf(array, startIndex, count, value, out retVal);
            if (r != 0)
                return retVal;

            Object[] objArray = array as Object[];
            int endIndex = startIndex - count + 1;
            if (objArray!=null) {
                if (value == null) {
                    for (int i = startIndex; i >= endIndex; i--) {
                        if (objArray[i] == null) return i;
                    }
                }
                else {
                    for (int i = startIndex; i >= endIndex; i--) {
                        Object obj = objArray[i];
                        if (obj != null && value.Equals(obj)) return i;
                    }
                }
            }
            else {
                // This is an array of value classes
                BCLDebug.Assert(array.GetType().GetElementType().IsValueType, "array.GetType().GetUnderlyingType().IsValueType");
                if (value==null)
                    return -1;
                for (int i = startIndex; i >= endIndex; i--) {
                    Object obj = array.GetValue(i);
                    if (obj != null && value.Equals(obj)) return i;
                }
            }
            return lb-1;  // Return lb-1 for arrays with negative lower bounds.
        }