github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/vendor_skip/go.mongodb.org/mongo-driver/internal/string_util.go (about)

     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 internal
     8  
     9  import (
    10  	"fmt"
    11  
    12  	"go.mongodb.org/mongo-driver/bson"
    13  )
    14  
    15  // StringSliceFromRawElement decodes the provided BSON element into a []string. This internally calls
    16  // StringSliceFromRawValue on the element's value. The error conditions outlined in that function's documentation
    17  // apply for this function as well.
    18  func StringSliceFromRawElement(element bson.RawElement) ([]string, error) {
    19  	return StringSliceFromRawValue(element.Key(), element.Value())
    20  }
    21  
    22  // StringSliceFromRawValue decodes the provided BSON value into a []string. This function returns an error if the value
    23  // is not an array or any of the elements in the array are not strings. The name parameter is used to add context to
    24  // error messages.
    25  func StringSliceFromRawValue(name string, val bson.RawValue) ([]string, error) {
    26  	arr, ok := val.ArrayOK()
    27  	if !ok {
    28  		return nil, fmt.Errorf("expected '%s' to be an array but it's a BSON %s", name, val.Type)
    29  	}
    30  
    31  	arrayValues, err := arr.Values()
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	strs := make([]string, 0, len(arrayValues))
    37  	for _, arrayVal := range arrayValues {
    38  		str, ok := arrayVal.StringValueOK()
    39  		if !ok {
    40  			return nil, fmt.Errorf("expected '%s' to be an array of strings, but found a BSON %s", name, arrayVal.Type)
    41  		}
    42  		strs = append(strs, str)
    43  	}
    44  	return strs, nil
    45  }