Ejemplo n.º 1
0
        public static string ToString(byte[] bytes, int index, int length, bool wrap)
        {
            ThrowHelper.ArgumentNull((bytes == null), nameof(bytes));
            ThrowHelper.ArgumentIndexOutOfRange((index < 0), nameof(index));
            ThrowHelper.ArgumentLengthOutOfRange((length < 0), nameof(length));
            ThrowHelper.ArgumentIndexLengthOutOfArray(((index + length) > bytes.Length));

            string[] buffer = new string[length];
            for (int i = index; i < index + length; i++)
            {
                buffer[i - index] = string.Format(
                    System.Globalization.CultureInfo.InvariantCulture,
                    "{0:X2}",
                    bytes[i]);
            }

            if (wrap)
            {
                string[][]    temp    = Meision.Collections.CollectionManager.Divide <string>(buffer, 16);
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < temp.Length; i++)
                {
                    builder.AppendLine(string.Join(" ", temp[i]));
                }
                return(builder.ToString());
            }
            else
            {
                return(string.Join(" ", buffer));
            }
        }
Ejemplo n.º 2
0
        public static NetworkEndPoint Create(string expression)
        {
            ThrowHelper.ArgumentNull((expression == null), nameof(expression));

            Match match = Regex.Match(expression, RegexConstant.GetFullRegularExpression(RegularExpression));

            if (!match.Success)
            {
                return(null);
            }

            Group hostGroup = match.Groups[RegularExpressionGroupName_Host];
            Group portGroup = match.Groups[RegularExpressionGroupName_Port];

            string host = hostGroup.Value;
            int    port = 0;

            if (portGroup.Success)
            {
                port = Convert.ToInt32(portGroup.Value);
            }

            NetworkEndPoint point = new NetworkEndPoint(host, port);

            return(point);
        }
Ejemplo n.º 3
0
    public static void Write(this Stream stream, byte[] buffer)
    {
        ThrowHelper.ArgumentNull((stream == null), nameof(stream));
        ThrowHelper.ArgumentNull((buffer == null), nameof(buffer));

        stream.Write(buffer, 0, buffer.Length);
    }
Ejemplo n.º 4
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            this.EnsureNotClosed();

            ThrowHelper.ArgumentNull((buffer == null), nameof(buffer));
            ThrowHelper.ArgumentIndexOutOfRange((offset < 0), nameof(offset));
            ThrowHelper.ArgumentLengthOutOfRange((count < 0), nameof(count));
            ThrowHelper.ArgumentIndexLengthOutOfArray((offset + count > buffer.Length));

            int n = Math.Min(this.Remaining, count);

            if (n <= 0)
            {
                return(0);
            }

            Debug.Assert(_index + n >= 0, "_position + n >= 0");  // len is less than 2^31 -1.

            if (n <= 8)
            {
                int byteCount = n;
                while (--byteCount >= 0)
                {
                    buffer[offset + byteCount] = this._buffer[this._index + byteCount];
                }
            }
            else
            {
                System.Buffer.BlockCopy(_buffer, _index, buffer, offset, n);
            }
            _index += n;
            return(n);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Divide unitary array to binary array.
        /// </summary>
        /// <param name="array">array which want to be divided</param>
        /// <param name="column">Element count in each dimension</param>
        /// <returns></returns>
        public static T[][] Divide <T>(this IList <T> source, int column)
        {
            // Validate prameters
            ThrowHelper.ArgumentNull((source == null), nameof(source));

            // Array length.
            int length = source.Count;
            // Dimesion to store the array.
            int dimesions = Meision.Algorithms.Calculator.CeilingDivision(length, column);
            // Count;
            int count = 0;

            T[][] matrix = new T[dimesions][];
            if (dimesions > 0)
            {
                for (int i = 0; i < dimesions - 1; i++)
                {
                    matrix[i] = new T[column];
                    // Fill elements
                    for (int j = 0; j < column; j++)
                    {
                        matrix[i][j] = source[count++];
                    }
                }
                // Deal with remainder elements.
                int left = length - (dimesions - 1) * column;
                matrix[dimesions - 1] = new T[left];
                for (int j = 0; j < left; j++)
                {
                    matrix[dimesions - 1][j] = source[count++];
                }
            }

            return(matrix);
        }
Ejemplo n.º 6
0
    /// <summary>
    ///     A string extension method that return the left part of the string.
    /// </summary>
    /// <param name="instance">The instance to act on.</param>
    /// <param name="length">The length.</param>
    /// <returns>The left part.</returns>
    public static string Left(this string instance, int length)
    {
        ThrowHelper.ArgumentNull((instance == null), nameof(instance));
        ThrowHelper.ArgumentMustNotNegative((length < 0), nameof(length));

        return(instance.Substring(0, length));
    }
Ejemplo n.º 7
0
        public static byte[] ConvertFromStringArray(string[] items)
        {
            ThrowHelper.ArgumentNull((items == null), nameof(items));
            if (items.Length == 0)
            {
                return(Empty);
            }

            // Calculate size of string.
            int count = 0;

            foreach (string item in items)
            {
                count += (item.Length * sizeof(char));
            }
            count += (items.Length) * sizeof(char);
            byte[] buffer = new byte[count];
            // Copy string array.
            int index = 0;

            foreach (string item in items)
            {
                unsafe
                {
                    fixed(char *pointer = item)
                    {
                        Marshal.Copy(new IntPtr(pointer), buffer, index, item.Length * sizeof(char));
                    }
                }
                index += (item.Length + 1) * sizeof(char);
            }

            return(buffer);
        }
Ejemplo n.º 8
0
        public static string ToHexString(this byte[] buffer, string delimiter = null)
        {
            ThrowHelper.ArgumentNull((buffer == null), nameof(buffer));
            if (buffer.Length == 0)
            {
                return(string.Empty);
            }

            int length = buffer.Length * 2;

            if (delimiter != null)
            {
                length += ((buffer.Length - 1) * delimiter.Length);
            }

            StringBuilder builder = new StringBuilder(length, length);

            builder.AppendFormat(buffer[0].ToString("X2"));
            for (int i = 1; i < buffer.Length; i++)
            {
                builder.Append(delimiter);
                builder.AppendFormat(buffer[i].ToString("X2"));
            }
            return(builder.ToString());
        }
Ejemplo n.º 9
0
    public static string GetBetween(this string instance, int startIndex, string leftText, string rightText)
    {
        ThrowHelper.ArgumentNull((instance == null), nameof(instance));
        ThrowHelper.ArgumentOutOfRange(((startIndex < 0) || (startIndex > instance.Length)), nameof(startIndex));

        int pos;

        if (string.IsNullOrEmpty(leftText))
        {
            pos = startIndex;
        }
        else
        {
            pos = instance.IndexOf(leftText, startIndex) + leftText.Length;
            if (pos < leftText.Length)
            {
                return(null);
            }
        }

        if (string.IsNullOrEmpty(rightText))
        {
            return(instance.Substring(pos));
        }
        else
        {
            int end = instance.IndexOf(rightText, pos, StringComparison.Ordinal);
            if (end < pos)
            {
                return(null);
            }

            return(instance.Substring(pos, end - pos));
        }
    }
Ejemplo n.º 10
0
    /// <summary>
    ///     A string extension method that right safe.
    /// </summary>
    /// <param name="instance">The instance to act on.</param>
    /// <param name="length">The length.</param>
    /// <returns>A string.</returns>
    public static string RightSafe(this string instance, int length)
    {
        ThrowHelper.ArgumentNull((instance == null), nameof(instance));
        ThrowHelper.ArgumentMustNotNegative((length < 0), nameof(length));

        return(instance.Substring(Math.Max(0, instance.Length - length)));
    }
Ejemplo n.º 11
0
        public static long Base2Decode(string text)
        {
            ThrowHelper.ArgumentNull((text == null), nameof(text));
            ThrowHelper.ArgumentStringMustNotEmpty((text.Length == 0), nameof(text));

            return(BaseXDecode(text, Base2Templates, Searching));
        }
Ejemplo n.º 12
0
        public static TResult[] MakeArray <TResult>(this Vector vector, Func <int, TResult> func)
        {
            ThrowHelper.ArgumentNull((func == null), nameof(func));

            int count = Math.Abs(vector.Length);

            TResult[] array = new TResult[count];
            if (vector.Length > 0)
            {
                int value = vector.Offset;
                for (int i = 0; i < count; i++)
                {
                    array[i] = func(value++);
                }
            }
            else if (vector.Length < 0)
            {
                int value = vector.Offset;
                for (int i = 0; i < count; i++)
                {
                    array[i] = func(value--);
                }
            }
            else
            {
            }
            return(array);
        }
Ejemplo n.º 13
0
        public static string GetUsableFilename(string directory, string filename)
        {
            ThrowHelper.ArgumentNull((directory == null), nameof(directory));
            if (!System.IO.Directory.Exists(directory))
            {
                throw new System.IO.DirectoryNotFoundException();
            }
            ThrowHelper.ArgumentNull((filename == null), nameof(filename));

            string path = Path.Combine(directory, filename);

            if (!System.IO.File.Exists(path))
            {
                return(filename);
            }

            int slashPosition     = path.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
            int extensionPosition = path.IndexOf(Meision.IO.FileManager.FileExtension, slashPosition);

            if (extensionPosition != -1)
            {
                string left  = path.Substring(0, extensionPosition);
                string right = path.Substring(extensionPosition);

                for (int i = 1; i < int.MaxValue; i++)
                {
                    string newPath = string.Format(
                        System.Globalization.CultureInfo.InvariantCulture,
                        NewFileFormat,
                        left,
                        i.ToString(),
                        right);

                    if (!System.IO.File.Exists(newPath))
                    {
                        return(System.IO.Path.GetFileName(newPath));
                    }
                }
            }
            else
            {
                for (int i = 1; i < int.MaxValue; i++)
                {
                    string newPath = string.Format(
                        System.Globalization.CultureInfo.InvariantCulture,
                        NewFileFormat,
                        path,
                        i.ToString(),
                        string.Empty);

                    if (!System.IO.File.Exists(newPath))
                    {
                        return(System.IO.Path.GetFileName(newPath));
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 14
0
            public override void ToBytes(SByte value, byte[] bytes, int index)
            {
                ThrowHelper.ArgumentNull((bytes == null), nameof(bytes));
                ThrowHelper.ArgumentIndexOutOfRange((index < 0), nameof(index));
                ThrowHelper.ArgumentIndexOutOfRange(((index + sizeof(SByte)) > bytes.Length), nameof(index));

                bytes[index] = (Byte)value;
            }
Ejemplo n.º 15
0
        //private NetworkEndPoint()
        //{
        //}

        public NetworkEndPoint(string host, int port)
        {
            ThrowHelper.ArgumentNull((host == null), nameof(host));
            ThrowHelper.ArgumentOutOfRange(((port < MinPort) || (port > MaxPort)), nameof(port), SR.NetworkEndPoint_Exception_InvalidPort);

            this._host = host;
            this._port = port;
        }
Ejemplo n.º 16
0
        // Writes this MemoryStream to another stream.
        public virtual void WriteTo(Stream stream)
        {
            this.EnsureNotClosed();

            ThrowHelper.ArgumentNull((stream == null), nameof(stream));

            stream.Write(this._buffer, this._start, this._end - this._start);
        }
Ejemplo n.º 17
0
            public override Boolean GetBoolean(byte[] data, int index)
            {
                ThrowHelper.ArgumentNull((data == null), nameof(data));
                ThrowHelper.ArgumentIndexOutOfRange((index < 0), nameof(index));
                ThrowHelper.ArgumentIndexOutOfRange(((index + sizeof(Boolean)) > data.Length), nameof(index));

                return(data[index] != 0);
            }
Ejemplo n.º 18
0
            public override SByte GetSByte(byte[] bytes, int index)
            {
                ThrowHelper.ArgumentNull((bytes == null), nameof(bytes));
                ThrowHelper.ArgumentIndexOutOfRange((index < 0), nameof(index));
                ThrowHelper.ArgumentIndexOutOfRange(((index + sizeof(SByte)) > bytes.Length), nameof(index));

                return((SByte)bytes[index]);
            }
Ejemplo n.º 19
0
        public static byte[] GetSegment(this byte[] array, int offset)
        {
            // Validate parameter(s).
            ThrowHelper.ArgumentNull((array == null), nameof(array));
            ThrowHelper.ArgumentIndexOutOfRange(((offset < 0) || (offset > array.Length)), nameof(offset));

            return(Bytes.GetSegment(array, offset, array.Length - offset));
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Constructs a new observe relation.
 /// </summary>
 /// <param name="config">the config</param>
 /// <param name="endpoint">the observing endpoint</param>
 /// <param name="resource">the observed resource</param>
 /// <param name="exchange">the exchange that tries to establish the observe relation</param>
 public ObserveRelation(ICoapConfig config, ObservingEndpoint endpoint, IResource resource, Exchange exchange)
 {
     _config   = config ?? throw ThrowHelper.ArgumentNull("config");
     _endpoint = endpoint ?? throw ThrowHelper.ArgumentNull("endpoint");
     Resource  = resource ?? throw ThrowHelper.ArgumentNull("resource");
     Exchange  = exchange ?? throw ThrowHelper.ArgumentNull("exchange");
     Key       = $"{Source}#{exchange.Request.TokenString}";
 }
Ejemplo n.º 21
0
 public Message AddETag(Byte[] opaque)
 {
     if (opaque == null)
     {
         throw ThrowHelper.ArgumentNull("opaque");
     }
     return(AddOption(Option.Create(OptionType.ETag, opaque)));
 }
Ejemplo n.º 22
0
 /// <inheritdoc/>
 public Int32 CompareTo(WebLink other)
 {
     if (other == null)
     {
         throw ThrowHelper.ArgumentNull("other");
     }
     return(_uri.CompareTo(other._uri));
 }
Ejemplo n.º 23
0
            public override Char GetChar(byte[] data, int index)
            {
                ThrowHelper.ArgumentNull((data == null), nameof(data));
                ThrowHelper.ArgumentIndexOutOfRange((index < 0), nameof(index));
                ThrowHelper.ArgumentIndexOutOfRange(((index + sizeof(Char)) > data.Length), nameof(index));

                return((Char)this.GetUInt16(data, index));
            }
Ejemplo n.º 24
0
            public override void ToBytes(Boolean value, byte[] bytes, int index)
            {
                ThrowHelper.ArgumentNull((bytes == null), nameof(bytes));
                ThrowHelper.ArgumentIndexOutOfRange((index < 0), nameof(index));
                ThrowHelper.ArgumentIndexOutOfRange(((index + sizeof(Boolean)) > bytes.Length), nameof(index));

                Endian.__little.ToBytes(value, bytes, index);
                Meision.Collections.Bytes.Reverse(bytes, index, sizeof(Boolean));
            }
Ejemplo n.º 25
0
        /// <inheritdoc/>
        public Int32 CompareTo(WebLink other)
        {
            if (other == null)
            {
                throw ThrowHelper.ArgumentNull("other");
            }

            return(string.Compare(Uri, other.Uri, StringComparison.Ordinal));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Find the index of pattern in origin array. BMH algorithm search
        /// </summary>
        /// <param name="origin">origin bytes.</param>
        /// <param name="index">index.</param>
        /// <param name="length">searching length</param>
        /// <param name="pattern">Find bytes.</param>
        /// <returns>Index position.</returns>
        public static int Search(byte[] origin, int index, byte[] pattern)
        {
            // Validate parameter(s).
            ThrowHelper.ArgumentNull((origin == null), nameof(origin));
            ThrowHelper.ArgumentIndexOutOfRange(((index < 0) || (index > origin.Length)), nameof(index));
            ThrowHelper.ArgumentNull((pattern == null), nameof(pattern));

            return(Bytes.Search(origin, index, origin.Length - index, pattern));
        }
Ejemplo n.º 27
0
    public static string FormatWith(this string instance, params object[] args)
    {
        ThrowHelper.ArgumentNull((instance == null), nameof(instance));

        return(string.Format(
                   System.Globalization.CultureInfo.InvariantCulture,
                   instance,
                   args));
    }
Ejemplo n.º 28
0
        public BufferStream(byte[] buffer, int offset, int count, bool writable, bool isLittleEndian)
        {
            ThrowHelper.ArgumentNull((buffer == null), nameof(buffer));
            ThrowHelper.ArgumentIndexOutOfRange((offset < 0), nameof(offset));
            ThrowHelper.ArgumentLengthOutOfRange((count < 0), nameof(count));
            ThrowHelper.ArgumentIndexLengthOutOfArray((offset + count > buffer.Length));

            this.InitFromExternBuffer(buffer, offset, count, writable, isLittleEndian);
        }
Ejemplo n.º 29
0
        public static void MoveToDirectory(string path, string directory)
        {
            ThrowHelper.ArgumentNull((path == null), nameof(path));
            ThrowHelper.ArgumentNull((directory == null), nameof(directory));

            string file = System.IO.Path.GetFileName(path);

            System.IO.File.Move(path, System.IO.Path.Combine(directory, file));
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Gets the http headers from a list of CoAP options. The method iterates
        /// over the list looking for a translation of each option in the predefined
        /// mapping. This process ignores the proxy-uri and the content-type because
        /// they are managed differently. If a mapping is present, the content of the
        /// option is mapped to a string accordingly to its original format and set
        /// as the content of the header.
        /// </summary>
        /// <param name="optionList"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static NameValueCollection GetHttpHeaders(IEnumerable <Option> optionList)
        {
            if (optionList == null)
            {
                throw ThrowHelper.ArgumentNull("optionList");
            }

            NameValueCollection headers = new NameValueCollection();

            foreach (Option opt in optionList)
            {
                // skip content-type because it should be translated while handling
                // the payload; skip proxy-uri because it has to be translated in a
                // different way
                if (opt.Type == OptionType.ContentType || opt.Type == OptionType.ProxyUri)
                {
                    continue;
                }

                string headerName;
                if (!_Coap2HttpHeader.TryGetValue(opt.Type, out headerName))
                {
                    continue;
                }

                // format the value
                string       headerValue = null;
                OptionFormat format      = Option.GetFormatByType(opt.Type);
                if (format == OptionFormat.Integer)
                {
                    headerValue = opt.IntValue.ToString();
                }
                else if (format == OptionFormat.String)
                {
                    headerValue = opt.StringValue;
                }
                else if (format == OptionFormat.Opaque)
                {
                    headerValue = ByteArrayUtils.ToHexString(opt.RawValue);
                }
                else
                {
                    continue;
                }

                // custom handling for max-age
                // format: cache-control: max-age=60
                if (opt.Type == OptionType.MaxAge)
                {
                    headerValue = "max-age=" + headerValue;
                }
                headers[headerName] = headerValue;
            }

            return(headers);
        }