From 66ef5fdae13964c85d85ce7d7b3a27215d4abbd5 Mon Sep 17 00:00:00 2001 From: Timothy Stack Date: Wed, 16 Mar 2022 15:38:08 -0700 Subject: [PATCH] [clang-format] init --- .clang-format | 46 +- CMakeLists.txt | 2 +- conanfile.py | 1 + src/CMakeLists.txt | 784 +- src/all_logs_vtab.cc | 52 +- src/all_logs_vtab.hh | 19 +- src/ansi_scrubber.cc | 52 +- src/ansi_scrubber.hh | 34 +- src/archive_manager.cc | 130 +- src/archive_manager.cfg.hh | 6 +- src/archive_manager.hh | 31 +- src/attr_line.cc | 110 +- src/attr_line.hh | 253 +- src/auto_fd.hh | 137 +- src/auto_mem.hh | 124 +- src/base/auto_pid.cc | 19 +- src/base/auto_pid.hh | 85 +- src/base/date_time_scanner.cc | 96 +- src/base/date_time_scanner.hh | 50 +- src/base/enum_util.hh | 13 +- src/base/file_range.hh | 19 +- src/base/fs_util.cc | 25 +- src/base/fs_util.hh | 30 +- src/base/func_util.hh | 31 +- src/base/future_util.hh | 23 +- src/base/humanize.cc | 32 +- src/base/humanize.file_size.tests.cc | 14 +- src/base/humanize.hh | 6 +- src/base/humanize.network.cc | 19 +- src/base/humanize.network.hh | 58 +- src/base/humanize.network.tests.cc | 25 +- src/base/humanize.time.cc | 73 +- src/base/humanize.time.hh | 26 +- src/base/humanize.time.tests.cc | 72 +- src/base/injector.bind.hh | 78 +- src/base/injector.hh | 104 +- src/base/intern_string.cc | 50 +- src/base/intern_string.hh | 301 +- src/base/intern_string.tests.cc | 15 +- src/base/is_utf8.cc | 268 +- src/base/is_utf8.hh | 7 +- src/base/isc.cc | 59 +- src/base/isc.hh | 103 +- src/base/lnav.gzip.cc | 53 +- src/base/lnav.gzip.hh | 14 +- src/base/lnav.gzip.tests.cc | 22 +- src/base/lnav_log.cc | 309 +- src/base/lnav_log.hh | 82 +- src/base/math_util.hh | 13 +- src/base/network.tcp.cc | 29 +- src/base/network.tcp.hh | 30 +- src/base/network.tcp.tests.cc | 12 +- src/base/opt_util.hh | 70 +- src/base/paths.cc | 40 +- src/base/paths.hh | 8 +- src/base/string_util.cc | 78 +- src/base/string_util.hh | 86 +- src/base/string_util.tests.cc | 26 +- src/base/test_base.cc | 4 +- src/base/time_util.cc | 76 +- src/base/time_util.hh | 75 +- src/big_array.hh | 63 +- src/bin2c.hh | 23 +- src/bookmarks.cc | 8 +- src/bookmarks.hh | 86 +- src/bottom_status_source.cc | 113 +- src/bottom_status_source.hh | 35 +- src/bound_tags.hh | 13 +- src/byte_array.hh | 35 +- src/collation-functions.cc | 113 +- src/column_namer.cc | 39 +- src/column_namer.hh | 10 +- src/command_executor.cc | 374 +- src/command_executor.hh | 121 +- src/curl_looper.cc | 115 +- src/curl_looper.hh | 114 +- src/data_parser.cc | 344 +- src/data_parser.hh | 322 +- src/data_scanner.cc | 467 +- src/data_scanner.hh | 37 +- src/data_scanner_re.cc | 163226 ++++++++++++------------ src/db_sub_source.cc | 226 +- src/db_sub_source.hh | 71 +- src/doc_status_source.hh | 22 +- src/elem_to_json.cc | 102 +- src/elem_to_json.hh | 11 +- src/environ_vtab.cc | 236 +- src/environ_vtab.hh | 8 +- src/extension-functions.cc | 3672 +- src/field_overlay_source.cc | 388 +- src/field_overlay_source.hh | 48 +- src/file_collection.cc | 251 +- src/file_collection.hh | 64 +- src/file_format.cc | 71 +- src/file_format.hh | 8 +- src/file_vtab.cc | 95 +- src/file_vtab.cfg.hh | 6 +- src/files_sub_source.cc | 352 +- src/files_sub_source.hh | 60 +- src/filter_observer.cc | 30 +- src/filter_observer.hh | 55 +- src/filter_status_source.cc | 170 +- src/filter_status_source.hh | 21 +- src/filter_sub_source.cc | 334 +- src/filter_sub_source.hh | 42 +- src/fs-extension-functions.cc | 221 +- src/fstat_vtab.cc | 88 +- src/fstat_vtab.hh | 6 +- src/fts_fuzzy_match.cc | 345 +- src/fts_fuzzy_match.hh | 47 +- src/grep_highlighter.hh | 8 +- src/grep_proc.cc | 139 +- src/grep_proc.hh | 167 +- src/help_text.cc | 47 +- src/help_text.hh | 105 +- src/help_text_formatter.cc | 290 +- src/help_text_formatter.hh | 31 +- src/highlighter.cc | 66 +- src/highlighter.hh | 46 +- src/hist_source.cc | 97 +- src/hist_source.hh | 191 +- src/hotkeys.cc | 540 +- src/hotkeys.hh | 8 +- src/input_dispatcher.cc | 63 +- src/input_dispatcher.hh | 30 +- src/json-extension-functions.cc | 596 +- src/line_buffer.cc | 404 +- src/line_buffer.hh | 172 +- src/listview_curses.cc | 351 +- src/listview_curses.hh | 291 +- src/lnav.cc | 1635 +- src/lnav.hh | 256 +- src/lnav_commands.cc | 4196 +- src/lnav_commands.hh | 6 +- src/lnav_config.cc | 1047 +- src/lnav_config.hh | 38 +- src/lnav_config_fwd.hh | 19 +- src/lnav_util.cc | 34 +- src/lnav_util.hh | 132 +- src/log_accel.cc | 33 +- src/log_accel.hh | 18 +- src/log_actions.cc | 62 +- src/log_actions.hh | 28 +- src/log_data_helper.cc | 74 +- src/log_data_helper.hh | 38 +- src/log_data_table.cc | 89 +- src/log_data_table.hh | 30 +- src/log_format.cc | 1569 +- src/log_format.hh | 263 +- src/log_format_ext.hh | 190 +- src/log_format_fwd.hh | 218 +- src/log_format_impls.cc | 916 +- src/log_format_loader.cc | 805 +- src/log_format_loader.hh | 35 +- src/log_gutter_source.hh | 26 +- src/log_level.cc | 60 +- src/log_level.hh | 31 +- src/log_level_re.cc | 1034 +- src/log_search_table.cc | 59 +- src/log_search_table.hh | 22 +- src/log_vtab_impl.cc | 1082 +- src/log_vtab_impl.hh | 100 +- src/logfile.cc | 275 +- src/logfile.cfg.hh | 8 +- src/logfile.hh | 277 +- src/logfile_fwd.hh | 34 +- src/logfile_stats.hh | 4 +- src/logfile_sub_source.cc | 764 +- src/logfile_sub_source.hh | 480 +- src/network-extension-functions.cc | 131 +- src/papertrail_proc.cc | 107 +- src/papertrail_proc.hh | 117 +- src/pcap_manager.cc | 70 +- src/pcap_manager.hh | 15 +- src/pcrepp/CMakeLists.txt | 4 + src/pcrepp/pcrepp.cc | 119 +- src/pcrepp/pcrepp.hh | 380 +- src/pcrepp/test_pcrepp.cc | 37 +- src/piper_proc.cc | 210 +- src/piper_proc.hh | 24 +- src/plain_text_source.hh | 70 +- src/plugins.hh | 9 +- src/pretty_printer.cc | 81 +- src/pretty_printer.hh | 37 +- src/preview_status_source.hh | 21 +- src/ptimec.hh | 500 +- src/ptimec_rt.cc | 130 +- src/readline_callbacks.cc | 596 +- src/readline_callbacks.hh | 30 +- src/readline_context.hh | 75 +- src/readline_curses.cc | 886 +- src/readline_curses.hh | 202 +- src/readline_highlighters.cc | 561 +- src/readline_highlighters.hh | 12 +- src/readline_possibilities.cc | 228 +- src/readline_possibilities.hh | 19 +- src/regexp_vtab.cc | 139 +- src/regexp_vtab.hh | 6 +- src/relative_time.cc | 404 +- src/relative_time.hh | 74 +- src/remote/remote.ssh.cc | 10 +- src/remote/remote.ssh.hh | 6 +- src/ring_span.hh | 834 +- src/sequence_matcher.cc | 34 +- src/sequence_matcher.hh | 32 +- src/sequence_sink.hh | 38 +- src/service_tags.hh | 18 +- src/session_data.cc | 1032 +- src/session_data.hh | 4 +- src/shared_buffer.cc | 36 +- src/shared_buffer.hh | 87 +- src/shlex.cc | 52 +- src/shlex.hh | 82 +- src/shlex.resolver.hh | 16 +- src/spectro_source.cc | 176 +- src/spectro_source.hh | 86 +- src/sql_commands.cc | 117 +- src/sql_help.hh | 13 +- src/sql_util.cc | 497 +- src/sql_util.hh | 84 +- src/sqlite-extension-func.cc | 1340 +- src/sqlite-extension-func.hh | 69 +- src/sqlitepp.hh | 6 +- src/state-extension-functions.cc | 96 +- src/statusview_curses.cc | 96 +- src/statusview_curses.hh | 161 +- src/string-extension-functions.cc | 510 +- src/string_attr_type.cc | 8 +- src/string_attr_type.hh | 13 +- src/strong_int.hh | 52 +- src/styling.cc | 143 +- src/styling.hh | 70 +- src/sysclip.cc | 79 +- src/sysclip.cfg.hh | 66 +- src/sysclip.hh | 62 +- src/tailer/drive_tailer.cc | 111 +- src/tailer/tailer.looper.cc | 476 +- src/tailer/tailer.looper.cfg.hh | 6 +- src/tailer/tailer.looper.hh | 54 +- src/tailer/tailerpp.cc | 37 +- src/tailer/tailerpp.hh | 180 +- src/term_extra.hh | 45 +- src/termios_guard.hh | 21 +- src/text_format.cc | 42 +- src/text_format.hh | 19 +- src/textfile_highlighters.cc | 811 +- src/textfile_highlighters.hh | 6 +- src/textfile_sub_source.cc | 111 +- src/textfile_sub_source.hh | 68 +- src/textview_curses.cc | 417 +- src/textview_curses.hh | 542 +- src/textview_curses_fwd.hh | 7 +- src/time-extension-functions.cc | 113 +- src/time_T.hh | 31 +- src/timer.cc | 48 +- src/timer.hh | 47 +- src/tools/bin2c.c | 133 +- src/top_status_source.cc | 66 +- src/top_status_source.hh | 20 +- src/top_sys_status_source.hh | 15 +- src/unique_path.cc | 45 +- src/unique_path.hh | 22 +- src/url_loader.hh | 66 +- src/view_curses.cc | 683 +- src/view_curses.hh | 227 +- src/view_helpers.cc | 375 +- src/view_helpers.examples.hh | 8 +- src/view_helpers.hh | 27 +- src/views_vtab.cc | 371 +- src/views_vtab.hh | 6 +- src/vis_line.hh | 6 +- src/vt52_curses.cc | 206 +- src/vt52_curses.hh | 100 +- src/vtab_module.cc | 8 +- src/vtab_module.hh | 521 +- src/vtab_module_json.hh | 13 +- src/xml_util.cc | 20 +- src/xml_util.hh | 8 +- src/xpath_vtab.cc | 152 +- src/xpath_vtab.hh | 6 +- src/xterm_mouse.cc | 35 +- src/xterm_mouse.hh | 54 +- src/yajl/CMakeLists.txt | 27 + src/yajlpp/CMakeLists.txt | 23 + src/yajlpp/drive_json_op.cc | 99 +- src/yajlpp/drive_json_ptr_walk.cc | 34 +- src/yajlpp/json_op.cc | 129 +- src/yajlpp/json_op.hh | 47 +- src/yajlpp/json_ptr.cc | 214 +- src/yajlpp/json_ptr.hh | 128 +- src/yajlpp/test_json_ptr.cc | 10 +- src/yajlpp/test_yajlpp.cc | 47 +- src/yajlpp/yajlpp.cc | 427 +- src/yajlpp/yajlpp.hh | 413 +- src/yajlpp/yajlpp_def.hh | 506 +- test/CMakeLists.txt | 40 +- test/aftest.cc | 56 +- test/drive_data_scanner.cc | 129 +- test/drive_grep_proc.cc | 68 +- test/drive_line_buffer.cc | 319 +- test/drive_listview.cc | 85 +- test/drive_logfile.cc | 194 +- test/drive_mvwattrline.cc | 81 +- test/drive_readline_curses.cc | 122 +- test/drive_sequencer.cc | 187 +- test/drive_shlexer.cc | 41 +- test/drive_sql.cc | 40 +- test/drive_sql_anno.cc | 16 +- test/drive_view_colors.cc | 135 +- test/drive_vt52_curses.cc | 156 +- test/gp_test.cc | 92 +- test/lb_test.cc | 49 +- test/lnav_doctests.cc | 55 +- test/rltest.cc | 273 +- test/scripty.cc | 392 +- test/si_test.cc | 22 +- test/slicer.cc | 26 +- test/test_abbrev.cc | 23 +- test/test_ansi_scrubber.cc | 14 +- test/test_auto_fd.cc | 38 +- test/test_auto_mem.cc | 35 +- test/test_bookmarks.cc | 156 +- test/test_date_time_scanner.cc | 65 +- test/test_grep_proc2.cc | 132 +- test/test_line_buffer2.cc | 34 +- test/test_log_accel.cc | 32 +- test/test_ncurses_unicode.cc | 20 +- test/test_reltime.cc | 173 +- test/test_stubs.cc | 39 +- test/test_top_status.cc | 27 +- 330 files changed, 114173 insertions(+), 105847 deletions(-) create mode 100644 src/yajl/CMakeLists.txt create mode 100644 src/yajlpp/CMakeLists.txt diff --git a/.clang-format b/.clang-format index 3f4f7735..5eeefee7 100644 --- a/.clang-format +++ b/.clang-format @@ -1,12 +1,12 @@ --- Language: Cpp # BasedOnStyle: Chromium -AccessModifierOffset: -2 +AccessModifierOffset: -4 AlignAfterOpenBracket: Align -AlignConsecutiveMacros: false -AlignConsecutiveAssignments: false -AlignConsecutiveBitFields: false -AlignConsecutiveDeclarations: false +AlignConsecutiveMacros: Consecutive +AlignConsecutiveAssignments: None +AlignConsecutiveBitFields: None +AlignConsecutiveDeclarations: None AlignEscapedNewlines: DontAlign AlignOperands: DontAlign AlignTrailingComments: false @@ -20,38 +20,38 @@ AllowShortFunctionsOnASingleLine: Inline AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: Never AllowShortLoopsOnASingleLine: false -AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: None +# AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: TopLevelDefinitions AlwaysBreakBeforeMultilineStrings: true AlwaysBreakTemplateDeclarations: Yes BinPackArguments: false BinPackParameters: false BraceWrapping: AfterCaseLabel: false - AfterClass: true + AfterClass: false AfterControlStatement: MultiLine - AfterEnum: true + AfterEnum: false AfterFunction: true - AfterNamespace: true + AfterNamespace: false AfterObjCDeclaration: false - AfterStruct: true - AfterUnion: true + AfterStruct: false + AfterUnion: false AfterExternBlock: true BeforeCatch: false BeforeElse: false - BeforeLambdaBody: true + BeforeLambdaBody: false BeforeWhile: false IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true -BreakBeforeBinaryOperators: NonAssignment +BreakBeforeBinaryOperators: All BreakBeforeBraces: Custom # BreakBeforeInheritanceComma: true BreakInheritanceList: BeforeComma BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: true -BreakConstructorInitializers: BeforeComma +# BreakConstructorInitializersBeforeComma: true +BreakConstructorInitializers: BeforeColon BreakAfterJavaFieldAnnotations: true BreakStringLiterals: true ColumnLimit: 80 @@ -88,7 +88,7 @@ IndentCaseBlocks: false IndentGotoLabels: true IndentPPDirectives: AfterHash IndentExternBlock: NoIndent -IndentWidth: 2 +IndentWidth: 4 IndentWrappedFunctionNames: false InsertTrailingCommas: Wrapped JavaScriptQuotes: Double @@ -99,11 +99,11 @@ MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Never -ObjCBlockIndentWidth: 2 +ObjCBlockIndentWidth: 4 ObjCBreakBeforeNestedBlockParam: true ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true -PenaltyBreakAssignment: 2 +PenaltyBreakAssignment: 4 PenaltyBreakBeforeFirstCallParameter: 1 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 @@ -143,13 +143,13 @@ RawStringFormats: CanonicalDelimiter: '' BasedOnStyle: google ReflowComments: true -SortIncludes: true +SortIncludes: CaseInsensitive SortUsingDeclarations: true -SpaceAfterCStyleCast: false +SpaceAfterCStyleCast: true SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: false SpaceBeforeAssignmentOperators: true -SpaceBeforeCpp11BracedList: true +SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatementsExceptForEachMacros @@ -157,7 +157,7 @@ SpaceBeforeRangeBasedForLoopColon: true SpaceInEmptyBlock: false SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 2 -SpacesInAngles: false +SpacesInAngles: Never SpacesInConditionalStatement: false SpacesInContainerLiterals: false SpacesInCStyleCastParentheses: false diff --git a/CMakeLists.txt b/CMakeLists.txt index 296e0152..eb497dab 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,7 +35,7 @@ set(lnav_LIBS ) add_subdirectory(src) -add_subdirectory(test) +# add_subdirectory(test) # ---- Install rules ---- diff --git a/conanfile.py b/conanfile.py index ab55c927..dcf7896f 100644 --- a/conanfile.py +++ b/conanfile.py @@ -35,6 +35,7 @@ class LnavConan(ConanFile): "pcre:with_jit": True, "sqlite3:enable_json1": True, "sqlite3:enable_soundex": True, + "readline:with_library": "curses", } def generate(self): diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d6aea8e6..b7be0cf5 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -19,6 +19,8 @@ add_subdirectory(pcrepp) add_subdirectory(remote) add_subdirectory(tailer) add_subdirectory(formats/logfmt) +add_subdirectory(yajl) +add_subdirectory(yajlpp) add_executable(bin2c bin2c.hh tools/bin2c.c) target_link_libraries(bin2c ZLIB::ZLIB) @@ -26,465 +28,447 @@ target_link_libraries(bin2c ZLIB::ZLIB) add_executable(ptimec ptimec.hh ptimec.c) set(TIME_FORMATS - "@%@" - "%Y-%m-%d %H:%M:%S" - "%Y-%m-%d %H:%M:%S%z" - "%Y-%m-%d %H:%M:%S %z" - "%Y-%m-%d %H:%M" - "%Y-%m-%dT%H:%M:%S.%f%z" - "%y-%m-%dT%H:%M:%S.%f%z" - "%Y-%m-%dT%H:%M:%SZ" - "%Y-%m-%dT%H:%M:%S%z" - "%Y-%m-%dT%H:%M:%S" - "%Y-%m-%dT%H:%M:%S%z" - "%Y/%m/%d %H:%M:%S" - "%Y/%m/%d %H:%M:%S %z" - "%Y/%m/%d %H:%M:%S%z" - "%Y/%m/%d %H:%M" - "%Y %b %d %a %H:%M:%S.%L" - "%Y %b %d %H:%M:%S.%L" - "%Y %b %d %H:%M:%S" - "%a %b %d %H:%M:%S %Y" - "%a %b %d %H:%M:%S.%f %Y" - "%a %b %d %H:%M:%S %Z %Y" - "%a %b %d %H:%M:%S " - "%a %b %d %H:%M:%S.%L " - "%d/%b/%Y:%H:%M:%S +0000" - "%d/%b/%Y:%H:%M:%S %z" - "%d-%b-%Y %H:%M:%S %z" - "%d-%b-%Y %H:%M:%S %Z" - "%d %b %Y %H:%M:%S" - "%d %b %Y %H:%M:%S.%L" - "%d %b %Y %H:%M:%S,%L" - "%b %d %H:%M:%S" - "%b %d %k:%M:%S" - "%b %d %l:%M:%S" - "%b %e, %Y %l:%M:%S %p" - "%m/%d/%y %H:%M:%S" - "%m/%d/%Y %I:%M:%S:%L %p %Z" - "%m/%d/%Y %I:%M:%S %p %Z" - "%m/%d/%Y %l:%M:%S %p %Z" - "%m/%e/%Y %I:%M:%S %p" - "%m/%e/%Y %l:%M:%S %p" - "%d/%b/%y %H:%M:%S" - "%m%d %H:%M:%S" - "%H:%M:%S" - "%M:%S" - "%m/%d %H:%M:%S" - "%Y-%m-%d" - "%Y-%m" - "%Y/%m/%d" - "%Y/%m" - "%s.%f") + "@%@" + "%Y-%m-%d %H:%M:%S" + "%Y-%m-%d %H:%M:%S%z" + "%Y-%m-%d %H:%M:%S %z" + "%Y-%m-%d %H:%M" + "%Y-%m-%dT%H:%M:%S.%f%z" + "%y-%m-%dT%H:%M:%S.%f%z" + "%Y-%m-%dT%H:%M:%SZ" + "%Y-%m-%dT%H:%M:%S%z" + "%Y-%m-%dT%H:%M:%S" + "%Y-%m-%dT%H:%M:%S%z" + "%Y/%m/%d %H:%M:%S" + "%Y/%m/%d %H:%M:%S %z" + "%Y/%m/%d %H:%M:%S%z" + "%Y/%m/%d %H:%M" + "%Y %b %d %a %H:%M:%S.%L" + "%Y %b %d %H:%M:%S.%L" + "%Y %b %d %H:%M:%S" + "%a %b %d %H:%M:%S %Y" + "%a %b %d %H:%M:%S.%f %Y" + "%a %b %d %H:%M:%S %Z %Y" + "%a %b %d %H:%M:%S " + "%a %b %d %H:%M:%S.%L " + "%d/%b/%Y:%H:%M:%S +0000" + "%d/%b/%Y:%H:%M:%S %z" + "%d-%b-%Y %H:%M:%S %z" + "%d-%b-%Y %H:%M:%S %Z" + "%d %b %Y %H:%M:%S" + "%d %b %Y %H:%M:%S.%L" + "%d %b %Y %H:%M:%S,%L" + "%b %d %H:%M:%S" + "%b %d %k:%M:%S" + "%b %d %l:%M:%S" + "%b %e, %Y %l:%M:%S %p" + "%m/%d/%y %H:%M:%S" + "%m/%d/%Y %I:%M:%S:%L %p %Z" + "%m/%d/%Y %I:%M:%S %p %Z" + "%m/%d/%Y %l:%M:%S %p %Z" + "%m/%e/%Y %I:%M:%S %p" + "%m/%e/%Y %l:%M:%S %p" + "%d/%b/%y %H:%M:%S" + "%m%d %H:%M:%S" + "%H:%M:%S" + "%M:%S" + "%m/%d %H:%M:%S" + "%Y-%m-%d" + "%Y-%m" + "%Y/%m/%d" + "%Y/%m" + "%s.%f") set(GEN_SRCS "") add_custom_command(OUTPUT time_fmts.cc COMMAND ptimec ${TIME_FORMATS} > - time_fmts.cc) -list(APPEND GEN_SRCS time_fmts.cc) + time_fmts.cc) + +add_library(lnavdt STATIC config.h.in ptimec.hh ptimec_rt.cc time_fmts.cc) +target_include_directories(lnavdt PUBLIC . ${CMAKE_CURRENT_BINARY_DIR}) function(bin2c) - cmake_parse_arguments(BIN2C_ "" "VARNAME" "" ${ARGN}) + cmake_parse_arguments(BIN2C_ "" "VARNAME" "" ${ARGN}) - list(TRANSFORM BIN2C_UNPARSED_ARGUMENTS "\\." "-") - add_custom_command( - OUTPUT "${DST_FILE}.h" "${DST_FILE}.cc" - COMMAND bin2c "${DST_FILE}" "${CMAKE_CURRENT_SOURCE_DIR}/${FILE_TO_LINK}" - DEPENDS bin2c "${FILE_TO_LINK}") + list(TRANSFORM BIN2C_UNPARSED_ARGUMENTS "\\." "-") + add_custom_command( + OUTPUT "${DST_FILE}.h" "${DST_FILE}.cc" + COMMAND bin2c "${DST_FILE}" "${CMAKE_CURRENT_SOURCE_DIR}/${FILE_TO_LINK}" + DEPENDS bin2c "${FILE_TO_LINK}") endfunction(bin2c) -foreach(FILE_TO_LINK ansi-palette.json xterm-palette.json help.txt init.sql) - string(REPLACE "." "-" DST_FILE "${FILE_TO_LINK}") - add_custom_command( - OUTPUT "${DST_FILE}.h" "${DST_FILE}.cc" - COMMAND bin2c "${DST_FILE}" "${CMAKE_CURRENT_SOURCE_DIR}/${FILE_TO_LINK}" - DEPENDS bin2c "${FILE_TO_LINK}") - list(APPEND GEN_SRCS "${CMAKE_CURRENT_BINARY_DIR}/${DST_FILE}.h" - "${CMAKE_CURRENT_BINARY_DIR}/${DST_FILE}.cc") -endforeach(FILE_TO_LINK) +foreach (FILE_TO_LINK ansi-palette.json xterm-palette.json help.txt init.sql) + string(REPLACE "." "-" DST_FILE "${FILE_TO_LINK}") + add_custom_command( + OUTPUT "${DST_FILE}.h" "${DST_FILE}.cc" + COMMAND bin2c "${DST_FILE}" "${CMAKE_CURRENT_SOURCE_DIR}/${FILE_TO_LINK}" + DEPENDS bin2c "${FILE_TO_LINK}") + list(APPEND GEN_SRCS "${CMAKE_CURRENT_BINARY_DIR}/${DST_FILE}.h" + "${CMAKE_CURRENT_BINARY_DIR}/${DST_FILE}.cc") +endforeach (FILE_TO_LINK) set(FORMAT_FILES - formats/access_log.json - formats/alb_log.json - formats/autodeploy_log.json - formats/block_log.json - formats/candlepin_log.json - formats/choose_repo_log.json - formats/cups_log.json - formats/dpkg_log.json - formats/elb_log.json - formats/engine_log.json - formats/error_log.json - formats/fsck_hfs_log.json - formats/glog_log.json - formats/haproxy_log.json - formats/java_log.json - formats/journald_json_log.json - formats/katello_log.json - formats/openam_log.json - formats/openamdb_log.json - formats/openstack_log.json - formats/page_log.json - formats/papertrail_log.json - formats/snaplogic_log.json - formats/sssd_log.json - formats/strace_log.json - formats/sudo_log.json - formats/syslog_log.json - formats/s3_log.json - formats/tcf_log.json - formats/tcsh_history.json - formats/uwsgi_log.json - formats/vdsm_log.json - formats/vmk_log.json - formats/vmw_log.json - formats/xmlrpc_log.json) + formats/access_log.json + formats/alb_log.json + formats/autodeploy_log.json + formats/block_log.json + formats/candlepin_log.json + formats/choose_repo_log.json + formats/cups_log.json + formats/dpkg_log.json + formats/elb_log.json + formats/engine_log.json + formats/error_log.json + formats/fsck_hfs_log.json + formats/glog_log.json + formats/haproxy_log.json + formats/java_log.json + formats/journald_json_log.json + formats/katello_log.json + formats/openam_log.json + formats/openamdb_log.json + formats/openstack_log.json + formats/page_log.json + formats/papertrail_log.json + formats/snaplogic_log.json + formats/sssd_log.json + formats/strace_log.json + formats/sudo_log.json + formats/syslog_log.json + formats/s3_log.json + formats/tcf_log.json + formats/tcsh_history.json + formats/uwsgi_log.json + formats/vdsm_log.json + formats/vmk_log.json + formats/vmw_log.json + formats/xmlrpc_log.json) set(FORMAT_FILE_PATHS ${FORMAT_FILES}) list(TRANSFORM FORMAT_FILE_PATHS PREPEND "${CMAKE_CURRENT_SOURCE_DIR}/") add_custom_command( - OUTPUT default-formats.h default-formats.cc - COMMAND bin2c -n lnav_format_json default-formats ${FORMAT_FILE_PATHS} - DEPENDS bin2c ${FORMAT_FILES}) + OUTPUT default-formats.h default-formats.cc + COMMAND bin2c -n lnav_format_json default-formats ${FORMAT_FILE_PATHS} + DEPENDS bin2c ${FORMAT_FILES}) list(APPEND GEN_SRCS default-formats.h default-formats.cc) set(CONFIG_FILES - root-config.json - keymaps/de-keymap.json - keymaps/default-keymap.json - keymaps/fr-keymap.json - keymaps/uk-keymap.json - keymaps/us-keymap.json - themes/default-theme.json - themes/grayscale.json - themes/eldar.json - themes/monocai.json - themes/night-owl.json - themes/solarized-dark.json - themes/solarized-light.json) + root-config.json + keymaps/de-keymap.json + keymaps/default-keymap.json + keymaps/fr-keymap.json + keymaps/uk-keymap.json + keymaps/us-keymap.json + themes/default-theme.json + themes/grayscale.json + themes/eldar.json + themes/monocai.json + themes/night-owl.json + themes/solarized-dark.json + themes/solarized-light.json) set(CONFIG_FILE_PATHS ${CONFIG_FILES}) list(TRANSFORM CONFIG_FILE_PATHS PREPEND "${CMAKE_CURRENT_SOURCE_DIR}/") add_custom_command( - OUTPUT default-config.h default-config.cc - COMMAND bin2c -n lnav_config_json default-config ${CONFIG_FILE_PATHS} - DEPENDS bin2c ${CONFIG_FILES}) + OUTPUT default-config.h default-config.cc + COMMAND bin2c -n lnav_config_json default-config ${CONFIG_FILE_PATHS} + DEPENDS bin2c ${CONFIG_FILES}) list(APPEND GEN_SRCS default-config.h default-config.cc) set(BUILTIN_LNAV_SCRIPTS - scripts/dhclient-summary.lnav scripts/lnav-pop-view.lnav - scripts/partition-by-boot.lnav scripts/rename-stdin.lnav - scripts/search-for.lnav) + scripts/dhclient-summary.lnav scripts/lnav-pop-view.lnav + scripts/partition-by-boot.lnav scripts/rename-stdin.lnav + scripts/search-for.lnav) set(BUILTIN_LNAV_SCRIPT_PATHS ${BUILTIN_LNAV_SCRIPTS}) list(TRANSFORM BUILTIN_LNAV_SCRIPT_PATHS PREPEND "${CMAKE_CURRENT_SOURCE_DIR}/") add_custom_command( - OUTPUT builtin-scripts.h builtin-scripts.cc - COMMAND bin2c -n lnav_scripts builtin-scripts ${BUILTIN_LNAV_SCRIPT_PATHS} - DEPENDS bin2c ${BUILTIN_LNAV_SCRIPTS}) + OUTPUT builtin-scripts.h builtin-scripts.cc + COMMAND bin2c -n lnav_scripts builtin-scripts ${BUILTIN_LNAV_SCRIPT_PATHS} + DEPENDS bin2c ${BUILTIN_LNAV_SCRIPTS}) list(APPEND GEN_SRCS builtin-scripts.h builtin-scripts.cc) set(BUILTIN_SH_SCRIPTS scripts/dhclient-summary.lnav scripts/lnav-pop-view.lnav - scripts/partition-by-boot.lnav scripts/search-for.lnav) + scripts/partition-by-boot.lnav scripts/search-for.lnav) set(BUILTIN_SH_SCRIPT_PATHS ${BUILTIN_SH_SCRIPTS}) list(TRANSFORM BUILTIN_SH_SCRIPT_PATHS PREPEND "${CMAKE_CURRENT_SOURCE_DIR}/") add_custom_command( - OUTPUT builtin-sh-scripts.h builtin-sh-scripts.cc - COMMAND bin2c -n lnav_sh_scripts builtin-sh-scripts ${BUILTIN_SH_SCRIPT_PATHS} - DEPENDS bin2c ${BUILTIN_SH_SCRIPTS}) + OUTPUT builtin-sh-scripts.h builtin-sh-scripts.cc + COMMAND bin2c -n lnav_sh_scripts builtin-sh-scripts ${BUILTIN_SH_SCRIPT_PATHS} + DEPENDS bin2c ${BUILTIN_SH_SCRIPTS}) list(APPEND GEN_SRCS builtin-sh-scripts.h builtin-sh-scripts.cc) add_library( - cppfmt STATIC - fmtlib/format.cc - fmtlib/os.cc - fmtlib/fmt/chrono.h - fmtlib/fmt/color.h - fmtlib/fmt/compile.h - fmtlib/fmt/core.h - fmtlib/fmt/format-inl.h - fmtlib/fmt/format.h - fmtlib/fmt/locale.h - fmtlib/fmt/os.h - fmtlib/fmt/ostream.h - fmtlib/fmt/posix.h - fmtlib/fmt/printf.h - fmtlib/fmt/ranges.h - fmtlib/fmt/time.h) + cppfmt STATIC + fmtlib/format.cc + fmtlib/os.cc + fmtlib/fmt/chrono.h + fmtlib/fmt/color.h + fmtlib/fmt/compile.h + fmtlib/fmt/core.h + fmtlib/fmt/format-inl.h + fmtlib/fmt/format.h + fmtlib/fmt/locale.h + fmtlib/fmt/os.h + fmtlib/fmt/ostream.h + fmtlib/fmt/posix.h + fmtlib/fmt/printf.h + fmtlib/fmt/ranges.h + fmtlib/fmt/time.h) +target_include_directories(cppfmt PUBLIC fmtlib) + +add_library(lnavfileio STATIC + grep_proc.hh + line_buffer.hh + shared_buffer.hh + + grep_proc.cc + line_buffer.cc + shared_buffer.cc + ) +target_include_directories(lnavfileio PRIVATE . ${CMAKE_CURRENT_BINARY_DIR}) +target_link_libraries(lnavfileio cppfmt pcrepp base BZip2::BZip2 ZLIB::ZLIB) add_library( - diag STATIC - ${GEN_SRCS} - config.h.in - all_logs_vtab.cc - ansi_scrubber.cc - archive_manager.cc - attr_line.cc - bin2c.hh - bookmarks.cc - bottom_status_source.cc - collation-functions.cc - column_namer.cc - command_executor.cc - curl_looper.cc - db_sub_source.cc - elem_to_json.cc - environ_vtab.cc - extension-functions.cc - field_overlay_source.cc - file_collection.cc - file_format.cc - file_vtab.cc - files_sub_source.cc - filter_observer.cc - filter_status_source.cc - filter_sub_source.cc - fs-extension-functions.cc - fstat_vtab.cc - fts_fuzzy_match.cc - grep_proc.cc - help_text.cc - help_text_formatter.cc - highlighter.cc - hist_source.cc - hotkeys.cc - input_dispatcher.cc - json-extension-functions.cc - yajlpp/json_op.cc - yajlpp/json_ptr.cc - line_buffer.cc - listview_curses.cc - lnav_commands.cc - lnav_config.cc - lnav_util.cc - log_accel.cc - log_actions.cc - log_data_helper.cc - log_data_table.cc - log_format.cc - log_format_loader.cc - log_level.cc - log_search_table.cc - logfile.cc - logfile_sub_source.cc - network-extension-functions.cc - data_scanner.cc - data_scanner_re.cc - data_parser.cc - papertrail_proc.cc - pcap_manager.cc - ptimec_rt.cc - pretty_printer.cc - pugixml/pugixml.cpp - readline_callbacks.cc - readline_curses.cc - readline_highlighters.cc - readline_possibilities.cc - regexp_vtab.cc - relative_time.cc - session_data.cc - sequence_matcher.cc - shared_buffer.cc - shlex.cc - sqlite-extension-func.cc - statusview_curses.cc - string-extension-functions.cc - sysclip.cc - piper_proc.cc - spectro_source.cc - sql_commands.cc - sql_util.cc - state-extension-functions.cc - styling.cc - string_attr_type.cc - text_format.cc - textfile_highlighters.cc - textfile_sub_source.cc - textview_curses.cc - top_status_source.cc - time-extension-functions.cc - timer.cc - unique_path.cc - unique_path.hh - view_curses.cc - view_helpers.cc - views_vtab.cc - vt52_curses.cc - vtab_module.cc - log_vtab_impl.cc - xml_util.cc - xpath_vtab.cc - xterm_mouse.cc - yajlpp/yajlpp.cc - yajl/yajl.c - yajl/yajl_alloc.c - yajl/yajl_alloc.h - yajl/yajl_buf.c - yajl/yajl_buf.h - yajl/yajl_bytestack.h - yajl/yajl_encode.c - yajl/yajl_encode.h - yajl/yajl_gen.c - yajl/yajl_lex.c - yajl/yajl_lex.h - yajl/yajl_parser.c - yajl/yajl_parser.h - yajl/yajl_tree.c - yajl/yajl_version.c - spookyhash/SpookyV2.cpp - third-party/sqlite/ext/series.c - third-party/sqlite/ext/dbdump.c - all_logs_vtab.hh - archive_manager.hh - archive_manager.cfg.hh - attr_line.hh - auto_fd.hh - auto_mem.hh - big_array.hh - bottom_status_source.hh - bound_tags.hh - byte_array.hh - command_executor.hh - column_namer.hh - curl_looper.hh - doc_status_source.hh - elem_to_json.hh - field_overlay_source.hh - file_collection.hh - file_format.hh - files_sub_source.hh - filter_observer.hh - filter_status_source.hh - filter_sub_source.hh - fstat_vtab.hh - fts_fuzzy_match.hh - grep_highlighter.hh - help_text.hh - help_text_formatter.hh - highlighter.hh - hotkeys.hh - input_dispatcher.hh - k_merge_tree.h - log_actions.hh - log_data_helper.hh - log_data_table.hh - log_format.hh - log_format_ext.hh - log_format_fwd.hh - log_format_impls.cc - log_gutter_source.hh - log_level.hh - log_search_table.hh - logfile.hh - logfile_fwd.hh - logfile_stats.hh - optional.hpp - papertrail_proc.hh - pcap_manager.hh - plain_text_source.hh - pretty_printer.hh - preview_status_source.hh - ptimec.hh - pugixml/pugiconfig.hpp - pugixml/pugixml.hpp - readline_callbacks.hh - readline_context.hh - readline_possibilities.hh - regexp_vtab.hh - relative_time.hh - styling.hh - ring_span.hh - safe/accessmode.h - safe/defaulttypes.h - safe/mutableref.h - safe/safe.h - sequence_sink.hh - shlex.hh - shlex.resolver.hh - simdutf8check.h - spectro_source.hh - sqlitepp.hh - sql_help.hh - sql_util.hh - strong_int.hh - string_attr_type.hh - sysclip.hh - sysclip.cfg.hh - term_extra.hh - termios_guard.hh - text_format.hh - textfile_highlighters.hh - textfile_sub_source.hh - textview_curses.hh - textview_curses_fwd.hh - time_T.hh - timer.hh - top_status_source.hh - url_loader.hh - view_helpers.hh - view_helpers.examples.hh - views_vtab.hh - vis_line.hh - vtab_module.hh - vtab_module_json.hh - yajlpp/yajlpp.hh - yajlpp/yajlpp_def.hh - xml_util.hh - xpath_vtab.hh - mapbox/recursive_wrapper.hpp - mapbox/variant.hpp - mapbox/variant_io.hpp - mapbox/variant_visitor.hpp - yajl/api/yajl_common.h - yajl/api/yajl_gen.h - yajl/api/yajl_parse.h - yajl/api/yajl_tree.h - ghc/filesystem.hpp - ghc/fs_fwd.hpp - ghc/fs_impl.hpp - ghc/fs_std.hpp - ghc/fs_std_fwd.hpp - ghc/fs_std_impl.hpp - ww898/cp_utf8.hpp - log_level_re.cc) + diag STATIC + ${GEN_SRCS} + config.h.in + all_logs_vtab.cc + ansi_scrubber.cc + archive_manager.cc + attr_line.cc + bin2c.hh + bookmarks.cc + bottom_status_source.cc + collation-functions.cc + column_namer.cc + command_executor.cc + curl_looper.cc + db_sub_source.cc + elem_to_json.cc + environ_vtab.cc + extension-functions.cc + field_overlay_source.cc + file_collection.cc + file_format.cc + file_vtab.cc + files_sub_source.cc + filter_observer.cc + filter_status_source.cc + filter_sub_source.cc + fs-extension-functions.cc + fstat_vtab.cc + fts_fuzzy_match.cc + help_text.cc + help_text_formatter.cc + highlighter.cc + hist_source.cc + hotkeys.cc + input_dispatcher.cc + json-extension-functions.cc + listview_curses.cc + lnav_commands.cc + lnav_config.cc + lnav_util.cc + log_accel.cc + log_actions.cc + log_data_helper.cc + log_data_table.cc + log_format.cc + log_format_loader.cc + log_level.cc + log_search_table.cc + logfile.cc + logfile_sub_source.cc + network-extension-functions.cc + data_scanner.cc + data_scanner_re.cc + data_parser.cc + papertrail_proc.cc + pcap_manager.cc + pretty_printer.cc + pugixml/pugixml.cpp + readline_callbacks.cc + readline_curses.cc + readline_highlighters.cc + readline_possibilities.cc + regexp_vtab.cc + relative_time.cc + session_data.cc + sequence_matcher.cc + shlex.cc + sqlite-extension-func.cc + statusview_curses.cc + string-extension-functions.cc + sysclip.cc + piper_proc.cc + spectro_source.cc + sql_commands.cc + sql_util.cc + state-extension-functions.cc + styling.cc + string_attr_type.cc + text_format.cc + textfile_highlighters.cc + textfile_sub_source.cc + textview_curses.cc + top_status_source.cc + time-extension-functions.cc + timer.cc + unique_path.cc + unique_path.hh + view_curses.cc + view_helpers.cc + views_vtab.cc + vt52_curses.cc + vtab_module.cc + log_vtab_impl.cc + xml_util.cc + xpath_vtab.cc + xterm_mouse.cc + spookyhash/SpookyV2.cpp + third-party/sqlite/ext/series.c + third-party/sqlite/ext/dbdump.c + all_logs_vtab.hh + archive_manager.hh + archive_manager.cfg.hh + attr_line.hh + auto_fd.hh + auto_mem.hh + big_array.hh + bottom_status_source.hh + bound_tags.hh + byte_array.hh + command_executor.hh + column_namer.hh + curl_looper.hh + doc_status_source.hh + elem_to_json.hh + field_overlay_source.hh + file_collection.hh + file_format.hh + files_sub_source.hh + filter_observer.hh + filter_status_source.hh + filter_sub_source.hh + fstat_vtab.hh + fts_fuzzy_match.hh + grep_highlighter.hh + help_text.hh + help_text_formatter.hh + highlighter.hh + hotkeys.hh + input_dispatcher.hh + k_merge_tree.h + log_actions.hh + log_data_helper.hh + log_data_table.hh + log_format.hh + log_format_ext.hh + log_format_fwd.hh + log_format_impls.cc + log_gutter_source.hh + log_level.hh + log_search_table.hh + logfile.hh + logfile_fwd.hh + logfile_stats.hh + optional.hpp + papertrail_proc.hh + pcap_manager.hh + plain_text_source.hh + pretty_printer.hh + preview_status_source.hh + pugixml/pugiconfig.hpp + pugixml/pugixml.hpp + readline_callbacks.hh + readline_context.hh + readline_possibilities.hh + regexp_vtab.hh + relative_time.hh + styling.hh + ring_span.hh + safe/accessmode.h + safe/defaulttypes.h + safe/mutableref.h + safe/safe.h + sequence_sink.hh + shlex.hh + shlex.resolver.hh + simdutf8check.h + spectro_source.hh + sqlitepp.hh + sql_help.hh + sql_util.hh + strong_int.hh + string_attr_type.hh + sysclip.hh + sysclip.cfg.hh + term_extra.hh + termios_guard.hh + text_format.hh + textfile_highlighters.hh + textfile_sub_source.hh + textview_curses.hh + textview_curses_fwd.hh + time_T.hh + timer.hh + top_status_source.hh + url_loader.hh + view_helpers.hh + view_helpers.examples.hh + views_vtab.hh + vis_line.hh + vtab_module.hh + vtab_module_json.hh + xml_util.hh + xpath_vtab.hh + mapbox/recursive_wrapper.hpp + mapbox/variant.hpp + mapbox/variant_io.hpp + mapbox/variant_visitor.hpp + ghc/filesystem.hpp + ghc/fs_fwd.hpp + ghc/fs_impl.hpp + ghc/fs_std.hpp + ghc/fs_std_fwd.hpp + ghc/fs_std_impl.hpp + ww898/cp_utf8.hpp + log_level_re.cc) set(lnav_SRCS lnav.cc) target_include_directories(diag PUBLIC . fmtlib ${CMAKE_CURRENT_BINARY_DIR} - third-party) + third-party) target_link_libraries( - diag - base - pcrepp - tailerservice - tailerpp - tailercommon - logfmt - ${lnav_LIBS}) + diag + base + lnavdt + lnavfileio + pcrepp + tailerservice + tailerpp + tailercommon + logfmt + yajlpp + ${lnav_LIBS}) target_compile_definitions(diag PRIVATE SQLITE_OMIT_LOAD_EXTENSION) check_library_exists(util openpty "" HAVE_LIBUTIL) -if(HAVE_LIBUTIL) - target_link_libraries(diag util) -endif() - -add_executable(test_yajlpp yajlpp/test_yajlpp.cc) -target_link_libraries(test_yajlpp diag ${lnav_LIBS}) -add_test(NAME test_yajlpp COMMAND test_yajlpp) - -add_executable(drive_json_op yajlpp/drive_json_op.cc) -target_link_libraries(drive_json_op diag ${lnav_LIBS}) +if (HAVE_LIBUTIL) + target_link_libraries(diag util) +endif () add_executable(lnav ${lnav_SRCS}) target_link_libraries(lnav diag) diff --git a/src/all_logs_vtab.cc b/src/all_logs_vtab.cc index 79a604d6..3db40e31 100644 --- a/src/all_logs_vtab.cc +++ b/src/all_logs_vtab.cc @@ -21,48 +21,54 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - #include "all_logs_vtab.hh" + +#include "config.h" #include "string_attr_type.hh" static auto intern_lifetime = intern_string::get_table_lifetime(); all_logs_vtab::all_logs_vtab() : log_vtab_impl(intern_string::lookup("all_logs")), - alv_value_meta(intern_string::lookup("log_format"), - value_kind_t::VALUE_TEXT, - 0), - alv_msg_meta(intern_string::lookup("log_msg_format"), - value_kind_t::VALUE_TEXT, - 1), - alv_schema_meta(intern_string::lookup("log_msg_schema"), - value_kind_t::VALUE_TEXT, - 2) { + alv_value_meta( + intern_string::lookup("log_format"), value_kind_t::VALUE_TEXT, 0), + alv_msg_meta( + intern_string::lookup("log_msg_format"), value_kind_t::VALUE_TEXT, 1), + alv_schema_meta( + intern_string::lookup("log_msg_schema"), value_kind_t::VALUE_TEXT, 2) +{ this->alv_value_meta.lvm_identifier = true; this->alv_msg_meta.lvm_identifier = true; this->alv_schema_meta.lvm_identifier = true; } -void all_logs_vtab::get_columns(std::vector &cols) const +void +all_logs_vtab::get_columns(std::vector& cols) const { cols.emplace_back(vtab_column(this->alv_value_meta.lvm_name.get()) .with_comment("The name of the log file format")); - cols.emplace_back(vtab_column(this->alv_msg_meta.lvm_name.get()) - .with_comment("The message format with variables replaced by hash marks")); - cols.emplace_back(this->alv_schema_meta.lvm_name.get(), SQLITE3_TEXT, "", true, + cols.emplace_back( + vtab_column(this->alv_msg_meta.lvm_name.get()) + .with_comment( + "The message format with variables replaced by hash marks")); + cols.emplace_back(this->alv_schema_meta.lvm_name.get(), + SQLITE3_TEXT, + "", + true, "The ID for the message schema"); } -void all_logs_vtab::extract(std::shared_ptr lf, uint64_t line_number, - shared_buffer_ref &line, - std::vector &values) +void +all_logs_vtab::extract(std::shared_ptr lf, + uint64_t line_number, + shared_buffer_ref& line, + std::vector& values) { auto format = lf->get_format(); values.emplace_back(this->alv_value_meta, format->get_name()); @@ -98,7 +104,8 @@ void all_logs_vtab::extract(std::shared_ptr lf, uint64_t line_number, values.emplace_back(this->alv_schema_meta, schema_ref); } -bool all_logs_vtab::is_valid(log_cursor &lc, logfile_sub_source &lss) +bool +all_logs_vtab::is_valid(log_cursor& lc, logfile_sub_source& lss) { auto cl = lss.at(lc.lc_curr_line); auto lf = lss.find(cl); @@ -111,7 +118,8 @@ bool all_logs_vtab::is_valid(log_cursor &lc, logfile_sub_source &lss) return true; } -bool all_logs_vtab::next(log_cursor &lc, logfile_sub_source &lss) +bool +all_logs_vtab::next(log_cursor& lc, logfile_sub_source& lss) { lc.lc_curr_line = lc.lc_curr_line + vis_line_t(1); lc.lc_sub_index = 0; diff --git a/src/all_logs_vtab.hh b/src/all_logs_vtab.hh index 17d28306..05c5f5d1 100644 --- a/src/all_logs_vtab.hh +++ b/src/all_logs_vtab.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -32,27 +32,26 @@ #include -#include "log_vtab_impl.hh" #include "data_parser.hh" +#include "log_vtab_impl.hh" /** * A virtual table that provides access to all log messages from all formats. */ class all_logs_vtab : public log_vtab_impl { public: - all_logs_vtab(); - void get_columns(std::vector &cols) const override; + void get_columns(std::vector& cols) const override; void extract(std::shared_ptr lf, uint64_t line_number, - shared_buffer_ref &line, - std::vector &values) override; + shared_buffer_ref& line, + std::vector& values) override; - bool is_valid(log_cursor &lc, logfile_sub_source &lss) override; + bool is_valid(log_cursor& lc, logfile_sub_source& lss) override; - bool next(log_cursor &lc, logfile_sub_source &lss) override; + bool next(log_cursor& lc, logfile_sub_source& lss) override; private: logline_value_meta alv_value_meta; @@ -62,4 +61,4 @@ private: std::array alv_schema_buffer{}; }; -#endif //LNAV_ALL_LOGS_VTAB_HH +#endif // LNAV_ALL_LOGS_VTAB_HH diff --git a/src/ansi_scrubber.cc b/src/ansi_scrubber.cc index dd4ba11f..7e668caa 100644 --- a/src/ansi_scrubber.cc +++ b/src/ansi_scrubber.cc @@ -21,44 +21,46 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file ansi_scrubber.cc */ -#include "config.h" - #include +#include "ansi_scrubber.hh" + #include "base/opt_util.hh" -#include "view_curses.hh" +#include "config.h" #include "pcrepp/pcrepp.hh" -#include "ansi_scrubber.hh" +#include "view_curses.hh" using namespace std; -static pcrepp &ansi_regex() +static pcrepp& +ansi_regex() { static pcrepp retval("\x1b\\[([\\d=;\\?]*)([a-zA-Z])"); return retval; } -void scrub_ansi_string(std::string &str, string_attrs_t &sa) +void +scrub_ansi_string(std::string& str, string_attrs_t& sa) { pcre_context_static<60> context; - pcrepp & regex = ansi_regex(); + pcrepp& regex = ansi_regex(); pcre_input pi(str); replace(str.begin(), str.end(), '\0', ' '); while (regex.match(context, pi)) { - pcre_context::capture_t *caps = context.all(); - struct line_range lr; + pcre_context::capture_t* caps = context.all(); + struct line_range lr; bool has_attrs = false; - attr_t attrs = 0; + attr_t attrs = 0; auto bg = nonstd::optional(); auto fg = nonstd::optional(); auto role = nonstd::optional(); @@ -67,7 +69,8 @@ void scrub_ansi_string(std::string &str, string_attrs_t &sa) switch (pi.get_substr_start(&caps[2])[0]) { case 'm': for (lpc = caps[1].c_begin; - lpc != string::npos && lpc < (size_t) caps[1].c_end;) { + lpc != string::npos && lpc < (size_t) caps[1].c_end;) + { int ansi_code = 0; if (sscanf(&(str[lpc]), "%d", &ansi_code) == 1) { @@ -110,9 +113,10 @@ void scrub_ansi_string(std::string &str, string_attrs_t &sa) case 'C': { unsigned int spaces = 0; - if (sscanf(&(str[caps[1].c_begin]), "%u", &spaces) == 1 && - spaces > 0) { - str.insert((unsigned long) caps[0].c_end, spaces, ' '); + if (sscanf(&(str[caps[1].c_begin]), "%u", &spaces) == 1 + && spaces > 0) { + str.insert( + (std::string::size_type) caps[0].c_end, spaces, ' '); } break; } @@ -120,11 +124,13 @@ void scrub_ansi_string(std::string &str, string_attrs_t &sa) case 'H': { unsigned int row = 0, spaces = 0; - if (sscanf(&(str[caps[1].c_begin]), "%u;%u", &row, &spaces) == 2 && - spaces > 1) { + if (sscanf(&(str[caps[1].c_begin]), "%u;%u", &row, &spaces) == 2 + && spaces > 1) { int ispaces = spaces - 1; if (ispaces > caps[0].c_begin) { - str.insert((unsigned long) caps[0].c_end, ispaces - caps[0].c_begin, ' '); + str.insert((unsigned long) caps[0].c_end, + ispaces - caps[0].c_begin, + ' '); } } break; @@ -142,8 +148,7 @@ void scrub_ansi_string(std::string &str, string_attrs_t &sa) break; } } - str.erase(str.begin() + caps[0].c_begin, - str.begin() + caps[0].c_end); + str.erase(str.begin() + caps[0].c_begin, str.begin() + caps[0].c_end); if (has_attrs) { for (auto rit = sa.rbegin(); rit != sa.rend(); rit++) { @@ -153,7 +158,7 @@ void scrub_ansi_string(std::string &str, string_attrs_t &sa) rit->sa_range.lr_end = caps[0].c_begin; } lr.lr_start = caps[0].c_begin; - lr.lr_end = -1; + lr.lr_end = -1; if (attrs) { sa.emplace_back(lr, &view_curses::VC_STYLE, attrs); } @@ -172,7 +177,8 @@ void scrub_ansi_string(std::string &str, string_attrs_t &sa) } } -void add_ansi_vars(std::map &vars) +void +add_ansi_vars(std::map& vars) { vars["ansi_csi"] = ANSI_CSI; vars["ansi_norm"] = ANSI_NORM; diff --git a/src/ansi_scrubber.hh b/src/ansi_scrubber.hh index 15f598a4..aeab0793 100644 --- a/src/ansi_scrubber.hh +++ b/src/ansi_scrubber.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -37,22 +37,22 @@ #include "attr_line.hh" -#define ANSI_CSI "\x1b[" -#define ANSI_CHAR_ATTR "m" -#define ANSI_BOLD_PARAM "1" -#define ANSI_BOLD_START ANSI_CSI ANSI_BOLD_PARAM ANSI_CHAR_ATTR -#define ANSI_UNDERLINE_START ANSI_CSI "4m" -#define ANSI_NORM ANSI_CSI "0m" -#define ANSI_STRIKE_PARAM "9" -#define ANSI_STRIKE_START ANSI_CSI ANSI_STRIKE_PARAM ANSI_CHAR_ATTR +#define ANSI_CSI "\x1b[" +#define ANSI_CHAR_ATTR "m" +#define ANSI_BOLD_PARAM "1" +#define ANSI_BOLD_START ANSI_CSI ANSI_BOLD_PARAM ANSI_CHAR_ATTR +#define ANSI_UNDERLINE_START ANSI_CSI "4m" +#define ANSI_NORM ANSI_CSI "0m" +#define ANSI_STRIKE_PARAM "9" +#define ANSI_STRIKE_START ANSI_CSI ANSI_STRIKE_PARAM ANSI_CHAR_ATTR -#define ANSI_BOLD(msg) ANSI_BOLD_START msg ANSI_NORM -#define ANSI_UNDERLINE(msg) ANSI_UNDERLINE_START msg ANSI_NORM +#define ANSI_BOLD(msg) ANSI_BOLD_START msg ANSI_NORM +#define ANSI_UNDERLINE(msg) ANSI_UNDERLINE_START msg ANSI_NORM -#define ANSI_ROLE(msg) ANSI_CSI "%dO" msg ANSI_NORM -#define XANSI_COLOR(col) "3" #col +#define ANSI_ROLE(msg) ANSI_CSI "%dO" msg ANSI_NORM +#define XANSI_COLOR(col) "3" #col #define ANSI_COLOR_PARAM(col) XANSI_COLOR(col) -#define ANSI_COLOR(col) ANSI_CSI XANSI_COLOR(col) "m" +#define ANSI_COLOR(col) ANSI_CSI XANSI_COLOR(col) "m" /** * Check a string for ANSI escape sequences, process them, remove them, and add @@ -61,12 +61,12 @@ * @param str The string to check for ANSI escape sequences. * @param sa The container for any style attributes. */ -void scrub_ansi_string(std::string &str, string_attrs_t &sa); +void scrub_ansi_string(std::string& str, string_attrs_t& sa); /** * Populate a variable map with strings that contain escape sequences that * might be useful to script writers. */ -void add_ansi_vars(std::map &vars); +void add_ansi_vars(std::map& vars); #endif diff --git a/src/archive_manager.cc b/src/archive_manager.cc index 24c233ff..b7344a7e 100644 --- a/src/archive_manager.cc +++ b/src/archive_manager.cc @@ -21,36 +21,35 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file archive_manager.cc */ -#include "config.h" - #include +#include "config.h" + #if HAVE_ARCHIVE_H -#include "archive.h" -#include "archive_entry.h" +# include "archive.h" +# include "archive_entry.h" #endif +#include "archive_manager.cfg.hh" +#include "archive_manager.hh" #include "auto_fd.hh" #include "auto_mem.hh" -#include "fmt/format.h" #include "base/fs_util.hh" +#include "base/humanize.hh" #include "base/injector.hh" #include "base/lnav_log.hh" -#include "base/humanize.hh" #include "base/paths.hh" +#include "fmt/format.h" #include "lnav_util.hh" -#include "archive_manager.hh" -#include "archive_manager.cfg.hh" - namespace fs = ghc::filesystem; namespace archive_manager { @@ -59,32 +58,37 @@ class archive_lock { public: class guard { public: - - explicit guard(archive_lock& arc_lock) : g_lock(arc_lock) { + explicit guard(archive_lock& arc_lock) : g_lock(arc_lock) + { this->g_lock.lock(); }; - ~guard() { + ~guard() + { this->g_lock.unlock(); }; private: - archive_lock &g_lock; + archive_lock& g_lock; }; - void lock() const { + void lock() const + { lockf(this->lh_fd, F_LOCK, 0); }; - void unlock() const { + void unlock() const + { lockf(this->lh_fd, F_ULOCK, 0); }; - explicit archive_lock(const fs::path& archive_path) { + explicit archive_lock(const fs::path& archive_path) + { auto lock_path = archive_path; lock_path += ".lck"; - this->lh_fd = lnav::filesystem::openp(lock_path, O_CREAT | O_RDWR, 0600); + this->lh_fd + = lnav::filesystem::openp(lock_path, O_CREAT | O_RDWR, 0600); log_perror(fcntl(this->lh_fd, F_SETFD, FD_CLOEXEC)); }; @@ -96,7 +100,8 @@ public: * Enables a subset of the supported archive formats to speed up detection, * since some formats, like xar are unlikely to be used. */ -static void enable_desired_archive_formats(archive *arc) +static void +enable_desired_archive_formats(archive* arc) { archive_read_support_format_7zip(arc); archive_read_support_format_cpio(arc); @@ -107,7 +112,8 @@ static void enable_desired_archive_formats(archive *arc) } #endif -bool is_archive(const fs::path& filename) +bool +is_archive(const fs::path& filename) { #if HAVE_ARCHIVE_H auto_mem arc(archive_read_free); @@ -120,7 +126,7 @@ bool is_archive(const fs::path& filename) log_debug("read open %s", filename.c_str()); auto r = archive_read_open_filename(arc, filename.c_str(), 128 * 1024); if (r == ARCHIVE_OK) { - struct archive_entry *entry; + struct archive_entry* entry; auto format_name = archive_format_name(arc); @@ -145,8 +151,8 @@ bool is_archive(const fs::path& filename) return false; } } - log_info("detected archive: %s -- %s", - filename.c_str(), format_name); + log_info( + "detected archive: %s -- %s", filename.c_str(), format_name); return true; } else { log_info("archive read header failed: %s -- %s", @@ -163,14 +169,14 @@ bool is_archive(const fs::path& filename) return false; } -static -fs::path archive_cache_path() +static fs::path +archive_cache_path() { return lnav::paths::workdir() / "archives"; } fs::path -filename_to_tmp_path(const std::string &filename) +filename_to_tmp_path(const std::string& filename) { auto fn_path = fs::path(filename); auto basename = fn_path.filename().string(); @@ -195,14 +201,14 @@ filename_to_tmp_path(const std::string &filename) #if HAVE_ARCHIVE_H static walk_result_t copy_data(const std::string& filename, - struct archive *ar, - struct archive_entry *entry, - struct archive *aw, - const fs::path &entry_path, - struct extract_progress *ep) + struct archive* ar, + struct archive_entry* entry, + struct archive* aw, + const fs::path& entry_path, + struct extract_progress* ep) { int r; - const void *buff; + const void* buff; size_t size, total = 0, next_space_check = 0; la_int64_t offset; @@ -213,7 +219,9 @@ copy_data(const std::string& filename, if (tmp_space.available < cfg.amc_min_free_space) { return Err(fmt::format( - FMT_STRING("available space on disk ({}) is below the minimum-free threshold ({}). Unable to unpack '{}' to '{}'"), + FMT_STRING("available space on disk ({}) is below the " + "minimum-free threshold ({}). Unable to unpack " + "'{}' to '{}'"), humanize::file_size(tmp_space.available), humanize::file_size(cfg.amc_min_free_space), entry_path.filename().string(), @@ -244,12 +252,11 @@ copy_data(const std::string& filename, } } -static walk_result_t extract(const std::string &filename, const extract_cb &cb) +static walk_result_t +extract(const std::string& filename, const extract_cb& cb) { - static int FLAGS = ARCHIVE_EXTRACT_TIME - | ARCHIVE_EXTRACT_PERM - | ARCHIVE_EXTRACT_ACL - | ARCHIVE_EXTRACT_FFLAGS; + static int FLAGS = ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM + | ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS; auto tmp_path = filename_to_tmp_path(filename); auto arc_lock = archive_lock(tmp_path); @@ -267,9 +274,9 @@ static walk_result_t extract(const std::string &filename, const extract_cb &cb) } } if (file_count > 0) { - fs::last_write_time( - done_path, std::chrono::system_clock::now()); - log_info("%s: archive has already been extracted!", done_path.c_str()); + fs::last_write_time(done_path, std::chrono::system_clock::now()); + log_info("%s: archive has already been extracted!", + done_path.c_str()); return Ok(); } else { log_warning("%s: archive cache has been damaged, re-extracting", @@ -289,17 +296,16 @@ static walk_result_t extract(const std::string &filename, const extract_cb &cb) ext = archive_write_disk_new(); archive_write_disk_set_options(ext, FLAGS); archive_write_disk_set_standard_lookup(ext); - if (archive_read_open_filename(arc, filename.c_str(), 10240) != ARCHIVE_OK) { + if (archive_read_open_filename(arc, filename.c_str(), 10240) != ARCHIVE_OK) + { return Err(fmt::format("unable to open archive: {} -- {}", filename, archive_error_string(arc))); } - log_info("extracting %s to %s", - filename.c_str(), - tmp_path.c_str()); + log_info("extracting %s to %s", filename.c_str(), tmp_path.c_str()); while (true) { - struct archive_entry *entry; + struct archive_entry* entry; auto r = archive_read_next_header(arc, &entry); if (r == ARCHIVE_EOF) { log_info("all done"); @@ -321,22 +327,21 @@ static walk_result_t extract(const std::string &filename, const extract_cb &cb) desired_pathname = fs::path(filename).filename(); } auto entry_path = tmp_path / desired_pathname; - auto prog = cb(entry_path, - archive_entry_size_is_set(entry) ? - archive_entry_size(entry) : -1); + auto prog = cb( + entry_path, + archive_entry_size_is_set(entry) ? archive_entry_size(entry) : -1); archive_entry_copy_pathname(wentry, entry_path.c_str()); auto entry_mode = archive_entry_mode(wentry); archive_entry_set_perm( - wentry, S_IRUSR | (S_ISDIR(entry_mode) ? S_IXUSR|S_IWUSR : 0)); + wentry, S_IRUSR | (S_ISDIR(entry_mode) ? S_IXUSR | S_IWUSR : 0)); r = archive_write_header(ext, wentry); if (r < ARCHIVE_OK) { return Err(fmt::format("unable to write entry: {} -- {}", entry_path.string(), archive_error_string(ext))); - } - else if (!archive_entry_size_is_set(entry) || - archive_entry_size(entry) > 0) { + } else if (!archive_entry_size_is_set(entry) + || archive_entry_size(entry) > 0) { TRY(copy_data(filename, arc, entry, ext, entry_path, prog)); } r = archive_write_finish_entry(ext); @@ -355,12 +360,12 @@ static walk_result_t extract(const std::string &filename, const extract_cb &cb) } #endif -walk_result_t walk_archive_files( - const std::string &filename, - const extract_cb &cb, - const std::function& callback) +walk_result_t +walk_archive_files( + const std::string& filename, + const extract_cb& cb, + const std::function& + callback) { #if HAVE_ARCHIVE_H auto tmp_path = filename_to_tmp_path(filename); @@ -385,7 +390,8 @@ walk_result_t walk_archive_files( #endif } -void cleanup_cache() +void +cleanup_cache() { (void) std::async(std::launch::async, []() { auto now = std::chrono::system_clock::now(); @@ -421,4 +427,4 @@ void cleanup_cache() }); } -} +} // namespace archive_manager diff --git a/src/archive_manager.cfg.hh b/src/archive_manager.cfg.hh index a7815d2e..4cce0261 100644 --- a/src/archive_manager.cfg.hh +++ b/src/archive_manager.cfg.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -41,6 +41,6 @@ struct config { std::chrono::seconds amc_cache_ttl{std::chrono::hours(48)}; }; -} +} // namespace archive_manager #endif diff --git a/src/archive_manager.hh b/src/archive_manager.hh index cf9b34c4..894fedc2 100644 --- a/src/archive_manager.hh +++ b/src/archive_manager.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -33,8 +33,8 @@ #define lnav_archive_manager_hh #include -#include #include +#include #include #include "base/result.h" @@ -43,34 +43,33 @@ namespace archive_manager { struct extract_progress { - extract_progress(ghc::filesystem::path path, - ssize_t total) : ep_path(std::move(path)), - ep_total_size(total) - {} + extract_progress(ghc::filesystem::path path, ssize_t total) + : ep_path(std::move(path)), ep_total_size(total) + { + } const ghc::filesystem::path ep_path; const ssize_t ep_total_size; std::atomic ep_out_size{0}; }; -using extract_cb = std::function; +using extract_cb + = std::function; bool is_archive(const ghc::filesystem::path& filename); -ghc::filesystem::path filename_to_tmp_path(const std::string &filename); +ghc::filesystem::path filename_to_tmp_path(const std::string& filename); using walk_result_t = Result; walk_result_t walk_archive_files( - const std::string &filename, - const extract_cb &cb, - const std::function &); + const std::string& filename, + const extract_cb& cb, + const std::function&); void cleanup_cache(); -} +} // namespace archive_manager #endif diff --git a/src/attr_line.cc b/src/attr_line.cc index 225782dc..42223d2c 100644 --- a/src/attr_line.cc +++ b/src/attr_line.cc @@ -21,22 +21,23 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - #include -#include "auto_mem.hh" +#include "attr_line.hh" + #include "ansi_scrubber.hh" +#include "auto_mem.hh" +#include "config.h" #include "view_curses.hh" -#include "attr_line.hh" -attr_line_t &attr_line_t::with_ansi_string(const char *str, ...) +attr_line_t& +attr_line_t::with_ansi_string(const char* str, ...) { auto_mem formatted_str; va_list args; @@ -53,7 +54,8 @@ attr_line_t &attr_line_t::with_ansi_string(const char *str, ...) return *this; } -attr_line_t &attr_line_t::with_ansi_string(const std::string &str) +attr_line_t& +attr_line_t::with_ansi_string(const std::string& str) { this->al_string = str; scrub_ansi_string(this->al_string, this->al_attrs); @@ -61,7 +63,10 @@ attr_line_t &attr_line_t::with_ansi_string(const std::string &str) return *this; } -attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_settings *tws) +attr_line_t& +attr_line_t::insert(size_t index, + const attr_line_t& al, + text_wrap_settings* tws) { if (index < this->al_string.length()) { shift_string_attrs(this->al_attrs, index, al.al_string.length()); @@ -69,10 +74,10 @@ attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_ this->al_string.insert(index, al.al_string); - for (auto &sa : al.al_attrs) { + for (auto& sa : al.al_attrs) { this->al_attrs.emplace_back(sa); - line_range &lr = this->al_attrs.back().sa_range; + line_range& lr = this->al_attrs.back().sa_range; lr.shift(0, index); if (lr.lr_end == -1) { @@ -80,7 +85,7 @@ attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_ } } - if (tws != nullptr && (int)this->al_string.length() > tws->tws_width) { + if (tws != nullptr && (int) this->al_string.length() > tws->tws_width) { ssize_t start_pos = index; ssize_t line_start = this->al_string.rfind('\n', start_pos); @@ -92,26 +97,27 @@ attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_ ssize_t line_len = index - line_start; ssize_t usable_width = tws->tws_width - tws->tws_indent; - ssize_t avail = std::max((ssize_t) 0, (ssize_t) tws->tws_width - line_len); + ssize_t avail + = std::max((ssize_t) 0, (ssize_t) tws->tws_width - line_len); if (avail == 0) { avail = INT_MAX; } - while (start_pos < (int)this->al_string.length()) { + while (start_pos < (int) this->al_string.length()) { ssize_t lpc; // Find the end of a word or a breakpoint. - for (lpc = start_pos; - lpc < (int)this->al_string.length() && - (isalnum(this->al_string[lpc]) || - this->al_string[lpc] == ',' || - this->al_string[lpc] == '_' || - this->al_string[lpc] == '.' || - this->al_string[lpc] == ';'); - lpc++) { - if (this->al_string[lpc] == '-' || - this->al_string[lpc] == '.') { + for (lpc = start_pos; lpc < (int) this->al_string.length() + && (isalnum(this->al_string[lpc]) + || this->al_string[lpc] == ',' + || this->al_string[lpc] == '_' + || this->al_string[lpc] == '.' + || this->al_string[lpc] == ';'); + lpc++) + { + if (this->al_string[lpc] == '-' || this->al_string[lpc] == '.') + { lpc += 1; break; } @@ -126,15 +132,15 @@ attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_ } else { // There's still room to add stuff. avail -= (lpc - start_pos); - while (lpc < (int)this->al_string.length() && avail) { + while (lpc < (int) this->al_string.length() && avail) { if (this->al_string[lpc] == '\n') { this->insert(lpc + 1, tws->tws_indent, ' '); avail = usable_width; lpc += 1 + tws->tws_indent; break; } - if (isalnum(this->al_string[lpc]) || - this->al_string[lpc] == '_') { + if (isalnum(this->al_string[lpc]) + || this->al_string[lpc] == '_') { break; } avail -= 1; @@ -147,10 +153,10 @@ attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_ start_pos += 1 + tws->tws_indent; avail = usable_width; - for (lpc = start_pos; - lpc < (int)this->al_string.length() && - this->al_string[lpc] == ' '; - lpc++) { + for (lpc = start_pos; lpc < (int) this->al_string.length() + && this->al_string[lpc] == ' '; + lpc++) + { } if (lpc != start_pos) { @@ -164,7 +170,8 @@ attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_ return *this; } -attr_line_t attr_line_t::subline(size_t start, size_t len) const +attr_line_t +attr_line_t::subline(size_t start, size_t len) const { if (len == std::string::npos) { len = this->al_string.length() - start; @@ -174,16 +181,17 @@ attr_line_t attr_line_t::subline(size_t start, size_t len) const attr_line_t retval; retval.al_string = this->al_string.substr(start, len); - for (auto &sa : this->al_attrs) { + for (auto& sa : this->al_attrs) { if (!lr.intersects(sa.sa_range)) { continue; } - retval.al_attrs.emplace_back(lr.intersection(sa.sa_range) - .shift(lr.lr_start, -lr.lr_start), - sa.sa_type, sa.sa_value); + retval.al_attrs.emplace_back( + lr.intersection(sa.sa_range).shift(lr.lr_start, -lr.lr_start), + sa.sa_type, + sa.sa_value); - line_range &last_lr = retval.al_attrs.back().sa_range; + line_range& last_lr = retval.al_attrs.back().sa_range; ensure(last_lr.lr_end <= (int) retval.al_string.length()); } @@ -191,7 +199,8 @@ attr_line_t attr_line_t::subline(size_t start, size_t len) const return retval; } -void attr_line_t::split_lines(std::vector &lines) const +void +attr_line_t::split_lines(std::vector& lines) const { size_t pos = 0, next_line; @@ -202,12 +211,13 @@ void attr_line_t::split_lines(std::vector &lines) const lines.emplace_back(this->subline(pos)); } -attr_line_t &attr_line_t::right_justify(unsigned long width) +attr_line_t& +attr_line_t::right_justify(unsigned long width) { long padding = width - this->length(); if (padding > 0) { this->al_string.insert(0, padding, ' '); - for (auto &al_attr : this->al_attrs) { + for (auto& al_attr : this->al_attrs) { if (al_attr.sa_range.lr_start > 0) { al_attr.sa_range.lr_start += padding; } @@ -220,7 +230,8 @@ attr_line_t &attr_line_t::right_justify(unsigned long width) return *this; } -size_t attr_line_t::nearest_text(size_t x) const +size_t +attr_line_t::nearest_text(size_t x) const { if (x > 0 && x >= (size_t) this->length()) { if (this->empty()) { @@ -237,18 +248,18 @@ size_t attr_line_t::nearest_text(size_t x) const return x; } -void attr_line_t::apply_hide() +void +attr_line_t::apply_hide() { auto& sa = this->al_attrs; - for (auto &sattr : sa) { - if (sattr.sa_type == &SA_HIDDEN && - sattr.sa_range.length() > 3) { - struct line_range &lr = sattr.sa_range; + for (auto& sattr : sa) { + if (sattr.sa_type == &SA_HIDDEN && sattr.sa_range.length() > 3) { + struct line_range& lr = sattr.sa_range; - std::for_each(sa.begin(), sa.end(), [&] (string_attr &attr) { - if (attr.sa_type == &view_curses::VC_STYLE && - lr.contains(attr.sa_range)) { + std::for_each(sa.begin(), sa.end(), [&](string_attr& attr) { + if (attr.sa_type == &view_curses::VC_STYLE + && lr.contains(attr.sa_range)) { attr.sa_type = &SA_REMOVED; } }); @@ -258,7 +269,6 @@ void attr_line_t::apply_hide() sattr.sa_type = &view_curses::VC_ROLE; sattr.sa_value.sav_int = view_colors::VCR_HIDDEN; lr.lr_end = lr.lr_start + 3; - } } } diff --git a/src/attr_line.hh b/src/attr_line.hh index 164f7db0..ffe2f08a 100644 --- a/src/attr_line.hh +++ b/src/attr_line.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -32,14 +32,14 @@ #ifndef attr_line_hh #define attr_line_hh -#include - #include #include +#include + +#include "base/intern_string.hh" #include "base/lnav_log.hh" #include "base/string_util.hh" -#include "base/intern_string.hh" #include "string_attr_type.hh" /** @@ -49,9 +49,11 @@ struct line_range { int lr_start; int lr_end; - explicit line_range(int start = -1, int end = -1) : lr_start(start), lr_end(end) { }; + explicit line_range(int start = -1, int end = -1) + : lr_start(start), lr_end(end){}; - bool is_valid() const { + bool is_valid() const + { return this->lr_start != -1; } @@ -60,19 +62,23 @@ struct line_range { return this->lr_end == -1 ? INT_MAX : this->lr_end - this->lr_start; }; - bool contains(int pos) const { + bool contains(int pos) const + { return this->lr_start <= pos && pos < this->lr_end; }; - bool contains(const struct line_range &other) const { + bool contains(const struct line_range& other) const + { return this->contains(other.lr_start) && other.lr_end <= this->lr_end; }; - bool intersects(const struct line_range &other) const { + bool intersects(const struct line_range& other) const + { return this->contains(other.lr_start) || this->contains(other.lr_end); }; - line_range intersection(const struct line_range &other) const { + line_range intersection(const struct line_range& other) const + { int actual_end; if (this->lr_end == -1) { @@ -85,7 +91,8 @@ struct line_range { return line_range{std::max(this->lr_start, other.lr_start), actual_end}; }; - line_range &shift(int32_t start, int32_t amount) { + line_range& shift(int32_t start, int32_t amount) + { if (this->lr_start >= start) { this->lr_start = std::max(0, this->lr_start + amount); } @@ -99,35 +106,46 @@ struct line_range { return *this; }; - void ltrim(const char *str) { + void ltrim(const char* str) + { while (this->lr_start < this->lr_end && isspace(str[this->lr_start])) { this->lr_start += 1; } }; - bool operator<(const struct line_range &rhs) const + bool operator<(const struct line_range& rhs) const { - if (this->lr_start < rhs.lr_start) { return true; } - else if (this->lr_start > rhs.lr_start) { return false; } + if (this->lr_start < rhs.lr_start) { + return true; + } else if (this->lr_start > rhs.lr_start) { + return false; + } - if (this->lr_end == rhs.lr_end) { return false; } + if (this->lr_end == rhs.lr_end) { + return false; + } - if (this->lr_end < rhs.lr_end) { return true; } + if (this->lr_end < rhs.lr_end) { + return true; + } return false; }; - bool operator==(const struct line_range &rhs) const { + bool operator==(const struct line_range& rhs) const + { return (this->lr_start == rhs.lr_start && this->lr_end == rhs.lr_end); }; - const char *substr(const std::string &str) const { + const char* substr(const std::string& str) const + { if (this->lr_start == -1) { return str.c_str(); } return &(str.c_str()[this->lr_start]); } - size_t sublen(const std::string &str) const { + size_t sublen(const std::string& str) const + { if (this->lr_start == -1) { return str.length(); } @@ -142,53 +160,67 @@ struct line_range { * Container for attribute values for a substring. */ typedef union { - const void *sav_ptr; + const void* sav_ptr; int64_t sav_int; } string_attr_value_t; struct string_attr { - string_attr(const struct line_range &lr, string_attr_type_t type, void *val) - : sa_range(lr), sa_type(type) { + string_attr(const struct line_range& lr, string_attr_type_t type, void* val) + : sa_range(lr), sa_type(type) + { require(lr.is_valid()); require(type); this->sa_value.sav_ptr = val; }; - string_attr(const struct line_range &lr, string_attr_type_t type, std::string val) - : sa_range(lr), sa_type(type), sa_str_value(std::move(val)) { + string_attr(const struct line_range& lr, + string_attr_type_t type, + std::string val) + : sa_range(lr), sa_type(type), sa_str_value(std::move(val)) + { require(lr.is_valid()); require(type); }; - string_attr(const struct line_range &lr, string_attr_type_t type, intern_string_t val) - : sa_range(lr), sa_type(type) { + string_attr(const struct line_range& lr, + string_attr_type_t type, + intern_string_t val) + : sa_range(lr), sa_type(type) + { require(lr.is_valid()); require(type); this->sa_value.sav_ptr = val.unwrap(); }; - string_attr(const struct line_range &lr, string_attr_type_t type, int64_t val = 0) - : sa_range(lr), sa_type(type) { + string_attr(const struct line_range& lr, + string_attr_type_t type, + int64_t val = 0) + : sa_range(lr), sa_type(type) + { require(lr.is_valid()); require(type); this->sa_value.sav_int = val; }; - string_attr(const struct line_range &lr, string_attr_type_t type, string_attr_value_t val) - : sa_range(lr), sa_type(type), sa_value(val) { + string_attr(const struct line_range& lr, + string_attr_type_t type, + string_attr_value_t val) + : sa_range(lr), sa_type(type), sa_value(val) + { require(lr.is_valid()); require(type); }; - string_attr() : sa_type(nullptr) { }; + string_attr() : sa_type(nullptr){}; - bool operator<(const struct string_attr &rhs) const + bool operator<(const struct string_attr& rhs) const { return this->sa_range < rhs.sa_range; }; - intern_string_t to_string() const { - return intern_string_t((const intern_string *) this->sa_value.sav_ptr); + intern_string_t to_string() const + { + return intern_string_t((const intern_string*) this->sa_value.sav_ptr); }; struct line_range sa_range; @@ -201,7 +233,9 @@ struct string_attr { typedef std::vector string_attrs_t; inline string_attrs_t::const_iterator -find_string_attr(const string_attrs_t &sa, string_attr_type_t type, int start = 0) +find_string_attr(const string_attrs_t& sa, + string_attr_type_t type, + int start = 0) { string_attrs_t::const_iterator iter; @@ -215,7 +249,9 @@ find_string_attr(const string_attrs_t &sa, string_attr_type_t type, int start = } inline nonstd::optional -get_string_attr(const string_attrs_t &sa, string_attr_type_t type, int start = 0) +get_string_attr(const string_attrs_t& sa, + string_attr_type_t type, + int start = 0) { auto iter = find_string_attr(sa, type, start); @@ -228,7 +264,9 @@ get_string_attr(const string_attrs_t &sa, string_attr_type_t type, int start = 0 template inline string_attrs_t::const_iterator -find_string_attr_containing(const string_attrs_t &sa, string_attr_type_t type, T x) +find_string_attr_containing(const string_attrs_t& sa, + string_attr_type_t type, + T x) { string_attrs_t::const_iterator iter; @@ -242,7 +280,7 @@ find_string_attr_containing(const string_attrs_t &sa, string_attr_type_t type, T } inline string_attrs_t::iterator -find_string_attr(string_attrs_t &sa, const struct line_range &lr) +find_string_attr(string_attrs_t& sa, const struct line_range& lr) { string_attrs_t::iterator iter; @@ -256,13 +294,13 @@ find_string_attr(string_attrs_t &sa, const struct line_range &lr) } inline string_attrs_t::const_iterator -find_string_attr(const string_attrs_t &sa, size_t near) +find_string_attr(const string_attrs_t& sa, size_t near) { string_attrs_t::const_iterator iter, nearest = sa.end(); ssize_t last_diff = INT_MAX; for (iter = sa.begin(); iter != sa.end(); ++iter) { - auto &lr = iter->sa_range; + auto& lr = iter->sa_range; if (!lr.is_valid() || !lr.contains(near)) { continue; @@ -280,13 +318,13 @@ find_string_attr(const string_attrs_t &sa, size_t near) template inline string_attrs_t::const_iterator -rfind_string_attr_if(const string_attrs_t &sa, ssize_t near, T predicate) +rfind_string_attr_if(const string_attrs_t& sa, ssize_t near, T predicate) { string_attrs_t::const_iterator iter, nearest = sa.end(); ssize_t last_diff = INT_MAX; for (iter = sa.begin(); iter != sa.end(); ++iter) { - auto &lr = iter->sa_range; + auto& lr = iter->sa_range; if (lr.lr_start > near) { continue; @@ -307,7 +345,7 @@ rfind_string_attr_if(const string_attrs_t &sa, ssize_t near, T predicate) } inline struct line_range -find_string_attr_range(const string_attrs_t &sa, string_attr_type_t type) +find_string_attr_range(const string_attrs_t& sa, string_attr_type_t type) { auto iter = find_string_attr(sa, type); @@ -318,7 +356,8 @@ find_string_attr_range(const string_attrs_t &sa, string_attr_type_t type) return line_range(); } -inline void remove_string_attr(string_attrs_t &sa, const struct line_range &lr) +inline void +remove_string_attr(string_attrs_t& sa, const struct line_range& lr) { string_attrs_t::iterator iter; @@ -327,7 +366,8 @@ inline void remove_string_attr(string_attrs_t &sa, const struct line_range &lr) } } -inline void remove_string_attr(string_attrs_t &sa, string_attr_type_t type) +inline void +remove_string_attr(string_attrs_t& sa, string_attr_type_t type) { for (auto iter = sa.begin(); iter != sa.end();) { if (iter->sa_type == type) { @@ -338,22 +378,25 @@ inline void remove_string_attr(string_attrs_t &sa, string_attr_type_t type) } } -inline void shift_string_attrs(string_attrs_t &sa, int32_t start, int32_t amount) +inline void +shift_string_attrs(string_attrs_t& sa, int32_t start, int32_t amount) { - for (auto &iter : sa) { + for (auto& iter : sa) { iter.sa_range.shift(start, amount); } } struct text_wrap_settings { - text_wrap_settings() : tws_indent(2), tws_width(80) {}; + text_wrap_settings() : tws_indent(2), tws_width(80){}; - text_wrap_settings &with_indent(int indent) { + text_wrap_settings& with_indent(int indent) + { this->tws_indent = indent; return *this; }; - text_wrap_settings &with_width(int width) { + text_wrap_settings& with_width(int width) + { this->tws_width = width; return *this; }; @@ -367,62 +410,80 @@ struct text_wrap_settings { */ class attr_line_t { public: - attr_line_t() { + attr_line_t() + { this->al_attrs.reserve(RESERVE_SIZE); }; - attr_line_t(std::string str) : al_string(std::move(str)) { + attr_line_t(std::string str) : al_string(std::move(str)) + { this->al_attrs.reserve(RESERVE_SIZE); }; - attr_line_t(const char *str) : al_string(str) { + attr_line_t(const char* str) : al_string(str) + { this->al_attrs.reserve(RESERVE_SIZE); }; - static inline attr_line_t from_ansi_str(const char *str) { + static inline attr_line_t from_ansi_str(const char* str) + { attr_line_t retval; return retval.with_ansi_string("%s", str); }; /** @return The string itself. */ - std::string &get_string() { return this->al_string; }; + std::string& get_string() + { + return this->al_string; + }; - const std::string &get_string() const { return this->al_string; }; + const std::string& get_string() const + { + return this->al_string; + }; /** @return The attributes for the string. */ - string_attrs_t &get_attrs() { return this->al_attrs; }; + string_attrs_t& get_attrs() + { + return this->al_attrs; + }; - const string_attrs_t &get_attrs() const { return this->al_attrs; }; + const string_attrs_t& get_attrs() const + { + return this->al_attrs; + }; - attr_line_t &with_string(const std::string &str) { + attr_line_t& with_string(const std::string& str) + { this->al_string = str; return *this; } - attr_line_t &with_ansi_string(const char *str, ...); + attr_line_t& with_ansi_string(const char* str, ...); - attr_line_t &with_ansi_string(const std::string &str); + attr_line_t& with_ansi_string(const std::string& str); - attr_line_t &with_attr(const string_attr &sa) { + attr_line_t& with_attr(const string_attr& sa) + { this->al_attrs.push_back(sa); return *this; }; - attr_line_t &ensure_space() { - if (!this->al_string.empty() && - this->al_string.back() != ' ' && - this->al_string.back() != '[') { + attr_line_t& ensure_space() + { + if (!this->al_string.empty() && this->al_string.back() != ' ' + && this->al_string.back() != '[') + { this->append(1, ' '); } return *this; }; - template - attr_line_t &append(S str, - string_attr_type_t type = nullptr, - T val = T()) { + template + attr_line_t& append(S str, string_attr_type_t type = nullptr, T val = T()) + { size_t start_len = this->al_string.length(); this->al_string.append(str); @@ -434,24 +495,31 @@ public: return *this; }; - attr_line_t &append(const char *str, size_t len) { + attr_line_t& append(const char* str, size_t len) + { this->al_string.append(str, len); return *this; }; - attr_line_t &insert(size_t index, const attr_line_t &al, text_wrap_settings *tws = nullptr); + attr_line_t& insert(size_t index, + const attr_line_t& al, + text_wrap_settings* tws = nullptr); - attr_line_t &append(const attr_line_t &al, text_wrap_settings *tws = nullptr) { + attr_line_t& append(const attr_line_t& al, + text_wrap_settings* tws = nullptr) + { return this->insert(this->al_string.length(), al, tws); }; - attr_line_t &append(size_t len, char c) { + attr_line_t& append(size_t len, char c) + { this->al_string.append(len, c); return *this; }; - attr_line_t &insert(size_t index, size_t len, char c) { + attr_line_t& insert(size_t index, size_t len, char c) + { this->al_string.insert(index, len, c); shift_string_attrs(this->al_attrs, index, len); @@ -459,7 +527,8 @@ public: return *this; } - attr_line_t &insert(size_t index, const char *str) { + attr_line_t& insert(size_t index, const char* str) + { this->al_string.insert(index, str); shift_string_attrs(this->al_attrs, index, strlen(str)); @@ -467,7 +536,8 @@ public: return *this; } - attr_line_t &erase(size_t pos, size_t len = std::string::npos) { + attr_line_t& erase(size_t pos, size_t len = std::string::npos) + { this->al_string.erase(pos, len); shift_string_attrs(this->al_attrs, pos, -((int32_t) len)); @@ -475,19 +545,21 @@ public: return *this; }; - attr_line_t &erase_utf8_chars(size_t start) { + attr_line_t& erase_utf8_chars(size_t start) + { auto byte_index = utf8_char_to_byte_index(this->al_string, start); this->erase(byte_index); return *this; }; - attr_line_t &right_justify(unsigned long width); + attr_line_t& right_justify(unsigned long width); - ssize_t length() const { + ssize_t length() const + { size_t retval = this->al_string.length(); - for (const auto &al_attr : this->al_attrs) { + for (const auto& al_attr : this->al_attrs) { retval = std::max(retval, (size_t) al_attr.sa_range.lr_start); if (al_attr.sa_range.lr_end != -1) { retval = std::max(retval, (size_t) al_attr.sa_range.lr_end); @@ -497,14 +569,16 @@ public: return retval; }; - std::string get_substring(const line_range &lr) const { + std::string get_substring(const line_range& lr) const + { if (!lr.is_valid()) { return ""; } return this->al_string.substr(lr.lr_start, lr.length()); }; - string_attrs_t::const_iterator find_attr(size_t near) const { + string_attrs_t::const_iterator find_attr(size_t near) const + { near = std::min(near, this->al_string.length() - 1); while (near > 0 && isspace(this->al_string[near])) { @@ -514,12 +588,13 @@ public: return find_string_attr(this->al_attrs, near); }; - bool empty() const { + bool empty() const + { return this->length() == 0; }; /** Clear the string and the attributes for the string. */ - attr_line_t &clear() + attr_line_t& clear() { this->al_string.clear(); this->al_attrs.clear(); @@ -529,7 +604,7 @@ public: attr_line_t subline(size_t start, size_t len = std::string::npos) const; - void split_lines(std::vector &lines) const; + void split_lines(std::vector& lines) const; size_t nearest_text(size_t x) const; @@ -538,7 +613,7 @@ public: private: const static size_t RESERVE_SIZE = 128; - std::string al_string; + std::string al_string; string_attrs_t al_attrs; }; diff --git a/src/auto_fd.hh b/src/auto_fd.hh index 7acf153f..3df93663 100644 --- a/src/auto_fd.hh +++ b/src/auto_fd.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -32,14 +32,14 @@ #ifndef auto_fd_hh #define auto_fd_hh +#include +#include +#include + #include #include -#include #include - -#include -#include -#include +#include #include "base/lnav_log.hh" #include "base/result.h" @@ -51,7 +51,6 @@ */ class auto_fd { public: - /** * Wrapper for the posix pipe(2) function that stores the file descriptor * results in an auto_fd array. @@ -60,7 +59,7 @@ public: * contains the reader end of the pipe and the second contains the writer. * @return The result of the pipe(2) function. */ - static int pipe(auto_fd *af) + static int pipe(auto_fd* af) { int retval, fd[2]; @@ -80,7 +79,8 @@ public: * @param fd The file descriptor to duplicate. * @return A new auto_fd that contains the duplicated file descriptor. */ - static auto_fd dup_of(int fd) { + static auto_fd dup_of(int fd) + { if (fd == -1) { return auto_fd{}; } @@ -99,8 +99,7 @@ public: * * @param fd The file descriptor to be managed. */ - explicit auto_fd(int fd = -1) - : af_fd(fd) + explicit auto_fd(int fd = -1) : af_fd(fd) { require(fd >= -1); }; @@ -112,9 +111,7 @@ public: * * @param af The source of the file descriptor. */ - auto_fd(auto_fd && af) noexcept - : af_fd(af.release()) { - }; + auto_fd(auto_fd&& af) noexcept : af_fd(af.release()){}; /** * Const copy constructor. The file descriptor from the source will be @@ -122,8 +119,7 @@ public: * * @param af The source of the file descriptor. */ - auto_fd(const auto_fd &af) - : af_fd(-1) + auto_fd(const auto_fd& af) : af_fd(-1) { if (af.af_fd != -1 && (this->af_fd = dup(af.af_fd)) == -1) { throw std::bad_alloc(); @@ -139,7 +135,10 @@ public: }; /** @return The file descriptor as a plain integer. */ - operator int() const { return this->af_fd; }; + operator int() const + { + return this->af_fd; + }; /** * Replace the current descriptor with the given one. The current @@ -148,7 +147,7 @@ public: * @param fd The file descriptor to store in this object. * @return *this */ - auto_fd &operator=(int fd) + auto_fd& operator=(int fd) { require(fd >= -1); @@ -162,7 +161,8 @@ public: * @param af The old manager of the file descriptor. * @return *this */ - auto_fd &operator=(auto_fd && af) noexcept { + auto_fd& operator=(auto_fd&& af) noexcept + { this->reset(af.release()); return *this; }; @@ -173,7 +173,7 @@ public: * * @return A pointer to the internal integer. */ - int *out() + int* out() { this->reset(); return &this->af_fd; @@ -218,7 +218,8 @@ public: } }; - void close_on_exec() const { + void close_on_exec() const + { if (this->af_fd == -1) { return; } @@ -226,12 +227,13 @@ public: } private: - int af_fd; /*< The managed file descriptor. */ + int af_fd; /*< The managed file descriptor. */ }; class auto_pipe { public: - static Result for_child_fd(int child_fd) { + static Result for_child_fd(int child_fd) + { auto_pipe retval(child_fd); if (retval.open() == -1) { @@ -245,70 +247,73 @@ public: : ap_child_flags(child_flags), ap_child_fd(child_fd) { switch (child_fd) { - case STDIN_FILENO: - this->ap_child_flags = O_RDONLY; - break; - case STDOUT_FILENO: - case STDERR_FILENO: - this->ap_child_flags = O_WRONLY; - break; + case STDIN_FILENO: + this->ap_child_flags = O_RDONLY; + break; + case STDOUT_FILENO: + case STDERR_FILENO: + this->ap_child_flags = O_WRONLY; + break; } }; - int open() { + int open() + { return auto_fd::pipe(this->ap_fd); }; - void close() { + void close() + { this->ap_fd[0].reset(); this->ap_fd[1].reset(); }; - auto_fd &read_end() { + auto_fd& read_end() + { return this->ap_fd[0]; }; - auto_fd &write_end() { + auto_fd& write_end() + { return this->ap_fd[1]; }; - void after_fork(pid_t child_pid) { + void after_fork(pid_t child_pid) + { int new_fd; switch (child_pid) { - case -1: - this->close(); - break; - case 0: - if (this->ap_child_flags == O_RDONLY) { - this->write_end().reset(); - if (this->read_end().get() == -1) { - this->read_end() = ::open("/dev/null", O_RDONLY); + case -1: + this->close(); + break; + case 0: + if (this->ap_child_flags == O_RDONLY) { + this->write_end().reset(); + if (this->read_end().get() == -1) { + this->read_end() = ::open("/dev/null", O_RDONLY); + } + new_fd = this->read_end().get(); + } else { + this->read_end().reset(); + if (this->write_end().get() == -1) { + this->write_end() = ::open("/dev/null", O_WRONLY); + } + new_fd = this->write_end().get(); } - new_fd = this->read_end().get(); - } - else { - this->read_end().reset(); - if (this->write_end().get() == -1) { - this->write_end() = ::open("/dev/null", O_WRONLY); + if (this->ap_child_fd != -1) { + if (new_fd != this->ap_child_fd) { + dup2(new_fd, this->ap_child_fd); + this->close(); + } } - new_fd = this->write_end().get(); - } - if (this->ap_child_fd != -1) { - if (new_fd != this->ap_child_fd) { - dup2(new_fd, this->ap_child_fd); - this->close(); + break; + default: + if (this->ap_child_flags == O_RDONLY) { + this->read_end().reset(); + } else { + this->write_end().reset(); } - } - break; - default: - if (this->ap_child_flags == O_RDONLY) { - this->read_end().reset(); - } - else { - this->write_end().reset(); - } - break; + break; } }; diff --git a/src/auto_mem.hh b/src/auto_mem.hh index 68ab9581..6c1b3d60 100644 --- a/src/auto_mem.hh +++ b/src/auto_mem.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -32,15 +32,15 @@ #ifndef lnav_auto_mem_hh #define lnav_auto_mem_hh +#include + +#include #include #include -#include - -#include #include "base/result.h" -typedef void (*free_func_t)(void *); +typedef void (*free_func_t)(void*); /** * Resource management class for memory allocated by a custom allocator. @@ -51,126 +51,149 @@ typedef void (*free_func_t)(void *); template class auto_mem { public: - explicit auto_mem(T *ptr = nullptr) - : am_ptr(ptr), am_free_func(default_free) { - }; + explicit auto_mem(T* ptr = nullptr) + : am_ptr(ptr), am_free_func(default_free){}; - auto_mem(const auto_mem &am) = delete; + auto_mem(const auto_mem& am) = delete; template explicit auto_mem(F free_func) noexcept - : am_ptr(nullptr), am_free_func((free_func_t)free_func) { }; + : am_ptr(nullptr), am_free_func((free_func_t) free_func){}; - auto_mem(auto_mem &&other) noexcept - : am_ptr(other.release()), - am_free_func(other.am_free_func) { - }; + auto_mem(auto_mem&& other) noexcept + : am_ptr(other.release()), am_free_func(other.am_free_func){}; - ~auto_mem() { + ~auto_mem() + { this->reset(); }; - operator T *() const { return this->am_ptr; }; + operator T*() const + { + return this->am_ptr; + }; - auto_mem &operator =(T *ptr) + auto_mem& operator=(T* ptr) { this->reset(ptr); return *this; }; - auto_mem &operator=(auto_mem &) = delete; + auto_mem& operator=(auto_mem&) = delete; - auto_mem &operator =(auto_mem && am) noexcept + auto_mem& operator=(auto_mem&& am) noexcept { this->reset(am.release()); this->am_free_func = am.am_free_func; return *this; }; - T *release() + T* release() { - T *retval = this->am_ptr; + T* retval = this->am_ptr; this->am_ptr = nullptr; return retval; }; - T *in() const + T* in() const { return this->am_ptr; }; - T **out() + T** out() { this->reset(); return &this->am_ptr; }; - void reset(T *ptr = nullptr) + void reset(T* ptr = nullptr) { if (this->am_ptr != ptr) { if (this->am_ptr != nullptr) { - this->am_free_func((void *)this->am_ptr); + this->am_free_func((void*) this->am_ptr); } this->am_ptr = ptr; } }; private: - T * am_ptr; - void (*am_free_func)(void *); + T* am_ptr; + void (*am_free_func)(void*); }; -template +template class static_root_mem { public: - static_root_mem() { + static_root_mem() + { memset(&this->srm_value, 0, sizeof(T)); }; - ~static_root_mem() { free_func(&this->srm_value); }; + ~static_root_mem() + { + free_func(&this->srm_value); + }; - const T *operator->() const { return &this->srm_value; }; + const T* operator->() const + { + return &this->srm_value; + }; - const T &in() const { return this->srm_value; }; + const T& in() const + { + return this->srm_value; + }; - T *inout() { + T* inout() + { free_func(&this->srm_value); memset(&this->srm_value, 0, sizeof(T)); return &this->srm_value; }; private: - static_root_mem &operator =(T &) { return *this; }; + static_root_mem& operator=(T&) + { + return *this; + }; - static_root_mem &operator =(static_root_mem &) { return *this; }; + static_root_mem& operator=(static_root_mem&) + { + return *this; + }; T srm_value; }; class auto_buffer { public: - static auto_buffer alloc(size_t size) { - return auto_buffer{ (char *) malloc(size), size }; + static auto_buffer alloc(size_t size) + { + return auto_buffer{(char*) malloc(size), size}; } auto_buffer(auto_buffer&& other) noexcept - : ab_buffer(other.ab_buffer), ab_size(other.ab_size) { + : ab_buffer(other.ab_buffer), ab_size(other.ab_size) + { other.ab_buffer = nullptr; other.ab_size = 0; } - ~auto_buffer() { + ~auto_buffer() + { free(this->ab_buffer); this->ab_buffer = nullptr; this->ab_size = 0; } - char *in() { + char* in() + { return this->ab_buffer; } - std::pair release() { + std::pair release() + { auto retval = std::make_pair(this->ab_buffer, this->ab_size); this->ab_buffer = nullptr; @@ -178,16 +201,18 @@ public: return retval; } - size_t size() const { + size_t size() const + { return this->ab_size; } - void expand_by(size_t amount) { + void expand_by(size_t amount) + { if (amount == 0) { return; } auto new_size = this->ab_size + amount; - auto new_buffer = (char *) realloc(this->ab_buffer, new_size); + auto new_buffer = (char*) realloc(this->ab_buffer, new_size); if (new_buffer == nullptr) { throw std::bad_alloc(); @@ -197,15 +222,16 @@ public: this->ab_size = new_size; } - auto_buffer& shrink_to(size_t new_size) { + auto_buffer& shrink_to(size_t new_size) + { this->ab_size = new_size; return *this; } + private: - auto_buffer(char *buffer, size_t size) : ab_buffer(buffer), ab_size(size) { - } + auto_buffer(char* buffer, size_t size) : ab_buffer(buffer), ab_size(size) {} - char *ab_buffer; + char* ab_buffer; size_t ab_size; }; diff --git a/src/base/auto_pid.cc b/src/base/auto_pid.cc index 0b006451..300a4741 100644 --- a/src/base/auto_pid.cc +++ b/src/base/auto_pid.cc @@ -21,23 +21,24 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" +#include "auto_pid.hh" #include -#include "lnav_log.hh" +#include "config.h" #include "fmt/format.h" -#include "auto_pid.hh" +#include "lnav_log.hh" namespace lnav { namespace pid { -Result, std::string> from_fork() +Result, std::string> +from_fork() { auto pid = ::fork(); @@ -49,7 +50,7 @@ Result, std::string> from_fork() log_debug("started child: %d", pid); } - return Ok(auto_pid(pid)); -} -} + return Ok(auto_pid(pid)); } +} // namespace pid +} // namespace lnav diff --git a/src/base/auto_pid.hh b/src/base/auto_pid.hh index 7a9077c4..de4a84a5 100644 --- a/src/base/auto_pid.hh +++ b/src/base/auto_pid.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -32,50 +32,58 @@ #ifndef auto_pid_hh #define auto_pid_hh -#include -#include +#include +#include + #include #include -#include "base/result.h" #include "base/lnav_log.hh" +#include "base/result.h" #include "mapbox/variant.hpp" enum class process_state { - RUNNING, - FINISHED, + running, + finished, }; template class auto_pid { public: - explicit auto_pid(pid_t child, int status = 0) : ap_child(child), - ap_status(status) - {}; + explicit auto_pid(pid_t child, int status = 0) + : ap_child(child), ap_status(status) + { + } - auto_pid(const auto_pid &other) = delete; + auto_pid(const auto_pid& other) = delete; - auto_pid(auto_pid &&other) noexcept - : ap_child(std::move(other).release()), - ap_status(other.ap_status) - {}; + auto_pid(auto_pid&& other) noexcept + : ap_child(std::move(other).release()), ap_status(other.ap_status) + { + } ~auto_pid() noexcept - { this->reset(); }; + { + this->reset(); + } - auto_pid &operator=(auto_pid &&other) noexcept + auto_pid& operator=(auto_pid&& other) noexcept { this->reset(std::move(other).release()); this->ap_status = other.ap_status; return *this; - }; + } + + auto_pid& operator=(const auto_pid& other) = delete; pid_t in() const - { return this->ap_child; } + { + return this->ap_child; + } bool in_child() const { - static_assert(ProcState == process_state::RUNNING, + static_assert(ProcState == process_state::running, "this method is only available in the RUNNING state"); return this->ap_child == 0; }; @@ -87,31 +95,31 @@ public: int status() const { - static_assert(ProcState == process_state::FINISHED, + static_assert(ProcState == process_state::finished, "wait_for_child() must be called first"); return this->ap_status; }; bool was_normal_exit() const { - static_assert(ProcState == process_state::FINISHED, + static_assert(ProcState == process_state::finished, "wait_for_child() must be called first"); return WIFEXITED(this->ap_status); } int exit_status() const { - static_assert(ProcState == process_state::FINISHED, + static_assert(ProcState == process_state::finished, "wait_for_child() must be called first"); return WEXITSTATUS(this->ap_status); } - using poll_result = mapbox::util::variant< - auto_pid, - auto_pid - >; + using poll_result + = mapbox::util::variant, + auto_pid>; - poll_result poll() && { + poll_result poll() && + { if (this->ap_child != -1) { auto rc = waitpid(this->ap_child, &this->ap_status, WNOHANG); @@ -120,20 +128,21 @@ public: } } - return auto_pid( + return auto_pid( std::exchange(this->ap_child, -1), this->ap_status); } - auto_pid wait_for_child(int options = 0) && + auto_pid wait_for_child(int options = 0) && { if (this->ap_child != -1) { - while ((waitpid(this->ap_child, - &this->ap_status, - options)) < 0 && (errno == EINTR)) { ; + while ((waitpid(this->ap_child, &this->ap_status, options)) < 0 + && (errno == EINTR)) + { + ; } } - return auto_pid( + return auto_pid( std::exchange(this->ap_child, -1), this->ap_status); } @@ -141,7 +150,7 @@ public: { if (this->ap_child != child) { this->ap_status = 0; - if (ProcState == process_state::RUNNING && this->ap_child != -1) { + if (ProcState == process_state::running && this->ap_child != -1) { log_debug("sending SIGTERM to child: %d", this->ap_child); kill(this->ap_child, SIGTERM); } @@ -156,8 +165,8 @@ private: namespace lnav { namespace pid { -Result, std::string> from_fork(); -} -} +Result, std::string> from_fork(); +} // namespace pid +} // namespace lnav #endif diff --git a/src/base/date_time_scanner.cc b/src/base/date_time_scanner.cc index 6e3aab8d..ef05558a 100644 --- a/src/base/date_time_scanner.cc +++ b/src/base/date_time_scanner.cc @@ -21,20 +21,21 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file date_time_scanner.cc */ -#include "config.h" - #include "date_time_scanner.hh" + +#include "config.h" #include "ptimec.hh" -size_t date_time_scanner::ftime(char *dst, size_t len, const exttm &tm) const +size_t +date_time_scanner::ftime(char* dst, size_t len, const exttm& tm) const { off_t off = 0; @@ -43,7 +44,8 @@ size_t date_time_scanner::ftime(char *dst, size_t len, const exttm &tm) const return (size_t) off; } -bool next_format(const char * const fmt[], int &index, int &locked_index) +bool +next_format(const char* const fmt[], int& index, int& locked_index) { bool retval = true; @@ -52,40 +54,35 @@ bool next_format(const char * const fmt[], int &index, int &locked_index) if (fmt[index] == nullptr) { retval = false; } - } - else if (index == locked_index) { + } else if (index == locked_index) { retval = false; - } - else { + } else { index = locked_index; } return retval; } -const char *date_time_scanner::scan(const char *time_dest, - size_t time_len, - const char * const time_fmt[], - struct exttm *tm_out, - struct timeval &tv_out, - bool convert_local) +const char* +date_time_scanner::scan(const char* time_dest, + size_t time_len, + const char* const time_fmt[], + struct exttm* tm_out, + struct timeval& tv_out, + bool convert_local) { - int curr_time_fmt = -1; - bool found = false; - const char *retval = nullptr; + int curr_time_fmt = -1; + bool found = false; + const char* retval = nullptr; if (!time_fmt) { time_fmt = PTIMEC_FORMAT_STR; } - while (next_format(time_fmt, - curr_time_fmt, - this->dts_fmt_lock)) { + while (next_format(time_fmt, curr_time_fmt, this->dts_fmt_lock)) { *tm_out = this->dts_base_tm; tm_out->et_flags = 0; - if (time_len > 1 && - time_dest[0] == '+' && - isdigit(time_dest[1])) { + if (time_len > 1 && time_dest[0] == '+' && isdigit(time_dest[1])) { char time_cp[time_len + 1]; int gmt_int, off; @@ -105,7 +102,8 @@ const char *date_time_scanner::scan(const char *time_dest, } tv_out.tv_sec = gmt; tv_out.tv_usec = 0; - tm_out->et_flags = ETF_DAY_SET|ETF_MONTH_SET|ETF_YEAR_SET|ETF_MACHINE_ORIENTED|ETF_EPOCH_TIME; + tm_out->et_flags = ETF_DAY_SET | ETF_MONTH_SET | ETF_YEAR_SET + | ETF_MACHINE_ORIENTED | ETF_EPOCH_TIME; this->dts_fmt_lock = curr_time_fmt; this->dts_fmt_len = off; @@ -113,8 +111,7 @@ const char *date_time_scanner::scan(const char *time_dest, found = true; break; } - } - else if (time_fmt == PTIMEC_FORMAT_STR) { + } else if (time_fmt == PTIMEC_FORMAT_STR) { ptime_func func = PTIMEC_FORMATS[curr_time_fmt].pf_func; off_t off = 0; @@ -129,8 +126,10 @@ const char *date_time_scanner::scan(const char *time_dest, if (tm_out->et_tm.tm_year < 70) { tm_out->et_tm.tm_year = 80; } - if (convert_local && - (this->dts_local_time || tm_out->et_flags & ETF_EPOCH_TIME)) { + if (convert_local + && (this->dts_local_time + || tm_out->et_flags & ETF_EPOCH_TIME)) + { time_t gmt = tm2sec(&tm_out->et_tm); this->to_localtime(gmt, *tm_out); @@ -140,13 +139,12 @@ const char *date_time_scanner::scan(const char *time_dest, secs2wday(tv_out, &tm_out->et_tm); this->dts_fmt_lock = curr_time_fmt; - this->dts_fmt_len = retval - time_dest; + this->dts_fmt_len = retval - time_dest; found = true; break; } - } - else { + } else { off_t off = 0; #ifdef HAVE_STRUCT_TM_TM_ZONE @@ -154,14 +152,19 @@ const char *date_time_scanner::scan(const char *time_dest, tm_out->et_tm.tm_zone = nullptr; } #endif - if (ptime_fmt(time_fmt[curr_time_fmt], tm_out, time_dest, off, time_len) && - (time_dest[off] == '.' || time_dest[off] == ',' || off == (off_t)time_len)) { + if (ptime_fmt( + time_fmt[curr_time_fmt], tm_out, time_dest, off, time_len) + && (time_dest[off] == '.' || time_dest[off] == ',' + || off == (off_t) time_len)) + { retval = &time_dest[off]; if (tm_out->et_tm.tm_year < 70) { tm_out->et_tm.tm_year = 80; } - if (convert_local && - (this->dts_local_time || tm_out->et_flags & ETF_EPOCH_TIME)) { + if (convert_local + && (this->dts_local_time + || tm_out->et_flags & ETF_EPOCH_TIME)) + { time_t gmt = tm2sec(&tm_out->et_tm); this->to_localtime(gmt, *tm_out); @@ -176,7 +179,7 @@ const char *date_time_scanner::scan(const char *time_dest, secs2wday(tv_out, &tm_out->et_tm); this->dts_fmt_lock = curr_time_fmt; - this->dts_fmt_len = retval - time_dest; + this->dts_fmt_len = retval - time_dest; found = true; break; @@ -197,8 +200,7 @@ const char *date_time_scanner::scan(const char *time_dest, tv_out.tv_usec = tm_out->et_nsec / 1000; this->dts_fmt_len += 7; retval += 7; - } - else if (ptime_L(tm_out, time_dest, off, time_len)) { + } else if (ptime_L(tm_out, time_dest, off, time_len)) { tv_out.tv_usec = tm_out->et_nsec / 1000; this->dts_fmt_len += 4; retval += 4; @@ -209,15 +211,16 @@ const char *date_time_scanner::scan(const char *time_dest, return retval; } -void date_time_scanner::to_localtime(time_t t, exttm &tm_out) +void +date_time_scanner::to_localtime(time_t t, exttm& tm_out) { if (t < (24 * 60 * 60)) { // Don't convert and risk going past the epoch. return; } - if (t < this->dts_local_offset_valid || - t >= this->dts_local_offset_expiry) { + if (t < this->dts_local_offset_valid || t >= this->dts_local_offset_expiry) + { time_t new_gmt; localtime_r(&t, &tm_out.et_tm); @@ -230,10 +233,9 @@ void date_time_scanner::to_localtime(time_t t, exttm &tm_out) this->dts_local_offset_cache = t - new_gmt; this->dts_local_offset_valid = t; this->dts_local_offset_expiry = t + (EXPIRE_TIME - 1); - this->dts_local_offset_expiry -= - this->dts_local_offset_expiry % EXPIRE_TIME; - } - else { + this->dts_local_offset_expiry + -= this->dts_local_offset_expiry % EXPIRE_TIME; + } else { time_t adjust_gmt = t - this->dts_local_offset_cache; gmtime_r(&adjust_gmt, &tm_out.et_tm); } diff --git a/src/base/date_time_scanner.hh b/src/base/date_time_scanner.hh index a85fd50c..ae4345ec 100644 --- a/src/base/date_time_scanner.hh +++ b/src/base/date_time_scanner.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -32,11 +32,11 @@ #ifndef lnav_date_time_scanner_hh #define lnav_date_time_scanner_hh -#include -#include - #include +#include +#include + #include "time_util.hh" /** @@ -47,11 +47,13 @@ * an exttm struct to a string using the ftime() method. */ struct date_time_scanner { - date_time_scanner() { + date_time_scanner() + { this->clear(); }; - void clear() { + void clear() + { this->dts_base_time = 0; memset(&this->dts_base_tm, 0, sizeof(this->dts_base_tm)); this->dts_fmt_lock = -1; @@ -61,12 +63,14 @@ struct date_time_scanner { /** * Unlock this scanner so that the format is rediscovered. */ - void unlock() { + void unlock() + { this->dts_fmt_lock = -1; this->dts_fmt_len = -1; } - void set_base_time(time_t base_time) { + void set_base_time(time_t base_time) + { this->dts_base_time = base_time; localtime_r(&base_time, &this->dts_base_tm.et_tm); }; @@ -78,7 +82,7 @@ struct date_time_scanner { * every call, so we cache the result and only call it again if the * requested time falls outside of a fifteen minute range. */ - void to_localtime(time_t t, struct exttm &tm_out); + void to_localtime(time_t t, struct exttm& tm_out); bool dts_keep_base_tz{false}; bool dts_local_time{false}; @@ -92,19 +96,20 @@ struct date_time_scanner { static const int EXPIRE_TIME = 15 * 60; - const char *scan(const char *time_src, + const char* scan(const char* time_src, size_t time_len, - const char * const time_fmt[], - struct exttm *tm_out, - struct timeval &tv_out, + const char* const time_fmt[], + struct exttm* tm_out, + struct timeval& tv_out, bool convert_local = true); - size_t ftime(char *dst, size_t len, const struct exttm &tm) const; + size_t ftime(char* dst, size_t len, const struct exttm& tm) const; - bool convert_to_timeval(const char *time_src, + bool convert_to_timeval(const char* time_src, ssize_t time_len, - const char * const time_fmt[], - struct timeval &tv_out) { + const char* const time_fmt[], + struct timeval& tv_out) + { struct exttm tm; if (time_len == -1) { @@ -116,12 +121,13 @@ struct date_time_scanner { return false; }; - bool convert_to_timeval(const std::string &time_src, - struct timeval &tv_out) { + bool convert_to_timeval(const std::string& time_src, struct timeval& tv_out) + { struct exttm tm; - if (this->scan(time_src.c_str(), time_src.size(), - nullptr, &tm, tv_out) != nullptr) { + if (this->scan(time_src.c_str(), time_src.size(), nullptr, &tm, tv_out) + != nullptr) + { return true; } return false; diff --git a/src/base/enum_util.hh b/src/base/enum_util.hh index 2a456382..437292d5 100644 --- a/src/base/enum_util.hh +++ b/src/base/enum_util.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -35,13 +35,14 @@ namespace lnav { namespace enums { -template -constexpr auto to_underlying(E e) noexcept +template +constexpr auto +to_underlying(E e) noexcept { return static_cast>(e); } -} -} +} // namespace enums +} // namespace lnav #endif diff --git a/src/base/file_range.hh b/src/base/file_range.hh index 517bb4a2..a9fdf869 100644 --- a/src/base/file_range.hh +++ b/src/base/file_range.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -43,28 +43,31 @@ public: file_off_t fr_offset{0}; file_ssize_t fr_size{0}; - void clear() { + void clear() + { this->fr_offset = 0; this->fr_size = 0; } - ssize_t next_offset() const { + ssize_t next_offset() const + { return this->fr_offset + this->fr_size; } - bool empty() const { + bool empty() const + { return fr_size == 0; } }; struct source_location { source_location() - : sl_source(intern_string::lookup("unknown")), - sl_line_number(-1) { + : sl_source(intern_string::lookup("unknown")), sl_line_number(-1) + { } source_location(intern_string_t source, int line) - : sl_source(source), sl_line_number(line) {}; + : sl_source(source), sl_line_number(line){}; intern_string_t sl_source; int sl_line_number; diff --git a/src/base/fs_util.cc b/src/base/fs_util.cc index f1417586..1136f028 100644 --- a/src/base/fs_util.cc +++ b/src/base/fs_util.cc @@ -21,23 +21,23 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" +#include "fs_util.hh" +#include "config.h" #include "fmt/format.h" -#include "fs_util.hh" #include "opt_util.hh" namespace lnav { namespace filesystem { Result, std::string> -open_temp_file(const ghc::filesystem::path &pattern) +open_temp_file(const ghc::filesystem::path& pattern) { auto pattern_str = pattern.string(); char pattern_copy[pattern_str.size() + 1]; @@ -46,13 +46,15 @@ open_temp_file(const ghc::filesystem::path &pattern) strcpy(pattern_copy, pattern_str.c_str()); if ((fd = mkstemp(pattern_copy)) == -1) { return Err(fmt::format("unable to create temporary file: {} -- {}", - pattern.string(), strerror(errno))); + pattern.string(), + strerror(errno))); } return Ok(std::make_pair(ghc::filesystem::path(pattern_copy), fd)); } -Result read_file(const ghc::filesystem::path &path) +Result +read_file(const ghc::filesystem::path& path) { try { ghc::filesystem::ifstream file_stream(path); @@ -70,11 +72,12 @@ Result read_file(const ghc::filesystem::path &path) } } -std::string build_path(const std::vector &paths) +std::string +build_path(const std::vector& paths) { std::string retval; - for (const auto &path : paths) { + for (const auto& path : paths) { if (path.empty()) { continue; } @@ -90,5 +93,5 @@ std::string build_path(const std::vector &paths) return retval; } -} -} +} // namespace filesystem +} // namespace lnav diff --git a/src/base/fs_util.hh b/src/base/fs_util.hh index d9793e71..a9c35d14 100644 --- a/src/base/fs_util.hh +++ b/src/base/fs_util.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -33,32 +33,38 @@ #include #include -#include "result.h" #include "ghc/filesystem.hpp" +#include "result.h" namespace lnav { namespace filesystem { -inline int statp(const ghc::filesystem::path &path, struct stat *buf) { +inline int +statp(const ghc::filesystem::path& path, struct stat* buf) +{ return stat(path.c_str(), buf); } -inline int openp(const ghc::filesystem::path &path, int flags) { +inline int +openp(const ghc::filesystem::path& path, int flags) +{ return open(path.c_str(), flags); } -inline int openp(const ghc::filesystem::path &path, int flags, mode_t mode) { +inline int +openp(const ghc::filesystem::path& path, int flags, mode_t mode) +{ return open(path.c_str(), flags, mode); } -Result, std::string> -open_temp_file(const ghc::filesystem::path &pattern); +Result, std::string> open_temp_file( + const ghc::filesystem::path& pattern); -Result read_file(const ghc::filesystem::path &path); +Result read_file(const ghc::filesystem::path& path); -std::string build_path(const std::vector &paths); +std::string build_path(const std::vector& paths); -} -} +} // namespace filesystem +} // namespace lnav #endif diff --git a/src/base/func_util.hh b/src/base/func_util.hh index 01a71e24..ee910bf7 100644 --- a/src/base/func_util.hh +++ b/src/base/func_util.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -33,12 +33,11 @@ #include template -decltype(auto) bind_mem(F&& f, FrontArg&& frontArg) +decltype(auto) +bind_mem(F&& f, FrontArg&& frontArg) { - return [f=std::forward(f), - frontArg = std::forward(frontArg)] - (auto&&...backArgs) - { + return [f = std::forward(f), + frontArg = std::forward(frontArg)](auto&&... backArgs) { return (frontArg->*f)(std::forward(backArgs)...); }; } @@ -46,13 +45,23 @@ decltype(auto) bind_mem(F&& f, FrontArg&& frontArg) struct noop_func { struct anything { template - operator T(){ return {}; } + operator T() + { + return {}; + } // optional reference support. Somewhat evil. template - operator T&()const{ static T t{}; return t; } + operator T&() const + { + static T t{}; + return t; + } }; - template - anything operator()(Args&&...)const{return {};} + template + anything operator()(Args&&...) const + { + return {}; + } }; #endif diff --git a/src/base/future_util.hh b/src/base/future_util.hh index 9bfd6cab..8797faa9 100644 --- a/src/base/future_util.hh +++ b/src/base/future_util.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -44,7 +44,9 @@ namespace futures { * @return The new future. */ template -std::future> make_ready_future( T&& t ) { +std::future> +make_ready_future(T&& t) +{ std::promise> pr; auto r = pr.get_future(); pr.set_value(std::forward(t)); @@ -64,9 +66,10 @@ public: * @param processor The function to execute with the result of a future. */ explicit future_queue(std::function processor) - : fq_processor(processor) {}; + : fq_processor(processor){}; - ~future_queue() { + ~future_queue() + { this->pop_to(); } @@ -77,7 +80,8 @@ public: * * @param f The future to add to the queue. */ - void push_back(std::future&& f) { + void push_back(std::future&& f) + { this->fq_deque.emplace_back(std::move(f)); this->pop_to(MAX_QUEUE_SIZE); } @@ -88,7 +92,8 @@ public: * * @param size The new desired size of the queue. */ - void pop_to(size_t size = 0) { + void pop_to(size_t size = 0) + { while (this->fq_deque.size() > size) { auto v = this->fq_deque.front().get(); this->fq_processor(v); @@ -100,7 +105,7 @@ public: std::deque> fq_deque; }; -} -} +} // namespace futures +} // namespace lnav #endif diff --git a/src/base/humanize.cc b/src/base/humanize.cc index 12e6d19e..af63f78a 100644 --- a/src/base/humanize.cc +++ b/src/base/humanize.cc @@ -21,27 +21,34 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - #include #include -#include "fmt/format.h" #include "humanize.hh" +#include "config.h" +#include "fmt/format.h" + namespace humanize { -std::string file_size(file_ssize_t value) +std::string +file_size(file_ssize_t value) { static const double LN1024 = log(1024.0); - static const std::vector UNITS = { - " ", "K", "M", "G", "T", "P", "E", + static const std::vector UNITS = { + " ", + "K", + "M", + "G", + "T", + "P", + "E", }; if (value < 0) { @@ -52,8 +59,8 @@ std::string file_size(file_ssize_t value) return "0.0 B"; } - auto exp = floor(std::min(log(value) / LN1024, - (double) (UNITS.size() - 1))); + auto exp + = floor(std::min(log(value) / LN1024, (double) (UNITS.size() - 1))); auto divisor = pow(1024, exp); return fmt::format(FMT_STRING("{:.1f}{}B"), @@ -61,7 +68,8 @@ std::string file_size(file_ssize_t value) UNITS[exp]); } -const std::string& sparkline(double value, nonstd::optional upper_opt) +const std::string& +sparkline(double value, nonstd::optional upper_opt) { static const std::string ZERO = " "; static const std::string BARS[] = { @@ -91,4 +99,4 @@ const std::string& sparkline(double value, nonstd::optional upper_opt) return BARS[index]; } -} +} // namespace humanize diff --git a/src/base/humanize.file_size.tests.cc b/src/base/humanize.file_size.tests.cc index 2d0aad45..133b9a12 100644 --- a/src/base/humanize.file_size.tests.cc +++ b/src/base/humanize.file_size.tests.cc @@ -21,21 +21,21 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - #include -#include "doctest/doctest.h" - #include "base/humanize.hh" -TEST_CASE("humanize::file_size") { +#include "config.h" +#include "doctest/doctest.h" + +TEST_CASE("humanize::file_size") +{ CHECK(humanize::file_size(0) == "0.0 B"); CHECK(humanize::file_size(1) == "1.0 B"); CHECK(humanize::file_size(1024) == "1.0KB"); diff --git a/src/base/humanize.hh b/src/base/humanize.hh index 985662a4..306c88df 100644 --- a/src/base/humanize.hh +++ b/src/base/humanize.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -48,6 +48,6 @@ std::string file_size(file_ssize_t value); const std::string& sparkline(double value, nonstd::optional upper); -} +} // namespace humanize #endif diff --git a/src/base/humanize.network.cc b/src/base/humanize.network.cc index 6aab131c..004a435a 100644 --- a/src/base/humanize.network.cc +++ b/src/base/humanize.network.cc @@ -21,22 +21,23 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - #include "humanize.network.hh" + +#include "config.h" #include "pcrepp/pcrepp.hh" namespace humanize { namespace network { namespace path { -nonstd::optional<::network::path> from_str(const char *str) +nonstd::optional<::network::path> +from_str(const char* str) { static const pcrepp REMOTE_PATTERN( "(?:(?[\\w\\._\\-]+)@)?" @@ -60,11 +61,11 @@ nonstd::optional<::network::path> from_str(const char *str) path = "."; } return ::network::path{ - { username, locality_hostname, nonstd::nullopt }, + {username, locality_hostname, nonstd::nullopt}, path, }; } -} -} -} +} // namespace path +} // namespace network +} // namespace humanize diff --git a/src/base/humanize.network.hh b/src/base/humanize.network.hh index fa295852..8b0ec35a 100644 --- a/src/base/humanize.network.hh +++ b/src/base/humanize.network.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -32,15 +32,16 @@ #include -#include "optional.hpp" -#include "network.tcp.hh" #include "fmt/format.h" +#include "network.tcp.hh" +#include "optional.hpp" namespace fmt { template<> struct formatter { - constexpr auto parse(format_parse_context& ctx) { + constexpr auto parse(format_parse_context& ctx) + { auto it = ctx.begin(), end = ctx.end(); // Check if reached the end of the range: @@ -51,24 +52,25 @@ struct formatter { return it; } - template - auto format(const network::locality& l, FormatContext& ctx) { + template + auto format(const network::locality& l, FormatContext& ctx) + { bool is_ipv6 = l.l_hostname.find(':') != std::string::npos; - return format_to( - ctx.out(), - "{}{}{}{}{}", - l.l_username.value_or(std::string()), - l.l_username ? "@" : "", - is_ipv6 ? "[" : "", - l.l_hostname, - is_ipv6 ? "]" : ""); + return format_to(ctx.out(), + "{}{}{}{}{}", + l.l_username.value_or(std::string()), + l.l_username ? "@" : "", + is_ipv6 ? "[" : "", + l.l_hostname, + is_ipv6 ? "]" : ""); } }; template<> struct formatter { - constexpr auto parse(format_parse_context& ctx) { + constexpr auto parse(format_parse_context& ctx) + { auto it = ctx.begin(), end = ctx.end(); // Check if reached the end of the range: @@ -79,32 +81,30 @@ struct formatter { return it; } - template - auto format(const network::path& p, FormatContext& ctx) { + template + auto format(const network::path& p, FormatContext& ctx) + { return format_to( - ctx.out(), - "{}:{}", - p.p_locality, - p.p_path == "." ? "" : p.p_path); + ctx.out(), "{}:{}", p.p_locality, p.p_path == "." ? "" : p.p_path); } }; -} +} // namespace fmt namespace humanize { namespace network { namespace path { -nonstd::optional<::network::path> from_str(const char *str); +nonstd::optional<::network::path> from_str(const char* str); -inline nonstd::optional<::network::path> from_str(const std::string &str) +inline nonstd::optional<::network::path> +from_str(const std::string& str) { return from_str(str.c_str()); } -} -} -} - +} // namespace path +} // namespace network +} // namespace humanize #endif diff --git a/src/base/humanize.network.tests.cc b/src/base/humanize.network.tests.cc index 9a468f2d..3cbfcb88 100644 --- a/src/base/humanize.network.tests.cc +++ b/src/base/humanize.network.tests.cc @@ -21,21 +21,20 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - #include -#include "doctest/doctest.h" - #include "base/humanize.network.hh" +#include "config.h" +#include "doctest/doctest.h" -TEST_CASE("humanize::network::path") { +TEST_CASE("humanize::network::path") +{ { auto rp_opt = humanize::network::path::from_str("foobar"); CHECK(!rp_opt); @@ -70,8 +69,8 @@ TEST_CASE("humanize::network::path") { CHECK(!rp.p_locality.l_service.has_value()); CHECK(rp.p_path == "/var/log"); - CHECK(fmt::format("{}", rp.p_locality) == - "dean@[fe80::184f:c67:baf1:fe02%en0]"); + CHECK(fmt::format("{}", rp.p_locality) + == "dean@[fe80::184f:c67:baf1:fe02%en0]"); } { @@ -85,13 +84,13 @@ TEST_CASE("humanize::network::path") { CHECK(!rp.p_locality.l_service.has_value()); CHECK(rp.p_path == "/var/log"); - CHECK(fmt::format("{}", rp.p_locality) == - "[fe80::184f:c67:baf1:fe02%en0]"); + CHECK(fmt::format("{}", rp.p_locality) + == "[fe80::184f:c67:baf1:fe02%en0]"); } { - auto rp_opt = humanize::network::path::from_str( - "host1.example.com:/var/log"); + auto rp_opt + = humanize::network::path::from_str("host1.example.com:/var/log"); CHECK(rp_opt.has_value()); auto rp = *rp_opt; diff --git a/src/base/humanize.time.cc b/src/base/humanize.time.cc index 5d3fcd85..d48a2d52 100644 --- a/src/base/humanize.time.cc +++ b/src/base/humanize.time.cc @@ -21,35 +21,37 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - #include +#include "humanize.time.hh" + +#include "config.h" #include "fmt/format.h" #include "time_util.hh" -#include "humanize.time.hh" namespace humanize { namespace time { using namespace std::chrono_literals; -point point::from_tv(const timeval &tv) +point +point::from_tv(const timeval& tv) { return point(tv); } -std::string point::as_time_ago() const +std::string +point::as_time_ago() const { - struct timeval current_time = this->p_recent_point - .value_or(current_timeval()); - const char *fmt; + struct timeval current_time + = this->p_recent_point.value_or(current_timeval()); + const char* fmt; char buffer[64]; int amount; @@ -57,7 +59,8 @@ std::string point::as_time_ago() const current_time.tv_sec = convert_log_time_to_local(current_time.tv_sec); } - auto delta = std::chrono::seconds(current_time.tv_sec - this->p_past_point.tv_sec); + auto delta + = std::chrono::seconds(current_time.tv_sec - this->p_past_point.tv_sec); if (delta < 0s) { return "in the future"; } else if (delta < 1min) { @@ -66,7 +69,8 @@ std::string point::as_time_ago() const return "one minute ago"; } else if (delta < 1h) { fmt = "%d minutes ago"; - amount = std::chrono::duration_cast(delta).count(); + amount + = std::chrono::duration_cast(delta).count(); } else if (delta < 2h) { return "one hour ago"; } else if (delta < 24h) { @@ -89,7 +93,8 @@ std::string point::as_time_ago() const return std::string(buffer); } -std::string point::as_precise_time_ago() const +std::string +point::as_precise_time_ago() const { struct timeval now, diff; @@ -121,31 +126,33 @@ std::string point::as_precise_time_ago() const } } -duration duration::from_tv(const struct timeval &tv) +duration +duration::from_tv(const struct timeval& tv) { return duration{tv}; } -std::string duration::to_string() const +std::string +duration::to_string() const { /* 24h22m33s111 */ static const struct rel_interval { uint64_t length; - const char *format; - const char *symbol; + const char* format; + const char* symbol; } intervals[] = { - { 1000, "%03lld%s", "" }, - { 60, "%lld%s", "s" }, - { 60, "%lld%s", "m" }, - { 24, "%lld%s", "h" }, - { 0, "%lld%s", "d" }, + {1000, "%03lld%s", ""}, + {60, "%lld%s", "s"}, + {60, "%lld%s", "m"}, + {24, "%lld%s", "h"}, + {0, "%lld%s", "d"}, }; - auto *curr_interval = intervals; + auto* curr_interval = intervals; auto usecs = std::chrono::duration_cast( - std::chrono::seconds(this->d_timeval.tv_sec)) + - std::chrono::microseconds(this->d_timeval.tv_usec); + std::chrono::seconds(this->d_timeval.tv_sec)) + + std::chrono::microseconds(this->d_timeval.tv_usec); auto millis = std::chrono::duration_cast(usecs); std::string retval; bool neg = false; @@ -157,8 +164,8 @@ std::string duration::to_string() const uint64_t remaining; if (millis >= 10min) { - remaining = std::chrono::duration_cast(millis) - .count(); + remaining + = std::chrono::duration_cast(millis).count(); curr_interval += 1; } else { remaining = millis.count(); @@ -171,8 +178,7 @@ std::string duration::to_string() const if (curr_interval->length) { amount = remaining % curr_interval->length; remaining = remaining / curr_interval->length; - } - else { + } else { amount = remaining; remaining = 0; } @@ -181,7 +187,10 @@ std::string duration::to_string() const break; } - snprintf(segment, sizeof(segment), curr_interval->format, amount, + snprintf(segment, + sizeof(segment), + curr_interval->format, + amount, curr_interval->symbol); retval.insert(0, segment); } @@ -193,5 +202,5 @@ std::string duration::to_string() const return retval; } -} -} +} // namespace time +} // namespace humanize diff --git a/src/base/humanize.time.hh b/src/base/humanize.time.hh index b9e56318..96edebda 100644 --- a/src/base/humanize.time.hh +++ b/src/base/humanize.time.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -30,10 +30,10 @@ #ifndef lnav_humanize_time_hh #define lnav_humanize_time_hh -#include - #include +#include + #include "optional.hpp" namespace humanize { @@ -41,15 +41,15 @@ namespace time { class point { public: - static point from_tv(const struct timeval &tv); + static point from_tv(const struct timeval& tv); - point &with_recent_point(const struct timeval &tv) + point& with_recent_point(const struct timeval& tv) { this->p_recent_point = tv; return *this; } - point &with_convert_to_local(bool convert_to_local) + point& with_convert_to_local(bool convert_to_local) { this->p_convert_to_local = convert_to_local; return *this; @@ -60,9 +60,10 @@ public: std::string as_precise_time_ago() const; private: - explicit point(const struct timeval &tv) : p_past_point{tv.tv_sec, - tv.tv_usec} - {} + explicit point(const struct timeval& tv) + : p_past_point{tv.tv_sec, tv.tv_usec} + { + } struct timeval p_past_point; nonstd::optional p_recent_point; @@ -74,13 +75,14 @@ public: static duration from_tv(const struct timeval& tv); std::string to_string() const; + private: explicit duration(const struct timeval& tv) : d_timeval(tv) {} struct timeval d_timeval; }; -} -} +} // namespace time +} // namespace humanize #endif diff --git a/src/base/humanize.time.tests.cc b/src/base/humanize.time.tests.cc index 174e30e2..1b846841 100644 --- a/src/base/humanize.time.tests.cc +++ b/src/base/humanize.time.tests.cc @@ -21,18 +21,17 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - #include #include -#include "doctest/doctest.h" +#include "config.h" +#include "doctest/doctest.h" #include "humanize.time.hh" TEST_CASE("time ago") @@ -42,87 +41,82 @@ TEST_CASE("time ago") time_t t1 = 1610000000; auto t1_chrono = std::chrono::seconds(t1); - auto p1 = humanize::time::point::from_tv({t1, 0}) - .with_recent_point({(time_t) t1 + 5, 0}); + auto p1 = humanize::time::point::from_tv({t1, 0}).with_recent_point( + {(time_t) t1 + 5, 0}); CHECK(p1.as_time_ago() == "just now"); CHECK(p1.as_precise_time_ago() == " 5 seconds ago"); - auto p2 = humanize::time::point::from_tv({t1, 0}) - .with_recent_point({(time_t) t1 + 65, 0}); + auto p2 = humanize::time::point::from_tv({t1, 0}).with_recent_point( + {(time_t) t1 + 65, 0}); CHECK(p2.as_time_ago() == "one minute ago"); CHECK(p2.as_precise_time_ago() == " 1 minute and 5 seconds ago"); - auto p3 = humanize::time::point::from_tv({t1, 0}) - .with_recent_point({(time_t) t1 + (3 * 60 + 5), 0}); + auto p3 = humanize::time::point::from_tv({t1, 0}).with_recent_point( + {(time_t) t1 + (3 * 60 + 5), 0}); CHECK(p3.as_time_ago() == "3 minutes ago"); CHECK(p3.as_precise_time_ago() == " 3 minutes and 5 seconds ago"); - auto p4 = humanize::time::point::from_tv({t1, 0}) - .with_recent_point({(time_t) (t1_chrono + 65min).count(), 0}); + auto p4 = humanize::time::point::from_tv({t1, 0}).with_recent_point( + {(time_t) (t1_chrono + 65min).count(), 0}); CHECK(p4.as_time_ago() == "one hour ago"); CHECK(p4.as_precise_time_ago() == "one hour ago"); - auto p5 = humanize::time::point::from_tv({t1, 0}) - .with_recent_point({(time_t) (t1_chrono + 3h).count(), 0}); + auto p5 = humanize::time::point::from_tv({t1, 0}).with_recent_point( + {(time_t) (t1_chrono + 3h).count(), 0}); CHECK(p5.as_time_ago() == "3 hours ago"); CHECK(p5.as_precise_time_ago() == "3 hours ago"); - auto p6 = humanize::time::point::from_tv({t1, 0}) - .with_recent_point({(time_t) (t1_chrono + 25h).count(), 0}); + auto p6 = humanize::time::point::from_tv({t1, 0}).with_recent_point( + {(time_t) (t1_chrono + 25h).count(), 0}); CHECK(p6.as_time_ago() == "one day ago"); CHECK(p6.as_precise_time_ago() == "one day ago"); - auto p7 = humanize::time::point::from_tv({t1, 0}) - .with_recent_point({(time_t) (t1_chrono + 50h).count(), 0}); + auto p7 = humanize::time::point::from_tv({t1, 0}).with_recent_point( + {(time_t) (t1_chrono + 50h).count(), 0}); CHECK(p7.as_time_ago() == "2 days ago"); CHECK(p7.as_precise_time_ago() == "2 days ago"); - auto p8 = humanize::time::point::from_tv({t1, 0}) - .with_recent_point({(time_t) (t1_chrono + 370 * 24h).count(), 0}); + auto p8 = humanize::time::point::from_tv({t1, 0}).with_recent_point( + {(time_t) (t1_chrono + 370 * 24h).count(), 0}); CHECK(p8.as_time_ago() == "over a year ago"); CHECK(p8.as_precise_time_ago() == "over a year ago"); - auto p9 = humanize::time::point::from_tv({t1, 0}) - .with_recent_point({(time_t) (t1_chrono + 800 * 24h).count(), 0}); + auto p9 = humanize::time::point::from_tv({t1, 0}).with_recent_point( + {(time_t) (t1_chrono + 800 * 24h).count(), 0}); CHECK(p9.as_time_ago() == "over 2 years ago"); CHECK(p9.as_precise_time_ago() == "over 2 years ago"); CHECK(humanize::time::point::from_tv({1610000000, 0}) .with_recent_point({(time_t) 1612000000, 0}) - .as_time_ago() == "23 days ago"); + .as_time_ago() + == "23 days ago"); } -TEST_CASE("duration to_string") { +TEST_CASE("duration to_string") +{ std::string val; - val = humanize::time::duration::from_tv({25 * 60 * 60, 123000}) - .to_string(); + val = humanize::time::duration::from_tv({25 * 60 * 60, 123000}).to_string(); CHECK(val == "1d1h0m0s"); - val = humanize::time::duration::from_tv({10, 123000}) - .to_string(); + val = humanize::time::duration::from_tv({10, 123000}).to_string(); CHECK(val == "10s123"); - val = humanize::time::duration::from_tv({10, 0}) - .to_string(); + val = humanize::time::duration::from_tv({10, 0}).to_string(); CHECK(val == "10s000"); - val = humanize::time::duration::from_tv({0, 100000}) - .to_string(); + val = humanize::time::duration::from_tv({0, 100000}).to_string(); CHECK(val == "100"); - val = humanize::time::duration::from_tv({0, 0}) - .to_string(); + val = humanize::time::duration::from_tv({0, 0}).to_string(); CHECK(val == ""); - val = humanize::time::duration::from_tv({0, -10000}) - .to_string(); + val = humanize::time::duration::from_tv({0, -10000}).to_string(); CHECK(val == "-010"); - val = humanize::time::duration::from_tv({-10, 0}) - .to_string(); + val = humanize::time::duration::from_tv({-10, 0}).to_string(); CHECK(val == "-10s000"); } diff --git a/src/base/injector.bind.hh b/src/base/injector.bind.hh index 6ab493db..b7428c22 100644 --- a/src/base/injector.bind.hh +++ b/src/base/injector.bind.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -38,55 +38,60 @@ namespace injector { namespace details { -template -std::function()> create_factory(R (*)(Args...)) { - return []() { - return std::make_shared(::injector::get()...); - }; +template +std::function()> +create_factory(R (*)(Args...)) +{ + return []() { return std::make_shared(::injector::get()...); }; } -template::value, bool> = true> -std::function()> create_factory() { - typename I::injectable *i = nullptr; +template::value, bool> = true> +std::function()> +create_factory() +{ + typename I::injectable* i = nullptr; return create_factory(i); } -template::value, bool> = true> -std::function()> create_factory() noexcept { - return []() { - return std::make_shared(); - }; +template::value, bool> = true> +std::function()> +create_factory() noexcept +{ + return []() { return std::make_shared(); }; } -} +} // namespace details -template +template struct bind : singleton_storage { - static bool to_singleton() noexcept { + static bool to_singleton() noexcept + { static T storage; singleton_storage::ss_data = &storage; return true; } - template - static bool to_instance(T* (*f)(Args...)) noexcept { - singleton_storage::ss_data = f(::injector::get()...); + template + static bool to_instance(T* (*f)(Args...)) noexcept + { + singleton_storage::ss_data + = f(::injector::get()...); return true; } - static bool to_instance(T* data) noexcept { + static bool to_instance(T* data) noexcept + { singleton_storage::ss_data = data; return true; } template - static bool to() noexcept { - singleton_storage::ss_factory = - details::create_factory(); + static bool to() noexcept + { + singleton_storage::ss_factory + = details::create_factory(); return true; } }; @@ -96,15 +101,17 @@ struct bind_multiple : multiple_storage { bind_multiple() noexcept = default; template - bind_multiple& add() noexcept { - multiple_storage::get_factories()[typeid(I).name()] = - details::create_factory(); + bind_multiple& add() noexcept + { + multiple_storage::get_factories()[typeid(I).name()] + = details::create_factory(); return *this; } - template - bind_multiple& add_singleton() noexcept { + template + bind_multiple& add_singleton() noexcept + { auto factory = details::create_factory(); auto single = factory(); @@ -112,14 +119,13 @@ struct bind_multiple : multiple_storage { bind::to_instance(single.get()); } bind::to_instance(single.get()); - multiple_storage::get_factories()[typeid(I).name()] = [single]() { - return single; - }; + multiple_storage::get_factories()[typeid(I).name()] + = [single]() { return single; }; return *this; } }; -} +} // namespace injector #endif diff --git a/src/base/injector.hh b/src/base/injector.hh index 4818c535..daac28a7 100644 --- a/src/base/injector.hh +++ b/src/base/injector.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -32,12 +32,12 @@ #ifndef lnav_injector_hh #define lnav_injector_hh -#include - #include #include -#include #include +#include + +#include #include "base/lnav_log.hh" @@ -46,40 +46,45 @@ namespace injector { template void force_linking(Annotation anno); -template +template using void_t = void; -template -struct has_injectable : std::false_type {}; +template +struct has_injectable : std::false_type { +}; -template -struct has_injectable> : std::true_type -{}; +template +struct has_injectable> : std::true_type { +}; -template +template struct singleton_storage { - static T *get() { + static T* get() + { static int _[] = {0, (force_linking(Annotations{}), 0)...}; - (void)_; + (void) _; assert(ss_data != nullptr); return ss_data; } - static std::shared_ptr create() { + static std::shared_ptr create() + { static int _[] = {0, (force_linking(Annotations{}), 0)...}; - (void)_; + (void) _; return ss_factory(); } + protected: - static T *ss_data; + static T* ss_data; static std::function()> ss_factory; }; -template -T *singleton_storage::ss_data = nullptr; +template +T* singleton_storage::ss_data = nullptr; -template -std::function()> singleton_storage::ss_factory; +template +std::function()> + singleton_storage::ss_factory; template struct Impl { @@ -88,7 +93,8 @@ struct Impl { template struct multiple_storage { - static std::vector> create() { + static std::vector> create() + { std::vector> retval; for (const auto& pair : get_factories()) { @@ -96,28 +102,35 @@ struct multiple_storage { } return retval; } + protected: - using factory_map_t = std::map()>>; + using factory_map_t + = std::map()>>; - static factory_map_t& get_factories() { + static factory_map_t& get_factories() + { static factory_map_t retval; return retval; } }; -template::value, bool> = true> -T get() +template::value, bool> = true> +T +get() { using plain_t = std::remove_const_t>; return *singleton_storage::get(); } -template::value, bool> = true> -T get() +template::value, bool> = true> +T +get() { using plain_t = std::remove_const_t>; @@ -125,31 +138,38 @@ T get() } template -struct is_shared_ptr : std::false_type {}; +struct is_shared_ptr : std::false_type { +}; template -struct is_shared_ptr> : std::true_type {}; +struct is_shared_ptr> : std::true_type { +}; template -struct is_vector : std::false_type {}; +struct is_vector : std::false_type { +}; template -struct is_vector> : std::true_type {}; +struct is_vector> : std::true_type { +}; -template::value, bool> = true> -T get() +template::value, bool> = true> +T +get() { - return singleton_storage::create(); + return singleton_storage::create(); } -template::value, bool> = true> -T get() +template::value, bool> = true> +T +get() { return multiple_storage::create(); } -} +} // namespace injector #endif diff --git a/src/base/intern_string.cc b/src/base/intern_string.cc index e0f3fd12..5dc7e845 100644 --- a/src/base/intern_string.cc +++ b/src/base/intern_string.cc @@ -21,26 +21,27 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file intern_string.cc */ -#include "config.h" - -#include - #include #include "intern_string.hh" +#include + +#include "config.h" + const static int TABLE_SIZE = 4095; struct intern_string::intern_table { - ~intern_table() { + ~intern_table() + { for (auto is : this->it_table) { auto curr = is; @@ -53,10 +54,11 @@ struct intern_string::intern_table { } } - intern_string *it_table[TABLE_SIZE]; + intern_string* it_table[TABLE_SIZE]; }; -intern_table_lifetime intern_string::get_table_lifetime() +intern_table_lifetime +intern_string::get_table_lifetime() { static intern_table_lifetime retval = std::make_shared(); @@ -64,22 +66,23 @@ intern_table_lifetime intern_string::get_table_lifetime() } unsigned long -hash_str(const char *str, size_t len) +hash_str(const char* str, size_t len) { unsigned long retval = 5381; for (size_t lpc = 0; lpc < len; lpc++) { /* retval * 33 + c */ - retval = ((retval << 5) + retval) + (unsigned char)str[lpc]; + retval = ((retval << 5) + retval) + (unsigned char) str[lpc]; } return retval; } -const intern_string *intern_string::lookup(const char *str, ssize_t len) noexcept +const intern_string* +intern_string::lookup(const char* str, ssize_t len) noexcept { unsigned long h; - intern_string *curr; + intern_string* curr; if (len == -1) { len = strlen(str); @@ -94,7 +97,8 @@ const intern_string *intern_string::lookup(const char *str, ssize_t len) noexcep curr = tab->it_table[h]; while (curr != nullptr) { - if (curr->is_str.size() == len && strncmp(curr->is_str.c_str(), str, len) == 0) { + if (curr->is_str.size() == len + && strncmp(curr->is_str.c_str(), str, len) == 0) { return curr; } curr = curr->is_next; @@ -106,22 +110,24 @@ const intern_string *intern_string::lookup(const char *str, ssize_t len) noexcep return curr; } - } -const intern_string *intern_string::lookup(const string_fragment &sf) noexcept +const intern_string* +intern_string::lookup(const string_fragment& sf) noexcept { return lookup(sf.data(), sf.length()); } -const intern_string *intern_string::lookup(const std::string &str) noexcept +const intern_string* +intern_string::lookup(const std::string& str) noexcept { return lookup(str.c_str(), str.size()); } -bool intern_string::startswith(const char *prefix) const +bool +intern_string::startswith(const char* prefix) const { - const char *curr = this->is_str.data(); + const char* curr = this->is_str.data(); while (*prefix != '\0' && *prefix == *curr) { prefix += 1; @@ -131,7 +137,8 @@ bool intern_string::startswith(const char *prefix) const return *prefix == '\0'; } -void string_fragment::trim(const char *tokens) +void +string_fragment::trim(const char* tokens) { while (this->sf_begin < this->sf_end) { bool found = false; @@ -165,7 +172,8 @@ void string_fragment::trim(const char *tokens) } } -nonstd::optional string_fragment::consume_n(int amount) const +nonstd::optional +string_fragment::consume_n(int amount) const { if (amount > this->length()) { return nonstd::nullopt; diff --git a/src/base/intern_string.hh b/src/base/intern_string.hh index 0987be30..7ead7179 100644 --- a/src/base/intern_string.hh +++ b/src/base/intern_string.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -32,72 +32,81 @@ #ifndef intern_string_hh #define intern_string_hh +#include + #include #include -#include - +#include "fmt/format.h" #include "optional.hpp" #include "strnatcmp.h" -#include "fmt/format.h" struct string_fragment { - using iterator = const char *; - - explicit string_fragment(const char *str = "", int begin = 0, int end = -1) - : sf_string(str), sf_begin(begin), sf_end(end == -1 ? strlen(str) : end) { - }; + using iterator = const char*; - explicit string_fragment(const unsigned char *str, int begin = 0, int end = -1) - : sf_string((const char *) str), - sf_begin(begin), - sf_end(end == -1 ? strlen((const char *) str) : end) { - }; + explicit string_fragment(const char* str = "", int begin = 0, int end = -1) + : sf_string(str), sf_begin(begin), + sf_end(end == -1 ? strlen(str) : end){}; - string_fragment(const std::string &str) - : sf_string(str.c_str()), sf_begin(0), sf_end(str.length()) { + explicit string_fragment(const unsigned char* str, + int begin = 0, + int end = -1) + : sf_string((const char*) str), sf_begin(begin), + sf_end(end == -1 ? strlen((const char*) str) : end){}; + string_fragment(const std::string& str) + : sf_string(str.c_str()), sf_begin(0), sf_end(str.length()) + { } - bool is_valid() const { + bool is_valid() const + { return this->sf_begin != -1; }; - int length() const { + int length() const + { return this->sf_end - this->sf_begin; }; - const char *data() const { + const char* data() const + { return &this->sf_string[this->sf_begin]; } - iterator begin() const { + iterator begin() const + { return &this->sf_string[this->sf_begin]; } - iterator end() const { + iterator end() const + { return &this->sf_string[this->sf_end]; } - bool empty() const { + bool empty() const + { return !this->is_valid() || length() == 0; }; - char operator[](int index) const { + char operator[](int index) const + { return this->sf_string[sf_begin + index]; }; - bool operator==(const std::string &str) const { + bool operator==(const std::string& str) const + { if (this->length() != (int) str.length()) { return false; } - return memcmp(&this->sf_string[this->sf_begin], - str.c_str(), - str.length()) == 0; + return memcmp( + &this->sf_string[this->sf_begin], str.c_str(), str.length()) + == 0; }; - bool operator==(const string_fragment &sf) const { + bool operator==(const string_fragment& sf) const + { if (this->length() != sf.length()) { return false; } @@ -105,27 +114,32 @@ struct string_fragment { return memcmp(this->data(), sf.data(), sf.length()) == 0; }; - bool iequal(const string_fragment &sf) const { + bool iequal(const string_fragment& sf) const + { if (this->length() != sf.length()) { return false; } - return strnatcasecmp(this->length(), this->data(), - sf.length(), sf.data()) == 0; + return strnatcasecmp( + this->length(), this->data(), sf.length(), sf.data()) + == 0; }; - bool operator==(const char *str) const { + bool operator==(const char* str) const + { size_t len = strlen(str); - return len == (size_t) this->length() && - strncmp(this->data(), str, this->length()) == 0; + return len == (size_t) this->length() + && strncmp(this->data(), str, this->length()) == 0; }; - bool operator!=(const char *str) const { + bool operator!=(const char* str) const + { return !(*this == str); } - bool startswith(const char *prefix) const { + bool startswith(const char* prefix) const + { auto iter = this->begin(); while (*prefix != '\0' && *prefix == *iter && iter < this->end()) { @@ -136,15 +150,14 @@ struct string_fragment { return *prefix == '\0'; } - string_fragment substr(int begin) const { + string_fragment substr(int begin) const + { return string_fragment{ - this->sf_string, - this->sf_begin + begin, - this->sf_end - }; + this->sf_string, this->sf_begin + begin, this->sf_end}; } - nonstd::optional find(char ch) const { + nonstd::optional find(char ch) const + { for (int lpc = this->sf_begin; lpc < this->sf_end; lpc++) { if (this->sf_string[lpc] == ch) { return lpc; @@ -155,7 +168,8 @@ struct string_fragment { } template - nonstd::optional consume(P predicate) const { + nonstd::optional consume(P predicate) const + { int consumed = 0; while (consumed < this->length()) { if (!predicate(this->data()[consumed])) { @@ -179,7 +193,8 @@ struct string_fragment { nonstd::optional consume_n(int amount) const; template - string_fragment skip(P predicate) const { + string_fragment skip(P predicate) const + { int offset = 0; while (offset < this->length() && predicate(this->data()[offset])) { offset += 1; @@ -192,10 +207,12 @@ struct string_fragment { }; } - using split_result = nonstd::optional>; + using split_result + = nonstd::optional>; template - split_result split_while(P& predicate) const { + split_result split_while(P& predicate) const + { int consumed = 0; while (consumed < this->length()) { if (!predicate(this->data()[consumed])) { @@ -219,14 +236,14 @@ struct string_fragment { this->sf_string, this->sf_begin + consumed, this->sf_end, - } - ); + }); } struct tag1 { const char t_value; - bool operator()(char ch) const { + bool operator()(char ch) const + { return this->t_value == ch; } }; @@ -234,7 +251,8 @@ struct string_fragment { struct quoted_string_body { bool qs_in_escape{false}; - bool operator()(char ch) { + bool operator()(char ch) + { if (this->qs_in_escape) { this->qs_in_escape = false; return true; @@ -249,80 +267,93 @@ struct string_fragment { } }; - const char *to_string(char *buf) const { + const char* to_string(char* buf) const + { memcpy(buf, this->data(), this->length()); buf[this->length()] = '\0'; return buf; }; - std::string to_string() const { + std::string to_string() const + { return {this->data(), (size_t) this->length()}; } - void clear() { + void clear() + { this->sf_begin = 0; this->sf_end = 0; }; - void invalidate() { + void invalidate() + { this->sf_begin = -1; this->sf_end = -1; }; - void trim(const char *tokens); + void trim(const char* tokens); - const char *sf_string; + const char* sf_string; int sf_begin; int sf_end; }; -inline bool operator<(const char *left, const string_fragment &right) { +inline bool +operator<(const char* left, const string_fragment& right) +{ int rc = strncmp(left, right.data(), right.length()); return rc < 0; } -inline bool operator<(const string_fragment &left, const char *right) { +inline bool +operator<(const string_fragment& left, const char* right) +{ return strncmp(left.data(), right, left.length()) < 0; } class intern_string { - public: - static const intern_string *lookup(const char *str, ssize_t len) noexcept; + static const intern_string* lookup(const char* str, ssize_t len) noexcept; - static const intern_string *lookup(const string_fragment &sf) noexcept; + static const intern_string* lookup(const string_fragment& sf) noexcept; - static const intern_string *lookup(const std::string &str) noexcept; + static const intern_string* lookup(const std::string& str) noexcept; - const char *get() const { + const char* get() const + { return this->is_str.c_str(); }; - size_t size() const { + size_t size() const + { return this->is_str.size(); } - std::string to_string() const { + std::string to_string() const + { return this->is_str; } - string_fragment to_string_fragment() const { + string_fragment to_string_fragment() const + { return string_fragment{this->is_str}; } - bool startswith(const char *prefix) const; + bool startswith(const char* prefix) const; struct intern_table; static std::shared_ptr get_table_lifetime(); + private: friend intern_table; - intern_string(const char *str, ssize_t len) - : is_next(nullptr), is_str(str, (size_t) len) { + intern_string(const char* str, ssize_t len) + : is_next(nullptr), is_str(str, (size_t) len) + { } - intern_string *is_next; + intern_string* is_next; std::string is_str; }; @@ -330,97 +361,112 @@ using intern_table_lifetime = std::shared_ptr; class intern_string_t { public: - using iterator = const char *; - - intern_string_t(const intern_string *is = nullptr) : ist_interned_string(is) { + using iterator = const char*; + intern_string_t(const intern_string* is = nullptr) : ist_interned_string(is) + { } - const intern_string *unwrap() const { + const intern_string* unwrap() const + { return this->ist_interned_string; } - void clear() { + void clear() + { this->ist_interned_string = nullptr; }; - bool empty() const { + bool empty() const + { return this->ist_interned_string == nullptr; } - const char *get() const { + const char* get() const + { if (this->empty()) { return ""; } return this->ist_interned_string->get(); } - iterator begin() const { + iterator begin() const + { return this->get(); } - iterator end() const { + iterator end() const + { return this->get() + this->size(); } - size_t size() const { + size_t size() const + { if (this->ist_interned_string == nullptr) { return 0; } return this->ist_interned_string->size(); } - size_t hash() const { + size_t hash() const + { auto ptr = (uintptr_t) this->ist_interned_string; return ptr; } - std::string to_string() const { + std::string to_string() const + { if (this->ist_interned_string == nullptr) { return ""; } return this->ist_interned_string->to_string(); } - string_fragment to_string_fragment() const { + string_fragment to_string_fragment() const + { if (this->ist_interned_string == nullptr) { return string_fragment{"", 0, 0}; } return this->ist_interned_string->to_string_fragment(); } - bool operator<(const intern_string_t &rhs) const { + bool operator<(const intern_string_t& rhs) const + { return strcmp(this->get(), rhs.get()) < 0; } - bool operator==(const intern_string_t &rhs) const { + bool operator==(const intern_string_t& rhs) const + { return this->ist_interned_string == rhs.ist_interned_string; } - bool operator!=(const intern_string_t &rhs) const { + bool operator!=(const intern_string_t& rhs) const + { return !(*this == rhs); } - bool operator==(const char *rhs) const { + bool operator==(const char* rhs) const + { return strcmp(this->get(), rhs) == 0; } - bool operator!=(const char *rhs) const { + bool operator!=(const char* rhs) const + { return strcmp(this->get(), rhs) != 0; } private: - const intern_string *ist_interned_string; + const intern_string* ist_interned_string; }; -unsigned long hash_str(const char *str, size_t len); +unsigned long hash_str(const char* str, size_t len); namespace fmt { template<> struct formatter : formatter { template - auto format(const string_fragment &sf, FormatContext &ctx) + auto format(const string_fragment& sf, FormatContext& ctx) { return formatter::format( string_view{sf.data(), (size_t) sf.length()}, ctx); @@ -430,61 +476,80 @@ struct formatter : formatter { template<> struct formatter : formatter { template - auto format(const intern_string_t& is, FormatContext &ctx) + auto format(const intern_string_t& is, FormatContext& ctx) { return formatter::format( string_view{is.get(), (size_t) is.size()}, ctx); } }; -} +} // namespace fmt namespace std { - template <> - struct hash { - std::size_t operator()(const intern_string_t &ist) const { - return ist.hash(); - } - }; -} +template<> +struct hash { + std::size_t operator()(const intern_string_t& ist) const + { + return ist.hash(); + } +}; +} // namespace std -inline bool operator<(const char *left, const intern_string_t &right) { +inline bool +operator<(const char* left, const intern_string_t& right) +{ int rc = strncmp(left, right.get(), right.size()); return rc < 0; } -inline bool operator<(const intern_string_t &left, const char *right) { +inline bool +operator<(const intern_string_t& left, const char* right) +{ return strncmp(left.get(), right, left.size()) < 0; } -inline bool operator==(const intern_string_t &left, const string_fragment &sf) { - return ((int) left.size() == sf.length()) && - (memcmp(left.get(), sf.data(), left.size()) == 0); +inline bool +operator==(const intern_string_t& left, const string_fragment& sf) +{ + return ((int) left.size() == sf.length()) + && (memcmp(left.get(), sf.data(), left.size()) == 0); } -inline bool operator==(const string_fragment &left, const intern_string_t &right) { - return (left.length() == (int) right.size()) && - (memcmp(left.data(), right.get(), left.length()) == 0); +inline bool +operator==(const string_fragment& left, const intern_string_t& right) +{ + return (left.length() == (int) right.size()) + && (memcmp(left.data(), right.get(), left.length()) == 0); } namespace std { - inline string to_string(const string_fragment &s) { - return {s.data(), (size_t) s.length()}; - } +inline string +to_string(const string_fragment& s) +{ + return {s.data(), (size_t) s.length()}; +} - inline string to_string(const intern_string_t &s) { - return s.to_string(); - } +inline string +to_string(const intern_string_t& s) +{ + return s.to_string(); } +} // namespace std -inline string_fragment to_string_fragment(const string_fragment &s) { +inline string_fragment +to_string_fragment(const string_fragment& s) +{ return s; } -inline string_fragment to_string_fragment(const intern_string_t &s) { +inline string_fragment +to_string_fragment(const intern_string_t& s) +{ return string_fragment(s.get(), 0, s.size()); } -inline string_fragment to_string_fragment(const std::string &s) { +inline string_fragment +to_string_fragment(const std::string& s) +{ return string_fragment(s.c_str(), 0, s.length()); } diff --git a/src/base/intern_string.tests.cc b/src/base/intern_string.tests.cc index 033af549..93b299e5 100644 --- a/src/base/intern_string.tests.cc +++ b/src/base/intern_string.tests.cc @@ -21,28 +21,27 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - #include #include -#include "doctest/doctest.h" - #include "intern_string.hh" +#include "config.h" +#include "doctest/doctest.h" + TEST_CASE("consume") { auto is_eq = string_fragment::tag1{'='}; auto is_dq = string_fragment::tag1{'"'}; auto is_colon = string_fragment::tag1{':'}; - const char *pair = "foo = bar"; + const char* pair = "foo = bar"; auto sf = string_fragment(pair); auto split_sf = sf.split_while(isalnum); @@ -64,7 +63,7 @@ TEST_CASE("consume") auto no_value = sf.consume(is_colon); CHECK(!no_value.has_value()); - const char *qs = R"("foo \" bar")"; + const char* qs = R"("foo \" bar")"; auto qs_sf = string_fragment{qs}; auto qs_body = qs_sf.consume(is_dq); diff --git a/src/base/is_utf8.cc b/src/base/is_utf8.cc index 6cc5a5df..e861e175 100644 --- a/src/base/is_utf8.cc +++ b/src/base/is_utf8.cc @@ -25,10 +25,10 @@ * SUCH DAMAGE. */ -#include "config.h" - #include "is_utf8.hh" +#include "config.h" + /* Check if the given unsigned char * is a valid utf-8 sequence. @@ -56,240 +56,236 @@ ----------------------------------------------------------------------------- Returns the first erroneous byte position, and give in - `faulty_bytes` the number of actually existing bytes taking part in this error. + `faulty_bytes` the number of actually existing bytes taking part in this + error. */ -ssize_t is_utf8(unsigned char *str, size_t len, const char **message, int *faulty_bytes) +ssize_t +is_utf8(unsigned char* str, size_t len, const char** message, int* faulty_bytes) { size_t i = 0; *message = nullptr; *faulty_bytes = 0; - while (i < len) - { + while (i < len) { if (str[i] == '\n') { *message = nullptr; return i; } - if (str[i] <= 0x7F) /* 00..7F */ - { + if (str[i] <= 0x7F) /* 00..7F */ { i += 1; - } - else if (str[i] >= 0xC2 && str[i] <= 0xDF) /* C2..DF 80..BF */ - { - if (i + 1 < len) /* Expect a 2nd byte */ - { - if (str[i + 1] < 0x80 || str[i + 1] > 0xBF) - { - *message = "After a first byte between C2 and DF, expecting a 2nd byte between 80 and BF"; + } else if (str[i] >= 0xC2 && str[i] <= 0xDF) /* C2..DF 80..BF */ { + if (i + 1 < len) /* Expect a 2nd byte */ { + if (str[i + 1] < 0x80 || str[i + 1] > 0xBF) { + *message + = "After a first byte between C2 and DF, expecting a " + "2nd byte between 80 and BF"; *faulty_bytes = 2; return i; } - } - else - { - *message = "After a first byte between C2 and DF, expecting a 2nd byte."; + } else { + *message + = "After a first byte between C2 and DF, expecting a 2nd " + "byte."; *faulty_bytes = 1; return i; } i += 2; - } - else if (str[i] == 0xE0) /* E0 A0..BF 80..BF */ - { - if (i + 2 < len) /* Expect a 2nd and 3rd byte */ - { - if (str[i + 1] < 0xA0 || str[i + 1] > 0xBF) - { - *message = "After a first byte of E0, expecting a 2nd byte between A0 and BF."; + } else if (str[i] == 0xE0) /* E0 A0..BF 80..BF */ { + if (i + 2 < len) /* Expect a 2nd and 3rd byte */ { + if (str[i + 1] < 0xA0 || str[i + 1] > 0xBF) { + *message + = "After a first byte of E0, expecting a 2nd byte " + "between A0 and BF."; *faulty_bytes = 2; return i; } - if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) - { - *message = "After a first byte of E0, expecting a 3nd byte between 80 and BF."; + if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) { + *message + = "After a first byte of E0, expecting a 3nd byte " + "between 80 and BF."; *faulty_bytes = 3; return i; } - } - else - { - *message = "After a first byte of E0, expecting two following bytes."; + } else { + *message + = "After a first byte of E0, expecting two following " + "bytes."; *faulty_bytes = 1; return i; } i += 3; - } - else if (str[i] >= 0xE1 && str[i] <= 0xEC) /* E1..EC 80..BF 80..BF */ + } else if (str[i] >= 0xE1 && str[i] <= 0xEC) /* E1..EC 80..BF 80..BF */ { - if (i + 2 < len) /* Expect a 2nd and 3rd byte */ - { - if (str[i + 1] < 0x80 || str[i + 1] > 0xBF) - { - *message = "After a first byte between E1 and EC, expecting the 2nd byte between 80 and BF."; + if (i + 2 < len) /* Expect a 2nd and 3rd byte */ { + if (str[i + 1] < 0x80 || str[i + 1] > 0xBF) { + *message + = "After a first byte between E1 and EC, expecting the " + "2nd byte between 80 and BF."; *faulty_bytes = 2; return i; } - if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) - { - *message = "After a first byte between E1 and EC, expecting the 3rd byte between 80 and BF."; + if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) { + *message + = "After a first byte between E1 and EC, expecting the " + "3rd byte between 80 and BF."; *faulty_bytes = 3; return i; } - } - else - { - *message = "After a first byte between E1 and EC, expecting two following bytes."; + } else { + *message + = "After a first byte between E1 and EC, expecting two " + "following bytes."; *faulty_bytes = 1; return i; } i += 3; - } - else if (str[i] == 0xED) /* ED 80..9F 80..BF */ - { - if (i + 2 < len) /* Expect a 2nd and 3rd byte */ - { - if (str[i + 1] < 0x80 || str[i + 1] > 0x9F) - { - *message = "After a first byte of ED, expecting 2nd byte between 80 and 9F."; + } else if (str[i] == 0xED) /* ED 80..9F 80..BF */ { + if (i + 2 < len) /* Expect a 2nd and 3rd byte */ { + if (str[i + 1] < 0x80 || str[i + 1] > 0x9F) { + *message + = "After a first byte of ED, expecting 2nd byte " + "between 80 and 9F."; *faulty_bytes = 2; return i; } - if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) - { - *message = "After a first byte of ED, expecting 3rd byte between 80 and BF."; + if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) { + *message + = "After a first byte of ED, expecting 3rd byte " + "between 80 and BF."; *faulty_bytes = 3; return i; } - } - else - { - *message = "After a first byte of ED, expecting two following bytes."; + } else { + *message + = "After a first byte of ED, expecting two following " + "bytes."; *faulty_bytes = 1; return i; } i += 3; - } - else if (str[i] >= 0xEE && str[i] <= 0xEF) /* EE..EF 80..BF 80..BF */ + } else if (str[i] >= 0xEE && str[i] <= 0xEF) /* EE..EF 80..BF 80..BF */ { - if (i + 2 < len) /* Expect a 2nd and 3rd byte */ - { - if (str[i + 1] < 0x80 || str[i + 1] > 0xBF) - { - *message = "After a first byte between EE and EF, expecting 2nd byte between 80 and BF."; + if (i + 2 < len) /* Expect a 2nd and 3rd byte */ { + if (str[i + 1] < 0x80 || str[i + 1] > 0xBF) { + *message + = "After a first byte between EE and EF, expecting 2nd " + "byte between 80 and BF."; *faulty_bytes = 2; return i; } - if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) - { - *message = "After a first byte between EE and EF, expecting 3rd byte between 80 and BF."; + if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) { + *message + = "After a first byte between EE and EF, expecting 3rd " + "byte between 80 and BF."; *faulty_bytes = 3; return i; } - } - else - { - *message = "After a first byte between EE and EF, two following bytes."; + } else { + *message + = "After a first byte between EE and EF, two following " + "bytes."; *faulty_bytes = 1; return i; } i += 3; - } - else if (str[i] == 0xF0) /* F0 90..BF 80..BF 80..BF */ - { - if (i + 3 < len) /* Expect a 2nd, 3rd 3th byte */ - { - if (str[i + 1] < 0x90 || str[i + 1] > 0xBF) - { - *message = "After a first byte of F0, expecting 2nd byte between 90 and BF."; + } else if (str[i] == 0xF0) /* F0 90..BF 80..BF 80..BF */ { + if (i + 3 < len) /* Expect a 2nd, 3rd 3th byte */ { + if (str[i + 1] < 0x90 || str[i + 1] > 0xBF) { + *message + = "After a first byte of F0, expecting 2nd byte " + "between 90 and BF."; *faulty_bytes = 2; return i; } - if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) - { - *message = "After a first byte of F0, expecting 3rd byte between 80 and BF."; + if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) { + *message + = "After a first byte of F0, expecting 3rd byte " + "between 80 and BF."; *faulty_bytes = 3; return i; } - if (str[i + 3] < 0x80 || str[i + 3] > 0xBF) - { - *message = "After a first byte of F0, expecting 4th byte between 80 and BF."; + if (str[i + 3] < 0x80 || str[i + 3] > 0xBF) { + *message + = "After a first byte of F0, expecting 4th byte " + "between 80 and BF."; *faulty_bytes = 4; return i; } - } - else - { - *message = "After a first byte of F0, expecting three following bytes."; + } else { + *message + = "After a first byte of F0, expecting three following " + "bytes."; *faulty_bytes = 1; return i; } i += 4; - } - else if (str[i] >= 0xF1 && str[i] <= 0xF3) /* F1..F3 80..BF 80..BF 80..BF */ - { - if (i + 3 < len) /* Expect a 2nd, 3rd 3th byte */ - { - if (str[i + 1] < 0x80 || str[i + 1] > 0xBF) - { - *message = "After a first byte of F1, F2, or F3, expecting a 2nd byte between 80 and BF."; + } else if (str[i] >= 0xF1 + && str[i] <= 0xF3) /* F1..F3 80..BF 80..BF 80..BF */ { + if (i + 3 < len) /* Expect a 2nd, 3rd 3th byte */ { + if (str[i + 1] < 0x80 || str[i + 1] > 0xBF) { + *message + = "After a first byte of F1, F2, or F3, expecting a " + "2nd byte between 80 and BF."; *faulty_bytes = 2; return i; } - if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) - { - *message = "After a first byte of F1, F2, or F3, expecting a 3rd byte between 80 and BF."; + if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) { + *message + = "After a first byte of F1, F2, or F3, expecting a " + "3rd byte between 80 and BF."; *faulty_bytes = 3; return i; } - if (str[i + 3] < 0x80 || str[i + 3] > 0xBF) - { - *message = "After a first byte of F1, F2, or F3, expecting a 4th byte between 80 and BF."; + if (str[i + 3] < 0x80 || str[i + 3] > 0xBF) { + *message + = "After a first byte of F1, F2, or F3, expecting a " + "4th byte between 80 and BF."; *faulty_bytes = 4; return i; } - } - else - { - *message = "After a first byte of F1, F2, or F3, expecting three following bytes."; + } else { + *message + = "After a first byte of F1, F2, or F3, expecting three " + "following bytes."; *faulty_bytes = 1; return i; } i += 4; - } - else if (str[i] == 0xF4) /* F4 80..8F 80..BF 80..BF */ - { - if (i + 3 < len) /* Expect a 2nd, 3rd 3th byte */ - { - if (str[i + 1] < 0x80 || str[i + 1] > 0x8F) - { - *message = "After a first byte of F4, expecting 2nd byte between 80 and 8F."; + } else if (str[i] == 0xF4) /* F4 80..8F 80..BF 80..BF */ { + if (i + 3 < len) /* Expect a 2nd, 3rd 3th byte */ { + if (str[i + 1] < 0x80 || str[i + 1] > 0x8F) { + *message + = "After a first byte of F4, expecting 2nd byte " + "between 80 and 8F."; *faulty_bytes = 2; return i; } - if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) - { - *message = "After a first byte of F4, expecting 3rd byte between 80 and BF."; + if (str[i + 2] < 0x80 || str[i + 2] > 0xBF) { + *message + = "After a first byte of F4, expecting 3rd byte " + "between 80 and BF."; *faulty_bytes = 3; return i; } - if (str[i + 3] < 0x80 || str[i + 3] > 0xBF) - { - *message = "After a first byte of F4, expecting 4th byte between 80 and BF."; + if (str[i + 3] < 0x80 || str[i + 3] > 0xBF) { + *message + = "After a first byte of F4, expecting 4th byte " + "between 80 and BF."; *faulty_bytes = 4; return i; } - } - else - { - *message = "After a first byte of F4, expecting three following bytes."; + } else { + *message + = "After a first byte of F4, expecting three following " + "bytes."; *faulty_bytes = 1; return i; } i += 4; - } - else - { - *message = "Expecting bytes in the following ranges: 00..7F C2..F4."; + } else { + *message + = "Expecting bytes in the following ranges: 00..7F C2..F4."; *faulty_bytes = 1; return i; } diff --git a/src/base/is_utf8.hh b/src/base/is_utf8.hh index dc0a00da..2e39cdc7 100644 --- a/src/base/is_utf8.hh +++ b/src/base/is_utf8.hh @@ -28,9 +28,12 @@ #ifndef _IS_UTF8_H #define _IS_UTF8_H -#include #include +#include -ssize_t is_utf8(unsigned char *str, size_t len, const char **message, int *faulty_bytes); +ssize_t is_utf8(unsigned char* str, + size_t len, + const char** message, + int* faulty_bytes); #endif /* _IS_UTF8_H */ diff --git a/src/base/isc.cc b/src/base/isc.cc index 8d055d0a..6b784357 100644 --- a/src/base/isc.cc +++ b/src/base/isc.cc @@ -21,30 +21,32 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file isc.cc */ -#include "config.h" - #include #include "isc.hh" +#include "config.h" + namespace isc { -void service_base::start() +void +service_base::start() { log_debug("starting service thread for: %s", this->s_name.c_str()); this->s_thread = std::thread(&service_base::run, this); this->s_started = true; } -void *service_base::run() +void* +service_base::run() { log_info("BEGIN isc thread: %s", this->s_name.c_str()); while (this->s_looping) { @@ -66,7 +68,8 @@ void *service_base::run() return nullptr; } -void service_base::stop() +void +service_base::stop() { if (this->s_started) { log_debug("stopping service thread: %s", this->s_name.c_str()); @@ -81,8 +84,9 @@ void service_base::stop() } } -supervisor::supervisor(service_list servs, service_base *parent) - : s_service_list(std::move(servs)), s_parent(parent) { +supervisor::supervisor(service_list servs, service_base* parent) + : s_service_list(std::move(servs)), s_parent(parent) +{ for (auto& serv : this->s_service_list) { serv->start(); } @@ -93,7 +97,8 @@ supervisor::~supervisor() this->stop_children(); } -void supervisor::stop_children() +void +supervisor::stop_children() { for (auto& serv : this->s_service_list) { serv->stop(); @@ -101,29 +106,31 @@ void supervisor::stop_children() this->cleanup_children(); } -void supervisor::cleanup_children() +void +supervisor::cleanup_children() { this->s_service_list.erase( - std::remove_if( - this->s_service_list.begin(), this->s_service_list.end(), - [this](auto &child) { - if (child->is_looping()) { - return false; - } - - child->stop(); - if (this->s_parent != nullptr) { - this->s_parent->child_finished(child); - } - return true; - }), + std::remove_if(this->s_service_list.begin(), + this->s_service_list.end(), + [this](auto& child) { + if (child->is_looping()) { + return false; + } + + child->stop(); + if (this->s_parent != nullptr) { + this->s_parent->child_finished(child); + } + return true; + }), this->s_service_list.end()); } -void supervisor::add_child_service(std::shared_ptr new_service) +void +supervisor::add_child_service(std::shared_ptr new_service) { this->s_service_list.emplace_back(new_service); new_service->start(); } -} +} // namespace isc diff --git a/src/base/isc.hh b/src/base/isc.hh index 007e33be..74bd0384 100644 --- a/src/base/isc.hh +++ b/src/base/isc.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -30,19 +30,19 @@ */ #include -#include #include +#include +#include #include #include -#include #include #include "injector.hh" -#include "time_util.hh" #include "safe/safe.h" +#include "time_util.hh" #ifndef lnav_isc_hh -#define lnav_isc_hh +# define lnav_isc_hh namespace isc { @@ -50,28 +50,33 @@ struct msg { std::function m_callback; }; -inline msg empty_msg() { - return { []() { } }; +inline msg +empty_msg() +{ + return {[]() {}}; } class msg_port { public: msg_port() = default; - void send(msg&& m) { - safe::WriteAccess writable_msgs(this->mp_messages); + void send(msg&& m) + { + safe::WriteAccess writable_msgs( + this->mp_messages); writable_msgs->emplace_back(m); this->sp_cond.notify_all(); } template - void process_for(const std::chrono::duration& rel_time) { + void process_for(const std::chrono::duration& rel_time) + { std::deque tmp_msgs; { - safe::WriteAccess writable_msgs( - this->mp_messages); + safe::WriteAccess + writable_msgs(this->mp_messages); if (writable_msgs->empty()) { this->sp_cond.template wait_for(writable_msgs.lock, rel_time); @@ -80,12 +85,13 @@ public: tmp_msgs.swap(*writable_msgs); } while (!tmp_msgs.empty()) { - auto &m = tmp_msgs.front(); + auto& m = tmp_msgs.front(); m.m_callback(); tmp_msgs.pop_front(); } } + private: using message_list = std::deque; using safe_message_list = safe::Safe; @@ -99,11 +105,12 @@ using service_list = std::vector>; struct supervisor { explicit supervisor(service_list servs = {}, - service_base *parent = nullptr); + service_base* parent = nullptr); ~supervisor(); - bool empty() const { + bool empty() const + { return this->s_service_list.empty(); } @@ -112,39 +119,46 @@ struct supervisor { void stop_children(); void cleanup_children(); + protected: service_list s_service_list; - service_base *s_parent; + service_base* s_parent; }; class service_base : public std::enable_shared_from_this { public: explicit service_base(std::string name) - : s_name(std::move(name)), s_children({}, this) { + : s_name(std::move(name)), s_children({}, this) + { } virtual ~service_base() = default; - bool is_looping() const { + bool is_looping() const + { return this->s_looping; } - msg_port& get_port() { + msg_port& get_port() + { return this->s_port; } friend supervisor; + private: void start(); void stop(); protected: - virtual void *run(); - virtual void loop_body() {}; - virtual void child_finished(std::shared_ptr child) {}; - virtual void stopped() {}; - virtual std::chrono::milliseconds compute_timeout(mstime_t current_time) const { + virtual void* run(); + virtual void loop_body(){}; + virtual void child_finished(std::shared_ptr child){}; + virtual void stopped(){}; + virtual std::chrono::milliseconds compute_timeout( + mstime_t current_time) const + { using namespace std::literals::chrono_literals; return 1s; @@ -162,36 +176,37 @@ template class service : public service_base { public: explicit service(std::string sub_name = "") - : service_base(std::string(__PRETTY_FUNCTION__) + " " + sub_name) { + : service_base(std::string(__PRETTY_FUNCTION__) + " " + sub_name) + { } template - void send(F msg) { - this->s_port.send({ - [lifetime = this->shared_from_this(), this, msg]() { - msg(*(static_cast(this))); - } - }); + void send(F msg) + { + this->s_port.send({[lifetime = this->shared_from_this(), this, msg]() { + msg(*(static_cast(this))); + }}); } template void send_and_wait(F msg, - const std::chrono::duration& rel_time) { + const std::chrono::duration& rel_time) + { msg_port reply_port; - this->s_port.send({ - [lifetime = this->shared_from_this(), this, &reply_port, msg]() { - msg(*(static_cast(this))); + this->s_port.send( + {[lifetime = this->shared_from_this(), this, &reply_port, msg]() { + msg(*(static_cast(this))); reply_port.send(empty_msg()); - } - }); + }}); reply_port.template process_for(rel_time); } }; -template +template struct to { - void send(std::function cb) { + void send(std::function cb) + { auto& service = injector::get(); service.send(cb); @@ -199,19 +214,21 @@ struct to { template void send_and_wait(std::function cb, - const std::chrono::duration& rel_time) { + const std::chrono::duration& rel_time) + { auto& service = injector::get(); service.send_and_wait(cb, rel_time); } - void send_and_wait(std::function cb) { + void send_and_wait(std::function cb) + { using namespace std::literals::chrono_literals; this->send_and_wait(cb, 48h); } }; -} +} // namespace isc #endif diff --git a/src/base/lnav.gzip.cc b/src/base/lnav.gzip.cc index 3a70619a..1413bace 100644 --- a/src/base/lnav.gzip.cc +++ b/src/base/lnav.gzip.cc @@ -21,30 +21,32 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file lnav.gzip.cc */ -#include "config.h" +#include "lnav.gzip.hh" #include +#include "config.h" #include "fmt/format.h" -#include "lnav.gzip.hh" namespace lnav { namespace gzip { -bool is_gzipped(const char *buffer, size_t len) +bool +is_gzipped(const char* buffer, size_t len) { return len > 2 && buffer[0] == '\037' && buffer[1] == '\213'; } -Result compress(const void* input, size_t len) +Result +compress(const void* input, size_t len) { auto retval = auto_buffer::alloc(len + 4096); @@ -52,14 +54,16 @@ Result compress(const void* input, size_t len) zs.zalloc = Z_NULL; zs.zfree = Z_NULL; zs.opaque = Z_NULL; - zs.avail_in = (uInt)len; - zs.next_in = (Bytef *)input; - zs.avail_out = (uInt)retval.size(); - zs.next_out = (Bytef *)retval.in(); + zs.avail_in = (uInt) len; + zs.next_in = (Bytef*) input; + zs.avail_out = (uInt) retval.size(); + zs.next_out = (Bytef*) retval.in(); - auto rc = deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 | 16, 8, Z_DEFAULT_STRATEGY); + auto rc = deflateInit2( + &zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 | 16, 8, Z_DEFAULT_STRATEGY); if (rc != Z_OK) { - return Err(fmt::format("unable to initialize compressor -- {}", zError(rc))); + return Err( + fmt::format("unable to initialize compressor -- {}", zError(rc))); } rc = deflate(&zs, Z_FINISH); if (rc != Z_STREAM_END) { @@ -67,20 +71,20 @@ Result compress(const void* input, size_t len) } rc = deflateEnd(&zs); if (rc != Z_OK) { - return Err(fmt::format("unable to finalize compression -- {}", zError(rc))); + return Err( + fmt::format("unable to finalize compression -- {}", zError(rc))); } return Ok(std::move(retval.shrink_to(zs.total_out))); } -Result uncompress(const std::string& src, - const void *buffer, - size_t size) +Result +uncompress(const std::string& src, const void* buffer, size_t size) { auto uncomp = auto_buffer::alloc(size * 2); z_stream strm; int err; - strm.next_in = (Bytef *) buffer; + strm.next_in = (Bytef*) buffer; strm.avail_in = size; strm.total_out = 0; strm.zalloc = Z_NULL; @@ -88,7 +92,8 @@ Result uncompress(const std::string& src, if ((err = inflateInit2(&strm, (16 + MAX_WBITS))) != Z_OK) { return Err(fmt::format("invalid gzip data: {} -- {}", - src, strm.msg ? strm.msg : zError(err))); + src, + strm.msg ? strm.msg : zError(err))); } bool done = false; @@ -98,7 +103,7 @@ Result uncompress(const std::string& src, uncomp.expand_by(size / 2); } - strm.next_out = (Bytef *) (uncomp.in() + strm.total_out); + strm.next_out = (Bytef*) (uncomp.in() + strm.total_out); strm.avail_out = uncomp.size() - strm.total_out; // Inflate another chunk. @@ -108,17 +113,19 @@ Result uncompress(const std::string& src, } else if (err != Z_OK) { inflateEnd(&strm); return Err(fmt::format("unable to uncompress: {} -- {}", - src, strm.msg ? strm.msg : zError(err))); + src, + strm.msg ? strm.msg : zError(err))); } } if (inflateEnd(&strm) != Z_OK) { return Err(fmt::format("unable to uncompress: {} -- {}", - src, strm.msg ? strm.msg : zError(err))); + src, + strm.msg ? strm.msg : zError(err))); } return Ok(std::move(uncomp.shrink_to(strm.total_out))); } -} -} +} // namespace gzip +} // namespace lnav diff --git a/src/base/lnav.gzip.hh b/src/base/lnav.gzip.hh index ac346f8a..bd739653 100644 --- a/src/base/lnav.gzip.hh +++ b/src/base/lnav.gzip.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -40,15 +40,15 @@ namespace lnav { namespace gzip { -bool is_gzipped(const char *buffer, size_t len); +bool is_gzipped(const char* buffer, size_t len); -Result compress(const void *input, size_t len); +Result compress(const void* input, size_t len); Result uncompress(const std::string& src, - const void *buffer, + const void* buffer, size_t size); -} -} +} // namespace gzip +} // namespace lnav #endif diff --git a/src/base/lnav.gzip.tests.cc b/src/base/lnav.gzip.tests.cc index 2a3b5357..28a61bea 100644 --- a/src/base/lnav.gzip.tests.cc +++ b/src/base/lnav.gzip.tests.cc @@ -21,35 +21,35 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - -#include #include -#include "doctest/doctest.h" +#include #include "base/lnav.gzip.hh" +#include "config.h" +#include "doctest/doctest.h" -TEST_CASE("lnav::gzip::uncompress") { +TEST_CASE("lnav::gzip::uncompress") +{ { auto u_res = lnav::gzip::uncompress("empty", nullptr, 0); CHECK(u_res.isErr()); - CHECK(u_res.unwrapErr() == - "unable to uncompress: empty -- buffer error"); + CHECK(u_res.unwrapErr() + == "unable to uncompress: empty -- buffer error"); } { auto u_res = lnav::gzip::uncompress("garbage", "abc", 3); CHECK(u_res.isErr()); - CHECK(u_res.unwrapErr() == - "unable to uncompress: garbage -- incorrect header check"); + CHECK(u_res.unwrapErr() + == "unable to uncompress: garbage -- incorrect header check"); } } diff --git a/src/base/lnav_log.cc b/src/base/lnav_log.cc index 3281c805..b01b49a0 100644 --- a/src/base/lnav_log.cc +++ b/src/base/lnav_log.cc @@ -21,101 +21,104 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file lnav_log.cc */ -#include "config.h" - -#include +#include #include #include -#include -#include +#include #include +#include #include #include -#include -#include -#include #include +#include +#include +#include + +#include "config.h" #ifdef HAVE_EXECINFO_H -#include +# include #endif #if BACKWARD_HAS_DW == 1 -#include "backward-cpp/backward.hpp" +# include "backward-cpp/backward.hpp" #endif -#include -#include -#include -#include -#include - +#include #include #include #include -#include + +#include +#include +#include +#include +#include #ifdef HAVE_PCRE_H -#include +# include #elif HAVE_PCRE_PCRE_H -#include +# include #else -#error "pcre.h not found?" +# error "pcre.h not found?" #endif #if defined HAVE_NCURSESW_CURSES_H -# include -# include +# include +# include #elif defined HAVE_NCURSESW_H -# include -# include +# include +# include #elif defined HAVE_NCURSES_CURSES_H -# include -# include +# include +# include #elif defined HAVE_NCURSES_H -# include -# include +# include +# include #elif defined HAVE_CURSES_H -# include -# include +# include +# include #else -# error "SysV or X/Open-compatible Curses header file required" +# error "SysV or X/Open-compatible Curses header file required" #endif -#include "opt_util.hh" -#include "lnav_log.hh" -#include "enum_util.hh" #include "auto_mem.hh" +#include "enum_util.hh" +#include "lnav_log.hh" +#include "opt_util.hh" static const size_t BUFFER_SIZE = 256 * 1024; static const size_t MAX_LOG_LINE_SIZE = 2048; -static const char *CRASH_MSG = - "\n" - "\n" - "==== GURU MEDITATION ====\n" - "Unfortunately, lnav has crashed, sorry for the inconvenience.\n" - "\n" - "You can help improve lnav by sending the following file to " PACKAGE_BUGREPORT " :\n" - " %s\n" - "=========================\n"; - -nonstd::optional lnav_log_file; +static const char* CRASH_MSG + = "\n" + "\n" + "==== GURU MEDITATION ====\n" + "Unfortunately, lnav has crashed, sorry for the inconvenience.\n" + "\n" + "You can help improve lnav by sending the following file " + "to " PACKAGE_BUGREPORT + " :\n" + " %s\n" + "=========================\n"; + +nonstd::optional lnav_log_file; lnav_log_level_t lnav_log_level = lnav_log_level_t::DEBUG; -const char *lnav_log_crash_dir; -nonstd::optional lnav_log_orig_termios; +const char* lnav_log_crash_dir; +nonstd::optional lnav_log_orig_termios; // NOTE: This mutex is leaked so that it is not destroyed during exit. // Otherwise, any attempts to log will fail. -static std::mutex *lnav_log_mutex = new std::mutex(); +static std::mutex* lnav_log_mutex = new std::mutex(); -static std::vector& DUMPER_LIST() +static std::vector& +DUMPER_LIST() { static std::vector retval; @@ -141,14 +144,9 @@ static struct { off_t lr_frag_start; off_t lr_frag_end; char lr_data[BUFFER_SIZE]; -} log_ring = { - 0, - BUFFER_SIZE, - 0, - {} -}; +} log_ring = {0, BUFFER_SIZE, 0, {}}; -static const char *LEVEL_NAMES[] = { +static const char* LEVEL_NAMES[] = { "T", "D", "I", @@ -156,38 +154,40 @@ static const char *LEVEL_NAMES[] = { "E", }; -static char *log_alloc() +static char* +log_alloc() { off_t data_end = log_ring.lr_length + MAX_LOG_LINE_SIZE; - if (data_end >= (off_t)BUFFER_SIZE) { - const char *new_start = &log_ring.lr_data[MAX_LOG_LINE_SIZE]; + if (data_end >= (off_t) BUFFER_SIZE) { + const char* new_start = &log_ring.lr_data[MAX_LOG_LINE_SIZE]; - new_start = (const char *)memchr( + new_start = (const char*) memchr( new_start, '\n', log_ring.lr_length - MAX_LOG_LINE_SIZE); log_ring.lr_frag_start = new_start - log_ring.lr_data; log_ring.lr_frag_end = log_ring.lr_length; log_ring.lr_length = 0; assert(log_ring.lr_frag_start >= 0); - assert(log_ring.lr_frag_start <= (off_t)BUFFER_SIZE); + assert(log_ring.lr_frag_start <= (off_t) BUFFER_SIZE); } else if (data_end >= log_ring.lr_frag_start) { - const char *new_start = &log_ring.lr_data[log_ring.lr_frag_start]; + const char* new_start = &log_ring.lr_data[log_ring.lr_frag_start]; - new_start = (const char *)memchr( + new_start = (const char*) memchr( new_start, '\n', log_ring.lr_frag_end - log_ring.lr_frag_start); assert(new_start != nullptr); log_ring.lr_frag_start = new_start - log_ring.lr_data; assert(log_ring.lr_frag_start >= 0); - assert(log_ring.lr_frag_start <= (off_t)BUFFER_SIZE); + assert(log_ring.lr_frag_start <= (off_t) BUFFER_SIZE); } return &log_ring.lr_data[log_ring.lr_length]; } -void log_argv(int argc, char *argv[]) +void +log_argv(int argc, char* argv[]) { - const char *log_path = getenv("LNAV_LOG_PATH"); + const char* log_path = getenv("LNAV_LOG_PATH"); if (log_path != nullptr) { lnav_log_file = make_optional_from_nullable(fopen(log_path, "a")); @@ -199,15 +199,17 @@ void log_argv(int argc, char *argv[]) } } -void log_set_thread_prefix(std::string prefix) +void +log_set_thread_prefix(std::string prefix) { // thread_log_prefix = std::move(prefix); } -void log_host_info() +void +log_host_info() { char cwd[MAXPATHLEN]; - const char *jittarget; + const char* jittarget; struct utsname un; struct rusage ru; int pcre_jit; @@ -242,8 +244,7 @@ void log_host_info() log_info(" egid=%d", getegid()); if (getcwd(cwd, sizeof(cwd)) == nullptr) { log_info(" ERROR: getcwd failed"); - } - else { + } else { log_info(" cwd=%s", cwd); } log_info("Executable:"); @@ -253,13 +254,25 @@ void log_host_info() log_rusage(lnav_log_level_t::INFO, ru); } -void log_rusage_raw(enum lnav_log_level_t level, const char *src_file, int line_number, const struct rusage &ru) +void +log_rusage_raw(enum lnav_log_level_t level, + const char* src_file, + int line_number, + const struct rusage& ru) { log_msg(level, src_file, line_number, "rusage:"); - log_msg(level, src_file, line_number, " utime=%d.%06d", - ru.ru_utime.tv_sec, ru.ru_utime.tv_usec); - log_msg(level, src_file, line_number, " stime=%d.%06d", - ru.ru_stime.tv_sec, ru.ru_stime.tv_usec); + log_msg(level, + src_file, + line_number, + " utime=%d.%06d", + ru.ru_utime.tv_sec, + ru.ru_utime.tv_usec); + log_msg(level, + src_file, + line_number, + " stime=%d.%06d", + ru.ru_stime.tv_sec, + ru.ru_stime.tv_usec); log_msg(level, src_file, line_number, " maxrss=%ld", ru.ru_maxrss); log_msg(level, src_file, line_number, " ixrss=%ld", ru.ru_ixrss); log_msg(level, src_file, line_number, " idrss=%ld", ru.ru_idrss); @@ -276,8 +289,12 @@ void log_rusage_raw(enum lnav_log_level_t level, const char *src_file, int line_ log_msg(level, src_file, line_number, " nivcsw=%ld", ru.ru_nivcsw); } -void log_msg(lnav_log_level_t level, const char *src_file, int line_number, - const char *fmt, ...) +void +log_msg(lnav_log_level_t level, + const char* src_file, + int line_number, + const char* fmt, + ...) { struct timeval curr_time; struct tm localtm; @@ -294,7 +311,7 @@ void log_msg(lnav_log_level_t level, const char *src_file, int line_number, { // get the base name of the file. NB: can't use basename() since it // can modify its argument - const char *last_slash = src_file; + const char* last_slash = src_file; for (int lpc = 0; src_file[lpc]; lpc++) { if (src_file[lpc] == '/' || src_file[lpc] == '\\') { @@ -309,20 +326,20 @@ void log_msg(lnav_log_level_t level, const char *src_file, int line_number, gettimeofday(&curr_time, nullptr); localtime_r(&curr_time.tv_sec, &localtm); auto line = log_alloc(); - prefix_size = snprintf( - line, MAX_LOG_LINE_SIZE, - "%4d-%02d-%02dT%02d:%02d:%02d.%03d %s t%u %s:%d ", - localtm.tm_year + 1900, - localtm.tm_mon + 1, - localtm.tm_mday, - localtm.tm_hour, - localtm.tm_min, - localtm.tm_sec, - (int)(curr_time.tv_usec / 1000), - LEVEL_NAMES[lnav::enums::to_underlying(level)], - current_thid.t_id, - src_file, - line_number); + prefix_size = snprintf(line, + MAX_LOG_LINE_SIZE, + "%4d-%02d-%02dT%02d:%02d:%02d.%03d %s t%u %s:%d ", + localtm.tm_year + 1900, + localtm.tm_mon + 1, + localtm.tm_mday, + localtm.tm_hour, + localtm.tm_min, + localtm.tm_sec, + (int) (curr_time.tv_usec / 1000), + LEVEL_NAMES[lnav::enums::to_underlying(level)], + current_thid.t_id, + src_file, + line_number); #if 0 if (!thread_log_prefix.empty()) { prefix_size += snprintf( @@ -331,9 +348,9 @@ void log_msg(lnav_log_level_t level, const char *src_file, int line_number, thread_log_prefix.c_str()); } #endif - rc = vsnprintf(&line[prefix_size], MAX_LOG_LINE_SIZE - prefix_size, - fmt, args); - if (rc >= (ssize_t)(MAX_LOG_LINE_SIZE - prefix_size)) { + rc = vsnprintf( + &line[prefix_size], MAX_LOG_LINE_SIZE - prefix_size, fmt, args); + if (rc >= (ssize_t) (MAX_LOG_LINE_SIZE - prefix_size)) { rc = MAX_LOG_LINE_SIZE - prefix_size - 1; } line[prefix_size + rc] = '\n'; @@ -345,7 +362,8 @@ void log_msg(lnav_log_level_t level, const char *src_file, int line_number, va_end(args); } -void log_msg_extra(const char *fmt, ...) +void +log_msg_extra(const char* fmt, ...) { std::lock_guard mg(*lnav_log_mutex); va_list args; @@ -361,7 +379,8 @@ void log_msg_extra(const char *fmt, ...) va_end(args); } -void log_msg_extra_complete() +void +log_msg_extra_complete() { std::lock_guard mg(*lnav_log_mutex); auto line = log_alloc(); @@ -375,13 +394,14 @@ void log_msg_extra_complete() #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-result" -static void sigabrt(int sig, siginfo_t *info, void *ctx) +static void +sigabrt(int sig, siginfo_t* info, void* ctx) { char crash_path[1024], latest_crash_path[1024]; int fd; #ifdef HAVE_EXECINFO_H int frame_count; - void *frames[128]; + void* frames[128]; #endif struct tm localtm; time_t curr_time; @@ -398,45 +418,53 @@ static void sigabrt(int sig, siginfo_t *info, void *ctx) #endif curr_time = time(nullptr); localtime_r(&curr_time, &localtm); - snprintf(crash_path, sizeof(crash_path), - "%s/crash-%4d-%02d-%02d-%02d-%02d-%02d.%d.log", - lnav_log_crash_dir, - localtm.tm_year + 1900, - localtm.tm_mon + 1, - localtm.tm_mday, - localtm.tm_hour, - localtm.tm_min, - localtm.tm_sec, - getpid()); - snprintf(latest_crash_path, sizeof(latest_crash_path), - "%s/latest-crash.log", lnav_log_crash_dir); - if ((fd = open(crash_path, O_CREAT|O_TRUNC|O_RDWR, 0600)) != -1) { - if (log_ring.lr_frag_start < (off_t)BUFFER_SIZE) { - (void)write(fd, &log_ring.lr_data[log_ring.lr_frag_start], - log_ring.lr_frag_end - log_ring.lr_frag_start); + snprintf(crash_path, + sizeof(crash_path), + "%s/crash-%4d-%02d-%02d-%02d-%02d-%02d.%d.log", + lnav_log_crash_dir, + localtm.tm_year + 1900, + localtm.tm_mon + 1, + localtm.tm_mday, + localtm.tm_hour, + localtm.tm_min, + localtm.tm_sec, + getpid()); + snprintf(latest_crash_path, + sizeof(latest_crash_path), + "%s/latest-crash.log", + lnav_log_crash_dir); + if ((fd = open(crash_path, O_CREAT | O_TRUNC | O_RDWR, 0600)) != -1) { + if (log_ring.lr_frag_start < (off_t) BUFFER_SIZE) { + (void) write(fd, + &log_ring.lr_data[log_ring.lr_frag_start], + log_ring.lr_frag_end - log_ring.lr_frag_start); } - (void)write(fd, log_ring.lr_data, log_ring.lr_length); + (void) write(fd, log_ring.lr_data, log_ring.lr_length); #ifdef HAVE_EXECINFO_H backtrace_symbols_fd(frames, frame_count, fd); #endif #if BACKWARD_HAS_DW == 1 { - ucontext_t *uctx = static_cast(ctx); - void *error_addr = nullptr; + ucontext_t* uctx = static_cast(ctx); + void* error_addr = nullptr; -#ifdef REG_RIP // x86_64 - error_addr = reinterpret_cast(uctx->uc_mcontext.gregs[REG_RIP]); -#elif defined(REG_EIP) // x86_32 - error_addr = reinterpret_cast(uctx->uc_mcontext.gregs[REG_EIP]); -#endif +# ifdef REG_RIP // x86_64 + error_addr + = reinterpret_cast(uctx->uc_mcontext.gregs[REG_RIP]); +# elif defined(REG_EIP) // x86_32 + error_addr + = reinterpret_cast(uctx->uc_mcontext.gregs[REG_EIP]); +# endif backward::StackTrace st; if (error_addr) { - st.load_from(error_addr, 32, reinterpret_cast(uctx), + st.load_from(error_addr, + 32, + reinterpret_cast(uctx), info->si_addr); } else { - st.load_here(32, reinterpret_cast(uctx), info->si_addr); + st.load_here(32, reinterpret_cast(uctx), info->si_addr); } backward::TraceResolver tr; @@ -445,7 +473,8 @@ static void sigabrt(int sig, siginfo_t *info, void *ctx) auto trace = tr.resolve(st[lpc]); char buf[1024]; - snprintf(buf, sizeof(buf), + snprintf(buf, + sizeof(buf), "Frame %lu:%s:%s (%s:%d)\n", lpc, trace.object_filename.c_str(), @@ -466,9 +495,10 @@ static void sigabrt(int sig, siginfo_t *info, void *ctx) lsd->log_state(); } - if (log_ring.lr_frag_start < (off_t)BUFFER_SIZE) { - write(fd, &log_ring.lr_data[log_ring.lr_frag_start], - log_ring.lr_frag_end - log_ring.lr_frag_start); + if (log_ring.lr_frag_start < (off_t) BUFFER_SIZE) { + write(fd, + &log_ring.lr_data[log_ring.lr_frag_start], + log_ring.lr_frag_end - log_ring.lr_frag_start); } write(fd, log_ring.lr_data, log_ring.lr_length); if (getenv("DUMP_CRASH") != nullptr) { @@ -530,7 +560,6 @@ static void sigabrt(int sig, siginfo_t *info, void *ctx) int status; while (wait(&status) < 0) { - } break; } @@ -543,7 +572,8 @@ static void sigabrt(int sig, siginfo_t *info, void *ctx) } #pragma GCC diagnostic pop -void log_install_handlers() +void +log_install_handlers() { const size_t stack_size = 8 * 1024 * 1024; const int sigs[] = { @@ -575,15 +605,17 @@ void log_install_handlers() } } -void log_abort() +void +log_abort() { raise(SIGABRT); _exit(1); } -void log_pipe_err(int fd) +void +log_pipe_err(int fd) { - std::thread reader([fd] () { + std::thread reader([fd]() { char buffer[1024]; bool done = false; @@ -596,8 +628,7 @@ void log_pipe_err(int fd) done = true; break; default: - while (buffer[rc - 1] == '\n' || - buffer[rc - 1] == '\r') { + while (buffer[rc - 1] == '\n' || buffer[rc - 1] == '\r') { rc -= 1; } diff --git a/src/base/lnav_log.hh b/src/base/lnav_log.hh index 115dc767..8fd8e36c 100644 --- a/src/base/lnav_log.hh +++ b/src/base/lnav_log.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * @@ -32,13 +32,14 @@ #ifndef lnav_log_hh #define lnav_log_hh +#include + #include #include #include -#include #ifndef lnav_dead2 -#define lnav_dead2 __attribute__((noreturn)) +# define lnav_dead2 __attribute__((noreturn)) #endif #include "optional.hpp" @@ -53,12 +54,18 @@ enum class lnav_log_level_t : uint32_t { ERROR, }; -void log_argv(int argc, char *argv[]); +void log_argv(int argc, char* argv[]); void log_host_info(); -void log_rusage_raw(enum lnav_log_level_t level, const char *src_file, int line_number, const struct rusage &ru); -void log_msg(enum lnav_log_level_t level, const char *src_file, int line_number, - const char *fmt, ...); -void log_msg_extra(const char *fmt, ...); +void log_rusage_raw(enum lnav_log_level_t level, + const char* src_file, + int line_number, + const struct rusage& ru); +void log_msg(enum lnav_log_level_t level, + const char* src_file, + int line_number, + const char* fmt, + ...); +void log_msg_extra(const char* fmt, ...); void log_msg_extra_complete(); void log_install_handlers(); void log_abort() lnav_dead2; @@ -71,7 +78,7 @@ public: virtual ~log_state_dumper(); - virtual void log_state() { + virtual void log_state(){ }; @@ -88,9 +95,9 @@ public: virtual void log_crash_recover() = 0; }; -extern nonstd::optional lnav_log_file; -extern const char *lnav_log_crash_dir; -extern nonstd::optional lnav_log_orig_termios; +extern nonstd::optional lnav_log_file; +extern const char* lnav_log_crash_dir; +extern nonstd::optional lnav_log_orig_termios; extern enum lnav_log_level_t lnav_log_level; #define log_msg_wrapper(level, fmt...) \ @@ -98,40 +105,43 @@ extern enum lnav_log_level_t lnav_log_level; if (lnav_log_level <= level) { \ log_msg(level, __FILE__, __LINE__, fmt); \ } \ - } \ - while (false) + } while (false) -#define log_rusage(level, ru) \ - log_rusage_raw(level, __FILE__, __LINE__, ru); +#define log_rusage(level, ru) log_rusage_raw(level, __FILE__, __LINE__, ru); -#define log_error(fmt...) \ - log_msg_wrapper(lnav_log_level_t::ERROR, fmt); +#define log_error(fmt...) log_msg_wrapper(lnav_log_level_t::ERROR, fmt); -#define log_warning(fmt...) \ - log_msg_wrapper(lnav_log_level_t::WARNING, fmt); +#define log_warning(fmt...) log_msg_wrapper(lnav_log_level_t::WARNING, fmt); -#define log_info(fmt...) \ - log_msg_wrapper(lnav_log_level_t::INFO, fmt); +#define log_info(fmt...) log_msg_wrapper(lnav_log_level_t::INFO, fmt); -#define log_debug(fmt...) \ - log_msg_wrapper(lnav_log_level_t::DEBUG, fmt); +#define log_debug(fmt...) log_msg_wrapper(lnav_log_level_t::DEBUG, fmt); -#define log_trace(fmt...) \ - log_msg_wrapper(lnav_log_level_t::TRACE, fmt); +#define log_trace(fmt...) log_msg_wrapper(lnav_log_level_t::TRACE, fmt); -#define require(e) \ - ((void) ((e) ? 0 : lnav_require (#e, __FILE__, __LINE__))) +#define require(e) ((void) ((e) ? 0 : lnav_require(#e, __FILE__, __LINE__))) #define lnav_require(e, file, line) \ - (log_msg(lnav_log_level_t::ERROR, file, line, "failed precondition `%s'", e), log_abort(), 1) + (log_msg( \ + lnav_log_level_t::ERROR, file, line, "failed precondition `%s'", e), \ + log_abort(), \ + 1) -#define ensure(e) \ - ((void) ((e) ? 0 : lnav_ensure (#e, __FILE__, __LINE__))) +#define ensure(e) ((void) ((e) ? 0 : lnav_ensure(#e, __FILE__, __LINE__))) #define lnav_ensure(e, file, line) \ - (log_msg(lnav_log_level_t::ERROR, file, line, "failed postcondition `%s'", e), log_abort(), 1) + (log_msg( \ + lnav_log_level_t::ERROR, file, line, "failed postcondition `%s'", e), \ + log_abort(), \ + 1) -#define log_perror(e) \ - ((void) ((e != -1) ? 0 : lnav_log_perror (#e, __FILE__, __LINE__))) +#define log_perror(e) \ + ((void) ((e != -1) ? 0 : lnav_log_perror(#e, __FILE__, __LINE__))) #define lnav_log_perror(e, file, line) \ - (log_msg(lnav_log_level_t::ERROR, file, line, "syscall failed `%s' -- %s", e, strerror(errno)), 1) + (log_msg(lnav_log_level_t::ERROR, \ + file, \ + line, \ + "syscall failed `%s' -- %s", \ + e, \ + strerror(errno)), \ + 1) #endif diff --git a/src/base/math_util.hh b/src/base/math_util.hh index fd5f7204..6eea8c4a 100644 --- a/src/base/math_util.hh +++ b/src/base/math_util.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -41,17 +41,20 @@ * @param step The granularity. */ template -inline int rounddown(Size size, Step step) +inline int +rounddown(Size size, Step step) { return size - (size % step); } -inline int rounddown_offset(size_t size, int step, int offset) +inline int +rounddown_offset(size_t size, int step, int offset) { return size - ((size - offset) % step); } -inline size_t roundup_size(size_t size, int step) +inline size_t +roundup_size(size_t size, int step) { size_t retval = size + step; diff --git a/src/base/network.tcp.cc b/src/base/network.tcp.cc index dd3830a8..6a0ed08e 100644 --- a/src/base/network.tcp.cc +++ b/src/base/network.tcp.cc @@ -21,27 +21,26 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" +#include "network.tcp.hh" -#include -#include #include +#include +#include +#include "config.h" #include "fmt/format.h" -#include "network.tcp.hh" - namespace network { namespace tcp { -Result connect(const char *hostname, - const char *servname) +Result +connect(const char* hostname, const char* servname) { struct addrinfo hints, *ai; @@ -52,7 +51,9 @@ Result connect(const char *hostname, if (rc != 0) { return Err(fmt::format("unable to resolve {}:{} -- {}", - hostname, servname, gai_strerror(rc))); + hostname, + servname, + gai_strerror(rc))); } auto retval = auto_fd(socket(ai->ai_family, ai->ai_socktype, 0)); @@ -60,11 +61,13 @@ Result connect(const char *hostname, rc = ::connect(retval, ai->ai_addr, ai->ai_addrlen); if (rc != 0) { return Err(fmt::format("unable to connect to {}:{} -- {}", - hostname, servname, strerror(rc))); + hostname, + servname, + strerror(rc))); } return Ok(retval); } -} -} +} // namespace tcp +} // namespace network diff --git a/src/base/network.tcp.hh b/src/base/network.tcp.hh index c38e9843..619115ef 100644 --- a/src/base/network.tcp.hh +++ b/src/base/network.tcp.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -40,11 +40,11 @@ namespace network { struct locality { locality(nonstd::optional username, std::string hostname, - nonstd::optional service) : - l_username(std::move(username)), - l_hostname(std::move(hostname)), - l_service(std::move(service)) - {} + nonstd::optional service) + : l_username(std::move(username)), l_hostname(std::move(hostname)), + l_service(std::move(service)) + { + } nonstd::optional l_username; std::string l_hostname; @@ -55,11 +55,13 @@ struct path { locality p_locality; std::string p_path; - path(locality l, std::string path) : p_locality(std::move(l)), - p_path(std::move(path)) - {} + path(locality l, std::string path) + : p_locality(std::move(l)), p_path(std::move(path)) + { + } - path home() const { + path home() const + { return { this->p_locality, ".", @@ -69,10 +71,10 @@ struct path { namespace tcp { -Result connect(const char *hostname, - const char *servname); +Result connect(const char* hostname, + const char* servname); } -} +} // namespace network #endif diff --git a/src/base/network.tcp.tests.cc b/src/base/network.tcp.tests.cc index 611fce25..76846ca3 100644 --- a/src/base/network.tcp.tests.cc +++ b/src/base/network.tcp.tests.cc @@ -21,21 +21,19 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "config.h" - #include +#include "config.h" #include "doctest/doctest.h" - #include "network.tcp.hh" -TEST_CASE ("bad hostname") +TEST_CASE("bad hostname") { auto connect_res = network::tcp::connect("foobar.bazzer", "http"); CHECK(connect_res.unwrapErr() == @@ -43,7 +41,7 @@ TEST_CASE ("bad hostname") "provided, or not known"); } -TEST_CASE ("bad servname") +TEST_CASE("bad servname") { auto connect_res = network::tcp::connect("www.cnn.com", "non-existent"); CHECK(connect_res.unwrapErr() == diff --git a/src/base/opt_util.hh b/src/base/opt_util.hh index bdaf52d6..3c28596d 100644 --- a/src/base/opt_util.hh +++ b/src/base/opt_util.hh @@ -21,8 +21,8 @@ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @@ -37,36 +37,47 @@ namespace detail { - template - typename std::enable_if::value, T>::type - void_or_nullopt() - { - return; - } +template +typename std::enable_if::value, T>::type +void_or_nullopt() +{ + return; +} - template - typename std::enable_if::value, T>::type - void_or_nullopt() - { - return nonstd::nullopt; - } +template +typename std::enable_if::value, T>::type +void_or_nullopt() +{ + return nonstd::nullopt; +} - template - struct is_optional : std::false_type {}; +template +struct is_optional : std::false_type { +}; - template - struct is_optional> : std::true_type {}; -} +template +struct is_optional> : std::true_type { +}; +} // namespace detail -template >::value, int> = 0> -auto operator|(T&& t, F f) -> decltype(detail::void_or_nullopt(t).operator*()))>()) { +template>::value, int> = 0> +auto +operator|(T&& t, F f) + -> decltype(detail::void_or_nullopt(t). + operator*()))>()) +{ using return_type = decltype(f(std::forward(t).operator*())); - if (t) return f(std::forward(t).operator*()); - else return detail::void_or_nullopt(); + if (t) + return f(std::forward(t).operator*()); + else + return detail::void_or_nullopt(); } -template< class T > -optional_constexpr nonstd::optional< typename std::decay::type > make_optional_from_nullable( T && v ) +template +optional_constexpr nonstd::optional::type> +make_optional_from_nullable(T&& v) { if (v != nullptr) { return nonstd::optional::type>( @@ -75,8 +86,9 @@ optional_constexpr nonstd::optional< typename std::decay::type > make_optiona return nonstd::nullopt; } -template