repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
HelpGiveThanks/BudgetPlanner
|
scripts/gotoStore.c
|
<reponame>HelpGiveThanks/BudgetPlanner<gh_stars>0
gotoStore
Set Error Capture [ On ]
Allow User Abort [ Off ]
Set Field [ budget::outLayoutGlobal; Get (LayoutName) ]
Go to Layout [ “store” (store) ]
Enter Find Mode [ ]
Set Field [ store::kbudget; budget::budgetGlobal ]
Perform Find [ ]
Sort Records [ Specified Sort Order: store::store; ascending ]
[ Restore; No dialog ]
Go to Record/Request/Page
[ First ]
January 8, 平成26 18:49:04 Budget Research.fp7 - gotoStore -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/gotoOut.c
|
<filename>scripts/gotoOut.c
gotoOut
Allow User Abort [ Off ]
Set Error Capture [ On ]
#
If [ Get (LayoutName) = "budget" or
Get (LayoutName) = "store" or
Get (LayoutName) = "source" or
Get (LayoutName) = "people" ]
Else
Set Field [ budget::inLayoutGlobal; Get (LayoutName) ]
End If
#
If [ Get (FoundCount) = 0 & Get (LayoutName) = "Budget" ]
Show Custom Dialog [ Message: "There are no budgets to view."; Buttons: “OK” ]
Exit Script [ ]
End If
#
If [ budget::budgetGlobal = "" ]
Show Custom Dialog [ Message: "Click a button next the budget you want to view."; Buttons: “OK” ]
Exit Script [ ]
End If
#
If [ budget::outLayoutGlobal = "" ]
Else
Go to Layout [ budget::outLayoutGlobal ]
If [ Get (LayoutTableName) ≠ "out" ]
Go to Layout [ “PurchaseTotals3” (out) ]
End If
End If
#
Enter Find Mode [ ]
Set Field [ out::kbudget; budget::budgetGlobal ]
Perform Find [ ]
#
Perform Script [ “updatePurchaseHeaderCalc” ]
Sort Records [ Specified Sort Order: out::_Lyear; ascending
out::_Lmonth; ascending
person::person; ascending ]
[ Restore; No dialog ]
Go to Record/Request/Page
[ First ]
Scroll Window
[ Home ]
January 8, 平成26 19:00:56 Budget Research.fp7 - gotoOut -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/gotoNote.c
|
gotoNote
Go to Layout [ “people” (person) ]
Enter Browse Mode
January 8, 平成26 19:02:46 Budget Research.fp7 - gotoNote -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/newSource.c
|
<filename>scripts/newSource.c
newSource
Allow User Abort [ Off ]
Set Error Capture [ On ]
New Record/Request
Set Field [ source::kbudget; budget::budgetGlobal ]
Go to Field [ source::source ]
January 8, 平成26 18:53:06 Budget Research.fp7 - newSource -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/newIn.c
|
<gh_stars>0
newIn
New Record/Request
Set Field [ in::kbudget; budget::budgetGlobal ]
Go to Layout [ “income2” (in) ]
January 8, 平成26 18:51:10 Budget Research.fp7 - newIn -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/deletePurchase.c
|
deletePurchase
Set Variable [ $delete; Value:out::_Lout ]
Go to Field [ out::Date ]
Scroll Window
[ To Selection ]
Go to Field [ ]
Refresh Window
Show Custom Dialog [ Message: "delete current record?"; Buttons: “cancel”, “delete” ]
If [ Get (LastMessageChoice) = 1 ]
Set Variable [ $delete ]
Refresh Window
Exit Script [ ]
End If
Delete Record/Request
[ No dialog ]
Perform Script [ “updatePurchaseHeaderCalc” ]
// Insert Text [ out::UpdateCalcField; “1” ]
[ Select ]
// Commit Records/Requests
[ No dialog ]
// Clear [ out::UpdateCalcField ]
[ Select ]
// Commit Records/Requests
[ No dialog ]
// Enter Browse Mode
January 8, 平成26 19:03:12 Budget Research.fp7 - deletePurchase -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/deletePersonName.c
|
<gh_stars>0
deletePersonName
Set Error Capture [ On ]
Allow User Abort [ Off ]
Set Variable [ $delete; Value:person::_Lperson ]
New Window [ ]
Go to Layout [ “PurchaseTotals1” (out) ]
Enter Find Mode [ ]
Set Field [ out::kperson; $delete ]
Perform Find [ ]
If [ Get ( LastError ) = 0 ]
Set Variable [ $number; Value:Get (FoundCount) ]
Close Window [ Current Window ]
Show Custom Dialog [ Message: Case ( $number = 1 ; "Person/group is in use " & $number & " time. You can only delete a person/group name that is not in use. " ;
"Person/group is in use " & $number & " times. You can only delete a person/group name that is not in use. " ); Buttons: “OK” ]
Else If [ Get ( LastError ) = 401 ]
Close Window [ Current Window ]
Go to Field [ person::person ]
Scroll Window
[ To Selection ]
Go to Field [ ]
Refresh Window
Show Custom Dialog [ Message: "delete current record?"; Buttons: “cancel”, “delete” ]
If [ Get (LastMessageChoice) = 1 ]
Set Variable [ $delete ]
Refresh Window
Exit Script [ ]
End If
Delete Record/Request
[ No dialog ]
End If
January 8, 平成26 19:06:45 Budget Research.fp7 - deletePersonName -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/deletePortalRow.c
|
<reponame>HelpGiveThanks/BudgetPlanner
deletePortalRow
Delete Portal Row
[ No dialog ]
Perform Script [ “updatePurchaseHeaderCalc” ]
January 8, 平成26 19:08:54 Budget Research.fp7 - deletePortalRow -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/start.c
|
start
Go to Layout [ “budget” (budget) ]
Set Window Title [ Current Window; New Title: "Budget Planner" ]
Set Zoom Level
[ 100% ]
#
#Report version number to Memory Switch Table.
Set Field [ MemorySwitch::versionBudget; Reference::version ]
#
#Show regular menus if Admin logs in only.
Show/Hide Text Ruler
[ Hide ]
If [ Get ( AccountName ) = "Admin" ]
Show/Hide Status Area
[ Hide ]
Install Menu Set [ “[Standard FileMaker Menus]” ]
Else
Show/Hide Status Area
[ Lock; Hide ]
Install Menu Set [ “Custom Menu Set 1” ]
End If
January 30, 平成26 22:13:52 Budget Planner.fp7 - start -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/view.c
|
<reponame>HelpGiveThanks/BudgetPlanner
view
#
#Reveal more or fewer pictures and links for tag.
#
#from 1 to 2
If [ Right ( Get (LayoutName) ; 1) = 1
and
Left ( out::purchaseLayoutView ; 4 ) = "more" ]
Go to Layout [ “PurchaseTotals2” (out) ]
#from 2 to 3
Else If [ Right ( Get (LayoutName) ; 1) = 2
and
Left ( out::purchaseLayoutView ; 4 ) = "more" ]
Go to Layout [ “PurchaseTotals3” (out) ]
#from 3 to 4
Else If [ Right ( Get (LayoutName) ; 1) = 3
and
Left ( out::purchaseLayoutView ; 4 ) = "more" ]
Go to Layout [ “PurchaseTotals4” (out) ]
#from 4 to 3
Else If [ Right ( Get (LayoutName) ; 1) = 4
and
Left ( out::purchaseLayoutView ; 4 ) = "less" ]
Go to Layout [ “PurchaseTotals3” (out) ]
#from 3 to 2
Else If [ Right ( Get (LayoutName) ; 1) = 3
and
Left ( out::purchaseLayoutView ; 4 ) = "less" ]
Go to Layout [ “PurchaseTotals2” (out) ]
#from 2 to 1
Else If [ Right ( Get (LayoutName) ; 1) = 2
and
Left ( out::purchaseLayoutView ; 4 ) = "less" ]
Go to Layout [ “PurchaseTotals1” (out) ]
End If
#
#Remember layout user is on so they can be
#returned to correct view.
#
#from 1 to 2
If [ Right ( Get (LayoutName) ; 1) = 2
and
Left ( out::purchaseLayoutView ; 4 ) = "more" ]
Set Field [ out::purchaseLayoutView; "more" & Get (LayoutName) ]
#from 2 to 3
January 8, 平成26 19:10:01 Budget Research.fp7 - view -1-view
Else If [ Right ( Get (LayoutName) ; 1) = 3
and
Left ( out::purchaseLayoutView ; 4 ) = "more" ]
Set Field [ out::purchaseLayoutView; "more" & Get (LayoutName) ]
#from 3 to 4
Else If [ Right ( Get (LayoutName) ; 1) = 4
and
Left ( out::purchaseLayoutView ; 4 ) = "more" ]
Set Field [ out::purchaseLayoutView; "less" & Get (LayoutName) ]
#from 4 to 3
Else If [ Right ( Get (LayoutName) ; 1) = 3
and
Left ( out::purchaseLayoutView ; 4 ) = "less" ]
Set Field [ out::purchaseLayoutView; "less" & Get (LayoutName) ]
#from 3 to 2
Else If [ Right ( Get (LayoutName) ; 1) = 2
and
Left ( out::purchaseLayoutView ; 4 ) = "less" ]
Set Field [ out::purchaseLayoutView; "less" & Get (LayoutName) ]
#from 2 to 1
Else If [ Right ( Get (LayoutName) ; 1) = 1
and
Left ( out::purchaseLayoutView ; 4 ) = "less"
or
out::purchaseLayoutView = "" ]
Set Field [ out::purchaseLayoutView; "more" & Get (LayoutName) ]
End If
#
January 8, 平成26 19:10:01 Budget Research.fp7 - view -2-
|
HelpGiveThanks/BudgetPlanner
|
scripts/backToBudget.c
|
<reponame>HelpGiveThanks/BudgetPlanner<filename>scripts/backToBudget.c
backToBudget
#
If [ Get (LayoutTableName) = "in" ]
Set Field [ budget::inLayoutGlobal; Get (LayoutName) ]
Else If [ Get (LayoutTableName) = "out" ]
Set Field [ budget::outLayoutGlobal; Get (LayoutName) ]
End If
#
Go to Layout [ “budget” (budget) ]
Show All Records
Sort Records [ Specified Sort Order: budget::name; ascending ]
[ Restore; No dialog ]
January 8, 平成26 18:59:50 Budget Research.fp7 - backToBudget -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/changePerson.c
|
changePerson
Allow User Abort [ Off ]
Set Error Capture [ On ]
Set Variable [ $record; Value:out::_Lout ]
Set Variable [ $person; Value:out::kperson ]
New Window [ ]
Go to Layout [ “purchases” (Art) ]
Enter Find Mode [ ]
Set Field [ Art::kout; $record ]
Perform Find [ ]
Go to Record/Request/Page
[ First ]
Loop
Set Field [ Art::kperson; $person ]
Go to Record/Request/Page
[ Next; Exit after last ]
End Loop
Close Window [ Current Window ]
Sort Records [ ]
[ No dialog ]
January 8, 平成26 19:11:00 Budget Research.fp7 - changePerson -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/returnToPurchasesFromNote.c
|
returnToPurchasesFromNote
Go to Layout [ budget::outLayoutGlobal ]
January 8, 平成26 18:59:24 Budget Research.fp7 - returnToPurchasesFromNote -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/deleteSource.c
|
deleteSource
Set Error Capture [ On ]
Allow User Abort [ Off ]
Set Variable [ $delete; Value:source::_Lsource ]
New Window [ ]
Go to Layout [ “income2” (in) ]
Enter Find Mode [ ]
Set Field [ in::ksource; $delete ]
Perform Find [ ]
If [ Get ( LastError ) = 0 ]
Set Variable [ $number; Value:Get (FoundCount) ]
Close Window [ Current Window ]
Show Custom Dialog [ Message: Case ( $number = 1 ; "Source is in use " & $number & " time. You can only delete sources that are not in use. " ; "Source is in use " &
$number & " times. You can only delete sources that are not in use. " ); Buttons: “OK” ]
Set Variable [ $delete ]
Refresh Window
Exit Script [ ]
Else If [ Get ( LastError ) = 401 ]
Close Window [ Current Window ]
Go to Field [ source::source ]
Scroll Window
[ To Selection ]
Go to Field [ ]
Refresh Window
Show Custom Dialog [ Message: "delete current record?"; Buttons: “cancel”, “delete” ]
If [ Get (LastMessageChoice) = 1 ]
Set Variable [ $delete ]
Refresh Window
Exit Script [ ]
End If
Delete Record/Request
[ No dialog ]
End If
January 8, 平成26 19:05:49 Budget Research.fp7 - deleteSource -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/gotoPerson.c
|
<reponame>HelpGiveThanks/BudgetPlanner
gotoPerson
Set Error Capture [ On ]
Allow User Abort [ Off ]
Set Variable [ $$outLayout; Value:Get (LayoutName) ]
Set Field [ budget::outLayoutGlobal; Get (LayoutName) ]
Go to Layout [ “people” (person) ]
Enter Find Mode [ ]
Set Field [ person::kbudget; budget::budgetGlobal ]
Perform Find [ ]
Sort Records [ Specified Sort Order: person::person; ascending ]
[ Restore; No dialog ]
Go to Record/Request/Page
[ First ]
January 8, 平成26 18:49:33 Budget Research.fp7 - gotoPerson -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/deleteBudget.c
|
deleteBudget
Allow User Abort [ Off ]
Set Error Capture [ On ]
Go to Field [ ]
If [ Get (LastError) = 509 ]
Set Variable [ $noName; Value:1 ]
End If
Set Variable [ $delete; Value:budget::_Lbudget ]
#
New Window [ ]
Go to Layout [ “PurchaseTotals1” (out) ]
Enter Find Mode [ ]
Set Field [ out::kbudget; $delete ]
Perform Find [ ]
If [ Get ( LastError ) = 0 ]
Set Variable [ $outNumber; Value:Get (FoundCount) ]
End If
Go to Layout [ “income2” (in) ]
Enter Find Mode [ ]
Set Field [ in::kbudget; $delete ]
Perform Find [ ]
If [ Get ( LastError ) = 0 ]
Set Variable [ $inNumber; Value:Get (FoundCount) ]
Close Window [ Current Window ]
Show Custom Dialog [ Message: "This budget cannot be deleted because there are records attached to this budget: " &
Case ( $inNumber ≠ "" ; "in records = " & $inNumber ) &
Case ( $outNumber ≠ "" ; ", out records = " & $outNumber ) &
"."; Buttons: “OK” ]
#
Else If [ $inNumber + $outNumber < 1 ]
Close Window [ Current Window ]
Go to Field [ budget::name ]
Scroll Window
[ To Selection ]
Go to Field [ ]
Refresh Window
Show Custom Dialog [ Message: "delete current record?"; Buttons: “cancel”, “delete” ]
If [ Get (LastMessageChoice) = 1 ]
Set Variable [ $delete ]
Refresh Window
If [ $noName = 1 ]
Go to Field [ budget::name ]
January 8, 平成26 19:03:54 Budget Research.fp7 - deleteBudget -1-deleteBudget
End If
Exit Script [ ]
End If
Delete Record/Request
[ No dialog ]
If [ $delete = budget::budgetGlobal ]
Set Field [ budget::budgetGlobal; "" ]
End If
End If
#
January 8, 平成26 19:03:54 Budget Research.fp7 - deleteBudget -2-
|
HelpGiveThanks/BudgetPlanner
|
scripts/chooseBudget.c
|
chooseBudget
Allow User Abort [ Off ]
Set Error Capture [ On ]
Set Field [ budget::budgetGlobal; budget::_Lbudget ]
Go to Field [ ]
If [ Get (LastError) = 509 ]
Go to Field [ budget::name ]
End If
January 8, 平成26 19:01:54 Budget Research.fp7 - chooseBudget -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/newBudget.c
|
newBudget
Allow User Abort [ Off ]
Set Error Capture [ On ]
Go to Field [ ]
If [ Get (LastError) = 509 ]
Go to Field [ budget::name ]
Exit Script [ ]
End If
New Record/Request
Set Field [ budget::name; "test" ]
Set Variable [ $budget; Value:budget::_Lbudget ]
Go to Layout [ “target” (outTarget) ]
New Record/Request
Set Field [ outTarget::kbudget; $budget ]
Go to Layout [ “budget” (budget) ]
Set Field [ budget::name; "" ]
Go to Field [ budget::name ]
January 8, 平成26 18:48:30 Budget Research.fp7 - newBudget -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/gotoHelp.c
|
<gh_stars>0
gotoHelp
#
#Set back path from help to this solution.
Set Field [ MemorySwitch::backToSolution; "Budget Research" ]
#
If [ Get (LayoutName) = "Budget" ]
Set Field [ MemorySwitch::helpLayoutName; "Users and Budgets" ]
Set Field [ MemorySwitch::helpObjectName; "" ]
#
Else If [ Left ( Get (LayoutName) ; 1 ) = "P" or
Left ( Get (LayoutName) ; 2 ) = "St" ]
Set Field [ MemorySwitch::helpLayoutName; "Purchases = Out" ]
Set Field [ MemorySwitch::helpObjectName; "" ]
#
Else If [ Left ( Get (LayoutName) ; 1 ) = "I" or
Left ( Get (LayoutName) ; 2 ) = "Sc" ]
Set Field [ MemorySwitch::helpLayoutName; "Income = In" ]
Set Field [ MemorySwitch::helpObjectName; "" ]
#
End If
#
Open URL [ Case ( Get ( SystemPlatform ) = - 2 ;
Substitute ( Substitute ( Get (FilePath) ; Get (FileName) & Right ( Get (FilePath) ; 4 ) ; "help" & Right ( Get (FilePath) ; 4 ) ) ; " " ; "%20" ) ;
Substitute ( Substitute ( Substitute ( Get (FilePath) ; Get (FileName) & Right ( Get (FilePath) ; 4 ) ; "help" & Right ( Get (FilePath) ; 4 ) ) ; "file:/" ; "file://" ) ; " " ; "%20" ) ) ]
[ No dialog ]
Open URL [ Substitute ( Substitute ( Substitute ( Substitute ( Get (FilePath) ; Get (FileName) & Right ( Get (FilePath) ; 4 ) ; "help" & Right ( Get (FilePath) ; 4 ) ) ; "file:/" ; "file:
//" ) ; " " ; "%20" ) ; "file://" ; "file:///Volumes/" ) ]
[ No dialog ]
#
Select Window [ Name: "Help" ]
Select Window [ Name: "Tutorial" ]
#
#
January 8, 平成26 19:13:28 Budget Research.fp7 - gotoHelp -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/goTo.c
|
goTo
Go to Layout [ <unknown> ]
Go to Field [ Art::amount ]
Scroll Window
[ To Selection ]
January 8, 平成26 19:07:58 Budget Research.fp7 - goTo -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/duplicatePurchase.c
|
<gh_stars>0
duplicatePurchase
Allow User Abort [ Off ]
Set Error Capture [ On ]
Freeze Window
Set Variable [ $$stopMessage; Value:1 ]
Set Variable [ $record; Value:out::_Lout ]
Set Variable [ $date; Value:out::Date ]
Set Field [ budget::outLayoutGlobal; Get (LayoutName) ]
New Window [ ]
Freeze Window
New Record/Request
Set Variable [ $recordDuplicate; Value:out::_Lout ]
Delete Record/Request
[ No dialog ]
Enter Find Mode [ ]
Set Field [ out::_Lout; $record ]
Perform Find [ ]
Duplicate Record/Request
Set Field [ out::_Lout; $recordDuplicate ]
Set Field [ out::Date; Case ( Month ( $date ) + 1 = 13 ;
1 & "/" & 1 & "/" & Year ( $date ) + 1 ;
( Month ( $date ) + 1 ) & "/" & 1 & "/" & Year ( $date ) ) ]
Set Variable [ $date; Value:out::Date ]
Go to Layout [ “purchases” (Art) ]
Enter Find Mode [ ]
Set Field [ Art::kout; $record ]
Perform Find [ ]
Loop
Go to Record/Request/Page
[ Last ]
Set Variable [ $kout; Value:Art::kout ]
New Record/Request
Set Variable [ $purchaseDuplicate; Value:Art::_Lpurchases ]
Delete Record/Request
[ No dialog ]
Duplicate Record/Request
Set Field [ Art::_Lpurchases; $purchaseDuplicate ]
Set Field [ Art::kout; $recordDuplicate ]
Set Field [ Art::date; $date ]
Set Field [ Art::kmonth; Month ( $date ) ]
Set Field [ Art::kyear; Year ( $date ) ]
January 8, 平成26 18:54:27 Budget Research.fp7 - duplicatePurchase -1-duplicatePurchase
#507 errror due to invalid date.
#507 errror due to invalid date.
#507 errror due to invalid date.
#507 errror due to invalid date.
Omit Record
Omit Record
Exit Loop If [ Get ( FoundCount) = 0 ]
End Loop
Close Window [ Current Window ]
Sort Records [ ]
[ No dialog ]
Perform Script [ “gotoOut” ]
Loop
Go to Record/Request/Page
[ Next; Exit after last ]
Exit Loop If [ out::_Lout = $recordDuplicate ]
End Loop
Perform Script [ “updatePurchaseHeaderCalc” ]
Go to Field [ ]
Set Variable [ $$stopMessage ]
January 8, 平成26 18:54:27 Budget Research.fp7 - duplicatePurchase -2-
|
HelpGiveThanks/BudgetPlanner
|
scripts/gotoIn.c
|
gotoIn
Allow User Abort [ Off ]
Set Error Capture [ On ]
#
If [ Get (LayoutName) = "budget" or
Get (LayoutName) = "store" or
Get (LayoutName) = "source" or
Get (LayoutName) = "people" ]
Else
Set Field [ budget::outLayoutGlobal; Get (LayoutName) ]
End If
#
If [ Get (FoundCount) = 0 & Get (LayoutName) = "Budget" ]
Show Custom Dialog [ Message: "There are no budgets to view."; Buttons: “OK” ]
Exit Script [ ]
End If
#
If [ budget::budgetGlobal = "" ]
Show Custom Dialog [ Message: "Click a button next the budget you want to view."; Buttons: “OK” ]
Exit Script [ ]
End If
#
If [ budget::inLayoutGlobal = "" ]
Go to Layout [ “income2” (in) ]
Else
Go to Layout [ budget::inLayoutGlobal ]
If [ Get (LayoutTableName) ≠ "in" ]
Go to Layout [ “income2” (in) ]
End If
End If
#
Enter Find Mode [ ]
Set Field [ in::kbudget; budget::budgetGlobal ]
Perform Find [ ]
#
Perform Script [ “updateIncomeHeaderCalc” ]
Sort Records [ Specified Sort Order: in::year; ascending
in::Month; ascending ]
[ Restore; No dialog ]
Go to Record/Request/Page
[ First ]
Scroll Window
[ Home ]
January 8, 平成26 19:01:25 Budget Research.fp7 - gotoIn -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/newOut.c
|
newOut
New Record/Request
Go to Layout [ “PurchaseTotals4” (out) ]
Set Field [ out::purchaseLayoutView; "less" & Get (LayoutName) ]
Set Field [ out::kbudget; budget::budgetGlobal ]
Sort Records [ Specified Sort Order: out::_Lyear; ascending
out::_Lmonth; ascending
person::person; ascending ]
[ Restore; No dialog ]
January 8, 平成26 18:50:41 Budget Research.fp7 - newOut -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/newPerson.c
|
<reponame>HelpGiveThanks/BudgetPlanner<filename>scripts/newPerson.c
newPerson
Allow User Abort [ Off ]
Set Error Capture [ On ]
New Record/Request
Set Field [ person::kbudget; budget::budgetGlobal ]
Go to Field [ person::person ]
January 8, 平成26 18:54:00 Budget Research.fp7 - newPerson -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/newStore.c
|
newStore
Allow User Abort [ Off ]
Set Error Capture [ On ]
New Record/Request
Set Field [ store::kbudget; budget::budgetGlobal ]
Go to Field [ store::store ]
January 8, 平成26 18:52:05 Budget Research.fp7 - newStore -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/clearDates.c
|
clearDates
Clear [ Reference::FDateDayFrom ]
[ Select ]
Clear [ Reference::FDateYearFrom ]
[ Select ]
Clear [ Reference::TDateDayTo ]
[ Select ]
Clear [ Reference::TDateMonthTo ]
[ Select ]
Clear [ Reference::TDateYearTo ]
[ Select ]
Clear [ Reference::FDateMonthFrom ]
[ Select ]
January 8, 平成26 18:58:55 Budget Research.fp7 - clearDates -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/gotoTimer.c
|
gotoTimer
Set Field [ MemorySwitch::budgetPath; Get (WindowName) ]
Select Window [ Name: "Tag" ]
Select Window [ Name: "Day" ]
Select Window [ Name: "Specific Action" ]
Select Window [ Name: "Timer" ]
Select Window [ Name: "HelpGiveThanks Solutions" ]
January 8, 平成26 19:13:00 Budget Research.fp7 - gotoTimer -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/updatePurchaseHeaderCalc.c
|
<filename>scripts/updatePurchaseHeaderCalc.c
updatePurchaseHeaderCalc
If [ Get (FoundCount) = 0 ]
Set Variable [ $$stopMessage; Value:1 ]
New Record/Request
Set Variable [ $delete; Value:1 ]
End If
If [ out::UpdateCalcField = "" ]
Set Field [ out::UpdateCalcField; "t" ]
Else
Set Field [ out::UpdateCalcField; "" ]
End If
Commit Records/Requests
Refresh Window
If [ $delete = 1 ]
Delete Record/Request
[ No dialog ]
Set Variable [ $$stopMessage ]
End If
January 8, 平成26 19:11:42 Budget Research.fp7 - updatePurchaseHeaderCalc -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/return to Purchases from Store.c
|
return to Purchases from Store
Go to Layout [ “PurchaseTotals4” (out) ]
January 8, 平成26 18:55:46 Budget Research.fp7 - return to Purchases from Store -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/insurePersonIsSelected.c
|
insurePersonIsSelected
If [ out::kperson = "" ]
Go to Field [ ]
If [ $$stopMessage = "" ]
Show Custom Dialog [ Message: "Select a person or group of people doing the spending."; Buttons: “OK” ]
End If
Go to Field [ out::kperson ]
[ Select/perform ]
// Go to Object [ Object Name: "person" ]
End If
January 8, 平成26 19:08:27 Budget Research.fp7 - insurePersonIsSelected -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/exit.c
|
exit
Go to Field [ ]
January 8, 平成26 19:09:21 Budget Research.fp7 - exit -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/changeDate.c
|
changeDate
Allow User Abort [ Off ]
Set Error Capture [ On ]
Set Variable [ $record; Value:out::_Lout ]
Set Variable [ $month; Value:out::_Lmonth ]
Set Variable [ $year; Value:out::_Lyear ]
New Window [ ]
Go to Layout [ “purchases” (Art) ]
Enter Find Mode [ ]
Set Field [ Art::kout; $record ]
Perform Find [ ]
Go to Record/Request/Page
[ First ]
Loop
Set Field [ Art::kmonth; $month ]
Set Field [ Art::kyear; $year ]
Go to Record/Request/Page
[ Next; Exit after last ]
End Loop
Close Window [ Current Window ]
Sort Records [ ]
[ No dialog ]
January 8, 平成26 19:10:33 Budget Research.fp7 - changeDate -1-
|
bricsi0000000000000/Chess
|
Chess/InputManager.h
|
#ifndef INPUT_MANAGER_H
#define INPUT_MANAGER_H
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <time.h>
#include <chrono>
#include <thread>
#include "GameManager.h"
#include "PieceManager.h"
#include "RuleManager.h"
#include "Grid.h"
#include "PieceType.h"
#include "Color.h"
using namespace std::this_thread;
using namespace std::chrono;
class InputManager
{
private:
~InputManager();
InputManager() {}
static InputManager* instance;
bool check = false;
int check_mate_steps = 0;
int bot_thinking = 0;
bool bot_thinking_text_once = false;
const int MAX_BOT_THINK = 25000;
const int BOT_THINK_WRITE_BOT_THINK = 1000;
const seconds BOT_WAIT_FOR_SEC = 1s;
bool checkInput(int column, int row);
bool isInPossibleSteps(Grid* grid, PieceManager* piece_manager, RuleManager* rule_manager, std::shared_ptr<Piece> piece, std::shared_ptr<Position> position);
int actPlayersPossibleStepsCount(Grid* grid, PieceManager* piece_manager, RuleManager* rule_manager, GameManager* game_manager);
bool checkCheckMate(Grid* grid, PieceManager* piece_manager, RuleManager* rule_manager, Color color, GameManager* game_manager);
int getPieceValue(std::shared_ptr<Piece> piece);
int exit();
std::vector<std::shared_ptr<Position>> possibleSteps(Grid* grid, PieceManager* piece_manager, RuleManager* rule_manager, std::shared_ptr<Piece> piece);
void promotion(PieceManager* piece_manager, std::shared_ptr<Piece> piece, bool bot);
void checkCheck(Grid* grid, PieceManager* piece_manager, RuleManager* rule_manager, Color color);
void clearConsole();
void play(GameManager* previous_game_manager = nullptr);
void results();
bool increaseBotThinking(GameManager* game_manager);
public:
static InputManager* Instance();
void Menu();
void ReadCommand(PieceManager* piece_manager, Grid* grid, RuleManager* rule_manager, GameManager* game_manager);
};
#endif INPUT_MANAGER_H
|
bricsi0000000000000/Chess
|
Chess/Grid.h
|
<reponame>bricsi0000000000000/Chess
#ifndef GRID_H
#define GRID_H
#include<vector>
#include "Field.h"
#include "Position.h"
#include "PieceManager.h"
#ifdef _WIN32
#include <Windows.h>
#endif
class Grid
{
private:
std::vector<std::vector<std::shared_ptr<Field>>> grid;
PieceManager* piece_manager;
#pragma GRID_CHARACTERS
#ifdef _WIN32
const char horizontal_line = (char)196;
#endif
#ifdef linux
const char horizontal_line = '-';
#endif
#ifdef _WIN32
const char cross_line = (char)197;
#endif
#ifdef linux
const char cross_line = '+';
#endif
#ifdef _WIN32
const char vertical_line = (char)179;
#endif
#ifdef linux
const char vertical_line = '|';
#endif
#ifdef _WIN32
const char top_right_edge = (char)191;
#endif
#ifdef linux
const char top_right_edge = '-';
#endif
#ifdef _WIN32
const char top_left_edge = (char)218;
#endif
#ifdef linux
const char top_left_edge = '-';
#endif
#ifdef _WIN32
const char bottom_left_edge = (char)192;
#endif
#ifdef linux
const char bottom_left_edge = '-';
#endif
#ifdef _WIN32
const char bottom_right_edge = (char)217;
#endif
#ifdef linux
const char bottom_right_edge = '-';
#endif
#ifdef _WIN32
const char bottom_mid = (char)193;
#endif
#ifdef linux
const char bottom_mid = '-';
#endif
#ifdef _WIN32
const char top_mid = (char)194;
#endif
#ifdef linux
const char top_mid = '-';
#endif
#ifdef _WIN32
const char right_mid = (char)180;
#endif
#ifdef linux
const char right_mid = '|';
#endif
#ifdef _WIN32
const char left_mid = (char)195;
#endif
#ifdef linux
const char left_mid = '|';
#endif
#pragma endregion
#ifdef _WIN32
#pragma region CONSOLE_COLORS
HANDLE coloring = GetStdHandle(STD_OUTPUT_HANDLE);
int black_white = 7;
int border_color = 8;
int white_piece_color = 15;
int black_piece_color = 14;
int pink_color = 13;
#pragma endregion
#endif
void setConsoleColor(std::string color_name);
void clearConsole();
void writePieceNameInitials(std::shared_ptr<Piece> piece);
public:
void InitGrid(PieceManager* piece_manager);
void DrawGrid(GameManager* game_manager, std::vector<std::shared_ptr<Position>> highlight_cells = {});
std::vector<std::vector<std::shared_ptr<Field>>> GetGrid();
};
#endif GRID_H
|
bricsi0000000000000/Chess
|
linux/Chess/PieceType.h
|
<filename>linux/Chess/PieceType.h
#ifndef PIECETYPE_H
#define PIECETYPE_H
enum class PieceType
{
Pawn, Rook, Knight, Bishop, Queen, King, Nothing
};
#endif // PIECETYPE_H
|
bricsi0000000000000/Chess
|
linux/Chess/Player.h
|
<filename>linux/Chess/Player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <string>
#include <vector>
#include "Color.h"
#include "Piece.h"
class Player
{
private:
std::string name;
int points;
Color color;
std::vector<std::shared_ptr<Piece>> off_pieces;
bool is_bot;
std::string step_from;
std::string step_to;
std::shared_ptr<Piece> step_piece;
public:
Player(std::string name, Color color, bool is_bot);
std::string GetName();
int GetPoints();
void AddPoints(int points);
Color GetColor();
std::vector<std::shared_ptr<Piece>> GetOffPieces();
void AddOffPiece(std::shared_ptr<Piece> piece);
void RemoveOffPiece(std::shared_ptr<Piece> piece);
void ClearOffPieces();
bool IsBot();
std::string GetStepFrom();
std::string GetStepTo();
void SetStepFrom(std::string position);
void SetStepTo(std::string position);
std::shared_ptr<Piece> GetStepPiece();
void SetStepPiece(std::shared_ptr<Piece> piece);
};
#endif // PLAYER_H
|
bricsi0000000000000/Chess
|
Chess/PieceType.h
|
<reponame>bricsi0000000000000/Chess
#ifndef PIECE_TYPE_H
#define PIECE_TYPE_H
enum class PieceType
{
Pawn, Rook, Knight, Bishop, Queen, King, Nothing
};
#endif PIECE_TYPE_H
|
bricsi0000000000000/Chess
|
linux/Chess/RuleManager.h
|
#ifndef RULEMANAGER_H
#define RULEMANAGER_H
#include <iostream>
#include <cmath>
#include "Piece.h"
#include "Position.h"
#include "PieceManager.h"
class RuleManager {
private:
~RuleManager();
RuleManager() {}
static RuleManager* instance;
public:
static RuleManager* Instance();
static bool CanStep(std::shared_ptr<Piece> piece, std::shared_ptr<Position> position, PieceManager* piece_manager);
};
#endif // RULEMANAGER_H
|
bricsi0000000000000/Chess
|
Chess/Position.h
|
#ifndef POSITION_H
#define POSITION_H
#include<iostream>
class Position {
public:
Position(int x, int y) : x(x), y(y) {}
int x;
int y;
};
#endif POSITION_H
|
bricsi0000000000000/Chess
|
Chess/GameManager.h
|
#ifndef GAME_MANAGER_H
#define GAME_MANAGER_H
#include <fstream>
#include <sstream>
#include "Player.h"
class GameManager {
private:
~GameManager();
GameManager() {}
static GameManager* instance;
bool game_over = false;
Player* player_one;
Player* player_two;
int act_player = 1;
std::stringstream all_steps;
void saveResults();
void saveAllSteps();
public:
static GameManager* Instance();
void ReStartGame();
void StartGame(std::string player_one_name, bool player_one_is_bot, std::string player_two_name, bool player_two_is_bot);
bool GetGameOver();
void GameOver(bool opposite_player = false);
void GiveUp();
Player* GetPlayerOne();
Player* GetPlayerTwo();
Player* GetActPlayer();
int GetActPlayerNumber();
Player* GetOppositePlayer();
void ChangePlayer();
void AddStepToAllSteps();
};
#endif GAME_MANAGER_H
|
bricsi0000000000000/Chess
|
linux/Chess/PieceManager.h
|
#ifndef PIECEMANAGER_H
#define PIECEMANAGER_H
#include<vector>
#include<memory>
#include "Piece.h"
#include "PieceType.h"
#include "GameManager.h"
#include "Color.h"
class PieceManager {
private:
std::vector<std::shared_ptr<Piece>> pieces;
~PieceManager();
PieceManager() {}
static PieceManager* instance;
public:
static PieceManager* Instance();
void InitPieces();
std::shared_ptr<Piece> GetKing(Color color);
int GetPieceCount(Color color);
int GetPieceCount(PieceType piece_type, Color color);
std::shared_ptr<Piece> GetPiece(std::shared_ptr<Position> position);
bool CanMove(std::shared_ptr<Position> from_position, std::shared_ptr<Position> to_position);
void MovePiece(std::shared_ptr<Position> from_position, std::shared_ptr<Position> to_position);
void RemovePiece(std::shared_ptr<Position> position, GameManager* game_manager);
void RevivePiece(std::shared_ptr<Piece> piece, GameManager* game_manager);
void ChangePiece(std::shared_ptr<Piece> old_piece, std::string name, PieceType piece_type);
std::vector<std::shared_ptr<Piece>> GetPieces();
};
#endif // PIECEMANAGER_H
|
bricsi0000000000000/Chess
|
Chess/Color.h
|
<filename>Chess/Color.h
#ifndef COLOR_H
#define COLOR_H
enum class Color
{
White, Black, Nothing
};
#endif COLOR_H
|
bricsi0000000000000/Chess
|
Chess/Field.h
|
#ifndef FIELD_H
#define FIELD_H
#include<memory>
#include "Position.h"
#include "Piece.h"
class Field
{
private:
std::shared_ptr<Position> position;
std::shared_ptr<Piece> piece;
Color color;
public:
Field(std::shared_ptr<Position> position, std::shared_ptr<Piece> piece, Color color);
std::shared_ptr<Position> GetPosition();
std::shared_ptr<Piece> GetPiece();
Color GetColor();
};
#endif FIELD_H
|
bricsi0000000000000/Chess
|
Chess/Piece.h
|
<filename>Chess/Piece.h
#ifndef PIECE_H
#define PIECE_H
#include<string>
#include "Position.h"
#include "Color.h"
#include "PieceType.h"
class Piece
{
private:
std::string name;
std::shared_ptr<Position> position;
Color color;
PieceType piece_type;
public:
Piece();
Piece(std::string name, std::shared_ptr<Position> position, Color color, PieceType piece_type);
std::string GetName();
void SetName(std::string name);
std::shared_ptr<Position> GetPosition();
void SetPosition(std::shared_ptr<Position> to_position);
Color GetColor();
PieceType GetPieceType();
void SetPieceType(PieceType piece_type);
};
#endif PIECE_H
|
Dont-laugh/DLSoftRender
|
src/include/DLVector2.h
|
#pragma once
#include <cmath>
namespace DontLaugh
{
/* 2D Vector implemented by DontLaugh */
struct DLVector2
{
public:
float X;
float Y;
public:
DLVector2();
DLVector2(float InF);
DLVector2(float X, float Y);
static const DLVector2 Zero;
static const DLVector2 One;
static DLVector2 Cross(const DLVector2& A, const DLVector2& B);
static float Dot(const DLVector2& A, const DLVector2& B);
float Length() const;
bool Equals(const DLVector2& V) const;
DLVector2 operator+(const DLVector2& V);
DLVector2 operator-(const DLVector2& V);
DLVector2 operator*(const DLVector2& V);
DLVector2 operator/(const DLVector2& V);
private:
static const float epsilon;
};
const DLVector2 DLVector2::Zero(0, 0);
const DLVector2 DLVector2::One(1, 1);
constexpr float DLVector2::epsilon = 1e-4f;
inline DLVector2::DLVector2() : X(0), Y(0) { }
inline DLVector2::DLVector2(float InF) : X(InF), Y(InF) { }
inline DLVector2::DLVector2(float X, float Y) : X(X), Y(Y) { }
inline DLVector2 DLVector2::Cross(const DLVector2& A, const DLVector2& B)
{
return { A.X * B.Y - B.X * A.Y };
}
inline float DLVector2::Dot(const DLVector2& A, const DLVector2& B)
{
return A.X * B.X + A.Y * B.Y;
}
inline float DLVector2::Length() const
{
return std::sqrt(X * X + Y * Y);
}
inline bool DLVector2::Equals(const DLVector2& V) const
{
return std::abs(X - V.X) <= epsilon && std::abs(Y - V.Y) <= epsilon;
}
inline DLVector2 DLVector2::operator+(const DLVector2& V)
{
return { X + V.X, Y + V.Y };
}
inline DLVector2 DLVector2::operator-(const DLVector2& V)
{
return { X - V.X, Y - V.Y };
}
inline DLVector2 DLVector2::operator*(const DLVector2& V)
{
return { X * V.X, Y * V.Y };
}
inline DLVector2 DLVector2::operator/(const DLVector2& V)
{
return { X / V.X, Y / V.Y };
}
}
|
Dont-laugh/DLSoftRender
|
src/include/DLPoint.h
|
<reponame>Dont-laugh/DLSoftRender<gh_stars>0
#pragma once
namespace DontLaugh
{
/* Point implemented by DontLaugh */
struct DLPoint
{
int X;
int Y;
};
}
|
Dont-laugh/DLSoftRender
|
src/include/DLRenderer.h
|
<reponame>Dont-laugh/DLSoftRender
#pragma once
#include <functional>
#include "SDL.h"
#include "DLPoint.h"
namespace DontLaugh
{
/* Soft renderer implemented by DontLaugh */
class DLRenderer
{
public:
DLRenderer();
DLRenderer(int Width, int Height);
~DLRenderer();
void RenderLoop(const std::function<void(SDL_Event&)>& Callback) const;
void SetRenderColor(Uint8 R, Uint8 G, Uint8 B, Uint8 A) const;
void DrawPixel(int X, int Y) const;
void DrawLine(int X0, int Y0, int X1, int Y1) const;
void DrawTriangle(DLPoint* Points) const;
Uint32 GetTicks() const { return SDL_GetTicks(); }
private:
static Uint32 fps;
static Uint32 last_time;
static Uint32 frame_count;
SDL_Window* window;
SDL_Renderer* renderer;
std::string title;
};
}
|
Dont-laugh/DLSoftRender
|
src/include/DLRect.h
|
#pragma once
namespace DontLaugh
{
struct DLRect
{
public:
int X;
int Y;
int Width;
int Height;
public:
DLRect();
DLRect(int X, int Y, int Width, int Height);
};
DLRect::DLRect() : X(0), Y(0), Width(0), Height(0)
{
}
DLRect::DLRect(int X, int Y, int Width, int Height) : X(X), Y(Y), Width(Width), Height(Height)
{
}
}
|
Dont-laugh/DLSoftRender
|
src/include/DLQuat.h
|
#pragma once
#include "DLVector3.h"
namespace DontLaugh
{
/* Quaternion implemented by DontLaugh */
struct DLQuat
{
public:
float X;
float Y;
float Z;
float W;
public:
DLQuat();
DLQuat(float InX, float InY, float InZ, float InW);
DLQuat(DLVector3 Axis, float AngleRad);
static const DLQuat Identity;
};
}
|
Dont-laugh/DLSoftRender
|
src/include/DLVector3.h
|
#pragma once
#include <cmath>
namespace DontLaugh
{
/* 3D Vector implemented by DontLaugh */
struct DLVector3
{
public:
float X;
float Y;
float Z;
public:
DLVector3();
DLVector3(float InF);
DLVector3(float X, float Y, float Z);
static const DLVector3 Zero;
static const DLVector3 One;
static DLVector3 Cross(const DLVector3& A, const DLVector3& B);
static float Dot(const DLVector3& A, const DLVector3& B);
float Length() const;
bool Equals(const DLVector3& V) const;
DLVector3 operator+(const DLVector3& V);
DLVector3 operator-(const DLVector3& V);
DLVector3 operator*(const DLVector3& V);
DLVector3 operator/(const DLVector3& V);
private:
static const float epsilon;
};
const DLVector3 DLVector3::Zero(0, 0, 0);
const DLVector3 DLVector3::One(1, 1, 1);
constexpr float DLVector3::epsilon = 1e-4f;
inline DLVector3::DLVector3() : X(0), Y(0), Z(0) { }
inline DLVector3::DLVector3(float InF) : X(InF), Y(InF), Z(InF) { }
inline DLVector3::DLVector3(float X, float Y, float Z) : X(X), Y(Y), Z(Z) { }
inline DLVector3 DLVector3::Cross(const DLVector3& A, const DLVector3& B)
{
return { A.Y * B.Z - A.Z * B.Y, A.Z * B.X - A.X * B.Z, A.X * B.Y - A.Y * B.X };
}
inline float DLVector3::Dot(const DLVector3& A, const DLVector3& B)
{
return A.X * B.X + A.Y * B.Y + A.Z * B.Z;
}
inline float DLVector3::Length() const
{
return std::sqrt(X * X + Y * Y + Z * Z);
}
inline bool DLVector3::Equals(const DLVector3& V) const
{
return std::abs(X - V.X) <= epsilon && std::abs(Y - V.Y) <= epsilon && std::abs(Z - V.Z) <= epsilon;
}
inline DLVector3 DLVector3::operator+(const DLVector3& V)
{
return { X + V.X, Y + V.Y, Z + V.Z };
}
inline DLVector3 DLVector3::operator-(const DLVector3& V)
{
return { X - V.X, Y - V.Y, Z - V.Z };
}
inline DLVector3 DLVector3::operator*(const DLVector3& V)
{
return { X * V.X, Y * V.Y, Z * V.Z };
}
inline DLVector3 DLVector3::operator/(const DLVector3& V)
{
return { X / V.X, Y / V.Y, Z / V.Z };
}
}
|
SNU-Programming-Tools/nballerina
|
runtime/tests/list_construct.c
|
<reponame>SNU-Programming-Tools/nballerina
#include "string_utils.h"
#include "list_utils.h"
ListDesc DESC_INT = LIST_DESC_INIT_INT_ARRAY(10);
ListDesc DESC_STRING = LIST_DESC_INIT_GENERIC(120, 1 << TAG_STRING);
HASH_DEFINE_KEY;
void testListConstructEmpty() {
ListPtr lp = _bal_list_construct_8(&DESC_INT, 0);
assert(lp->desc == &DESC_INT);
assert(lp->tpArray.length == 0);
assert(lp->tpArray.capacity == 0);
assert(lp->tpArray.members == NULL);
}
void testListConstruct() {
int64_t capacity = 10;
ListPtr lp = _bal_list_construct_8(&DESC_INT, capacity);
assert(lp->desc == &DESC_INT);
assert(lp->tpArray.length == 0);
assert(lp->tpArray.capacity == capacity);
assert(lp->tpArray.members != NULL);
}
bool isByte(struct UniformSubtype * ut, TaggedPtr tp) {
if ((getTag(tp) & UT_MASK) != TAG_INT) {
return false;
}
int64_t i = taggedToInt(tp);
return i < 0 || UINT8_MAX < i;
}
typedef struct {
uint32_t all;
uint32_t some;
UniformSubtypePtr subtypes[1];
} ByteComplexType;
void testByteList() {
UniformSubtype byteSubtype = { isByte };
ByteComplexType byteComplexType = { 0, 1 << TAG_INT, { &byteSubtype } };
MemberType byteType = (MemberType)&byteComplexType;
ListDesc descByte = LIST_DESC_INIT_BYTE_ARRAY(84, byteType);
int64_t capacity = 10;
ListPtr lp = _bal_list_construct_1(&descByte, capacity);
assert(lp->desc == &descByte);
assert(lp->tpArray.length == 0);
assert(lp->tpArray.capacity == capacity);
assert(lp->tpArray.members != NULL);
TaggedPtr tp = ptrAddFlags(lp, ((uint64_t)TAG_LIST_RW << TAG_SHIFT)|EXACT_FLAG);
PanicCode err;
err = _bal_list_byte_array_set_int(tp, 4, 256);
assert(err);
err = _bal_list_byte_array_set_tagged(tp, 24, randSmallString());
assert(err);
int i;
for (i = 0; i < 50; i++) {
err = _bal_list_byte_array_set_int(tp, i, i);
assert(!err);
}
for (i = 50; i < 100; i++) {
err = _bal_list_byte_array_set_tagged(tp, i, intToTagged(i));
assert(!err);
}
for (i = 0; i < 100; i++) {
assert(_bal_list_byte_array_get_int(tp, i) == i);
}
}
void testListSet(int64_t capacity, int64_t length) {
TaggedPtr *strs = malloc(sizeof(TaggedPtr) * length);
int i;
for (i = 0; i < length; i++) {
strs[i] = randSmallString();
}
ListPtr lp = _bal_list_construct_8(&DESC_STRING, capacity);
assert(lp->tpArray.capacity == capacity);
TaggedPtr taggedLp = ptrAddFlags(lp, ((uint64_t)TAG_LIST_RW << TAG_SHIFT)|EXACT_FLAG);
for (i = 0; i < length; i++) {
_bal_list_generic_set_tagged(taggedLp, i, strs[i]);
}
assert(lp->desc == &DESC_STRING);
assert(lp->tpArray.length == length);
assert(lp->tpArray.capacity >= length);
GC TaggedPtr *members = lp->tpArray.members;
for (i = 0; i < length; i++) {
assert(members[i] == strs[i]);
}
}
int main() {
testListConstructEmpty();
testListConstruct();
testByteList();
testListSet(4, 4);
testListSet(8, 5);
testListSet(3, 6);
return 0;
}
|
SNU-Programming-Tools/nballerina
|
runtime/tests/string_len.c
|
#include "string_utils.h"
void validateStringSizeInt64(const uint64_t stringSize, const uint64_t headerSize, const uint64_t lengthInBytes) {
uint64_t size = lengthInBytes + headerSize;
uint64_t multiple = size / 8;
if (size % 8 != 0)
multiple++;
uint64_t expectedSize = 8 * multiple;
assert(expectedSize == stringSize);
}
void validateStringSizeInt(const int stringSize, const int headerSize, const int lengthInBytes) {
uint64_t size = lengthInBytes + headerSize;
uint64_t multiple = size / 8;
if (size % 8 != 0)
multiple++;
uint64_t expectedSize = 8 * multiple;
assert(expectedSize == stringSize);
}
void validateTaggedStringLength(const TaggedPtr ptr, const uint64_t lengthInBytes, const uint64_t lengthInCodePoints) {
const StringLength actual = taggedStringLength(ptr);
assert(lengthInBytes == actual.nBytes);
assert(lengthInCodePoints == actual.nCodePoints);
bool isChar = taggedStringIsChar(ptr);
assert(isChar == (lengthInCodePoints == 1));
}
void testLargeStringSize(){
validateStringSizeInt64(largeStringSize(0), 16, 0);
validateStringSizeInt64(largeStringSize(UINT64_MAX), 16, UINT64_MAX);
for (int i = 0; i < NTESTS; i++){
uint64_t val = rand();
validateStringSizeInt64(largeStringSize(val), 16, val);
}
}
void testMediumStringSize(){
validateStringSizeInt(mediumStringSize(0), 4, 0);
validateStringSizeInt(mediumStringSize(INT32_MAX), 4, INT32_MAX);
for (int i = 0; i < NTESTS; i++){
int val = rand();
validateStringSizeInt(mediumStringSize(val), 4, val);
}
}
TaggedPtr createMediumString(uint16_t lengthInBytes, uint16_t lengthInCodePoints) {
int size = mediumStringSize(lengthInBytes);
UntypedPtr p = _bal_alloc(size);
((GC uint64_t *)((GC char *)p + size))[-1] = 0;
MediumStringPtr ptr = p;
ptr->lengthInBytes = lengthInBytes;
ptr->lengthInCodePoints = lengthInCodePoints;
TaggedPtr tPtr = ptrAddFlags(ptr, (uint64_t)TAG_STRING << TAG_SHIFT);
return tPtr;
}
TaggedPtr createLargeString(int64_t lengthInBytes, int64_t lengthInCodePoints) {
int size = largeStringSize(lengthInBytes);
UntypedPtr p = _bal_alloc(size);
((GC uint64_t *)((GC char *)p + size))[-1] = 0;
LargeStringPtr ptr = p;
ptr->lengthInBytes = lengthInBytes;
ptr->lengthInCodePoints = lengthInCodePoints;
TaggedPtr tPtr = ptrAddFlags(ptr, ((uint64_t)TAG_STRING << TAG_SHIFT) | STRING_LARGE_FLAG);
return tPtr;
}
void testTaggedLargeStringLength() {
validateTaggedStringLength(createLargeString(7, 7), 7, 7);
validateTaggedStringLength(createLargeString(INT64_MAX, INT64_MAX), INT64_MAX, INT64_MAX);
for (int i = 0; i < NTESTS; i++)
{
int64_t byteLen = rand();
int64_t codePointLen = rand();
validateTaggedStringLength(createLargeString(byteLen, codePointLen), byteLen, codePointLen);
}
}
void testTaggedMediumStringLength() {
validateTaggedStringLength(createMediumString(7, 7), 7, 7);
validateTaggedStringLength(createMediumString(UINT16_MAX, UINT16_MAX), UINT16_MAX, UINT16_MAX);
for (int i = 0; i < NTESTS; i++)
{
int64_t byteLen = rand() % UINT16_MAX;
int64_t codePointLen = rand() % UINT16_MAX;
validateTaggedStringLength(createMediumString(byteLen, codePointLen), byteLen, codePointLen);
}
}
void testTaggedImmeidateStringLength() {
// test ASCII
validateTaggedStringLength(bitsToTaggedPtr(0x2AFFFFFFFFFFFFFF), 0, 0); // ""
validateTaggedStringLength(bitsToTaggedPtr(0x2AFFFFFFFFFF4142), 2, 2); // "BA"
validateTaggedStringLength(bitsToTaggedPtr(0x2AFFFFFFFF613223), 3, 3); // "#2a"
validateTaggedStringLength(bitsToTaggedPtr(0x2AFFFFFF256C6420), 4, 4); // " dl%"
validateTaggedStringLength(bitsToTaggedPtr(0x2AFFFF6162606364), 5, 5); // "cd`ba"
validateTaggedStringLength(bitsToTaggedPtr(0x2AFF2A2625242C3F), 6, 6); // "?,$%&*"
validateTaggedStringLength(bitsToTaggedPtr(0x2A61626364656667), 7, 7); // "gfedcab"
// testUnicode
validateTaggedStringLength(bitsToTaggedPtr(0x2AFFFFFFFFFFA2C2), 2, 1); // "¢"
validateTaggedStringLength(bitsToTaggedPtr(0x2AFFFFFFFF9E99E2), 3, 1); // "♞"
validateTaggedStringLength(bitsToTaggedPtr(0x2AFFFFFF97A49FF0), 4, 1); // "🤗"
validateTaggedStringLength(bitsToTaggedPtr(0x2AFFFFFF90A69FF0), 4, 1); // "🦀"
}
HASH_DEFINE_KEY;
int main() {
srand(1);
testLargeStringSize();
testMediumStringSize();
testTaggedLargeStringLength();
testTaggedMediumStringLength();
testTaggedImmeidateStringLength();
return 0;
}
|
SNU-Programming-Tools/nballerina
|
runtime/list.c
|
<filename>runtime/list.c
#include "balrt.h"
#include <string.h>
#define ARRAY_LENGTH_MAX ((int64_t)(INT64_MAX/sizeof(TaggedPtr)))
static inline Fillability arrayCreateFiller(ListDescPtr ldp, TaggedPtr *valuePtr) {
return _bal_structure_create_filler(ldp->restType, ldp->fillerDesc, valuePtr);
}
static inline bool listDescAllowsTaggedAt(ListDescPtr ldp, int64_t index, TaggedPtr val) {
MemberType mt;
// If we get a negative index here, we treat it as having the rest type.
if ((uint64_t)index < (uint64_t)ldp->minLength) {
uint32_t nMemberTypes = ldp->nMemberTypes;
mt = ldp->memberTypes[index < nMemberTypes ? index : nMemberTypes - 1];
}
else {
mt = ldp->restType;
}
return memberTypeContainsTagged(mt, val);
}
// Constructs a list with 8 bytes per member
ListPtr _bal_list_construct_8(ListDescPtr desc, int64_t capacity) {
ListPtr lp = _bal_alloc(sizeof(struct List));
lp->desc = desc;
initGenericArray(&(lp->gArray), capacity, TAGGED_PTR_SHIFT);
return lp;
}
// Constructs a list with 1 byte per member
ListPtr _bal_list_construct_1(ListDescPtr desc, int64_t capacity) {
ListPtr lp = _bal_alloc(sizeof(struct List));
lp->desc = desc;
initGenericArray(&(lp->gArray), capacity, BYTE_SHIFT);
return lp;
}
// _bal_list_*_get functions must be called with an index such that, 0 <= index < lp->gArray.length
TaggedPtr _bal_list_generic_get_tagged(TaggedPtr p, int64_t index) {
ListPtr lp = taggedToPtr(p);
GC TaggedPtrArray *ap = &(lp->tpArray);
return ap->members[index];
}
int64_t _bal_list_generic_get_int(TaggedPtr p, int64_t index) {
ListPtr lp = taggedToPtr(p);
GC TaggedPtrArray *ap = &(lp->tpArray);
return taggedToInt(ap->members[index]);
}
double _bal_list_generic_get_float(TaggedPtr p, int64_t index) {
ListPtr lp = taggedToPtr(p);
GC TaggedPtrArray *ap = &(lp->tpArray);
return taggedToFloat(ap->members[index]);
}
TaggedPtr _bal_list_int_array_get_tagged(TaggedPtr p, int64_t index) {
ListPtr lp = taggedToPtr(p);
GC IntArray *ap = &(lp->iArray);
return intToTagged(ap->members[index]);
}
int64_t _bal_list_int_array_get_int(TaggedPtr p, int64_t index) {
// SUBSET should only be called when subset supports int subtype arrays
fprintf(stderr, "warning: access int array via int type desc func pointer\n");
ListPtr lp = taggedToPtr(p);
GC IntArray *ap = &(lp->iArray);
return ap->members[index];
}
TaggedPtr _bal_list_byte_array_get_tagged(TaggedPtr p, int64_t index) {
ListPtr lp = taggedToPtr(p);
GC ByteArray *ap = &(lp->bArray);
return intToTagged(ap->members[index]);
}
int64_t _bal_list_byte_array_get_int(TaggedPtr p, int64_t index) {
ListPtr lp = taggedToPtr(p);
GC ByteArray *ap = &(lp->bArray);
return ap->members[index];
}
TaggedPtr _bal_list_float_array_get_tagged(TaggedPtr p, int64_t index) {
ListPtr lp = taggedToPtr(p);
GC FloatArray *ap = &(lp->fArray);
return floatToTagged(ap->members[index]);
}
double _bal_list_float_array_get_float(TaggedPtr p, int64_t index) {
// SUBSET should only be called when subset supports float subtype arrays
fprintf(stderr, "warning: access float array via float type desc func pointer\n");
ListPtr lp = taggedToPtr(p);
GC FloatArray *ap = &(lp->fArray);
return ap->members[index];
}
// We use this in the case where exactness does not guarantee that the set will succeed.
PanicCode _bal_list_generic_inexact_set_tagged(TaggedPtr p, int64_t index, TaggedPtr val) {
PanicCode code = _bal_list_generic_set_tagged(p, index, val);
return code == 0 ? 0 : PANIC_LIST_STORE;
}
PanicCode _bal_list_generic_set_tagged(TaggedPtr p, int64_t index, TaggedPtr val) {
ListPtr lp = taggedToPtr(p);
ListDescPtr ldp = lp->desc;
if (!listDescAllowsTaggedAt(ldp, index, val)) {
return storePanicCode(p, PANIC_LIST_STORE);
}
GC TaggedPtrArray *ap = &(lp->tpArray);
// The cast makes this handle the negative case also in a single comparison
if (likely((uint64_t)index < (uint64_t)ap->length)) {
ap->members[index] = val;
return 0;
}
TaggedPtr filler;
Fillability fill;
if (index > ap->length) {
// we have a gap to fill
fill = arrayCreateFiller(ldp, &filler);
if (fill == FILL_NONE) {
// Note that we panic before trying to grow the array
return PANIC_NO_FILLER;
}
}
else {
fill = FILL_NONE;
}
// The cast makes this handle the negative case also in a single comparison
if (unlikely((uint64_t)index >= (uint64_t)ap->capacity)) {
if (unlikely((uint64_t)index >= ARRAY_LENGTH_MAX)) {
return index < 0 ? PANIC_INDEX_OUT_OF_BOUNDS : PANIC_LIST_TOO_LONG;
}
_bal_array_grow(&(lp->gArray), index + 1, TAGGED_PTR_SHIFT);
}
// Know that: ap->length <= index < ap->capacity
if (fill != FILL_NONE) {
// gap is from length..<index
ap->members[ap->length] = filler;
for (int64_t i = ap->length + 1; i < index; i++) {
if (fill == FILL_EACH) {
(void)arrayCreateFiller(ldp, &filler);
}
ap->members[i] = filler;
}
}
ap->members[index] = val;
ap->length = index + 1;
return 0;
}
TaggedPtrPanicCode _bal_list_filling_get(TaggedPtr p, int64_t index) {
TaggedPtrPanicCode result;
ListPtr lp = taggedToPtr(p);
GC TaggedPtrArray *ap = &(lp->tpArray);
if (likely((uint64_t)index < (uint64_t)ap->length)) {
result.ptr = ap->members[index];
result.panicCode = 0;
return result;
}
if (unlikely(index < 0)) {
result.panicCode = PANIC_INDEX_OUT_OF_BOUNDS;
return result;
}
ListDescPtr ldp = lp->desc;
TaggedPtr filler;
Fillability fill = arrayCreateFiller(ldp, &filler);
if (fill == FILL_NONE) {
result.panicCode = PANIC_NO_FILLER;
return result;
}
if (index >= ap->capacity) {
if (index >= ARRAY_LENGTH_MAX) {
result.panicCode = PANIC_LIST_TOO_LONG;
return result;
}
_bal_array_grow(&(lp->gArray), index + 1, TAGGED_PTR_SHIFT);
}
ap->members[index] = filler;
result.ptr = filler;
result.panicCode = 0;
for (int64_t i = ap->length; i < index; i++) {
// Probably will only call this when FILL_EACH would be true,
// but let's handle all cases.
if (likely(fill == FILL_EACH)) {
(void)arrayCreateFiller(ldp, &filler);
}
ap->members[i] = filler;
}
ap->length = index + 1;
return result;
}
PanicCode _bal_list_generic_inexact_set_float(TaggedPtr p, int64_t index, double val) {
return _bal_list_generic_inexact_set_tagged(p, index, floatToTagged(val));
}
PanicCode _bal_list_generic_set_float(TaggedPtr p, int64_t index, double val) {
return _bal_list_generic_set_tagged(p, index, floatToTagged(val));
}
PanicCode _bal_list_generic_inexact_set_int(TaggedPtr p, int64_t index, int64_t val) {
return _bal_list_generic_inexact_set_tagged(p, index, intToTagged(val));
}
PanicCode _bal_list_generic_set_int(TaggedPtr p, int64_t index, int64_t val) {
return _bal_list_generic_set_tagged(p, index, intToTagged(val));
}
PanicCode _bal_list_int_array_set_tagged(TaggedPtr p, int64_t index, TaggedPtr val) {
if ((getTag(val) & UT_MASK) != TAG_INT) {
return storePanicCode(p, PANIC_LIST_STORE);
}
return _bal_list_int_array_set_int(p, index, taggedToInt(val));
}
PanicCode _bal_list_int_array_set_int(TaggedPtr p, int64_t index, int64_t val) {
ListPtr lp = taggedToPtr(p);
GC IntArray *ap = &(lp->iArray);
// The cast makes this handle the negative case also in a single comparison
if (likely((uint64_t)index < (uint64_t)ap->length)) {
ap->members[index] = val;
return 0;
}
// The cast makes this handle the negative case also in a single comparison
if (unlikely((uint64_t)index >= (uint64_t)ap->capacity)) {
if (unlikely((uint64_t)index >= ARRAY_LENGTH_MAX)) {
return index < 0 ? PANIC_INDEX_OUT_OF_BOUNDS : PANIC_LIST_TOO_LONG;
}
_bal_array_grow(&(lp->gArray), index + 1, TAGGED_PTR_SHIFT);
}
// Know that: ap->length <= index < ap->capacity
if (index > ap->length) {
// we have a gap to fill
// from length..<index
memset(&(ap->members[ap->length]), 0, sizeof(int64_t) * (index - ap->length));
}
ap->members[index] = val;
ap->length = index + 1;
return 0;
}
PanicCode _bal_list_int_array_set_float(TaggedPtr p, UNUSED int64_t index, UNUSED double val) {
return storePanicCode(p, PANIC_LIST_STORE);
}
PanicCode _bal_list_byte_array_set_tagged(TaggedPtr p, int64_t index, TaggedPtr val) {
if ((getTag(val) & UT_MASK) != TAG_INT) {
return storePanicCode(p, PANIC_LIST_STORE);
}
return _bal_list_byte_array_set_int(p, index, taggedToInt(val));
}
PanicCode _bal_list_byte_array_set_int(TaggedPtr p, int64_t index, int64_t valInt) {
if (valInt < 0 || UINT8_MAX < valInt) {
return storePanicCode(p, PANIC_LIST_STORE);
}
uint8_t val = (uint8_t)valInt;
ListPtr lp = taggedToPtr(p);
GC ByteArray *ap = &(lp->bArray);
// The cast makes this handle the negative case also in a single comparison
if (likely((uint64_t)index < (uint64_t)ap->length)) {
ap->members[index] = val;
return 0;
}
// The cast makes this handle the negative case also in a single comparison
if (unlikely((uint64_t)index >= (uint64_t)ap->capacity)) {
if (unlikely((uint64_t)index >= ARRAY_LENGTH_MAX)) {
return index < 0 ? PANIC_INDEX_OUT_OF_BOUNDS : PANIC_LIST_TOO_LONG;
}
_bal_array_grow(&(lp->gArray), index + 1, BYTE_SHIFT);
}
// Know that: ap->length <= index < ap->capacity
if (index > ap->length) {
// we have a gap to fill
// from length..<index
memset(&(ap->members[ap->length]), 0, index - ap->length);
}
ap->members[index] = val;
ap->length = index + 1;
return 0;
}
PanicCode _bal_list_byte_array_set_float(TaggedPtr p, UNUSED int64_t index, UNUSED double val) {
return storePanicCode(p, PANIC_LIST_STORE);
}
PanicCode _bal_list_float_array_set_tagged(TaggedPtr p, int64_t index, TaggedPtr val) {
if ((getTag(val) & UT_MASK) != TAG_FLOAT) {
return storePanicCode(p, PANIC_LIST_STORE);
}
return _bal_list_float_array_set_float(p, index, taggedToFloat(val));
}
PanicCode _bal_list_float_array_set_int(TaggedPtr p, UNUSED int64_t index, UNUSED int64_t val) {
return storePanicCode(p, PANIC_LIST_STORE);
}
PanicCode _bal_list_float_array_set_float(TaggedPtr p, int64_t index, double val) {
ListPtr lp = taggedToPtr(p);
GC FloatArray *ap = &(lp->fArray);
// The cast makes this handle the negative case also in a single comparison
if (likely((uint64_t)index < (uint64_t)ap->length)) {
ap->members[index] = val;
return 0;
}
// The cast makes this handle the negative case also in a single comparison
if (unlikely((uint64_t)index >= (uint64_t)ap->capacity)) {
if (unlikely((uint64_t)index >= ARRAY_LENGTH_MAX)) {
return index < 0 ? PANIC_INDEX_OUT_OF_BOUNDS : PANIC_LIST_TOO_LONG;
}
_bal_array_grow(&(lp->gArray), index + 1, TAGGED_PTR_SHIFT);
}
// Know that: ap->length <= index < ap->capacity
if (index > ap->length) {
// we have a gap to fill
// from length..<index
memset(&(ap->members[ap->length]), 0, sizeof(int64_t) * (index - ap->length));
}
ap->members[index] = val;
ap->length = index + 1;
return 0;
}
#define INITIAL_CAPACITY 4
// Grows the array.
// The new capacity must be greater than both the old capacity
// and min_capacity.
// Caller must ensure min_capacity <= ARRAY_LENGTH_MAX
void _bal_array_grow(GC GenericArray *ap, int64_t min_capacity, int shift) {
int64_t old_capacity = ap->capacity;
int64_t new_capacity;
// Deal with case where capacity is 0
// Implies length is also 0
if (old_capacity == 0) {
new_capacity = min_capacity > INITIAL_CAPACITY ? min_capacity : INITIAL_CAPACITY;
ap->members = _bal_alloc(new_capacity << shift);
ap->capacity = new_capacity;
return;
}
// Increase capacity by a factor of 1.5
int64_t extra_capacity = ap->capacity >> 1;
if (likely(old_capacity <= ARRAY_LENGTH_MAX - extra_capacity)) {
// we know that this addition cannot overflow
// and that new_capacity <= ARRAY_LENGTH_MAX
new_capacity = old_capacity + extra_capacity;
}
else {
new_capacity = ARRAY_LENGTH_MAX;
if (new_capacity == old_capacity)
_bal_panic(_bal_panic_construct(PANIC_LIST_TOO_LONG)); // we won't get a line number, but this is very unlikely to be possible
}
if (unlikely(new_capacity < min_capacity)) {
new_capacity = min_capacity;
}
// we know the multiplication cannot overflow because new_capacity <= ARRAY_MAX
GC TaggedPtr *new_members = _bal_alloc(new_capacity << shift);
// ap->length may be zero, but ap->members will not be null in this case
// because we checked at the beginning that capacity was not zero
memcpy(new_members, ap->members, ap->length << shift);
ap->members = new_members;
ap->capacity = new_capacity;
}
bool _bal_list_eq(TaggedPtr p1, TaggedPtr p2) {
return _bal_list_eq_internal(p1, p2, 0);
}
bool _bal_list_eq_internal(TaggedPtr p1, TaggedPtr p2, EqStack *sp) {
ListPtr lp1 = taggedToPtr(p1);
GC TaggedPtrArray *ap1 = &(lp1->tpArray);
ListPtr lp2 = taggedToPtr(p2);
GC TaggedPtrArray *ap2 = &(lp2->tpArray);
int64_t len = ap1->length;
if (ap2->length != len) {
return false;
}
TaggedPtr (*get1)(TaggedPtr lp, int64_t index) = lp1->desc->get;
TaggedPtr (*get2)(TaggedPtr lp, int64_t index) = lp2->desc->get;
for (int64_t i = 0; i < len; i++) {
if (!taggedPtrEq(get1(p1, i), get2(p2, i), sp)) {
return false;
}
}
return true;
}
bool _bal_array_subtype_contains(UniformSubtypePtr stp, TaggedPtr p) {
ListPtr lp = taggedToPtr(p);
ListDescPtr ldp = lp->desc;
uint32_t typeBitSet = ((ArraySubtypePtr)stp)->bitSet;
uint32_t nMemberTypes = ldp->nMemberTypes;
for (int64_t i = 0; i < nMemberTypes; i++) {
if (!memberTypeIsSubtypeSimple(ldp->memberTypes[i], typeBitSet)) {
return false;
}
}
return memberTypeIsSubtypeSimple(ldp->restType, typeBitSet);
}
CompareResult READONLY _bal_array_exact_int_compare(TaggedPtr tp1, TaggedPtr tp2) {
if (tp1 == tp2) {
return COMPARE_EQ;
}
ListPtr lp1 = taggedToPtr(tp1);
ListPtr lp2 = taggedToPtr(tp2);
int64_t len1 = lp1->iArray.length;
int64_t len2 = lp2->iArray.length;
int64_t len = (len1 <= len2) ? len1 : len2;
GC int64_t *arr1 = lp1->iArray.members;
GC int64_t *arr2 = lp2->iArray.members;
for (int64_t i = 0; i < len; i++) {
int64_t n1 = arr1[i];
int64_t n2 = arr2[i];
if (n1 > n2) {
return COMPARE_GT;
}
if (n1 < n2) {
return COMPARE_LT;
}
}
return intCompare(len1, len2);
}
static READONLY inline CompareResult optListDoCompare(TaggedPtr tp1, TaggedPtr tp2, int64_t (*compare)(TaggedPtr, TaggedPtr)) {
if (tp1 == tp2) {
return COMPARE_EQ;
}
if (tp1 == NIL || tp2 == NIL) {
return COMPARE_UN;
}
ListPtr lp1 = taggedToPtr(tp1);
ListPtr lp2 = taggedToPtr(tp2);
int64_t len1 = lp1->tpArray.length;
int64_t len2 = lp2->tpArray.length;
int64_t len = (len1 <= len2) ? len1 : len2;
TaggedPtr (*get1)(TaggedPtr lp, int64_t index) = lp1->desc->get;
TaggedPtr (*get2)(TaggedPtr lp, int64_t index) = lp2->desc->get;
for (int64_t i = 0; i < len; i++) {
int64_t result = (*compare)(get1(tp1, i), get2(tp2, i));
if (result != COMPARE_EQ) {
return result;
}
}
return intCompare(len1, len2);
}
CompareResult READONLY _bal_opt_list_compare(TaggedPtr tp1, TaggedPtr tp2) {
#if 0
if (tp1 == tp2) {
return COMPARE_EQ;
}
if (tp1 == NIL || tp2 == NIL) {
return COMPARE_UN;
}
ListPtr lp1 = taggedToPtr(tp1);
ListPtr lp2 = taggedToPtr(tp2);
ListDescPtr ldp1 = lp1->desc;
ListDescPtr ldp2 = lp2->desc;
ListDescPtr ldp;
if (ldp1->memberType == BITSET_MEMBER_TYPE(1 << TAG_NIL)) {
if (ldp2->memberType == BITSET_MEMBER_TYPE(1 << TAG_NIL)) {
return intCompare(lp1->tpArray.length, lp2->tpArray.length);
}
else {
ldp = ldp2;
}
}
else {
ldp = ldp1;
}
return optListDoCompare(tp1, tp2, getArrayComparator(ldp->memberType));
#else
return optListDoCompare(tp1, tp2, &taggedPtrCompare);
#endif
}
#if 0
typedef CompareResult (*TaggedPtrComparator)(TaggedPtr, TaggedPtr);
static READONLY TaggedPtrComparator getArrayComparator(MemberType memberType);
static READONLY TaggedPtrComparator getArrayComparator(MemberType memberType) {
uint32_t bitSet;
if ((memberType & 1) == 0) {
return &taggedPtrCompare;
}
else {
bitSet = (uint32_t)(memberType >> 1) & ~((uint32_t)1 << TAG_NIL);
switch (bitSet) {
case (1 << TAG_BOOLEAN):
return &optBooleanCompare;
case (1 << TAG_INT):
return &optIntCompare;
case (1 << TAG_FLOAT):
return &optFloatCompare;
case (1 << TAG_STRING):
return &optStringCompare;
case (1 << TAG_DECIMAL):
return &optDecimalCompare;
}
unreachable();
}
}
#endif
CompareResult READONLY _bal_array_int_compare(TaggedPtr tp1, TaggedPtr tp2) {
return optListDoCompare(tp1, tp2, &optIntCompare);
}
CompareResult READONLY _bal_array_float_compare(TaggedPtr tp1, TaggedPtr tp2) {
return optListDoCompare(tp1, tp2, &optFloatCompare);
}
CompareResult READONLY _bal_array_string_compare(TaggedPtr tp1, TaggedPtr tp2) {
return optListDoCompare(tp1, tp2, &optStringCompare);
}
CompareResult READONLY _bal_array_boolean_compare(TaggedPtr tp1, TaggedPtr tp2) {
return optListDoCompare(tp1, tp2, &optBooleanCompare);
}
CompareResult READONLY _bal_array_decimal_compare(TaggedPtr tp1, TaggedPtr tp2) {
return optListDoCompare(tp1, tp2, &optDecimalCompare);
}
CompareResult READONLY _bal_array_list_compare(TaggedPtr tp1, TaggedPtr tp2) {
return optListDoCompare(tp1, tp2, &_bal_opt_list_compare);
}
|
SNU-Programming-Tools/nballerina
|
runtime/decimal_inline.c
|
#include "balrt.h"
CompareResult READONLY _bal_opt_decimal_compare(TaggedPtr lhs, TaggedPtr rhs) {
return optDecimalCompare(lhs, rhs);
}
|
SNU-Programming-Tools/nballerina
|
runtime/tests/inlinert_list.c
|
#include "string_utils.h"
#include "list_utils.h"
#include "../balrt_inline.h"
#include <stdio.h>
ListDesc DESC_INT = LIST_DESC_INIT_INT_ARRAY(0);
ListDesc DESC_INT_NIL = LIST_DESC_INIT_GENERIC(0, 1 << TAG_INT | 1 << TAG_NIL);
ListDesc DESC_FLOAT = LIST_DESC_INIT_FLOAT_ARRAY(4);
ListDesc DESC_FLOAT_NIL = LIST_DESC_INIT_GENERIC(12, 1 << TAG_FLOAT | 1 << TAG_NIL);
ListDesc DESC_STRING = LIST_DESC_INIT_GENERIC(100, 1 << TAG_STRING);
ListDesc DESC_STRING_NIL = LIST_DESC_INIT_GENERIC(150, 1 << TAG_STRING | 1 << TAG_NIL);
TaggedPtr constructListWithDesc(ListDescPtr desc) {
GC TaggedPtr *members = _bal_alloc(sizeof(TaggedPtr));
GC TaggedPtrArray *arr = _bal_alloc(sizeof(TaggedPtrArray));
arr->length = 0;
arr->capacity = 0;
arr-> members = members;
ListPtr ptr = _bal_alloc(sizeof(ListDescPtr) + sizeof(GenericArray) + sizeof(TaggedPtrArray));
ptr->desc = desc;
ptr->tpArray = *arr;
return ptrAddShiftedTag(ptr, ((uint64_t)TAG_LIST_RO|TAG_LIST_RW) << TAG_SHIFT);
}
TaggedPtr constructIntList() {
return constructListWithDesc(&DESC_INT);
}
TaggedPtr constructIntNilList() {
return constructListWithDesc(&DESC_INT_NIL);
}
TaggedPtr constructFloatList() {
return constructListWithDesc(&DESC_FLOAT);
}
TaggedPtr constructFloatNilList() {
return constructListWithDesc(&DESC_FLOAT_NIL);
}
TaggedPtr constructStringList() {
return constructListWithDesc(&DESC_STRING);
}
TaggedPtr constructStringNilList() {
return constructListWithDesc(&DESC_STRING_NIL);
}
void pushString(TaggedPtr l, const char* str) {
BAL_LANG_ARRAY_NAME(push)(l, makeString(str));
}
void pushInt(TaggedPtr l, int64_t i) {
BAL_LANG_ARRAY_NAME(push)(l, _bal_int_to_tagged(i));
}
void pushFloat(TaggedPtr l, double f) {
BAL_LANG_ARRAY_NAME(push)(l, _bal_float_to_tagged(f));
}
void pushNil(TaggedPtr l) {
BAL_LANG_ARRAY_NAME(push)(l, getNil());
}
void testStringArr(TaggedPtr (*constructList)()) {
TaggedPtr a = constructList(); // ["abc", "abcd", "abb"]
pushString(a, "abc");
pushString(a, "abcd");
pushString(a, "abb");
TaggedPtr b = constructList(); // ["abc", "xyz", "abb"]
pushString(b, "abc");
pushString(b, "xyz");
pushString(b, "abb");
assert(_bal_array_string_compare(a, a) == COMPARE_EQ);
assert(_bal_array_string_compare(a, b) == COMPARE_LT);
assert(_bal_array_string_compare(b, a) == COMPARE_GT);
TaggedPtr c = constructList(); // ["abc", "abcd", "abb", "abc"]
pushString(c, "abc");
pushString(c, "abcd");
pushString(c, "abb");
pushString(c, "abc");
assert(_bal_array_string_compare(a, c) == COMPARE_LT);
assert(_bal_array_string_compare(c, a) == COMPARE_GT);
TaggedPtr d = getNil();
assert(_bal_array_string_compare(a, d) == COMPARE_UN);
assert(_bal_array_string_compare(d, a) == COMPARE_UN);
}
void testStringNilArr(TaggedPtr (*constructList)()) {
TaggedPtr a = constructList(); // ["abc", "abcd", "abb"]
pushString(a, "abc");
pushString(a, "abcd");
pushString(a, "abb");
TaggedPtr e = constructList(); // ["abc", "abcd", "abb"]
pushString(e, "abc");
pushNil(e);
pushString(e, "abb");
assert(_bal_array_string_compare(a, e) == COMPARE_UN);
assert(_bal_array_string_compare(e, a) == COMPARE_UN);
}
void testFloatArr(TaggedPtr (*constructList)()) {
TaggedPtr a = constructList(); // [0.1, 2.0, 0.33]
pushFloat(a, 0.1);
pushFloat(a, 2.0);
pushFloat(a, 0.33);
TaggedPtr b = constructList(); // [0.1, 4, 0.33]
pushFloat(b, 0.1);
pushFloat(b, 4);
pushFloat(b, 0.33);
assert(_bal_array_float_compare(a, a) == COMPARE_EQ);
assert(_bal_array_float_compare(a, b) == COMPARE_LT);
assert(_bal_array_float_compare(b, a) == COMPARE_GT);
TaggedPtr c = constructList(); // [0.1, 2.0, 0.33, 0.1]
pushFloat(c, 0.1);
pushFloat(c, 2.0);
pushFloat(c, 0.33);
pushFloat(c, 0.1);
assert(_bal_array_float_compare(a, c) == COMPARE_LT);
assert(_bal_array_float_compare(c, a) == COMPARE_GT);
TaggedPtr d = getNil();
assert(_bal_array_float_compare(a, d) == COMPARE_UN);
assert(_bal_array_float_compare(d, a) == COMPARE_UN);
}
void testFloatNilArr(TaggedPtr (*constructList)()) {
TaggedPtr a = constructList(); // [0.1, 2.0, 0.33]
pushFloat(a, 0.1);
pushFloat(a, 2.0);
pushFloat(a, 0.33);
TaggedPtr e = constructList(); // [0.1, (), 0.33]
pushFloat(e, 0.1);
pushNil(e);
pushFloat(e, 0.33);
assert(_bal_array_float_compare(a, e) == COMPARE_UN);
assert(_bal_array_float_compare(e, a) == COMPARE_UN);
}
void testIntArr(TaggedPtr (*constructList)()) {
TaggedPtr a = constructList(); // [1, 2, 3]
pushInt(a, 1);
pushInt(a, 2);
pushInt(a, 3);
TaggedPtr b = constructList(); // [1, 4, 3]
pushInt(b, 1);
pushInt(b, 4);
pushInt(b, 3);
assert(_bal_array_int_compare(a, a) == COMPARE_EQ);
assert(_bal_array_int_compare(a, b) == COMPARE_LT);
assert(_bal_array_int_compare(b, a) == COMPARE_GT);
TaggedPtr c = constructList(); // [1, 2, 3, 1]
pushInt(c, 1);
pushInt(c, 2);
pushInt(c, 3);
pushInt(c, 1);
assert(_bal_array_int_compare(a, c) == COMPARE_LT);
assert(_bal_array_int_compare(c, a) == COMPARE_GT);
TaggedPtr d = getNil();
assert(_bal_array_int_compare(a, d) == COMPARE_UN);
assert(_bal_array_int_compare(d, a) == COMPARE_UN);
}
void testIntNilArr(TaggedPtr (*constructList)()) {
TaggedPtr a = constructList(); // [1, 2, 3]
pushInt(a, 1);
pushInt(a, 2);
pushInt(a, 3);
TaggedPtr e = constructList(&DESC_INT); // [1, (), 3]
pushInt(e, 1);
pushNil(e);
pushInt(e, 3);
assert(_bal_array_int_compare(a, e) == COMPARE_UN);
assert(_bal_array_int_compare(e, a) == COMPARE_UN);
}
HASH_DEFINE_KEY;
int main() {
testIntArr(constructIntList);
testIntArr(constructIntNilList);
testIntNilArr(constructIntNilList);
testFloatArr(constructFloatList);
testFloatArr(constructFloatNilList);
testFloatNilArr(constructFloatNilList);
testStringArr(constructStringList);
testStringArr(constructStringNilList);
testStringNilArr(constructStringNilList);
return 0;
}
|
SNU-Programming-Tools/nballerina
|
runtime/balrt.h
|
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include <inttypes.h>
#include <stdio.h>
#include "tag.h"
#include "panic.h"
#define TAG_MASK 0xFF
#define UT_MASK 0x1F
#define TAG_SHIFT 56
#define NIL ((TaggedPtr)0)
#define COMPARE_UN -1
#define COMPARE_LT 0
#define COMPARE_EQ 1
#define COMPARE_GT 2
// CompareResult is one of the above four COMPARE_* value.
typedef int64_t CompareResult;
#define HEAP_ALIGNMENT 8
#define POINTER_MASK (((uint64_t)1 << TAG_SHIFT) - 1)
#define ALIGN_MASK (~(uint64_t)(HEAP_ALIGNMENT - 1))
#define IMMEDIATE_FLAG (((uint64_t)0x20) << TAG_SHIFT)
#define EXACT_FLAG ((uint64_t)0x4)
#define STRING_LARGE_FLAG 1
#ifdef __clang__
#define NODEREF __attribute__((noderef))
#define NORETURN __attribute__((noreturn))
#define GC __attribute__((address_space(1)))
#define COLD __attribute__((cold))
// LLVM readonly attribute corresponds to clang pure
#define READONLY __attribute__((pure))
// LLVM readnone attribute corresponds to clang const
#define READNONE __attribute__((const))
#define ALIGNED(n) __attribute__((aligned(n)))
#define UNUSED __attribute__((unused))
#else
#define NODEREF /* as nothing */
#define NORETURN /* as nothing */
#define GC /* as nothing */
#define COLD /* as nothing */
#define READONLY /* as nothing */
#define READNONE /* as nothing */
#define ALIGNED(n) /* as nothing */
#deifne UNUSED /* as nothing */
#endif
#define likely(x) __builtin_expect((x), 1)
#define unlikely(x) __builtin_expect((x), 0)
#define unreachable() __builtin_unreachable()
#ifndef STACK_SIZE
#ifdef STACK_DEBUG
#define STACK_SIZE 1024
#else
#define STACK_SIZE (1024*1024)
#endif
#endif
#define IMMEDIATE_INT_MIN -((int64_t)1 << (TAG_SHIFT - 1))
#define IMMEDIATE_INT_MAX (((int64_t)1 << (TAG_SHIFT - 1)) - 1)
#define IMMEDIATE_INT_TRUNCATE(n) (n & (((int64_t)1 << TAG_SHIFT) - 1))
extern char *_bal_stack_guard;
typedef GC char NODEREF *TaggedPtr;
typedef GC void *UntypedPtr;
typedef GC int64_t *IntPtr;
typedef GC double *FloatPtr;
typedef uint64_t PanicCode;
// An internally-generated panic is currently represented as int with the error code in the lo byte
// and line number right-shifted 8.
typedef uint64_t PackedPanic;
typedef uintptr_t PC;
typedef struct {
int64_t length;
int64_t capacity;
GC void *members;
} GenericArray;
typedef struct {
int64_t length;
int64_t capacity;
GC TaggedPtr *members;
} TaggedPtrArray;
typedef struct {
int64_t length;
int64_t capacity;
GC int64_t *members;
} IntArray;
typedef struct {
int64_t length;
int64_t capacity;
GC uint8_t *members;
} ByteArray;
typedef struct {
int64_t length;
int64_t capacity;
GC double *members;
} FloatArray;
typedef uint32_t Tid;
// Represents the type of a member of a structure
// Either a ComplexTypePtr or a shifted bitset
// Shifted bitSet is shifted 1 and or'ed with 1
typedef uint64_t MemberType;
#define BITSET_MEMBER_TYPE(bitSet) (((uint64_t)(bitSet) << 1)|1)
// All mapping and list descriptors start with this.
typedef struct {
Tid tid;
} StructureDesc, *StructureDescPtr;
// All mapping and list values start with this
typedef GC struct {
StructureDescPtr desc;
} Structure, *StructurePtr;
// This extends StructureDesc
// i.e must start with tid
typedef struct {
Tid tid;
// the number of entries in memberTypes
uint32_t nMemberTypes;
// The minimum length of the list; always >= 0
// minLength is always >= nMemberTypes.
// If minLength > 0, then nMemberTypes > 0
int64_t minLength;
TaggedPtr (*get)(TaggedPtr lp, int64_t index);
PanicCode (*set)(TaggedPtr lp, int64_t index, TaggedPtr val);
PanicCode (*inexactSet)(TaggedPtr lp, int64_t index, TaggedPtr val);
int64_t (*getInt)(TaggedPtr lp, int64_t index);
PanicCode (*setInt)(TaggedPtr lp, int64_t index, int64_t val);
PanicCode (*inexactSetInt)(TaggedPtr lp, int64_t index, int64_t val);
double (*getFloat)(TaggedPtr lp, int64_t index);
PanicCode (*setFloat)(TaggedPtr lp, int64_t index, double val);
PanicCode (*inexactSetFloat)(TaggedPtr lp, int64_t index, double val);
// the type of members with index >= minLength
MemberType restType;
StructureDescPtr fillerDesc;
// The types of the members at the start of the list.
// For member with index i in 0 ..< nMemberTypes, the type is memberTypes[i]
// For member with index i in nMemberTypes ..< minLength, the type is memberTypes[nMemberTypes - 1]
// The number of members is nMemberTypes.
MemberType memberTypes[];
} ListDesc, *ListDescPtr;
// Extends Structure
typedef GC struct List {
ListDescPtr desc;
// This isn't strictly portable because void* and TaggedPtr* might have different alignments/sizes
// But we ain't writing portable code here
union {
GenericArray gArray;
TaggedPtrArray tpArray;
IntArray iArray;
FloatArray fArray;
ByteArray bArray;
};
} *ListPtr;
typedef struct {
TaggedPtr key;
TaggedPtr value;
} MapField;
typedef struct {
int64_t length;
int64_t capacity;
GC MapField *members;
} MapFieldArray;
// This extends StructureDesc
// i.e must start with tid
typedef struct {
Tid tid;
uint32_t nFields;
MemberType restType;
StructureDescPtr fillerDesc;
MemberType fieldTypes[];
} MappingDesc, *MappingDescPtr;
// Extends Structure
typedef GC struct Mapping {
MappingDescPtr desc;
union {
GenericArray gArray;
MapFieldArray fArray;
};
// The table is a hash table. Each element is either -1 representing an empty entry or is an index into fArray.
// It uses the hash of the key of the indexed mapField.
// It consists of (1 << tableLengthShift) elements each of size (1 << tableElementShift) bytes.
// tableElementShift is between 0 and 3 inclusive, representing uint8_t, uint16_t, uint32_t and int64_t respectively.
// tableElementShift is the minimum to allow an element to represent all values between 0 and (1 << tableLengthShift)/2.
// The length of fArray will always be <= (1 << tableLengthShift)/2 - 1.
// For example, if tableLengthShift is 0, meaning table contains bytes, then the array can have a length of up to 255,
// meaning indices into the array are between 0 and 254 inclusive, and the table can be up to 512 bytes long.
// The hash table uses open addressing and linear probing (with probing backwards to 0).
// Note that the load factor is fixed (1 element less than 50%), so that changes in table element size are in sync
// with changes in table length (50% is a good load factor for linear probing anyway).
UntypedPtr table;
uint8_t tableElementShift;
uint8_t tableLengthShift;
} *MappingPtr;
typedef struct UniformSubtype {
bool (*contains)(struct UniformSubtype *, TaggedPtr);
} UniformSubtype, *UniformSubtypePtr;
typedef struct {
TaggedPtr fieldName;
uint32_t fieldBitSet;
} RecordSubtypeField;
typedef struct {
UniformSubtype uniform;
uint32_t nFields;
RecordSubtypeField fields[];
} *RecordSubtypePtr;
typedef struct {
UniformSubtype uniform;
uint32_t bitSet;
} *MapSubtypePtr, *ArraySubtypePtr;
typedef struct {
UniformSubtype uniform;
uint32_t nTids;
uint32_t tids[];
} *PrecomputedSubtypePtr;
typedef struct {
int64_t min;
int64_t max;
} IntRange;
typedef struct {
UniformSubtype uniform;
// Use 64 bits to avoid padding.
// nRanges must be > 0
int64_t nRanges;
// Sorted
IntRange ranges[];
} *IntSubtypePtr;
typedef struct {
UniformSubtype uniform;
// nFloats must be > 0.
int32_t nFloats;
// This is 0 or 1. Use 32 bits to avoid padding.
// 1 means members of decimals are included in the type
int32_t included;
// If NaN is included, it will be the first entry.
// The remaining entries are ordered.
// It is not possible to have both +0 and -0.
double floats[];
} *FloatSubtypePtr;
typedef const char *DecimalConstPtr;
typedef struct {
UniformSubtype uniform;
// nDecimals must be > 0
int32_t nDecimals;
// This is 0 or 1. Use 32 bits to avoid padding.
// 1 means members of decimals are included in the type
int32_t included;
DecimalConstPtr decimals[];
} *DecimalSubtypePtr;
typedef struct {
UniformSubtype uniform;
// nStrs may be 0
uint32_t nStrs;
// If a string has length 1 and it's in the strs list, isCharInStrsAllowed says whether it's included in the type.
// If a string has length != 1 and it's in the strs list, isNonCharInStrsAllowed says whether it's included in the type.
// If the string is not in the strs list, it's included iff it wouldn't be included if it was in the list.
// These two fields are uint16 rather than bool, just to avoid any padding problems.
uint16_t isCharInStrsIncluded;
uint16_t isNonCharInStrsIncluded;
// Sorted list of strings
TaggedPtr strs[];
} *StringSubtypePtr;
typedef struct {
uint32_t all;
uint32_t some;
UniformSubtypePtr subtypes[];
} ComplexType, *ComplexTypePtr;
typedef struct EqStack {
TaggedPtr p1;
TaggedPtr p2;
struct EqStack *next;
} EqStack;
typedef GC struct Error {
TaggedPtr message;
int64_t lineNumber;
int backtraceErrorCode;
char *backtraceErrorMessage;
uint32_t nPCs;
PC pcs[];
} *ErrorPtr;
// Both of these are 8-byte aligned and zero-padded so the total size is a multiple of 8
typedef GC struct MediumString {
uint16_t lengthInBytes;
uint16_t lengthInCodePoints;
char bytes[];
} *MediumStringPtr;
typedef GC struct LargeString {
int64_t lengthInBytes;
int64_t lengthInCodePoints;
char bytes[];
} *LargeStringPtr;
// Roundup to multiple of 8
static inline int roundUpInt(int n) {
return (n + 7) & ~7;
}
static inline int mediumStringSize(int lengthInBytes) {
return roundUpInt(lengthInBytes + sizeof(struct MediumString));
}
static inline uint64_t roundUpUint64(uint64_t n) {
return (n + 7) & ~(uint64_t)7;
}
static inline uint64_t largeStringSize(int64_t lengthInBytes) {
return roundUpUint64(lengthInBytes + sizeof(struct LargeString));
}
typedef struct {
int64_t nBytes;
int64_t nCodePoints;
} StringLength;
typedef struct {
int64_t lengthInBytes;
int64_t lengthInCodePoints;
GC char *bytes;
} StringData;
typedef struct {
TaggedPtr ptr;
PanicCode panicCode;
} TaggedPtrPanicCode;
typedef struct {
int64_t value;
bool overflow;
} IntWithOverflow;
typedef struct {
TaggedPtr ptr;
bool overflow;
} TaggedWithOverflow;
#define ALIGN_HEAP 8
// Don't declare functions here if they are balrt_inline.c
extern UntypedPtr _bal_alloc(uint64_t nBytes);
extern NORETURN void _bal_panic(TaggedPtr tp);
extern bool _bal_float_eq(double, double);
// precondition is that both strings are on the heap and the pointers are not ==
extern READONLY bool _bal_string_heap_eq(TaggedPtr tp1, TaggedPtr tp2);
extern READONLY int64_t _bal_string_cmp(TaggedPtr tp1, TaggedPtr tp2);
extern READONLY TaggedPtr _bal_string_concat(TaggedPtr tp1, TaggedPtr tp2);
extern READONLY uint64_t _bal_string_hash(TaggedPtr tp);
extern char *_bal_string_alloc(uint64_t lengthInBytes, uint64_t lengthInCodePoints, TaggedPtr *resultPtr);
#define TAGGED_PTR_SHIFT 3
// log2(sizeof(uint8_t)) = 0
#define BYTE_SHIFT 0
extern void _bal_array_grow(GC GenericArray *ap, int64_t min_capacity, int shift);
extern ListPtr _bal_list_construct_8(ListDescPtr desc, int64_t capacity);
extern ListPtr _bal_list_construct_1(ListDescPtr desc, int64_t capacity);
extern TaggedPtr _bal_list_generic_get_tagged(TaggedPtr p, int64_t index);
extern int64_t _bal_list_generic_get_int(TaggedPtr p, int64_t index);
double _bal_list_generic_get_float(TaggedPtr p, int64_t index);
extern PanicCode _bal_list_generic_set_tagged(TaggedPtr p, int64_t index, TaggedPtr val);
extern PanicCode _bal_list_generic_set_int(TaggedPtr p, int64_t index, int64_t val);
PanicCode _bal_list_generic_set_float(TaggedPtr p, int64_t index, double val);
extern PanicCode _bal_list_generic_inexact_set_tagged(TaggedPtr p, int64_t index, TaggedPtr val);
extern PanicCode _bal_list_generic_inexact_set_int(TaggedPtr p, int64_t index, int64_t val);
PanicCode _bal_list_generic_inexact_set_float(TaggedPtr p, int64_t index, double val);
extern TaggedPtr _bal_list_int_array_get_tagged(TaggedPtr p, int64_t index);
extern int64_t _bal_list_int_array_get_int(TaggedPtr p, int64_t index);
extern PanicCode _bal_list_int_array_set_tagged(TaggedPtr p, int64_t index, TaggedPtr val);
extern PanicCode _bal_list_int_array_set_int(TaggedPtr p, int64_t index, int64_t val);
extern PanicCode _bal_list_int_array_set_float(TaggedPtr p, int64_t index, double val);
extern TaggedPtr _bal_list_byte_array_get_tagged(TaggedPtr p, int64_t index);
extern int64_t _bal_list_byte_array_get_int(TaggedPtr p, int64_t index);
extern PanicCode _bal_list_byte_array_set_tagged(TaggedPtr p, int64_t index, TaggedPtr val);
extern PanicCode _bal_list_byte_array_set_int(TaggedPtr p, int64_t index, int64_t val);
extern PanicCode _bal_list_byte_array_set_float(TaggedPtr p, int64_t index, double val);
extern TaggedPtr _bal_list_float_array_get_tagged(TaggedPtr p, int64_t index);
extern double _bal_list_float_array_get_float(TaggedPtr p, int64_t index);
extern PanicCode _bal_list_float_array_set_tagged(TaggedPtr p, int64_t index, TaggedPtr val);
extern PanicCode _bal_list_float_array_set_int(TaggedPtr p, int64_t index, int64_t val);
extern PanicCode _bal_list_float_array_set_float(TaggedPtr p, int64_t index, double val);
extern READONLY bool _bal_list_eq(TaggedPtr p1, TaggedPtr p2);
extern READONLY bool _bal_list_eq_internal(TaggedPtr p1, TaggedPtr p2, EqStack *sp);
// Compare any two comparable values that are lists or nil
extern CompareResult READONLY _bal_opt_list_compare(TaggedPtr tp1, TaggedPtr tp2);
#define MAP_FIELD_SHIFT (TAGGED_PTR_SHIFT*2)
extern TaggedPtr _bal_mapping_construct(MappingDescPtr desc, int64_t capacity);
extern void _bal_mapping_init_member(TaggedPtr mapping, TaggedPtr key, TaggedPtr val);
extern PanicCode _bal_mapping_set(TaggedPtr mapping, TaggedPtr key, TaggedPtr val);
extern READONLY TaggedPtr _bal_mapping_get(TaggedPtr mapping, TaggedPtr key);
extern READONLY bool _bal_mapping_eq(TaggedPtr p1, TaggedPtr p2);
extern READONLY bool _bal_mapping_eq_internal(TaggedPtr p1, TaggedPtr p2, EqStack *sp);
typedef enum {
FILL_NONE,
FILL_EACH,
FILL_COPY
} Fillability;
extern Fillability _bal_structure_create_filler(MemberType memberType, StructureDescPtr fillerDesc, TaggedPtr *valuePtr);
extern READNONE UntypedPtr _bal_tagged_to_ptr(TaggedPtr p);
extern READNONE UntypedPtr _bal_tagged_to_ptr_exact(TaggedPtr p);
extern READNONE TaggedPtr _bal_tagged_clear_exact(TaggedPtr p);
extern READNONE UntypedPtr _bal_ptr_mask(TaggedPtr ptr, uint64_t mask);
extern TaggedPtr _bal_error_construct(TaggedPtr message, int64_t lineNumber);
extern void _bal_error_backtrace_print(ErrorPtr ep, uint32_t start, FILE *fp);
extern void _bal_print_mangled_name(const char *mangledName, FILE *fp);
// Returns an error value
extern TaggedPtr COLD _bal_panic_construct(PackedPanic err);
extern NORETURN COLD void _bal_panic_internal(PanicCode code);
extern TaggedPtr _bal_decimal_const(const char *decString);
extern TaggedPtrPanicCode _bal_decimal_add(TaggedPtr tp1, TaggedPtr tp2);
extern TaggedPtrPanicCode _bal_decimal_sub(TaggedPtr tp1, TaggedPtr tp2);
extern TaggedPtrPanicCode _bal_decimal_mul(TaggedPtr tp1, TaggedPtr tp2);
extern TaggedPtrPanicCode _bal_decimal_div(TaggedPtr tp1, TaggedPtr tp2);
extern TaggedPtr _bal_decimal_neg(TaggedPtr tp);
extern TaggedPtrPanicCode _bal_decimal_rem(TaggedPtr tp1, TaggedPtr tp2);
extern int64_t _bal_decimal_cmp(TaggedPtr tp1, TaggedPtr tp2);
extern bool _bal_decimal_exact_eq(TaggedPtr tp1, TaggedPtr tp2);
extern double _bal_decimal_to_float(TaggedPtr tp);
extern TaggedPtr _bal_decimal_from_int(int64_t val);
extern TaggedPtrPanicCode _bal_decimal_from_float(double val);
extern IntWithOverflow _bal_decimal_to_int(TaggedPtr tp);
// These handle nil for both the list and members of list
// In other words for int, the type must be `int?[]?`
extern CompareResult READONLY _bal_array_int_compare(TaggedPtr tp1, TaggedPtr tp2);
extern CompareResult READONLY _bal_array_float_compare(TaggedPtr tp1, TaggedPtr tp2);
extern CompareResult READONLY _bal_array_string_compare(TaggedPtr tp1, TaggedPtr tp2);
extern CompareResult READONLY _bal_array_boolean_compare(TaggedPtr tp1, TaggedPtr tp2);
extern CompareResult READONLY _bal_array_decimal_compare(TaggedPtr tp1, TaggedPtr tp2);
extern CompareResult READONLY _bal_array_list_compare(TaggedPtr tp1, TaggedPtr tp2);
extern TaggedPtr READONLY _bal_convert_to_float(TaggedPtr tp);
extern TaggedWithOverflow READONLY _bal_convert_to_int(TaggedPtr tp);
// Library mangling
#define BAL_ROOT_NAME(sym) _B04root ## sym
#define BAL_LIB_IO_NAME(sym) _Bb02io ## sym
#define BAL_LANG_INT_NAME(sym) _Bb0m4lang3int ## sym
#define BAL_LANG_STRING_NAME(sym) _Bb0m4lang6string ## sym
#define BAL_LANG_ARRAY_NAME(sym) _Bb0m4lang5array ## sym
#define BAL_LANG_MAP_NAME(sym) _Bb0m4lang3map ## sym
#define BAL_LANG_ERROR_NAME(sym) _Bb0m4lang5error ## sym
// Library functions
extern TaggedPtr BAL_LANG_ERROR_NAME(message)(TaggedPtr p);
extern void BAL_LIB_IO_NAME(println)(TaggedPtr p);
static READNONE inline uint64_t taggedPtrBits(TaggedPtr p) {
return (uint64_t)(char *)p;
}
static inline TaggedPtr bitsToTaggedPtr(uint64_t bits) {
char *p = (char *)bits;
return (TaggedPtr)p;
}
static READNONE inline int getTag(TaggedPtr p) {
return (int)((taggedPtrBits(p) >> TAG_SHIFT) & TAG_MASK);
}
static READNONE inline int taggedToBoolean(TaggedPtr p) {
return (int)(taggedPtrBits(p) & 1);
}
static READNONE inline UntypedPtr taggedToPtr(TaggedPtr p) {
return _bal_ptr_mask(p, POINTER_MASK & ALIGN_MASK);
}
static READNONE inline UntypedPtr taggedToPtrExact(TaggedPtr p) {
return _bal_ptr_mask(p, (POINTER_MASK & ALIGN_MASK)|EXACT_FLAG);
}
static READONLY inline bool memberTypeIsSubtypeSimple(MemberType memberType, uint32_t bitSet) {
uint32_t memberBitSet;
if (memberType & 1) {
memberBitSet = (uint32_t)(memberType >> 1);
}
else {
ComplexTypePtr ctp = (ComplexTypePtr)memberType;
memberBitSet = ctp->all | ctp->some;
}
return (memberBitSet & ~(uint64_t)bitSet) == 0;
}
static READONLY inline bool complexTypeContainsTagged(ComplexTypePtr ctp, TaggedPtr p) {
int flag = 1 << ((getTag(p) & UT_MASK));
if (ctp->all & flag) {
return true;
}
if (!(ctp->some & flag)) {
return false;
}
int i = __builtin_popcount(ctp->some & (flag - 1));
UniformSubtypePtr vp = ctp->subtypes[i];
return (vp->contains)(vp, p);
}
typedef struct {
// If this is null, then contains is the result
UniformSubtypePtr ptr;
bool contains;
} UniformSubtypeData;
static READONLY inline UniformSubtypeData complexTypeUniformSubtypeData(ComplexTypePtr ctp, int tag) {
int flag = 1 << tag;
UniformSubtypeData result;
if (ctp->all & flag) {
result.ptr = 0;
result.contains = true;
}
else if (!(ctp->some & flag)) {
result.ptr = 0;
result.contains = false;
}
else {
int i = __builtin_popcount(ctp->some & (flag - 1));
result.ptr = ctp->subtypes[i];
}
return result;
}
static READONLY inline bool memberTypeContainsTagged(MemberType memberType, TaggedPtr tp) {
if (memberType & 1) {
uint64_t flag = (uint64_t)1 << (1 + (getTag(tp) & UT_MASK));
return (memberType & flag) != 0;
}
else {
return complexTypeContainsTagged((ComplexTypePtr)memberType, tp);
}
}
static READNONE inline PanicCode storePanicCode(TaggedPtr p, PanicCode code) {
// If the exact bit is set, then these will be unequal and the error should not occur.
return taggedToPtr(p) == taggedToPtrExact(p) ? code : PANIC_INTERNAL_ERROR;
}
static READONLY inline int64_t taggedToInt(TaggedPtr p) {
uint64_t n = taggedPtrBits(p);
if (likely((n & IMMEDIATE_FLAG) != 0)) {
n &= POINTER_MASK;
// sign extend
n <<= 8;
return ((int64_t)n) >> 8;
}
else {
GC int64_t *np = taggedToPtr(p);
return *np;
}
}
static READONLY inline CompareResult optDoCompare(TaggedPtr tp1, TaggedPtr tp2, int64_t (*compare)(TaggedPtr, TaggedPtr)) {
if (tp1 == NIL) {
return tp2 == NIL ? COMPARE_EQ : COMPARE_UN;
}
else if (tp2 == NIL) {
return COMPARE_UN;
}
return (*compare)(tp1, tp2);
}
static READONLY inline CompareResult intCompare(int64_t n1, int64_t n2) {
if (n1 == n2) {
return COMPARE_EQ;
}
return n1 < n2 ? COMPARE_LT : COMPARE_GT;
}
static READONLY inline CompareResult taggedIntCompare(TaggedPtr tp1, TaggedPtr tp2) {
return intCompare(taggedToInt(tp1), taggedToInt(tp2));
}
static READONLY inline CompareResult optIntCompare(TaggedPtr tp1, TaggedPtr tp2) {
return optDoCompare(tp1, tp2, &taggedIntCompare);
}
static READONLY inline double taggedToFloat(TaggedPtr p) {
GC double *np = taggedToPtr(p);
return *np;
}
static READONLY inline CompareResult taggedFloatCompare(TaggedPtr tp1, TaggedPtr tp2) {
double v1 = taggedToFloat(tp1);
double v2 = taggedToFloat(tp2);
if (v1 == v2) {
return COMPARE_EQ;
}
if (v1 < v2) {
return COMPARE_LT;
}
if (v1 > v2) {
return COMPARE_GT;
}
return COMPARE_UN;
}
static READONLY inline int64_t optFloatCompare(TaggedPtr tp1, TaggedPtr tp2) {
return optDoCompare(tp1, tp2, &taggedFloatCompare);
}
static READONLY inline CompareResult taggedBooleanCompare(TaggedPtr tp1, TaggedPtr tp2) {
if (tp1 == tp2) {
return COMPARE_EQ;
}
int b1 = taggedToBoolean(tp1);
int b2 = taggedToBoolean(tp2);
return b1 < b2 ? COMPARE_LT : COMPARE_GT;
}
static READONLY inline int64_t optBooleanCompare(TaggedPtr tp1, TaggedPtr tp2) {
return optDoCompare(tp1, tp2, &taggedBooleanCompare);
}
static READONLY inline CompareResult optStringCompare(TaggedPtr tp1, TaggedPtr tp2) {
if (tp1 == NIL) {
return tp2 == NIL ? COMPARE_EQ : COMPARE_UN;
}
else if (tp2 == NIL) {
return COMPARE_UN;
}
return intCompare(_bal_string_cmp(tp1, tp2), 0);
}
static READONLY inline CompareResult optDecimalCompare(TaggedPtr tp1, TaggedPtr tp2) {
if (tp1 == NIL) {
return tp2 == NIL ? COMPARE_EQ : COMPARE_UN;
}
else if (tp2 == NIL) {
return COMPARE_UN;
}
return intCompare(_bal_decimal_cmp(tp1, tp2), 0);
}
// Precondition is that they are comparable
static READONLY inline CompareResult taggedPtrCompare(TaggedPtr tp1, TaggedPtr tp2) {
// `& 0xF` turns LIST_RW into LIST_RO
int tag1 = getTag(tp1) & 0xF;
int tag2 = getTag(tp2) & 0xF;
if (tag1 != tag2) {
// This can only happen if one is nil
return COMPARE_UN;
}
switch (tag1) {
case TAG_INT:
return taggedIntCompare(tp1, tp2);
case TAG_BOOLEAN:
return taggedBooleanCompare(tp1, tp2);
case TAG_FLOAT:
return taggedFloatCompare(tp1, tp2);
case TAG_DECIMAL:
return intCompare(_bal_decimal_cmp(tp1, tp2), 0);
case TAG_STRING:
return intCompare(_bal_string_cmp(tp1, tp2), 0);
case TAG_LIST_RO:
return _bal_opt_list_compare(tp1, tp2);
default:
// This is NIL case
return COMPARE_EQ;
}
}
static READNONE inline StringLength immediateStringLength(uint64_t bits) {
StringLength len;
unsigned loByte = bits & 0xFF;
if (loByte == 0xFF) {
len.nBytes = 0;
len.nCodePoints = 0;
}
else if (loByte & 0x80) {
len.nBytes = __builtin_clz((uint8_t)~loByte) - (sizeof(unsigned) - 1)*8;
len.nCodePoints = 1;
}
else {
bits = ~bits;
bits &= ((uint64_t)1 << 56) - 1;
len.nBytes = len.nCodePoints = 8 - (__builtin_clzl(bits) >> 3);
}
return len;
}
static READONLY inline StringLength taggedStringLength(TaggedPtr p) {
uint64_t bits = taggedPtrBits(p);
if (bits & IMMEDIATE_FLAG) {
return immediateStringLength(bits);
}
if (likely((bits & STRING_LARGE_FLAG) == 0)) {
MediumStringPtr sp = taggedToPtr(p);
StringLength len = { sp->lengthInBytes, sp->lengthInCodePoints };
return len;
}
else {
LargeStringPtr sp = taggedToPtr(p);
StringLength len = { sp->lengthInBytes, sp->lengthInCodePoints };
return len;
}
}
// A more efficient version of taggedStringLength(p) == 1
// This is READNONE because we can do this looking just at the tagged ptr
static READNONE inline bool taggedStringIsChar(TaggedPtr p) {
uint64_t bits = taggedPtrBits(p);
if (bits & IMMEDIATE_FLAG) {
unsigned loByte = bits & 0xFF;
if (loByte & 0x80) {
return loByte != 0xFF;
}
else {
// This char uses one byte.
// So it's one char 1 if the other bytes are all padding (0xFF).
return (~bits >> 8) == 0;
}
}
else {
// non-immediate strings have length > 1
return false;
}
}
static READONLY inline char *taggedStringBytes(TaggedPtr *p) {
uint64_t bits = taggedPtrBits(*p);
if (bits & IMMEDIATE_FLAG) {
return (char *)p;
}
if (likely((bits & STRING_LARGE_FLAG) == 0)) {
MediumStringPtr sp = taggedToPtr(*p);
// cast away address space
return (char *)sp->bytes;
}
else {
LargeStringPtr sp = taggedToPtr(*p);
return (char *)sp->bytes;
}
}
static READONLY inline bool taggedStringEqual(TaggedPtr tp1, TaggedPtr tp2) {
uint64_t bits1 = taggedPtrBits(tp1);
uint64_t bits2 = taggedPtrBits(tp2);
if (bits1 == bits2) {
return true;
}
if (bits1 & IMMEDIATE_FLAG) {
return false;
}
if (bits2 & IMMEDIATE_FLAG) {
// one of them is immediate and the bits are not equal
// so they are not equal
return false;
}
return _bal_string_heap_eq(tp1, tp2);
}
static READONLY inline bool taggedPtrEq(TaggedPtr tp1, TaggedPtr tp2, EqStack *stackPtr) {
if (tp1 == tp2) {
return true;
}
int tag1 = getTag(tp1);
int tag2 = getTag(tp2);
if (tag1 != tag2) {
return false;
}
switch (tag1) {
case TAG_STRING:
return taggedStringEqual(tp1, tp2);
case TAG_INT:
{
IntPtr p1 = taggedToPtr(tp1);
IntPtr p2 = taggedToPtr(tp2);
return *p1 == *p2;
}
case TAG_FLOAT:
{
FloatPtr p1 = taggedToPtr(tp1);
FloatPtr p2 = taggedToPtr(tp2);
return _bal_float_eq(*p1, *p2);
}
case TAG_DECIMAL:
return _bal_decimal_cmp(tp1, tp2) == 0;
case TAG_LIST_RW:
case TAG_MAPPING_RW:
{
EqStack stack;
for (EqStack *sp = stackPtr; sp; sp = sp->next) {
if (tp1 == sp->p1 && tp2 == sp->p2) {
return true;
}
}
stack.p1 = tp1;
stack.p2 = tp2;
stack.next = stackPtr;
return (tag1 == TAG_LIST_RW
? _bal_list_eq_internal(tp1, tp2, &stack)
: _bal_mapping_eq_internal(tp1, tp2, &stack));
}
}
return false;
}
static READNONE inline TaggedPtr ptrAddFlags(UntypedPtr p, uint64_t flags) {
char *p0 = (void *)p;
p0 = (char *)((uint64_t)p0 | flags);
return (TaggedPtr)p0;
}
// We are trying to avoid doing inttoptr or ptrtoint in address space 1
static inline TaggedPtr ptrAddShiftedTag(UntypedPtr tp, uint64_t shiftedTag) {
char *p = (char *)tp;
uint64_t bits = (uint64_t)p;
bits |= shiftedTag;
p = (char *)bits;
return (TaggedPtr)p;
}
static inline void initGenericArray(GC GenericArray *ap, int64_t capacity, int shift) {
ap->length = 0;
ap->capacity = capacity;
if (capacity == 0) {
ap->members = 0;
}
else {
ap->members = _bal_alloc(capacity << shift);
}
}
static inline TaggedPtr floatToTagged(double n) {
GC double *p = _bal_alloc(sizeof(double));
*p = n;
return ptrAddShiftedTag(p, ((uint64_t)TAG_FLOAT) << TAG_SHIFT);
}
static inline TaggedPtr intToTagged(int64_t n) {
if (likely(n >= IMMEDIATE_INT_MIN & n <= IMMEDIATE_INT_MAX)) {
return bitsToTaggedPtr(IMMEDIATE_INT_TRUNCATE(n) | IMMEDIATE_FLAG | (((uint64_t)TAG_INT) << TAG_SHIFT));
}
else {
GC int64_t *p = _bal_alloc(sizeof(int64_t));
*p = n;
return ptrAddShiftedTag(p, ((uint64_t)TAG_INT) << TAG_SHIFT);
}
}
|
SNU-Programming-Tools/nballerina
|
runtime/boolean_inline.c
|
#include "balrt.h"
int64_t READONLY _bal_opt_boolean_compare(TaggedPtr lhs, TaggedPtr rhs) {
return optBooleanCompare(lhs, rhs);
}
|
SNU-Programming-Tools/nballerina
|
runtime/float_inline.c
|
<reponame>SNU-Programming-Tools/nballerina
#include "balrt.h"
TaggedPtr _bal_float_to_tagged(double n) {
return floatToTagged(n);
}
double READONLY _bal_tagged_to_float(TaggedPtr p) {
return taggedToFloat(p);
}
int64_t READONLY _bal_opt_float_compare(TaggedPtr lhs, TaggedPtr rhs) {
return optFloatCompare(lhs, rhs);
}
|
SNU-Programming-Tools/nballerina
|
runtime/boolean.c
|
#include "balrt.h"
bool _bal_true_subtype_contains(UNUSED UniformSubtypePtr stp, TaggedPtr tp) {
return taggedToBoolean(tp) == 1;
}
bool _bal_false_subtype_contains(UNUSED UniformSubtypePtr stp, TaggedPtr tp) {
return taggedToBoolean(tp) == 0;
}
|
SNU-Programming-Tools/nballerina
|
runtime/decimal.c
|
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "balrt.h"
#include "third-party/decNumber/decQuad.h"
#include "third-party/dtoa/emyg_dtoa.h"
typedef GC decQuad *DecimalPtr;
// Status flags that we should treat as failure
// XXX need to investigate DEC_Underflow
#define DECIMAL_STATUS_FAIL DEC_Errors
static TaggedPtrPanicCode finish(decQuad *dq, decContext *cx);
static bool decimalListContains(const DecimalConstPtr *start, const DecimalConstPtr *end, const decQuad *dq);
static inline TaggedPtr createDecimal(decQuad *dq) {
DecimalPtr dp = _bal_alloc(sizeof(decQuad));
*dp = *dq;
return ptrAddFlags(dp, (uint64_t)TAG_DECIMAL << TAG_SHIFT);
}
static inline const decQuad *taggedToDecQuad(TaggedPtr tp) {
UntypedPtr p = taggedToPtr(tp);
return (void *)p;
}
static inline void initContext(decContext *cx) {
cx->status = 0;
cx->round = DEC_ROUND_HALF_EVEN;
}
TaggedPtrPanicCode _bal_decimal_add(TaggedPtr tp1, TaggedPtr tp2) {
decQuad d;
decContext cx;
initContext(&cx);
decQuadAdd(&d, taggedToDecQuad(tp1), taggedToDecQuad(tp2), &cx);
return finish(&d, &cx);
}
TaggedPtrPanicCode _bal_decimal_sub(TaggedPtr tp1, TaggedPtr tp2) {
decQuad d;
decContext cx;
initContext(&cx);
decQuadSubtract(&d, taggedToDecQuad(tp1), taggedToDecQuad(tp2), &cx);
return finish(&d, &cx);
}
TaggedPtrPanicCode _bal_decimal_mul(TaggedPtr tp1, TaggedPtr tp2) {
decQuad d;
decContext cx;
initContext(&cx);
decQuadMultiply(&d, taggedToDecQuad(tp1), taggedToDecQuad(tp2), &cx);
return finish(&d, &cx);
}
TaggedPtrPanicCode _bal_decimal_div(TaggedPtr tp1, TaggedPtr tp2) {
decQuad d;
decContext cx;
initContext(&cx);
decQuadDivide(&d, taggedToDecQuad(tp1), taggedToDecQuad(tp2), &cx);
return finish(&d, &cx);
}
TaggedPtrPanicCode _bal_decimal_rem(TaggedPtr tp1, TaggedPtr tp2) {
decQuad d;
decContext cx;
initContext(&cx);
decQuadRemainder(&d, taggedToDecQuad(tp1), taggedToDecQuad(tp2), &cx);
return finish(&d, &cx);
}
static TaggedPtrPanicCode finish(decQuad *dq, decContext *cx) {
TaggedPtrPanicCode result;
enum decClass class = decQuadClass(dq);
if (class == DEC_CLASS_POS_ZERO ||
class == DEC_CLASS_NEG_ZERO ||
class == DEC_CLASS_POS_SUBNORMAL ||
class == DEC_CLASS_NEG_SUBNORMAL) {
decQuadZero(dq);
result.panicCode = 0;
result.ptr = createDecimal(dq);
return result;
}
uint32_t status = cx->status;
if (status & DECIMAL_STATUS_FAIL) {
if (status & DEC_Division_by_zero) {
result.panicCode = PANIC_DIVIDE_BY_ZERO;
}
else if (status & DEC_Overflow) {
result.panicCode = PANIC_ARITHMETIC_OVERFLOW;
}
else if (status & DEC_Underflow) {
// The reason to do this check is, there are subnormal cases
// which cannot be identified using decQuadClass.
// Consider this example: mul(9.999999999999999999999999999999999E-6001, 1E-143)
// Before rounding the result is 9.999999999999999999999999999999999E-6144,
// which is subnormal. After rounding The class of result is
// +Normal and value is 1.000000000000000000000000000000000E-6143
// Also underflow flag is raised.
// But according the The X3.274 subset, the expected value should be 0.
// Therefore it is unable to identify cases like this using decQuadClass.
// In the library,
// 1. Multiplication happens in two logical stages:
// perform the multiplication to a precision greater than allowed by decimal128 format,
// and then round to fit into a decimal128
// 2. It is possible for the result of the first stage to be subnormal,
// but then be rounded in the second stage to become normal
// 3. In this case, decNumber in subset mode will return 0.
// 4. We can detect this case in decQuad by checking the Underflow flag.
decQuadZero(dq);
result.panicCode = 0;
result.ptr = createDecimal(dq);
}
else {
// status & DEC_IEEE_754_Invalid_operation = true
// This is used in a case where a float operation would return NaN
result.panicCode = PANIC_INVALID_DECIMAL;
}
}
else {
result.panicCode = 0;
result.ptr = createDecimal(dq);
}
return result;
}
TaggedPtr _bal_decimal_neg(TaggedPtr tp) {
const decQuad *dq = taggedToDecQuad(tp);
if (decQuadClass(dq) == DEC_CLASS_POS_ZERO) {
return tp;
}
decQuad d;
decQuadCopyNegate(&d, dq);
return createDecimal(&d);
}
bool _bal_decimal_exact_eq(TaggedPtr tp1, TaggedPtr tp2) {
decQuad d1;
decQuad d2;
decQuadCanonical(&d1, taggedToDecQuad(tp1));
decQuadCanonical(&d2, taggedToDecQuad(tp2));
return memcmp(&d1, &d2, DECQUAD_Bytes) == 0;
}
int64_t _bal_decimal_cmp(TaggedPtr tp1, TaggedPtr tp2) {
decQuad d;
decContext cx;
initContext(&cx);
decQuadCompare(&d, taggedToDecQuad(tp1), taggedToDecQuad(tp2), &cx);
// The return value of decQuadCompare can be 1, 0, -1 or NaN:
// since this is represented as a decQuad, decQuadClass is used to
// identify 1, 0, -1.
// NaN is returned only if lhs or rhs is a NaN.
// It is not an expected output because both arguments are valid decimals.
enum decClass class = decQuadClass(&d);
if (class == DEC_CLASS_POS_ZERO) {
return 0;
}
else if (class == DEC_CLASS_POS_NORMAL) {
return 1;
}
else {
return -1;
}
}
double _bal_decimal_to_float(TaggedPtr tp) {
char dblStr[DECQUAD_String];
decQuadToString(taggedToDecQuad(tp), dblStr);
return strtod(dblStr, NULL);
}
TaggedPtr _bal_decimal_from_int(int64_t val) {
decQuad d;
if (INT32_MIN <= val && val <= INT32_MAX) {
decQuadFromInt32(&d, (int32_t)val);
}
else {
#define STR_CONVERT(x) #x
#define STR(x) STR_CONVERT(x)
#define INT64_MAX_LEN sizeof(STR(INT64_MIN))
char intStr[INT64_MAX_LEN];
sprintf(intStr, "%" PRId64, val);
decContext cx;
initContext(&cx);
decQuadFromString(&d, intStr, &cx);
}
return createDecimal(&d);
}
TaggedPtrPanicCode _bal_decimal_from_float(double val) {
TaggedPtrPanicCode result;
if (isnan(val)) {
result.panicCode = PANIC_INVALID_DECIMAL;
return result;
}
if (isinf(val)) {
result.panicCode = PANIC_ARITHMETIC_OVERFLOW;
return result;
}
result.panicCode = 0;
decQuad d;
if (val == 0.0) {
decQuadZero(&d);
result.ptr = createDecimal(&d);
return result;
}
char str[EMYG_DTOA_BUFFER_LEN];
emyg_dtoa_non_special(val, str);
decContext cx;
initContext(&cx);
decQuadFromString(&d, str, &cx);
decQuad dTrim;
decQuadReduce(&dTrim, &d, &cx);
result.ptr = createDecimal(&dTrim);
return result;
}
IntWithOverflow _bal_decimal_to_int(TaggedPtr tp) {
decQuad dQuantize;
decQuad dZero;
decQuadZero(&dZero);
decContext cx;
initContext(&cx);
decQuadQuantize(&dQuantize, taggedToDecQuad(tp), &dZero, &cx);
IntWithOverflow res;
if (cx.status & DEC_Invalid_operation) {
// The invalid operation flag is raised,
// when maximum precision(34 digits) is not enough to represent quantized decimal value.
// This situation can be considered as an overflow scenario,
// because reaching maximum precision of decimal is an overflow of 64 bit integer(19 digits).
res.overflow = true;
return res;
}
char str[DECQUAD_String];
decQuadToString(&dQuantize, str);
errno = 0;
int64_t value = strtol(str, NULL, 0);
if (errno == ERANGE) {
res.overflow = true;
return res;
}
res.overflow = false;
res.value = value;
return res;
}
TaggedPtr _bal_decimal_const(const char *decString) {
decContext cx;
initContext(&cx);
decQuad dq;
decQuadFromString(&dq, decString, &cx);
return createDecimal(&dq);
}
bool _bal_decimal_subtype_contains(UniformSubtypePtr stp, TaggedPtr tp) {
DecimalSubtypePtr dstp = (DecimalSubtypePtr)stp;
return decimalListContains(dstp->decimals, dstp->decimals + dstp->nDecimals, taggedToDecQuad(tp));
}
// Do binary search for tp
// Approximately the same code as tidListContains
// The decimal constants are currently stored as ASCII strings,
// which means we have to convert each before we compare it.
// (Obviously far from optimal: the compiler should convert decimal constants into the IEEE binary128
// format used by decNumber. This will be easier if we can self-host since we can link to decNumber.)
static bool decimalListContains(const DecimalConstPtr *start, const DecimalConstPtr *end, const decQuad *dq) {
// Lower bound inclusive; upper bound is exclusive
// Invariant: if there is a member in the list == to dq, then its address p
// satisfies start <= p < end
decContext cx;
initContext(&cx);
while (start < end) {
const DecimalConstPtr *mid = start + (end - start)/2;
decQuad midVal;
decQuadFromString(&midVal, *mid, &cx);
decQuad cmp;
decQuadCompare(&cmp, dq, &midVal, &cx);
enum decClass cmpClass = decQuadClass(&cmp);
// We have start <= mid < end
// int64_t cmp = _bal_decimal_cmp(tp, *mid);
if (cmpClass == DEC_CLASS_POS_ZERO) {
return true;
}
if (cmpClass == DEC_CLASS_NEG_NORMAL) {
// this decreases end, since mid < end
// still have start <= end
end = mid;
}
else {
// this increases start, since mid >= start
// still have start <= end
start = mid + 1;
}
}
// start == end, so there is no such member
return false;
}
|
SNU-Programming-Tools/nballerina
|
runtime/balrt_inline.h
|
<gh_stars>1-10
extern bool _bal_float_exact_eq(double, double);
extern IntWithOverflow _bal_float_to_int(double);
TaggedPtr _bal_float_to_tagged(double n);
TaggedPtr _bal_int_to_tagged(int64_t n);
CompareResult _bal_opt_int_compare(TaggedPtr lhs, TaggedPtr rhs);
CompareResult _bal_opt_float_compare(TaggedPtr lhs, TaggedPtr rhs);
CompareResult _bal_opt_decimal_compare(TaggedPtr lhs, TaggedPtr rhs);
CompareResult _bal_opt_string_compare(TaggedPtr lhs, TaggedPtr rhs);
void BAL_LANG_ARRAY_NAME(push)(TaggedPtr p, TaggedPtr val);
|
SNU-Programming-Tools/nballerina
|
runtime/tests/inlinert_int.c
|
#include "test_utils.h"
#include "../balrt_inline.h"
void testIntNilCmp() {
TaggedPtr a = _bal_int_to_tagged(5);
TaggedPtr b = _bal_int_to_tagged(IMMEDIATE_INT_MAX + 1);
TaggedPtr c = _bal_int_to_tagged(IMMEDIATE_INT_MIN - 1);
TaggedPtr nil = getNil();
assert(_bal_opt_int_compare(a, nil) == COMPARE_UN);
assert(_bal_opt_int_compare(b, nil) == COMPARE_UN);
assert(_bal_opt_int_compare(c, nil) == COMPARE_UN);
assert(_bal_opt_int_compare(nil, a) == COMPARE_UN);
assert(_bal_opt_int_compare(nil, b) == COMPARE_UN);
assert(_bal_opt_int_compare(nil, c) == COMPARE_UN);
assert(_bal_opt_int_compare(nil, nil) == COMPARE_EQ);
}
void testIntIntCmp() {
TaggedPtr a = _bal_int_to_tagged(5);
TaggedPtr b = _bal_int_to_tagged(-5);
TaggedPtr c = _bal_int_to_tagged(IMMEDIATE_INT_MAX + 1);
TaggedPtr d = _bal_int_to_tagged(IMMEDIATE_INT_MIN - 1);
assert(_bal_opt_int_compare(a, a) == COMPARE_EQ);
assert(_bal_opt_int_compare(a, b) == COMPARE_GT);
assert(_bal_opt_int_compare(a, c) == COMPARE_LT);
assert(_bal_opt_int_compare(a, d) == COMPARE_GT);
assert(_bal_opt_int_compare(b, a) == COMPARE_LT);
assert(_bal_opt_int_compare(b, b) == COMPARE_EQ);
assert(_bal_opt_int_compare(b, c) == COMPARE_LT);
assert(_bal_opt_int_compare(b, d) == COMPARE_GT);
assert(_bal_opt_int_compare(c, a) == COMPARE_GT);
assert(_bal_opt_int_compare(c, b) == COMPARE_GT);
assert(_bal_opt_int_compare(c, c) == COMPARE_EQ);
assert(_bal_opt_int_compare(c, d) == COMPARE_GT);
assert(_bal_opt_int_compare(d, a) == COMPARE_LT);
assert(_bal_opt_int_compare(d, b) == COMPARE_LT);
assert(_bal_opt_int_compare(d, c) == COMPARE_LT);
assert(_bal_opt_int_compare(d, d) == COMPARE_EQ);
}
int main() {
testIntNilCmp();
testIntIntCmp();
return 0;
}
|
SNU-Programming-Tools/nballerina
|
runtime/int_inline.c
|
#include "balrt.h"
TaggedPtr _bal_int_to_tagged(int64_t n) {
return intToTagged(n);
}
int64_t READONLY _bal_tagged_to_int(TaggedPtr p) {
return taggedToInt(p);
}
int64_t _bal_opt_int_compare(TaggedPtr lhs, TaggedPtr rhs) {
return optIntCompare(lhs, rhs);
}
|
SNU-Programming-Tools/nballerina
|
runtime/tests/list_utils.h
|
#define LIST_DESC_FUNC(kind,mid,suffix) _bal_list_ ## kind ## mid ## suffix
#define _bal_list_int_array_get_float NULL
#define _bal_list_byte_array_get_float NULL
#define _bal_list_float_array_get_int NULL
#define LIST_DESC_VTABLE(kind, inexact_set) \
LIST_DESC_FUNC(kind, _get_, tagged),\
LIST_DESC_FUNC(kind, _set_, tagged),\
LIST_DESC_FUNC(kind, inexact_set, tagged),\
LIST_DESC_FUNC(kind, _get_, int),\
LIST_DESC_FUNC(kind, _set_, int),\
LIST_DESC_FUNC(kind, inexact_set, int),\
LIST_DESC_FUNC(kind, _get_, float),\
LIST_DESC_FUNC(kind, _set_, float),\
LIST_DESC_FUNC(kind, inexact_set, float)
#define LIST_DESC_INIT_GENERIC(tid, bitSet) {\
tid, 0, 0,\
LIST_DESC_VTABLE(generic, _inexact_set_),\
BITSET_MEMBER_TYPE(bitSet)\
}
#define LIST_DESC_INIT_INT_ARRAY(tid) {\
tid, 0, 0,\
LIST_DESC_VTABLE(int_array, _set_),\
BITSET_MEMBER_TYPE(1 << TAG_INT)\
}
#define LIST_DESC_INIT_BYTE_ARRAY(tid, byteType) {\
tid, 0, 0,\
LIST_DESC_VTABLE(byte_array, _set_),\
byteType\
}
#define LIST_DESC_INIT_FLOAT_ARRAY(tid) {\
tid, 0, 0,\
LIST_DESC_VTABLE(float_array, _set_),\
BITSET_MEMBER_TYPE(1 << TAG_FLOAT)\
}
|
imChay/Test
|
LibTest/CYPrint.h
|
<reponame>imChay/Test
//
// CYPrint.h
// LibTest
//
// Created by cy on 2018/1/14.
// Copyright © 2018年 cy. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface CYPrint : NSObject
+ (void)print;
@end
|
imChay/Test
|
LibTest/LibTest.h
|
<filename>LibTest/LibTest.h
//
// LibTest.h
// LibTest
//
// Created by cy on 2018/1/14.
// Copyright © 2018年 cy. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for LibTest.
FOUNDATION_EXPORT double LibTestVersionNumber;
//! Project version string for LibTest.
FOUNDATION_EXPORT const unsigned char LibTestVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <LibTest/PublicHeader.h>
#if __has_include(<LibTest/LibTest.h>)
#import <LibTest/CYPrint.h>
#else
#import "CYPrint.h"
#endif
|
nickolasburr/str
|
include/mem.h
|
<filename>include/mem.h
/**
* mem.h
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#ifndef STR_MEM_H
#define STR_MEM_H
#include "common.h"
#include "assert.h"
#include "except.h"
extern const Except_T Mem_Failed;
extern void *Mem_alloc(long nbytes, const char *file, int line);
extern void *Mem_calloc(long count, long nbytes, const char *file, int line);
extern void Mem_free(void *ptr, const char *file, int line);
extern void *Mem_resize(void *ptr, long nbytes, const char *file, int line);
#define ALLOC(nbytes) Mem_alloc((nbytes), __FILE__, __LINE__)
#define CALLOC(count, nbytes) Mem_calloc((count), (nbytes), __FILE__, __LINE__)
#define NEW(p) ((p) = ALLOC((long)sizeof *(p)))
#define NEW0(p) ((p) = CALLOC(1, (long)sizeof *(p)))
#define FREE(ptr) ((void)(Mem_free((ptr), __FILE__, __LINE__), (ptr) = 0))
#define RESIZE(ptr, nbytes) ((ptr) = Mem_resize((ptr), (nbytes), __FILE__, __LINE__))
#endif /* STR_MEM_H */
|
nickolasburr/str
|
include/common.h
|
<filename>include/common.h
/**
* common.h
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#ifndef STR_COMMON_H
#define STR_COMMON_H
#include <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifdef __APPLE__
#include <limits.h>
#else
#include <linux/limits.h>
#endif
#define is_null(ptr) ((ptr) == ((void *) 0))
#define NULL_BYTE 1
#define EXECNAME "str"
#define EXECVERS "1.0.0"
#endif /* STR_COMMON_H */
|
nickolasburr/str
|
src/argv.c
|
/**
* argv.c
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#include "argv.h"
static option_t options[] = {
{
"--help",
"-h",
"Show help information.",
},
{
"--version",
"-v",
"Show version number.",
},
{
"--quiet",
"-q",
"Suppress filename output.",
},
{
"--extension",
"-e",
"Set file extension.",
},
};
/**
* Print usage information.
*/
void usage (void) {
int index;
fprintf(stdout, "Usage: %s [OPTIONS]\n\n", EXECNAME);
fprintf(stdout, "OPTIONS:\n\n");
for (index = 0; index < NUM_OPTS; index += 1) {
option_t *option = &options[index];
fprintf(stdout, "%4s%s, %s: %-24s\n", "", option->alias, option->value, option->desc);
}
}
|
nickolasburr/str
|
src/except.c
|
<gh_stars>0
/**
* except.c
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#include "common.h"
#include "assert.h"
#include "except.h"
#define T Except_T
Except_Frame *Except_stack = NULL;
void Except_raise (const T *e, const char *file, int line) {
Except_Frame *p = Except_stack;
assert(e);
if (is_null(p)) {
fprintf(stderr, "Uncaught exception");
if (e->reason) {
fprintf(stderr, " %s", e->reason);
} else {
fprintf(stderr, " at 0x%p", e);
}
if (file && line > 0) {
fprintf(stderr, " raised at %s:%d\n", file, line);
}
fprintf(stderr, "aborting...\n");
fflush(stderr);
abort();
}
p->exception = e;
p->file = file;
p->line = line;
Except_stack = Except_stack->prev;
longjmp(p->env, Except_raised);
}
|
nickolasburr/str
|
include/main.h
|
<reponame>nickolasburr/str
/**
* main.h
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#ifndef STR_MAIN_H
#define STR_MAIN_H
#include "common.h"
#include "assert.h"
#include "except.h"
#include "argv.h"
#include "mem.h"
#include "rand.h"
#include "utils.h"
#endif /* STR_MAIN_H */
|
nickolasburr/str
|
include/assert.h
|
<reponame>nickolasburr/str
/**
* assert.h
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#undef assert
#ifdef NDEBUG
#define assert(e) ((void)0)
#else
#include "except.h"
extern void assert(int e);
#define assert(e) ((void)((e)||(RAISE(Assert_Failed),0)))
#endif
|
nickolasburr/str
|
include/rand.h
|
/**
* rand.h
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#ifndef STR_RAND_H
#define STR_RAND_H
#include "common.h"
#include "mem.h"
#define RANDSTR_MIN_LEN 8
#define RANDSTR_CHARSET "0123456789abcdefghijklmnopqrstuvwxyz"
char *randstr(size_t);
#endif /* STR_RAND_H */
|
nickolasburr/str
|
include/error.h
|
/**
* error.h
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#ifndef STR_ERROR_H
#define STR_ERROR_H
int is_error(int, int);
#endif /* STR_ERROR_H */
|
nickolasburr/str
|
src/rand.c
|
<reponame>nickolasburr/str
/**
* rand.c
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
* Adapted from https://tinyurl.com/vy8ygj2
*/
#include "rand.h"
char *randstr(size_t length) {
size_t index, key;
char *buf = NULL;
if (length < RANDSTR_MIN_LEN) {
length = RANDSTR_MIN_LEN;
}
buf = ALLOC(length + NULL_BYTE);
if (!is_null(buf)) {
for (index = 0; index < length; index += 1) {
key = rand() % (int)(sizeof(RANDSTR_CHARSET) - NULL_BYTE);
buf[index] = RANDSTR_CHARSET[key];
}
buf[length] = '\0';
}
return buf;
}
|
nickolasburr/str
|
src/mem.c
|
<filename>src/mem.c<gh_stars>0
/**
* mem.c
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#include "mem.h"
const Except_T Mem_Failed = {
"Allocation Failed"
};
void *Mem_alloc (long nbytes, const char *file, int line) {
void *ptr;
assert(nbytes > 0);
ptr = malloc(nbytes);
if (is_null(ptr)) {
if (is_null(file)) {
RAISE(Mem_Failed);
} else {
Except_raise(&Mem_Failed, file, line);
}
}
return ptr;
}
void *Mem_calloc (long count, long nbytes, const char *file, int line) {
void *ptr;
assert(count > 0);
assert(nbytes > 0);
ptr = calloc(count, nbytes);
if (is_null(ptr)) {
if (is_null(file)) {
RAISE(Mem_Failed);
} else {
Except_raise(&Mem_Failed, file, line);
}
}
return ptr;
}
void Mem_free (void *ptr, const char *file, int line) {
if (ptr) {
free(ptr);
}
}
void *Mem_resize (void *ptr, long nbytes, const char *file, int line) {
assert(ptr);
assert(nbytes > 0);
ptr = realloc(ptr, nbytes);
if (is_null(ptr)) {
if (is_null(file)) {
RAISE(Mem_Failed);
} else {
Except_raise(&Mem_Failed, file, line);
}
}
return ptr;
}
|
nickolasburr/str
|
src/main.c
|
<reponame>nickolasburr/str<filename>src/main.c
/**
* main.c
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#include "main.h"
int main (int argc, char **argv) {
int error, index, quiet, value;
size_t length;
ssize_t read;
FILE *file = NULL;
char *extn = NULL,
*line = NULL,
*base = NULL,
*name = NULL;
static struct option long_opts[] = {
{ "help", no_argument, 0, 'h' },
{ "version", no_argument, 0, 'v' },
{ "quiet", no_argument, 0, 'q' },
{ "extension", required_argument, 0, 'e' }
};
index = 0;
quiet = 0;
while ((value = getopt_long(argc, argv, OPT_ARGS, long_opts, &index)) != -1) {
switch (value) {
case 'h':
usage();
exit(EXIT_SUCCESS);
case 'v':
fprintf(stdout, "%s\n", EXECVERS);
exit(EXIT_SUCCESS);
case 'q':
quiet = 1;
break;
case 'e':
if (is_null(optarg)) {
fprintf(stdout, "%s: Missing file extension.\n", EXECNAME);
goto on_error;
}
extn = optarg;
break;
case '?':
usage();
exit(EXIT_FAILURE);
default:
usage();
exit(EXIT_FAILURE);
}
}
if (is_null(extn)) {
fprintf(stdout, "%s: Missing file extension.\n", EXECNAME);
goto on_error;
}
srand(time(NULL));
base = concat(randstr(RANDSTR_MIN_LEN), ".");
name = concat(base, extn);
file = get_file(&error, name, "w");
if (error) {
fprintf(stderr, "Unable to open file for writing.\n");
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &length, stdin)) != -1) {
fwrite(line, read, 1, file);
}
if (!quiet) {
fprintf(stdout, "%s\n", name);
}
fclose(file);
return EXIT_SUCCESS;
on_error:
return EXIT_FAILURE;
}
|
nickolasburr/str
|
src/assert.c
|
/**
* assert.c
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#include "assert.h"
const Except_T Assert_Failed = {
"Assertion failed"
};
void (assert)(int e) {
assert(e);
}
|
nickolasburr/str
|
include/argv.h
|
<gh_stars>0
/**
* argv.h
*
* Copyright (C) 2020 <NAME> <<EMAIL>>
*/
#ifndef STR_ARGV_H
#define STR_ARGV_H
#include "common.h"
#include "error.h"
#include "utils.h"
#define NUM_OPTS 4
#define OPT_ARGS "hvqe:"
typedef struct {
char *value;
char *alias;
char *desc;
} option_t;
static option_t options[NUM_OPTS];
void usage(void);
#endif /* STR_ARGV_H */
|
scheibo/dat
|
ext/logic/logic.c
|
<reponame>scheibo/dat
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include "ruby.h"
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define ASCII_A 65
#define ALPHABET_SIZE 26
/* only allow strings up to length of 30 */
#define SIZE_BYTES 32
/* save space by storing the string lengths in a small int */
typedef int8_t size;
#if !defined(RSTRING_LEN)
#define RSTRING_LEN(x) (RSTRING(x)->len)
#define RSTRING_PTR(x) (RSTRING(x)->ptr)
#endif
/* Use these instead of using const_get */
#define MIN_SIZE 3
#define WEIGHT_THRESHOLD 0.7
#define NUM_CHARS 4
static ID id_get;
static ID id_real_get;
static ID id_reject;
static const char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static VALUE init(int argc, VALUE *argv, VALUE self) {
VALUE dict, opt, add, replace, delete, transpose;
rb_scan_args(argc, argv, "11", &dict, &opt);
if (NIL_P(opt)) opt = rb_hash_new();
rb_iv_set(self, "@dict", dict);
add = rb_hash_lookup2(opt, ID2SYM(rb_intern("add")), Qtrue);
replace = rb_hash_lookup2(opt, ID2SYM(rb_intern("replace")), Qtrue);
delete = rb_hash_lookup2(opt, ID2SYM(rb_intern("delete")), Qtrue);
transpose = rb_hash_lookup2(opt, ID2SYM(rb_intern("delete")), Qfalse);
rb_iv_set(self, "@add", add);
rb_iv_set(self, "@replace", replace);
rb_iv_set(self, "@delete", delete) ;
rb_iv_set(self, "@transpose", transpose);
rb_iv_set(self, "@min_size", rb_hash_lookup2(opt, ID2SYM(rb_intern("min_size")), INT2FIX(MIN_SIZE)));
rb_iv_set(self, "@cachable", (RTEST(add) && RTEST(replace) && RTEST(delete) && !RTEST(transpose) ? Qtrue : Qfalse));
rb_iv_set(self, "@perturb_cache", rb_hash_new());
return self;
}
/* Helper function to add values to the results array */
static void add_if_in_dict(VALUE dict, char *word, VALUE result) {
VALUE w = rb_str_new_cstr(word);
VALUE d = rb_funcall(dict, id_get, 1, w);
if (RTEST(d)) rb_ary_push(result, d);
}
static VALUE reject_i(VALUE word, VALUE used) {
return RTEST(rb_funcall(used, id_get, 1, rb_funcall(word, id_real_get, 0)));
}
static VALUE perturb_impl(VALUE self, VALUE str) {
char cacheable = RTEST(rb_iv_get(self, "@cachable"));
VALUE cache = rb_iv_get(self, "@perturb_cache");
if (cacheable) {
VALUE r = rb_hash_aref(cache, str);
if (RTEST(r)) return r;
}
VALUE dict = rb_iv_get(self, "@dict");
size min_size = FIX2LONG(rb_iv_get(self, "@min_size"));
char start[SIZE_BYTES], fin[SIZE_BYTES], w[SIZE_BYTES];
char *word = StringValueCStr(str); /* word is assumed to already be uppercase */
size len = RSTRING_LEN(str); /* should be strlen(word) */
VALUE result = rb_ary_new();
char add = RTEST(rb_iv_get(self, "@add"));
char replace = RTEST(rb_iv_get(self, "@replace"));
char delete = RTEST(rb_iv_get(self, "@delete"));
char transpose = RTEST(rb_iv_get(self, "@transpose"));
size i, j;
char c;
for(i = 0; i <= len; i++) {
strncpy(start, word, i);
start[i] = '\0';
for(j = 0; c = alpha[j]; j++) {
if (add && len >= min_size+1) {
strncpy(fin, word+i, len+1);
strncpy(w, start, i+1);
strncat(w, &c, 1);
strncat(w, fin, len-i);
add_if_in_dict(dict, w, result);
}
if (i < len) {
if (replace && len >= min_size) {
(i+1 == len) ? strncpy(fin, "", 2) : strncpy(fin, word+i+1, len+1);
strncpy(w, start, i+1);
strncat(w, &c, 1);
strncat(w, fin, len-i-1);
w[len+1] = '\0';
if (strncmp(word, w, len)) {
add_if_in_dict(dict, w, result);
}
}
}
}
if (i < len && delete && len > min_size) {
(i+1 == len) ? strncpy(fin, "", 2) : strncpy(fin, word+i+1, len+1);
strncpy(w, start, i+1);
strncat(w, fin, len-i-1);
w[len] = '\0';
add_if_in_dict(dict, w, result);
}
}
if (cacheable) {
rb_hash_aset(cache, str, result);
}
return result;
}
static VALUE perturb(int argc, VALUE *argv, VALUE self) {
VALUE str, used;
rb_scan_args(argc, argv, "11", &str, &used);
if (NIL_P(used)) used = rb_hash_new();
VALUE result = rb_block_call(perturb_impl(self, str), id_reject, 0, 0, reject_i, used);
return result;
}
static VALUE jaro_winkler(VALUE self, VALUE a, VALUE b) {
int i, j, start, fin;
char *s = StringValueCStr(a);
char *t = StringValueCStr(b);
size m = (size) RSTRING_LEN(a);
size n = (size) RSTRING_LEN(b);
if (m == 0) return rb_float_new(n == 0 ? 1.0 : 0.0);
size range = MAX(0, (MAX(m,n)/2) - 1);
char s_matched[SIZE_BYTES];
char t_matched[SIZE_BYTES];
for (i = 0; i < m; i++) s_matched[i] = 0;
for (i = 0; i < n; i++) t_matched[i] = 0;
int common = 0;
for (i = 0; i < m; i++) {
start = MAX(0,i-range);
fin = MIN(i+range+1, n);
for (j = start; j < fin; j++) {
if (t_matched[j] || s[i] != t[j]) continue;
s_matched[i] = 1;
t_matched[j] = 1;
common++;
break;
}
}
if (!common) return rb_float_new(0.0);
int transposed = 0;
j = 0;
for (i = 0; i < m; i++) {
if (!s_matched[i]) continue;
while (!t_matched[j]) j++;
if (s[i] != t[j]) transposed++;
j++;
}
transposed /= 2;
double weight = (((double)common/m) + ((double)common/n) + ((double)(common-transposed)/common)) / 3.0;
if (weight <= WEIGHT_THRESHOLD) return rb_float_new(weight);
int max = MIN(NUM_CHARS, MIN(m,n));
int pos = 0;
while (pos < max && s[pos] == t[pos]) pos++;
if (pos == 0) return rb_float_new(weight);
return rb_float_new(weight + 0.1 * pos * (1.0 - weight));
}
/* precondition: a and b not nil and the words are uppercase */
static VALUE damlev(VALUE self, VALUE a, VALUE b) {
size i, j, w, x, y, z;
char *s = StringValueCStr(a);
char *t = StringValueCStr(b);
size m = (size) RSTRING_LEN(a);
size n = (size) RSTRING_LEN(b);
if (!m) return INT2FIX(n);
if (!n) return INT2FIX(m);
size h[SIZE_BYTES][SIZE_BYTES];
size inf = m + n;
h[0][0] = inf;
for (i = 0; i <= m; i++) { h[i+1][1] = i; h[i+1][0] = inf; }
for (j = 0; j <= n; j++) { h[1][j+1] = j; h[0][j+1] = inf; }
size da[ALPHABET_SIZE];
for (i = 0; i < ALPHABET_SIZE; i++) {
da[i] = 0;
}
size db, i1, j1, d;
for (i = 1; i <= m; i++) {
db = 0;
for (j = 1; j <= n; j++) {
i1 = da[t[j-1]-ASCII_A];
j1 = db;
d = ( (s[i-1] == t[j-1]) ? 0 : 1);
if (!d) {
db = j;
}
w = h[i][j]+d; x = h[i+1][j] + 1; y = h[i][j+1]+1; z = h[i1][j1] + (i-i1-1) + 1 + (j-j1-1);
h[i+1][j+1] = MIN( MIN( MIN(w, x), y ), z );
}
da[s[i-1]-ASCII_A] = i;
}
VALUE val = INT2FIX(h[m+1][n+1]);
return val;
}
static VALUE leven(VALUE self, VALUE a, VALUE b) {
size i, j;
char *s = StringValueCStr(a);
char *t = StringValueCStr(b);
size m = (size) RSTRING_LEN(a);
size n = (size) RSTRING_LEN(b);
/* for all i and j, d[i,j] will hold the Levenshtein distance between
* the first i characters of s and the first j characters of t;
* note that d has (m+1)x(n+1) values */
size d[SIZE_BYTES][SIZE_BYTES];
for (i = 0; i <= m; i++) {
d[i][0] = i;
for (j = 0; j <= n; j++) {
d[0][j] = j;
}
}
for (j = 1; j <= n; j++) {
for (i = 1; i <= m; i++) {
if (s[i-1] == t[j-1]) {
d[i][j] = d[i-1][j-1];
} else { /* delete */ /* insert */ /* replace */
d[i][j] = MIN( MIN((d[i-1][j] + 1), (d[i][j-1] + 1)), (d[i-1][j-1] + 1) );
}
}
}
VALUE val = INT2FIX(d[m][n]);
return val;
}
void Init_logic(void) {
VALUE mDat = rb_define_module("Dat");
VALUE cLogic = rb_define_class_under(mDat, "Logic", rb_cObject);
rb_const_set(cLogic, rb_intern("MIN_SIZE"), MIN_SIZE);
rb_const_set(cLogic, rb_intern("WEIGHT_THRESHOLD"), WEIGHT_THRESHOLD);
rb_const_set(cLogic, rb_intern("NUM_CHARS"), NUM_CHARS);
rb_define_attr(cLogic, "min_size", 1, 0);
rb_define_method(cLogic, "initialize", init, -1);
rb_define_method(cLogic, "perturb", perturb, -1);
rb_define_private_method(cLogic, "perturb_impl", perturb_impl, 1);
rb_define_method(cLogic, "jaro_winkler", jaro_winkler, 2);
rb_define_method(cLogic, "leven", leven, 2);
rb_define_method(cLogic, "damlev", damlev, 2);
id_get = rb_intern("[]");
id_real_get = rb_intern("get");
id_reject = rb_intern("reject");
}
|
1Basile/pseudorandom_number_generators
|
extended_grade_common_devider_alg.h
|
<reponame>1Basile/pseudorandom_number_generators<gh_stars>0
#ifndef EXTENDED_GRADE_COMMON_DEVIDER_ALG_IMMPORTED
#define EXTENDED_GRADE_COMMON_DEVIDER_ALG_IMMPORTED
// C function for extended Euclidean Algorithm
int ext_gcd(int a, int b, int* x, int* y)
{
// Base Case
if (a == 0) {
*x = 0;
*y = 1;
return b;
}
int x1, y1; // To store results of recursive call
int gcd = ext_gcd(b % a, a, &x1, &y1);
// Update x and y using results of recursive
// call
*x = y1 - (b / a) * x1;
*y = x1;
return gcd;
}
// Driver Program
/* int main() */
/* { */
/* int x, y; */
/* int a = 35, b = 15; */
/* int g = ext_gcd(a, b, &x, &y); */
/* printf("gcd(%d, %d) = %d\n", a, b, g); */
/* printf("%d*%d + %d*%d = %d\n", a, x, b, y, g); */
/* return 0; */
/* } */
#endif
|
1Basile/pseudorandom_number_generators
|
ratio_method_generator.h
|
#ifndef RATIO_METHOD_GENERATOR_IMPORTED
#define RATIO_METHOD_GENERATOR_IMPORTED
#include "linear_congruential_generator.h"
#include <math.h>
// #define rat_rand(...) rat_rand_predef((inner_func_params_t){__VA_ARGS__})
#ifndef inner_func_params_t_defined
#define inner_func_params_t_defined
typedef struct {
unsigned char normalize;
} inner_func_params_t;
#endif
double rat_rand_base(unsigned char to_normalize) {
double u, v, x;
do {
do {
u = lcg_rand_norm();
} while ( u == 0 );
v = lcg_rand_norm();
x = sqrt(((double)8 / exp(1))) * ((v - 0.5) / u);
if (x*x <= 5 - 4*exp(0.25)*u) { return x; }
} while ( x*x >= (4*exp(-1.35) / u) + 1.4 || x*x > -4*log(u));
return x;
}
double rat_rand(void) {
double u, v, x;
do {
do {
u = lcg_rand_norm();
} while ( u == 0 );
v = lcg_rand_norm();
x = sqrt(((double)8 / exp(1))) * ((v - 0.5) / u);
if (x*x <= 5 - 4*exp(0.25)*u) { return x; }
} while ( x*x >= (4*exp(-1.35) / u) + 1.4 || x*x > -4*log(u));
return x;
}
// Function wallper
double rat_rand_predef(inner_func_params_t in){
unsigned char normalize = in.normalize ? in.normalize : 0;
return rat_rand_base(normalize);
}
#endif
|
1Basile/pseudorandom_number_generators
|
quadratic_congruential_generator.h
|
#ifndef QUADRATIC_CONGRUENTIAL_GENERATOR_IMPORTED
#define QUADRATIC_CONGRUENTIAL_GENERATOR_IMPORTED
double qcg_rand(void) {
static unsigned long int step = 11;
static const unsigned int a = 85;
static const unsigned int c = 139;
static const unsigned int m = 3539;
static const unsigned int d = 252; /* 0, 84, 252, 336, 504, 588, 756, 840 */
step = ((d*step*step) * (a*step) + c) % m;
return (double)step;
}
double qcg_rand_norm(void) {
static unsigned long int step = 11;
static const unsigned int a = 85;
static const unsigned int c = 139;
static const unsigned int m = 3539;
static const unsigned int d = 252; /* 0, 84, 252, 336, 504, 588, 756, 840 */
step = ((d*step*step) * (a*step) + c) % m;
return (double)step / (double)m;
}
double qcg_rand_base(unsigned char to_normalize) {
static unsigned long int step = 7;
static const unsigned int a = 84589;
static const unsigned int c = 45989;
static const unsigned int m = 217728;
static const unsigned int d = 84; /* 0, 84, 252, 336, 504, 588, 756, 840 */
step = ((d*step*step) * (a*step) + c) % m;
return to_normalize == 1 ? (double)step / (double)m : (double)step;
}
// #define qcg_rand(...) qcg_rand_predef((inner_func_params_t){__VA_ARGS__})
#ifndef inner_func_params_t_defined
#define inner_func_params_t_defined
typedef struct {
unsigned char normalize;
} inner_func_params_t;
#endif
// Function wallper
double qcg_rand_predef(inner_func_params_t in){
unsigned char normalize = in.normalize ? in.normalize : 0;
return qcg_rand_base(normalize);
}
#endif
|
1Basile/pseudorandom_number_generators
|
log_method_for_exponential_distribution_generator.h
|
#ifndef LOG_METHOD_FOR_EXPONENTIAL_DISTRIBUTION_GENERATOR_IMPORTED
#define LOG_METHOD_FOR_EXPONENTIAL_DISTRIBUTION_GENERATOR_IMPORTED
#include "linear_congruential_generator.h"
#include <math.h>
// #define log_exp_rand(...) log_exp_rand_predef((inner_func_params_t){__VA_ARGS__})
#ifndef inner_func_params_t_defined
#define inner_func_params_t_defined
typedef struct {
unsigned char normalize;
} inner_func_params_t;
#endif
double log_exp_rand_base(unsigned char to_normalize) {
double u = lcg_rand_norm();
double mu = 9; // Random constant
return -mu*log(u);
}
double log_exp_rand(void) {
double u = lcg_rand_norm();
double mu = 9; // Random constant
return -mu*log(u);
}
// Function wallper
double log_exp_rand_predef(inner_func_params_t in){
unsigned char normalize = in.normalize ? in.normalize : 0;
return log_exp_rand_base(normalize);
}
#endif
|
1Basile/pseudorandom_number_generators
|
arensa_method_for_gamma_distribution_generator.h
|
<reponame>1Basile/pseudorandom_number_generators
#ifndef ARENSA_METHOD_FOR_GAMMA_DISTRIBUTION_GENERATOR_IMPORTED
#define ARENSA_METHOD_FOR_GAMMA_DISTRIBUTION_GENERATOR_IMPORTED
#include "linear_congruential_generator.h"
#include <math.h>
// #define arensa_gamma_rand(...) arensa_gamma_rand_predef((inner_func_params_t){__VA_ARGS__})
#ifndef inner_func_params_t_defined
#define inner_func_params_t_defined
typedef struct {
unsigned char normalize;
} inner_func_params_t;
#endif
double arensa_gamma_rand(void) {
double u, y, x, v;
static double a = 3;
StartOfTheLoop:do {
u = lcg_rand_norm();
y = tan(M_PI*u);
x = sqrt(2*a - 1)*y + a - 1;
if ( x <= 0 ) { goto StartOfTheLoop; }
v = lcg_rand_norm();
} while ( v > (1 + y*y)*exp( (a - 1)*log(x/(a - 1)) - sqrt(2*a - 1)*y ));
return x;
}
double arensa_gamma_rand_base(unsigned char to_normalize) {
double u, y, x, v;
static double a = 3;
do {
u = lcg_rand_norm();
y = tan(M_PI*u);
x = sqrt(2*a - 1)*y + a - 1;
if ( x <= 0 ) { continue; }
v = lcg_rand_norm();
} while ( v > (1 + y*y)*exp( (a - 1)*log(x/(a - 1)) - sqrt(2*a - 1)*y ));
return x;
}
// Function wallper
double arensa_gamma_rand_predef(inner_func_params_t in){
unsigned char normalize = in.normalize ? in.normalize : 0;
return arensa_gamma_rand_base(normalize);
}
#endif
|
1Basile/pseudorandom_number_generators
|
simga_3_normal_distribution_generator.h
|
<reponame>1Basile/pseudorandom_number_generators<gh_stars>0
#ifndef SIGMA_3_NORMAL_DISTRIBUTION_GENERATOR_IMPORTED
#define SIGMA_3_NORMAL_DISTRIBUTION_GENERATOR_IMPORTED
#include "linear_congruential_generator.h"
#include "./quadratic_congruential_generator.h"
/* #define sig_3_n_rand(...) sig_3_n_rand_predef((inner_func_params_t){__VA_ARGS__}) */
#ifndef inner_func_params_t_defined
#define inner_func_params_t_defined
typedef struct {
unsigned char normalize;
} inner_func_params_t;
#endif
double sig_3_n_rand_base(unsigned char to_normalize) {
double menian = 0;
double variance = 1;
double sum = 0;
unsigned char i;
for (i=1;i<13;i++) { sum += lcg_rand_norm(); } // Get sum of 12 random normalized values
return menian + (sum - (double)6)*variance;
}
// Function wallper
double sig_3_n_rand_predef(inner_func_params_t in){
unsigned char normalize = in.normalize ? in.normalize : 0;
return sig_3_n_rand_base(normalize);
}
double sig_3_n_rand(void) {
double menian = 0;
double variance = 1;
double sum = 0;
unsigned char i;
for (i=1;i<13;i++) { sum += lcg_rand_norm(); } // Get sum of 12 random normalized values
return menian + (sum - (double)6)*variance;
}
#endif
|
1Basile/pseudorandom_number_generators
|
fibonacci_number_generator.h
|
<reponame>1Basile/pseudorandom_number_generators
#ifndef FIBONACCI_NUMBER_GENERATOR_IMPORTED
# define FIBONACCI_NUMBER_GENERATOR_IMPORTED
// #define fib_next_num(...) fib_next_num_predef((inner_func_params_t){__VA_ARGS__})
#ifndef inner_func_params_t_defined
#define inner_func_params_t_defined
typedef struct {
unsigned char normalize;
} inner_func_params_t;
#endif
double fib_next_num_base(unsigned char to_normalize) {
static unsigned long int m = 5323;
static unsigned long int prev_step = 0;
static unsigned long int curr_step = 1;
static unsigned long int next_step;
next_step = (curr_step + prev_step) % m;
prev_step = curr_step;
curr_step = next_step;
return to_normalize == 1 ? (double)next_step / (double)m : (double)next_step;
}
double fib_next_num_norm(void) {
static unsigned long int m = 5323;
static unsigned long int prev_step = 0;
static unsigned long int curr_step = 1;
static unsigned long int next_step;
next_step = (curr_step + prev_step) % m;
prev_step = curr_step;
curr_step = next_step;
return (double)next_step / (double)m;
}
double fib_next_num(void) {
static unsigned long int m = 5323;
static unsigned long int prev_step = 0;
static unsigned long int curr_step = 1;
static unsigned long int next_step;
next_step = (curr_step + prev_step) % m;
prev_step = curr_step;
curr_step = next_step;
return (double)next_step;
}
// Function wallper
double fib_next_num_predef(inner_func_params_t in){
unsigned char normalize = in.normalize ? in.normalize : 0;
return fib_next_num_base(normalize);
}
#endif
|
1Basile/pseudorandom_number_generators
|
polar_coordinates_normal_distribution_generator.h
|
<reponame>1Basile/pseudorandom_number_generators
#ifndef POLAR_COORDINATES_NORMAL_DISTRIBUTION_GENERATOR_IMPORTED
#define POLAR_COORDINATES_NORMAL_DISTRIBUTION_GENERATOR_IMPORTED
#include "linear_congruential_generator.h"
#include <math.h>
#include <stdio.h>
// #define pol_coord_n_rand(...) pol_coord_n_rand_predef((inner_func_params_with_pointers_t){__VA_ARGS__})
#ifndef inner_func_params_with_pointers_t_defined
#define inner_func_params_with_pointers_t_defined
typedef struct {
unsigned char normalize;
double *x_1_p;
double *x_2_p;
} inner_func_params_with_pointers_t;
#endif
void pol_coord_n_rand_base(unsigned char to_normalize, double *x_1_p, double *x_2_p) {
double u_1, u_2, v_1, v_2, s;
do {
u_1 = lcg_rand_norm();
u_2 = lcg_rand_norm();
v_1 = 2*u_1 - 1;
v_2 = 2*u_2 - 1;
s = (v_1 * v_1) + (v_2 * v_2);
} while( s >= 1 );
*x_1_p = v_1 * sqrt((-2*log(s) / s));
*x_2_p = v_2 * sqrt((-2*log(s) / s));
}
void pol_coord_n_rand(double *x_1_p, double *x_2_p) {
double u_1, u_2, v_1, v_2, s;
do {
u_1 = lcg_rand_norm();
u_2 = lcg_rand_norm();
v_1 = 2*u_1 - 1;
v_2 = 2*u_2 - 1;
s = (v_1 * v_1) + (v_2 * v_2);
} while( s >= 1 );
*x_1_p = v_1 * sqrt(((-2*log(s)) / s));
*x_2_p = v_2 * sqrt(((-2*log(s)) / s));
}
// Function wallper
void pol_coord_n_rand_predef(inner_func_params_with_pointers_t in){
double x_ext;
unsigned char normalize = in.normalize ? in.normalize : 0;
double * x_2_p = in.x_2_p ? in.x_2_p : &x_ext;
double * x_1_p = in.x_1_p ? in.x_1_p : &x_ext;
pol_coord_n_rand_base(normalize, x_1_p, x_2_p);
}
#endif
|
1Basile/pseudorandom_number_generators
|
reverse_congruential_generator.h
|
<filename>reverse_congruential_generator.h
#ifndef REVERSE_CONGRUENTIAL_GENERATOR_IMPORTED
#define REVERSE_CONGRUENTIAL_GENERATOR_IMPORTED
#include "mod_inverse_alg.h"
double rcg_rand_base(unsigned char to_normalize) {
static unsigned int a = 69;
static unsigned int c = 4358;
static unsigned int p = 91193;
static unsigned int step = 1;
step = mod_inverse(step, p);
step = (a*step + c) % p;
return to_normalize == 1 ? (double)step / (double)p : (double)step;
}
/* #define rcg_rand(...) rcg_rand_predef((inner_func_params_t){__VA_ARGS__}) */
#ifndef inner_func_params_t_defined
#define inner_func_params_t_defined
typedef struct {
unsigned char normalize;
} inner_func_params_t;
#endif
// Function wallper
double rcg_rand_predef(inner_func_params_t in){
unsigned char normalize = in.normalize ? in.normalize : 0;
return rcg_rand_base(normalize);
}
double rcg_rand(void) {
static unsigned int a = 69;
static unsigned int c = 4358;
static unsigned int p = 91193;
static unsigned int step = 1;
step = mod_inverse(step, p);
step = (a*step + c) % p;
return (double)step;
}
double rcg_rand_norm(void) {
static unsigned int a = 69;
static unsigned int c = 4358;
static unsigned int p = 91193;
static unsigned int step = 1;
step = mod_inverse(step, p);
step = (a*step + c) % p;
return (double)step / (double)p;
}
#endif
|
1Basile/pseudorandom_number_generators
|
linear_congruential_generator.h
|
#ifndef LINEAR_CONGRUENTIAL_GENERATOR_IMPORTED
#define LINEAR_CONGRUENTIAL_GENERATOR_IMPORTED
double lcg_rand_base(unsigned char to_normalize) {
static unsigned long int step = 1;
static const unsigned int a = 84589;
static const unsigned int c = 45989;
static const unsigned int m = 217728;
step = (a * step + c) % m;
return to_normalize == 1 ? (double)step / (double)m : (double)step;
}
double lcg_rand(void) {
static unsigned long int step = 1;
static const unsigned int a = 84589;
static const unsigned int c = 45989;
static const unsigned int m = 217728;
step = (a * step + c) % m;
return (double)step;
}
double lcg_rand_norm(void) {
static unsigned long int step = 1;
static const unsigned int a = 84589;
static const unsigned int c = 45989;
static const unsigned int m = 217728;
step = (a * step + c) % m;
return (double)step / (double)m;
}
// #define lcg_rand(...) lcg_rand_predef((inner_func_params_t){__VA_ARGS__})
#ifndef inner_func_params_t_defined
#define inner_func_params_t_defined
typedef struct {
unsigned char normalize;
} inner_func_params_t;
#endif
// Function wallper
double lcg_rand_predef(inner_func_params_t in){
unsigned char normalize = in.normalize ? in.normalize : 0;
return lcg_rand_base(normalize);
}
#endif
|
1Basile/pseudorandom_number_generators
|
union_method_generator.h
|
#ifndef UNINON_METHOD_GENERATOR_IMPORTED
#define UNINON_METHOD_GENERATOR_IMPORTED
#include "linear_congruential_generator.h"
#include "quadratic_congruential_generator.h"
/* #define un_rand(...) un_rand_predef((inner_func_params_t){__VA_ARGS__}) */
#ifndef inner_func_params_t_defined
#define inner_func_params_t_defined
typedef struct {
unsigned char normalize;
} inner_func_params_t;
#endif
double un_rand_base(unsigned char to_normalize) {
unsigned int m = 217728; // Module from lcg_rand
unsigned int x_n = lcg_rand();
unsigned int y_n = qcg_rand();
return to_normalize == 1 ? (double)((x_n - y_n) % m) / (double)m : (double)((x_n - y_n) % m);
}
// Function wallper
double un_rand_predef(inner_func_params_t in){
unsigned char normalize = in.normalize ? in.normalize : 0;
return un_rand_base(normalize);
}
double un_rand(void) {
unsigned int m = 217728; // Module from lcg_rand
unsigned int x_n = rcg_rand();
unsigned int y_n = qcg_rand();
return (double)((x_n - y_n) % m);
}
double un_rand_norm(void) {
unsigned int m = 217728; // Module from lcg_rand
unsigned int x_n = lcg_rand();
unsigned int y_n = qcg_rand();
return (double)((x_n - y_n) % m) / (double)m;
}
#endif
|
1Basile/pseudorandom_number_generators
|
test_algorithms.c
|
#include<stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include "linear_congruential_generator.h"
#include "quadratic_congruential_generator.h"
#include "fibonacci_number_generator.h"
#include "reverse_congruential_generator.h"
#include "union_method_generator.h"
#include "simga_3_normal_distribution_generator.h"
#include "polar_coordinates_normal_distribution_generator.h"
#include "ratio_method_generator.h"
#include "log_method_for_exponential_distribution_generator.h"
#include "arensa_method_for_gamma_distribution_generator.h"
#include "ratio_method_generator.h"
void clean_window (void) {
printf("\e[1;1H\e[2J");
}
void draw_distribution_table_for(int generator_number) {
double (*generator_function) (void);
unsigned char distribution_limits = 0; // 0 - [0, 1], 1 - [-3, 3], 2 - [0, 100]
unsigned int distribution[10] = { 0 };
int number_of_tries = 90000;
switch ( generator_number )
{
case 1:
generator_function = &lcg_rand_norm;
break;
case 2:
generator_function = &qcg_rand_norm;
break;
case 3:
generator_function = &fib_next_num_norm;
break;
case 4:
generator_function = &rcg_rand_norm;
break;
case 5:
generator_function = &un_rand_norm;
break;
case 6:
generator_function = &sig_3_n_rand;
distribution_limits = 1;
break;
case 7:
distribution_limits = 1;
break;
case 8:
generator_function = &rat_rand;
distribution_limits = 1;
break;
case 9:
generator_function = &log_exp_rand;
distribution_limits = 2;
break;
case 10:
generator_function = &arensa_gamma_rand;
distribution_limits = 2;
break;
}
if ( generator_number == 7 ) {
double x_n[2];
int i, j;
for (i=1;i<=number_of_tries / 2;i++) {
pol_coord_n_rand(&x_n[0], &x_n[1]);
for (j=0;j<2;j++) {
double do_some_math = (int)((x_n[j] / 3) * 10); // a in [-10, 10]
if (do_some_math > 10) { do_some_math = 9.9; } // a in (-10, 10)
if (do_some_math < -10) { do_some_math = -9.9; } // a in (-10, 10)
do_some_math = do_some_math / 2; // a in (-5, 5)
if (do_some_math > 0) { distribution[(int)do_some_math + 5]++;}
if (do_some_math < 0) { distribution[4 + ((int)do_some_math)]++; }
}
}
}
else if ( distribution_limits == 0 ) { // a in [0, 1]
int i;
double rand_num = 0;
for (i=1;i<=number_of_tries;i++) {
rand_num = generator_function();
if (rand_num == 1) { rand_num = 0.99; }
distribution[(int)(rand_num * 10)]++;
/* printf("%d # %f | ", rand_num, (int)(rand_num * 10)); */
}
}
else if ( distribution_limits == 1 ) { // a in [-3, 3]
int i;
double rand_num;
for (i=1;i<=number_of_tries;i++) {
rand_num = generator_function();
double do_some_math = (int)((rand_num / 3) * 10); // a in [-10, 10]
if (do_some_math > 10) { do_some_math = 9.9; } // a in (-10, 10)
if (do_some_math < -10) { do_some_math = -9.9; } // a in (-10, 10)
do_some_math = do_some_math / 2; // a in (-5, 5)
if (do_some_math > 0) { distribution[(int)do_some_math + 5]++;}
if (do_some_math < 0) { distribution[4 + ((int)do_some_math)]++; }
/* printf("%d # %f | ", rand_num, (int)(rand_num * 10)); */
}
}
else if ( distribution_limits == 2 ) { // a in [0, 100]
int i;
double rand_num;
for (i=1;i<=number_of_tries;i++) {
rand_num = generator_function();
if (rand_num >= 100) { rand_num = 99; }
if (rand_num < 0) { rand_num = 0; }
distribution[(int)(rand_num / 10)]++;
/* printf("%d # %f | ", rand_num, (int)(rand_num / 10)); */
}
}
printf("\n");
switch ( distribution_limits )
{
double start_interval;
double interval_step;
int i;
case 0:
start_interval = 0;
interval_step = 0.1;
printf("%10s\t%15s\n", "Interval", "Frequency");
for (i=0;i<10;i++)
{
printf("[%- 4.1f, %- 4.1f]\t\t%.2f\n", start_interval, start_interval + interval_step, ((double)distribution[i] / (double)number_of_tries));
start_interval += interval_step;
}
break;
case 1:
start_interval = -3;
interval_step = 0.6;
printf("%10s\t%15s\n", "Interval", "Frequency");
for (i=0;i<10;i++)
{
printf("[%- 4.1f, %- 4.1f]\t\t%.2f\n", start_interval, start_interval + interval_step, ((double)distribution[i] / (double)number_of_tries));
start_interval += interval_step;
}
break;
case 2:
start_interval = 0;
interval_step = 10;
printf("%9s\t%15s\n", "Interval", "Frequency");
for (i=0;i<10;i++)
{
printf("[%- 3d, %3d]\t\t%.2f\n", (int)start_interval, (int)(start_interval + interval_step), ((double)distribution[i] / (double)number_of_tries));
start_interval += interval_step;
}
break;
}
}
short int read_input(void) {
long a;
char buf[1024]; // use 1KiB just to be sure
int success; // flag for successful conversion
do
{
if (!fgets(buf, 1024, stdin))
{
// reading input failed:
return 1;
}
// have some input, convert it to integer:
char *endptr;
errno = 0; // reset error number
a = strtol(buf, &endptr, 10);
if (errno == ERANGE)
{
success = 0;
}
else if (endptr == buf)
{
// no character was read
success = 0;
}
else if (*endptr && *endptr != '\n')
{
// *endptr is neither end of string nor newline,
// so we didn't convert the *whole* input
success = 0;
}
else if ( (a < 1) || (a > 10))
{
// number not in [1, 10]
success = 0;
}
else
{
success = 1;
}
} while (!success); // repeat until we got a valid number
return a;
}
int get_generator_num (bool to_clear) {
char greeding_text[] = "Choose pseudorandom number generator to draw distribution table for.\n";
char geenrators_to_choose[] = "linear congrurental[1] | quadratic cogurantal[2] | fibonacci number[3] | reverse congrurental[4] | union method[5]\n 3 sigma [6] | polar coordinates[7] | ratio method[8] | logarithm method [9] | Arens method [10]\n\n";
char promt[] = "Enter number from 1 to 10: ";
int generator_number;
char buf[1024]; // use 1KiB just to be sure
int success; // flag for successful conversion
do {
if ( to_clear ) { clean_window(); }
puts(greeding_text);
puts(geenrators_to_choose);
printf("%s", promt);
if (!fgets(buf, 1024, stdin))
{
// reading input failed:
}
// have some input, convert it to integer:
char *endptr;
errno = 0; // reset error number
generator_number = strtol(buf, &endptr, 10);
if (errno == ERANGE)
{
success = 0;
}
else if (endptr == buf)
{
// no character was read
success = 0;
}
else if (*endptr && *endptr != '\n')
{
// *endptr is neither end of string nor newline,
// so we didn't convert the *whole* input
success = 0;
}
else if ( (generator_number < 1) || (generator_number > 10))
{
// number not in [1, 10]
success = 0;
}
else
{
success = 1;
}
} while (!success); // repeat until we got a valid number
return generator_number;
}
int promt_to_continue_working(void)
{
char *buffer = NULL;
int read;
long unsigned int len;
puts("\nDo you want to check another algorithm?");
puts("\nPress [q]uit to exit programm or any other button to do further work.");
do {
read = getline(&buffer, &len, stdin);
} while ( strcmp(buffer, "") == 0 );
if ( strcmp(buffer, "q\n") == 0 )
{
return 0;
}
else
{
return 1;
}
}
int main(void) {
do {
clean_window();
draw_distribution_table_for(get_generator_num(true));
} while ( promt_to_continue_working() );
puts("\nProgram was made by <NAME>, student K-21.");
return 1;
}
|
1Basile/pseudorandom_number_generators
|
mod_inverse_alg.h
|
<gh_stars>0
#ifndef MOD_INVERSE_ALG_IMPORTED
#include "extended_grade_common_devider_alg.h"
#define MOD_INVERSE_ALG_IMPORTED
// Function to find modulo inverse of a
int mod_inverse(int a, int m)
{
int x, y;
int g = ext_gcd(a, m, &x, &y);
if (g != 1)
return -1; // Error: it`s impossible to find inverse value, -1 not in [0, m-1] so impossible value
else
{
// m is added to handle negative x
int res = (x%m + m) % m;
return res;
}
}
// Driver Program
/* int main(void) { */
/* int a = 3; */
/* int b = 7; */
/* printf("Mod invers of %d by %d is %d", a, b, mod_inverse(a, b)); */
/* return 0; */
/* } */
#endif
|
IT1050-2022-Feb/tutorial-01-IT21262418
|
Tute03.c
|
<reponame>IT1050-2022-Feb/tutorial-01-IT21262418<gh_stars>0
/*Exercise 3 - Repetition
Write a C program to calculate the sum of the numbers from 1 to n.
Where n is a keyboard input.
e.g.
n -> 100
sum = 1+2+3+....+ 99+100 = 5050
n -> 1-
sum = 1+2+3+...+10 = 55 */
#include <stdio.h>
int main() {
int number;
int i;
int total=0;
printf("Enter the number you want to count sum of previous numbers :");
scanf("%d",&number);
for (i=1;i<=number;i++)
{
total = total+i;
}
printf("sum :%d",total);
return 0;
}
|
TuoniTuoni/git_notes
|
hello.c
|
<gh_stars>0
print('nihao')
return
return
return
return
return
|
zbigg/sandbox
|
task_queue.h
|
<gh_stars>0
#ifndef simple_async_engine_h_included
#define simple_async_engine_h_included
#include <queue>
///
/// Simple async engine
///
/// Single threaded async engine that queues
/// callbacks and calls them in order from main loop.
///
class task_queue {
//
// async impl
//
std::queue<std::function<void()>> queue;
// std::mutex async_mutex;
// std::condition_variable async_cond;
public:
task_queue()
{
}
~task_queue()
{
}
void execute_tasks()
{
while( true ) {
std::function<void()> next;
// std::lock_guard<std::mutex> lock(async_mutex);
// {
if( queue.empty() ) {
return;
}
std::swap(queue.front(), next);
queue.pop();
// }
// DOUT("async::call");
next();
}
// DOUT("async_quit");
}
/*
template <typename T, typename F>
future<T> async_future(F fun) {
future<T> f;
// DOUT("async::push future");
// std::lock_guard<std::mutex> lock(async_mutex);
queue.push([=]() {
try {
f.consume( fun() );
} catch( ... ) {
// TBD, f.set_exception not implemented
std::cerr << "async: exception_caught, not propagatinh, abortinh aaaa\n";
throw;
}
});
return f;
};
*/
bool empty() const {
return this->queue.empty();
}
template <typename Fun, typename... Args>
void push(Fun f, Args&&... args) {
// DOUT("async::push");
// std::lock_guard<std::mutex> lock(async_mutex);
this->queue.push([=]() {
f(std::forward<Args&&...>(args)...);
});
};
template <typename Fun, typename... Args>
void operator()(Fun f, Args&&... args) {
this->push(f, std::forward<Args&&...>(args)...);
}
};
#endif // simple_async_engine_h_included
|
zbigg/sandbox
|
lazy_byte_consumer.h
|
<gh_stars>0
//
// Copyright (C) 2008 <NAME> <<EMAIL>>,
// licensed to the public under the terms of the GNU GPL (>= 2)
// see the file COPYING for details
// I.e., do what you like, but keep copyright and there's NO WARRANTY.
//
#ifndef tinfra_lazy_byte_consumer_h_included__
#define tinfra_lazy_byte_consumer_h_included__
#include "interruptible.h"
#include <tinfra/tstring.h>
#include "tinfra/trace.h"
#include <stdexcept>
#include <string>
namespace tinfra {
template <typename IMPL>
class lazy_byte_consumer: public interruptible<IMPL, int, tstring> {
typedef typename interruptible<IMPL,int,tstring>::step_method step_method;
public:
lazy_byte_consumer(IMPL& i, step_method s = 0):
interruptible<IMPL,int,tstring>(i,s),
last_found_pos_(0),
waiting_for_(NOTHING)
{}
void wait_for_anything(step_method method) {
waiting_for_ = ANYTHING;
this->next(method);
}
void wait_for_bytes(size_t count, step_method method);
void wait_for_delimiter(tstring const& delim, step_method method);
size_t last_found_pos() const { return last_found_pos_ };
protected:
int call(step_method m, tstring const& input);
private:
size_t waiter_count_;
std::string waiter_delim_;
size_t last_found_pos_;
enum wait_type {
NOTHING,
ANYTHING,
COUNT,
DELIMITER,
} waiting_for_;
int maybe_have_delim(tstring const& input);
int maybe_have_enough_bytes(tstring const& input);
};
template <typename IMPL>
int lazy_byte_consumer<IMPL>::call(step_method m, tstring const& input)
{
switch( waiting_for_ ) {
case NOTHING:
//TINFRA_TRACE_VAR(input);
throw std::logic_error("lazy_byte_consumer doesn't expect input now");
case ANYTHING:
break;
case COUNT:
if( input.size() < waiter_count_ ) {
this->again();
return 0;
}
break;
case DELIMITER:
{
size_t pos = input.find(waiter_delim_);
if( pos == tstring::npos ) {
this->again();
return 0;
}
this->last_found_pos_ = pos;
}
break;
}
waiting_for_ = NOTHING;
//TINFRA_TRACE_VAR(input);
return interruptible<IMPL, int, tstring>::call(m, input);
}
template<typename IMPL>
void lazy_byte_consumer<IMPL>::wait_for_bytes(size_t count, step_method method)
{
waiting_for_ = COUNT;
waiter_count_ = count;
this->next(method);
}
template<typename IMPL>
void lazy_byte_consumer<IMPL>::wait_for_delimiter(tstring const& delim, step_method method)
{
waiting_for_ = DELIMITER;
waiter_delim_.assign(delim.data(), delim.size());
this->next(method);
}
} // end namespace tinfra
#endif // tinfra_lazy_byte_consumer_h_included__
// jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++
|
zbigg/sandbox
|
tarray.h
|
<reponame>zbigg/sandbox
#ifndef tinfra_tarray_h_included
#define tinfra_tarray_h_included
#include <stdexcept> // for std::out_of_range
namespace tinfra {
/** Array view - an non-owning STL compatible object array
Access modeled after std::vector and std::array.
Limited to "access" only methods.
Doesn't own and/or release underlying storage.
*/
template <typename T>
class tarray {
private:
T* begin_;
T* end_;
public:
typedef T value_type;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T& reference;
typedef T const & const_reference;
typedef T* pointer;
typedef T const* const_pointer;
typedef T* iterator;
typedef T const* const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
tarray(pointer begin, pointer end)
begin_(begin),
end_(end)
{
}
tarray(pointer begin, size_t size)
begin_(begin),
end_(begin + size)
{
}
//
// iterators
//
iterator begin() { return begin_; }
const_iterator begin() const { return begin_; }
const_iterator cbegin() const { return begin_; }
iterator end() { return end_; }
const_iterator end() const { return end_; }
const_iterator cend() const { return end_; }
reverse_iterator rbegin() { return reverse_iterator(end()) };
const_reverse_iterator crbegin() { return const_reverse_iterator(end()) };
reverse_iterator rend() { return reverse_iterator(begin()) };
const_reverse_iterator crend() { return const_reverse_iterator(begin()) };
//
// capacity
//
size_type size() const { return end_ - begin_; }
size_type max_size() const { return size(); }
size_type capacity() const { return size(); }
size_type empty() const { return begin_ != end_; }
//
// element access
//
reference operator[](size_t idx) { return begin_[idx]; }
const_reference operator[](size_t idx) const { return begin_[idx]; }
reference at(size_t idx);
const_reference at(size_t idx) const;
reference front() { return *begin_ }
const_reference front() const { return *begin_ }
reference back() { return *(end-1) }
const_reference back() const { return *(end-1) }
value_type* data() { return begin_ }
const value_type* data() const { return begin_ }
};
//
// inline (template) implementation
//
template <typename T>
tarray<T>::reference tarray::at(size_t idx) {
if( idx >= size() {
throw std::out_of_range("tarray::at index out of range");
}
return begin_[idx];
}
template <typename T>
tarray<T>::const_reference tarray::at(size_t idx) const {
if( idx >= size() {
throw std::out_of_range("tarray::at index out of range");
}
return begin_[idx];
}
} // end namespace tinfra
#endif // tinfra_tarray_h_included
|
zbigg/sandbox
|
atomic_transaction.h
|
<reponame>zbigg/sandbox
template <typename T, typename Rest...>
class atomic_transaction: public atomic_transaction<Rest...> {
private:
T* rv;
T copy;
atomic_transaction(T& v, Rest... args):
atomic_transaction(Rest...),
rv(v),
copy(
{
}
};
|
zbigg/sandbox
|
interruptible.h
|
//
// Copyright (C) 2008 <NAME> <<EMAIL>>,
// licensed to the public under the terms of the GNU GPL (>= 2)
// see the file COPYING for details
// I.e., do what you like, but keep copyright and there's NO WARRANTY.
//
#ifndef tinfra_interruptible_h_included__
#define tinfra_interruptible_h_included__
#include <stdexcept>
namespace tinfra {
template<typename IMPL, typename R, typename T>
class interruptible {
public:
typedef R (IMPL::*step_method)(T const& e);
interruptible(IMPL& impl, step_method m = 0):
implementation_(impl),
next_method_(m),
again_(false),
finished_(false)
{
}
virtual ~interruptible() {}
R process(T const& input)
{
if( finished_ ) {
throw std::logic_error("already finished");
}
step_method current_method = next_method_;
next_method_ = 0;
again_ = false;
R output = call(current_method, input);
if( again_ ) {
next_method_ = current_method;
} else if( !next_method_ ) {
finished_ = true;
}
return output;
}
bool is_finished() const {
return finished_;
}
void next(step_method s) {
next_method_ = s;
}
void again() {
again_ = true;
}
void finish() {
// nothing needed
}
protected:
virtual R call(step_method m, T const& a)
{
return (implementation_.*m)(a);
}
private:
IMPL& implementation_;
step_method next_method_;
bool again_;
bool finished_;
};
} // end namespace tinfra
#endif // tinfra_interruptible_h_included__
// jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.