summaryrefslogtreecommitdiff
path: root/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ArrayWithOffset.cs
blob: eb2a2cba1429dd9c855f440bb19de1bb8d48ea3f (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Runtime.CompilerServices;

#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif

namespace System.Runtime.InteropServices
{
    public struct ArrayWithOffset
    {
        private object m_array;
        private int m_offset;
        private int m_count;

        // From MAX_SIZE_FOR_INTEROP in mlinfo.h
        private const int MaxSizeForInterop = 0x7ffffff0;

        public ArrayWithOffset(object array, int offset)
        {
            int totalSize = 0;
            if (array != null)
            {
                if (!(array is Array arrayObj) || (arrayObj.Rank != 1) || !Marshal.IsPinnable(arrayObj))
                {
                    throw new ArgumentException(SR.Argument_NotIsomorphic);
                }

                nuint nativeTotalSize = (nuint)arrayObj.LongLength * (nuint)arrayObj.GetElementSize();
                if (nativeTotalSize > MaxSizeForInterop)
                {
                    throw new ArgumentException(SR.Argument_StructArrayTooLarge);
                }

                totalSize = (int)nativeTotalSize;
            }

            if ((uint)offset > (uint)totalSize)
            {
                throw new IndexOutOfRangeException(SR.IndexOutOfRange_ArrayWithOffset);
            }

            m_array = array;
            m_offset = offset;
            m_count = totalSize - offset;
        }

        public object GetArray() => m_array;

        public int GetOffset() => m_offset;

        public override int GetHashCode() => m_count + m_offset;

        public override bool Equals(object obj)
        {
            return obj is ArrayWithOffset && Equals((ArrayWithOffset)obj);
        }

        public bool Equals(ArrayWithOffset obj)
        {
            return obj.m_array == m_array && obj.m_offset == m_offset && obj.m_count == m_count;
        }

        public static bool operator ==(ArrayWithOffset a, ArrayWithOffset b)
        {
            return a.Equals(b);
        }

        public static bool operator !=(ArrayWithOffset a, ArrayWithOffset b)
        {
            return !(a == b);
        }
    }
}