You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
2.2 KiB

  1. // 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. package bson
  7. import (
  8. "go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
  9. )
  10. // RawElement represents a BSON element in byte form. This type provides a simple way to
  11. // transform a slice of bytes into a BSON element and extract information from it.
  12. //
  13. // RawElement is a thin wrapper around a bsoncore.Element.
  14. type RawElement []byte
  15. // Key returns the key for this element. If the element is not valid, this method returns an empty
  16. // string. If knowing if the element is valid is important, use KeyErr.
  17. func (re RawElement) Key() string { return bsoncore.Element(re).Key() }
  18. // KeyErr returns the key for this element, returning an error if the element is not valid.
  19. func (re RawElement) KeyErr() (string, error) { return bsoncore.Element(re).KeyErr() }
  20. // Value returns the value of this element. If the element is not valid, this method returns an
  21. // empty Value. If knowing if the element is valid is important, use ValueErr.
  22. func (re RawElement) Value() RawValue { return convertFromCoreValue(bsoncore.Element(re).Value()) }
  23. // ValueErr returns the value for this element, returning an error if the element is not valid.
  24. func (re RawElement) ValueErr() (RawValue, error) {
  25. val, err := bsoncore.Element(re).ValueErr()
  26. return convertFromCoreValue(val), err
  27. }
  28. // Validate ensures re is a valid BSON element.
  29. func (re RawElement) Validate() error { return bsoncore.Element(re).Validate() }
  30. // String implements the fmt.Stringer interface. The output will be in extended JSON format.
  31. func (re RawElement) String() string {
  32. doc := bsoncore.BuildDocument(nil, re)
  33. j, err := MarshalExtJSON(Raw(doc), true, false)
  34. if err != nil {
  35. return "<malformed>"
  36. }
  37. return string(j)
  38. }
  39. // DebugString outputs a human readable version of RawElement. It will attempt to stringify the
  40. // valid components of the element even if the entire element is not valid.
  41. func (re RawElement) DebugString() string { return bsoncore.Element(re).DebugString() }