blob: 2a01390bfdf4e495f739eae510f07a36f6d0b782 [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001// Copyright (C) MongoDB, Inc. 2017-present.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7package bson
8
9import (
10 "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore"
11)
12
13// RawElement represents a BSON element in byte form. This type provides a simple way to
14// transform a slice of bytes into a BSON element and extract information from it.
15//
16// RawElement is a thin wrapper around a bsoncore.Element.
17type RawElement []byte
18
19// Key returns the key for this element. If the element is not valid, this method returns an empty
20// string. If knowing if the element is valid is important, use KeyErr.
21func (re RawElement) Key() string { return bsoncore.Element(re).Key() }
22
23// KeyErr returns the key for this element, returning an error if the element is not valid.
24func (re RawElement) KeyErr() (string, error) { return bsoncore.Element(re).KeyErr() }
25
26// Value returns the value of this element. If the element is not valid, this method returns an
27// empty Value. If knowing if the element is valid is important, use ValueErr.
28func (re RawElement) Value() RawValue { return convertFromCoreValue(bsoncore.Element(re).Value()) }
29
30// ValueErr returns the value for this element, returning an error if the element is not valid.
31func (re RawElement) ValueErr() (RawValue, error) {
32 val, err := bsoncore.Element(re).ValueErr()
33 return convertFromCoreValue(val), err
34}
35
36// Validate ensures re is a valid BSON element.
37func (re RawElement) Validate() error { return bsoncore.Element(re).Validate() }
38
39// String implements the fmt.Stringer interface. The output will be in extended JSON format.
40func (re RawElement) String() string {
41 doc := bsoncore.BuildDocument(nil, re)
42 j, err := MarshalExtJSON(Raw(doc), true, false)
43 if err != nil {
44 return "<malformed>"
45 }
46 return string(j)
47}
48
49// DebugString outputs a human readable version of RawElement. It will attempt to stringify the
50// valid components of the element even if the entire element is not valid.
51func (re RawElement) DebugString() string { return bsoncore.Element(re).DebugString() }