| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package pmetric // import "go.opentelemetry.io/collector/pdata/pmetric" |
| 5 |
|
| 6 |
import ( |
| 7 |
"slices" |
| 8 |
|
| 9 |
"go.opentelemetry.io/collector/pdata/internal/json" |
| 10 |
"go.opentelemetry.io/collector/pdata/internal/otlp" |
| 11 |
) |
| 12 |
|
| 13 |
var _ Marshaler = (*JSONMarshaler)(nil) |
| 14 |
|
| 15 |
// JSONMarshaler marshals Metrics to JSON bytes using the OTLP/JSON format. |
| 16 |
type JSONMarshaler struct{} |
| 17 |
|
| 18 |
// MarshalMetrics to the OTLP/JSON format. |
| 19 |
func (*JSONMarshaler) MarshalMetrics(md Metrics) ([]byte, error) { |
| 20 |
dest := json.BorrowStream(nil) |
| 21 |
defer json.ReturnStream(dest) |
| 22 |
md.getOrig().MarshalJSON(dest) |
| 23 |
if dest.Error() != nil { |
| 24 |
return nil, dest.Error() |
| 25 |
} |
| 26 |
return slices.Clone(dest.Buffer()), nil |
| 27 |
} |
| 28 |
|
| 29 |
// JSONUnmarshaler unmarshals OTLP/JSON formatted-bytes to Metrics. |
| 30 |
type JSONUnmarshaler struct{} |
| 31 |
|
| 32 |
// UnmarshalMetrics from OTLP/JSON format into Metrics. |
| 33 |
func (*JSONUnmarshaler) UnmarshalMetrics(buf []byte) (Metrics, error) { |
| 34 |
iter := json.BorrowIterator(buf) |
| 35 |
defer json.ReturnIterator(iter) |
| 36 |
md := NewMetrics() |
| 37 |
md.getOrig().UnmarshalJSON(iter) |
| 38 |
if iter.Error() != nil { |
| 39 |
return Metrics{}, iter.Error() |
| 40 |
} |
| 41 |
otlp.MigrateMetrics(md.getOrig().ResourceMetrics) |
| 42 |
return md, nil |
| 43 |
} |