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

folly의 fmt::format 통합 — 모던 포맷팅 채택

· Hawk · 3분 읽기

#한 줄 요약

Folly는 자체 folly::format을 거두고 {fmt}를 채택했다. sformat은 wrapper로 남았으나 새 코드는 fmt::format을 직접 쓰는 것이 정답이다.

#동기

C++20의 <format>{fmt}의 fork이지만 컴파일러 지원이 늦었고 매크로 디버깅이 어려웠다. Meta는 다음을 원했다.

  • printf의 성능, iostream의 type safety.
  • Python str.format 수준의 가독성.
  • locale 비의존 (data center에서 locale은 일관성을 깬다).
  • 사용자 타입에 대한 customization point.

초기에는 folly::sformat이 자체 구현이었으나 {fmt}가 더 빠르고 표준에 가까워지자 2018년경 dependency로 흡수했다. 지금은 folly/Format.h가 대부분 fmt로 forward 한다.

folly::sformat("user={} count={}", user, n); // 여전히 동작
fmt::format("user={} count={}", user, n); // 더 권장

#API & 사용법

#include <folly/Format.h>
#include <fmt/format.h>
// 1. 문자열 반환
std::string s = fmt::format("v={:.2f}", 3.14159); // "v=3.14"
// 2. 출력 stream에 쓰기
fmt::print(stderr, "[{}] {}\n", level, msg);
// 3. 미리 컴파일된 format
constexpr auto fmt_spec = FMT_COMPILE("id={} value={}");
auto s2 = fmt::format(fmt_spec, id, val); // 런타임 파싱 없음
// 4. 위치 인자
fmt::format("{1} > {0}", 10, 20); // "20 > 10"
// 5. 명명 인자 (folly::sformat 한정)
folly::sformat("{name} is {age}", FOLLY_FORMAT_NAMED(name, age));

folly::format은 lazy expression을 반환한다(operator<< 또는 .str() 호출 시 평가). fmt::format은 eager std::string을 반환한다. 일반 use case에서는 차이가 무의미하므로 후자가 단순하다.

#내부 구현

fmt의 핵심은 format string을 컴파일 타임에 파싱하고 type-erased writer로 출력하는 것이다.

// 약식
template <typename... Args>
std::string format(format_string<Args...> spec, Args&&... args) {
basic_memory_buffer<char> buf; // SSO 500-byte stack buffer
vformat_to(buf, spec, fmt::make_format_args(args...));
return std::string(buf.data(), buf.size());
}

format_string<Args...>consteval 생성자로 컴파일 타임 파싱하며, placeholder 수와 타입이 인자와 다르면 컴파일 에러가 난다. printf의 런타임 mismatch와 결정적으로 다르다.

make_format_args는 인자를 type tag + pointer 쌍의 작은 배열로 만든다. 평균 16 byte 정도라 stack에 머문다. virtual call 없이 switch로 dispatch한다.

#sformat vs fmt::format 성능

benchmark: format "user={} count={}" with string + int
fmt::format 28 ns
folly::sformat 40 ns (fmt에 위임 + folly wrapper)
ostringstream 450 ns
snprintf 120 ns

sformat은 wrapper overhead 약 12 ns. 새 코드는 fmt::format을 직접 호출해도 무방하다.

#Customization — 사용자 타입 formatter

특정 타입을 fmt가 출력하게 하려면 fmt::formatter 특화를 둔다.

struct UserId {
uint64_t value;
};
template <>
struct fmt::formatter<UserId> {
// 1. parse: 포맷 specifier 해석
constexpr auto parse(format_parse_context& ctx) {
auto it = ctx.begin(), end = ctx.end();
// {} 만 지원
if (it != end && *it != '}') throw format_error("invalid");
return it;
}
// 2. format: 실제 출력
template <typename FormatContext>
auto format(const UserId& u, FormatContext& ctx) const {
return fmt::format_to(ctx.out(), "U#{:016x}", u.value);
}
};
// 이제 자동 동작
fmt::format("id={}", UserId{0xabc}); // "id=U#0000000000000abc"

parse에서 추가 specifier({:short}, {:long})를 받으면 출력 형태를 사용자 정의할 수 있다. fbcode에서 folly::Range, folly::dynamic, folly::Optional이 이런 특화를 갖고 있다.

#Folly가 제공하는 formatter

fmt::format("{}", folly::StringPiece{"hi"}); // "hi"
fmt::format("{}", folly::dynamic{1, 2, 3}); // "[1,2,3]"
fmt::format("{}", folly::Range<int*>{arr, n}); // "[1, 2, 3]"

#std/abseil 비교

항목printf<format> (C++20)fmt::formatabsl::StrFormat
Type safety컴파일 X컴파일 O컴파일 O컴파일 O (absl::ParsedFormat)
사용자 타입Xformatter 특화formatter 특화AbslStringify
컴파일 시간짧음중간길음 (template-heavy)짧음
Locale의존선택비의존 (default)비의존
성능빠름fmt와 비슷매우 빠름매우 빠름
Header-onlyN/Astd선택컴파일 단위

absl::StrFormatprintf syntax를 쓰는 반면 fmt는 Python {} syntax다. fbcode/Meta는 후자를 선호한다.

#코드 리뷰 포인트

// Bad — 매번 format string 파싱
for (int i = 0; i < N; ++i) {
log_buf += fmt::format("[{}] ", i);
}
// Good — FMT_COMPILE로 컴파일 타임 파싱
constexpr auto spec = FMT_COMPILE("[{}] ");
for (int i = 0; i < N; ++i) {
fmt::format_to(std::back_inserter(log_buf), spec, i);
}

루프 안의 format은 hot path에서 FMT_COMPILE + format_to로 바꾸면 2-3배 빨라진다.

// Bad — format이 throw할 수 있음을 무시
auto s = fmt::format(user_input_fmt, value); // injection
// Good — 사용자 입력은 format string으로 쓰지 않는다
auto s = fmt::format("{}", value);

format string이 외부 입력이면 placeholder count mismatch로 fmt::format_error가 던져진다. injection 회피를 위해 format string은 항상 컴파일 타임 상수다.

#안티패턴

  • folly::format의 lazy expression을 그대로 함수에 전달: 평가 시점이 모호해진다. .str() 또는 fmt::format으로 즉시 문자열로 변환.
  • wide-char 출력에 fmt::format 사용: UTF-8 데이터에 wstring을 끼면 인코딩 변환 비용이 든다. UTF-8 표현은 std::string으로 유지하고 출력 단계에서만 변환.
  • 로그에 fmt::format 호출 후 즉시 버림: 로그 레벨 필터를 통과하지 못해도 format 호출은 일어난다. XLOG(INFO, "{}", val) 처럼 매크로 lazy form 사용.

#정리

  • {fmt}는 컴파일 타임 파싱 + type-safe placeholder로 printf 대체.
  • folly::sformat은 wrapper로 남아 호환성을 유지하나 새 코드는 fmt::format 권장.
  • 사용자 타입은 fmt::formatter 특화로 {} 안에 자유롭게 사용.
  • hot path는 FMT_COMPILE로 런타임 파싱 제거.
  • format string은 항상 컴파일 타임 상수, 사용자 입력은 인자로만.

#다음 편

다음은 folly::StringPiecestd::string_view와 어떻게 같고 다른지, 그리고 왜 둘 다 남아 있는지 본다.

#관련 항목

Folly Code Review · 25 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 사용의 실전