Blender  V3.3
Classes | Namespaces
BLI_string_ref.hh File Reference
#include <cstring>
#include <sstream>
#include <string>
#include <string_view>
#include "BLI_span.hh"
#include "BLI_utildefines.h"

Go to the source code of this file.

Classes

class  blender::StringRefBase
 
class  blender::StringRefNull
 
class  blender::StringRef
 

Namespaces

 blender
 

Functions

#StringRefBase Inline Methods
constexpr int64_t blender::index_or_npos_to_int64 (size_t index)
 
Operator Overloads
std::ostream & blender::operator<< (std::ostream &stream, StringRef ref)
 
std::ostream & blender::operator<< (std::ostream &stream, StringRefNull ref)
 
std::string blender::operator+ (StringRef a, StringRef b)
 
constexpr bool blender::operator== (StringRef a, StringRef b)
 
constexpr bool blender::operator!= (StringRef a, StringRef b)
 
constexpr bool blender::operator< (StringRef a, StringRef b)
 
constexpr bool blender::operator> (StringRef a, StringRef b)
 
constexpr bool blender::operator<= (StringRef a, StringRef b)
 
constexpr bool blender::operator>= (StringRef a, StringRef b)
 

Detailed Description

A blender::StringRef references a const char array owned by someone else. It is just a pointer and a size. Since the memory is not owned, StringRef should not be used to transfer ownership of the string. The data referenced by a StringRef cannot be mutated through it.

A StringRef is NOT null-terminated. This makes it much more powerful within C++, because we can also cut off parts of the end without creating a copy. When interfacing with C code that expects null-terminated strings, blender::StringRefNull can be used. It is essentially the same as StringRef, but with the restriction that the string has to be null-terminated.

Whenever possible, string parameters should be of type StringRef and the string return type should be StringRefNull. Don't forget that the StringRefNull does not own the string, so don't return it when the string exists only in the scope of the function. This convention makes functions usable in the most contexts.

blender::StringRef vs. std::string_view: Both types are certainly very similar. The main benefit of using StringRef in Blender is that this allows us to add convenience methods at any time. Especially, when doing a lot of string manipulation, this helps to keep the code clean. Furthermore, we need StringRefNull anyway, because there is a lot of C code that expects null-terminated strings. Conversion between StringRef and string_view is very cheap and can be done at api boundaries at essentially no cost. Another benefit of using StringRef is that it uses signed integers, thus developers have to deal less with issues resulting from unsigned integers.

Definition in file BLI_string_ref.hh.