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

folly::format — legacy formatter 분석

· Hawk · 4분 읽기

한 줄 요약: folly::format은 fmt와 std::format이 표준에 들어오기 전의 type-safe formatter다. 새 코드는 fmt/std::format을 쓰되 fbcode에 깊이 박힌 legacy folly::format을 어떻게 마이그레이션하는지 안다.

#동기

C++ formatter의 역사는 셋이다.

  1. printf — type-unsafe, format string과 인자가 컴파일러 체크 안 됨.
  2. iostream — type-safe지만 verbose, locale 동작 미묘.
  3. type-safe formatter — Python-style {} 플레이스홀더. 컴파일 타임 체크.

Folly는 2014~2015년경 자체 formatter folly::format을 만들었다. 같은 시기에 외부 fmt 라이브러리(Victor Zverovich)가 성장 중이었고, fmt가 결국 C++20 std::format으로 표준화됐다. 그래서 folly 내부에는 두 세대가 공존한다.

시점도구
~2015folly::format 도입
2015~2020folly가 fmt를 의존성으로 통합 (Part 5-02)
2020+std::format 표준화
현재folly 새 코드는 fmt, 레거시 코드는 folly::format 잔존

#API

#include <folly/Format.h>
// 1. format → folly::Formatter (operator<<로 출력 가능)
std::cout << folly::format("hello {}, {}\n", name, age);
// 2. format → fbstring (str())
auto s = folly::format("x={}, y={}", x, y).str();
// 3. format → append to string buffer
folly::format(&buffer, "value = {}", v); // buffer(std::string)에 append
// 4. positional
auto a = folly::format("{0}-{1}-{0}", "x", "y").str(); // "x-y-x"
// 5. width/precision
auto b = folly::format("{:>10}", "hi").str(); // " hi"
auto c = folly::format("{:.3f}", 3.14159).str(); // "3.142"

표층 API는 std::format/fmt::format과 유사. Python-style {} 플레이스홀더.

#차이점

// folly::format → Formatter 객체 반환 (lazy)
auto fmt = folly::format("x={}", x);
std::cout << fmt; // 이 시점에 format 수행
auto s = fmt.str(); // 또는 str() 호출
// fmt::format / std::format → string 반환 (eager)
auto s2 = fmt::format("x={}", x); // 즉시 std::string

folly::formatlazy다. operator<<나 .str()이 호출돼야 실제 포맷팅. 한 번 만들고 여러 sink에 출력 가능한 장점, 그러나 형식 검사가 lazy하다는 단점.

std::format / fmt::formateager. 즉시 string 생성, compile-time 검사 가능.

#내부 구현 개요

// folly/Format.h 약식
template <bool ContainerMode, class... Args>
class Formatter {
public:
Formatter(StringPiece fmt, Args&&... args)
: fmt_(fmt), args_(std::forward<Args>(args)...) {}
template <class Out>
void operator()(Out& out) const {
// 1. fmt_ 파싱 (runtime)
// 2. 각 {}에 args_의 해당 element를 변환
// 3. out에 write
}
fbstring str() const {
fbstring s;
auto adapter = stringAppender(s);
(*this)(adapter);
return s;
}
};

핵심은 runtime parsing. format string 안의 {}, {:>10} 같은 패턴을 호출 시점에 파싱. fmt/std::format은 컴파일러가 일부 검사 가능 (constexpr format string).

#std::format / fmt와의 비교

항목folly::formatfmt::formatstd::format (C++20)
시점20142014~2020
평가lazyeagereager
compile-time 검사강 (constexpr fmt)강 (std::format_string)
custom formatter가능fmt::formatter<T>std::formatter<T>
sinkiterator/Out callbackiteratorformat_to/back_inserter
표준folly외부std
의존성follyheader-onlystd lib
컴파일 시간보통

folly::format의 약점은 compile-time 검사. format string의 {} 수와 인자 수가 다르거나, 타입이 호환 안 될 때 runtime exception. fmt/std::format은 그걸 컴파일 타임에 잡는다.

// folly — runtime throw
folly::format("x={}, y={}", 42).str(); // y 인자 없음 → 예외
// std::format — compile error (C++20+)
auto s = std::format("x={}, y={}", 42); // 컴파일 안 됨

#마이그레이션 경로

// Before (legacy)
auto s = folly::format("{}-{}", a, b).str();
LOG(INFO) << folly::format("x={}, y={}", x, y);
// After (fmt)
auto s = fmt::format("{}-{}", a, b);
LOG(INFO) << fmt::format("x={}, y={}", x, y);
// After (std::format, C++20+)
auto s = std::format("{}-{}", a, b);

대부분 1

변환. 주의:

  • folly::formatlazy라 여러 sink에 나눠 출력하던 코드는 string 한 번 만들어 여러 sink에 보내야.
  • custom formatter는 folly::FormatValue<T>fmt::formatter<T> 또는 std::formatter<T> 재작성.
  • format string의 일부 확장 syntax (예: container 출력) 가 fmt에 없을 수 있음 — 호환 변환 필요.

#Custom formatter — folly 방식

// folly 방식
namespace folly {
template <>
class FormatValue<MyType> {
public:
explicit FormatValue(const MyType& v) : v_(v) {}
template <class FormatCallback>
void format(FormatArg& arg, FormatCallback& cb) const {
cb(folly::to<fbstring>(v_.toString()));
}
private:
const MyType& v_;
};
}
// fmt 방식
namespace fmt {
template <>
struct formatter<MyType> : formatter<std::string> {
template <class FormatContext>
auto format(const MyType& v, FormatContext& ctx) const {
return formatter<std::string>::format(v.toString(), ctx);
}
};
}

fmt 방식이 더 깔끔 — base formatter 상속으로 width/alignment 자동 처리.

#코드 리뷰 포인트

  • 새 코드에 folly::format 등장 → fmt 또는 std::format으로 변경 권유.
  • legacy 코드의 lazy 평가 의존이 있는지 — string으로 한 번에 만들어도 되는 코드인지 확인.
  • format string이 runtime concat (folly::format(prefix + "{}", x))인가 — compile-time 검사 의미 없음. fmt도 같은 한계.
  • custom FormatValue가 있으면 fmt::formatter 재작성.

#자주 보는 안티패턴

// 1. folly::format 객체를 보관 후 늦게 .str()
auto fmt = folly::format("x={}", x); // x가 reference로 캡처될 수도
sleep(100);
auto s = fmt.str(); // x가 살아있어야 — 위험
// 2. format string이 동적
std::string fmtStr = LoadTemplate();
folly::format(fmtStr, args...).str(); // compile-time 검사 불가능
// 3. exception 무시
auto s = folly::format("{} {}", x).str(); // arg 수 불일치 → 예외
// → catch 없으면 process abort

#std::format으로 가는 미래

C++20 std::format이 표준이 됐고 C++23에서 std::print/std::println도 들어왔다. fbcode가 점진적으로 다음 순서로 이동.

  1. 새 코드: fmt::format (사용 가능하면).
  2. C++20 사용 가능한 환경: std::format.
  3. legacy folly::format: 점진적 변환.

folly::format유지되지만 활발한 개선은 받지 않는다. 새 기능은 fmt/std에 의존.

#정리

  • folly::format은 fmt/std::format 이전 시대의 type-safe formatter.
  • lazy 평가, runtime parsing — fmt/std는 eager + compile-time 검사.
  • 새 코드는 fmt 또는 std::format 선택.
  • legacy 코드 마이그레이션은 대부분 1
    , custom formatter만 재작성.
  • folly::format이 fbcode에 깊이 박혀 있어 한동안 공존.

#다음 편

Part 19-02: folly::demangle에서 typeid 디망글링을 본다.

#관련 항목

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