예제 #1
0
        static IEnumerable <byte> MetricGroupsToBytes(string name, string tags, IEnumerable <RawMetricValue> rawValues)
        {
            byte[] nameArray  = Encoding.UTF8.GetBytes(name);
            byte[] nameLength = BitConverter.GetBytes(name.Length);

            byte[] tagsArray  = Encoding.UTF8.GetBytes(tags);
            byte[] tagsLength = BitConverter.GetBytes(tags.Length);

            // Unfortunately this extra array is necessary, since we need to know the length before we enumerate the values.
            RawMetricValue[]   rawValuesArray = rawValues.ToArray();
            byte[]             valuesLength   = BitConverter.GetBytes(rawValuesArray.Length);
            IEnumerable <byte> values         = RawMetricValue.RawValuesToBytes(rawValuesArray);

            return(nameLength.Concat(nameArray).Concat(tagsLength).Concat(tagsArray).Concat(valuesLength).Concat(values));
        }
예제 #2
0
        public static IEnumerable <Metric> BytesToMetrics(byte[] bytes)
        {
            int index = 0;

            while (index < bytes.Length)
            {
                string name;
                Dictionary <string, string>  tags;
                IEnumerable <RawMetricValue> rawValues;
                try
                {
                    int nameLength = BitConverter.ToInt32(bytes, index);
                    index = checked (index + sizeof(int));
                    name  = Encoding.UTF8.GetString(bytes, index, nameLength);
                    index = checked (index + nameLength);

                    int tagsLength = BitConverter.ToInt32(bytes, index);
                    index = checked (index + sizeof(int));
                    string rawTags = Encoding.UTF8.GetString(bytes, index, tagsLength);
                    index = checked (index + tagsLength);
                    tags  = JsonConvert.DeserializeObject <Dictionary <string, string> >(rawTags);

                    int valuesLength = BitConverter.ToInt32(bytes, index);
                    index = checked (index + sizeof(int));

                    int oldIndex = index;
                    index     = checked (index + valuesLength * RawMetricValue.EncodedSize);
                    rawValues = RawMetricValue.BytesToRawValues(bytes, oldIndex, valuesLength);
                }
                catch (Exception e) when(e is OverflowException || e is ArgumentException || e is ArgumentOutOfRangeException || e is JsonSerializationException)
                {
                    throw new InvalidDataException("Error decoding metrics", e);
                }

                foreach (RawMetricValue rawValue in rawValues)
                {
                    yield return(new Metric(
                                     rawValue.TimeGeneratedUtc,
                                     name,
                                     rawValue.Value,
                                     tags));
                }
            }
        }