util/StringView: add method Split()

This commit is contained in:
Max Kellermann 2019-06-06 12:15:50 +02:00
parent c1719a5200
commit 76eb550011

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2013-2017 Max Kellermann <max.kellermann@gmail.com>
* Copyright 2013-2019 Max Kellermann <max.kellermann@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@ -33,6 +33,8 @@
#include "ConstBuffer.hxx"
#include "StringAPI.hxx"
#include <utility>
template<typename T>
struct BasicStringView : ConstBuffer<T> {
typedef typename ConstBuffer<T>::size_type size_type;
@ -65,6 +67,8 @@ struct BasicStringView : ConstBuffer<T> {
:ConstBuffer<T>(n) {}
using ConstBuffer<T>::empty;
using ConstBuffer<T>::begin;
using ConstBuffer<T>::end;
using ConstBuffer<T>::front;
using ConstBuffer<T>::back;
using ConstBuffer<T>::pop_front;
@ -76,6 +80,20 @@ struct BasicStringView : ConstBuffer<T> {
return StringFind(data, ch, this->size);
}
/**
* Split the string at the first occurrence of the given
* character. If the character is not found, then the first
* value is the whole string and the second value is nullptr.
*/
gcc_pure
std::pair<BasicStringView<T>, BasicStringView<T>> Split(value_type ch) const noexcept {
const auto separator = Find(ch);
if (separator == nullptr)
return {*this, nullptr};
return {{begin(), separator}, {separator + 1, end()}};
}
gcc_pure
bool StartsWith(BasicStringView<T> needle) const noexcept {
return this->size >= needle.size &&