1 //===--- SourceCode.h - Manipulating source code as strings -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 #include "SourceCode.h"
10 
11 namespace clang {
12 namespace clangd {
13 using namespace llvm;
14 
15 size_t positionToOffset(StringRef Code, Position P) {
16   if (P.line < 0)
17     return 0;
18   size_t StartOfLine = 0;
19   for (int I = 0; I != P.line; ++I) {
20     size_t NextNL = Code.find('\n', StartOfLine);
21     if (NextNL == StringRef::npos)
22       return Code.size();
23     StartOfLine = NextNL + 1;
24   }
25   // FIXME: officially P.character counts UTF-16 code units, not UTF-8 bytes!
26   return std::min(Code.size(), StartOfLine + std::max(0, P.character));
27 }
28 
29 Position offsetToPosition(StringRef Code, size_t Offset) {
30   Offset = std::min(Code.size(), Offset);
31   StringRef Before = Code.substr(0, Offset);
32   int Lines = Before.count('\n');
33   size_t PrevNL = Before.rfind('\n');
34   size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
35   // FIXME: officially character counts UTF-16 code units, not UTF-8 bytes!
36   return {Lines, static_cast<int>(Offset - StartOfLine)};
37 }
38 
39 } // namespace clangd
40 } // namespace clang
41 
42