diff --git a/.clang-format b/.clang-format index 0b8c0be..86cbf0d 100644 --- a/.clang-format +++ b/.clang-format @@ -1,17 +1,163 @@ -BasedOnStyle: LLVM -IndentWidth: 4 -ColumnLimit: 140 -TabWidth: 4 -UseTab: Never -BreakBeforeBraces: Allman -AllowShortFunctionsOnASingleLine: Empty -PointerAlignment: Left +--- +Language: Cpp +# BasedOnStyle: Microsoft +AccessModifierOffset: -2 +AlignAfterOpenBracket: BlockIndent +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: false +AlignConsecutiveAssignments: true +AlignConsecutiveDeclarations: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortEnumsOnASingleLine: false +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: false +BinPackParameters: AlwaysOnePerLine +BraceWrapping: + AfterCaseLabel: false + AfterClass: true + AfterControlStatement: Always + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: false + AfterExternBlock: true + BeforeCatch: true + BeforeElse: true + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: true +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DeriveLineEnding: true DerivePointerAlignment: false +DisableFormat: false +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +StatementAttributeLikeMacros: + - Q_EMIT +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentCaseLabels: false +IndentCaseBlocks: false +IndentGotoLabels: true +IndentPPDirectives: None +IndentExternBlock: AfterExternBlock +IndentRequires: false +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 1000 +PenaltyIndentedWhitespace: 0 +PointerAlignment: Right +ReflowComments: true +SortIncludes: true +SortJavaStaticImport: Before +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements -SortIncludes: true -IncludeBlocks: Regroup -ReflowComments: true -ContinuationIndentWidth: 4 -BinPackParameters: false -BinPackArguments: false - \ No newline at end of file +SpaceAroundPointerQualifiers: Default +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +BitFieldColonSpacing: Both +Standard: Latest +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 4 +UseCRLF: false +UseTab: Never +WhitespaceSensitiveMacros: + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME +... diff --git a/.clang-tidy b/.clang-tidy index 6793178..3ddf761 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,30 +1,593 @@ -Checks: > - -*, - readability-* , - modernize-* , - -modernize-use-trailing-return-type, - -readability-magic-numbers, - -WarningsAsErrors: > - bugprone-* , - performance-* , - clang-analyzer-* - -HeaderFilterRegex: 'src/.*' -FormatStyle: file - +--- +Checks: '*, + -bugprone-easily-swappable-parameters, + -bugprone-lambda-function-name, + -readability-magic-numbers, + -hicpp-no-array-decay, + -hicpp-signed-bitwise, + -hicpp-vararg, + -misc-non-private-member-variables-in-classes, + -cppcoreguidelines-*, + -fuchsia-*, + -altera-*, + -android-*, + -llvmlibc-*, + -readability-convert-member-functions-to-static, + -boost-use-ranges, + -google-objc-function-naming, + -google-objc-global-variable-declaration, + -performance-enum-size' +WarningsAsErrors: '' +HeaderFilterRegex: '^(?!magic_enum).*$' +FormatStyle: Microsoft CheckOptions: + - key: readability-identifier-naming.ClassCase + value: CamelCase + - key: readability-identifier-naming.ClassMemberCase + value: lower_case + - key: readability-identifier-naming.ConstexprVariableCase + value: CamelCase + - key: readability-identifier-naming.ConstexprVariablePrefix + value: k + - key: readability-identifier-naming.EnumCase + value: CamelCase + - key: readability-identifier-naming.EnumConstantCase + value: CamelCase + - key: readability-identifier-naming.EnumConstantPrefix + value: k + - key: readability-identifier-naming.FunctionCase + value: camelBack + - key: readability-identifier-naming.FunctionIgnoredRegexp + value: '^BM_.*$' + - key: readability-identifier-naming.GlobalConstantCase + value: CamelCase + - key: readability-identifier-naming.GlobalConstantPrefix + value: k + - key: readability-identifier-naming.StaticConstantCase + value: CamelCase + - key: readability-identifier-naming.StaticConstantPrefix + value: k + - key: readability-identifier-naming.StaticVariableCase + value: lower_case + - key: readability-identifier-naming.MacroDefinitionCase + value: UPPER_CASE + - key: readability-identifier-naming.MacroDefinitionIgnoredRegexp + value: '^[A-Z]+(_[A-Z]+)*_$' + - key: readability-identifier-naming.MemberCase + value: lower_case + - key: readability-identifier-naming.PrivateMemberSuffix + value: _ + - key: readability-identifier-naming.PublicMemberSuffix + value: '' + - key: readability-identifier-naming.NamespaceCase + value: lower_case + - key: readability-identifier-naming.ParameterCase + value: lower_case + - key: readability-identifier-naming.TypeAliasCase + value: CamelCase + - key: readability-identifier-naming.TypedefCase + value: CamelCase + - key: readability-identifier-naming.VariableCase + value: lower_case + - key: readability-identifier-naming.IgnoreMainLikeFunctions + value: 'true' + - key: readability-identifier-naming.AggressiveDependentMemberLookup + value: 'false' + - key: readability-identifier-naming.IgnoreFailedSplit + value: 'false' + - key: abseil-string-find-startswith.AbseilStringsMatchHeader + value: 'absl/strings/match.h' + - key: abseil-string-find-startswith.IncludeStyle + value: llvm + - key: abseil-string-find-startswith.StringLikeClasses + value: '::std::basic_string' + - key: abseil-string-find-str-contains.AbseilStringsMatchHeader + value: 'absl/strings/match.h' + - key: abseil-string-find-str-contains.IncludeStyle + value: llvm + - key: abseil-string-find-str-contains.StringLikeClasses + value: '::std::basic_string;::std::basic_string_view;::absl::string_view' + - key: bugprone-argument-comment.CommentBoolLiterals + value: '0' + - key: bugprone-argument-comment.CommentCharacterLiterals + value: '0' + - key: bugprone-argument-comment.CommentFloatLiterals + value: '0' + - key: bugprone-argument-comment.CommentIntegerLiterals + value: '0' + - key: bugprone-argument-comment.CommentNullPtrs + value: '0' + - key: bugprone-argument-comment.CommentStringLiterals + value: '0' + - key: bugprone-argument-comment.CommentUserDefinedLiterals + value: '0' + - key: bugprone-argument-comment.IgnoreSingleArgument + value: '0' + - key: bugprone-argument-comment.StrictMode + value: '0' + - key: bugprone-assert-side-effect.AssertMacros + value: assert + - key: bugprone-assert-side-effect.CheckFunctionCalls + value: 'false' + - key: bugprone-dangling-handle.HandleClasses + value: 'std::basic_string_view;std::experimental::basic_string_view' + - key: bugprone-dynamic-static-initializers.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: bugprone-exception-escape.FunctionsThatShouldNotThrow + value: '' + - key: bugprone-exception-escape.IgnoredExceptions + value: '' + - key: bugprone-misplaced-widening-cast.CheckImplicitCasts + value: 'false' + - key: bugprone-narrowing-conversions.PedanticMode + value: 'false' + - key: bugprone-narrowing-conversions.WarnOnFloatingPointNarrowingConversion + value: 'true' + - key: bugprone-not-null-terminated-result.WantToUseSafeFunctions + value: 'true' + - key: bugprone-reserved-identifier.AggressiveDependentMemberLookup + value: 'false' + - key: bugprone-reserved-identifier.AllowedIdentifiers + value: '' + - key: bugprone-reserved-identifier.Invert + value: 'false' + - key: bugprone-signed-char-misuse.CharTypdefsToIgnore + value: '' + - key: bugprone-signed-char-misuse.DiagnoseSignedUnsignedCharComparisons + value: 'true' + - key: bugprone-sizeof-expression.WarnOnSizeOfCompareToConstant + value: 'true' + - key: bugprone-sizeof-expression.WarnOnSizeOfConstant + value: 'true' + - key: bugprone-sizeof-expression.WarnOnSizeOfIntegerExpression + value: 'false' + - key: bugprone-sizeof-expression.WarnOnSizeOfThis + value: 'true' + - key: bugprone-string-constructor.LargeLengthThreshold + value: '8388608' + - key: bugprone-string-constructor.WarnOnLargeLength + value: 'true' + - key: bugprone-suspicious-enum-usage.StrictMode + value: 'false' + - key: bugprone-suspicious-include.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: bugprone-suspicious-include.ImplementationFileExtensions + value: 'c;cc;cpp;cxx' + - key: bugprone-suspicious-missing-comma.MaxConcatenatedTokens + value: '5' + - key: bugprone-suspicious-missing-comma.RatioThreshold + value: '0.200000' + - key: bugprone-suspicious-missing-comma.SizeThreshold + value: '5' + - key: bugprone-suspicious-string-compare.StringCompareLikeFunctions + value: '' + - key: bugprone-suspicious-string-compare.WarnOnImplicitComparison + value: 'true' + - key: bugprone-suspicious-string-compare.WarnOnLogicalNotComparison + value: 'false' + - key: bugprone-too-small-loop-variable.MagnitudeBitsUpperLimit + value: '16' + - key: bugprone-unhandled-self-assignment.WarnOnlyIfThisHasSuspiciousField + value: 'true' + - key: bugprone-unused-return-value.CheckedFunctions + value: '::std::async;::std::launder;::std::remove;::std::remove_if;::std::unique;::std::unique_ptr::release;::std::basic_string::empty;::std::vector::empty;::std::back_inserter;::std::distance;::std::find;::std::find_if;::std::inserter;::std::lower_bound;::std::make_pair;::std::map::count;::std::map::find;::std::map::lower_bound;::std::multimap::equal_range;::std::multimap::upper_bound;::std::set::count;::std::set::find;::std::setfill;::std::setprecision;::std::setw;::std::upper_bound;::std::vector::at;::bsearch;::ferror;::feof;::isalnum;::isalpha;::isblank;::iscntrl;::isdigit;::isgraph;::islower;::isprint;::ispunct;::isspace;::isupper;::iswalnum;::iswprint;::iswspace;::isxdigit;::memchr;::memcmp;::strcmp;::strcoll;::strncmp;::strpbrk;::strrchr;::strspn;::strstr;::wcscmp;::access;::bind;::connect;::difftime;::dlsym;::fnmatch;::getaddrinfo;::getopt;::htonl;::htons;::iconv_open;::inet_addr;::isascii;::isatty;::mmap;::newlocale;::openat;::pathconf;::pthread_equal;::pthread_getspecific;::pthread_mutex_trylock;::readdir;::readlink;::recvmsg;::regexec;::scandir;::semget;::setjmp;::shm_open;::shmget;::sigismember;::strcasecmp;::strsignal;::ttyname' + - key: cert-dcl16-c.IgnoreMacros + value: 'true' + - key: cert-dcl16-c.NewSuffixes + value: 'L;LL;LU;LLU' + - key: cert-dcl37-c.AggressiveDependentMemberLookup + value: 'false' + - key: cert-dcl37-c.AllowedIdentifiers + value: '' + - key: cert-dcl37-c.Invert + value: 'false' + - key: cert-dcl51-cpp.AggressiveDependentMemberLookup + value: 'false' + - key: cert-dcl51-cpp.AllowedIdentifiers + value: '' + - key: cert-dcl51-cpp.Invert + value: 'false' + - key: cert-dcl59-cpp.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: cert-err09-cpp.CheckThrowTemporaries + value: 'true' + - key: cert-err09-cpp.MaxSize + value: '-1' + - key: cert-err09-cpp.WarnOnLargeObjects + value: 'false' + - key: cert-err61-cpp.CheckThrowTemporaries + value: 'true' + - key: cert-err61-cpp.MaxSize + value: '-1' + - key: cert-err61-cpp.WarnOnLargeObjects + value: 'false' + - key: cert-msc32-c.DisallowedSeedTypes + value: 'time_t,std::time_t' + - key: cert-msc51-cpp.DisallowedSeedTypes + value: 'time_t,std::time_t' + - key: cert-oop11-cpp.IncludeStyle + value: llvm + - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField + value: 'false' + - key: cert-oop57-cpp.MemCmpNames + value: '' + - key: cert-oop57-cpp.MemCpyNames + value: '' + - key: cert-oop57-cpp.MemSetNames + value: '' + - key: cert-str34-c.CharTypdefsToIgnore + value: '' + - key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons + value: 'false' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoreAllFloatingPointValues + value: 'false' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoreBitFieldsWidths + value: 'true' + - key: cppcoreguidelines-avoid-magic-numbers.IgnorePowersOf2IntegerValues + value: 'false' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: cppcoreguidelines-explicit-virtual-functions.AllowOverrideAndFinal + value: 'false' + - key: cppcoreguidelines-explicit-virtual-functions.FinalSpelling + value: final + - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors + value: 'true' + - key: cppcoreguidelines-explicit-virtual-functions.OverrideSpelling + value: override + - key: cppcoreguidelines-init-variables.IncludeStyle + value: llvm + - key: cppcoreguidelines-init-variables.MathHeader + value: math.h + - key: cppcoreguidelines-macro-usage.AllowedRegexp + value: '^DEBUG_*' + - key: cppcoreguidelines-macro-usage.CheckCapsOnly + value: 'false' + - key: cppcoreguidelines-macro-usage.IgnoreCommandLineMacros + value: 'true' + - key: cppcoreguidelines-narrowing-conversions.PedanticMode + value: 'false' + - key: cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion + value: 'true' + - key: cppcoreguidelines-no-malloc.Allocations + value: '::malloc;::calloc' + - key: cppcoreguidelines-no-malloc.Deallocations + value: '::free' + - key: cppcoreguidelines-no-malloc.Reallocations + value: '::realloc' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: 'true' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnorePublicMemberVariables + value: 'false' + - key: cppcoreguidelines-owning-memory.LegacyResourceConsumers + value: '::free;::realloc;::freopen;::fclose' + - key: cppcoreguidelines-owning-memory.LegacyResourceProducers + value: '::malloc;::aligned_alloc;::realloc;::calloc;::fopen;::freopen;::tmpfile' + - key: cppcoreguidelines-pro-bounds-constant-array-index.GslHeader + value: '' + - key: cppcoreguidelines-pro-bounds-constant-array-index.IncludeStyle + value: llvm + - key: cppcoreguidelines-pro-type-member-init.IgnoreArrays + value: 'false' + - key: cppcoreguidelines-pro-type-member-init.UseAssignment + value: 'false' + - key: cppcoreguidelines-special-member-functions.AllowMissingMoveFunctions + value: 'false' + - key: cppcoreguidelines-special-member-functions.AllowMissingMoveFunctionsWhenCopyIsDeleted + value: 'false' + - key: cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor + value: 'false' + - key: google-build-namespaces.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: google-global-names-in-headers.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: google-readability-braces-around-statements.ShortStatementLines + value: '1' + - key: google-readability-function-size.BranchThreshold + value: '4294967295' + - key: google-readability-function-size.LineThreshold + value: '4294967295' + - key: google-readability-function-size.NestingThreshold + value: '4294967295' + - key: google-readability-function-size.ParameterThreshold + value: '4294967295' + - key: google-readability-function-size.StatementThreshold + value: '800' + - key: google-readability-function-size.VariableThreshold + value: '4294967295' + - key: google-readability-namespace-comments.ShortNamespaceLines + value: '10' + - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' + - key: google-runtime-int.SignedTypePrefix + value: int + - key: google-runtime-int.TypeSuffix + value: '' + - key: google-runtime-int.UnsignedTypePrefix + value: uint + - key: google-runtime-references.IncludedTypes + value: '' + - key: hicpp-braces-around-statements.ShortStatementLines + value: '0' + - key: hicpp-function-size.BranchThreshold + value: '4294967295' + - key: hicpp-function-size.LineThreshold + value: '4294967295' + - key: hicpp-function-size.NestingThreshold + value: '4294967295' + - key: hicpp-function-size.ParameterThreshold + value: '4294967295' + - key: hicpp-function-size.StatementThreshold + value: '800' + - key: hicpp-function-size.VariableThreshold + value: '4294967295' + - key: hicpp-member-init.IgnoreArrays + value: 'false' + - key: hicpp-member-init.UseAssignment + value: 'false' + - key: hicpp-move-const-arg.CheckTriviallyCopyableMove + value: 'true' + - key: hicpp-multiway-paths-covered.WarnOnMissingElse + value: 'false' + - key: hicpp-no-malloc.Allocations + value: '::malloc;::calloc' + - key: hicpp-no-malloc.Deallocations + value: '::free' + - key: hicpp-no-malloc.Reallocations + value: '::realloc' + - key: hicpp-signed-bitwise.IgnorePositiveIntegerLiterals + value: 'false' + - key: hicpp-special-member-functions.AllowMissingMoveFunctions + value: 'false' + - key: hicpp-special-member-functions.AllowMissingMoveFunctionsWhenCopyIsDeleted + value: 'false' + - key: hicpp-special-member-functions.AllowSoleDefaultDtor + value: 'false' + - key: hicpp-uppercase-literal-suffix.IgnoreMacros + value: 'true' + - key: hicpp-uppercase-literal-suffix.NewSuffixes + value: '' + - key: hicpp-use-auto.MinTypeNameLength + value: '5' + - key: hicpp-use-auto.RemoveStars + value: 'false' + - key: hicpp-use-emplace.ContainersWithPushBack + value: '::std::vector;::std::list;::std::deque' + - key: hicpp-use-emplace.IgnoreImplicitConstructors + value: 'false' + - key: hicpp-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' + - key: hicpp-use-emplace.TupleMakeFunctions + value: '::std::make_pair;::std::make_tuple' + - key: hicpp-use-emplace.TupleTypes + value: '::std::pair;::std::tuple' + - key: hicpp-use-equals-default.IgnoreMacros + value: 'true' + - key: hicpp-use-equals-delete.IgnoreMacros + value: 'true' + - key: hicpp-use-noexcept.ReplacementString + value: '' + - key: hicpp-use-noexcept.UseNoexceptFalse + value: 'true' + - key: hicpp-use-nullptr.NullMacros + value: '' + - key: hicpp-use-override.AllowOverrideAndFinal + value: 'false' + - key: hicpp-use-override.FinalSpelling + value: final + - key: hicpp-use-override.IgnoreDestructors + value: 'false' + - key: hicpp-use-override.OverrideSpelling + value: override + - key: llvm-else-after-return.WarnOnConditionVariables + value: 'false' + - key: llvm-else-after-return.WarnOnUnfixable + value: 'false' + - key: llvm-header-guard.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: llvm-namespace-comment.ShortNamespaceLines + value: '1' + - key: llvm-namespace-comment.SpacesBeforeComments + value: '1' + - key: llvm-qualified-auto.AddConstToQualified + value: 'false' + - key: misc-definitions-in-headers.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: misc-definitions-in-headers.UseHeaderFileExtension + value: 'true' + - key: misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: 'false' + - key: misc-non-private-member-variables-in-classes.IgnorePublicMemberVariables + value: 'false' + - key: misc-throw-by-value-catch-by-reference.CheckThrowTemporaries + value: 'true' + - key: misc-throw-by-value-catch-by-reference.MaxSize + value: '-1' + - key: misc-throw-by-value-catch-by-reference.WarnOnLargeObjects + value: 'false' + - key: misc-unused-parameters.StrictMode + value: 'false' + - key: modernize-avoid-bind.PermissiveParameterList + value: 'false' + - key: modernize-loop-convert.MaxCopySize + value: '16' + - key: modernize-loop-convert.MinConfidence + value: reasonable + - key: modernize-loop-convert.NamingStyle + value: CamelCase + - key: modernize-make-shared.IgnoreMacros + value: 'true' + - key: modernize-make-shared.IncludeStyle + value: llvm + - key: modernize-make-shared.MakeSmartPtrFunction + value: 'std::make_shared' + - key: modernize-make-shared.MakeSmartPtrFunctionHeader + value: memory + - key: modernize-make-unique.IgnoreMacros + value: 'true' + - key: modernize-make-unique.IncludeStyle + value: llvm + - key: modernize-make-unique.MakeSmartPtrFunction + value: 'std::make_unique' + - key: modernize-make-unique.MakeSmartPtrFunctionHeader + value: memory + - key: modernize-pass-by-value.IncludeStyle + value: llvm + - key: modernize-pass-by-value.ValuesOnly + value: 'false' + - key: modernize-raw-string-literal.DelimiterStem + value: lit + - key: modernize-raw-string-literal.ReplaceShorterLiterals + value: 'false' + - key: modernize-replace-auto-ptr.IncludeStyle + value: llvm + - key: modernize-replace-disallow-copy-and-assign-macro.MacroName + value: DISALLOW_COPY_AND_ASSIGN + - key: modernize-replace-random-shuffle.IncludeStyle + value: llvm - key: modernize-use-auto.MinTypeNameLength value: '5' - key: modernize-use-auto.RemoveStars value: 'false' - - key: readability-identifier-naming.VariableCase - value: lower_case - - key: readability-identifier-naming.MemberCase - value: lower_case - - key: readability-identifier-naming.PrivateMemberPrefix - value: '_' - - key: readability-function-size.ParameterThreshold - value: '8' + - key: modernize-use-bool-literals.IgnoreMacros + value: 'true' + - key: modernize-use-default-member-init.IgnoreMacros + value: 'true' + - key: modernize-use-default-member-init.UseAssignment + value: 'false' + - key: modernize-use-emplace.ContainersWithPushBack + value: '::std::vector;::std::list;::std::deque' + - key: modernize-use-emplace.IgnoreImplicitConstructors + value: 'false' + - key: modernize-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' + - key: modernize-use-emplace.TupleMakeFunctions + value: '::std::make_pair;::std::make_tuple' + - key: modernize-use-emplace.TupleTypes + value: '::std::pair;::std::tuple' + - key: modernize-use-equals-default.IgnoreMacros + value: 'true' + - key: modernize-use-equals-delete.IgnoreMacros + value: 'true' + - key: modernize-use-nodiscard.ReplacementString + value: '[[nodiscard]]' + - key: modernize-use-noexcept.ReplacementString + value: '' + - key: modernize-use-noexcept.UseNoexceptFalse + value: 'true' + - key: modernize-use-nullptr.NullMacros + value: 'NULL' + - key: modernize-use-override.AllowOverrideAndFinal + value: 'false' + - key: modernize-use-override.FinalSpelling + value: final + - key: modernize-use-override.IgnoreDestructors + value: 'false' + - key: modernize-use-override.OverrideSpelling + value: override + - key: modernize-use-transparent-functors.SafeMode + value: 'false' + - key: modernize-use-using.IgnoreMacros + value: 'true' + - key: objc-forbidden-subclassing.ForbiddenSuperClassNames + value: 'ABNewPersonViewController;ABPeoplePickerNavigationController;ABPersonViewController;ABUnknownPersonViewController;NSHashTable;NSMapTable;NSPointerArray;NSPointerFunctions;NSTimer;UIActionSheet;UIAlertView;UIImagePickerController;UITextInputMode;UIWebView' + - key: openmp-exception-escape.IgnoredExceptions + value: '' + - key: performance-faster-string-find.StringLikeClasses + value: '::std::basic_string;::std::basic_string_view' + - key: performance-for-range-copy.AllowedTypes + value: '' + - key: performance-for-range-copy.WarnOnAllAutoCopies + value: 'false' + - key: performance-inefficient-string-concatenation.StrictMode + value: 'false' + - key: performance-inefficient-vector-operation.EnableProto + value: 'false' + - key: performance-inefficient-vector-operation.VectorLikeClasses + value: '::std::vector' + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: 'true' + - key: performance-move-constructor-init.IncludeStyle + value: llvm + - key: performance-no-automatic-move.AllowedTypes + value: '' + - key: performance-type-promotion-in-math-fn.IncludeStyle + value: llvm + - key: performance-unnecessary-copy-initialization.AllowedTypes + value: '' + - key: performance-unnecessary-value-param.AllowedTypes + value: '' + - key: performance-unnecessary-value-param.IncludeStyle + value: llvm + - key: portability-restrict-system-includes.Includes + value: '*' + - key: portability-simd-intrinsics.Std + value: '' + - key: portability-simd-intrinsics.Suggest + value: '0' - key: readability-braces-around-statements.ShortStatementLines value: '0' + - key: readability-else-after-return.WarnOnConditionVariables + value: 'true' + - key: readability-else-after-return.WarnOnUnfixable + value: 'true' + - key: readability-function-size.BranchThreshold + value: '4294967295' + - key: readability-function-size.LineThreshold + value: '4294967295' + - key: readability-function-size.NestingThreshold + value: '4294967295' + - key: readability-function-size.ParameterThreshold + value: '4294967295' + - key: readability-function-size.StatementThreshold + value: '800' + - key: readability-function-size.VariableThreshold + value: '4294967295' + - key: readability-implicit-bool-conversion.AllowIntegerConditions + value: 'false' + - key: readability-implicit-bool-conversion.AllowPointerConditions + value: 'false' + - key: readability-inconsistent-declaration-parameter-name.IgnoreMacros + value: 'true' + - key: readability-inconsistent-declaration-parameter-name.Strict + value: 'false' + - key: readability-magic-numbers.IgnoreAllFloatingPointValues + value: 'false' + - key: readability-magic-numbers.IgnoreBitFieldsWidths + value: 'true' + - key: readability-magic-numbers.IgnorePowersOf2IntegerValues + value: 'false' + - key: readability-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: readability-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: readability-qualified-auto.AddConstToQualified + value: 'true' + - key: readability-redundant-declaration.IgnoreMacros + value: 'true' + - key: readability-redundant-member-init.IgnoreBaseInCopyConstructors + value: 'false' + - key: readability-redundant-smartptr-get.IgnoreMacros + value: 'true' + - key: readability-redundant-string-init.StringNames + value: '::std::basic_string' + - key: readability-simplify-boolean-expr.ChainedConditionalAssignment + value: 'false' + - key: readability-simplify-boolean-expr.ChainedConditionalReturn + value: 'false' + - key: readability-simplify-subscript-expr.Types + value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array' + - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold + value: '3' + - key: readability-uppercase-literal-suffix.IgnoreMacros + value: 'true' + - key: readability-uppercase-literal-suffix.NewSuffixes + value: '' + - key: zircon-temporary-objects.Names + value: '' +# allow x,y,z single letter names, to be used for coordinates + - key: readability-identifier-length.IgnoredVariableNames + value: '^[xyz]|m0|m1|_$' +... diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2a66b50..571733f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -name: Build & Release CPP-Unix-Bindings +name: Build & Release cpp_unix_bindings on: push: @@ -12,34 +12,24 @@ jobs: build: name: Build shared library runs-on: ubuntu-latest - env: - CC: clang - CXX: clang++ steps: - name: Checkout repository uses: actions/checkout@v3 - - name: Install build dependencies + - name: Build in manylinux2014 container run: | - sudo apt-get update - sudo apt-get install -y build-essential cmake clang make - - - name: Configure CMake - run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release - - - name: Compile - run: cmake --build build -j $(nproc) + docker run --rm -v "${{ github.workspace }}:/project" -w /project quay.io/pypa/manylinux2014_x86_64 /bin/bash -c "yum install -y cmake3 devtoolset-11-gcc devtoolset-11-gcc-c++ && ln -sf /usr/bin/cmake3 /usr/bin/cmake && source /opt/rh/devtoolset-11/enable && cmake -S . -B build -DCMAKE_BUILD_TYPE=Release && cmake --build build -j\$(nproc)" - name: Upload library artifact uses: actions/upload-artifact@v4 with: - name: libCPP-Unix-Bindings - path: build/libCPP-Unix-Bindings.so + name: libcpp_unix_bindings + path: build/libcpp_unix_bindings.so retention-days: 14 - name: Attach library to release if: github.event_name == 'release' uses: softprops/action-gh-release@v1 with: - files: build/libCPP-Unix-Bindings.so + files: build/libcpp_unix_bindings.so diff --git a/.gitignore b/.gitignore index f80d786..33bb172 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ .vscode/ build/ -src/version_config.cpp +src/version_config.h .cache/ compile_commands.json diff --git a/CMakeLists.txt b/CMakeLists.txt index e1886b7..5d00efa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,105 +1,72 @@ cmake_minimum_required(VERSION 3.30) -set(VERSION_MAJOR 0) -set(VERSION_MINOR 2) -set(VERSION_PATCH 0) +project(cpp_unix_bindings VERSION 1.0.0 LANGUAGES CXX) -set(PROJECT_N CPP-Unix-Bindings) -project(${PROJECT_N} VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}) +# Ensure position-independent code for all targets (required for shared libraries) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +# Always use pthread +add_link_options(-pthread) +add_compile_options(-pthread) # Generate compile_commands.json for clang-based tooling (clangd / clang-tidy) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +# C++ standard +set(CMAKE_CXX_STANDARD 23) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + include(cmake/CPM.cmake) +# Dependencies CPMAddPackage( - NAME "googletest" - GITHUB_REPOSITORY "google/googletest" - GIT_TAG "v1.17.0" + NAME googletest + GITHUB_REPOSITORY google/googletest + GIT_TAG v1.17.0 GIT_SHALLOW TRUE - OPTIONS "GTEST_BUILD_TESTS OFF" - OPTIONS "GTEST_BUILD_EXAMPLES OFF" - OPTIONS "GTEST_BUILD_DOCS OFF" + OPTIONS + "GTEST_BUILD_TESTS OFF" + "GTEST_BUILD_EXAMPLES OFF" + "GTEST_BUILD_DOCS OFF" ) -# Ensure clang tooling can pick up compile_commands.json from project root -if(CMAKE_EXPORT_COMPILE_COMMANDS) - add_custom_target(copy-compile-commands ALL - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${CMAKE_BINARY_DIR}/compile_commands.json - ${PROJECT_SOURCE_DIR}/compile_commands.json - COMMENT "Copy compile_commands.json to project root" - VERBATIM) -endif() - -set(CMAKE_CXX_STANDARD 23) -set(CMAKE_CXX_STANDARD_REQUIRED True) - -file(GLOB_RECURSE SRCS ${PROJECT_SOURCE_DIR}/src/**.cpp) - -set(LIB true) - -configure_file(versioning/version_config.cpp.in ${PROJECT_SOURCE_DIR}/src/version_config.cpp) - -# a macro that gets all of the header containing directories. -MACRO(header_directories return_list includes_base_folder extention ) - FILE(GLOB_RECURSE new_list ${includes_base_folder}/*.${extention}) - SET(dir_list "") - FOREACH(file_path ${new_list}) - GET_FILENAME_COMPONENT(dir_path ${file_path} PATH) - SET(dir_list ${dir_list} ${dir_path}) - ENDFOREACH() - LIST(REMOVE_DUPLICATES dir_list) - SET(${return_list} ${dir_list}) -ENDMACRO() - -# using said macro. -header_directories(INCLUDES ${PROJECT_SOURCE_DIR}/src/ hpp) - -message("src files:") -foreach(file ${SRCS}) - message(STATUS ${file}) -endforeach() - -message("include directories:") -foreach(dir ${INCLUDES}) - message(STATUS ${dir}) -endforeach() - -if(LIB) - add_library(${PROJECT_N} SHARED ${SRCS}) -else() - add_executable(${PROJECT_N} ${SRCS}) -endif(LIB) +CPMAddPackage( + NAME cpp_core + GITHUB_REPOSITORY Serial-IO/cpp-core + GIT_TAG revamp-project +) -set_target_properties(${PROJECT_N} PROPERTIES - VERSION ${PROJECT_VERSION} - SOVERSION ${PROJECT_VERSION_MAJOR}) +# Collect all source files +file(GLOB_RECURSE SRCS ${PROJECT_SOURCE_DIR}/src/*.cpp) -target_include_directories(${PROJECT_N} PUBLIC ${PROJECT_SOURCE_DIR}/src) +# Main library +add_library(${PROJECT_NAME} SHARED ${SRCS}) -add_executable(serial_integration_tests tests/serial_test.cpp) -target_link_libraries(serial_integration_tests PRIVATE ${PROJECT_N} gtest_main) +target_link_libraries(${PROJECT_NAME} PRIVATE cpp_core) +target_include_directories(${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/src) -target_include_directories(serial_integration_tests PRIVATE ${PROJECT_SOURCE_DIR}/src) +set_target_properties(${PROJECT_NAME} PROPERTIES + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} +) -add_custom_command(TARGET serial_integration_tests POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - $ - $ - COMMENT "Copy shared library next to test binary") +# Test executable +add_executable(tests + tests/serial_test.cpp + tests/serial_unit_tests.cpp +) -# Unit test target covering additional API aspects -add_executable(serial_unit_tests tests/serial_unit_tests.cpp) -target_link_libraries(serial_unit_tests PRIVATE ${PROJECT_N} gtest_main) -target_include_directories(serial_unit_tests PRIVATE ${PROJECT_SOURCE_DIR}/src) +target_link_libraries(tests PRIVATE ${PROJECT_NAME} gtest cpp_core) +target_include_directories(tests PRIVATE ${PROJECT_SOURCE_DIR}/src) -add_custom_command(TARGET serial_unit_tests POST_BUILD +# Copy shared library next to test binary +add_custom_command(TARGET tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different - $ - $ - COMMENT "Copy shared library next to unit test binary") + $ + $ + COMMENT "Copy shared library next to test binary" +) +# Testing enable_testing() -add_test(NAME SerialEchoTest COMMAND serial_integration_tests /dev/ttyUSB0) -add_test(NAME SerialUnitTests COMMAND serial_unit_tests) +add_test(NAME AllTests COMMAND tests /dev/ttyUSB0) diff --git a/README.md b/README.md index 3e4d0c0..2d50175 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -# CPP-Unix-Bindings +# cpp_unix_bindings A compact C++23 library for talking to serial devices on Linux (e.g. Arduino). -The project builds a **shared library `libCPP-Unix-Bindings.so`** that can be used via +The project builds a **shared library `libcpp_unix_bindings.so`** that can be used via Deno's native FFI. --- @@ -21,7 +21,7 @@ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release cmake --build build -j # The resulting library will be located at -# build/libCPP-Unix-Bindings.so +# build/libcpp_unix_bindings.so ``` > Because `CMAKE_EXPORT_COMPILE_COMMANDS` is enabled, the build also generates a @@ -36,7 +36,7 @@ Deno ships with a first-class FFI API. ```ts // serial_deno.ts -const lib = Deno.dlopen('./build/libCPP-Unix-Bindings.so', { +const lib = Deno.dlopen('./build/libcpp_unix_bindings.so', { serialOpen: { parameters: [ 'buffer', 'i32', 'i32', 'i32', 'i32' ], result: 'pointer' }, serialClose: { parameters: [ 'pointer' ], result: 'void' }, serialRead: { parameters: [ 'pointer', 'buffer', 'i32', 'i32', 'i32' ], result: 'i32' }, @@ -64,16 +64,72 @@ lib.close(); ## 3 C API reference -| Function | Description | -|----------|-------------| -| `intptr_t serialOpen(const char* dev, int baud, int bits, int parity, int stop)` | Open a device and return a handle. | -| `void serialClose(intptr_t handle)` | Close the port. | -| `int serialRead(...)` | Read bytes with timeout. | -| `int serialWrite(...)` | Write bytes with timeout. | -| `int serialGetPortsInfo(char* buffer, int len, const char* sep)` | List ports under `/dev/serial/by-id`. | -| `void serialOnError(void (*)(int))` | Register an error callback. | -| *(others in `serial.h`)* | - -Return values ≤ 0 indicate error codes defined in `status_codes.h`. +Below is a condensed overview of the most relevant functions. See `serial.h` for full +signatures and additional helpers. + +### Connection +* `serialOpen(...)` – open a serial device and return a handle +* `serialClose(handle)` – close the device + +### I/O +* `serialRead(...)` / `serialWrite(...)` – basic read/write with timeout +* `serialReadUntil(...)` – read until a specific char is encountered (inclusive) +* `serialReadLine(...)` – read until `\n` +* `serialWriteLine(...)` – write buffer and append `\n` +* `serialReadUntilToken(...)` – read until a string token is encountered +* `serialReadFrame(...)` – read a frame delimited by start & end bytes + +### Helpers +* `serialPeek(...)` – look at the next byte without consuming it +* `serialDrain(...)` – wait until all TX bytes are sent +* `serialClearBufferIn/Out(...)` – drop buffered bytes +* `serialAbortRead/Write(...)` – abort pending I/O operations + +### Statistics +* `serialGetRxBytes(handle)` / `serialGetTxBytes(handle)` – cumulative RX / TX byte counters + +### Enumeration & autodetect +* `serialGetPortsInfo(...)` – list available ports under `/dev/serial/by-id` + +### Callbacks +* `serialOnError(func)` – error callback +* `serialOnRead(func)` – read callback (bytes read) +* `serialOnWrite(func)` – write callback (bytes written) + +Return values ≤ 0 correspond to error codes defined in `status_codes.h`. + +--- + +## 4 Ready-made Deno examples + +Two runnable scripts live in `examples/` and require only Deno plus the compiled +shared library. + +- **serial_echo.ts** – Minimal echo test that lists available ports, opens the + first one and verifies that the micro-controller echoes the sent string. + Run it with: + ```bash + deno run --allow-ffi --allow-read examples/serial_echo.ts \ + --lib ./build/libcpp_unix_bindings.so \ + --port /dev/ttyUSB0 + ``` + +- **serial_advanced.ts** – Shows the high-level helpers (`serialWriteLine`, + `serialReadLine`, `serialPeek`, `statistics`, `serialDrain`). It sends three + lines and then prints the TX/RX counters. + ```bash + deno run --allow-ffi --allow-read examples/serial_advanced.ts \ + --lib ./build/libcpp_unix_bindings.so \ + --port /dev/ttyUSB0 + ``` + +Notes: +1. `--lib` defaults to `./build/libcpp_unix_bindings.so`; pass a custom path if +you installed the library elsewhere. +2. `--port` defaults to `/dev/ttyUSB0`; adjust if your board shows up under a +different device (e.g. `/dev/ttyACM0`). +3. On most Arduino boards opening the port toggles DTR and triggers a reset. + Both scripts therefore wait ~2 s after opening the device before sending the + first command. --- diff --git a/docs/api_reference.md b/docs/api_reference.md new file mode 100644 index 0000000..7ef8a2b --- /dev/null +++ b/docs/api_reference.md @@ -0,0 +1,129 @@ +# C API Reference + +**Scope** – Public interface of `libcpp_unix_bindings` (C-linkable). +*Linux fully supported · Windows fully supported* + +Every function is declared in `src/serial.h` and follows the same +convention: **positive / non-zero** ⇒ success, **≤ 0** ⇒ failure (maps to +`StatusCodes`). + +--- + +## 1 · Connection + +```c +intptr_t serialOpen(void* port, int baud, int dataBits, + int parity /*0-none·1-even·2-odd*/, + int stopBits /*0-1bit·2-2bit*/); + +void serialClose(int64_t handle); +``` + +*Linux*: `port` is a NULL-terminated path like `/dev/ttyUSB0` or +`/dev/tty.SLAB_USBtoUART`. +*Windows*: use `"COM3"`, `"\\.\\COM12"`, etc. (to be implemented). + +--- + +## 2 · Basic I/O + +```c +int serialRead (int64_t handle, void* buf, int len, int timeoutMs, int mult); +int serialWrite(int64_t handle, const void* buf, int len, int timeoutMs, int mult); + +int serialReadUntil(int64_t handle, void* buf, int len, + int timeoutMs, int mult, void* untilCharPtr); +``` + +*mult* is a polling multiplier (usually **1**). `serialReadUntil` stops **after** +the delimiter byte has been copied into *buf*. + +--- + +## 3 · Convenience helpers + +```c +int serialReadLine (int64_t h, void* buf, int len, int timeoutMs); // until '\n' +int serialWriteLine(int64_t h, const void* buf, int len, int timeoutMs); // appends '\n' + +int serialReadUntilSequence(int64_t h, void* buf, int len, + int timeoutMs, void* sequencePtr); + +int serialReadFrame(int64_t h, void* buf, int len, int timeoutMs, + char startByte, char endByte); +``` + +--- + +## 4 · Statistics & Buffer control + +```c +int64_t serialInBytesTotal (int64_t handle); // cumulative RX +int64_t serialOutBytesTotal(int64_t handle); // cumulative TX + +int serialInBytesWaiting (int64_t handle); // queued in driver +int serialOutBytesWaiting(int64_t handle); + +int serialDrain(int64_t handle); // wait for TX empty + +void serialClearBufferIn (int64_t handle); +void serialClearBufferOut(int64_t handle); + +void serialAbortRead (int64_t handle); +void serialAbortWrite(int64_t handle); +``` + +--- + +## 5 · Port enumeration & Callbacks + +```c +// Enumerate available ports. For each port the callback receives: +// portPath, aliasPath, manufacturer, serialNumber, pnpId, +// locationId, productId, vendorId +int serialGetPortsInfo(void (*cb)(const char*, const char*, const char*, + const char*, const char*, const char*, + const char*, const char*)); + +void serialOnError(void (*cb)(int code, const char* msg)); +void serialOnRead (void (*cb)(int bytes)); +void serialOnWrite(void (*cb)(int bytes)); +``` + +*Linux*: implementation scans `/dev/serial/by-id` if present, otherwise falls +back to common tty names. +*Windows*: will iterate over available COM ports. + +--- + +## 6 · StatusCodes + +```c++ +enum class StatusCodes : int { + SUCCESS = 0, + CLOSE_HANDLE_ERROR = -1, + INVALID_HANDLE_ERROR = -2, + READ_ERROR = -3, + WRITE_ERROR = -4, + GET_STATE_ERROR = -5, + SET_STATE_ERROR = -6, + SET_TIMEOUT_ERROR = -7, + BUFFER_ERROR = -8, + NOT_FOUND_ERROR = -9, + CLEAR_BUFFER_IN_ERROR = -10, + CLEAR_BUFFER_OUT_ERROR = -11, + ABORT_READ_ERROR = -12, + ABORT_WRITE_ERROR = -13 +}; +``` + +--- + +### Error-handling idiom + +```c +int rv = serialWrite(h, data, len, 500, 1); +if (rv <= 0) { + // handle error – detailed info via registered onError callback (if any) +} +``` diff --git a/docs/building.md b/docs/building.md new file mode 100644 index 0000000..fc447a9 --- /dev/null +++ b/docs/building.md @@ -0,0 +1,55 @@ +# Building the shared library + +## 1. Prerequisites + +* **Compiler:** `g++` or `clang++` with C++23 support +* **CMake ≥ 3.30** +* POSIX development headers (`termios.h`, `fcntl.h`, …) + +Example install on Debian/Ubuntu: + +```bash +sudo apt-get update +sudo apt-get install build-essential cmake clang make +``` + +--- + +## 2. Configure & Compile + +```bash +# From the repository root +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release +cmake --build build -j$(nproc) +``` + +This produces: + +* `build/libcpp_unix_bindings.so` – the shared library +* `build/tests` – aggregated gtest binary (run via `ctest` or `./tests`) +* `compile_commands.json` – copied to project root for clang-tools + +### Debug build + +```bash +cmake -S . -B build/debug -DCMAKE_BUILD_TYPE=Debug +cmake --build build/debug -j +``` + +### Installing system-wide + +```bash +sudo cmake --install build +``` + +Set `CMAKE_INSTALL_PREFIX` to control the destination directory. + +--- + +## 3. Troubleshooting + +| Symptom | Possible Fix | +|---------|--------------| +| *Linker cannot find `stdc++fs`* | Ensure GCC ≥ 8 or Clang ≥ 10 | +| *Undefined reference to `cfsetspeed`* | Make sure `-pthread` is not stripped | +| *`EACCES` when opening `/dev/ttyUSB0`* | Add your user to the `dialout` (Ubuntu) or `uucp` (Arch) group or run via `sudo` | diff --git a/docs/examples.md b/docs/examples.md new file mode 100644 index 0000000..6beccb7 --- /dev/null +++ b/docs/examples.md @@ -0,0 +1,25 @@ +# Deno example scripts + +| Script | Purpose | +|--------|---------| +| `serial_echo.ts` | Minimal echo test: enumerate ports, open the first one and verify that each line sent is echoed back by the MCU. | +| `serial_advanced.ts` | Demonstrates helpers (`serialReadLine`, statistics, peek, `serialDrain`) and prints TX/RX counters. | +| `serial_callbacks.ts` | Shows how to register error / read / write callbacks and prints diagnostics for every transfer. | + +--- + +## Running an example + +```bash +deno run --allow-ffi --allow-read examples/