Merge develop
This commit is contained in:
commit
b4c55b397d
.circleci
.eslintignore.gitignore.husky
CONTRIBUTING.md__tests__/__snapshots__
android
app/src
debug
main
play/java/chat/rocket/reactnative
fastlane
gradle.propertiesgradle/wrapper
gradlewgradlew.batapp
containers
presentation/UnreadBadge
sagas
utils
views/SettingsView
e2e/tests
assorted
room
team
ios
GemfileGemfile.lockPodfilePodfile.lock
Pods
CocoaAsyncSocket
CocoaLibEvent
LICENSEREADME.md
lib
src
evdns.hevent.h
event2
buffer.hbuffer_compat.hbufferevent.hbufferevent_compat.hbufferevent_ssl.hbufferevent_struct.hdns.hdns_compat.hdns_struct.hevent-config.hevent.hevent_compat.hevent_struct.hhttp.hhttp_compat.hhttp_struct.hkeyvalq_struct.hlistener.hrpc.hrpc_compat.hrpc_struct.htag.htag_compat.hthread.hutil.hvisibility.h
evhttp.hevrpc.hevutil.hDoubleConversion
Firebase
|
@ -3,7 +3,7 @@ defaults: &defaults
|
|||
|
||||
macos: &macos
|
||||
macos:
|
||||
xcode: "12.1.0"
|
||||
xcode: "12.5.0"
|
||||
|
||||
bash-env: &bash-env
|
||||
BASH_ENV: "~/.nvm/nvm.sh"
|
||||
|
@ -37,15 +37,6 @@ save-npm-cache-mac: &save-npm-cache-mac
|
|||
paths:
|
||||
- ./node_modules
|
||||
|
||||
install-node: &install-node
|
||||
name: Install Node
|
||||
command: |
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
|
||||
source ~/.nvm/nvm.sh
|
||||
INSTALLED_NODE=`nvm which current`
|
||||
echo "export PATH=\"${INSTALLED_NODE%%/node}:\$PATH\"" >> ~/.bash_profile
|
||||
source ~/.bash_profile
|
||||
|
||||
restore-gems-cache: &restore-gems-cache
|
||||
name: Restore gems cache
|
||||
key: bundle-v1-{{ checksum "ios/Gemfile.lock" }}
|
||||
|
@ -83,13 +74,32 @@ restore_cache: &restore-gradle-cache
|
|||
# COMMANDS
|
||||
commands:
|
||||
|
||||
manage-pods:
|
||||
description: "Restore/Get/Save cache of pods libs"
|
||||
steps:
|
||||
- restore_cache:
|
||||
name: Restore pods
|
||||
# TODO: CircleCI isn't caching Podfile.lock correctly, because checksum changes after install
|
||||
# key: pods-v1-{{ checksum "ios/Podfile.lock" }}
|
||||
key: pods-v1-{{ checksum "ios/Podfile" }}
|
||||
- run:
|
||||
name: Install pods libs
|
||||
command: |
|
||||
bundle exec pod install
|
||||
working_directory: ios
|
||||
- save_cache:
|
||||
name: Save pods specs and pods cache
|
||||
# key: pods-v1-{{ checksum "ios/Podfile.lock" }}
|
||||
key: pods-v1-{{ checksum "ios/Podfile" }}
|
||||
paths:
|
||||
- ~/.pods
|
||||
- ios/Pods
|
||||
|
||||
android-build:
|
||||
description: "Build Android app"
|
||||
steps:
|
||||
- checkout
|
||||
|
||||
- run: *install-node
|
||||
|
||||
- restore_cache: *restore-npm-cache-linux
|
||||
|
||||
- run: *install-npm-modules
|
||||
|
@ -196,9 +206,9 @@ commands:
|
|||
- checkout
|
||||
- restore_cache: *restore-gems-cache
|
||||
- restore_cache: *restore-npm-cache-mac
|
||||
- run: *install-node
|
||||
- run: *install-npm-modules
|
||||
- run: *update-fastlane-ios
|
||||
- manage-pods
|
||||
- run:
|
||||
name: Set Google Services
|
||||
command: |
|
||||
|
@ -231,7 +241,7 @@ commands:
|
|||
fi
|
||||
- run:
|
||||
name: Fastlane Build
|
||||
no_output_timeout: 1200
|
||||
no_output_timeout: 40m
|
||||
command: |
|
||||
agvtool new-version -all $CIRCLE_BUILD_NUM
|
||||
if [[ $CIRCLE_JOB == "ios-build-official" ]]; then
|
||||
|
@ -246,8 +256,8 @@ commands:
|
|||
/usr/libexec/PlistBuddy -c "Set IS_OFFICIAL NO" ./NotificationService/Info.plist
|
||||
fi
|
||||
|
||||
if [[ $APP_STORE_CONNECT_API_KEY ]]; then
|
||||
echo $APP_STORE_CONNECT_API_KEY | base64 --decode > ./fastlane/app_store_connect_api_key.p8
|
||||
if [[ $APP_STORE_CONNECT_API_BASE64 ]]; then
|
||||
echo $APP_STORE_CONNECT_API_BASE64 | base64 --decode > ./fastlane/app_store_connect_api_key.p8
|
||||
if [[ $CIRCLE_JOB == "ios-build-official" ]]; then
|
||||
bundle exec fastlane ios build_official
|
||||
else
|
||||
|
@ -290,6 +300,23 @@ commands:
|
|||
command: bundle exec fastlane android beta official:<< parameters.official >>
|
||||
working_directory: android
|
||||
|
||||
# EXPERIMENTAL ONLY
|
||||
upload-to-internal-app-sharing:
|
||||
description: "Upload to Internal App Sharing"
|
||||
steps:
|
||||
- checkout
|
||||
- attach_workspace:
|
||||
at: android
|
||||
- run:
|
||||
name: Store the google service account key
|
||||
command: echo "$FASTLANE_GOOGLE_SERVICE_ACCOUNT" | base64 --decode > service_account.json
|
||||
working_directory: android
|
||||
- run: *update-fastlane-android
|
||||
- run:
|
||||
name: Fastlane Play Store Upload
|
||||
command: bundle exec fastlane android internal_app_sharing
|
||||
working_directory: android
|
||||
|
||||
# EXPERIMENTAL ONLY
|
||||
# No plans to do it for Official
|
||||
upload-to-google-play-production:
|
||||
|
@ -318,11 +345,13 @@ commands:
|
|||
- attach_workspace:
|
||||
at: ios
|
||||
- restore_cache: *restore-gems-cache
|
||||
- restore_cache: *restore-npm-cache-mac
|
||||
- run: *update-fastlane-ios
|
||||
- manage-pods
|
||||
- run:
|
||||
name: Fastlane Tesflight Upload
|
||||
command: |
|
||||
echo $APP_STORE_CONNECT_API_KEY | base64 --decode > ./fastlane/app_store_connect_api_key.p8
|
||||
echo $APP_STORE_CONNECT_API_BASE64 | base64 --decode > ./fastlane/app_store_connect_api_key.p8
|
||||
bundle exec fastlane ios beta official:<< parameters.official >>
|
||||
working_directory: ios
|
||||
- save_cache: *save-gems-cache
|
||||
|
@ -341,7 +370,7 @@ jobs:
|
|||
lint-testunit:
|
||||
<<: *defaults
|
||||
docker:
|
||||
- image: circleci/node:10
|
||||
- image: circleci/node:15
|
||||
|
||||
environment:
|
||||
CODECOV_TOKEN: caa771ab-3d45-4756-8e2a-e1f25996fef6
|
||||
|
@ -374,7 +403,7 @@ jobs:
|
|||
android-build-experimental:
|
||||
<<: *defaults
|
||||
docker:
|
||||
- image: circleci/android:api-28-node
|
||||
- image: circleci/android:api-29-node
|
||||
environment:
|
||||
<<: *android-env
|
||||
<<: *bash-env
|
||||
|
@ -384,18 +413,26 @@ jobs:
|
|||
android-build-official:
|
||||
<<: *defaults
|
||||
docker:
|
||||
- image: circleci/android:api-28-node
|
||||
- image: circleci/android:api-29-node
|
||||
environment:
|
||||
<<: *android-env
|
||||
<<: *bash-env
|
||||
steps:
|
||||
- android-build
|
||||
|
||||
android-google-play-beta-experimental:
|
||||
android-internal-app-sharing-experimental:
|
||||
<<: *defaults
|
||||
docker:
|
||||
- image: circleci/android:api-28-node
|
||||
|
||||
steps:
|
||||
- upload-to-internal-app-sharing
|
||||
|
||||
android-google-play-beta-experimental:
|
||||
<<: *defaults
|
||||
docker:
|
||||
- image: circleci/android:api-29-node
|
||||
|
||||
steps:
|
||||
- upload-to-google-play-beta:
|
||||
official: false
|
||||
|
@ -403,14 +440,14 @@ jobs:
|
|||
android-google-play-production-experimental:
|
||||
<<: *defaults
|
||||
docker:
|
||||
- image: circleci/android:api-28-node
|
||||
- image: circleci/android:api-29-node
|
||||
steps:
|
||||
- upload-to-google-play-production
|
||||
|
||||
android-google-play-beta-official:
|
||||
<<: *defaults
|
||||
docker:
|
||||
- image: circleci/android:api-28-node
|
||||
- image: circleci/android:api-29-node
|
||||
|
||||
steps:
|
||||
- upload-to-google-play-beta:
|
||||
|
@ -452,13 +489,9 @@ workflows:
|
|||
- ios-build-experimental:
|
||||
requires:
|
||||
- ios-hold-build-experimental
|
||||
- ios-hold-testflight-experimental:
|
||||
type: approval
|
||||
requires:
|
||||
- ios-build-experimental
|
||||
- ios-testflight-experimental:
|
||||
requires:
|
||||
- ios-hold-testflight-experimental
|
||||
- ios-build-experimental
|
||||
|
||||
# iOS Official
|
||||
- ios-hold-build-official:
|
||||
|
@ -484,6 +517,9 @@ workflows:
|
|||
- android-build-experimental:
|
||||
requires:
|
||||
- android-hold-build-experimental
|
||||
- android-internal-app-sharing-experimental:
|
||||
requires:
|
||||
- android-build-experimental
|
||||
- android-hold-google-play-beta-experimental:
|
||||
type: approval
|
||||
requires:
|
||||
|
|
|
@ -3,4 +3,5 @@ node_modules
|
|||
coverage
|
||||
e2e/docker
|
||||
android
|
||||
ios
|
||||
ios
|
||||
.eslintrc.js
|
|
@ -22,6 +22,7 @@ DerivedData
|
|||
*.xcuserstate
|
||||
project.xcworkspace
|
||||
*.mobileprovision
|
||||
ios/Pods/
|
||||
|
||||
# Android/IntelliJ
|
||||
#
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
_
|
|
@ -0,0 +1,4 @@
|
|||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
npm run precommit
|
|
@ -20,6 +20,7 @@ yarn
|
|||
|
||||
Run the app:
|
||||
```sh
|
||||
npx pod-install
|
||||
yarn ios
|
||||
```
|
||||
|
||||
|
|
|
@ -48892,8 +48892,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
}
|
||||
>
|
||||
<View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -49282,8 +49286,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -49713,8 +49721,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -50144,8 +50156,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -50575,8 +50591,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -51006,8 +51026,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -51437,8 +51461,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -51868,8 +51896,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -52299,8 +52331,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -52730,8 +52766,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -53161,8 +53201,12 @@ exports[`Storyshots Room Item Alerts 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -53605,8 +53649,12 @@ exports[`Storyshots Room Item Basic 1`] = `
|
|||
}
|
||||
>
|
||||
<View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -54003,8 +54051,12 @@ exports[`Storyshots Room Item Last Message 1`] = `
|
|||
}
|
||||
>
|
||||
<View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -54447,8 +54499,12 @@ exports[`Storyshots Room Item Last Message 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -54891,8 +54947,12 @@ exports[`Storyshots Room Item Last Message 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -55335,8 +55395,12 @@ exports[`Storyshots Room Item Last Message 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -55779,8 +55843,12 @@ exports[`Storyshots Room Item Last Message 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -56279,8 +56347,12 @@ exports[`Storyshots Room Item Last Message 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -56779,8 +56851,12 @@ exports[`Storyshots Room Item Last Message 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -57292,8 +57368,12 @@ exports[`Storyshots Room Item Tag 1`] = `
|
|||
}
|
||||
>
|
||||
<View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -57713,8 +57793,12 @@ exports[`Storyshots Room Item Tag 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -58194,8 +58278,12 @@ exports[`Storyshots Room Item Tag 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -58615,8 +58703,12 @@ exports[`Storyshots Room Item Tag 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -59109,8 +59201,12 @@ exports[`Storyshots Room Item Touch 1`] = `
|
|||
}
|
||||
>
|
||||
<View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -59507,8 +59603,12 @@ exports[`Storyshots Room Item Type 1`] = `
|
|||
}
|
||||
>
|
||||
<View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -59892,8 +59992,12 @@ exports[`Storyshots Room Item Type 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -60265,8 +60369,12 @@ exports[`Storyshots Room Item Type 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -60638,8 +60746,12 @@ exports[`Storyshots Room Item Type 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -61011,8 +61123,12 @@ exports[`Storyshots Room Item Type 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -61384,8 +61500,12 @@ exports[`Storyshots Room Item Type 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -61757,8 +61877,12 @@ exports[`Storyshots Room Item Type 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -62143,8 +62267,12 @@ exports[`Storyshots Room Item User 1`] = `
|
|||
}
|
||||
>
|
||||
<View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -62528,8 +62656,12 @@ exports[`Storyshots Room Item User 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -62926,8 +63058,12 @@ exports[`Storyshots Room Item User status 1`] = `
|
|||
}
|
||||
>
|
||||
<View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -63311,8 +63447,12 @@ exports[`Storyshots Room Item User status 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -63696,8 +63836,12 @@ exports[`Storyshots Room Item User status 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -64081,8 +64225,12 @@ exports[`Storyshots Room Item User status 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -64466,8 +64614,12 @@ exports[`Storyshots Room Item User status 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -64851,8 +65003,12 @@ exports[`Storyshots Room Item User status 1`] = `
|
|||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
<View>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
style={Object {}}
|
||||
>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={
|
||||
|
@ -69410,6 +69566,7 @@ exports[`Storyshots ServerItem content 1`] = `
|
|||
Array [
|
||||
<View
|
||||
accessible={true}
|
||||
collapsable={false}
|
||||
focusable={true}
|
||||
onBlur={[Function]}
|
||||
onClick={[Function]}
|
||||
|
@ -69552,6 +69709,7 @@ Array [
|
|||
</View>,
|
||||
<View
|
||||
accessible={true}
|
||||
collapsable={false}
|
||||
focusable={true}
|
||||
onBlur={[Function]}
|
||||
onClick={[Function]}
|
||||
|
@ -69667,6 +69825,7 @@ Array [
|
|||
</View>,
|
||||
<View
|
||||
accessible={true}
|
||||
collapsable={false}
|
||||
focusable={true}
|
||||
onBlur={[Function]}
|
||||
onClick={[Function]}
|
||||
|
@ -69780,6 +69939,7 @@ exports[`Storyshots ServerItem themes 1`] = `
|
|||
Array [
|
||||
<View
|
||||
accessible={true}
|
||||
collapsable={false}
|
||||
focusable={true}
|
||||
onBlur={[Function]}
|
||||
onClick={[Function]}
|
||||
|
@ -69922,6 +70082,7 @@ Array [
|
|||
</View>,
|
||||
<View
|
||||
accessible={true}
|
||||
collapsable={false}
|
||||
focusable={true}
|
||||
onBlur={[Function]}
|
||||
onClick={[Function]}
|
||||
|
@ -70064,6 +70225,7 @@ Array [
|
|||
</View>,
|
||||
<View
|
||||
accessible={true}
|
||||
collapsable={false}
|
||||
focusable={true}
|
||||
onBlur={[Function]}
|
||||
onClick={[Function]}
|
||||
|
@ -70211,6 +70373,7 @@ exports[`Storyshots ServerItem touchable 1`] = `
|
|||
Array [
|
||||
<View
|
||||
accessible={true}
|
||||
collapsable={false}
|
||||
focusable={true}
|
||||
onBlur={[Function]}
|
||||
onClick={[Function]}
|
||||
|
@ -70326,6 +70489,7 @@ Array [
|
|||
</View>,
|
||||
<View
|
||||
accessible={true}
|
||||
collapsable={false}
|
||||
focusable={true}
|
||||
onBlur={[Function]}
|
||||
onClick={[Function]}
|
||||
|
@ -70441,6 +70605,7 @@ Array [
|
|||
</View>,
|
||||
<View
|
||||
accessible={true}
|
||||
collapsable={false}
|
||||
focusable={true}
|
||||
onBlur={[Function]}
|
||||
onClick={[Function]}
|
||||
|
|
|
@ -7,7 +7,9 @@
|
|||
tools:ignore="GoogleAppIndexingWarning"
|
||||
tools:replace="android:name"
|
||||
tools:targetApi="28"
|
||||
android:networkSecurityConfig="@xml/network_security_config" />
|
||||
android:networkSecurityConfig="@xml/network_security_config">
|
||||
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
|
||||
</application>
|
||||
|
||||
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||
</manifest>
|
|
@ -57,7 +57,6 @@
|
|||
android:scheme="rocketchat" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
|
||||
<activity
|
||||
android:name="chat.rocket.reactnative.share.ShareActivity"
|
||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
<resources>
|
||||
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
|
||||
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
|
||||
<item name="android:colorEdgeEffect">#aaaaaa</item>
|
||||
<item name="colorPrimaryDark">@color/splashBackground</item>
|
||||
<item name="android:navigationBarColor">@color/splashBackground</item>
|
||||
|
|
|
@ -115,7 +115,7 @@ class Encryption {
|
|||
jwk.putString("dq", privKey.dq);
|
||||
jwk.putString("qi", privKey.qi);
|
||||
|
||||
return new RCTRsaUtils().jwkToPrivatePkcs1(jwk);
|
||||
return new RCTRsaUtils(reactContext).jwkToPrivatePkcs1(jwk);
|
||||
}
|
||||
|
||||
public String decryptRoomKey(final String e2eKey, final Ejson ejson) throws Exception {
|
||||
|
|
|
@ -8,10 +8,11 @@ buildscript {
|
|||
def isPlay = !taskRequests.contains("foss")
|
||||
|
||||
ext {
|
||||
buildToolsVersion = "29.0.2"
|
||||
buildToolsVersion = "29.0.3"
|
||||
minSdkVersion = 23
|
||||
compileSdkVersion = 29
|
||||
targetSdkVersion = 29
|
||||
ndkVersion = "20.1.5948944"
|
||||
glideVersion = "4.11.0"
|
||||
kotlin_version = "1.3.50"
|
||||
supportLibVersion = "28.0.0"
|
||||
|
@ -33,9 +34,9 @@ buildscript {
|
|||
if (isPlay) {
|
||||
classpath 'com.google.gms:google-services:4.2.0'
|
||||
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.0.0'
|
||||
classpath 'com.bugsnag:bugsnag-android-gradle-plugin:4.+'
|
||||
classpath 'com.bugsnag:bugsnag-android-gradle-plugin:5.+'
|
||||
}
|
||||
classpath 'com.android.tools.build:gradle:3.5.3'
|
||||
classpath 'com.android.tools.build:gradle:4.1.0'
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
}
|
||||
}
|
||||
|
@ -68,7 +69,7 @@ subprojects { subproject ->
|
|||
if ((subproject.plugins.hasPlugin('android') || subproject.plugins.hasPlugin('android-library'))) {
|
||||
android {
|
||||
compileSdkVersion 29
|
||||
buildToolsVersion "29.0.2"
|
||||
buildToolsVersion "29.0.3"
|
||||
defaultConfig {
|
||||
targetSdkVersion 29
|
||||
}
|
||||
|
|
|
@ -33,6 +33,14 @@ platform :android do
|
|||
end
|
||||
end
|
||||
|
||||
desc "Upload App to Internal App Sharing"
|
||||
lane :internal_app_sharing do
|
||||
upload_to_play_store_internal_app_sharing(
|
||||
package_name: 'chat.rocket.reactnative',
|
||||
aab: 'android/app/build/outputs/bundle/experimentalPlayRelease/app-experimental-play-release.aab'
|
||||
)
|
||||
end
|
||||
|
||||
desc "Upload App to Play Store Production"
|
||||
lane :production do |options|
|
||||
upload_to_play_store(
|
||||
|
|
|
@ -12,33 +12,28 @@ Install _fastlane_ using
|
|||
```
|
||||
[sudo] gem install fastlane -NV
|
||||
```
|
||||
or alternatively using `brew cask install fastlane`
|
||||
or alternatively using `brew install fastlane`
|
||||
|
||||
# Available Actions
|
||||
## Android
|
||||
### android playBuild
|
||||
### android beta
|
||||
```
|
||||
fastlane android playBuild
|
||||
fastlane android beta
|
||||
```
|
||||
Play build for development
|
||||
### android fossRelease
|
||||
Upload App to Play Store Internal
|
||||
### android internal_app_sharing
|
||||
```
|
||||
fastlane android fossRelease
|
||||
fastlane android internal_app_sharing
|
||||
```
|
||||
Foss build for release
|
||||
### android playRelease
|
||||
Upload App to Internal App Sharing
|
||||
### android production
|
||||
```
|
||||
fastlane android playRelease
|
||||
fastlane android production
|
||||
```
|
||||
Play build for release
|
||||
### android playAlpha
|
||||
```
|
||||
fastlane android playAlpha
|
||||
```
|
||||
Upload App to Play store
|
||||
Upload App to Play Store Production
|
||||
|
||||
----
|
||||
|
||||
This README.md is auto-generated and will be re-generated every time [fastlane](https://fastlane.tools) is run.
|
||||
This README.md is auto-generated and will be re-generated every time [_fastlane_](https://fastlane.tools) is run.
|
||||
More information about fastlane can be found on [fastlane.tools](https://fastlane.tools).
|
||||
The documentation of fastlane can be found on [docs.fastlane.tools](https://docs.fastlane.tools).
|
||||
|
|
|
@ -27,7 +27,7 @@ android.useAndroidX=true
|
|||
android.enableJetifier=true
|
||||
|
||||
# Version of flipper SDK to use with React Native
|
||||
FLIPPER_VERSION=0.51.0
|
||||
FLIPPER_VERSION=0.75.1
|
||||
|
||||
# Application ID
|
||||
APPLICATION_ID=chat.rocket.reactnative
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
|
@ -82,6 +82,7 @@ esac
|
|||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
|
@ -129,6 +130,7 @@ fi
|
|||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
|
|
|
@ -40,7 +40,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
|
|||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
@ -54,7 +54,7 @@ goto fail
|
|||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
|
@ -64,28 +64,14 @@ echo location of your Java installation.
|
|||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
|
|
|
@ -427,6 +427,8 @@ const MessageActions = React.memo(forwardRef(({
|
|||
};
|
||||
|
||||
useImperativeHandle(ref, () => ({ showMessageActions }));
|
||||
|
||||
return null;
|
||||
}));
|
||||
MessageActions.propTypes = {
|
||||
room: PropTypes.object,
|
||||
|
|
|
@ -93,9 +93,10 @@ const MessageErrorActions = forwardRef(({ tmid }, ref) => {
|
|||
useImperativeHandle(ref, () => ({
|
||||
showMessageErrorActions
|
||||
}));
|
||||
|
||||
return null;
|
||||
});
|
||||
MessageErrorActions.propTypes = {
|
||||
message: PropTypes.object,
|
||||
tmid: PropTypes.string
|
||||
};
|
||||
|
||||
|
|
|
@ -34,7 +34,7 @@ const UnreadBadge = React.memo(({
|
|||
theme, unread, userMentions, groupMentions, style, tunread, tunreadUser, tunreadGroup, small
|
||||
}) => {
|
||||
if ((!unread || unread <= 0) && (!tunread?.length)) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
const { backgroundColor, color } = getUnreadStyle({
|
||||
theme, unread, userMentions, groupMentions, tunread, tunreadUser, tunreadGroup
|
||||
|
|
|
@ -67,8 +67,8 @@ const restore = function* restore() {
|
|||
}
|
||||
};
|
||||
|
||||
const start = function start() {
|
||||
RNBootSplash.hide();
|
||||
const start = function* start() {
|
||||
yield RNBootSplash.hide();
|
||||
};
|
||||
|
||||
const root = function* root() {
|
||||
|
|
|
@ -103,7 +103,7 @@ export const localAuthenticate = async(server) => {
|
|||
// if screen lock is enabled
|
||||
if (serverRecord?.autoLock) {
|
||||
// Make sure splash screen has been hidden
|
||||
RNBootSplash.hide();
|
||||
await RNBootSplash.hide();
|
||||
|
||||
// Check if the app has passcode
|
||||
const result = await checkHasPasscode({ serverRecord });
|
||||
|
|
|
@ -5,7 +5,7 @@ import {
|
|||
import PropTypes from 'prop-types';
|
||||
import { connect } from 'react-redux';
|
||||
import FastImage from '@rocket.chat/react-native-fast-image';
|
||||
import CookieManager from '@react-native-community/cookies';
|
||||
import CookieManager from '@react-native-cookies/cookies';
|
||||
|
||||
import { logout as logoutAction } from '../../actions/login';
|
||||
import { selectServerRequest as selectServerRequestAction } from '../../actions/server';
|
||||
|
|
|
@ -135,7 +135,7 @@ describe('Join public room', () => {
|
|||
await mockMessage('message');
|
||||
});
|
||||
|
||||
it('should have disable notifications and leave channel', async() => {
|
||||
it('should have notifications and leave channel', async() => {
|
||||
await navigateToRoomActions();
|
||||
await expect(element(by.id('room-actions-view'))).toBeVisible();
|
||||
await expect(element(by.id('room-actions-info'))).toBeVisible();
|
||||
|
@ -145,7 +145,7 @@ describe('Join public room', () => {
|
|||
await expect(element(by.id('room-actions-files'))).toBeVisible();
|
||||
await expect(element(by.id('room-actions-mentioned'))).toBeVisible();
|
||||
await expect(element(by.id('room-actions-starred'))).toBeVisible();
|
||||
await element(by.type('UIScrollView')).atIndex(1).swipe('down');
|
||||
await element(by.id('room-actions-scrollview')).swipe('down');
|
||||
await expect(element(by.id('room-actions-share'))).toBeVisible();
|
||||
await expect(element(by.id('room-actions-pinned'))).toBeVisible();
|
||||
await expect(element(by.id('room-actions-notifications'))).toBeVisible();
|
||||
|
|
|
@ -102,7 +102,7 @@ describe('Discussion', () => {
|
|||
});
|
||||
|
||||
it('should have share', async() => {
|
||||
await element(by.type('UIScrollView')).atIndex(1).swipe('up');
|
||||
await element(by.id('room-actions-scrollview')).swipe('up');
|
||||
await expect(element(by.id('room-actions-share'))).toBeVisible();
|
||||
});
|
||||
|
||||
|
@ -118,8 +118,8 @@ describe('Discussion', () => {
|
|||
await expect(element(by.id('room-actions-leave-channel'))).toBeVisible();
|
||||
});
|
||||
|
||||
it('should navigate to RoomActionsView', async() => {
|
||||
await element(by.type('UIScrollView')).atIndex(1).swipe('down');
|
||||
it('should navigate to RoomActionView', async() => {
|
||||
await element(by.id('room-actions-scrollview')).swipe('down');
|
||||
await expect(element(by.id('room-actions-info'))).toBeVisible();
|
||||
await element(by.id('room-actions-info')).tap();
|
||||
await waitFor(element(by.id('room-info-view'))).toExist().withTimeout(60000);
|
||||
|
|
|
@ -112,6 +112,7 @@ describe('Threads', () => {
|
|||
it('should mark send to channel and show on main channel', async() => {
|
||||
const messageText = 'sendToChannel';
|
||||
await element(by.id(`message-thread-button-${ thread }`)).tap();
|
||||
await waitFor(element(by.id('messagebox-input-thread'))).toExist().withTimeout(5000);
|
||||
await element(by.id('messagebox-input-thread')).typeText(messageText);
|
||||
await element(by.id('messagebox-send-to-channel')).tap();
|
||||
await element(by.id('messagebox-send-message')).tap();
|
||||
|
@ -127,6 +128,7 @@ describe('Threads', () => {
|
|||
await mockMessage('dummymessagebetweenthethread');
|
||||
await dismissReviewNag(); // TODO: Create a proper test for this elsewhere.
|
||||
await element(by.id(`message-thread-button-${ thread }`)).tap();
|
||||
await waitFor(element(by.id('messagebox-input-thread'))).toExist().withTimeout(5000);
|
||||
await element(by.id('messagebox-input-thread')).typeText(messageText);
|
||||
await element(by.id('messagebox-send-to-channel')).tap();
|
||||
await element(by.id('messagebox-send-message')).tap();
|
||||
|
@ -137,6 +139,7 @@ describe('Threads', () => {
|
|||
await element(by.id(`message-thread-replied-on-${ thread }`)).tap();
|
||||
await waitFor(element(by.id(`room-view-title-${ thread }`))).toExist().withTimeout(5000);
|
||||
await expect(element(by.id(`room-view-title-${ thread }`))).toExist();
|
||||
await sleep(2000);
|
||||
await tapBack();
|
||||
});
|
||||
|
||||
|
@ -144,7 +147,6 @@ describe('Threads', () => {
|
|||
await waitFor(element(by.id('room-view-header-threads'))).toExist().withTimeout(1000);
|
||||
await element(by.id('room-view-header-threads')).tap();
|
||||
await waitFor(element(by.id('thread-messages-view'))).toExist().withTimeout(5000);
|
||||
await expect(element(by.id('thread-messages-view'))).toExist();
|
||||
await element(by.id(`thread-messages-view-${ thread }`)).atIndex(0).tap();
|
||||
await waitFor(element(by.id(`room-view-title-${ thread }`))).toExist().withTimeout(5000);
|
||||
await expect(element(by.id(`room-view-title-${ thread }`))).toExist();
|
||||
|
|
|
@ -26,7 +26,7 @@ async function clearCache() {
|
|||
|
||||
async function waitForLoading() {
|
||||
await waitFor(element(by.id('loading'))).toBeVisible().withTimeout(5000);
|
||||
await waitFor(element(by.id('loading'))).toBeNotVisible().withTimeout(5000);
|
||||
await waitFor(element(by.id('loading'))).toBeNotVisible().withTimeout(10000);
|
||||
}
|
||||
|
||||
describe('Room', () => {
|
||||
|
@ -41,7 +41,7 @@ describe('Room', () => {
|
|||
await waitFor(element(by.label('Quote first message'))).toExist().withTimeout(5000);
|
||||
await element(by.label('1')).atIndex(0).tap();
|
||||
await waitForLoading();
|
||||
await expect(element(by.label('1')).atIndex(0)).toExist();
|
||||
await waitFor(element(by.label('1')).atIndex(0)).toExist().withTimeout(10000);
|
||||
await expect(element(by.label('2'))).toExist();
|
||||
});
|
||||
|
||||
|
@ -84,7 +84,7 @@ describe('Room', () => {
|
|||
|
||||
it('should load newer and older messages', async() => {
|
||||
await element(by.id('room-view-messages')).atIndex(0).swipe('down', 'fast', 0.8);
|
||||
await waitFor(element(by.label('5'))).toExist().withTimeout(5000);
|
||||
await waitFor(element(by.label('5'))).toExist().withTimeout(10000);
|
||||
await waitFor(element(by.label('Load Older'))).toExist().withTimeout(5000);
|
||||
await element(by.label('Load Older')).atIndex(0).tap();
|
||||
await waitFor(element(by.label('4'))).toExist().withTimeout(5000);
|
||||
|
|
|
@ -37,6 +37,7 @@ describe('Create team screen', () => {
|
|||
it('should get invalid team name', async() => {
|
||||
await element(by.id('create-channel-name')).typeText(`${ data.teams.private.name }`);
|
||||
await element(by.id('create-channel-submit')).tap();
|
||||
await waitFor(element(by.text('OK'))).toBeVisible().withTimeout(5000);
|
||||
await element(by.text('OK')).tap();
|
||||
});
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
source "https://rubygems.org"
|
||||
gem 'fastlane'
|
||||
|
||||
gem "cocoapods"
|
||||
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
|
||||
eval_gemfile(plugins_path) if File.exist?(plugins_path)
|
||||
|
|
204
ios/Gemfile.lock
204
ios/Gemfile.lock
|
@ -1,57 +1,122 @@
|
|||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
CFPropertyList (3.0.2)
|
||||
addressable (2.7.0)
|
||||
CFPropertyList (3.0.3)
|
||||
activesupport (5.2.6)
|
||||
concurrent-ruby (~> 1.0, >= 1.0.2)
|
||||
i18n (>= 0.7, < 2)
|
||||
minitest (~> 5.1)
|
||||
tzinfo (~> 1.1)
|
||||
addressable (2.8.0)
|
||||
public_suffix (>= 2.0.2, < 5.0)
|
||||
algoliasearch (1.27.5)
|
||||
httpclient (~> 2.8, >= 2.8.3)
|
||||
json (>= 1.5.1)
|
||||
artifactory (3.0.15)
|
||||
atomos (0.1.3)
|
||||
aws-eventstream (1.1.0)
|
||||
aws-partitions (1.381.0)
|
||||
aws-sdk-core (3.109.1)
|
||||
aws-eventstream (1.1.1)
|
||||
aws-partitions (1.478.0)
|
||||
aws-sdk-core (3.117.0)
|
||||
aws-eventstream (~> 1, >= 1.0.2)
|
||||
aws-partitions (~> 1, >= 1.239.0)
|
||||
aws-sigv4 (~> 1.1)
|
||||
jmespath (~> 1.0)
|
||||
aws-sdk-kms (1.39.0)
|
||||
aws-sdk-core (~> 3, >= 3.109.0)
|
||||
aws-sdk-kms (1.44.0)
|
||||
aws-sdk-core (~> 3, >= 3.112.0)
|
||||
aws-sigv4 (~> 1.1)
|
||||
aws-sdk-s3 (1.83.0)
|
||||
aws-sdk-core (~> 3, >= 3.109.0)
|
||||
aws-sdk-s3 (1.96.1)
|
||||
aws-sdk-core (~> 3, >= 3.112.0)
|
||||
aws-sdk-kms (~> 1)
|
||||
aws-sigv4 (~> 1.1)
|
||||
aws-sigv4 (1.2.2)
|
||||
aws-sigv4 (1.2.4)
|
||||
aws-eventstream (~> 1, >= 1.0.2)
|
||||
babosa (1.0.4)
|
||||
claide (1.0.3)
|
||||
cocoapods (1.10.1)
|
||||
addressable (~> 2.6)
|
||||
claide (>= 1.0.2, < 2.0)
|
||||
cocoapods-core (= 1.10.1)
|
||||
cocoapods-deintegrate (>= 1.0.3, < 2.0)
|
||||
cocoapods-downloader (>= 1.4.0, < 2.0)
|
||||
cocoapods-plugins (>= 1.0.0, < 2.0)
|
||||
cocoapods-search (>= 1.0.0, < 2.0)
|
||||
cocoapods-trunk (>= 1.4.0, < 2.0)
|
||||
cocoapods-try (>= 1.1.0, < 2.0)
|
||||
colored2 (~> 3.1)
|
||||
escape (~> 0.0.4)
|
||||
fourflusher (>= 2.3.0, < 3.0)
|
||||
gh_inspector (~> 1.0)
|
||||
molinillo (~> 0.6.6)
|
||||
nap (~> 1.0)
|
||||
ruby-macho (~> 1.4)
|
||||
xcodeproj (>= 1.19.0, < 2.0)
|
||||
cocoapods-core (1.10.1)
|
||||
activesupport (> 5.0, < 6)
|
||||
addressable (~> 2.6)
|
||||
algoliasearch (~> 1.0)
|
||||
concurrent-ruby (~> 1.1)
|
||||
fuzzy_match (~> 2.0.4)
|
||||
nap (~> 1.0)
|
||||
netrc (~> 0.11)
|
||||
public_suffix
|
||||
typhoeus (~> 1.0)
|
||||
cocoapods-deintegrate (1.0.4)
|
||||
cocoapods-downloader (1.4.0)
|
||||
cocoapods-plugins (1.0.0)
|
||||
nap
|
||||
cocoapods-search (1.0.0)
|
||||
cocoapods-trunk (1.5.0)
|
||||
nap (>= 0.8, < 2.0)
|
||||
netrc (~> 0.11)
|
||||
cocoapods-try (1.2.0)
|
||||
colored (1.2)
|
||||
colored2 (3.1.2)
|
||||
commander-fastlane (4.4.6)
|
||||
highline (~> 1.7.2)
|
||||
commander (4.6.0)
|
||||
highline (~> 2.0.0)
|
||||
concurrent-ruby (1.1.9)
|
||||
declarative (0.0.20)
|
||||
declarative-option (0.1.0)
|
||||
digest-crc (0.6.1)
|
||||
rake (~> 13.0)
|
||||
digest-crc (0.6.3)
|
||||
rake (>= 12.0.0, < 14.0.0)
|
||||
domain_name (0.5.20190701)
|
||||
unf (>= 0.0.5, < 1.0.0)
|
||||
dotenv (2.7.6)
|
||||
emoji_regex (3.0.0)
|
||||
excon (0.76.0)
|
||||
faraday (1.0.1)
|
||||
emoji_regex (3.2.2)
|
||||
escape (0.0.4)
|
||||
ethon (0.14.0)
|
||||
ffi (>= 1.15.0)
|
||||
excon (0.84.0)
|
||||
faraday (1.5.1)
|
||||
faraday-em_http (~> 1.0)
|
||||
faraday-em_synchrony (~> 1.0)
|
||||
faraday-excon (~> 1.1)
|
||||
faraday-httpclient (~> 1.0.1)
|
||||
faraday-net_http (~> 1.0)
|
||||
faraday-net_http_persistent (~> 1.1)
|
||||
faraday-patron (~> 1.0)
|
||||
multipart-post (>= 1.2, < 3)
|
||||
ruby2_keywords (>= 0.0.4)
|
||||
faraday-cookie_jar (0.0.7)
|
||||
faraday (>= 0.8.0)
|
||||
http-cookie (~> 1.0.0)
|
||||
faraday-em_http (1.0.0)
|
||||
faraday-em_synchrony (1.0.0)
|
||||
faraday-excon (1.1.0)
|
||||
faraday-httpclient (1.0.1)
|
||||
faraday-net_http (1.0.1)
|
||||
faraday-net_http_persistent (1.2.0)
|
||||
faraday-patron (1.0.0)
|
||||
faraday_middleware (1.0.0)
|
||||
faraday (~> 1.0)
|
||||
fastimage (2.2.0)
|
||||
fastlane (2.163.0)
|
||||
fastimage (2.2.4)
|
||||
fastlane (2.187.0)
|
||||
CFPropertyList (>= 2.3, < 4.0.0)
|
||||
addressable (>= 2.3, < 3.0.0)
|
||||
artifactory (~> 3.0)
|
||||
aws-sdk-s3 (~> 1.0)
|
||||
babosa (>= 1.0.3, < 2.0.0)
|
||||
bundler (>= 1.12.0, < 3.0.0)
|
||||
colored
|
||||
commander-fastlane (>= 4.4.6, < 5.0.0)
|
||||
commander (~> 4.6)
|
||||
dotenv (>= 2.1.1, < 3.0.0)
|
||||
emoji_regex (>= 0.1, < 4.0)
|
||||
excon (>= 0.71.0, < 1.0.0)
|
||||
|
@ -60,18 +125,19 @@ GEM
|
|||
faraday_middleware (~> 1.0)
|
||||
fastimage (>= 2.1.0, < 3.0.0)
|
||||
gh_inspector (>= 1.1.2, < 2.0.0)
|
||||
google-api-client (>= 0.37.0, < 0.39.0)
|
||||
google-cloud-storage (>= 1.15.0, < 2.0.0)
|
||||
highline (>= 1.7.2, < 2.0.0)
|
||||
google-apis-androidpublisher_v3 (~> 0.1)
|
||||
google-apis-playcustomapp_v1 (~> 0.1)
|
||||
google-cloud-storage (~> 1.31)
|
||||
highline (~> 2.0)
|
||||
json (< 3.0.0)
|
||||
jwt (>= 2.1.0, < 3)
|
||||
mini_magick (>= 4.9.4, < 5.0.0)
|
||||
multipart-post (~> 2.0.0)
|
||||
naturally (~> 2.2)
|
||||
plist (>= 3.1.0, < 4.0.0)
|
||||
rubyzip (>= 2.0.0, < 3.0.0)
|
||||
security (= 0.1.3)
|
||||
simctl (~> 1.6.3)
|
||||
slack-notifier (>= 2.0.0, < 3.0.0)
|
||||
terminal-notifier (>= 2.0.0, < 3.0.0)
|
||||
terminal-table (>= 1.4.5, < 2.0.0)
|
||||
tty-screen (>= 0.6.3, < 1.0.0)
|
||||
|
@ -80,62 +146,84 @@ GEM
|
|||
xcodeproj (>= 1.13.0, < 2.0.0)
|
||||
xcpretty (~> 0.3.0)
|
||||
xcpretty-travis-formatter (>= 0.0.3)
|
||||
ffi (1.15.3)
|
||||
fourflusher (2.3.1)
|
||||
fuzzy_match (2.0.4)
|
||||
gh_inspector (1.1.3)
|
||||
google-api-client (0.38.0)
|
||||
google-apis-androidpublisher_v3 (0.8.0)
|
||||
google-apis-core (>= 0.4, < 2.a)
|
||||
google-apis-core (0.4.0)
|
||||
addressable (~> 2.5, >= 2.5.1)
|
||||
googleauth (~> 0.9)
|
||||
httpclient (>= 2.8.1, < 3.0)
|
||||
googleauth (>= 0.16.2, < 2.a)
|
||||
httpclient (>= 2.8.1, < 3.a)
|
||||
mini_mime (~> 1.0)
|
||||
representable (~> 3.0)
|
||||
retriable (>= 2.0, < 4.0)
|
||||
signet (~> 0.12)
|
||||
google-cloud-core (1.5.0)
|
||||
retriable (>= 2.0, < 4.a)
|
||||
rexml
|
||||
webrick
|
||||
google-apis-iamcredentials_v1 (0.6.0)
|
||||
google-apis-core (>= 0.4, < 2.a)
|
||||
google-apis-playcustomapp_v1 (0.5.0)
|
||||
google-apis-core (>= 0.4, < 2.a)
|
||||
google-apis-storage_v1 (0.6.0)
|
||||
google-apis-core (>= 0.4, < 2.a)
|
||||
google-cloud-core (1.6.0)
|
||||
google-cloud-env (~> 1.0)
|
||||
google-cloud-errors (~> 1.0)
|
||||
google-cloud-env (1.4.0)
|
||||
google-cloud-env (1.5.0)
|
||||
faraday (>= 0.17.3, < 2.0)
|
||||
google-cloud-errors (1.0.1)
|
||||
google-cloud-storage (1.29.1)
|
||||
google-cloud-errors (1.1.0)
|
||||
google-cloud-storage (1.34.1)
|
||||
addressable (~> 2.5)
|
||||
digest-crc (~> 0.4)
|
||||
google-api-client (~> 0.33)
|
||||
google-cloud-core (~> 1.2)
|
||||
googleauth (~> 0.9)
|
||||
google-apis-iamcredentials_v1 (~> 0.1)
|
||||
google-apis-storage_v1 (~> 0.1)
|
||||
google-cloud-core (~> 1.6)
|
||||
googleauth (>= 0.16.2, < 2.a)
|
||||
mini_mime (~> 1.0)
|
||||
googleauth (0.14.0)
|
||||
googleauth (0.16.2)
|
||||
faraday (>= 0.17.3, < 2.0)
|
||||
jwt (>= 1.4, < 3.0)
|
||||
memoist (~> 0.16)
|
||||
multi_json (~> 1.11)
|
||||
os (>= 0.9, < 2.0)
|
||||
signet (~> 0.14)
|
||||
highline (1.7.10)
|
||||
http-cookie (1.0.3)
|
||||
highline (2.0.3)
|
||||
http-cookie (1.0.4)
|
||||
domain_name (~> 0.5)
|
||||
httpclient (2.8.3)
|
||||
i18n (1.8.10)
|
||||
concurrent-ruby (~> 1.0)
|
||||
jmespath (1.4.0)
|
||||
json (2.3.1)
|
||||
jwt (2.2.2)
|
||||
json (2.5.1)
|
||||
jwt (2.2.3)
|
||||
memoist (0.16.2)
|
||||
mini_magick (4.10.1)
|
||||
mini_mime (1.0.2)
|
||||
mini_magick (4.11.0)
|
||||
mini_mime (1.1.0)
|
||||
minitest (5.14.4)
|
||||
molinillo (0.6.6)
|
||||
multi_json (1.15.0)
|
||||
multipart-post (2.0.0)
|
||||
nanaimo (0.3.0)
|
||||
naturally (2.2.0)
|
||||
nap (1.1.0)
|
||||
naturally (2.2.1)
|
||||
netrc (0.11.0)
|
||||
os (1.1.1)
|
||||
plist (3.5.0)
|
||||
plist (3.6.0)
|
||||
public_suffix (4.0.6)
|
||||
rake (13.0.1)
|
||||
representable (3.0.4)
|
||||
rake (13.0.6)
|
||||
representable (3.1.1)
|
||||
declarative (< 0.1.0)
|
||||
declarative-option (< 0.2.0)
|
||||
trailblazer-option (>= 0.1.1, < 0.2.0)
|
||||
uber (< 0.2.0)
|
||||
retriable (3.1.2)
|
||||
rexml (3.2.5)
|
||||
rouge (2.0.7)
|
||||
rubyzip (2.3.0)
|
||||
ruby-macho (1.4.0)
|
||||
ruby2_keywords (0.0.4)
|
||||
rubyzip (2.3.2)
|
||||
security (0.1.3)
|
||||
signet (0.14.0)
|
||||
signet (0.15.0)
|
||||
addressable (~> 2.3)
|
||||
faraday (>= 0.17.3, < 2.0)
|
||||
jwt (>= 1.5, < 3.0)
|
||||
|
@ -143,35 +231,43 @@ GEM
|
|||
simctl (1.6.8)
|
||||
CFPropertyList
|
||||
naturally
|
||||
slack-notifier (2.3.2)
|
||||
terminal-notifier (2.0.0)
|
||||
terminal-table (1.8.0)
|
||||
unicode-display_width (~> 1.1, >= 1.1.1)
|
||||
thread_safe (0.3.6)
|
||||
trailblazer-option (0.1.1)
|
||||
tty-cursor (0.7.1)
|
||||
tty-screen (0.8.1)
|
||||
tty-spinner (0.9.3)
|
||||
tty-cursor (~> 0.7)
|
||||
typhoeus (1.4.0)
|
||||
ethon (>= 0.9.0)
|
||||
tzinfo (1.2.9)
|
||||
thread_safe (~> 0.1)
|
||||
uber (0.1.0)
|
||||
unf (0.1.4)
|
||||
unf_ext
|
||||
unf_ext (0.0.7.7)
|
||||
unicode-display_width (1.7.0)
|
||||
webrick (1.7.0)
|
||||
word_wrap (1.0.0)
|
||||
xcodeproj (1.19.0)
|
||||
xcodeproj (1.20.0)
|
||||
CFPropertyList (>= 2.3.3, < 4.0)
|
||||
atomos (~> 0.1.3)
|
||||
claide (>= 1.0.2, < 2.0)
|
||||
colored2 (~> 3.1)
|
||||
nanaimo (~> 0.3.0)
|
||||
rexml (~> 3.2.4)
|
||||
xcpretty (0.3.0)
|
||||
rouge (~> 2.0.7)
|
||||
xcpretty-travis-formatter (1.0.0)
|
||||
xcpretty-travis-formatter (1.0.1)
|
||||
xcpretty (~> 0.2, >= 0.0.7)
|
||||
|
||||
PLATFORMS
|
||||
ruby
|
||||
|
||||
DEPENDENCIES
|
||||
cocoapods
|
||||
fastlane
|
||||
|
||||
BUNDLED WITH
|
||||
|
|
12
ios/Podfile
12
ios/Podfile
|
@ -6,8 +6,11 @@ require_relative '../node_modules/react-native-unimodules/cocoapods.rb'
|
|||
def all_pods
|
||||
config = use_native_modules!
|
||||
use_unimodules!
|
||||
use_react_native!(:path => config["reactNativePath"])
|
||||
use_flipper!
|
||||
use_react_native!(
|
||||
:path => config[:reactNativePath],
|
||||
:hermes_enabled => true
|
||||
)
|
||||
use_flipper!()
|
||||
end
|
||||
|
||||
abstract_target 'defaults' do
|
||||
|
@ -30,7 +33,7 @@ target 'ShareRocketChatRN' do
|
|||
pod 'UMImageLoaderInterface', :path=> "../node_modules/unimodules-image-loader-interface/ios"
|
||||
pod 'UMReactNativeAdapter', :path=> "../node_modules/@unimodules/react-native-adapter/ios"
|
||||
|
||||
use_react_native!(:path => '../node_modules/react-native')
|
||||
use_react_native!(:path => '../node_modules/react-native', :hermes_enabled => true)
|
||||
|
||||
pod 'RNFBApp', :path => '../node_modules/@react-native-firebase/app'
|
||||
pod 'RNFBAnalytics', :path => '../node_modules/@react-native-firebase/analytics'
|
||||
|
@ -67,7 +70,8 @@ post_install do |installer|
|
|||
installer.pods_project.targets.each do |target|
|
||||
target.build_configurations.each do |config|
|
||||
config.build_settings['APPLICATION_EXTENSION_API_ONLY'] = 'NO'
|
||||
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '11.0'
|
||||
end
|
||||
end
|
||||
flipper_post_install(installer)
|
||||
react_native_post_install(installer)
|
||||
end
|
717
ios/Podfile.lock
717
ios/Podfile.lock
File diff suppressed because it is too large
Load Diff
|
@ -1,35 +0,0 @@
|
|||
This library is in the public domain.
|
||||
However, not all organizations are allowed to use such a license.
|
||||
For example, Germany doesn't recognize the Public Domain and one is not allowed to use libraries under such license (or similar).
|
||||
|
||||
Thus, the library is now dual licensed,
|
||||
and one is allowed to choose which license they would like to use.
|
||||
|
||||
##################################################
|
||||
License Option #1 :
|
||||
##################################################
|
||||
|
||||
Public Domain
|
||||
|
||||
##################################################
|
||||
License Option #2 :
|
||||
##################################################
|
||||
|
||||
Software License Agreement (BSD License)
|
||||
|
||||
Copyright (c) 2017, Deusty, LLC
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use of this software in source and binary forms,
|
||||
with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above
|
||||
copyright notice, this list of conditions and the
|
||||
following disclaimer.
|
||||
|
||||
* Neither the name of Deusty LLC nor the names of its
|
||||
contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior
|
||||
written permission of Deusty LLC.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -1,121 +0,0 @@
|
|||
# CocoaAsyncSocket
|
||||
[](https://travis-ci.org/robbiehanson/CocoaAsyncSocket) [](http://cocoadocs.org/docsets/CocoaAsyncSocket) [](https://github.com/Carthage/Carthage) [](http://cocoapods.org/?q=CocoaAsyncSocket) [](https://en.wikipedia.org/wiki/Public_domain)
|
||||
|
||||
|
||||
CocoaAsyncSocket provides easy-to-use and powerful asynchronous socket libraries for macOS, iOS, and tvOS. The classes are described below.
|
||||
|
||||
## Installation
|
||||
|
||||
#### CocoaPods
|
||||
|
||||
Install using [CocoaPods](https://cocoapods.org) by adding this line to your Podfile:
|
||||
|
||||
````ruby
|
||||
use_frameworks! # Add this if you are targeting iOS 8+ or using Swift
|
||||
pod 'CocoaAsyncSocket'
|
||||
````
|
||||
|
||||
#### Carthage
|
||||
|
||||
CocoaAsyncSocket is [Carthage](https://github.com/Carthage/Carthage) compatible. To include it add the following line to your `Cartfile`
|
||||
|
||||
```bash
|
||||
github "robbiehanson/CocoaAsyncSocket" "master"
|
||||
```
|
||||
|
||||
The project is currently configured to build for **iOS**, **tvOS** and **Mac**. After building with carthage the resultant frameworks will be stored in:
|
||||
|
||||
* `Carthage/Build/iOS/CocoaAsyncSocket.framework`
|
||||
* `Carthage/Build/tvOS/CocoaAsyncSocket.framework`
|
||||
* `Carthage/Build/Mac/CocoaAsyncSocket.framework`
|
||||
|
||||
Select the correct framework(s) and drag it into your project.
|
||||
|
||||
#### Swift Package Manager
|
||||
|
||||
Simply add the package dependency to your Package.swift and depend on "CocoaAsyncSocket" in the necessary targets:
|
||||
```swift
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/robbiehanson/CocoaAsyncSocket", from: "7.6.4")
|
||||
]
|
||||
```
|
||||
|
||||
#### Manual
|
||||
|
||||
You can also include it into your project by adding the source files directly, but you should probably be using a dependency manager to keep up to date.
|
||||
|
||||
### Importing
|
||||
|
||||
Using Objective-C:
|
||||
|
||||
```obj-c
|
||||
// When using Clang Modules:
|
||||
@import CocoaAsyncSocket;
|
||||
|
||||
// or when not:
|
||||
#import "GCDAsyncSocket.h" // for TCP
|
||||
#import "GCDAsyncUdpSocket.h" // for UDP
|
||||
```
|
||||
|
||||
Using Swift:
|
||||
|
||||
```swift
|
||||
import CocoaAsyncSocket
|
||||
```
|
||||
|
||||
## TCP
|
||||
|
||||
**GCDAsyncSocket** is a TCP/IP socket networking library built atop Grand Central Dispatch. Here are the key features available:
|
||||
|
||||
- Native Objective-C, fully self-contained in one class.<br/>
|
||||
_No need to muck around with sockets or streams. This class handles everything for you._
|
||||
|
||||
- Full delegate support<br/>
|
||||
_Errors, connections, read completions, write completions, progress, and disconnections all result in a call to your delegate method._
|
||||
|
||||
- Queued non-blocking reads and writes, with optional timeouts.<br/>
|
||||
_You tell it what to read or write, and it handles everything for you. Queueing, buffering, and searching for termination sequences within the stream - all handled for you automatically._
|
||||
|
||||
- Automatic socket acceptance.<br/>
|
||||
_Spin up a server socket, tell it to accept connections, and it will call you with new instances of itself for each connection._
|
||||
|
||||
- Support for TCP streams over IPv4 and IPv6.<br/>
|
||||
_Automatically connect to IPv4 or IPv6 hosts. Automatically accept incoming connections over both IPv4 and IPv6 with a single instance of this class. No more worrying about multiple sockets._
|
||||
|
||||
- Support for TLS / SSL<br/>
|
||||
_Secure your socket with ease using just a single method call. Available for both client and server sockets._
|
||||
|
||||
- Fully GCD based and Thread-Safe<br/>
|
||||
_It runs entirely within its own GCD dispatch_queue, and is completely thread-safe. Further, the delegate methods are all invoked asynchronously onto a dispatch_queue of your choosing. This means parallel operation of your socket code, and your delegate/processing code._
|
||||
|
||||
## UDP
|
||||
|
||||
**GCDAsyncUdpSocket** is a UDP/IP socket networking library built atop Grand Central Dispatch. Here are the key features available:
|
||||
|
||||
- Native Objective-C, fully self-contained in one class.<br/>
|
||||
_No need to muck around with low-level sockets. This class handles everything for you._
|
||||
|
||||
- Full delegate support.<br/>
|
||||
_Errors, send completions, receive completions, and disconnections all result in a call to your delegate method._
|
||||
|
||||
- Queued non-blocking send and receive operations, with optional timeouts.<br/>
|
||||
_You tell it what to send or receive, and it handles everything for you. Queueing, buffering, waiting and checking errno - all handled for you automatically._
|
||||
|
||||
- Support for IPv4 and IPv6.<br/>
|
||||
_Automatically send/recv using IPv4 and/or IPv6. No more worrying about multiple sockets._
|
||||
|
||||
- Fully GCD based and Thread-Safe<br/>
|
||||
_It runs entirely within its own GCD dispatch_queue, and is completely thread-safe. Further, the delegate methods are all invoked asynchronously onto a dispatch_queue of your choosing. This means parallel operation of your socket code, and your delegate/processing code._
|
||||
|
||||
***
|
||||
|
||||
For those new(ish) to networking, it's recommended you **[read the wiki](https://github.com/robbiehanson/CocoaAsyncSocket/wiki)**.<br/>_Sockets might not work exactly like you think they do..._
|
||||
|
||||
**Still got questions?** Try the **[CocoaAsyncSocket Mailing List](https://groups.google.com/group/cocoaasyncsocket)**.
|
||||
***
|
||||
|
||||
Love the project? Wanna buy me a ☕️ ? (or a 🍺 😀 ):
|
||||
|
||||
[](https://onename.com/robbiehanson)
|
||||
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2M8C699FQ8AW2)
|
||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -1,19 +0,0 @@
|
|||
Copyright (c) 2018 99789999@qq.com <99789999@qq.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
|
@ -1,29 +0,0 @@
|
|||
# CocoaLibEvent
|
||||
|
||||
[](https://travis-ci.org/99789999@qq.com/CocoaLibEvent)
|
||||
[](http://cocoapods.org/pods/CocoaLibEvent)
|
||||
[](http://cocoapods.org/pods/CocoaLibEvent)
|
||||
[](http://cocoapods.org/pods/CocoaLibEvent)
|
||||
|
||||
## Example
|
||||
|
||||
To run the example project, clone the repo, and run `pod install` from the Example directory first.
|
||||
|
||||
## Requirements
|
||||
|
||||
## Installation
|
||||
|
||||
CocoaLibEvent is available through [CocoaPods](http://cocoapods.org). To install
|
||||
it, simply add the following line to your Podfile:
|
||||
|
||||
```ruby
|
||||
pod 'CocoaLibEvent'
|
||||
```
|
||||
|
||||
## Author
|
||||
|
||||
99789999@qq.com, 99789999@qq.com
|
||||
|
||||
## License
|
||||
|
||||
CocoaLibEvent is available under the MIT license. See the LICENSE file for more info.
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -1,45 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT1_EVDNS_H_INCLUDED_
|
||||
#define EVENT1_EVDNS_H_INCLUDED_
|
||||
|
||||
/** @file evdns.h
|
||||
|
||||
A dns subsystem for Libevent.
|
||||
|
||||
The <evdns.h> header is deprecated in Libevent 2.0 and later; please
|
||||
use <event2/evdns.h> instead. Depending on what functionality you
|
||||
need, you may also want to include more of the other <event2/...>
|
||||
headers.
|
||||
*/
|
||||
|
||||
#include <event.h>
|
||||
#include <event2/dns.h>
|
||||
#include <event2/dns_compat.h>
|
||||
#include <event2/dns_struct.h>
|
||||
|
||||
#endif /* EVENT1_EVDNS_H_INCLUDED_ */
|
|
@ -1,83 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT1_EVENT_H_INCLUDED_
|
||||
#define EVENT1_EVENT_H_INCLUDED_
|
||||
|
||||
/** @file event.h
|
||||
|
||||
A library for writing event-driven network servers.
|
||||
|
||||
The <event.h> header is deprecated in Libevent 2.0 and later; please
|
||||
use <event2/event.h> instead. Depending on what functionality you
|
||||
need, you may also want to include more of the other event2/
|
||||
headers.
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
#ifdef EVENT__HAVE_SYS_TYPES_H
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_SYS_TIME_H
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_STDINT_H
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
#include <stdarg.h>
|
||||
|
||||
/* For int types. */
|
||||
#include <evutil.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <winsock2.h>
|
||||
#include <windows.h>
|
||||
#undef WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
|
||||
#include <event2/event_struct.h>
|
||||
#include <event2/event.h>
|
||||
#include <event2/event_compat.h>
|
||||
#include <event2/buffer.h>
|
||||
#include <event2/buffer_compat.h>
|
||||
#include <event2/bufferevent.h>
|
||||
#include <event2/bufferevent_struct.h>
|
||||
#include <event2/bufferevent_compat.h>
|
||||
#include <event2/tag.h>
|
||||
#include <event2/tag_compat.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT1_EVENT_H_INCLUDED_ */
|
File diff suppressed because it is too large
Load Diff
|
@ -1,115 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef EVENT2_BUFFER_COMPAT_H_INCLUDED_
|
||||
#define EVENT2_BUFFER_COMPAT_H_INCLUDED_
|
||||
|
||||
#include <event2/visibility.h>
|
||||
|
||||
/** @file event2/buffer_compat.h
|
||||
|
||||
Obsolete and deprecated versions of the functions in buffer.h: provided
|
||||
only for backward compatibility.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
Obsolete alias for evbuffer_readln(buffer, NULL, EVBUFFER_EOL_ANY).
|
||||
|
||||
@deprecated This function is deprecated because its behavior is not correct
|
||||
for almost any protocol, and also because it's wholly subsumed by
|
||||
evbuffer_readln().
|
||||
|
||||
@param buffer the evbuffer to read from
|
||||
@return pointer to a single line, or NULL if an error occurred
|
||||
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
char *evbuffer_readline(struct evbuffer *buffer);
|
||||
|
||||
/** Type definition for a callback that is invoked whenever data is added or
|
||||
removed from an evbuffer.
|
||||
|
||||
An evbuffer may have one or more callbacks set at a time. The order
|
||||
in which they are executed is undefined.
|
||||
|
||||
A callback function may add more callbacks, or remove itself from the
|
||||
list of callbacks, or add or remove data from the buffer. It may not
|
||||
remove another callback from the list.
|
||||
|
||||
If a callback adds or removes data from the buffer or from another
|
||||
buffer, this can cause a recursive invocation of your callback or
|
||||
other callbacks. If you ask for an infinite loop, you might just get
|
||||
one: watch out!
|
||||
|
||||
@param buffer the buffer whose size has changed
|
||||
@param old_len the previous length of the buffer
|
||||
@param new_len the current length of the buffer
|
||||
@param arg a pointer to user data
|
||||
*/
|
||||
typedef void (*evbuffer_cb)(struct evbuffer *buffer, size_t old_len, size_t new_len, void *arg);
|
||||
|
||||
/**
|
||||
Replace all callbacks on an evbuffer with a single new callback, or
|
||||
remove them.
|
||||
|
||||
Subsequent calls to evbuffer_setcb() replace callbacks set by previous
|
||||
calls. Setting the callback to NULL removes any previously set callback.
|
||||
|
||||
@deprecated This function is deprecated because it clears all previous
|
||||
callbacks set on the evbuffer, which can cause confusing behavior if
|
||||
multiple parts of the code all want to add their own callbacks on a
|
||||
buffer. Instead, use evbuffer_add(), evbuffer_del(), and
|
||||
evbuffer_setflags() to manage your own evbuffer callbacks without
|
||||
interfering with callbacks set by others.
|
||||
|
||||
@param buffer the evbuffer to be monitored
|
||||
@param cb the callback function to invoke when the evbuffer is modified,
|
||||
or NULL to remove all callbacks.
|
||||
@param cbarg an argument to be provided to the callback function
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evbuffer_setcb(struct evbuffer *buffer, evbuffer_cb cb, void *cbarg);
|
||||
|
||||
|
||||
/**
|
||||
Find a string within an evbuffer.
|
||||
|
||||
@param buffer the evbuffer to be searched
|
||||
@param what the string to be searched for
|
||||
@param len the length of the search string
|
||||
@return a pointer to the beginning of the search string, or NULL if the search failed.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
unsigned char *evbuffer_find(struct evbuffer *buffer, const unsigned char *what, size_t len);
|
||||
|
||||
/** deprecated in favor of calling the functions directly */
|
||||
#define EVBUFFER_LENGTH(x) evbuffer_get_length(x)
|
||||
/** deprecated in favor of calling the functions directly */
|
||||
#define EVBUFFER_DATA(x) evbuffer_pullup((x), -1)
|
||||
|
||||
#endif
|
||||
|
File diff suppressed because it is too large
Load Diff
|
@ -1,100 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2007-2012 Niels Provos, Nick Mathewson
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_BUFFEREVENT_COMPAT_H_INCLUDED_
|
||||
#define EVENT2_BUFFEREVENT_COMPAT_H_INCLUDED_
|
||||
|
||||
#define evbuffercb bufferevent_data_cb
|
||||
#define everrorcb bufferevent_event_cb
|
||||
|
||||
/**
|
||||
Create a new bufferevent for an fd.
|
||||
|
||||
This function is deprecated. Use bufferevent_socket_new and
|
||||
bufferevent_set_callbacks instead.
|
||||
|
||||
Libevent provides an abstraction on top of the regular event callbacks.
|
||||
This abstraction is called a buffered event. A buffered event provides
|
||||
input and output buffers that get filled and drained automatically. The
|
||||
user of a buffered event no longer deals directly with the I/O, but
|
||||
instead is reading from input and writing to output buffers.
|
||||
|
||||
Once initialized, the bufferevent structure can be used repeatedly with
|
||||
bufferevent_enable() and bufferevent_disable().
|
||||
|
||||
When read enabled the bufferevent will try to read from the file descriptor
|
||||
and call the read callback. The write callback is executed whenever the
|
||||
output buffer is drained below the write low watermark, which is 0 by
|
||||
default.
|
||||
|
||||
If multiple bases are in use, bufferevent_base_set() must be called before
|
||||
enabling the bufferevent for the first time.
|
||||
|
||||
@deprecated This function is deprecated because it uses the current
|
||||
event base, and as such can be error prone for multithreaded programs.
|
||||
Use bufferevent_socket_new() instead.
|
||||
|
||||
@param fd the file descriptor from which data is read and written to.
|
||||
This file descriptor is not allowed to be a pipe(2).
|
||||
@param readcb callback to invoke when there is data to be read, or NULL if
|
||||
no callback is desired
|
||||
@param writecb callback to invoke when the file descriptor is ready for
|
||||
writing, or NULL if no callback is desired
|
||||
@param errorcb callback to invoke when there is an error on the file
|
||||
descriptor
|
||||
@param cbarg an argument that will be supplied to each of the callbacks
|
||||
(readcb, writecb, and errorcb)
|
||||
@return a pointer to a newly allocated bufferevent struct, or NULL if an
|
||||
error occurred
|
||||
@see bufferevent_base_set(), bufferevent_free()
|
||||
*/
|
||||
struct bufferevent *bufferevent_new(evutil_socket_t fd,
|
||||
evbuffercb readcb, evbuffercb writecb, everrorcb errorcb, void *cbarg);
|
||||
|
||||
|
||||
/**
|
||||
Set the read and write timeout for a buffered event.
|
||||
|
||||
@param bufev the bufferevent to be modified
|
||||
@param timeout_read the read timeout
|
||||
@param timeout_write the write timeout
|
||||
*/
|
||||
void bufferevent_settimeout(struct bufferevent *bufev,
|
||||
int timeout_read, int timeout_write);
|
||||
|
||||
#define EVBUFFER_READ BEV_EVENT_READING
|
||||
#define EVBUFFER_WRITE BEV_EVENT_WRITING
|
||||
#define EVBUFFER_EOF BEV_EVENT_EOF
|
||||
#define EVBUFFER_ERROR BEV_EVENT_ERROR
|
||||
#define EVBUFFER_TIMEOUT BEV_EVENT_TIMEOUT
|
||||
|
||||
/** macro for getting access to the input buffer of a bufferevent */
|
||||
#define EVBUFFER_INPUT(x) bufferevent_get_input(x)
|
||||
/** macro for getting access to the output buffer of a bufferevent */
|
||||
#define EVBUFFER_OUTPUT(x) bufferevent_get_output(x)
|
||||
|
||||
#endif
|
|
@ -1,134 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_BUFFEREVENT_SSL_H_INCLUDED_
|
||||
#define EVENT2_BUFFEREVENT_SSL_H_INCLUDED_
|
||||
|
||||
/** @file event2/bufferevent_ssl.h
|
||||
|
||||
OpenSSL support for bufferevents.
|
||||
*/
|
||||
#include <event2/visibility.h>
|
||||
#include <event2/event-config.h>
|
||||
#include <event2/bufferevent.h>
|
||||
#include <event2/util.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* This is what openssl's SSL objects are underneath. */
|
||||
struct ssl_st;
|
||||
|
||||
/**
|
||||
The state of an SSL object to be used when creating a new
|
||||
SSL bufferevent.
|
||||
*/
|
||||
enum bufferevent_ssl_state {
|
||||
BUFFEREVENT_SSL_OPEN = 0,
|
||||
BUFFEREVENT_SSL_CONNECTING = 1,
|
||||
BUFFEREVENT_SSL_ACCEPTING = 2
|
||||
};
|
||||
|
||||
#if defined(EVENT__HAVE_OPENSSL) || defined(EVENT_IN_DOXYGEN_)
|
||||
/**
|
||||
Create a new SSL bufferevent to send its data over another bufferevent.
|
||||
|
||||
@param base An event_base to use to detect reading and writing. It
|
||||
must also be the base for the underlying bufferevent.
|
||||
@param underlying A socket to use for this SSL
|
||||
@param ssl A SSL* object from openssl.
|
||||
@param state The current state of the SSL connection
|
||||
@param options One or more bufferevent_options
|
||||
@return A new bufferevent on success, or NULL on failure
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct bufferevent *
|
||||
bufferevent_openssl_filter_new(struct event_base *base,
|
||||
struct bufferevent *underlying,
|
||||
struct ssl_st *ssl,
|
||||
enum bufferevent_ssl_state state,
|
||||
int options);
|
||||
|
||||
/**
|
||||
Create a new SSL bufferevent to send its data over an SSL * on a socket.
|
||||
|
||||
@param base An event_base to use to detect reading and writing
|
||||
@param fd A socket to use for this SSL
|
||||
@param ssl A SSL* object from openssl.
|
||||
@param state The current state of the SSL connection
|
||||
@param options One or more bufferevent_options
|
||||
@return A new bufferevent on success, or NULL on failure.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct bufferevent *
|
||||
bufferevent_openssl_socket_new(struct event_base *base,
|
||||
evutil_socket_t fd,
|
||||
struct ssl_st *ssl,
|
||||
enum bufferevent_ssl_state state,
|
||||
int options);
|
||||
|
||||
/** Control how to report dirty SSL shutdowns.
|
||||
|
||||
If the peer (or the network, or an attacker) closes the TCP
|
||||
connection before closing the SSL channel, and the protocol is SSL >= v3,
|
||||
this is a "dirty" shutdown. If allow_dirty_shutdown is 0 (default),
|
||||
this is reported as BEV_EVENT_ERROR.
|
||||
|
||||
If instead allow_dirty_shutdown=1, a dirty shutdown is reported as
|
||||
BEV_EVENT_EOF.
|
||||
|
||||
(Note that if the protocol is < SSLv3, you will always receive
|
||||
BEV_EVENT_EOF, since SSL 2 and earlier cannot distinguish a secure
|
||||
connection close from a dirty one. This is one reason (among many)
|
||||
not to use SSL 2.)
|
||||
*/
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int bufferevent_openssl_get_allow_dirty_shutdown(struct bufferevent *bev);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void bufferevent_openssl_set_allow_dirty_shutdown(struct bufferevent *bev,
|
||||
int allow_dirty_shutdown);
|
||||
|
||||
/** Return the underlying openssl SSL * object for an SSL bufferevent. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct ssl_st *
|
||||
bufferevent_openssl_get_ssl(struct bufferevent *bufev);
|
||||
|
||||
/** Tells a bufferevent to begin SSL renegotiation. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int bufferevent_ssl_renegotiate(struct bufferevent *bev);
|
||||
|
||||
/** Return the most recent OpenSSL error reported on an SSL bufferevent. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
unsigned long bufferevent_get_openssl_error(struct bufferevent *bev);
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_BUFFEREVENT_SSL_H_INCLUDED_ */
|
|
@ -1,116 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_BUFFEREVENT_STRUCT_H_INCLUDED_
|
||||
#define EVENT2_BUFFEREVENT_STRUCT_H_INCLUDED_
|
||||
|
||||
/** @file event2/bufferevent_struct.h
|
||||
|
||||
Data structures for bufferevents. Using these structures may hurt forward
|
||||
compatibility with later versions of Libevent: be careful!
|
||||
|
||||
@deprecated Use of bufferevent_struct.h is completely deprecated; these
|
||||
structures are only exposed for backward compatibility with programs
|
||||
written before Libevent 2.0 that used them.
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
#ifdef EVENT__HAVE_SYS_TYPES_H
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_SYS_TIME_H
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
|
||||
/* For int types. */
|
||||
#include <event2/util.h>
|
||||
/* For struct event */
|
||||
#include <event2/event_struct.h>
|
||||
|
||||
struct event_watermark {
|
||||
size_t low;
|
||||
size_t high;
|
||||
};
|
||||
|
||||
/**
|
||||
Shared implementation of a bufferevent.
|
||||
|
||||
This type is exposed only because it was exposed in previous versions,
|
||||
and some people's code may rely on manipulating it. Otherwise, you
|
||||
should really not rely on the layout, size, or contents of this structure:
|
||||
it is fairly volatile, and WILL change in future versions of the code.
|
||||
**/
|
||||
struct bufferevent {
|
||||
/** Event base for which this bufferevent was created. */
|
||||
struct event_base *ev_base;
|
||||
/** Pointer to a table of function pointers to set up how this
|
||||
bufferevent behaves. */
|
||||
const struct bufferevent_ops *be_ops;
|
||||
|
||||
/** A read event that triggers when a timeout has happened or a socket
|
||||
is ready to read data. Only used by some subtypes of
|
||||
bufferevent. */
|
||||
struct event ev_read;
|
||||
/** A write event that triggers when a timeout has happened or a socket
|
||||
is ready to write data. Only used by some subtypes of
|
||||
bufferevent. */
|
||||
struct event ev_write;
|
||||
|
||||
/** An input buffer. Only the bufferevent is allowed to add data to
|
||||
this buffer, though the user is allowed to drain it. */
|
||||
struct evbuffer *input;
|
||||
|
||||
/** An input buffer. Only the bufferevent is allowed to drain data
|
||||
from this buffer, though the user is allowed to add it. */
|
||||
struct evbuffer *output;
|
||||
|
||||
struct event_watermark wm_read;
|
||||
struct event_watermark wm_write;
|
||||
|
||||
bufferevent_data_cb readcb;
|
||||
bufferevent_data_cb writecb;
|
||||
/* This should be called 'eventcb', but renaming it would break
|
||||
* backward compatibility */
|
||||
bufferevent_event_cb errorcb;
|
||||
void *cbarg;
|
||||
|
||||
struct timeval timeout_read;
|
||||
struct timeval timeout_write;
|
||||
|
||||
/** Events that are currently enabled: currently EV_READ and EV_WRITE
|
||||
are supported. */
|
||||
short enabled;
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_BUFFEREVENT_STRUCT_H_INCLUDED_ */
|
|
@ -1,717 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
/*
|
||||
* The original DNS code is due to Adam Langley with heavy
|
||||
* modifications by Nick Mathewson. Adam put his DNS software in the
|
||||
* public domain. You can find his original copyright below. Please,
|
||||
* aware that the code as part of Libevent is governed by the 3-clause
|
||||
* BSD license above.
|
||||
*
|
||||
* This software is Public Domain. To view a copy of the public domain dedication,
|
||||
* visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
|
||||
* Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
|
||||
*
|
||||
* I ask and expect, but do not require, that all derivative works contain an
|
||||
* attribution similar to:
|
||||
* Parts developed by Adam Langley <agl@imperialviolet.org>
|
||||
*
|
||||
* You may wish to replace the word "Parts" with something else depending on
|
||||
* the amount of original code.
|
||||
*
|
||||
* (Derivative works does not include programs which link against, run or include
|
||||
* the source verbatim in their source distributions)
|
||||
*/
|
||||
|
||||
/** @file event2/dns.h
|
||||
*
|
||||
* Welcome, gentle reader
|
||||
*
|
||||
* Async DNS lookups are really a whole lot harder than they should be,
|
||||
* mostly stemming from the fact that the libc resolver has never been
|
||||
* very good at them. Before you use this library you should see if libc
|
||||
* can do the job for you with the modern async call getaddrinfo_a
|
||||
* (see http://www.imperialviolet.org/page25.html#e498). Otherwise,
|
||||
* please continue.
|
||||
*
|
||||
* The library keeps track of the state of nameservers and will avoid
|
||||
* them when they go down. Otherwise it will round robin between them.
|
||||
*
|
||||
* Quick start guide:
|
||||
* #include "evdns.h"
|
||||
* void callback(int result, char type, int count, int ttl,
|
||||
* void *addresses, void *arg);
|
||||
* evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
|
||||
* evdns_resolve("www.hostname.com", 0, callback, NULL);
|
||||
*
|
||||
* When the lookup is complete the callback function is called. The
|
||||
* first argument will be one of the DNS_ERR_* defines in evdns.h.
|
||||
* Hopefully it will be DNS_ERR_NONE, in which case type will be
|
||||
* DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
|
||||
* which the data can be cached for (in seconds), addresses will point
|
||||
* to an array of uint32_t's and arg will be whatever you passed to
|
||||
* evdns_resolve.
|
||||
*
|
||||
* Searching:
|
||||
*
|
||||
* In order for this library to be a good replacement for glibc's resolver it
|
||||
* supports searching. This involves setting a list of default domains, in
|
||||
* which names will be queried for. The number of dots in the query name
|
||||
* determines the order in which this list is used.
|
||||
*
|
||||
* Searching appears to be a single lookup from the point of view of the API,
|
||||
* although many DNS queries may be generated from a single call to
|
||||
* evdns_resolve. Searching can also drastically slow down the resolution
|
||||
* of names.
|
||||
*
|
||||
* To disable searching:
|
||||
* 1. Never set it up. If you never call evdns_resolv_conf_parse or
|
||||
* evdns_search_add then no searching will occur.
|
||||
*
|
||||
* 2. If you do call evdns_resolv_conf_parse then don't pass
|
||||
* DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it).
|
||||
*
|
||||
* 3. When calling evdns_resolve, pass the DNS_QUERY_NO_SEARCH flag.
|
||||
*
|
||||
* The order of searches depends on the number of dots in the name. If the
|
||||
* number is greater than the ndots setting then the names is first tried
|
||||
* globally. Otherwise each search domain is appended in turn.
|
||||
*
|
||||
* The ndots setting can either be set from a resolv.conf, or by calling
|
||||
* evdns_search_ndots_set.
|
||||
*
|
||||
* For example, with ndots set to 1 (the default) and a search domain list of
|
||||
* ["myhome.net"]:
|
||||
* Query: www
|
||||
* Order: www.myhome.net, www.
|
||||
*
|
||||
* Query: www.abc
|
||||
* Order: www.abc., www.abc.myhome.net
|
||||
*
|
||||
* Internals:
|
||||
*
|
||||
* Requests are kept in two queues. The first is the inflight queue. In
|
||||
* this queue requests have an allocated transaction id and nameserver.
|
||||
* They will soon be transmitted if they haven't already been.
|
||||
*
|
||||
* The second is the waiting queue. The size of the inflight ring is
|
||||
* limited and all other requests wait in waiting queue for space. This
|
||||
* bounds the number of concurrent requests so that we don't flood the
|
||||
* nameserver. Several algorithms require a full walk of the inflight
|
||||
* queue and so bounding its size keeps thing going nicely under huge
|
||||
* (many thousands of requests) loads.
|
||||
*
|
||||
* If a nameserver loses too many requests it is considered down and we
|
||||
* try not to use it. After a while we send a probe to that nameserver
|
||||
* (a lookup for google.com) and, if it replies, we consider it working
|
||||
* again. If the nameserver fails a probe we wait longer to try again
|
||||
* with the next probe.
|
||||
*/
|
||||
|
||||
#ifndef EVENT2_DNS_H_INCLUDED_
|
||||
#define EVENT2_DNS_H_INCLUDED_
|
||||
|
||||
#include <event2/visibility.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* For integer types. */
|
||||
#include <event2/util.h>
|
||||
|
||||
/** Error codes 0-5 are as described in RFC 1035. */
|
||||
#define DNS_ERR_NONE 0
|
||||
/** The name server was unable to interpret the query */
|
||||
#define DNS_ERR_FORMAT 1
|
||||
/** The name server was unable to process this query due to a problem with the
|
||||
* name server */
|
||||
#define DNS_ERR_SERVERFAILED 2
|
||||
/** The domain name does not exist */
|
||||
#define DNS_ERR_NOTEXIST 3
|
||||
/** The name server does not support the requested kind of query */
|
||||
#define DNS_ERR_NOTIMPL 4
|
||||
/** The name server refuses to reform the specified operation for policy
|
||||
* reasons */
|
||||
#define DNS_ERR_REFUSED 5
|
||||
/** The reply was truncated or ill-formatted */
|
||||
#define DNS_ERR_TRUNCATED 65
|
||||
/** An unknown error occurred */
|
||||
#define DNS_ERR_UNKNOWN 66
|
||||
/** Communication with the server timed out */
|
||||
#define DNS_ERR_TIMEOUT 67
|
||||
/** The request was canceled because the DNS subsystem was shut down. */
|
||||
#define DNS_ERR_SHUTDOWN 68
|
||||
/** The request was canceled via a call to evdns_cancel_request */
|
||||
#define DNS_ERR_CANCEL 69
|
||||
/** There were no answers and no error condition in the DNS packet.
|
||||
* This can happen when you ask for an address that exists, but a record
|
||||
* type that doesn't. */
|
||||
#define DNS_ERR_NODATA 70
|
||||
|
||||
#define DNS_IPv4_A 1
|
||||
#define DNS_PTR 2
|
||||
#define DNS_IPv6_AAAA 3
|
||||
|
||||
#define DNS_QUERY_NO_SEARCH 1
|
||||
|
||||
#define DNS_OPTION_SEARCH 1
|
||||
#define DNS_OPTION_NAMESERVERS 2
|
||||
#define DNS_OPTION_MISC 4
|
||||
#define DNS_OPTION_HOSTSFILE 8
|
||||
#define DNS_OPTIONS_ALL 15
|
||||
|
||||
/* Obsolete name for DNS_QUERY_NO_SEARCH */
|
||||
#define DNS_NO_SEARCH DNS_QUERY_NO_SEARCH
|
||||
|
||||
/**
|
||||
* The callback that contains the results from a lookup.
|
||||
* - result is one of the DNS_ERR_* values (DNS_ERR_NONE for success)
|
||||
* - type is either DNS_IPv4_A or DNS_PTR or DNS_IPv6_AAAA
|
||||
* - count contains the number of addresses of form type
|
||||
* - ttl is the number of seconds the resolution may be cached for.
|
||||
* - addresses needs to be cast according to type. It will be an array of
|
||||
* 4-byte sequences for ipv4, or an array of 16-byte sequences for ipv6,
|
||||
* or a nul-terminated string for PTR.
|
||||
*/
|
||||
typedef void (*evdns_callback_type) (int result, char type, int count, int ttl, void *addresses, void *arg);
|
||||
|
||||
struct evdns_base;
|
||||
struct event_base;
|
||||
|
||||
/** Flag for evdns_base_new: process resolv.conf. */
|
||||
#define EVDNS_BASE_INITIALIZE_NAMESERVERS 1
|
||||
/** Flag for evdns_base_new: Do not prevent the libevent event loop from
|
||||
* exiting when we have no active dns requests. */
|
||||
#define EVDNS_BASE_DISABLE_WHEN_INACTIVE 0x8000
|
||||
|
||||
/**
|
||||
Initialize the asynchronous DNS library.
|
||||
|
||||
This function initializes support for non-blocking name resolution by
|
||||
calling evdns_resolv_conf_parse() on UNIX and
|
||||
evdns_config_windows_nameservers() on Windows.
|
||||
|
||||
@param event_base the event base to associate the dns client with
|
||||
@param flags any of EVDNS_BASE_INITIALIZE_NAMESERVERS|
|
||||
EVDNS_BASE_DISABLE_WHEN_INACTIVE
|
||||
@return evdns_base object if successful, or NULL if an error occurred.
|
||||
@see evdns_base_free()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct evdns_base * evdns_base_new(struct event_base *event_base, int initialize_nameservers);
|
||||
|
||||
|
||||
/**
|
||||
Shut down the asynchronous DNS resolver and terminate all active requests.
|
||||
|
||||
If the 'fail_requests' option is enabled, all active requests will return
|
||||
an empty result with the error flag set to DNS_ERR_SHUTDOWN. Otherwise,
|
||||
the requests will be silently discarded.
|
||||
|
||||
@param evdns_base the evdns base to free
|
||||
@param fail_requests if zero, active requests will be aborted; if non-zero,
|
||||
active requests will return DNS_ERR_SHUTDOWN.
|
||||
@see evdns_base_new()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_base_free(struct evdns_base *base, int fail_requests);
|
||||
|
||||
/**
|
||||
Remove all hosts entries that have been loaded into the event_base via
|
||||
evdns_base_load_hosts or via event_base_resolv_conf_parse.
|
||||
|
||||
@param evdns_base the evdns base to remove outdated host addresses from
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_base_clear_host_addresses(struct evdns_base *base);
|
||||
|
||||
/**
|
||||
Convert a DNS error code to a string.
|
||||
|
||||
@param err the DNS error code
|
||||
@return a string containing an explanation of the error code
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
const char *evdns_err_to_string(int err);
|
||||
|
||||
|
||||
/**
|
||||
Add a nameserver.
|
||||
|
||||
The address should be an IPv4 address in network byte order.
|
||||
The type of address is chosen so that it matches in_addr.s_addr.
|
||||
|
||||
@param base the evdns_base to which to add the name server
|
||||
@param address an IP address in network byte order
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_base_nameserver_ip_add()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_base_nameserver_add(struct evdns_base *base,
|
||||
unsigned long int address);
|
||||
|
||||
/**
|
||||
Get the number of configured nameservers.
|
||||
|
||||
This returns the number of configured nameservers (not necessarily the
|
||||
number of running nameservers). This is useful for double-checking
|
||||
whether our calls to the various nameserver configuration functions
|
||||
have been successful.
|
||||
|
||||
@param base the evdns_base to which to apply this operation
|
||||
@return the number of configured nameservers
|
||||
@see evdns_base_nameserver_add()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_base_count_nameservers(struct evdns_base *base);
|
||||
|
||||
/**
|
||||
Remove all configured nameservers, and suspend all pending resolves.
|
||||
|
||||
Resolves will not necessarily be re-attempted until evdns_base_resume() is called.
|
||||
|
||||
@param base the evdns_base to which to apply this operation
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_base_resume()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_base_clear_nameservers_and_suspend(struct evdns_base *base);
|
||||
|
||||
|
||||
/**
|
||||
Resume normal operation and continue any suspended resolve requests.
|
||||
|
||||
Re-attempt resolves left in limbo after an earlier call to
|
||||
evdns_base_clear_nameservers_and_suspend().
|
||||
|
||||
@param base the evdns_base to which to apply this operation
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_base_clear_nameservers_and_suspend()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_base_resume(struct evdns_base *base);
|
||||
|
||||
/**
|
||||
Add a nameserver by string address.
|
||||
|
||||
This function parses a n IPv4 or IPv6 address from a string and adds it as a
|
||||
nameserver. It supports the following formats:
|
||||
- [IPv6Address]:port
|
||||
- [IPv6Address]
|
||||
- IPv6Address
|
||||
- IPv4Address:port
|
||||
- IPv4Address
|
||||
|
||||
If no port is specified, it defaults to 53.
|
||||
|
||||
@param base the evdns_base to which to apply this operation
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_base_nameserver_add()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_base_nameserver_ip_add(struct evdns_base *base,
|
||||
const char *ip_as_string);
|
||||
|
||||
/**
|
||||
Add a nameserver by sockaddr.
|
||||
**/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int
|
||||
evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
|
||||
const struct sockaddr *sa, ev_socklen_t len, unsigned flags);
|
||||
|
||||
struct evdns_request;
|
||||
|
||||
/**
|
||||
Lookup an A record for a given name.
|
||||
|
||||
@param base the evdns_base to which to apply this operation
|
||||
@param name a DNS hostname
|
||||
@param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
|
||||
@param callback a callback function to invoke when the request is completed
|
||||
@param ptr an argument to pass to the callback function
|
||||
@return an evdns_request object if successful, or NULL if an error occurred.
|
||||
@see evdns_resolve_ipv6(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6(), evdns_cancel_request()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct evdns_request *evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags, evdns_callback_type callback, void *ptr);
|
||||
|
||||
/**
|
||||
Lookup an AAAA record for a given name.
|
||||
|
||||
@param base the evdns_base to which to apply this operation
|
||||
@param name a DNS hostname
|
||||
@param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
|
||||
@param callback a callback function to invoke when the request is completed
|
||||
@param ptr an argument to pass to the callback function
|
||||
@return an evdns_request object if successful, or NULL if an error occurred.
|
||||
@see evdns_resolve_ipv4(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6(), evdns_cancel_request()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct evdns_request *evdns_base_resolve_ipv6(struct evdns_base *base, const char *name, int flags, evdns_callback_type callback, void *ptr);
|
||||
|
||||
struct in_addr;
|
||||
struct in6_addr;
|
||||
|
||||
/**
|
||||
Lookup a PTR record for a given IP address.
|
||||
|
||||
@param base the evdns_base to which to apply this operation
|
||||
@param in an IPv4 address
|
||||
@param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
|
||||
@param callback a callback function to invoke when the request is completed
|
||||
@param ptr an argument to pass to the callback function
|
||||
@return an evdns_request object if successful, or NULL if an error occurred.
|
||||
@see evdns_resolve_reverse_ipv6(), evdns_cancel_request()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct evdns_request *evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr);
|
||||
|
||||
|
||||
/**
|
||||
Lookup a PTR record for a given IPv6 address.
|
||||
|
||||
@param base the evdns_base to which to apply this operation
|
||||
@param in an IPv6 address
|
||||
@param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
|
||||
@param callback a callback function to invoke when the request is completed
|
||||
@param ptr an argument to pass to the callback function
|
||||
@return an evdns_request object if successful, or NULL if an error occurred.
|
||||
@see evdns_resolve_reverse_ipv6(), evdns_cancel_request()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct evdns_request *evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr);
|
||||
|
||||
/**
|
||||
Cancels a pending DNS resolution request.
|
||||
|
||||
@param base the evdns_base that was used to make the request
|
||||
@param req the evdns_request that was returned by calling a resolve function
|
||||
@see evdns_base_resolve_ipv4(), evdns_base_resolve_ipv6, evdns_base_resolve_reverse
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_cancel_request(struct evdns_base *base, struct evdns_request *req);
|
||||
|
||||
/**
|
||||
Set the value of a configuration option.
|
||||
|
||||
The currently available configuration options are:
|
||||
|
||||
ndots, timeout, max-timeouts, max-inflight, attempts, randomize-case,
|
||||
bind-to, initial-probe-timeout, getaddrinfo-allow-skew.
|
||||
|
||||
In versions before Libevent 2.0.3-alpha, the option name needed to end with
|
||||
a colon.
|
||||
|
||||
@param base the evdns_base to which to apply this operation
|
||||
@param option the name of the configuration option to be modified
|
||||
@param val the value to be set
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_base_set_option(struct evdns_base *base, const char *option, const char *val);
|
||||
|
||||
|
||||
/**
|
||||
Parse a resolv.conf file.
|
||||
|
||||
The 'flags' parameter determines what information is parsed from the
|
||||
resolv.conf file. See the man page for resolv.conf for the format of this
|
||||
file.
|
||||
|
||||
The following directives are not parsed from the file: sortlist, rotate,
|
||||
no-check-names, inet6, debug.
|
||||
|
||||
If this function encounters an error, the possible return values are: 1 =
|
||||
failed to open file, 2 = failed to stat file, 3 = file too large, 4 = out of
|
||||
memory, 5 = short read from file, 6 = no nameservers listed in the file
|
||||
|
||||
@param base the evdns_base to which to apply this operation
|
||||
@param flags any of DNS_OPTION_NAMESERVERS|DNS_OPTION_SEARCH|DNS_OPTION_MISC|
|
||||
DNS_OPTION_HOSTSFILE|DNS_OPTIONS_ALL
|
||||
@param filename the path to the resolv.conf file
|
||||
@return 0 if successful, or various positive error codes if an error
|
||||
occurred (see above)
|
||||
@see resolv.conf(3), evdns_config_windows_nameservers()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename);
|
||||
|
||||
/**
|
||||
Load an /etc/hosts-style file from 'hosts_fname' into 'base'.
|
||||
|
||||
If hosts_fname is NULL, add minimal entries for localhost, and nothing
|
||||
else.
|
||||
|
||||
Note that only evdns_getaddrinfo uses the /etc/hosts entries.
|
||||
|
||||
This function does not replace previously loaded hosts entries; to do that,
|
||||
call evdns_base_clear_host_addresses first.
|
||||
|
||||
Return 0 on success, negative on failure.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname);
|
||||
|
||||
/**
|
||||
Obtain nameserver information using the Windows API.
|
||||
|
||||
Attempt to configure a set of nameservers based on platform settings on
|
||||
a win32 host. Preferentially tries to use GetNetworkParams; if that fails,
|
||||
looks in the registry.
|
||||
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_resolv_conf_parse()
|
||||
*/
|
||||
#ifdef _WIN32
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_base_config_windows_nameservers(struct evdns_base *);
|
||||
#define EVDNS_BASE_CONFIG_WINDOWS_NAMESERVERS_IMPLEMENTED
|
||||
#endif
|
||||
|
||||
|
||||
/**
|
||||
Clear the list of search domains.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_base_search_clear(struct evdns_base *base);
|
||||
|
||||
|
||||
/**
|
||||
Add a domain to the list of search domains
|
||||
|
||||
@param domain the domain to be added to the search list
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_base_search_add(struct evdns_base *base, const char *domain);
|
||||
|
||||
|
||||
/**
|
||||
Set the 'ndots' parameter for searches.
|
||||
|
||||
Sets the number of dots which, when found in a name, causes
|
||||
the first query to be without any search domain.
|
||||
|
||||
@param ndots the new ndots parameter
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_base_search_ndots_set(struct evdns_base *base, const int ndots);
|
||||
|
||||
/**
|
||||
A callback that is invoked when a log message is generated
|
||||
|
||||
@param is_warning indicates if the log message is a 'warning'
|
||||
@param msg the content of the log message
|
||||
*/
|
||||
typedef void (*evdns_debug_log_fn_type)(int is_warning, const char *msg);
|
||||
|
||||
|
||||
/**
|
||||
Set the callback function to handle DNS log messages. If this
|
||||
callback is not set, evdns log messages are handled with the regular
|
||||
Libevent logging system.
|
||||
|
||||
@param fn the callback to be invoked when a log message is generated
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_set_log_fn(evdns_debug_log_fn_type fn);
|
||||
|
||||
/**
|
||||
Set a callback that will be invoked to generate transaction IDs. By
|
||||
default, we pick transaction IDs based on the current clock time, which
|
||||
is bad for security.
|
||||
|
||||
@param fn the new callback, or NULL to use the default.
|
||||
|
||||
NOTE: This function has no effect in Libevent 2.0.4-alpha and later,
|
||||
since Libevent now provides its own secure RNG.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void));
|
||||
|
||||
/**
|
||||
Set a callback used to generate random bytes. By default, we use
|
||||
the same function as passed to evdns_set_transaction_id_fn to generate
|
||||
bytes two at a time. If a function is provided here, it's also used
|
||||
to generate transaction IDs.
|
||||
|
||||
NOTE: This function has no effect in Libevent 2.0.4-alpha and later,
|
||||
since Libevent now provides its own secure RNG.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_set_random_bytes_fn(void (*fn)(char *, size_t));
|
||||
|
||||
/*
|
||||
* Functions used to implement a DNS server.
|
||||
*/
|
||||
|
||||
struct evdns_server_request;
|
||||
struct evdns_server_question;
|
||||
|
||||
/**
|
||||
A callback to implement a DNS server. The callback function receives a DNS
|
||||
request. It should then optionally add a number of answers to the reply
|
||||
using the evdns_server_request_add_*_reply functions, before calling either
|
||||
evdns_server_request_respond to send the reply back, or
|
||||
evdns_server_request_drop to decline to answer the request.
|
||||
|
||||
@param req A newly received request
|
||||
@param user_data A pointer that was passed to
|
||||
evdns_add_server_port_with_base().
|
||||
*/
|
||||
typedef void (*evdns_request_callback_fn_type)(struct evdns_server_request *, void *);
|
||||
#define EVDNS_ANSWER_SECTION 0
|
||||
#define EVDNS_AUTHORITY_SECTION 1
|
||||
#define EVDNS_ADDITIONAL_SECTION 2
|
||||
|
||||
#define EVDNS_TYPE_A 1
|
||||
#define EVDNS_TYPE_NS 2
|
||||
#define EVDNS_TYPE_CNAME 5
|
||||
#define EVDNS_TYPE_SOA 6
|
||||
#define EVDNS_TYPE_PTR 12
|
||||
#define EVDNS_TYPE_MX 15
|
||||
#define EVDNS_TYPE_TXT 16
|
||||
#define EVDNS_TYPE_AAAA 28
|
||||
|
||||
#define EVDNS_QTYPE_AXFR 252
|
||||
#define EVDNS_QTYPE_ALL 255
|
||||
|
||||
#define EVDNS_CLASS_INET 1
|
||||
|
||||
/* flags that can be set in answers; as part of the err parameter */
|
||||
#define EVDNS_FLAGS_AA 0x400
|
||||
#define EVDNS_FLAGS_RD 0x080
|
||||
|
||||
/** Create a new DNS server port.
|
||||
|
||||
@param base The event base to handle events for the server port.
|
||||
@param socket A UDP socket to accept DNS requests.
|
||||
@param flags Always 0 for now.
|
||||
@param callback A function to invoke whenever we get a DNS request
|
||||
on the socket.
|
||||
@param user_data Data to pass to the callback.
|
||||
@return an evdns_server_port structure for this server port.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct evdns_server_port *evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type callback, void *user_data);
|
||||
/** Close down a DNS server port, and free associated structures. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_close_server_port(struct evdns_server_port *port);
|
||||
|
||||
/** Sets some flags in a reply we're building.
|
||||
Allows setting of the AA or RD flags
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_server_request_set_flags(struct evdns_server_request *req, int flags);
|
||||
|
||||
/* Functions to add an answer to an in-progress DNS reply.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_server_request_add_reply(struct evdns_server_request *req, int section, const char *name, int type, int dns_class, int ttl, int datalen, int is_name, const char *data);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl);
|
||||
|
||||
/**
|
||||
Send back a response to a DNS request, and free the request structure.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_server_request_respond(struct evdns_server_request *req, int err);
|
||||
/**
|
||||
Free a DNS request without sending back a reply.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_server_request_drop(struct evdns_server_request *req);
|
||||
struct sockaddr;
|
||||
/**
|
||||
Get the address that made a DNS request.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_server_request_get_requesting_addr(struct evdns_server_request *req, struct sockaddr *sa, int addr_len);
|
||||
|
||||
/** Callback for evdns_getaddrinfo. */
|
||||
typedef void (*evdns_getaddrinfo_cb)(int result, struct evutil_addrinfo *res, void *arg);
|
||||
|
||||
struct evdns_base;
|
||||
struct evdns_getaddrinfo_request;
|
||||
/** Make a non-blocking getaddrinfo request using the dns_base in 'dns_base'.
|
||||
*
|
||||
* If we can answer the request immediately (with an error or not!), then we
|
||||
* invoke cb immediately and return NULL. Otherwise we return
|
||||
* an evdns_getaddrinfo_request and invoke cb later.
|
||||
*
|
||||
* When the callback is invoked, we pass as its first argument the error code
|
||||
* that getaddrinfo would return (or 0 for no error). As its second argument,
|
||||
* we pass the evutil_addrinfo structures we found (or NULL on error). We
|
||||
* pass 'arg' as the third argument.
|
||||
*
|
||||
* Limitations:
|
||||
*
|
||||
* - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
|
||||
* - For ai_socktype, we only handle SOCKTYPE_STREAM, SOCKTYPE_UDP, and 0.
|
||||
* - For ai_protocol, we only handle IPPROTO_TCP, IPPROTO_UDP, and 0.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct evdns_getaddrinfo_request *evdns_getaddrinfo(
|
||||
struct evdns_base *dns_base,
|
||||
const char *nodename, const char *servname,
|
||||
const struct evutil_addrinfo *hints_in,
|
||||
evdns_getaddrinfo_cb cb, void *arg);
|
||||
|
||||
/* Cancel an in-progress evdns_getaddrinfo. This MUST NOT be called after the
|
||||
* getaddrinfo's callback has been invoked. The resolves will be canceled,
|
||||
* and the callback will be invoked with the error EVUTIL_EAI_CANCEL. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *req);
|
||||
|
||||
/**
|
||||
Retrieve the address of the 'idx'th configured nameserver.
|
||||
|
||||
@param base The evdns_base to examine.
|
||||
@param idx The index of the nameserver to get the address of.
|
||||
@param sa A location to receive the server's address.
|
||||
@param len The number of bytes available at sa.
|
||||
|
||||
@return the number of bytes written into sa on success. On failure, returns
|
||||
-1 if idx is greater than the number of configured nameservers, or a
|
||||
value greater than 'len' if len was not high enough.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evdns_base_get_nameserver_addr(struct evdns_base *base, int idx,
|
||||
struct sockaddr *sa, ev_socklen_t len);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* !EVENT2_DNS_H_INCLUDED_ */
|
|
@ -1,336 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_DNS_COMPAT_H_INCLUDED_
|
||||
#define EVENT2_DNS_COMPAT_H_INCLUDED_
|
||||
|
||||
/** @file event2/dns_compat.h
|
||||
|
||||
Potentially non-threadsafe versions of the functions in dns.h: provided
|
||||
only for backwards compatibility.
|
||||
|
||||
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
#ifdef EVENT__HAVE_SYS_TYPES_H
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_SYS_TIME_H
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
|
||||
/* For int types. */
|
||||
#include <event2/util.h>
|
||||
|
||||
/**
|
||||
Initialize the asynchronous DNS library.
|
||||
|
||||
This function initializes support for non-blocking name resolution by
|
||||
calling evdns_resolv_conf_parse() on UNIX and
|
||||
evdns_config_windows_nameservers() on Windows.
|
||||
|
||||
@deprecated This function is deprecated because it always uses the current
|
||||
event base, and is easily confused by multiple calls to event_init(), and
|
||||
so is not safe for multithreaded use. Additionally, it allocates a global
|
||||
structure that only one thread can use. The replacement is
|
||||
evdns_base_new().
|
||||
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_shutdown()
|
||||
*/
|
||||
int evdns_init(void);
|
||||
|
||||
struct evdns_base;
|
||||
/**
|
||||
Return the global evdns_base created by event_init() and used by the other
|
||||
deprecated functions.
|
||||
|
||||
@deprecated This function is deprecated because use of the global
|
||||
evdns_base is error-prone.
|
||||
*/
|
||||
struct evdns_base *evdns_get_global_base(void);
|
||||
|
||||
/**
|
||||
Shut down the asynchronous DNS resolver and terminate all active requests.
|
||||
|
||||
If the 'fail_requests' option is enabled, all active requests will return
|
||||
an empty result with the error flag set to DNS_ERR_SHUTDOWN. Otherwise,
|
||||
the requests will be silently discarded.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_shutdown().
|
||||
|
||||
@param fail_requests if zero, active requests will be aborted; if non-zero,
|
||||
active requests will return DNS_ERR_SHUTDOWN.
|
||||
@see evdns_init()
|
||||
*/
|
||||
void evdns_shutdown(int fail_requests);
|
||||
|
||||
/**
|
||||
Add a nameserver.
|
||||
|
||||
The address should be an IPv4 address in network byte order.
|
||||
The type of address is chosen so that it matches in_addr.s_addr.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_nameserver_add().
|
||||
|
||||
@param address an IP address in network byte order
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_nameserver_ip_add()
|
||||
*/
|
||||
int evdns_nameserver_add(unsigned long int address);
|
||||
|
||||
/**
|
||||
Get the number of configured nameservers.
|
||||
|
||||
This returns the number of configured nameservers (not necessarily the
|
||||
number of running nameservers). This is useful for double-checking
|
||||
whether our calls to the various nameserver configuration functions
|
||||
have been successful.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_count_nameservers().
|
||||
|
||||
@return the number of configured nameservers
|
||||
@see evdns_nameserver_add()
|
||||
*/
|
||||
int evdns_count_nameservers(void);
|
||||
|
||||
/**
|
||||
Remove all configured nameservers, and suspend all pending resolves.
|
||||
|
||||
Resolves will not necessarily be re-attempted until evdns_resume() is called.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_clear_nameservers_and_suspend().
|
||||
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_resume()
|
||||
*/
|
||||
int evdns_clear_nameservers_and_suspend(void);
|
||||
|
||||
/**
|
||||
Resume normal operation and continue any suspended resolve requests.
|
||||
|
||||
Re-attempt resolves left in limbo after an earlier call to
|
||||
evdns_clear_nameservers_and_suspend().
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_resume().
|
||||
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_clear_nameservers_and_suspend()
|
||||
*/
|
||||
int evdns_resume(void);
|
||||
|
||||
/**
|
||||
Add a nameserver.
|
||||
|
||||
This wraps the evdns_nameserver_add() function by parsing a string as an IP
|
||||
address and adds it as a nameserver.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_nameserver_ip_add().
|
||||
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_nameserver_add()
|
||||
*/
|
||||
int evdns_nameserver_ip_add(const char *ip_as_string);
|
||||
|
||||
/**
|
||||
Lookup an A record for a given name.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_resolve_ipv4().
|
||||
|
||||
@param name a DNS hostname
|
||||
@param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
|
||||
@param callback a callback function to invoke when the request is completed
|
||||
@param ptr an argument to pass to the callback function
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_resolve_ipv6(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6()
|
||||
*/
|
||||
int evdns_resolve_ipv4(const char *name, int flags, evdns_callback_type callback, void *ptr);
|
||||
|
||||
/**
|
||||
Lookup an AAAA record for a given name.
|
||||
|
||||
@param name a DNS hostname
|
||||
@param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
|
||||
@param callback a callback function to invoke when the request is completed
|
||||
@param ptr an argument to pass to the callback function
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_resolve_ipv4(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6()
|
||||
*/
|
||||
int evdns_resolve_ipv6(const char *name, int flags, evdns_callback_type callback, void *ptr);
|
||||
|
||||
struct in_addr;
|
||||
struct in6_addr;
|
||||
|
||||
/**
|
||||
Lookup a PTR record for a given IP address.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_resolve_reverse().
|
||||
|
||||
@param in an IPv4 address
|
||||
@param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
|
||||
@param callback a callback function to invoke when the request is completed
|
||||
@param ptr an argument to pass to the callback function
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_resolve_reverse_ipv6()
|
||||
*/
|
||||
int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr);
|
||||
|
||||
/**
|
||||
Lookup a PTR record for a given IPv6 address.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_resolve_reverse_ipv6().
|
||||
|
||||
@param in an IPv6 address
|
||||
@param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
|
||||
@param callback a callback function to invoke when the request is completed
|
||||
@param ptr an argument to pass to the callback function
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
@see evdns_resolve_reverse_ipv6()
|
||||
*/
|
||||
int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr);
|
||||
|
||||
/**
|
||||
Set the value of a configuration option.
|
||||
|
||||
The currently available configuration options are:
|
||||
|
||||
ndots, timeout, max-timeouts, max-inflight, and attempts
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_set_option().
|
||||
|
||||
@param option the name of the configuration option to be modified
|
||||
@param val the value to be set
|
||||
@param flags Ignored.
|
||||
@return 0 if successful, or -1 if an error occurred
|
||||
*/
|
||||
int evdns_set_option(const char *option, const char *val, int flags);
|
||||
|
||||
/**
|
||||
Parse a resolv.conf file.
|
||||
|
||||
The 'flags' parameter determines what information is parsed from the
|
||||
resolv.conf file. See the man page for resolv.conf for the format of this
|
||||
file.
|
||||
|
||||
The following directives are not parsed from the file: sortlist, rotate,
|
||||
no-check-names, inet6, debug.
|
||||
|
||||
If this function encounters an error, the possible return values are: 1 =
|
||||
failed to open file, 2 = failed to stat file, 3 = file too large, 4 = out of
|
||||
memory, 5 = short read from file, 6 = no nameservers listed in the file
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_resolv_conf_parse().
|
||||
|
||||
@param flags any of DNS_OPTION_NAMESERVERS|DNS_OPTION_SEARCH|DNS_OPTION_MISC|
|
||||
DNS_OPTIONS_ALL
|
||||
@param filename the path to the resolv.conf file
|
||||
@return 0 if successful, or various positive error codes if an error
|
||||
occurred (see above)
|
||||
@see resolv.conf(3), evdns_config_windows_nameservers()
|
||||
*/
|
||||
int evdns_resolv_conf_parse(int flags, const char *const filename);
|
||||
|
||||
/**
|
||||
Clear the list of search domains.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_search_clear().
|
||||
*/
|
||||
void evdns_search_clear(void);
|
||||
|
||||
/**
|
||||
Add a domain to the list of search domains
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_search_add().
|
||||
|
||||
@param domain the domain to be added to the search list
|
||||
*/
|
||||
void evdns_search_add(const char *domain);
|
||||
|
||||
/**
|
||||
Set the 'ndots' parameter for searches.
|
||||
|
||||
Sets the number of dots which, when found in a name, causes
|
||||
the first query to be without any search domain.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which evdns_base it applies to. The recommended
|
||||
function is evdns_base_search_ndots_set().
|
||||
|
||||
@param ndots the new ndots parameter
|
||||
*/
|
||||
void evdns_search_ndots_set(const int ndots);
|
||||
|
||||
/**
|
||||
As evdns_server_new_with_base.
|
||||
|
||||
@deprecated This function is deprecated because it does not allow the
|
||||
caller to specify which even_base it uses. The recommended
|
||||
function is evdns_add_server_port_with_base().
|
||||
|
||||
*/
|
||||
struct evdns_server_port *evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type callback, void *user_data);
|
||||
|
||||
#ifdef _WIN32
|
||||
int evdns_config_windows_nameservers(void);
|
||||
#define EVDNS_CONFIG_WINDOWS_NAMESERVERS_IMPLEMENTED
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
|
|
@ -1,80 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_DNS_STRUCT_H_INCLUDED_
|
||||
#define EVENT2_DNS_STRUCT_H_INCLUDED_
|
||||
|
||||
/** @file event2/dns_struct.h
|
||||
|
||||
Data structures for dns. Using these structures may hurt forward
|
||||
compatibility with later versions of Libevent: be careful!
|
||||
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
#ifdef EVENT__HAVE_SYS_TYPES_H
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_SYS_TIME_H
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
|
||||
/* For int types. */
|
||||
#include <event2/util.h>
|
||||
|
||||
/*
|
||||
* Structures used to implement a DNS server.
|
||||
*/
|
||||
|
||||
struct evdns_server_request {
|
||||
int flags;
|
||||
int nquestions;
|
||||
struct evdns_server_question **questions;
|
||||
};
|
||||
struct evdns_server_question {
|
||||
int type;
|
||||
#ifdef __cplusplus
|
||||
int dns_question_class;
|
||||
#else
|
||||
/* You should refer to this field as "dns_question_class". The
|
||||
* name "class" works in C for backward compatibility, and will be
|
||||
* removed in a future version. (1.5 or later). */
|
||||
int class;
|
||||
#define dns_question_class class
|
||||
#endif
|
||||
char name[1];
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_DNS_STRUCT_H_INCLUDED_ */
|
||||
|
|
@ -1,544 +0,0 @@
|
|||
/* event2/event-config.h
|
||||
*
|
||||
* This file was generated by autoconf when libevent was built, and post-
|
||||
* processed by Libevent so that its macros would have a uniform prefix.
|
||||
*
|
||||
* DO NOT EDIT THIS FILE.
|
||||
*
|
||||
* Do not rely on macros in this file existing in later versions.
|
||||
*/
|
||||
|
||||
#ifndef EVENT2_EVENT_CONFIG_H_INCLUDED_
|
||||
#define EVENT2_EVENT_CONFIG_H_INCLUDED_
|
||||
/* config.h. Generated from config.h.in by configure. */
|
||||
/* config.h.in. Generated from configure.ac by autoheader. */
|
||||
|
||||
/* Define if libevent should build without support for a debug mode */
|
||||
#define EVENT__DISABLE_DEBUG_MODE 1
|
||||
|
||||
/* Define if libevent should not allow replacing the mm functions */
|
||||
/* #undef EVENT__DISABLE_MM_REPLACEMENT */
|
||||
|
||||
/* Define if libevent should not be compiled with thread support */
|
||||
/* #undef EVENT__DISABLE_THREAD_SUPPORT */
|
||||
|
||||
/* Define to 1 if you have the `accept4' function. */
|
||||
/* #undef EVENT__HAVE_ACCEPT4 */
|
||||
|
||||
/* Define to 1 if you have the `arc4random' function. */
|
||||
#define EVENT__HAVE_ARC4RANDOM 1
|
||||
|
||||
/* Define to 1 if you have the `arc4random_buf' function. */
|
||||
#define EVENT__HAVE_ARC4RANDOM_BUF 1
|
||||
|
||||
/* Define to 1 if you have the <arpa/inet.h> header file. */
|
||||
#define EVENT__HAVE_ARPA_INET_H 1
|
||||
|
||||
/* Define to 1 if you have the `clock_gettime' function. */
|
||||
/* #undef EVENT__HAVE_CLOCK_GETTIME */
|
||||
|
||||
/* Define to 1 if you have the declaration of `CTL_KERN', and to 0 if you
|
||||
don't. */
|
||||
#define EVENT__HAVE_DECL_CTL_KERN 1
|
||||
|
||||
/* Define to 1 if you have the declaration of `KERN_ARND', and to 0 if you
|
||||
don't. */
|
||||
#define EVENT__HAVE_DECL_KERN_ARND 0
|
||||
|
||||
/* Define to 1 if you have the declaration of `KERN_RANDOM', and to 0 if you
|
||||
don't. */
|
||||
#define EVENT__HAVE_DECL_KERN_RANDOM 0
|
||||
|
||||
/* Define to 1 if you have the declaration of `RANDOM_UUID', and to 0 if you
|
||||
don't. */
|
||||
#define EVENT__HAVE_DECL_RANDOM_UUID 0
|
||||
|
||||
/* Define if /dev/poll is available */
|
||||
/* #undef EVENT__HAVE_DEVPOLL */
|
||||
|
||||
/* Define to 1 if you have the <dlfcn.h> header file. */
|
||||
#define EVENT__HAVE_DLFCN_H 1
|
||||
|
||||
/* Define if your system supports the epoll system calls */
|
||||
/* #undef EVENT__HAVE_EPOLL */
|
||||
|
||||
/* Define to 1 if you have the `epoll_create1' function. */
|
||||
/* #undef EVENT__HAVE_EPOLL_CREATE1 */
|
||||
|
||||
/* Define to 1 if you have the `epoll_ctl' function. */
|
||||
/* #undef EVENT__HAVE_EPOLL_CTL */
|
||||
|
||||
/* Define to 1 if you have the <errno.h> header file. */
|
||||
#define EVENT__HAVE_ERRNO_H 1
|
||||
|
||||
/* Define to 1 if you have ERR_remove_thread_stat(). */
|
||||
/* #undef EVENT__HAVE_ERR_REMOVE_THREAD_STATE */
|
||||
|
||||
/* Define to 1 if you have the `eventfd' function. */
|
||||
/* #undef EVENT__HAVE_EVENTFD */
|
||||
|
||||
/* Define if your system supports event ports */
|
||||
/* #undef EVENT__HAVE_EVENT_PORTS */
|
||||
|
||||
/* Define to 1 if you have the `fcntl' function. */
|
||||
#define EVENT__HAVE_FCNTL 1
|
||||
|
||||
/* Define to 1 if you have the <fcntl.h> header file. */
|
||||
#define EVENT__HAVE_FCNTL_H 1
|
||||
|
||||
/* Define to 1 if the system has the type `fd_mask'. */
|
||||
#define EVENT__HAVE_FD_MASK 1
|
||||
|
||||
/* Do we have getaddrinfo()? */
|
||||
#define EVENT__HAVE_GETADDRINFO 1
|
||||
|
||||
/* Define to 1 if you have the `getegid' function. */
|
||||
#define EVENT__HAVE_GETEGID 1
|
||||
|
||||
/* Define to 1 if you have the `geteuid' function. */
|
||||
#define EVENT__HAVE_GETEUID 1
|
||||
|
||||
/* Define this if you have any gethostbyname_r() */
|
||||
/* #undef EVENT__HAVE_GETHOSTBYNAME_R */
|
||||
|
||||
/* Define this if gethostbyname_r takes 3 arguments */
|
||||
/* #undef EVENT__HAVE_GETHOSTBYNAME_R_3_ARG */
|
||||
|
||||
/* Define this if gethostbyname_r takes 5 arguments */
|
||||
/* #undef EVENT__HAVE_GETHOSTBYNAME_R_5_ARG */
|
||||
|
||||
/* Define this if gethostbyname_r takes 6 arguments */
|
||||
/* #undef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG */
|
||||
|
||||
/* Define to 1 if you have the `getifaddrs' function. */
|
||||
#define EVENT__HAVE_GETIFADDRS 1
|
||||
|
||||
/* Define to 1 if you have the `getnameinfo' function. */
|
||||
#define EVENT__HAVE_GETNAMEINFO 1
|
||||
|
||||
/* Define to 1 if you have the `getprotobynumber' function. */
|
||||
#define EVENT__HAVE_GETPROTOBYNUMBER 1
|
||||
|
||||
/* Define to 1 if you have the `getservbyname' function. */
|
||||
#define EVENT__HAVE_GETSERVBYNAME 1
|
||||
|
||||
/* Define to 1 if you have the `gettimeofday' function. */
|
||||
#define EVENT__HAVE_GETTIMEOFDAY 1
|
||||
|
||||
/* Define to 1 if you have the <ifaddrs.h> header file. */
|
||||
#define EVENT__HAVE_IFADDRS_H 1
|
||||
|
||||
/* Define to 1 if you have the `inet_ntop' function. */
|
||||
#define EVENT__HAVE_INET_NTOP 1
|
||||
|
||||
/* Define to 1 if you have the `inet_pton' function. */
|
||||
#define EVENT__HAVE_INET_PTON 1
|
||||
|
||||
/* Define to 1 if you have the <inttypes.h> header file. */
|
||||
#define EVENT__HAVE_INTTYPES_H 1
|
||||
|
||||
/* Define to 1 if you have the `issetugid' function. */
|
||||
#define EVENT__HAVE_ISSETUGID 1
|
||||
|
||||
/* Define to 1 if you have the `kqueue' function. */
|
||||
#define EVENT__HAVE_KQUEUE 1
|
||||
|
||||
/* Define if the system has zlib */
|
||||
#define EVENT__HAVE_LIBZ 1
|
||||
|
||||
/* Define to 1 if you have the `mach_absolute_time' function. */
|
||||
#define EVENT__HAVE_MACH_ABSOLUTE_TIME 1
|
||||
|
||||
/* Define to 1 if you have the <mach/mach_time.h> header file. */
|
||||
#define EVENT__HAVE_MACH_MACH_TIME_H 1
|
||||
|
||||
/* Define to 1 if you have the <memory.h> header file. */
|
||||
#define EVENT__HAVE_MEMORY_H 1
|
||||
|
||||
/* Define to 1 if you have the `mmap' function. */
|
||||
#define EVENT__HAVE_MMAP 1
|
||||
|
||||
/* Define to 1 if you have the `nanosleep' function. */
|
||||
#define EVENT__HAVE_NANOSLEEP 1
|
||||
|
||||
/* Define to 1 if you have the <netdb.h> header file. */
|
||||
#define EVENT__HAVE_NETDB_H 1
|
||||
|
||||
/* Define to 1 if you have the <netinet/in6.h> header file. */
|
||||
/* #undef EVENT__HAVE_NETINET_IN6_H */
|
||||
|
||||
/* Define to 1 if you have the <netinet/in.h> header file. */
|
||||
#define EVENT__HAVE_NETINET_IN_H 1
|
||||
|
||||
/* Define to 1 if you have the <netinet/tcp.h> header file. */
|
||||
#define EVENT__HAVE_NETINET_TCP_H 1
|
||||
|
||||
/* Define if the system has openssl */
|
||||
/* #undef EVENT__HAVE_OPENSSL */
|
||||
|
||||
/* Define to 1 if you have the `pipe' function. */
|
||||
#define EVENT__HAVE_PIPE 1
|
||||
|
||||
/* Define to 1 if you have the `pipe2' function. */
|
||||
/* #undef EVENT__HAVE_PIPE2 */
|
||||
|
||||
/* Define to 1 if you have the `poll' function. */
|
||||
#define EVENT__HAVE_POLL 1
|
||||
|
||||
/* Define to 1 if you have the <poll.h> header file. */
|
||||
#define EVENT__HAVE_POLL_H 1
|
||||
|
||||
/* Define to 1 if you have the `port_create' function. */
|
||||
/* #undef EVENT__HAVE_PORT_CREATE */
|
||||
|
||||
/* Define to 1 if you have the <port.h> header file. */
|
||||
/* #undef EVENT__HAVE_PORT_H */
|
||||
|
||||
/* Define if you have POSIX threads libraries and header files. */
|
||||
/* #undef EVENT__HAVE_PTHREAD */
|
||||
|
||||
/* Define if we have pthreads on this system */
|
||||
#define EVENT__HAVE_PTHREADS 1
|
||||
|
||||
/* Define to 1 if you have the `putenv' function. */
|
||||
#define EVENT__HAVE_PUTENV 1
|
||||
|
||||
/* Define to 1 if the system has the type `sa_family_t'. */
|
||||
#define EVENT__HAVE_SA_FAMILY_T 1
|
||||
|
||||
/* Define to 1 if you have the `select' function. */
|
||||
#define EVENT__HAVE_SELECT 1
|
||||
|
||||
/* Define to 1 if you have the `sendfile' function. */
|
||||
#define EVENT__HAVE_SENDFILE 1
|
||||
|
||||
/* Define to 1 if you have the `setenv' function. */
|
||||
#define EVENT__HAVE_SETENV 1
|
||||
|
||||
/* Define if F_SETFD is defined in <fcntl.h> */
|
||||
#define EVENT__HAVE_SETFD 1
|
||||
|
||||
/* Define to 1 if you have the `setrlimit' function. */
|
||||
#define EVENT__HAVE_SETRLIMIT 1
|
||||
|
||||
/* Define to 1 if you have the `sigaction' function. */
|
||||
#define EVENT__HAVE_SIGACTION 1
|
||||
|
||||
/* Define to 1 if you have the `signal' function. */
|
||||
#define EVENT__HAVE_SIGNAL 1
|
||||
|
||||
/* Define to 1 if you have the `splice' function. */
|
||||
/* #undef EVENT__HAVE_SPLICE */
|
||||
|
||||
/* Define to 1 if you have the <stdarg.h> header file. */
|
||||
#define EVENT__HAVE_STDARG_H 1
|
||||
|
||||
/* Define to 1 if you have the <stddef.h> header file. */
|
||||
#define EVENT__HAVE_STDDEF_H 1
|
||||
|
||||
/* Define to 1 if you have the <stdint.h> header file. */
|
||||
#define EVENT__HAVE_STDINT_H 1
|
||||
|
||||
/* Define to 1 if you have the <stdlib.h> header file. */
|
||||
#define EVENT__HAVE_STDLIB_H 1
|
||||
|
||||
/* Define to 1 if you have the <strings.h> header file. */
|
||||
#define EVENT__HAVE_STRINGS_H 1
|
||||
|
||||
/* Define to 1 if you have the <string.h> header file. */
|
||||
#define EVENT__HAVE_STRING_H 1
|
||||
|
||||
/* Define to 1 if you have the `strlcpy' function. */
|
||||
#define EVENT__HAVE_STRLCPY 1
|
||||
|
||||
/* Define to 1 if you have the `strsep' function. */
|
||||
#define EVENT__HAVE_STRSEP 1
|
||||
|
||||
/* Define to 1 if you have the `strtok_r' function. */
|
||||
#define EVENT__HAVE_STRTOK_R 1
|
||||
|
||||
/* Define to 1 if you have the `strtoll' function. */
|
||||
#define EVENT__HAVE_STRTOLL 1
|
||||
|
||||
/* Define to 1 if the system has the type `struct addrinfo'. */
|
||||
#define EVENT__HAVE_STRUCT_ADDRINFO 1
|
||||
|
||||
/* Define to 1 if the system has the type `struct in6_addr'. */
|
||||
#define EVENT__HAVE_STRUCT_IN6_ADDR 1
|
||||
|
||||
/* Define to 1 if `s6_addr16' is a member of `struct in6_addr'. */
|
||||
/* #undef EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16 */
|
||||
|
||||
/* Define to 1 if `s6_addr32' is a member of `struct in6_addr'. */
|
||||
/* #undef EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32 */
|
||||
|
||||
/* Define to 1 if the system has the type `struct sockaddr_in6'. */
|
||||
#define EVENT__HAVE_STRUCT_SOCKADDR_IN6 1
|
||||
|
||||
/* Define to 1 if `sin6_len' is a member of `struct sockaddr_in6'. */
|
||||
#define EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN 1
|
||||
|
||||
/* Define to 1 if `sin_len' is a member of `struct sockaddr_in'. */
|
||||
#define EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN 1
|
||||
|
||||
/* Define to 1 if the system has the type `struct sockaddr_storage'. */
|
||||
#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE 1
|
||||
|
||||
/* Define to 1 if `ss_family' is a member of `struct sockaddr_storage'. */
|
||||
#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY 1
|
||||
|
||||
/* Define to 1 if `__ss_family' is a member of `struct sockaddr_storage'. */
|
||||
/* #undef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY */
|
||||
|
||||
/* Define to 1 if the system has the type `struct so_linger'. */
|
||||
/* #undef EVENT__HAVE_STRUCT_SO_LINGER */
|
||||
|
||||
/* Define to 1 if you have the `sysctl' function. */
|
||||
#define EVENT__HAVE_SYSCTL 1
|
||||
|
||||
/* Define to 1 if you have the <sys/devpoll.h> header file. */
|
||||
/* #undef EVENT__HAVE_SYS_DEVPOLL_H */
|
||||
|
||||
/* Define to 1 if you have the <sys/epoll.h> header file. */
|
||||
/* #undef EVENT__HAVE_SYS_EPOLL_H */
|
||||
|
||||
/* Define to 1 if you have the <sys/eventfd.h> header file. */
|
||||
/* #undef EVENT__HAVE_SYS_EVENTFD_H */
|
||||
|
||||
/* Define to 1 if you have the <sys/event.h> header file. */
|
||||
#define EVENT__HAVE_SYS_EVENT_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/ioctl.h> header file. */
|
||||
#define EVENT__HAVE_SYS_IOCTL_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/mman.h> header file. */
|
||||
#define EVENT__HAVE_SYS_MMAN_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/param.h> header file. */
|
||||
#define EVENT__HAVE_SYS_PARAM_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/queue.h> header file. */
|
||||
#define EVENT__HAVE_SYS_QUEUE_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/resource.h> header file. */
|
||||
#define EVENT__HAVE_SYS_RESOURCE_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/select.h> header file. */
|
||||
#define EVENT__HAVE_SYS_SELECT_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/sendfile.h> header file. */
|
||||
/* #undef EVENT__HAVE_SYS_SENDFILE_H */
|
||||
|
||||
/* Define to 1 if you have the <sys/socket.h> header file. */
|
||||
#define EVENT__HAVE_SYS_SOCKET_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/stat.h> header file. */
|
||||
#define EVENT__HAVE_SYS_STAT_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/sysctl.h> header file. */
|
||||
#define EVENT__HAVE_SYS_SYSCTL_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/timerfd.h> header file. */
|
||||
/* #undef EVENT__HAVE_SYS_TIMERFD_H */
|
||||
|
||||
/* Define to 1 if you have the <sys/time.h> header file. */
|
||||
#define EVENT__HAVE_SYS_TIME_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/types.h> header file. */
|
||||
#define EVENT__HAVE_SYS_TYPES_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/uio.h> header file. */
|
||||
#define EVENT__HAVE_SYS_UIO_H 1
|
||||
|
||||
/* Define to 1 if you have the <sys/wait.h> header file. */
|
||||
#define EVENT__HAVE_SYS_WAIT_H 1
|
||||
|
||||
/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
|
||||
#define EVENT__HAVE_TAILQFOREACH 1
|
||||
|
||||
/* Define if timeradd is defined in <sys/time.h> */
|
||||
#define EVENT__HAVE_TIMERADD 1
|
||||
|
||||
/* Define if timerclear is defined in <sys/time.h> */
|
||||
#define EVENT__HAVE_TIMERCLEAR 1
|
||||
|
||||
/* Define if timercmp is defined in <sys/time.h> */
|
||||
#define EVENT__HAVE_TIMERCMP 1
|
||||
|
||||
/* Define to 1 if you have the `timerfd_create' function. */
|
||||
/* #undef EVENT__HAVE_TIMERFD_CREATE */
|
||||
|
||||
/* Define if timerisset is defined in <sys/time.h> */
|
||||
#define EVENT__HAVE_TIMERISSET 1
|
||||
|
||||
/* Define to 1 if the system has the type `uint16_t'. */
|
||||
#define EVENT__HAVE_UINT16_T 1
|
||||
|
||||
/* Define to 1 if the system has the type `uint32_t'. */
|
||||
#define EVENT__HAVE_UINT32_T 1
|
||||
|
||||
/* Define to 1 if the system has the type `uint64_t'. */
|
||||
#define EVENT__HAVE_UINT64_T 1
|
||||
|
||||
/* Define to 1 if the system has the type `uint8_t'. */
|
||||
#define EVENT__HAVE_UINT8_T 1
|
||||
|
||||
/* Define to 1 if the system has the type `uintptr_t'. */
|
||||
#define EVENT__HAVE_UINTPTR_T 1
|
||||
|
||||
/* Define to 1 if you have the `umask' function. */
|
||||
#define EVENT__HAVE_UMASK 1
|
||||
|
||||
/* Define to 1 if you have the <unistd.h> header file. */
|
||||
#define EVENT__HAVE_UNISTD_H 1
|
||||
|
||||
/* Define to 1 if you have the `unsetenv' function. */
|
||||
#define EVENT__HAVE_UNSETENV 1
|
||||
|
||||
/* Define to 1 if you have the `usleep' function. */
|
||||
#define EVENT__HAVE_USLEEP 1
|
||||
|
||||
/* Define to 1 if you have the `vasprintf' function. */
|
||||
#define EVENT__HAVE_VASPRINTF 1
|
||||
|
||||
/* Define if waitpid() supports WNOWAIT */
|
||||
/* #undef EVENT__HAVE_WAITPID_WITH_WNOWAIT */
|
||||
|
||||
/* Define if kqueue works correctly with pipes */
|
||||
/* #undef EVENT__HAVE_WORKING_KQUEUE */
|
||||
|
||||
/* Define to 1 if you have the <zlib.h> header file. */
|
||||
#define EVENT__HAVE_ZLIB_H 1
|
||||
|
||||
/* Define to the sub-directory where libtool stores uninstalled libraries. */
|
||||
#define EVENT__LT_OBJDIR ".libs/"
|
||||
|
||||
/* Numeric representation of the version */
|
||||
#define EVENT__NUMERIC_VERSION 0x02010800
|
||||
|
||||
/* Name of package */
|
||||
#define EVENT__PACKAGE "libevent"
|
||||
|
||||
/* Define to the address where bug reports for this package should be sent. */
|
||||
#define EVENT__PACKAGE_BUGREPORT ""
|
||||
|
||||
/* Define to the full name of this package. */
|
||||
#define EVENT__PACKAGE_NAME "libevent"
|
||||
|
||||
/* Define to the full name and version of this package. */
|
||||
#define EVENT__PACKAGE_STRING "libevent 2.1.8-stable"
|
||||
|
||||
/* Define to the one symbol short name of this package. */
|
||||
#define EVENT__PACKAGE_TARNAME "libevent"
|
||||
|
||||
/* Define to the home page for this package. */
|
||||
#define EVENT__PACKAGE_URL ""
|
||||
|
||||
/* Define to the version of this package. */
|
||||
#define EVENT__PACKAGE_VERSION "2.1.8-stable"
|
||||
|
||||
/* Define to necessary symbol if this constant uses a non-standard name on
|
||||
your system. */
|
||||
/* #undef EVENT__PTHREAD_CREATE_JOINABLE */
|
||||
|
||||
/* The size of `int', as computed by sizeof. */
|
||||
#define EVENT__SIZEOF_INT 4
|
||||
|
||||
/* The size of `long', as computed by sizeof. */
|
||||
#define EVENT__SIZEOF_LONG 4
|
||||
|
||||
/* The size of `long long', as computed by sizeof. */
|
||||
#define EVENT__SIZEOF_LONG_LONG 8
|
||||
|
||||
/* The size of `off_t', as computed by sizeof. */
|
||||
#define EVENT__SIZEOF_OFF_T 8
|
||||
|
||||
/* The size of `pthread_t', as computed by sizeof. */
|
||||
#define EVENT__SIZEOF_PTHREAD_T 4
|
||||
|
||||
/* The size of `short', as computed by sizeof. */
|
||||
#define EVENT__SIZEOF_SHORT 2
|
||||
|
||||
/* The size of `size_t', as computed by sizeof. */
|
||||
#define EVENT__SIZEOF_SIZE_T 4
|
||||
|
||||
/* The size of `void *', as computed by sizeof. */
|
||||
#define EVENT__SIZEOF_VOID_P 4
|
||||
|
||||
/* Define to 1 if you have the ANSI C header files. */
|
||||
#define EVENT__STDC_HEADERS 1
|
||||
|
||||
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
|
||||
#define EVENT__TIME_WITH_SYS_TIME 1
|
||||
|
||||
/* Enable extensions on AIX 3, Interix. */
|
||||
#ifndef EVENT___ALL_SOURCE
|
||||
# define EVENT___ALL_SOURCE 1
|
||||
#endif
|
||||
/* Enable GNU extensions on systems that have them. */
|
||||
#ifndef EVENT___GNU_SOURCE
|
||||
# define EVENT___GNU_SOURCE 1
|
||||
#endif
|
||||
/* Enable threading extensions on Solaris. */
|
||||
#ifndef EVENT___POSIX_PTHREAD_SEMANTICS
|
||||
# define EVENT___POSIX_PTHREAD_SEMANTICS 1
|
||||
#endif
|
||||
/* Enable extensions on HP NonStop. */
|
||||
#ifndef EVENT___TANDEM_SOURCE
|
||||
# define EVENT___TANDEM_SOURCE 1
|
||||
#endif
|
||||
/* Enable general extensions on Solaris. */
|
||||
#ifndef EVENT____EXTENSIONS__
|
||||
# define EVENT____EXTENSIONS__ 1
|
||||
#endif
|
||||
|
||||
|
||||
/* Version number of package */
|
||||
#define EVENT__VERSION "2.1.8-stable"
|
||||
|
||||
/* Enable large inode numbers on Mac OS X 10.5. */
|
||||
#ifndef EVENT___DARWIN_USE_64_BIT_INODE
|
||||
# define EVENT___DARWIN_USE_64_BIT_INODE 1
|
||||
#endif
|
||||
|
||||
/* Number of bits in a file offset, on hosts where this is settable. */
|
||||
/* #undef EVENT___FILE_OFFSET_BITS */
|
||||
|
||||
/* Define for large files, on AIX-style hosts. */
|
||||
/* #undef EVENT___LARGE_FILES */
|
||||
|
||||
/* Define to 1 if on MINIX. */
|
||||
/* #undef EVENT___MINIX */
|
||||
|
||||
/* Define to 2 if the system does not provide POSIX.1 features except with
|
||||
this defined. */
|
||||
/* #undef EVENT___POSIX_1_SOURCE */
|
||||
|
||||
/* Define to 1 if you need to in order for `stat' and other things to work. */
|
||||
/* #undef EVENT___POSIX_SOURCE */
|
||||
|
||||
/* Define to appropriate substitue if compiler doesnt have __func__ */
|
||||
/* #undef EVENT____func__ */
|
||||
|
||||
/* Define to empty if `const' does not conform to ANSI C. */
|
||||
/* #undef EVENT__const */
|
||||
|
||||
/* Define to `__inline__' or `__inline' if that's what the C compiler
|
||||
calls it, or to nothing if 'inline' is not supported under any name. */
|
||||
#ifndef EVENT____cplusplus
|
||||
/* #undef EVENT__inline */
|
||||
#endif
|
||||
|
||||
/* Define to `int' if <sys/types.h> does not define. */
|
||||
/* #undef EVENT__pid_t */
|
||||
|
||||
/* Define to `unsigned int' if <sys/types.h> does not define. */
|
||||
/* #undef EVENT__size_t */
|
||||
|
||||
/* Define to unsigned int if you dont have it */
|
||||
/* #undef EVENT__socklen_t */
|
||||
|
||||
/* Define to `int' if <sys/types.h> does not define. */
|
||||
/* #undef EVENT__ssize_t */
|
||||
|
||||
#endif /* event2/event-config.h */
|
File diff suppressed because it is too large
Load Diff
|
@ -1,230 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_EVENT_COMPAT_H_INCLUDED_
|
||||
#define EVENT2_EVENT_COMPAT_H_INCLUDED_
|
||||
|
||||
/** @file event2/event_compat.h
|
||||
|
||||
Potentially non-threadsafe versions of the functions in event.h: provided
|
||||
only for backwards compatibility.
|
||||
|
||||
In the oldest versions of Libevent, event_base was not a first-class
|
||||
structure. Instead, there was a single event base that every function
|
||||
manipulated. Later, when separate event bases were added, the old functions
|
||||
that didn't take an event_base argument needed to work by manipulating the
|
||||
"current" event base. This could lead to thread-safety issues, and obscure,
|
||||
hard-to-diagnose bugs.
|
||||
|
||||
@deprecated All functions in this file are by definition deprecated.
|
||||
*/
|
||||
#include <event2/visibility.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
#ifdef EVENT__HAVE_SYS_TYPES_H
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_SYS_TIME_H
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
|
||||
/* For int types. */
|
||||
#include <event2/util.h>
|
||||
|
||||
/**
|
||||
Initialize the event API.
|
||||
|
||||
The event API needs to be initialized with event_init() before it can be
|
||||
used. Sets the global current base that gets used for events that have no
|
||||
base associated with them.
|
||||
|
||||
@deprecated This function is deprecated because it replaces the "current"
|
||||
event_base, and is totally unsafe for multithreaded use. The replacement
|
||||
is event_base_new().
|
||||
|
||||
@see event_base_set(), event_base_new()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct event_base *event_init(void);
|
||||
|
||||
/**
|
||||
Loop to process events.
|
||||
|
||||
Like event_base_dispatch(), but uses the "current" base.
|
||||
|
||||
@deprecated This function is deprecated because it is easily confused by
|
||||
multiple calls to event_init(), and because it is not safe for
|
||||
multithreaded use. The replacement is event_base_dispatch().
|
||||
|
||||
@see event_base_dispatch(), event_init()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int event_dispatch(void);
|
||||
|
||||
/**
|
||||
Handle events.
|
||||
|
||||
This function behaves like event_base_loop(), but uses the "current" base
|
||||
|
||||
@deprecated This function is deprecated because it uses the event base from
|
||||
the last call to event_init, and is therefore not safe for multithreaded
|
||||
use. The replacement is event_base_loop().
|
||||
|
||||
@see event_base_loop(), event_init()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int event_loop(int);
|
||||
|
||||
|
||||
/**
|
||||
Exit the event loop after the specified time.
|
||||
|
||||
This function behaves like event_base_loopexit(), except that it uses the
|
||||
"current" base.
|
||||
|
||||
@deprecated This function is deprecated because it uses the event base from
|
||||
the last call to event_init, and is therefore not safe for multithreaded
|
||||
use. The replacement is event_base_loopexit().
|
||||
|
||||
@see event_init, event_base_loopexit()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int event_loopexit(const struct timeval *);
|
||||
|
||||
|
||||
/**
|
||||
Abort the active event_loop() immediately.
|
||||
|
||||
This function behaves like event_base_loopbreakt(), except that it uses the
|
||||
"current" base.
|
||||
|
||||
@deprecated This function is deprecated because it uses the event base from
|
||||
the last call to event_init, and is therefore not safe for multithreaded
|
||||
use. The replacement is event_base_loopbreak().
|
||||
|
||||
@see event_base_loopbreak(), event_init()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int event_loopbreak(void);
|
||||
|
||||
/**
|
||||
Schedule a one-time event to occur.
|
||||
|
||||
@deprecated This function is obsolete, and has been replaced by
|
||||
event_base_once(). Its use is deprecated because it relies on the
|
||||
"current" base configured by event_init().
|
||||
|
||||
@see event_base_once()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int event_once(evutil_socket_t , short,
|
||||
void (*)(evutil_socket_t, short, void *), void *, const struct timeval *);
|
||||
|
||||
|
||||
/**
|
||||
Get the kernel event notification mechanism used by Libevent.
|
||||
|
||||
@deprecated This function is obsolete, and has been replaced by
|
||||
event_base_get_method(). Its use is deprecated because it relies on the
|
||||
"current" base configured by event_init().
|
||||
|
||||
@see event_base_get_method()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
const char *event_get_method(void);
|
||||
|
||||
|
||||
/**
|
||||
Set the number of different event priorities.
|
||||
|
||||
@deprecated This function is deprecated because it is easily confused by
|
||||
multiple calls to event_init(), and because it is not safe for
|
||||
multithreaded use. The replacement is event_base_priority_init().
|
||||
|
||||
@see event_base_priority_init()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int event_priority_init(int);
|
||||
|
||||
/**
|
||||
Prepare an event structure to be added.
|
||||
|
||||
@deprecated event_set() is not recommended for new code, because it requires
|
||||
a subsequent call to event_base_set() to be safe under most circumstances.
|
||||
Use event_assign() or event_new() instead.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void event_set(struct event *, evutil_socket_t, short, void (*)(evutil_socket_t, short, void *), void *);
|
||||
|
||||
#define evtimer_set(ev, cb, arg) event_set((ev), -1, 0, (cb), (arg))
|
||||
#define evsignal_set(ev, x, cb, arg) \
|
||||
event_set((ev), (x), EV_SIGNAL|EV_PERSIST, (cb), (arg))
|
||||
|
||||
|
||||
/**
|
||||
@name timeout_* macros
|
||||
|
||||
@deprecated These macros are deprecated because their naming is inconsistent
|
||||
with the rest of Libevent. Use the evtimer_* macros instead.
|
||||
@{
|
||||
*/
|
||||
#define timeout_add(ev, tv) event_add((ev), (tv))
|
||||
#define timeout_set(ev, cb, arg) event_set((ev), -1, 0, (cb), (arg))
|
||||
#define timeout_del(ev) event_del(ev)
|
||||
#define timeout_pending(ev, tv) event_pending((ev), EV_TIMEOUT, (tv))
|
||||
#define timeout_initialized(ev) event_initialized(ev)
|
||||
/**@}*/
|
||||
|
||||
/**
|
||||
@name signal_* macros
|
||||
|
||||
@deprecated These macros are deprecated because their naming is inconsistent
|
||||
with the rest of Libevent. Use the evsignal_* macros instead.
|
||||
@{
|
||||
*/
|
||||
#define signal_add(ev, tv) event_add((ev), (tv))
|
||||
#define signal_set(ev, x, cb, arg) \
|
||||
event_set((ev), (x), EV_SIGNAL|EV_PERSIST, (cb), (arg))
|
||||
#define signal_del(ev) event_del(ev)
|
||||
#define signal_pending(ev, tv) event_pending((ev), EV_SIGNAL, (tv))
|
||||
#define signal_initialized(ev) event_initialized(ev)
|
||||
/**@}*/
|
||||
|
||||
#ifndef EVENT_FD
|
||||
/* These macros are obsolete; use event_get_fd and event_get_signal instead. */
|
||||
#define EVENT_FD(ev) ((int)event_get_fd(ev))
|
||||
#define EVENT_SIGNAL(ev) event_get_signal(ev)
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
|
|
@ -1,180 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_EVENT_STRUCT_H_INCLUDED_
|
||||
#define EVENT2_EVENT_STRUCT_H_INCLUDED_
|
||||
|
||||
/** @file event2/event_struct.h
|
||||
|
||||
Structures used by event.h. Using these structures directly WILL harm
|
||||
forward compatibility: be careful.
|
||||
|
||||
No field declared in this file should be used directly in user code. Except
|
||||
for historical reasons, these fields would not be exposed at all.
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
#ifdef EVENT__HAVE_SYS_TYPES_H
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_SYS_TIME_H
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
|
||||
/* For int types. */
|
||||
#include <event2/util.h>
|
||||
|
||||
/* For evkeyvalq */
|
||||
#include <event2/keyvalq_struct.h>
|
||||
|
||||
#define EVLIST_TIMEOUT 0x01
|
||||
#define EVLIST_INSERTED 0x02
|
||||
#define EVLIST_SIGNAL 0x04
|
||||
#define EVLIST_ACTIVE 0x08
|
||||
#define EVLIST_INTERNAL 0x10
|
||||
#define EVLIST_ACTIVE_LATER 0x20
|
||||
#define EVLIST_FINALIZING 0x40
|
||||
#define EVLIST_INIT 0x80
|
||||
|
||||
#define EVLIST_ALL 0xff
|
||||
|
||||
/* Fix so that people don't have to run with <sys/queue.h> */
|
||||
#ifndef TAILQ_ENTRY
|
||||
#define EVENT_DEFINED_TQENTRY_
|
||||
#define TAILQ_ENTRY(type) \
|
||||
struct { \
|
||||
struct type *tqe_next; /* next element */ \
|
||||
struct type **tqe_prev; /* address of previous next element */ \
|
||||
}
|
||||
#endif /* !TAILQ_ENTRY */
|
||||
|
||||
#ifndef TAILQ_HEAD
|
||||
#define EVENT_DEFINED_TQHEAD_
|
||||
#define TAILQ_HEAD(name, type) \
|
||||
struct name { \
|
||||
struct type *tqh_first; \
|
||||
struct type **tqh_last; \
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Fix so that people don't have to run with <sys/queue.h> */
|
||||
#ifndef LIST_ENTRY
|
||||
#define EVENT_DEFINED_LISTENTRY_
|
||||
#define LIST_ENTRY(type) \
|
||||
struct { \
|
||||
struct type *le_next; /* next element */ \
|
||||
struct type **le_prev; /* address of previous next element */ \
|
||||
}
|
||||
#endif /* !LIST_ENTRY */
|
||||
|
||||
#ifndef LIST_HEAD
|
||||
#define EVENT_DEFINED_LISTHEAD_
|
||||
#define LIST_HEAD(name, type) \
|
||||
struct name { \
|
||||
struct type *lh_first; /* first element */ \
|
||||
}
|
||||
#endif /* !LIST_HEAD */
|
||||
|
||||
struct event;
|
||||
|
||||
struct event_callback {
|
||||
TAILQ_ENTRY(event_callback) evcb_active_next;
|
||||
short evcb_flags;
|
||||
ev_uint8_t evcb_pri; /* smaller numbers are higher priority */
|
||||
ev_uint8_t evcb_closure;
|
||||
/* allows us to adopt for different types of events */
|
||||
union {
|
||||
void (*evcb_callback)(evutil_socket_t, short, void *);
|
||||
void (*evcb_selfcb)(struct event_callback *, void *);
|
||||
void (*evcb_evfinalize)(struct event *, void *);
|
||||
void (*evcb_cbfinalize)(struct event_callback *, void *);
|
||||
} evcb_cb_union;
|
||||
void *evcb_arg;
|
||||
};
|
||||
|
||||
struct event_base;
|
||||
struct event {
|
||||
struct event_callback ev_evcallback;
|
||||
|
||||
/* for managing timeouts */
|
||||
union {
|
||||
TAILQ_ENTRY(event) ev_next_with_common_timeout;
|
||||
int min_heap_idx;
|
||||
} ev_timeout_pos;
|
||||
evutil_socket_t ev_fd;
|
||||
|
||||
struct event_base *ev_base;
|
||||
|
||||
union {
|
||||
/* used for io events */
|
||||
struct {
|
||||
LIST_ENTRY (event) ev_io_next;
|
||||
struct timeval ev_timeout;
|
||||
} ev_io;
|
||||
|
||||
/* used by signal events */
|
||||
struct {
|
||||
LIST_ENTRY (event) ev_signal_next;
|
||||
short ev_ncalls;
|
||||
/* Allows deletes in callback */
|
||||
short *ev_pncalls;
|
||||
} ev_signal;
|
||||
} ev_;
|
||||
|
||||
short ev_events;
|
||||
short ev_res; /* result passed to event callback */
|
||||
struct timeval ev_timeout;
|
||||
};
|
||||
|
||||
TAILQ_HEAD (event_list, event);
|
||||
|
||||
#ifdef EVENT_DEFINED_TQENTRY_
|
||||
#undef TAILQ_ENTRY
|
||||
#endif
|
||||
|
||||
#ifdef EVENT_DEFINED_TQHEAD_
|
||||
#undef TAILQ_HEAD
|
||||
#endif
|
||||
|
||||
LIST_HEAD (event_dlist, event);
|
||||
|
||||
#ifdef EVENT_DEFINED_LISTENTRY_
|
||||
#undef LIST_ENTRY
|
||||
#endif
|
||||
|
||||
#ifdef EVENT_DEFINED_LISTHEAD_
|
||||
#undef LIST_HEAD
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_EVENT_STRUCT_H_INCLUDED_ */
|
File diff suppressed because it is too large
Load Diff
|
@ -1,90 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_HTTP_COMPAT_H_INCLUDED_
|
||||
#define EVENT2_HTTP_COMPAT_H_INCLUDED_
|
||||
|
||||
/** @file event2/http_compat.h
|
||||
|
||||
Potentially non-threadsafe versions of the functions in http.h: provided
|
||||
only for backwards compatibility.
|
||||
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
#ifdef EVENT__HAVE_SYS_TYPES_H
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_SYS_TIME_H
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
|
||||
/* For int types. */
|
||||
#include <event2/util.h>
|
||||
|
||||
/**
|
||||
* Start an HTTP server on the specified address and port
|
||||
*
|
||||
* @deprecated It does not allow an event base to be specified
|
||||
*
|
||||
* @param address the address to which the HTTP server should be bound
|
||||
* @param port the port number on which the HTTP server should listen
|
||||
* @return an struct evhttp object
|
||||
*/
|
||||
struct evhttp *evhttp_start(const char *address, ev_uint16_t port);
|
||||
|
||||
/**
|
||||
* A connection object that can be used to for making HTTP requests. The
|
||||
* connection object tries to establish the connection when it is given an
|
||||
* http request object.
|
||||
*
|
||||
* @deprecated It does not allow an event base to be specified
|
||||
*/
|
||||
struct evhttp_connection *evhttp_connection_new(
|
||||
const char *address, ev_uint16_t port);
|
||||
|
||||
/**
|
||||
* Associates an event base with the connection - can only be called
|
||||
* on a freshly created connection object that has not been used yet.
|
||||
*
|
||||
* @deprecated XXXX Why?
|
||||
*/
|
||||
void evhttp_connection_set_base(struct evhttp_connection *evcon,
|
||||
struct event_base *base);
|
||||
|
||||
|
||||
/** Returns the request URI */
|
||||
#define evhttp_request_uri evhttp_request_get_uri
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
|
|
@ -1,152 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_HTTP_STRUCT_H_INCLUDED_
|
||||
#define EVENT2_HTTP_STRUCT_H_INCLUDED_
|
||||
|
||||
/** @file event2/http_struct.h
|
||||
|
||||
Data structures for http. Using these structures may hurt forward
|
||||
compatibility with later versions of Libevent: be careful!
|
||||
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
#ifdef EVENT__HAVE_SYS_TYPES_H
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_SYS_TIME_H
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
|
||||
/* For int types. */
|
||||
#include <event2/util.h>
|
||||
|
||||
/**
|
||||
* the request structure that a server receives.
|
||||
* WARNING: expect this structure to change. I will try to provide
|
||||
* reasonable accessors.
|
||||
*/
|
||||
struct evhttp_request {
|
||||
#if defined(TAILQ_ENTRY)
|
||||
TAILQ_ENTRY(evhttp_request) next;
|
||||
#else
|
||||
struct {
|
||||
struct evhttp_request *tqe_next;
|
||||
struct evhttp_request **tqe_prev;
|
||||
} next;
|
||||
#endif
|
||||
|
||||
/* the connection object that this request belongs to */
|
||||
struct evhttp_connection *evcon;
|
||||
int flags;
|
||||
/** The request obj owns the evhttp connection and needs to free it */
|
||||
#define EVHTTP_REQ_OWN_CONNECTION 0x0001
|
||||
/** Request was made via a proxy */
|
||||
#define EVHTTP_PROXY_REQUEST 0x0002
|
||||
/** The request object is owned by the user; the user must free it */
|
||||
#define EVHTTP_USER_OWNED 0x0004
|
||||
/** The request will be used again upstack; freeing must be deferred */
|
||||
#define EVHTTP_REQ_DEFER_FREE 0x0008
|
||||
/** The request should be freed upstack */
|
||||
#define EVHTTP_REQ_NEEDS_FREE 0x0010
|
||||
|
||||
struct evkeyvalq *input_headers;
|
||||
struct evkeyvalq *output_headers;
|
||||
|
||||
/* address of the remote host and the port connection came from */
|
||||
char *remote_host;
|
||||
ev_uint16_t remote_port;
|
||||
|
||||
/* cache of the hostname for evhttp_request_get_host */
|
||||
char *host_cache;
|
||||
|
||||
enum evhttp_request_kind kind;
|
||||
enum evhttp_cmd_type type;
|
||||
|
||||
size_t headers_size;
|
||||
size_t body_size;
|
||||
|
||||
char *uri; /* uri after HTTP request was parsed */
|
||||
struct evhttp_uri *uri_elems; /* uri elements */
|
||||
|
||||
char major; /* HTTP Major number */
|
||||
char minor; /* HTTP Minor number */
|
||||
|
||||
int response_code; /* HTTP Response code */
|
||||
char *response_code_line; /* Readable response */
|
||||
|
||||
struct evbuffer *input_buffer; /* read data */
|
||||
ev_int64_t ntoread;
|
||||
unsigned chunked:1, /* a chunked request */
|
||||
userdone:1; /* the user has sent all data */
|
||||
|
||||
struct evbuffer *output_buffer; /* outgoing post or data */
|
||||
|
||||
/* Callback */
|
||||
void (*cb)(struct evhttp_request *, void *);
|
||||
void *cb_arg;
|
||||
|
||||
/*
|
||||
* Chunked data callback - call for each completed chunk if
|
||||
* specified. If not specified, all the data is delivered via
|
||||
* the regular callback.
|
||||
*/
|
||||
void (*chunk_cb)(struct evhttp_request *, void *);
|
||||
|
||||
/*
|
||||
* Callback added for forked-daapd so they can collect ICY
|
||||
* (shoutcast) metadata from the http header. If return
|
||||
* int is negative the connection will be closed.
|
||||
*/
|
||||
int (*header_cb)(struct evhttp_request *, void *);
|
||||
|
||||
/*
|
||||
* Error callback - called when error is occured.
|
||||
* @see evhttp_request_error for error types.
|
||||
*
|
||||
* @see evhttp_request_set_error_cb()
|
||||
*/
|
||||
void (*error_cb)(enum evhttp_request_error, void *);
|
||||
|
||||
/*
|
||||
* Send complete callback - called when the request is actually
|
||||
* sent and completed.
|
||||
*/
|
||||
void (*on_complete_cb)(struct evhttp_request *, void *);
|
||||
void *on_complete_cb_arg;
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_HTTP_STRUCT_H_INCLUDED_ */
|
||||
|
|
@ -1,80 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_KEYVALQ_STRUCT_H_INCLUDED_
|
||||
#define EVENT2_KEYVALQ_STRUCT_H_INCLUDED_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Fix so that people don't have to run with <sys/queue.h> */
|
||||
/* XXXX This code is duplicated with event_struct.h */
|
||||
#ifndef TAILQ_ENTRY
|
||||
#define EVENT_DEFINED_TQENTRY_
|
||||
#define TAILQ_ENTRY(type) \
|
||||
struct { \
|
||||
struct type *tqe_next; /* next element */ \
|
||||
struct type **tqe_prev; /* address of previous next element */ \
|
||||
}
|
||||
#endif /* !TAILQ_ENTRY */
|
||||
|
||||
#ifndef TAILQ_HEAD
|
||||
#define EVENT_DEFINED_TQHEAD_
|
||||
#define TAILQ_HEAD(name, type) \
|
||||
struct name { \
|
||||
struct type *tqh_first; \
|
||||
struct type **tqh_last; \
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Key-Value pairs. Can be used for HTTP headers but also for
|
||||
* query argument parsing.
|
||||
*/
|
||||
struct evkeyval {
|
||||
TAILQ_ENTRY(evkeyval) next;
|
||||
|
||||
char *key;
|
||||
char *value;
|
||||
};
|
||||
|
||||
TAILQ_HEAD (evkeyvalq, evkeyval);
|
||||
|
||||
/* XXXX This code is duplicated with event_struct.h */
|
||||
#ifdef EVENT_DEFINED_TQENTRY_
|
||||
#undef TAILQ_ENTRY
|
||||
#endif
|
||||
|
||||
#ifdef EVENT_DEFINED_TQHEAD_
|
||||
#undef TAILQ_HEAD
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
|
@ -1,180 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_LISTENER_H_INCLUDED_
|
||||
#define EVENT2_LISTENER_H_INCLUDED_
|
||||
|
||||
#include <event2/visibility.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event.h>
|
||||
|
||||
struct sockaddr;
|
||||
struct evconnlistener;
|
||||
|
||||
/**
|
||||
A callback that we invoke when a listener has a new connection.
|
||||
|
||||
@param listener The evconnlistener
|
||||
@param fd The new file descriptor
|
||||
@param addr The source address of the connection
|
||||
@param socklen The length of addr
|
||||
@param user_arg the pointer passed to evconnlistener_new()
|
||||
*/
|
||||
typedef void (*evconnlistener_cb)(struct evconnlistener *, evutil_socket_t, struct sockaddr *, int socklen, void *);
|
||||
|
||||
/**
|
||||
A callback that we invoke when a listener encounters a non-retriable error.
|
||||
|
||||
@param listener The evconnlistener
|
||||
@param user_arg the pointer passed to evconnlistener_new()
|
||||
*/
|
||||
typedef void (*evconnlistener_errorcb)(struct evconnlistener *, void *);
|
||||
|
||||
/** Flag: Indicates that we should not make incoming sockets nonblocking
|
||||
* before passing them to the callback. */
|
||||
#define LEV_OPT_LEAVE_SOCKETS_BLOCKING (1u<<0)
|
||||
/** Flag: Indicates that freeing the listener should close the underlying
|
||||
* socket. */
|
||||
#define LEV_OPT_CLOSE_ON_FREE (1u<<1)
|
||||
/** Flag: Indicates that we should set the close-on-exec flag, if possible */
|
||||
#define LEV_OPT_CLOSE_ON_EXEC (1u<<2)
|
||||
/** Flag: Indicates that we should disable the timeout (if any) between when
|
||||
* this socket is closed and when we can listen again on the same port. */
|
||||
#define LEV_OPT_REUSEABLE (1u<<3)
|
||||
/** Flag: Indicates that the listener should be locked so it's safe to use
|
||||
* from multiple threadcs at once. */
|
||||
#define LEV_OPT_THREADSAFE (1u<<4)
|
||||
/** Flag: Indicates that the listener should be created in disabled
|
||||
* state. Use evconnlistener_enable() to enable it later. */
|
||||
#define LEV_OPT_DISABLED (1u<<5)
|
||||
/** Flag: Indicates that the listener should defer accept() until data is
|
||||
* available, if possible. Ignored on platforms that do not support this.
|
||||
*
|
||||
* This option can help performance for protocols where the client transmits
|
||||
* immediately after connecting. Do not use this option if your protocol
|
||||
* _doesn't_ start out with the client transmitting data, since in that case
|
||||
* this option will sometimes cause the kernel to never tell you about the
|
||||
* connection.
|
||||
*
|
||||
* This option is only supported by evconnlistener_new_bind(): it can't
|
||||
* work with evconnlistener_new_fd(), since the listener needs to be told
|
||||
* to use the option before it is actually bound.
|
||||
*/
|
||||
#define LEV_OPT_DEFERRED_ACCEPT (1u<<6)
|
||||
/** Flag: Indicates that we ask to allow multiple servers (processes or
|
||||
* threads) to bind to the same port if they each set the option.
|
||||
*
|
||||
* SO_REUSEPORT is what most people would expect SO_REUSEADDR to be, however
|
||||
* SO_REUSEPORT does not imply SO_REUSEADDR.
|
||||
*
|
||||
* This is only available on Linux and kernel 3.9+
|
||||
*/
|
||||
#define LEV_OPT_REUSEABLE_PORT (1u<<7)
|
||||
|
||||
/**
|
||||
Allocate a new evconnlistener object to listen for incoming TCP connections
|
||||
on a given file descriptor.
|
||||
|
||||
@param base The event base to associate the listener with.
|
||||
@param cb A callback to be invoked when a new connection arrives. If the
|
||||
callback is NULL, the listener will be treated as disabled until the
|
||||
callback is set.
|
||||
@param ptr A user-supplied pointer to give to the callback.
|
||||
@param flags Any number of LEV_OPT_* flags
|
||||
@param backlog Passed to the listen() call to determine the length of the
|
||||
acceptable connection backlog. Set to -1 for a reasonable default.
|
||||
Set to 0 if the socket is already listening.
|
||||
@param fd The file descriptor to listen on. It must be a nonblocking
|
||||
file descriptor, and it should already be bound to an appropriate
|
||||
port and address.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct evconnlistener *evconnlistener_new(struct event_base *base,
|
||||
evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
|
||||
evutil_socket_t fd);
|
||||
/**
|
||||
Allocate a new evconnlistener object to listen for incoming TCP connections
|
||||
on a given address.
|
||||
|
||||
@param base The event base to associate the listener with.
|
||||
@param cb A callback to be invoked when a new connection arrives. If the
|
||||
callback is NULL, the listener will be treated as disabled until the
|
||||
callback is set.
|
||||
@param ptr A user-supplied pointer to give to the callback.
|
||||
@param flags Any number of LEV_OPT_* flags
|
||||
@param backlog Passed to the listen() call to determine the length of the
|
||||
acceptable connection backlog. Set to -1 for a reasonable default.
|
||||
@param addr The address to listen for connections on.
|
||||
@param socklen The length of the address.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct evconnlistener *evconnlistener_new_bind(struct event_base *base,
|
||||
evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
|
||||
const struct sockaddr *sa, int socklen);
|
||||
/**
|
||||
Disable and deallocate an evconnlistener.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evconnlistener_free(struct evconnlistener *lev);
|
||||
/**
|
||||
Re-enable an evconnlistener that has been disabled.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evconnlistener_enable(struct evconnlistener *lev);
|
||||
/**
|
||||
Stop listening for connections on an evconnlistener.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evconnlistener_disable(struct evconnlistener *lev);
|
||||
|
||||
/** Return an evconnlistener's associated event_base. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct event_base *evconnlistener_get_base(struct evconnlistener *lev);
|
||||
|
||||
/** Return the socket that an evconnlistner is listening on. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
evutil_socket_t evconnlistener_get_fd(struct evconnlistener *lev);
|
||||
|
||||
/** Change the callback on the listener to cb and its user_data to arg.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evconnlistener_set_cb(struct evconnlistener *lev,
|
||||
evconnlistener_cb cb, void *arg);
|
||||
|
||||
/** Set an evconnlistener's error callback. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evconnlistener_set_error_cb(struct evconnlistener *lev,
|
||||
evconnlistener_errorcb errorcb);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
|
@ -1,596 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_RPC_H_INCLUDED_
|
||||
#define EVENT2_RPC_H_INCLUDED_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** @file rpc.h
|
||||
*
|
||||
* This header files provides basic support for an RPC server and client.
|
||||
*
|
||||
* To support RPCs in a server, every supported RPC command needs to be
|
||||
* defined and registered.
|
||||
*
|
||||
* EVRPC_HEADER(SendCommand, Request, Reply);
|
||||
*
|
||||
* SendCommand is the name of the RPC command.
|
||||
* Request is the name of a structure generated by event_rpcgen.py.
|
||||
* It contains all parameters relating to the SendCommand RPC. The
|
||||
* server needs to fill in the Reply structure.
|
||||
* Reply is the name of a structure generated by event_rpcgen.py. It
|
||||
* contains the answer to the RPC.
|
||||
*
|
||||
* To register an RPC with an HTTP server, you need to first create an RPC
|
||||
* base with:
|
||||
*
|
||||
* struct evrpc_base *base = evrpc_init(http);
|
||||
*
|
||||
* A specific RPC can then be registered with
|
||||
*
|
||||
* EVRPC_REGISTER(base, SendCommand, Request, Reply, FunctionCB, arg);
|
||||
*
|
||||
* when the server receives an appropriately formatted RPC, the user callback
|
||||
* is invoked. The callback needs to fill in the reply structure.
|
||||
*
|
||||
* void FunctionCB(EVRPC_STRUCT(SendCommand)* rpc, void *arg);
|
||||
*
|
||||
* To send the reply, call EVRPC_REQUEST_DONE(rpc);
|
||||
*
|
||||
* See the regression test for an example.
|
||||
*/
|
||||
|
||||
/**
|
||||
Determines if the member has been set in the message
|
||||
|
||||
@param msg the message to inspect
|
||||
@param member the member variable to test for presences
|
||||
@return 1 if it's present or 0 otherwise.
|
||||
*/
|
||||
#define EVTAG_HAS(msg, member) \
|
||||
((msg)->member##_set == 1)
|
||||
|
||||
#ifndef EVENT2_RPC_COMPAT_H_INCLUDED_
|
||||
|
||||
/**
|
||||
Assigns a value to the member in the message.
|
||||
|
||||
@param msg the message to which to assign a value
|
||||
@param member the name of the member variable
|
||||
@param value the value to assign
|
||||
*/
|
||||
#define EVTAG_ASSIGN(msg, member, value) \
|
||||
(*(msg)->base->member##_assign)((msg), (value))
|
||||
/**
|
||||
Assigns a value to the member in the message.
|
||||
|
||||
@param msg the message to which to assign a value
|
||||
@param member the name of the member variable
|
||||
@param value the value to assign
|
||||
@param len the length of the value
|
||||
*/
|
||||
#define EVTAG_ASSIGN_WITH_LEN(msg, member, value, len) \
|
||||
(*(msg)->base->member##_assign)((msg), (value), (len))
|
||||
/**
|
||||
Returns the value for a member.
|
||||
|
||||
@param msg the message from which to get the value
|
||||
@param member the name of the member variable
|
||||
@param pvalue a pointer to the variable to hold the value
|
||||
@return 0 on success, -1 otherwise.
|
||||
*/
|
||||
#define EVTAG_GET(msg, member, pvalue) \
|
||||
(*(msg)->base->member##_get)((msg), (pvalue))
|
||||
/**
|
||||
Returns the value for a member.
|
||||
|
||||
@param msg the message from which to get the value
|
||||
@param member the name of the member variable
|
||||
@param pvalue a pointer to the variable to hold the value
|
||||
@param plen a pointer to the length of the value
|
||||
@return 0 on success, -1 otherwise.
|
||||
*/
|
||||
#define EVTAG_GET_WITH_LEN(msg, member, pvalue, plen) \
|
||||
(*(msg)->base->member##_get)((msg), (pvalue), (plen))
|
||||
|
||||
#endif /* EVENT2_RPC_COMPAT_H_INCLUDED_ */
|
||||
|
||||
/**
|
||||
Adds a value to an array.
|
||||
*/
|
||||
#define EVTAG_ARRAY_ADD_VALUE(msg, member, value) \
|
||||
(*(msg)->base->member##_add)((msg), (value))
|
||||
/**
|
||||
Allocates a new entry in the array and returns it.
|
||||
*/
|
||||
#define EVTAG_ARRAY_ADD(msg, member) \
|
||||
(*(msg)->base->member##_add)(msg)
|
||||
/**
|
||||
Gets a variable at the specified offset from the array.
|
||||
*/
|
||||
#define EVTAG_ARRAY_GET(msg, member, offset, pvalue) \
|
||||
(*(msg)->base->member##_get)((msg), (offset), (pvalue))
|
||||
/**
|
||||
Returns the number of entries in the array.
|
||||
*/
|
||||
#define EVTAG_ARRAY_LEN(msg, member) ((msg)->member##_length)
|
||||
|
||||
|
||||
struct evbuffer;
|
||||
struct event_base;
|
||||
struct evrpc_req_generic;
|
||||
struct evrpc_request_wrapper;
|
||||
struct evrpc;
|
||||
|
||||
/** The type of a specific RPC Message
|
||||
*
|
||||
* @param rpcname the name of the RPC message
|
||||
*/
|
||||
#define EVRPC_STRUCT(rpcname) struct evrpc_req__##rpcname
|
||||
|
||||
struct evhttp_request;
|
||||
struct evrpc_status;
|
||||
struct evrpc_hook_meta;
|
||||
|
||||
/** Creates the definitions and prototypes for an RPC
|
||||
*
|
||||
* You need to use EVRPC_HEADER to create structures and function prototypes
|
||||
* needed by the server and client implementation. The structures have to be
|
||||
* defined in an .rpc file and converted to source code via event_rpcgen.py
|
||||
*
|
||||
* @param rpcname the name of the RPC
|
||||
* @param reqstruct the name of the RPC request structure
|
||||
* @param replystruct the name of the RPC reply structure
|
||||
* @see EVRPC_GENERATE()
|
||||
*/
|
||||
#define EVRPC_HEADER(rpcname, reqstruct, rplystruct) \
|
||||
EVRPC_STRUCT(rpcname) { \
|
||||
struct evrpc_hook_meta *hook_meta; \
|
||||
struct reqstruct* request; \
|
||||
struct rplystruct* reply; \
|
||||
struct evrpc* rpc; \
|
||||
struct evhttp_request* http_req; \
|
||||
struct evbuffer* rpc_data; \
|
||||
}; \
|
||||
int evrpc_send_request_##rpcname(struct evrpc_pool *, \
|
||||
struct reqstruct *, struct rplystruct *, \
|
||||
void (*)(struct evrpc_status *, \
|
||||
struct reqstruct *, struct rplystruct *, void *cbarg), \
|
||||
void *);
|
||||
|
||||
struct evrpc_pool;
|
||||
|
||||
/** use EVRPC_GENERATE instead */
|
||||
struct evrpc_request_wrapper *evrpc_make_request_ctx(
|
||||
struct evrpc_pool *pool, void *request, void *reply,
|
||||
const char *rpcname,
|
||||
void (*req_marshal)(struct evbuffer*, void *),
|
||||
void (*rpl_clear)(void *),
|
||||
int (*rpl_unmarshal)(void *, struct evbuffer *),
|
||||
void (*cb)(struct evrpc_status *, void *, void *, void *),
|
||||
void *cbarg);
|
||||
|
||||
/** Creates a context structure that contains rpc specific information.
|
||||
*
|
||||
* EVRPC_MAKE_CTX is used to populate a RPC specific context that
|
||||
* contains information about marshaling the RPC data types.
|
||||
*
|
||||
* @param rpcname the name of the RPC
|
||||
* @param reqstruct the name of the RPC request structure
|
||||
* @param replystruct the name of the RPC reply structure
|
||||
* @param pool the evrpc_pool over which to make the request
|
||||
* @param request a pointer to the RPC request structure object
|
||||
* @param reply a pointer to the RPC reply structure object
|
||||
* @param cb the callback function to call when the RPC has completed
|
||||
* @param cbarg the argument to supply to the callback
|
||||
*/
|
||||
#define EVRPC_MAKE_CTX(rpcname, reqstruct, rplystruct, \
|
||||
pool, request, reply, cb, cbarg) \
|
||||
evrpc_make_request_ctx(pool, request, reply, \
|
||||
#rpcname, \
|
||||
(void (*)(struct evbuffer *, void *))reqstruct##_marshal, \
|
||||
(void (*)(void *))rplystruct##_clear, \
|
||||
(int (*)(void *, struct evbuffer *))rplystruct##_unmarshal, \
|
||||
(void (*)(struct evrpc_status *, void *, void *, void *))cb, \
|
||||
cbarg)
|
||||
|
||||
/** Generates the code for receiving and sending an RPC message
|
||||
*
|
||||
* EVRPC_GENERATE is used to create the code corresponding to sending
|
||||
* and receiving a particular RPC message
|
||||
*
|
||||
* @param rpcname the name of the RPC
|
||||
* @param reqstruct the name of the RPC request structure
|
||||
* @param replystruct the name of the RPC reply structure
|
||||
* @see EVRPC_HEADER()
|
||||
*/
|
||||
#define EVRPC_GENERATE(rpcname, reqstruct, rplystruct) \
|
||||
int evrpc_send_request_##rpcname(struct evrpc_pool *pool, \
|
||||
struct reqstruct *request, struct rplystruct *reply, \
|
||||
void (*cb)(struct evrpc_status *, \
|
||||
struct reqstruct *, struct rplystruct *, void *cbarg), \
|
||||
void *cbarg) { \
|
||||
return evrpc_send_request_generic(pool, request, reply, \
|
||||
(void (*)(struct evrpc_status *, void *, void *, void *))cb, \
|
||||
cbarg, \
|
||||
#rpcname, \
|
||||
(void (*)(struct evbuffer *, void *))reqstruct##_marshal, \
|
||||
(void (*)(void *))rplystruct##_clear, \
|
||||
(int (*)(void *, struct evbuffer *))rplystruct##_unmarshal); \
|
||||
}
|
||||
|
||||
/** Provides access to the HTTP request object underlying an RPC
|
||||
*
|
||||
* Access to the underlying http object; can be used to look at headers or
|
||||
* for getting the remote ip address
|
||||
*
|
||||
* @param rpc_req the rpc request structure provided to the server callback
|
||||
* @return an struct evhttp_request object that can be inspected for
|
||||
* HTTP headers or sender information.
|
||||
*/
|
||||
#define EVRPC_REQUEST_HTTP(rpc_req) (rpc_req)->http_req
|
||||
|
||||
/** completes the server response to an rpc request */
|
||||
void evrpc_request_done(struct evrpc_req_generic *req);
|
||||
|
||||
/** accessors for request and reply */
|
||||
void *evrpc_get_request(struct evrpc_req_generic *req);
|
||||
void *evrpc_get_reply(struct evrpc_req_generic *req);
|
||||
|
||||
/** Creates the reply to an RPC request
|
||||
*
|
||||
* EVRPC_REQUEST_DONE is used to answer a request; the reply is expected
|
||||
* to have been filled in. The request and reply pointers become invalid
|
||||
* after this call has finished.
|
||||
*
|
||||
* @param rpc_req the rpc request structure provided to the server callback
|
||||
*/
|
||||
#define EVRPC_REQUEST_DONE(rpc_req) do { \
|
||||
struct evrpc_req_generic *req_ = (struct evrpc_req_generic *)(rpc_req); \
|
||||
evrpc_request_done(req_); \
|
||||
} while (0)
|
||||
|
||||
|
||||
struct evrpc_base;
|
||||
struct evhttp;
|
||||
|
||||
/* functions to start up the rpc system */
|
||||
|
||||
/** Creates a new rpc base from which RPC requests can be received
|
||||
*
|
||||
* @param server a pointer to an existing HTTP server
|
||||
* @return a newly allocated evrpc_base struct
|
||||
* @see evrpc_free()
|
||||
*/
|
||||
struct evrpc_base *evrpc_init(struct evhttp *server);
|
||||
|
||||
/**
|
||||
* Frees the evrpc base
|
||||
*
|
||||
* For now, you are responsible for making sure that no rpcs are ongoing.
|
||||
*
|
||||
* @param base the evrpc_base object to be freed
|
||||
* @see evrpc_init
|
||||
*/
|
||||
void evrpc_free(struct evrpc_base *base);
|
||||
|
||||
/** register RPCs with the HTTP Server
|
||||
*
|
||||
* registers a new RPC with the HTTP server, each RPC needs to have
|
||||
* a unique name under which it can be identified.
|
||||
*
|
||||
* @param base the evrpc_base structure in which the RPC should be
|
||||
* registered.
|
||||
* @param name the name of the RPC
|
||||
* @param request the name of the RPC request structure
|
||||
* @param reply the name of the RPC reply structure
|
||||
* @param callback the callback that should be invoked when the RPC
|
||||
* is received. The callback has the following prototype
|
||||
* void (*callback)(EVRPC_STRUCT(Message)* rpc, void *arg)
|
||||
* @param cbarg an additional parameter that can be passed to the callback.
|
||||
* The parameter can be used to carry around state.
|
||||
*/
|
||||
#define EVRPC_REGISTER(base, name, request, reply, callback, cbarg) \
|
||||
evrpc_register_generic(base, #name, \
|
||||
(void (*)(struct evrpc_req_generic *, void *))callback, cbarg, \
|
||||
(void *(*)(void *))request##_new, NULL, \
|
||||
(void (*)(void *))request##_free, \
|
||||
(int (*)(void *, struct evbuffer *))request##_unmarshal, \
|
||||
(void *(*)(void *))reply##_new, NULL, \
|
||||
(void (*)(void *))reply##_free, \
|
||||
(int (*)(void *))reply##_complete, \
|
||||
(void (*)(struct evbuffer *, void *))reply##_marshal)
|
||||
|
||||
/**
|
||||
Low level function for registering an RPC with a server.
|
||||
|
||||
Use EVRPC_REGISTER() instead.
|
||||
|
||||
@see EVRPC_REGISTER()
|
||||
*/
|
||||
int evrpc_register_rpc(struct evrpc_base *, struct evrpc *,
|
||||
void (*)(struct evrpc_req_generic*, void *), void *);
|
||||
|
||||
/**
|
||||
* Unregisters an already registered RPC
|
||||
*
|
||||
* @param base the evrpc_base object from which to unregister an RPC
|
||||
* @param name the name of the rpc to unregister
|
||||
* @return -1 on error or 0 when successful.
|
||||
* @see EVRPC_REGISTER()
|
||||
*/
|
||||
#define EVRPC_UNREGISTER(base, name) evrpc_unregister_rpc((base), #name)
|
||||
|
||||
int evrpc_unregister_rpc(struct evrpc_base *base, const char *name);
|
||||
|
||||
/*
|
||||
* Client-side RPC support
|
||||
*/
|
||||
|
||||
struct evhttp_connection;
|
||||
struct evrpc_status;
|
||||
|
||||
/** launches an RPC and sends it to the server
|
||||
*
|
||||
* EVRPC_MAKE_REQUEST() is used by the client to send an RPC to the server.
|
||||
*
|
||||
* @param name the name of the RPC
|
||||
* @param pool the evrpc_pool that contains the connection objects over which
|
||||
* the request should be sent.
|
||||
* @param request a pointer to the RPC request structure - it contains the
|
||||
* data to be sent to the server.
|
||||
* @param reply a pointer to the RPC reply structure. It is going to be filled
|
||||
* if the request was answered successfully
|
||||
* @param cb the callback to invoke when the RPC request has been answered
|
||||
* @param cbarg an additional argument to be passed to the client
|
||||
* @return 0 on success, -1 on failure
|
||||
*/
|
||||
#define EVRPC_MAKE_REQUEST(name, pool, request, reply, cb, cbarg) \
|
||||
evrpc_send_request_##name((pool), (request), (reply), (cb), (cbarg))
|
||||
|
||||
/**
|
||||
Makes an RPC request based on the provided context.
|
||||
|
||||
This is a low-level function and should not be used directly
|
||||
unless a custom context object is provided. Use EVRPC_MAKE_REQUEST()
|
||||
instead.
|
||||
|
||||
@param ctx a context from EVRPC_MAKE_CTX()
|
||||
@returns 0 on success, -1 otherwise.
|
||||
@see EVRPC_MAKE_REQUEST(), EVRPC_MAKE_CTX()
|
||||
*/
|
||||
int evrpc_make_request(struct evrpc_request_wrapper *ctx);
|
||||
|
||||
/** creates an rpc connection pool
|
||||
*
|
||||
* a pool has a number of connections associated with it.
|
||||
* rpc requests are always made via a pool.
|
||||
*
|
||||
* @param base a pointer to an struct event_based object; can be left NULL
|
||||
* in singled-threaded applications
|
||||
* @return a newly allocated struct evrpc_pool object
|
||||
* @see evrpc_pool_free()
|
||||
*/
|
||||
struct evrpc_pool *evrpc_pool_new(struct event_base *base);
|
||||
/** frees an rpc connection pool
|
||||
*
|
||||
* @param pool a pointer to an evrpc_pool allocated via evrpc_pool_new()
|
||||
* @see evrpc_pool_new()
|
||||
*/
|
||||
void evrpc_pool_free(struct evrpc_pool *pool);
|
||||
|
||||
/**
|
||||
* Adds a connection over which rpc can be dispatched to the pool.
|
||||
*
|
||||
* The connection object must have been newly created.
|
||||
*
|
||||
* @param pool the pool to which to add the connection
|
||||
* @param evcon the connection to add to the pool.
|
||||
*/
|
||||
void evrpc_pool_add_connection(struct evrpc_pool *pool,
|
||||
struct evhttp_connection *evcon);
|
||||
|
||||
/**
|
||||
* Removes a connection from the pool.
|
||||
*
|
||||
* The connection object must have been newly created.
|
||||
*
|
||||
* @param pool the pool from which to remove the connection
|
||||
* @param evcon the connection to remove from the pool.
|
||||
*/
|
||||
void evrpc_pool_remove_connection(struct evrpc_pool *pool,
|
||||
struct evhttp_connection *evcon);
|
||||
|
||||
/**
|
||||
* Sets the timeout in secs after which a request has to complete. The
|
||||
* RPC is completely aborted if it does not complete by then. Setting
|
||||
* the timeout to 0 means that it never timeouts and can be used to
|
||||
* implement callback type RPCs.
|
||||
*
|
||||
* Any connection already in the pool will be updated with the new
|
||||
* timeout. Connections added to the pool after set_timeout has be
|
||||
* called receive the pool timeout only if no timeout has been set
|
||||
* for the connection itself.
|
||||
*
|
||||
* @param pool a pointer to a struct evrpc_pool object
|
||||
* @param timeout_in_secs the number of seconds after which a request should
|
||||
* timeout and a failure be returned to the callback.
|
||||
*/
|
||||
void evrpc_pool_set_timeout(struct evrpc_pool *pool, int timeout_in_secs);
|
||||
|
||||
/**
|
||||
* Hooks for changing the input and output of RPCs; this can be used to
|
||||
* implement compression, authentication, encryption, ...
|
||||
*/
|
||||
|
||||
enum EVRPC_HOOK_TYPE {
|
||||
EVRPC_INPUT, /**< apply the function to an input hook */
|
||||
EVRPC_OUTPUT /**< apply the function to an output hook */
|
||||
};
|
||||
|
||||
#ifndef _WIN32
|
||||
/** Deprecated alias for EVRPC_INPUT. Not available on windows, where it
|
||||
* conflicts with platform headers. */
|
||||
#define INPUT EVRPC_INPUT
|
||||
/** Deprecated alias for EVRPC_OUTPUT. Not available on windows, where it
|
||||
* conflicts with platform headers. */
|
||||
#define OUTPUT EVRPC_OUTPUT
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Return value from hook processing functions
|
||||
*/
|
||||
|
||||
enum EVRPC_HOOK_RESULT {
|
||||
EVRPC_TERMINATE = -1, /**< indicates the rpc should be terminated */
|
||||
EVRPC_CONTINUE = 0, /**< continue processing the rpc */
|
||||
EVRPC_PAUSE = 1 /**< pause processing request until resumed */
|
||||
};
|
||||
|
||||
/** adds a processing hook to either an rpc base or rpc pool
|
||||
*
|
||||
* If a hook returns TERMINATE, the processing is aborted. On CONTINUE,
|
||||
* the request is immediately processed after the hook returns. If the
|
||||
* hook returns PAUSE, request processing stops until evrpc_resume_request()
|
||||
* has been called.
|
||||
*
|
||||
* The add functions return handles that can be used for removing hooks.
|
||||
*
|
||||
* @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
|
||||
* @param hook_type either INPUT or OUTPUT
|
||||
* @param cb the callback to call when the hook is activated
|
||||
* @param cb_arg an additional argument for the callback
|
||||
* @return a handle to the hook so it can be removed later
|
||||
* @see evrpc_remove_hook()
|
||||
*/
|
||||
void *evrpc_add_hook(void *vbase,
|
||||
enum EVRPC_HOOK_TYPE hook_type,
|
||||
int (*cb)(void *, struct evhttp_request *, struct evbuffer *, void *),
|
||||
void *cb_arg);
|
||||
|
||||
/** removes a previously added hook
|
||||
*
|
||||
* @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
|
||||
* @param hook_type either INPUT or OUTPUT
|
||||
* @param handle a handle returned by evrpc_add_hook()
|
||||
* @return 1 on success or 0 on failure
|
||||
* @see evrpc_add_hook()
|
||||
*/
|
||||
int evrpc_remove_hook(void *vbase,
|
||||
enum EVRPC_HOOK_TYPE hook_type,
|
||||
void *handle);
|
||||
|
||||
/** resume a paused request
|
||||
*
|
||||
* @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
|
||||
* @param ctx the context pointer provided to the original hook call
|
||||
*/
|
||||
int
|
||||
evrpc_resume_request(void *vbase, void *ctx, enum EVRPC_HOOK_RESULT res);
|
||||
|
||||
/** adds meta data to request
|
||||
*
|
||||
* evrpc_hook_add_meta() allows hooks to add meta data to a request. for
|
||||
* a client request, the meta data can be inserted by an outgoing request hook
|
||||
* and retrieved by the incoming request hook.
|
||||
*
|
||||
* @param ctx the context provided to the hook call
|
||||
* @param key a NUL-terminated c-string
|
||||
* @param data the data to be associated with the key
|
||||
* @param data_size the size of the data
|
||||
*/
|
||||
void evrpc_hook_add_meta(void *ctx, const char *key,
|
||||
const void *data, size_t data_size);
|
||||
|
||||
/** retrieves meta data previously associated
|
||||
*
|
||||
* evrpc_hook_find_meta() can be used to retrieve meta data associated to a
|
||||
* request by a previous hook.
|
||||
* @param ctx the context provided to the hook call
|
||||
* @param key a NUL-terminated c-string
|
||||
* @param data pointer to a data pointer that will contain the retrieved data
|
||||
* @param data_size pointer to the size of the data
|
||||
* @return 0 on success or -1 on failure
|
||||
*/
|
||||
int evrpc_hook_find_meta(void *ctx, const char *key,
|
||||
void **data, size_t *data_size);
|
||||
|
||||
/**
|
||||
* returns the connection object associated with the request
|
||||
*
|
||||
* @param ctx the context provided to the hook call
|
||||
* @return a pointer to the evhttp_connection object
|
||||
*/
|
||||
struct evhttp_connection *evrpc_hook_get_connection(void *ctx);
|
||||
|
||||
/**
|
||||
Function for sending a generic RPC request.
|
||||
|
||||
Do not call this function directly, use EVRPC_MAKE_REQUEST() instead.
|
||||
|
||||
@see EVRPC_MAKE_REQUEST()
|
||||
*/
|
||||
int evrpc_send_request_generic(struct evrpc_pool *pool,
|
||||
void *request, void *reply,
|
||||
void (*cb)(struct evrpc_status *, void *, void *, void *),
|
||||
void *cb_arg,
|
||||
const char *rpcname,
|
||||
void (*req_marshal)(struct evbuffer *, void *),
|
||||
void (*rpl_clear)(void *),
|
||||
int (*rpl_unmarshal)(void *, struct evbuffer *));
|
||||
|
||||
/**
|
||||
Function for registering a generic RPC with the RPC base.
|
||||
|
||||
Do not call this function directly, use EVRPC_REGISTER() instead.
|
||||
|
||||
@see EVRPC_REGISTER()
|
||||
*/
|
||||
int
|
||||
evrpc_register_generic(struct evrpc_base *base, const char *name,
|
||||
void (*callback)(struct evrpc_req_generic *, void *), void *cbarg,
|
||||
void *(*req_new)(void *), void *req_new_arg, void (*req_free)(void *),
|
||||
int (*req_unmarshal)(void *, struct evbuffer *),
|
||||
void *(*rpl_new)(void *), void *rpl_new_arg, void (*rpl_free)(void *),
|
||||
int (*rpl_complete)(void *),
|
||||
void (*rpl_marshal)(struct evbuffer *, void *));
|
||||
|
||||
/** accessors for obscure and undocumented functionality */
|
||||
struct evrpc_pool* evrpc_request_get_pool(struct evrpc_request_wrapper *ctx);
|
||||
void evrpc_request_set_pool(struct evrpc_request_wrapper *ctx,
|
||||
struct evrpc_pool *pool);
|
||||
void evrpc_request_set_cb(struct evrpc_request_wrapper *ctx,
|
||||
void (*cb)(struct evrpc_status*, void *request, void *reply, void *arg),
|
||||
void *cb_arg);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_RPC_H_INCLUDED_ */
|
|
@ -1,61 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_RPC_COMPAT_H_INCLUDED_
|
||||
#define EVENT2_RPC_COMPAT_H_INCLUDED_
|
||||
|
||||
/** @file event2/rpc_compat.h
|
||||
|
||||
Deprecated versions of the functions in rpc.h: provided only for
|
||||
backwards compatibility.
|
||||
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** backwards compatible accessors that work only with gcc */
|
||||
#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
|
||||
|
||||
#undef EVTAG_ASSIGN
|
||||
#undef EVTAG_GET
|
||||
#undef EVTAG_ADD
|
||||
|
||||
#define EVTAG_ASSIGN(msg, member, args...) \
|
||||
(*(msg)->base->member##_assign)(msg, ## args)
|
||||
#define EVTAG_GET(msg, member, args...) \
|
||||
(*(msg)->base->member##_get)(msg, ## args)
|
||||
#define EVTAG_ADD(msg, member, args...) \
|
||||
(*(msg)->base->member##_add)(msg, ## args)
|
||||
#endif
|
||||
#define EVTAG_LEN(msg, member) ((msg)->member##_length)
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
|
|
@ -1,100 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_RPC_STRUCT_H_INCLUDED_
|
||||
#define EVENT2_RPC_STRUCT_H_INCLUDED_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** @file event2/rpc_struct.h
|
||||
|
||||
Structures used by rpc.h. Using these structures directly may harm
|
||||
forward compatibility: be careful!
|
||||
|
||||
*/
|
||||
|
||||
/**
|
||||
* provides information about the completed RPC request.
|
||||
*/
|
||||
struct evrpc_status {
|
||||
#define EVRPC_STATUS_ERR_NONE 0
|
||||
#define EVRPC_STATUS_ERR_TIMEOUT 1
|
||||
#define EVRPC_STATUS_ERR_BADPAYLOAD 2
|
||||
#define EVRPC_STATUS_ERR_UNSTARTED 3
|
||||
#define EVRPC_STATUS_ERR_HOOKABORTED 4
|
||||
int error;
|
||||
|
||||
/* for looking at headers or other information */
|
||||
struct evhttp_request *http_req;
|
||||
};
|
||||
|
||||
/* the structure below needs to be synchronized with evrpc_req_generic */
|
||||
|
||||
/* Encapsulates a request */
|
||||
struct evrpc {
|
||||
TAILQ_ENTRY(evrpc) next;
|
||||
|
||||
/* the URI at which the request handler lives */
|
||||
const char* uri;
|
||||
|
||||
/* creates a new request structure */
|
||||
void *(*request_new)(void *);
|
||||
void *request_new_arg;
|
||||
|
||||
/* frees the request structure */
|
||||
void (*request_free)(void *);
|
||||
|
||||
/* unmarshals the buffer into the proper request structure */
|
||||
int (*request_unmarshal)(void *, struct evbuffer *);
|
||||
|
||||
/* creates a new reply structure */
|
||||
void *(*reply_new)(void *);
|
||||
void *reply_new_arg;
|
||||
|
||||
/* frees the reply structure */
|
||||
void (*reply_free)(void *);
|
||||
|
||||
/* verifies that the reply is valid */
|
||||
int (*reply_complete)(void *);
|
||||
|
||||
/* marshals the reply into a buffer */
|
||||
void (*reply_marshal)(struct evbuffer*, void *);
|
||||
|
||||
/* the callback invoked for each received rpc */
|
||||
void (*cb)(struct evrpc_req_generic *, void *);
|
||||
void *cb_arg;
|
||||
|
||||
/* reference for further configuration */
|
||||
struct evrpc_base *base;
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_RPC_STRUCT_H_INCLUDED_ */
|
|
@ -1,146 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_TAG_H_INCLUDED_
|
||||
#define EVENT2_TAG_H_INCLUDED_
|
||||
|
||||
/** @file event2/tag.h
|
||||
|
||||
Helper functions for reading and writing tagged data onto buffers.
|
||||
|
||||
*/
|
||||
|
||||
#include <event2/visibility.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
#ifdef EVENT__HAVE_SYS_TYPES_H
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_SYS_TIME_H
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
|
||||
/* For int types. */
|
||||
#include <event2/util.h>
|
||||
|
||||
struct evbuffer;
|
||||
|
||||
/*
|
||||
* Marshaling tagged data - We assume that all tags are inserted in their
|
||||
* numeric order - so that unknown tags will always be higher than the
|
||||
* known ones - and we can just ignore the end of an event buffer.
|
||||
*/
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evtag_init(void);
|
||||
|
||||
/**
|
||||
Unmarshals the header and returns the length of the payload
|
||||
|
||||
@param evbuf the buffer from which to unmarshal data
|
||||
@param ptag a pointer in which the tag id is being stored
|
||||
@returns -1 on failure or the number of bytes in the remaining payload.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_unmarshal_header(struct evbuffer *evbuf, ev_uint32_t *ptag);
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evtag_marshal(struct evbuffer *evbuf, ev_uint32_t tag, const void *data,
|
||||
ev_uint32_t len);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evtag_marshal_buffer(struct evbuffer *evbuf, ev_uint32_t tag,
|
||||
struct evbuffer *data);
|
||||
|
||||
/**
|
||||
Encode an integer and store it in an evbuffer.
|
||||
|
||||
We encode integers by nybbles; the first nibble contains the number
|
||||
of significant nibbles - 1; this allows us to encode up to 64-bit
|
||||
integers. This function is byte-order independent.
|
||||
|
||||
@param evbuf evbuffer to store the encoded number
|
||||
@param number a 32-bit integer
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evtag_encode_int(struct evbuffer *evbuf, ev_uint32_t number);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evtag_encode_int64(struct evbuffer *evbuf, ev_uint64_t number);
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evtag_marshal_int(struct evbuffer *evbuf, ev_uint32_t tag,
|
||||
ev_uint32_t integer);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evtag_marshal_int64(struct evbuffer *evbuf, ev_uint32_t tag,
|
||||
ev_uint64_t integer);
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evtag_marshal_string(struct evbuffer *buf, ev_uint32_t tag,
|
||||
const char *string);
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evtag_marshal_timeval(struct evbuffer *evbuf, ev_uint32_t tag,
|
||||
struct timeval *tv);
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_unmarshal(struct evbuffer *src, ev_uint32_t *ptag,
|
||||
struct evbuffer *dst);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_peek(struct evbuffer *evbuf, ev_uint32_t *ptag);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_peek_length(struct evbuffer *evbuf, ev_uint32_t *plength);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_payload_length(struct evbuffer *evbuf, ev_uint32_t *plength);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_consume(struct evbuffer *evbuf);
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_unmarshal_int(struct evbuffer *evbuf, ev_uint32_t need_tag,
|
||||
ev_uint32_t *pinteger);
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_unmarshal_int64(struct evbuffer *evbuf, ev_uint32_t need_tag,
|
||||
ev_uint64_t *pinteger);
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_unmarshal_fixed(struct evbuffer *src, ev_uint32_t need_tag,
|
||||
void *data, size_t len);
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_unmarshal_string(struct evbuffer *evbuf, ev_uint32_t need_tag,
|
||||
char **pstring);
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evtag_unmarshal_timeval(struct evbuffer *evbuf, ev_uint32_t need_tag,
|
||||
struct timeval *ptv);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_TAG_H_INCLUDED_ */
|
|
@ -1,49 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_TAG_COMPAT_H_INCLUDED_
|
||||
#define EVENT2_TAG_COMPAT_H_INCLUDED_
|
||||
|
||||
/** @file event2/tag_compat.h
|
||||
|
||||
Obsolete/deprecated functions from tag.h; provided only for backwards
|
||||
compatibility.
|
||||
*/
|
||||
|
||||
/**
|
||||
@name Misnamed functions
|
||||
|
||||
@deprecated These macros are deprecated because their names don't follow
|
||||
Libevent's naming conventions. Use evtag_encode_int and
|
||||
evtag_encode_int64 instead.
|
||||
|
||||
@{
|
||||
*/
|
||||
#define encode_int(evbuf, number) evtag_encode_int((evbuf), (number))
|
||||
#define encode_int64(evbuf, number) evtag_encode_int64((evbuf), (number))
|
||||
/**@}*/
|
||||
|
||||
#endif /* EVENT2_TAG_H_INCLUDED_ */
|
|
@ -1,253 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2008-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_THREAD_H_INCLUDED_
|
||||
#define EVENT2_THREAD_H_INCLUDED_
|
||||
|
||||
/** @file event2/thread.h
|
||||
|
||||
Functions for multi-threaded applications using Libevent.
|
||||
|
||||
When using a multi-threaded application in which multiple threads
|
||||
add and delete events from a single event base, Libevent needs to
|
||||
lock its data structures.
|
||||
|
||||
Like the memory-management function hooks, all of the threading functions
|
||||
_must_ be set up before an event_base is created if you want the base to
|
||||
use them.
|
||||
|
||||
Most programs will either be using Windows threads or Posix threads. You
|
||||
can configure Libevent to use one of these event_use_windows_threads() or
|
||||
event_use_pthreads() respectively. If you're using another threading
|
||||
library, you'll need to configure threading functions manually using
|
||||
evthread_set_lock_callbacks() and evthread_set_condition_callbacks().
|
||||
|
||||
*/
|
||||
|
||||
#include <event2/visibility.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
|
||||
/**
|
||||
@name Flags passed to lock functions
|
||||
|
||||
@{
|
||||
*/
|
||||
/** A flag passed to a locking callback when the lock was allocated as a
|
||||
* read-write lock, and we want to acquire or release the lock for writing. */
|
||||
#define EVTHREAD_WRITE 0x04
|
||||
/** A flag passed to a locking callback when the lock was allocated as a
|
||||
* read-write lock, and we want to acquire or release the lock for reading. */
|
||||
#define EVTHREAD_READ 0x08
|
||||
/** A flag passed to a locking callback when we don't want to block waiting
|
||||
* for the lock; if we can't get the lock immediately, we will instead
|
||||
* return nonzero from the locking callback. */
|
||||
#define EVTHREAD_TRY 0x10
|
||||
/**@}*/
|
||||
|
||||
#if !defined(EVENT__DISABLE_THREAD_SUPPORT) || defined(EVENT_IN_DOXYGEN_)
|
||||
|
||||
#define EVTHREAD_LOCK_API_VERSION 1
|
||||
|
||||
/**
|
||||
@name Types of locks
|
||||
|
||||
@{*/
|
||||
/** A recursive lock is one that can be acquired multiple times at once by the
|
||||
* same thread. No other process can allocate the lock until the thread that
|
||||
* has been holding it has unlocked it as many times as it locked it. */
|
||||
#define EVTHREAD_LOCKTYPE_RECURSIVE 1
|
||||
/* A read-write lock is one that allows multiple simultaneous readers, but
|
||||
* where any one writer excludes all other writers and readers. */
|
||||
#define EVTHREAD_LOCKTYPE_READWRITE 2
|
||||
/**@}*/
|
||||
|
||||
/** This structure describes the interface a threading library uses for
|
||||
* locking. It's used to tell evthread_set_lock_callbacks() how to use
|
||||
* locking on this platform.
|
||||
*/
|
||||
struct evthread_lock_callbacks {
|
||||
/** The current version of the locking API. Set this to
|
||||
* EVTHREAD_LOCK_API_VERSION */
|
||||
int lock_api_version;
|
||||
/** Which kinds of locks does this version of the locking API
|
||||
* support? A bitfield of EVTHREAD_LOCKTYPE_RECURSIVE and
|
||||
* EVTHREAD_LOCKTYPE_READWRITE.
|
||||
*
|
||||
* (Note that RECURSIVE locks are currently mandatory, and
|
||||
* READWRITE locks are not currently used.)
|
||||
**/
|
||||
unsigned supported_locktypes;
|
||||
/** Function to allocate and initialize new lock of type 'locktype'.
|
||||
* Returns NULL on failure. */
|
||||
void *(*alloc)(unsigned locktype);
|
||||
/** Funtion to release all storage held in 'lock', which was created
|
||||
* with type 'locktype'. */
|
||||
void (*free)(void *lock, unsigned locktype);
|
||||
/** Acquire an already-allocated lock at 'lock' with mode 'mode'.
|
||||
* Returns 0 on success, and nonzero on failure. */
|
||||
int (*lock)(unsigned mode, void *lock);
|
||||
/** Release a lock at 'lock' using mode 'mode'. Returns 0 on success,
|
||||
* and nonzero on failure. */
|
||||
int (*unlock)(unsigned mode, void *lock);
|
||||
};
|
||||
|
||||
/** Sets a group of functions that Libevent should use for locking.
|
||||
* For full information on the required callback API, see the
|
||||
* documentation for the individual members of evthread_lock_callbacks.
|
||||
*
|
||||
* Note that if you're using Windows or the Pthreads threading library, you
|
||||
* probably shouldn't call this function; instead, use
|
||||
* evthread_use_windows_threads() or evthread_use_posix_threads() if you can.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evthread_set_lock_callbacks(const struct evthread_lock_callbacks *);
|
||||
|
||||
#define EVTHREAD_CONDITION_API_VERSION 1
|
||||
|
||||
struct timeval;
|
||||
|
||||
/** This structure describes the interface a threading library uses for
|
||||
* condition variables. It's used to tell evthread_set_condition_callbacks
|
||||
* how to use locking on this platform.
|
||||
*/
|
||||
struct evthread_condition_callbacks {
|
||||
/** The current version of the conditions API. Set this to
|
||||
* EVTHREAD_CONDITION_API_VERSION */
|
||||
int condition_api_version;
|
||||
/** Function to allocate and initialize a new condition variable.
|
||||
* Returns the condition variable on success, and NULL on failure.
|
||||
* The 'condtype' argument will be 0 with this API version.
|
||||
*/
|
||||
void *(*alloc_condition)(unsigned condtype);
|
||||
/** Function to free a condition variable. */
|
||||
void (*free_condition)(void *cond);
|
||||
/** Function to signal a condition variable. If 'broadcast' is 1, all
|
||||
* threads waiting on 'cond' should be woken; otherwise, only on one
|
||||
* thread is worken. Should return 0 on success, -1 on failure.
|
||||
* This function will only be called while holding the associated
|
||||
* lock for the condition.
|
||||
*/
|
||||
int (*signal_condition)(void *cond, int broadcast);
|
||||
/** Function to wait for a condition variable. The lock 'lock'
|
||||
* will be held when this function is called; should be released
|
||||
* while waiting for the condition to be come signalled, and
|
||||
* should be held again when this function returns.
|
||||
* If timeout is provided, it is interval of seconds to wait for
|
||||
* the event to become signalled; if it is NULL, the function
|
||||
* should wait indefinitely.
|
||||
*
|
||||
* The function should return -1 on error; 0 if the condition
|
||||
* was signalled, or 1 on a timeout. */
|
||||
int (*wait_condition)(void *cond, void *lock,
|
||||
const struct timeval *timeout);
|
||||
};
|
||||
|
||||
/** Sets a group of functions that Libevent should use for condition variables.
|
||||
* For full information on the required callback API, see the
|
||||
* documentation for the individual members of evthread_condition_callbacks.
|
||||
*
|
||||
* Note that if you're using Windows or the Pthreads threading library, you
|
||||
* probably shouldn't call this function; instead, use
|
||||
* evthread_use_windows_threads() or evthread_use_pthreads() if you can.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evthread_set_condition_callbacks(
|
||||
const struct evthread_condition_callbacks *);
|
||||
|
||||
/**
|
||||
Sets the function for determining the thread id.
|
||||
|
||||
@param base the event base for which to set the id function
|
||||
@param id_fn the identify function Libevent should invoke to
|
||||
determine the identity of a thread.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evthread_set_id_callback(
|
||||
unsigned long (*id_fn)(void));
|
||||
|
||||
#if (defined(_WIN32) && !defined(EVENT__DISABLE_THREAD_SUPPORT)) || defined(EVENT_IN_DOXYGEN_)
|
||||
/** Sets up Libevent for use with Windows builtin locking and thread ID
|
||||
functions. Unavailable if Libevent is not built for Windows.
|
||||
|
||||
@return 0 on success, -1 on failure. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evthread_use_windows_threads(void);
|
||||
/**
|
||||
Defined if Libevent was built with support for evthread_use_windows_threads()
|
||||
*/
|
||||
#define EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED 1
|
||||
#endif
|
||||
|
||||
#if defined(EVENT__HAVE_PTHREADS) || defined(EVENT_IN_DOXYGEN_)
|
||||
/** Sets up Libevent for use with Pthreads locking and thread ID functions.
|
||||
Unavailable if Libevent is not build for use with pthreads. Requires
|
||||
libraries to link against Libevent_pthreads as well as Libevent.
|
||||
|
||||
@return 0 on success, -1 on failure. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evthread_use_pthreads(void);
|
||||
/** Defined if Libevent was built with support for evthread_use_pthreads() */
|
||||
#define EVTHREAD_USE_PTHREADS_IMPLEMENTED 1
|
||||
|
||||
#endif
|
||||
|
||||
/** Enable debugging wrappers around the current lock callbacks. If Libevent
|
||||
* makes one of several common locking errors, exit with an assertion failure.
|
||||
*
|
||||
* If you're going to call this function, you must do so before any locks are
|
||||
* allocated.
|
||||
**/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evthread_enable_lock_debugging(void);
|
||||
|
||||
/* Old (misspelled) version: This is deprecated; use
|
||||
* evthread_enable_log_debugging instead. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evthread_enable_lock_debuging(void);
|
||||
|
||||
#endif /* EVENT__DISABLE_THREAD_SUPPORT */
|
||||
|
||||
struct event_base;
|
||||
/** Make sure it's safe to tell an event base to wake up from another thread
|
||||
or a signal handler.
|
||||
|
||||
You shouldn't need to call this by hand; configuring the base with thread
|
||||
support should be necessary and sufficient.
|
||||
|
||||
@return 0 on success, -1 on failure.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evthread_make_base_notifiable(struct event_base *base);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_THREAD_H_INCLUDED_ */
|
|
@ -1,866 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_UTIL_H_INCLUDED_
|
||||
#define EVENT2_UTIL_H_INCLUDED_
|
||||
|
||||
/** @file event2/util.h
|
||||
|
||||
Common convenience functions for cross-platform portability and
|
||||
related socket manipulations.
|
||||
|
||||
*/
|
||||
#include <event2/visibility.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <event2/event-config.h>
|
||||
#ifdef EVENT__HAVE_SYS_TIME_H
|
||||
#include <sys/time.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_STDINT_H
|
||||
#include <stdint.h>
|
||||
#elif defined(EVENT__HAVE_INTTYPES_H)
|
||||
#include <inttypes.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_SYS_TYPES_H
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
#ifdef EVENT__HAVE_STDDEF_H
|
||||
#include <stddef.h>
|
||||
#endif
|
||||
#ifdef _MSC_VER
|
||||
#include <BaseTsd.h>
|
||||
#endif
|
||||
#include <stdarg.h>
|
||||
#ifdef EVENT__HAVE_NETDB_H
|
||||
#if !defined(_GNU_SOURCE)
|
||||
#define _GNU_SOURCE
|
||||
#endif
|
||||
#include <netdb.h>
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
#ifdef EVENT__HAVE_GETADDRINFO
|
||||
/* for EAI_* definitions. */
|
||||
#include <ws2tcpip.h>
|
||||
#endif
|
||||
#else
|
||||
#ifdef EVENT__HAVE_ERRNO_H
|
||||
#include <errno.h>
|
||||
#endif
|
||||
#include <sys/socket.h>
|
||||
#endif
|
||||
|
||||
#include <time.h>
|
||||
|
||||
/* Some openbsd autoconf versions get the name of this macro wrong. */
|
||||
#if defined(EVENT__SIZEOF_VOID__) && !defined(EVENT__SIZEOF_VOID_P)
|
||||
#define EVENT__SIZEOF_VOID_P EVENT__SIZEOF_VOID__
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @name Standard integer types.
|
||||
*
|
||||
* Integer type definitions for types that are supposed to be defined in the
|
||||
* C99-specified stdint.h. Shamefully, some platforms do not include
|
||||
* stdint.h, so we need to replace it. (If you are on a platform like this,
|
||||
* your C headers are now over 10 years out of date. You should bug them to
|
||||
* do something about this.)
|
||||
*
|
||||
* We define:
|
||||
*
|
||||
* <dl>
|
||||
* <dt>ev_uint64_t, ev_uint32_t, ev_uint16_t, ev_uint8_t</dt>
|
||||
* <dd>unsigned integer types of exactly 64, 32, 16, and 8 bits
|
||||
* respectively.</dd>
|
||||
* <dt>ev_int64_t, ev_int32_t, ev_int16_t, ev_int8_t</dt>
|
||||
* <dd>signed integer types of exactly 64, 32, 16, and 8 bits
|
||||
* respectively.</dd>
|
||||
* <dt>ev_uintptr_t, ev_intptr_t</dt>
|
||||
* <dd>unsigned/signed integers large enough
|
||||
* to hold a pointer without loss of bits.</dd>
|
||||
* <dt>ev_ssize_t</dt>
|
||||
* <dd>A signed type of the same size as size_t</dd>
|
||||
* <dt>ev_off_t</dt>
|
||||
* <dd>A signed type typically used to represent offsets within a
|
||||
* (potentially large) file</dd>
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
#ifdef EVENT__HAVE_UINT64_T
|
||||
#define ev_uint64_t uint64_t
|
||||
#define ev_int64_t int64_t
|
||||
#elif defined(_WIN32)
|
||||
#define ev_uint64_t unsigned __int64
|
||||
#define ev_int64_t signed __int64
|
||||
#elif EVENT__SIZEOF_LONG_LONG == 8
|
||||
#define ev_uint64_t unsigned long long
|
||||
#define ev_int64_t long long
|
||||
#elif EVENT__SIZEOF_LONG == 8
|
||||
#define ev_uint64_t unsigned long
|
||||
#define ev_int64_t long
|
||||
#elif defined(EVENT_IN_DOXYGEN_)
|
||||
#define ev_uint64_t ...
|
||||
#define ev_int64_t ...
|
||||
#else
|
||||
#error "No way to define ev_uint64_t"
|
||||
#endif
|
||||
|
||||
#ifdef EVENT__HAVE_UINT32_T
|
||||
#define ev_uint32_t uint32_t
|
||||
#define ev_int32_t int32_t
|
||||
#elif defined(_WIN32)
|
||||
#define ev_uint32_t unsigned int
|
||||
#define ev_int32_t signed int
|
||||
#elif EVENT__SIZEOF_LONG == 4
|
||||
#define ev_uint32_t unsigned long
|
||||
#define ev_int32_t signed long
|
||||
#elif EVENT__SIZEOF_INT == 4
|
||||
#define ev_uint32_t unsigned int
|
||||
#define ev_int32_t signed int
|
||||
#elif defined(EVENT_IN_DOXYGEN_)
|
||||
#define ev_uint32_t ...
|
||||
#define ev_int32_t ...
|
||||
#else
|
||||
#error "No way to define ev_uint32_t"
|
||||
#endif
|
||||
|
||||
#ifdef EVENT__HAVE_UINT16_T
|
||||
#define ev_uint16_t uint16_t
|
||||
#define ev_int16_t int16_t
|
||||
#elif defined(_WIN32)
|
||||
#define ev_uint16_t unsigned short
|
||||
#define ev_int16_t signed short
|
||||
#elif EVENT__SIZEOF_INT == 2
|
||||
#define ev_uint16_t unsigned int
|
||||
#define ev_int16_t signed int
|
||||
#elif EVENT__SIZEOF_SHORT == 2
|
||||
#define ev_uint16_t unsigned short
|
||||
#define ev_int16_t signed short
|
||||
#elif defined(EVENT_IN_DOXYGEN_)
|
||||
#define ev_uint16_t ...
|
||||
#define ev_int16_t ...
|
||||
#else
|
||||
#error "No way to define ev_uint16_t"
|
||||
#endif
|
||||
|
||||
#ifdef EVENT__HAVE_UINT8_T
|
||||
#define ev_uint8_t uint8_t
|
||||
#define ev_int8_t int8_t
|
||||
#elif defined(EVENT_IN_DOXYGEN_)
|
||||
#define ev_uint8_t ...
|
||||
#define ev_int8_t ...
|
||||
#else
|
||||
#define ev_uint8_t unsigned char
|
||||
#define ev_int8_t signed char
|
||||
#endif
|
||||
|
||||
#ifdef EVENT__HAVE_UINTPTR_T
|
||||
#define ev_uintptr_t uintptr_t
|
||||
#define ev_intptr_t intptr_t
|
||||
#elif EVENT__SIZEOF_VOID_P <= 4
|
||||
#define ev_uintptr_t ev_uint32_t
|
||||
#define ev_intptr_t ev_int32_t
|
||||
#elif EVENT__SIZEOF_VOID_P <= 8
|
||||
#define ev_uintptr_t ev_uint64_t
|
||||
#define ev_intptr_t ev_int64_t
|
||||
#elif defined(EVENT_IN_DOXYGEN_)
|
||||
#define ev_uintptr_t ...
|
||||
#define ev_intptr_t ...
|
||||
#else
|
||||
#error "No way to define ev_uintptr_t"
|
||||
#endif
|
||||
|
||||
#ifdef EVENT__ssize_t
|
||||
#define ev_ssize_t EVENT__ssize_t
|
||||
#else
|
||||
#define ev_ssize_t ssize_t
|
||||
#endif
|
||||
|
||||
/* Note that we define ev_off_t based on the compile-time size of off_t that
|
||||
* we used to build Libevent, and not based on the current size of off_t.
|
||||
* (For example, we don't define ev_off_t to off_t.). We do this because
|
||||
* some systems let you build your software with different off_t sizes
|
||||
* at runtime, and so putting in any dependency on off_t would risk API
|
||||
* mismatch.
|
||||
*/
|
||||
#ifdef _WIN32
|
||||
#define ev_off_t ev_int64_t
|
||||
#elif EVENT__SIZEOF_OFF_T == 8
|
||||
#define ev_off_t ev_int64_t
|
||||
#elif EVENT__SIZEOF_OFF_T == 4
|
||||
#define ev_off_t ev_int32_t
|
||||
#elif defined(EVENT_IN_DOXYGEN_)
|
||||
#define ev_off_t ...
|
||||
#else
|
||||
#define ev_off_t off_t
|
||||
#endif
|
||||
/**@}*/
|
||||
|
||||
/* Limits for integer types.
|
||||
|
||||
We're making two assumptions here:
|
||||
- The compiler does constant folding properly.
|
||||
- The platform does signed arithmetic in two's complement.
|
||||
*/
|
||||
|
||||
/**
|
||||
@name Limits for integer types
|
||||
|
||||
These macros hold the largest or smallest values possible for the
|
||||
ev_[u]int*_t types.
|
||||
|
||||
@{
|
||||
*/
|
||||
#ifndef EVENT__HAVE_STDINT_H
|
||||
#define EV_UINT64_MAX ((((ev_uint64_t)0xffffffffUL) << 32) | 0xffffffffUL)
|
||||
#define EV_INT64_MAX ((((ev_int64_t) 0x7fffffffL) << 32) | 0xffffffffL)
|
||||
#define EV_INT64_MIN ((-EV_INT64_MAX) - 1)
|
||||
#define EV_UINT32_MAX ((ev_uint32_t)0xffffffffUL)
|
||||
#define EV_INT32_MAX ((ev_int32_t) 0x7fffffffL)
|
||||
#define EV_INT32_MIN ((-EV_INT32_MAX) - 1)
|
||||
#define EV_UINT16_MAX ((ev_uint16_t)0xffffUL)
|
||||
#define EV_INT16_MAX ((ev_int16_t) 0x7fffL)
|
||||
#define EV_INT16_MIN ((-EV_INT16_MAX) - 1)
|
||||
#define EV_UINT8_MAX 255
|
||||
#define EV_INT8_MAX 127
|
||||
#define EV_INT8_MIN ((-EV_INT8_MAX) - 1)
|
||||
#else
|
||||
#define EV_UINT64_MAX UINT64_MAX
|
||||
#define EV_INT64_MAX INT64_MAX
|
||||
#define EV_INT64_MIN INT64_MIN
|
||||
#define EV_UINT32_MAX UINT32_MAX
|
||||
#define EV_INT32_MAX INT32_MAX
|
||||
#define EV_INT32_MIN INT32_MIN
|
||||
#define EV_UINT16_MAX UINT16_MAX
|
||||
#define EV_INT16_MAX INT16_MAX
|
||||
#define EV_UINT8_MAX UINT8_MAX
|
||||
#define EV_INT8_MAX INT8_MAX
|
||||
#define EV_INT8_MIN INT8_MIN
|
||||
/** @} */
|
||||
#endif
|
||||
|
||||
|
||||
/**
|
||||
@name Limits for SIZE_T and SSIZE_T
|
||||
|
||||
@{
|
||||
*/
|
||||
#if EVENT__SIZEOF_SIZE_T == 8
|
||||
#define EV_SIZE_MAX EV_UINT64_MAX
|
||||
#define EV_SSIZE_MAX EV_INT64_MAX
|
||||
#elif EVENT__SIZEOF_SIZE_T == 4
|
||||
#define EV_SIZE_MAX EV_UINT32_MAX
|
||||
#define EV_SSIZE_MAX EV_INT32_MAX
|
||||
#elif defined(EVENT_IN_DOXYGEN_)
|
||||
#define EV_SIZE_MAX ...
|
||||
#define EV_SSIZE_MAX ...
|
||||
#else
|
||||
#error "No way to define SIZE_MAX"
|
||||
#endif
|
||||
|
||||
#define EV_SSIZE_MIN ((-EV_SSIZE_MAX) - 1)
|
||||
/**@}*/
|
||||
|
||||
#ifdef _WIN32
|
||||
#define ev_socklen_t int
|
||||
#elif defined(EVENT__socklen_t)
|
||||
#define ev_socklen_t EVENT__socklen_t
|
||||
#else
|
||||
#define ev_socklen_t socklen_t
|
||||
#endif
|
||||
|
||||
#ifdef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY
|
||||
#if !defined(EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) \
|
||||
&& !defined(ss_family)
|
||||
#define ss_family __ss_family
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/**
|
||||
* A type wide enough to hold the output of "socket()" or "accept()". On
|
||||
* Windows, this is an intptr_t; elsewhere, it is an int. */
|
||||
#ifdef _WIN32
|
||||
#define evutil_socket_t intptr_t
|
||||
#else
|
||||
#define evutil_socket_t int
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Structure to hold information about a monotonic timer
|
||||
*
|
||||
* Use this with evutil_configure_monotonic_time() and
|
||||
* evutil_gettime_monotonic().
|
||||
*
|
||||
* This is an opaque structure; you can allocate one using
|
||||
* evutil_monotonic_timer_new().
|
||||
*
|
||||
* @see evutil_monotonic_timer_new(), evutil_monotonic_timer_free(),
|
||||
* evutil_configure_monotonic_time(), evutil_gettime_monotonic()
|
||||
*/
|
||||
struct evutil_monotonic_timer
|
||||
#ifdef EVENT_IN_DOXYGEN_
|
||||
{/*Empty body so that doxygen will generate documentation here.*/}
|
||||
#endif
|
||||
;
|
||||
|
||||
#define EV_MONOT_PRECISE 1
|
||||
#define EV_MONOT_FALLBACK 2
|
||||
|
||||
/** Format a date string using RFC 1123 format (used in HTTP).
|
||||
* If `tm` is NULL, current system's time will be used.
|
||||
* The number of characters written will be returned.
|
||||
* One should check if the return value is smaller than `datelen` to check if
|
||||
* the result is truncated or not.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL int
|
||||
evutil_date_rfc1123(char *date, const size_t datelen, const struct tm *tm);
|
||||
|
||||
/** Allocate a new struct evutil_monotonic_timer for use with the
|
||||
* evutil_configure_monotonic_time() and evutil_gettime_monotonic()
|
||||
* functions. You must configure the timer with
|
||||
* evutil_configure_monotonic_time() before using it.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
struct evutil_monotonic_timer * evutil_monotonic_timer_new(void);
|
||||
|
||||
/** Free a struct evutil_monotonic_timer that was allocated using
|
||||
* evutil_monotonic_timer_new().
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evutil_monotonic_timer_free(struct evutil_monotonic_timer *timer);
|
||||
|
||||
/** Set up a struct evutil_monotonic_timer; flags can include
|
||||
* EV_MONOT_PRECISE and EV_MONOT_FALLBACK.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_configure_monotonic_time(struct evutil_monotonic_timer *timer,
|
||||
int flags);
|
||||
|
||||
/** Query the current monotonic time from a struct evutil_monotonic_timer
|
||||
* previously configured with evutil_configure_monotonic_time(). Monotonic
|
||||
* time is guaranteed never to run in reverse, but is not necessarily epoch-
|
||||
* based, or relative to any other definite point. Use it to make reliable
|
||||
* measurements of elapsed time between events even when the system time
|
||||
* may be changed.
|
||||
*
|
||||
* It is not safe to use this funtion on the same timer from multiple
|
||||
* threads.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_gettime_monotonic(struct evutil_monotonic_timer *timer,
|
||||
struct timeval *tp);
|
||||
|
||||
/** Create two new sockets that are connected to each other.
|
||||
|
||||
On Unix, this simply calls socketpair(). On Windows, it uses the
|
||||
loopback network interface on 127.0.0.1, and only
|
||||
AF_INET,SOCK_STREAM are supported.
|
||||
|
||||
(This may fail on some Windows hosts where firewall software has cleverly
|
||||
decided to keep 127.0.0.1 from talking to itself.)
|
||||
|
||||
Parameters and return values are as for socketpair()
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_socketpair(int d, int type, int protocol, evutil_socket_t sv[2]);
|
||||
/** Do platform-specific operations as needed to make a socket nonblocking.
|
||||
|
||||
@param sock The socket to make nonblocking
|
||||
@return 0 on success, -1 on failure
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_make_socket_nonblocking(evutil_socket_t sock);
|
||||
|
||||
/** Do platform-specific operations to make a listener socket reusable.
|
||||
|
||||
Specifically, we want to make sure that another program will be able
|
||||
to bind this address right after we've closed the listener.
|
||||
|
||||
This differs from Windows's interpretation of "reusable", which
|
||||
allows multiple listeners to bind the same address at the same time.
|
||||
|
||||
@param sock The socket to make reusable
|
||||
@return 0 on success, -1 on failure
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_make_listen_socket_reuseable(evutil_socket_t sock);
|
||||
|
||||
/** Do platform-specific operations to make a listener port reusable.
|
||||
|
||||
Specifically, we want to make sure that multiple programs which also
|
||||
set the same socket option will be able to bind, listen at the same time.
|
||||
|
||||
This is a feature available only to Linux 3.9+
|
||||
|
||||
@param sock The socket to make reusable
|
||||
@return 0 on success, -1 on failure
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_make_listen_socket_reuseable_port(evutil_socket_t sock);
|
||||
|
||||
/** Do platform-specific operations as needed to close a socket upon a
|
||||
successful execution of one of the exec*() functions.
|
||||
|
||||
@param sock The socket to be closed
|
||||
@return 0 on success, -1 on failure
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_make_socket_closeonexec(evutil_socket_t sock);
|
||||
|
||||
/** Do the platform-specific call needed to close a socket returned from
|
||||
socket() or accept().
|
||||
|
||||
@param sock The socket to be closed
|
||||
@return 0 on success, -1 on failure
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_closesocket(evutil_socket_t sock);
|
||||
#define EVUTIL_CLOSESOCKET(s) evutil_closesocket(s)
|
||||
|
||||
/** Do platform-specific operations, if possible, to make a tcp listener
|
||||
* socket defer accept()s until there is data to read.
|
||||
*
|
||||
* Not all platforms support this. You don't want to do this for every
|
||||
* listener socket: only the ones that implement a protocol where the
|
||||
* client transmits before the server needs to respond.
|
||||
*
|
||||
* @param sock The listening socket to to make deferred
|
||||
* @return 0 on success (whether the operation is supported or not),
|
||||
* -1 on failure
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock);
|
||||
|
||||
#ifdef _WIN32
|
||||
/** Return the most recent socket error. Not idempotent on all platforms. */
|
||||
#define EVUTIL_SOCKET_ERROR() WSAGetLastError()
|
||||
/** Replace the most recent socket error with errcode */
|
||||
#define EVUTIL_SET_SOCKET_ERROR(errcode) \
|
||||
do { WSASetLastError(errcode); } while (0)
|
||||
/** Return the most recent socket error to occur on sock. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_socket_geterror(evutil_socket_t sock);
|
||||
/** Convert a socket error to a string. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
const char *evutil_socket_error_to_string(int errcode);
|
||||
#elif defined(EVENT_IN_DOXYGEN_)
|
||||
/**
|
||||
@name Socket error functions
|
||||
|
||||
These functions are needed for making programs compatible between
|
||||
Windows and Unix-like platforms.
|
||||
|
||||
You see, Winsock handles socket errors differently from the rest of
|
||||
the world. Elsewhere, a socket error is like any other error and is
|
||||
stored in errno. But winsock functions require you to retrieve the
|
||||
error with a special function, and don't let you use strerror for
|
||||
the error codes. And handling EWOULDBLOCK is ... different.
|
||||
|
||||
@{
|
||||
*/
|
||||
/** Return the most recent socket error. Not idempotent on all platforms. */
|
||||
#define EVUTIL_SOCKET_ERROR() ...
|
||||
/** Replace the most recent socket error with errcode */
|
||||
#define EVUTIL_SET_SOCKET_ERROR(errcode) ...
|
||||
/** Return the most recent socket error to occur on sock. */
|
||||
#define evutil_socket_geterror(sock) ...
|
||||
/** Convert a socket error to a string. */
|
||||
#define evutil_socket_error_to_string(errcode) ...
|
||||
/**@}*/
|
||||
#else
|
||||
#define EVUTIL_SOCKET_ERROR() (errno)
|
||||
#define EVUTIL_SET_SOCKET_ERROR(errcode) \
|
||||
do { errno = (errcode); } while (0)
|
||||
#define evutil_socket_geterror(sock) (errno)
|
||||
#define evutil_socket_error_to_string(errcode) (strerror(errcode))
|
||||
#endif
|
||||
|
||||
|
||||
/**
|
||||
* @name Manipulation macros for struct timeval.
|
||||
*
|
||||
* We define replacements
|
||||
* for timeradd, timersub, timerclear, timercmp, and timerisset.
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
#ifdef EVENT__HAVE_TIMERADD
|
||||
#define evutil_timeradd(tvp, uvp, vvp) timeradd((tvp), (uvp), (vvp))
|
||||
#define evutil_timersub(tvp, uvp, vvp) timersub((tvp), (uvp), (vvp))
|
||||
#else
|
||||
#define evutil_timeradd(tvp, uvp, vvp) \
|
||||
do { \
|
||||
(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec; \
|
||||
(vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec; \
|
||||
if ((vvp)->tv_usec >= 1000000) { \
|
||||
(vvp)->tv_sec++; \
|
||||
(vvp)->tv_usec -= 1000000; \
|
||||
} \
|
||||
} while (0)
|
||||
#define evutil_timersub(tvp, uvp, vvp) \
|
||||
do { \
|
||||
(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
|
||||
(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
|
||||
if ((vvp)->tv_usec < 0) { \
|
||||
(vvp)->tv_sec--; \
|
||||
(vvp)->tv_usec += 1000000; \
|
||||
} \
|
||||
} while (0)
|
||||
#endif /* !EVENT__HAVE_TIMERADD */
|
||||
|
||||
#ifdef EVENT__HAVE_TIMERCLEAR
|
||||
#define evutil_timerclear(tvp) timerclear(tvp)
|
||||
#else
|
||||
#define evutil_timerclear(tvp) (tvp)->tv_sec = (tvp)->tv_usec = 0
|
||||
#endif
|
||||
/**@}*/
|
||||
|
||||
/** Return true iff the tvp is related to uvp according to the relational
|
||||
* operator cmp. Recognized values for cmp are ==, <=, <, >=, and >. */
|
||||
#define evutil_timercmp(tvp, uvp, cmp) \
|
||||
(((tvp)->tv_sec == (uvp)->tv_sec) ? \
|
||||
((tvp)->tv_usec cmp (uvp)->tv_usec) : \
|
||||
((tvp)->tv_sec cmp (uvp)->tv_sec))
|
||||
|
||||
#ifdef EVENT__HAVE_TIMERISSET
|
||||
#define evutil_timerisset(tvp) timerisset(tvp)
|
||||
#else
|
||||
#define evutil_timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec)
|
||||
#endif
|
||||
|
||||
/** Replacement for offsetof on platforms that don't define it. */
|
||||
#ifdef offsetof
|
||||
#define evutil_offsetof(type, field) offsetof(type, field)
|
||||
#else
|
||||
#define evutil_offsetof(type, field) ((off_t)(&((type *)0)->field))
|
||||
#endif
|
||||
|
||||
/* big-int related functions */
|
||||
/** Parse a 64-bit value from a string. Arguments are as for strtol. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
ev_int64_t evutil_strtoll(const char *s, char **endptr, int base);
|
||||
|
||||
/** Replacement for gettimeofday on platforms that lack it. */
|
||||
#ifdef EVENT__HAVE_GETTIMEOFDAY
|
||||
#define evutil_gettimeofday(tv, tz) gettimeofday((tv), (tz))
|
||||
#else
|
||||
struct timezone;
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_gettimeofday(struct timeval *tv, struct timezone *tz);
|
||||
#endif
|
||||
|
||||
/** Replacement for snprintf to get consistent behavior on platforms for
|
||||
which the return value of snprintf does not conform to C99.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
|
||||
#ifdef __GNUC__
|
||||
__attribute__((format(printf, 3, 4)))
|
||||
#endif
|
||||
;
|
||||
/** Replacement for vsnprintf to get consistent behavior on platforms for
|
||||
which the return value of snprintf does not conform to C99.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
|
||||
#ifdef __GNUC__
|
||||
__attribute__((format(printf, 3, 0)))
|
||||
#endif
|
||||
;
|
||||
|
||||
/** Replacement for inet_ntop for platforms which lack it. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
const char *evutil_inet_ntop(int af, const void *src, char *dst, size_t len);
|
||||
/** Replacement for inet_pton for platforms which lack it. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_inet_pton(int af, const char *src, void *dst);
|
||||
struct sockaddr;
|
||||
|
||||
/** Parse an IPv4 or IPv6 address, with optional port, from a string.
|
||||
|
||||
Recognized formats are:
|
||||
- [IPv6Address]:port
|
||||
- [IPv6Address]
|
||||
- IPv6Address
|
||||
- IPv4Address:port
|
||||
- IPv4Address
|
||||
|
||||
If no port is specified, the port in the output is set to 0.
|
||||
|
||||
@param str The string to parse.
|
||||
@param out A struct sockaddr to hold the result. This should probably be
|
||||
a struct sockaddr_storage.
|
||||
@param outlen A pointer to the number of bytes that that 'out' can safely
|
||||
hold. Set to the number of bytes used in 'out' on success.
|
||||
@return -1 if the address is not well-formed, if the port is out of range,
|
||||
or if out is not large enough to hold the result. Otherwise returns
|
||||
0 on success.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_parse_sockaddr_port(const char *str, struct sockaddr *out, int *outlen);
|
||||
|
||||
/** Compare two sockaddrs; return 0 if they are equal, or less than 0 if sa1
|
||||
* preceeds sa2, or greater than 0 if sa1 follows sa2. If include_port is
|
||||
* true, consider the port as well as the address. Only implemented for
|
||||
* AF_INET and AF_INET6 addresses. The ordering is not guaranteed to remain
|
||||
* the same between Libevent versions. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
|
||||
int include_port);
|
||||
|
||||
/** As strcasecmp, but always compares the characters in locale-independent
|
||||
ASCII. That's useful if you're handling data in ASCII-based protocols.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_ascii_strcasecmp(const char *str1, const char *str2);
|
||||
/** As strncasecmp, but always compares the characters in locale-independent
|
||||
ASCII. That's useful if you're handling data in ASCII-based protocols.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_ascii_strncasecmp(const char *str1, const char *str2, size_t n);
|
||||
|
||||
/* Here we define evutil_addrinfo to the native addrinfo type, or redefine it
|
||||
* if this system has no getaddrinfo(). */
|
||||
#ifdef EVENT__HAVE_STRUCT_ADDRINFO
|
||||
#define evutil_addrinfo addrinfo
|
||||
#else
|
||||
/** A definition of struct addrinfo for systems that lack it.
|
||||
|
||||
(This is just an alias for struct addrinfo if the system defines
|
||||
struct addrinfo.)
|
||||
*/
|
||||
struct evutil_addrinfo {
|
||||
int ai_flags; /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
|
||||
int ai_family; /* PF_xxx */
|
||||
int ai_socktype; /* SOCK_xxx */
|
||||
int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
|
||||
size_t ai_addrlen; /* length of ai_addr */
|
||||
char *ai_canonname; /* canonical name for nodename */
|
||||
struct sockaddr *ai_addr; /* binary address */
|
||||
struct evutil_addrinfo *ai_next; /* next structure in linked list */
|
||||
};
|
||||
#endif
|
||||
/** @name evutil_getaddrinfo() error codes
|
||||
|
||||
These values are possible error codes for evutil_getaddrinfo() and
|
||||
related functions.
|
||||
|
||||
@{
|
||||
*/
|
||||
#if defined(EAI_ADDRFAMILY) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_EAI_ADDRFAMILY EAI_ADDRFAMILY
|
||||
#else
|
||||
#define EVUTIL_EAI_ADDRFAMILY -901
|
||||
#endif
|
||||
#if defined(EAI_AGAIN) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_EAI_AGAIN EAI_AGAIN
|
||||
#else
|
||||
#define EVUTIL_EAI_AGAIN -902
|
||||
#endif
|
||||
#if defined(EAI_BADFLAGS) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_EAI_BADFLAGS EAI_BADFLAGS
|
||||
#else
|
||||
#define EVUTIL_EAI_BADFLAGS -903
|
||||
#endif
|
||||
#if defined(EAI_FAIL) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_EAI_FAIL EAI_FAIL
|
||||
#else
|
||||
#define EVUTIL_EAI_FAIL -904
|
||||
#endif
|
||||
#if defined(EAI_FAMILY) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_EAI_FAMILY EAI_FAMILY
|
||||
#else
|
||||
#define EVUTIL_EAI_FAMILY -905
|
||||
#endif
|
||||
#if defined(EAI_MEMORY) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_EAI_MEMORY EAI_MEMORY
|
||||
#else
|
||||
#define EVUTIL_EAI_MEMORY -906
|
||||
#endif
|
||||
/* This test is a bit complicated, since some MS SDKs decide to
|
||||
* remove NODATA or redefine it to be the same as NONAME, in a
|
||||
* fun interpretation of RFC 2553 and RFC 3493. */
|
||||
#if defined(EAI_NODATA) && defined(EVENT__HAVE_GETADDRINFO) && (!defined(EAI_NONAME) || EAI_NODATA != EAI_NONAME)
|
||||
#define EVUTIL_EAI_NODATA EAI_NODATA
|
||||
#else
|
||||
#define EVUTIL_EAI_NODATA -907
|
||||
#endif
|
||||
#if defined(EAI_NONAME) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_EAI_NONAME EAI_NONAME
|
||||
#else
|
||||
#define EVUTIL_EAI_NONAME -908
|
||||
#endif
|
||||
#if defined(EAI_SERVICE) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_EAI_SERVICE EAI_SERVICE
|
||||
#else
|
||||
#define EVUTIL_EAI_SERVICE -909
|
||||
#endif
|
||||
#if defined(EAI_SOCKTYPE) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_EAI_SOCKTYPE EAI_SOCKTYPE
|
||||
#else
|
||||
#define EVUTIL_EAI_SOCKTYPE -910
|
||||
#endif
|
||||
#if defined(EAI_SYSTEM) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_EAI_SYSTEM EAI_SYSTEM
|
||||
#else
|
||||
#define EVUTIL_EAI_SYSTEM -911
|
||||
#endif
|
||||
|
||||
#define EVUTIL_EAI_CANCEL -90001
|
||||
|
||||
#if defined(AI_PASSIVE) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_AI_PASSIVE AI_PASSIVE
|
||||
#else
|
||||
#define EVUTIL_AI_PASSIVE 0x1000
|
||||
#endif
|
||||
#if defined(AI_CANONNAME) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_AI_CANONNAME AI_CANONNAME
|
||||
#else
|
||||
#define EVUTIL_AI_CANONNAME 0x2000
|
||||
#endif
|
||||
#if defined(AI_NUMERICHOST) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_AI_NUMERICHOST AI_NUMERICHOST
|
||||
#else
|
||||
#define EVUTIL_AI_NUMERICHOST 0x4000
|
||||
#endif
|
||||
#if defined(AI_NUMERICSERV) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_AI_NUMERICSERV AI_NUMERICSERV
|
||||
#else
|
||||
#define EVUTIL_AI_NUMERICSERV 0x8000
|
||||
#endif
|
||||
#if defined(AI_V4MAPPED) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_AI_V4MAPPED AI_V4MAPPED
|
||||
#else
|
||||
#define EVUTIL_AI_V4MAPPED 0x10000
|
||||
#endif
|
||||
#if defined(AI_ALL) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_AI_ALL AI_ALL
|
||||
#else
|
||||
#define EVUTIL_AI_ALL 0x20000
|
||||
#endif
|
||||
#if defined(AI_ADDRCONFIG) && defined(EVENT__HAVE_GETADDRINFO)
|
||||
#define EVUTIL_AI_ADDRCONFIG AI_ADDRCONFIG
|
||||
#else
|
||||
#define EVUTIL_AI_ADDRCONFIG 0x40000
|
||||
#endif
|
||||
/**@}*/
|
||||
|
||||
struct evutil_addrinfo;
|
||||
/**
|
||||
* This function clones getaddrinfo for systems that don't have it. For full
|
||||
* details, see RFC 3493, section 6.1.
|
||||
*
|
||||
* Limitations:
|
||||
* - When the system has no getaddrinfo, we fall back to gethostbyname_r or
|
||||
* gethostbyname, with their attendant issues.
|
||||
* - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
|
||||
*
|
||||
* For a nonblocking variant, see evdns_getaddrinfo.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_getaddrinfo(const char *nodename, const char *servname,
|
||||
const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res);
|
||||
|
||||
/** Release storage allocated by evutil_getaddrinfo or evdns_getaddrinfo. */
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evutil_freeaddrinfo(struct evutil_addrinfo *ai);
|
||||
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
const char *evutil_gai_strerror(int err);
|
||||
|
||||
/** Generate n bytes of secure pseudorandom data, and store them in buf.
|
||||
*
|
||||
* Current versions of Libevent use an ARC4-based random number generator,
|
||||
* seeded using the platform's entropy source (/dev/urandom on Unix-like
|
||||
* systems; CryptGenRandom on Windows). This is not actually as secure as it
|
||||
* should be: ARC4 is a pretty lousy cipher, and the current implementation
|
||||
* provides only rudimentary prediction- and backtracking-resistance. Don't
|
||||
* use this for serious cryptographic applications.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evutil_secure_rng_get_bytes(void *buf, size_t n);
|
||||
|
||||
/**
|
||||
* Seed the secure random number generator if needed, and return 0 on
|
||||
* success or -1 on failure.
|
||||
*
|
||||
* It is okay to call this function more than once; it will still return
|
||||
* 0 if the RNG has been successfully seeded and -1 if it can't be
|
||||
* seeded.
|
||||
*
|
||||
* Ordinarily you don't need to call this function from your own code;
|
||||
* Libevent will seed the RNG itself the first time it needs good random
|
||||
* numbers. You only need to call it if (a) you want to double-check
|
||||
* that one of the seeding methods did succeed, or (b) you plan to drop
|
||||
* the capability to seed (by chrooting, or dropping capabilities, or
|
||||
* whatever), and you want to make sure that seeding happens before your
|
||||
* program loses the ability to do it.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_secure_rng_init(void);
|
||||
|
||||
/**
|
||||
* Set a filename to use in place of /dev/urandom for seeding the secure
|
||||
* PRNG. Return 0 on success, -1 on failure.
|
||||
*
|
||||
* Call this function BEFORE calling any other initialization or RNG
|
||||
* functions.
|
||||
*
|
||||
* (This string will _NOT_ be copied internally. Do not free it while any
|
||||
* user of the secure RNG might be running. Don't pass anything other than a
|
||||
* real /dev/...random device file here, or you might lose security.)
|
||||
*
|
||||
* This API is unstable, and might change in a future libevent version.
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
int evutil_secure_rng_set_urandom_device_file(char *fname);
|
||||
|
||||
/** Seed the random number generator with extra random bytes.
|
||||
|
||||
You should almost never need to call this function; it should be
|
||||
sufficient to invoke evutil_secure_rng_init(), or let Libevent take
|
||||
care of calling evutil_secure_rng_init() on its own.
|
||||
|
||||
If you call this function as a _replacement_ for the regular
|
||||
entropy sources, then you need to be sure that your input
|
||||
contains a fairly large amount of strong entropy. Doing so is
|
||||
notoriously hard: most people who try get it wrong. Watch out!
|
||||
|
||||
@param dat a buffer full of a strong source of random numbers
|
||||
@param datlen the number of bytes to read from datlen
|
||||
*/
|
||||
EVENT2_EXPORT_SYMBOL
|
||||
void evutil_secure_rng_add_bytes(const char *dat, size_t datlen);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* EVENT1_EVUTIL_H_INCLUDED_ */
|
|
@ -1,50 +0,0 @@
|
|||
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
|
||||
/*
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT2_VISIBILITY_H_INCLUDED_
|
||||
#define EVENT2_VISIBILITY_H_INCLUDED_
|
||||
|
||||
#include <event2/event-config.h>
|
||||
|
||||
#if defined(event_EXPORTS) || defined(event_extra_EXPORTS) || defined(event_core_EXPORTS)
|
||||
# if defined (__SUNPRO_C) && (__SUNPRO_C >= 0x550)
|
||||
# define EVENT2_EXPORT_SYMBOL __global
|
||||
# elif defined __GNUC__
|
||||
# define EVENT2_EXPORT_SYMBOL __attribute__ ((visibility("default")))
|
||||
# elif defined(_MSC_VER)
|
||||
# define EVENT2_EXPORT_SYMBOL extern __declspec(dllexport)
|
||||
# else
|
||||
# define EVENT2_EXPORT_SYMBOL /* unknown compiler */
|
||||
# endif
|
||||
#else
|
||||
# if defined(EVENT__NEED_DLLIMPORT) && defined(_MSC_VER) && !defined(EVENT_BUILDING_REGRESS_TEST)
|
||||
# define EVENT2_EXPORT_SYMBOL extern __declspec(dllimport)
|
||||
# else
|
||||
# define EVENT2_EXPORT_SYMBOL
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#endif /* EVENT2_VISIBILITY_H_INCLUDED_ */
|
|
@ -1,45 +0,0 @@
|
|||
/*
|
||||
* Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT1_EVHTTP_H_INCLUDED_
|
||||
#define EVENT1_EVHTTP_H_INCLUDED_
|
||||
|
||||
/** @file evhttp.h
|
||||
|
||||
An http implementation subsystem for Libevent.
|
||||
|
||||
The <evhttp.h> header is deprecated in Libevent 2.0 and later; please
|
||||
use <event2/http.h> instead. Depending on what functionality you
|
||||
need, you may also want to include more of the other <event2/...>
|
||||
headers.
|
||||
*/
|
||||
|
||||
#include <event.h>
|
||||
#include <event2/http.h>
|
||||
#include <event2/http_struct.h>
|
||||
#include <event2/http_compat.h>
|
||||
|
||||
#endif /* EVENT1_EVHTTP_H_INCLUDED_ */
|
|
@ -1,45 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT1_EVRPC_H_INCLUDED_
|
||||
#define EVENT1_EVRPC_H_INCLUDED_
|
||||
|
||||
/** @file evrpc.h
|
||||
|
||||
An RPC system for Libevent.
|
||||
|
||||
The <evrpc.h> header is deprecated in Libevent 2.0 and later; please
|
||||
use <event2/rpc.h> instead. Depending on what functionality you
|
||||
need, you may also want to include more of the other <event2/...>
|
||||
headers.
|
||||
*/
|
||||
|
||||
#include <event.h>
|
||||
#include <event2/rpc.h>
|
||||
#include <event2/rpc_struct.h>
|
||||
#include <event2/rpc_compat.h>
|
||||
|
||||
#endif /* EVENT1_EVRPC_H_INCLUDED_ */
|
|
@ -1,39 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
#ifndef EVENT1_EVUTIL_H_INCLUDED_
|
||||
#define EVENT1_EVUTIL_H_INCLUDED_
|
||||
|
||||
/** @file evutil.h
|
||||
|
||||
Utility and compatibility functions for Libevent.
|
||||
|
||||
The <evutil.h> header is deprecated in Libevent 2.0 and later; please
|
||||
use <event2/util.h> instead.
|
||||
*/
|
||||
|
||||
#include <event2/util.h>
|
||||
|
||||
#endif /* EVENT1_EVUTIL_H_INCLUDED_ */
|
|
@ -1,26 +0,0 @@
|
|||
Copyright 2006-2011, the V8 project authors. All rights reserved.
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials provided
|
||||
with the distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -1,54 +0,0 @@
|
|||
http://code.google.com/p/double-conversion
|
||||
|
||||
This project (double-conversion) provides binary-decimal and decimal-binary
|
||||
routines for IEEE doubles.
|
||||
|
||||
The library consists of efficient conversion routines that have been extracted
|
||||
from the V8 JavaScript engine. The code has been refactored and improved so that
|
||||
it can be used more easily in other projects.
|
||||
|
||||
There is extensive documentation in src/double-conversion.h. Other examples can
|
||||
be found in test/cctest/test-conversions.cc.
|
||||
|
||||
|
||||
Building
|
||||
========
|
||||
|
||||
This library can be built with scons [0] or cmake [1].
|
||||
The checked-in Makefile simply forwards to scons, and provides a
|
||||
shortcut to run all tests:
|
||||
|
||||
make
|
||||
make test
|
||||
|
||||
Scons
|
||||
-----
|
||||
|
||||
The easiest way to install this library is to use `scons`. It builds
|
||||
the static and shared library, and is set up to install those at the
|
||||
correct locations:
|
||||
|
||||
scons install
|
||||
|
||||
Use the `DESTDIR` option to change the target directory:
|
||||
|
||||
scons DESTDIR=alternative_directory install
|
||||
|
||||
Cmake
|
||||
-----
|
||||
|
||||
To use cmake run `cmake .` in the root directory. This overwrites the
|
||||
existing Makefile.
|
||||
|
||||
Use `-DBUILD_SHARED_LIBS=ON` to enable the compilation of shared libraries.
|
||||
Note that this disables static libraries. There is currently no way to
|
||||
build both libraries at the same time with cmake.
|
||||
|
||||
Use `-DBUILD_TESTING=ON` to build the test executable.
|
||||
|
||||
cmake . -DBUILD_TESTING=ON
|
||||
make
|
||||
test/cctest/cctest --list | tr -d '<' | xargs test/cctest/cctest
|
||||
|
||||
[0]: http://www.scons.org
|
||||
[1]: http://www.cmake.org
|
|
@ -1,641 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "bignum-dtoa.h"
|
||||
|
||||
#include "bignum.h"
|
||||
#include "ieee.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
static int NormalizedExponent(uint64_t significand, int exponent) {
|
||||
ASSERT(significand != 0);
|
||||
while ((significand & Double::kHiddenBit) == 0) {
|
||||
significand = significand << 1;
|
||||
exponent = exponent - 1;
|
||||
}
|
||||
return exponent;
|
||||
}
|
||||
|
||||
|
||||
// Forward declarations:
|
||||
// Returns an estimation of k such that 10^(k-1) <= v < 10^k.
|
||||
static int EstimatePower(int exponent);
|
||||
// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
|
||||
// and denominator.
|
||||
static void InitialScaledStartValues(uint64_t significand,
|
||||
int exponent,
|
||||
bool lower_boundary_is_closer,
|
||||
int estimated_power,
|
||||
bool need_boundary_deltas,
|
||||
Bignum* numerator,
|
||||
Bignum* denominator,
|
||||
Bignum* delta_minus,
|
||||
Bignum* delta_plus);
|
||||
// Multiplies numerator/denominator so that its values lies in the range 1-10.
|
||||
// Returns decimal_point s.t.
|
||||
// v = numerator'/denominator' * 10^(decimal_point-1)
|
||||
// where numerator' and denominator' are the values of numerator and
|
||||
// denominator after the call to this function.
|
||||
static void FixupMultiply10(int estimated_power, bool is_even,
|
||||
int* decimal_point,
|
||||
Bignum* numerator, Bignum* denominator,
|
||||
Bignum* delta_minus, Bignum* delta_plus);
|
||||
// Generates digits from the left to the right and stops when the generated
|
||||
// digits yield the shortest decimal representation of v.
|
||||
static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
|
||||
Bignum* delta_minus, Bignum* delta_plus,
|
||||
bool is_even,
|
||||
Vector<char> buffer, int* length);
|
||||
// Generates 'requested_digits' after the decimal point.
|
||||
static void BignumToFixed(int requested_digits, int* decimal_point,
|
||||
Bignum* numerator, Bignum* denominator,
|
||||
Vector<char>(buffer), int* length);
|
||||
// Generates 'count' digits of numerator/denominator.
|
||||
// Once 'count' digits have been produced rounds the result depending on the
|
||||
// remainder (remainders of exactly .5 round upwards). Might update the
|
||||
// decimal_point when rounding up (for example for 0.9999).
|
||||
static void GenerateCountedDigits(int count, int* decimal_point,
|
||||
Bignum* numerator, Bignum* denominator,
|
||||
Vector<char>(buffer), int* length);
|
||||
|
||||
|
||||
void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
|
||||
Vector<char> buffer, int* length, int* decimal_point) {
|
||||
ASSERT(v > 0);
|
||||
ASSERT(!Double(v).IsSpecial());
|
||||
uint64_t significand;
|
||||
int exponent;
|
||||
bool lower_boundary_is_closer;
|
||||
if (mode == BIGNUM_DTOA_SHORTEST_SINGLE) {
|
||||
float f = static_cast<float>(v);
|
||||
ASSERT(f == v);
|
||||
significand = Single(f).Significand();
|
||||
exponent = Single(f).Exponent();
|
||||
lower_boundary_is_closer = Single(f).LowerBoundaryIsCloser();
|
||||
} else {
|
||||
significand = Double(v).Significand();
|
||||
exponent = Double(v).Exponent();
|
||||
lower_boundary_is_closer = Double(v).LowerBoundaryIsCloser();
|
||||
}
|
||||
bool need_boundary_deltas =
|
||||
(mode == BIGNUM_DTOA_SHORTEST || mode == BIGNUM_DTOA_SHORTEST_SINGLE);
|
||||
|
||||
bool is_even = (significand & 1) == 0;
|
||||
int normalized_exponent = NormalizedExponent(significand, exponent);
|
||||
// estimated_power might be too low by 1.
|
||||
int estimated_power = EstimatePower(normalized_exponent);
|
||||
|
||||
// Shortcut for Fixed.
|
||||
// The requested digits correspond to the digits after the point. If the
|
||||
// number is much too small, then there is no need in trying to get any
|
||||
// digits.
|
||||
if (mode == BIGNUM_DTOA_FIXED && -estimated_power - 1 > requested_digits) {
|
||||
buffer[0] = '\0';
|
||||
*length = 0;
|
||||
// Set decimal-point to -requested_digits. This is what Gay does.
|
||||
// Note that it should not have any effect anyways since the string is
|
||||
// empty.
|
||||
*decimal_point = -requested_digits;
|
||||
return;
|
||||
}
|
||||
|
||||
Bignum numerator;
|
||||
Bignum denominator;
|
||||
Bignum delta_minus;
|
||||
Bignum delta_plus;
|
||||
// Make sure the bignum can grow large enough. The smallest double equals
|
||||
// 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
|
||||
// The maximum double is 1.7976931348623157e308 which needs fewer than
|
||||
// 308*4 binary digits.
|
||||
ASSERT(Bignum::kMaxSignificantBits >= 324*4);
|
||||
InitialScaledStartValues(significand, exponent, lower_boundary_is_closer,
|
||||
estimated_power, need_boundary_deltas,
|
||||
&numerator, &denominator,
|
||||
&delta_minus, &delta_plus);
|
||||
// We now have v = (numerator / denominator) * 10^estimated_power.
|
||||
FixupMultiply10(estimated_power, is_even, decimal_point,
|
||||
&numerator, &denominator,
|
||||
&delta_minus, &delta_plus);
|
||||
// We now have v = (numerator / denominator) * 10^(decimal_point-1), and
|
||||
// 1 <= (numerator + delta_plus) / denominator < 10
|
||||
switch (mode) {
|
||||
case BIGNUM_DTOA_SHORTEST:
|
||||
case BIGNUM_DTOA_SHORTEST_SINGLE:
|
||||
GenerateShortestDigits(&numerator, &denominator,
|
||||
&delta_minus, &delta_plus,
|
||||
is_even, buffer, length);
|
||||
break;
|
||||
case BIGNUM_DTOA_FIXED:
|
||||
BignumToFixed(requested_digits, decimal_point,
|
||||
&numerator, &denominator,
|
||||
buffer, length);
|
||||
break;
|
||||
case BIGNUM_DTOA_PRECISION:
|
||||
GenerateCountedDigits(requested_digits, decimal_point,
|
||||
&numerator, &denominator,
|
||||
buffer, length);
|
||||
break;
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
buffer[*length] = '\0';
|
||||
}
|
||||
|
||||
|
||||
// The procedure starts generating digits from the left to the right and stops
|
||||
// when the generated digits yield the shortest decimal representation of v. A
|
||||
// decimal representation of v is a number lying closer to v than to any other
|
||||
// double, so it converts to v when read.
|
||||
//
|
||||
// This is true if d, the decimal representation, is between m- and m+, the
|
||||
// upper and lower boundaries. d must be strictly between them if !is_even.
|
||||
// m- := (numerator - delta_minus) / denominator
|
||||
// m+ := (numerator + delta_plus) / denominator
|
||||
//
|
||||
// Precondition: 0 <= (numerator+delta_plus) / denominator < 10.
|
||||
// If 1 <= (numerator+delta_plus) / denominator < 10 then no leading 0 digit
|
||||
// will be produced. This should be the standard precondition.
|
||||
static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
|
||||
Bignum* delta_minus, Bignum* delta_plus,
|
||||
bool is_even,
|
||||
Vector<char> buffer, int* length) {
|
||||
// Small optimization: if delta_minus and delta_plus are the same just reuse
|
||||
// one of the two bignums.
|
||||
if (Bignum::Equal(*delta_minus, *delta_plus)) {
|
||||
delta_plus = delta_minus;
|
||||
}
|
||||
*length = 0;
|
||||
for (;;) {
|
||||
uint16_t digit;
|
||||
digit = numerator->DivideModuloIntBignum(*denominator);
|
||||
ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
|
||||
// digit = numerator / denominator (integer division).
|
||||
// numerator = numerator % denominator.
|
||||
buffer[(*length)++] = static_cast<char>(digit + '0');
|
||||
|
||||
// Can we stop already?
|
||||
// If the remainder of the division is less than the distance to the lower
|
||||
// boundary we can stop. In this case we simply round down (discarding the
|
||||
// remainder).
|
||||
// Similarly we test if we can round up (using the upper boundary).
|
||||
bool in_delta_room_minus;
|
||||
bool in_delta_room_plus;
|
||||
if (is_even) {
|
||||
in_delta_room_minus = Bignum::LessEqual(*numerator, *delta_minus);
|
||||
} else {
|
||||
in_delta_room_minus = Bignum::Less(*numerator, *delta_minus);
|
||||
}
|
||||
if (is_even) {
|
||||
in_delta_room_plus =
|
||||
Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
|
||||
} else {
|
||||
in_delta_room_plus =
|
||||
Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
|
||||
}
|
||||
if (!in_delta_room_minus && !in_delta_room_plus) {
|
||||
// Prepare for next iteration.
|
||||
numerator->Times10();
|
||||
delta_minus->Times10();
|
||||
// We optimized delta_plus to be equal to delta_minus (if they share the
|
||||
// same value). So don't multiply delta_plus if they point to the same
|
||||
// object.
|
||||
if (delta_minus != delta_plus) {
|
||||
delta_plus->Times10();
|
||||
}
|
||||
} else if (in_delta_room_minus && in_delta_room_plus) {
|
||||
// Let's see if 2*numerator < denominator.
|
||||
// If yes, then the next digit would be < 5 and we can round down.
|
||||
int compare = Bignum::PlusCompare(*numerator, *numerator, *denominator);
|
||||
if (compare < 0) {
|
||||
// Remaining digits are less than .5. -> Round down (== do nothing).
|
||||
} else if (compare > 0) {
|
||||
// Remaining digits are more than .5 of denominator. -> Round up.
|
||||
// Note that the last digit could not be a '9' as otherwise the whole
|
||||
// loop would have stopped earlier.
|
||||
// We still have an assert here in case the preconditions were not
|
||||
// satisfied.
|
||||
ASSERT(buffer[(*length) - 1] != '9');
|
||||
buffer[(*length) - 1]++;
|
||||
} else {
|
||||
// Halfway case.
|
||||
// TODO(floitsch): need a way to solve half-way cases.
|
||||
// For now let's round towards even (since this is what Gay seems to
|
||||
// do).
|
||||
|
||||
if ((buffer[(*length) - 1] - '0') % 2 == 0) {
|
||||
// Round down => Do nothing.
|
||||
} else {
|
||||
ASSERT(buffer[(*length) - 1] != '9');
|
||||
buffer[(*length) - 1]++;
|
||||
}
|
||||
}
|
||||
return;
|
||||
} else if (in_delta_room_minus) {
|
||||
// Round down (== do nothing).
|
||||
return;
|
||||
} else { // in_delta_room_plus
|
||||
// Round up.
|
||||
// Note again that the last digit could not be '9' since this would have
|
||||
// stopped the loop earlier.
|
||||
// We still have an ASSERT here, in case the preconditions were not
|
||||
// satisfied.
|
||||
ASSERT(buffer[(*length) -1] != '9');
|
||||
buffer[(*length) - 1]++;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Let v = numerator / denominator < 10.
|
||||
// Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
|
||||
// from left to right. Once 'count' digits have been produced we decide wether
|
||||
// to round up or down. Remainders of exactly .5 round upwards. Numbers such
|
||||
// as 9.999999 propagate a carry all the way, and change the
|
||||
// exponent (decimal_point), when rounding upwards.
|
||||
static void GenerateCountedDigits(int count, int* decimal_point,
|
||||
Bignum* numerator, Bignum* denominator,
|
||||
Vector<char> buffer, int* length) {
|
||||
ASSERT(count >= 0);
|
||||
for (int i = 0; i < count - 1; ++i) {
|
||||
uint16_t digit;
|
||||
digit = numerator->DivideModuloIntBignum(*denominator);
|
||||
ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
|
||||
// digit = numerator / denominator (integer division).
|
||||
// numerator = numerator % denominator.
|
||||
buffer[i] = static_cast<char>(digit + '0');
|
||||
// Prepare for next iteration.
|
||||
numerator->Times10();
|
||||
}
|
||||
// Generate the last digit.
|
||||
uint16_t digit;
|
||||
digit = numerator->DivideModuloIntBignum(*denominator);
|
||||
if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
|
||||
digit++;
|
||||
}
|
||||
ASSERT(digit <= 10);
|
||||
buffer[count - 1] = static_cast<char>(digit + '0');
|
||||
// Correct bad digits (in case we had a sequence of '9's). Propagate the
|
||||
// carry until we hat a non-'9' or til we reach the first digit.
|
||||
for (int i = count - 1; i > 0; --i) {
|
||||
if (buffer[i] != '0' + 10) break;
|
||||
buffer[i] = '0';
|
||||
buffer[i - 1]++;
|
||||
}
|
||||
if (buffer[0] == '0' + 10) {
|
||||
// Propagate a carry past the top place.
|
||||
buffer[0] = '1';
|
||||
(*decimal_point)++;
|
||||
}
|
||||
*length = count;
|
||||
}
|
||||
|
||||
|
||||
// Generates 'requested_digits' after the decimal point. It might omit
|
||||
// trailing '0's. If the input number is too small then no digits at all are
|
||||
// generated (ex.: 2 fixed digits for 0.00001).
|
||||
//
|
||||
// Input verifies: 1 <= (numerator + delta) / denominator < 10.
|
||||
static void BignumToFixed(int requested_digits, int* decimal_point,
|
||||
Bignum* numerator, Bignum* denominator,
|
||||
Vector<char>(buffer), int* length) {
|
||||
// Note that we have to look at more than just the requested_digits, since
|
||||
// a number could be rounded up. Example: v=0.5 with requested_digits=0.
|
||||
// Even though the power of v equals 0 we can't just stop here.
|
||||
if (-(*decimal_point) > requested_digits) {
|
||||
// The number is definitively too small.
|
||||
// Ex: 0.001 with requested_digits == 1.
|
||||
// Set decimal-point to -requested_digits. This is what Gay does.
|
||||
// Note that it should not have any effect anyways since the string is
|
||||
// empty.
|
||||
*decimal_point = -requested_digits;
|
||||
*length = 0;
|
||||
return;
|
||||
} else if (-(*decimal_point) == requested_digits) {
|
||||
// We only need to verify if the number rounds down or up.
|
||||
// Ex: 0.04 and 0.06 with requested_digits == 1.
|
||||
ASSERT(*decimal_point == -requested_digits);
|
||||
// Initially the fraction lies in range (1, 10]. Multiply the denominator
|
||||
// by 10 so that we can compare more easily.
|
||||
denominator->Times10();
|
||||
if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
|
||||
// If the fraction is >= 0.5 then we have to include the rounded
|
||||
// digit.
|
||||
buffer[0] = '1';
|
||||
*length = 1;
|
||||
(*decimal_point)++;
|
||||
} else {
|
||||
// Note that we caught most of similar cases earlier.
|
||||
*length = 0;
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
// The requested digits correspond to the digits after the point.
|
||||
// The variable 'needed_digits' includes the digits before the point.
|
||||
int needed_digits = (*decimal_point) + requested_digits;
|
||||
GenerateCountedDigits(needed_digits, decimal_point,
|
||||
numerator, denominator,
|
||||
buffer, length);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Returns an estimation of k such that 10^(k-1) <= v < 10^k where
|
||||
// v = f * 2^exponent and 2^52 <= f < 2^53.
|
||||
// v is hence a normalized double with the given exponent. The output is an
|
||||
// approximation for the exponent of the decimal approimation .digits * 10^k.
|
||||
//
|
||||
// The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
|
||||
// Note: this property holds for v's upper boundary m+ too.
|
||||
// 10^k <= m+ < 10^k+1.
|
||||
// (see explanation below).
|
||||
//
|
||||
// Examples:
|
||||
// EstimatePower(0) => 16
|
||||
// EstimatePower(-52) => 0
|
||||
//
|
||||
// Note: e >= 0 => EstimatedPower(e) > 0. No similar claim can be made for e<0.
|
||||
static int EstimatePower(int exponent) {
|
||||
// This function estimates log10 of v where v = f*2^e (with e == exponent).
|
||||
// Note that 10^floor(log10(v)) <= v, but v <= 10^ceil(log10(v)).
|
||||
// Note that f is bounded by its container size. Let p = 53 (the double's
|
||||
// significand size). Then 2^(p-1) <= f < 2^p.
|
||||
//
|
||||
// Given that log10(v) == log2(v)/log2(10) and e+(len(f)-1) is quite close
|
||||
// to log2(v) the function is simplified to (e+(len(f)-1)/log2(10)).
|
||||
// The computed number undershoots by less than 0.631 (when we compute log3
|
||||
// and not log10).
|
||||
//
|
||||
// Optimization: since we only need an approximated result this computation
|
||||
// can be performed on 64 bit integers. On x86/x64 architecture the speedup is
|
||||
// not really measurable, though.
|
||||
//
|
||||
// Since we want to avoid overshooting we decrement by 1e10 so that
|
||||
// floating-point imprecisions don't affect us.
|
||||
//
|
||||
// Explanation for v's boundary m+: the computation takes advantage of
|
||||
// the fact that 2^(p-1) <= f < 2^p. Boundaries still satisfy this requirement
|
||||
// (even for denormals where the delta can be much more important).
|
||||
|
||||
const double k1Log10 = 0.30102999566398114; // 1/lg(10)
|
||||
|
||||
// For doubles len(f) == 53 (don't forget the hidden bit).
|
||||
const int kSignificandSize = Double::kSignificandSize;
|
||||
double estimate = ceil((exponent + kSignificandSize - 1) * k1Log10 - 1e-10);
|
||||
return static_cast<int>(estimate);
|
||||
}
|
||||
|
||||
|
||||
// See comments for InitialScaledStartValues.
|
||||
static void InitialScaledStartValuesPositiveExponent(
|
||||
uint64_t significand, int exponent,
|
||||
int estimated_power, bool need_boundary_deltas,
|
||||
Bignum* numerator, Bignum* denominator,
|
||||
Bignum* delta_minus, Bignum* delta_plus) {
|
||||
// A positive exponent implies a positive power.
|
||||
ASSERT(estimated_power >= 0);
|
||||
// Since the estimated_power is positive we simply multiply the denominator
|
||||
// by 10^estimated_power.
|
||||
|
||||
// numerator = v.
|
||||
numerator->AssignUInt64(significand);
|
||||
numerator->ShiftLeft(exponent);
|
||||
// denominator = 10^estimated_power.
|
||||
denominator->AssignPowerUInt16(10, estimated_power);
|
||||
|
||||
if (need_boundary_deltas) {
|
||||
// Introduce a common denominator so that the deltas to the boundaries are
|
||||
// integers.
|
||||
denominator->ShiftLeft(1);
|
||||
numerator->ShiftLeft(1);
|
||||
// Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
|
||||
// denominator (of 2) delta_plus equals 2^e.
|
||||
delta_plus->AssignUInt16(1);
|
||||
delta_plus->ShiftLeft(exponent);
|
||||
// Same for delta_minus. The adjustments if f == 2^p-1 are done later.
|
||||
delta_minus->AssignUInt16(1);
|
||||
delta_minus->ShiftLeft(exponent);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// See comments for InitialScaledStartValues
|
||||
static void InitialScaledStartValuesNegativeExponentPositivePower(
|
||||
uint64_t significand, int exponent,
|
||||
int estimated_power, bool need_boundary_deltas,
|
||||
Bignum* numerator, Bignum* denominator,
|
||||
Bignum* delta_minus, Bignum* delta_plus) {
|
||||
// v = f * 2^e with e < 0, and with estimated_power >= 0.
|
||||
// This means that e is close to 0 (have a look at how estimated_power is
|
||||
// computed).
|
||||
|
||||
// numerator = significand
|
||||
// since v = significand * 2^exponent this is equivalent to
|
||||
// numerator = v * / 2^-exponent
|
||||
numerator->AssignUInt64(significand);
|
||||
// denominator = 10^estimated_power * 2^-exponent (with exponent < 0)
|
||||
denominator->AssignPowerUInt16(10, estimated_power);
|
||||
denominator->ShiftLeft(-exponent);
|
||||
|
||||
if (need_boundary_deltas) {
|
||||
// Introduce a common denominator so that the deltas to the boundaries are
|
||||
// integers.
|
||||
denominator->ShiftLeft(1);
|
||||
numerator->ShiftLeft(1);
|
||||
// Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
|
||||
// denominator (of 2) delta_plus equals 2^e.
|
||||
// Given that the denominator already includes v's exponent the distance
|
||||
// to the boundaries is simply 1.
|
||||
delta_plus->AssignUInt16(1);
|
||||
// Same for delta_minus. The adjustments if f == 2^p-1 are done later.
|
||||
delta_minus->AssignUInt16(1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// See comments for InitialScaledStartValues
|
||||
static void InitialScaledStartValuesNegativeExponentNegativePower(
|
||||
uint64_t significand, int exponent,
|
||||
int estimated_power, bool need_boundary_deltas,
|
||||
Bignum* numerator, Bignum* denominator,
|
||||
Bignum* delta_minus, Bignum* delta_plus) {
|
||||
// Instead of multiplying the denominator with 10^estimated_power we
|
||||
// multiply all values (numerator and deltas) by 10^-estimated_power.
|
||||
|
||||
// Use numerator as temporary container for power_ten.
|
||||
Bignum* power_ten = numerator;
|
||||
power_ten->AssignPowerUInt16(10, -estimated_power);
|
||||
|
||||
if (need_boundary_deltas) {
|
||||
// Since power_ten == numerator we must make a copy of 10^estimated_power
|
||||
// before we complete the computation of the numerator.
|
||||
// delta_plus = delta_minus = 10^estimated_power
|
||||
delta_plus->AssignBignum(*power_ten);
|
||||
delta_minus->AssignBignum(*power_ten);
|
||||
}
|
||||
|
||||
// numerator = significand * 2 * 10^-estimated_power
|
||||
// since v = significand * 2^exponent this is equivalent to
|
||||
// numerator = v * 10^-estimated_power * 2 * 2^-exponent.
|
||||
// Remember: numerator has been abused as power_ten. So no need to assign it
|
||||
// to itself.
|
||||
ASSERT(numerator == power_ten);
|
||||
numerator->MultiplyByUInt64(significand);
|
||||
|
||||
// denominator = 2 * 2^-exponent with exponent < 0.
|
||||
denominator->AssignUInt16(1);
|
||||
denominator->ShiftLeft(-exponent);
|
||||
|
||||
if (need_boundary_deltas) {
|
||||
// Introduce a common denominator so that the deltas to the boundaries are
|
||||
// integers.
|
||||
numerator->ShiftLeft(1);
|
||||
denominator->ShiftLeft(1);
|
||||
// With this shift the boundaries have their correct value, since
|
||||
// delta_plus = 10^-estimated_power, and
|
||||
// delta_minus = 10^-estimated_power.
|
||||
// These assignments have been done earlier.
|
||||
// The adjustments if f == 2^p-1 (lower boundary is closer) are done later.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Let v = significand * 2^exponent.
|
||||
// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
|
||||
// and denominator. The functions GenerateShortestDigits and
|
||||
// GenerateCountedDigits will then convert this ratio to its decimal
|
||||
// representation d, with the required accuracy.
|
||||
// Then d * 10^estimated_power is the representation of v.
|
||||
// (Note: the fraction and the estimated_power might get adjusted before
|
||||
// generating the decimal representation.)
|
||||
//
|
||||
// The initial start values consist of:
|
||||
// - a scaled numerator: s.t. numerator/denominator == v / 10^estimated_power.
|
||||
// - a scaled (common) denominator.
|
||||
// optionally (used by GenerateShortestDigits to decide if it has the shortest
|
||||
// decimal converting back to v):
|
||||
// - v - m-: the distance to the lower boundary.
|
||||
// - m+ - v: the distance to the upper boundary.
|
||||
//
|
||||
// v, m+, m-, and therefore v - m- and m+ - v all share the same denominator.
|
||||
//
|
||||
// Let ep == estimated_power, then the returned values will satisfy:
|
||||
// v / 10^ep = numerator / denominator.
|
||||
// v's boundarys m- and m+:
|
||||
// m- / 10^ep == v / 10^ep - delta_minus / denominator
|
||||
// m+ / 10^ep == v / 10^ep + delta_plus / denominator
|
||||
// Or in other words:
|
||||
// m- == v - delta_minus * 10^ep / denominator;
|
||||
// m+ == v + delta_plus * 10^ep / denominator;
|
||||
//
|
||||
// Since 10^(k-1) <= v < 10^k (with k == estimated_power)
|
||||
// or 10^k <= v < 10^(k+1)
|
||||
// we then have 0.1 <= numerator/denominator < 1
|
||||
// or 1 <= numerator/denominator < 10
|
||||
//
|
||||
// It is then easy to kickstart the digit-generation routine.
|
||||
//
|
||||
// The boundary-deltas are only filled if the mode equals BIGNUM_DTOA_SHORTEST
|
||||
// or BIGNUM_DTOA_SHORTEST_SINGLE.
|
||||
|
||||
static void InitialScaledStartValues(uint64_t significand,
|
||||
int exponent,
|
||||
bool lower_boundary_is_closer,
|
||||
int estimated_power,
|
||||
bool need_boundary_deltas,
|
||||
Bignum* numerator,
|
||||
Bignum* denominator,
|
||||
Bignum* delta_minus,
|
||||
Bignum* delta_plus) {
|
||||
if (exponent >= 0) {
|
||||
InitialScaledStartValuesPositiveExponent(
|
||||
significand, exponent, estimated_power, need_boundary_deltas,
|
||||
numerator, denominator, delta_minus, delta_plus);
|
||||
} else if (estimated_power >= 0) {
|
||||
InitialScaledStartValuesNegativeExponentPositivePower(
|
||||
significand, exponent, estimated_power, need_boundary_deltas,
|
||||
numerator, denominator, delta_minus, delta_plus);
|
||||
} else {
|
||||
InitialScaledStartValuesNegativeExponentNegativePower(
|
||||
significand, exponent, estimated_power, need_boundary_deltas,
|
||||
numerator, denominator, delta_minus, delta_plus);
|
||||
}
|
||||
|
||||
if (need_boundary_deltas && lower_boundary_is_closer) {
|
||||
// The lower boundary is closer at half the distance of "normal" numbers.
|
||||
// Increase the common denominator and adapt all but the delta_minus.
|
||||
denominator->ShiftLeft(1); // *2
|
||||
numerator->ShiftLeft(1); // *2
|
||||
delta_plus->ShiftLeft(1); // *2
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// This routine multiplies numerator/denominator so that its values lies in the
|
||||
// range 1-10. That is after a call to this function we have:
|
||||
// 1 <= (numerator + delta_plus) /denominator < 10.
|
||||
// Let numerator the input before modification and numerator' the argument
|
||||
// after modification, then the output-parameter decimal_point is such that
|
||||
// numerator / denominator * 10^estimated_power ==
|
||||
// numerator' / denominator' * 10^(decimal_point - 1)
|
||||
// In some cases estimated_power was too low, and this is already the case. We
|
||||
// then simply adjust the power so that 10^(k-1) <= v < 10^k (with k ==
|
||||
// estimated_power) but do not touch the numerator or denominator.
|
||||
// Otherwise the routine multiplies the numerator and the deltas by 10.
|
||||
static void FixupMultiply10(int estimated_power, bool is_even,
|
||||
int* decimal_point,
|
||||
Bignum* numerator, Bignum* denominator,
|
||||
Bignum* delta_minus, Bignum* delta_plus) {
|
||||
bool in_range;
|
||||
if (is_even) {
|
||||
// For IEEE doubles half-way cases (in decimal system numbers ending with 5)
|
||||
// are rounded to the closest floating-point number with even significand.
|
||||
in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
|
||||
} else {
|
||||
in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
|
||||
}
|
||||
if (in_range) {
|
||||
// Since numerator + delta_plus >= denominator we already have
|
||||
// 1 <= numerator/denominator < 10. Simply update the estimated_power.
|
||||
*decimal_point = estimated_power + 1;
|
||||
} else {
|
||||
*decimal_point = estimated_power;
|
||||
numerator->Times10();
|
||||
if (Bignum::Equal(*delta_minus, *delta_plus)) {
|
||||
delta_minus->Times10();
|
||||
delta_plus->AssignBignum(*delta_minus);
|
||||
} else {
|
||||
delta_minus->Times10();
|
||||
delta_plus->Times10();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace double_conversion
|
|
@ -1,84 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#ifndef DOUBLE_CONVERSION_BIGNUM_DTOA_H_
|
||||
#define DOUBLE_CONVERSION_BIGNUM_DTOA_H_
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
enum BignumDtoaMode {
|
||||
// Return the shortest correct representation.
|
||||
// For example the output of 0.299999999999999988897 is (the less accurate but
|
||||
// correct) 0.3.
|
||||
BIGNUM_DTOA_SHORTEST,
|
||||
// Same as BIGNUM_DTOA_SHORTEST but for single-precision floats.
|
||||
BIGNUM_DTOA_SHORTEST_SINGLE,
|
||||
// Return a fixed number of digits after the decimal point.
|
||||
// For instance fixed(0.1, 4) becomes 0.1000
|
||||
// If the input number is big, the output will be big.
|
||||
BIGNUM_DTOA_FIXED,
|
||||
// Return a fixed number of digits, no matter what the exponent is.
|
||||
BIGNUM_DTOA_PRECISION
|
||||
};
|
||||
|
||||
// Converts the given double 'v' to ascii.
|
||||
// The result should be interpreted as buffer * 10^(point-length).
|
||||
// The buffer will be null-terminated.
|
||||
//
|
||||
// The input v must be > 0 and different from NaN, and Infinity.
|
||||
//
|
||||
// The output depends on the given mode:
|
||||
// - SHORTEST: produce the least amount of digits for which the internal
|
||||
// identity requirement is still satisfied. If the digits are printed
|
||||
// (together with the correct exponent) then reading this number will give
|
||||
// 'v' again. The buffer will choose the representation that is closest to
|
||||
// 'v'. If there are two at the same distance, than the number is round up.
|
||||
// In this mode the 'requested_digits' parameter is ignored.
|
||||
// - FIXED: produces digits necessary to print a given number with
|
||||
// 'requested_digits' digits after the decimal point. The produced digits
|
||||
// might be too short in which case the caller has to fill the gaps with '0's.
|
||||
// Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
|
||||
// Halfway cases are rounded up. The call toFixed(0.15, 2) thus returns
|
||||
// buffer="2", point=0.
|
||||
// Note: the length of the returned buffer has no meaning wrt the significance
|
||||
// of its digits. That is, just because it contains '0's does not mean that
|
||||
// any other digit would not satisfy the internal identity requirement.
|
||||
// - PRECISION: produces 'requested_digits' where the first digit is not '0'.
|
||||
// Even though the length of produced digits usually equals
|
||||
// 'requested_digits', the function is allowed to return fewer digits, in
|
||||
// which case the caller has to fill the missing digits with '0's.
|
||||
// Halfway cases are again rounded up.
|
||||
// 'BignumDtoa' expects the given buffer to be big enough to hold all digits
|
||||
// and a terminating null-character.
|
||||
void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
|
||||
Vector<char> buffer, int* length, int* point);
|
||||
|
||||
} // namespace double_conversion
|
||||
|
||||
#endif // DOUBLE_CONVERSION_BIGNUM_DTOA_H_
|
|
@ -1,766 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#include "bignum.h"
|
||||
#include "utils.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
Bignum::Bignum()
|
||||
: bigits_(bigits_buffer_, kBigitCapacity), used_digits_(0), exponent_(0) {
|
||||
for (int i = 0; i < kBigitCapacity; ++i) {
|
||||
bigits_[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
template<typename S>
|
||||
static int BitSize(S value) {
|
||||
(void) value; // Mark variable as used.
|
||||
return 8 * sizeof(value);
|
||||
}
|
||||
|
||||
// Guaranteed to lie in one Bigit.
|
||||
void Bignum::AssignUInt16(uint16_t value) {
|
||||
ASSERT(kBigitSize >= BitSize(value));
|
||||
Zero();
|
||||
if (value == 0) return;
|
||||
|
||||
EnsureCapacity(1);
|
||||
bigits_[0] = value;
|
||||
used_digits_ = 1;
|
||||
}
|
||||
|
||||
|
||||
void Bignum::AssignUInt64(uint64_t value) {
|
||||
const int kUInt64Size = 64;
|
||||
|
||||
Zero();
|
||||
if (value == 0) return;
|
||||
|
||||
int needed_bigits = kUInt64Size / kBigitSize + 1;
|
||||
EnsureCapacity(needed_bigits);
|
||||
for (int i = 0; i < needed_bigits; ++i) {
|
||||
bigits_[i] = value & kBigitMask;
|
||||
value = value >> kBigitSize;
|
||||
}
|
||||
used_digits_ = needed_bigits;
|
||||
Clamp();
|
||||
}
|
||||
|
||||
|
||||
void Bignum::AssignBignum(const Bignum& other) {
|
||||
exponent_ = other.exponent_;
|
||||
for (int i = 0; i < other.used_digits_; ++i) {
|
||||
bigits_[i] = other.bigits_[i];
|
||||
}
|
||||
// Clear the excess digits (if there were any).
|
||||
for (int i = other.used_digits_; i < used_digits_; ++i) {
|
||||
bigits_[i] = 0;
|
||||
}
|
||||
used_digits_ = other.used_digits_;
|
||||
}
|
||||
|
||||
|
||||
static uint64_t ReadUInt64(Vector<const char> buffer,
|
||||
int from,
|
||||
int digits_to_read) {
|
||||
uint64_t result = 0;
|
||||
for (int i = from; i < from + digits_to_read; ++i) {
|
||||
int digit = buffer[i] - '0';
|
||||
ASSERT(0 <= digit && digit <= 9);
|
||||
result = result * 10 + digit;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
void Bignum::AssignDecimalString(Vector<const char> value) {
|
||||
// 2^64 = 18446744073709551616 > 10^19
|
||||
const int kMaxUint64DecimalDigits = 19;
|
||||
Zero();
|
||||
int length = value.length();
|
||||
int pos = 0;
|
||||
// Let's just say that each digit needs 4 bits.
|
||||
while (length >= kMaxUint64DecimalDigits) {
|
||||
uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
|
||||
pos += kMaxUint64DecimalDigits;
|
||||
length -= kMaxUint64DecimalDigits;
|
||||
MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
|
||||
AddUInt64(digits);
|
||||
}
|
||||
uint64_t digits = ReadUInt64(value, pos, length);
|
||||
MultiplyByPowerOfTen(length);
|
||||
AddUInt64(digits);
|
||||
Clamp();
|
||||
}
|
||||
|
||||
|
||||
static int HexCharValue(char c) {
|
||||
if ('0' <= c && c <= '9') return c - '0';
|
||||
if ('a' <= c && c <= 'f') return 10 + c - 'a';
|
||||
ASSERT('A' <= c && c <= 'F');
|
||||
return 10 + c - 'A';
|
||||
}
|
||||
|
||||
|
||||
void Bignum::AssignHexString(Vector<const char> value) {
|
||||
Zero();
|
||||
int length = value.length();
|
||||
|
||||
int needed_bigits = length * 4 / kBigitSize + 1;
|
||||
EnsureCapacity(needed_bigits);
|
||||
int string_index = length - 1;
|
||||
for (int i = 0; i < needed_bigits - 1; ++i) {
|
||||
// These bigits are guaranteed to be "full".
|
||||
Chunk current_bigit = 0;
|
||||
for (int j = 0; j < kBigitSize / 4; j++) {
|
||||
current_bigit += HexCharValue(value[string_index--]) << (j * 4);
|
||||
}
|
||||
bigits_[i] = current_bigit;
|
||||
}
|
||||
used_digits_ = needed_bigits - 1;
|
||||
|
||||
Chunk most_significant_bigit = 0; // Could be = 0;
|
||||
for (int j = 0; j <= string_index; ++j) {
|
||||
most_significant_bigit <<= 4;
|
||||
most_significant_bigit += HexCharValue(value[j]);
|
||||
}
|
||||
if (most_significant_bigit != 0) {
|
||||
bigits_[used_digits_] = most_significant_bigit;
|
||||
used_digits_++;
|
||||
}
|
||||
Clamp();
|
||||
}
|
||||
|
||||
|
||||
void Bignum::AddUInt64(uint64_t operand) {
|
||||
if (operand == 0) return;
|
||||
Bignum other;
|
||||
other.AssignUInt64(operand);
|
||||
AddBignum(other);
|
||||
}
|
||||
|
||||
|
||||
void Bignum::AddBignum(const Bignum& other) {
|
||||
ASSERT(IsClamped());
|
||||
ASSERT(other.IsClamped());
|
||||
|
||||
// If this has a greater exponent than other append zero-bigits to this.
|
||||
// After this call exponent_ <= other.exponent_.
|
||||
Align(other);
|
||||
|
||||
// There are two possibilities:
|
||||
// aaaaaaaaaaa 0000 (where the 0s represent a's exponent)
|
||||
// bbbbb 00000000
|
||||
// ----------------
|
||||
// ccccccccccc 0000
|
||||
// or
|
||||
// aaaaaaaaaa 0000
|
||||
// bbbbbbbbb 0000000
|
||||
// -----------------
|
||||
// cccccccccccc 0000
|
||||
// In both cases we might need a carry bigit.
|
||||
|
||||
EnsureCapacity(1 + Max(BigitLength(), other.BigitLength()) - exponent_);
|
||||
Chunk carry = 0;
|
||||
int bigit_pos = other.exponent_ - exponent_;
|
||||
ASSERT(bigit_pos >= 0);
|
||||
for (int i = 0; i < other.used_digits_; ++i) {
|
||||
Chunk sum = bigits_[bigit_pos] + other.bigits_[i] + carry;
|
||||
bigits_[bigit_pos] = sum & kBigitMask;
|
||||
carry = sum >> kBigitSize;
|
||||
bigit_pos++;
|
||||
}
|
||||
|
||||
while (carry != 0) {
|
||||
Chunk sum = bigits_[bigit_pos] + carry;
|
||||
bigits_[bigit_pos] = sum & kBigitMask;
|
||||
carry = sum >> kBigitSize;
|
||||
bigit_pos++;
|
||||
}
|
||||
used_digits_ = Max(bigit_pos, used_digits_);
|
||||
ASSERT(IsClamped());
|
||||
}
|
||||
|
||||
|
||||
void Bignum::SubtractBignum(const Bignum& other) {
|
||||
ASSERT(IsClamped());
|
||||
ASSERT(other.IsClamped());
|
||||
// We require this to be bigger than other.
|
||||
ASSERT(LessEqual(other, *this));
|
||||
|
||||
Align(other);
|
||||
|
||||
int offset = other.exponent_ - exponent_;
|
||||
Chunk borrow = 0;
|
||||
int i;
|
||||
for (i = 0; i < other.used_digits_; ++i) {
|
||||
ASSERT((borrow == 0) || (borrow == 1));
|
||||
Chunk difference = bigits_[i + offset] - other.bigits_[i] - borrow;
|
||||
bigits_[i + offset] = difference & kBigitMask;
|
||||
borrow = difference >> (kChunkSize - 1);
|
||||
}
|
||||
while (borrow != 0) {
|
||||
Chunk difference = bigits_[i + offset] - borrow;
|
||||
bigits_[i + offset] = difference & kBigitMask;
|
||||
borrow = difference >> (kChunkSize - 1);
|
||||
++i;
|
||||
}
|
||||
Clamp();
|
||||
}
|
||||
|
||||
|
||||
void Bignum::ShiftLeft(int shift_amount) {
|
||||
if (used_digits_ == 0) return;
|
||||
exponent_ += shift_amount / kBigitSize;
|
||||
int local_shift = shift_amount % kBigitSize;
|
||||
EnsureCapacity(used_digits_ + 1);
|
||||
BigitsShiftLeft(local_shift);
|
||||
}
|
||||
|
||||
|
||||
void Bignum::MultiplyByUInt32(uint32_t factor) {
|
||||
if (factor == 1) return;
|
||||
if (factor == 0) {
|
||||
Zero();
|
||||
return;
|
||||
}
|
||||
if (used_digits_ == 0) return;
|
||||
|
||||
// The product of a bigit with the factor is of size kBigitSize + 32.
|
||||
// Assert that this number + 1 (for the carry) fits into double chunk.
|
||||
ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1);
|
||||
DoubleChunk carry = 0;
|
||||
for (int i = 0; i < used_digits_; ++i) {
|
||||
DoubleChunk product = static_cast<DoubleChunk>(factor) * bigits_[i] + carry;
|
||||
bigits_[i] = static_cast<Chunk>(product & kBigitMask);
|
||||
carry = (product >> kBigitSize);
|
||||
}
|
||||
while (carry != 0) {
|
||||
EnsureCapacity(used_digits_ + 1);
|
||||
bigits_[used_digits_] = carry & kBigitMask;
|
||||
used_digits_++;
|
||||
carry >>= kBigitSize;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Bignum::MultiplyByUInt64(uint64_t factor) {
|
||||
if (factor == 1) return;
|
||||
if (factor == 0) {
|
||||
Zero();
|
||||
return;
|
||||
}
|
||||
ASSERT(kBigitSize < 32);
|
||||
uint64_t carry = 0;
|
||||
uint64_t low = factor & 0xFFFFFFFF;
|
||||
uint64_t high = factor >> 32;
|
||||
for (int i = 0; i < used_digits_; ++i) {
|
||||
uint64_t product_low = low * bigits_[i];
|
||||
uint64_t product_high = high * bigits_[i];
|
||||
uint64_t tmp = (carry & kBigitMask) + product_low;
|
||||
bigits_[i] = tmp & kBigitMask;
|
||||
carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
|
||||
(product_high << (32 - kBigitSize));
|
||||
}
|
||||
while (carry != 0) {
|
||||
EnsureCapacity(used_digits_ + 1);
|
||||
bigits_[used_digits_] = carry & kBigitMask;
|
||||
used_digits_++;
|
||||
carry >>= kBigitSize;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Bignum::MultiplyByPowerOfTen(int exponent) {
|
||||
const uint64_t kFive27 = UINT64_2PART_C(0x6765c793, fa10079d);
|
||||
const uint16_t kFive1 = 5;
|
||||
const uint16_t kFive2 = kFive1 * 5;
|
||||
const uint16_t kFive3 = kFive2 * 5;
|
||||
const uint16_t kFive4 = kFive3 * 5;
|
||||
const uint16_t kFive5 = kFive4 * 5;
|
||||
const uint16_t kFive6 = kFive5 * 5;
|
||||
const uint32_t kFive7 = kFive6 * 5;
|
||||
const uint32_t kFive8 = kFive7 * 5;
|
||||
const uint32_t kFive9 = kFive8 * 5;
|
||||
const uint32_t kFive10 = kFive9 * 5;
|
||||
const uint32_t kFive11 = kFive10 * 5;
|
||||
const uint32_t kFive12 = kFive11 * 5;
|
||||
const uint32_t kFive13 = kFive12 * 5;
|
||||
const uint32_t kFive1_to_12[] =
|
||||
{ kFive1, kFive2, kFive3, kFive4, kFive5, kFive6,
|
||||
kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 };
|
||||
|
||||
ASSERT(exponent >= 0);
|
||||
if (exponent == 0) return;
|
||||
if (used_digits_ == 0) return;
|
||||
|
||||
// We shift by exponent at the end just before returning.
|
||||
int remaining_exponent = exponent;
|
||||
while (remaining_exponent >= 27) {
|
||||
MultiplyByUInt64(kFive27);
|
||||
remaining_exponent -= 27;
|
||||
}
|
||||
while (remaining_exponent >= 13) {
|
||||
MultiplyByUInt32(kFive13);
|
||||
remaining_exponent -= 13;
|
||||
}
|
||||
if (remaining_exponent > 0) {
|
||||
MultiplyByUInt32(kFive1_to_12[remaining_exponent - 1]);
|
||||
}
|
||||
ShiftLeft(exponent);
|
||||
}
|
||||
|
||||
|
||||
void Bignum::Square() {
|
||||
ASSERT(IsClamped());
|
||||
int product_length = 2 * used_digits_;
|
||||
EnsureCapacity(product_length);
|
||||
|
||||
// Comba multiplication: compute each column separately.
|
||||
// Example: r = a2a1a0 * b2b1b0.
|
||||
// r = 1 * a0b0 +
|
||||
// 10 * (a1b0 + a0b1) +
|
||||
// 100 * (a2b0 + a1b1 + a0b2) +
|
||||
// 1000 * (a2b1 + a1b2) +
|
||||
// 10000 * a2b2
|
||||
//
|
||||
// In the worst case we have to accumulate nb-digits products of digit*digit.
|
||||
//
|
||||
// Assert that the additional number of bits in a DoubleChunk are enough to
|
||||
// sum up used_digits of Bigit*Bigit.
|
||||
if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_digits_) {
|
||||
UNIMPLEMENTED();
|
||||
}
|
||||
DoubleChunk accumulator = 0;
|
||||
// First shift the digits so we don't overwrite them.
|
||||
int copy_offset = used_digits_;
|
||||
for (int i = 0; i < used_digits_; ++i) {
|
||||
bigits_[copy_offset + i] = bigits_[i];
|
||||
}
|
||||
// We have two loops to avoid some 'if's in the loop.
|
||||
for (int i = 0; i < used_digits_; ++i) {
|
||||
// Process temporary digit i with power i.
|
||||
// The sum of the two indices must be equal to i.
|
||||
int bigit_index1 = i;
|
||||
int bigit_index2 = 0;
|
||||
// Sum all of the sub-products.
|
||||
while (bigit_index1 >= 0) {
|
||||
Chunk chunk1 = bigits_[copy_offset + bigit_index1];
|
||||
Chunk chunk2 = bigits_[copy_offset + bigit_index2];
|
||||
accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
|
||||
bigit_index1--;
|
||||
bigit_index2++;
|
||||
}
|
||||
bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
|
||||
accumulator >>= kBigitSize;
|
||||
}
|
||||
for (int i = used_digits_; i < product_length; ++i) {
|
||||
int bigit_index1 = used_digits_ - 1;
|
||||
int bigit_index2 = i - bigit_index1;
|
||||
// Invariant: sum of both indices is again equal to i.
|
||||
// Inner loop runs 0 times on last iteration, emptying accumulator.
|
||||
while (bigit_index2 < used_digits_) {
|
||||
Chunk chunk1 = bigits_[copy_offset + bigit_index1];
|
||||
Chunk chunk2 = bigits_[copy_offset + bigit_index2];
|
||||
accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
|
||||
bigit_index1--;
|
||||
bigit_index2++;
|
||||
}
|
||||
// The overwritten bigits_[i] will never be read in further loop iterations,
|
||||
// because bigit_index1 and bigit_index2 are always greater
|
||||
// than i - used_digits_.
|
||||
bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
|
||||
accumulator >>= kBigitSize;
|
||||
}
|
||||
// Since the result was guaranteed to lie inside the number the
|
||||
// accumulator must be 0 now.
|
||||
ASSERT(accumulator == 0);
|
||||
|
||||
// Don't forget to update the used_digits and the exponent.
|
||||
used_digits_ = product_length;
|
||||
exponent_ *= 2;
|
||||
Clamp();
|
||||
}
|
||||
|
||||
|
||||
void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) {
|
||||
ASSERT(base != 0);
|
||||
ASSERT(power_exponent >= 0);
|
||||
if (power_exponent == 0) {
|
||||
AssignUInt16(1);
|
||||
return;
|
||||
}
|
||||
Zero();
|
||||
int shifts = 0;
|
||||
// We expect base to be in range 2-32, and most often to be 10.
|
||||
// It does not make much sense to implement different algorithms for counting
|
||||
// the bits.
|
||||
while ((base & 1) == 0) {
|
||||
base >>= 1;
|
||||
shifts++;
|
||||
}
|
||||
int bit_size = 0;
|
||||
int tmp_base = base;
|
||||
while (tmp_base != 0) {
|
||||
tmp_base >>= 1;
|
||||
bit_size++;
|
||||
}
|
||||
int final_size = bit_size * power_exponent;
|
||||
// 1 extra bigit for the shifting, and one for rounded final_size.
|
||||
EnsureCapacity(final_size / kBigitSize + 2);
|
||||
|
||||
// Left to Right exponentiation.
|
||||
int mask = 1;
|
||||
while (power_exponent >= mask) mask <<= 1;
|
||||
|
||||
// The mask is now pointing to the bit above the most significant 1-bit of
|
||||
// power_exponent.
|
||||
// Get rid of first 1-bit;
|
||||
mask >>= 2;
|
||||
uint64_t this_value = base;
|
||||
|
||||
bool delayed_multipliciation = false;
|
||||
const uint64_t max_32bits = 0xFFFFFFFF;
|
||||
while (mask != 0 && this_value <= max_32bits) {
|
||||
this_value = this_value * this_value;
|
||||
// Verify that there is enough space in this_value to perform the
|
||||
// multiplication. The first bit_size bits must be 0.
|
||||
if ((power_exponent & mask) != 0) {
|
||||
uint64_t base_bits_mask =
|
||||
~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
|
||||
bool high_bits_zero = (this_value & base_bits_mask) == 0;
|
||||
if (high_bits_zero) {
|
||||
this_value *= base;
|
||||
} else {
|
||||
delayed_multipliciation = true;
|
||||
}
|
||||
}
|
||||
mask >>= 1;
|
||||
}
|
||||
AssignUInt64(this_value);
|
||||
if (delayed_multipliciation) {
|
||||
MultiplyByUInt32(base);
|
||||
}
|
||||
|
||||
// Now do the same thing as a bignum.
|
||||
while (mask != 0) {
|
||||
Square();
|
||||
if ((power_exponent & mask) != 0) {
|
||||
MultiplyByUInt32(base);
|
||||
}
|
||||
mask >>= 1;
|
||||
}
|
||||
|
||||
// And finally add the saved shifts.
|
||||
ShiftLeft(shifts * power_exponent);
|
||||
}
|
||||
|
||||
|
||||
// Precondition: this/other < 16bit.
|
||||
uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
|
||||
ASSERT(IsClamped());
|
||||
ASSERT(other.IsClamped());
|
||||
ASSERT(other.used_digits_ > 0);
|
||||
|
||||
// Easy case: if we have less digits than the divisor than the result is 0.
|
||||
// Note: this handles the case where this == 0, too.
|
||||
if (BigitLength() < other.BigitLength()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
Align(other);
|
||||
|
||||
uint16_t result = 0;
|
||||
|
||||
// Start by removing multiples of 'other' until both numbers have the same
|
||||
// number of digits.
|
||||
while (BigitLength() > other.BigitLength()) {
|
||||
// This naive approach is extremely inefficient if `this` divided by other
|
||||
// is big. This function is implemented for doubleToString where
|
||||
// the result should be small (less than 10).
|
||||
ASSERT(other.bigits_[other.used_digits_ - 1] >= ((1 << kBigitSize) / 16));
|
||||
ASSERT(bigits_[used_digits_ - 1] < 0x10000);
|
||||
// Remove the multiples of the first digit.
|
||||
// Example this = 23 and other equals 9. -> Remove 2 multiples.
|
||||
result += static_cast<uint16_t>(bigits_[used_digits_ - 1]);
|
||||
SubtractTimes(other, bigits_[used_digits_ - 1]);
|
||||
}
|
||||
|
||||
ASSERT(BigitLength() == other.BigitLength());
|
||||
|
||||
// Both bignums are at the same length now.
|
||||
// Since other has more than 0 digits we know that the access to
|
||||
// bigits_[used_digits_ - 1] is safe.
|
||||
Chunk this_bigit = bigits_[used_digits_ - 1];
|
||||
Chunk other_bigit = other.bigits_[other.used_digits_ - 1];
|
||||
|
||||
if (other.used_digits_ == 1) {
|
||||
// Shortcut for easy (and common) case.
|
||||
int quotient = this_bigit / other_bigit;
|
||||
bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
|
||||
ASSERT(quotient < 0x10000);
|
||||
result += static_cast<uint16_t>(quotient);
|
||||
Clamp();
|
||||
return result;
|
||||
}
|
||||
|
||||
int division_estimate = this_bigit / (other_bigit + 1);
|
||||
ASSERT(division_estimate < 0x10000);
|
||||
result += static_cast<uint16_t>(division_estimate);
|
||||
SubtractTimes(other, division_estimate);
|
||||
|
||||
if (other_bigit * (division_estimate + 1) > this_bigit) {
|
||||
// No need to even try to subtract. Even if other's remaining digits were 0
|
||||
// another subtraction would be too much.
|
||||
return result;
|
||||
}
|
||||
|
||||
while (LessEqual(other, *this)) {
|
||||
SubtractBignum(other);
|
||||
result++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
template<typename S>
|
||||
static int SizeInHexChars(S number) {
|
||||
ASSERT(number > 0);
|
||||
int result = 0;
|
||||
while (number != 0) {
|
||||
number >>= 4;
|
||||
result++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
static char HexCharOfValue(int value) {
|
||||
ASSERT(0 <= value && value <= 16);
|
||||
if (value < 10) return static_cast<char>(value + '0');
|
||||
return static_cast<char>(value - 10 + 'A');
|
||||
}
|
||||
|
||||
|
||||
bool Bignum::ToHexString(char* buffer, int buffer_size) const {
|
||||
ASSERT(IsClamped());
|
||||
// Each bigit must be printable as separate hex-character.
|
||||
ASSERT(kBigitSize % 4 == 0);
|
||||
const int kHexCharsPerBigit = kBigitSize / 4;
|
||||
|
||||
if (used_digits_ == 0) {
|
||||
if (buffer_size < 2) return false;
|
||||
buffer[0] = '0';
|
||||
buffer[1] = '\0';
|
||||
return true;
|
||||
}
|
||||
// We add 1 for the terminating '\0' character.
|
||||
int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
|
||||
SizeInHexChars(bigits_[used_digits_ - 1]) + 1;
|
||||
if (needed_chars > buffer_size) return false;
|
||||
int string_index = needed_chars - 1;
|
||||
buffer[string_index--] = '\0';
|
||||
for (int i = 0; i < exponent_; ++i) {
|
||||
for (int j = 0; j < kHexCharsPerBigit; ++j) {
|
||||
buffer[string_index--] = '0';
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < used_digits_ - 1; ++i) {
|
||||
Chunk current_bigit = bigits_[i];
|
||||
for (int j = 0; j < kHexCharsPerBigit; ++j) {
|
||||
buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
|
||||
current_bigit >>= 4;
|
||||
}
|
||||
}
|
||||
// And finally the last bigit.
|
||||
Chunk most_significant_bigit = bigits_[used_digits_ - 1];
|
||||
while (most_significant_bigit != 0) {
|
||||
buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
|
||||
most_significant_bigit >>= 4;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
Bignum::Chunk Bignum::BigitAt(int index) const {
|
||||
if (index >= BigitLength()) return 0;
|
||||
if (index < exponent_) return 0;
|
||||
return bigits_[index - exponent_];
|
||||
}
|
||||
|
||||
|
||||
int Bignum::Compare(const Bignum& a, const Bignum& b) {
|
||||
ASSERT(a.IsClamped());
|
||||
ASSERT(b.IsClamped());
|
||||
int bigit_length_a = a.BigitLength();
|
||||
int bigit_length_b = b.BigitLength();
|
||||
if (bigit_length_a < bigit_length_b) return -1;
|
||||
if (bigit_length_a > bigit_length_b) return +1;
|
||||
for (int i = bigit_length_a - 1; i >= Min(a.exponent_, b.exponent_); --i) {
|
||||
Chunk bigit_a = a.BigitAt(i);
|
||||
Chunk bigit_b = b.BigitAt(i);
|
||||
if (bigit_a < bigit_b) return -1;
|
||||
if (bigit_a > bigit_b) return +1;
|
||||
// Otherwise they are equal up to this digit. Try the next digit.
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
|
||||
ASSERT(a.IsClamped());
|
||||
ASSERT(b.IsClamped());
|
||||
ASSERT(c.IsClamped());
|
||||
if (a.BigitLength() < b.BigitLength()) {
|
||||
return PlusCompare(b, a, c);
|
||||
}
|
||||
if (a.BigitLength() + 1 < c.BigitLength()) return -1;
|
||||
if (a.BigitLength() > c.BigitLength()) return +1;
|
||||
// The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
|
||||
// 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
|
||||
// of 'a'.
|
||||
if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength()) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
Chunk borrow = 0;
|
||||
// Starting at min_exponent all digits are == 0. So no need to compare them.
|
||||
int min_exponent = Min(Min(a.exponent_, b.exponent_), c.exponent_);
|
||||
for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
|
||||
Chunk chunk_a = a.BigitAt(i);
|
||||
Chunk chunk_b = b.BigitAt(i);
|
||||
Chunk chunk_c = c.BigitAt(i);
|
||||
Chunk sum = chunk_a + chunk_b;
|
||||
if (sum > chunk_c + borrow) {
|
||||
return +1;
|
||||
} else {
|
||||
borrow = chunk_c + borrow - sum;
|
||||
if (borrow > 1) return -1;
|
||||
borrow <<= kBigitSize;
|
||||
}
|
||||
}
|
||||
if (borrow == 0) return 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
void Bignum::Clamp() {
|
||||
while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) {
|
||||
used_digits_--;
|
||||
}
|
||||
if (used_digits_ == 0) {
|
||||
// Zero.
|
||||
exponent_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool Bignum::IsClamped() const {
|
||||
return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
|
||||
}
|
||||
|
||||
|
||||
void Bignum::Zero() {
|
||||
for (int i = 0; i < used_digits_; ++i) {
|
||||
bigits_[i] = 0;
|
||||
}
|
||||
used_digits_ = 0;
|
||||
exponent_ = 0;
|
||||
}
|
||||
|
||||
|
||||
void Bignum::Align(const Bignum& other) {
|
||||
if (exponent_ > other.exponent_) {
|
||||
// If "X" represents a "hidden" digit (by the exponent) then we are in the
|
||||
// following case (a == this, b == other):
|
||||
// a: aaaaaaXXXX or a: aaaaaXXX
|
||||
// b: bbbbbbX b: bbbbbbbbXX
|
||||
// We replace some of the hidden digits (X) of a with 0 digits.
|
||||
// a: aaaaaa000X or a: aaaaa0XX
|
||||
int zero_digits = exponent_ - other.exponent_;
|
||||
EnsureCapacity(used_digits_ + zero_digits);
|
||||
for (int i = used_digits_ - 1; i >= 0; --i) {
|
||||
bigits_[i + zero_digits] = bigits_[i];
|
||||
}
|
||||
for (int i = 0; i < zero_digits; ++i) {
|
||||
bigits_[i] = 0;
|
||||
}
|
||||
used_digits_ += zero_digits;
|
||||
exponent_ -= zero_digits;
|
||||
ASSERT(used_digits_ >= 0);
|
||||
ASSERT(exponent_ >= 0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Bignum::BigitsShiftLeft(int shift_amount) {
|
||||
ASSERT(shift_amount < kBigitSize);
|
||||
ASSERT(shift_amount >= 0);
|
||||
Chunk carry = 0;
|
||||
for (int i = 0; i < used_digits_; ++i) {
|
||||
Chunk new_carry = bigits_[i] >> (kBigitSize - shift_amount);
|
||||
bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
|
||||
carry = new_carry;
|
||||
}
|
||||
if (carry != 0) {
|
||||
bigits_[used_digits_] = carry;
|
||||
used_digits_++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Bignum::SubtractTimes(const Bignum& other, int factor) {
|
||||
ASSERT(exponent_ <= other.exponent_);
|
||||
if (factor < 3) {
|
||||
for (int i = 0; i < factor; ++i) {
|
||||
SubtractBignum(other);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Chunk borrow = 0;
|
||||
int exponent_diff = other.exponent_ - exponent_;
|
||||
for (int i = 0; i < other.used_digits_; ++i) {
|
||||
DoubleChunk product = static_cast<DoubleChunk>(factor) * other.bigits_[i];
|
||||
DoubleChunk remove = borrow + product;
|
||||
Chunk difference = bigits_[i + exponent_diff] - (remove & kBigitMask);
|
||||
bigits_[i + exponent_diff] = difference & kBigitMask;
|
||||
borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
|
||||
(remove >> kBigitSize));
|
||||
}
|
||||
for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i) {
|
||||
if (borrow == 0) return;
|
||||
Chunk difference = bigits_[i] - borrow;
|
||||
bigits_[i] = difference & kBigitMask;
|
||||
borrow = difference >> (kChunkSize - 1);
|
||||
}
|
||||
Clamp();
|
||||
}
|
||||
|
||||
|
||||
} // namespace double_conversion
|
|
@ -1,145 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#ifndef DOUBLE_CONVERSION_BIGNUM_H_
|
||||
#define DOUBLE_CONVERSION_BIGNUM_H_
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
class Bignum {
|
||||
public:
|
||||
// 3584 = 128 * 28. We can represent 2^3584 > 10^1000 accurately.
|
||||
// This bignum can encode much bigger numbers, since it contains an
|
||||
// exponent.
|
||||
static const int kMaxSignificantBits = 3584;
|
||||
|
||||
Bignum();
|
||||
void AssignUInt16(uint16_t value);
|
||||
void AssignUInt64(uint64_t value);
|
||||
void AssignBignum(const Bignum& other);
|
||||
|
||||
void AssignDecimalString(Vector<const char> value);
|
||||
void AssignHexString(Vector<const char> value);
|
||||
|
||||
void AssignPowerUInt16(uint16_t base, int exponent);
|
||||
|
||||
void AddUInt16(uint16_t operand);
|
||||
void AddUInt64(uint64_t operand);
|
||||
void AddBignum(const Bignum& other);
|
||||
// Precondition: this >= other.
|
||||
void SubtractBignum(const Bignum& other);
|
||||
|
||||
void Square();
|
||||
void ShiftLeft(int shift_amount);
|
||||
void MultiplyByUInt32(uint32_t factor);
|
||||
void MultiplyByUInt64(uint64_t factor);
|
||||
void MultiplyByPowerOfTen(int exponent);
|
||||
void Times10() { return MultiplyByUInt32(10); }
|
||||
// Pseudocode:
|
||||
// int result = this / other;
|
||||
// this = this % other;
|
||||
// In the worst case this function is in O(this/other).
|
||||
uint16_t DivideModuloIntBignum(const Bignum& other);
|
||||
|
||||
bool ToHexString(char* buffer, int buffer_size) const;
|
||||
|
||||
// Returns
|
||||
// -1 if a < b,
|
||||
// 0 if a == b, and
|
||||
// +1 if a > b.
|
||||
static int Compare(const Bignum& a, const Bignum& b);
|
||||
static bool Equal(const Bignum& a, const Bignum& b) {
|
||||
return Compare(a, b) == 0;
|
||||
}
|
||||
static bool LessEqual(const Bignum& a, const Bignum& b) {
|
||||
return Compare(a, b) <= 0;
|
||||
}
|
||||
static bool Less(const Bignum& a, const Bignum& b) {
|
||||
return Compare(a, b) < 0;
|
||||
}
|
||||
// Returns Compare(a + b, c);
|
||||
static int PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c);
|
||||
// Returns a + b == c
|
||||
static bool PlusEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
|
||||
return PlusCompare(a, b, c) == 0;
|
||||
}
|
||||
// Returns a + b <= c
|
||||
static bool PlusLessEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
|
||||
return PlusCompare(a, b, c) <= 0;
|
||||
}
|
||||
// Returns a + b < c
|
||||
static bool PlusLess(const Bignum& a, const Bignum& b, const Bignum& c) {
|
||||
return PlusCompare(a, b, c) < 0;
|
||||
}
|
||||
private:
|
||||
typedef uint32_t Chunk;
|
||||
typedef uint64_t DoubleChunk;
|
||||
|
||||
static const int kChunkSize = sizeof(Chunk) * 8;
|
||||
static const int kDoubleChunkSize = sizeof(DoubleChunk) * 8;
|
||||
// With bigit size of 28 we loose some bits, but a double still fits easily
|
||||
// into two chunks, and more importantly we can use the Comba multiplication.
|
||||
static const int kBigitSize = 28;
|
||||
static const Chunk kBigitMask = (1 << kBigitSize) - 1;
|
||||
// Every instance allocates kBigitLength chunks on the stack. Bignums cannot
|
||||
// grow. There are no checks if the stack-allocated space is sufficient.
|
||||
static const int kBigitCapacity = kMaxSignificantBits / kBigitSize;
|
||||
|
||||
void EnsureCapacity(int size) {
|
||||
if (size > kBigitCapacity) {
|
||||
UNREACHABLE();
|
||||
}
|
||||
}
|
||||
void Align(const Bignum& other);
|
||||
void Clamp();
|
||||
bool IsClamped() const;
|
||||
void Zero();
|
||||
// Requires this to have enough capacity (no tests done).
|
||||
// Updates used_digits_ if necessary.
|
||||
// shift_amount must be < kBigitSize.
|
||||
void BigitsShiftLeft(int shift_amount);
|
||||
// BigitLength includes the "hidden" digits encoded in the exponent.
|
||||
int BigitLength() const { return used_digits_ + exponent_; }
|
||||
Chunk BigitAt(int index) const;
|
||||
void SubtractTimes(const Bignum& other, int factor);
|
||||
|
||||
Chunk bigits_buffer_[kBigitCapacity];
|
||||
// A vector backed by bigits_buffer_. This way accesses to the array are
|
||||
// checked for out-of-bounds errors.
|
||||
Vector<Chunk> bigits_;
|
||||
int used_digits_;
|
||||
// The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize).
|
||||
int exponent_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(Bignum);
|
||||
};
|
||||
|
||||
} // namespace double_conversion
|
||||
|
||||
#endif // DOUBLE_CONVERSION_BIGNUM_H_
|
|
@ -1,176 +0,0 @@
|
|||
// Copyright 2006-2008 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#include <stdarg.h>
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
#include "cached-powers.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
struct CachedPower {
|
||||
uint64_t significand;
|
||||
int16_t binary_exponent;
|
||||
int16_t decimal_exponent;
|
||||
};
|
||||
|
||||
static const CachedPower kCachedPowers[] = {
|
||||
{UINT64_2PART_C(0xfa8fd5a0, 081c0288), -1220, -348},
|
||||
{UINT64_2PART_C(0xbaaee17f, a23ebf76), -1193, -340},
|
||||
{UINT64_2PART_C(0x8b16fb20, 3055ac76), -1166, -332},
|
||||
{UINT64_2PART_C(0xcf42894a, 5dce35ea), -1140, -324},
|
||||
{UINT64_2PART_C(0x9a6bb0aa, 55653b2d), -1113, -316},
|
||||
{UINT64_2PART_C(0xe61acf03, 3d1a45df), -1087, -308},
|
||||
{UINT64_2PART_C(0xab70fe17, c79ac6ca), -1060, -300},
|
||||
{UINT64_2PART_C(0xff77b1fc, bebcdc4f), -1034, -292},
|
||||
{UINT64_2PART_C(0xbe5691ef, 416bd60c), -1007, -284},
|
||||
{UINT64_2PART_C(0x8dd01fad, 907ffc3c), -980, -276},
|
||||
{UINT64_2PART_C(0xd3515c28, 31559a83), -954, -268},
|
||||
{UINT64_2PART_C(0x9d71ac8f, ada6c9b5), -927, -260},
|
||||
{UINT64_2PART_C(0xea9c2277, 23ee8bcb), -901, -252},
|
||||
{UINT64_2PART_C(0xaecc4991, 4078536d), -874, -244},
|
||||
{UINT64_2PART_C(0x823c1279, 5db6ce57), -847, -236},
|
||||
{UINT64_2PART_C(0xc2109436, 4dfb5637), -821, -228},
|
||||
{UINT64_2PART_C(0x9096ea6f, 3848984f), -794, -220},
|
||||
{UINT64_2PART_C(0xd77485cb, 25823ac7), -768, -212},
|
||||
{UINT64_2PART_C(0xa086cfcd, 97bf97f4), -741, -204},
|
||||
{UINT64_2PART_C(0xef340a98, 172aace5), -715, -196},
|
||||
{UINT64_2PART_C(0xb23867fb, 2a35b28e), -688, -188},
|
||||
{UINT64_2PART_C(0x84c8d4df, d2c63f3b), -661, -180},
|
||||
{UINT64_2PART_C(0xc5dd4427, 1ad3cdba), -635, -172},
|
||||
{UINT64_2PART_C(0x936b9fce, bb25c996), -608, -164},
|
||||
{UINT64_2PART_C(0xdbac6c24, 7d62a584), -582, -156},
|
||||
{UINT64_2PART_C(0xa3ab6658, 0d5fdaf6), -555, -148},
|
||||
{UINT64_2PART_C(0xf3e2f893, dec3f126), -529, -140},
|
||||
{UINT64_2PART_C(0xb5b5ada8, aaff80b8), -502, -132},
|
||||
{UINT64_2PART_C(0x87625f05, 6c7c4a8b), -475, -124},
|
||||
{UINT64_2PART_C(0xc9bcff60, 34c13053), -449, -116},
|
||||
{UINT64_2PART_C(0x964e858c, 91ba2655), -422, -108},
|
||||
{UINT64_2PART_C(0xdff97724, 70297ebd), -396, -100},
|
||||
{UINT64_2PART_C(0xa6dfbd9f, b8e5b88f), -369, -92},
|
||||
{UINT64_2PART_C(0xf8a95fcf, 88747d94), -343, -84},
|
||||
{UINT64_2PART_C(0xb9447093, 8fa89bcf), -316, -76},
|
||||
{UINT64_2PART_C(0x8a08f0f8, bf0f156b), -289, -68},
|
||||
{UINT64_2PART_C(0xcdb02555, 653131b6), -263, -60},
|
||||
{UINT64_2PART_C(0x993fe2c6, d07b7fac), -236, -52},
|
||||
{UINT64_2PART_C(0xe45c10c4, 2a2b3b06), -210, -44},
|
||||
{UINT64_2PART_C(0xaa242499, 697392d3), -183, -36},
|
||||
{UINT64_2PART_C(0xfd87b5f2, 8300ca0e), -157, -28},
|
||||
{UINT64_2PART_C(0xbce50864, 92111aeb), -130, -20},
|
||||
{UINT64_2PART_C(0x8cbccc09, 6f5088cc), -103, -12},
|
||||
{UINT64_2PART_C(0xd1b71758, e219652c), -77, -4},
|
||||
{UINT64_2PART_C(0x9c400000, 00000000), -50, 4},
|
||||
{UINT64_2PART_C(0xe8d4a510, 00000000), -24, 12},
|
||||
{UINT64_2PART_C(0xad78ebc5, ac620000), 3, 20},
|
||||
{UINT64_2PART_C(0x813f3978, f8940984), 30, 28},
|
||||
{UINT64_2PART_C(0xc097ce7b, c90715b3), 56, 36},
|
||||
{UINT64_2PART_C(0x8f7e32ce, 7bea5c70), 83, 44},
|
||||
{UINT64_2PART_C(0xd5d238a4, abe98068), 109, 52},
|
||||
{UINT64_2PART_C(0x9f4f2726, 179a2245), 136, 60},
|
||||
{UINT64_2PART_C(0xed63a231, d4c4fb27), 162, 68},
|
||||
{UINT64_2PART_C(0xb0de6538, 8cc8ada8), 189, 76},
|
||||
{UINT64_2PART_C(0x83c7088e, 1aab65db), 216, 84},
|
||||
{UINT64_2PART_C(0xc45d1df9, 42711d9a), 242, 92},
|
||||
{UINT64_2PART_C(0x924d692c, a61be758), 269, 100},
|
||||
{UINT64_2PART_C(0xda01ee64, 1a708dea), 295, 108},
|
||||
{UINT64_2PART_C(0xa26da399, 9aef774a), 322, 116},
|
||||
{UINT64_2PART_C(0xf209787b, b47d6b85), 348, 124},
|
||||
{UINT64_2PART_C(0xb454e4a1, 79dd1877), 375, 132},
|
||||
{UINT64_2PART_C(0x865b8692, 5b9bc5c2), 402, 140},
|
||||
{UINT64_2PART_C(0xc83553c5, c8965d3d), 428, 148},
|
||||
{UINT64_2PART_C(0x952ab45c, fa97a0b3), 455, 156},
|
||||
{UINT64_2PART_C(0xde469fbd, 99a05fe3), 481, 164},
|
||||
{UINT64_2PART_C(0xa59bc234, db398c25), 508, 172},
|
||||
{UINT64_2PART_C(0xf6c69a72, a3989f5c), 534, 180},
|
||||
{UINT64_2PART_C(0xb7dcbf53, 54e9bece), 561, 188},
|
||||
{UINT64_2PART_C(0x88fcf317, f22241e2), 588, 196},
|
||||
{UINT64_2PART_C(0xcc20ce9b, d35c78a5), 614, 204},
|
||||
{UINT64_2PART_C(0x98165af3, 7b2153df), 641, 212},
|
||||
{UINT64_2PART_C(0xe2a0b5dc, 971f303a), 667, 220},
|
||||
{UINT64_2PART_C(0xa8d9d153, 5ce3b396), 694, 228},
|
||||
{UINT64_2PART_C(0xfb9b7cd9, a4a7443c), 720, 236},
|
||||
{UINT64_2PART_C(0xbb764c4c, a7a44410), 747, 244},
|
||||
{UINT64_2PART_C(0x8bab8eef, b6409c1a), 774, 252},
|
||||
{UINT64_2PART_C(0xd01fef10, a657842c), 800, 260},
|
||||
{UINT64_2PART_C(0x9b10a4e5, e9913129), 827, 268},
|
||||
{UINT64_2PART_C(0xe7109bfb, a19c0c9d), 853, 276},
|
||||
{UINT64_2PART_C(0xac2820d9, 623bf429), 880, 284},
|
||||
{UINT64_2PART_C(0x80444b5e, 7aa7cf85), 907, 292},
|
||||
{UINT64_2PART_C(0xbf21e440, 03acdd2d), 933, 300},
|
||||
{UINT64_2PART_C(0x8e679c2f, 5e44ff8f), 960, 308},
|
||||
{UINT64_2PART_C(0xd433179d, 9c8cb841), 986, 316},
|
||||
{UINT64_2PART_C(0x9e19db92, b4e31ba9), 1013, 324},
|
||||
{UINT64_2PART_C(0xeb96bf6e, badf77d9), 1039, 332},
|
||||
{UINT64_2PART_C(0xaf87023b, 9bf0ee6b), 1066, 340},
|
||||
};
|
||||
|
||||
static const int kCachedPowersLength = ARRAY_SIZE(kCachedPowers);
|
||||
static const int kCachedPowersOffset = 348; // -1 * the first decimal_exponent.
|
||||
static const double kD_1_LOG2_10 = 0.30102999566398114; // 1 / lg(10)
|
||||
// Difference between the decimal exponents in the table above.
|
||||
const int PowersOfTenCache::kDecimalExponentDistance = 8;
|
||||
const int PowersOfTenCache::kMinDecimalExponent = -348;
|
||||
const int PowersOfTenCache::kMaxDecimalExponent = 340;
|
||||
|
||||
void PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
|
||||
int min_exponent,
|
||||
int max_exponent,
|
||||
DiyFp* power,
|
||||
int* decimal_exponent) {
|
||||
int kQ = DiyFp::kSignificandSize;
|
||||
double k = ceil((min_exponent + kQ - 1) * kD_1_LOG2_10);
|
||||
int foo = kCachedPowersOffset;
|
||||
int index =
|
||||
(foo + static_cast<int>(k) - 1) / kDecimalExponentDistance + 1;
|
||||
ASSERT(0 <= index && index < kCachedPowersLength);
|
||||
CachedPower cached_power = kCachedPowers[index];
|
||||
ASSERT(min_exponent <= cached_power.binary_exponent);
|
||||
(void) max_exponent; // Mark variable as used.
|
||||
ASSERT(cached_power.binary_exponent <= max_exponent);
|
||||
*decimal_exponent = cached_power.decimal_exponent;
|
||||
*power = DiyFp(cached_power.significand, cached_power.binary_exponent);
|
||||
}
|
||||
|
||||
|
||||
void PowersOfTenCache::GetCachedPowerForDecimalExponent(int requested_exponent,
|
||||
DiyFp* power,
|
||||
int* found_exponent) {
|
||||
ASSERT(kMinDecimalExponent <= requested_exponent);
|
||||
ASSERT(requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance);
|
||||
int index =
|
||||
(requested_exponent + kCachedPowersOffset) / kDecimalExponentDistance;
|
||||
CachedPower cached_power = kCachedPowers[index];
|
||||
*power = DiyFp(cached_power.significand, cached_power.binary_exponent);
|
||||
*found_exponent = cached_power.decimal_exponent;
|
||||
ASSERT(*found_exponent <= requested_exponent);
|
||||
ASSERT(requested_exponent < *found_exponent + kDecimalExponentDistance);
|
||||
}
|
||||
|
||||
} // namespace double_conversion
|
|
@ -1,64 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#ifndef DOUBLE_CONVERSION_CACHED_POWERS_H_
|
||||
#define DOUBLE_CONVERSION_CACHED_POWERS_H_
|
||||
|
||||
#include "diy-fp.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
class PowersOfTenCache {
|
||||
public:
|
||||
|
||||
// Not all powers of ten are cached. The decimal exponent of two neighboring
|
||||
// cached numbers will differ by kDecimalExponentDistance.
|
||||
static const int kDecimalExponentDistance;
|
||||
|
||||
static const int kMinDecimalExponent;
|
||||
static const int kMaxDecimalExponent;
|
||||
|
||||
// Returns a cached power-of-ten with a binary exponent in the range
|
||||
// [min_exponent; max_exponent] (boundaries included).
|
||||
static void GetCachedPowerForBinaryExponentRange(int min_exponent,
|
||||
int max_exponent,
|
||||
DiyFp* power,
|
||||
int* decimal_exponent);
|
||||
|
||||
// Returns a cached power of ten x ~= 10^k such that
|
||||
// k <= decimal_exponent < k + kCachedPowersDecimalDistance.
|
||||
// The given decimal_exponent must satisfy
|
||||
// kMinDecimalExponent <= requested_exponent, and
|
||||
// requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance.
|
||||
static void GetCachedPowerForDecimalExponent(int requested_exponent,
|
||||
DiyFp* power,
|
||||
int* found_exponent);
|
||||
};
|
||||
|
||||
} // namespace double_conversion
|
||||
|
||||
#endif // DOUBLE_CONVERSION_CACHED_POWERS_H_
|
|
@ -1,57 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
#include "diy-fp.h"
|
||||
#include "utils.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
void DiyFp::Multiply(const DiyFp& other) {
|
||||
// Simply "emulates" a 128 bit multiplication.
|
||||
// However: the resulting number only contains 64 bits. The least
|
||||
// significant 64 bits are only used for rounding the most significant 64
|
||||
// bits.
|
||||
const uint64_t kM32 = 0xFFFFFFFFU;
|
||||
uint64_t a = f_ >> 32;
|
||||
uint64_t b = f_ & kM32;
|
||||
uint64_t c = other.f_ >> 32;
|
||||
uint64_t d = other.f_ & kM32;
|
||||
uint64_t ac = a * c;
|
||||
uint64_t bc = b * c;
|
||||
uint64_t ad = a * d;
|
||||
uint64_t bd = b * d;
|
||||
uint64_t tmp = (bd >> 32) + (ad & kM32) + (bc & kM32);
|
||||
// By adding 1U << 31 to tmp we round the final result.
|
||||
// Halfway cases will be round up.
|
||||
tmp += 1U << 31;
|
||||
uint64_t result_f = ac + (ad >> 32) + (bc >> 32) + (tmp >> 32);
|
||||
e_ += other.e_ + 64;
|
||||
f_ = result_f;
|
||||
}
|
||||
|
||||
} // namespace double_conversion
|
|
@ -1,118 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#ifndef DOUBLE_CONVERSION_DIY_FP_H_
|
||||
#define DOUBLE_CONVERSION_DIY_FP_H_
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
// This "Do It Yourself Floating Point" class implements a floating-point number
|
||||
// with a uint64 significand and an int exponent. Normalized DiyFp numbers will
|
||||
// have the most significant bit of the significand set.
|
||||
// Multiplication and Subtraction do not normalize their results.
|
||||
// DiyFp are not designed to contain special doubles (NaN and Infinity).
|
||||
class DiyFp {
|
||||
public:
|
||||
static const int kSignificandSize = 64;
|
||||
|
||||
DiyFp() : f_(0), e_(0) {}
|
||||
DiyFp(uint64_t f, int e) : f_(f), e_(e) {}
|
||||
|
||||
// this = this - other.
|
||||
// The exponents of both numbers must be the same and the significand of this
|
||||
// must be bigger than the significand of other.
|
||||
// The result will not be normalized.
|
||||
void Subtract(const DiyFp& other) {
|
||||
ASSERT(e_ == other.e_);
|
||||
ASSERT(f_ >= other.f_);
|
||||
f_ -= other.f_;
|
||||
}
|
||||
|
||||
// Returns a - b.
|
||||
// The exponents of both numbers must be the same and this must be bigger
|
||||
// than other. The result will not be normalized.
|
||||
static DiyFp Minus(const DiyFp& a, const DiyFp& b) {
|
||||
DiyFp result = a;
|
||||
result.Subtract(b);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// this = this * other.
|
||||
void Multiply(const DiyFp& other);
|
||||
|
||||
// returns a * b;
|
||||
static DiyFp Times(const DiyFp& a, const DiyFp& b) {
|
||||
DiyFp result = a;
|
||||
result.Multiply(b);
|
||||
return result;
|
||||
}
|
||||
|
||||
void Normalize() {
|
||||
ASSERT(f_ != 0);
|
||||
uint64_t f = f_;
|
||||
int e = e_;
|
||||
|
||||
// This method is mainly called for normalizing boundaries. In general
|
||||
// boundaries need to be shifted by 10 bits. We thus optimize for this case.
|
||||
const uint64_t k10MSBits = UINT64_2PART_C(0xFFC00000, 00000000);
|
||||
while ((f & k10MSBits) == 0) {
|
||||
f <<= 10;
|
||||
e -= 10;
|
||||
}
|
||||
while ((f & kUint64MSB) == 0) {
|
||||
f <<= 1;
|
||||
e--;
|
||||
}
|
||||
f_ = f;
|
||||
e_ = e;
|
||||
}
|
||||
|
||||
static DiyFp Normalize(const DiyFp& a) {
|
||||
DiyFp result = a;
|
||||
result.Normalize();
|
||||
return result;
|
||||
}
|
||||
|
||||
uint64_t f() const { return f_; }
|
||||
int e() const { return e_; }
|
||||
|
||||
void set_f(uint64_t new_value) { f_ = new_value; }
|
||||
void set_e(int new_value) { e_ = new_value; }
|
||||
|
||||
private:
|
||||
static const uint64_t kUint64MSB = UINT64_2PART_C(0x80000000, 00000000);
|
||||
|
||||
uint64_t f_;
|
||||
int e_;
|
||||
};
|
||||
|
||||
} // namespace double_conversion
|
||||
|
||||
#endif // DOUBLE_CONVERSION_DIY_FP_H_
|
|
@ -1,910 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "double-conversion.h"
|
||||
|
||||
#include "bignum-dtoa.h"
|
||||
#include "fast-dtoa.h"
|
||||
#include "fixed-dtoa.h"
|
||||
#include "ieee.h"
|
||||
#include "strtod.h"
|
||||
#include "utils.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() {
|
||||
int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
|
||||
static DoubleToStringConverter converter(flags,
|
||||
"Infinity",
|
||||
"NaN",
|
||||
'e',
|
||||
-6, 21,
|
||||
6, 0);
|
||||
return converter;
|
||||
}
|
||||
|
||||
|
||||
bool DoubleToStringConverter::HandleSpecialValues(
|
||||
double value,
|
||||
StringBuilder* result_builder) const {
|
||||
Double double_inspect(value);
|
||||
if (double_inspect.IsInfinite()) {
|
||||
if (infinity_symbol_ == NULL) return false;
|
||||
if (value < 0) {
|
||||
result_builder->AddCharacter('-');
|
||||
}
|
||||
result_builder->AddString(infinity_symbol_);
|
||||
return true;
|
||||
}
|
||||
if (double_inspect.IsNan()) {
|
||||
if (nan_symbol_ == NULL) return false;
|
||||
result_builder->AddString(nan_symbol_);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
void DoubleToStringConverter::CreateExponentialRepresentation(
|
||||
const char* decimal_digits,
|
||||
int length,
|
||||
int exponent,
|
||||
StringBuilder* result_builder) const {
|
||||
ASSERT(length != 0);
|
||||
result_builder->AddCharacter(decimal_digits[0]);
|
||||
if (length != 1) {
|
||||
result_builder->AddCharacter('.');
|
||||
result_builder->AddSubstring(&decimal_digits[1], length-1);
|
||||
}
|
||||
result_builder->AddCharacter(exponent_character_);
|
||||
if (exponent < 0) {
|
||||
result_builder->AddCharacter('-');
|
||||
exponent = -exponent;
|
||||
} else {
|
||||
if ((flags_ & EMIT_POSITIVE_EXPONENT_SIGN) != 0) {
|
||||
result_builder->AddCharacter('+');
|
||||
}
|
||||
}
|
||||
if (exponent == 0) {
|
||||
result_builder->AddCharacter('0');
|
||||
return;
|
||||
}
|
||||
ASSERT(exponent < 1e4);
|
||||
const int kMaxExponentLength = 5;
|
||||
char buffer[kMaxExponentLength + 1];
|
||||
buffer[kMaxExponentLength] = '\0';
|
||||
int first_char_pos = kMaxExponentLength;
|
||||
while (exponent > 0) {
|
||||
buffer[--first_char_pos] = '0' + (exponent % 10);
|
||||
exponent /= 10;
|
||||
}
|
||||
result_builder->AddSubstring(&buffer[first_char_pos],
|
||||
kMaxExponentLength - first_char_pos);
|
||||
}
|
||||
|
||||
|
||||
void DoubleToStringConverter::CreateDecimalRepresentation(
|
||||
const char* decimal_digits,
|
||||
int length,
|
||||
int decimal_point,
|
||||
int digits_after_point,
|
||||
StringBuilder* result_builder) const {
|
||||
// Create a representation that is padded with zeros if needed.
|
||||
if (decimal_point <= 0) {
|
||||
// "0.00000decimal_rep".
|
||||
result_builder->AddCharacter('0');
|
||||
if (digits_after_point > 0) {
|
||||
result_builder->AddCharacter('.');
|
||||
result_builder->AddPadding('0', -decimal_point);
|
||||
ASSERT(length <= digits_after_point - (-decimal_point));
|
||||
result_builder->AddSubstring(decimal_digits, length);
|
||||
int remaining_digits = digits_after_point - (-decimal_point) - length;
|
||||
result_builder->AddPadding('0', remaining_digits);
|
||||
}
|
||||
} else if (decimal_point >= length) {
|
||||
// "decimal_rep0000.00000" or "decimal_rep.0000"
|
||||
result_builder->AddSubstring(decimal_digits, length);
|
||||
result_builder->AddPadding('0', decimal_point - length);
|
||||
if (digits_after_point > 0) {
|
||||
result_builder->AddCharacter('.');
|
||||
result_builder->AddPadding('0', digits_after_point);
|
||||
}
|
||||
} else {
|
||||
// "decima.l_rep000"
|
||||
ASSERT(digits_after_point > 0);
|
||||
result_builder->AddSubstring(decimal_digits, decimal_point);
|
||||
result_builder->AddCharacter('.');
|
||||
ASSERT(length - decimal_point <= digits_after_point);
|
||||
result_builder->AddSubstring(&decimal_digits[decimal_point],
|
||||
length - decimal_point);
|
||||
int remaining_digits = digits_after_point - (length - decimal_point);
|
||||
result_builder->AddPadding('0', remaining_digits);
|
||||
}
|
||||
if (digits_after_point == 0) {
|
||||
if ((flags_ & EMIT_TRAILING_DECIMAL_POINT) != 0) {
|
||||
result_builder->AddCharacter('.');
|
||||
}
|
||||
if ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) {
|
||||
result_builder->AddCharacter('0');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool DoubleToStringConverter::ToShortestIeeeNumber(
|
||||
double value,
|
||||
StringBuilder* result_builder,
|
||||
DoubleToStringConverter::DtoaMode mode) const {
|
||||
ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE);
|
||||
if (Double(value).IsSpecial()) {
|
||||
return HandleSpecialValues(value, result_builder);
|
||||
}
|
||||
|
||||
int decimal_point;
|
||||
bool sign;
|
||||
const int kDecimalRepCapacity = kBase10MaximalLength + 1;
|
||||
char decimal_rep[kDecimalRepCapacity];
|
||||
int decimal_rep_length;
|
||||
|
||||
DoubleToAscii(value, mode, 0, decimal_rep, kDecimalRepCapacity,
|
||||
&sign, &decimal_rep_length, &decimal_point);
|
||||
|
||||
bool unique_zero = (flags_ & UNIQUE_ZERO) != 0;
|
||||
if (sign && (value != 0.0 || !unique_zero)) {
|
||||
result_builder->AddCharacter('-');
|
||||
}
|
||||
|
||||
int exponent = decimal_point - 1;
|
||||
if ((decimal_in_shortest_low_ <= exponent) &&
|
||||
(exponent < decimal_in_shortest_high_)) {
|
||||
CreateDecimalRepresentation(decimal_rep, decimal_rep_length,
|
||||
decimal_point,
|
||||
Max(0, decimal_rep_length - decimal_point),
|
||||
result_builder);
|
||||
} else {
|
||||
CreateExponentialRepresentation(decimal_rep, decimal_rep_length, exponent,
|
||||
result_builder);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool DoubleToStringConverter::ToFixed(double value,
|
||||
int requested_digits,
|
||||
StringBuilder* result_builder) const {
|
||||
ASSERT(kMaxFixedDigitsBeforePoint == 60);
|
||||
const double kFirstNonFixed = 1e60;
|
||||
|
||||
if (Double(value).IsSpecial()) {
|
||||
return HandleSpecialValues(value, result_builder);
|
||||
}
|
||||
|
||||
if (requested_digits > kMaxFixedDigitsAfterPoint) return false;
|
||||
if (value >= kFirstNonFixed || value <= -kFirstNonFixed) return false;
|
||||
|
||||
// Find a sufficiently precise decimal representation of n.
|
||||
int decimal_point;
|
||||
bool sign;
|
||||
// Add space for the '\0' byte.
|
||||
const int kDecimalRepCapacity =
|
||||
kMaxFixedDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
|
||||
char decimal_rep[kDecimalRepCapacity];
|
||||
int decimal_rep_length;
|
||||
DoubleToAscii(value, FIXED, requested_digits,
|
||||
decimal_rep, kDecimalRepCapacity,
|
||||
&sign, &decimal_rep_length, &decimal_point);
|
||||
|
||||
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
||||
if (sign && (value != 0.0 || !unique_zero)) {
|
||||
result_builder->AddCharacter('-');
|
||||
}
|
||||
|
||||
CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
|
||||
requested_digits, result_builder);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool DoubleToStringConverter::ToExponential(
|
||||
double value,
|
||||
int requested_digits,
|
||||
StringBuilder* result_builder) const {
|
||||
if (Double(value).IsSpecial()) {
|
||||
return HandleSpecialValues(value, result_builder);
|
||||
}
|
||||
|
||||
if (requested_digits < -1) return false;
|
||||
if (requested_digits > kMaxExponentialDigits) return false;
|
||||
|
||||
int decimal_point;
|
||||
bool sign;
|
||||
// Add space for digit before the decimal point and the '\0' character.
|
||||
const int kDecimalRepCapacity = kMaxExponentialDigits + 2;
|
||||
ASSERT(kDecimalRepCapacity > kBase10MaximalLength);
|
||||
char decimal_rep[kDecimalRepCapacity];
|
||||
int decimal_rep_length;
|
||||
|
||||
if (requested_digits == -1) {
|
||||
DoubleToAscii(value, SHORTEST, 0,
|
||||
decimal_rep, kDecimalRepCapacity,
|
||||
&sign, &decimal_rep_length, &decimal_point);
|
||||
} else {
|
||||
DoubleToAscii(value, PRECISION, requested_digits + 1,
|
||||
decimal_rep, kDecimalRepCapacity,
|
||||
&sign, &decimal_rep_length, &decimal_point);
|
||||
ASSERT(decimal_rep_length <= requested_digits + 1);
|
||||
|
||||
for (int i = decimal_rep_length; i < requested_digits + 1; ++i) {
|
||||
decimal_rep[i] = '0';
|
||||
}
|
||||
decimal_rep_length = requested_digits + 1;
|
||||
}
|
||||
|
||||
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
||||
if (sign && (value != 0.0 || !unique_zero)) {
|
||||
result_builder->AddCharacter('-');
|
||||
}
|
||||
|
||||
int exponent = decimal_point - 1;
|
||||
CreateExponentialRepresentation(decimal_rep,
|
||||
decimal_rep_length,
|
||||
exponent,
|
||||
result_builder);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool DoubleToStringConverter::ToPrecision(double value,
|
||||
int precision,
|
||||
StringBuilder* result_builder) const {
|
||||
if (Double(value).IsSpecial()) {
|
||||
return HandleSpecialValues(value, result_builder);
|
||||
}
|
||||
|
||||
if (precision < kMinPrecisionDigits || precision > kMaxPrecisionDigits) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Find a sufficiently precise decimal representation of n.
|
||||
int decimal_point;
|
||||
bool sign;
|
||||
// Add one for the terminating null character.
|
||||
const int kDecimalRepCapacity = kMaxPrecisionDigits + 1;
|
||||
char decimal_rep[kDecimalRepCapacity];
|
||||
int decimal_rep_length;
|
||||
|
||||
DoubleToAscii(value, PRECISION, precision,
|
||||
decimal_rep, kDecimalRepCapacity,
|
||||
&sign, &decimal_rep_length, &decimal_point);
|
||||
ASSERT(decimal_rep_length <= precision);
|
||||
|
||||
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
||||
if (sign && (value != 0.0 || !unique_zero)) {
|
||||
result_builder->AddCharacter('-');
|
||||
}
|
||||
|
||||
// The exponent if we print the number as x.xxeyyy. That is with the
|
||||
// decimal point after the first digit.
|
||||
int exponent = decimal_point - 1;
|
||||
|
||||
int extra_zero = ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) ? 1 : 0;
|
||||
if ((-decimal_point + 1 > max_leading_padding_zeroes_in_precision_mode_) ||
|
||||
(decimal_point - precision + extra_zero >
|
||||
max_trailing_padding_zeroes_in_precision_mode_)) {
|
||||
// Fill buffer to contain 'precision' digits.
|
||||
// Usually the buffer is already at the correct length, but 'DoubleToAscii'
|
||||
// is allowed to return less characters.
|
||||
for (int i = decimal_rep_length; i < precision; ++i) {
|
||||
decimal_rep[i] = '0';
|
||||
}
|
||||
|
||||
CreateExponentialRepresentation(decimal_rep,
|
||||
precision,
|
||||
exponent,
|
||||
result_builder);
|
||||
} else {
|
||||
CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
|
||||
Max(0, precision - decimal_point),
|
||||
result_builder);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
static BignumDtoaMode DtoaToBignumDtoaMode(
|
||||
DoubleToStringConverter::DtoaMode dtoa_mode) {
|
||||
switch (dtoa_mode) {
|
||||
case DoubleToStringConverter::SHORTEST: return BIGNUM_DTOA_SHORTEST;
|
||||
case DoubleToStringConverter::SHORTEST_SINGLE:
|
||||
return BIGNUM_DTOA_SHORTEST_SINGLE;
|
||||
case DoubleToStringConverter::FIXED: return BIGNUM_DTOA_FIXED;
|
||||
case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION;
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void DoubleToStringConverter::DoubleToAscii(double v,
|
||||
DtoaMode mode,
|
||||
int requested_digits,
|
||||
char* buffer,
|
||||
int buffer_length,
|
||||
bool* sign,
|
||||
int* length,
|
||||
int* point) {
|
||||
Vector<char> vector(buffer, buffer_length);
|
||||
ASSERT(!Double(v).IsSpecial());
|
||||
ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE || requested_digits >= 0);
|
||||
|
||||
if (Double(v).Sign() < 0) {
|
||||
*sign = true;
|
||||
v = -v;
|
||||
} else {
|
||||
*sign = false;
|
||||
}
|
||||
|
||||
if (mode == PRECISION && requested_digits == 0) {
|
||||
vector[0] = '\0';
|
||||
*length = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
if (v == 0) {
|
||||
vector[0] = '0';
|
||||
vector[1] = '\0';
|
||||
*length = 1;
|
||||
*point = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
bool fast_worked;
|
||||
switch (mode) {
|
||||
case SHORTEST:
|
||||
fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, vector, length, point);
|
||||
break;
|
||||
case SHORTEST_SINGLE:
|
||||
fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST_SINGLE, 0,
|
||||
vector, length, point);
|
||||
break;
|
||||
case FIXED:
|
||||
fast_worked = FastFixedDtoa(v, requested_digits, vector, length, point);
|
||||
break;
|
||||
case PRECISION:
|
||||
fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
|
||||
vector, length, point);
|
||||
break;
|
||||
default:
|
||||
fast_worked = false;
|
||||
UNREACHABLE();
|
||||
}
|
||||
if (fast_worked) return;
|
||||
|
||||
// If the fast dtoa didn't succeed use the slower bignum version.
|
||||
BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
|
||||
BignumDtoa(v, bignum_mode, requested_digits, vector, length, point);
|
||||
vector[*length] = '\0';
|
||||
}
|
||||
|
||||
|
||||
// Consumes the given substring from the iterator.
|
||||
// Returns false, if the substring does not match.
|
||||
static bool ConsumeSubString(const char** current,
|
||||
const char* end,
|
||||
const char* substring) {
|
||||
ASSERT(**current == *substring);
|
||||
for (substring++; *substring != '\0'; substring++) {
|
||||
++*current;
|
||||
if (*current == end || **current != *substring) return false;
|
||||
}
|
||||
++*current;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
// Maximum number of significant digits in decimal representation.
|
||||
// The longest possible double in decimal representation is
|
||||
// (2^53 - 1) * 2 ^ -1074 that is (2 ^ 53 - 1) * 5 ^ 1074 / 10 ^ 1074
|
||||
// (768 digits). If we parse a number whose first digits are equal to a
|
||||
// mean of 2 adjacent doubles (that could have up to 769 digits) the result
|
||||
// must be rounded to the bigger one unless the tail consists of zeros, so
|
||||
// we don't need to preserve all the digits.
|
||||
const int kMaxSignificantDigits = 772;
|
||||
|
||||
|
||||
// Returns true if a nonspace found and false if the end has reached.
|
||||
static inline bool AdvanceToNonspace(const char** current, const char* end) {
|
||||
while (*current != end) {
|
||||
if (**current != ' ') return true;
|
||||
++*current;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
static bool isDigit(int x, int radix) {
|
||||
return (x >= '0' && x <= '9' && x < '0' + radix)
|
||||
|| (radix > 10 && x >= 'a' && x < 'a' + radix - 10)
|
||||
|| (radix > 10 && x >= 'A' && x < 'A' + radix - 10);
|
||||
}
|
||||
|
||||
|
||||
static double SignedZero(bool sign) {
|
||||
return sign ? -0.0 : 0.0;
|
||||
}
|
||||
|
||||
|
||||
// Returns true if 'c' is a decimal digit that is valid for the given radix.
|
||||
//
|
||||
// The function is small and could be inlined, but VS2012 emitted a warning
|
||||
// because it constant-propagated the radix and concluded that the last
|
||||
// condition was always true. By moving it into a separate function the
|
||||
// compiler wouldn't warn anymore.
|
||||
static bool IsDecimalDigitForRadix(int c, int radix) {
|
||||
return '0' <= c && c <= '9' && (c - '0') < radix;
|
||||
}
|
||||
|
||||
// Returns true if 'c' is a character digit that is valid for the given radix.
|
||||
// The 'a_character' should be 'a' or 'A'.
|
||||
//
|
||||
// The function is small and could be inlined, but VS2012 emitted a warning
|
||||
// because it constant-propagated the radix and concluded that the first
|
||||
// condition was always false. By moving it into a separate function the
|
||||
// compiler wouldn't warn anymore.
|
||||
static bool IsCharacterDigitForRadix(int c, int radix, char a_character) {
|
||||
return radix > 10 && c >= a_character && c < a_character + radix - 10;
|
||||
}
|
||||
|
||||
|
||||
// Parsing integers with radix 2, 4, 8, 16, 32. Assumes current != end.
|
||||
template <int radix_log_2>
|
||||
static double RadixStringToIeee(const char* current,
|
||||
const char* end,
|
||||
bool sign,
|
||||
bool allow_trailing_junk,
|
||||
double junk_string_value,
|
||||
bool read_as_double,
|
||||
const char** trailing_pointer) {
|
||||
ASSERT(current != end);
|
||||
|
||||
const int kDoubleSize = Double::kSignificandSize;
|
||||
const int kSingleSize = Single::kSignificandSize;
|
||||
const int kSignificandSize = read_as_double? kDoubleSize: kSingleSize;
|
||||
|
||||
// Skip leading 0s.
|
||||
while (*current == '0') {
|
||||
++current;
|
||||
if (current == end) {
|
||||
*trailing_pointer = end;
|
||||
return SignedZero(sign);
|
||||
}
|
||||
}
|
||||
|
||||
int64_t number = 0;
|
||||
int exponent = 0;
|
||||
const int radix = (1 << radix_log_2);
|
||||
|
||||
do {
|
||||
int digit;
|
||||
if (IsDecimalDigitForRadix(*current, radix)) {
|
||||
digit = static_cast<char>(*current) - '0';
|
||||
} else if (IsCharacterDigitForRadix(*current, radix, 'a')) {
|
||||
digit = static_cast<char>(*current) - 'a' + 10;
|
||||
} else if (IsCharacterDigitForRadix(*current, radix, 'A')) {
|
||||
digit = static_cast<char>(*current) - 'A' + 10;
|
||||
} else {
|
||||
if (allow_trailing_junk || !AdvanceToNonspace(¤t, end)) {
|
||||
break;
|
||||
} else {
|
||||
return junk_string_value;
|
||||
}
|
||||
}
|
||||
|
||||
number = number * radix + digit;
|
||||
int overflow = static_cast<int>(number >> kSignificandSize);
|
||||
if (overflow != 0) {
|
||||
// Overflow occurred. Need to determine which direction to round the
|
||||
// result.
|
||||
int overflow_bits_count = 1;
|
||||
while (overflow > 1) {
|
||||
overflow_bits_count++;
|
||||
overflow >>= 1;
|
||||
}
|
||||
|
||||
int dropped_bits_mask = ((1 << overflow_bits_count) - 1);
|
||||
int dropped_bits = static_cast<int>(number) & dropped_bits_mask;
|
||||
number >>= overflow_bits_count;
|
||||
exponent = overflow_bits_count;
|
||||
|
||||
bool zero_tail = true;
|
||||
for (;;) {
|
||||
++current;
|
||||
if (current == end || !isDigit(*current, radix)) break;
|
||||
zero_tail = zero_tail && *current == '0';
|
||||
exponent += radix_log_2;
|
||||
}
|
||||
|
||||
if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
|
||||
return junk_string_value;
|
||||
}
|
||||
|
||||
int middle_value = (1 << (overflow_bits_count - 1));
|
||||
if (dropped_bits > middle_value) {
|
||||
number++; // Rounding up.
|
||||
} else if (dropped_bits == middle_value) {
|
||||
// Rounding to even to consistency with decimals: half-way case rounds
|
||||
// up if significant part is odd and down otherwise.
|
||||
if ((number & 1) != 0 || !zero_tail) {
|
||||
number++; // Rounding up.
|
||||
}
|
||||
}
|
||||
|
||||
// Rounding up may cause overflow.
|
||||
if ((number & ((int64_t)1 << kSignificandSize)) != 0) {
|
||||
exponent++;
|
||||
number >>= 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
++current;
|
||||
} while (current != end);
|
||||
|
||||
ASSERT(number < ((int64_t)1 << kSignificandSize));
|
||||
ASSERT(static_cast<int64_t>(static_cast<double>(number)) == number);
|
||||
|
||||
*trailing_pointer = current;
|
||||
|
||||
if (exponent == 0) {
|
||||
if (sign) {
|
||||
if (number == 0) return -0.0;
|
||||
number = -number;
|
||||
}
|
||||
return static_cast<double>(number);
|
||||
}
|
||||
|
||||
ASSERT(number != 0);
|
||||
return Double(DiyFp(number, exponent)).value();
|
||||
}
|
||||
|
||||
|
||||
double StringToDoubleConverter::StringToIeee(
|
||||
const char* input,
|
||||
int length,
|
||||
int* processed_characters_count,
|
||||
bool read_as_double) const {
|
||||
const char* current = input;
|
||||
const char* end = input + length;
|
||||
|
||||
*processed_characters_count = 0;
|
||||
|
||||
const bool allow_trailing_junk = (flags_ & ALLOW_TRAILING_JUNK) != 0;
|
||||
const bool allow_leading_spaces = (flags_ & ALLOW_LEADING_SPACES) != 0;
|
||||
const bool allow_trailing_spaces = (flags_ & ALLOW_TRAILING_SPACES) != 0;
|
||||
const bool allow_spaces_after_sign = (flags_ & ALLOW_SPACES_AFTER_SIGN) != 0;
|
||||
|
||||
// To make sure that iterator dereferencing is valid the following
|
||||
// convention is used:
|
||||
// 1. Each '++current' statement is followed by check for equality to 'end'.
|
||||
// 2. If AdvanceToNonspace returned false then current == end.
|
||||
// 3. If 'current' becomes equal to 'end' the function returns or goes to
|
||||
// 'parsing_done'.
|
||||
// 4. 'current' is not dereferenced after the 'parsing_done' label.
|
||||
// 5. Code before 'parsing_done' may rely on 'current != end'.
|
||||
if (current == end) return empty_string_value_;
|
||||
|
||||
if (allow_leading_spaces || allow_trailing_spaces) {
|
||||
if (!AdvanceToNonspace(¤t, end)) {
|
||||
*processed_characters_count = static_cast<int>(current - input);
|
||||
return empty_string_value_;
|
||||
}
|
||||
if (!allow_leading_spaces && (input != current)) {
|
||||
// No leading spaces allowed, but AdvanceToNonspace moved forward.
|
||||
return junk_string_value_;
|
||||
}
|
||||
}
|
||||
|
||||
// The longest form of simplified number is: "-<significant digits>.1eXXX\0".
|
||||
const int kBufferSize = kMaxSignificantDigits + 10;
|
||||
char buffer[kBufferSize]; // NOLINT: size is known at compile time.
|
||||
int buffer_pos = 0;
|
||||
|
||||
// Exponent will be adjusted if insignificant digits of the integer part
|
||||
// or insignificant leading zeros of the fractional part are dropped.
|
||||
int exponent = 0;
|
||||
int significant_digits = 0;
|
||||
int insignificant_digits = 0;
|
||||
bool nonzero_digit_dropped = false;
|
||||
|
||||
bool sign = false;
|
||||
|
||||
if (*current == '+' || *current == '-') {
|
||||
sign = (*current == '-');
|
||||
++current;
|
||||
const char* next_non_space = current;
|
||||
// Skip following spaces (if allowed).
|
||||
if (!AdvanceToNonspace(&next_non_space, end)) return junk_string_value_;
|
||||
if (!allow_spaces_after_sign && (current != next_non_space)) {
|
||||
return junk_string_value_;
|
||||
}
|
||||
current = next_non_space;
|
||||
}
|
||||
|
||||
if (infinity_symbol_ != NULL) {
|
||||
if (*current == infinity_symbol_[0]) {
|
||||
if (!ConsumeSubString(¤t, end, infinity_symbol_)) {
|
||||
return junk_string_value_;
|
||||
}
|
||||
|
||||
if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
|
||||
return junk_string_value_;
|
||||
}
|
||||
if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
|
||||
return junk_string_value_;
|
||||
}
|
||||
|
||||
ASSERT(buffer_pos == 0);
|
||||
*processed_characters_count = static_cast<int>(current - input);
|
||||
return sign ? -Double::Infinity() : Double::Infinity();
|
||||
}
|
||||
}
|
||||
|
||||
if (nan_symbol_ != NULL) {
|
||||
if (*current == nan_symbol_[0]) {
|
||||
if (!ConsumeSubString(¤t, end, nan_symbol_)) {
|
||||
return junk_string_value_;
|
||||
}
|
||||
|
||||
if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
|
||||
return junk_string_value_;
|
||||
}
|
||||
if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
|
||||
return junk_string_value_;
|
||||
}
|
||||
|
||||
ASSERT(buffer_pos == 0);
|
||||
*processed_characters_count = static_cast<int>(current - input);
|
||||
return sign ? -Double::NaN() : Double::NaN();
|
||||
}
|
||||
}
|
||||
|
||||
bool leading_zero = false;
|
||||
if (*current == '0') {
|
||||
++current;
|
||||
if (current == end) {
|
||||
*processed_characters_count = static_cast<int>(current - input);
|
||||
return SignedZero(sign);
|
||||
}
|
||||
|
||||
leading_zero = true;
|
||||
|
||||
// It could be hexadecimal value.
|
||||
if ((flags_ & ALLOW_HEX) && (*current == 'x' || *current == 'X')) {
|
||||
++current;
|
||||
if (current == end || !isDigit(*current, 16)) {
|
||||
return junk_string_value_; // "0x".
|
||||
}
|
||||
|
||||
const char* tail_pointer = NULL;
|
||||
double result = RadixStringToIeee<4>(current,
|
||||
end,
|
||||
sign,
|
||||
allow_trailing_junk,
|
||||
junk_string_value_,
|
||||
read_as_double,
|
||||
&tail_pointer);
|
||||
if (tail_pointer != NULL) {
|
||||
if (allow_trailing_spaces) AdvanceToNonspace(&tail_pointer, end);
|
||||
*processed_characters_count = static_cast<int>(tail_pointer - input);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Ignore leading zeros in the integer part.
|
||||
while (*current == '0') {
|
||||
++current;
|
||||
if (current == end) {
|
||||
*processed_characters_count = static_cast<int>(current - input);
|
||||
return SignedZero(sign);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool octal = leading_zero && (flags_ & ALLOW_OCTALS) != 0;
|
||||
|
||||
// Copy significant digits of the integer part (if any) to the buffer.
|
||||
while (*current >= '0' && *current <= '9') {
|
||||
if (significant_digits < kMaxSignificantDigits) {
|
||||
ASSERT(buffer_pos < kBufferSize);
|
||||
buffer[buffer_pos++] = static_cast<char>(*current);
|
||||
significant_digits++;
|
||||
// Will later check if it's an octal in the buffer.
|
||||
} else {
|
||||
insignificant_digits++; // Move the digit into the exponential part.
|
||||
nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
|
||||
}
|
||||
octal = octal && *current < '8';
|
||||
++current;
|
||||
if (current == end) goto parsing_done;
|
||||
}
|
||||
|
||||
if (significant_digits == 0) {
|
||||
octal = false;
|
||||
}
|
||||
|
||||
if (*current == '.') {
|
||||
if (octal && !allow_trailing_junk) return junk_string_value_;
|
||||
if (octal) goto parsing_done;
|
||||
|
||||
++current;
|
||||
if (current == end) {
|
||||
if (significant_digits == 0 && !leading_zero) {
|
||||
return junk_string_value_;
|
||||
} else {
|
||||
goto parsing_done;
|
||||
}
|
||||
}
|
||||
|
||||
if (significant_digits == 0) {
|
||||
// octal = false;
|
||||
// Integer part consists of 0 or is absent. Significant digits start after
|
||||
// leading zeros (if any).
|
||||
while (*current == '0') {
|
||||
++current;
|
||||
if (current == end) {
|
||||
*processed_characters_count = static_cast<int>(current - input);
|
||||
return SignedZero(sign);
|
||||
}
|
||||
exponent--; // Move this 0 into the exponent.
|
||||
}
|
||||
}
|
||||
|
||||
// There is a fractional part.
|
||||
// We don't emit a '.', but adjust the exponent instead.
|
||||
while (*current >= '0' && *current <= '9') {
|
||||
if (significant_digits < kMaxSignificantDigits) {
|
||||
ASSERT(buffer_pos < kBufferSize);
|
||||
buffer[buffer_pos++] = static_cast<char>(*current);
|
||||
significant_digits++;
|
||||
exponent--;
|
||||
} else {
|
||||
// Ignore insignificant digits in the fractional part.
|
||||
nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
|
||||
}
|
||||
++current;
|
||||
if (current == end) goto parsing_done;
|
||||
}
|
||||
}
|
||||
|
||||
if (!leading_zero && exponent == 0 && significant_digits == 0) {
|
||||
// If leading_zeros is true then the string contains zeros.
|
||||
// If exponent < 0 then string was [+-]\.0*...
|
||||
// If significant_digits != 0 the string is not equal to 0.
|
||||
// Otherwise there are no digits in the string.
|
||||
return junk_string_value_;
|
||||
}
|
||||
|
||||
// Parse exponential part.
|
||||
if (*current == 'e' || *current == 'E') {
|
||||
if (octal && !allow_trailing_junk) return junk_string_value_;
|
||||
if (octal) goto parsing_done;
|
||||
++current;
|
||||
if (current == end) {
|
||||
if (allow_trailing_junk) {
|
||||
goto parsing_done;
|
||||
} else {
|
||||
return junk_string_value_;
|
||||
}
|
||||
}
|
||||
char sign = '+';
|
||||
if (*current == '+' || *current == '-') {
|
||||
sign = static_cast<char>(*current);
|
||||
++current;
|
||||
if (current == end) {
|
||||
if (allow_trailing_junk) {
|
||||
goto parsing_done;
|
||||
} else {
|
||||
return junk_string_value_;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (current == end || *current < '0' || *current > '9') {
|
||||
if (allow_trailing_junk) {
|
||||
goto parsing_done;
|
||||
} else {
|
||||
return junk_string_value_;
|
||||
}
|
||||
}
|
||||
|
||||
const int max_exponent = INT_MAX / 2;
|
||||
ASSERT(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
|
||||
int num = 0;
|
||||
do {
|
||||
// Check overflow.
|
||||
int digit = *current - '0';
|
||||
if (num >= max_exponent / 10
|
||||
&& !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
|
||||
num = max_exponent;
|
||||
} else {
|
||||
num = num * 10 + digit;
|
||||
}
|
||||
++current;
|
||||
} while (current != end && *current >= '0' && *current <= '9');
|
||||
|
||||
exponent += (sign == '-' ? -num : num);
|
||||
}
|
||||
|
||||
if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
|
||||
return junk_string_value_;
|
||||
}
|
||||
if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
|
||||
return junk_string_value_;
|
||||
}
|
||||
if (allow_trailing_spaces) {
|
||||
AdvanceToNonspace(¤t, end);
|
||||
}
|
||||
|
||||
parsing_done:
|
||||
exponent += insignificant_digits;
|
||||
|
||||
if (octal) {
|
||||
double result;
|
||||
const char* tail_pointer = NULL;
|
||||
result = RadixStringToIeee<3>(buffer,
|
||||
buffer + buffer_pos,
|
||||
sign,
|
||||
allow_trailing_junk,
|
||||
junk_string_value_,
|
||||
read_as_double,
|
||||
&tail_pointer);
|
||||
ASSERT(tail_pointer != NULL);
|
||||
*processed_characters_count = static_cast<int>(current - input);
|
||||
return result;
|
||||
}
|
||||
|
||||
if (nonzero_digit_dropped) {
|
||||
buffer[buffer_pos++] = '1';
|
||||
exponent--;
|
||||
}
|
||||
|
||||
ASSERT(buffer_pos < kBufferSize);
|
||||
buffer[buffer_pos] = '\0';
|
||||
|
||||
double converted;
|
||||
if (read_as_double) {
|
||||
converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
|
||||
} else {
|
||||
converted = Strtof(Vector<const char>(buffer, buffer_pos), exponent);
|
||||
}
|
||||
*processed_characters_count = static_cast<int>(current - input);
|
||||
return sign? -converted: converted;
|
||||
}
|
||||
|
||||
} // namespace double_conversion
|
|
@ -1,536 +0,0 @@
|
|||
// Copyright 2012 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
||||
#define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
class DoubleToStringConverter {
|
||||
public:
|
||||
// When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint
|
||||
// or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the
|
||||
// function returns false.
|
||||
static const int kMaxFixedDigitsBeforePoint = 60;
|
||||
static const int kMaxFixedDigitsAfterPoint = 60;
|
||||
|
||||
// When calling ToExponential with a requested_digits
|
||||
// parameter > kMaxExponentialDigits then the function returns false.
|
||||
static const int kMaxExponentialDigits = 120;
|
||||
|
||||
// When calling ToPrecision with a requested_digits
|
||||
// parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits
|
||||
// then the function returns false.
|
||||
static const int kMinPrecisionDigits = 1;
|
||||
static const int kMaxPrecisionDigits = 120;
|
||||
|
||||
enum Flags {
|
||||
NO_FLAGS = 0,
|
||||
EMIT_POSITIVE_EXPONENT_SIGN = 1,
|
||||
EMIT_TRAILING_DECIMAL_POINT = 2,
|
||||
EMIT_TRAILING_ZERO_AFTER_POINT = 4,
|
||||
UNIQUE_ZERO = 8
|
||||
};
|
||||
|
||||
// Flags should be a bit-or combination of the possible Flags-enum.
|
||||
// - NO_FLAGS: no special flags.
|
||||
// - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent
|
||||
// form, emits a '+' for positive exponents. Example: 1.2e+2.
|
||||
// - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is
|
||||
// converted into decimal format then a trailing decimal point is appended.
|
||||
// Example: 2345.0 is converted to "2345.".
|
||||
// - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point
|
||||
// emits a trailing '0'-character. This flag requires the
|
||||
// EXMIT_TRAILING_DECIMAL_POINT flag.
|
||||
// Example: 2345.0 is converted to "2345.0".
|
||||
// - UNIQUE_ZERO: "-0.0" is converted to "0.0".
|
||||
//
|
||||
// Infinity symbol and nan_symbol provide the string representation for these
|
||||
// special values. If the string is NULL and the special value is encountered
|
||||
// then the conversion functions return false.
|
||||
//
|
||||
// The exponent_character is used in exponential representations. It is
|
||||
// usually 'e' or 'E'.
|
||||
//
|
||||
// When converting to the shortest representation the converter will
|
||||
// represent input numbers in decimal format if they are in the interval
|
||||
// [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[
|
||||
// (lower boundary included, greater boundary excluded).
|
||||
// Example: with decimal_in_shortest_low = -6 and
|
||||
// decimal_in_shortest_high = 21:
|
||||
// ToShortest(0.000001) -> "0.000001"
|
||||
// ToShortest(0.0000001) -> "1e-7"
|
||||
// ToShortest(111111111111111111111.0) -> "111111111111111110000"
|
||||
// ToShortest(100000000000000000000.0) -> "100000000000000000000"
|
||||
// ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
|
||||
//
|
||||
// When converting to precision mode the converter may add
|
||||
// max_leading_padding_zeroes before returning the number in exponential
|
||||
// format.
|
||||
// Example with max_leading_padding_zeroes_in_precision_mode = 6.
|
||||
// ToPrecision(0.0000012345, 2) -> "0.0000012"
|
||||
// ToPrecision(0.00000012345, 2) -> "1.2e-7"
|
||||
// Similarily the converter may add up to
|
||||
// max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
|
||||
// returning an exponential representation. A zero added by the
|
||||
// EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
|
||||
// Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
|
||||
// ToPrecision(230.0, 2) -> "230"
|
||||
// ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
|
||||
// ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
|
||||
DoubleToStringConverter(int flags,
|
||||
const char* infinity_symbol,
|
||||
const char* nan_symbol,
|
||||
char exponent_character,
|
||||
int decimal_in_shortest_low,
|
||||
int decimal_in_shortest_high,
|
||||
int max_leading_padding_zeroes_in_precision_mode,
|
||||
int max_trailing_padding_zeroes_in_precision_mode)
|
||||
: flags_(flags),
|
||||
infinity_symbol_(infinity_symbol),
|
||||
nan_symbol_(nan_symbol),
|
||||
exponent_character_(exponent_character),
|
||||
decimal_in_shortest_low_(decimal_in_shortest_low),
|
||||
decimal_in_shortest_high_(decimal_in_shortest_high),
|
||||
max_leading_padding_zeroes_in_precision_mode_(
|
||||
max_leading_padding_zeroes_in_precision_mode),
|
||||
max_trailing_padding_zeroes_in_precision_mode_(
|
||||
max_trailing_padding_zeroes_in_precision_mode) {
|
||||
// When 'trailing zero after the point' is set, then 'trailing point'
|
||||
// must be set too.
|
||||
ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) ||
|
||||
!((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0));
|
||||
}
|
||||
|
||||
// Returns a converter following the EcmaScript specification.
|
||||
static const DoubleToStringConverter& EcmaScriptConverter();
|
||||
|
||||
// Computes the shortest string of digits that correctly represent the input
|
||||
// number. Depending on decimal_in_shortest_low and decimal_in_shortest_high
|
||||
// (see constructor) it then either returns a decimal representation, or an
|
||||
// exponential representation.
|
||||
// Example with decimal_in_shortest_low = -6,
|
||||
// decimal_in_shortest_high = 21,
|
||||
// EMIT_POSITIVE_EXPONENT_SIGN activated, and
|
||||
// EMIT_TRAILING_DECIMAL_POINT deactived:
|
||||
// ToShortest(0.000001) -> "0.000001"
|
||||
// ToShortest(0.0000001) -> "1e-7"
|
||||
// ToShortest(111111111111111111111.0) -> "111111111111111110000"
|
||||
// ToShortest(100000000000000000000.0) -> "100000000000000000000"
|
||||
// ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
|
||||
//
|
||||
// Note: the conversion may round the output if the returned string
|
||||
// is accurate enough to uniquely identify the input-number.
|
||||
// For example the most precise representation of the double 9e59 equals
|
||||
// "899999999999999918767229449717619953810131273674690656206848", but
|
||||
// the converter will return the shorter (but still correct) "9e59".
|
||||
//
|
||||
// Returns true if the conversion succeeds. The conversion always succeeds
|
||||
// except when the input value is special and no infinity_symbol or
|
||||
// nan_symbol has been given to the constructor.
|
||||
bool ToShortest(double value, StringBuilder* result_builder) const {
|
||||
return ToShortestIeeeNumber(value, result_builder, SHORTEST);
|
||||
}
|
||||
|
||||
// Same as ToShortest, but for single-precision floats.
|
||||
bool ToShortestSingle(float value, StringBuilder* result_builder) const {
|
||||
return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE);
|
||||
}
|
||||
|
||||
|
||||
// Computes a decimal representation with a fixed number of digits after the
|
||||
// decimal point. The last emitted digit is rounded.
|
||||
//
|
||||
// Examples:
|
||||
// ToFixed(3.12, 1) -> "3.1"
|
||||
// ToFixed(3.1415, 3) -> "3.142"
|
||||
// ToFixed(1234.56789, 4) -> "1234.5679"
|
||||
// ToFixed(1.23, 5) -> "1.23000"
|
||||
// ToFixed(0.1, 4) -> "0.1000"
|
||||
// ToFixed(1e30, 2) -> "1000000000000000019884624838656.00"
|
||||
// ToFixed(0.1, 30) -> "0.100000000000000005551115123126"
|
||||
// ToFixed(0.1, 17) -> "0.10000000000000001"
|
||||
//
|
||||
// If requested_digits equals 0, then the tail of the result depends on
|
||||
// the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT.
|
||||
// Examples, for requested_digits == 0,
|
||||
// let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be
|
||||
// - false and false: then 123.45 -> 123
|
||||
// 0.678 -> 1
|
||||
// - true and false: then 123.45 -> 123.
|
||||
// 0.678 -> 1.
|
||||
// - true and true: then 123.45 -> 123.0
|
||||
// 0.678 -> 1.0
|
||||
//
|
||||
// Returns true if the conversion succeeds. The conversion always succeeds
|
||||
// except for the following cases:
|
||||
// - the input value is special and no infinity_symbol or nan_symbol has
|
||||
// been provided to the constructor,
|
||||
// - 'value' > 10^kMaxFixedDigitsBeforePoint, or
|
||||
// - 'requested_digits' > kMaxFixedDigitsAfterPoint.
|
||||
// The last two conditions imply that the result will never contain more than
|
||||
// 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters
|
||||
// (one additional character for the sign, and one for the decimal point).
|
||||
bool ToFixed(double value,
|
||||
int requested_digits,
|
||||
StringBuilder* result_builder) const;
|
||||
|
||||
// Computes a representation in exponential format with requested_digits
|
||||
// after the decimal point. The last emitted digit is rounded.
|
||||
// If requested_digits equals -1, then the shortest exponential representation
|
||||
// is computed.
|
||||
//
|
||||
// Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and
|
||||
// exponent_character set to 'e'.
|
||||
// ToExponential(3.12, 1) -> "3.1e0"
|
||||
// ToExponential(5.0, 3) -> "5.000e0"
|
||||
// ToExponential(0.001, 2) -> "1.00e-3"
|
||||
// ToExponential(3.1415, -1) -> "3.1415e0"
|
||||
// ToExponential(3.1415, 4) -> "3.1415e0"
|
||||
// ToExponential(3.1415, 3) -> "3.142e0"
|
||||
// ToExponential(123456789000000, 3) -> "1.235e14"
|
||||
// ToExponential(1000000000000000019884624838656.0, -1) -> "1e30"
|
||||
// ToExponential(1000000000000000019884624838656.0, 32) ->
|
||||
// "1.00000000000000001988462483865600e30"
|
||||
// ToExponential(1234, 0) -> "1e3"
|
||||
//
|
||||
// Returns true if the conversion succeeds. The conversion always succeeds
|
||||
// except for the following cases:
|
||||
// - the input value is special and no infinity_symbol or nan_symbol has
|
||||
// been provided to the constructor,
|
||||
// - 'requested_digits' > kMaxExponentialDigits.
|
||||
// The last condition implies that the result will never contain more than
|
||||
// kMaxExponentialDigits + 8 characters (the sign, the digit before the
|
||||
// decimal point, the decimal point, the exponent character, the
|
||||
// exponent's sign, and at most 3 exponent digits).
|
||||
bool ToExponential(double value,
|
||||
int requested_digits,
|
||||
StringBuilder* result_builder) const;
|
||||
|
||||
// Computes 'precision' leading digits of the given 'value' and returns them
|
||||
// either in exponential or decimal format, depending on
|
||||
// max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the
|
||||
// constructor).
|
||||
// The last computed digit is rounded.
|
||||
//
|
||||
// Example with max_leading_padding_zeroes_in_precision_mode = 6.
|
||||
// ToPrecision(0.0000012345, 2) -> "0.0000012"
|
||||
// ToPrecision(0.00000012345, 2) -> "1.2e-7"
|
||||
// Similarily the converter may add up to
|
||||
// max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
|
||||
// returning an exponential representation. A zero added by the
|
||||
// EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
|
||||
// Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
|
||||
// ToPrecision(230.0, 2) -> "230"
|
||||
// ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
|
||||
// ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
|
||||
// Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no
|
||||
// EMIT_TRAILING_ZERO_AFTER_POINT:
|
||||
// ToPrecision(123450.0, 6) -> "123450"
|
||||
// ToPrecision(123450.0, 5) -> "123450"
|
||||
// ToPrecision(123450.0, 4) -> "123500"
|
||||
// ToPrecision(123450.0, 3) -> "123000"
|
||||
// ToPrecision(123450.0, 2) -> "1.2e5"
|
||||
//
|
||||
// Returns true if the conversion succeeds. The conversion always succeeds
|
||||
// except for the following cases:
|
||||
// - the input value is special and no infinity_symbol or nan_symbol has
|
||||
// been provided to the constructor,
|
||||
// - precision < kMinPericisionDigits
|
||||
// - precision > kMaxPrecisionDigits
|
||||
// The last condition implies that the result will never contain more than
|
||||
// kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the
|
||||
// exponent character, the exponent's sign, and at most 3 exponent digits).
|
||||
bool ToPrecision(double value,
|
||||
int precision,
|
||||
StringBuilder* result_builder) const;
|
||||
|
||||
enum DtoaMode {
|
||||
// Produce the shortest correct representation.
|
||||
// For example the output of 0.299999999999999988897 is (the less accurate
|
||||
// but correct) 0.3.
|
||||
SHORTEST,
|
||||
// Same as SHORTEST, but for single-precision floats.
|
||||
SHORTEST_SINGLE,
|
||||
// Produce a fixed number of digits after the decimal point.
|
||||
// For instance fixed(0.1, 4) becomes 0.1000
|
||||
// If the input number is big, the output will be big.
|
||||
FIXED,
|
||||
// Fixed number of digits (independent of the decimal point).
|
||||
PRECISION
|
||||
};
|
||||
|
||||
// The maximal number of digits that are needed to emit a double in base 10.
|
||||
// A higher precision can be achieved by using more digits, but the shortest
|
||||
// accurate representation of any double will never use more digits than
|
||||
// kBase10MaximalLength.
|
||||
// Note that DoubleToAscii null-terminates its input. So the given buffer
|
||||
// should be at least kBase10MaximalLength + 1 characters long.
|
||||
static const int kBase10MaximalLength = 17;
|
||||
|
||||
// Converts the given double 'v' to ascii. 'v' must not be NaN, +Infinity, or
|
||||
// -Infinity. In SHORTEST_SINGLE-mode this restriction also applies to 'v'
|
||||
// after it has been casted to a single-precision float. That is, in this
|
||||
// mode static_cast<float>(v) must not be NaN, +Infinity or -Infinity.
|
||||
//
|
||||
// The result should be interpreted as buffer * 10^(point-length).
|
||||
//
|
||||
// The output depends on the given mode:
|
||||
// - SHORTEST: produce the least amount of digits for which the internal
|
||||
// identity requirement is still satisfied. If the digits are printed
|
||||
// (together with the correct exponent) then reading this number will give
|
||||
// 'v' again. The buffer will choose the representation that is closest to
|
||||
// 'v'. If there are two at the same distance, than the one farther away
|
||||
// from 0 is chosen (halfway cases - ending with 5 - are rounded up).
|
||||
// In this mode the 'requested_digits' parameter is ignored.
|
||||
// - SHORTEST_SINGLE: same as SHORTEST but with single-precision.
|
||||
// - FIXED: produces digits necessary to print a given number with
|
||||
// 'requested_digits' digits after the decimal point. The produced digits
|
||||
// might be too short in which case the caller has to fill the remainder
|
||||
// with '0's.
|
||||
// Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
|
||||
// Halfway cases are rounded towards +/-Infinity (away from 0). The call
|
||||
// toFixed(0.15, 2) thus returns buffer="2", point=0.
|
||||
// The returned buffer may contain digits that would be truncated from the
|
||||
// shortest representation of the input.
|
||||
// - PRECISION: produces 'requested_digits' where the first digit is not '0'.
|
||||
// Even though the length of produced digits usually equals
|
||||
// 'requested_digits', the function is allowed to return fewer digits, in
|
||||
// which case the caller has to fill the missing digits with '0's.
|
||||
// Halfway cases are again rounded away from 0.
|
||||
// DoubleToAscii expects the given buffer to be big enough to hold all
|
||||
// digits and a terminating null-character. In SHORTEST-mode it expects a
|
||||
// buffer of at least kBase10MaximalLength + 1. In all other modes the
|
||||
// requested_digits parameter and the padding-zeroes limit the size of the
|
||||
// output. Don't forget the decimal point, the exponent character and the
|
||||
// terminating null-character when computing the maximal output size.
|
||||
// The given length is only used in debug mode to ensure the buffer is big
|
||||
// enough.
|
||||
static void DoubleToAscii(double v,
|
||||
DtoaMode mode,
|
||||
int requested_digits,
|
||||
char* buffer,
|
||||
int buffer_length,
|
||||
bool* sign,
|
||||
int* length,
|
||||
int* point);
|
||||
|
||||
private:
|
||||
// Implementation for ToShortest and ToShortestSingle.
|
||||
bool ToShortestIeeeNumber(double value,
|
||||
StringBuilder* result_builder,
|
||||
DtoaMode mode) const;
|
||||
|
||||
// If the value is a special value (NaN or Infinity) constructs the
|
||||
// corresponding string using the configured infinity/nan-symbol.
|
||||
// If either of them is NULL or the value is not special then the
|
||||
// function returns false.
|
||||
bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
|
||||
// Constructs an exponential representation (i.e. 1.234e56).
|
||||
// The given exponent assumes a decimal point after the first decimal digit.
|
||||
void CreateExponentialRepresentation(const char* decimal_digits,
|
||||
int length,
|
||||
int exponent,
|
||||
StringBuilder* result_builder) const;
|
||||
// Creates a decimal representation (i.e 1234.5678).
|
||||
void CreateDecimalRepresentation(const char* decimal_digits,
|
||||
int length,
|
||||
int decimal_point,
|
||||
int digits_after_point,
|
||||
StringBuilder* result_builder) const;
|
||||
|
||||
const int flags_;
|
||||
const char* const infinity_symbol_;
|
||||
const char* const nan_symbol_;
|
||||
const char exponent_character_;
|
||||
const int decimal_in_shortest_low_;
|
||||
const int decimal_in_shortest_high_;
|
||||
const int max_leading_padding_zeroes_in_precision_mode_;
|
||||
const int max_trailing_padding_zeroes_in_precision_mode_;
|
||||
|
||||
DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter);
|
||||
};
|
||||
|
||||
|
||||
class StringToDoubleConverter {
|
||||
public:
|
||||
// Enumeration for allowing octals and ignoring junk when converting
|
||||
// strings to numbers.
|
||||
enum Flags {
|
||||
NO_FLAGS = 0,
|
||||
ALLOW_HEX = 1,
|
||||
ALLOW_OCTALS = 2,
|
||||
ALLOW_TRAILING_JUNK = 4,
|
||||
ALLOW_LEADING_SPACES = 8,
|
||||
ALLOW_TRAILING_SPACES = 16,
|
||||
ALLOW_SPACES_AFTER_SIGN = 32
|
||||
};
|
||||
|
||||
// Flags should be a bit-or combination of the possible Flags-enum.
|
||||
// - NO_FLAGS: no special flags.
|
||||
// - ALLOW_HEX: recognizes the prefix "0x". Hex numbers may only be integers.
|
||||
// Ex: StringToDouble("0x1234") -> 4660.0
|
||||
// In StringToDouble("0x1234.56") the characters ".56" are trailing
|
||||
// junk. The result of the call is hence dependent on
|
||||
// the ALLOW_TRAILING_JUNK flag and/or the junk value.
|
||||
// With this flag "0x" is a junk-string. Even with ALLOW_TRAILING_JUNK,
|
||||
// the string will not be parsed as "0" followed by junk.
|
||||
//
|
||||
// - ALLOW_OCTALS: recognizes the prefix "0" for octals:
|
||||
// If a sequence of octal digits starts with '0', then the number is
|
||||
// read as octal integer. Octal numbers may only be integers.
|
||||
// Ex: StringToDouble("01234") -> 668.0
|
||||
// StringToDouble("012349") -> 12349.0 // Not a sequence of octal
|
||||
// // digits.
|
||||
// In StringToDouble("01234.56") the characters ".56" are trailing
|
||||
// junk. The result of the call is hence dependent on
|
||||
// the ALLOW_TRAILING_JUNK flag and/or the junk value.
|
||||
// In StringToDouble("01234e56") the characters "e56" are trailing
|
||||
// junk, too.
|
||||
// - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of
|
||||
// a double literal.
|
||||
// - ALLOW_LEADING_SPACES: skip over leading spaces.
|
||||
// - ALLOW_TRAILING_SPACES: ignore trailing spaces.
|
||||
// - ALLOW_SPACES_AFTER_SIGN: ignore spaces after the sign.
|
||||
// Ex: StringToDouble("- 123.2") -> -123.2.
|
||||
// StringToDouble("+ 123.2") -> 123.2
|
||||
//
|
||||
// empty_string_value is returned when an empty string is given as input.
|
||||
// If ALLOW_LEADING_SPACES or ALLOW_TRAILING_SPACES are set, then a string
|
||||
// containing only spaces is converted to the 'empty_string_value', too.
|
||||
//
|
||||
// junk_string_value is returned when
|
||||
// a) ALLOW_TRAILING_JUNK is not set, and a junk character (a character not
|
||||
// part of a double-literal) is found.
|
||||
// b) ALLOW_TRAILING_JUNK is set, but the string does not start with a
|
||||
// double literal.
|
||||
//
|
||||
// infinity_symbol and nan_symbol are strings that are used to detect
|
||||
// inputs that represent infinity and NaN. They can be null, in which case
|
||||
// they are ignored.
|
||||
// The conversion routine first reads any possible signs. Then it compares the
|
||||
// following character of the input-string with the first character of
|
||||
// the infinity, and nan-symbol. If either matches, the function assumes, that
|
||||
// a match has been found, and expects the following input characters to match
|
||||
// the remaining characters of the special-value symbol.
|
||||
// This means that the following restrictions apply to special-value symbols:
|
||||
// - they must not start with signs ('+', or '-'),
|
||||
// - they must not have the same first character.
|
||||
// - they must not start with digits.
|
||||
//
|
||||
// Examples:
|
||||
// flags = ALLOW_HEX | ALLOW_TRAILING_JUNK,
|
||||
// empty_string_value = 0.0,
|
||||
// junk_string_value = NaN,
|
||||
// infinity_symbol = "infinity",
|
||||
// nan_symbol = "nan":
|
||||
// StringToDouble("0x1234") -> 4660.0.
|
||||
// StringToDouble("0x1234K") -> 4660.0.
|
||||
// StringToDouble("") -> 0.0 // empty_string_value.
|
||||
// StringToDouble(" ") -> NaN // junk_string_value.
|
||||
// StringToDouble(" 1") -> NaN // junk_string_value.
|
||||
// StringToDouble("0x") -> NaN // junk_string_value.
|
||||
// StringToDouble("-123.45") -> -123.45.
|
||||
// StringToDouble("--123.45") -> NaN // junk_string_value.
|
||||
// StringToDouble("123e45") -> 123e45.
|
||||
// StringToDouble("123E45") -> 123e45.
|
||||
// StringToDouble("123e+45") -> 123e45.
|
||||
// StringToDouble("123E-45") -> 123e-45.
|
||||
// StringToDouble("123e") -> 123.0 // trailing junk ignored.
|
||||
// StringToDouble("123e-") -> 123.0 // trailing junk ignored.
|
||||
// StringToDouble("+NaN") -> NaN // NaN string literal.
|
||||
// StringToDouble("-infinity") -> -inf. // infinity literal.
|
||||
// StringToDouble("Infinity") -> NaN // junk_string_value.
|
||||
//
|
||||
// flags = ALLOW_OCTAL | ALLOW_LEADING_SPACES,
|
||||
// empty_string_value = 0.0,
|
||||
// junk_string_value = NaN,
|
||||
// infinity_symbol = NULL,
|
||||
// nan_symbol = NULL:
|
||||
// StringToDouble("0x1234") -> NaN // junk_string_value.
|
||||
// StringToDouble("01234") -> 668.0.
|
||||
// StringToDouble("") -> 0.0 // empty_string_value.
|
||||
// StringToDouble(" ") -> 0.0 // empty_string_value.
|
||||
// StringToDouble(" 1") -> 1.0
|
||||
// StringToDouble("0x") -> NaN // junk_string_value.
|
||||
// StringToDouble("0123e45") -> NaN // junk_string_value.
|
||||
// StringToDouble("01239E45") -> 1239e45.
|
||||
// StringToDouble("-infinity") -> NaN // junk_string_value.
|
||||
// StringToDouble("NaN") -> NaN // junk_string_value.
|
||||
StringToDoubleConverter(int flags,
|
||||
double empty_string_value,
|
||||
double junk_string_value,
|
||||
const char* infinity_symbol,
|
||||
const char* nan_symbol)
|
||||
: flags_(flags),
|
||||
empty_string_value_(empty_string_value),
|
||||
junk_string_value_(junk_string_value),
|
||||
infinity_symbol_(infinity_symbol),
|
||||
nan_symbol_(nan_symbol) {
|
||||
}
|
||||
|
||||
// Performs the conversion.
|
||||
// The output parameter 'processed_characters_count' is set to the number
|
||||
// of characters that have been processed to read the number.
|
||||
// Spaces than are processed with ALLOW_{LEADING|TRAILING}_SPACES are included
|
||||
// in the 'processed_characters_count'. Trailing junk is never included.
|
||||
double StringToDouble(const char* buffer,
|
||||
int length,
|
||||
int* processed_characters_count) const {
|
||||
return StringToIeee(buffer, length, processed_characters_count, true);
|
||||
}
|
||||
|
||||
// Same as StringToDouble but reads a float.
|
||||
// Note that this is not equivalent to static_cast<float>(StringToDouble(...))
|
||||
// due to potential double-rounding.
|
||||
float StringToFloat(const char* buffer,
|
||||
int length,
|
||||
int* processed_characters_count) const {
|
||||
return static_cast<float>(StringToIeee(buffer, length,
|
||||
processed_characters_count, false));
|
||||
}
|
||||
|
||||
private:
|
||||
const int flags_;
|
||||
const double empty_string_value_;
|
||||
const double junk_string_value_;
|
||||
const char* const infinity_symbol_;
|
||||
const char* const nan_symbol_;
|
||||
|
||||
double StringToIeee(const char* buffer,
|
||||
int length,
|
||||
int* processed_characters_count,
|
||||
bool read_as_double) const;
|
||||
|
||||
DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter);
|
||||
};
|
||||
|
||||
} // namespace double_conversion
|
||||
|
||||
#endif // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
|
@ -1,665 +0,0 @@
|
|||
// Copyright 2012 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#include "fast-dtoa.h"
|
||||
|
||||
#include "cached-powers.h"
|
||||
#include "diy-fp.h"
|
||||
#include "ieee.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
// The minimal and maximal target exponent define the range of w's binary
|
||||
// exponent, where 'w' is the result of multiplying the input by a cached power
|
||||
// of ten.
|
||||
//
|
||||
// A different range might be chosen on a different platform, to optimize digit
|
||||
// generation, but a smaller range requires more powers of ten to be cached.
|
||||
static const int kMinimalTargetExponent = -60;
|
||||
static const int kMaximalTargetExponent = -32;
|
||||
|
||||
|
||||
// Adjusts the last digit of the generated number, and screens out generated
|
||||
// solutions that may be inaccurate. A solution may be inaccurate if it is
|
||||
// outside the safe interval, or if we cannot prove that it is closer to the
|
||||
// input than a neighboring representation of the same length.
|
||||
//
|
||||
// Input: * buffer containing the digits of too_high / 10^kappa
|
||||
// * the buffer's length
|
||||
// * distance_too_high_w == (too_high - w).f() * unit
|
||||
// * unsafe_interval == (too_high - too_low).f() * unit
|
||||
// * rest = (too_high - buffer * 10^kappa).f() * unit
|
||||
// * ten_kappa = 10^kappa * unit
|
||||
// * unit = the common multiplier
|
||||
// Output: returns true if the buffer is guaranteed to contain the closest
|
||||
// representable number to the input.
|
||||
// Modifies the generated digits in the buffer to approach (round towards) w.
|
||||
static bool RoundWeed(Vector<char> buffer,
|
||||
int length,
|
||||
uint64_t distance_too_high_w,
|
||||
uint64_t unsafe_interval,
|
||||
uint64_t rest,
|
||||
uint64_t ten_kappa,
|
||||
uint64_t unit) {
|
||||
uint64_t small_distance = distance_too_high_w - unit;
|
||||
uint64_t big_distance = distance_too_high_w + unit;
|
||||
// Let w_low = too_high - big_distance, and
|
||||
// w_high = too_high - small_distance.
|
||||
// Note: w_low < w < w_high
|
||||
//
|
||||
// The real w (* unit) must lie somewhere inside the interval
|
||||
// ]w_low; w_high[ (often written as "(w_low; w_high)")
|
||||
|
||||
// Basically the buffer currently contains a number in the unsafe interval
|
||||
// ]too_low; too_high[ with too_low < w < too_high
|
||||
//
|
||||
// too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||
// ^v 1 unit ^ ^ ^ ^
|
||||
// boundary_high --------------------- . . . .
|
||||
// ^v 1 unit . . . .
|
||||
// - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . .
|
||||
// . . ^ . .
|
||||
// . big_distance . . .
|
||||
// . . . . rest
|
||||
// small_distance . . . .
|
||||
// v . . . .
|
||||
// w_high - - - - - - - - - - - - - - - - - - . . . .
|
||||
// ^v 1 unit . . . .
|
||||
// w ---------------------------------------- . . . .
|
||||
// ^v 1 unit v . . .
|
||||
// w_low - - - - - - - - - - - - - - - - - - - - - . . .
|
||||
// . . v
|
||||
// buffer --------------------------------------------------+-------+--------
|
||||
// . .
|
||||
// safe_interval .
|
||||
// v .
|
||||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .
|
||||
// ^v 1 unit .
|
||||
// boundary_low ------------------------- unsafe_interval
|
||||
// ^v 1 unit v
|
||||
// too_low - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||
//
|
||||
//
|
||||
// Note that the value of buffer could lie anywhere inside the range too_low
|
||||
// to too_high.
|
||||
//
|
||||
// boundary_low, boundary_high and w are approximations of the real boundaries
|
||||
// and v (the input number). They are guaranteed to be precise up to one unit.
|
||||
// In fact the error is guaranteed to be strictly less than one unit.
|
||||
//
|
||||
// Anything that lies outside the unsafe interval is guaranteed not to round
|
||||
// to v when read again.
|
||||
// Anything that lies inside the safe interval is guaranteed to round to v
|
||||
// when read again.
|
||||
// If the number inside the buffer lies inside the unsafe interval but not
|
||||
// inside the safe interval then we simply do not know and bail out (returning
|
||||
// false).
|
||||
//
|
||||
// Similarly we have to take into account the imprecision of 'w' when finding
|
||||
// the closest representation of 'w'. If we have two potential
|
||||
// representations, and one is closer to both w_low and w_high, then we know
|
||||
// it is closer to the actual value v.
|
||||
//
|
||||
// By generating the digits of too_high we got the largest (closest to
|
||||
// too_high) buffer that is still in the unsafe interval. In the case where
|
||||
// w_high < buffer < too_high we try to decrement the buffer.
|
||||
// This way the buffer approaches (rounds towards) w.
|
||||
// There are 3 conditions that stop the decrementation process:
|
||||
// 1) the buffer is already below w_high
|
||||
// 2) decrementing the buffer would make it leave the unsafe interval
|
||||
// 3) decrementing the buffer would yield a number below w_high and farther
|
||||
// away than the current number. In other words:
|
||||
// (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
|
||||
// Instead of using the buffer directly we use its distance to too_high.
|
||||
// Conceptually rest ~= too_high - buffer
|
||||
// We need to do the following tests in this order to avoid over- and
|
||||
// underflows.
|
||||
ASSERT(rest <= unsafe_interval);
|
||||
while (rest < small_distance && // Negated condition 1
|
||||
unsafe_interval - rest >= ten_kappa && // Negated condition 2
|
||||
(rest + ten_kappa < small_distance || // buffer{-1} > w_high
|
||||
small_distance - rest >= rest + ten_kappa - small_distance)) {
|
||||
buffer[length - 1]--;
|
||||
rest += ten_kappa;
|
||||
}
|
||||
|
||||
// We have approached w+ as much as possible. We now test if approaching w-
|
||||
// would require changing the buffer. If yes, then we have two possible
|
||||
// representations close to w, but we cannot decide which one is closer.
|
||||
if (rest < big_distance &&
|
||||
unsafe_interval - rest >= ten_kappa &&
|
||||
(rest + ten_kappa < big_distance ||
|
||||
big_distance - rest > rest + ten_kappa - big_distance)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Weeding test.
|
||||
// The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
|
||||
// Since too_low = too_high - unsafe_interval this is equivalent to
|
||||
// [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
|
||||
// Conceptually we have: rest ~= too_high - buffer
|
||||
return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
|
||||
}
|
||||
|
||||
|
||||
// Rounds the buffer upwards if the result is closer to v by possibly adding
|
||||
// 1 to the buffer. If the precision of the calculation is not sufficient to
|
||||
// round correctly, return false.
|
||||
// The rounding might shift the whole buffer in which case the kappa is
|
||||
// adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
|
||||
//
|
||||
// If 2*rest > ten_kappa then the buffer needs to be round up.
|
||||
// rest can have an error of +/- 1 unit. This function accounts for the
|
||||
// imprecision and returns false, if the rounding direction cannot be
|
||||
// unambiguously determined.
|
||||
//
|
||||
// Precondition: rest < ten_kappa.
|
||||
static bool RoundWeedCounted(Vector<char> buffer,
|
||||
int length,
|
||||
uint64_t rest,
|
||||
uint64_t ten_kappa,
|
||||
uint64_t unit,
|
||||
int* kappa) {
|
||||
ASSERT(rest < ten_kappa);
|
||||
// The following tests are done in a specific order to avoid overflows. They
|
||||
// will work correctly with any uint64 values of rest < ten_kappa and unit.
|
||||
//
|
||||
// If the unit is too big, then we don't know which way to round. For example
|
||||
// a unit of 50 means that the real number lies within rest +/- 50. If
|
||||
// 10^kappa == 40 then there is no way to tell which way to round.
|
||||
if (unit >= ten_kappa) return false;
|
||||
// Even if unit is just half the size of 10^kappa we are already completely
|
||||
// lost. (And after the previous test we know that the expression will not
|
||||
// over/underflow.)
|
||||
if (ten_kappa - unit <= unit) return false;
|
||||
// If 2 * (rest + unit) <= 10^kappa we can safely round down.
|
||||
if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) {
|
||||
return true;
|
||||
}
|
||||
// If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
|
||||
if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) {
|
||||
// Increment the last digit recursively until we find a non '9' digit.
|
||||
buffer[length - 1]++;
|
||||
for (int i = length - 1; i > 0; --i) {
|
||||
if (buffer[i] != '0' + 10) break;
|
||||
buffer[i] = '0';
|
||||
buffer[i - 1]++;
|
||||
}
|
||||
// If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
|
||||
// exception of the first digit all digits are now '0'. Simply switch the
|
||||
// first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
|
||||
// the power (the kappa) is increased.
|
||||
if (buffer[0] == '0' + 10) {
|
||||
buffer[0] = '1';
|
||||
(*kappa) += 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Returns the biggest power of ten that is less than or equal to the given
|
||||
// number. We furthermore receive the maximum number of bits 'number' has.
|
||||
//
|
||||
// Returns power == 10^(exponent_plus_one-1) such that
|
||||
// power <= number < power * 10.
|
||||
// If number_bits == 0 then 0^(0-1) is returned.
|
||||
// The number of bits must be <= 32.
|
||||
// Precondition: number < (1 << (number_bits + 1)).
|
||||
|
||||
// Inspired by the method for finding an integer log base 10 from here:
|
||||
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
|
||||
static unsigned int const kSmallPowersOfTen[] =
|
||||
{0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
|
||||
1000000000};
|
||||
|
||||
static void BiggestPowerTen(uint32_t number,
|
||||
int number_bits,
|
||||
uint32_t* power,
|
||||
int* exponent_plus_one) {
|
||||
ASSERT(number < (1u << (number_bits + 1)));
|
||||
// 1233/4096 is approximately 1/lg(10).
|
||||
int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12);
|
||||
// We increment to skip over the first entry in the kPowersOf10 table.
|
||||
// Note: kPowersOf10[i] == 10^(i-1).
|
||||
exponent_plus_one_guess++;
|
||||
// We don't have any guarantees that 2^number_bits <= number.
|
||||
if (number < kSmallPowersOfTen[exponent_plus_one_guess]) {
|
||||
exponent_plus_one_guess--;
|
||||
}
|
||||
*power = kSmallPowersOfTen[exponent_plus_one_guess];
|
||||
*exponent_plus_one = exponent_plus_one_guess;
|
||||
}
|
||||
|
||||
// Generates the digits of input number w.
|
||||
// w is a floating-point number (DiyFp), consisting of a significand and an
|
||||
// exponent. Its exponent is bounded by kMinimalTargetExponent and
|
||||
// kMaximalTargetExponent.
|
||||
// Hence -60 <= w.e() <= -32.
|
||||
//
|
||||
// Returns false if it fails, in which case the generated digits in the buffer
|
||||
// should not be used.
|
||||
// Preconditions:
|
||||
// * low, w and high are correct up to 1 ulp (unit in the last place). That
|
||||
// is, their error must be less than a unit of their last digits.
|
||||
// * low.e() == w.e() == high.e()
|
||||
// * low < w < high, and taking into account their error: low~ <= high~
|
||||
// * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
|
||||
// Postconditions: returns false if procedure fails.
|
||||
// otherwise:
|
||||
// * buffer is not null-terminated, but len contains the number of digits.
|
||||
// * buffer contains the shortest possible decimal digit-sequence
|
||||
// such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
|
||||
// correct values of low and high (without their error).
|
||||
// * if more than one decimal representation gives the minimal number of
|
||||
// decimal digits then the one closest to W (where W is the correct value
|
||||
// of w) is chosen.
|
||||
// Remark: this procedure takes into account the imprecision of its input
|
||||
// numbers. If the precision is not enough to guarantee all the postconditions
|
||||
// then false is returned. This usually happens rarely (~0.5%).
|
||||
//
|
||||
// Say, for the sake of example, that
|
||||
// w.e() == -48, and w.f() == 0x1234567890abcdef
|
||||
// w's value can be computed by w.f() * 2^w.e()
|
||||
// We can obtain w's integral digits by simply shifting w.f() by -w.e().
|
||||
// -> w's integral part is 0x1234
|
||||
// w's fractional part is therefore 0x567890abcdef.
|
||||
// Printing w's integral part is easy (simply print 0x1234 in decimal).
|
||||
// In order to print its fraction we repeatedly multiply the fraction by 10 and
|
||||
// get each digit. Example the first digit after the point would be computed by
|
||||
// (0x567890abcdef * 10) >> 48. -> 3
|
||||
// The whole thing becomes slightly more complicated because we want to stop
|
||||
// once we have enough digits. That is, once the digits inside the buffer
|
||||
// represent 'w' we can stop. Everything inside the interval low - high
|
||||
// represents w. However we have to pay attention to low, high and w's
|
||||
// imprecision.
|
||||
static bool DigitGen(DiyFp low,
|
||||
DiyFp w,
|
||||
DiyFp high,
|
||||
Vector<char> buffer,
|
||||
int* length,
|
||||
int* kappa) {
|
||||
ASSERT(low.e() == w.e() && w.e() == high.e());
|
||||
ASSERT(low.f() + 1 <= high.f() - 1);
|
||||
ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
|
||||
// low, w and high are imprecise, but by less than one ulp (unit in the last
|
||||
// place).
|
||||
// If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
|
||||
// the new numbers are outside of the interval we want the final
|
||||
// representation to lie in.
|
||||
// Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
|
||||
// numbers that are certain to lie in the interval. We will use this fact
|
||||
// later on.
|
||||
// We will now start by generating the digits within the uncertain
|
||||
// interval. Later we will weed out representations that lie outside the safe
|
||||
// interval and thus _might_ lie outside the correct interval.
|
||||
uint64_t unit = 1;
|
||||
DiyFp too_low = DiyFp(low.f() - unit, low.e());
|
||||
DiyFp too_high = DiyFp(high.f() + unit, high.e());
|
||||
// too_low and too_high are guaranteed to lie outside the interval we want the
|
||||
// generated number in.
|
||||
DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low);
|
||||
// We now cut the input number into two parts: the integral digits and the
|
||||
// fractionals. We will not write any decimal separator though, but adapt
|
||||
// kappa instead.
|
||||
// Reminder: we are currently computing the digits (stored inside the buffer)
|
||||
// such that: too_low < buffer * 10^kappa < too_high
|
||||
// We use too_high for the digit_generation and stop as soon as possible.
|
||||
// If we stop early we effectively round down.
|
||||
DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
|
||||
// Division by one is a shift.
|
||||
uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e());
|
||||
// Modulo by one is an and.
|
||||
uint64_t fractionals = too_high.f() & (one.f() - 1);
|
||||
uint32_t divisor;
|
||||
int divisor_exponent_plus_one;
|
||||
BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
|
||||
&divisor, &divisor_exponent_plus_one);
|
||||
*kappa = divisor_exponent_plus_one;
|
||||
*length = 0;
|
||||
// Loop invariant: buffer = too_high / 10^kappa (integer division)
|
||||
// The invariant holds for the first iteration: kappa has been initialized
|
||||
// with the divisor exponent + 1. And the divisor is the biggest power of ten
|
||||
// that is smaller than integrals.
|
||||
while (*kappa > 0) {
|
||||
int digit = integrals / divisor;
|
||||
ASSERT(digit <= 9);
|
||||
buffer[*length] = static_cast<char>('0' + digit);
|
||||
(*length)++;
|
||||
integrals %= divisor;
|
||||
(*kappa)--;
|
||||
// Note that kappa now equals the exponent of the divisor and that the
|
||||
// invariant thus holds again.
|
||||
uint64_t rest =
|
||||
(static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
|
||||
// Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
|
||||
// Reminder: unsafe_interval.e() == one.e()
|
||||
if (rest < unsafe_interval.f()) {
|
||||
// Rounding down (by not emitting the remaining digits) yields a number
|
||||
// that lies within the unsafe interval.
|
||||
return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(),
|
||||
unsafe_interval.f(), rest,
|
||||
static_cast<uint64_t>(divisor) << -one.e(), unit);
|
||||
}
|
||||
divisor /= 10;
|
||||
}
|
||||
|
||||
// The integrals have been generated. We are at the point of the decimal
|
||||
// separator. In the following loop we simply multiply the remaining digits by
|
||||
// 10 and divide by one. We just need to pay attention to multiply associated
|
||||
// data (like the interval or 'unit'), too.
|
||||
// Note that the multiplication by 10 does not overflow, because w.e >= -60
|
||||
// and thus one.e >= -60.
|
||||
ASSERT(one.e() >= -60);
|
||||
ASSERT(fractionals < one.f());
|
||||
ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
|
||||
for (;;) {
|
||||
fractionals *= 10;
|
||||
unit *= 10;
|
||||
unsafe_interval.set_f(unsafe_interval.f() * 10);
|
||||
// Integer division by one.
|
||||
int digit = static_cast<int>(fractionals >> -one.e());
|
||||
ASSERT(digit <= 9);
|
||||
buffer[*length] = static_cast<char>('0' + digit);
|
||||
(*length)++;
|
||||
fractionals &= one.f() - 1; // Modulo by one.
|
||||
(*kappa)--;
|
||||
if (fractionals < unsafe_interval.f()) {
|
||||
return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit,
|
||||
unsafe_interval.f(), fractionals, one.f(), unit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Generates (at most) requested_digits digits of input number w.
|
||||
// w is a floating-point number (DiyFp), consisting of a significand and an
|
||||
// exponent. Its exponent is bounded by kMinimalTargetExponent and
|
||||
// kMaximalTargetExponent.
|
||||
// Hence -60 <= w.e() <= -32.
|
||||
//
|
||||
// Returns false if it fails, in which case the generated digits in the buffer
|
||||
// should not be used.
|
||||
// Preconditions:
|
||||
// * w is correct up to 1 ulp (unit in the last place). That
|
||||
// is, its error must be strictly less than a unit of its last digit.
|
||||
// * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
|
||||
//
|
||||
// Postconditions: returns false if procedure fails.
|
||||
// otherwise:
|
||||
// * buffer is not null-terminated, but length contains the number of
|
||||
// digits.
|
||||
// * the representation in buffer is the most precise representation of
|
||||
// requested_digits digits.
|
||||
// * buffer contains at most requested_digits digits of w. If there are less
|
||||
// than requested_digits digits then some trailing '0's have been removed.
|
||||
// * kappa is such that
|
||||
// w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
|
||||
//
|
||||
// Remark: This procedure takes into account the imprecision of its input
|
||||
// numbers. If the precision is not enough to guarantee all the postconditions
|
||||
// then false is returned. This usually happens rarely, but the failure-rate
|
||||
// increases with higher requested_digits.
|
||||
static bool DigitGenCounted(DiyFp w,
|
||||
int requested_digits,
|
||||
Vector<char> buffer,
|
||||
int* length,
|
||||
int* kappa) {
|
||||
ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
|
||||
ASSERT(kMinimalTargetExponent >= -60);
|
||||
ASSERT(kMaximalTargetExponent <= -32);
|
||||
// w is assumed to have an error less than 1 unit. Whenever w is scaled we
|
||||
// also scale its error.
|
||||
uint64_t w_error = 1;
|
||||
// We cut the input number into two parts: the integral digits and the
|
||||
// fractional digits. We don't emit any decimal separator, but adapt kappa
|
||||
// instead. Example: instead of writing "1.2" we put "12" into the buffer and
|
||||
// increase kappa by 1.
|
||||
DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
|
||||
// Division by one is a shift.
|
||||
uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e());
|
||||
// Modulo by one is an and.
|
||||
uint64_t fractionals = w.f() & (one.f() - 1);
|
||||
uint32_t divisor;
|
||||
int divisor_exponent_plus_one;
|
||||
BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
|
||||
&divisor, &divisor_exponent_plus_one);
|
||||
*kappa = divisor_exponent_plus_one;
|
||||
*length = 0;
|
||||
|
||||
// Loop invariant: buffer = w / 10^kappa (integer division)
|
||||
// The invariant holds for the first iteration: kappa has been initialized
|
||||
// with the divisor exponent + 1. And the divisor is the biggest power of ten
|
||||
// that is smaller than 'integrals'.
|
||||
while (*kappa > 0) {
|
||||
int digit = integrals / divisor;
|
||||
ASSERT(digit <= 9);
|
||||
buffer[*length] = static_cast<char>('0' + digit);
|
||||
(*length)++;
|
||||
requested_digits--;
|
||||
integrals %= divisor;
|
||||
(*kappa)--;
|
||||
// Note that kappa now equals the exponent of the divisor and that the
|
||||
// invariant thus holds again.
|
||||
if (requested_digits == 0) break;
|
||||
divisor /= 10;
|
||||
}
|
||||
|
||||
if (requested_digits == 0) {
|
||||
uint64_t rest =
|
||||
(static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
|
||||
return RoundWeedCounted(buffer, *length, rest,
|
||||
static_cast<uint64_t>(divisor) << -one.e(), w_error,
|
||||
kappa);
|
||||
}
|
||||
|
||||
// The integrals have been generated. We are at the point of the decimal
|
||||
// separator. In the following loop we simply multiply the remaining digits by
|
||||
// 10 and divide by one. We just need to pay attention to multiply associated
|
||||
// data (the 'unit'), too.
|
||||
// Note that the multiplication by 10 does not overflow, because w.e >= -60
|
||||
// and thus one.e >= -60.
|
||||
ASSERT(one.e() >= -60);
|
||||
ASSERT(fractionals < one.f());
|
||||
ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
|
||||
while (requested_digits > 0 && fractionals > w_error) {
|
||||
fractionals *= 10;
|
||||
w_error *= 10;
|
||||
// Integer division by one.
|
||||
int digit = static_cast<int>(fractionals >> -one.e());
|
||||
ASSERT(digit <= 9);
|
||||
buffer[*length] = static_cast<char>('0' + digit);
|
||||
(*length)++;
|
||||
requested_digits--;
|
||||
fractionals &= one.f() - 1; // Modulo by one.
|
||||
(*kappa)--;
|
||||
}
|
||||
if (requested_digits != 0) return false;
|
||||
return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error,
|
||||
kappa);
|
||||
}
|
||||
|
||||
|
||||
// Provides a decimal representation of v.
|
||||
// Returns true if it succeeds, otherwise the result cannot be trusted.
|
||||
// There will be *length digits inside the buffer (not null-terminated).
|
||||
// If the function returns true then
|
||||
// v == (double) (buffer * 10^decimal_exponent).
|
||||
// The digits in the buffer are the shortest representation possible: no
|
||||
// 0.09999999999999999 instead of 0.1. The shorter representation will even be
|
||||
// chosen even if the longer one would be closer to v.
|
||||
// The last digit will be closest to the actual v. That is, even if several
|
||||
// digits might correctly yield 'v' when read again, the closest will be
|
||||
// computed.
|
||||
static bool Grisu3(double v,
|
||||
FastDtoaMode mode,
|
||||
Vector<char> buffer,
|
||||
int* length,
|
||||
int* decimal_exponent) {
|
||||
DiyFp w = Double(v).AsNormalizedDiyFp();
|
||||
// boundary_minus and boundary_plus are the boundaries between v and its
|
||||
// closest floating-point neighbors. Any number strictly between
|
||||
// boundary_minus and boundary_plus will round to v when convert to a double.
|
||||
// Grisu3 will never output representations that lie exactly on a boundary.
|
||||
DiyFp boundary_minus, boundary_plus;
|
||||
if (mode == FAST_DTOA_SHORTEST) {
|
||||
Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
|
||||
} else {
|
||||
ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE);
|
||||
float single_v = static_cast<float>(v);
|
||||
Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
|
||||
}
|
||||
ASSERT(boundary_plus.e() == w.e());
|
||||
DiyFp ten_mk; // Cached power of ten: 10^-k
|
||||
int mk; // -k
|
||||
int ten_mk_minimal_binary_exponent =
|
||||
kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
|
||||
int ten_mk_maximal_binary_exponent =
|
||||
kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
|
||||
PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
|
||||
ten_mk_minimal_binary_exponent,
|
||||
ten_mk_maximal_binary_exponent,
|
||||
&ten_mk, &mk);
|
||||
ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
|
||||
DiyFp::kSignificandSize) &&
|
||||
(kMaximalTargetExponent >= w.e() + ten_mk.e() +
|
||||
DiyFp::kSignificandSize));
|
||||
// Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
|
||||
// 64 bit significand and ten_mk is thus only precise up to 64 bits.
|
||||
|
||||
// The DiyFp::Times procedure rounds its result, and ten_mk is approximated
|
||||
// too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
|
||||
// off by a small amount.
|
||||
// In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
|
||||
// In other words: let f = scaled_w.f() and e = scaled_w.e(), then
|
||||
// (f-1) * 2^e < w*10^k < (f+1) * 2^e
|
||||
DiyFp scaled_w = DiyFp::Times(w, ten_mk);
|
||||
ASSERT(scaled_w.e() ==
|
||||
boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
|
||||
// In theory it would be possible to avoid some recomputations by computing
|
||||
// the difference between w and boundary_minus/plus (a power of 2) and to
|
||||
// compute scaled_boundary_minus/plus by subtracting/adding from
|
||||
// scaled_w. However the code becomes much less readable and the speed
|
||||
// enhancements are not terriffic.
|
||||
DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
|
||||
DiyFp scaled_boundary_plus = DiyFp::Times(boundary_plus, ten_mk);
|
||||
|
||||
// DigitGen will generate the digits of scaled_w. Therefore we have
|
||||
// v == (double) (scaled_w * 10^-mk).
|
||||
// Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
|
||||
// integer than it will be updated. For instance if scaled_w == 1.23 then
|
||||
// the buffer will be filled with "123" und the decimal_exponent will be
|
||||
// decreased by 2.
|
||||
int kappa;
|
||||
bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
|
||||
buffer, length, &kappa);
|
||||
*decimal_exponent = -mk + kappa;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// The "counted" version of grisu3 (see above) only generates requested_digits
|
||||
// number of digits. This version does not generate the shortest representation,
|
||||
// and with enough requested digits 0.1 will at some point print as 0.9999999...
|
||||
// Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
|
||||
// therefore the rounding strategy for halfway cases is irrelevant.
|
||||
static bool Grisu3Counted(double v,
|
||||
int requested_digits,
|
||||
Vector<char> buffer,
|
||||
int* length,
|
||||
int* decimal_exponent) {
|
||||
DiyFp w = Double(v).AsNormalizedDiyFp();
|
||||
DiyFp ten_mk; // Cached power of ten: 10^-k
|
||||
int mk; // -k
|
||||
int ten_mk_minimal_binary_exponent =
|
||||
kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
|
||||
int ten_mk_maximal_binary_exponent =
|
||||
kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
|
||||
PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
|
||||
ten_mk_minimal_binary_exponent,
|
||||
ten_mk_maximal_binary_exponent,
|
||||
&ten_mk, &mk);
|
||||
ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
|
||||
DiyFp::kSignificandSize) &&
|
||||
(kMaximalTargetExponent >= w.e() + ten_mk.e() +
|
||||
DiyFp::kSignificandSize));
|
||||
// Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
|
||||
// 64 bit significand and ten_mk is thus only precise up to 64 bits.
|
||||
|
||||
// The DiyFp::Times procedure rounds its result, and ten_mk is approximated
|
||||
// too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
|
||||
// off by a small amount.
|
||||
// In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
|
||||
// In other words: let f = scaled_w.f() and e = scaled_w.e(), then
|
||||
// (f-1) * 2^e < w*10^k < (f+1) * 2^e
|
||||
DiyFp scaled_w = DiyFp::Times(w, ten_mk);
|
||||
|
||||
// We now have (double) (scaled_w * 10^-mk).
|
||||
// DigitGen will generate the first requested_digits digits of scaled_w and
|
||||
// return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
|
||||
// will not always be exactly the same since DigitGenCounted only produces a
|
||||
// limited number of digits.)
|
||||
int kappa;
|
||||
bool result = DigitGenCounted(scaled_w, requested_digits,
|
||||
buffer, length, &kappa);
|
||||
*decimal_exponent = -mk + kappa;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
bool FastDtoa(double v,
|
||||
FastDtoaMode mode,
|
||||
int requested_digits,
|
||||
Vector<char> buffer,
|
||||
int* length,
|
||||
int* decimal_point) {
|
||||
ASSERT(v > 0);
|
||||
ASSERT(!Double(v).IsSpecial());
|
||||
|
||||
bool result = false;
|
||||
int decimal_exponent = 0;
|
||||
switch (mode) {
|
||||
case FAST_DTOA_SHORTEST:
|
||||
case FAST_DTOA_SHORTEST_SINGLE:
|
||||
result = Grisu3(v, mode, buffer, length, &decimal_exponent);
|
||||
break;
|
||||
case FAST_DTOA_PRECISION:
|
||||
result = Grisu3Counted(v, requested_digits,
|
||||
buffer, length, &decimal_exponent);
|
||||
break;
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
if (result) {
|
||||
*decimal_point = *length + decimal_exponent;
|
||||
buffer[*length] = '\0';
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace double_conversion
|
|
@ -1,88 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#ifndef DOUBLE_CONVERSION_FAST_DTOA_H_
|
||||
#define DOUBLE_CONVERSION_FAST_DTOA_H_
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
enum FastDtoaMode {
|
||||
// Computes the shortest representation of the given input. The returned
|
||||
// result will be the most accurate number of this length. Longer
|
||||
// representations might be more accurate.
|
||||
FAST_DTOA_SHORTEST,
|
||||
// Same as FAST_DTOA_SHORTEST but for single-precision floats.
|
||||
FAST_DTOA_SHORTEST_SINGLE,
|
||||
// Computes a representation where the precision (number of digits) is
|
||||
// given as input. The precision is independent of the decimal point.
|
||||
FAST_DTOA_PRECISION
|
||||
};
|
||||
|
||||
// FastDtoa will produce at most kFastDtoaMaximalLength digits. This does not
|
||||
// include the terminating '\0' character.
|
||||
static const int kFastDtoaMaximalLength = 17;
|
||||
// Same for single-precision numbers.
|
||||
static const int kFastDtoaMaximalSingleLength = 9;
|
||||
|
||||
// Provides a decimal representation of v.
|
||||
// The result should be interpreted as buffer * 10^(point - length).
|
||||
//
|
||||
// Precondition:
|
||||
// * v must be a strictly positive finite double.
|
||||
//
|
||||
// Returns true if it succeeds, otherwise the result can not be trusted.
|
||||
// There will be *length digits inside the buffer followed by a null terminator.
|
||||
// If the function returns true and mode equals
|
||||
// - FAST_DTOA_SHORTEST, then
|
||||
// the parameter requested_digits is ignored.
|
||||
// The result satisfies
|
||||
// v == (double) (buffer * 10^(point - length)).
|
||||
// The digits in the buffer are the shortest representation possible. E.g.
|
||||
// if 0.099999999999 and 0.1 represent the same double then "1" is returned
|
||||
// with point = 0.
|
||||
// The last digit will be closest to the actual v. That is, even if several
|
||||
// digits might correctly yield 'v' when read again, the buffer will contain
|
||||
// the one closest to v.
|
||||
// - FAST_DTOA_PRECISION, then
|
||||
// the buffer contains requested_digits digits.
|
||||
// the difference v - (buffer * 10^(point-length)) is closest to zero for
|
||||
// all possible representations of requested_digits digits.
|
||||
// If there are two values that are equally close, then FastDtoa returns
|
||||
// false.
|
||||
// For both modes the buffer must be large enough to hold the result.
|
||||
bool FastDtoa(double d,
|
||||
FastDtoaMode mode,
|
||||
int requested_digits,
|
||||
Vector<char> buffer,
|
||||
int* length,
|
||||
int* decimal_point);
|
||||
|
||||
} // namespace double_conversion
|
||||
|
||||
#endif // DOUBLE_CONVERSION_FAST_DTOA_H_
|
|
@ -1,404 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#include <math.h>
|
||||
|
||||
#include "fixed-dtoa.h"
|
||||
#include "ieee.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
// Represents a 128bit type. This class should be replaced by a native type on
|
||||
// platforms that support 128bit integers.
|
||||
class UInt128 {
|
||||
public:
|
||||
UInt128() : high_bits_(0), low_bits_(0) { }
|
||||
UInt128(uint64_t high, uint64_t low) : high_bits_(high), low_bits_(low) { }
|
||||
|
||||
void Multiply(uint32_t multiplicand) {
|
||||
uint64_t accumulator;
|
||||
|
||||
accumulator = (low_bits_ & kMask32) * multiplicand;
|
||||
uint32_t part = static_cast<uint32_t>(accumulator & kMask32);
|
||||
accumulator >>= 32;
|
||||
accumulator = accumulator + (low_bits_ >> 32) * multiplicand;
|
||||
low_bits_ = (accumulator << 32) + part;
|
||||
accumulator >>= 32;
|
||||
accumulator = accumulator + (high_bits_ & kMask32) * multiplicand;
|
||||
part = static_cast<uint32_t>(accumulator & kMask32);
|
||||
accumulator >>= 32;
|
||||
accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
|
||||
high_bits_ = (accumulator << 32) + part;
|
||||
ASSERT((accumulator >> 32) == 0);
|
||||
}
|
||||
|
||||
void Shift(int shift_amount) {
|
||||
ASSERT(-64 <= shift_amount && shift_amount <= 64);
|
||||
if (shift_amount == 0) {
|
||||
return;
|
||||
} else if (shift_amount == -64) {
|
||||
high_bits_ = low_bits_;
|
||||
low_bits_ = 0;
|
||||
} else if (shift_amount == 64) {
|
||||
low_bits_ = high_bits_;
|
||||
high_bits_ = 0;
|
||||
} else if (shift_amount <= 0) {
|
||||
high_bits_ <<= -shift_amount;
|
||||
high_bits_ += low_bits_ >> (64 + shift_amount);
|
||||
low_bits_ <<= -shift_amount;
|
||||
} else {
|
||||
low_bits_ >>= shift_amount;
|
||||
low_bits_ += high_bits_ << (64 - shift_amount);
|
||||
high_bits_ >>= shift_amount;
|
||||
}
|
||||
}
|
||||
|
||||
// Modifies *this to *this MOD (2^power).
|
||||
// Returns *this DIV (2^power).
|
||||
int DivModPowerOf2(int power) {
|
||||
if (power >= 64) {
|
||||
int result = static_cast<int>(high_bits_ >> (power - 64));
|
||||
high_bits_ -= static_cast<uint64_t>(result) << (power - 64);
|
||||
return result;
|
||||
} else {
|
||||
uint64_t part_low = low_bits_ >> power;
|
||||
uint64_t part_high = high_bits_ << (64 - power);
|
||||
int result = static_cast<int>(part_low + part_high);
|
||||
high_bits_ = 0;
|
||||
low_bits_ -= part_low << power;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
bool IsZero() const {
|
||||
return high_bits_ == 0 && low_bits_ == 0;
|
||||
}
|
||||
|
||||
int BitAt(int position) {
|
||||
if (position >= 64) {
|
||||
return static_cast<int>(high_bits_ >> (position - 64)) & 1;
|
||||
} else {
|
||||
return static_cast<int>(low_bits_ >> position) & 1;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static const uint64_t kMask32 = 0xFFFFFFFF;
|
||||
// Value == (high_bits_ << 64) + low_bits_
|
||||
uint64_t high_bits_;
|
||||
uint64_t low_bits_;
|
||||
};
|
||||
|
||||
|
||||
static const int kDoubleSignificandSize = 53; // Includes the hidden bit.
|
||||
|
||||
|
||||
static void FillDigits32FixedLength(uint32_t number, int requested_length,
|
||||
Vector<char> buffer, int* length) {
|
||||
for (int i = requested_length - 1; i >= 0; --i) {
|
||||
buffer[(*length) + i] = '0' + number % 10;
|
||||
number /= 10;
|
||||
}
|
||||
*length += requested_length;
|
||||
}
|
||||
|
||||
|
||||
static void FillDigits32(uint32_t number, Vector<char> buffer, int* length) {
|
||||
int number_length = 0;
|
||||
// We fill the digits in reverse order and exchange them afterwards.
|
||||
while (number != 0) {
|
||||
int digit = number % 10;
|
||||
number /= 10;
|
||||
buffer[(*length) + number_length] = static_cast<char>('0' + digit);
|
||||
number_length++;
|
||||
}
|
||||
// Exchange the digits.
|
||||
int i = *length;
|
||||
int j = *length + number_length - 1;
|
||||
while (i < j) {
|
||||
char tmp = buffer[i];
|
||||
buffer[i] = buffer[j];
|
||||
buffer[j] = tmp;
|
||||
i++;
|
||||
j--;
|
||||
}
|
||||
*length += number_length;
|
||||
}
|
||||
|
||||
|
||||
static void FillDigits64FixedLength(uint64_t number,
|
||||
Vector<char> buffer, int* length) {
|
||||
const uint32_t kTen7 = 10000000;
|
||||
// For efficiency cut the number into 3 uint32_t parts, and print those.
|
||||
uint32_t part2 = static_cast<uint32_t>(number % kTen7);
|
||||
number /= kTen7;
|
||||
uint32_t part1 = static_cast<uint32_t>(number % kTen7);
|
||||
uint32_t part0 = static_cast<uint32_t>(number / kTen7);
|
||||
|
||||
FillDigits32FixedLength(part0, 3, buffer, length);
|
||||
FillDigits32FixedLength(part1, 7, buffer, length);
|
||||
FillDigits32FixedLength(part2, 7, buffer, length);
|
||||
}
|
||||
|
||||
|
||||
static void FillDigits64(uint64_t number, Vector<char> buffer, int* length) {
|
||||
const uint32_t kTen7 = 10000000;
|
||||
// For efficiency cut the number into 3 uint32_t parts, and print those.
|
||||
uint32_t part2 = static_cast<uint32_t>(number % kTen7);
|
||||
number /= kTen7;
|
||||
uint32_t part1 = static_cast<uint32_t>(number % kTen7);
|
||||
uint32_t part0 = static_cast<uint32_t>(number / kTen7);
|
||||
|
||||
if (part0 != 0) {
|
||||
FillDigits32(part0, buffer, length);
|
||||
FillDigits32FixedLength(part1, 7, buffer, length);
|
||||
FillDigits32FixedLength(part2, 7, buffer, length);
|
||||
} else if (part1 != 0) {
|
||||
FillDigits32(part1, buffer, length);
|
||||
FillDigits32FixedLength(part2, 7, buffer, length);
|
||||
} else {
|
||||
FillDigits32(part2, buffer, length);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void RoundUp(Vector<char> buffer, int* length, int* decimal_point) {
|
||||
// An empty buffer represents 0.
|
||||
if (*length == 0) {
|
||||
buffer[0] = '1';
|
||||
*decimal_point = 1;
|
||||
*length = 1;
|
||||
return;
|
||||
}
|
||||
// Round the last digit until we either have a digit that was not '9' or until
|
||||
// we reached the first digit.
|
||||
buffer[(*length) - 1]++;
|
||||
for (int i = (*length) - 1; i > 0; --i) {
|
||||
if (buffer[i] != '0' + 10) {
|
||||
return;
|
||||
}
|
||||
buffer[i] = '0';
|
||||
buffer[i - 1]++;
|
||||
}
|
||||
// If the first digit is now '0' + 10, we would need to set it to '0' and add
|
||||
// a '1' in front. However we reach the first digit only if all following
|
||||
// digits had been '9' before rounding up. Now all trailing digits are '0' and
|
||||
// we simply switch the first digit to '1' and update the decimal-point
|
||||
// (indicating that the point is now one digit to the right).
|
||||
if (buffer[0] == '0' + 10) {
|
||||
buffer[0] = '1';
|
||||
(*decimal_point)++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// The given fractionals number represents a fixed-point number with binary
|
||||
// point at bit (-exponent).
|
||||
// Preconditions:
|
||||
// -128 <= exponent <= 0.
|
||||
// 0 <= fractionals * 2^exponent < 1
|
||||
// The buffer holds the result.
|
||||
// The function will round its result. During the rounding-process digits not
|
||||
// generated by this function might be updated, and the decimal-point variable
|
||||
// might be updated. If this function generates the digits 99 and the buffer
|
||||
// already contained "199" (thus yielding a buffer of "19999") then a
|
||||
// rounding-up will change the contents of the buffer to "20000".
|
||||
static void FillFractionals(uint64_t fractionals, int exponent,
|
||||
int fractional_count, Vector<char> buffer,
|
||||
int* length, int* decimal_point) {
|
||||
ASSERT(-128 <= exponent && exponent <= 0);
|
||||
// 'fractionals' is a fixed-point number, with binary point at bit
|
||||
// (-exponent). Inside the function the non-converted remainder of fractionals
|
||||
// is a fixed-point number, with binary point at bit 'point'.
|
||||
if (-exponent <= 64) {
|
||||
// One 64 bit number is sufficient.
|
||||
ASSERT(fractionals >> 56 == 0);
|
||||
int point = -exponent;
|
||||
for (int i = 0; i < fractional_count; ++i) {
|
||||
if (fractionals == 0) break;
|
||||
// Instead of multiplying by 10 we multiply by 5 and adjust the point
|
||||
// location. This way the fractionals variable will not overflow.
|
||||
// Invariant at the beginning of the loop: fractionals < 2^point.
|
||||
// Initially we have: point <= 64 and fractionals < 2^56
|
||||
// After each iteration the point is decremented by one.
|
||||
// Note that 5^3 = 125 < 128 = 2^7.
|
||||
// Therefore three iterations of this loop will not overflow fractionals
|
||||
// (even without the subtraction at the end of the loop body). At this
|
||||
// time point will satisfy point <= 61 and therefore fractionals < 2^point
|
||||
// and any further multiplication of fractionals by 5 will not overflow.
|
||||
fractionals *= 5;
|
||||
point--;
|
||||
int digit = static_cast<int>(fractionals >> point);
|
||||
ASSERT(digit <= 9);
|
||||
buffer[*length] = static_cast<char>('0' + digit);
|
||||
(*length)++;
|
||||
fractionals -= static_cast<uint64_t>(digit) << point;
|
||||
}
|
||||
// If the first bit after the point is set we have to round up.
|
||||
if (((fractionals >> (point - 1)) & 1) == 1) {
|
||||
RoundUp(buffer, length, decimal_point);
|
||||
}
|
||||
} else { // We need 128 bits.
|
||||
ASSERT(64 < -exponent && -exponent <= 128);
|
||||
UInt128 fractionals128 = UInt128(fractionals, 0);
|
||||
fractionals128.Shift(-exponent - 64);
|
||||
int point = 128;
|
||||
for (int i = 0; i < fractional_count; ++i) {
|
||||
if (fractionals128.IsZero()) break;
|
||||
// As before: instead of multiplying by 10 we multiply by 5 and adjust the
|
||||
// point location.
|
||||
// This multiplication will not overflow for the same reasons as before.
|
||||
fractionals128.Multiply(5);
|
||||
point--;
|
||||
int digit = fractionals128.DivModPowerOf2(point);
|
||||
ASSERT(digit <= 9);
|
||||
buffer[*length] = static_cast<char>('0' + digit);
|
||||
(*length)++;
|
||||
}
|
||||
if (fractionals128.BitAt(point - 1) == 1) {
|
||||
RoundUp(buffer, length, decimal_point);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Removes leading and trailing zeros.
|
||||
// If leading zeros are removed then the decimal point position is adjusted.
|
||||
static void TrimZeros(Vector<char> buffer, int* length, int* decimal_point) {
|
||||
while (*length > 0 && buffer[(*length) - 1] == '0') {
|
||||
(*length)--;
|
||||
}
|
||||
int first_non_zero = 0;
|
||||
while (first_non_zero < *length && buffer[first_non_zero] == '0') {
|
||||
first_non_zero++;
|
||||
}
|
||||
if (first_non_zero != 0) {
|
||||
for (int i = first_non_zero; i < *length; ++i) {
|
||||
buffer[i - first_non_zero] = buffer[i];
|
||||
}
|
||||
*length -= first_non_zero;
|
||||
*decimal_point -= first_non_zero;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool FastFixedDtoa(double v,
|
||||
int fractional_count,
|
||||
Vector<char> buffer,
|
||||
int* length,
|
||||
int* decimal_point) {
|
||||
const uint32_t kMaxUInt32 = 0xFFFFFFFF;
|
||||
uint64_t significand = Double(v).Significand();
|
||||
int exponent = Double(v).Exponent();
|
||||
// v = significand * 2^exponent (with significand a 53bit integer).
|
||||
// If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
|
||||
// don't know how to compute the representation. 2^73 ~= 9.5*10^21.
|
||||
// If necessary this limit could probably be increased, but we don't need
|
||||
// more.
|
||||
if (exponent > 20) return false;
|
||||
if (fractional_count > 20) return false;
|
||||
*length = 0;
|
||||
// At most kDoubleSignificandSize bits of the significand are non-zero.
|
||||
// Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
|
||||
// bits: 0..11*..0xxx..53*..xx
|
||||
if (exponent + kDoubleSignificandSize > 64) {
|
||||
// The exponent must be > 11.
|
||||
//
|
||||
// We know that v = significand * 2^exponent.
|
||||
// And the exponent > 11.
|
||||
// We simplify the task by dividing v by 10^17.
|
||||
// The quotient delivers the first digits, and the remainder fits into a 64
|
||||
// bit number.
|
||||
// Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
|
||||
const uint64_t kFive17 = UINT64_2PART_C(0xB1, A2BC2EC5); // 5^17
|
||||
uint64_t divisor = kFive17;
|
||||
int divisor_power = 17;
|
||||
uint64_t dividend = significand;
|
||||
uint32_t quotient;
|
||||
uint64_t remainder;
|
||||
// Let v = f * 2^e with f == significand and e == exponent.
|
||||
// Then need q (quotient) and r (remainder) as follows:
|
||||
// v = q * 10^17 + r
|
||||
// f * 2^e = q * 10^17 + r
|
||||
// f * 2^e = q * 5^17 * 2^17 + r
|
||||
// If e > 17 then
|
||||
// f * 2^(e-17) = q * 5^17 + r/2^17
|
||||
// else
|
||||
// f = q * 5^17 * 2^(17-e) + r/2^e
|
||||
if (exponent > divisor_power) {
|
||||
// We only allow exponents of up to 20 and therefore (17 - e) <= 3
|
||||
dividend <<= exponent - divisor_power;
|
||||
quotient = static_cast<uint32_t>(dividend / divisor);
|
||||
remainder = (dividend % divisor) << divisor_power;
|
||||
} else {
|
||||
divisor <<= divisor_power - exponent;
|
||||
quotient = static_cast<uint32_t>(dividend / divisor);
|
||||
remainder = (dividend % divisor) << exponent;
|
||||
}
|
||||
FillDigits32(quotient, buffer, length);
|
||||
FillDigits64FixedLength(remainder, buffer, length);
|
||||
*decimal_point = *length;
|
||||
} else if (exponent >= 0) {
|
||||
// 0 <= exponent <= 11
|
||||
significand <<= exponent;
|
||||
FillDigits64(significand, buffer, length);
|
||||
*decimal_point = *length;
|
||||
} else if (exponent > -kDoubleSignificandSize) {
|
||||
// We have to cut the number.
|
||||
uint64_t integrals = significand >> -exponent;
|
||||
uint64_t fractionals = significand - (integrals << -exponent);
|
||||
if (integrals > kMaxUInt32) {
|
||||
FillDigits64(integrals, buffer, length);
|
||||
} else {
|
||||
FillDigits32(static_cast<uint32_t>(integrals), buffer, length);
|
||||
}
|
||||
*decimal_point = *length;
|
||||
FillFractionals(fractionals, exponent, fractional_count,
|
||||
buffer, length, decimal_point);
|
||||
} else if (exponent < -128) {
|
||||
// This configuration (with at most 20 digits) means that all digits must be
|
||||
// 0.
|
||||
ASSERT(fractional_count <= 20);
|
||||
buffer[0] = '\0';
|
||||
*length = 0;
|
||||
*decimal_point = -fractional_count;
|
||||
} else {
|
||||
*decimal_point = 0;
|
||||
FillFractionals(significand, exponent, fractional_count,
|
||||
buffer, length, decimal_point);
|
||||
}
|
||||
TrimZeros(buffer, length, decimal_point);
|
||||
buffer[*length] = '\0';
|
||||
if ((*length) == 0) {
|
||||
// The string is empty and the decimal_point thus has no importance. Mimick
|
||||
// Gay's dtoa and and set it to -fractional_count.
|
||||
*decimal_point = -fractional_count;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace double_conversion
|
|
@ -1,56 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#ifndef DOUBLE_CONVERSION_FIXED_DTOA_H_
|
||||
#define DOUBLE_CONVERSION_FIXED_DTOA_H_
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
// Produces digits necessary to print a given number with
|
||||
// 'fractional_count' digits after the decimal point.
|
||||
// The buffer must be big enough to hold the result plus one terminating null
|
||||
// character.
|
||||
//
|
||||
// The produced digits might be too short in which case the caller has to fill
|
||||
// the gaps with '0's.
|
||||
// Example: FastFixedDtoa(0.001, 5, ...) is allowed to return buffer = "1", and
|
||||
// decimal_point = -2.
|
||||
// Halfway cases are rounded towards +/-Infinity (away from 0). The call
|
||||
// FastFixedDtoa(0.15, 2, ...) thus returns buffer = "2", decimal_point = 0.
|
||||
// The returned buffer may contain digits that would be truncated from the
|
||||
// shortest representation of the input.
|
||||
//
|
||||
// This method only works for some parameters. If it can't handle the input it
|
||||
// returns false. The output is null-terminated when the function succeeds.
|
||||
bool FastFixedDtoa(double v, int fractional_count,
|
||||
Vector<char> buffer, int* length, int* decimal_point);
|
||||
|
||||
} // namespace double_conversion
|
||||
|
||||
#endif // DOUBLE_CONVERSION_FIXED_DTOA_H_
|
|
@ -1,402 +0,0 @@
|
|||
// Copyright 2012 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#ifndef DOUBLE_CONVERSION_DOUBLE_H_
|
||||
#define DOUBLE_CONVERSION_DOUBLE_H_
|
||||
|
||||
#include "diy-fp.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
// We assume that doubles and uint64_t have the same endianness.
|
||||
static uint64_t double_to_uint64(double d) { return BitCast<uint64_t>(d); }
|
||||
static double uint64_to_double(uint64_t d64) { return BitCast<double>(d64); }
|
||||
static uint32_t float_to_uint32(float f) { return BitCast<uint32_t>(f); }
|
||||
static float uint32_to_float(uint32_t d32) { return BitCast<float>(d32); }
|
||||
|
||||
// Helper functions for doubles.
|
||||
class Double {
|
||||
public:
|
||||
static const uint64_t kSignMask = UINT64_2PART_C(0x80000000, 00000000);
|
||||
static const uint64_t kExponentMask = UINT64_2PART_C(0x7FF00000, 00000000);
|
||||
static const uint64_t kSignificandMask = UINT64_2PART_C(0x000FFFFF, FFFFFFFF);
|
||||
static const uint64_t kHiddenBit = UINT64_2PART_C(0x00100000, 00000000);
|
||||
static const int kPhysicalSignificandSize = 52; // Excludes the hidden bit.
|
||||
static const int kSignificandSize = 53;
|
||||
|
||||
Double() : d64_(0) {}
|
||||
explicit Double(double d) : d64_(double_to_uint64(d)) {}
|
||||
explicit Double(uint64_t d64) : d64_(d64) {}
|
||||
explicit Double(DiyFp diy_fp)
|
||||
: d64_(DiyFpToUint64(diy_fp)) {}
|
||||
|
||||
// The value encoded by this Double must be greater or equal to +0.0.
|
||||
// It must not be special (infinity, or NaN).
|
||||
DiyFp AsDiyFp() const {
|
||||
ASSERT(Sign() > 0);
|
||||
ASSERT(!IsSpecial());
|
||||
return DiyFp(Significand(), Exponent());
|
||||
}
|
||||
|
||||
// The value encoded by this Double must be strictly greater than 0.
|
||||
DiyFp AsNormalizedDiyFp() const {
|
||||
ASSERT(value() > 0.0);
|
||||
uint64_t f = Significand();
|
||||
int e = Exponent();
|
||||
|
||||
// The current double could be a denormal.
|
||||
while ((f & kHiddenBit) == 0) {
|
||||
f <<= 1;
|
||||
e--;
|
||||
}
|
||||
// Do the final shifts in one go.
|
||||
f <<= DiyFp::kSignificandSize - kSignificandSize;
|
||||
e -= DiyFp::kSignificandSize - kSignificandSize;
|
||||
return DiyFp(f, e);
|
||||
}
|
||||
|
||||
// Returns the double's bit as uint64.
|
||||
uint64_t AsUint64() const {
|
||||
return d64_;
|
||||
}
|
||||
|
||||
// Returns the next greater double. Returns +infinity on input +infinity.
|
||||
double NextDouble() const {
|
||||
if (d64_ == kInfinity) return Double(kInfinity).value();
|
||||
if (Sign() < 0 && Significand() == 0) {
|
||||
// -0.0
|
||||
return 0.0;
|
||||
}
|
||||
if (Sign() < 0) {
|
||||
return Double(d64_ - 1).value();
|
||||
} else {
|
||||
return Double(d64_ + 1).value();
|
||||
}
|
||||
}
|
||||
|
||||
double PreviousDouble() const {
|
||||
if (d64_ == (kInfinity | kSignMask)) return -Double::Infinity();
|
||||
if (Sign() < 0) {
|
||||
return Double(d64_ + 1).value();
|
||||
} else {
|
||||
if (Significand() == 0) return -0.0;
|
||||
return Double(d64_ - 1).value();
|
||||
}
|
||||
}
|
||||
|
||||
int Exponent() const {
|
||||
if (IsDenormal()) return kDenormalExponent;
|
||||
|
||||
uint64_t d64 = AsUint64();
|
||||
int biased_e =
|
||||
static_cast<int>((d64 & kExponentMask) >> kPhysicalSignificandSize);
|
||||
return biased_e - kExponentBias;
|
||||
}
|
||||
|
||||
uint64_t Significand() const {
|
||||
uint64_t d64 = AsUint64();
|
||||
uint64_t significand = d64 & kSignificandMask;
|
||||
if (!IsDenormal()) {
|
||||
return significand + kHiddenBit;
|
||||
} else {
|
||||
return significand;
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true if the double is a denormal.
|
||||
bool IsDenormal() const {
|
||||
uint64_t d64 = AsUint64();
|
||||
return (d64 & kExponentMask) == 0;
|
||||
}
|
||||
|
||||
// We consider denormals not to be special.
|
||||
// Hence only Infinity and NaN are special.
|
||||
bool IsSpecial() const {
|
||||
uint64_t d64 = AsUint64();
|
||||
return (d64 & kExponentMask) == kExponentMask;
|
||||
}
|
||||
|
||||
bool IsNan() const {
|
||||
uint64_t d64 = AsUint64();
|
||||
return ((d64 & kExponentMask) == kExponentMask) &&
|
||||
((d64 & kSignificandMask) != 0);
|
||||
}
|
||||
|
||||
bool IsInfinite() const {
|
||||
uint64_t d64 = AsUint64();
|
||||
return ((d64 & kExponentMask) == kExponentMask) &&
|
||||
((d64 & kSignificandMask) == 0);
|
||||
}
|
||||
|
||||
int Sign() const {
|
||||
uint64_t d64 = AsUint64();
|
||||
return (d64 & kSignMask) == 0? 1: -1;
|
||||
}
|
||||
|
||||
// Precondition: the value encoded by this Double must be greater or equal
|
||||
// than +0.0.
|
||||
DiyFp UpperBoundary() const {
|
||||
ASSERT(Sign() > 0);
|
||||
return DiyFp(Significand() * 2 + 1, Exponent() - 1);
|
||||
}
|
||||
|
||||
// Computes the two boundaries of this.
|
||||
// The bigger boundary (m_plus) is normalized. The lower boundary has the same
|
||||
// exponent as m_plus.
|
||||
// Precondition: the value encoded by this Double must be greater than 0.
|
||||
void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
|
||||
ASSERT(value() > 0.0);
|
||||
DiyFp v = this->AsDiyFp();
|
||||
DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
|
||||
DiyFp m_minus;
|
||||
if (LowerBoundaryIsCloser()) {
|
||||
m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2);
|
||||
} else {
|
||||
m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1);
|
||||
}
|
||||
m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e()));
|
||||
m_minus.set_e(m_plus.e());
|
||||
*out_m_plus = m_plus;
|
||||
*out_m_minus = m_minus;
|
||||
}
|
||||
|
||||
bool LowerBoundaryIsCloser() const {
|
||||
// The boundary is closer if the significand is of the form f == 2^p-1 then
|
||||
// the lower boundary is closer.
|
||||
// Think of v = 1000e10 and v- = 9999e9.
|
||||
// Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but
|
||||
// at a distance of 1e8.
|
||||
// The only exception is for the smallest normal: the largest denormal is
|
||||
// at the same distance as its successor.
|
||||
// Note: denormals have the same exponent as the smallest normals.
|
||||
bool physical_significand_is_zero = ((AsUint64() & kSignificandMask) == 0);
|
||||
return physical_significand_is_zero && (Exponent() != kDenormalExponent);
|
||||
}
|
||||
|
||||
double value() const { return uint64_to_double(d64_); }
|
||||
|
||||
// Returns the significand size for a given order of magnitude.
|
||||
// If v = f*2^e with 2^p-1 <= f <= 2^p then p+e is v's order of magnitude.
|
||||
// This function returns the number of significant binary digits v will have
|
||||
// once it's encoded into a double. In almost all cases this is equal to
|
||||
// kSignificandSize. The only exceptions are denormals. They start with
|
||||
// leading zeroes and their effective significand-size is hence smaller.
|
||||
static int SignificandSizeForOrderOfMagnitude(int order) {
|
||||
if (order >= (kDenormalExponent + kSignificandSize)) {
|
||||
return kSignificandSize;
|
||||
}
|
||||
if (order <= kDenormalExponent) return 0;
|
||||
return order - kDenormalExponent;
|
||||
}
|
||||
|
||||
static double Infinity() {
|
||||
return Double(kInfinity).value();
|
||||
}
|
||||
|
||||
static double NaN() {
|
||||
return Double(kNaN).value();
|
||||
}
|
||||
|
||||
private:
|
||||
static const int kExponentBias = 0x3FF + kPhysicalSignificandSize;
|
||||
static const int kDenormalExponent = -kExponentBias + 1;
|
||||
static const int kMaxExponent = 0x7FF - kExponentBias;
|
||||
static const uint64_t kInfinity = UINT64_2PART_C(0x7FF00000, 00000000);
|
||||
static const uint64_t kNaN = UINT64_2PART_C(0x7FF80000, 00000000);
|
||||
|
||||
const uint64_t d64_;
|
||||
|
||||
static uint64_t DiyFpToUint64(DiyFp diy_fp) {
|
||||
uint64_t significand = diy_fp.f();
|
||||
int exponent = diy_fp.e();
|
||||
while (significand > kHiddenBit + kSignificandMask) {
|
||||
significand >>= 1;
|
||||
exponent++;
|
||||
}
|
||||
if (exponent >= kMaxExponent) {
|
||||
return kInfinity;
|
||||
}
|
||||
if (exponent < kDenormalExponent) {
|
||||
return 0;
|
||||
}
|
||||
while (exponent > kDenormalExponent && (significand & kHiddenBit) == 0) {
|
||||
significand <<= 1;
|
||||
exponent--;
|
||||
}
|
||||
uint64_t biased_exponent;
|
||||
if (exponent == kDenormalExponent && (significand & kHiddenBit) == 0) {
|
||||
biased_exponent = 0;
|
||||
} else {
|
||||
biased_exponent = static_cast<uint64_t>(exponent + kExponentBias);
|
||||
}
|
||||
return (significand & kSignificandMask) |
|
||||
(biased_exponent << kPhysicalSignificandSize);
|
||||
}
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(Double);
|
||||
};
|
||||
|
||||
class Single {
|
||||
public:
|
||||
static const uint32_t kSignMask = 0x80000000;
|
||||
static const uint32_t kExponentMask = 0x7F800000;
|
||||
static const uint32_t kSignificandMask = 0x007FFFFF;
|
||||
static const uint32_t kHiddenBit = 0x00800000;
|
||||
static const int kPhysicalSignificandSize = 23; // Excludes the hidden bit.
|
||||
static const int kSignificandSize = 24;
|
||||
|
||||
Single() : d32_(0) {}
|
||||
explicit Single(float f) : d32_(float_to_uint32(f)) {}
|
||||
explicit Single(uint32_t d32) : d32_(d32) {}
|
||||
|
||||
// The value encoded by this Single must be greater or equal to +0.0.
|
||||
// It must not be special (infinity, or NaN).
|
||||
DiyFp AsDiyFp() const {
|
||||
ASSERT(Sign() > 0);
|
||||
ASSERT(!IsSpecial());
|
||||
return DiyFp(Significand(), Exponent());
|
||||
}
|
||||
|
||||
// Returns the single's bit as uint64.
|
||||
uint32_t AsUint32() const {
|
||||
return d32_;
|
||||
}
|
||||
|
||||
int Exponent() const {
|
||||
if (IsDenormal()) return kDenormalExponent;
|
||||
|
||||
uint32_t d32 = AsUint32();
|
||||
int biased_e =
|
||||
static_cast<int>((d32 & kExponentMask) >> kPhysicalSignificandSize);
|
||||
return biased_e - kExponentBias;
|
||||
}
|
||||
|
||||
uint32_t Significand() const {
|
||||
uint32_t d32 = AsUint32();
|
||||
uint32_t significand = d32 & kSignificandMask;
|
||||
if (!IsDenormal()) {
|
||||
return significand + kHiddenBit;
|
||||
} else {
|
||||
return significand;
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true if the single is a denormal.
|
||||
bool IsDenormal() const {
|
||||
uint32_t d32 = AsUint32();
|
||||
return (d32 & kExponentMask) == 0;
|
||||
}
|
||||
|
||||
// We consider denormals not to be special.
|
||||
// Hence only Infinity and NaN are special.
|
||||
bool IsSpecial() const {
|
||||
uint32_t d32 = AsUint32();
|
||||
return (d32 & kExponentMask) == kExponentMask;
|
||||
}
|
||||
|
||||
bool IsNan() const {
|
||||
uint32_t d32 = AsUint32();
|
||||
return ((d32 & kExponentMask) == kExponentMask) &&
|
||||
((d32 & kSignificandMask) != 0);
|
||||
}
|
||||
|
||||
bool IsInfinite() const {
|
||||
uint32_t d32 = AsUint32();
|
||||
return ((d32 & kExponentMask) == kExponentMask) &&
|
||||
((d32 & kSignificandMask) == 0);
|
||||
}
|
||||
|
||||
int Sign() const {
|
||||
uint32_t d32 = AsUint32();
|
||||
return (d32 & kSignMask) == 0? 1: -1;
|
||||
}
|
||||
|
||||
// Computes the two boundaries of this.
|
||||
// The bigger boundary (m_plus) is normalized. The lower boundary has the same
|
||||
// exponent as m_plus.
|
||||
// Precondition: the value encoded by this Single must be greater than 0.
|
||||
void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
|
||||
ASSERT(value() > 0.0);
|
||||
DiyFp v = this->AsDiyFp();
|
||||
DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
|
||||
DiyFp m_minus;
|
||||
if (LowerBoundaryIsCloser()) {
|
||||
m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2);
|
||||
} else {
|
||||
m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1);
|
||||
}
|
||||
m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e()));
|
||||
m_minus.set_e(m_plus.e());
|
||||
*out_m_plus = m_plus;
|
||||
*out_m_minus = m_minus;
|
||||
}
|
||||
|
||||
// Precondition: the value encoded by this Single must be greater or equal
|
||||
// than +0.0.
|
||||
DiyFp UpperBoundary() const {
|
||||
ASSERT(Sign() > 0);
|
||||
return DiyFp(Significand() * 2 + 1, Exponent() - 1);
|
||||
}
|
||||
|
||||
bool LowerBoundaryIsCloser() const {
|
||||
// The boundary is closer if the significand is of the form f == 2^p-1 then
|
||||
// the lower boundary is closer.
|
||||
// Think of v = 1000e10 and v- = 9999e9.
|
||||
// Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but
|
||||
// at a distance of 1e8.
|
||||
// The only exception is for the smallest normal: the largest denormal is
|
||||
// at the same distance as its successor.
|
||||
// Note: denormals have the same exponent as the smallest normals.
|
||||
bool physical_significand_is_zero = ((AsUint32() & kSignificandMask) == 0);
|
||||
return physical_significand_is_zero && (Exponent() != kDenormalExponent);
|
||||
}
|
||||
|
||||
float value() const { return uint32_to_float(d32_); }
|
||||
|
||||
static float Infinity() {
|
||||
return Single(kInfinity).value();
|
||||
}
|
||||
|
||||
static float NaN() {
|
||||
return Single(kNaN).value();
|
||||
}
|
||||
|
||||
private:
|
||||
static const int kExponentBias = 0x7F + kPhysicalSignificandSize;
|
||||
static const int kDenormalExponent = -kExponentBias + 1;
|
||||
static const int kMaxExponent = 0xFF - kExponentBias;
|
||||
static const uint32_t kInfinity = 0x7F800000;
|
||||
static const uint32_t kNaN = 0x7FC00000;
|
||||
|
||||
const uint32_t d32_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(Single);
|
||||
};
|
||||
|
||||
} // namespace double_conversion
|
||||
|
||||
#endif // DOUBLE_CONVERSION_DOUBLE_H_
|
|
@ -1,555 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#include <stdarg.h>
|
||||
#include <limits.h>
|
||||
|
||||
#include "strtod.h"
|
||||
#include "bignum.h"
|
||||
#include "cached-powers.h"
|
||||
#include "ieee.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
// 2^53 = 9007199254740992.
|
||||
// Any integer with at most 15 decimal digits will hence fit into a double
|
||||
// (which has a 53bit significand) without loss of precision.
|
||||
static const int kMaxExactDoubleIntegerDecimalDigits = 15;
|
||||
// 2^64 = 18446744073709551616 > 10^19
|
||||
static const int kMaxUint64DecimalDigits = 19;
|
||||
|
||||
// Max double: 1.7976931348623157 x 10^308
|
||||
// Min non-zero double: 4.9406564584124654 x 10^-324
|
||||
// Any x >= 10^309 is interpreted as +infinity.
|
||||
// Any x <= 10^-324 is interpreted as 0.
|
||||
// Note that 2.5e-324 (despite being smaller than the min double) will be read
|
||||
// as non-zero (equal to the min non-zero double).
|
||||
static const int kMaxDecimalPower = 309;
|
||||
static const int kMinDecimalPower = -324;
|
||||
|
||||
// 2^64 = 18446744073709551616
|
||||
static const uint64_t kMaxUint64 = UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF);
|
||||
|
||||
|
||||
static const double exact_powers_of_ten[] = {
|
||||
1.0, // 10^0
|
||||
10.0,
|
||||
100.0,
|
||||
1000.0,
|
||||
10000.0,
|
||||
100000.0,
|
||||
1000000.0,
|
||||
10000000.0,
|
||||
100000000.0,
|
||||
1000000000.0,
|
||||
10000000000.0, // 10^10
|
||||
100000000000.0,
|
||||
1000000000000.0,
|
||||
10000000000000.0,
|
||||
100000000000000.0,
|
||||
1000000000000000.0,
|
||||
10000000000000000.0,
|
||||
100000000000000000.0,
|
||||
1000000000000000000.0,
|
||||
10000000000000000000.0,
|
||||
100000000000000000000.0, // 10^20
|
||||
1000000000000000000000.0,
|
||||
// 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
|
||||
10000000000000000000000.0
|
||||
};
|
||||
static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten);
|
||||
|
||||
// Maximum number of significant digits in the decimal representation.
|
||||
// In fact the value is 772 (see conversions.cc), but to give us some margin
|
||||
// we round up to 780.
|
||||
static const int kMaxSignificantDecimalDigits = 780;
|
||||
|
||||
static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) {
|
||||
for (int i = 0; i < buffer.length(); i++) {
|
||||
if (buffer[i] != '0') {
|
||||
return buffer.SubVector(i, buffer.length());
|
||||
}
|
||||
}
|
||||
return Vector<const char>(buffer.start(), 0);
|
||||
}
|
||||
|
||||
|
||||
static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) {
|
||||
for (int i = buffer.length() - 1; i >= 0; --i) {
|
||||
if (buffer[i] != '0') {
|
||||
return buffer.SubVector(0, i + 1);
|
||||
}
|
||||
}
|
||||
return Vector<const char>(buffer.start(), 0);
|
||||
}
|
||||
|
||||
|
||||
static void CutToMaxSignificantDigits(Vector<const char> buffer,
|
||||
int exponent,
|
||||
char* significant_buffer,
|
||||
int* significant_exponent) {
|
||||
for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) {
|
||||
significant_buffer[i] = buffer[i];
|
||||
}
|
||||
// The input buffer has been trimmed. Therefore the last digit must be
|
||||
// different from '0'.
|
||||
ASSERT(buffer[buffer.length() - 1] != '0');
|
||||
// Set the last digit to be non-zero. This is sufficient to guarantee
|
||||
// correct rounding.
|
||||
significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
|
||||
*significant_exponent =
|
||||
exponent + (buffer.length() - kMaxSignificantDecimalDigits);
|
||||
}
|
||||
|
||||
|
||||
// Trims the buffer and cuts it to at most kMaxSignificantDecimalDigits.
|
||||
// If possible the input-buffer is reused, but if the buffer needs to be
|
||||
// modified (due to cutting), then the input needs to be copied into the
|
||||
// buffer_copy_space.
|
||||
static void TrimAndCut(Vector<const char> buffer, int exponent,
|
||||
char* buffer_copy_space, int space_size,
|
||||
Vector<const char>* trimmed, int* updated_exponent) {
|
||||
Vector<const char> left_trimmed = TrimLeadingZeros(buffer);
|
||||
Vector<const char> right_trimmed = TrimTrailingZeros(left_trimmed);
|
||||
exponent += left_trimmed.length() - right_trimmed.length();
|
||||
if (right_trimmed.length() > kMaxSignificantDecimalDigits) {
|
||||
(void) space_size; // Mark variable as used.
|
||||
ASSERT(space_size >= kMaxSignificantDecimalDigits);
|
||||
CutToMaxSignificantDigits(right_trimmed, exponent,
|
||||
buffer_copy_space, updated_exponent);
|
||||
*trimmed = Vector<const char>(buffer_copy_space,
|
||||
kMaxSignificantDecimalDigits);
|
||||
} else {
|
||||
*trimmed = right_trimmed;
|
||||
*updated_exponent = exponent;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Reads digits from the buffer and converts them to a uint64.
|
||||
// Reads in as many digits as fit into a uint64.
|
||||
// When the string starts with "1844674407370955161" no further digit is read.
|
||||
// Since 2^64 = 18446744073709551616 it would still be possible read another
|
||||
// digit if it was less or equal than 6, but this would complicate the code.
|
||||
static uint64_t ReadUint64(Vector<const char> buffer,
|
||||
int* number_of_read_digits) {
|
||||
uint64_t result = 0;
|
||||
int i = 0;
|
||||
while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
|
||||
int digit = buffer[i++] - '0';
|
||||
ASSERT(0 <= digit && digit <= 9);
|
||||
result = 10 * result + digit;
|
||||
}
|
||||
*number_of_read_digits = i;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// Reads a DiyFp from the buffer.
|
||||
// The returned DiyFp is not necessarily normalized.
|
||||
// If remaining_decimals is zero then the returned DiyFp is accurate.
|
||||
// Otherwise it has been rounded and has error of at most 1/2 ulp.
|
||||
static void ReadDiyFp(Vector<const char> buffer,
|
||||
DiyFp* result,
|
||||
int* remaining_decimals) {
|
||||
int read_digits;
|
||||
uint64_t significand = ReadUint64(buffer, &read_digits);
|
||||
if (buffer.length() == read_digits) {
|
||||
*result = DiyFp(significand, 0);
|
||||
*remaining_decimals = 0;
|
||||
} else {
|
||||
// Round the significand.
|
||||
if (buffer[read_digits] >= '5') {
|
||||
significand++;
|
||||
}
|
||||
// Compute the binary exponent.
|
||||
int exponent = 0;
|
||||
*result = DiyFp(significand, exponent);
|
||||
*remaining_decimals = buffer.length() - read_digits;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static bool DoubleStrtod(Vector<const char> trimmed,
|
||||
int exponent,
|
||||
double* result) {
|
||||
#if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
|
||||
// On x86 the floating-point stack can be 64 or 80 bits wide. If it is
|
||||
// 80 bits wide (as is the case on Linux) then double-rounding occurs and the
|
||||
// result is not accurate.
|
||||
// We know that Windows32 uses 64 bits and is therefore accurate.
|
||||
// Note that the ARM simulator is compiled for 32bits. It therefore exhibits
|
||||
// the same problem.
|
||||
return false;
|
||||
#endif
|
||||
if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
|
||||
int read_digits;
|
||||
// The trimmed input fits into a double.
|
||||
// If the 10^exponent (resp. 10^-exponent) fits into a double too then we
|
||||
// can compute the result-double simply by multiplying (resp. dividing) the
|
||||
// two numbers.
|
||||
// This is possible because IEEE guarantees that floating-point operations
|
||||
// return the best possible approximation.
|
||||
if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
|
||||
// 10^-exponent fits into a double.
|
||||
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
||||
ASSERT(read_digits == trimmed.length());
|
||||
*result /= exact_powers_of_ten[-exponent];
|
||||
return true;
|
||||
}
|
||||
if (0 <= exponent && exponent < kExactPowersOfTenSize) {
|
||||
// 10^exponent fits into a double.
|
||||
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
||||
ASSERT(read_digits == trimmed.length());
|
||||
*result *= exact_powers_of_ten[exponent];
|
||||
return true;
|
||||
}
|
||||
int remaining_digits =
|
||||
kMaxExactDoubleIntegerDecimalDigits - trimmed.length();
|
||||
if ((0 <= exponent) &&
|
||||
(exponent - remaining_digits < kExactPowersOfTenSize)) {
|
||||
// The trimmed string was short and we can multiply it with
|
||||
// 10^remaining_digits. As a result the remaining exponent now fits
|
||||
// into a double too.
|
||||
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
||||
ASSERT(read_digits == trimmed.length());
|
||||
*result *= exact_powers_of_ten[remaining_digits];
|
||||
*result *= exact_powers_of_ten[exponent - remaining_digits];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Returns 10^exponent as an exact DiyFp.
|
||||
// The given exponent must be in the range [1; kDecimalExponentDistance[.
|
||||
static DiyFp AdjustmentPowerOfTen(int exponent) {
|
||||
ASSERT(0 < exponent);
|
||||
ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
|
||||
// Simply hardcode the remaining powers for the given decimal exponent
|
||||
// distance.
|
||||
ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
|
||||
switch (exponent) {
|
||||
case 1: return DiyFp(UINT64_2PART_C(0xa0000000, 00000000), -60);
|
||||
case 2: return DiyFp(UINT64_2PART_C(0xc8000000, 00000000), -57);
|
||||
case 3: return DiyFp(UINT64_2PART_C(0xfa000000, 00000000), -54);
|
||||
case 4: return DiyFp(UINT64_2PART_C(0x9c400000, 00000000), -50);
|
||||
case 5: return DiyFp(UINT64_2PART_C(0xc3500000, 00000000), -47);
|
||||
case 6: return DiyFp(UINT64_2PART_C(0xf4240000, 00000000), -44);
|
||||
case 7: return DiyFp(UINT64_2PART_C(0x98968000, 00000000), -40);
|
||||
default:
|
||||
UNREACHABLE();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// If the function returns true then the result is the correct double.
|
||||
// Otherwise it is either the correct double or the double that is just below
|
||||
// the correct double.
|
||||
static bool DiyFpStrtod(Vector<const char> buffer,
|
||||
int exponent,
|
||||
double* result) {
|
||||
DiyFp input;
|
||||
int remaining_decimals;
|
||||
ReadDiyFp(buffer, &input, &remaining_decimals);
|
||||
// Since we may have dropped some digits the input is not accurate.
|
||||
// If remaining_decimals is different than 0 than the error is at most
|
||||
// .5 ulp (unit in the last place).
|
||||
// We don't want to deal with fractions and therefore keep a common
|
||||
// denominator.
|
||||
const int kDenominatorLog = 3;
|
||||
const int kDenominator = 1 << kDenominatorLog;
|
||||
// Move the remaining decimals into the exponent.
|
||||
exponent += remaining_decimals;
|
||||
uint64_t error = (remaining_decimals == 0 ? 0 : kDenominator / 2);
|
||||
|
||||
int old_e = input.e();
|
||||
input.Normalize();
|
||||
error <<= old_e - input.e();
|
||||
|
||||
ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
|
||||
if (exponent < PowersOfTenCache::kMinDecimalExponent) {
|
||||
*result = 0.0;
|
||||
return true;
|
||||
}
|
||||
DiyFp cached_power;
|
||||
int cached_decimal_exponent;
|
||||
PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent,
|
||||
&cached_power,
|
||||
&cached_decimal_exponent);
|
||||
|
||||
if (cached_decimal_exponent != exponent) {
|
||||
int adjustment_exponent = exponent - cached_decimal_exponent;
|
||||
DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent);
|
||||
input.Multiply(adjustment_power);
|
||||
if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
|
||||
// The product of input with the adjustment power fits into a 64 bit
|
||||
// integer.
|
||||
ASSERT(DiyFp::kSignificandSize == 64);
|
||||
} else {
|
||||
// The adjustment power is exact. There is hence only an error of 0.5.
|
||||
error += kDenominator / 2;
|
||||
}
|
||||
}
|
||||
|
||||
input.Multiply(cached_power);
|
||||
// The error introduced by a multiplication of a*b equals
|
||||
// error_a + error_b + error_a*error_b/2^64 + 0.5
|
||||
// Substituting a with 'input' and b with 'cached_power' we have
|
||||
// error_b = 0.5 (all cached powers have an error of less than 0.5 ulp),
|
||||
// error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64
|
||||
int error_b = kDenominator / 2;
|
||||
int error_ab = (error == 0 ? 0 : 1); // We round up to 1.
|
||||
int fixed_error = kDenominator / 2;
|
||||
error += error_b + error_ab + fixed_error;
|
||||
|
||||
old_e = input.e();
|
||||
input.Normalize();
|
||||
error <<= old_e - input.e();
|
||||
|
||||
// See if the double's significand changes if we add/subtract the error.
|
||||
int order_of_magnitude = DiyFp::kSignificandSize + input.e();
|
||||
int effective_significand_size =
|
||||
Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude);
|
||||
int precision_digits_count =
|
||||
DiyFp::kSignificandSize - effective_significand_size;
|
||||
if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) {
|
||||
// This can only happen for very small denormals. In this case the
|
||||
// half-way multiplied by the denominator exceeds the range of an uint64.
|
||||
// Simply shift everything to the right.
|
||||
int shift_amount = (precision_digits_count + kDenominatorLog) -
|
||||
DiyFp::kSignificandSize + 1;
|
||||
input.set_f(input.f() >> shift_amount);
|
||||
input.set_e(input.e() + shift_amount);
|
||||
// We add 1 for the lost precision of error, and kDenominator for
|
||||
// the lost precision of input.f().
|
||||
error = (error >> shift_amount) + 1 + kDenominator;
|
||||
precision_digits_count -= shift_amount;
|
||||
}
|
||||
// We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
|
||||
ASSERT(DiyFp::kSignificandSize == 64);
|
||||
ASSERT(precision_digits_count < 64);
|
||||
uint64_t one64 = 1;
|
||||
uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
|
||||
uint64_t precision_bits = input.f() & precision_bits_mask;
|
||||
uint64_t half_way = one64 << (precision_digits_count - 1);
|
||||
precision_bits *= kDenominator;
|
||||
half_way *= kDenominator;
|
||||
DiyFp rounded_input(input.f() >> precision_digits_count,
|
||||
input.e() + precision_digits_count);
|
||||
if (precision_bits >= half_way + error) {
|
||||
rounded_input.set_f(rounded_input.f() + 1);
|
||||
}
|
||||
// If the last_bits are too close to the half-way case than we are too
|
||||
// inaccurate and round down. In this case we return false so that we can
|
||||
// fall back to a more precise algorithm.
|
||||
|
||||
*result = Double(rounded_input).value();
|
||||
if (half_way - error < precision_bits && precision_bits < half_way + error) {
|
||||
// Too imprecise. The caller will have to fall back to a slower version.
|
||||
// However the returned number is guaranteed to be either the correct
|
||||
// double, or the next-lower double.
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Returns
|
||||
// - -1 if buffer*10^exponent < diy_fp.
|
||||
// - 0 if buffer*10^exponent == diy_fp.
|
||||
// - +1 if buffer*10^exponent > diy_fp.
|
||||
// Preconditions:
|
||||
// buffer.length() + exponent <= kMaxDecimalPower + 1
|
||||
// buffer.length() + exponent > kMinDecimalPower
|
||||
// buffer.length() <= kMaxDecimalSignificantDigits
|
||||
static int CompareBufferWithDiyFp(Vector<const char> buffer,
|
||||
int exponent,
|
||||
DiyFp diy_fp) {
|
||||
ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1);
|
||||
ASSERT(buffer.length() + exponent > kMinDecimalPower);
|
||||
ASSERT(buffer.length() <= kMaxSignificantDecimalDigits);
|
||||
// Make sure that the Bignum will be able to hold all our numbers.
|
||||
// Our Bignum implementation has a separate field for exponents. Shifts will
|
||||
// consume at most one bigit (< 64 bits).
|
||||
// ln(10) == 3.3219...
|
||||
ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits);
|
||||
Bignum buffer_bignum;
|
||||
Bignum diy_fp_bignum;
|
||||
buffer_bignum.AssignDecimalString(buffer);
|
||||
diy_fp_bignum.AssignUInt64(diy_fp.f());
|
||||
if (exponent >= 0) {
|
||||
buffer_bignum.MultiplyByPowerOfTen(exponent);
|
||||
} else {
|
||||
diy_fp_bignum.MultiplyByPowerOfTen(-exponent);
|
||||
}
|
||||
if (diy_fp.e() > 0) {
|
||||
diy_fp_bignum.ShiftLeft(diy_fp.e());
|
||||
} else {
|
||||
buffer_bignum.ShiftLeft(-diy_fp.e());
|
||||
}
|
||||
return Bignum::Compare(buffer_bignum, diy_fp_bignum);
|
||||
}
|
||||
|
||||
|
||||
// Returns true if the guess is the correct double.
|
||||
// Returns false, when guess is either correct or the next-lower double.
|
||||
static bool ComputeGuess(Vector<const char> trimmed, int exponent,
|
||||
double* guess) {
|
||||
if (trimmed.length() == 0) {
|
||||
*guess = 0.0;
|
||||
return true;
|
||||
}
|
||||
if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) {
|
||||
*guess = Double::Infinity();
|
||||
return true;
|
||||
}
|
||||
if (exponent + trimmed.length() <= kMinDecimalPower) {
|
||||
*guess = 0.0;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (DoubleStrtod(trimmed, exponent, guess) ||
|
||||
DiyFpStrtod(trimmed, exponent, guess)) {
|
||||
return true;
|
||||
}
|
||||
if (*guess == Double::Infinity()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
double Strtod(Vector<const char> buffer, int exponent) {
|
||||
char copy_buffer[kMaxSignificantDecimalDigits];
|
||||
Vector<const char> trimmed;
|
||||
int updated_exponent;
|
||||
TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
|
||||
&trimmed, &updated_exponent);
|
||||
exponent = updated_exponent;
|
||||
|
||||
double guess;
|
||||
bool is_correct = ComputeGuess(trimmed, exponent, &guess);
|
||||
if (is_correct) return guess;
|
||||
|
||||
DiyFp upper_boundary = Double(guess).UpperBoundary();
|
||||
int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
|
||||
if (comparison < 0) {
|
||||
return guess;
|
||||
} else if (comparison > 0) {
|
||||
return Double(guess).NextDouble();
|
||||
} else if ((Double(guess).Significand() & 1) == 0) {
|
||||
// Round towards even.
|
||||
return guess;
|
||||
} else {
|
||||
return Double(guess).NextDouble();
|
||||
}
|
||||
}
|
||||
|
||||
float Strtof(Vector<const char> buffer, int exponent) {
|
||||
char copy_buffer[kMaxSignificantDecimalDigits];
|
||||
Vector<const char> trimmed;
|
||||
int updated_exponent;
|
||||
TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
|
||||
&trimmed, &updated_exponent);
|
||||
exponent = updated_exponent;
|
||||
|
||||
double double_guess;
|
||||
bool is_correct = ComputeGuess(trimmed, exponent, &double_guess);
|
||||
|
||||
float float_guess = static_cast<float>(double_guess);
|
||||
if (float_guess == double_guess) {
|
||||
// This shortcut triggers for integer values.
|
||||
return float_guess;
|
||||
}
|
||||
|
||||
// We must catch double-rounding. Say the double has been rounded up, and is
|
||||
// now a boundary of a float, and rounds up again. This is why we have to
|
||||
// look at previous too.
|
||||
// Example (in decimal numbers):
|
||||
// input: 12349
|
||||
// high-precision (4 digits): 1235
|
||||
// low-precision (3 digits):
|
||||
// when read from input: 123
|
||||
// when rounded from high precision: 124.
|
||||
// To do this we simply look at the neigbors of the correct result and see
|
||||
// if they would round to the same float. If the guess is not correct we have
|
||||
// to look at four values (since two different doubles could be the correct
|
||||
// double).
|
||||
|
||||
double double_next = Double(double_guess).NextDouble();
|
||||
double double_previous = Double(double_guess).PreviousDouble();
|
||||
|
||||
float f1 = static_cast<float>(double_previous);
|
||||
float f2 = float_guess;
|
||||
float f3 = static_cast<float>(double_next);
|
||||
float f4;
|
||||
if (is_correct) {
|
||||
f4 = f3;
|
||||
} else {
|
||||
double double_next2 = Double(double_next).NextDouble();
|
||||
f4 = static_cast<float>(double_next2);
|
||||
}
|
||||
(void) f2; // Mark variable as used.
|
||||
ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4);
|
||||
|
||||
// If the guess doesn't lie near a single-precision boundary we can simply
|
||||
// return its float-value.
|
||||
if (f1 == f4) {
|
||||
return float_guess;
|
||||
}
|
||||
|
||||
ASSERT((f1 != f2 && f2 == f3 && f3 == f4) ||
|
||||
(f1 == f2 && f2 != f3 && f3 == f4) ||
|
||||
(f1 == f2 && f2 == f3 && f3 != f4));
|
||||
|
||||
// guess and next are the two possible canditates (in the same way that
|
||||
// double_guess was the lower candidate for a double-precision guess).
|
||||
float guess = f1;
|
||||
float next = f4;
|
||||
DiyFp upper_boundary;
|
||||
if (guess == 0.0f) {
|
||||
float min_float = 1e-45f;
|
||||
upper_boundary = Double(static_cast<double>(min_float) / 2).AsDiyFp();
|
||||
} else {
|
||||
upper_boundary = Single(guess).UpperBoundary();
|
||||
}
|
||||
int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
|
||||
if (comparison < 0) {
|
||||
return guess;
|
||||
} else if (comparison > 0) {
|
||||
return next;
|
||||
} else if ((Single(guess).Significand() & 1) == 0) {
|
||||
// Round towards even.
|
||||
return guess;
|
||||
} else {
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace double_conversion
|
|
@ -1,45 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#ifndef DOUBLE_CONVERSION_STRTOD_H_
|
||||
#define DOUBLE_CONVERSION_STRTOD_H_
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
// The buffer must only contain digits in the range [0-9]. It must not
|
||||
// contain a dot or a sign. It must not start with '0', and must not be empty.
|
||||
double Strtod(Vector<const char> buffer, int exponent);
|
||||
|
||||
// The buffer must only contain digits in the range [0-9]. It must not
|
||||
// contain a dot or a sign. It must not start with '0', and must not be empty.
|
||||
float Strtof(Vector<const char> buffer, int exponent);
|
||||
|
||||
} // namespace double_conversion
|
||||
|
||||
#endif // DOUBLE_CONVERSION_STRTOD_H_
|
|
@ -1,324 +0,0 @@
|
|||
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following
|
||||
// disclaimer in the documentation and/or other materials provided
|
||||
// with the distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived
|
||||
// from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#ifndef DOUBLE_CONVERSION_UTILS_H_
|
||||
#define DOUBLE_CONVERSION_UTILS_H_
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <assert.h>
|
||||
#ifndef ASSERT
|
||||
#define ASSERT(condition) \
|
||||
assert(condition);
|
||||
#endif
|
||||
#ifndef UNIMPLEMENTED
|
||||
#define UNIMPLEMENTED() (abort())
|
||||
#endif
|
||||
#ifndef UNREACHABLE
|
||||
#define UNREACHABLE() (abort())
|
||||
#endif
|
||||
|
||||
// Double operations detection based on target architecture.
|
||||
// Linux uses a 80bit wide floating point stack on x86. This induces double
|
||||
// rounding, which in turn leads to wrong results.
|
||||
// An easy way to test if the floating-point operations are correct is to
|
||||
// evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then
|
||||
// the result is equal to 89255e-22.
|
||||
// The best way to test this, is to create a division-function and to compare
|
||||
// the output of the division with the expected result. (Inlining must be
|
||||
// disabled.)
|
||||
// On Linux,x86 89255e-22 != Div_double(89255.0/1e22)
|
||||
#if defined(_M_X64) || defined(__x86_64__) || \
|
||||
defined(__ARMEL__) || defined(__avr32__) || \
|
||||
defined(__hppa__) || defined(__ia64__) || \
|
||||
defined(__mips__) || \
|
||||
defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \
|
||||
defined(__sparc__) || defined(__sparc) || defined(__s390__) || \
|
||||
defined(__SH4__) || defined(__alpha__) || \
|
||||
defined(_MIPS_ARCH_MIPS32R2) || \
|
||||
defined(__AARCH64EL__)
|
||||
#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
|
||||
#elif defined(__mc68000__)
|
||||
#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
|
||||
#elif defined(_M_IX86) || defined(__i386__) || defined(__i386)
|
||||
#if defined(_WIN32)
|
||||
// Windows uses a 64bit wide floating point stack.
|
||||
#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
|
||||
#else
|
||||
#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
|
||||
#endif // _WIN32
|
||||
#else
|
||||
#error Target architecture was not detected as supported by Double-Conversion.
|
||||
#endif
|
||||
|
||||
#if defined(__GNUC__)
|
||||
#define DOUBLE_CONVERSION_UNUSED __attribute__((unused))
|
||||
#else
|
||||
#define DOUBLE_CONVERSION_UNUSED
|
||||
#endif
|
||||
|
||||
#if defined(_WIN32) && !defined(__MINGW32__)
|
||||
|
||||
typedef signed char int8_t;
|
||||
typedef unsigned char uint8_t;
|
||||
typedef short int16_t; // NOLINT
|
||||
typedef unsigned short uint16_t; // NOLINT
|
||||
typedef int int32_t;
|
||||
typedef unsigned int uint32_t;
|
||||
typedef __int64 int64_t;
|
||||
typedef unsigned __int64 uint64_t;
|
||||
// intptr_t and friends are defined in crtdefs.h through stdio.h.
|
||||
|
||||
#else
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#endif
|
||||
|
||||
// The following macro works on both 32 and 64-bit platforms.
|
||||
// Usage: instead of writing 0x1234567890123456
|
||||
// write UINT64_2PART_C(0x12345678,90123456);
|
||||
#define UINT64_2PART_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
|
||||
|
||||
|
||||
// The expression ARRAY_SIZE(a) is a compile-time constant of type
|
||||
// size_t which represents the number of elements of the given
|
||||
// array. You should only use ARRAY_SIZE on statically allocated
|
||||
// arrays.
|
||||
#ifndef ARRAY_SIZE
|
||||
#define ARRAY_SIZE(a) \
|
||||
((sizeof(a) / sizeof(*(a))) / \
|
||||
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
|
||||
#endif
|
||||
|
||||
// A macro to disallow the evil copy constructor and operator= functions
|
||||
// This should be used in the private: declarations for a class
|
||||
#ifndef DISALLOW_COPY_AND_ASSIGN
|
||||
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
|
||||
TypeName(const TypeName&); \
|
||||
void operator=(const TypeName&)
|
||||
#endif
|
||||
|
||||
// A macro to disallow all the implicit constructors, namely the
|
||||
// default constructor, copy constructor and operator= functions.
|
||||
//
|
||||
// This should be used in the private: declarations for a class
|
||||
// that wants to prevent anyone from instantiating it. This is
|
||||
// especially useful for classes containing only static methods.
|
||||
#ifndef DISALLOW_IMPLICIT_CONSTRUCTORS
|
||||
#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
|
||||
TypeName(); \
|
||||
DISALLOW_COPY_AND_ASSIGN(TypeName)
|
||||
#endif
|
||||
|
||||
namespace double_conversion {
|
||||
|
||||
static const int kCharSize = sizeof(char);
|
||||
|
||||
// Returns the maximum of the two parameters.
|
||||
template <typename T>
|
||||
static T Max(T a, T b) {
|
||||
return a < b ? b : a;
|
||||
}
|
||||
|
||||
|
||||
// Returns the minimum of the two parameters.
|
||||
template <typename T>
|
||||
static T Min(T a, T b) {
|
||||
return a < b ? a : b;
|
||||
}
|
||||
|
||||
|
||||
inline int StrLength(const char* string) {
|
||||
size_t length = strlen(string);
|
||||
ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
|
||||
return static_cast<int>(length);
|
||||
}
|
||||
|
||||
// This is a simplified version of V8's Vector class.
|
||||
template <typename T>
|
||||
class Vector {
|
||||
public:
|
||||
Vector() : start_(NULL), length_(0) {}
|
||||
Vector(T* data, int length) : start_(data), length_(length) {
|
||||
ASSERT(length == 0 || (length > 0 && data != NULL));
|
||||
}
|
||||
|
||||
// Returns a vector using the same backing storage as this one,
|
||||
// spanning from and including 'from', to but not including 'to'.
|
||||
Vector<T> SubVector(int from, int to) {
|
||||
ASSERT(to <= length_);
|
||||
ASSERT(from < to);
|
||||
ASSERT(0 <= from);
|
||||
return Vector<T>(start() + from, to - from);
|
||||
}
|
||||
|
||||
// Returns the length of the vector.
|
||||
int length() const { return length_; }
|
||||
|
||||
// Returns whether or not the vector is empty.
|
||||
bool is_empty() const { return length_ == 0; }
|
||||
|
||||
// Returns the pointer to the start of the data in the vector.
|
||||
T* start() const { return start_; }
|
||||
|
||||
// Access individual vector elements - checks bounds in debug mode.
|
||||
T& operator[](int index) const {
|
||||
ASSERT(0 <= index && index < length_);
|
||||
return start_[index];
|
||||
}
|
||||
|
||||
T& first() { return start_[0]; }
|
||||
|
||||
T& last() { return start_[length_ - 1]; }
|
||||
|
||||
private:
|
||||
T* start_;
|
||||
int length_;
|
||||
};
|
||||
|
||||
|
||||
// Helper class for building result strings in a character buffer. The
|
||||
// purpose of the class is to use safe operations that checks the
|
||||
// buffer bounds on all operations in debug mode.
|
||||
class StringBuilder {
|
||||
public:
|
||||
StringBuilder(char* buffer, int size)
|
||||
: buffer_(buffer, size), position_(0) { }
|
||||
|
||||
~StringBuilder() { if (!is_finalized()) Finalize(); }
|
||||
|
||||
int size() const { return buffer_.length(); }
|
||||
|
||||
// Get the current position in the builder.
|
||||
int position() const {
|
||||
ASSERT(!is_finalized());
|
||||
return position_;
|
||||
}
|
||||
|
||||
// Reset the position.
|
||||
void Reset() { position_ = 0; }
|
||||
|
||||
// Add a single character to the builder. It is not allowed to add
|
||||
// 0-characters; use the Finalize() method to terminate the string
|
||||
// instead.
|
||||
void AddCharacter(char c) {
|
||||
ASSERT(c != '\0');
|
||||
ASSERT(!is_finalized() && position_ < buffer_.length());
|
||||
buffer_[position_++] = c;
|
||||
}
|
||||
|
||||
// Add an entire string to the builder. Uses strlen() internally to
|
||||
// compute the length of the input string.
|
||||
void AddString(const char* s) {
|
||||
AddSubstring(s, StrLength(s));
|
||||
}
|
||||
|
||||
// Add the first 'n' characters of the given string 's' to the
|
||||
// builder. The input string must have enough characters.
|
||||
void AddSubstring(const char* s, int n) {
|
||||
ASSERT(!is_finalized() && position_ + n < buffer_.length());
|
||||
ASSERT(static_cast<size_t>(n) <= strlen(s));
|
||||
memmove(&buffer_[position_], s, n * kCharSize);
|
||||
position_ += n;
|
||||
}
|
||||
|
||||
|
||||
// Add character padding to the builder. If count is non-positive,
|
||||
// nothing is added to the builder.
|
||||
void AddPadding(char c, int count) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
AddCharacter(c);
|
||||
}
|
||||
}
|
||||
|
||||
// Finalize the string by 0-terminating it and returning the buffer.
|
||||
char* Finalize() {
|
||||
ASSERT(!is_finalized() && position_ < buffer_.length());
|
||||
buffer_[position_] = '\0';
|
||||
// Make sure nobody managed to add a 0-character to the
|
||||
// buffer while building the string.
|
||||
ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_));
|
||||
position_ = -1;
|
||||
ASSERT(is_finalized());
|
||||
return buffer_.start();
|
||||
}
|
||||
|
||||
private:
|
||||
Vector<char> buffer_;
|
||||
int position_;
|
||||
|
||||
bool is_finalized() const { return position_ < 0; }
|
||||
|
||||
DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
|
||||
};
|
||||
|
||||
// The type-based aliasing rule allows the compiler to assume that pointers of
|
||||
// different types (for some definition of different) never alias each other.
|
||||
// Thus the following code does not work:
|
||||
//
|
||||
// float f = foo();
|
||||
// int fbits = *(int*)(&f);
|
||||
//
|
||||
// The compiler 'knows' that the int pointer can't refer to f since the types
|
||||
// don't match, so the compiler may cache f in a register, leaving random data
|
||||
// in fbits. Using C++ style casts makes no difference, however a pointer to
|
||||
// char data is assumed to alias any other pointer. This is the 'memcpy
|
||||
// exception'.
|
||||
//
|
||||
// Bit_cast uses the memcpy exception to move the bits from a variable of one
|
||||
// type of a variable of another type. Of course the end result is likely to
|
||||
// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
|
||||
// will completely optimize BitCast away.
|
||||
//
|
||||
// There is an additional use for BitCast.
|
||||
// Recent gccs will warn when they see casts that may result in breakage due to
|
||||
// the type-based aliasing rule. If you have checked that there is no breakage
|
||||
// you can use BitCast to cast one pointer type to another. This confuses gcc
|
||||
// enough that it can no longer see that you have cast one pointer type to
|
||||
// another thus avoiding the warning.
|
||||
template <class Dest, class Source>
|
||||
inline Dest BitCast(const Source& source) {
|
||||
// Compile time assertion: sizeof(Dest) == sizeof(Source)
|
||||
// A compile error here means your Dest and Source have different sizes.
|
||||
DOUBLE_CONVERSION_UNUSED
|
||||
typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
|
||||
|
||||
Dest dest;
|
||||
memmove(&dest, &source, sizeof(dest));
|
||||
return dest;
|
||||
}
|
||||
|
||||
template <class Dest, class Source>
|
||||
inline Dest BitCast(Source* source) {
|
||||
return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
|
||||
}
|
||||
|
||||
} // namespace double_conversion
|
||||
|
||||
#endif // DOUBLE_CONVERSION_UTILS_H_
|
|
@ -1,172 +0,0 @@
|
|||
// Copyright 2019 Google
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#import <FirebaseCore/FirebaseCore.h>
|
||||
|
||||
#if !defined(__has_include)
|
||||
#error "Firebase.h won't import anything if your compiler doesn't support __has_include. Please \
|
||||
import the headers individually."
|
||||
#else
|
||||
#if __has_include(<FirebaseAnalytics/FirebaseAnalytics.h>)
|
||||
#import <FirebaseAnalytics/FirebaseAnalytics.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseAuth/FirebaseAuth.h>)
|
||||
#import <FirebaseAuth/FirebaseAuth.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseCrashlytics/FirebaseCrashlytics.h>)
|
||||
#import <FirebaseCrashlytics/FirebaseCrashlytics.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseDatabase/FirebaseDatabase.h>)
|
||||
#import <FirebaseDatabase/FirebaseDatabase.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseDynamicLinks/FirebaseDynamicLinks.h>)
|
||||
#import <FirebaseDynamicLinks/FirebaseDynamicLinks.h>
|
||||
#if !__has_include(<FirebaseAnalytics/FirebaseAnalytics.h>)
|
||||
#ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
|
||||
#warning "FirebaseAnalytics.framework is not included in your target. Please add \
|
||||
`Firebase/Analytics` to your Podfile or add FirebaseAnalytics.framework to your project to ensure \
|
||||
Firebase Dynamic Links works as intended."
|
||||
#endif // #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseFirestore/FirebaseFirestore.h>)
|
||||
#import <FirebaseFirestore/FirebaseFirestore.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseFunctions/FirebaseFunctions.h>)
|
||||
#import <FirebaseFunctions/FirebaseFunctions.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseInAppMessaging/FirebaseInAppMessaging.h>)
|
||||
#import <FirebaseInAppMessaging/FirebaseInAppMessaging.h>
|
||||
#if !__has_include(<FirebaseAnalytics/FirebaseAnalytics.h>)
|
||||
#ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
|
||||
#warning "FirebaseAnalytics.framework is not included in your target. Please add \
|
||||
`Firebase/Analytics` to your Podfile or add FirebaseAnalytics.framework to your project to ensure \
|
||||
Firebase In App Messaging works as intended."
|
||||
#endif // #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseInstanceID/FirebaseInstanceID.h>)
|
||||
#import <FirebaseInstanceID/FirebaseInstanceID.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMessaging/FirebaseMessaging.h>)
|
||||
#import <FirebaseMessaging/FirebaseMessaging.h>
|
||||
#if !__has_include(<FirebaseAnalytics/FirebaseAnalytics.h>)
|
||||
#ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
|
||||
#warning "FirebaseAnalytics.framework is not included in your target. Please add \
|
||||
`Firebase/Analytics` to your Podfile or add FirebaseAnalytics.framework to your project to ensure \
|
||||
Firebase Messaging works as intended."
|
||||
#endif // #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLCommon/FirebaseMLCommon.h>)
|
||||
#import <FirebaseMLCommon/FirebaseMLCommon.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLModelInterpreter/FirebaseMLModelInterpreter.h>)
|
||||
#import <FirebaseMLModelInterpreter/FirebaseMLModelInterpreter.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLNLLanguageID/FirebaseMLNLLanguageID.h>)
|
||||
#import <FirebaseMLNLLanguageID/FirebaseMLNLLanguageID.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLNLSmartReply/FirebaseMLNLSmartReply.h>)
|
||||
#import <FirebaseMLNLSmartReply/FirebaseMLNLSmartReply.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLNLTranslate/FirebaseMLNLTranslate.h>)
|
||||
#import <FirebaseMLNLTranslate/FirebaseMLNLTranslate.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLNaturalLanguage/FirebaseMLNaturalLanguage.h>)
|
||||
#import <FirebaseMLNaturalLanguage/FirebaseMLNaturalLanguage.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLVision/FirebaseMLVision.h>)
|
||||
#import <FirebaseMLVision/FirebaseMLVision.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLVisionAutoML/FirebaseMLVisionAutoML.h>)
|
||||
#import <FirebaseMLVisionAutoML/FirebaseMLVisionAutoML.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLVisionBarcodeModel/FirebaseMLVisionBarcodeModel.h>)
|
||||
#import <FirebaseMLVisionBarcodeModel/FirebaseMLVisionBarcodeModel.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLVisionFaceModel/FirebaseMLVisionFaceModel.h>)
|
||||
#import <FirebaseMLVisionFaceModel/FirebaseMLVisionFaceModel.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLVisionLabelModel/FirebaseMLVisionLabelModel.h>)
|
||||
#import <FirebaseMLVisionLabelModel/FirebaseMLVisionLabelModel.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLVisionObjectDetection/FirebaseMLVisionObjectDetection.h>)
|
||||
#import <FirebaseMLVisionObjectDetection/FirebaseMLVisionObjectDetection.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseMLVisionTextModel/FirebaseMLVisionTextModel.h>)
|
||||
#import <FirebaseMLVisionTextModel/FirebaseMLVisionTextModel.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebasePerformance/FirebasePerformance.h>)
|
||||
#import <FirebasePerformance/FirebasePerformance.h>
|
||||
#if !__has_include(<FirebaseAnalytics/FirebaseAnalytics.h>)
|
||||
#ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
|
||||
#warning "FirebaseAnalytics.framework is not included in your target. Please add \
|
||||
`Firebase/Analytics` to your Podfile or add FirebaseAnalytics.framework to your project to ensure \
|
||||
Firebase Performance works as intended."
|
||||
#endif // #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseRemoteConfig/FirebaseRemoteConfig.h>)
|
||||
#import <FirebaseRemoteConfig/FirebaseRemoteConfig.h>
|
||||
#if !__has_include(<FirebaseAnalytics/FirebaseAnalytics.h>)
|
||||
#ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
|
||||
#warning "FirebaseAnalytics.framework is not included in your target. Please add \
|
||||
`Firebase/Analytics` to your Podfile or add FirebaseAnalytics.framework to your project to ensure \
|
||||
Firebase Remote Config works as intended."
|
||||
#endif // #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if __has_include(<FirebaseStorage/FirebaseStorage.h>)
|
||||
#import <FirebaseStorage/FirebaseStorage.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<GoogleMobileAds/GoogleMobileAds.h>)
|
||||
#import <GoogleMobileAds/GoogleMobileAds.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<Fabric/Fabric.h>)
|
||||
#import <Fabric/Fabric.h>
|
||||
#endif
|
||||
|
||||
#if __has_include(<Crashlytics/Crashlytics.h>)
|
||||
#import <Crashlytics/Crashlytics.h>
|
||||
#endif
|
||||
|
||||
#endif // defined(__has_include)
|
|
@ -1,4 +0,0 @@
|
|||
module Firebase {
|
||||
export *
|
||||
header "Firebase.h"
|
||||
}
|
|
@ -1,202 +0,0 @@
|
|||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -1,311 +0,0 @@
|
|||
[](https://cocoapods.org/pods/Firebase)
|
||||
[](https://cocoapods.org/pods/Firebase)
|
||||
[](https://cocoapods.org/pods/Firebase)
|
||||
|
||||
[![Actions Status][gh-abtesting-badge]][gh-actions]
|
||||
[![Actions Status][gh-auth-badge]][gh-actions]
|
||||
[![Actions Status][gh-core-badge]][gh-actions]
|
||||
[![Actions Status][gh-crashlytics-badge]][gh-actions]
|
||||
[![Actions Status][gh-database-badge]][gh-actions]
|
||||
[![Actions Status][gh-datatransport-badge]][gh-actions]
|
||||
[![Actions Status][gh-dynamiclinks-badge]][gh-actions]
|
||||
[![Actions Status][gh-firebasepod-badge]][gh-actions]
|
||||
[![Actions Status][gh-firestore-badge]][gh-actions]
|
||||
[![Actions Status][gh-functions-badge]][gh-actions]
|
||||
[![Actions Status][gh-inappmessaging-badge]][gh-actions]
|
||||
[![Actions Status][gh-interop-badge]][gh-actions]
|
||||
[![Actions Status][gh-messaging-badge]][gh-actions]
|
||||
[![Actions Status][gh-remoteconfig-badge]][gh-actions]
|
||||
[![Actions Status][gh-storage-badge]][gh-actions]
|
||||
[![Actions Status][gh-symbolcollision-badge]][gh-actions]
|
||||
[![Actions Status][gh-zip-badge]][gh-actions]
|
||||
[](https://travis-ci.org/firebase/firebase-ios-sdk)
|
||||
|
||||
# Firebase Apple Open Source Development
|
||||
|
||||
This repository contains all Apple platform Firebase SDK source except FirebaseAnalytics,
|
||||
FirebasePerformance, and FirebaseML.
|
||||
|
||||
The repository also includes GoogleUtilities source. The
|
||||
[GoogleUtilities](GoogleUtilities/README.md) pod is
|
||||
a set of utilities used by Firebase and other Google products.
|
||||
|
||||
Firebase is an app development platform with tools to help you build, grow and
|
||||
monetize your app. More information about Firebase can be found at
|
||||
[https://firebase.google.com](https://firebase.google.com).
|
||||
|
||||
## Installation
|
||||
|
||||
See the three subsections for details about three different installation methods.
|
||||
1. [Standard pod install](README.md#standard-pod-install)
|
||||
1. [Installing from the GitHub repo](README.md#installing-from-github)
|
||||
1. [Experimental Carthage](README.md#carthage-ios-only)
|
||||
|
||||
### Standard pod install
|
||||
|
||||
Go to
|
||||
[https://firebase.google.com/docs/ios/setup](https://firebase.google.com/docs/ios/setup).
|
||||
|
||||
### Installing from GitHub
|
||||
|
||||
For releases starting with 5.0.0, the source for each release is also deployed
|
||||
to CocoaPods master and available via standard
|
||||
[CocoaPods Podfile syntax](https://guides.cocoapods.org/syntax/podfile.html#pod).
|
||||
|
||||
These instructions can be used to access the Firebase repo at other branches,
|
||||
tags, or commits.
|
||||
|
||||
#### Background
|
||||
|
||||
See
|
||||
[the Podfile Syntax Reference](https://guides.cocoapods.org/syntax/podfile.html#pod)
|
||||
for instructions and options about overriding pod source locations.
|
||||
|
||||
#### Accessing Firebase Source Snapshots
|
||||
|
||||
All of the official releases are tagged in this repo and available via CocoaPods. To access a local
|
||||
source snapshot or unreleased branch, use Podfile directives like the following:
|
||||
|
||||
To access FirebaseFirestore via a branch:
|
||||
```
|
||||
pod 'FirebaseCore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master'
|
||||
pod 'FirebaseFirestore', :git => 'https://github.com/firebase/firebase-ios-sdk.git', :branch => 'master'
|
||||
```
|
||||
|
||||
To access FirebaseMessaging via a checked out version of the firebase-ios-sdk repo do:
|
||||
|
||||
```
|
||||
pod 'FirebaseCore', :path => '/path/to/firebase-ios-sdk'
|
||||
pod 'FirebaseMessaging', :path => '/path/to/firebase-ios-sdk'
|
||||
```
|
||||
|
||||
### Carthage (iOS only)
|
||||
|
||||
Instructions for the experimental Carthage distribution are at
|
||||
[Carthage](Carthage.md).
|
||||
|
||||
### Rome
|
||||
|
||||
Instructions for installing binary frameworks via
|
||||
[Rome](https://github.com/CocoaPods/Rome) are at [Rome](Rome.md).
|
||||
|
||||
### Using Firebase from a Framework or a library
|
||||
|
||||
[Using Firebase from a Framework or a library](docs/firebase_in_libraries.md)
|
||||
|
||||
## Development
|
||||
|
||||
To develop Firebase software in this repository, ensure that you have at least
|
||||
the following software:
|
||||
|
||||
* Xcode 10.3 (or later)
|
||||
* CocoaPods 1.7.2 (or later)
|
||||
* [CocoaPods generate](https://github.com/square/cocoapods-generate)
|
||||
|
||||
For the pod that you want to develop:
|
||||
|
||||
`pod gen Firebase{name here}.podspec --local-sources=./ --auto-open --platforms=ios`
|
||||
|
||||
Note: If the CocoaPods cache is out of date, you may need to run
|
||||
`pod repo update` before the `pod gen` command.
|
||||
|
||||
Note: Set the `--platforms` option to `macos` or `tvos` to develop/test for
|
||||
those platforms. Since 10.2, Xcode does not properly handle multi-platform
|
||||
CocoaPods workspaces.
|
||||
|
||||
Firestore has a self contained Xcode project. See
|
||||
[Firestore/README.md](Firestore/README.md).
|
||||
|
||||
### Development for Catalyst
|
||||
* `pod gen {name here}.podspec --local-sources=./ --auto-open --platforms=ios`
|
||||
* Check the Mac box in the App-iOS Build Settings
|
||||
* Sign the App in the Settings Signing & Capabilities tab
|
||||
* Click Pods in the Project Manager
|
||||
* Add Signing to the iOS host app and unit test targets
|
||||
* Select the Unit-unit scheme
|
||||
* Run it to build and test
|
||||
|
||||
### Adding a New Firebase Pod
|
||||
|
||||
See [AddNewPod.md](AddNewPod.md).
|
||||
|
||||
### Managing Headers and Imports
|
||||
|
||||
See [HeadersImports.md](HeadersImports.md).
|
||||
|
||||
### Code Formatting
|
||||
|
||||
To ensure that the code is formatted consistently, run the script
|
||||
[./scripts/style.sh](https://github.com/firebase/firebase-ios-sdk/blob/master/scripts/style.sh)
|
||||
before creating a PR.
|
||||
|
||||
Travis will verify that any code changes are done in a style compliant way. Install
|
||||
`clang-format` and `swiftformat`.
|
||||
These commands will get the right versions:
|
||||
|
||||
```
|
||||
brew upgrade https://raw.githubusercontent.com/Homebrew/homebrew-core/c6f1cbd/Formula/clang-format.rb
|
||||
brew upgrade https://raw.githubusercontent.com/Homebrew/homebrew-core/c13eda8/Formula/swiftformat.rb
|
||||
```
|
||||
|
||||
Note: if you already have a newer version of these installed you may need to
|
||||
`brew switch` to this version.
|
||||
|
||||
To update this section, find the versions of clang-format and swiftformat.rb to
|
||||
match the versions in the CI failure logs
|
||||
[here](https://github.com/Homebrew/homebrew-core/tree/master/Formula).
|
||||
|
||||
### Running Unit Tests
|
||||
|
||||
Select a scheme and press Command-u to build a component and run its unit tests.
|
||||
|
||||
#### Viewing Code Coverage (Deprecated)
|
||||
|
||||
First, make sure that [xcov](https://github.com/nakiostudio/xcov) is installed with `gem install xcov`.
|
||||
|
||||
After running the `AllUnitTests_iOS` scheme in Xcode, execute
|
||||
`xcov --workspace Firebase.xcworkspace --scheme AllUnitTests_iOS --output_directory xcov_output`
|
||||
at Example/ in the terminal. This will aggregate the coverage, and you can run `open xcov_output/index.html` to see the results.
|
||||
|
||||
### Running Sample Apps
|
||||
In order to run the sample apps and integration tests, you'll need valid
|
||||
`GoogleService-Info.plist` files for those samples. The Firebase Xcode project contains dummy plist
|
||||
files without real values, but can be replaced with real plist files. To get your own
|
||||
`GoogleService-Info.plist` files:
|
||||
|
||||
1. Go to the [Firebase Console](https://console.firebase.google.com/)
|
||||
2. Create a new Firebase project, if you don't already have one
|
||||
3. For each sample app you want to test, create a new Firebase app with the sample app's bundle
|
||||
identifier (e.g. `com.google.Database-Example`)
|
||||
4. Download the resulting `GoogleService-Info.plist` and replace the appropriate dummy plist file
|
||||
(e.g. in [Example/Database/App/](Example/Database/App/));
|
||||
|
||||
Some sample apps like Firebase Messaging ([Example/Messaging/App](Example/Messaging/App)) require
|
||||
special Apple capabilities, and you will have to change the sample app to use a unique bundle
|
||||
identifier that you can control in your own Apple Developer account.
|
||||
|
||||
## Specific Component Instructions
|
||||
See the sections below for any special instructions for those components.
|
||||
|
||||
### Firebase Auth
|
||||
|
||||
If you're doing specific Firebase Auth development, see
|
||||
[the Auth Sample README](FirebaseAuth/Tests/Sample/README.md) for instructions about
|
||||
building and running the FirebaseAuth pod along with various samples and tests.
|
||||
|
||||
### Firebase Database
|
||||
|
||||
The Firebase Database Integration tests can be run against a locally running Database Emulator
|
||||
or against a production instance.
|
||||
|
||||
To run against a local emulator instance, invoke `./scripts/run_database_emulator.sh start` before
|
||||
running the integration test.
|
||||
|
||||
To run against a production instance, provide a valid GoogleServices-Info.plist and copy it to
|
||||
`Example/Database/App/GoogleService-Info.plist`. Your Security Rule must be set to
|
||||
[public](https://firebase.google.com/docs/database/security/quickstart) while your tests are
|
||||
running.
|
||||
|
||||
### Firebase Storage
|
||||
|
||||
To run the Storage Integration tests, follow the instructions in
|
||||
[FIRStorageIntegrationTests.m](FirebaseStorage/Tests/Integration/FIRStorageIntegrationTests.m).
|
||||
|
||||
#### Push Notifications
|
||||
|
||||
Push notifications can only be delivered to specially provisioned App IDs in the developer portal.
|
||||
In order to actually test receiving push notifications, you will need to:
|
||||
|
||||
1. Change the bundle identifier of the sample app to something you own in your Apple Developer
|
||||
account, and enable that App ID for push notifications.
|
||||
2. You'll also need to
|
||||
[upload your APNs Provider Authentication Key or certificate to the Firebase Console](https://firebase.google.com/docs/cloud-messaging/ios/certs)
|
||||
at **Project Settings > Cloud Messaging > [Your Firebase App]**.
|
||||
3. Ensure your iOS device is added to your Apple Developer portal as a test device.
|
||||
|
||||
#### iOS Simulator
|
||||
|
||||
The iOS Simulator cannot register for remote notifications, and will not receive push notifications.
|
||||
In order to receive push notifications, you'll have to follow the steps above and run the app on a
|
||||
physical device.
|
||||
|
||||
## Community Supported Efforts
|
||||
|
||||
We've seen an amazing amount of interest and contributions to improve the Firebase SDKs, and we are
|
||||
very grateful! We'd like to empower as many developers as we can to be able to use Firebase and
|
||||
participate in the Firebase community.
|
||||
|
||||
### tvOS, macOS, watchOS and Catalyst
|
||||
Thanks to contributions from the community, many of Firebase SDKs now compile, run unit tests, and work on
|
||||
tvOS, macOS, watchOS and Catalyst.
|
||||
|
||||
For tvOS, checkout the [Sample](Example/tvOSSample).
|
||||
For watchOS, currently only Messaging and Storage (and their dependencies) have limited support. Checkout the
|
||||
[Independent Watch App Sample](Example/watchOSSample).
|
||||
|
||||
Keep in mind that macOS, tvOS, watchOS and Catalyst are not officially supported by Firebase, and this
|
||||
repository is actively developed primarily for iOS. While we can catch basic unit test issues with
|
||||
Travis, there may be some changes where the SDK no longer works as expected on macOS, tvOS or watchOS. If you
|
||||
encounter this, please [file an issue](https://github.com/firebase/firebase-ios-sdk/issues).
|
||||
|
||||
During app setup in the console, you may get to a step that mentions something like "Checking if the app
|
||||
has communicated with our servers". This relies on Analytics and will not work on macOS/tvOS/watchOS/Catalyst.
|
||||
**It's safe to ignore the message and continue**, the rest of the SDKs will work as expected.
|
||||
|
||||
To install, add a subset of the following to the Podfile:
|
||||
|
||||
```
|
||||
pod 'Firebase/ABTesting' # No watchOS support yet
|
||||
pod 'Firebase/Auth' # No watchOS support yet
|
||||
pod 'Firebase/Crashlytics' # No watchOS support yet
|
||||
pod 'Firebase/Database' # No watchOS support yet
|
||||
pod 'Firebase/Firestore' # No watchOS support yet
|
||||
pod 'Firebase/Functions' # No watchOS support yet
|
||||
pod 'Firebase/Messaging'
|
||||
pod 'Firebase/RemoteConfig' # No watchOS support yet
|
||||
pod 'Firebase/Storage'
|
||||
```
|
||||
|
||||
#### Additional Catalyst Notes
|
||||
|
||||
* FirebaseAuth and FirebaseMessaging require adding `Keychain Sharing Capability`
|
||||
to Build Settings.
|
||||
* FirebaseFirestore requires signing the
|
||||
[gRPC Resource target](https://github.com/firebase/firebase-ios-sdk/issues/3500#issuecomment-518741681).
|
||||
|
||||
## Roadmap
|
||||
|
||||
See [Roadmap](ROADMAP.md) for more about the Firebase iOS SDK Open Source
|
||||
plans and directions.
|
||||
|
||||
## Contributing
|
||||
|
||||
See [Contributing](CONTRIBUTING.md) for more information on contributing to the Firebase
|
||||
iOS SDK.
|
||||
|
||||
## License
|
||||
|
||||
The contents of this repository is licensed under the
|
||||
[Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
|
||||
Your use of Firebase is governed by the
|
||||
[Terms of Service for Firebase Services](https://firebase.google.com/terms/).
|
||||
|
||||
[gh-actions]: https://github.com/firebase/firebase-ios-sdk/actions
|
||||
[gh-abtesting-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/abtesting/badge.svg
|
||||
[gh-auth-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/auth/badge.svg
|
||||
[gh-core-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/core/badge.svg
|
||||
[gh-crashlytics-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/crashlytics/badge.svg
|
||||
[gh-database-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/database/badge.svg
|
||||
[gh-datatransport-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/datatransport/badge.svg
|
||||
[gh-dynamiclinks-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/dynamiclinks/badge.svg
|
||||
[gh-firebasepod-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/firebasepod/badge.svg
|
||||
[gh-firestore-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/firestore/badge.svg
|
||||
[gh-functions-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/functions/badge.svg
|
||||
[gh-inappmessaging-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/inappmessaging/badge.svg
|
||||
[gh-interop-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/interop/badge.svg
|
||||
[gh-messaging-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/messaging/badge.svg
|
||||
[gh-remoteconfig-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/remoteconfig/badge.svg
|
||||
[gh-storage-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/storage/badge.svg
|
||||
[gh-symbolcollision-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/symbolcollision/badge.svg
|
||||
[gh-zip-badge]: https://github.com/firebase/firebase-ios-sdk/workflows/zip/badge.svg
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue