folly::io::Cursor·RWCursor — chain 위의 stream
한 줄 요약:
folly::io::Cursor는 IOBuf chain 위를 단일 byte stream처럼 순회한다. chain 경계를 자동으로 넘기고 endian-safe primitive read/write를 제공한다.
#동기 — chain 위 parse의 boilerplate
IOBuf chain을 직접 parse하면 chain 경계가 매번 문제다.
// chain 직접 — boilerplateuint32_t readU32(IOBuf* buf, size_t offset) { IOBuf* cur = buf; while (cur && offset >= cur->length()) { offset -= cur->length(); cur = cur->next(); } // cur에 [offset, offset+4)이 들어맞는지 확인 // 안 맞으면 다음 buffer로 넘어가서 합쳐서 읽기 ...}이 로직이 모든 primitive read마다 필요하다. Cursor는 이를 추상화한다.
#기본 사용
#include <folly/io/Cursor.h>
auto buf = ...; // IOBuf chain
folly::io::Cursor cur(buf.get());
uint32_t magic = cur.readBE<uint32_t>(); // big-endianuint8_t type = cur.read<uint8_t>();uint64_t size = cur.readLE<uint64_t>(); // little-endian
// 문자열 읽기std::string name = cur.readFixedString(16);
// 가변 길이auto body = std::make_unique<folly::IOBuf>(folly::IOBuf::create(size));cur.pull(body->writableTail(), size);body->append(size);
// 남은 길이size_t remaining = cur.totalLength();Cursor는 read-only다. write는 RWCursor를 쓴다(아래).
#핵심 메서드
// folly/io/Cursor.h (요약)class CursorBase { public: // peek (advance 안 함) template <class T> T peekBE() const; template <class T> T peekLE() const; template <class T> T peek() const;
// read (advance) template <class T> T readBE(); template <class T> T readLE(); template <class T> T read();
// pull bytes void pull(void* buf, size_t n); size_t pullAtMost(void* buf, size_t n);
// skip void skip(size_t n); size_t skipAtMost(size_t n);
// clone — 같은 chain, 다른 cursor CursorBase clone() const;
// accessors size_t totalLength() const; bool isAtEnd() const;};#RWCursor — write 가능 Cursor
#include <folly/io/Cursor.h>
auto buf = folly::IOBuf::create(1024);buf->append(64); // 64 bytes 영역 확보
folly::io::RWCursor cur(buf.get());
cur.writeBE<uint32_t>(0xDEADBEEF);cur.writeBE<uint32_t>(0x12345678);cur.write<uint8_t>(0xFF);RWCursor는 기존 IOBuf의 data를 덮어쓴다. 새 buffer를 만들지 않는다. data가 chain 경계에 걸치면 각 buffer에 부분적으로 쓴다.
#QueueAppender — 늘려 쓰는 cursor
folly::IOBufQueue q;folly::io::QueueAppender app(&q, 4096); // chunk 4096
app.writeBE<uint32_t>(0xDEADBEEF);app.push(reinterpret_cast<const uint8_t*>("hello"), 5);app.write<uint8_t>(0xFF);
// q에 모두 들어감QueueAppender는 queue를 늘려가며 쓴다. tailroom이 부족하면 새 IOBuf를 만들어 chain에 추가한다. protocol message serializer의 표준 구현이다.
#endian-safe primitive
// 네트워크 byte order = big-endiancur.writeBE<uint16_t>(port);cur.writeBE<uint32_t>(addr);
// 일부 protocol은 little-endian (Windows API 등)cur.writeLE<uint64_t>(timestamp);
// host-endian (보통 little)cur.write<uint32_t>(localValue);readBE/writeBE는 내부적으로 __builtin_bswap32 등을 사용한다. portability 보장.
#실전 — protocol parser
struct Header { uint32_t magic; uint8_t version; uint8_t type; uint16_t flags; uint32_t length;};
Header parseHeader(folly::IOBufQueue& q) { if (q.chainLength() < sizeof(Header)) { throw std::runtime_error("not enough data"); } folly::io::Cursor cur(q.front()); Header h; h.magic = cur.readBE<uint32_t>(); h.version = cur.read<uint8_t>(); h.type = cur.read<uint8_t>(); h.flags = cur.readBE<uint16_t>(); h.length = cur.readBE<uint32_t>(); return h;}queue에서 header만 peek하고 body는 split으로 빼내는 패턴이다.
#skip vs pull
// pull — buffer로 복사char temp[64];cur.pull(temp, 64);
// skip — 그냥 건너뜀cur.skip(64);
// pullAtMost — 부분도 OKsize_t n = cur.pullAtMost(temp, 64);
// skipAtMost — 마찬가지size_t skipped = cur.skipAtMost(64);unrecognized field를 처리 없이 넘길 때 skip이 효율적이다.
#clone — 같은 위치에서 분기
auto cur1 = folly::io::Cursor(buf.get());
auto magic = cur1.peekBE<uint32_t>();if (magic == kVersion1) { parseV1(cur1);} else { // 다른 parsing 시도 auto cur2 = cur1.clone(); parseV2(cur2); // cur1은 여전히 원래 위치 유지}clone()은 같은 chain의 다른 cursor를 만든다. ref-count 증가 없이, 단순히 같은 위치를 가리킨다.
#std::istream과 비교
std::istream은 char by char를 읽지만 IOBuf chain을 직접 다루지 못한다. byte buffer 전체를 미리 합쳐야 한다.
| 항목 | std::istream | folly::io::Cursor |
|---|---|---|
| 입력 | flat byte buffer | IOBuf chain |
| endian | 사용자가 직접 | readBE/readLE |
| zero-copy | 불가 | 자연스러움 |
| peek | .peek() (1 byte) | .peek<T>() |
| 분기 | tellg/seekg | clone |
Cursor가 훨씬 가볍고 표현적이다.
#코드 리뷰 포인트
- endian이 명시적인가?
read<T>()는 host-endian. network protocol이면readBE/readLE. pull후skip이 빠지진 않았는가? pull은 advance하지만 어떤 코드는 skip + pull을 섞는다.isAtEnd()체크? stream 끝에서 read하면 throw된다.RWCursor로 read-only buffer를 쓰지 않았는가? clone()된 buffer 쓰면 ref-count share buffer를 mutate.
#자주 보는 안티패턴
// 1. endian 잘못cur.read<uint32_t>(); // host-endian — network protocol이면 BE 필요
// 2. 길이 검증 없이 readauto h = cur.read<Header>(); // 모자라면 throw — 부분 도착 처리 안 됨// 옳음:if (cur.totalLength() < sizeof(Header)) return std::nullopt;
// 3. RWCursor + cloned bufferauto cloned = buf->clone();folly::io::RWCursor cur(cloned.get());cur.writeBE<uint32_t>(0); // 원본 buf의 data도 바뀜 — share
// 4. struct를 raw readstruct Pkt { uint32_t a; uint64_t b; };auto p = cur.read<Pkt>(); // padding/alignment 위험 — 필드별로 읽자#정리
folly::io::Cursor는 IOBuf chain을 단일 stream처럼 read한다. chain 경계를 자동으로 넘긴다.RWCursor는 기존 chain을 덮어 쓴다.QueueAppender는 queue를 늘려가며 쓴다.- endian-safe primitive(
readBE/writeBE/readLE/writeLE)를 제공한다. clone()으로 같은 위치에서 분기 parsing이 가능하다.skip/pull을 적절히 섞어 unrecognized field를 효율적으로 처리한다.- protocol parser/serializer의 표준 도구다.
#다음 편
Part 4-04: Zero-copy 패턴에서 IOBuf 기반 zero-copy 송수신 패턴을 본다.
#관련 항목
Folly Code Review · 21 of 89
- 1 Folly Code Review — Meta의 production-grade C++ 라이브러리 코드 분석
- 2 Folly 개요 — Meta가 production에서 검증한 utility 모음 분석
- 3 Folly vs Abseil 철학 비교 — performance-first vs std-compatible
- 4 Folly 빌드와 fbcode 환경 — monorepo의 그림자
- 5 Folly API stability 정책 — 어떤 보장도 없다는 솔직함
- 6 Folly production validation 문화 — peta-scale에서 단련된 코드
- 7 folly::Future 분석 — std::future의 한계를 넘는 composable async
- 8 folly::Promise·makeFuture — Future를 만드는 두 길
- 9 folly::SemiFuture vs Future — executor binding의 명시화
- 10 folly::Future thenValue·thenError·thenTry — continuation 체인 분석
- 11 folly::collect·collectAll·collectAny — fan-in 패턴 분석
- 12 folly::Future retry·window·via — 제어 흐름 조합자
- 13 folly::fibers 분석 — M:N stackful coroutine
- 14 folly::InlineExecutor — 호출자 thread에서 즉시 실행
- 15 folly::CPUThreadPoolExecutor — CPU-bound 작업의 표준 thread pool
- 16 folly::IOThreadPoolExecutor — libevent 기반 I/O pool
- 17 folly::ManualExecutor — 결정적 테스트를 위한 수동 진행
- 18 folly::EventBase 분석 — libevent 이벤트 루프의 핵심
- 19 folly::IOBuf 분석 — zero-copy buffer chain의 기본 단위
- 20 folly::IOBufQueue — chain의 push/pull 추상화
- 21 folly::io::Cursor·RWCursor — chain 위의 stream
- 22 folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
- 23 folly::IOBuf shared semantics — clone·unshare·takeOwnership
- 24 folly::FBString 분석 — SSO + COW 구현
- 25 folly의 fmt::format 통합 — 모던 포맷팅 채택
- 26 folly::StringPiece — string_view 호환 분석
- 27 folly Join·Split utilities — 문자열 분해와 결합
- 28 folly::to·tryTo — text↔num 변환 분석
- 29 folly Conv Customization — 사용자 타입 지원
- 30 folly Conv 성능 비교 — sprintf·stringstream 대비
- 31 folly::F14ValueMap vs std::unordered_map
- 32 folly::F14NodeMap — stable pointer가 필요할 때
- 33 folly::F14VectorMap — cache-friendly iteration
- 34 folly::F14FastMap — auto-select 동작
- 35 folly F14 internals — SIMD probing 메커니즘
- 36 folly::small_vector — inline storage 분석
- 37 folly::FixedString — compile-time string
- 38 folly::AtomicHashMap — lock-free read 분석
- 39 folly::ConcurrentHashMap — sharded 동시 해시 맵
- 40 folly::EvictingCacheMap — LRU 구현 분석
- 41 folly::Synchronized — lock wrapper 패턴
- 42 folly::SharedMutex 분석
- 43 folly::Baton — one-shot wait 동기화
- 44 folly::RWSpinLock 분석
- 45 folly::PicoSpinLock — 1-byte spinlock
- 46 folly::ProducerConsumerQueue — SPSC 큐 분석
- 47 folly::MPMCQueue — multi-producer multi-consumer
- 48 folly::UnboundedQueue — 동적 크기 lock-free
- 49 folly::fibers::Channel — Go-like channel
- 50 folly::dynamic — JSON-like dynamic type 분석
- 51 folly JSON conversion — toJson·parseJson
- 52 folly dynamic ↔ struct — manual marshaling
- 53 folly dynamic Visitor pattern — type별 분기
- 54 folly::Singleton vs Meyers/static — 왜 Folly의 Singleton인가
- 55 folly::SingletonVault 분석 — 등록·소멸·의존성
- 56 folly::Singleton try_get·try_get_fast — TLS-cached 접근
- 57 folly::ExceptionWrapper — type-erased exception holder
- 58 folly::ScopeGuard·SCOPE_EXIT — RAII cleanup
- 59 folly::Optional vs std::optional
- 60 folly::Function vs std::function
- 61 folly::Lazy — 지연 초기화 wrapper
- 62 folly Meta 스타일 code review 패턴
- 63 folly anti-patterns — 잘못 쓰면 std보다 느림
- 64 folly vs std 선택 기준 분석
- 65 folly::coro 개요 — production C++20 코루틴 어댑터
- 66 folly::coro::Task — lazy single-shot 코루틴
- 67 folly::coro::AsyncGenerator — 비동기 스트림
- 68 folly coro blockingWait·collectAll — 동기 경계와 fan-in
- 69 folly::coro::Baton·Mutex — 코루틴-aware 동기화
- 70 folly::Expected — 결과 또는 오류
- 71 folly::Try — Future 결과 wrapper
- 72 folly::Try vs Expected 선택 기준
- 73 folly::Range — 일반 iterator pair
- 74 folly::Uri — URL 파서
- 75 folly Fingerprint64·128 — 분산 hash
- 76 folly SpookyHashV2 — fast non-crypto hash
- 77 folly::Init — main() 부트스트랩
- 78 folly::Indestructible — global lifetime 패턴
- 79 folly::MicroLock — 1-byte 락
- 80 folly::MicroSpinLock — 가장 좁은 spin lock
- 81 folly::format — legacy formatter 분석
- 82 folly::demangle — typeid 디망글링
- 83 folly::DynamicConverter — dynamic ↔ struct
- 84 folly::RecordIO — append-only 로그 파일 포맷
- 85 folly::io::Compression — zstd·lz4·snappy wrapper
- 86 folly::AsyncIO — io_uring·Linux AIO
- 87 folly::CancellationToken — 코루틴·Future 취소 전파
- 88 folly::observer — hot config의 atomic refresh
- 89 fbcode 패턴 모음 — folly 사용의 실전
관련 글
folly::coro::AsyncGenerator — 비동기 스트림
AsyncGenerator<T>의 pull-based 모델, co_yield, for co_await — 비동기 iterator의 표준 후보 패턴.
같은 시리즈에서 이어 읽기
folly::IOBuf shared semantics — clone·unshare·takeOwnership
IOBuf의 ref-count는 buffer share를 표현한다. clone/unshare/takeOwnership의 의미를 정확히 이해해야 zero-copy가 안전하다.
같은 시리즈에서 이어 읽기
folly Zero-copy 패턴 — IOBuf로 ScatterGather I/O 표현
IOBuf chain을 직접 writev/readv에 넘기고, splice/sendfile과 결합해 zero-copy 송수신 파이프라인을 구성한다.
같은 시리즈에서 이어 읽기