diff --git a/.clang-format b/.clang-format index 0742409328..92b40492f0 100644 --- a/.clang-format +++ b/.clang-format @@ -1,89 +1,107 @@ ---- -Language: Cpp -BasedOnStyle: Google -AccessModifierOffset: -1 -AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: false -AlignEscapedNewlinesLeft: true -AlignOperands: true -AlignTrailingComments: true -AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: false -AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: All -AllowShortIfStatementsOnASingleLine: true -AllowShortLoopsOnASingleLine: true -AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: true -AlwaysBreakTemplateDeclarations: true -BinPackArguments: true -BinPackParameters: true -BraceWrapping: - AfterClass: false - AfterControlStatement: false - AfterEnum: false - AfterFunction: false - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - BeforeCatch: false - BeforeElse: false - IndentBraces: false -BreakBeforeBinaryOperators: None -BreakBeforeBraces: Attach -BreakBeforeTernaryOperators: true -BreakConstructorInitializersBeforeComma: false -ColumnLimit: 80 -CommentPragmas: '^ IWYU pragma:' -ConstructorInitializerAllOnOneLineOrOnePerLine: true -ConstructorInitializerIndentWidth: 4 -ContinuationIndentWidth: 4 -Cpp11BracedListStyle: true -DerivePointerAlignment: false -DisableFormat: false -ExperimentalAutoDetectBinPacking: false -ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] -IncludeCategories: - - Regex: '^<.*\.h>' - Priority: 1 - - Regex: '^<.*' - Priority: 2 - - Regex: '.*' - Priority: 3 -IndentCaseLabels: true -IndentWidth: 2 -IndentWrappedFunctionNames: false -KeepEmptyLinesAtTheStartOfBlocks: false -MacroBlockBegin: '' -MacroBlockEnd: '' -MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None -ObjCBlockIndentWidth: 2 -ObjCSpaceAfterProperty: false -ObjCSpaceBeforeProtocolList: false -PenaltyBreakBeforeFirstCallParameter: 1 -PenaltyBreakComment: 300 -PenaltyBreakFirstLessLess: 120 -PenaltyBreakString: 1000 -PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 200 -PointerAlignment: Left -ReflowComments: true -SortIncludes: true -SpaceAfterCStyleCast: false -SpaceBeforeAssignmentOperators: true -SpaceBeforeParens: ControlStatements -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 2 -SpacesInAngles: false -SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false -SpacesInSquareBrackets: false -Standard: Auto -TabWidth: 8 -UseTab: Never -... +--- +Language: Cpp +BasedOnStyle: Google +AccessModifierOffset: -1 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Left +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: true +AllowShortLoopsOnASingleLine: true +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: true +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeCategories: + - Regex: '^<.*\.h>' + Priority: 1 + - Regex: '^<.*' + Priority: 2 + - Regex: '.*' + Priority: 3 +IncludeIsMainRegex: '([-_](test|unittest))?$' +IndentCaseLabels: true +IndentWidth: 2 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: false +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left +ReflowComments: true +SortIncludes: false +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto +TabWidth: 8 +UseTab: Never +... diff --git a/.styleguide b/.styleguide new file mode 100644 index 0000000000..f40ca704df --- /dev/null +++ b/.styleguide @@ -0,0 +1,35 @@ +cppHeaderFileInclude { + \.h$ + \.inc$ +} + +cppSrcFileInclude { + \.cpp$ +} + +generatedFileExclude { + gmock/ + llvm/ + src/main/native/cpp/support/json + src/main/native/include/support/json + src/test/native/cpp/json/ +} + +licenseUpdateExclude { + src/main/native/cpp/support/Base64\.cpp$ + src/main/native/cpp/support/sha1\.cpp$ + src/main/native/cpp/tcpsockets/TCPAcceptor\.cpp$ + src/main/native/cpp/tcpsockets/TCPConnector\.cpp$ + src/main/native/cpp/tcpsockets/TCPStream\.cpp$ + src/main/native/include/support/ConcurrentQueue\.h$ + src/main/native/include/support/sha1\.h$ + src/main/native/include/tcpsockets/TCPAcceptor\.h$ + src/main/native/include/tcpsockets/TCPConnector\.h$ + src/main/native/include/tcpsockets/TCPStream\.h$ +} + +includeGuardRoots { + src/main/native/cpp/ + src/main/native/include/ + src/test/native/cpp/ +} diff --git a/.styleguide-license b/.styleguide-license new file mode 100644 index 0000000000..b8023700ce --- /dev/null +++ b/.styleguide-license @@ -0,0 +1,6 @@ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) {year} FIRST. All Rights Reserved.{padding}*/ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ diff --git a/.travis-scripts/install.sh b/.travis-scripts/install.sh index 75d95ced3b..7f4773b23b 100755 --- a/.travis-scripts/install.sh +++ b/.travis-scripts/install.sh @@ -2,7 +2,21 @@ if [[ $TRAVIS_OS_NAME != 'osx' ]]; then # Install custom requirements on Linux + sudo sh -c 'echo "deb http://apt.llvm.org/trusty/ llvm-toolchain-trusty-5.0 main" > /etc/apt/sources.list.d/llvm.list' + wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key|sudo apt-key add - sudo add-apt-repository ppa:wpilib/toolchain -y sudo apt-get update -q - sudo apt-get install frc-toolchain -y + sudo apt-get install clang-format-5.0 frc-toolchain -y + + wget https://bootstrap.pypa.io/get-pip.py + sudo python3.5 get-pip.py + python3.5 -m pip install --user wpiformat +else + echo PATH=$PATH + brew update + brew install python3 clang-format + clang-format --version + echo PATH=$PATH + + pip3 install --user wpiformat fi diff --git a/.travis-scripts/wpiformat.sh b/.travis-scripts/wpiformat.sh new file mode 100755 index 0000000000..fc6e646dbf --- /dev/null +++ b/.travis-scripts/wpiformat.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +if [[ $TRAVIS_OS_NAME != 'osx' ]]; then + python3.5 -m wpiformat -y 2017 -clang 5.0 +else + python3 -m wpiformat -y 2017 +fi + +git --no-pager diff --exit-code HEAD # Ensure formatter made no changes diff --git a/.travis.yml b/.travis.yml index 8290b37708..346230cefc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,4 @@ +sudo: true language: java matrix: @@ -10,9 +11,12 @@ matrix: addons: apt: + sources: + - deadsnakes packages: - g++-multilib - lib32stdc++6 + - python3.5 before_install: - .travis-scripts/install.sh @@ -21,6 +25,7 @@ install: - ./gradlew assemble -PbuildAll script: + - .travis-scripts/wpiformat.sh - ./gradlew build -PbuildAll before_cache: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 911951bd59..fc2203cb3f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,53 +1,53 @@ -# Contributing to wpiutil - -So you want to contribute your changes back to ntcore. Great! We have a few contributing rules that will help you make sure your changes will be accepted into the project. Please remember to follow the rules written here, and behave with Gracious Professionalism. - -- [General Contribution Rules](#general-contribution-rules) -- [What to Contribute](#what-to-contribute) -- [Coding Guidelines](#coding-guidelines) -- [Submitting Changes](#submitting-changes) - - [Pull Request Format](#pull-request-format) - - [Merge Process](#merge-process) -- [Licensing](#licensing) - -## General Contribution Rules - -- Everything in the library must work for the 3000+ teams that will be using it. -- We need to be able to maintain submitted changes, even if you are no longer working on the project. -- Excluding bug fixes, changes in one language generally need to have corresponding changes in other languages. - - Substantial changes often need to have corresponding LabVIEW changes. To do this, we will work with NI on these large changes. - - Protocol changes must be carefully considered. Please open issues for protocol enhancements so we can discuss first. -- Changes should have tests. -- Code should be well documented. - - This often involves ScreenSteps. To add content to ScreenSteps, we will work with you to get the appropriate articles written. - -## What to Contribute - -- Bug reports and fixes - - We will generally accept bug fixes without too much question. If they are only implemented for one language, we will implement them for any other necessary languages. Bug reports are also welcome, please submit them to our GitHub issue tracker. -- While we do welcome improvements to the API, there are a few important rules to consider: - - Features must be added to both the C++ API and the Java API, with rare exceptions. - - During competition season, we will not merge any new feature additions. We want to ensure that the API is stable during the season to help minimize issues for teams. - - Ask about large changes before spending a bunch of time on them! You can create a new issue on our GitHub tracker for feature request/discussion and talk about it with us there. - - Features that make it easier for teams with less experience to be more successful are more likely to be accepted. - - Features in ntcore should be broadly applicable to all teams. Anything that is team specific should not be submitted. - -## Coding Guidelines - -ntcore uses Google style guides for both C++ and Java. Autoformatters are available for many popular editors at [https://github.com/google/styleguide]. An online version of the styleguide for [C++](https://google.github.io/styleguide/cppguide.html) and [Java](https://google.github.io/styleguide/javaguide.html) are also available. Additionally, offline copies of the style guide can be found in the style guide directory of the repository. - -While the library should be fully formatted according to the styles, additional elements of the style guide were not followed when the library was initially created. All new code should follow the guidelines. If you are looking for some easy ramp-up tasks, finding areas that don't follow the style guide and fixing them is very welcome. - -## Submitting Changes - -### Pull Request Format - -Changes should be submitted as a Pull Request against the master branch of ntcore. For most changes, we ask that you squash your changes down to a single commit. For particularly large changes, multiple commits are ok, but assume one commit unless asked otherwise. No change will be merged unless it is up to date with the current master. We will also not merge any changes with merge commits in them; please rebase off of master before submitting a pull request. We do this to make sure that the git history isn't too cluttered. - -### Merge Process - -When you first submit changes, Travis-CI will attempt to run `./gradlew check` on your change. If this fails, you will need to fix any issues that it sees. Once Travis passes, we will begin the review process in more earnest. One or more WPILib team members will review your change. This will be a back-and-forth process with the WPILib team and the greater community. Once we are satisfied that your change is ready, we will allow our Jenkins instance to test it. This will run the full gamut of checks, including integration tests on actual hardware. Once all tests have passed and the team is satisfied, we will merge your change into the WPILib repository. - -## Licensing - -By contributing to ntcore, you agree that your code will be distributed with ntcore, and licensed under the license for the ntcore project. You should not contribute code that you do not have permission to relicense in this manner. This includes code that is licensed under the GPL that you do not have permission to relicense, as ntcore is not released under a copyleft license. Our license is the 3-clause BSD license, which you can find [here](license.txt). \ No newline at end of file +# Contributing to wpiutil + +So you want to contribute your changes back to ntcore. Great! We have a few contributing rules that will help you make sure your changes will be accepted into the project. Please remember to follow the rules written here, and behave with Gracious Professionalism. + +- [General Contribution Rules](#general-contribution-rules) +- [What to Contribute](#what-to-contribute) +- [Coding Guidelines](#coding-guidelines) +- [Submitting Changes](#submitting-changes) + - [Pull Request Format](#pull-request-format) + - [Merge Process](#merge-process) +- [Licensing](#licensing) + +## General Contribution Rules + +- Everything in the library must work for the 3000+ teams that will be using it. +- We need to be able to maintain submitted changes, even if you are no longer working on the project. +- Excluding bug fixes, changes in one language generally need to have corresponding changes in other languages. + - Substantial changes often need to have corresponding LabVIEW changes. To do this, we will work with NI on these large changes. + - Protocol changes must be carefully considered. Please open issues for protocol enhancements so we can discuss first. +- Changes should have tests. +- Code should be well documented. + - This often involves ScreenSteps. To add content to ScreenSteps, we will work with you to get the appropriate articles written. + +## What to Contribute + +- Bug reports and fixes + - We will generally accept bug fixes without too much question. If they are only implemented for one language, we will implement them for any other necessary languages. Bug reports are also welcome, please submit them to our GitHub issue tracker. +- While we do welcome improvements to the API, there are a few important rules to consider: + - Features must be added to both the C++ API and the Java API, with rare exceptions. + - During competition season, we will not merge any new feature additions. We want to ensure that the API is stable during the season to help minimize issues for teams. + - Ask about large changes before spending a bunch of time on them! You can create a new issue on our GitHub tracker for feature request/discussion and talk about it with us there. + - Features that make it easier for teams with less experience to be more successful are more likely to be accepted. + - Features in ntcore should be broadly applicable to all teams. Anything that is team specific should not be submitted. + +## Coding Guidelines + +ntcore uses Google style guides for both C++ and Java. Autoformatters are available for many popular editors at [https://github.com/google/styleguide]. An online version of the styleguide for [C++](https://google.github.io/styleguide/cppguide.html) and [Java](https://google.github.io/styleguide/javaguide.html) are also available. Additionally, offline copies of the style guide can be found in the style guide directory of the repository. + +While the library should be fully formatted according to the styles, additional elements of the style guide were not followed when the library was initially created. All new code should follow the guidelines. If you are looking for some easy ramp-up tasks, finding areas that don't follow the style guide and fixing them is very welcome. + +## Submitting Changes + +### Pull Request Format + +Changes should be submitted as a Pull Request against the master branch of ntcore. For most changes, we ask that you squash your changes down to a single commit. For particularly large changes, multiple commits are ok, but assume one commit unless asked otherwise. No change will be merged unless it is up to date with the current master. We will also not merge any changes with merge commits in them; please rebase off of master before submitting a pull request. We do this to make sure that the git history isn't too cluttered. + +### Merge Process + +When you first submit changes, Travis-CI will attempt to run `./gradlew check` on your change. If this fails, you will need to fix any issues that it sees. Once Travis passes, we will begin the review process in more earnest. One or more WPILib team members will review your change. This will be a back-and-forth process with the WPILib team and the greater community. Once we are satisfied that your change is ready, we will allow our Jenkins instance to test it. This will run the full gamut of checks, including integration tests on actual hardware. Once all tests have passed and the team is satisfied, we will merge your change into the WPILib repository. + +## Licensing + +By contributing to ntcore, you agree that your code will be distributed with ntcore, and licensed under the license for the ntcore project. You should not contribute code that you do not have permission to relicense in this manner. This includes code that is licensed under the GPL that you do not have permission to relicense, as ntcore is not released under a copyleft license. Our license is the 3-clause BSD license, which you can find [here](license.txt). diff --git a/publish.gradle b/publish.gradle index 82e6353595..6e58025ca4 100644 --- a/publish.gradle +++ b/publish.gradle @@ -1,221 +1,221 @@ -apply plugin: 'maven-publish' -apply plugin: 'edu.wpi.first.wpilib.versioning.WPILibVersioningPlugin' - -def getVersion = { - if (WPILibVersion.version.contains('-')) - return WPILibVersion.version.substring(WPILibVersion.version.indexOf('-')) - else - return "" -} - -if (!hasProperty('releaseType')) { - WPILibVersion { - releaseType = 'dev' - } -} - -def pubVersion -if (project.hasProperty("publishVersion")) { - pubVersion = project.publishVersion -} else { - pubVersion = WPILibVersion.version -} - -def outputsFolder = file("$buildDir/outputs") - -def versionFile = file("$outputsFolder/version.txt") - -task outputVersions() { - description = 'Prints the versions of wpiutil to a file for use by the downstream packaging project' - group = 'Build' - outputs.files(versionFile) - - doFirst { - outputsFolder.mkdir() - } - - doLast { - versionFile.write pubVersion - } -} - -build.dependsOn outputVersions - -def baseArtifactId = 'wpiutil' -def artifactGroupId = 'edu.wpi.first.wpiutil' - -def licenseFile = file("$rootDir/license.txt") - -task cppSourcesZip(type: Zip) { - destinationDir = outputsFolder - classifier = "sources" - - from(licenseFile) { - into '/' - } - - from('src/main/native/cpp') { - into '/' - } -} - -task cppHeadersZip(type: Zip) { - destinationDir = outputsFolder - classifier = "headers" - - from(licenseFile) { - into '/' - } - - from('src/main/native/include') { - into '/' - } -} - -task sourcesJar(type: Jar, dependsOn: classes) { - classifier = 'sources' - from sourceSets.main.allSource -} - -task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from javadoc.destinationDir -} - -if (project.hasProperty('jenkinsBuild')) { - jar { - classifier = 'javaArtifact' - } -} - -artifacts { - archives sourcesJar - archives javadocJar - archives cppHeadersZip - archives cppSourcesZip - outputVersions.outputs.files.each { - archives it - } -} - -def createComponentZipTasks = { components, name, base, type, project, func -> - def configMap = [:] - components.each { - if (it in NativeLibrarySpec && it.name == name) { - it.binaries.each { - def target = getClassifier(it) - if (configMap.containsKey(target)) { - configMap.get(target).add(it) - } else { - configMap.put(target, []) - configMap.get(target).add(it) - } - } - } - } - def taskList = [] - configMap.each { key, value -> - def baseN = base + name - def task = project.tasks.create(baseN + "-${key}", type) { - description = 'Creates component archive for platform ' + key - destinationDir = outputsFolder - classifier = key - baseName = baseN + '-classifier' - duplicatesStrategy = 'exclude' - - from(licenseFile) { - into '/' - } - - func(it, value) - } - taskList.add(task) - - project.build.dependsOn task - - project.artifacts { - archives task - } - } - return taskList -} - -model { - publishing { - def wpiutilTaskList = createComponentZipTasks($.components, 'wpiutil', 'zipcppwpiutil', Zip, project, { task, value -> - value.each { binary-> - if (binary.buildable) { - if (binary instanceof SharedLibraryBinarySpec) { - task.dependsOn binary.buildTask - task.from(new File(binary.sharedLibraryFile.absolutePath + ".debug")) { - into getPlatformPath(binary) + '/shared' - } - task.from (binary.sharedLibraryFile) { - into getPlatformPath(binary) + '/shared' - } - task.from (binary.sharedLibraryLinkFile) { - into getPlatformPath(binary) + '/shared' - } - } else if (binary instanceof StaticLibraryBinarySpec) { - task.dependsOn binary.buildTask - task.from (binary.staticLibraryFile) { - into getPlatformPath(binary) + '/static' - } - } - } - } - }) - - def allCppTask - if (!project.hasProperty('jenkinsBuild')) { - allCppTask = project.tasks.create("wpiutilAllZip", Zip) { - description = 'Creates a zip with all Cpp artifacts' - classifier = 'all' - baseName = 'zipcppwpiutilwpiutil' - destinationDir = outputsFolder - duplicatesStrategy = 'exclude' - - wpiutilTaskList.each { - it.outputs.files.each { - from project.zipTree(it) - } - dependsOn it - } - } - project.build.dependsOn allCppTask - } - - publications { - cpp(MavenPublication) { - wpiutilTaskList.each { - artifact it - } - artifact cppHeadersZip - artifact cppSourcesZip - - if (!project.hasProperty('jenkinsBuild')) { - artifact allCppTask - } - - artifactId = "${baseArtifactId}-cpp" - groupId artifactGroupId - version pubVersion - } - } - } -} - -publishing { - publications { - - java(MavenPublication) { - artifact jar - artifact sourcesJar - artifact javadocJar - - artifactId = "${baseArtifactId}-java" - groupId artifactGroupId - version pubVersion - } - } -} +apply plugin: 'maven-publish' +apply plugin: 'edu.wpi.first.wpilib.versioning.WPILibVersioningPlugin' + +def getVersion = { + if (WPILibVersion.version.contains('-')) + return WPILibVersion.version.substring(WPILibVersion.version.indexOf('-')) + else + return "" +} + +if (!hasProperty('releaseType')) { + WPILibVersion { + releaseType = 'dev' + } +} + +def pubVersion +if (project.hasProperty("publishVersion")) { + pubVersion = project.publishVersion +} else { + pubVersion = WPILibVersion.version +} + +def outputsFolder = file("$buildDir/outputs") + +def versionFile = file("$outputsFolder/version.txt") + +task outputVersions() { + description = 'Prints the versions of wpiutil to a file for use by the downstream packaging project' + group = 'Build' + outputs.files(versionFile) + + doFirst { + outputsFolder.mkdir() + } + + doLast { + versionFile.write pubVersion + } +} + +build.dependsOn outputVersions + +def baseArtifactId = 'wpiutil' +def artifactGroupId = 'edu.wpi.first.wpiutil' + +def licenseFile = file("$rootDir/license.txt") + +task cppSourcesZip(type: Zip) { + destinationDir = outputsFolder + classifier = "sources" + + from(licenseFile) { + into '/' + } + + from('src/main/native/cpp') { + into '/' + } +} + +task cppHeadersZip(type: Zip) { + destinationDir = outputsFolder + classifier = "headers" + + from(licenseFile) { + into '/' + } + + from('src/main/native/include') { + into '/' + } +} + +task sourcesJar(type: Jar, dependsOn: classes) { + classifier = 'sources' + from sourceSets.main.allSource +} + +task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from javadoc.destinationDir +} + +if (project.hasProperty('jenkinsBuild')) { + jar { + classifier = 'javaArtifact' + } +} + +artifacts { + archives sourcesJar + archives javadocJar + archives cppHeadersZip + archives cppSourcesZip + outputVersions.outputs.files.each { + archives it + } +} + +def createComponentZipTasks = { components, name, base, type, project, func -> + def configMap = [:] + components.each { + if (it in NativeLibrarySpec && it.name == name) { + it.binaries.each { + def target = getClassifier(it) + if (configMap.containsKey(target)) { + configMap.get(target).add(it) + } else { + configMap.put(target, []) + configMap.get(target).add(it) + } + } + } + } + def taskList = [] + configMap.each { key, value -> + def baseN = base + name + def task = project.tasks.create(baseN + "-${key}", type) { + description = 'Creates component archive for platform ' + key + destinationDir = outputsFolder + classifier = key + baseName = baseN + '-classifier' + duplicatesStrategy = 'exclude' + + from(licenseFile) { + into '/' + } + + func(it, value) + } + taskList.add(task) + + project.build.dependsOn task + + project.artifacts { + archives task + } + } + return taskList +} + +model { + publishing { + def wpiutilTaskList = createComponentZipTasks($.components, 'wpiutil', 'zipcppwpiutil', Zip, project, { task, value -> + value.each { binary-> + if (binary.buildable) { + if (binary instanceof SharedLibraryBinarySpec) { + task.dependsOn binary.buildTask + task.from(new File(binary.sharedLibraryFile.absolutePath + ".debug")) { + into getPlatformPath(binary) + '/shared' + } + task.from (binary.sharedLibraryFile) { + into getPlatformPath(binary) + '/shared' + } + task.from (binary.sharedLibraryLinkFile) { + into getPlatformPath(binary) + '/shared' + } + } else if (binary instanceof StaticLibraryBinarySpec) { + task.dependsOn binary.buildTask + task.from (binary.staticLibraryFile) { + into getPlatformPath(binary) + '/static' + } + } + } + } + }) + + def allCppTask + if (!project.hasProperty('jenkinsBuild')) { + allCppTask = project.tasks.create("wpiutilAllZip", Zip) { + description = 'Creates a zip with all Cpp artifacts' + classifier = 'all' + baseName = 'zipcppwpiutilwpiutil' + destinationDir = outputsFolder + duplicatesStrategy = 'exclude' + + wpiutilTaskList.each { + it.outputs.files.each { + from project.zipTree(it) + } + dependsOn it + } + } + project.build.dependsOn allCppTask + } + + publications { + cpp(MavenPublication) { + wpiutilTaskList.each { + artifact it + } + artifact cppHeadersZip + artifact cppSourcesZip + + if (!project.hasProperty('jenkinsBuild')) { + artifact allCppTask + } + + artifactId = "${baseArtifactId}-cpp" + groupId artifactGroupId + version pubVersion + } + } + } +} + +publishing { + publications { + + java(MavenPublication) { + artifact jar + artifact sourcesJar + artifact javadocJar + + artifactId = "${baseArtifactId}-java" + groupId artifactGroupId + version pubVersion + } + } +} diff --git a/readme.md b/readme.md index 10d3941d95..def70be570 100644 --- a/readme.md +++ b/readme.md @@ -1,73 +1,72 @@ -# wpiutil - -wpiutil is a utility library designed for making C++ interfacing easier. - -## Build Requirements -To build wpiutil, a few requirements must be met: - -- Platform Native Toolchain - You must have a toolchain for your native platform installed if you wish to build wpiutil for your machine. On Windows, this is Visual Studio. On Mac, this is Clang, and on Linux, this is GCC. Your toolchain must support the `-std=c++11` language flag. -- Platform Native JDK - In order to compile wpiutil your native platform, you must have the JDK for your platform installed, so that the correct JNI headers can be included. -- ARM Toolchain - To crosscompile wpiutil for the roboRIO, you must have the FRC ARM toolchain installed, which can be found [here](http://first.wpi.edu/FRC/roborio/toolchains/). -- Cross Toolchains (coming soon) - -## Building -Gradle is the main build system used by wpiutil. All tasks are run with the `gradlew` wrapper, which is included in the root of the repository. All targets that can be accomplished by Gradle are referred to as tasks. The main task available is `build`. To run Gradle, cd into the build directory and run: - -```bash -./gradlew build -``` - -This will build the roboRIO wpiutil library, in addition to the library for your native platform. Note if the roboRIO compiler cannot be found, the build will skip the roboRIO build. To build for either only the roboRIO, or every platform except the roboRIO, use the following flags: - -```bash --PskipAthena --PonlyAthena -``` - -Note if you choose the `onlyAthena` flag, tests will not be ran, as they depend on the current platform being built. - -In addition, more platforms can be built. For instance, with additional cross compilers more Arm binaries can be built. In addition, the second bitness for your current platform can be built with an additional flag. To enable every possible platform, use the following flag. - -```bash --PbuildAll -``` - -If you are building the native version on a 64 bit Linux computer, use a GCC installation which has multilib support enabled (it can compile both 32 and 64 bit programs). The package providing that support on most Linux distributions is called `gcc-multilib`. - -By default, debug binaries of the libraries will be built. To switch to instead build release binaries, use the following flag - -```bash --PreleaseBuild -``` - -### Custom Cross Compilers -Coming soon - -### Testing -By default, tests will be built for any native platform, and will be run during any execution of the `build` or `publish` tasks. To skip building and running the tests, use the `-PskipAllTests` command line flag. - -### Publishing -to use wpiutil in downstream projects as a Maven-style dependency, use the `publish` command. This will publish the following artifact id's: - -- edu.wpi.first.wpiutil:wpiutil-cpp -- edu.wpi.first.wpiutil:wpiutil-java - -The `wpiutil-cpp` artifact will contain the following 2 classifiers: - -- `headers` (contains C++ headers) -- `sources` (contains C++ sources) - -In addition, a classifier will be created for each binary built by the current build. The internal layout of the artifacts will be as follows. - -- `/os/arch/shared/` (shared binaries located here) -- `/os/arch/static/` (static binaries located here) - -The `wpiutil-java` artifact will contain a jar with no classifiers. This is the java jar file. In addition, the following 2 classifiers will be contained - -- `sources` (contains Java sources) -- `javadoc` (contains Javadoc sources) - -All of these artifacts by default are published to `~/releases/maven/development`. To switch to the release repository (`~/release/maven/release`), use the flag `-PreleaseType=OFFICIAL`. - -All downstream projects are configured to use the individual classifier artifacts. The previouse `desktop` classifier does not exist anymore. - +# wpiutil + +wpiutil is a utility library designed for making C++ interfacing easier. + +## Build Requirements +To build wpiutil, a few requirements must be met: + +- Platform Native Toolchain - You must have a toolchain for your native platform installed if you wish to build wpiutil for your machine. On Windows, this is Visual Studio. On Mac, this is Clang, and on Linux, this is GCC. Your toolchain must support the `-std=c++11` language flag. +- Platform Native JDK - In order to compile wpiutil your native platform, you must have the JDK for your platform installed, so that the correct JNI headers can be included. +- ARM Toolchain - To crosscompile wpiutil for the roboRIO, you must have the FRC ARM toolchain installed, which can be found [here](http://first.wpi.edu/FRC/roborio/toolchains/). +- Cross Toolchains (coming soon) + +## Building +Gradle is the main build system used by wpiutil. All tasks are run with the `gradlew` wrapper, which is included in the root of the repository. All targets that can be accomplished by Gradle are referred to as tasks. The main task available is `build`. To run Gradle, cd into the build directory and run: + +```bash +./gradlew build +``` + +This will build the roboRIO wpiutil library, in addition to the library for your native platform. Note if the roboRIO compiler cannot be found, the build will skip the roboRIO build. To build for either only the roboRIO, or every platform except the roboRIO, use the following flags: + +```bash +-PskipAthena +-PonlyAthena +``` + +Note if you choose the `onlyAthena` flag, tests will not be ran, as they depend on the current platform being built. + +In addition, more platforms can be built. For instance, with additional cross compilers more Arm binaries can be built. In addition, the second bitness for your current platform can be built with an additional flag. To enable every possible platform, use the following flag. + +```bash +-PbuildAll +``` + +If you are building the native version on a 64 bit Linux computer, use a GCC installation which has multilib support enabled (it can compile both 32 and 64 bit programs). The package providing that support on most Linux distributions is called `gcc-multilib`. + +By default, debug binaries of the libraries will be built. To switch to instead build release binaries, use the following flag + +```bash +-PreleaseBuild +``` + +### Custom Cross Compilers +Coming soon + +### Testing +By default, tests will be built for any native platform, and will be run during any execution of the `build` or `publish` tasks. To skip building and running the tests, use the `-PskipAllTests` command line flag. + +### Publishing +to use wpiutil in downstream projects as a Maven-style dependency, use the `publish` command. This will publish the following artifact id's: + +- edu.wpi.first.wpiutil:wpiutil-cpp +- edu.wpi.first.wpiutil:wpiutil-java + +The `wpiutil-cpp` artifact will contain the following 2 classifiers: + +- `headers` (contains C++ headers) +- `sources` (contains C++ sources) + +In addition, a classifier will be created for each binary built by the current build. The internal layout of the artifacts will be as follows. + +- `/os/arch/shared/` (shared binaries located here) +- `/os/arch/static/` (static binaries located here) + +The `wpiutil-java` artifact will contain a jar with no classifiers. This is the java jar file. In addition, the following 2 classifiers will be contained + +- `sources` (contains Java sources) +- `javadoc` (contains Javadoc sources) + +All of these artifacts by default are published to `~/releases/maven/development`. To switch to the release repository (`~/release/maven/release`), use the flag `-PreleaseType=OFFICIAL`. + +All downstream projects are configured to use the individual classifier artifacts. The previouse `desktop` classifier does not exist anymore. diff --git a/src/dev/java/edu/wpi/first/wpiutil/DevMain.java b/src/dev/java/edu/wpi/first/wpiutil/DevMain.java index b1e99970d2..74db5398c6 100644 --- a/src/dev/java/edu/wpi/first/wpiutil/DevMain.java +++ b/src/dev/java/edu/wpi/first/wpiutil/DevMain.java @@ -1,8 +1,15 @@ -package edu.wpi.first.wpiutil; - -public class DevMain { - public static void main(String[] args) { - System.out.println("Hello World!"); - System.out.println(RuntimeDetector.getPlatformPath()); - } -} +/*----------------------------------------------------------------------------*/ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ + +package edu.wpi.first.wpiutil; + +public class DevMain { + public static void main(String[] args) { + System.out.println("Hello World!"); + System.out.println(RuntimeDetector.getPlatformPath()); + } +} diff --git a/src/dev/native/cpp/main.cpp b/src/dev/native/cpp/main.cpp index 41b2126618..8285cc3ebc 100644 --- a/src/dev/native/cpp/main.cpp +++ b/src/dev/native/cpp/main.cpp @@ -1,10 +1,17 @@ -#include "llvm/StringRef.h" -#include "llvm/SmallVector.h" -#include - -#include "support/hostname.h" - -int main() { - llvm::StringRef v1("Hello"); - std::cout << v1.lower() << std::endl; -} +/*----------------------------------------------------------------------------*/ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ + +#include + +#include "llvm/SmallVector.h" +#include "llvm/StringRef.h" +#include "support/hostname.h" + +int main() { + llvm::StringRef v1("Hello"); + std::cout << v1.lower() << std::endl; +} diff --git a/src/main/java/edu/wpi/first/wpiutil/RuntimeDetector.java b/src/main/java/edu/wpi/first/wpiutil/RuntimeDetector.java index e7b39680c6..5473ca11d8 100644 --- a/src/main/java/edu/wpi/first/wpiutil/RuntimeDetector.java +++ b/src/main/java/edu/wpi/first/wpiutil/RuntimeDetector.java @@ -1,105 +1,112 @@ -package edu.wpi.first.wpiutil; - -import java.io.File; -import java.io.IOException; -import java.io.BufferedReader; -import java.io.InputStreamReader; - -public class RuntimeDetector { - private static String filePrefix; - private static String fileExtension; - private static String filePath; - - private static synchronized void computePlatform() { - if (fileExtension != null && filePath != null && filePrefix != null) { - return; - } - - - boolean intel32 = is32BitIntel(); - boolean intel64 = is64BitIntel(); - - if (isWindows()) { - filePrefix = ""; - fileExtension = ".dll"; - if (intel32) { - filePath = "/windows/x86/"; - } else { - filePath = "/windows/x86-64/"; - } - } else if (isMac()) { - filePrefix = "lib"; - fileExtension = ".dylib"; - if (intel32) { - filePath = "/osx/x86"; - } else { - filePath = "/osx/x86-64/"; - } - } else if (isLinux()) { - filePrefix = "lib"; - fileExtension = ".so"; - if (intel32) { - filePath = "/linux/x86/"; - } else if (intel64) { - filePath = "/linux/x86-64/"; - } else if (isAthena()) { - filePath = "/linux/athena/"; - } else { - filePath = "/linux/nativearm/"; - } - } else { - throw new RuntimeException("Failed to determine OS"); - } - } - - public static synchronized String getFilePrefix() { - computePlatform(); - - return filePrefix; - } - - public static synchronized String getFileExtension() { - computePlatform(); - - return fileExtension; - } - - public static synchronized String getPlatformPath() { - computePlatform(); - - return filePath; - } - - public static synchronized String getLibraryResource(String libName) { - computePlatform(); - - return filePath + filePrefix + libName + fileExtension; - } - - public static boolean isAthena() { - File runRobotFile = new File("/usr/local/frc/bin/frcRunRobot.sh"); - return runRobotFile.exists(); - } - - public static boolean isLinux() { - return System.getProperty("os.name").startsWith("Linux"); - } - - public static boolean isWindows() { - return System.getProperty("os.name").startsWith("Windows"); - } - - public static boolean isMac() { - return System.getProperty("os.name").startsWith("Mac"); - } - - public static boolean is32BitIntel() { - String arch = System.getProperty("os.arch"); - return arch.equals("x86") || arch.equals("i386"); - } - - public static boolean is64BitIntel() { - String arch = System.getProperty("os.arch"); - return arch.equals("amd64") || arch.equals("x86_64"); - } -} +/*----------------------------------------------------------------------------*/ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ + +package edu.wpi.first.wpiutil; + +import java.io.File; +import java.io.IOException; +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class RuntimeDetector { + private static String filePrefix; + private static String fileExtension; + private static String filePath; + + private static synchronized void computePlatform() { + if (fileExtension != null && filePath != null && filePrefix != null) { + return; + } + + + boolean intel32 = is32BitIntel(); + boolean intel64 = is64BitIntel(); + + if (isWindows()) { + filePrefix = ""; + fileExtension = ".dll"; + if (intel32) { + filePath = "/windows/x86/"; + } else { + filePath = "/windows/x86-64/"; + } + } else if (isMac()) { + filePrefix = "lib"; + fileExtension = ".dylib"; + if (intel32) { + filePath = "/osx/x86"; + } else { + filePath = "/osx/x86-64/"; + } + } else if (isLinux()) { + filePrefix = "lib"; + fileExtension = ".so"; + if (intel32) { + filePath = "/linux/x86/"; + } else if (intel64) { + filePath = "/linux/x86-64/"; + } else if (isAthena()) { + filePath = "/linux/athena/"; + } else { + filePath = "/linux/nativearm/"; + } + } else { + throw new RuntimeException("Failed to determine OS"); + } + } + + public static synchronized String getFilePrefix() { + computePlatform(); + + return filePrefix; + } + + public static synchronized String getFileExtension() { + computePlatform(); + + return fileExtension; + } + + public static synchronized String getPlatformPath() { + computePlatform(); + + return filePath; + } + + public static synchronized String getLibraryResource(String libName) { + computePlatform(); + + return filePath + filePrefix + libName + fileExtension; + } + + public static boolean isAthena() { + File runRobotFile = new File("/usr/local/frc/bin/frcRunRobot.sh"); + return runRobotFile.exists(); + } + + public static boolean isLinux() { + return System.getProperty("os.name").startsWith("Linux"); + } + + public static boolean isWindows() { + return System.getProperty("os.name").startsWith("Windows"); + } + + public static boolean isMac() { + return System.getProperty("os.name").startsWith("Mac"); + } + + public static boolean is32BitIntel() { + String arch = System.getProperty("os.arch"); + return arch.equals("x86") || arch.equals("i386"); + } + + public static boolean is64BitIntel() { + String arch = System.getProperty("os.arch"); + return arch.equals("amd64") || arch.equals("x86_64"); + } +} diff --git a/src/main/native/cpp/support/Base64.cpp b/src/main/native/cpp/support/Base64.cpp index 82f062dd6b..461d752629 100644 --- a/src/main/native/cpp/support/Base64.cpp +++ b/src/main/native/cpp/support/Base64.cpp @@ -1,10 +1,3 @@ -/*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ -/* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ -/*----------------------------------------------------------------------------*/ - /* ==================================================================== * Copyright (c) 1995-1999 The Apache Group. All rights reserved. * @@ -70,34 +63,30 @@ namespace wpi { // aaaack but it's fast and const should make it shared text page. -static const unsigned char pr2six[256] = -{ +static const unsigned char pr2six[256] = { // ASCII table - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, - 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, - 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, - 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 -}; + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 64, 64, 64, 64, 64, 64, 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, + 64, 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64}; -std::size_t Base64Decode(llvm::raw_ostream& os, llvm::StringRef encoded) { - const unsigned char *end = encoded.bytes_begin(); +size_t Base64Decode(llvm::raw_ostream& os, llvm::StringRef encoded) { + const unsigned char* end = encoded.bytes_begin(); while (pr2six[*end] <= 63 && end != encoded.bytes_end()) ++end; - std::size_t nprbytes = end - encoded.bytes_begin(); + size_t nprbytes = end - encoded.bytes_begin(); if (nprbytes == 0) return 0; - const unsigned char *cur = encoded.bytes_begin(); + const unsigned char* cur = encoded.bytes_begin(); while (nprbytes > 4) { os << static_cast(pr2six[cur[0]] << 2 | pr2six[cur[1]] >> 4); @@ -118,15 +107,15 @@ std::size_t Base64Decode(llvm::raw_ostream& os, llvm::StringRef encoded) { return (end - encoded.bytes_begin()) + ((4 - nprbytes) & 3); } -std::size_t Base64Decode(llvm::StringRef encoded, std::string* plain) { +size_t Base64Decode(llvm::StringRef encoded, std::string* plain) { plain->resize(0); llvm::raw_string_ostream os(*plain); - std::size_t rv = Base64Decode(os, encoded); + size_t rv = Base64Decode(os, encoded); os.flush(); return rv; } -llvm::StringRef Base64Decode(llvm::StringRef encoded, std::size_t* num_read, +llvm::StringRef Base64Decode(llvm::StringRef encoded, size_t* num_read, llvm::SmallVectorImpl& buf) { buf.clear(); llvm::raw_svector_ostream os(buf); @@ -139,14 +128,15 @@ static const char basis_64[] = void Base64Encode(llvm::raw_ostream& os, llvm::StringRef plain) { if (plain.empty()) return; - std::size_t len = plain.size(); + size_t len = plain.size(); - std::size_t i; + size_t i; for (i = 0; (i + 2) < len; i += 3) { os << basis_64[(plain[i] >> 2) & 0x3F]; - os << basis_64[((plain[i] & 0x3) << 4) | ((int)(plain[i + 1] & 0xF0) >> 4)]; + os << basis_64[((plain[i] & 0x3) << 4) | + (static_cast(plain[i + 1] & 0xF0) >> 4)]; os << basis_64[((plain[i + 1] & 0xF) << 2) | - ((int)(plain[i + 2] & 0xC0) >> 6)]; + (static_cast(plain[i + 2] & 0xC0) >> 6)]; os << basis_64[plain[i + 2] & 0x3F]; } if (i < len) { @@ -156,7 +146,7 @@ void Base64Encode(llvm::raw_ostream& os, llvm::StringRef plain) { os << '='; } else { os << basis_64[((plain[i] & 0x3) << 4) | - ((int)(plain[i + 1] & 0xF0) >> 4)]; + (static_cast(plain[i + 1] & 0xF0) >> 4)]; os << basis_64[((plain[i + 1] & 0xF) << 2)]; } os << '='; diff --git a/src/main/native/cpp/support/HttpUtil.cpp b/src/main/native/cpp/support/HttpUtil.cpp index 8b84c0b468..83636a3cde 100644 --- a/src/main/native/cpp/support/HttpUtil.cpp +++ b/src/main/native/cpp/support/HttpUtil.cpp @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2016. All Rights Reserved. */ +/* Copyright (c) 2016-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -9,10 +9,10 @@ #include -#include "support/Base64.h" -#include "llvm/raw_ostream.h" #include "llvm/STLExtras.h" #include "llvm/StringExtras.h" +#include "llvm/raw_ostream.h" +#include "support/Base64.h" #include "tcpsockets/TCPConnector.h" namespace wpi { @@ -59,7 +59,7 @@ llvm::StringRef UnescapeURI(const llvm::Twine& str, llvm::StringRef EscapeURI(const llvm::Twine& str, llvm::SmallVectorImpl& buf, bool spacePlus) { - static const char *const hexLut = "0123456789ABCDEF"; + static const char* const hexLut = "0123456789ABCDEF"; llvm::SmallString<128> strBuf; llvm::StringRef strStr = str.toStringRef(strBuf); @@ -158,11 +158,9 @@ bool FindMultipartBoundary(raw_istream& is, llvm::StringRef boundary, // Fast-scan for '-' size_t pos = searchBuf.find('-', searchBuf[0] == '-' ? 1 : 0); if (pos == llvm::StringRef::npos) { - if (saveBuf) - saveBuf->append(searchBuf.data(), searchBuf.size()); + if (saveBuf) saveBuf->append(searchBuf.data(), searchBuf.size()); } else { - if (saveBuf) - saveBuf->append(searchBuf.data(), pos); + if (saveBuf) saveBuf->append(searchBuf.data(), pos); // move '-' and following to start of buffer (next read will fill) std::memmove(searchBuf.data(), searchBuf.data() + pos, diff --git a/src/main/native/cpp/support/hostname.cpp b/src/main/native/cpp/support/hostname.cpp index a6830d9583..662e0700c1 100644 --- a/src/main/native/cpp/support/hostname.cpp +++ b/src/main/native/cpp/support/hostname.cpp @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -15,6 +15,7 @@ #endif #include + #include "llvm/SmallVector.h" #include "llvm/StringRef.h" @@ -27,7 +28,6 @@ struct WSAHelper { } ~WSAHelper() { WSACleanup(); } }; - static WSAHelper& GetWSAHelper() { static WSAHelper helper; return helper; @@ -40,7 +40,8 @@ static bool GetHostnameImpl(char* name, size_t name_len) { GetWSAHelper(); #endif if (::gethostname(name, name_len) != 0) return false; - name[name_len - 1] = '\0'; // Per POSIX, may not be null terminated if too long + name[name_len - 1] = + '\0'; // Per POSIX, may not be null terminated if too long return true; } diff --git a/src/main/native/cpp/support/leb128.cpp b/src/main/native/cpp/support/leb128.cpp index 11605bc3d6..841c8b3f02 100644 --- a/src/main/native/cpp/support/leb128.cpp +++ b/src/main/native/cpp/support/leb128.cpp @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -20,8 +20,8 @@ namespace wpi { * on the encodings refer to section "7.6 - Variable Length Data". Return * the number of bytes required. */ -std::size_t SizeUleb128(unsigned long val) { - std::size_t count = 0; +uint64_t SizeUleb128(uint64_t val) { + size_t count = 0; do { val >>= 7; ++count; @@ -39,8 +39,8 @@ std::size_t SizeUleb128(unsigned long val) { * encodings refer to section "7.6 - Variable Length Data". Return * the number of bytes written. */ -std::size_t WriteUleb128(llvm::SmallVectorImpl& dest, unsigned long val) { - std::size_t count = 0; +uint64_t WriteUleb128(llvm::SmallVectorImpl& dest, uint64_t val) { + size_t count = 0; do { unsigned char byte = val & 0x7f; @@ -66,10 +66,10 @@ std::size_t WriteUleb128(llvm::SmallVectorImpl& dest, unsigned long val) { * encodings refer to section "7.6 - Variable Length Data". Return * the number of bytes read. */ -std::size_t ReadUleb128(const char* addr, unsigned long* ret) { - unsigned long result = 0; +uint64_t ReadUleb128(const char* addr, uint64_t* ret) { + uint32_t result = 0; int shift = 0; - std::size_t count = 0; + size_t count = 0; while (1) { unsigned char byte = *reinterpret_cast(addr); @@ -97,13 +97,13 @@ std::size_t ReadUleb128(const char* addr, unsigned long* ret) { * encodings refer to section "7.6 - Variable Length Data". Return * false on stream error, true on success. */ -bool ReadUleb128(raw_istream& is, unsigned long* ret) { - unsigned long result = 0; +bool ReadUleb128(raw_istream& is, uint64_t* ret) { + uint32_t result = 0; int shift = 0; while (1) { unsigned char byte; - is.read((char*)&byte, 1); + is.read(reinterpret_cast(&byte), 1); if (is.has_error()) return false; result |= (byte & 0x7f) << shift; diff --git a/src/main/native/cpp/support/raw_istream.cpp b/src/main/native/cpp/support/raw_istream.cpp index e0e204a93e..bdb3b9cc7b 100644 --- a/src/main/native/cpp/support/raw_istream.cpp +++ b/src/main/native/cpp/support/raw_istream.cpp @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -7,28 +7,28 @@ #include "support/raw_istream.h" -#include -#include - #ifdef _WIN32 #include #else #include #endif +#include +#include + #include "llvm/FileSystem.h" #include "llvm/SmallVector.h" #include "llvm/StringRef.h" #if defined(_MSC_VER) #ifndef STDIN_FILENO -# define STDIN_FILENO 0 +#define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO -# define STDOUT_FILENO 1 +#define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO -# define STDERR_FILENO 2 +#define STDERR_FILENO 2 #endif #endif @@ -53,9 +53,9 @@ raw_mem_istream::raw_mem_istream(llvm::StringRef mem) void raw_mem_istream::close() {} -std::size_t raw_mem_istream::in_avail() const { return m_left; } +size_t raw_mem_istream::in_avail() const { return m_left; } -void raw_mem_istream::read_impl(void* data, std::size_t len) { +void raw_mem_istream::read_impl(void* data, size_t len) { if (len > m_left) { error_detected(); return; @@ -65,7 +65,7 @@ void raw_mem_istream::read_impl(void* data, std::size_t len) { m_left -= len; } -static int getFD(const llvm::Twine& Filename, std::error_code &EC) { +static int getFD(const llvm::Twine& Filename, std::error_code& EC) { // Handle "-" as stdin. Note that when we do this, we consider ourself // the owner of stdin. This means that we can do things like close the // file descriptor when we're done and set the "binary" flag globally. @@ -77,18 +77,17 @@ static int getFD(const llvm::Twine& Filename, std::error_code &EC) { int FD; EC = llvm::sys::fs::openFileForRead(Filename, FD); - if (EC) - return -1; + if (EC) return -1; EC = std::error_code(); return FD; } raw_fd_istream::raw_fd_istream(const llvm::Twine& filename, std::error_code& ec, - std::size_t bufSize) + size_t bufSize) : raw_fd_istream(getFD(filename, ec), true, bufSize) {} -raw_fd_istream::raw_fd_istream(int fd, bool shouldClose, std::size_t bufSize) +raw_fd_istream::raw_fd_istream(int fd, bool shouldClose, size_t bufSize) : m_bufSize(bufSize), m_fd(fd), m_shouldClose(shouldClose) { m_cur = m_end = m_buf = static_cast(std::malloc(bufSize)); } @@ -105,10 +104,10 @@ void raw_fd_istream::close() { } } -std::size_t raw_fd_istream::in_avail() const { return m_end - m_cur; } +size_t raw_fd_istream::in_avail() const { return m_end - m_cur; } -void raw_fd_istream::read_impl(void* data, std::size_t len) { - std::size_t left = m_end - m_cur; +void raw_fd_istream::read_impl(void* data, size_t len) { + size_t left = m_end - m_cur; if (left < len) { // not enough data if (m_cur == m_end) { diff --git a/src/main/native/cpp/support/raw_socket_istream.cpp b/src/main/native/cpp/support/raw_socket_istream.cpp index 4f27dfb141..7d6e0deae1 100644 --- a/src/main/native/cpp/support/raw_socket_istream.cpp +++ b/src/main/native/cpp/support/raw_socket_istream.cpp @@ -1,23 +1,23 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "support/raw_socket_istream.h" + #include "tcpsockets/NetworkStream.h" using namespace wpi; -void raw_socket_istream::read_impl(void* data, std::size_t len) { +void raw_socket_istream::read_impl(void* data, size_t len) { char* cdata = static_cast(data); - std::size_t pos = 0; + size_t pos = 0; while (pos < len) { NetworkStream::Error err; - std::size_t count = - m_stream.receive(&cdata[pos], len - pos, &err, m_timeout); + size_t count = m_stream.receive(&cdata[pos], len - pos, &err, m_timeout); if (count == 0) { error_detected(); return; @@ -28,4 +28,4 @@ void raw_socket_istream::read_impl(void* data, std::size_t len) { void raw_socket_istream::close() { m_stream.close(); } -std::size_t raw_socket_istream::in_avail() const { return 0; } +size_t raw_socket_istream::in_avail() const { return 0; } diff --git a/src/main/native/cpp/support/raw_socket_ostream.cpp b/src/main/native/cpp/support/raw_socket_ostream.cpp index 67bcd8c035..c0f520ed15 100644 --- a/src/main/native/cpp/support/raw_socket_ostream.cpp +++ b/src/main/native/cpp/support/raw_socket_ostream.cpp @@ -1,11 +1,12 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "support/raw_socket_ostream.h" + #include "tcpsockets/NetworkStream.h" using namespace wpi; @@ -15,13 +16,12 @@ raw_socket_ostream::~raw_socket_ostream() { if (m_shouldClose) close(); } -void raw_socket_ostream::write_impl(const char* data, std::size_t len) { - std::size_t pos = 0; +void raw_socket_ostream::write_impl(const char* data, size_t len) { + size_t pos = 0; while (pos < len) { NetworkStream::Error err; - std::size_t count = - m_stream.send(&data[pos], len - pos, &err); + size_t count = m_stream.send(&data[pos], len - pos, &err); if (count == 0) { error_detected(); return; diff --git a/src/main/native/cpp/support/sha1.cpp b/src/main/native/cpp/support/sha1.cpp index 4154f43fc2..3de313b056 100644 --- a/src/main/native/cpp/support/sha1.cpp +++ b/src/main/native/cpp/support/sha1.cpp @@ -26,305 +26,276 @@ using namespace wpi; -static const size_t BLOCK_INTS = 16; /* number of 32bit integers per SHA1 block */ +static const size_t BLOCK_INTS = + 16; /* number of 32bit integers per SHA1 block */ static const size_t BLOCK_BYTES = BLOCK_INTS * 4; +static void reset(uint32_t digest[], size_t& buf_size, uint64_t& transforms) { + /* SHA1 initialization constants */ + digest[0] = 0x67452301; + digest[1] = 0xefcdab89; + digest[2] = 0x98badcfe; + digest[3] = 0x10325476; + digest[4] = 0xc3d2e1f0; -static void reset(uint32_t digest[], size_t &buf_size, uint64_t &transforms) -{ - /* SHA1 initialization constants */ - digest[0] = 0x67452301; - digest[1] = 0xefcdab89; - digest[2] = 0x98badcfe; - digest[3] = 0x10325476; - digest[4] = 0xc3d2e1f0; - - /* Reset counters */ - buf_size = 0; - transforms = 0; + /* Reset counters */ + buf_size = 0; + transforms = 0; } - -static uint32_t rol(const uint32_t value, const size_t bits) -{ - return (value << bits) | (value >> (32 - bits)); +static uint32_t rol(const uint32_t value, const size_t bits) { + return (value << bits) | (value >> (32 - bits)); } - -static uint32_t blk(const uint32_t block[BLOCK_INTS], const size_t i) -{ - return rol(block[(i+13)&15] ^ block[(i+8)&15] ^ block[(i+2)&15] ^ block[i], 1); +static uint32_t blk(const uint32_t block[BLOCK_INTS], const size_t i) { + return rol(block[(i + 13) & 15] ^ block[(i + 8) & 15] ^ block[(i + 2) & 15] ^ + block[i], + 1); } - /* * (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ -static void R0(const uint32_t block[BLOCK_INTS], const uint32_t v, uint32_t &w, const uint32_t x, const uint32_t y, uint32_t &z, const size_t i) -{ - z += ((w&(x^y))^y) + block[i] + 0x5a827999 + rol(v, 5); - w = rol(w, 30); +static void R0(const uint32_t block[BLOCK_INTS], const uint32_t v, uint32_t& w, + const uint32_t x, const uint32_t y, uint32_t& z, + const size_t i) { + z += ((w & (x ^ y)) ^ y) + block[i] + 0x5a827999 + rol(v, 5); + w = rol(w, 30); } - -static void R1(uint32_t block[BLOCK_INTS], const uint32_t v, uint32_t &w, const uint32_t x, const uint32_t y, uint32_t &z, const size_t i) -{ - block[i] = blk(block, i); - z += ((w&(x^y))^y) + block[i] + 0x5a827999 + rol(v, 5); - w = rol(w, 30); +static void R1(uint32_t block[BLOCK_INTS], const uint32_t v, uint32_t& w, + const uint32_t x, const uint32_t y, uint32_t& z, + const size_t i) { + block[i] = blk(block, i); + z += ((w & (x ^ y)) ^ y) + block[i] + 0x5a827999 + rol(v, 5); + w = rol(w, 30); } - -static void R2(uint32_t block[BLOCK_INTS], const uint32_t v, uint32_t &w, const uint32_t x, const uint32_t y, uint32_t &z, const size_t i) -{ - block[i] = blk(block, i); - z += (w^x^y) + block[i] + 0x6ed9eba1 + rol(v, 5); - w = rol(w, 30); +static void R2(uint32_t block[BLOCK_INTS], const uint32_t v, uint32_t& w, + const uint32_t x, const uint32_t y, uint32_t& z, + const size_t i) { + block[i] = blk(block, i); + z += (w ^ x ^ y) + block[i] + 0x6ed9eba1 + rol(v, 5); + w = rol(w, 30); } - -static void R3(uint32_t block[BLOCK_INTS], const uint32_t v, uint32_t &w, const uint32_t x, const uint32_t y, uint32_t &z, const size_t i) -{ - block[i] = blk(block, i); - z += (((w|x)&y)|(w&x)) + block[i] + 0x8f1bbcdc + rol(v, 5); - w = rol(w, 30); +static void R3(uint32_t block[BLOCK_INTS], const uint32_t v, uint32_t& w, + const uint32_t x, const uint32_t y, uint32_t& z, + const size_t i) { + block[i] = blk(block, i); + z += (((w | x) & y) | (w & x)) + block[i] + 0x8f1bbcdc + rol(v, 5); + w = rol(w, 30); } - -static void R4(uint32_t block[BLOCK_INTS], const uint32_t v, uint32_t &w, const uint32_t x, const uint32_t y, uint32_t &z, const size_t i) -{ - block[i] = blk(block, i); - z += (w^x^y) + block[i] + 0xca62c1d6 + rol(v, 5); - w = rol(w, 30); +static void R4(uint32_t block[BLOCK_INTS], const uint32_t v, uint32_t& w, + const uint32_t x, const uint32_t y, uint32_t& z, + const size_t i) { + block[i] = blk(block, i); + z += (w ^ x ^ y) + block[i] + 0xca62c1d6 + rol(v, 5); + w = rol(w, 30); } - /* * Hash a single 512-bit block. This is the core of the algorithm. */ -static void transform(uint32_t digest[], uint32_t block[BLOCK_INTS], uint64_t &transforms) -{ - /* Copy digest[] to working vars */ - uint32_t a = digest[0]; - uint32_t b = digest[1]; - uint32_t c = digest[2]; - uint32_t d = digest[3]; - uint32_t e = digest[4]; +static void transform(uint32_t digest[], uint32_t block[BLOCK_INTS], + uint64_t& transforms) { + /* Copy digest[] to working vars */ + uint32_t a = digest[0]; + uint32_t b = digest[1]; + uint32_t c = digest[2]; + uint32_t d = digest[3]; + uint32_t e = digest[4]; - /* 4 rounds of 20 operations each. Loop unrolled. */ - R0(block, a, b, c, d, e, 0); - R0(block, e, a, b, c, d, 1); - R0(block, d, e, a, b, c, 2); - R0(block, c, d, e, a, b, 3); - R0(block, b, c, d, e, a, 4); - R0(block, a, b, c, d, e, 5); - R0(block, e, a, b, c, d, 6); - R0(block, d, e, a, b, c, 7); - R0(block, c, d, e, a, b, 8); - R0(block, b, c, d, e, a, 9); - R0(block, a, b, c, d, e, 10); - R0(block, e, a, b, c, d, 11); - R0(block, d, e, a, b, c, 12); - R0(block, c, d, e, a, b, 13); - R0(block, b, c, d, e, a, 14); - R0(block, a, b, c, d, e, 15); - R1(block, e, a, b, c, d, 0); - R1(block, d, e, a, b, c, 1); - R1(block, c, d, e, a, b, 2); - R1(block, b, c, d, e, a, 3); - R2(block, a, b, c, d, e, 4); - R2(block, e, a, b, c, d, 5); - R2(block, d, e, a, b, c, 6); - R2(block, c, d, e, a, b, 7); - R2(block, b, c, d, e, a, 8); - R2(block, a, b, c, d, e, 9); - R2(block, e, a, b, c, d, 10); - R2(block, d, e, a, b, c, 11); - R2(block, c, d, e, a, b, 12); - R2(block, b, c, d, e, a, 13); - R2(block, a, b, c, d, e, 14); - R2(block, e, a, b, c, d, 15); - R2(block, d, e, a, b, c, 0); - R2(block, c, d, e, a, b, 1); - R2(block, b, c, d, e, a, 2); - R2(block, a, b, c, d, e, 3); - R2(block, e, a, b, c, d, 4); - R2(block, d, e, a, b, c, 5); - R2(block, c, d, e, a, b, 6); - R2(block, b, c, d, e, a, 7); - R3(block, a, b, c, d, e, 8); - R3(block, e, a, b, c, d, 9); - R3(block, d, e, a, b, c, 10); - R3(block, c, d, e, a, b, 11); - R3(block, b, c, d, e, a, 12); - R3(block, a, b, c, d, e, 13); - R3(block, e, a, b, c, d, 14); - R3(block, d, e, a, b, c, 15); - R3(block, c, d, e, a, b, 0); - R3(block, b, c, d, e, a, 1); - R3(block, a, b, c, d, e, 2); - R3(block, e, a, b, c, d, 3); - R3(block, d, e, a, b, c, 4); - R3(block, c, d, e, a, b, 5); - R3(block, b, c, d, e, a, 6); - R3(block, a, b, c, d, e, 7); - R3(block, e, a, b, c, d, 8); - R3(block, d, e, a, b, c, 9); - R3(block, c, d, e, a, b, 10); - R3(block, b, c, d, e, a, 11); - R4(block, a, b, c, d, e, 12); - R4(block, e, a, b, c, d, 13); - R4(block, d, e, a, b, c, 14); - R4(block, c, d, e, a, b, 15); - R4(block, b, c, d, e, a, 0); - R4(block, a, b, c, d, e, 1); - R4(block, e, a, b, c, d, 2); - R4(block, d, e, a, b, c, 3); - R4(block, c, d, e, a, b, 4); - R4(block, b, c, d, e, a, 5); - R4(block, a, b, c, d, e, 6); - R4(block, e, a, b, c, d, 7); - R4(block, d, e, a, b, c, 8); - R4(block, c, d, e, a, b, 9); - R4(block, b, c, d, e, a, 10); - R4(block, a, b, c, d, e, 11); - R4(block, e, a, b, c, d, 12); - R4(block, d, e, a, b, c, 13); - R4(block, c, d, e, a, b, 14); - R4(block, b, c, d, e, a, 15); + /* 4 rounds of 20 operations each. Loop unrolled. */ + R0(block, a, b, c, d, e, 0); + R0(block, e, a, b, c, d, 1); + R0(block, d, e, a, b, c, 2); + R0(block, c, d, e, a, b, 3); + R0(block, b, c, d, e, a, 4); + R0(block, a, b, c, d, e, 5); + R0(block, e, a, b, c, d, 6); + R0(block, d, e, a, b, c, 7); + R0(block, c, d, e, a, b, 8); + R0(block, b, c, d, e, a, 9); + R0(block, a, b, c, d, e, 10); + R0(block, e, a, b, c, d, 11); + R0(block, d, e, a, b, c, 12); + R0(block, c, d, e, a, b, 13); + R0(block, b, c, d, e, a, 14); + R0(block, a, b, c, d, e, 15); + R1(block, e, a, b, c, d, 0); + R1(block, d, e, a, b, c, 1); + R1(block, c, d, e, a, b, 2); + R1(block, b, c, d, e, a, 3); + R2(block, a, b, c, d, e, 4); + R2(block, e, a, b, c, d, 5); + R2(block, d, e, a, b, c, 6); + R2(block, c, d, e, a, b, 7); + R2(block, b, c, d, e, a, 8); + R2(block, a, b, c, d, e, 9); + R2(block, e, a, b, c, d, 10); + R2(block, d, e, a, b, c, 11); + R2(block, c, d, e, a, b, 12); + R2(block, b, c, d, e, a, 13); + R2(block, a, b, c, d, e, 14); + R2(block, e, a, b, c, d, 15); + R2(block, d, e, a, b, c, 0); + R2(block, c, d, e, a, b, 1); + R2(block, b, c, d, e, a, 2); + R2(block, a, b, c, d, e, 3); + R2(block, e, a, b, c, d, 4); + R2(block, d, e, a, b, c, 5); + R2(block, c, d, e, a, b, 6); + R2(block, b, c, d, e, a, 7); + R3(block, a, b, c, d, e, 8); + R3(block, e, a, b, c, d, 9); + R3(block, d, e, a, b, c, 10); + R3(block, c, d, e, a, b, 11); + R3(block, b, c, d, e, a, 12); + R3(block, a, b, c, d, e, 13); + R3(block, e, a, b, c, d, 14); + R3(block, d, e, a, b, c, 15); + R3(block, c, d, e, a, b, 0); + R3(block, b, c, d, e, a, 1); + R3(block, a, b, c, d, e, 2); + R3(block, e, a, b, c, d, 3); + R3(block, d, e, a, b, c, 4); + R3(block, c, d, e, a, b, 5); + R3(block, b, c, d, e, a, 6); + R3(block, a, b, c, d, e, 7); + R3(block, e, a, b, c, d, 8); + R3(block, d, e, a, b, c, 9); + R3(block, c, d, e, a, b, 10); + R3(block, b, c, d, e, a, 11); + R4(block, a, b, c, d, e, 12); + R4(block, e, a, b, c, d, 13); + R4(block, d, e, a, b, c, 14); + R4(block, c, d, e, a, b, 15); + R4(block, b, c, d, e, a, 0); + R4(block, a, b, c, d, e, 1); + R4(block, e, a, b, c, d, 2); + R4(block, d, e, a, b, c, 3); + R4(block, c, d, e, a, b, 4); + R4(block, b, c, d, e, a, 5); + R4(block, a, b, c, d, e, 6); + R4(block, e, a, b, c, d, 7); + R4(block, d, e, a, b, c, 8); + R4(block, c, d, e, a, b, 9); + R4(block, b, c, d, e, a, 10); + R4(block, a, b, c, d, e, 11); + R4(block, e, a, b, c, d, 12); + R4(block, d, e, a, b, c, 13); + R4(block, c, d, e, a, b, 14); + R4(block, b, c, d, e, a, 15); - /* Add the working vars back into digest[] */ - digest[0] += a; - digest[1] += b; - digest[2] += c; - digest[3] += d; - digest[4] += e; + /* Add the working vars back into digest[] */ + digest[0] += a; + digest[1] += b; + digest[2] += c; + digest[3] += d; + digest[4] += e; - /* Count the number of transformations */ - transforms++; + /* Count the number of transformations */ + transforms++; } +static void buffer_to_block(const unsigned char* buffer, + uint32_t block[BLOCK_INTS]) { + /* Convert the std::string (byte buffer) to a uint32_t array (MSB) */ + for (size_t i = 0; i < BLOCK_INTS; i++) { + block[i] = (buffer[4 * i + 3] & 0xff) | (buffer[4 * i + 2] & 0xff) << 8 | + (buffer[4 * i + 1] & 0xff) << 16 | + (buffer[4 * i + 0] & 0xff) << 24; + } +} -static void buffer_to_block(const unsigned char* buffer, uint32_t block[BLOCK_INTS]) -{ - /* Convert the std::string (byte buffer) to a uint32_t array (MSB) */ - for (size_t i = 0; i < BLOCK_INTS; i++) - { - block[i] = (buffer[4*i+3] & 0xff) - | (buffer[4*i+2] & 0xff)<<8 - | (buffer[4*i+1] & 0xff)<<16 - | (buffer[4*i+0] & 0xff)<<24; +SHA1::SHA1() { reset(digest, buf_size, transforms); } + +void SHA1::Update(llvm::StringRef s) { + raw_mem_istream is(s); + Update(is); +} + +void SHA1::Update(raw_istream& is) { + while (true) { + buf_size += is.readsome(&buffer[buf_size], BLOCK_BYTES - buf_size); + if (buf_size != BLOCK_BYTES) { + return; } + uint32_t block[BLOCK_INTS]; + buffer_to_block(buffer, block); + transform(digest, block, transforms); + buf_size = 0; + } } - -SHA1::SHA1() -{ - reset(digest, buf_size, transforms); -} - - -void SHA1::Update(llvm::StringRef s) -{ - raw_mem_istream is(s); - Update(is); -} - - -void SHA1::Update(raw_istream &is) -{ - while (true) - { - buf_size += is.readsome(&buffer[buf_size], BLOCK_BYTES - buf_size); - if (buf_size != BLOCK_BYTES) - { - return; - } - uint32_t block[BLOCK_INTS]; - buffer_to_block(buffer, block); - transform(digest, block, transforms); - buf_size = 0; - } -} - - /* * Add padding and return the message digest. */ -static void finalize(uint32_t digest[], unsigned char* buffer, size_t& buf_size, uint64_t &transforms, llvm::raw_ostream& os) -{ - /* Total number of hashed bits */ - uint64_t total_bits = (transforms*BLOCK_BYTES + buf_size) * 8; +static void finalize(uint32_t digest[], unsigned char* buffer, size_t& buf_size, + uint64_t& transforms, llvm::raw_ostream& os) { + /* Total number of hashed bits */ + uint64_t total_bits = (transforms * BLOCK_BYTES + buf_size) * 8; - /* Padding */ - buffer[buf_size++] = 0x80; - for (size_t i = buf_size; i < BLOCK_BYTES; ++i) - { - buffer[i] = 0x00; - } + /* Padding */ + buffer[buf_size++] = 0x80; + for (size_t i = buf_size; i < BLOCK_BYTES; ++i) { + buffer[i] = 0x00; + } - uint32_t block[BLOCK_INTS]; - buffer_to_block(buffer, block); + uint32_t block[BLOCK_INTS]; + buffer_to_block(buffer, block); - if (buf_size > BLOCK_BYTES - 8) - { - transform(digest, block, transforms); - for (size_t i = 0; i < BLOCK_INTS - 2; i++) - { - block[i] = 0; - } - } - - /* Append total_bits, split this uint64_t into two uint32_t */ - block[BLOCK_INTS - 1] = total_bits; - block[BLOCK_INTS - 2] = (total_bits >> 32); + if (buf_size > BLOCK_BYTES - 8) { transform(digest, block, transforms); - - /* Hex string */ - static const char *const LUT = "0123456789abcdef"; - for (size_t i = 0; i < 5; i++) - { - uint32_t v = digest[i]; - os << LUT[(v >> 28) & 0xf] << LUT[(v >> 24) & 0xf] - << LUT[(v >> 20) & 0xf] << LUT[(v >> 16) & 0xf] - << LUT[(v >> 12) & 0xf] << LUT[(v >> 8) & 0xf] - << LUT[(v >> 4) & 0xf] << LUT[(v >> 0) & 0xf]; + for (size_t i = 0; i < BLOCK_INTS - 2; i++) { + block[i] = 0; } + } - /* Reset for next run */ - reset(digest, buf_size, transforms); + /* Append total_bits, split this uint64_t into two uint32_t */ + block[BLOCK_INTS - 1] = total_bits; + block[BLOCK_INTS - 2] = (total_bits >> 32); + transform(digest, block, transforms); + + /* Hex string */ + static const char* const LUT = "0123456789abcdef"; + for (size_t i = 0; i < 5; i++) { + uint32_t v = digest[i]; + os << LUT[(v >> 28) & 0xf] << LUT[(v >> 24) & 0xf] << LUT[(v >> 20) & 0xf] + << LUT[(v >> 16) & 0xf] << LUT[(v >> 12) & 0xf] << LUT[(v >> 8) & 0xf] + << LUT[(v >> 4) & 0xf] << LUT[(v >> 0) & 0xf]; + } + + /* Reset for next run */ + reset(digest, buf_size, transforms); } +std::string SHA1::Final() { + std::string out; + llvm::raw_string_ostream os(out); -std::string SHA1::Final() -{ - std::string out; - llvm::raw_string_ostream os(out); + finalize(digest, buffer, buf_size, transforms, os); - finalize(digest, buffer, buf_size, transforms, os); - - return os.str(); + return os.str(); } +llvm::StringRef SHA1::Final(llvm::SmallVectorImpl& buf) { + llvm::raw_svector_ostream os(buf); -llvm::StringRef SHA1::Final(llvm::SmallVectorImpl& buf) -{ - llvm::raw_svector_ostream os(buf); + finalize(digest, buffer, buf_size, transforms, os); - finalize(digest, buffer, buf_size, transforms, os); - - return os.str(); + return os.str(); } - -std::string SHA1::FromFile(llvm::StringRef filename) -{ - std::error_code ec; - raw_fd_istream stream(filename, ec); - SHA1 checksum; - checksum.Update(stream); - return checksum.Final(); +std::string SHA1::FromFile(llvm::StringRef filename) { + std::error_code ec; + raw_fd_istream stream(filename, ec); + SHA1 checksum; + checksum.Update(stream); + return checksum.Final(); } diff --git a/src/main/native/cpp/support/timestamp.cpp b/src/main/native/cpp/support/timestamp.cpp index 727cbad294..70965b868f 100644 --- a/src/main/native/cpp/support/timestamp.cpp +++ b/src/main/native/cpp/support/timestamp.cpp @@ -1,17 +1,19 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ + #include "support/timestamp.h" #include #ifdef _WIN32 +#include + #include #include -#include #else #include #endif @@ -34,10 +36,9 @@ static uint64_t zerotime() { tmpres -= deltaepoch; return tmpres; #else - // 100-ns intervals - using namespace std::chrono; - return duration_cast( - high_resolution_clock::now().time_since_epoch()) + // 1-us intervals + return std::chrono::duration_cast( + std::chrono::high_resolution_clock::now().time_since_epoch()) .count(); #endif } @@ -51,8 +52,8 @@ static uint64_t timestamp() { return static_cast(li.QuadPart); #else // 1-us intervals - using namespace std::chrono; - return duration_cast(steady_clock::now().time_since_epoch()) + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) .count(); #endif } diff --git a/src/main/native/cpp/tcpsockets/SocketError.cpp b/src/main/native/cpp/tcpsockets/SocketError.cpp index 2db2a24c54..36ff84ff24 100644 --- a/src/main/native/cpp/tcpsockets/SocketError.cpp +++ b/src/main/native/cpp/tcpsockets/SocketError.cpp @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -8,11 +8,10 @@ #include "tcpsockets/SocketError.h" #ifdef _WIN32 -#include -#include +#include #else -#include -#include +#include +#include #endif namespace wpi { @@ -28,13 +27,13 @@ int SocketErrno() { std::string SocketStrerror(int code) { #ifdef _WIN32 LPSTR errstr = nullptr; - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - 0, code, 0, (LPSTR)&errstr, 0, 0); + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, + code, 0, (LPSTR)&errstr, 0, 0); std::string rv(errstr); LocalFree(errstr); return rv; #else - return strerror(code); + return std::strerror(code); #endif } diff --git a/src/main/native/cpp/tcpsockets/TCPAcceptor.cpp b/src/main/native/cpp/tcpsockets/TCPAcceptor.cpp index 64b6554eb7..a71356c60c 100644 --- a/src/main/native/cpp/tcpsockets/TCPAcceptor.cpp +++ b/src/main/native/cpp/tcpsockets/TCPAcceptor.cpp @@ -6,7 +6,7 @@ ------------------------------------------ - Copyright © 2013 [Vic Hargrave - http://vichargrave.com] + Copyright (c) 2013 [Vic Hargrave - http://vichargrave.com] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,15 +25,16 @@ #include #include + #ifdef _WIN32 #include #include #pragma comment(lib, "Ws2_32.lib") #else #include +#include #include #include -#include #endif #include "llvm/SmallString.h" @@ -101,23 +102,26 @@ int TCPAcceptor::start() { #ifdef _WIN32 int optval = 1; - setsockopt(m_lsd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&optval, sizeof optval); + setsockopt(m_lsd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, + reinterpret_cast(&optval), sizeof optval); #else int optval = 1; - setsockopt(m_lsd, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof optval); + setsockopt(m_lsd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&optval), + sizeof optval); #endif - int result = bind(m_lsd, (struct sockaddr*)&address, sizeof(address)); + int result = bind(m_lsd, reinterpret_cast(&address), + sizeof(address)); if (result != 0) { - WPI_ERROR(m_logger, "bind() to port " << m_port - << " failed: " << SocketStrerror()); + WPI_ERROR(m_logger, + "bind() to port " << m_port << " failed: " << SocketStrerror()); return result; } result = listen(m_lsd, 5); if (result != 0) { - WPI_ERROR(m_logger, "listen() on port " << m_port - << " failed: " << SocketStrerror()); + WPI_ERROR(m_logger, + "listen() on port " << m_port << " failed: " << SocketStrerror()); return result; } m_listening = true; diff --git a/src/main/native/cpp/tcpsockets/TCPConnector.cpp b/src/main/native/cpp/tcpsockets/TCPConnector.cpp index ac563d17a6..a9e7df8303 100644 --- a/src/main/native/cpp/tcpsockets/TCPConnector.cpp +++ b/src/main/native/cpp/tcpsockets/TCPConnector.cpp @@ -6,7 +6,7 @@ ------------------------------------------ - Copyright © 2013 [Vic Hargrave - http://vichargrave.com] + Copyright (c) 2013 [Vic Hargrave - http://vichargrave.com] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -23,26 +23,27 @@ #include "tcpsockets/TCPConnector.h" -#include #include + +#include #include #include + #ifdef _WIN32 -#include #include +#include #else -#include #include +#include #include #include #include #endif -#include "tcpsockets/TCPStream.h" - #include "llvm/SmallString.h" #include "support/Logger.h" #include "tcpsockets/SocketError.h" +#include "tcpsockets/TCPStream.h" using namespace wpi; @@ -60,8 +61,9 @@ static int ResolveHostName(const char* hostname, struct in_addr* addr) { hints.ai_next = nullptr; int result = getaddrinfo(hostname, nullptr, &hints, &res); if (result == 0) { - std::memcpy(addr, &((struct sockaddr_in*)res->ai_addr)->sin_addr, - sizeof(struct in_addr)); + std::memcpy( + addr, &(reinterpret_cast(res->ai_addr)->sin_addr), + sizeof(struct in_addr)); freeaddrinfo(res); } return result; @@ -107,7 +109,8 @@ std::unique_ptr TCPConnector::connect(const char* server, return nullptr; } if (::connect(sd, (struct sockaddr*)&address, sizeof(address)) != 0) { - WPI_ERROR(logger, "connect() to " << server << " port " << port << " failed: " << SocketStrerror()); + WPI_ERROR(logger, "connect() to " << server << " port " << port + << " failed: " << SocketStrerror()); #ifdef _WIN32 closesocket(sd); #else @@ -127,14 +130,14 @@ std::unique_ptr TCPConnector::connect(const char* server, return nullptr; } - // Set socket to non-blocking +// Set socket to non-blocking #ifdef _WIN32 u_long mode = 1; if (ioctlsocket(sd, FIONBIO, &mode) == SOCKET_ERROR) WPI_WARNING(logger, "could not set socket to non-blocking: " << SocketStrerror()); #else - long arg; + int arg; arg = fcntl(sd, F_GETFL, nullptr); if (arg < 0) { WPI_WARNING(logger, @@ -162,20 +165,28 @@ std::unique_ptr TCPConnector::connect(const char* server, FD_SET(sd, &sdset); if (select(sd + 1, nullptr, &sdset, nullptr, &tv) > 0) { len = sizeof(int); - getsockopt(sd, SOL_SOCKET, SO_ERROR, (char*)(&valopt), &len); + getsockopt(sd, SOL_SOCKET, SO_ERROR, reinterpret_cast(&valopt), + &len); if (valopt) { - WPI_ERROR(logger, "select() to " << server << " port " << port << " error " << valopt << " - " << SocketStrerror(valopt)); + WPI_ERROR(logger, "select() to " << server << " port " << port + << " error " << valopt << " - " + << SocketStrerror(valopt)); } // connection established else result = 0; - } else - WPI_INFO(logger, "connect() to " << server << " port " << port << " timed out"); - } else - WPI_ERROR(logger, "connect() to " << server << " port " << port << " error " << SocketErrno() << " - " << SocketStrerror()); + } else { + WPI_INFO(logger, + "connect() to " << server << " port " << port << " timed out"); + } + } else { + WPI_ERROR(logger, "connect() to " << server << " port " << port + << " error " << SocketErrno() << " - " + << SocketStrerror()); + } } - // Return socket to blocking mode +// Return socket to blocking mode #ifdef _WIN32 mode = 0; if (ioctlsocket(sd, FIONBIO, &mode) == SOCKET_ERROR) @@ -197,9 +208,9 @@ std::unique_ptr TCPConnector::connect(const char* server, // Create stream object if connected, close if not. if (result == -1) { #ifdef _WIN32 - closesocket(sd); + closesocket(sd); #else - ::close(sd); + ::close(sd); #endif return nullptr; } diff --git a/src/main/native/cpp/tcpsockets/TCPConnector_parallel.cpp b/src/main/native/cpp/tcpsockets/TCPConnector_parallel.cpp index dbbc3e968d..955a154a98 100644 --- a/src/main/native/cpp/tcpsockets/TCPConnector_parallel.cpp +++ b/src/main/native/cpp/tcpsockets/TCPConnector_parallel.cpp @@ -1,11 +1,11 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ -#include "tcpsockets/TCPConnector.h" +#include "tcpsockets/TCPConnector.h" // NOLINT(build/include_order) #include #include @@ -107,7 +107,8 @@ std::unique_ptr TCPConnector::connect_parallel( } ++result->count; result->cv.notify_all(); - }).detach(); + }) + .detach(); } // wait for a result, timeout, or all finished diff --git a/src/main/native/cpp/tcpsockets/TCPStream.cpp b/src/main/native/cpp/tcpsockets/TCPStream.cpp index d738abef9d..399a4e9e48 100644 --- a/src/main/native/cpp/tcpsockets/TCPStream.cpp +++ b/src/main/native/cpp/tcpsockets/TCPStream.cpp @@ -6,7 +6,7 @@ ------------------------------------------ - Copyright © 2013 [Vic Hargrave - http://vichargrave.com] + Copyright (c) 2013 [Vic Hargrave - http://vichargrave.com] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ #include "tcpsockets/TCPStream.h" #include + #ifdef _WIN32 #include #include @@ -41,12 +42,13 @@ TCPStream::TCPStream(int sd, sockaddr_in* address) #ifdef _WIN32 InetNtop(PF_INET, &(address->sin_addr.s_addr), ip, sizeof(ip) - 1); #else - inet_ntop(PF_INET, (in_addr*)&(address->sin_addr.s_addr), ip, - sizeof(ip) - 1); + inet_ntop(PF_INET, reinterpret_cast(&(address->sin_addr.s_addr)), + ip, sizeof(ip) - 1); #ifdef SO_NOSIGPIPE // disable SIGPIPE on Mac OS X int set = 1; - setsockopt(m_sd, SOL_SOCKET, SO_NOSIGPIPE, (char*)&set, sizeof set); + setsockopt(m_sd, SOL_SOCKET, SO_NOSIGPIPE, reinterpret_cast(&set), + sizeof set); #endif #endif m_peerIP = ip; @@ -55,7 +57,7 @@ TCPStream::TCPStream(int sd, sockaddr_in* address) TCPStream::~TCPStream() { close(); } -std::size_t TCPStream::send(const char* buffer, std::size_t len, Error* err) { +size_t TCPStream::send(const char* buffer, size_t len, Error* err) { if (m_sd < 0) { *err = kConnectionClosed; return 0; @@ -82,7 +84,8 @@ std::size_t TCPStream::send(const char* buffer, std::size_t len, Error* err) { #ifdef _MSC_VER sprintf_s(Buffer, "Send() failed: WSA error=%d\n", WSAGetLastError()); #else - std::snprintf(Buffer, 128, "Send() failed: WSA error=%d\n", WSAGetLastError()); + std::snprintf(Buffer, sizeof(Buffer), "Send() failed: WSA error=%d\n", + WSAGetLastError()); #endif OutputDebugStringA(Buffer); *err = kConnectionReset; @@ -103,11 +106,10 @@ std::size_t TCPStream::send(const char* buffer, std::size_t len, Error* err) { return 0; } #endif - return static_cast(rv); + return static_cast(rv); } -std::size_t TCPStream::receive(char* buffer, std::size_t len, Error* err, - int timeout) { +size_t TCPStream::receive(char* buffer, size_t len, Error* err, int timeout) { if (m_sd < 0) { *err = kConnectionClosed; return 0; @@ -123,8 +125,7 @@ std::size_t TCPStream::receive(char* buffer, std::size_t len, Error* err, #else rv = read(m_sd, buffer, len); #endif - } - else if (WaitForReadEvent(timeout)) { + } else if (WaitForReadEvent(timeout)) { #ifdef _WIN32 rv = recv(m_sd, buffer, len, 0); #else @@ -145,7 +146,7 @@ std::size_t TCPStream::receive(char* buffer, std::size_t len, Error* err, *err = kConnectionReset; return 0; } - return static_cast(rv); + return static_cast(rv); } void TCPStream::close() { @@ -168,7 +169,8 @@ int TCPStream::getPeerPort() const { return m_peerPort; } void TCPStream::setNoDelay() { if (m_sd < 0) return; int optval = 1; - setsockopt(m_sd, IPPROTO_TCP, TCP_NODELAY, (char*)&optval, sizeof optval); + setsockopt(m_sd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&optval), + sizeof optval); } bool TCPStream::setBlocking(bool enabled) { @@ -177,7 +179,7 @@ bool TCPStream::setBlocking(bool enabled) { u_long mode = enabled ? 0 : 1; if (ioctlsocket(m_sd, FIONBIO, &mode) == SOCKET_ERROR) return false; #else - long flags = fcntl(m_sd, F_GETFL, nullptr); + int flags = fcntl(m_sd, F_GETFL, nullptr); if (flags < 0) return false; if (enabled) flags &= ~O_NONBLOCK; @@ -188,9 +190,7 @@ bool TCPStream::setBlocking(bool enabled) { return true; } -int TCPStream::getNativeHandle() const { - return m_sd; -} +int TCPStream::getNativeHandle() const { return m_sd; } bool TCPStream::WaitForReadEvent(int timeout) { fd_set sdset; diff --git a/src/main/native/cpp/udpsockets/UDPClient.cpp b/src/main/native/cpp/udpsockets/UDPClient.cpp index c76d0a0321..98cce4217e 100644 --- a/src/main/native/cpp/udpsockets/UDPClient.cpp +++ b/src/main/native/cpp/udpsockets/UDPClient.cpp @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -13,24 +13,20 @@ #pragma comment(lib, "Ws2_32.lib") #else #include +#include #include #include -#include #endif #include "support/Logger.h" #include "tcpsockets/SocketError.h" - using namespace wpi; -UDPClient::UDPClient(Logger& logger) - : UDPClient("", logger) {} +UDPClient::UDPClient(Logger& logger) : UDPClient("", logger) {} UDPClient::UDPClient(llvm::StringRef address, Logger& logger) - : m_lsd(0), - m_address(address), - m_logger(logger) {} + : m_lsd(0), m_address(address), m_logger(logger) {} UDPClient::UDPClient(UDPClient&& other) : m_lsd(other.m_lsd), @@ -113,8 +109,8 @@ void UDPClient::shutdown() { } } -int UDPClient::send(llvm::ArrayRef data, - llvm::StringRef server, int port) { +int UDPClient::send(llvm::ArrayRef data, llvm::StringRef server, + int port) { // server must be a resolvable IP address struct sockaddr_in addr; std::memset(&addr, 0, sizeof(addr)); @@ -138,14 +134,13 @@ int UDPClient::send(llvm::ArrayRef data, addr.sin_port = htons(port); // sendto should not block - int result = sendto(m_lsd, reinterpret_cast(data.data()), - data.size(), 0, reinterpret_cast(&addr), - sizeof(addr)); + int result = + sendto(m_lsd, reinterpret_cast(data.data()), data.size(), 0, + reinterpret_cast(&addr), sizeof(addr)); return result; } -int UDPClient::send(llvm::StringRef data, - llvm::StringRef server, int port) { +int UDPClient::send(llvm::StringRef data, llvm::StringRef server, int port) { // server must be a resolvable IP address struct sockaddr_in addr; std::memset(&addr, 0, sizeof(addr)); diff --git a/src/main/native/include/support/Base64.h b/src/main/native/include/support/Base64.h index 85bada6060..a5f7703e6a 100644 --- a/src/main/native/include/support/Base64.h +++ b/src/main/native/include/support/Base64.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -17,15 +17,15 @@ namespace llvm { template class SmallVectorImpl; class raw_ostream; -} +} // namespace llvm namespace wpi { -std::size_t Base64Decode(llvm::raw_ostream& os, llvm::StringRef encoded); +size_t Base64Decode(llvm::raw_ostream& os, llvm::StringRef encoded); -std::size_t Base64Decode(llvm::StringRef encoded, std::string* plain); +size_t Base64Decode(llvm::StringRef encoded, std::string* plain); -llvm::StringRef Base64Decode(llvm::StringRef encoded, std::size_t* num_read, +llvm::StringRef Base64Decode(llvm::StringRef encoded, size_t* num_read, llvm::SmallVectorImpl& buf); void Base64Encode(llvm::raw_ostream& os, llvm::StringRef plain); diff --git a/src/main/native/include/support/ConcurrentQueue.h b/src/main/native/include/support/ConcurrentQueue.h index 599274b708..f2cc7c9421 100644 --- a/src/main/native/include/support/ConcurrentQueue.h +++ b/src/main/native/include/support/ConcurrentQueue.h @@ -4,14 +4,15 @@ // - see < http://opensource.org/licenses/BSD-2-Clause> // -#ifndef WPIUTIL_SUPPORT_CONCURRENT_QUEUE_H_ -#define WPIUTIL_SUPPORT_CONCURRENT_QUEUE_H_ +#ifndef WPIUTIL_SUPPORT_CONCURRENTQUEUE_H_ +#define WPIUTIL_SUPPORT_CONCURRENTQUEUE_H_ #include #include +#include -#include "support/mutex.h" #include "support/condition_variable.h" +#include "support/mutex.h" namespace wpi { @@ -81,4 +82,4 @@ class ConcurrentQueue { } // namespace wpi -#endif // WPIUTIL_SUPPORT_CONCURRENT_QUEUE_H_ +#endif // WPIUTIL_SUPPORT_CONCURRENTQUEUE_H_ diff --git a/src/main/native/include/support/HttpUtil.h b/src/main/native/include/support/HttpUtil.h index f02c581131..eb8860570d 100644 --- a/src/main/native/include/support/HttpUtil.h +++ b/src/main/native/include/support/HttpUtil.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2016. All Rights Reserved. */ +/* Copyright (c) 2016-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -10,6 +10,8 @@ #include #include +#include +#include #include "llvm/ArrayRef.h" #include "llvm/SmallString.h" @@ -64,8 +66,8 @@ class HttpLocation { HttpLocation() = default; HttpLocation(const llvm::Twine& url_, bool* error, std::string* errorMsg); - std::string url; // retain copy - std::string user; // unescaped + std::string url; // retain copy + std::string user; // unescaped std::string password; // unescaped std::string host; int port; @@ -78,7 +80,8 @@ class HttpRequest { public: HttpRequest() = default; - HttpRequest(const HttpLocation& loc) : host{loc.host}, port{loc.port} { + explicit HttpRequest(const HttpLocation& loc) + : host{loc.host}, port{loc.port} { SetPath(loc.path, loc.params); SetAuth(loc); } @@ -109,13 +112,17 @@ class HttpRequest { void SetPath(llvm::StringRef path_, const T& params); template - static llvm::StringRef GetFirst(const T& elem) { return elem.first; } + static llvm::StringRef GetFirst(const T& elem) { + return elem.first; + } template static llvm::StringRef GetFirst(const llvm::StringMapEntry& elem) { return elem.getKey(); } template - static llvm::StringRef GetSecond(const T& elem) { return elem.second; } + static llvm::StringRef GetSecond(const T& elem) { + return elem.second; + } }; class HttpConnection { @@ -136,7 +143,7 @@ class HttpConnection { explicit operator bool() const { return stream && !is.has_error(); } }; -} // namespace wpi +} // namespace wpi #include "HttpUtil.inl" diff --git a/src/main/native/include/support/Logger.h b/src/main/native/include/support/Logger.h index f4c412253d..e40492805c 100644 --- a/src/main/native/include/support/Logger.h +++ b/src/main/native/include/support/Logger.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -10,8 +10,8 @@ #include -#include "llvm/raw_ostream.h" #include "llvm/SmallString.h" +#include "llvm/raw_ostream.h" namespace wpi { @@ -30,7 +30,8 @@ enum LogLevel { class Logger { public: typedef std::function LogFunc; + unsigned int line, const char* msg)> + LogFunc; Logger() = default; explicit Logger(const LogFunc& func) : m_func(func) {} @@ -71,11 +72,21 @@ class Logger { #define WPI_INFO(inst, x) WPI_LOG(inst, ::wpi::WPI_LOG_INFO, x) #ifdef NDEBUG -#define WPI_DEBUG(inst, x) do {} while (0) -#define WPI_DEBUG1(inst, x) do {} while (0) -#define WPI_DEBUG2(inst, x) do {} while (0) -#define WPI_DEBUG3(inst, x) do {} while (0) -#define WPI_DEBUG4(inst, x) do {} while (0) +#define WPI_DEBUG(inst, x) \ + do { \ + } while (0) +#define WPI_DEBUG1(inst, x) \ + do { \ + } while (0) +#define WPI_DEBUG2(inst, x) \ + do { \ + } while (0) +#define WPI_DEBUG3(inst, x) \ + do { \ + } while (0) +#define WPI_DEBUG4(inst, x) \ + do { \ + } while (0) #else #define WPI_DEBUG(inst, x) WPI_LOG(inst, ::wpi::WPI_LOG_DEBUG, x) #define WPI_DEBUG1(inst, x) WPI_LOG(inst, ::wpi::WPI_LOG_DEBUG1, x) @@ -84,6 +95,6 @@ class Logger { #define WPI_DEBUG4(inst, x) WPI_LOG(inst, ::wpi::WPI_LOG_DEBUG4, x) #endif -} // namespace wpi +} // namespace wpi #endif // WPIUTIL_SUPPORT_LOGGER_H_ diff --git a/src/main/native/include/support/SafeThread.h b/src/main/native/include/support/SafeThread.h index e0d357a50d..e957e0cd13 100644 --- a/src/main/native/include/support/SafeThread.h +++ b/src/main/native/include/support/SafeThread.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -33,7 +33,7 @@ namespace detail { // Non-template proxy base class for common proxy code. class SafeThreadProxyBase { public: - SafeThreadProxyBase(SafeThread* thr) : m_thread(thr) { + explicit SafeThreadProxyBase(SafeThread* thr) : m_thread(thr) { if (!m_thread) return; m_lock = std::unique_lock(m_thread->m_mutex); if (!m_thread->m_active) { @@ -55,7 +55,7 @@ class SafeThreadProxyBase { template class SafeThreadProxy : public SafeThreadProxyBase { public: - SafeThreadProxy(SafeThread* thr) : SafeThreadProxyBase(thr) {} + explicit SafeThreadProxy(SafeThread* thr) : SafeThreadProxyBase(thr) {} T& operator*() const { return *static_cast(m_thread); } T* operator->() const { return static_cast(m_thread); } }; diff --git a/src/main/native/include/support/UidVector.h b/src/main/native/include/support/UidVector.h index 3f0aa9af6f..c12465af02 100644 --- a/src/main/native/include/support/UidVector.h +++ b/src/main/native/include/support/UidVector.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -8,6 +8,7 @@ #ifndef WPIUTIL_SUPPORT_UIDVECTOR_H_ #define WPIUTIL_SUPPORT_UIDVECTOR_H_ +#include #include namespace wpi { diff --git a/src/main/native/include/support/atomic_static.h b/src/main/native/include/support/atomic_static.h index 146a1de478..31f8efa3b6 100644 --- a/src/main/native/include/support/atomic_static.h +++ b/src/main/native/include/support/atomic_static.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -24,25 +24,25 @@ #include #include -#define ATOMIC_STATIC(cls, inst) \ - cls* inst##tmp = m_instance.load(std::memory_order_acquire); \ - if (inst##tmp == nullptr) { \ - std::lock_guard lock(m_instance_mutex); \ - inst##tmp = m_instance.load(std::memory_order_relaxed); \ - if (inst##tmp == nullptr) { \ - inst##tmp = new cls; \ - m_instance.store(inst##tmp, std::memory_order_release); \ - } \ - } \ - cls& inst = *inst##tmp +#define ATOMIC_STATIC(cls, inst) \ + cls* inst##tmp = m_instance.load(std::memory_order_acquire); \ + if (inst##tmp == nullptr) { \ + std::lock_guard lock(m_instance_mutex); \ + inst##tmp = m_instance.load(std::memory_order_relaxed); \ + if (inst##tmp == nullptr) { \ + inst##tmp = new cls; \ + m_instance.store(inst##tmp, std::memory_order_release); \ + } \ + } \ + cls& inst = *inst##tmp -#define ATOMIC_STATIC_DECL(cls) \ - static std::atomic m_instance; \ - static std::mutex m_instance_mutex; +#define ATOMIC_STATIC_DECL(cls) \ + static std::atomic m_instance; \ + static std::mutex m_instance_mutex; -#define ATOMIC_STATIC_INIT(cls) \ - std::atomic cls::m_instance; \ - std::mutex cls::m_instance_mutex; +#define ATOMIC_STATIC_INIT(cls) \ + std::atomic cls::m_instance; \ + std::mutex cls::m_instance_mutex; #endif diff --git a/src/main/native/include/support/deprecated.h b/src/main/native/include/support/deprecated.h index 4a22b7377d..77f71a2b77 100644 --- a/src/main/native/include/support/deprecated.h +++ b/src/main/native/include/support/deprecated.h @@ -1,33 +1,33 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ -#ifndef DEPRECATED_H_ -#define DEPRECATED_H_ +#ifndef WPIUTIL_SUPPORT_DEPRECATED_H_ +#define WPIUTIL_SUPPORT_DEPRECATED_H_ // [[deprecated(msg)]] is a C++14 feature not supported by MSVC or GCC < 4.9. // We provide an equivalent warning implementation for those compilers here. #ifndef WPI_DEPRECATED - #if defined(_MSC_VER) - #define WPI_DEPRECATED(msg) __declspec(deprecated(msg)) - #elif defined(__GNUC__) - #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8) - #if __cplusplus > 201103L - #define WPI_DEPRECATED(msg) [[deprecated(msg)]] - #else - #define WPI_DEPRECATED(msg) [[gnu::deprecated(msg)]] - #endif - #else - #define WPI_DEPRECATED(msg) __attribute__((deprecated(msg))) - #endif - #elif __cplusplus > 201103L - #define WPI_DEPRECATED(msg) [[deprecated(msg)]] - #else - #define WPI_DEPRECATED(msg) /*nothing*/ - #endif +#if defined(_MSC_VER) +#define WPI_DEPRECATED(msg) __declspec(deprecated(msg)) +#elif defined(__GNUC__) +#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8) +#if __cplusplus > 201103L +#define WPI_DEPRECATED(msg) [[deprecated(msg)]] +#else +#define WPI_DEPRECATED(msg) [[gnu::deprecated(msg)]] +#endif +#else +#define WPI_DEPRECATED(msg) __attribute__((deprecated(msg))) +#endif +#elif __cplusplus > 201103L +#define WPI_DEPRECATED(msg) [[deprecated(msg)]] +#else +#define WPI_DEPRECATED(msg) /*nothing*/ +#endif #endif -#endif // DEPRECATED_H_ +#endif // WPIUTIL_SUPPORT_DEPRECATED_H_ diff --git a/src/main/native/include/support/hostname.h b/src/main/native/include/support/hostname.h index 0460900c54..cb2e438bb2 100644 --- a/src/main/native/include/support/hostname.h +++ b/src/main/native/include/support/hostname.h @@ -1,24 +1,25 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ -#ifndef HOSTNAME_H_ -#define HOSTNAME_H_ +#ifndef WPIUTIL_SUPPORT_HOSTNAME_H_ +#define WPIUTIL_SUPPORT_HOSTNAME_H_ #include + #include "llvm/StringRef.h" namespace llvm { - template - class SmallVectorImpl; - } +template +class SmallVectorImpl; +} // namespace llvm namespace wpi { std::string GetHostname(); llvm::StringRef GetHostname(llvm::SmallVectorImpl& name); } // namespace wpi -#endif // HOSTNAME_H_ +#endif // WPIUTIL_SUPPORT_HOSTNAME_H_ diff --git a/src/main/native/include/support/jni_util.h b/src/main/native/include/support/jni_util.h index ef364f5ac8..7b83239d0d 100644 --- a/src/main/native/include/support/jni_util.h +++ b/src/main/native/include/support/jni_util.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2016. All Rights Reserved. */ +/* Copyright (c) 2016-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -8,23 +8,24 @@ #ifndef WPIUTIL_SUPPORT_JNI_UTIL_H_ #define WPIUTIL_SUPPORT_JNI_UTIL_H_ +#include + +#include #include #include -#include +#include #include -#include - #include "llvm/ArrayRef.h" #include "llvm/ConvertUTF.h" -#include "llvm/raw_ostream.h" #include "llvm/SmallString.h" #include "llvm/SmallVector.h" #include "llvm/StringRef.h" +#include "llvm/raw_ostream.h" +#include "support/SafeThread.h" #include "support/atomic_static.h" #include "support/deprecated.h" #include "support/mutex.h" -#include "support/SafeThread.h" namespace wpi { namespace java { @@ -37,12 +38,12 @@ std::string GetJavaStackTrace( llvm::StringRef excludeFuncPrefix = llvm::StringRef()); // Shim for backwards compatibility -template +template WPI_DEPRECATED("use StringRef function instead") std::string GetJavaStackTrace(JNIEnv* env, std::string* func) { - return GetJavaStackTrace(env, func, excludeFuncPrefix == nullptr - ? llvm::StringRef() - : excludeFuncPrefix); + return GetJavaStackTrace( + env, func, + excludeFuncPrefix == nullptr ? llvm::StringRef() : excludeFuncPrefix); } // Finds a class and keep it as a global reference. @@ -59,7 +60,7 @@ class JClass { env->DeleteLocalRef(local); } - void free(JNIEnv *env) { + void free(JNIEnv* env) { if (m_cls) env->DeleteGlobalRef(m_cls); m_cls = nullptr; } @@ -77,7 +78,7 @@ class JClass { template class JLocal { public: - JLocal(JNIEnv *env, T obj) : m_env(env), m_obj(obj) {} + JLocal(JNIEnv* env, T obj) : m_env(env), m_obj(obj) {} JLocal(const JLocal&) = delete; JLocal(JLocal&& oth) : m_env(oth.m_env), m_obj(oth.m_obj) { oth.m_obj = nullptr; @@ -96,7 +97,7 @@ class JLocal { T obj() { return m_obj; } private: - JNIEnv *m_env; + JNIEnv* m_env; T m_obj; }; @@ -109,10 +110,10 @@ class JLocal { // characters, but it's named this way for consistency. class JStringRef { public: - JStringRef(JNIEnv *env, jstring str) { + JStringRef(JNIEnv* env, jstring str) { if (str) { jsize size = env->GetStringLength(str); - const jchar *chars = env->GetStringCritical(str, nullptr); + const jchar* chars = env->GetStringCritical(str, nullptr); if (chars) { llvm::convertUTF16ToUTF8String(llvm::makeArrayRef(chars, size), m_str); env->ReleaseStringCritical(str, chars); @@ -148,9 +149,9 @@ class JArrayRefInner { operator llvm::StringRef() const { return str(); } llvm::StringRef str() const { - auto arr = static_cast(this)->array(); + auto arr = static_cast(this)->array(); if (arr.empty()) return llvm::StringRef{}; - return llvm::StringRef{reinterpret_cast(arr.data()), + return llvm::StringRef{reinterpret_cast(arr.data()), arr.size()}; } }; @@ -191,24 +192,24 @@ class JArrayRefBase : public JArrayRefInner, T> { } protected: - JArrayRefBase(JNIEnv *env, T* elements, size_t size) { + JArrayRefBase(JNIEnv* env, T* elements, size_t size) { this->m_env = env; this->m_jarr = nullptr; this->m_size = size; this->m_elements = elements; } - JArrayRefBase(JNIEnv *env, jarray jarr) { + JArrayRefBase(JNIEnv* env, jarray jarr) { this->m_env = env; this->m_jarr = jarr; this->m_size = jarr ? env->GetArrayLength(jarr) : 0; this->m_elements = nullptr; } - JNIEnv *m_env; + JNIEnv* m_env; jarray m_jarr = nullptr; size_t m_size; - T *m_elements; + T* m_elements; }; } // namespace detail @@ -274,7 +275,7 @@ WPI_JNI_JARRAYREF(jdouble, Double) // // Convert a UTF8 string into a jstring. -inline jstring MakeJString(JNIEnv *env, llvm::StringRef str) { +inline jstring MakeJString(JNIEnv* env, llvm::StringRef str) { llvm::SmallVector chars; llvm::convertUTF8ToUTF16String(str, chars); return env->NewString(chars.begin(), chars.size()); @@ -289,11 +290,11 @@ namespace detail { template ::value && sizeof(jint) == sizeof(T))> struct ConvertIntArray { - static jintArray ToJava(JNIEnv *env, llvm::ArrayRef arr) { + static jintArray ToJava(JNIEnv* env, llvm::ArrayRef arr) { jintArray jarr = env->NewIntArray(arr.size()); if (!jarr) return nullptr; - jint *elements = - static_cast(env->GetPrimitiveArrayCritical(jarr, nullptr)); + jint* elements = + static_cast(env->GetPrimitiveArrayCritical(jarr, nullptr)); if (!elements) return nullptr; for (size_t i = 0; i < arr.size(); ++i) elements[i] = static_cast(arr[i]); @@ -305,10 +306,10 @@ struct ConvertIntArray { // Fast path (use SetIntArrayRegion) template struct ConvertIntArray { - static jintArray ToJava(JNIEnv *env, llvm::ArrayRef arr) { + static jintArray ToJava(JNIEnv* env, llvm::ArrayRef arr) { jintArray jarr = env->NewIntArray(arr.size()); if (!jarr) return nullptr; - env->SetIntArrayRegion(jarr, 0, arr.size(), + env->SetIntArrayRegion(jarr, 0, arr.size(), reinterpret_cast(arr.data())); return jarr; } @@ -318,40 +319,39 @@ struct ConvertIntArray { // Convert an ArrayRef to a jintArray. template -inline jintArray MakeJIntArray(JNIEnv *env, llvm::ArrayRef arr) { +inline jintArray MakeJIntArray(JNIEnv* env, llvm::ArrayRef arr) { return detail::ConvertIntArray::ToJava(env, arr); } // Convert a SmallVector to a jintArray. This is required in addition to // ArrayRef because template resolution occurs prior to implicit conversions. template -inline jintArray MakeJIntArray(JNIEnv *env, - const llvm::SmallVectorImpl &arr) { +inline jintArray MakeJIntArray(JNIEnv* env, + const llvm::SmallVectorImpl& arr) { return detail::ConvertIntArray::ToJava(env, arr); } // Convert a std::vector to a jintArray. This is required in addition to // ArrayRef because template resolution occurs prior to implicit conversions. template -inline jintArray MakeJIntArray(JNIEnv *env, const std::vector &arr) { +inline jintArray MakeJIntArray(JNIEnv* env, const std::vector& arr) { return detail::ConvertIntArray::ToJava(env, arr); } // Convert a StringRef into a jbyteArray. -inline jbyteArray MakeJByteArray(JNIEnv *env, llvm::StringRef str) { +inline jbyteArray MakeJByteArray(JNIEnv* env, llvm::StringRef str) { jbyteArray jarr = env->NewByteArray(str.size()); if (!jarr) return nullptr; env->SetByteArrayRegion(jarr, 0, str.size(), - reinterpret_cast(str.data())); + reinterpret_cast(str.data())); return jarr; } // Convert an array of integers into a jbooleanArray. -inline jbooleanArray MakeJBooleanArray(JNIEnv *env, llvm::ArrayRef arr) -{ +inline jbooleanArray MakeJBooleanArray(JNIEnv* env, llvm::ArrayRef arr) { jbooleanArray jarr = env->NewBooleanArray(arr.size()); if (!jarr) return nullptr; - jboolean *elements = + jboolean* elements = static_cast(env->GetPrimitiveArrayCritical(jarr, nullptr)); if (!elements) return nullptr; for (size_t i = 0; i < arr.size(); ++i) @@ -361,11 +361,10 @@ inline jbooleanArray MakeJBooleanArray(JNIEnv *env, llvm::ArrayRef arr) } // Convert an array of booleans into a jbooleanArray. -inline jbooleanArray MakeJBooleanArray(JNIEnv *env, llvm::ArrayRef arr) -{ +inline jbooleanArray MakeJBooleanArray(JNIEnv* env, llvm::ArrayRef arr) { jbooleanArray jarr = env->NewBooleanArray(arr.size()); if (!jarr) return nullptr; - jboolean *elements = + jboolean* elements = static_cast(env->GetPrimitiveArrayCritical(jarr, nullptr)); if (!elements) return nullptr; for (size_t i = 0; i < arr.size(); ++i) @@ -374,10 +373,10 @@ inline jbooleanArray MakeJBooleanArray(JNIEnv *env, llvm::ArrayRef arr) return jarr; } -// Other MakeJ*Array conversions. + // Other MakeJ*Array conversions. #define WPI_JNI_MAKEJARRAY(T, F) \ - inline T##Array MakeJ##F##Array(JNIEnv *env, llvm::ArrayRef arr) { \ + inline T##Array MakeJ##F##Array(JNIEnv* env, llvm::ArrayRef arr) { \ T##Array jarr = env->New##F##Array(arr.size()); \ if (!jarr) return nullptr; \ env->Set##F##ArrayRegion(jarr, 0, arr.size(), arr.data()); \ @@ -394,13 +393,13 @@ WPI_JNI_MAKEJARRAY(jdouble, Double) #undef WPI_JNI_MAKEJARRAY // Convert an array of std::string into a jarray of jstring. -inline jobjectArray MakeJStringArray(JNIEnv *env, +inline jobjectArray MakeJStringArray(JNIEnv* env, llvm::ArrayRef arr) { static JClass stringCls{env, "java/lang/String"}; if (!stringCls) return nullptr; jobjectArray jarr = env->NewObjectArray(arr.size(), stringCls, nullptr); if (!jarr) return nullptr; - for (std::size_t i = 0; i < arr.size(); ++i) { + for (size_t i = 0; i < arr.size(); ++i) { JLocal elem{env, MakeJString(env, arr[i])}; env->SetObjectArrayElement(jarr, i, elem.obj()); } @@ -466,12 +465,13 @@ void JCallbackManager::Send(Args&&... args) { template void JCallbackThread::Main() { - JNIEnv *env; + JNIEnv* env; JavaVMAttachArgs args; args.version = JNI_VERSION_1_2; args.name = const_cast(T::GetName()); args.group = nullptr; - jint rs = T::GetJVM()->AttachCurrentThreadAsDaemon((void**)&env, &args); + jint rs = T::GetJVM()->AttachCurrentThreadAsDaemon( + reinterpret_cast(&env), &args); if (rs != JNI_OK) return; std::unique_lock lock(m_mutex); @@ -568,10 +568,10 @@ inline std::string GetJavaStackTrace(JNIEnv* env, std::string* func, if (func) { // func is caller of immediate caller (if there was one) // or, if we see it, the first user function - if (i == 1) + if (i == 1) { *func = elem.str(); - else if (i > 1 && !haveLoc && !excludeFuncPrefix.empty() && - !elem.str().startswith(excludeFuncPrefix)) { + } else if (i > 1 && !haveLoc && !excludeFuncPrefix.empty() && + !elem.str().startswith(excludeFuncPrefix)) { *func = elem.str(); haveLoc = true; } diff --git a/src/main/native/include/support/leb128.h b/src/main/native/include/support/leb128.h index de08a23a32..5e03592cec 100644 --- a/src/main/native/include/support/leb128.h +++ b/src/main/native/include/support/leb128.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -16,10 +16,10 @@ namespace wpi { class raw_istream; -std::size_t SizeUleb128(unsigned long val); -std::size_t WriteUleb128(llvm::SmallVectorImpl& dest, unsigned long val); -std::size_t ReadUleb128(const char* addr, unsigned long* ret); -bool ReadUleb128(raw_istream& is, unsigned long* ret); +uint64_t SizeUleb128(uint64_t val); +uint64_t WriteUleb128(llvm::SmallVectorImpl& dest, uint64_t val); +uint64_t ReadUleb128(const char* addr, uint64_t* ret); +bool ReadUleb128(raw_istream& is, uint64_t* ret); } // namespace wpi diff --git a/src/main/native/include/support/priority_condition_variable.h b/src/main/native/include/support/priority_condition_variable.h index 28065599be..7ad1fc8a5a 100644 --- a/src/main/native/include/support/priority_condition_variable.h +++ b/src/main/native/include/support/priority_condition_variable.h @@ -7,14 +7,14 @@ #pragma once -#include -#include -#include - #ifdef __linux__ #include #endif +#include +#include +#include + #include "priority_mutex.h" namespace wpi { @@ -36,13 +36,9 @@ class priority_condition_variable { priority_condition_variable& operator=(const priority_condition_variable&) = delete; - void notify_one() noexcept { - pthread_cond_signal(&m_cond); - } + void notify_one() noexcept { pthread_cond_signal(&m_cond); } - void notify_all() noexcept { - pthread_cond_broadcast(&m_cond); - } + void notify_all() noexcept { pthread_cond_broadcast(&m_cond); } void wait(std::unique_lock& lock) noexcept { int e = pthread_cond_wait(&m_cond, lock.mutex()->native_handle()); @@ -113,7 +109,7 @@ class priority_condition_variable { struct timespec ts = { static_cast(s.time_since_epoch().count()), - static_cast(ns.count())}; + static_cast(ns.count())}; // NOLINT(runtime/int) pthread_cond_timedwait(&m_cond, lock.mutex()->native_handle(), &ts); diff --git a/src/main/native/include/support/priority_mutex.h b/src/main/native/include/support/priority_mutex.h index 1d435560c4..9b4cb63299 100644 --- a/src/main/native/include/support/priority_mutex.h +++ b/src/main/native/include/support/priority_mutex.h @@ -8,12 +8,12 @@ #pragma once // Allows usage with std::lock_guard without including separately -#include - #ifdef __linux__ #include #endif +#include + namespace wpi { #ifdef __linux__ diff --git a/src/main/native/include/support/raw_istream.h b/src/main/native/include/support/raw_istream.h index d8d09846d8..c0c299f0d0 100644 --- a/src/main/native/include/support/raw_istream.h +++ b/src/main/native/include/support/raw_istream.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -38,17 +38,17 @@ class raw_istream { return *this; } - raw_istream& read(void* data, std::size_t len) { + raw_istream& read(void* data, size_t len) { read_impl(data, len); return *this; } - std::size_t readsome(void* data, std::size_t len) { - std::size_t readlen = std::min(in_avail(), len); + size_t readsome(void* data, size_t len) { + size_t readlen = std::min(in_avail(), len); if (readlen == 0) return 0; read_impl(data, readlen); return readlen; - }; + } // Read a line from an input stream (up to a maximum length). // The returned buffer will contain the trailing \n (unless the maximum length @@ -59,7 +59,7 @@ class raw_istream { llvm::StringRef getline(llvm::SmallVectorImpl& buf, int maxLen); virtual void close() = 0; - virtual std::size_t in_avail() const = 0; + virtual size_t in_avail() const = 0; bool has_error() const { return m_error; } void clear_error() { m_error = false; } @@ -71,41 +71,41 @@ class raw_istream { void error_detected() { m_error = true; } private: - virtual void read_impl(void* data, std::size_t len) = 0; + virtual void read_impl(void* data, size_t len) = 0; bool m_error = false; }; class raw_mem_istream : public raw_istream { public: - raw_mem_istream(llvm::StringRef mem); - raw_mem_istream(const char* mem, std::size_t len) : m_cur(mem), m_left(len) {} + explicit raw_mem_istream(llvm::StringRef mem); + raw_mem_istream(const char* mem, size_t len) : m_cur(mem), m_left(len) {} void close() override; - std::size_t in_avail() const override; + size_t in_avail() const override; private: - void read_impl(void* data, std::size_t len) override; + void read_impl(void* data, size_t len) override; const char* m_cur; - std::size_t m_left; + size_t m_left; }; class raw_fd_istream : public raw_istream { public: raw_fd_istream(const llvm::Twine& filename, std::error_code& ec, - std::size_t bufSize = 4096); - raw_fd_istream(int fd, bool shouldClose, std::size_t bufSize = 4096); + size_t bufSize = 4096); + raw_fd_istream(int fd, bool shouldClose, size_t bufSize = 4096); ~raw_fd_istream() override; void close() override; - std::size_t in_avail() const override; + size_t in_avail() const override; private: - void read_impl(void* data, std::size_t len) override; + void read_impl(void* data, size_t len) override; char* m_buf; char* m_cur; char* m_end; - std::size_t m_bufSize; + size_t m_bufSize; int m_fd; bool m_shouldClose; }; diff --git a/src/main/native/include/support/raw_socket_istream.h b/src/main/native/include/support/raw_socket_istream.h index 475d3d041d..6a8b3738f2 100644 --- a/src/main/native/include/support/raw_socket_istream.h +++ b/src/main/native/include/support/raw_socket_istream.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -20,10 +20,10 @@ class raw_socket_istream : public raw_istream { : m_stream(stream), m_timeout(timeout) {} void close() override; - std::size_t in_avail() const override; + size_t in_avail() const override; private: - void read_impl(void* data, std::size_t len) override; + void read_impl(void* data, size_t len) override; NetworkStream& m_stream; int m_timeout; diff --git a/src/main/native/include/support/raw_socket_ostream.h b/src/main/native/include/support/raw_socket_ostream.h index 65793d30ac..afd37f68e4 100644 --- a/src/main/native/include/support/raw_socket_ostream.h +++ b/src/main/native/include/support/raw_socket_ostream.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2016. All Rights Reserved. */ +/* Copyright (c) 2016-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -29,7 +29,7 @@ class raw_socket_ostream : public llvm::raw_ostream { void error_detected() { m_error = true; } private: - void write_impl(const char* data, std::size_t len) override; + void write_impl(const char* data, size_t len) override; uint64_t current_pos() const override; NetworkStream& m_stream; diff --git a/src/main/native/include/support/sha1.h b/src/main/native/include/support/sha1.h index f156f888f5..9871393b1b 100644 --- a/src/main/native/include/support/sha1.h +++ b/src/main/native/include/support/sha1.h @@ -17,39 +17,40 @@ -- Eugene Hopkinson */ -#ifndef SHA1_HPP -#define SHA1_HPP +#ifndef WPIUTIL_SUPPORT_SHA1_H_ +#define WPIUTIL_SUPPORT_SHA1_H_ +#include -#include #include + #include "llvm/StringRef.h" namespace llvm { -template class SmallVectorImpl; -} +template +class SmallVectorImpl; +} // namespace llvm namespace wpi { class raw_istream; -class SHA1 -{ -public: - SHA1(); - void Update(llvm::StringRef s); - void Update(raw_istream &is); - std::string Final(); - llvm::StringRef Final(llvm::SmallVectorImpl& buf); - static std::string FromFile(llvm::StringRef filename); +class SHA1 { + public: + SHA1(); + void Update(llvm::StringRef s); + void Update(raw_istream& is); + std::string Final(); + llvm::StringRef Final(llvm::SmallVectorImpl& buf); + static std::string FromFile(llvm::StringRef filename); -private: - uint32_t digest[5]; - unsigned char buffer[64]; - size_t buf_size; - uint64_t transforms; + private: + uint32_t digest[5]; + unsigned char buffer[64]; + size_t buf_size; + uint64_t transforms; }; } // namespace wpi -#endif /* SHA1_HPP */ +#endif // WPIUTIL_SUPPORT_SHA1_H_ diff --git a/src/main/native/include/support/timestamp.h b/src/main/native/include/support/timestamp.h index a1441db657..bb276dd639 100644 --- a/src/main/native/include/support/timestamp.h +++ b/src/main/native/include/support/timestamp.h @@ -1,9 +1,10 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ + #ifndef WPIUTIL_SUPPORT_TIMESTAMP_H_ #define WPIUTIL_SUPPORT_TIMESTAMP_H_ @@ -36,7 +37,7 @@ void WPI_SetNowImpl(uint64_t (*func)(void)); uint64_t WPI_Now(void); #ifdef __cplusplus -} +} // extern "C" #endif #ifdef __cplusplus @@ -47,7 +48,7 @@ namespace wpi { * In general this is the time returned by the operating system. * @return Time in microseconds. */ -uint64_t NowDefault(); +uint64_t NowDefault(void); /** * Set the implementation used by Now(). @@ -62,7 +63,7 @@ void SetNowImpl(uint64_t (*func)()); * This is a monotonic clock with an undefined epoch. * @return Time in microseconds. */ -uint64_t Now(); +uint64_t Now(void); } // namespace wpi #endif diff --git a/src/main/native/include/tcpsockets/NetworkAcceptor.h b/src/main/native/include/tcpsockets/NetworkAcceptor.h index f4d91204b3..9933e04c19 100644 --- a/src/main/native/include/tcpsockets/NetworkAcceptor.h +++ b/src/main/native/include/tcpsockets/NetworkAcceptor.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -8,6 +8,8 @@ #ifndef WPIUTIL_TCPSOCKETS_NETWORKACCEPTOR_H_ #define WPIUTIL_TCPSOCKETS_NETWORKACCEPTOR_H_ +#include + #include "tcpsockets/NetworkStream.h" namespace wpi { diff --git a/src/main/native/include/tcpsockets/NetworkStream.h b/src/main/native/include/tcpsockets/NetworkStream.h index 03b3a93ae6..134c5847dc 100644 --- a/src/main/native/include/tcpsockets/NetworkStream.h +++ b/src/main/native/include/tcpsockets/NetworkStream.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -26,9 +26,9 @@ class NetworkStream { kWouldBlock = -3 }; - virtual std::size_t send(const char* buffer, std::size_t len, Error* err) = 0; - virtual std::size_t receive(char* buffer, std::size_t len, Error* err, - int timeout = 0) = 0; + virtual size_t send(const char* buffer, size_t len, Error* err) = 0; + virtual size_t receive(char* buffer, size_t len, Error* err, + int timeout = 0) = 0; virtual void close() = 0; virtual llvm::StringRef getPeerIP() const = 0; diff --git a/src/main/native/include/tcpsockets/SocketError.h b/src/main/native/include/tcpsockets/SocketError.h index 0835797270..0abd1cd0ff 100644 --- a/src/main/native/include/tcpsockets/SocketError.h +++ b/src/main/native/include/tcpsockets/SocketError.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ diff --git a/src/main/native/include/tcpsockets/TCPAcceptor.h b/src/main/native/include/tcpsockets/TCPAcceptor.h index 99403a3aca..d20545d35d 100644 --- a/src/main/native/include/tcpsockets/TCPAcceptor.h +++ b/src/main/native/include/tcpsockets/TCPAcceptor.h @@ -6,7 +6,7 @@ ------------------------------------------ - Copyright © 2013 [Vic Hargrave - http://vichargrave.com] + Copyright (c) 2013 [Vic Hargrave - http://vichargrave.com] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/main/native/include/tcpsockets/TCPConnector.h b/src/main/native/include/tcpsockets/TCPConnector.h index 6b056eca3f..9d2535bd80 100644 --- a/src/main/native/include/tcpsockets/TCPConnector.h +++ b/src/main/native/include/tcpsockets/TCPConnector.h @@ -6,7 +6,7 @@ ------------------------------------------ - Copyright © 2013 [Vic Hargrave - http://vichargrave.com] + Copyright (c) 2013 [Vic Hargrave - http://vichargrave.com] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ #define WPIUTIL_TCPSOCKETS_TCPCONNECTOR_H_ #include +#include #include "llvm/ArrayRef.h" #include "tcpsockets/NetworkStream.h" diff --git a/src/main/native/include/tcpsockets/TCPStream.h b/src/main/native/include/tcpsockets/TCPStream.h index d58e6a979d..9e80bbc58f 100644 --- a/src/main/native/include/tcpsockets/TCPStream.h +++ b/src/main/native/include/tcpsockets/TCPStream.h @@ -6,7 +6,7 @@ ------------------------------------------ - Copyright © 2013 [Vic Hargrave - http://vichargrave.com] + Copyright (c) 2013 [Vic Hargrave - http://vichargrave.com] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -45,9 +45,9 @@ class TCPStream : public NetworkStream { ~TCPStream(); - std::size_t send(const char* buffer, std::size_t len, Error* err) override; - std::size_t receive(char* buffer, std::size_t len, Error* err, - int timeout = 0) override; + size_t send(const char* buffer, size_t len, Error* err) override; + size_t receive(char* buffer, size_t len, Error* err, + int timeout = 0) override; void close() override; llvm::StringRef getPeerIP() const override; @@ -58,6 +58,7 @@ class TCPStream : public NetworkStream { TCPStream(const TCPStream& stream) = delete; TCPStream& operator=(const TCPStream&) = delete; + private: bool WaitForReadEvent(int timeout); @@ -67,4 +68,4 @@ class TCPStream : public NetworkStream { } // namespace wpi -#endif +#endif // WPIUTIL_TCPSOCKETS_TCPSTREAM_H_ diff --git a/src/main/native/include/udpsockets/UDPClient.h b/src/main/native/include/udpsockets/UDPClient.h index a7e8eca814..84f996315b 100644 --- a/src/main/native/include/udpsockets/UDPClient.h +++ b/src/main/native/include/udpsockets/UDPClient.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -14,7 +14,6 @@ #include "llvm/StringRef.h" #include "support/mutex.h" - namespace wpi { class Logger; @@ -24,7 +23,7 @@ class UDPClient { std::string m_address; Logger& m_logger; -public: + public: explicit UDPClient(Logger& logger); UDPClient(llvm::StringRef address, Logger& logger); UDPClient(const UDPClient& other) = delete; diff --git a/src/test/native/cpp/Base64Test.cpp b/src/test/native/cpp/Base64Test.cpp index 5415ce874b..db34c8fc2c 100644 --- a/src/test/native/cpp/Base64Test.cpp +++ b/src/test/native/cpp/Base64Test.cpp @@ -1,14 +1,13 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ -#include "support/Base64.h" - #include "gtest/gtest.h" #include "llvm/SmallString.h" +#include "support/Base64.h" namespace wpi { @@ -66,7 +65,7 @@ TEST_P(Base64Test, DecodeStdString) { TEST_P(Base64Test, DecodeSmallString) { llvm::SmallString<128> buf; llvm::StringRef encoded = GetParam().encoded; - std::size_t len; + size_t len; llvm::StringRef plain = Base64Decode(encoded, &len, buf); EXPECT_EQ(encoded.size(), len); ASSERT_EQ(GetPlain(), plain); @@ -86,7 +85,8 @@ static Base64TestParam sample[] = { "mQgc28gb24uLi4K"}, }; -INSTANTIATE_TEST_CASE_P(Base64Sample, Base64Test, ::testing::ValuesIn(sample),); +INSTANTIATE_TEST_CASE_P(Base64Sample, Base64Test, + ::testing::ValuesIn(sample), ); static Base64TestParam standard[] = { {0, "", ""}, diff --git a/src/test/native/cpp/hostname.cpp b/src/test/native/cpp/hostname.cpp index 915819fc57..19b28929e0 100644 --- a/src/test/native/cpp/hostname.cpp +++ b/src/test/native/cpp/hostname.cpp @@ -1,20 +1,18 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2017. All Rights Reserved. */ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "support/hostname.h" + +#include "gtest/gtest.h" #include "llvm/SmallString.h" #include "llvm/SmallVector.h" -#include "gtest/gtest.h" - namespace wpi { -TEST(HostNameTest, HostNameNotEmpty) { - ASSERT_NE(wpi::GetHostname(), ""); -} +TEST(HostNameTest, HostNameNotEmpty) { ASSERT_NE(wpi::GetHostname(), ""); } TEST(HostNameTest, HostNameNotEmptySmallVector) { llvm::SmallVector name; ASSERT_NE(wpi::GetHostname(name), ""); diff --git a/src/test/native/cpp/leb128Test.cpp b/src/test/native/cpp/leb128Test.cpp index 00a79eebd2..1c9a0e00d9 100644 --- a/src/test/native/cpp/leb128Test.cpp +++ b/src/test/native/cpp/leb128Test.cpp @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -14,28 +14,26 @@ // //===----------------------------------------------------------------------===// -#include "support/leb128.h" +#include -#include "gtest/gtest.h" - -#include #include +#include "gtest/gtest.h" #include "llvm/SmallString.h" #include "llvm/StringRef.h" - +#include "support/leb128.h" #include "support/raw_istream.h" namespace wpi { TEST(LEB128Test, WriteUleb128) { -#define EXPECT_ULEB128_EQ(EXPECTED, VALUE, PAD) \ - do { \ - llvm::StringRef expected(EXPECTED, sizeof(EXPECTED)-1); \ - llvm::SmallString<32> buf; \ - std::size_t size = WriteUleb128(buf, VALUE); \ - EXPECT_EQ(size, buf.size()); \ - EXPECT_EQ(expected, buf.str()); \ +#define EXPECT_ULEB128_EQ(EXPECTED, VALUE, PAD) \ + do { \ + llvm::StringRef expected(EXPECTED, sizeof(EXPECTED) - 1); \ + llvm::SmallString<32> buf; \ + size_t size = WriteUleb128(buf, VALUE); \ + EXPECT_EQ(size, buf.size()); \ + EXPECT_EQ(expected, buf.str()); \ } while (0) // Write ULEB128 @@ -56,11 +54,11 @@ TEST(LEB128Test, WriteUleb128) { TEST(LEB128Test, ReadUleb128) { #define EXPECT_READ_ULEB128_EQ(EXPECTED, VALUE) \ - do { \ - unsigned long val = 0; \ - std::size_t size = ReadUleb128(VALUE, &val); \ - EXPECT_EQ(sizeof(VALUE) - 1, size); \ - EXPECT_EQ(EXPECTED, val); \ + do { \ + uint64_t val = 0; \ + size_t size = ReadUleb128(VALUE, &val); \ + EXPECT_EQ(sizeof(VALUE) - 1, size); \ + EXPECT_EQ(EXPECTED, val); \ } while (0) // Read ULEB128 @@ -86,7 +84,7 @@ TEST(LEB128Test, SizeUleb128) { // (2) 128 ^ n * 64 ....... need (n+1) bytes // (3) 128 ^ (n+1) - 1 .... need (n+1) bytes - EXPECT_EQ(1u, SizeUleb128(0)); // special case + EXPECT_EQ(1u, SizeUleb128(0)); // special case EXPECT_EQ(1u, SizeUleb128(0x1UL)); EXPECT_EQ(1u, SizeUleb128(0x40UL)); diff --git a/src/test/native/cpp/main.cpp b/src/test/native/cpp/main.cpp index e380efdd59..d5b0c6a737 100644 --- a/src/test/native/cpp/main.cpp +++ b/src/test/native/cpp/main.cpp @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2015. All Rights Reserved. */ +/* Copyright (c) 2015-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ @@ -7,8 +7,7 @@ #include "gtest/gtest.h" -int main(int argc, char **argv) -{ +int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); return ret; diff --git a/src/test/native/cpp/priority_condition_variable_test.cpp b/src/test/native/cpp/priority_condition_variable_test.cpp index 3bed1acc71..ff7b3b94f8 100644 --- a/src/test/native/cpp/priority_condition_variable_test.cpp +++ b/src/test/native/cpp/priority_condition_variable_test.cpp @@ -5,15 +5,15 @@ /* the project. */ /*----------------------------------------------------------------------------*/ +#include +#include + #include #include #include #include #include -#include -#include - #include "gtest/gtest.h" namespace wpi { diff --git a/src/test/native/cpp/sha1Test.cpp b/src/test/native/cpp/sha1Test.cpp index 5f71fe0a9b..c1d943273b 100644 --- a/src/test/native/cpp/sha1Test.cpp +++ b/src/test/native/cpp/sha1Test.cpp @@ -1,12 +1,19 @@ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) 2017 FIRST. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ + /* test_sha1.cpp - test program of - + ============ SHA-1 in C++ ============ - + 100% Public Domain. - + Original C Code -- Steve Reid Small changes to fit into bglibs @@ -15,11 +22,10 @@ -- Volker Grabsch */ -#include "support/sha1.h" +#include #include "gtest/gtest.h" - -#include +#include "support/sha1.h" namespace wpi { @@ -27,67 +33,60 @@ namespace wpi { * The 3 test vectors from FIPS PUB 180-1 */ -TEST(SHA1Test, Standard1) -{ - SHA1 checksum; - checksum.Update("abc"); - ASSERT_EQ(checksum.Final(), "a9993e364706816aba3e25717850c26c9cd0d89d"); +TEST(SHA1Test, Standard1) { + SHA1 checksum; + checksum.Update("abc"); + ASSERT_EQ(checksum.Final(), "a9993e364706816aba3e25717850c26c9cd0d89d"); } -TEST(SHA1Test, Standard2) -{ - SHA1 checksum; - checksum.Update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); - ASSERT_EQ(checksum.Final(), "84983e441c3bd26ebaae4aa1f95129e5e54670f1"); +TEST(SHA1Test, Standard2) { + SHA1 checksum; + checksum.Update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); + ASSERT_EQ(checksum.Final(), "84983e441c3bd26ebaae4aa1f95129e5e54670f1"); } -TEST(SHA1Test, Standard3) -{ - SHA1 checksum; - // A million repetitions of 'a' - for (int i = 0; i < 1000000/200; ++i) - { - checksum.Update("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - ); - } - ASSERT_EQ(checksum.Final(), "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); +TEST(SHA1Test, Standard3) { + SHA1 checksum; + // A million repetitions of 'a' + for (int i = 0; i < 1000000 / 200; ++i) { + checksum.Update( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + } + ASSERT_EQ(checksum.Final(), "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); } - /* * Other tests */ -TEST(SHA1Test, OtherNoString) -{ - SHA1 checksum; - ASSERT_EQ(checksum.Final(), "da39a3ee5e6b4b0d3255bfef95601890afd80709"); +TEST(SHA1Test, OtherNoString) { + SHA1 checksum; + ASSERT_EQ(checksum.Final(), "da39a3ee5e6b4b0d3255bfef95601890afd80709"); } -TEST(SHA1Test, OtherEmptyString) -{ - SHA1 checksum; - checksum.Update(""); - ASSERT_EQ(checksum.Final(), "da39a3ee5e6b4b0d3255bfef95601890afd80709"); +TEST(SHA1Test, OtherEmptyString) { + SHA1 checksum; + checksum.Update(""); + ASSERT_EQ(checksum.Final(), "da39a3ee5e6b4b0d3255bfef95601890afd80709"); } -TEST(SHA1Test, OtherABCDE) -{ - SHA1 checksum; - checksum.Update("abcde"); - ASSERT_EQ(checksum.Final(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); +TEST(SHA1Test, OtherABCDE) { + SHA1 checksum; + checksum.Update("abcde"); + ASSERT_EQ(checksum.Final(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); } -TEST(SHA1Test, Concurrent) -{ - // Two concurrent checksum calculations - SHA1 checksum1, checksum2; - checksum1.Update("abc"); - ASSERT_EQ(checksum2.Final(), "da39a3ee5e6b4b0d3255bfef95601890afd80709"); /* "" */ - ASSERT_EQ(checksum1.Final(), "a9993e364706816aba3e25717850c26c9cd0d89d"); /* "abc" */ +TEST(SHA1Test, Concurrent) { + // Two concurrent checksum calculations + SHA1 checksum1, checksum2; + checksum1.Update("abc"); + ASSERT_EQ(checksum2.Final(), + "da39a3ee5e6b4b0d3255bfef95601890afd80709"); /* "" */ + ASSERT_EQ(checksum1.Final(), + "a9993e364706816aba3e25717850c26c9cd0d89d"); /* "abc" */ } } // namespace wpi