raw_element.go raw

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