skia2/experimental/editor/stringslice.cpp
Mike Klein ad44dd500f preserve comments past the #include ""
Tacking on parts[2] lets us keep things like IWYU comments

    #include "something.h" // IWYU pragma: keep

Rerun the script too... not much interesting.

Change-Id: I9f02c81ffece0ecf3e99730d4a12d49e01417ddc
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/213697
Commit-Queue: Mike Klein <mtklein@google.com>
Commit-Queue: Brian Osman <brianosman@google.com>
Auto-Submit: Mike Klein <mtklein@google.com>
Reviewed-by: Brian Osman <brianosman@google.com>
2019-05-14 19:35:34 +00:00

75 lines
2.0 KiB
C++

// Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "experimental/editor/stringslice.h"
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <cstring>
using namespace editor;
void StringSlice::FreeWrapper::operator()(void* t) { std::free(t); }
StringSlice::StringSlice(StringSlice&& that)
: fPtr(std::move(that.fPtr))
, fLength(that.fLength)
, fCapacity(that.fCapacity)
{
that.fLength = 0;
that.fCapacity = 0;
}
StringSlice& StringSlice::operator=(StringSlice&& that) {
if (this != &that) {
this->~StringSlice();
new (this)StringSlice(std::move(that));
}
return *this;
}
void StringSlice::insert(std::size_t offset, const char* text, std::size_t length) {
if (length) {
offset = std::min(fLength, offset);
this->reserve(fLength + length); // TODO: reserve extra???
char* s = fPtr.get();
assert(s);
if (offset != fLength) {
std::memmove(s + offset + length, s + offset, fLength - offset);
}
if (text) {
std::memcpy(s + offset, text, length);
} else {
std::memset(s + offset, 0, length);
}
fLength += length;
}
}
void StringSlice::remove(std::size_t offset, std::size_t length) {
if (length && offset < fLength) {
length = std::min(length, fLength - offset);
assert(length > 0);
assert(length + offset <= fLength);
if (length + offset < fLength) {
char* s = fPtr.get();
assert(s);
std::memmove(s + offset, s + offset + length, fLength - (length + offset));
}
fLength -= length;
}
}
void StringSlice::reserve(std::size_t length) {
if (length && length > fCapacity) {
fPtr.reset((char*)std::realloc(fPtr.release(), length));
fCapacity = length;
}
}
void StringSlice::shrink() {
fPtr.reset((char*)std::realloc(fPtr.release(), fLength));
fCapacity = fLength;
}