본문으로 건너뛰기
Folly Code Review · 36/89

folly::FixedString — compile-time string

· Hawk · 3분 읽기

#한 줄 요약

folly::FixedString<N>은 N 크기의 char 배열을 가진 fully constexpr 문자열. heap 없음, throw 없음, 모든 연산이 constexpr. compile-time string concat과 hash 계산이 가능.

#동기

C++의 string handling은 runtime이 default다. std::string은 heap, std::string_view는 view만, const char*는 길이 정보 없음. compile-time에 다음을 하고 싶다.

  • enum to string compile-time conversion.
  • log tag concatenation "[module=" + name + "]".
  • constexpr hash key.
  • table lookup의 key를 constexpr 생성.

C++17의 std::string_view는 view, C++20의 consteval은 표현력, C++26의 constexpr std::string은 아직 미정. 이 빈자리를 FixedString이 채운다.

constexpr auto tag = folly::makeFixedString("hello") +
folly::makeFixedString(", world");
// tag는 컴파일 타임에 "hello, world"
static_assert(tag.size() == 12);

#API & 사용법

#include <folly/FixedString.h>
// 1. 생성 — N은 컴파일 타임
constexpr folly::FixedString<5> s1{"hello"};
constexpr auto s2 = folly::makeFixedString("world"); // 추론
// 2. 표준 string 인터페이스
constexpr auto len = s1.size(); // 5
constexpr char c = s1[0]; // 'h'
constexpr bool b = s1.starts_with("he"); // true
// 3. 연산 — 모두 constexpr
constexpr auto greeting = s1 + ", " + s2;
constexpr auto substr = greeting.substr(0, 5); // "hello"
// 4. string_view로 변환 (런타임에)
folly::StringPiece sp = s1;
std::string_view sv = s1;
// 5. compile-time hash
constexpr auto h = folly::FixedString{"key"}.hash();

FixedString<N>은 정확히 N+1 char buffer를 가진다(null terminator 포함). 모든 길이 정보가 type에 들어 있어 더 작은 객체.

#내부 구현

// 약식 — folly/FixedString.h
template <size_t N>
class BasicFixedString {
char data_[N + 1]; // null terminator 위해 +1
size_t size_;
public:
constexpr BasicFixedString() : data_{}, size_(0) {}
constexpr BasicFixedString(const char (&s)[N + 1])
: data_{}, size_(N) {
for (size_t i = 0; i < N; ++i) data_[i] = s[i];
data_[N] = '\0';
}
constexpr size_t size() const { return size_; }
constexpr const char* data() const { return data_; }
constexpr const char* c_str() const { return data_; }
// ...
};
template <size_t N>
using FixedString = BasicFixedString<N>;

data_는 stack/static 영역. heap 호출 없음. constexpr context에서는 컴파일러가 buffer를 실제로 만들고 character를 채워 둔다.

#Operator+의 reductio

template <size_t M, size_t N>
constexpr BasicFixedString<M + N> operator+(
const BasicFixedString<M>& a,
const BasicFixedString<N>& b) {
BasicFixedString<M + N> r;
for (size_t i = 0; i < M; ++i) r.data_[i] = a.data_[i];
for (size_t i = 0; i < N; ++i) r.data_[M + i] = b.data_[i];
r.data_[M + N] = '\0';
r.size_ = M + N;
return r;
}

결과 타입의 N이 두 operand size 합. compile-time 산술로 결정.

#Compile-time hash

// 약식
constexpr uint64_t fnv1a(const char* s, size_t n) {
uint64_t h = 0xcbf29ce484222325;
for (size_t i = 0; i < n; ++i) {
h ^= s[i];
h *= 0x100000001b3;
}
return h;
}
template <size_t N>
constexpr uint64_t BasicFixedString<N>::hash() const {
return fnv1a(data_, size_);
}

constexpr이므로 컴파일러가 hash 값을 미리 계산. switch (FixedString{"key"}.hash()) { case ... } 같은 코드가 동작.

#std/abseil 비교

// std (C++26 후보)
// constexpr std::string — 아직 미확정
// 현재 std
constexpr std::string_view sv = "hello"; // view만
// 길이 정보는 있으나 storage 합성 불가
// abseil — 직접 대응 없음. CharSet 정도
// folly
constexpr folly::FixedString s = "hello"; // 완전 constexpr

C++20의 std::string_view는 view만이라 새 문자열 합성 불가. constexpr std::string은 표준 일정에 따라 다름. FixedString지금 compile-time 합성을 제공.

#사용 사례

#1. Enum to string

enum class Level { Info, Warning, Error };
constexpr auto levelName(Level l) {
switch (l) {
case Level::Info: return folly::makeFixedString("INFO");
case Level::Warning: return folly::makeFixedString("WARN");
case Level::Error: return folly::makeFixedString("ERR");
}
}
// 호출도 constexpr 가능

#2. Log prefix concatenation

template <size_t N>
constexpr auto logPrefix(folly::FixedString<N> module) {
return folly::makeFixedString("[mod=") + module + "] ";
}
constexpr auto prefix = logPrefix(folly::makeFixedString("net"));
// "[mod=net] "

#3. Compile-time map key

constexpr struct {
folly::FixedString<8> name;
int value;
} table[] = {
{ folly::makeFixedString("alpha"), 1 },
{ folly::makeFixedString("beta"), 2 },
{ folly::makeFixedString("gamma"), 3 },
};

#코드 리뷰 포인트

// Bad — runtime string을 FixedString으로
auto s = folly::makeFixedString(GetRuntimeString().c_str());
// N을 컴파일 타임에 알 수 없어 안 됨
// Good — runtime은 fbstring/string
folly::fbstring s = GetRuntimeString();

FixedString<N>의 N은 컴파일 타임 상수여야 한다. runtime 길이면 다른 type을 쓴다.

// 주의 — 큰 N은 객체 크기 증가
constexpr folly::FixedString<10000> buf; // 10KB stack/object

FixedString<N>의 sizeof는 N+1+sizeof(size_t). 큰 N은 stack/static 메모리 압박.

#안티패턴

  • template parameter pack에 FixedString 잘못 사용: template argument에 사용하려면 C++20 consteval/constexpr이 잘 동작하는 컴파일러 필요. gcc 9+, clang 10+.
  • runtime string과 mix: folly::FixedString + std::string은 불가. 명시적 변환 후 연결.
  • N을 type 시그니처에 노출: 함수 인자 void f(FixedString<5>)은 오직 5-char만 받음. template 함수로 N 추론하게.

#정리

  • FixedString<N>은 N+1 char buffer + size의 constexpr 문자열.
  • 모든 연산이 constexpr — compile-time concat, hash, substr.
  • heap 없음, exception 없음.
  • 런타임 길이가 가변이면 다른 type.
  • C++26 constexpr std::string 표준화 전까지의 best practice.

#다음 편

AtomicHashMap은 lock-free read가 가능한 hash map이다. append-only 제약 하에서 어떻게 동작하는지.

#관련 항목

Folly Code Review · 37 of 89

  1. 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
  2. 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
  3. 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
  4. 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
  5. 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
  6. 6 Folly production validation 문화 — peta-scale에서 단련된 코드
  7. 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
  8. 8 folly::Promise·makeFuture — Future를 만드는 두 길
  9. 9 folly::SemiFuture vs Future — executor binding의 명시화
  10. 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
  11. 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
  12. 12 folly::Future retry·window·via — 제어 흐름 조합자
  13. 13 folly::fibers 분석 — M:N stackful coroutine
  14. 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
  15. 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
  16. 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
  17. 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
  18. 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
  19. 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
  20. 20 folly::IOBufQueue — chain의 push/pull 추상화
  21. 21 folly::io::Cursor·RWCursor — chain 위의 stream
  22. 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
  23. 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
  24. 24 folly::FBString 분석 — SSO + COW 구현
  25. 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
  26. 26 folly::StringPiece — string_view 호환 분석
  27. 27 folly Join·Split utilities — 문자열 분해와 결합
  28. 28 folly::to·tryTo — text↔num 변환 분석
  29. 29 folly Conv Customization — 사용자 타입 지원
  30. 30 folly Conv 성능 비교 — sprintf·stringstream 대비
  31. 31 folly::F14ValueMap vs std::unordered_map
  32. 32 folly::F14NodeMap — stable pointer가 필요할 때
  33. 33 folly::F14VectorMap — cache-friendly iteration
  34. 34 folly::F14FastMap — auto-select 동작
  35. 35 folly F14 internals — SIMD probing 메커니즘
  36. 36 folly::small_vector — inline storage 분석
  37. 37 folly::FixedString — compile-time string
  38. 38 folly::AtomicHashMap — lock-free read 분석
  39. 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
  40. 40 folly::EvictingCacheMap — LRU 구현 분석
  41. 41 folly::Synchronized — lock wrapper 패턴
  42. 42 folly::SharedMutex 분석
  43. 43 folly::Baton — one-shot wait 동기화
  44. 44 folly::RWSpinLock 분석
  45. 45 folly::PicoSpinLock — 1-byte spinlock
  46. 46 folly::ProducerConsumerQueue — SPSC 큐 분석
  47. 47 folly::MPMCQueue — multi-producer multi-consumer
  48. 48 folly::UnboundedQueue — 동적 크기 lock-free
  49. 49 folly::fibers::Channel — Go-like channel
  50. 50 folly::dynamic — JSON-like dynamic type 분석
  51. 51 folly JSON conversion — toJson·parseJson
  52. 52 folly dynamic ↔ struct — manual marshaling
  53. 53 folly dynamic Visitor pattern — type별 분기
  54. 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
  55. 55 folly::SingletonVault 분석 — 등록·소멸·의존성
  56. 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
  57. 57 folly::ExceptionWrapper — type-erased exception holder
  58. 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
  59. 59 folly::Optional vs std::optional
  60. 60 folly::Function vs std::function
  61. 61 folly::Lazy — 지연 초기화 wrapper
  62. 62 folly Meta 스타일 code review 패턴
  63. 63 folly anti-patterns — 잘못 쓰면 std보다 느림
  64. 64 folly vs std 선택 기준 분석
  65. 65 folly::coro 개요 — production C++20 코루틴 어댑터
  66. 66 folly::coro::Task — lazy single-shot 코루틴
  67. 67 folly::coro::AsyncGenerator — 비동기 스트림
  68. 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
  69. 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
  70. 70 folly::Expected — 결과 또는 오류
  71. 71 folly::Try — Future 결과 wrapper
  72. 72 folly::Try vs Expected 선택 기준
  73. 73 folly::Range — 일반 iterator pair
  74. 74 folly::Uri — URL 파서
  75. 75 folly Fingerprint64·128 — 분산 hash
  76. 76 folly SpookyHashV2 — fast non-crypto hash
  77. 77 folly::Init — main() 부트스트랩
  78. 78 folly::Indestructible — global lifetime 패턴
  79. 79 folly::MicroLock — 1-byte 락
  80. 80 folly::MicroSpinLock — 가장 좁은 spin lock
  81. 81 folly::format — legacy formatter 분석
  82. 82 folly::demangle — typeid 디망글링
  83. 83 folly::DynamicConverter — dynamic ↔ struct
  84. 84 folly::RecordIO — append-only 로그 파일 포맷
  85. 85 folly::io::Compression — zstd·lz4·snappy wrapper
  86. 86 folly::AsyncIO — io_uring·Linux AIO
  87. 87 folly::CancellationToken — 코루틴·Future 취소 전파
  88. 88 folly::observer — hot config의 atomic refresh
  89. 89 fbcode 패턴 모음 — folly 사용의 실전