ccls/src/position.cc

99 lines
2.4 KiB
C++
Raw Normal View History

2018-08-21 05:27:52 +00:00
// Copyright 2017-2018 ccls Authors
// SPDX-License-Identifier: Apache-2.0
2018-10-29 04:21:21 +00:00
#include "position.hh"
2017-04-05 08:06:18 +00:00
#include "serializer.hh"
2017-04-05 08:06:18 +00:00
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
2017-04-05 08:06:18 +00:00
namespace ccls {
Pos Pos::FromString(const std::string &encoded) {
2018-08-09 17:08:14 +00:00
char *p = const_cast<char *>(encoded.c_str());
uint16_t line = uint16_t(strtoul(p, &p, 10) - 1);
2018-03-15 04:12:55 +00:00
assert(*p == ':');
p++;
int16_t column = int16_t(strtol(p, &p, 10)) - 1;
return {line, column};
2017-04-05 08:06:18 +00:00
}
std::string Pos::ToString() {
char buf[99];
snprintf(buf, sizeof buf, "%d:%d", line + 1, column + 1);
return buf;
2017-04-05 08:06:18 +00:00
}
2018-08-09 17:08:14 +00:00
Range Range::FromString(const std::string &encoded) {
Pos start, end;
2018-08-09 17:08:14 +00:00
char *p = const_cast<char *>(encoded.c_str());
start.line = uint16_t(strtoul(p, &p, 10) - 1);
assert(*p == ':');
p++;
start.column = int16_t(strtol(p, &p, 10)) - 1;
assert(*p == '-');
p++;
end.line = uint16_t(strtoul(p, &p, 10) - 1);
assert(*p == ':');
p++;
end.column = int16_t(strtol(p, nullptr, 10)) - 1;
return {start, end};
2017-04-05 08:06:18 +00:00
}
bool Range::Contains(int line, int column) const {
if (line > INT16_MAX)
return false;
Pos p{(uint16_t)line, (int16_t)std::min<int>(column, INT16_MAX)};
return !(p < start) && p < end;
}
2017-04-05 08:06:18 +00:00
std::string Range::ToString() {
char buf[99];
snprintf(buf, sizeof buf, "%d:%d-%d:%d", start.line + 1, start.column + 1,
end.line + 1, end.column + 1);
return buf;
2017-05-19 07:02:01 +00:00
}
void Reflect(JsonReader &vis, Pos &v) { v = Pos::FromString(vis.GetString()); }
void Reflect(JsonReader &vis, Range &v) {
v = Range::FromString(vis.GetString());
}
void Reflect(JsonWriter &vis, Pos &v) {
std::string output = v.ToString();
vis.String(output.c_str(), output.size());
}
void Reflect(JsonWriter &vis, Range &v) {
std::string output = v.ToString();
vis.String(output.c_str(), output.size());
}
void Reflect(BinaryReader &visitor, Pos &value) {
Reflect(visitor, value.line);
Reflect(visitor, value.column);
2017-05-19 07:02:01 +00:00
}
void Reflect(BinaryReader &visitor, Range &value) {
Reflect(visitor, value.start.line);
Reflect(visitor, value.start.column);
Reflect(visitor, value.end.line);
Reflect(visitor, value.end.column);
2017-05-19 07:02:01 +00:00
}
void Reflect(BinaryWriter &vis, Pos &v) {
Reflect(vis, v.line);
Reflect(vis, v.column);
2017-05-19 07:02:01 +00:00
}
void Reflect(BinaryWriter &vis, Range &v) {
Reflect(vis, v.start.line);
Reflect(vis, v.start.column);
Reflect(vis, v.end.line);
Reflect(vis, v.end.column);
}
} // namespace ccls