raw_element.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 is a raw encoded BSON document or array element.
  11. type RawElement []byte
  12. // Key returns the key for this element. If the element is not valid, this method returns an empty
  13. // string. If knowing if the element is valid is important, use KeyErr.
  14. func (re RawElement) Key() string { return bsoncore.Element(re).Key() }
  15. // KeyErr returns the key for this element, returning an error if the element is not valid.
  16. func (re RawElement) KeyErr() (string, error) { return bsoncore.Element(re).KeyErr() }
  17. // Value returns the value of this element. If the element is not valid, this method returns an
  18. // empty Value. If knowing if the element is valid is important, use ValueErr.
  19. func (re RawElement) Value() RawValue { return convertFromCoreValue(bsoncore.Element(re).Value()) }
  20. // ValueErr returns the value for this element, returning an error if the element is not valid.
  21. func (re RawElement) ValueErr() (RawValue, error) {
  22. val, err := bsoncore.Element(re).ValueErr()
  23. return convertFromCoreValue(val), err
  24. }
  25. // Validate ensures re is a valid BSON element.
  26. func (re RawElement) Validate() error { return bsoncore.Element(re).Validate() }
  27. // String returns the BSON element encoded as Extended JSON.
  28. func (re RawElement) String() string {
  29. doc := bsoncore.BuildDocument(nil, re)
  30. j, err := MarshalExtJSON(Raw(doc), true, false)
  31. if err != nil {
  32. return "<malformed>"
  33. }
  34. return string(j)
  35. }
  36. // DebugString outputs a human readable version of RawElement. It will attempt to stringify the
  37. // valid components of the element even if the entire element is not valid.
  38. func (re RawElement) DebugString() string { return bsoncore.Element(re).DebugString() }