[libc-commits] [libc] [libc] Template the writing mode for the writer class (PR #111559)

Michael Jones via libc-commits libc-commits at lists.llvm.org
Wed Mar 12 10:12:51 PDT 2025


================
@@ -92,40 +107,69 @@ struct WriteBuffer {
   // this with an empty string will flush the buffer if relevant.
 
   LIBC_INLINE int overflow_write(cpp::string_view new_str) {
-    switch (write_mode) {
-    case WriteMode::FILL_BUFF_AND_DROP_OVERFLOW:
+#ifdef LIBC_COPT_PRINTF_RUNTIME_DISPATCH
+    if (write_mode_ == WriteMode::FILL_BUFF_AND_DROP_OVERFLOW)
       return fill_remaining_to_buff(new_str);
-    case WriteMode::FLUSH_TO_STREAM:
+    else if (write_mode_ == WriteMode::FLUSH_TO_STREAM)
       return flush_to_stream(new_str);
-    case WriteMode::RESIZE_AND_FILL_BUFF:
+    else if (write_mode_ == WriteMode::RESIZE_AND_FILL_BUFF)
       return resize_and_write(new_str);
-    }
+#else
+    if constexpr (write_mode == WriteMode::FILL_BUFF_AND_DROP_OVERFLOW)
+      return fill_remaining_to_buff(new_str);
+    else if constexpr (write_mode == WriteMode::FLUSH_TO_STREAM)
+      return flush_to_stream(new_str);
+    else if constexpr (write_mode == WriteMode::RESIZE_AND_FILL_BUFF)
+      return resize_and_write(new_str);
+#endif
----------------
michaelrj-google wrote:

I think this might be better, if a bit confusing due to the similar variable names. This way the condition is actually expressed in the template instead of based on the compile flag.
```
  if constexpr(write_mode == WriteMode::RUNTIME_DISPATCH) {
    if (write_mode_ == WriteMode::FILL_BUFF_AND_DROP_OVERFLOW)
      return fill_remaining_to_buff(new_str);
    else if (write_mode_ == WriteMode::FLUSH_TO_STREAM)
      return flush_to_stream(new_str);
    else if (write_mode_ == WriteMode::RESIZE_AND_FILL_BUFF)
      return resize_and_write(new_str);
  } else {
    if constexpr (write_mode == WriteMode::FILL_BUFF_AND_DROP_OVERFLOW)
      return fill_remaining_to_buff(new_str);
    else if constexpr (write_mode == WriteMode::FLUSH_TO_STREAM)
      return flush_to_stream(new_str);
    else if constexpr (write_mode == WriteMode::RESIZE_AND_FILL_BUFF)
      return resize_and_write(new_str);
  }
```

https://github.com/llvm/llvm-project/pull/111559


More information about the libc-commits mailing list