diff --git a/.gitattributes b/.gitattributes index db0a8091b13a8fc7b8b461381c617c48f5e835ef..4977155bee983851b7e1a83c93f934a7f397e3d1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -5072,3 +5072,57 @@ dotnet/sdk/9.0.313/DotnetTools/dotnet-format/tr/Microsoft.CodeAnalysis.VisualBas dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hans/Microsoft.CodeAnalysis.CSharp.resources.dll filter=lfs diff=lfs merge=lfs -text dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hans/Microsoft.CodeAnalysis.Features.resources.dll filter=lfs diff=lfs merge=lfs -text dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hans/Microsoft.CodeAnalysis.VisualBasic.resources.dll filter=lfs diff=lfs merge=lfs -text +dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll filter=lfs diff=lfs merge=lfs -text +dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hant/Microsoft.CodeAnalysis.Features.resources.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AnalysisData.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AppLib.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AppLibInterfaces.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/arrow.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Assert.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_filesystem-vc141-mt-x64-1_78.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_iostreams-vc141-mt-x64-1_78.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_locale-vc141-mt-x64-1_78.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_program_options-vc141-mt-x64-1_78.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_python310-vc141-mt-x64-1_78.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_regex-vc141-mt-x64-1_78.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_serialization-vc141-mt-x64-1_78.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CommonProtoServices.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Core.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CrashReporter.exe filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CudaDrvApiWrapper.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/DeviceProperty.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/DevicePropertyProto.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ETWEventsHandlers.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/EventSource.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/EventsView.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/exporter.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GenericHierarchy.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GpuInfo.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GpuTraits.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ImportNvtxt.exe filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InjectionCommunicator.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceData.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceShared.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceSharedBase.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceSharedCore.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/libcrypto-3-x64.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/libssl-3-x64.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/msdia140.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/nsys-ui.exe filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NVIDIA_SLA.pdf filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NvQtGui.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/nvsym.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NvtxExtData.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/opengl32sw.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/parquet.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProcessLauncher.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/protobuf-shared.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufComm.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufCommClient.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufCommProto.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/QdstrmImporter.exe filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Charts.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Core.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Designer.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6DesignerComponents.dll filter=lfs diff=lfs merge=lfs -text +cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Gui.dll filter=lfs diff=lfs merge=lfs -text diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AnalysisData.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AnalysisData.dll new file mode 100644 index 0000000000000000000000000000000000000000..b4a3732fee1d541a4cbb827cd2143222d2479b55 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AnalysisData.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:488b896eb6b0df115f3be0d543b54a3be3f2b2fb4aa87b85eabcb25c132ce2ea +size 4872800 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AppLib.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AppLib.dll new file mode 100644 index 0000000000000000000000000000000000000000..23fe002f4d84d633b93fd74ae6b3abb334254218 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AppLib.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6add84b04353b8c4e25bf1c32ac2e4fb195f23430670834869129cc820d1fd98 +size 1750624 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AppLibInterfaces.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AppLibInterfaces.dll new file mode 100644 index 0000000000000000000000000000000000000000..7fcb17d5f2f14d7c0070c503aafb1cb67b199379 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/AppLibInterfaces.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b53da85d61aef5f5ca00ce77f5c23b08553451f228ac3bf54536aaa2d451867c +size 132704 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Assert.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Assert.dll new file mode 100644 index 0000000000000000000000000000000000000000..2f9e397f59233a83ef31963273f680d859d4c396 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Assert.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:714f9546287b5cf39f9faf4d5f452ae617a1150e2e6e63569885d46239a10bad +size 214608 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CommonProtoServices.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CommonProtoServices.dll new file mode 100644 index 0000000000000000000000000000000000000000..94b7663a242ecd99f528c11f49ef389357ee053c --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CommonProtoServices.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3e1f2ab76e1d984de0cf513bccde2ed7d3c2fdbc049664610b0a21ad1681580 +size 3234368 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Core.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Core.dll new file mode 100644 index 0000000000000000000000000000000000000000..3969b39a76828ececc8196fe96895089c9a898db --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Core.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b91d28a789d080370e03b494e70abf7a66cfe6df118d6c7336e8dc87396f833 +size 766008 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CrashReporter.exe b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CrashReporter.exe new file mode 100644 index 0000000000000000000000000000000000000000..ac5814bfec1924d954fc6e50aa635488431d0503 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CrashReporter.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:634383e9ed76e9513ba58fb2a2dbeb246bc95c219c689dcadb224062de022d33 +size 1123944 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CudaDrvApiWrapper.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CudaDrvApiWrapper.dll new file mode 100644 index 0000000000000000000000000000000000000000..22d4cd561b0fe18912b1dff1751f67a6d91d4b04 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/CudaDrvApiWrapper.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52879785c6226079fe36e66d85605a03d0dd8932d9f8071f60f1f1fb16610938 +size 256088 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/DeviceProperty.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/DeviceProperty.dll new file mode 100644 index 0000000000000000000000000000000000000000..0b54aa465c887c5b56a2f1a3095ea2d46912aac7 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/DeviceProperty.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4785e669f088dd734094d9001f38eb74dbe358131fd993deba75d4133a09d6f0 +size 156264 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/DevicePropertyProto.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/DevicePropertyProto.dll new file mode 100644 index 0000000000000000000000000000000000000000..f5b7fac02b230c79d8bb605552c71746b14afc7b --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/DevicePropertyProto.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:debf9098d729b7c4f388f14136fc78431feaff6274e5d0dc54b6738be7190a98 +size 129640 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ETWEventsHandlers.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ETWEventsHandlers.dll new file mode 100644 index 0000000000000000000000000000000000000000..6df7809295828842403b14da30f5e79bf988f202 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ETWEventsHandlers.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7be665503a9aca59d4ef616665ec06abb526069cae8b871167eefddfd2061082 +size 1143896 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/EventSource.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/EventSource.dll new file mode 100644 index 0000000000000000000000000000000000000000..ae44f6c138d637947f862d55e1bef13b0a20dfa2 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/EventSource.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2764e4a559d6c801787ff764e26e959020c1a838d5efe2eea974b7cd125bbfc2 +size 113240 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/EventsView.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/EventsView.dll new file mode 100644 index 0000000000000000000000000000000000000000..119d5aec994427f0f7a92abf4194d40626062ede --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/EventsView.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:953a59403aa74ffa91ce9f3513208ad8cb1c351c553acecaf73b793308239766 +size 314952 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GenericHierarchy.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GenericHierarchy.dll new file mode 100644 index 0000000000000000000000000000000000000000..7e7df20bc7d40d5ebcaa2074045dde965c65fc3e --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GenericHierarchy.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:287c13eaa0bc077637d84d0f33115e7f205c3d29cd804c4034728be1f8e4c6ba +size 1029224 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GpuInfo.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GpuInfo.dll new file mode 100644 index 0000000000000000000000000000000000000000..5f5fd934103e17e2ff247770f6734fb6b12943e1 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GpuInfo.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5fb7c6a44217d7c4a8d70491e89ffa8a53e1a4d7836ff4736e3a9e84bc23a9aa +size 783440 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GpuTraits.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GpuTraits.dll new file mode 100644 index 0000000000000000000000000000000000000000..0236a7df0ff86d0b300b36827534101eab6814ce --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/GpuTraits.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0c24ef94e60424d76f80bd7cd54a63f58430d1a73532ae6e7be62f2238b185c +size 195152 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ImportNvtxt.exe b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ImportNvtxt.exe new file mode 100644 index 0000000000000000000000000000000000000000..b91d01d8ce0de8fb12ee12d401e3c5e9307cfa57 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ImportNvtxt.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:543015e8d2de03a92d7cb226fe5c507916217a51af2f6bc318c4de367b40960a +size 412760 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InjectionCommunicator.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InjectionCommunicator.dll new file mode 100644 index 0000000000000000000000000000000000000000..582ac6e4ecd5890c9107d9ad5eb4763fb991f74f --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InjectionCommunicator.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84ac41c17f6114d7416dc81e729f34e7d521cc57ba9cffdc71d5906aee3fbd02 +size 297064 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceData.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceData.dll new file mode 100644 index 0000000000000000000000000000000000000000..55dbc766f2f0c99b94fcbef549c0dc5a78e42f38 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceData.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:948cb29db7f6d54d0c5b273e06c815fc356e97fb7e07071566d6a4a1a61014e6 +size 767560 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceShared.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceShared.dll new file mode 100644 index 0000000000000000000000000000000000000000..1d9fb46df3c14f2372eab789a8fef27452758439 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceShared.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86f06db0548eefc2aaf6eee412bef9f008d6d773bc2c81c0008f0d2dd7a48f93 +size 452680 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceSharedBase.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceSharedBase.dll new file mode 100644 index 0000000000000000000000000000000000000000..88314e0f8a503d3567aad67ebcdbd25e5e7afa35 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceSharedBase.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3024fecb4760962a55cb6d8c251c24a19a4bccfa94c6f8f607faf1768016b9dc +size 118344 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceSharedCore.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceSharedCore.dll new file mode 100644 index 0000000000000000000000000000000000000000..aa297889de50dfd6ad5be6766e8f58fca810088c --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/InterfaceSharedCore.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b6ca9a293db82e9bae6e3ffe43621beb8008a811598f1f0bf3adcd82c31b982 +size 113224 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NVIDIA_SLA.pdf b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NVIDIA_SLA.pdf new file mode 100644 index 0000000000000000000000000000000000000000..a65b98b4b05507eb0728a4b02ea0efa59b808e15 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NVIDIA_SLA.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:131226d6828e02298a81146a640682789732e724b5dbc98877699fc0c398d031 +size 384767 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NvQtGui.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NvQtGui.dll new file mode 100644 index 0000000000000000000000000000000000000000..43cc83ccffe24a67d5c299bf9ef0b2030d40ec9c --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NvQtGui.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e60cae34f718a4044aa491a405603d97d24aab319079a8b89e6e98bbb66ed90 +size 9471032 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NvtxExtData.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NvtxExtData.dll new file mode 100644 index 0000000000000000000000000000000000000000..3ef8443b8a263a0c6a284a28294617b867fb2826 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/NvtxExtData.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65135b973a97fd7fd39258ac7fd74d96c800d9fa9a70bf37034adc1d7cfb47f7 +size 290360 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProcessLauncher.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProcessLauncher.dll new file mode 100644 index 0000000000000000000000000000000000000000..d4626bdfeefb300f596fab2e45ccc8f02cf10e13 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProcessLauncher.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03ac85b043acca9e98f935dd7160ff3caa9ed3a29ee677022b01d8ea4c3def74 +size 518240 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufComm.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufComm.dll new file mode 100644 index 0000000000000000000000000000000000000000..9e378b44cc9e04d99a0e72c229cfda3c788e1861 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufComm.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2a0c88ee8eac3701b3ba7c3cf45d9082ec114c46879556b1dda53bc63b21abe +size 443456 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufCommClient.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufCommClient.dll new file mode 100644 index 0000000000000000000000000000000000000000..36dfa60d453963b1958039cfae87644a273b956a --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufCommClient.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a17c9f08360fb0c0c0784e2dd0f219ef7d7c6ecb9a1ab6d56b2052a73c37c059 +size 313408 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufCommProto.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufCommProto.dll new file mode 100644 index 0000000000000000000000000000000000000000..da0592d85342ee4b55ec2ed6b0fb9bc259bf04e6 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/ProtobufCommProto.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54a2ef52788129683cd483c3ce3db08689e95e0c774e5b64ff5766b9057b68e6 +size 106048 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/QdstrmImporter.exe b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/QdstrmImporter.exe new file mode 100644 index 0000000000000000000000000000000000000000..3a802af4face9bcd55e3ee94e691319e95dbdc15 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/QdstrmImporter.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b3e8082d7607660d379e2a3a797f69590e1568c1999d35e4308c2e9663d1494 +size 195656 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Charts.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Charts.dll new file mode 100644 index 0000000000000000000000000000000000000000..d8cc794ee3225b9f945b2f79ebe365389f2ab08d --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Charts.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a7b4fbbe6b665ceeceffd3879b55774b8e97e93f6fe8e7459ffbfde22e82128 +size 1669264 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Core.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Core.dll new file mode 100644 index 0000000000000000000000000000000000000000..b1e45d00c4847385d6c6ef8ae0a4589de2cc12e4 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Core.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:697026ff2b482df169794bd7b17a41fb47d87a518730588c668045e1f21a53da +size 5793424 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Designer.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Designer.dll new file mode 100644 index 0000000000000000000000000000000000000000..f5e4c974cc29103b3fd86212e203f06876be5034 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Designer.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5bbb6bd6b632800ecaf795a300f9ef22c3c294bb154009ba04147da220000860 +size 5075088 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6DesignerComponents.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6DesignerComponents.dll new file mode 100644 index 0000000000000000000000000000000000000000..cfabd534d6ef2e9ed0fbecbf473d7a891459128b --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6DesignerComponents.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d347004be6c96f290c408bbd91031da55916614a5c95674ecd14f5f4f8fba1ca +size 2342544 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Gui.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Gui.dll new file mode 100644 index 0000000000000000000000000000000000000000..1b90c6203fe267c87775f9b3c9b65242b0c000fd --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/Qt6Gui.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b56854670882cbf1423929ffe64f22357ce2414ecfe8a6bf041efa8a2408bd1 +size 8071824 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/arrow.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/arrow.dll new file mode 100644 index 0000000000000000000000000000000000000000..ed7b5501eb852295f9e6d60577fcff487992ac20 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/arrow.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3d208d5b76258264c4c22b259bbdf7f23e6f32aad5dba6901d15b95a85aabdb +size 8399936 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_filesystem-vc141-mt-x64-1_78.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_filesystem-vc141-mt-x64-1_78.dll new file mode 100644 index 0000000000000000000000000000000000000000..ec771d4a37b628eca51134e2892101cb0068a7e8 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_filesystem-vc141-mt-x64-1_78.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c752511c643b3d493442bc6e3c019d724c4d0057875153253d141946e1b3efa +size 142416 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_iostreams-vc141-mt-x64-1_78.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_iostreams-vc141-mt-x64-1_78.dll new file mode 100644 index 0000000000000000000000000000000000000000..1f96029d71309b0301ee6a93b70a26af4dadbe16 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_iostreams-vc141-mt-x64-1_78.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8abdb3d4b8338d3ad836a7a03970d68c9348ef0b4a6376bf0f20167bea85afc5 +size 119376 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_locale-vc141-mt-x64-1_78.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_locale-vc141-mt-x64-1_78.dll new file mode 100644 index 0000000000000000000000000000000000000000..104d9a6a2ff4b60d4f3cca4536db8dac3ae20439 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_locale-vc141-mt-x64-1_78.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ddfada5a89d58f1b56a88dd05733ca2686c5d73e5819d93cd33356de6c109e2d +size 485968 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_program_options-vc141-mt-x64-1_78.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_program_options-vc141-mt-x64-1_78.dll new file mode 100644 index 0000000000000000000000000000000000000000..520518449c010c9c024105fa809c09869506d13e --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_program_options-vc141-mt-x64-1_78.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe9eef198b16a0cc0a89c28bfe77e1fc18690191f5f3560f77d0b4afdeb3b5b7 +size 362576 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_python310-vc141-mt-x64-1_78.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_python310-vc141-mt-x64-1_78.dll new file mode 100644 index 0000000000000000000000000000000000000000..cc73a195f397f93ac0e4e603309094cd9efc6dfc --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_python310-vc141-mt-x64-1_78.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4bb25f68a0643260b66abc7effa49ef160d481155042e2fc23d860025c5790d0 +size 203344 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_regex-vc141-mt-x64-1_78.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_regex-vc141-mt-x64-1_78.dll new file mode 100644 index 0000000000000000000000000000000000000000..4f45853841b7f00568d1f64bbec20885309d0288 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_regex-vc141-mt-x64-1_78.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4642184ca20e0e3863a222ad5fbf5063506f067671b735611bec135f59d7d2f0 +size 245328 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_serialization-vc141-mt-x64-1_78.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_serialization-vc141-mt-x64-1_78.dll new file mode 100644 index 0000000000000000000000000000000000000000..3a4cb8582ef42b66daac2a1cc3d1a6d454e0d91d --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/boost_serialization-vc141-mt-x64-1_78.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2414051bb2ae2c29d3737ac0a5e0f0634c534b86178075b510b52f10514935c +size 219216 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/exporter.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/exporter.dll new file mode 100644 index 0000000000000000000000000000000000000000..a29471c14693f7c62c38181d5a8f0fedc72bb5d1 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/exporter.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77b07c14dbe07d2ef2abe9f75ef3d2a0d68a1a873db63283aae97449ac2bf96d +size 17138248 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/libcrypto-3-x64.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/libcrypto-3-x64.dll new file mode 100644 index 0000000000000000000000000000000000000000..015f59527fa38ceee715566b04aad79fba0a04c4 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/libcrypto-3-x64.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e4a4753becbd5cbc1fe3d18ecce0bfc525a942e7efcffaf4955ebb27e29b440 +size 4566600 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/libssl-3-x64.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/libssl-3-x64.dll new file mode 100644 index 0000000000000000000000000000000000000000..3ae5b70c5c2f445167a39eaf1b68c7d5d9d87461 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/libssl-3-x64.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf420ffddc7fec79d9b6fcc04c207e5a9761419b33b11e6eff44dfaeb9831154 +size 785968 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/msdia140.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/msdia140.dll new file mode 100644 index 0000000000000000000000000000000000000000..771f9680a60561bf80129ab07ae70a52f6dd2f7b --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/msdia140.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba67e8b5f387843191ace001ce2ca2ab279458be5e5967e964af2ae62eaaadca +size 1870736 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/nsys-ui.exe b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/nsys-ui.exe new file mode 100644 index 0000000000000000000000000000000000000000..999cbe18a72a0290c1b1fd6ec6af1365f2c8b0ec --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/nsys-ui.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d564835270a4bbe6e96791395ef87bb9b7b7df5d8a72ab067263734c35a4eeb +size 606808 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/nvsym.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/nvsym.dll new file mode 100644 index 0000000000000000000000000000000000000000..f4889498ae09ac3848c55ab9eb591e282dae8728 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/nvsym.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4efa6c6046b74c1d17b60fbd44a643923b4fd516f7995807e491387ce62b09ce +size 3770936 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/opengl32sw.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/opengl32sw.dll new file mode 100644 index 0000000000000000000000000000000000000000..b5c33713f2b9fe770f7fcbd4bd6cfe958dbf9315 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/opengl32sw.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30b1217821b51c26f9b4a13c81fc554c1a9732c6078fdb92aa366c13fd6be798 +size 33130568 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/parquet.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/parquet.dll new file mode 100644 index 0000000000000000000000000000000000000000..1f8b23ef334cfb54231c3eed592bfe22d54edd3e --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/parquet.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc6fabac0f808c3ab94e49a18e3dd9620286100113f1eecd17a41cbeed2c862f +size 1736784 diff --git a/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/protobuf-shared.dll b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/protobuf-shared.dll new file mode 100644 index 0000000000000000000000000000000000000000..e383f23b22dfcd1068b6e9edcabfdec3ad2bf788 --- /dev/null +++ b/cuda_toolkit/nsight-systems/nsight-systems/2023.4.4/host-windows-x64/protobuf-shared.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a72257e335eafe77edcf3272b5745e399dfc5cdd36d973628bb34266767f3601 +size 2529856 diff --git a/dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll b/dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll new file mode 100644 index 0000000000000000000000000000000000000000..91a9180bd9807cbc4f73633221929c8ca35d7f59 --- /dev/null +++ b/dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hant/Microsoft.CodeAnalysis.CSharp.resources.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ef3176b3ac2890298baaba67f2a895673cf790f0faf21ce30048723a911a092 +size 401160 diff --git a/dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hant/Microsoft.CodeAnalysis.Features.resources.dll b/dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hant/Microsoft.CodeAnalysis.Features.resources.dll new file mode 100644 index 0000000000000000000000000000000000000000..eedaaff574bdc71f48f6ce0bc2beb9a8e243a12e --- /dev/null +++ b/dotnet/sdk/9.0.313/DotnetTools/dotnet-format/zh-Hant/Microsoft.CodeAnalysis.Features.resources.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69bf7830474fa21ac0b36159e1f2276627a108ca4d24ae9db679567bba552208 +size 176952 diff --git a/git/usr/share/perl5/core_perl/Test2/Manual.pm b/git/usr/share/perl5/core_perl/Test2/Manual.pm new file mode 100644 index 0000000000000000000000000000000000000000..9a7cf8b219f55da3c43560e1ffda617bc5ecd911 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Test2/Manual.pm @@ -0,0 +1,80 @@ +package Test2::Manual; +use strict; +use warnings; + +our $VERSION = '1.302210'; + +1; + +__END__ + +=head1 NAME + +Test2::Manual - Documentation hub for Test2 and Test2-Suite. + +=head1 DESCRIPTION + +This is the hub for L and L documentation. + +=head1 WRITING TESTS + +The L POD is the hub for documentation related to +writing tests. + +=head1 WRITING TOOLS + +The L POD is the hub for documentation related to +writing new tools. + +=head1 GUTS AND INNER WORKINGS + +The L POD is the hub for documentation of the inner +workings of Test2 components. + +=head1 A NOTE ON CONCURRENCY (SUPPORT FOR FORKING AND THREADING) + +The L POD documents the concurrency support policy +for L. + +=head1 CONTRIBUTING + +The L POD is for people who want to contribute to +L or L directly. + +=head1 SEE ALSO + +L - Test2 itself. + +L - Initial tools built using L. + +=head1 SOURCE + +The source code repository for Test2-Manual can be found at +F. + +=head1 MAINTAINERS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 AUTHORS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 COPYRIGHT + +Copyright Chad Granum Eexodist@cpan.orgE. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + +See F + +=cut diff --git a/git/usr/share/perl5/core_perl/Test2/Mock.pm b/git/usr/share/perl5/core_perl/Test2/Mock.pm new file mode 100644 index 0000000000000000000000000000000000000000..44a132b3bd5046e612ac470c49cfdd8e0377bf2e --- /dev/null +++ b/git/usr/share/perl5/core_perl/Test2/Mock.pm @@ -0,0 +1,907 @@ +package Test2::Mock; +use strict; +use warnings; + +our $VERSION = '1.302210'; + +use Carp qw/croak confess/; +our @CARP_NOT = (__PACKAGE__); + +use Scalar::Util qw/weaken reftype blessed set_prototype/; +use Test2::Util qw/pkg_to_file/; +use Test2::Util::Stash qw/parse_symbol slot_to_sig get_symbol get_stash purge_symbol/; +use Test2::Util::Sub qw/gen_accessor gen_reader gen_writer/; + +sub new; # Prevent hashbase from giving us 'new'; +use Test2::Util::HashBase qw/class parent child _purge_on_destroy _blocked_load _symbols _track sub_tracking call_tracking/; + +sub new { + my $class = shift; + + croak "Called new() on a blessed instance, did you mean to call \$control->class->new()?" + if blessed($class); + + my $self = bless({}, $class); + + $self->{+SUB_TRACKING} ||= {}; + $self->{+CALL_TRACKING} ||= []; + + my @sets; + while (my $arg = shift @_) { + my $val = shift @_; + + if ($class->can(uc($arg))) { + $self->{$arg} = $val; + next; + } + + push @sets => [$arg, $val]; + } + + croak "The 'class' field is required" + unless $self->{+CLASS}; + + for my $set (@sets) { + my ($meth, $val) = @$set; + my $type = reftype($val); + + confess "'$meth' is not a valid constructor argument for $class" + unless $self->can($meth); + + if (!$type) { + $self->$meth($val); + } + elsif($type eq 'HASH') { + $self->$meth(%$val); + } + elsif($type eq 'ARRAY') { + $self->$meth(@$val); + } + else { + croak "'$val' is not a valid argument for '$meth'" + } + } + + return $self; +} + +sub _check { + return unless $_[0]->{+CHILD}; + croak "There is an active child controller, cannot proceed"; +} + +sub purge_on_destroy { + my $self = shift; + ($self->{+_PURGE_ON_DESTROY}) = @_ if @_; + return $self->{+_PURGE_ON_DESTROY}; +} + +sub stash { + my $self = shift; + get_stash($self->{+CLASS}); +} + +sub file { + my $self = shift; + my $file = $self->class; + return pkg_to_file($self->class); +} + +sub block_load { + my $self = shift; + $self->_check(); + + my $file = $self->file; + + croak "Cannot block the loading of module '" . $self->class . "', already loaded in file $INC{$file}" + if $INC{$file}; + + $INC{$file} = __FILE__; + + $self->{+_BLOCKED_LOAD} = 1; +} + +my %NEW = ( + hash => sub { + my ($class, %params) = @_; + return bless \%params, $class; + }, + array => sub { + my ($class, @params) = @_; + return bless \@params, $class; + }, + ref => sub { + my ($class, $params) = @_; + return bless $params, $class; + }, + ref_copy => sub { + my ($class, $params) = @_; + my $type = reftype($params); + + return bless {%$params}, $class + if $type eq 'HASH'; + + return bless [@$params], $class + if $type eq 'ARRAY'; + + croak "Not sure how to construct an '$class' from '$params'"; + }, +); + +sub override_constructor { + my $self = shift; + my ($name, $type) = @_; + $self->_check(); + + my $sub = $NEW{$type} + || croak "'$type' is not a known constructor type"; + + $self->override($name => $sub); +} + +sub add_constructor { + my $self = shift; + my ($name, $type) = @_; + $self->_check(); + + my $sub = $NEW{$type} + || croak "'$type' is not a known constructor type"; + + $self->add($name => $sub); +} + +sub autoload { + my $self = shift; + $self->_check(); + my $class = $self->class; + my $stash = $self->stash; + + croak "Class '$class' already has an AUTOLOAD" + if $stash->{AUTOLOAD} && *{$stash->{AUTOLOAD}}{CODE}; + croak "Class '$class' already has an can" + if $stash->{can} && *{$stash->{can}}{CODE}; + + # Weaken this reference so that AUTOLOAD does not prevent its own + # destruction. + weaken(my $c = $self); + + my ($file, $line) = (__FILE__, __LINE__ + 3); + my $autoload = eval <{\$name}) = \@_ if \@_; + return \$self->{\$name}; + }; + + \$c->add(\$name => \$sub); + + if (\$c->{_track}) { + my \$call = {sub_name => \$name, sub_ref => \$sub, args => [\@_]}; + push \@{\$c->{sub_tracking}->{\$name}} => \$call; + push \@{\$c->{call_tracking}} => \$call; + } + + goto &\$sub; + } +EOT + + $line = __LINE__ + 3; + my $can = eval <SUPER::can(\$meth)) { + return \$self->SUPER::can(\$meth); + } + elsif (ref \$self && reftype \$self eq 'HASH' && exists \$self->{\$meth}) { + return sub { shift->\$meth(\@_) }; + } + return undef; + } +EOT + + { + local $self->{+_TRACK} = 0; + $self->add(AUTOLOAD => $autoload); + $self->add(can => $can); + } +} + +sub before { + my $self = shift; + my ($name, $sub) = @_; + $self->_check(); + my $orig = $self->current($name, required => 1); + $self->_inject({}, $name => set_prototype(sub { $sub->(@_); $orig->(@_) }, prototype $sub)); +} + +sub after { + my $self = shift; + my ($name, $sub) = @_; + $self->_check(); + my $orig = $self->current($name, required => 1); + $self->_inject( + {}, + $name => set_prototype( + sub { + my @out; + + my $want = wantarray; + + if ($want) { + @out = $orig->(@_); + } + elsif (defined $want) { + $out[0] = $orig->(@_); + } + else { + $orig->(@_); + } + + $sub->(@_); + + return @out if $want; + return $out[0] if defined $want; + return; + }, + prototype $sub, + ) + ); +} + +sub around { + my $self = shift; + my ($name, $sub) = @_; + $self->_check(); + my $orig = $self->current($name, required => 1); + $self->_inject({}, $name => set_prototype(sub { $sub->($orig, @_) }, prototype $sub)); +} + +sub add { + my $self = shift; + $self->_check(); + $self->_inject({add => 1}, @_); +} + +sub override { + my $self = shift; + $self->_check(); + $self->_inject({}, @_); +} + +sub set { + my $self = shift; + $self->_check(); + $self->_inject({set => 1}, @_); +} + +sub current { + my $self = shift; + my ($sym, %params) = @_; + + my $out = get_symbol($sym, $self->{+CLASS}); + return $out unless $params{required}; + confess "Attempt to modify a sub that does not exist '$self->{+CLASS}\::$sym' (Mock operates on packages, not classes, are you looking for a symbol in a parent class?)" + unless $out; + return $out; +} + +sub orig { + my $self = shift; + my ($sym) = @_; + + $sym = "&$sym" unless $sym =~ m/^[&\$\%\@]/; + + my $syms = $self->{+_SYMBOLS} + or croak "No symbols have been mocked yet"; + + my $ref = $syms->{$sym}; + + croak "Symbol '$sym' is not mocked" + unless $ref && @$ref; + + my ($orig) = @$ref; + + return $orig; +} + +sub track { + my $self = shift; + + ($self->{+_TRACK}) = @_ if @_; + + return $self->{+_TRACK}; +} + +sub clear_call_tracking { @{shift->{+CALL_TRACKING}} = () } + +sub clear_sub_tracking { + my $self = shift; + + unless (@_) { + %{$self->{+SUB_TRACKING}} = (); + return; + } + + for my $item (@_) { + delete $self->{+SUB_TRACKING}->{$item}; + } + + return; +} + +sub _parse_inject { + my $self = shift; + my ($param, $arg) = @_; + + if ($param =~ m/^-(.*)$/) { + my $sym = $1; + my $sig = slot_to_sig(reftype($arg)); + my $ref = $arg; + return ($sig, $sym, $ref); + } + + return ('&', $param, $arg) + if ref($arg) && reftype($arg) eq 'CODE'; + + my ($is, $field, $val); + + if(defined($arg) && !ref($arg) && $arg =~ m/^(rw|ro|wo)$/) { + $is = $arg; + $field = $param; + } + elsif (!ref($arg)) { + $val = $arg; + $is = 'val'; + } + elsif (reftype($arg) eq 'HASH') { + $field = delete $arg->{field} || $param; + + $val = delete $arg->{val}; + $is = delete $arg->{is}; + + croak "Cannot specify 'is' and 'val' together" if $val && $is; + + $is ||= $val ? 'val' : 'rw'; + + croak "The following keys are not valid when defining a mocked sub with a hashref: " . join(", " => keys %$arg) + if keys %$arg; + } + else { + confess "'$arg' is not a valid argument when defining a mocked sub"; + } + + my $sub; + if ($is eq 'rw') { + $sub = gen_accessor($field); + } + elsif ($is eq 'ro') { + $sub = gen_reader($field); + } + elsif ($is eq 'wo') { + $sub = gen_writer($field); + } + else { # val + $sub = sub { $val }; + } + + return ('&', $param, $sub); +} + +sub _inject { + my $self = shift; + my ($params, @pairs) = @_; + + my $add = $params->{add}; + my $set = $params->{set}; + + my $class = $self->{+CLASS}; + + $self->{+_SYMBOLS} ||= {}; + my $syms = $self->{+_SYMBOLS}; + + while (my $param = shift @pairs) { + my $arg = shift @pairs; + my ($sig, $sym, $ref) = $self->_parse_inject($param, $arg); + my $orig = $self->current("$sig$sym"); + + croak "Cannot override '$sig$class\::$sym', symbol is not already defined" + unless $orig || $add || $set || ($sig eq '&' && $class->can($sym)); + + # Cannot be too sure about scalars in globs + croak "Cannot add '$sig$class\::$sym', symbol is already defined" + if $add && $orig + && (reftype($orig) ne 'SCALAR' || defined($$orig)); + + $syms->{"$sig$sym"} ||= []; + push @{$syms->{"$sig$sym"}} => $orig; # Might be undef, thats expected + + if ($self->{+_TRACK} && $sig eq '&') { + my $sub_tracker = $self->{+SUB_TRACKING}; + my $call_tracker = $self->{+CALL_TRACKING}; + my $sub = $ref; + $ref = sub { + my $call = {sub_name => $sym, sub_ref => $sub, args => [@_]}; + push @{$sub_tracker->{$param}} => $call; + push @$call_tracker => $call; + goto &$sub; + }; + } + + no strict 'refs'; + no warnings 'redefine'; + *{"$class\::$sym"} = $ref; + } + + return; +} + +sub _set_or_unset { + my $self = shift; + my ($symbol, $set) = @_; + + my $class = $self->{+CLASS}; + + return purge_symbol($symbol, $class) + unless $set; + + my $sym = parse_symbol($symbol, $class); + no strict 'refs'; + no warnings 'redefine'; + *{"$class\::$sym->{name}"} = $set; +} + +sub restore { + my $self = shift; + my ($sym) = @_; + $self->_check(); + + $sym = "&$sym" unless $sym =~ m/^[&\$\%\@]/; + + my $syms = $self->{+_SYMBOLS} + or croak "No symbols are mocked"; + + my $ref = $syms->{$sym}; + + croak "Symbol '$sym' is not mocked" + unless $ref && @$ref; + + my $old = pop @$ref; + delete $syms->{$sym} unless @$ref; + + return $self->_set_or_unset($sym, $old); +} + +sub reset { + my $self = shift; + my ($sym) = @_; + $self->_check(); + + $sym = "&$sym" unless $sym =~ m/^[&\$\%\@]/; + + my $syms = $self->{+_SYMBOLS} + or croak "No symbols are mocked"; + + my $ref = delete $syms->{$sym}; + + croak "Symbol '$sym' is not mocked" + unless $ref && @$ref; + + my ($old) = @$ref; + + return $self->_set_or_unset($sym, $old); +} + +sub reset_all { + my $self = shift; + $self->_check(); + + my $syms = $self->{+_SYMBOLS} || return; + + $self->reset($_) for keys %$syms; + + delete $self->{+_SYMBOLS}; +} + +sub _purge { + my $self = shift; + my $stash = $self->stash; + delete $stash->{$_} for keys %$stash; +} + +sub DESTROY { + my $self = shift; + + delete $self->{+CHILD}; + $self->reset_all if $self->{+_SYMBOLS}; + + delete $INC{$self->file} if $self->{+_BLOCKED_LOAD}; + + $self->_purge if $self->{+_PURGE_ON_DESTROY}; +} + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test2::Mock - Module for managing mocked classes and instances. + +=head1 DESCRIPTION + +This module lets you add and override methods for any package temporarily. When +the instance is destroyed it will restore the package to its original state. + +=head1 SYNOPSIS + + use Test2::Mock; + use MyClass; + + my $mock = Test2::Mock->new( + track => $BOOL, # enable call tracking if desired + class => 'MyClass', + override => [ + name => sub { 'fred' }, + ... + ], + add => [ + is_mocked => sub { 1 } + ... + ], + ... + ); + + # Unmock the 'name' sub + $mock->restore('name'); + + ... + + $mock = undef; # Will remove all the mocking + +=head1 CONSTRUCTION + +=head1 METHODS + +=over 4 + +=item $mock = Test2::Mock->new(class => $CLASS, ...) + +This will create a new instance of L that manages mocking +for the specified C<$CLASS>. + +Any C method can be used as a constructor argument, each +should be followed by an arrayref of arguments to be used within the method. For +instance the C method: + + my $mock = Test2::Mock->new( + class => 'AClass', + add => [foo => sub { 'foo' }], + ); + +is identical to this: + + my $mock = Test2::Mock->new( + class => 'AClass', + ); + $mock->add(foo => sub { 'foo' }); + +=item $mock->track($bool) + +Turn tracking on or off. Any sub added/overridden/set when tracking is on will +log every call in a hash retrievable via C<< $mock->tracking >>. Changing the +tracking toggle will not affect subs already altered, but will affect any +additional alterations. + +=item $hashref = $mock->sub_tracking + +The tracking data looks like this: + + { + sub_name => [ + {sub_name => $sub_name, sub_ref => $mock_subref, args => [... copy of @_ from the call ... ]}, + ..., + ..., + ], + } + +Unlike call_tracking, this lists all calls by sub, so you can choose to only +look at the sub specific calls. + +B The hashref items with the subname and args are shared with +call_tracking, modifying one modifies the other, so copy first! + +=item $arrayref = $mock->call_tracking + +The tracking data looks like this: + + [ + {sub_name => $sub_name, sub_ref => $mock_subref, args => [... copy of @_ from the call ... ]}, + ..., + ..., + ] + +Unlike sub_tracking this lists all calls to any mocked sub, in the order they +were called. To filter by sub use sub_tracking. + +B The hashref items with the subname and args are shared with +sub_tracking, modifying one modifies the other, so copy first! + +=item $mock->clear_sub_tracking() + +=item $mock->clear_sub_tracking(\@subnames) + +Clear tracking data. With no arguments ALL tracking data is cleared. When +arguments are provided then only those specific keys will be cleared. + +=item $mock->clear_call_tracking() + +Clear all items from call_tracking. + +=item $mock->add('symbol' => ..., 'symbol2' => ...) + +=item $mock->override('symbol1' => ..., 'symbol2' => ...) + +=item $mock->set('symbol1' => ..., 'symbol2' => ...) + +C and C are the primary ways to add/modify methods for a +class. Both accept the exact same type of arguments. The difference is that +C will fail unless the symbol you are overriding already exists, +C on the other hand will fail if the symbol does already exist. + +C was more recently added for cases where you may not know if the sub +already exists. These cases are rare, and set should be avoided (think of it +like 'no strict'). However there are valid use cases, so it was added. + +B Think of override as a push operation. If you call override on the +same symbol multiple times it will track that. You can use C as a +pop operation to go back to the previous mock. C can be used to remove +all the mocking for a symbol. + +Arguments must be a symbol name, with optional sigil, followed by a new +specification of the symbol. If no sigil is specified then '&' (sub) is +assumed. A simple example of overriding a sub: + + $mock->override(foo => sub { 'overridden foo' }); + my $val = $class->foo; # Runs our override + # $val is now set to 'overridden foo' + +You can also simply provide a value and it will be wrapped in a sub for you: + + $mock->override( foo => 'foo' ); + +The example above will generate a sub that always returns the string 'foo'. + +There are three *special* values that can be used to generate accessors: + + $mock->add( + name => 'rw', # Generates a read/write accessor + age => 'ro', # Generates a read only accessor + size => 'wo', # Generates a write only accessor + ); + +If you want to have a sub that actually returns one of the three special strings, or +that returns a coderef, you can use a hashref as the spec: + + my $ref = sub { 'my sub' }; + $mock->add( + rw_string => { val => 'rw' }, + ro_string => { val => 'ro' }, + wo_string => { val => 'wo' }, + coderef => { val => $ref }, # the coderef method returns $ref each time + ); + +You can also override/add other symbol types, such as hash: + + package Foo; + ... + + $mock->add('%foo' => {a => 1}); + + print $Foo::foo{a}; # prints '1' + +You can also tell mock to deduce the symbol type for the add/override from the +reference, rules are similar to glob assignments: + + $mock->add( + -foo => sub { 'foo' }, # Adds the &foo sub to the package + -foo => { foo => 1 }, # Adds the %foo hash to the package + -foo => [ 'f', 'o', 'o' ], # Adds the @foo array to the package + -foo => \"foo", # Adds the $foo scalar to the package + ); + +=item $mock->restore($SYMBOL) + +Restore the symbol to what it was before the last override. If the symbol was +recently added this will remove it. If the symbol has been overridden multiple +times this will ONLY restore it to the previous state. Think of C as a +push operation, and C as the pop operation. + +=item $mock->reset($SYMBOL) + +Remove all mocking of the symbol and restore the original symbol. If the symbol +was initially added then it will be completely removed. + +=item $mock->orig($SYMBOL) + +This will return the original symbol, before any mocking. For symbols that were +added this will return undef. + +=item $mock->current($SYMBOL) + +This will return the current symbol. + +=item $mock->reset_all + +Remove all added symbols, and restore all overridden symbols to their originals. + +=item $mock->add_constructor($NAME => $TYPE) + +=item $mock->override_constructor($NAME => $TYPE) + +This can be used to inject constructors. The first argument should be the name +of the constructor. The second argument specifies the constructor type. + +The C type is the most common, all arguments are used to create a new +hash that is blessed. + + hash => sub { + my ($class, %params) = @_; + return bless \%params, $class; + }; + +The C type is similar to the hash type, but accepts a list instead of +key/value pairs: + + array => sub { + my ($class, @params) = @_; + return bless \@params, $class; + }; + +The C type takes a reference and blesses it. This will modify your +original input argument. + + ref => sub { + my ($class, $params) = @_; + return bless $params, $class; + }; + +The C type will copy your reference and bless the copy: + + ref_copy => sub { + my ($class, $params) = @_; + my $type = reftype($params); + + return bless {%$params}, $class + if $type eq 'HASH'; + + return bless [@$params], $class + if $type eq 'ARRAY'; + + croak "Not sure how to construct a '$class' from '$params'"; + }; + +=item $mock->before($NAME, sub { ... }) + +This will replace the original sub C<$NAME> with a new sub that calls your +custom code just before calling the original method. The return from your +custom sub is ignored. Your sub and the original both get the unmodified +arguments. + +=item $mock->after($NAME, sub { ... }) + +This is similar to before, except your callback runs after the original code. +The return from your callback is ignored. + +=item $mock->around($NAME, sub { ... }) + +This gives you the chance to wrap the original sub: + + $mock->around(foo => sub { + my $orig = shift; + my $self = shift; + my (@args) = @_; + + ... + $self->$orig(@args); + ... + + return ...; + }); + +The original sub is passed in as the first argument, even before C<$self>. You +are responsible for making sure your wrapper sub returns the correct thing. + +=item $mock->autoload + +This will inject an C sub into the class. This autoload will +automatically generate read-write accessors for any sub called that does not +already exist. + +=item $mock->block_load + +This will prevent the real class from loading until the mock is destroyed. This +will fail if the class is already loaded. This will let you mock a class +completely without loading the original module. + +=item $pm_file = $mock->file + +This returns the relative path to the file for the module. This corresponds to +the C<%INC> entry. + +=item $bool = $mock->purge_on_destroy($bool) + +When true, this will cause the package stash to be completely obliterated when +the mock object falls out of scope or is otherwise destroyed. You do not +normally want this. + +=item $stash = $mock->stash + +This returns the stash for the class being mocked. This is the equivalent of: + + my $stash = \%{"${class}\::"}; + +This saves you from needing to turn off strict. + +=item $class = $mock->class + +The class being mocked by this instance. + +=item $p = $mock->parent + +If you mock a class twice the first instance is the parent, the second is the +child. This prevents the parent from being destroyed before the child, which +would lead to a very unpleasant situation. + +=item $c = $mock->child + +Returns the child mock, if any. + +=back + +=head1 SOURCE + +The source code repository for Test2-Suite can be found at +L. + +=head1 MAINTAINERS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 AUTHORS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 COPYRIGHT + +Copyright Chad Granum Eexodist@cpan.orgE. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + +See L + +=cut diff --git a/git/usr/share/perl5/core_perl/Test2/Plugin.pm b/git/usr/share/perl5/core_perl/Test2/Plugin.pm new file mode 100644 index 0000000000000000000000000000000000000000..bee47e0c0ec675193d45fc0385165578e531dec5 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Test2/Plugin.pm @@ -0,0 +1,81 @@ +package Test2::Plugin; +use strict; +use warnings; + +our $VERSION = '1.302210'; + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test2::Plugin - Documentation for plugins + +=head1 DESCRIPTION + +Plugins are packages that cause behavior changes, or other side-effects for the +test file that loads them. They should not export any functions, or provide any +tools. Plugins should be distinct units of functionality. + +If you wish to combine behavior changes with tools then you should write a +Plugin, a Tools module, and a bundle that loads them both. + +=head1 FAQ + +=over 4 + +=item Should I subclass Test2::Plugin? + +No. Currently this class is empty. Eventually we may want to add behavior, in +which case we do not want anyone to already be subclassing it. + +=back + +=head1 HOW DO I WRITE A PLUGIN? + +Writing a plugin is not as simple as writing an L, or writing +L. Plugins alter behavior, or cause desirable side-effects. To +accomplish this you typically need a custom C method that calls one +or more functions provided by the L package. + +If you want to write a plugin you should look at existing plugins, as well as +the L and L documentation. There is no formula for a +Plugin, they are generally unique, however consistent rules are that they +should not load other plugins, or export any functions. + +=head1 SOURCE + +The source code repository for Test2-Suite can be found at +F. + +=head1 MAINTAINERS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 AUTHORS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 COPYRIGHT + +Copyright Chad Granum Eexodist@cpan.orgE. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + +See F + +=cut diff --git a/git/usr/share/perl5/core_perl/Test2/Require.pm b/git/usr/share/perl5/core_perl/Test2/Require.pm new file mode 100644 index 0000000000000000000000000000000000000000..7f10a5f951b6de645d4cfa593c56665c06efac50 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Test2/Require.pm @@ -0,0 +1,137 @@ +package Test2::Require; +use strict; +use warnings; + +our $VERSION = '1.302210'; + +use Test2::API qw/context/; +use Carp qw/croak/; + +sub skip { + my $class = shift; + croak "Class '$class' needs to implement 'skip()'"; +} + +sub import { + my $class = shift; + return if $class eq __PACKAGE__; + + my $skip = $class->skip(@_); + return unless defined $skip; + + my $ctx = context(); + $ctx->plan(0, SKIP => $skip || "No reason given."); + $ctx->release; +} + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test2::Require - Base class and documentation for skip-unless type test +packages. + +=head1 DESCRIPTION + +Test2::Require::* packages are packages you load to ensure your test file is +skipped unless a specific requirement is met. Modules in this namespace may +subclass L if they wish, but it is not strictly necessary to do +so. + +=head1 HOW DO I WRITE A 'REQUIRE' MODULE? + +=head2 AS A SUBCLASS + + package Test2::Require::Widget; + use strict; + use warnings; + + use base 'Test2::Require'; + + sub HAVE_WIDGETS { ... }; + + sub skip { + my $class = shift; + my @import_args = @_; + + if (HAVE_WIDGETS()) { + # We have widgets, do not skip + return undef; + } + else { + # No widgets, skip the test + return "Skipped because there are no widgets" unless HAVE_WIDGETS(); + } + } + + 1; + +A subclass of L simply needs to implement a C method. +This method will receive all import arguments. This method should return undef +if the test should run, and should return a reason for skipping if the test +should be skipped. + +=head2 STAND-ALONE + +If you do not wish to subclass L then you should write an +C method: + + package Test2::Require::Widget; + use strict; + use warnings; + + use Test2::API qw/context/; + + sub HAVE_WIDGETS { ... }; + + sub import { + my $class = shift; + + # Have widgets, should run. + return if HAVE_WIDGETS(); + + # Use the context object to create the event + my $ctx = context(); + $ctx->plan(0, SKIP => "Skipped because there are no widgets"); + $ctx->release; + } + + 1; + +=head1 SOURCE + +The source code repository for Test2-Suite can be found at +F. + +=head1 MAINTAINERS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 AUTHORS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 COPYRIGHT + +Copyright Chad Granum Eexodist@cpan.orgE. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + +See F + +=cut diff --git a/git/usr/share/perl5/core_perl/Test2/Suite.pm b/git/usr/share/perl5/core_perl/Test2/Suite.pm new file mode 100644 index 0000000000000000000000000000000000000000..8b5cc5a13fe836ca2f4345df27f0558a63d7fd3a --- /dev/null +++ b/git/usr/share/perl5/core_perl/Test2/Suite.pm @@ -0,0 +1,382 @@ +package Test2::Suite; +use strict; +use warnings; + +our $VERSION = '1.302210'; + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test2::Suite - Distribution with a rich set of tools built upon the Test2 +framework. + +=head1 DESCRIPTION + +Rich set of tools, plugins, bundles, etc built upon the L testing +library. If you are interested in writing tests, this is the distribution for +you. + +=head2 WHAT ARE TOOLS, PLUGINS, AND BUNDLES? + +=over 4 + +=item TOOLS + +Tools are packages that export functions for use in test files. These functions +typically generate events. Tools B alter behavior of other tools, +or the system in general. + +=item PLUGINS + +Plugins are packages that produce effects, or alter behavior of tools. An +example would be a plugin that causes the test to bail out after the first +failure. Plugins B export anything. + +=item BUNDLES + +Bundles are collections of tools and plugins. A bundle should load and +re-export functions from Tool packages. A bundle may also load and configure +any number of plugins. + +=back + +If you want to write something that both exports new functions, and affects +behavior, you should write both a Tools distribution, and a Plugin distribution, +then a Bundle that loads them both. This is important as it helps avoid the +problem where a package exports much-desired tools, but +also produces undesirable side-effects. + +=head1 INCLUDED BUNDLES + +=over 4 + +=item Test2::V# + +These do not live in the bundle namespace as they are the primary ways to use +Test2::Suite. + +The current latest is L. + + use Test2::V0; + # strict and warnings are on for you now. + + ok(...); + + # Note: is does deep checking, unlike the 'is' from Test::More. + is(...); + + ... + + done_testing; + +This bundle includes every tool listed in the L section below, +except for L. This bundle provides most of what +anyone writing tests could need. This is also the preferred bundle/toolset of +the L author. + +See L for complete documentation. + +=item Extended + +B<** Deprecated **> See L + + use Test2::Bundle::Extended; + # strict and warnings are on for you now. + + ok(...); + + # Note: is does deep checking, unlike the 'is' from Test::More. + is(...); + + ... + + done_testing; + +This bundle includes every tool listed in the L section below, +except for L. This bundle provides most of what +anyone writing tests could need. This is also the preferred bundle/toolset of +the L author. + +See L for complete documentation. + +=item More + + use Test2::Bundle::More; + use strict; + use warnings; + + plan 3; # Or you can use done_testing at the end + + ok(...); + + is(...); # Note: String compare + + is_deeply(...); + + ... + + done_testing; # Use instead of plan + +This bundle is meant to be a I drop-in replacement for L. +There are some notable differences to be aware of however. Some exports are +missing: C, C, C, C<$TODO>, C, C, +C. As well it is no longer possible to set the plan at import: +C<< use .. tests => 5 >>. C<$TODO> has been replaced by the C +function. Planning is done using C, C, or C. + +See L for complete documentation. + +=item Simple + + use Test2::Bundle::Simple; + use strict; + use warnings; + + plan 1; + + ok(...); + +This bundle is meant to be a I drop-in replacement for L. +See L for complete documentation. + +=back + +=head1 INCLUDED TOOLS + +=over 4 + +=item Basic + +Basic provides most of the essential tools previously found in L. +However it does not export any tools used for comparison. The basic C, +C, C functions are present, as are functions for planning. + +See L for complete documentation. + +=item Compare + +This provides C, C, C, C, and several additional +helpers. B These are all I comparison tools and work like a +combination of L's C and C. + +See L for complete documentation. + +=item ClassicCompare + +This provides L flavored C, C, C, C, and +C. It also provides C. + +See L for complete documentation. + +=item Class + +This provides functions for testing objects and classes, things like C. + +See L for complete documentation. + +=item Defer + +This provides functions for writing test functions in one place, but running +them later. This is useful for testing things that run in an altered state. + +See L for complete documentation. + +=item Encoding + +This exports a single function that can be used to change the encoding of all +your test output. + +See L for complete documentation. + +=item Exports + +This provides tools for verifying exports. You can verify that functions have +been imported, or that they have not been imported. + +See L for complete documentation. + +=item Mock + +This provides tools for mocking objects and classes. This is based largely on +L, but several interface improvements have been added that cannot +be added to Mock::Quick itself without breaking backwards compatibility. + +See L for complete documentation. + +=item Ref + +This exports tools for validating and comparing references. + +See L for complete documentation. + +=item Spec + +This is an RSPEC implementation with concurrency support. + +See L for more details. + +=item Subtest + +This exports tools for running subtests. + +See L for complete documentation. + +=item Target + +This lets you load the package(s) you intend to test, and alias them into +constants/package variables. + +See L for complete documentation. + +=back + +=head1 INCLUDED PLUGINS + +=over 4 + +=item BailOnFail + +The much requested "bail-out on first failure" plugin. When this plugin is +loaded, any failure will cause the test to bail out immediately. + +See L for complete documentation. + +=item DieOnFail + +The much requested "die on first failure" plugin. When this plugin is +loaded, any failure will cause the test to die immediately. + +See L for complete documentation. + +=item ExitSummary + +This plugin gives you statistics and diagnostics at the end of your test in the +event of a failure. + +See L for complete documentation. + +=item SRand + +Use this to set the random seed to a specific seed, or to the current date. + +See L for complete documentation. + +=item UTF8 + +Turn on utf8 for your testing. This sets the current file to be utf8, it also +sets STDERR, STDOUT, and your formatter to all output utf8. + +See L for complete documentation. + +=back + +=head1 INCLUDED REQUIREMENT CHECKERS + +=over 4 + +=item AuthorTesting + +Using this package will cause the test file to be skipped unless the +AUTHOR_TESTING environment variable is set. + +See L for complete documentation. + +=item EnvVar + +Using this package will cause the test file to be skipped unless a custom +environment variable is set. + +See L for complete documentation. + +=item Fork + +Using this package will cause the test file to be skipped unless the system is +capable of forking (including emulated forking). + +See L for complete documentation. + +=item RealFork + +Using this package will cause the test file to be skipped unless the system is +capable of true forking. + +See L for complete documentation. + +=item Module + +Using this package will cause the test file to be skipped unless the specified +module is installed (and optionally at a minimum version). + +See L for complete documentation. + +=item Perl + +Using this package will cause the test file to be skipped unless the specified +minimum perl version is met. + +See L for complete documentation. + +=item Threads + +Using this package will cause the test file to be skipped unless the system has +threading enabled. + +B This will not turn threading on for you. + +See L for complete documentation. + +=back + +=head1 SEE ALSO + +See the L documentation for a namespace map. Everything in this +distribution uses L. + +L is the Test2 Manual. + +=head1 CONTACTING US + +Many Test2 developers and users lurk on L. We also +have a slack team that can be joined by anyone with an C<@cpan.org> email +address L If you do not have an C<@cpan.org> +email you can ask for a slack invite by emailing Chad Granum +Eexodist@cpan.orgE. + +=head1 SOURCE + +The source code repository for Test2-Suite can be found at +F. + +=head1 MAINTAINERS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 AUTHORS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 COPYRIGHT + +Copyright Chad Granum Eexodist@cpan.orgE. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + +See F + +=cut diff --git a/git/usr/share/perl5/core_perl/Test2/Todo.pm b/git/usr/share/perl5/core_perl/Test2/Todo.pm new file mode 100644 index 0000000000000000000000000000000000000000..691786091cf3512aa5761b01fd9795562c697ffa --- /dev/null +++ b/git/usr/share/perl5/core_perl/Test2/Todo.pm @@ -0,0 +1,184 @@ +package Test2::Todo; +use strict; +use warnings; + +use Carp qw/croak/; +use Test2::Util::HashBase qw/hub _filter reason/; + +use Test2::API qw/test2_stack/; + +use overload '""' => \&reason, fallback => 1; + +our $VERSION = '1.302210'; + +sub init { + my $self = shift; + + my $reason = $self->{+REASON}; + croak "The 'reason' attribute is required" unless defined $reason; + + my $hub = $self->{+HUB} ||= test2_stack->top; + + $self->{+_FILTER} = $hub->pre_filter( + sub { + my ($active_hub, $event) = @_; + + # Turn a diag into a note + return Test2::Event::Note->new(%$event) if ref($event) eq 'Test2::Event::Diag'; + + if ($active_hub == $hub) { + $event->set_todo($reason) if $event->can('set_todo'); + $event->add_amnesty({tag => 'TODO', details => $reason}); + $event->set_effective_pass(1) if $event->isa('Test2::Event::Ok'); + } + else { + $event->add_amnesty({tag => 'TODO', details => $reason, inherited => 1}); + } + + return $event; + }, + inherit => 1, + todo => $reason, + ); +} + +sub end { + my $self = shift; + my $hub = $self->{+HUB} or return; + + $hub->pre_unfilter($self->{+_FILTER}); + delete $self->{+HUB}; + delete $self->{+_FILTER}; +} + +sub DESTROY { + my $self = shift; + $self->end; +} + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test2::Todo - TODO extension for Test2. + +=head1 DESCRIPTION + +This is an object that lets you create and manage TODO states for tests. This +is an extension, not a plugin or a tool. This library can be used by plugins +and tools to manage todo states. + +If you simply want to write a todo test then you should look at the C +function provided by L. + +=head1 SYNOPSIS + + use Test2::Todo; + + # Start the todo + my $todo = Test2::Todo->new(reason => 'Fix later'); + + # Will be considered todo, so suite still passes + ok(0, "oops"); + + # End the todo + $todo->end; + + # TODO has ended, this test will actually fail. + ok(0, "oops"); + +=head1 CONSTRUCTION OPTIONS + +=over 4 + +=item reason (required) + +The reason for the todo, this can be any defined value. + +=item hub (optional) + +The hub to which the TODO state should be applied. If none is provided then the +current global hub is used. + +=back + +=head1 INSTANCE METHODS + +=over 4 + +=item $todo->end + +End the todo state. + +=back + +=head1 CLASS METHODS + +=over 4 + +=item $count = Test2::Todo->hub_in_todo($hub) + +If the hub has any todo objects this will return the total number of them. If +the hub has no todo objects it will return 0. + +=back + +=head1 OTHER NOTES + +=head2 How it works + +When an instance is created a filter sub is added to the L. This +filter will set the C and C attributes on all events as they +come in. When the instance is destroyed, or C is called, the filter is +removed. + +When a new hub is pushed (such as when a subtest is started) the new hub will +inherit the filter, but it will only set C, it will not set C +on events in child hubs. + +=head2 $todo->end is called at destruction + +If your C<$todo> object falls out of scope and gets garbage collected, the todo +will end. + +=head2 Can I use multiple instances? + +Yes. The most recently created one that is still active will win. + +=head1 SOURCE + +The source code repository for Test2-Suite can be found at +F. + +=head1 MAINTAINERS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 AUTHORS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 COPYRIGHT + +Copyright Chad Granum Eexodist@cpan.orgE. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + +See F + +=cut diff --git a/git/usr/share/perl5/core_perl/Test2/Tools.pm b/git/usr/share/perl5/core_perl/Test2/Tools.pm new file mode 100644 index 0000000000000000000000000000000000000000..53bbc40173f4eaaa2bb03585721cf41c034e96a6 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Test2/Tools.pm @@ -0,0 +1,117 @@ +package Test2::Tools; +use strict; +use warnings; + +our $VERSION = '1.302210'; + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test2::Tools - Documentation for Tools. + +=head1 DESCRIPTION + +Tools are packages that export test functions, typically all related to a +specific aspect of testing. If you have a couple different categories of +exports then you may want to break them into separate modules. + +Tools should export testing functions. Loading tools B have side- +effects, or alter the behavior of other tools. If you want to alter behaviors +or create side-effects then you probably want to write a L. + +=head1 FAQ + +=over 4 + +=item Why is it called Test2::Tools, and not Test2::Tool? + +This question arises since Tools is the only namespace in the plural. This is +because each Plugin should be a distinct unit of functionality, but a Tools +dist can (and usually should) export several tools. A bundle is also typically +described as a single unit. Nobody would like Test2::Bundles::Foo. + +=item Should my tools subclass Test2::Tools? + +No. Currently this class is empty. Eventually we may want to add behavior, in +which case we do not want anyone to already be subclassing it. + +=back + +=head1 HOW DO I WRITE A 'TOOLS' MODULE? + +It is very easy to write tools: + + package Test2::Tools::Mine + use strict; + use warnings; + + # All tools should use the context() function. + use Test2::API qw/context/; + + our @EXPORTS = qw/ok plan/; + use base 'Exporter'; + + sub ok($;$) { + my ($bool, $name) = @_; + + # All tool functions should start by grabbing a context + my $ctx = context(); + + # The context is the primary interface for generating events + $ctx->ok($bool, $name); + + # When you are done you release the context + $ctx->release; + + return $bool ? 1 : 0; + } + + sub plan { + my ($max) = @_; + my $ctx = context(); + $ctx->plan($max); + $ctx->release; + } + + 1; + +See L for documentation on what the C<$ctx> object can do. + +=head1 SOURCE + +The source code repository for Test2-Suite can be found at +F. + +=head1 MAINTAINERS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 AUTHORS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 COPYRIGHT + +Copyright Chad Granum Eexodist@cpan.orgE. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + +See F + +=cut diff --git a/git/usr/share/perl5/core_perl/Test2/Util.pm b/git/usr/share/perl5/core_perl/Test2/Util.pm new file mode 100644 index 0000000000000000000000000000000000000000..f7103a4f8b4997bd2e2a7db6bce8cac18cff0331 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Test2/Util.pm @@ -0,0 +1,400 @@ +package Test2::Util; +use strict; +use warnings; + +our $VERSION = '1.302210'; + +use Config qw/%Config/; +use Carp qw/croak/; + +BEGIN { + *HAVE_PERLIO = defined &PerlIO::get_layers ? sub() { 1 } : sub() { 0 }; +} + +our @EXPORT_OK = qw{ + try + + pkg_to_file + + get_tid USE_THREADS + CAN_THREAD + CAN_REALLY_FORK + CAN_FORK + + CAN_SIGSYS + + IS_WIN32 + + ipc_separator + + gen_uid + + do_rename do_unlink + + try_sig_mask + + clone_io +}; +BEGIN { require Exporter; our @ISA = qw(Exporter) } + +BEGIN { + *IS_WIN32 = ($^O eq 'MSWin32') ? sub() { 1 } : sub() { 0 }; +} + +sub _can_thread { + return 0 unless $] >= 5.008001; + return 0 unless $Config{'useithreads'}; + + # Threads are broken on perl 5.10.0 built with gcc 4.8+ + if ($] == 5.010000 && $Config{'ccname'} eq 'gcc' && $Config{'gccversion'}) { + return 0 unless $Config{'gccversion'} =~ m/^(\d+)\.(\d+)/; + my @parts = split /[\.\s]+/, $Config{'gccversion'}; + return 0 if $parts[0] > 4 || ($parts[0] == 4 && $parts[1] >= 8); + } + + # Change to a version check if this ever changes + return 0 if $INC{'Devel/Cover.pm'}; + return 1; +} + +sub _can_fork { + return 1 if $Config{d_fork}; + return 0 unless IS_WIN32 || $^O eq 'NetWare'; + return 0 unless $Config{useithreads}; + return 0 unless $Config{ccflags} =~ /-DPERL_IMPLICIT_SYS/; + + return _can_thread(); +} + +BEGIN { + no warnings 'once'; + *CAN_THREAD = _can_thread() ? sub() { 1 } : sub() { 0 }; +} +my $can_fork; +sub CAN_FORK () { + return $can_fork + if defined $can_fork; + $can_fork = !!_can_fork(); + no warnings 'redefine'; + *CAN_FORK = $can_fork ? sub() { 1 } : sub() { 0 }; + $can_fork; +} +my $can_really_fork; +sub CAN_REALLY_FORK () { + return $can_really_fork + if defined $can_really_fork; + $can_really_fork = !!$Config{d_fork}; + no warnings 'redefine'; + *CAN_REALLY_FORK = $can_really_fork ? sub() { 1 } : sub() { 0 }; + $can_really_fork; +} + +sub _manual_try(&;@) { + my $code = shift; + my $args = \@_; + my $err; + + my $die = delete $SIG{__DIE__}; + + eval { $code->(@$args); 1 } or $err = $@ || "Error was squashed!\n"; + + $die ? $SIG{__DIE__} = $die : delete $SIG{__DIE__}; + + return (!defined($err), $err); +} + +sub _local_try(&;@) { + my $code = shift; + my $args = \@_; + my $err; + + no warnings; + local $SIG{__DIE__}; + eval { $code->(@$args); 1 } or $err = $@ || "Error was squashed!\n"; + + return (!defined($err), $err); +} + +# Older versions of perl have a nasty bug on win32 when localizing a variable +# before forking or starting a new thread. So for those systems we use the +# non-local form. When possible though we use the faster 'local' form. +BEGIN { + if (IS_WIN32 && $] < 5.020002) { + *try = \&_manual_try; + } + else { + *try = \&_local_try; + } +} + +BEGIN { + if (CAN_THREAD) { + if ($INC{'threads.pm'}) { + # Threads are already loaded, so we do not need to check if they + # are loaded each time + *USE_THREADS = sub() { 1 }; + *get_tid = sub() { threads->tid() }; + } + else { + # :-( Need to check each time to see if they have been loaded. + *USE_THREADS = sub() { $INC{'threads.pm'} ? 1 : 0 }; + *get_tid = sub() { $INC{'threads.pm'} ? threads->tid() : 0 }; + } + } + else { + # No threads, not now, not ever! + *USE_THREADS = sub() { 0 }; + *get_tid = sub() { 0 }; + } +} + +sub pkg_to_file { + my $pkg = shift; + my $file = $pkg; + $file =~ s{(::|')}{/}g; + $file .= '.pm'; + return $file; +} + +sub ipc_separator() { "~" } + +my $UID = 1; +sub gen_uid() { join ipc_separator() => ($$, get_tid(), time, $UID++) } + +sub _check_for_sig_sys { + my $sig_list = shift; + return $sig_list =~ m/\bSYS\b/; +} + +my $CAN_SIGSYS; +sub CAN_SIGSYS () { + if (!defined $CAN_SIGSYS) { + $CAN_SIGSYS = _check_for_sig_sys($Config{sig_name}); + } + $CAN_SIGSYS; +} + +my %PERLIO_SKIP = ( + unix => 1, + via => 1, +); + +sub clone_io { + my ($fh) = @_; + my $fileno = eval { fileno($fh) }; + + return $fh if !defined($fileno) || !length($fileno) || $fileno < 0; + + open(my $out, '>&' . $fileno) or die "Can't dup fileno $fileno: $!"; + + my %seen; + my @layers = HAVE_PERLIO ? grep { !$PERLIO_SKIP{$_} and !$seen{$_}++ } PerlIO::get_layers($fh) : (); + binmode($out, join(":", "", "raw", @layers)); + + my $old = select $fh; + my $af = $|; + select $out; + $| = $af; + select $old; + + return $out; +} + +BEGIN { + if (IS_WIN32) { + my $max_tries = 5; + + *do_rename = sub { + my ($from, $to) = @_; + + my $err; + for (1 .. $max_tries) { + return (1) if rename($from, $to); + $err = "$!"; + last if $_ == $max_tries; + sleep 1; + } + + return (0, $err); + }; + *do_unlink = sub { + my ($file) = @_; + + my $err; + for (1 .. $max_tries) { + return (1) if unlink($file); + $err = "$!"; + last if $_ == $max_tries; + sleep 1; + } + + return (0, "$!"); + }; + } + else { + *do_rename = sub { + my ($from, $to) = @_; + return (1) if rename($from, $to); + return (0, "$!"); + }; + *do_unlink = sub { + my ($file) = @_; + return (1) if unlink($file); + return (0, "$!"); + }; + } +} + +#for backwards compatibility +sub try_sig_mask(&) { + require Test2::Util::Sig; + goto &Test2::Util::Sig::try_sig_mask; +} + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test2::Util - Tools used by Test2 and friends. + +=head1 DESCRIPTION + +Collection of tools used by L and friends. + +=head1 EXPORTS + +All exports are optional. You must specify subs to import. + +=over 4 + +=item ($success, $error) = try { ... } + +Eval the codeblock, return success or failure, and the error message. This code +protects $@ and $!, they will be restored by the end of the run. This code also +temporarily blocks $SIG{DIE} handlers. + +=item protect { ... } + +Similar to try, except that it does not catch exceptions. The idea here is to +protect $@ and $! from changes. $@ and $! will be restored to whatever they +were before the run so long as it is successful. If the run fails $! will still +be restored, but $@ will contain the exception being thrown. + +=item CAN_FORK + +True if this system is capable of true or pseudo-fork. + +=item CAN_REALLY_FORK + +True if the system can really fork. This will be false for systems where fork +is emulated. + +=item CAN_THREAD + +True if this system is capable of using threads. + +=item USE_THREADS + +Returns true if threads are enabled, false if they are not. + +=item get_tid + +This will return the id of the current thread when threads are enabled, +otherwise it returns 0. + +=item my $file = pkg_to_file($package) + +Convert a package name to a filename. + +=item $string = ipc_separator() + +Get the IPC separator. Currently this is always the string C<'~'>. + +=item $string = gen_uid() + +Generate a unique id (NOT A UUID). This will typically be the process id, the +thread id, the time, and an incrementing integer all joined with the +C. + +These ID's are unique enough for most purposes. For identical ids to be +generated you must have 2 processes with the same PID generate IDs at the same +time with the same current state of the incrementing integer. This is a +perfectly reasonable thing to expect to happen across multiple machines, but is +quite unlikely to happen on one machine. + +This can fail to be unique if a process generates an id, calls exec, and does +it again after the exec and it all happens in less than a second. It can also +happen if the systems process id's cycle in less than a second allowing 2 +different programs that use this generator to run with the same PID in less +than a second. Both these cases are sufficiently unlikely. If you need +universally unique ids, or ids that are unique in these conditions, look at +L. + +=item ($ok, $err) = do_rename($old_name, $new_name) + +Rename a file, this wraps C in a way that makes it more reliable +cross-platform when trying to rename files you recently altered. + +=item ($ok, $err) = do_unlink($filename) + +Unlink a file, this wraps C in a way that makes it more reliable +cross-platform when trying to unlink files you recently altered. + +=back + +=head1 NOTES && CAVEATS + +=over 4 + +=item 5.10.0 + +Perl 5.10.0 has a bug when compiled with newer gcc versions. This bug causes a +segfault whenever a new thread is launched. Test2 will attempt to detect +this, and note that the system is not capable of forking when it is detected. + +=item Devel::Cover + +Devel::Cover does not support threads. CAN_THREAD will return false if +Devel::Cover is loaded before the check is first run. + +=back + +=head1 SOURCE + +The source code repository for Test2 can be found at +L. + +=head1 MAINTAINERS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 AUTHORS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=item Kent Fredric Ekentnl@cpan.orgE + +=back + +=head1 COPYRIGHT + +Copyright Chad Granum Eexodist@cpan.orgE. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + +See L + +=cut diff --git a/git/usr/share/perl5/core_perl/Test2/V0.pm b/git/usr/share/perl5/core_perl/Test2/V0.pm new file mode 100644 index 0000000000000000000000000000000000000000..39835a96db05f4ba6f35a9ab90a45f83c5c59542 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Test2/V0.pm @@ -0,0 +1,637 @@ +package Test2::V0; +use strict; +use warnings; + +use Test2::Util::Importer; + +our $VERSION = '1.302210'; + +use Carp qw/croak/; + +use Test2::Plugin::SRand(); +use Test2::Plugin::UTF8(); +use Test2::Tools::Target(); + +use Test2::Plugin::ExitSummary; + +use Test2::API qw/intercept context/; + +use Test2::Tools::Event qw/gen_event/; + +use Test2::Tools::Defer qw/def do_def/; + +use Test2::Tools::Basic qw{ + ok pass fail diag note todo skip + plan skip_all done_testing bail_out +}; + +use Test2::Tools::Compare qw{ + is like isnt unlike + match mismatch validator + hash array bag object meta meta_check number float rounded within string subset bool check_isa + number_lt number_le number_ge number_gt + in_set not_in_set check_set + item field call call_list call_hash prop check all_items all_keys all_vals all_values + etc end filter_items + T F D DF E DNE FDNE U L + event fail_events + exact_ref +}; + +use Test2::Tools::Warnings qw{ + warns warning warnings no_warnings +}; + +use Test2::Tools::ClassicCompare qw/cmp_ok/; + +use Test2::Util::Importer 'Test2::Tools::Subtest' => ( + subtest_buffered => { -as => 'subtest' }, +); + +use Test2::Tools::Class qw/can_ok isa_ok DOES_ok/; +use Test2::Tools::Encoding qw/set_encoding/; +use Test2::Tools::Exports qw/imported_ok not_imported_ok/; +use Test2::Tools::Ref qw/ref_ok ref_is ref_is_not/; +use Test2::Tools::Mock qw/mock mocked/; +use Test2::Tools::Exception qw/try_ok dies lives/; +use Test2::Tools::Refcount qw/is_refcount is_oneref refcount/; + +our @EXPORT = qw{ + ok pass fail diag note todo skip + plan skip_all done_testing bail_out + + intercept context + + gen_event + + def do_def + + cmp_ok + + warns warning warnings no_warnings + + subtest + can_ok isa_ok DOES_ok + set_encoding + imported_ok not_imported_ok + ref_ok ref_is ref_is_not + mock mocked + dies lives try_ok + + is like isnt unlike + match mismatch validator + hash array bag object meta meta_check number float rounded within string subset bool check_isa + number_lt number_le number_ge number_gt + in_set not_in_set check_set + item field call call_list call_hash prop check all_items all_keys all_vals all_values + etc end filter_items + T F D DF E DNE FDNE U L + event fail_events + exact_ref + + is_refcount is_oneref refcount +}; + +my $SRAND; +sub import { + my $class = shift; + + my $caller = caller; + my (@exports, %options); + while (my $arg = shift @_) { + push @exports => $arg and next unless substr($arg, 0, 1) eq '-'; + $options{$arg} = shift @_; + } + + # SRand handling + my $srand = delete $options{'-srand'}; + + my $no_srand = exists $options{'-no_srand'}; + delete $options{'-no_srand'} if $no_srand; + + croak "Cannot combine '-srand' and '-no_srand' options" + if $no_srand && defined($srand); + + if ( !$no_srand ) { + Test2::Plugin::SRand->import($srand ? $srand : ()) if defined($srand) || !$SRAND++; + } + + # Pragmas + my $no_pragmas = delete $options{'-no_pragmas'}; + my $no_strict = delete $options{'-no_strict'} || $no_pragmas; + my $no_warnings = delete $options{'-no_warnings'} || $no_pragmas; + my $no_utf8 = delete $options{'-no_utf8'} || $no_pragmas; + + strict->import() unless $no_strict; + 'warnings'->import() unless $no_warnings; + Test2::Plugin::UTF8->import() unless $no_utf8; + + my $target = delete $options{'-target'}; + Test2::Tools::Target->import_into($caller, $target) + if $target; + + croak "Unknown option(s): " . join(', ', sort keys %options) if keys %options; + + Test2::Util::Importer->import_into($class, $caller, @exports); +} + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test2::V0 - 0Th edition of the Test2 recommended bundle. + +=head1 DESCRIPTION + +This is the big-daddy bundle. This bundle includes nearly every tool, and +several plugins, that the Test2 author uses. This bundle is used +extensively to test L itself. + +=head1 NAMING, USING, DEPENDING + +This bundle should not change in a I incompatible way. Some minor +breaking changes, specially bugfixes, may be allowed. If breaking changes are +needed then a new C module should be released instead. + +As new C modules are released old ones I be moved to different cpan +distributions. You should always use a specific bundle version and list that +version in your distributions testing requirements. You should never simply +list L as your modules dep, instead list the specific bundle, or +tools and plugins you use directly in your metadata. + +=head1 SYNOPSIS + + use Test2::V0; + + ok(1, "pass"); + + ... + + done_testing; + +=head1 RESOLVING CONFLICTS WITH MOOSE + + use Test2::V0 '!meta'; + +L and L both export very different C +subs. Adding C<'!meta'> to the import args will prevent the sub from being +imported. This bundle also exports the sub under the name C so +you can use that spelling as an alternative. + +=head2 TAGS + +=over 4 + +=item :DEFAULT + +The following are both identical: + + use Test2::V0; + + use Test2::V0 ':DEFAULT'; + +=back + +=head2 RENAMING ON IMPORT + + use Test2::V0 ':DEFAULT', '!ok', ok => {-as => 'my_ok'}; + +This bundle uses L for exporting, as such you can use any arguments +it accepts. + +Explanation: + +=over 4 + +=item '!ok' + +Do not export C + +=item ok => {-as => 'my_ok'} + +Actually, go ahead and import C but under the name C. + +=back + +If you did not add the C<'!ok'> argument then you would have both C and +C + +=head1 PRAGMAS + +All of these can be disabled via individual import arguments, or by the +C<-no_pragmas> argument. + + use Test2::V0 -no_pragmas => 1; + +=head2 STRICT + +L is turned on for you. You can disable this with the C<-no_strict> or +C<-no_pragmas> import arguments: + + use Test2::V0 -no_strict => 1; + +=head2 WARNINGS + +L are turned on for you. You can disable this with the +C<-no_warnings> or C<-no_pragmas> import arguments: + + use Test2::V0 -no_warnings => 1; + +=head2 UTF8 + +This is actually done via the L plugin, see the +L section for details. + +B C<< -no_pragmas => 1 >> will turn off the entire plugin. + +=head1 PLUGINS + +=head2 SRAND + +See L. + +This will set the random seed to today's date. You can provide an alternate seed +with the C<-srand> import option: + + use Test2::V0 -srand => 1234; + +You can also disable this behavior: + + use Test2::V0 -no_srand => 1; + +B When srand is on (default) it can cause problems with things like +L which will end up attempting the same "random" filenames for +every test process started on a given day (or sharing the same seed). + +=head2 UTF8 + +See L. + +This will set the file, and all output handles (including formatter handles), to +utf8. This will turn on the utf8 pragma for the current scope. + +This can be disabled using the C<< -no_utf8 => 1 >> or C<< -no_pragmas => 1 >> +import arguments. + + use Test2::V0 -no_utf8 => 1; + +=head2 EXIT SUMMARY + +See L. + +This plugin has no configuration. + +=head1 ENVIRONMENT VARIABLES + +See L for a list of meaningul environment variables. + +=head1 API FUNCTIONS + +See L for these + +=over 4 + +=item $ctx = context() + +=item $events = intercept { ... } + +=back + +=head1 TOOLS + +=head2 TARGET + +See L. + +You can specify a target class with the C<-target> import argument. If you do +not provide a target then C<$CLASS> and C will not be imported. + + use Test2::V0 -target => 'My::Class'; + + print $CLASS; # My::Class + print CLASS(); # My::Class + +Or you can specify names: + + use Test2::V0 -target => { pkg => 'Some::Package' }; + + pkg()->xxx; # Call 'xxx' on Some::Package + $pkg->xxx; # Same + +=over 4 + +=item $CLASS + +Package variable that contains the target class name. + +=item $class = CLASS() + +Constant function that returns the target class name. + +=back + +=head2 DEFER + +See L. + +=over 4 + +=item def $func => @args; + +=item do_def() + +=back + +=head2 BASIC + +See L. + +=over 4 + +=item ok($bool, $name) + +=item ok($bool, $name, @diag) + +=item pass($name) + +=item pass($name, @diag) + +=item fail($name) + +=item fail($name, @diag) + +=item diag($message) + +=item note($message) + +=item $todo = todo($reason) + +=item todo $reason => sub { ... } + +=item skip($reason, $count) + +=item plan($count) + +=item skip_all($reason) + +=item done_testing() + +=item bail_out($reason) + +=back + +=head2 COMPARE + +See L. + +=over 4 + +=item is($got, $want, $name) + +=item isnt($got, $do_not_want, $name) + +=item like($got, qr/match/, $name) + +=item unlike($got, qr/mismatch/, $name) + +=item $check = match(qr/pattern/) + +=item $check = mismatch(qr/pattern/) + +=item $check = validator(sub { return $bool }) + +=item $check = hash { ... } + +=item $check = array { ... } + +=item $check = bag { ... } + +=item $check = object { ... } + +=item $check = meta { ... } + +=item $check = number($num) + +=item $check = string($str) + +=item $check = bool($bool) + +=item $check = check_isa($class_name) + +=item $check = in_set(@things) + +=item $check = not_in_set(@things) + +=item $check = check_set(@things) + +=item $check = item($thing) + +=item $check = item($idx => $thing) + +=item $check = field($name => $val) + +=item $check = call($method => $expect) + +=item $check = call_list($method => $expect) + +=item $check = call_hash($method => $expect) + +=item $check = prop($name => $expect) + +=item $check = check($thing) + +=item $check = T() + +=item $check = F() + +=item $check = D() + +=item $check = DF() + +=item $check = E() + +=item $check = DNE() + +=item $check = FDNE() + +=item $check = U() + +=item $check = L() + +=item $check = exact_ref($ref) + +=item end() + +=item etc() + +=item filter_items { grep { ... } @_ } + +=item $check = event $type => ... + +=item @checks = fail_events $type => ... + +=back + +=head2 CLASSIC COMPARE + +See L. + +=over 4 + +=item cmp_ok($got, $op, $want, $name) + +=back + +=head2 SUBTEST + +See L. + +=over 4 + +=item subtest $name => sub { ... }; + +(Note: This is called C in the Tools module.) + +=back + +=head2 CLASS + +See L. + +=over 4 + +=item can_ok($thing, @methods) + +=item isa_ok($thing, @classes) + +=item DOES_ok($thing, @roles) + +=back + +=head2 ENCODING + +See L. + +=over 4 + +=item set_encoding($encoding) + +=back + +=head2 EXPORTS + +See L. + +=over 4 + +=item imported_ok('function', '$scalar', ...) + +=item not_imported_ok('function', '$scalar', ...) + +=back + +=head2 REF + +See L. + +=over 4 + +=item ref_ok($ref, $type) + +=item ref_is($got, $want) + +=item ref_is_not($got, $do_not_want) + +=back + +See L. + +=over 4 + +=item is_refcount($ref, $count, $description) + +=item is_oneref($ref, $description) + +=item $count = refcount($ref) + +=back + +=head2 MOCK + +See L. + +=over 4 + +=item $control = mock ... + +=item $bool = mocked($thing) + +=back + +=head2 EXCEPTION + +See L. + +=over 4 + +=item $exception = dies { ... } + +=item $bool = lives { ... } + +=item $bool = try_ok { ... } + +=back + +=head2 WARNINGS + +See L. + +=over 4 + +=item $count = warns { ... } + +=item $warning = warning { ... } + +=item $warnings_ref = warnings { ... } + +=item $bool = no_warnings { ... } + +=back + +=head1 SOURCE + +The source code repository for Test2-Suite can be found at +F. + +=head1 MAINTAINERS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 AUTHORS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 COPYRIGHT + +Copyright Chad Granum Eexodist@cpan.orgE. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + +See F + +=cut diff --git a/git/usr/share/perl5/core_perl/Test2/Workflow.pm b/git/usr/share/perl5/core_perl/Test2/Workflow.pm new file mode 100644 index 0000000000000000000000000000000000000000..f38cceab38a2dc1c3d46fd3d01cffac09e8a0f90 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Test2/Workflow.pm @@ -0,0 +1,288 @@ +package Test2::Workflow; +use strict; +use warnings; + +our $VERSION = '1.302210'; + +our @EXPORT_OK = qw/parse_args current_build build root_build init_root build_stack/; +use base 'Exporter'; + +use Test2::Workflow::Build; +use Test2::Workflow::Task::Group; +use Test2::API qw/intercept/; +use Scalar::Util qw/blessed/; + +sub parse_args { + my %input = @_; + my $args = delete $input{args}; + my %out; + my %props; + + my $caller = $out{frame} = $input{caller} || caller(defined $input{level} ? $input{level} : 1); + delete @input{qw/caller level/}; + + for my $arg (@$args) { + if (my $r = ref($arg)) { + if ($r eq 'HASH') { + %props = (%props, %$arg); + } + elsif ($r eq 'CODE') { + die "Code is already set, did you provide multiple code blocks at $caller->[1] line $caller->[2].\n" + if $out{code}; + + $out{code} = $arg + } + else { + die "Not sure what to do with $arg at $caller->[1] line $caller->[2].\n"; + } + next; + } + + if ($arg =~ m/^\d+$/) { + push @{$out{lines}} => $arg; + next; + } + + die "Name is already set to '$out{name}', cannot set to '$arg', did you specify multiple names at $caller->[1] line $caller->[2].\n" + if $out{name}; + + $out{name} = $arg; + } + + die "a name must be provided, and must be truthy at $caller->[1] line $caller->[2].\n" + unless $out{name}; + + die "a codeblock must be provided at $caller->[1] line $caller->[2].\n" + unless $out{code}; + + return { %props, %out, %input }; +} + +{ + my %ROOT_BUILDS; + my @BUILD_STACK; + + sub root_build { $ROOT_BUILDS{$_[0]} } + sub current_build { @BUILD_STACK ? $BUILD_STACK[-1] : undef } + sub build_stack { @BUILD_STACK } + + sub init_root { + my ($pkg, %args) = @_; + $ROOT_BUILDS{$pkg} ||= Test2::Workflow::Build->new( + name => $pkg, + flat => 1, + iso => 0, + async => 0, + is_root => 1, + %args, + ); + + return $ROOT_BUILDS{$pkg}; + } + + sub build { + my %params = @_; + my $args = parse_args(%params); + + my $build = Test2::Workflow::Build->new(%$args); + + return $build if $args->{skip}; + + push @BUILD_STACK => $build; + + my ($ok, $err); + my $events = intercept { + my $todo = $args->{todo} ? Test2::Todo->new(reason => $args->{todo}) : undef; + $ok = eval { $args->{code}->(); 1 }; + $err = $@; + $todo->end if $todo; + }; + + # Clear the stash + $build->{stash} = []; + $build->set_events($events); + + pop @BUILD_STACK; + + unless($ok) { + my $hub = Test2::API::test2_stack->top; + my $count = @$events; + my $list = $count + ? "Overview of unseen events:\n" . join "" => map " " . blessed($_) . " " . $_->trace($hub)->debug . "\n", @$events + : ""; + die <<" EOT"; +Exception in build '$args->{name}' with $count unseen event(s). +$err +$list + EOT + } + + return $build; + } +} + +1; + +__END__ + +=pod + +=encoding UTF-8 + +=head1 NAME + +Test2::Workflow - A test workflow is a way of structuring tests using +composable units. + +=head1 DESCRIPTION + +A test workflow is a way of structuring tests using composable units. A well +known example of a test workflow is L. RSPEC is +implemented using Test2::Workflow in L along with several +extensions. + +=head1 IMPORTANT CONCEPTS + +=head2 BUILD + +L + +A Build is used to compose tasks. Usually a build object is pushed to the stack +before running code that adds tasks to the build. Once the build sub is +complete the build is popped and returned. Usually a build is converted into a +root task or task group. + +=head2 RUNNER + +L + +A runner takes the composed tasks and executes them in the proper order. + +=head2 TASK + +L + +A task is a unit of work to accomplish. There are 2 main types of task. + +=head3 ACTION + +An action is the most simple unit used in composition. An action is essentially +a name and a codeblock to run. + +=head3 GROUP + +A group is a task that is composed of other tasks. + +=head1 EXPORTS + +All exports are optional, you must request the ones you want. + +=over 4 + +=item $parsed = parse_args(args => \@args) + +=item $parsed = parse_args(args => \@args, level => $L) + +=item $parsed = parse_args(args => \@args, caller => [caller($L)]) + +This will parse a "typical" task builders arguments. The C<@args> array MUST +contain a name (plain scalar containing text) and also a single CODE reference. +The C<@args> array MAY also contain any quantity of line numbers or hashrefs. +The resulting data structure will be a single hashref with all the provided +hashrefs squashed together, and the 'name', 'code', 'lines' and 'frame' keys +set from other arguments. + + { + # All hashrefs from @args get squashed together: + %squashed_input_hashref_data, + + # @args must have exactly 1 plaintext scalar that is not a number, it + # is considered the name: + name => 'name from input args' + + # Integer values are treated as line numbers + lines => [ 35, 44 ], + + # Exactly 1 coderef must be provided in @args: + code => \&some_code, + + # 'frame' contains the 'caller' data. This may be passed in directly, + # obtained from the 'level' parameter, or automatically deduced. + frame => ['A::Package', 'a_file.pm', 42, ...], + } + +=item $build = init_root($pkg, %args) + +This will initialize (or return the existing) a build for the specified +package. C<%args> get passed into the L constructor. +This uses the following defaults (which can be overridden using C<%args>): + + name => $pkg, + flat => 1, + iso => 0, + async => 0, + is_root => 1, + +Note that C<%args> is completely ignored if the package build has already been +initialized. + +=item $build = root_build($pkg) + +This will return the root build for the specified package. + +=item $build = current_build() + +This will return the build currently at the top of the build stack (or undef). + +=item $build = build($name, \%params, sub { ... }) + +This will push a new build object onto the build stash then run the provided +codeblock. Once the codeblock has finished running the build will be popped off +the stack and returned. + +See C for details about argument processing. + +=back + +=head1 SEE ALSO + +=over 4 + +=item Test2::Tools::Spec + +L is an implementation of RSPEC using this library. + +=back + +=head1 SOURCE + +The source code repository for Test2-Workflow can be found at +F. + +=head1 MAINTAINERS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 AUTHORS + +=over 4 + +=item Chad Granum Eexodist@cpan.orgE + +=back + +=head1 COPYRIGHT + +Copyright Chad Granum Eexodist7@gmail.comE. + +This program is free software; you can redistribute it and/or +modify it under the same terms as Perl itself. + +See F + +=cut + diff --git a/git/usr/share/perl5/core_perl/Text/Abbrev.pm b/git/usr/share/perl5/core_perl/Text/Abbrev.pm new file mode 100644 index 0000000000000000000000000000000000000000..3c179697f9f401c28245d46fc72a2e0f8f159936 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Text/Abbrev.pm @@ -0,0 +1,84 @@ +package Text::Abbrev; +require 5.005; # Probably works on earlier versions too. +require Exporter; + +our $VERSION = '1.02'; + +=head1 NAME + +Text::Abbrev - abbrev - create an abbreviation table from a list + +=head1 SYNOPSIS + + use Text::Abbrev; + abbrev $hashref, LIST + + +=head1 DESCRIPTION + +Stores all unambiguous truncations of each element of LIST +as keys in the associative array referenced by C<$hashref>. +The values are the original list elements. + +=head1 EXAMPLE + + $hashref = abbrev qw(list edit send abort gripe); + + %hash = abbrev qw(list edit send abort gripe); + + abbrev $hashref, qw(list edit send abort gripe); + + abbrev(*hash, qw(list edit send abort gripe)); + +=cut + +@ISA = qw(Exporter); +@EXPORT = qw(abbrev); + +# Usage: +# abbrev \%foo, LIST; +# ... +# $long = $foo{$short}; + +sub abbrev { + my ($word, $hashref, $glob, %table, $returnvoid); + + @_ or return; # So we don't autovivify onto @_ and trigger warning + if (ref($_[0])) { # hash reference preferably + $hashref = shift; + $returnvoid = 1; + } elsif (ref \$_[0] eq 'GLOB') { # is actually a glob (deprecated) + $hashref = \%{shift()}; + $returnvoid = 1; + } + %{$hashref} = (); + + WORD: foreach $word (@_) { + for (my $len = (length $word) - 1; $len > 0; --$len) { + my $abbrev = substr($word,0,$len); + my $seen = ++$table{$abbrev}; + if ($seen == 1) { # We're the first word so far to have + # this abbreviation. + $hashref->{$abbrev} = $word; + } elsif ($seen == 2) { # We're the second word to have this + # abbreviation, so we can't use it. + delete $hashref->{$abbrev}; + } else { # We're the third word to have this + # abbreviation, so skip to the next word. + next WORD; + } + } + } + # Non-abbreviations always get entered, even if they aren't unique + foreach $word (@_) { + $hashref->{$word} = $word; + } + return if $returnvoid; + if (wantarray) { + %{$hashref}; + } else { + $hashref; + } +} + +1; diff --git a/git/usr/share/perl5/core_perl/Text/Balanced.pm b/git/usr/share/perl5/core_perl/Text/Balanced.pm new file mode 100644 index 0000000000000000000000000000000000000000..49f3d8926c738dadaf2d70076ecdd33b5353b194 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Text/Balanced.pm @@ -0,0 +1,2434 @@ +# Copyright (C) 1997-2001 Damian Conway. All rights reserved. +# Copyright (C) 2009 Adam Kennedy. +# Copyright (C) 2015, 2022 Steve Hay and other contributors. All rights +# reserved. + +# This module is free software; you can redistribute it and/or modify it under +# the same terms as Perl itself, i.e. under the terms of either the GNU General +# Public License or the Artistic License, as specified in the F file. + +package Text::Balanced; + +# EXTRACT VARIOUSLY DELIMITED TEXT SEQUENCES FROM STRINGS. +# FOR FULL DOCUMENTATION SEE Balanced.pod + +use 5.008001; +use strict; +use Exporter (); + +use vars qw { $VERSION @ISA %EXPORT_TAGS }; +BEGIN { + $VERSION = '2.06'; + @ISA = 'Exporter'; + %EXPORT_TAGS = ( + ALL => [ qw{ + &extract_delimited + &extract_bracketed + &extract_quotelike + &extract_codeblock + &extract_variable + &extract_tagged + &extract_multiple + &gen_delimited_pat + &gen_extract_tagged + &delimited_pat + } ], + ); +} + +Exporter::export_ok_tags('ALL'); + +our $RE_PREREGEX_PAT = qr#( + [!=]~ + | split|grep|map + | not|and|or|xor +)#x; +our $RE_EXPR_PAT = qr#( + (?:\*\*|&&|\|\||<<|>>|//|[-+*x%^&|.])=? + | /(?:[^/]) + | =(?!>) + | return + | [\(\[] +)#x; +our $RE_NUM = qr/\s*[+\-.0-9][+\-.0-9e]*/i; # numerical constant + +our %ref2slashvalid; # is quotelike /.../ pattern valid here for given textref? +our %ref2qmarkvalid; # is quotelike ?...? pattern valid here for given textref? + +# HANDLE RETURN VALUES IN VARIOUS CONTEXTS + +sub _failmsg { + my ($message, $pos) = @_; + $@ = bless { + error => $message, + pos => $pos, + }, 'Text::Balanced::ErrorMsg'; +} + +sub _fail { + my ($wantarray, $textref, $message, $pos) = @_; + _failmsg $message, $pos if $message; + return (undef, $$textref, undef) if $wantarray; + return; +} + +sub _succeed { + $@ = undef; + my ($wantarray,$textref) = splice @_, 0, 2; + my ($extrapos, $extralen) = @_ > 18 + ? splice(@_, -2, 2) + : (0, 0); + my ($startlen, $oppos) = @_[5,6]; + my $remainderpos = $_[2]; + if ( $wantarray ) { + my @res; + while (my ($from, $len) = splice @_, 0, 2) { + push @res, substr($$textref, $from, $len); + } + if ( $extralen ) { # CORRECT FILLET + my $extra = substr($res[0], $extrapos-$oppos, $extralen, "\n"); + $res[1] = "$extra$res[1]"; + eval { substr($$textref,$remainderpos,0) = $extra; + substr($$textref,$extrapos,$extralen,"\n")} ; + #REARRANGE HERE DOC AND FILLET IF POSSIBLE + pos($$textref) = $remainderpos-$extralen+1; # RESET \G + } else { + pos($$textref) = $remainderpos; # RESET \G + } + return @res; + } else { + my $match = substr($$textref,$_[0],$_[1]); + substr($match,$extrapos-$_[0]-$startlen,$extralen,"") if $extralen; + my $extra = $extralen + ? substr($$textref, $extrapos, $extralen)."\n" : ""; + eval {substr($$textref,$_[4],$_[1]+$_[5])=$extra} ; #CHOP OUT PREFIX & MATCH, IF POSSIBLE + pos($$textref) = $_[4]; # RESET \G + return $match; + } +} + +# BUILD A PATTERN MATCHING A SIMPLE DELIMITED STRING +## no critic (Subroutines::ProhibitSubroutinePrototypes) + +sub gen_delimited_pat($;$) # ($delimiters;$escapes) +{ + my ($dels, $escs) = @_; + return "" unless $dels =~ /\S/; + $escs = '\\' unless $escs; + $escs .= substr($escs,-1) x (length($dels)-length($escs)); + my @pat = (); + my $i; + for ($i=0; $i\0-\377/[[(({{</; + my $posbug = pos; + $ldel = join('|', map { quotemeta $_ } split('', $ldel)); + $rdel = join('|', map { quotemeta $_ } split('', $rdel)); + pos = $posbug; + @{ $eb_delim_cache{$ldel_orig} = [ + qr/\G($ldel)/, $qdel && qr/\G([$qdel])/, $quotelike, qr/\G($rdel)/ + ] }; +} +sub extract_bracketed (;$$$) +{ + my $textref = defined $_[0] ? \$_[0] : \$_; + $ref2slashvalid{$textref} = 1, $ref2qmarkvalid{$textref} = 0 if !pos($$textref); # reset + my $ldel = defined $_[1] ? $_[1] : '{([<'; + my $pre = defined $_[2] ? qr/\G$_[2]/ : qr/\G\s*/; + my $wantarray = wantarray; + my @ret = _eb_delims($ldel); + unless (@ret) + { + return _fail $wantarray, $textref, + "Did not find a suitable bracket in delimiter: \"$_[1]\"", + 0; + } + + my $startpos = pos $$textref || 0; + my @match = _match_bracketed($textref, $pre, @ret); + + return _fail ($wantarray, $textref) unless @match; + + return _succeed ( $wantarray, $textref, + $match[2], $match[5]+2, # MATCH + @match[8,9], # REMAINDER + @match[0,1], # PREFIX + ); +} + +sub _match_bracketed # $textref, $pre, $ldel, $qdel, $quotelike, $rdel +{ + my ($textref, $pre, $ldel, $qdel, $quotelike, $rdel) = @_; + my ($startpos, $ldelpos, $endpos) = (pos $$textref = pos $$textref||0); + unless ($$textref =~ m/$pre/gc) + { + _failmsg "Did not find prefix: /$pre/", $startpos; + return; + } + + $ldelpos = pos $$textref; + + unless ($$textref =~ m/$ldel/gc) + { + _failmsg "Did not find opening bracket after prefix: \"$pre\"", + pos $$textref; + pos $$textref = $startpos; + return; + } + + my @nesting = ( $1 ); + my $textlen = length $$textref; + while (pos $$textref < $textlen) + { + next if $$textref =~ m/\G\\./gcs; + + if ($$textref =~ m/$ldel/gc) + { + push @nesting, $1; + } + elsif ($$textref =~ m/$rdel/gc) + { + my ($found, $brackettype) = ($1, $1); + if ($#nesting < 0) + { + _failmsg "Unmatched closing bracket: \"$found\"", + pos $$textref; + pos $$textref = $startpos; + return; + } + my $expected = pop(@nesting); + $expected =~ tr/({[/; + if ($expected ne $brackettype) + { + _failmsg qq{Mismatched closing bracket: expected "$expected" but found "$found"}, + pos $$textref; + pos $$textref = $startpos; + return; + } + last if $#nesting < 0; + } + elsif ($qdel && $$textref =~ m/$qdel/gc) + { + $$textref =~ m/\G[^\\$1]*(?:\\.[^\\$1]*)*(\Q$1\E)/gsc and next; + _failmsg "Unmatched embedded quote ($1)", + pos $$textref; + pos $$textref = $startpos; + return; + } + elsif ($quotelike && _match_quotelike($textref,qr/\G()/,$ref2slashvalid{$textref},$ref2qmarkvalid{$textref})) + { + $ref2slashvalid{$textref} = $ref2qmarkvalid{$textref} = 1; # back-compat + next; + } + + else { $$textref =~ m/\G(?:[a-zA-Z0-9]+|.)/gcs } + } + if ($#nesting>=0) + { + _failmsg "Unmatched opening bracket(s): " + . join("..",@nesting)."..", + pos $$textref; + pos $$textref = $startpos; + return; + } + + $endpos = pos $$textref; + + return ( + $startpos, $ldelpos-$startpos, # PREFIX + $ldelpos, 1, # OPENING BRACKET + $ldelpos+1, $endpos-$ldelpos-2, # CONTENTS + $endpos-1, 1, # CLOSING BRACKET + $endpos, length($$textref)-$endpos, # REMAINDER + ); +} + +sub _revbracket($) +{ + my $brack = reverse $_[0]; + $brack =~ tr/[({/; + return $brack; +} + +my $XMLNAME = q{[a-zA-Z_:][a-zA-Z0-9_:.-]*}; + +my $et_default_ldel = '<\w+(?:' . gen_delimited_pat(q{'"}) . '|[^>])*>'; +sub extract_tagged (;$$$$$) # ($text, $opentag, $closetag, $pre, \%options) +{ + my $textref = defined $_[0] ? \$_[0] : \$_; + $ref2slashvalid{$textref} = 1, $ref2qmarkvalid{$textref} = 0 if !pos($$textref); # reset + my $ldel = $_[1]; + my $rdel = $_[2]; + my $pre = defined $_[3] ? qr/\G$_[3]/ : qr/\G\s*/; + my %options = defined $_[4] ? %{$_[4]} : (); + my $omode = defined $options{fail} ? $options{fail} : ''; + my $bad = ref($options{reject}) eq 'ARRAY' ? join('|', @{$options{reject}}) + : defined($options{reject}) ? $options{reject} + : '' + ; + my $ignore = ref($options{ignore}) eq 'ARRAY' ? join('|', @{$options{ignore}}) + : defined($options{ignore}) ? $options{ignore} + : '' + ; + + $ldel = $et_default_ldel if !defined $ldel; + $@ = undef; + + my @match = _match_tagged($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore); + + return _fail(wantarray, $textref) unless @match; + return _succeed wantarray, $textref, + $match[2], $match[3]+$match[5]+$match[7], # MATCH + @match[8..9,0..1,2..7]; # REM, PRE, BITS +} + +sub _match_tagged # ($$$$$$$) +{ + my ($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore) = @_; + my $rdelspec; + + my ($startpos, $opentagpos, $textpos, $parapos, $closetagpos, $endpos) = ( pos($$textref) = pos($$textref)||0 ); + + unless ($$textref =~ m/$pre/gc) + { + _failmsg "Did not find prefix: /$pre/", pos $$textref; + goto failed; + } + + $opentagpos = pos($$textref); + + unless ($$textref =~ m/\G$ldel/gc) + { + _failmsg "Did not find opening tag: /$ldel/", pos $$textref; + goto failed; + } + + $textpos = pos($$textref); + + if (!defined $rdel) + { + $rdelspec = substr($$textref, $-[0], $+[0] - $-[0]); + unless ($rdelspec =~ s/\A([[(<{]+)($XMLNAME).*/ quotemeta "$1\/$2". _revbracket($1) /oes) + { + _failmsg "Unable to construct closing tag to match: $rdel", + pos $$textref; + goto failed; + } + } + else + { + ## no critic (BuiltinFunctions::ProhibitStringyEval) + $rdelspec = eval "qq{$rdel}" || do { + my $del; + for (qw,~ ! ^ & * ) _ + - = } ] : " ; ' > . ? / | ',) + { next if $rdel =~ /\Q$_/; $del = $_; last } + unless ($del) { + use Carp; + croak "Can't interpolate right delimiter $rdel" + } + eval "qq$del$rdel$del"; + }; + } + + while (pos($$textref) < length($$textref)) + { + next if $$textref =~ m/\G\\./gc; + + if ($$textref =~ m/\G(\n[ \t]*\n)/gc ) + { + $parapos = pos($$textref) - length($1) + unless defined $parapos; + } + elsif ($$textref =~ m/\G($rdelspec)/gc ) + { + $closetagpos = pos($$textref)-length($1); + goto matched; + } + elsif ($ignore && $$textref =~ m/\G(?:$ignore)/gc) + { + next; + } + elsif ($bad && $$textref =~ m/\G($bad)/gcs) + { + pos($$textref) -= length($1); # CUT OFF WHATEVER CAUSED THE SHORTNESS + goto short if ($omode eq 'PARA' || $omode eq 'MAX'); + _failmsg "Found invalid nested tag: $1", pos $$textref; + goto failed; + } + elsif ($$textref =~ m/\G($ldel)/gc) + { + my $tag = $1; + pos($$textref) -= length($tag); # REWIND TO NESTED TAG + unless (_match_tagged(@_)) # MATCH NESTED TAG + { + goto short if $omode eq 'PARA' || $omode eq 'MAX'; + _failmsg "Found unbalanced nested tag: $tag", + pos $$textref; + goto failed; + } + } + else { $$textref =~ m/./gcs } + } + +short: + $closetagpos = pos($$textref); + goto matched if $omode eq 'MAX'; + goto failed unless $omode eq 'PARA'; + + if (defined $parapos) { pos($$textref) = $parapos } + else { $parapos = pos($$textref) } + + return ( + $startpos, $opentagpos-$startpos, # PREFIX + $opentagpos, $textpos-$opentagpos, # OPENING TAG + $textpos, $parapos-$textpos, # TEXT + $parapos, 0, # NO CLOSING TAG + $parapos, length($$textref)-$parapos, # REMAINDER + ); + +matched: + $endpos = pos($$textref); + return ( + $startpos, $opentagpos-$startpos, # PREFIX + $opentagpos, $textpos-$opentagpos, # OPENING TAG + $textpos, $closetagpos-$textpos, # TEXT + $closetagpos, $endpos-$closetagpos, # CLOSING TAG + $endpos, length($$textref)-$endpos, # REMAINDER + ); + +failed: + _failmsg "Did not find closing tag", pos $$textref unless $@; + pos($$textref) = $startpos; + return; +} + +sub extract_variable (;$$) +{ + my $textref = defined $_[0] ? \$_[0] : \$_; + return ("","","") unless defined $$textref; + $ref2slashvalid{$textref} = 1, $ref2qmarkvalid{$textref} = 0 if !pos($$textref); # reset + my $pre = defined $_[1] ? qr/\G$_[1]/ : qr/\G\s*/; + + my @match = _match_variable($textref,$pre); + + return _fail wantarray, $textref unless @match; + + return _succeed wantarray, $textref, + @match[2..3,4..5,0..1]; # MATCH, REMAINDER, PREFIX +} + +sub _match_variable +{ +# $# +# $^ +# $$ + my ($textref, $pre) = @_; + my $startpos = pos($$textref) = pos($$textref)||0; + unless ($$textref =~ m/$pre/gc) + { + _failmsg "Did not find prefix: /$pre/", pos $$textref; + return; + } + my $varpos = pos($$textref); + unless ($$textref =~ m{\G\$\s*(?!::)(\d+|[][&`'+*./|,";%=~:?!\@<>()-]|\^[a-z]?)}gci) + { + unless ($$textref =~ m/\G((\$#?|[*\@\%]|\\&)+)/gc) + { + _failmsg "Did not find leading dereferencer", pos $$textref; + pos $$textref = $startpos; + return; + } + my $deref = $1; + + unless ($$textref =~ m/\G\s*(?:::|')?(?:[_a-z]\w*(?:::|'))*[_a-z]\w*/gci + or _match_codeblock($textref, qr/\G()/, '\{', qr/\G\s*(\})/, '\{', '\}', 0, 1) + or $deref eq '$#' or $deref eq '$$' + or pos($$textref) == length $$textref ) + { + _failmsg "Bad identifier after dereferencer", pos $$textref; + pos $$textref = $startpos; + return; + } + } + + while (1) + { + next if $$textref =~ m/\G\s*(?:->)?\s*[{]\w+[}]/gc; + next if _match_codeblock($textref, + qr/\G\s*->\s*(?:[_a-zA-Z]\w+\s*)?/, + qr/[({[]/, qr/\G\s*([)}\]])/, + qr/[({[]/, qr/[)}\]]/, 0, 1); + next if _match_codeblock($textref, + qr/\G\s*/, qr/[{[]/, qr/\G\s*([}\]])/, + qr/[{[]/, qr/[}\]]/, 0, 1); + next if _match_variable($textref,qr/\G\s*->\s*/); + next if $$textref =~ m/\G\s*->\s*\w+(?![{([])/gc; + last; + } + $ref2slashvalid{$textref} = $ref2qmarkvalid{$textref} = 0; + + my $endpos = pos($$textref); + return ($startpos, $varpos-$startpos, + $varpos, $endpos-$varpos, + $endpos, length($$textref)-$endpos + ); +} + +my %ec_delim_cache; +sub _ec_delims { + my ($ldel_inner, $ldel_outer) = @_; + return @{ $ec_delim_cache{$ldel_outer}{$ldel_inner} } + if $ec_delim_cache{$ldel_outer}{$ldel_inner}; + my $rdel_inner = $ldel_inner; + my $rdel_outer = $ldel_outer; + my $posbug = pos; + for ($ldel_inner, $ldel_outer) { tr/[]()<>{}\0-\377/[[((<<{{/ds } + for ($rdel_inner, $rdel_outer) { tr/[]()<>{}\0-\377/]]))>>}}/ds } + for ($ldel_inner, $ldel_outer, $rdel_inner, $rdel_outer) + { + $_ = '('.join('|',map { quotemeta $_ } split('',$_)).')' + } + pos = $posbug; + @{ $ec_delim_cache{$ldel_outer}{$ldel_inner} = [ + $ldel_outer, qr/\G\s*($rdel_outer)/, $ldel_inner, $rdel_inner + ] }; +} +sub extract_codeblock (;$$$$$) +{ + my $textref = defined $_[0] ? \$_[0] : \$_; + $ref2slashvalid{$textref} = 1, $ref2qmarkvalid{$textref} = 0 if !pos($$textref); # reset + my $wantarray = wantarray; + my $ldel_inner = defined $_[1] ? $_[1] : '{'; + my $pre = !defined $_[2] ? qr/\G\s*/ : qr/\G$_[2]/; + my $ldel_outer = defined $_[3] ? $_[3] : $ldel_inner; + my $rd = $_[4]; + my @delims = _ec_delims($ldel_inner, $ldel_outer); + + my @match = _match_codeblock($textref, $pre, @delims, $rd, 1); + return _fail($wantarray, $textref) unless @match; + return _succeed($wantarray, $textref, + @match[2..3,4..5,0..1] # MATCH, REMAINDER, PREFIX + ); +} + +sub _match_codeblock +{ + my ($textref, $pre, $ldel_outer, $rdel_outer, $ldel_inner, $rdel_inner, $rd, $no_backcompat) = @_; + $rdel_outer = qr/\G\s*($rdel_outer)/ if !$no_backcompat; # Switch calls this func directly + my $startpos = pos($$textref) = pos($$textref) || 0; + unless ($$textref =~ m/$pre/gc) + { + _failmsg qq{Did not match prefix /$pre/ at"} . + substr($$textref,pos($$textref),20) . + q{..."}, + pos $$textref; + return; + } + my $codepos = pos($$textref); + unless ($$textref =~ m/\G($ldel_outer)/gc) # OUTERMOST DELIMITER + { + _failmsg qq{Did not find expected opening bracket at "} . + substr($$textref,pos($$textref),20) . + q{..."}, + pos $$textref; + pos $$textref = $startpos; + return; + } + my $closing = $1; + $closing =~ tr/([<{/)]>}/; + my $matched; + $ref2slashvalid{$textref} = 1, $ref2qmarkvalid{$textref} = 0 + if !pos($$textref) or !defined $ref2slashvalid{$textref}; # default, or reset + while (pos($$textref) < length($$textref)) + { + if ($rd && $$textref =~ m#\G(\Q(?)\E|\Q(s?)\E|\Q(s)\E)#gc) + { + $ref2slashvalid{$textref} = $ref2qmarkvalid{$textref} = 0; + next; + } + + if ($$textref =~ m/\G\s*#.*/gc) + { + next; + } + + if ($$textref =~ m/$rdel_outer/gc) + { + unless ($matched = ($closing && $1 eq $closing) ) + { + next if $1 eq '>'; # MIGHT BE A "LESS THAN" + _failmsg q{Mismatched closing bracket at "} . + substr($$textref,pos($$textref),20) . + qq{...". Expected '$closing'}, + pos $$textref; + } + last; + } + + if (_match_variable($textref,qr/\G\s*/) || + _match_quotelike($textref,qr/\G\s*/,$ref2slashvalid{$textref},$ref2qmarkvalid{$textref}) ) + { + $ref2slashvalid{$textref} = $ref2qmarkvalid{$textref} = 0; + next; + } + + if ($$textref =~ m#\G\s*(?!$ldel_inner)(?:$RE_PREREGEX_PAT|$RE_EXPR_PAT)#gc) + { + $ref2slashvalid{$textref} = $ref2qmarkvalid{$textref} = 1; + next; + } + + if ( _match_codeblock($textref, qr/\G\s*/, $ldel_inner, qr/\G\s*($rdel_inner)/, $ldel_inner, $rdel_inner, $rd, 1) ) + { + $ref2slashvalid{$textref} = $ref2qmarkvalid{$textref} = 1; + next; + } + + if ($$textref =~ m/\G\s*$ldel_outer/gc) + { + _failmsg q{Improperly nested codeblock at "} . + substr($$textref,pos($$textref),20) . + q{..."}, + pos $$textref; + last; + } + + $ref2slashvalid{$textref} = $ref2qmarkvalid{$textref} = 0; + $$textref =~ m/\G\s*(\w+|[-=>]>|.|\Z)/gc; + } + continue { $@ = undef } + + unless ($matched) + { + _failmsg 'No match found for opening bracket', pos $$textref + unless $@; + return; + } + + $ref2slashvalid{$textref} = $ref2qmarkvalid{$textref} = undef; + my $endpos = pos($$textref); + return ( $startpos, $codepos-$startpos, + $codepos, $endpos-$codepos, + $endpos, length($$textref)-$endpos, + ); +} + + +my %mods = ( + 'none' => '[cgimsox]*', + 'm' => '[cgimsox]*', + 's' => '[cegimsox]*', + 'tr' => '[cds]*', + 'y' => '[cds]*', + 'qq' => '', + 'qx' => '', + 'qw' => '', + 'qr' => '[imsx]*', + 'q' => '', +); + +sub extract_quotelike (;$$) +{ + my $textref = $_[0] ? \$_[0] : \$_; + $ref2slashvalid{$textref} = 1, $ref2qmarkvalid{$textref} = 0 if !pos($$textref); # reset + my $wantarray = wantarray; + my $pre = defined $_[1] ? qr/\G$_[1]/ : qr/\G\s*/; + + my @match = _match_quotelike($textref,$pre,$ref2slashvalid{$textref},$ref2qmarkvalid{$textref}); + return _fail($wantarray, $textref) unless @match; + return _succeed($wantarray, $textref, + $match[2], $match[18]-$match[2], # MATCH + @match[18,19], # REMAINDER + @match[0,1], # PREFIX + @match[2..17], # THE BITS + @match[20,21], # ANY FILLET? + ); +}; + +my %maybe_quote = map +($_=>1), qw(" ' `); +sub _match_quotelike +{ + my ($textref, $pre, $allow_slash_match, $allow_qmark_match) = @_; + $ref2slashvalid{$textref} = 1, $ref2qmarkvalid{$textref} = 0 + if !pos($$textref) or !defined $ref2slashvalid{$textref}; # default, or reset + + my ($textlen,$startpos, + $preld1pos,$ld1pos,$str1pos,$rd1pos, + $preld2pos,$ld2pos,$str2pos,$rd2pos, + $modpos) = ( length($$textref), pos($$textref) = pos($$textref) || 0 ); + + unless ($$textref =~ m/$pre/gc) + { + _failmsg qq{Did not find prefix /$pre/ at "} . + substr($$textref, pos($$textref), 20) . + q{..."}, + pos $$textref; + return; + } + my $oppos = pos($$textref); + my $initial = substr($$textref,$oppos,1); + if ($initial && $maybe_quote{$initial} + || $allow_slash_match && $initial eq '/' + || $allow_qmark_match && $initial eq '?') + { + unless ($$textref =~ m/\G \Q$initial\E [^\\$initial]* (\\.[^\\$initial]*)* \Q$initial\E /gcsx) + { + _failmsg qq{Did not find closing delimiter to match '$initial' at "} . + substr($$textref, $oppos, 20) . + q{..."}, + pos $$textref; + pos $$textref = $startpos; + return; + } + $modpos= pos($$textref); + $rd1pos = $modpos-1; + + if ($initial eq '/' || $initial eq '?') + { + $$textref =~ m/\G$mods{none}/gc + } + + my $endpos = pos($$textref); + $ref2qmarkvalid{$textref} = $ref2slashvalid{$textref} = 0; + return ( + $startpos, $oppos-$startpos, # PREFIX + $oppos, 0, # NO OPERATOR + $oppos, 1, # LEFT DEL + $oppos+1, $rd1pos-$oppos-1, # STR/PAT + $rd1pos, 1, # RIGHT DEL + $modpos, 0, # NO 2ND LDEL + $modpos, 0, # NO 2ND STR + $modpos, 0, # NO 2ND RDEL + $modpos, $endpos-$modpos, # MODIFIERS + $endpos, $textlen-$endpos, # REMAINDER + ); + } + + unless ($$textref =~ m{\G(\b(?:m|s|qq|qx|qw|q|qr|tr|y)\b(?=\s*\S)|<<(?=[a-zA-Z]|\s*['"`;,]))}gc) + { + _failmsg q{No quotelike operator found after prefix at "} . + substr($$textref, pos($$textref), 20) . + q{..."}, + pos $$textref; + pos $$textref = $startpos; + return; + } + + my $op = $1; + $preld1pos = pos($$textref); + if ($op eq '<<') { + $ld1pos = pos($$textref); + my $label; + if ($$textref =~ m{\G([A-Za-z_]\w*)}gc) { + $label = $1; + } + elsif ($$textref =~ m{ \G ' ([^'\\]* (?:\\.[^'\\]*)*) ' + | \G " ([^"\\]* (?:\\.[^"\\]*)*) " + | \G ` ([^`\\]* (?:\\.[^`\\]*)*) ` + }gcsx) { + $label = $+; + } + else { + $label = ""; + } + my $extrapos = pos($$textref); + $$textref =~ m{.*\n}gc; + $str1pos = pos($$textref)--; + unless ($$textref =~ m{.*?\n(?=\Q$label\E\n)}gc) { + _failmsg qq{Missing here doc terminator ('$label') after "} . + substr($$textref, $startpos, 20) . + q{..."}, + pos $$textref; + pos $$textref = $startpos; + return; + } + $rd1pos = pos($$textref); + $$textref =~ m{\Q$label\E\n}gc; + $ld2pos = pos($$textref); + $ref2qmarkvalid{$textref} = $ref2slashvalid{$textref} = 0; + return ( + $startpos, $oppos-$startpos, # PREFIX + $oppos, length($op), # OPERATOR + $ld1pos, $extrapos-$ld1pos, # LEFT DEL + $str1pos, $rd1pos-$str1pos, # STR/PAT + $rd1pos, $ld2pos-$rd1pos, # RIGHT DEL + $ld2pos, 0, # NO 2ND LDEL + $ld2pos, 0, # NO 2ND STR + $ld2pos, 0, # NO 2ND RDEL + $ld2pos, 0, # NO MODIFIERS + $ld2pos, $textlen-$ld2pos, # REMAINDER + $extrapos, $str1pos-$extrapos, # FILLETED BIT + ); + } + + $$textref =~ m/\G\s*/gc; + $ld1pos = pos($$textref); + $str1pos = $ld1pos+1; + + if ($$textref !~ m/\G(\S)/gc) # SHOULD USE LOOKAHEAD + { + _failmsg "No block delimiter found after quotelike $op", + pos $$textref; + pos $$textref = $startpos; + return; + } + elsif (substr($$textref, $ld1pos, 2) eq '=>') + { + _failmsg "quotelike $op was actually quoted by '=>'", + pos $$textref; + pos $$textref = $startpos; + return; + } + pos($$textref) = $ld1pos; # HAVE TO DO THIS BECAUSE LOOKAHEAD BROKEN + my ($ldel1, $rdel1) = ("\Q$1","\Q$1"); + if ($ldel1 =~ /[[(<{]/) + { + $rdel1 =~ tr/[({/; + defined(_match_bracketed($textref,qr/\G/,qr/\G($ldel1)/,"","",qr/\G($rdel1)/)) + || do { pos $$textref = $startpos; return }; + $ld2pos = pos($$textref); + $rd1pos = $ld2pos-1; + } + else + { + $$textref =~ /\G$ldel1[^\\$ldel1]*(\\.[^\\$ldel1]*)*$ldel1/gcs + || do { pos $$textref = $startpos; return }; + $ld2pos = $rd1pos = pos($$textref)-1; + } + + my $second_arg = $op =~ /s|tr|y/ ? 1 : 0; + if ($second_arg) + { + my ($ldel2, $rdel2); + if ($ldel1 =~ /[[(<{]/) + { + unless ($$textref =~ /\G\s*(\S)/gc) # SHOULD USE LOOKAHEAD + { + _failmsg "Missing second block for quotelike $op", + pos $$textref; + pos $$textref = $startpos; + return; + } + $ldel2 = $rdel2 = "\Q$1"; + $rdel2 =~ tr/[({/; + } + else + { + $ldel2 = $rdel2 = $ldel1; + } + $str2pos = $ld2pos+1; + + if ($ldel2 =~ /[[(<{]/) + { + pos($$textref)--; # OVERCOME BROKEN LOOKAHEAD + defined(_match_bracketed($textref,qr/\G/,qr/\G($ldel2)/,"","",qr/\G($rdel2)/)) + || do { pos $$textref = $startpos; return }; + } + else + { + $$textref =~ /[^\\$ldel2]*(\\.[^\\$ldel2]*)*$ldel2/gcs + || do { pos $$textref = $startpos; return }; + } + $rd2pos = pos($$textref)-1; + } + else + { + $ld2pos = $str2pos = $rd2pos = $rd1pos; + } + + $modpos = pos $$textref; + + $$textref =~ m/\G($mods{$op})/gc; + my $endpos = pos $$textref; + $ref2qmarkvalid{$textref} = $ref2slashvalid{$textref} = undef; + + return ( + $startpos, $oppos-$startpos, # PREFIX + $oppos, length($op), # OPERATOR + $ld1pos, 1, # LEFT DEL + $str1pos, $rd1pos-$str1pos, # STR/PAT + $rd1pos, 1, # RIGHT DEL + $ld2pos, $second_arg, # 2ND LDEL (MAYBE) + $str2pos, $rd2pos-$str2pos, # 2ND STR (MAYBE) + $rd2pos, $second_arg, # 2ND RDEL (MAYBE) + $modpos, $endpos-$modpos, # MODIFIERS + $endpos, $textlen-$endpos, # REMAINDER + ); +} + +my $def_func = [ + sub { extract_variable($_[0], '') }, + sub { extract_quotelike($_[0],'') }, + sub { extract_codeblock($_[0],'{}','') }, +]; +my %ref_not_regex = map +($_=>1), qw(CODE Text::Balanced::Extractor); + +sub _update_patvalid { + my ($textref, $text) = @_; + if ($ref2slashvalid{$textref} && $text =~ m/(?:$RE_NUM|[\)\]])\s*$/) + { + $ref2slashvalid{$textref} = $ref2qmarkvalid{$textref} = 0; + } elsif (!$ref2slashvalid{$textref} && $text =~ m/$RE_PREREGEX_PAT\s*$/) + { + $ref2slashvalid{$textref} = $ref2qmarkvalid{$textref} = 1; + } elsif (!$ref2slashvalid{$textref} && $text =~ m/$RE_EXPR_PAT\s*$/) + { + $ref2slashvalid{$textref} = 1; + $ref2qmarkvalid{$textref} = 0; + } +} +sub extract_multiple (;$$$$) # ($text, $functions_ref, $max_fields, $ignoreunknown) +{ + my $textref = defined($_[0]) ? \$_[0] : \$_; + $ref2slashvalid{$textref} = 1, $ref2qmarkvalid{$textref} = 0 if !pos($$textref); # reset + my $posbug = pos; + my ($lastpos, $firstpos); + my @fields = (); + + #for ($$textref) + { + my @func = defined $_[1] ? @{$_[1]} : @{$def_func}; + my $max = defined $_[2] && $_[2]>0 ? $_[2] : 1_000_000_000; + my $igunk = $_[3]; + + pos $$textref ||= 0; + + unless (wantarray) + { + use Carp; + carp "extract_multiple reset maximal count to 1 in scalar context" + if $^W && defined($_[2]) && $max > 1; + $max = 1 + } + + my @class; + foreach my $func ( @func ) + { + push @class, undef; + ($class[-1], $func) = %$func if ref($func) eq 'HASH'; + $func = qr/\G$func/ if !$ref_not_regex{ref $func}; + } + + my $unkpos; + FIELD: while (pos($$textref) < length($$textref)) + { + foreach my $i ( 0..$#func ) + { + my ($field, $pref); + my ($class, $func) = ($class[$i], $func[$i]); + $lastpos = pos $$textref; + if (ref($func) eq 'CODE') + { ($field,undef,$pref) = $func->($$textref) } + elsif (ref($func) eq 'Text::Balanced::Extractor') + { $field = $func->extract($$textref) } + elsif( $$textref =~ m/$func[$i]/gc ) + { $field = defined($1) + ? $1 + : substr($$textref, $-[0], $+[0] - $-[0]) + } + $pref ||= ""; + if (defined($field) && length($field)) + { + if (!$igunk) { + $unkpos = $lastpos + if length($pref) && !defined($unkpos); + if (defined $unkpos) + { + push @fields, substr($$textref, $unkpos, $lastpos-$unkpos).$pref; + $firstpos = $unkpos unless defined $firstpos; + undef $unkpos; + last FIELD if @fields == $max; + } + } + push @fields, $class ? bless(\$field, $class) : $field; + _update_patvalid($textref, $fields[-1]); + $firstpos = $lastpos unless defined $firstpos; + $lastpos = pos $$textref; + last FIELD if @fields == $max; + next FIELD; + } + } + if ($$textref =~ /\G(.)/gcs) + { + $unkpos = pos($$textref)-1 + unless $igunk || defined $unkpos; + _update_patvalid($textref, substr $$textref, $unkpos, pos($$textref)-$unkpos); + } + } + + if (defined $unkpos) + { + push @fields, substr($$textref, $unkpos); + $firstpos = $unkpos unless defined $firstpos; + $lastpos = length $$textref; + } + last; + } + + pos $$textref = $lastpos; + return @fields if wantarray; + + $firstpos ||= 0; + eval { substr($$textref,$firstpos,$lastpos-$firstpos)=""; + pos $$textref = $firstpos }; + return $fields[0]; +} + +sub gen_extract_tagged # ($opentag, $closetag, $pre, \%options) +{ + my $ldel = $_[0]; + my $rdel = $_[1]; + my $pre = defined $_[2] ? qr/\G$_[2]/ : qr/\G\s*/; + my %options = defined $_[3] ? %{$_[3]} : (); + my $omode = defined $options{fail} ? $options{fail} : ''; + my $bad = ref($options{reject}) eq 'ARRAY' ? join('|', @{$options{reject}}) + : defined($options{reject}) ? $options{reject} + : '' + ; + my $ignore = ref($options{ignore}) eq 'ARRAY' ? join('|', @{$options{ignore}}) + : defined($options{ignore}) ? $options{ignore} + : '' + ; + + $ldel = $et_default_ldel if !defined $ldel; + + my $posbug = pos; + for ($ldel, $bad, $ignore) { $_ = qr/$_/ if $_ } + pos = $posbug; + + my $closure = sub + { + my $textref = defined $_[0] ? \$_[0] : \$_; + my @match = _match_tagged($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore); + + return _fail(wantarray, $textref) unless @match; + return _succeed wantarray, $textref, + $match[2], $match[3]+$match[5]+$match[7], # MATCH + @match[8..9,0..1,2..7]; # REM, PRE, BITS + }; + + bless $closure, 'Text::Balanced::Extractor'; +} + +package Text::Balanced::Extractor; + +sub extract($$) # ($self, $text) +{ + &{$_[0]}($_[1]); +} + +package Text::Balanced::ErrorMsg; + +use overload + '""' => sub { "$_[0]->{error}, detected at offset $_[0]->{pos}" }, + fallback => 1; + +1; + +__END__ + +=pod + +=head1 NAME + +Text::Balanced - Extract delimited text sequences from strings. + +=head1 SYNOPSIS + + use Text::Balanced qw ( + extract_delimited + extract_bracketed + extract_quotelike + extract_codeblock + extract_variable + extract_tagged + extract_multiple + gen_delimited_pat + gen_extract_tagged + ); + + # Extract the initial substring of $text that is delimited by + # two (unescaped) instances of the first character in $delim. + + ($extracted, $remainder) = extract_delimited($text,$delim); + + # Extract the initial substring of $text that is bracketed + # with a delimiter(s) specified by $delim (where the string + # in $delim contains one or more of '(){}[]<>'). + + ($extracted, $remainder) = extract_bracketed($text,$delim); + + # Extract the initial substring of $text that is bounded by + # an XML tag. + + ($extracted, $remainder) = extract_tagged($text); + + # Extract the initial substring of $text that is bounded by + # a C...C pair. Don't allow nested C tags + + ($extracted, $remainder) = + extract_tagged($text,"BEGIN","END",undef,{bad=>["BEGIN"]}); + + # Extract the initial substring of $text that represents a + # Perl "quote or quote-like operation" + + ($extracted, $remainder) = extract_quotelike($text); + + # Extract the initial substring of $text that represents a block + # of Perl code, bracketed by any of character(s) specified by $delim + # (where the string $delim contains one or more of '(){}[]<>'). + + ($extracted, $remainder) = extract_codeblock($text,$delim); + + # Extract the initial substrings of $text that would be extracted by + # one or more sequential applications of the specified functions + # or regular expressions + + @extracted = extract_multiple($text, + [ \&extract_bracketed, + \&extract_quotelike, + \&some_other_extractor_sub, + qr/[xyz]*/, + 'literal', + ]); + + # Create a string representing an optimized pattern (a la Friedl) + # that matches a substring delimited by any of the specified characters + # (in this case: any type of quote or a slash) + + $patstring = gen_delimited_pat(q{'"`/}); + + # Generate a reference to an anonymous sub that is just like extract_tagged + # but pre-compiled and optimized for a specific pair of tags, and + # consequently much faster (i.e. 3 times faster). It uses qr// for better + # performance on repeated calls. + + $extract_head = gen_extract_tagged('',''); + ($extracted, $remainder) = $extract_head->($text); + +=head1 DESCRIPTION + +The various C subroutines may be used to +extract a delimited substring, possibly after skipping a +specified prefix string. By default, that prefix is +optional whitespace (C), but you can change it to whatever +you wish (see below). + +The substring to be extracted must appear at the +current C location of the string's variable +(or at index zero, if no C position is defined). +In other words, the C subroutines I +extract the first occurrence of a substring anywhere +in a string (like an unanchored regex would). Rather, +they extract an occurrence of the substring appearing +immediately at the current matching position in the +string (like a C<\G>-anchored regex would). + +=head2 General Behaviour in List Contexts + +In a list context, all the subroutines return a list, the first three +elements of which are always: + +=over 4 + +=item [0] + +The extracted string, including the specified delimiters. +If the extraction fails C is returned. + +=item [1] + +The remainder of the input string (i.e. the characters after the +extracted string). On failure, the entire string is returned. + +=item [2] + +The skipped prefix (i.e. the characters before the extracted string). +On failure, C is returned. + +=back + +Note that in a list context, the contents of the original input text (the first +argument) are not modified in any way. + +However, if the input text was passed in a variable, that variable's +C value is updated to point at the first character after the +extracted text. That means that in a list context the various +subroutines can be used much like regular expressions. For example: + + while ( $next = (extract_quotelike($text))[0] ) + { + # process next quote-like (in $next) + } + +=head2 General Behaviour in Scalar and Void Contexts + +In a scalar context, the extracted string is returned, having first been +removed from the input text. Thus, the following code also processes +each quote-like operation, but actually removes them from $text: + + while ( $next = extract_quotelike($text) ) + { + # process next quote-like (in $next) + } + +Note that if the input text is a read-only string (i.e. a literal), +no attempt is made to remove the extracted text. + +In a void context the behaviour of the extraction subroutines is +exactly the same as in a scalar context, except (of course) that the +extracted substring is not returned. + +=head2 A Note About Prefixes + +Prefix patterns are matched without any trailing modifiers (C etc.) +This can bite you if you're expecting a prefix specification like +'.*?(?=

)' to skip everything up to the first

tag. Such a prefix +pattern will only succeed if the

tag is on the current line, since +. normally doesn't match newlines. + +To overcome this limitation, you need to turn on /s matching within +the prefix pattern, using the C<(?s)> directive: '(?s).*?(?=

)' + +=head2 Functions + +=over 4 + +=item C + +The C function formalizes the common idiom +of extracting a single-character-delimited substring from the start of +a string. For example, to extract a single-quote delimited string, the +following code is typically used: + + ($remainder = $text) =~ s/\A('(\\.|[^'])*')//s; + $extracted = $1; + +but with C it can be simplified to: + + ($extracted,$remainder) = extract_delimited($text, "'"); + +C takes up to four scalars (the input text, the +delimiters, a prefix pattern to be skipped, and any escape characters) +and extracts the initial substring of the text that +is appropriately delimited. If the delimiter string has multiple +characters, the first one encountered in the text is taken to delimit +the substring. +The third argument specifies a prefix pattern that is to be skipped +(but must be present!) before the substring is extracted. +The final argument specifies the escape character to be used for each +delimiter. + +All arguments are optional. If the escape characters are not specified, +every delimiter is escaped with a backslash (C<\>). +If the prefix is not specified, the +pattern C<'\s*'> - optional whitespace - is used. If the delimiter set +is also not specified, the set C is used. If the text to be processed +is not specified either, C<$_> is used. + +In list context, C returns a array of three +elements, the extracted substring (I), the remainder of the text, and the skipped prefix (if +any). If a suitable delimited substring is not found, the first +element of the array is the empty string, the second is the complete +original text, and the prefix returned in the third element is an +empty string. + +In a scalar context, just the extracted substring is returned. In +a void context, the extracted substring (and any prefix) are simply +removed from the beginning of the first argument. + +Examples: + + # Remove a single-quoted substring from the very beginning of $text: + + $substring = extract_delimited($text, "'", ''); + + # Remove a single-quoted Pascalish substring (i.e. one in which + # doubling the quote character escapes it) from the very + # beginning of $text: + + $substring = extract_delimited($text, "'", '', "'"); + + # Extract a single- or double- quoted substring from the + # beginning of $text, optionally after some whitespace + # (note the list context to protect $text from modification): + + ($substring) = extract_delimited $text, q{"'}; + + # Delete the substring delimited by the first '/' in $text: + + $text = join '', (extract_delimited($text,'/','[^/]*')[2,1]; + +Note that this last example is I the same as deleting the first +quote-like pattern. For instance, if C<$text> contained the string: + + "if ('./cmd' =~ m/$UNIXCMD/s) { $cmd = $1; }" + +then after the deletion it would contain: + + "if ('.$UNIXCMD/s) { $cmd = $1; }" + +not: + + "if ('./cmd' =~ ms) { $cmd = $1; }" + +See L<"extract_quotelike"> for a (partial) solution to this problem. + +=item C + +Like C<"extract_delimited">, the C function takes +up to three optional scalar arguments: a string to extract from, a delimiter +specifier, and a prefix pattern. As before, a missing prefix defaults to +optional whitespace and a missing text defaults to C<$_>. However, a missing +delimiter specifier defaults to C<'{}()[]EE'> (see below). + +C extracts a balanced-bracket-delimited +substring (using any one (or more) of the user-specified delimiter +brackets: '(..)', '{..}', '[..]', or '<..>'). Optionally it will also +respect quoted unbalanced brackets (see below). + +A "delimiter bracket" is a bracket in list of delimiters passed as +C's second argument. Delimiter brackets are +specified by giving either the left or right (or both!) versions +of the required bracket(s). Note that the order in which +two or more delimiter brackets are specified is not significant. + +A "balanced-bracket-delimited substring" is a substring bounded by +matched brackets, such that any other (left or right) delimiter +bracket I the substring is also matched by an opposite +(right or left) delimiter bracket I. Any +type of bracket not in the delimiter list is treated as an ordinary +character. + +In other words, each type of bracket specified as a delimiter must be +balanced and correctly nested within the substring, and any other kind of +("non-delimiter") bracket in the substring is ignored. + +For example, given the string: + + $text = "{ an '[irregularly :-(] {} parenthesized >:-)' string }"; + +then a call to C in a list context: + + @result = extract_bracketed( $text, '{}' ); + +would return: + + ( "{ an '[irregularly :-(] {} parenthesized >:-)' string }" , "" , "" ) + +since both sets of C<'{..}'> brackets are properly nested and evenly balanced. +(In a scalar context just the first element of the array would be returned. In +a void context, C<$text> would be replaced by an empty string.) + +Likewise the call in: + + @result = extract_bracketed( $text, '{[' ); + +would return the same result, since all sets of both types of specified +delimiter brackets are correctly nested and balanced. + +However, the call in: + + @result = extract_bracketed( $text, '{([<' ); + +would fail, returning: + + ( undef , "{ an '[irregularly :-(] {} parenthesized >:-)' string }" ); + +because the embedded pairs of C<'(..)'>s and C<'[..]'>s are "cross-nested" and +the embedded C<'E'> is unbalanced. (In a scalar context, this call would +return an empty string. In a void context, C<$text> would be unchanged.) + +Note that the embedded single-quotes in the string don't help in this +case, since they have not been specified as acceptable delimiters and are +therefore treated as non-delimiter characters (and ignored). + +However, if a particular species of quote character is included in the +delimiter specification, then that type of quote will be correctly handled. +for example, if C<$text> is: + + $text = 'link'; + +then + + @result = extract_bracketed( $text, '<">' ); + +returns: + + ( '', 'link', "" ) + +as expected. Without the specification of C<"> as an embedded quoter: + + @result = extract_bracketed( $text, '<>' ); + +the result would be: + + ( 'link', "" ) + +In addition to the quote delimiters C<'>, C<">, and C<`>, full Perl quote-like +quoting (i.e. q{string}, qq{string}, etc) can be specified by including the +letter 'q' as a delimiter. Hence: + + @result = extract_bracketed( $text, '' ); + +would correctly match something like this: + + $text = ''; + +See also: C<"extract_quotelike"> and C<"extract_codeblock">. + +=item C + +C extracts any valid Perl variable or +variable-involved expression, including scalars, arrays, hashes, array +accesses, hash look-ups, method calls through objects, subroutine calls +through subroutine references, etc. + +The subroutine takes up to two optional arguments: + +=over 4 + +=item 1. + +A string to be processed (C<$_> if the string is omitted or C) + +=item 2. + +A string specifying a pattern to be matched as a prefix (which is to be +skipped). If omitted, optional whitespace is skipped. + +=back + +On success in a list context, an array of 3 elements is returned. The +elements are: + +=over 4 + +=item [0] + +the extracted variable, or variablish expression + +=item [1] + +the remainder of the input text, + +=item [2] + +the prefix substring (if any), + +=back + +On failure, all of these values (except the remaining text) are C. + +In a scalar context, C returns just the complete +substring that matched a variablish expression. C is returned on +failure. In addition, the original input text has the returned substring +(and any prefix) removed from it. + +In a void context, the input text just has the matched substring (and +any specified prefix) removed. + +=item C + +C extracts and segments text between (balanced) +specified tags. + +The subroutine takes up to five optional arguments: + +=over 4 + +=item 1. + +A string to be processed (C<$_> if the string is omitted or C) + +=item 2. + +A string specifying a pattern (i.e. regex) to be matched as the opening tag. +If the pattern string is omitted (or C) then a pattern +that matches any standard XML tag is used. + +=item 3. + +A string specifying a pattern to be matched at the closing tag. +If the pattern string is omitted (or C) then the closing +tag is constructed by inserting a C after any leading bracket +characters in the actual opening tag that was matched (I the pattern +that matched the tag). For example, if the opening tag pattern +is specified as C<'{{\w+}}'> and actually matched the opening tag +C<"{{DATA}}">, then the constructed closing tag would be C<"{{/DATA}}">. + +=item 4. + +A string specifying a pattern to be matched as a prefix (which is to be +skipped). If omitted, optional whitespace is skipped. + +=item 5. + +A hash reference containing various parsing options (see below) + +=back + +The various options that can be specified are: + +=over 4 + +=item C $listref> + +The list reference contains one or more strings specifying patterns +that must I appear within the tagged text. + +For example, to extract +an HTML link (which should not contain nested links) use: + + extract_tagged($text, '', '', undef, {reject => ['']} ); + +=item C $listref> + +The list reference contains one or more strings specifying patterns +that are I to be treated as nested tags within the tagged text +(even if they would match the start tag pattern). + +For example, to extract an arbitrary XML tag, but ignore "empty" elements: + + extract_tagged($text, undef, undef, undef, {ignore => ['<[^>]*/>']} ); + +(also see L<"gen_delimited_pat"> below). + +=item C $str> + +The C option indicates the action to be taken if a matching end +tag is not encountered (i.e. before the end of the string or some +C pattern matches). By default, a failure to match a closing +tag causes C to immediately fail. + +However, if the string value associated with is "MAX", then +C returns the complete text up to the point of failure. +If the string is "PARA", C returns only the first paragraph +after the tag (up to the first line that is either empty or contains +only whitespace characters). +If the string is "", the default behaviour (i.e. failure) is reinstated. + +For example, suppose the start tag "/para" introduces a paragraph, which then +continues until the next "/endpara" tag or until another "/para" tag is +encountered: + + $text = "/para line 1\n\nline 3\n/para line 4"; + + extract_tagged($text, '/para', '/endpara', undef, + {reject => '/para', fail => MAX ); + + # EXTRACTED: "/para line 1\n\nline 3\n" + +Suppose instead, that if no matching "/endpara" tag is found, the "/para" +tag refers only to the immediately following paragraph: + + $text = "/para line 1\n\nline 3\n/para line 4"; + + extract_tagged($text, '/para', '/endpara', undef, + {reject => '/para', fail => MAX ); + + # EXTRACTED: "/para line 1\n" + +Note that the specified C behaviour applies to nested tags as well. + +=back + +On success in a list context, an array of 6 elements is returned. The elements are: + +=over 4 + +=item [0] + +the extracted tagged substring (including the outermost tags), + +=item [1] + +the remainder of the input text, + +=item [2] + +the prefix substring (if any), + +=item [3] + +the opening tag + +=item [4] + +the text between the opening and closing tags + +=item [5] + +the closing tag (or "" if no closing tag was found) + +=back + +On failure, all of these values (except the remaining text) are C. + +In a scalar context, C returns just the complete +substring that matched a tagged text (including the start and end +tags). C is returned on failure. In addition, the original input +text has the returned substring (and any prefix) removed from it. + +In a void context, the input text just has the matched substring (and +any specified prefix) removed. + +=item C + +C generates a new anonymous subroutine which +extracts text between (balanced) specified tags. In other words, +it generates a function identical in function to C. + +The difference between C and the anonymous +subroutines generated by +C, is that those generated subroutines: + +=over 4 + +=item * + +do not have to reparse tag specification or parsing options every time +they are called (whereas C has to effectively rebuild +its tag parser on every call); + +=item * + +make use of the new qr// construct to pre-compile the regexes they use +(whereas C uses standard string variable interpolation +to create tag-matching patterns). + +=back + +The subroutine takes up to four optional arguments (the same set as +C except for the string to be processed). It returns +a reference to a subroutine which in turn takes a single argument (the text to +be extracted from). + +In other words, the implementation of C is exactly +equivalent to: + + sub extract_tagged + { + my $text = shift; + $extractor = gen_extract_tagged(@_); + return $extractor->($text); + } + +(although C is not currently implemented that way). + +Using C to create extraction functions for specific tags +is a good idea if those functions are going to be called more than once, since +their performance is typically twice as good as the more general-purpose +C. + +=item C + +C attempts to recognize, extract, and segment any +one of the various Perl quotes and quotelike operators (see +L) Nested backslashed delimiters, embedded balanced bracket +delimiters (for the quotelike operators), and trailing modifiers are +all caught. For example, in: + + extract_quotelike 'q # an octothorpe: \# (not the end of the q!) #' + + extract_quotelike ' "You said, \"Use sed\"." ' + + extract_quotelike ' s{([A-Z]{1,8}\.[A-Z]{3})} /\L$1\E/; ' + + extract_quotelike ' tr/\\\/\\\\/\\\//ds; ' + +the full Perl quotelike operations are all extracted correctly. + +Note too that, when using the /x modifier on a regex, any comment +containing the current pattern delimiter will cause the regex to be +immediately terminated. In other words: + + 'm / + (?i) # CASE INSENSITIVE + [a-z_] # LEADING ALPHABETIC/UNDERSCORE + [a-z0-9]* # FOLLOWED BY ANY NUMBER OF ALPHANUMERICS + /x' + +will be extracted as if it were: + + 'm / + (?i) # CASE INSENSITIVE + [a-z_] # LEADING ALPHABETIC/' + +This behaviour is identical to that of the actual compiler. + +C takes two arguments: the text to be processed and +a prefix to be matched at the very beginning of the text. If no prefix +is specified, optional whitespace is the default. If no text is given, +C<$_> is used. + +In a list context, an array of 11 elements is returned. The elements are: + +=over 4 + +=item [0] + +the extracted quotelike substring (including trailing modifiers), + +=item [1] + +the remainder of the input text, + +=item [2] + +the prefix substring (if any), + +=item [3] + +the name of the quotelike operator (if any), + +=item [4] + +the left delimiter of the first block of the operation, + +=item [5] + +the text of the first block of the operation +(that is, the contents of +a quote, the regex of a match or substitution or the target list of a +translation), + +=item [6] + +the right delimiter of the first block of the operation, + +=item [7] + +the left delimiter of the second block of the operation +(that is, if it is a C, C, or C), + +=item [8] + +the text of the second block of the operation +(that is, the replacement of a substitution or the translation list +of a translation), + +=item [9] + +the right delimiter of the second block of the operation (if any), + +=item [10] + +the trailing modifiers on the operation (if any). + +=back + +For each of the fields marked "(if any)" the default value on success is +an empty string. +On failure, all of these values (except the remaining text) are C. + +In a scalar context, C returns just the complete substring +that matched a quotelike operation (or C on failure). In a scalar or +void context, the input text has the same substring (and any specified +prefix) removed. + +Examples: + + # Remove the first quotelike literal that appears in text + + $quotelike = extract_quotelike($text,'.*?'); + + # Replace one or more leading whitespace-separated quotelike + # literals in $_ with "" + + do { $_ = join '', (extract_quotelike)[2,1] } until $@; + + + # Isolate the search pattern in a quotelike operation from $text + + ($op,$pat) = (extract_quotelike $text)[3,5]; + if ($op =~ /[ms]/) + { + print "search pattern: $pat\n"; + } + else + { + print "$op is not a pattern matching operation\n"; + } + +=item C + +C can successfully extract "here documents" from an input +string, but with an important caveat in list contexts. + +Unlike other types of quote-like literals, a here document is rarely +a contiguous substring. For example, a typical piece of code using +here document might look like this: + + <<'EOMSG' || die; + This is the message. + EOMSG + exit; + +Given this as an input string in a scalar context, C +would correctly return the string "<<'EOMSG'\nThis is the message.\nEOMSG", +leaving the string " || die;\nexit;" in the original variable. In other words, +the two separate pieces of the here document are successfully extracted and +concatenated. + +In a list context, C would return the list + +=over 4 + +=item [0] + +"<<'EOMSG'\nThis is the message.\nEOMSG\n" (i.e. the full extracted here document, +including fore and aft delimiters), + +=item [1] + +" || die;\nexit;" (i.e. the remainder of the input text, concatenated), + +=item [2] + +"" (i.e. the prefix substring -- trivial in this case), + +=item [3] + +"<<" (i.e. the "name" of the quotelike operator) + +=item [4] + +"'EOMSG'" (i.e. the left delimiter of the here document, including any quotes), + +=item [5] + +"This is the message.\n" (i.e. the text of the here document), + +=item [6] + +"EOMSG" (i.e. the right delimiter of the here document), + +=item [7..10] + +"" (a here document has no second left delimiter, second text, second right +delimiter, or trailing modifiers). + +=back + +However, the matching position of the input variable would be set to +"exit;" (i.e. I the closing delimiter of the here document), +which would cause the earlier " || die;\nexit;" to be skipped in any +sequence of code fragment extractions. + +To avoid this problem, when it encounters a here document whilst +extracting from a modifiable string, C silently +rearranges the string to an equivalent piece of Perl: + + <<'EOMSG' + This is the message. + EOMSG + || die; + exit; + +in which the here document I contiguous. It still leaves the +matching position after the here document, but now the rest of the line +on which the here document starts is not skipped. + +To prevent from mucking about with the input in this way +(this is the only case where a list-context C does so), +you can pass the input variable as an interpolated literal: + + $quotelike = extract_quotelike("$var"); + +=item C + +C attempts to recognize and extract a balanced +bracket delimited substring that may contain unbalanced brackets +inside Perl quotes or quotelike operations. That is, C +is like a combination of C<"extract_bracketed"> and +C<"extract_quotelike">. + +C takes the same initial three parameters as C: +a text to process, a set of delimiter brackets to look for, and a prefix to +match first. It also takes an optional fourth parameter, which allows the +outermost delimiter brackets to be specified separately (see below), +and a fifth parameter used only by L. + +Omitting the first argument (input text) means process C<$_> instead. +Omitting the second argument (delimiter brackets) indicates that only C<'{'> is to be used. +Omitting the third argument (prefix argument) implies optional whitespace at the start. +Omitting the fourth argument (outermost delimiter brackets) indicates that the +value of the second argument is to be used for the outermost delimiters. + +Once the prefix and the outermost opening delimiter bracket have been +recognized, code blocks are extracted by stepping through the input text and +trying the following alternatives in sequence: + +=over 4 + +=item 1. + +Try and match a closing delimiter bracket. If the bracket was the same +species as the last opening bracket, return the substring to that +point. If the bracket was mismatched, return an error. + +=item 2. + +Try to match a quote or quotelike operator. If found, call +C to eat it. If C fails, return +the error it returned. Otherwise go back to step 1. + +=item 3. + +Try to match an opening delimiter bracket. If found, call +C recursively to eat the embedded block. If the +recursive call fails, return an error. Otherwise, go back to step 1. + +=item 4. + +Unconditionally match a bareword or any other single character, and +then go back to step 1. + +=back + +Examples: + + # Find a while loop in the text + + if ($text =~ s/.*?while\s*\{/{/) + { + $loop = "while " . extract_codeblock($text); + } + + # Remove the first round-bracketed list (which may include + # round- or curly-bracketed code blocks or quotelike operators) + + extract_codeblock $text, "(){}", '[^(]*'; + + +The ability to specify a different outermost delimiter bracket is useful +in some circumstances. For example, in the Parse::RecDescent module, +parser actions which are to be performed only on a successful parse +are specified using a Cdefer:...E> directive. For example: + + sentence: subject verb object + + +Parse::RecDescent uses CE')> to extract the code +within the Cdefer:...E> directive, but there's a problem. + +A deferred action like this: + + 10) {$count--}} > + +will be incorrectly parsed as: + + + +because the "less than" operator is interpreted as a closing delimiter. + +But, by extracting the directive using +SE')>> +the '>' character is only treated as a delimited at the outermost +level of the code block, so the directive is parsed correctly. + +=item C + +The C subroutine takes a string to be processed and a +list of extractors (subroutines or regular expressions) to apply to that string. + +In an array context C returns an array of substrings +of the original string, as extracted by the specified extractors. +In a scalar context, C returns the first +substring successfully extracted from the original string. In both +scalar and void contexts the original string has the first successfully +extracted substring removed from it. In all contexts +C starts at the current C of the string, and +sets that C appropriately after it matches. + +Hence, the aim of a call to C in a list context +is to split the processed string into as many non-overlapping fields as +possible, by repeatedly applying each of the specified extractors +to the remainder of the string. Thus C is +a generalized form of Perl's C subroutine. + +The subroutine takes up to four optional arguments: + +=over 4 + +=item 1. + +A string to be processed (C<$_> if the string is omitted or C) + +=item 2. + +A reference to a list of subroutine references and/or qr// objects and/or +literal strings and/or hash references, specifying the extractors +to be used to split the string. If this argument is omitted (or +C) the list: + + [ + sub { extract_variable($_[0], '') }, + sub { extract_quotelike($_[0],'') }, + sub { extract_codeblock($_[0],'{}','') }, + ] + +is used. + +=item 3. + +An number specifying the maximum number of fields to return. If this +argument is omitted (or C), split continues as long as possible. + +If the third argument is I, then extraction continues until I fields +have been successfully extracted, or until the string has been completely +processed. + +Note that in scalar and void contexts the value of this argument is +automatically reset to 1 (under C<-w>, a warning is issued if the argument +has to be reset). + +=item 4. + +A value indicating whether unmatched substrings (see below) within the +text should be skipped or returned as fields. If the value is true, +such substrings are skipped. Otherwise, they are returned. + +=back + +The extraction process works by applying each extractor in +sequence to the text string. + +If the extractor is a subroutine it is called in a list context and is +expected to return a list of a single element, namely the extracted +text. It may optionally also return two further arguments: a string +representing the text left after extraction (like $' for a pattern +match), and a string representing any prefix skipped before the +extraction (like $` in a pattern match). Note that this is designed +to facilitate the use of other Text::Balanced subroutines with +C. Note too that the value returned by an extractor +subroutine need not bear any relationship to the corresponding substring +of the original text (see examples below). + +If the extractor is a precompiled regular expression or a string, +it is matched against the text in a scalar context with a leading +'\G' and the gc modifiers enabled. The extracted value is either +$1 if that variable is defined after the match, or else the +complete match (i.e. $&). + +If the extractor is a hash reference, it must contain exactly one element. +The value of that element is one of the +above extractor types (subroutine reference, regular expression, or string). +The key of that element is the name of a class into which the successful +return value of the extractor will be blessed. + +If an extractor returns a defined value, that value is immediately +treated as the next extracted field and pushed onto the list of fields. +If the extractor was specified in a hash reference, the field is also +blessed into the appropriate class, + +If the extractor fails to match (in the case of a regex extractor), or returns an empty list or an undefined value (in the case of a subroutine extractor), it is +assumed to have failed to extract. +If none of the extractor subroutines succeeds, then one +character is extracted from the start of the text and the extraction +subroutines reapplied. Characters which are thus removed are accumulated and +eventually become the next field (unless the fourth argument is true, in which +case they are discarded). + +For example, the following extracts substrings that are valid Perl variables: + + @fields = extract_multiple($text, + [ sub { extract_variable($_[0]) } ], + undef, 1); + +This example separates a text into fields which are quote delimited, +curly bracketed, and anything else. The delimited and bracketed +parts are also blessed to identify them (the "anything else" is unblessed): + + @fields = extract_multiple($text, + [ + { Delim => sub { extract_delimited($_[0],q{'"}) } }, + { Brack => sub { extract_bracketed($_[0],'{}') } }, + ]); + +This call extracts the next single substring that is a valid Perl quotelike +operator (and removes it from $text): + + $quotelike = extract_multiple($text, + [ + sub { extract_quotelike($_[0]) }, + ], undef, 1); + +Finally, here is yet another way to do comma-separated value parsing: + + $csv_text = "a,'x b',c"; + @fields = extract_multiple($csv_text, + [ + sub { extract_delimited($_[0],q{'"}) }, + qr/([^,]+)/, + ], + undef,1); + # @fields is now ('a', "'x b'", 'c') + +The list in the second argument means: +I<"Try and extract a ' or " delimited string, otherwise extract anything up to a comma...">. +The undef third argument means: +I<"...as many times as possible...">, +and the true value in the fourth argument means +I<"...discarding anything else that appears (i.e. the commas)">. + +If you wanted the commas preserved as separate fields (i.e. like split +does if your split pattern has capturing parentheses), you would +just make the last parameter undefined (or remove it). + +=item C + +The C subroutine takes a single (string) argument and +builds a Friedl-style optimized regex that matches a string delimited +by any one of the characters in the single argument. For example: + + gen_delimited_pat(q{'"}) + +returns the regex: + + (?:\"(?:\\\"|(?!\").)*\"|\'(?:\\\'|(?!\').)*\') + +Note that the specified delimiters are automatically quotemeta'd. + +A typical use of C would be to build special purpose tags +for C. For example, to properly ignore "empty" XML elements +(which might contain quoted strings): + + my $empty_tag = '<(' . gen_delimited_pat(q{'"}) . '|.)+/>'; + + extract_tagged($text, undef, undef, undef, {ignore => [$empty_tag]} ); + +C may also be called with an optional second argument, +which specifies the "escape" character(s) to be used for each delimiter. +For example to match a Pascal-style string (where ' is the delimiter +and '' is a literal ' within the string): + + gen_delimited_pat(q{'},q{'}); + +Different escape characters can be specified for different delimiters. +For example, to specify that '/' is the escape for single quotes +and '%' is the escape for double quotes: + + gen_delimited_pat(q{'"},q{/%}); + +If more delimiters than escape chars are specified, the last escape char +is used for the remaining delimiters. +If no escape char is specified for a given specified delimiter, '\' is used. + +=item C + +Note that C was previously called C. +That name may still be used, but is now deprecated. + +=back + +=head1 DIAGNOSTICS + +In a list context, all the functions return C<(undef,$original_text)> +on failure. In a scalar context, failure is indicated by returning C +(in this case the input text is not modified in any way). + +In addition, on failure in I context, the C<$@> variable is set. +Accessing C<$@-E{error}> returns one of the error diagnostics listed +below. +Accessing C<$@-E{pos}> returns the offset into the original string at +which the error was detected (although not necessarily where it occurred!) +Printing C<$@> directly produces the error message, with the offset appended. +On success, the C<$@> variable is guaranteed to be C. + +The available diagnostics are: + +=over 4 + +=item C + +The delimiter provided to C was not one of +C<'()[]EE{}'>. + +=item C + +A non-optional prefix was specified but wasn't found at the start of the text. + +=item C + +C or C was expecting a +particular kind of bracket at the start of the text, and didn't find it. + +=item C + +C didn't find one of the quotelike operators C, +C, C, C, C, C or C at the start of the substring +it was extracting. + +=item C + +C, C or C encountered +a closing bracket where none was expected. + +=item C + +C, C or C ran +out of characters in the text before closing one or more levels of nested +brackets. + +=item C + +C attempted to match an embedded quoted substring, but +failed to find a closing quote to match it. + +=item C + +C was unable to find a closing delimiter to match the +one that opened the quote-like operation. + +=item C + +C, C or C found +a valid bracket delimiter, but it was the wrong species. This usually +indicates a nesting error, but may indicate incorrect quoting or escaping. + +=item C + +C or C found one of the +quotelike operators C, C, C, C, C, C or C +without a suitable block after it. + +=item C + +C was expecting one of '$', '@', or '%' at the start of +a variable, but didn't find any of them. + +=item C + +C found a '$', '@', or '%' indicating a variable, but that +character was not followed by a legal Perl identifier. + +=item C + +C failed to find any of the outermost opening brackets +that were specified. + +=item C + +A nested code block was found that started with a delimiter that was specified +as being only to be used as an outermost bracket. + +=item C + +C or C found one of the +quotelike operators C, C or C followed by only one block. + +=item C + +C failed to find a closing bracket to match the outermost +opening bracket. + +=item C + +C did not find a suitable opening tag (after any specified +prefix was removed). + +=item C + +C matched the specified opening tag and tried to +modify the matched text to produce a matching closing tag (because +none was specified). It failed to generate the closing tag, almost +certainly because the opening tag did not start with a +bracket of some kind. + +=item C + +C found a nested tag that appeared in the "reject" list +(and the failure mode was not "MAX" or "PARA"). + +=item C + +C found a nested opening tag that was not matched by a +corresponding nested closing tag (and the failure mode was not "MAX" or "PARA"). + +=item C + +C reached the end of the text without finding a closing tag +to match the original opening tag (and the failure mode was not +"MAX" or "PARA"). + +=back + +=head1 EXPORTS + +The following symbols are, or can be, exported by this module: + +=over 4 + +=item Default Exports + +I. + +=item Optional Exports + +C, +C, +C, +C, +C, +C, +C, +C, +C, +C. + +=item Export Tags + +=over 4 + +=item C<:ALL> + +C, +C, +C, +C, +C, +C, +C, +C, +C, +C. + +=back + +=back + +=head1 KNOWN BUGS + +See L. + +=head1 FEEDBACK + +Patches, bug reports, suggestions or any other feedback is welcome. + +Patches can be sent as GitHub pull requests at +L. + +Bug reports and suggestions can be made on the CPAN Request Tracker at +L. + +Currently active requests on the CPAN Request Tracker can be viewed at +L. + +Please test this distribution. See CPAN Testers Reports at +L for details of how to get involved. + +Previous test results on CPAN Testers Reports can be viewed at +L. + +Please rate this distribution on CPAN Ratings at +L. + +=head1 AVAILABILITY + +The latest version of this module is available from CPAN (see +L for details) at + +L or + +L or + +L. + +The latest source code is available from GitHub at +L. + +=head1 INSTALLATION + +See the F file. + +=head1 AUTHOR + +Damian Conway ELE. + +Steve Hay ELE is now maintaining +Text::Balanced as of version 2.03. + +=head1 COPYRIGHT + +Copyright (C) 1997-2001 Damian Conway. All rights reserved. + +Copyright (C) 2009 Adam Kennedy. + +Copyright (C) 2015, 2020, 2022 Steve Hay and other contributors. All rights +reserved. + +=head1 LICENCE + +This module is free software; you can redistribute it and/or modify it under the +same terms as Perl itself, i.e. under the terms of either the GNU General Public +License or the Artistic License, as specified in the F file. + +=head1 VERSION + +Version 2.06 + +=head1 DATE + +05 Jun 2022 + +=head1 HISTORY + +See the F file. + +=cut diff --git a/git/usr/share/perl5/core_perl/Text/ParseWords.pm b/git/usr/share/perl5/core_perl/Text/ParseWords.pm new file mode 100644 index 0000000000000000000000000000000000000000..2bfe74d4a314444388f7f329284d30ec62dd876b --- /dev/null +++ b/git/usr/share/perl5/core_perl/Text/ParseWords.pm @@ -0,0 +1,327 @@ +package Text::ParseWords; + +use strict; +use warnings; +require 5.006; +our $VERSION = "3.31"; + + +use Exporter; +our @ISA = qw(Exporter); +our @EXPORT = qw(shellwords quotewords nested_quotewords parse_line); +our @EXPORT_OK = qw(old_shellwords); +our $PERL_SINGLE_QUOTE; + + +sub shellwords { + my (@lines) = @_; + my @allwords; + + foreach my $line (@lines) { + $line =~ s/^\s+//; + my @words = parse_line('\s+', 0, $line); + pop @words if (@words and !defined $words[-1]); + return() unless (@words || !length($line)); + push(@allwords, @words); + } + return(@allwords); +} + + + +sub quotewords { + my($delim, $keep, @lines) = @_; + my($line, @words, @allwords); + + foreach $line (@lines) { + @words = parse_line($delim, $keep, $line); + return() unless (@words || !length($line)); + push(@allwords, @words); + } + return(@allwords); +} + + + +sub nested_quotewords { + my($delim, $keep, @lines) = @_; + my($i, @allwords); + + for ($i = 0; $i < @lines; $i++) { + @{$allwords[$i]} = parse_line($delim, $keep, $lines[$i]); + return() unless (@{$allwords[$i]} || !length($lines[$i])); + } + return(@allwords); +} + + + +sub parse_line { + my($delimiter, $keep, $line) = @_; + my($word, @pieces); + + no warnings 'uninitialized'; # we will be testing undef strings + + while (length($line)) { + # This pattern is optimised to be stack conservative on older perls. + # Do not refactor without being careful and testing it on very long strings. + # See Perl bug #42980 for an example of a stack busting input. + $line =~ s/^ + (?: + # double quoted string + (") # $quote + ((?>[^\\"]*(?:\\.[^\\"]*)*))" # $quoted + | # --OR-- + # singe quoted string + (') # $quote + ((?>[^\\']*(?:\\.[^\\']*)*))' # $quoted + | # --OR-- + # unquoted string + ( # $unquoted + (?:\\.|[^\\"'])*? + ) + # followed by + ( # $delim + \Z(?!\n) # EOL + | # --OR-- + (?-x:$delimiter) # delimiter + | # --OR-- + (?!^)(?=["']) # a quote + ) + )//xs or return; # extended layout + my ($quote, $quoted, $unquoted, $delim) = (($1 ? ($1,$2) : ($3,$4)), $5, $6); + + + return() unless( defined($quote) || length($unquoted) || length($delim)); + + if ($keep) { + $quoted = "$quote$quoted$quote"; + } + else { + $unquoted =~ s/\\(.)/$1/sg; + if (defined $quote) { + $quoted =~ s/\\(.)/$1/sg if ($quote eq '"'); + $quoted =~ s/\\([\\'])/$1/g if ( $PERL_SINGLE_QUOTE && $quote eq "'"); + } + } + $word .= substr($line, 0, 0); # leave results tainted + $word .= defined $quote ? $quoted : $unquoted; + + if (length($delim)) { + push(@pieces, $word); + push(@pieces, $delim) if ($keep eq 'delimiters'); + undef $word; + } + if (!length($line)) { + push(@pieces, $word); + } + } + return(@pieces); +} + + + +sub old_shellwords { + + # Usage: + # use ParseWords; + # @words = old_shellwords($line); + # or + # @words = old_shellwords(@lines); + # or + # @words = old_shellwords(); # defaults to $_ (and clobbers it) + + no warnings 'uninitialized'; # we will be testing undef strings + local *_ = \join('', @_) if @_; + my (@words, $snippet); + + s/\A\s+//; + while ($_ ne '') { + my $field = substr($_, 0, 0); # leave results tainted + for (;;) { + if (s/\A"(([^"\\]|\\.)*)"//s) { + ($snippet = $1) =~ s#\\(.)#$1#sg; + } + elsif (/\A"/) { + require Carp; + Carp::carp("Unmatched double quote: $_"); + return(); + } + elsif (s/\A'(([^'\\]|\\.)*)'//s) { + ($snippet = $1) =~ s#\\(.)#$1#sg; + } + elsif (/\A'/) { + require Carp; + Carp::carp("Unmatched single quote: $_"); + return(); + } + elsif (s/\A\\(.?)//s) { + $snippet = $1; + } + elsif (s/\A([^\s\\'"]+)//) { + $snippet = $1; + } + else { + s/\A\s+//; + last; + } + $field .= $snippet; + } + push(@words, $field); + } + return @words; +} + +1; + +__END__ + +=head1 NAME + +Text::ParseWords - parse text into an array of tokens or array of arrays + +=head1 SYNOPSIS + + use Text::ParseWords; + @lists = nested_quotewords($delim, $keep, @lines); + @words = quotewords($delim, $keep, @lines); + @words = shellwords(@lines); + @words = parse_line($delim, $keep, $line); + @words = old_shellwords(@lines); # DEPRECATED! + +=head1 DESCRIPTION + +The C and C functions accept a delimiter +(which can be a regular expression) +and a list of lines and then breaks those lines up into a list of +words ignoring delimiters that appear inside quotes. C +returns all of the tokens in a single long list, while C +returns a list of token lists corresponding to the elements of C<@lines>. +C does tokenizing on a single string. The C<*quotewords()> +functions simply call C, so if you're only splitting +one line you can call C directly and save a function +call. + +The C<$keep> controls what happens with delimters and special characters: + +=over 4 + +=item true + +If true, then the tokens are split on the specified delimiter, +but all other characters (including quotes and backslashes) +are kept in the tokens. + +=item false + +If $keep is false then the C<*quotewords()> functions +remove all quotes and backslashes that are +not themselves backslash-escaped or inside of single quotes (i.e., +C tries to interpret these characters just like the Bourne +shell). NB: these semantics are significantly different from the +original version of this module shipped with Perl 5.000 through 5.004. + +=item C<"delimiters"> + +As an additional feature, $keep may be the keyword "delimiters" which +causes the functions to preserve the delimiters in each string as +tokens in the token lists, in addition to preserving quote and +backslash characters. + +=back + +C is written as a special case of C, and it +does token parsing with whitespace as a delimiter-- similar to most +Unix shells. + +=head1 EXAMPLES + +The sample program: + + use Text::ParseWords; + @words = quotewords('\s+', 0, q{this is "a test" of\ quotewords \"for you}); + $i = 0; + foreach (@words) { + print "$i: <$_>\n"; + $i++; + } + +produces: + + 0: + 1: + 2: + 3: + 4: <"for> + 5: + +demonstrating: + +=over 4 + +=item 0Z<> + +a simple word + +=item 1Z<> + +multiple spaces are skipped because of our $delim + +=item 2Z<> + +use of quotes to include a space in a word + +=item 3Z<> + +use of a backslash to include a space in a word + +=item 4Z<> + +use of a backslash to remove the special meaning of a double-quote + +=item 5Z<> + +another simple word (note the lack of effect of the +backslashed double-quote) + +=back + +Replacing C +with C +is a simpler way to accomplish the same thing. + +=head1 SEE ALSO + +L - for parsing CSV files + +=head1 AUTHORS + +The original author is unknown, +but presumably this evolved from C in Perl 4. + +Much of the code for C +(including the primary regexp) +came from Joerk Behrends Ejbehrends@multimediaproduzenten.deE. + +Examples section and other documentation provided by +John Heidemann Ejohnh@ISI.EDUE. + +Hal Pomeranz Epomeranz@netcom.comE +maintained this from 1994 through 1999, +and did the first CPAN release. + +Alexandr Ciornii EalexchornyATgmail.comE +maintained this from 2008 to 2015. + +Many other people have contributed, +with special thanks due to +Michael Schwern Eschwern@envirolink.orgE +and +Jeff Friedl Ejfriedl@yahoo-inc.comE. + +=head1 COPYRIGHT AND LICENSE + +This library is free software; you may redistribute and/or modify it +under the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/core_perl/Text/Tabs.pm b/git/usr/share/perl5/core_perl/Text/Tabs.pm new file mode 100644 index 0000000000000000000000000000000000000000..165c6e64aef07c038c5ed2d116ae626747583fb4 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Text/Tabs.pm @@ -0,0 +1,151 @@ +use strict; use warnings; + +package Text::Tabs; + +BEGIN { require Exporter; *import = \&Exporter::import } + +our @EXPORT = qw( expand unexpand $tabstop ); + +our $VERSION = '2024.001'; +our $SUBVERSION = 'modern'; # back-compat vestige + +our $tabstop = 8; + +sub expand { + my @l; + my $pad; + for ( @_ ) { + defined or do { push @l, ''; next }; + my $s = ''; + for (split(/^/m, $_, -1)) { + my $offs; + for (split(/\t/, $_, -1)) { + if (defined $offs) { + $pad = $tabstop - $offs % $tabstop; + $s .= " " x $pad; + } + $s .= $_; + $offs = /^\pM/ + ( () = /\PM/g ); + } + } + push(@l, $s); + } + return @l if wantarray; + return $l[0]; +} + +sub unexpand +{ + my (@l) = @_; + my @e; + my $x; + my $line; + my @lines; + my $lastbit; + my $ts_as_space = " " x $tabstop; + for $x (@l) { + defined $x or next; + @lines = split("\n", $x, -1); + for $line (@lines) { + $line = expand($line); + @e = split(/((?:\PM\pM*|^\pM+){$tabstop})/,$line,-1); + $lastbit = pop(@e); + $lastbit = '' + unless defined $lastbit; + $lastbit = "\t" + if $lastbit eq $ts_as_space; + for $_ (@e) { + s/ +$/\t/; + } + $line = join('',@e, $lastbit); + } + $x = join("\n", @lines); + } + return @l if wantarray; + return $l[0]; +} + +1; + +__END__ + +=head1 NAME + +Text::Tabs - expand and unexpand tabs like unix expand(1) and unexpand(1) + +=head1 SYNOPSIS + + use Text::Tabs; + + $tabstop = 4; # default = 8 + @lines_without_tabs = expand(@lines_with_tabs); + @lines_with_tabs = unexpand(@lines_without_tabs); + +=head1 DESCRIPTION + +Text::Tabs does most of what the unix utilities expand(1) and unexpand(1) +do. Given a line with tabs in it, C replaces those tabs with +the appropriate number of spaces. Given a line with or without tabs in +it, C adds tabs when it can save bytes by doing so, +like the C command. + +Unlike the old unix utilities, this module correctly accounts for +any Unicode combining characters (such as diacriticals) that may occur +in each line for both expansion and unexpansion. These are overstrike +characters that do not increment the logical position. Make sure +you have the appropriate Unicode settings enabled. + +=head1 EXPORTS + +The following are exported: + +=over 4 + +=item expand + +=item unexpand + +=item $tabstop + +The C<$tabstop> variable controls how many column positions apart each +tabstop is. The default is 8. + +Please note that C doesn't do the right thing and if you want +to use C to override C<$tabstop>, you need to use +C. + +=back + +=head1 EXAMPLE + + #!perl + # unexpand -a + use Text::Tabs; + + while (<>) { + print unexpand $_; + } + +Instead of the shell's C command, use: + + perl -MText::Tabs -n -e 'print expand $_' + +Instead of the shell's C command, use: + + perl -MText::Tabs -n -e 'print unexpand $_' + +=head1 BUGS + +Text::Tabs handles only tabs (C<"\t">) and combining characters (C). It doesn't +count backwards for backspaces (C<"\t">), omit other non-printing control characters (C), +or otherwise deal with any other zero-, half-, and full-width characters. + +=head1 LICENSE + +Copyright (C) 1996-2002,2005,2006 David Muir Sharnoff. +Copyright (C) 2005 Aristotle Pagaltzis +Copyright (C) 2012-2013 Google, Inc. +This module may be modified, used, copied, and redistributed at your own risk. +Although allowed by the preceding license, please do not publicly +redistribute modified versions of this code with the name "Text::Tabs" +unless it passes the unmodified Text::Tabs test suite. diff --git a/git/usr/share/perl5/core_perl/Text/Wrap.pm b/git/usr/share/perl5/core_perl/Text/Wrap.pm new file mode 100644 index 0000000000000000000000000000000000000000..ff9ac1ba055262f5185b8ed1df8f793bb8dcf5fe --- /dev/null +++ b/git/usr/share/perl5/core_perl/Text/Wrap.pm @@ -0,0 +1,279 @@ +use strict; use warnings; + +package Text::Wrap; + +use warnings::register; + +BEGIN { require Exporter; *import = \&Exporter::import } + +our @EXPORT = qw( wrap fill ); +our @EXPORT_OK = qw( $columns $break $huge ); + +our $VERSION = '2024.001'; +our $SUBVERSION = 'modern'; # back-compat vestige + +BEGIN { eval sprintf 'sub REGEXPS_USE_BYTES () { %d }', scalar( pack('U*', 0x80) =~ /\xc2/ ) } + +my $brkspc = "\x{a0}\x{202f}" =~ /\s/ ? '[^\x{a0}\x{202f}\S]' : '\s'; + +our $columns = 76; # <= screen width +our $break = '(?>\n|\r\n|'.$brkspc.'\pM*)'; +our $huge = 'wrap'; # alternatively: 'die' or 'overflow' +our $unexpand = 1; +our $tabstop = 8; +our $separator = "\n"; +our $separator2 = undef; + +sub _xlen { $_[0] =~ /^\pM/ + ( () = $_[0] =~ /\PM/g ) } + +use Text::Tabs qw(expand unexpand); + +sub wrap +{ + my ($ip, $xp, @t) = map +( defined $_ ? $_ : '' ), @_; + + local($Text::Tabs::tabstop) = $tabstop; + my $r = ""; + my $tail = pop(@t); + my $t = expand(join("", (map { /\s+\z/ ? ( $_ ) : ($_, ' ') } @t), $tail)); + my $lead = $ip; + my $nll = $columns - _xlen(expand($xp)) - 1; + if ($nll <= 0 && $xp ne '') { + my $nc = _xlen(expand($xp)) + 2; + warnings::warnif "Increasing \$Text::Wrap::columns from $columns to $nc to accommodate length of subsequent tab"; + $columns = $nc; + $nll = 1; + } + my $ll = $columns - _xlen(expand($ip)) - 1; + $ll = 0 if $ll < 0; + my $nl = ""; + my $remainder = ""; + + use re 'taint'; + + pos($t) = 0; + while ($t !~ /\G(?:$break)*\Z/gc) { + if ($t =~ /\G((?>(?!\n)\PM\pM*|(?(?!\n)\PM\pM*|(? + + use Text::Wrap; + + $initial_tab = "\t"; # Tab before first line + $subsequent_tab = ""; # All other lines flush left + + print wrap($initial_tab, $subsequent_tab, @text); + print fill($initial_tab, $subsequent_tab, @text); + + $lines = wrap($initial_tab, $subsequent_tab, @text); + + @paragraphs = fill($initial_tab, $subsequent_tab, @text); + +B + + use Text::Wrap qw(wrap $columns $huge); + + $columns = 132; # Wrap at 132 characters + $huge = 'die'; + $huge = 'wrap'; + $huge = 'overflow'; + +B + + use Text::Wrap; + + $Text::Wrap::columns = 72; + print wrap('', '', @text); + +=head1 DESCRIPTION + +C is a very simple paragraph formatter. It formats a +single paragraph at a time by breaking lines at word boundaries. +Indentation is controlled for the first line (C<$initial_tab>) and +all subsequent lines (C<$subsequent_tab>) independently. Please note: +C<$initial_tab> and C<$subsequent_tab> are the literal strings that will +be used: it is unlikely you would want to pass in a number. + +C is a simple multi-paragraph formatter. It formats +each paragraph separately and then joins them together when it's done. It +will destroy any whitespace in the original text. It breaks text into +paragraphs by looking for whitespace after a newline. In other respects, +it acts like wrap(). + +C compresses trailing whitespace into one newline, and C +deletes all trailing whitespace. + +Both C and C return a single string. + +Unlike the old Unix fmt(1) utility, this module correctly accounts for +any Unicode combining characters (such as diacriticals) that may occur +in each line for both expansion and unexpansion. These are overstrike +characters that do not increment the logical position. Make sure +you have the appropriate Unicode settings enabled. + +=head1 OVERRIDES + +C has a number of variables that control its behavior. +Because other modules might be using C it is suggested +that you leave these variables alone! If you can't do that, then +use C when you change the +values so that the original value is restored. This C trick +will not work if you import the variable into your own namespace. + +Lines are wrapped at C<$Text::Wrap::columns> columns (default value: 76). +C<$Text::Wrap::columns> should be set to the full width of your output +device. In fact, every resulting line will have length of no more than +C<$columns - 1>. + +It is possible to control which characters terminate words by +modifying C<$Text::Wrap::break>. Set this to a string such as +C<'[\s:]'> (to break before spaces or colons) or a pre-compiled regexp +such as C (to break before spaces or apostrophes). The +default is simply C<'\s'>; that is, words are terminated by spaces. +(This means, among other things, that trailing punctuation such as +full stops or commas stay with the word they are "attached" to.) +Setting C<$Text::Wrap::break> to a regular expression that doesn't +eat any characters (perhaps just a forward look-ahead assertion) will +cause warnings. + +Beginner note: In example 2, above C<$columns> is imported into +the local namespace, and set locally. In example 3, +C<$Text::Wrap::columns> is set in its own namespace without importing it. + +C starts its work by expanding all the tabs in its +input into spaces. The last thing it does it to turn spaces back +into tabs. If you do not want tabs in your results, set +C<$Text::Wrap::unexpand> to a false value. Likewise if you do not +want to use 8-character tabstops, set C<$Text::Wrap::tabstop> to +the number of characters you do want for your tabstops. + +If you want to separate your lines with something other than C<\n> +then set C<$Text::Wrap::separator> to your preference. This replaces +all newlines with C<$Text::Wrap::separator>. If you just want to +preserve existing newlines but add new breaks with something else, set +C<$Text::Wrap::separator2> instead. + +When words that are longer than C<$columns> are encountered, they +are broken up. C adds a C<"\n"> at column C<$columns>. +This behavior can be overridden by setting C<$huge> to +'die' or to 'overflow'. When set to 'die', large words will cause +C to be called. When set to 'overflow', large words will be +left intact. + +Historical notes: 'die' used to be the default value of +C<$huge>. Now, 'wrap' is the default value. + +=head1 EXAMPLES + +Code: + + print wrap("\t","",<. For more detailed controls: L. + +=head1 AUTHOR + +David Muir Sharnoff with help from Tim Pierce and +many many others. + +=head1 LICENSE + +Copyright (C) 1996-2009 David Muir Sharnoff. +Copyright (C) 2012-2013 Google, Inc. +This module may be modified, used, copied, and redistributed at your own risk. +Although allowed by the preceding license, please do not publicly +redistribute modified versions of this code with the name "Text::Wrap" +unless it passes the unmodified Text::Wrap test suite. diff --git a/git/usr/share/perl5/core_perl/Thread/Queue.pm b/git/usr/share/perl5/core_perl/Thread/Queue.pm new file mode 100644 index 0000000000000000000000000000000000000000..731d0b2f457be8cf18841e229f91ae5912274d54 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Thread/Queue.pm @@ -0,0 +1,657 @@ +package Thread::Queue; + +use strict; +use warnings; + +our $VERSION = '3.14'; # remember to update version in POD! +$VERSION = eval $VERSION; + +use threads::shared 1.21; +use Scalar::Util 1.10 qw(looks_like_number blessed reftype refaddr); + +# Carp errors from threads::shared calls should complain about caller +our @CARP_NOT = ("threads::shared"); + +# Create a new queue possibly pre-populated with items +sub new +{ + my $class = shift; + my @queue :shared = map { shared_clone($_) } @_; + my %self :shared = ( 'queue' => \@queue ); + return bless(\%self, $class); +} + +# Add items to the tail of a queue +sub enqueue +{ + my $self = shift; + lock(%$self); + + if ($$self{'ENDED'}) { + require Carp; + Carp::croak("'enqueue' method called on queue that has been 'end'ed"); + } + + # Block if queue size exceeds any specified limit + my $queue = $$self{'queue'}; + cond_wait(%$self) while ($$self{'LIMIT'} && (@$queue >= $$self{'LIMIT'})); + + # Add items to queue, and then signal other threads + push(@$queue, map { shared_clone($_) } @_) + and cond_signal(%$self); +} + +# Set or return the max. size for a queue +sub limit : lvalue +{ + my $self = shift; + lock(%$self); + $$self{'LIMIT'}; +} + +# Return a count of the number of items on a queue +sub pending +{ + my $self = shift; + lock(%$self); + return if ($$self{'ENDED'} && ! @{$$self{'queue'}}); + return scalar(@{$$self{'queue'}}); +} + +# Indicate that no more data will enter the queue +sub end +{ + my $self = shift; + lock(%$self); + # No more data is coming + $$self{'ENDED'} = 1; + + cond_signal(%$self); # Unblock possibly waiting threads +} + +# Return 1 or more items from the head of a queue, blocking if needed +sub dequeue +{ + my $self = shift; + lock(%$self); + my $queue = $$self{'queue'}; + + my $count = @_ ? $self->_validate_count(shift) : 1; + + # Wait for requisite number of items + cond_wait(%$self) while ((@$queue < $count) && ! $$self{'ENDED'}); + + # If no longer blocking, try getting whatever is left on the queue + return $self->dequeue_nb($count) if ($$self{'ENDED'}); + + # Return single item + if ($count == 1) { + my $item = shift(@$queue); + cond_signal(%$self); # Unblock possibly waiting threads + return $item; + } + + # Return multiple items + my @items; + push(@items, shift(@$queue)) for (1..$count); + cond_signal(%$self); # Unblock possibly waiting threads + return @items; +} + +# Return items from the head of a queue with no blocking +sub dequeue_nb +{ + my $self = shift; + lock(%$self); + my $queue = $$self{'queue'}; + + my $count = @_ ? $self->_validate_count(shift) : 1; + + # Return single item + if ($count == 1) { + my $item = shift(@$queue); + cond_signal(%$self); # Unblock possibly waiting threads + return $item; + } + + # Return multiple items + my @items; + for (1..$count) { + last if (! @$queue); + push(@items, shift(@$queue)); + } + cond_signal(%$self); # Unblock possibly waiting threads + return @items; +} + +# Return items from the head of a queue, blocking if needed up to a timeout +sub dequeue_timed +{ + my $self = shift; + lock(%$self); + my $queue = $$self{'queue'}; + + # Timeout may be relative or absolute + my $timeout = @_ ? $self->_validate_timeout(shift) : -1; + # Convert to an absolute time for use with cond_timedwait() + if ($timeout < 32000000) { # More than one year + $timeout += time(); + } + + my $count = @_ ? $self->_validate_count(shift) : 1; + + # Wait for requisite number of items, or until timeout + while ((@$queue < $count) && ! $$self{'ENDED'}) { + last if (! cond_timedwait(%$self, $timeout)); + } + + # Get whatever we need off the queue if available + return $self->dequeue_nb($count); +} + +# Return an item without removing it from a queue +sub peek +{ + my $self = shift; + lock(%$self); + my $index = @_ ? $self->_validate_index(shift) : 0; + return $$self{'queue'}[$index]; +} + +# Insert items anywhere into a queue +sub insert +{ + my $self = shift; + lock(%$self); + + if ($$self{'ENDED'}) { + require Carp; + Carp::croak("'insert' method called on queue that has been 'end'ed"); + } + + my $queue = $$self{'queue'}; + + my $index = $self->_validate_index(shift); + + return if (! @_); # Nothing to insert + + # Support negative indices + if ($index < 0) { + $index += @$queue; + if ($index < 0) { + $index = 0; + } + } + + # Dequeue items from $index onward + my @tmp; + while (@$queue > $index) { + unshift(@tmp, pop(@$queue)) + } + + # Add new items to the queue + push(@$queue, map { shared_clone($_) } @_); + + # Add previous items back onto the queue + push(@$queue, @tmp); + + cond_signal(%$self); # Unblock possibly waiting threads +} + +# Remove items from anywhere in a queue +sub extract +{ + my $self = shift; + lock(%$self); + my $queue = $$self{'queue'}; + + my $index = @_ ? $self->_validate_index(shift) : 0; + my $count = @_ ? $self->_validate_count(shift) : 1; + + # Support negative indices + if ($index < 0) { + $index += @$queue; + if ($index < 0) { + $count += $index; + return if ($count <= 0); # Beyond the head of the queue + return $self->dequeue_nb($count); # Extract from the head + } + } + + # Dequeue items from $index+$count onward + my @tmp; + while (@$queue > ($index+$count)) { + unshift(@tmp, pop(@$queue)) + } + + # Extract desired items + my @items; + unshift(@items, pop(@$queue)) while (@$queue > $index); + + # Add back any removed items + push(@$queue, @tmp); + + cond_signal(%$self); # Unblock possibly waiting threads + + # Return single item + return $items[0] if ($count == 1); + + # Return multiple items + return @items; +} + +### Internal Methods ### + +# Check value of the requested index +sub _validate_index +{ + my $self = shift; + my $index = shift; + + if (! defined($index) || + ! looks_like_number($index) || + (int($index) != $index)) + { + require Carp; + my ($method) = (caller(1))[3]; + my $class_name = ref($self); + $method =~ s/$class_name\:://; + $index = 'undef' if (! defined($index)); + Carp::croak("Invalid 'index' argument ($index) to '$method' method"); + } + + return $index; +}; + +# Check value of the requested count +sub _validate_count +{ + my $self = shift; + my $count = shift; + + if (! defined($count) || + ! looks_like_number($count) || + (int($count) != $count) || + ($count < 1) || + ($$self{'LIMIT'} && $count > $$self{'LIMIT'})) + { + require Carp; + my ($method) = (caller(1))[3]; + my $class_name = ref($self); + $method =~ s/$class_name\:://; + $count = 'undef' if (! defined($count)); + if ($$self{'LIMIT'} && $count > $$self{'LIMIT'}) { + Carp::croak("'count' argument ($count) to '$method' method exceeds queue size limit ($$self{'LIMIT'})"); + } else { + Carp::croak("Invalid 'count' argument ($count) to '$method' method"); + } + } + + return $count; +}; + +# Check value of the requested timeout +sub _validate_timeout +{ + my $self = shift; + my $timeout = shift; + + if (! defined($timeout) || + ! looks_like_number($timeout)) + { + require Carp; + my ($method) = (caller(1))[3]; + my $class_name = ref($self); + $method =~ s/$class_name\:://; + $timeout = 'undef' if (! defined($timeout)); + Carp::croak("Invalid 'timeout' argument ($timeout) to '$method' method"); + } + + return $timeout; +}; + +1; + +=head1 NAME + +Thread::Queue - Thread-safe queues + +=head1 VERSION + +This document describes Thread::Queue version 3.14 + +=head1 SYNOPSIS + + use strict; + use warnings; + + use threads; + use Thread::Queue; + + my $q = Thread::Queue->new(); # A new empty queue + + # Worker thread + my $thr = threads->create( + sub { + # Thread will loop until no more work + while (defined(my $item = $q->dequeue())) { + # Do work on $item + ... + } + } + ); + + # Send work to the thread + $q->enqueue($item1, ...); + # Signal that there is no more work to be sent + $q->end(); + # Join up with the thread when it finishes + $thr->join(); + + ... + + # Count of items in the queue + my $left = $q->pending(); + + # Non-blocking dequeue + if (defined(my $item = $q->dequeue_nb())) { + # Work on $item + } + + # Blocking dequeue with 5-second timeout + if (defined(my $item = $q->dequeue_timed(5))) { + # Work on $item + } + + # Set a size for a queue + $q->limit = 5; + + # Get the second item in the queue without dequeuing anything + my $item = $q->peek(1); + + # Insert two items into the queue just behind the head + $q->insert(1, $item1, $item2); + + # Extract the last two items on the queue + my ($item1, $item2) = $q->extract(-2, 2); + +=head1 DESCRIPTION + +This module provides thread-safe FIFO queues that can be accessed safely by +any number of threads. + +Any data types supported by L can be passed via queues: + +=over + +=item Ordinary scalars + +=item Array refs + +=item Hash refs + +=item Scalar refs + +=item Objects based on the above + +=back + +Ordinary scalars are added to queues as they are. + +If not already thread-shared, the other complex data types will be cloned +(recursively, if needed, and including any Cings and read-only +settings) into thread-shared structures before being placed onto a queue. + +For example, the following would cause L to create a empty, +shared array reference via C<&shared([])>, copy the elements 'foo', 'bar' +and 'baz' from C<@ary> into it, and then place that shared reference onto +the queue: + + my @ary = qw/foo bar baz/; + $q->enqueue(\@ary); + +However, for the following, the items are already shared, so their references +are added directly to the queue, and no cloning takes place: + + my @ary :shared = qw/foo bar baz/; + $q->enqueue(\@ary); + + my $obj = &shared({}); + $$obj{'foo'} = 'bar'; + $$obj{'qux'} = 99; + bless($obj, 'My::Class'); + $q->enqueue($obj); + +See L for caveats related to passing objects via queues. + +=head1 QUEUE CREATION + +=over + +=item ->new() + +Creates a new empty queue. + +=item ->new(LIST) + +Creates a new queue pre-populated with the provided list of items. + +=back + +=head1 BASIC METHODS + +The following methods deal with queues on a FIFO basis. + +=over + +=item ->enqueue(LIST) + +Adds a list of items onto the end of the queue. + +=item ->dequeue() + +=item ->dequeue(COUNT) + +Removes the requested number of items (default is 1) from the head of the +queue, and returns them. If the queue contains fewer than the requested +number of items, then the thread will be blocked until the requisite number +of items are available (i.e., until other threads C more items). + +=item ->dequeue_nb() + +=item ->dequeue_nb(COUNT) + +Removes the requested number of items (default is 1) from the head of the +queue, and returns them. If the queue contains fewer than the requested +number of items, then it immediately (i.e., non-blocking) returns whatever +items there are on the queue. If the queue is empty, then C is +returned. + +=item ->dequeue_timed(TIMEOUT) + +=item ->dequeue_timed(TIMEOUT, COUNT) + +Removes the requested number of items (default is 1) from the head of the +queue, and returns them. If the queue contains fewer than the requested +number of items, then the thread will be blocked until the requisite number of +items are available, or until the timeout is reached. If the timeout is +reached, it returns whatever items there are on the queue, or C if the +queue is empty. + +The timeout may be a number of seconds relative to the current time (e.g., 5 +seconds from when the call is made), or may be an absolute timeout in I +seconds the same as would be used with +L. +Fractional seconds (e.g., 2.5 seconds) are also supported (to the extent of +the underlying implementation). + +If C is missing, C, or less than or equal to 0, then this call +behaves the same as C. + +=item ->pending() + +Returns the number of items still in the queue. Returns C if the queue +has been ended (see below), and there are no more items in the queue. + +=item ->limit + +Sets the size of the queue. If set, calls to C will block until +the number of pending items in the queue drops below the C. The +C does not prevent enqueuing items beyond that count: + + my $q = Thread::Queue->new(1, 2); + $q->limit = 4; + $q->enqueue(3, 4, 5); # Does not block + $q->enqueue(6); # Blocks until at least 2 items are + # dequeued + my $size = $q->limit; # Returns the current limit (may return + # 'undef') + $q->limit = 0; # Queue size is now unlimited + +Calling any of the dequeue methods with C greater than a queue's +C will generate an error. + +=item ->end() + +Declares that no more items will be added to the queue. + +All threads blocking on C calls will be unblocked with any +remaining items in the queue and/or C being returned. Any subsequent +calls to C will behave like C. + +Once ended, no more items may be placed in the queue. + +=back + +=head1 ADVANCED METHODS + +The following methods can be used to manipulate items anywhere in a queue. + +To prevent the contents of a queue from being modified by another thread +while it is being examined and/or changed, L the queue inside a local block: + + { + lock($q); # Keep other threads from changing the queue's contents + my $item = $q->peek(); + if ($item ...) { + ... + } + } + # Queue is now unlocked + +=over + +=item ->peek() + +=item ->peek(INDEX) + +Returns an item from the queue without dequeuing anything. Defaults to the +head of queue (at index position 0) if no index is specified. Negative +index values are supported as with L (i.e., -1 +is the end of the queue, -2 is next to last, and so on). + +If no items exists at the specified index (i.e., the queue is empty, or the +index is beyond the number of items on the queue), then C is returned. + +Remember, the returned item is not removed from the queue, so manipulating a +Ced at reference affects the item on the queue. + +=item ->insert(INDEX, LIST) + +Adds the list of items to the queue at the specified index position (0 +is the head of the list). Any existing items at and beyond that position are +pushed back past the newly added items: + + $q->enqueue(1, 2, 3, 4); + $q->insert(1, qw/foo bar/); + # Queue now contains: 1, foo, bar, 2, 3, 4 + +Specifying an index position greater than the number of items in the queue +just adds the list to the end. + +Negative index positions are supported: + + $q->enqueue(1, 2, 3, 4); + $q->insert(-2, qw/foo bar/); + # Queue now contains: 1, 2, foo, bar, 3, 4 + +Specifying a negative index position greater than the number of items in the +queue adds the list to the head of the queue. + +=item ->extract() + +=item ->extract(INDEX) + +=item ->extract(INDEX, COUNT) + +Removes and returns the specified number of items (defaults to 1) from the +specified index position in the queue (0 is the head of the queue). When +called with no arguments, C operates the same as C. + +This method is non-blocking, and will return only as many items as are +available to fulfill the request: + + $q->enqueue(1, 2, 3, 4); + my $item = $q->extract(2) # Returns 3 + # Queue now contains: 1, 2, 4 + my @items = $q->extract(1, 3) # Returns (2, 4) + # Queue now contains: 1 + +Specifying an index position greater than the number of items in the +queue results in C or an empty list being returned. + + $q->enqueue('foo'); + my $nada = $q->extract(3) # Returns undef + my @nada = $q->extract(1, 3) # Returns () + +Negative index positions are supported. Specifying a negative index position +greater than the number of items in the queue may return items from the head +of the queue (similar to C) if the count overlaps the head of the +queue from the specified position (i.e. if queue size + index + count is +greater than zero): + + $q->enqueue(qw/foo bar baz/); + my @nada = $q->extract(-6, 2); # Returns () - (3+(-6)+2) <= 0 + my @some = $q->extract(-6, 4); # Returns (foo) - (3+(-6)+4) > 0 + # Queue now contains: bar, baz + my @rest = $q->extract(-3, 4); # Returns (bar, baz) - + # (2+(-3)+4) > 0 + +=back + +=head1 NOTES + +Queues created by L can be used in both threaded and +non-threaded applications. + +=head1 LIMITATIONS + +Passing objects on queues may not work if the objects' classes do not support +sharing. See L for more. + +Passing array/hash refs that contain objects may not work for Perl prior to +5.10.0. + +=head1 SEE ALSO + +Thread::Queue on MetaCPAN: +L + +Code repository for CPAN distribution: +L + +L, L + +Sample code in the I directory of this distribution on CPAN. + +=head1 MAINTAINER + +Jerry D. Hedden, Sjdhedden AT cpan DOT orgE> + +=head1 LICENSE + +This program is free software; you can redistribute it and/or modify it under +the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/core_perl/Thread/Semaphore.pm b/git/usr/share/perl5/core_perl/Thread/Semaphore.pm new file mode 100644 index 0000000000000000000000000000000000000000..0154798e2244dd288ad4aec3c3ff410842dd5218 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Thread/Semaphore.pm @@ -0,0 +1,273 @@ +package Thread::Semaphore; + +use strict; +use warnings; + +our $VERSION = '2.13'; +$VERSION = eval $VERSION; + +use threads::shared; +use Scalar::Util 1.10 qw(looks_like_number); + +# Predeclarations for internal functions +my ($validate_arg); + +# Create a new semaphore optionally with specified count (count defaults to 1) +sub new { + my $class = shift; + + my $val :shared = 1; + if (@_) { + $val = shift; + if (! defined($val) || + ! looks_like_number($val) || + (int($val) != $val)) + { + require Carp; + $val = 'undef' if (! defined($val)); + Carp::croak("Semaphore initializer is not an integer: $val"); + } + } + + return bless(\$val, $class); +} + +# Decrement a semaphore's count (decrement amount defaults to 1) +sub down { + my $sema = shift; + my $dec = @_ ? $validate_arg->(shift) : 1; + + lock($$sema); + cond_wait($$sema) until ($$sema >= $dec); + $$sema -= $dec; +} + +# Decrement a semaphore's count only if count >= decrement value +# (decrement amount defaults to 1) +sub down_nb { + my $sema = shift; + my $dec = @_ ? $validate_arg->(shift) : 1; + + lock($$sema); + my $ok = ($$sema >= $dec); + $$sema -= $dec if $ok; + return $ok; +} + +# Decrement a semaphore's count even if the count goes below 0 +# (decrement amount defaults to 1) +sub down_force { + my $sema = shift; + my $dec = @_ ? $validate_arg->(shift) : 1; + + lock($$sema); + $$sema -= $dec; +} + +# Decrement a semaphore's count with timeout +# (timeout in seconds; decrement amount defaults to 1) +sub down_timed { + my $sema = shift; + my $timeout = $validate_arg->(shift); + my $dec = @_ ? $validate_arg->(shift) : 1; + + lock($$sema); + my $abs = time() + $timeout; + until ($$sema >= $dec) { + return if !cond_timedwait($$sema, $abs); + } + $$sema -= $dec; + return 1; +} + +# Increment a semaphore's count (increment amount defaults to 1) +sub up { + my $sema = shift; + my $inc = @_ ? $validate_arg->(shift) : 1; + + lock($$sema); + ($$sema += $inc) > 0 and cond_broadcast($$sema); +} + +### Internal Functions ### + +# Validate method argument +$validate_arg = sub { + my $arg = shift; + + if (! defined($arg) || + ! looks_like_number($arg) || + (int($arg) != $arg) || + ($arg < 1)) + { + require Carp; + my ($method) = (caller(1))[3]; + $method =~ s/Thread::Semaphore:://; + $arg = 'undef' if (! defined($arg)); + Carp::croak("Argument to semaphore method '$method' is not a positive integer: $arg"); + } + + return $arg; +}; + +1; + +=head1 NAME + +Thread::Semaphore - Thread-safe semaphores + +=head1 VERSION + +This document describes Thread::Semaphore version 2.13 + +=head1 SYNOPSIS + + use Thread::Semaphore; + my $s = Thread::Semaphore->new(); + $s->down(); # Also known as the semaphore P operation. + # The guarded section is here + $s->up(); # Also known as the semaphore V operation. + + # Decrement the semaphore only if it would immediately succeed. + if ($s->down_nb()) { + # The guarded section is here + $s->up(); + } + + # Forcefully decrement the semaphore even if its count goes below 0. + $s->down_force(); + + # The default value for semaphore operations is 1 + my $s = Thread::Semaphore->new($initial_value); + $s->down($down_value); + $s->up($up_value); + if ($s->down_nb($down_value)) { + ... + $s->up($up_value); + } + $s->down_force($down_value); + +=head1 DESCRIPTION + +Semaphores provide a mechanism to regulate access to resources. Unlike +locks, semaphores aren't tied to particular scalars, and so may be used to +control access to anything you care to use them for. + +Semaphores don't limit their values to zero and one, so they can be used to +control access to some resource that there may be more than one of (e.g., +filehandles). Increment and decrement amounts aren't fixed at one either, +so threads can reserve or return multiple resources at once. + +=head1 METHODS + +=over 8 + +=item ->new() + +=item ->new(NUMBER) + +C creates a new semaphore, and initializes its count to the specified +number (which must be an integer). If no number is specified, the +semaphore's count defaults to 1. + +=item ->down() + +=item ->down(NUMBER) + +The C method decreases the semaphore's count by the specified number +(which must be an integer >= 1), or by one if no number is specified. + +If the semaphore's count would drop below zero, this method will block +until such time as the semaphore's count is greater than or equal to the +amount you're Cing the semaphore's count by. + +This is the semaphore "P operation" (the name derives from the Dutch +word "pak", which means "capture" -- the semaphore operations were +named by the late Dijkstra, who was Dutch). + +=item ->down_nb() + +=item ->down_nb(NUMBER) + +The C method attempts to decrease the semaphore's count by the +specified number (which must be an integer >= 1), or by one if no number +is specified. + +If the semaphore's count would drop below zero, this method will return +I, and the semaphore's count remains unchanged. Otherwise, the +semaphore's count is decremented and this method returns I. + +=item ->down_force() + +=item ->down_force(NUMBER) + +The C method decreases the semaphore's count by the specified +number (which must be an integer >= 1), or by one if no number is specified. +This method does not block, and may cause the semaphore's count to drop +below zero. + +=item ->down_timed(TIMEOUT) + +=item ->down_timed(TIMEOUT, NUMBER) + +The C method attempts to decrease the semaphore's count by 1 +or by the specified number within the specified timeout period given in +seconds (which must be an integer >= 0). + +If the semaphore's count would drop below zero, this method will block +until either the semaphore's count is greater than or equal to the +amount you're Cing the semaphore's count by, or until the timeout is +reached. + +If the timeout is reached, this method will return I, and the +semaphore's count remains unchanged. Otherwise, the semaphore's count is +decremented and this method returns I. + +=item ->up() + +=item ->up(NUMBER) + +The C method increases the semaphore's count by the number specified +(which must be an integer >= 1), or by one if no number is specified. + +This will unblock any thread that is blocked trying to C the +semaphore if the C raises the semaphore's count above the amount that +the C is trying to decrement it by. For example, if three threads +are blocked trying to C a semaphore by one, and another thread Cs +the semaphore by two, then two of the blocked threads (which two is +indeterminate) will become unblocked. + +This is the semaphore "V operation" (the name derives from the Dutch +word "vrij", which means "release"). + +=back + +=head1 NOTES + +Semaphores created by L can be used in both threaded and +non-threaded applications. This allows you to write modules and packages +that potentially make use of semaphores, and that will function in either +environment. + +=head1 SEE ALSO + +Thread::Semaphore on MetaCPAN: +L + +Code repository for CPAN distribution: +L + +L, L + +Sample code in the I directory of this distribution on CPAN. + +=head1 MAINTAINER + +Jerry D. Hedden, Sjdhedden AT cpan DOT orgE> + +=head1 LICENSE + +This program is free software; you can redistribute it and/or modify it under +the same terms as Perl itself. + +=cut diff --git a/git/usr/share/perl5/core_perl/Tie/Array.pm b/git/usr/share/perl5/core_perl/Tie/Array.pm new file mode 100644 index 0000000000000000000000000000000000000000..192983b42878e2b30c3e797e51d9fa886b98f00a --- /dev/null +++ b/git/usr/share/perl5/core_perl/Tie/Array.pm @@ -0,0 +1,283 @@ +package Tie::Array; + +use 5.006_001; +use strict; +use Carp; +our $VERSION = '1.07'; + +# Pod documentation after __END__ below. + +sub DESTROY { } +sub EXTEND { } +sub UNSHIFT { scalar shift->SPLICE(0,0,@_) } +sub SHIFT { shift->SPLICE(0,1) } +sub CLEAR { shift->STORESIZE(0) } + +sub PUSH +{ + my $obj = shift; + my $i = $obj->FETCHSIZE; + $obj->STORE($i++, shift) while (@_); +} + +sub POP +{ + my $obj = shift; + my $newsize = $obj->FETCHSIZE - 1; + my $val; + if ($newsize >= 0) + { + $val = $obj->FETCH($newsize); + $obj->STORESIZE($newsize); + } + $val; +} + +sub SPLICE { + my $obj = shift; + my $sz = $obj->FETCHSIZE; + my $off = (@_) ? shift : 0; + $off += $sz if ($off < 0); + my $len = (@_) ? shift : $sz - $off; + $len += $sz - $off if $len < 0; + my @result; + for (my $i = 0; $i < $len; $i++) { + push(@result,$obj->FETCH($off+$i)); + } + $off = $sz if $off > $sz; + $len -= $off + $len - $sz if $off + $len > $sz; + if (@_ > $len) { + # Move items up to make room + my $d = @_ - $len; + my $e = $off+$len; + $obj->EXTEND($sz+$d); + for (my $i=$sz-1; $i >= $e; $i--) { + my $val = $obj->FETCH($i); + $obj->STORE($i+$d,$val); + } + } + elsif (@_ < $len) { + # Move items down to close the gap + my $d = $len - @_; + my $e = $off+$len; + for (my $i=$off+$len; $i < $sz; $i++) { + my $val = $obj->FETCH($i); + $obj->STORE($i-$d,$val); + } + $obj->STORESIZE($sz-$d); + } + for (my $i=0; $i < @_; $i++) { + $obj->STORE($off+$i,$_[$i]); + } + return wantarray ? @result : pop @result; +} + +sub EXISTS { + my $pkg = ref $_[0]; + croak "$pkg doesn't define an EXISTS method"; +} + +sub DELETE { + my $pkg = ref $_[0]; + croak "$pkg doesn't define a DELETE method"; +} + +package Tie::StdArray; +our @ISA = 'Tie::Array'; + +sub TIEARRAY { bless [], $_[0] } +sub FETCHSIZE { scalar @{$_[0]} } +sub STORESIZE { $#{$_[0]} = $_[1]-1 } +sub STORE { $_[0]->[$_[1]] = $_[2] } +sub FETCH { $_[0]->[$_[1]] } +sub CLEAR { @{$_[0]} = () } +sub POP { pop(@{$_[0]}) } +sub PUSH { my $o = shift; push(@$o,@_) } +sub SHIFT { shift(@{$_[0]}) } +sub UNSHIFT { my $o = shift; unshift(@$o,@_) } +sub EXISTS { exists $_[0]->[$_[1]] } +sub DELETE { delete $_[0]->[$_[1]] } + +sub SPLICE +{ + my $ob = shift; + my $sz = $ob->FETCHSIZE; + my $off = @_ ? shift : 0; + $off += $sz if $off < 0; + my $len = @_ ? shift : $sz-$off; + return splice(@$ob,$off,$len,@_); +} + +1; + +__END__ + +=head1 NAME + +Tie::Array - base class for tied arrays + +=head1 SYNOPSIS + + package Tie::NewArray; + use Tie::Array; + @ISA = ('Tie::Array'); + + # mandatory methods + sub TIEARRAY { ... } + sub FETCH { ... } + sub FETCHSIZE { ... } + + sub STORE { ... } # mandatory if elements writeable + sub STORESIZE { ... } # mandatory if elements can be added/deleted + sub EXISTS { ... } # mandatory if exists() expected to work + sub DELETE { ... } # mandatory if delete() expected to work + + # optional methods - for efficiency + sub CLEAR { ... } + sub PUSH { ... } + sub POP { ... } + sub SHIFT { ... } + sub UNSHIFT { ... } + sub SPLICE { ... } + sub EXTEND { ... } + sub DESTROY { ... } + + package Tie::NewStdArray; + use Tie::Array; + + @ISA = ('Tie::StdArray'); + + # all methods provided by default + + package main; + + $object = tie @somearray,'Tie::NewArray'; + $object = tie @somearray,'Tie::StdArray'; + $object = tie @somearray,'Tie::NewStdArray'; + + + +=head1 DESCRIPTION + +This module provides methods for array-tying classes. See +L for a list of the functions required in order to tie an array +to a package. The basic B package provides stub C, +and C methods that do nothing, stub C and C +methods that croak() if the delete() or exists() builtins are ever called +on the tied array, and implementations of C, C, C, +C, C and C in terms of basic C, C, +C, C. + +The B package provides efficient methods required for tied arrays +which are implemented as blessed references to an "inner" perl array. +It inherits from B, and should cause tied arrays to behave exactly +like standard arrays, allowing for selective overloading of methods. + +For developers wishing to write their own tied arrays, the required methods +are briefly defined below. See the L section for more detailed +descriptive, as well as example code: + +=over 4 + +=item TIEARRAY classname, LIST + +The class method is invoked by the command C. Associates +an array instance with the specified class. C would represent +additional arguments (along the lines of L and compatriots) needed +to complete the association. The method should return an object of a class which +provides the methods below. + +=item STORE this, index, value + +Store datum I into I for the tied array associated with +object I. If this makes the array larger then +class's mapping of C should be returned for new positions. + +=item FETCH this, index + +Retrieve the datum in I for the tied array associated with +object I. + +=item FETCHSIZE this + +Returns the total number of items in the tied array associated with +object I. (Equivalent to C). + +=item STORESIZE this, count + +Sets the total number of items in the tied array associated with +object I to be I. If this makes the array larger then +class's mapping of C should be returned for new positions. +If the array becomes smaller then entries beyond count should be +deleted. + +=item EXTEND this, count + +Informative call that array is likely to grow to have I entries. +Can be used to optimize allocation. This method need do nothing. + +=item EXISTS this, key + +Verify that the element at index I exists in the tied array I. + +The B implementation is a stub that simply croaks. + +=item DELETE this, key + +Delete the element at index I from the tied array I. + +The B implementation is a stub that simply croaks. + +=item CLEAR this + +Clear (remove, delete, ...) all values from the tied array associated with +object I. + +=item DESTROY this + +Normal object destructor method. + +=item PUSH this, LIST + +Append elements of LIST to the array. + +=item POP this + +Remove last element of the array and return it. + +=item SHIFT this + +Remove the first element of the array (shifting other elements down) +and return it. + +=item UNSHIFT this, LIST + +Insert LIST elements at the beginning of the array, moving existing elements +up to make room. + +=item SPLICE this, offset, length, LIST + +Perform the equivalent of C on the array. + +I is optional and defaults to zero, negative values count back +from the end of the array. + +I is optional and defaults to rest of the array. + +I may be empty. + +Returns a list of the original I elements at I. + +=back + +=head1 CAVEATS + +There is no support at present for tied @ISA. There is a potential conflict +between magic entries needed to notice setting of @ISA, and those needed to +implement 'tie'. + +=head1 AUTHOR + +Nick Ing-Simmons Enik@tiuk.ti.comE + +=cut diff --git a/git/usr/share/perl5/core_perl/Tie/File.pm b/git/usr/share/perl5/core_perl/Tie/File.pm new file mode 100644 index 0000000000000000000000000000000000000000..bd348badc2a1cb8279132baf28fe48dcc4845f68 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Tie/File.pm @@ -0,0 +1,2639 @@ +package Tie::File; + +use strict; +use warnings; + +use Carp ':DEFAULT', 'confess'; +use POSIX 'SEEK_SET'; +use Fcntl 'O_CREAT', 'O_RDWR', 'LOCK_EX', 'LOCK_SH', 'O_WRONLY', 'O_RDONLY'; +use constant O_ACCMODE => O_RDONLY | O_RDWR | O_WRONLY; + + +our $VERSION = "1.10"; +my $DEFAULT_MEMORY_SIZE = 1<<21; # 2 megabytes +my $DEFAULT_AUTODEFER_THRESHHOLD = 3; # 3 records +my $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD = 65536; # 16 disk blocksful + +my %good_opt = map {$_ => 1, "-$_" => 1} + qw(memory dw_size mode recsep discipline + autodefer autochomp autodefer_threshhold concurrent); + +our $DIAGNOSTIC = 0; +our @OFF; # used as a temporary alias in some subroutines. +our @H; # used as a temporary alias in _annotate_ad_history + +sub TIEARRAY { + if (@_ % 2 != 0) { + croak "usage: tie \@array, $_[0], filename, [option => value]..."; + } + my ($pack, $file, %opts) = @_; + + # transform '-foo' keys into 'foo' keys + for my $key (keys %opts) { + unless ($good_opt{$key}) { + croak("$pack: Unrecognized option '$key'\n"); + } + my $okey = $key; + if ($key =~ s/^-+//) { + $opts{$key} = delete $opts{$okey}; + } + } + + if ($opts{concurrent}) { + croak("$pack: concurrent access not supported yet\n"); + } + + unless (defined $opts{memory}) { + # default is the larger of the default cache size and the + # deferred-write buffer size (if specified) + $opts{memory} = $DEFAULT_MEMORY_SIZE; + $opts{memory} = $opts{dw_size} + if defined $opts{dw_size} && $opts{dw_size} > $DEFAULT_MEMORY_SIZE; + # Dora Winifred Read + } + $opts{dw_size} = $opts{memory} unless defined $opts{dw_size}; + if ($opts{dw_size} > $opts{memory}) { + croak("$pack: dw_size may not be larger than total memory allocation\n"); + } + # are we in deferred-write mode? + $opts{defer} = 0 unless defined $opts{defer}; + $opts{deferred} = {}; # no records are presently deferred + $opts{deferred_s} = 0; # count of total bytes in ->{deferred} + $opts{deferred_max} = -1; # empty + + # What's a good way to arrange that this class can be overridden? + $opts{cache} = Tie::File::Cache->new($opts{memory}); + + # autodeferment is enabled by default + $opts{autodefer} = 1 unless defined $opts{autodefer}; + $opts{autodeferring} = 0; # but is not initially active + $opts{ad_history} = []; + $opts{autodefer_threshhold} = $DEFAULT_AUTODEFER_THRESHHOLD + unless defined $opts{autodefer_threshhold}; + $opts{autodefer_filelen_threshhold} = $DEFAULT_AUTODEFER_FILELEN_THRESHHOLD + unless defined $opts{autodefer_filelen_threshhold}; + + $opts{offsets} = [0]; + $opts{filename} = $file; + unless (defined $opts{recsep}) { + $opts{recsep} = _default_recsep(); + } + $opts{recseplen} = length($opts{recsep}); + if ($opts{recseplen} == 0) { + croak "Empty record separator not supported by $pack"; + } + + $opts{autochomp} = 1 unless defined $opts{autochomp}; + + $opts{mode} = O_CREAT|O_RDWR unless defined $opts{mode}; + $opts{rdonly} = (($opts{mode} & O_ACCMODE) == O_RDONLY); + $opts{sawlastrec} = undef; + + my $fh; + + if (UNIVERSAL::isa($file, 'GLOB')) { + # We use 1 here on the theory that some systems + # may not indicate failure if we use 0. + # MSWin32 does not indicate failure with 0, but I don't know if + # it will indicate failure with 1 or not. + unless (seek $file, 1, SEEK_SET) { + croak "$pack: your filehandle does not appear to be seekable"; + } + seek $file, 0, SEEK_SET; # put it back + $fh = $file; # setting binmode is the user's problem + } elsif (ref $file) { + croak "usage: tie \@array, $pack, filename, [option => value]..."; + } else { + sysopen $fh, $file, $opts{mode}, 0666 or return; + binmode $fh; + ++$opts{ourfh}; + } + { my $ofh = select $fh; $| = 1; select $ofh } # autoflush on write + if (defined $opts{discipline}) { + eval { binmode($fh, $opts{discipline}) }; + croak $@ if $@ =~ /Unknown discipline|IO layers .* unavailable/; + die if $@; + } + $opts{fh} = $fh; + + bless \%opts => $pack; +} + +sub FETCH { + my ($self, $n) = @_; + my $rec; + + # check the defer buffer + $rec = $self->{deferred}{$n} if exists $self->{deferred}{$n}; + $rec = $self->_fetch($n) unless defined $rec; + + # inlined _chomp1 + substr($rec, - $self->{recseplen}) = "" + if defined $rec && $self->{autochomp}; + $rec; +} + +# Chomp many records in-place; return nothing useful +sub _chomp { + my $self = shift; + return unless $self->{autochomp}; + if ($self->{autochomp}) { + for (@_) { + next unless defined; + substr($_, - $self->{recseplen}) = ""; + } + } +} + +# Chomp one record in-place; return modified record +sub _chomp1 { + my ($self, $rec) = @_; + return $rec unless $self->{autochomp}; + return unless defined $rec; + substr($rec, - $self->{recseplen}) = ""; + $rec; +} + +sub _fetch { + my ($self, $n) = @_; + + # check the record cache + { my $cached = $self->{cache}->lookup($n); + return $cached if defined $cached; + } + + if ($#{$self->{offsets}} < $n) { + return if $self->{eof}; # request for record beyond end of file + my $o = $self->_fill_offsets_to($n); + # If it's still undefined, there is no such record, so return 'undef' + return unless defined $o; + } + + my $fh = $self->{FH}; + $self->_seek($n); # we can do this now that offsets is populated + my $rec = $self->_read_record; + +# If we happen to have just read the first record, check to see if +# the length of the record matches what 'tell' says. If not, Tie::File +# won't work, and should drop dead. +# +# if ($n == 0 && defined($rec) && tell($self->{fh}) != length($rec)) { +# if (defined $self->{discipline}) { +# croak "I/O discipline $self->{discipline} not supported"; +# } else { +# croak "File encoding not supported"; +# } +# } + + $self->{cache}->insert($n, $rec) if defined $rec && not $self->{flushing}; + $rec; +} + +sub STORE { + my ($self, $n, $rec) = @_; + die "STORE called from _check_integrity!" if $DIAGNOSTIC; + + $self->_fixrecs($rec); + + if ($self->{autodefer}) { + $self->_annotate_ad_history($n); + } + + return $self->_store_deferred($n, $rec) if $self->_is_deferring; + + + # We need this to decide whether the new record will fit + # It incidentally populates the offsets table + # Note we have to do this before we alter the cache + # 20020324 Wait, but this DOES alter the cache. TODO BUG? + my $oldrec = $self->_fetch($n); + + if (not defined $oldrec) { + # We're storing a record beyond the end of the file + $self->_extend_file_to($n+1); + $oldrec = $self->{recsep}; + } +# return if $oldrec eq $rec; # don't bother + my $len_diff = length($rec) - length($oldrec); + + # length($oldrec) here is not consistent with text mode TODO XXX BUG + $self->_mtwrite($rec, $self->{offsets}[$n], length($oldrec)); + $self->_oadjust([$n, 1, $rec]); + $self->{cache}->update($n, $rec); +} + +sub _store_deferred { + my ($self, $n, $rec) = @_; + $self->{cache}->remove($n); + my $old_deferred = $self->{deferred}{$n}; + + if (defined $self->{deferred_max} && $n > $self->{deferred_max}) { + $self->{deferred_max} = $n; + } + $self->{deferred}{$n} = $rec; + + my $len_diff = length($rec); + $len_diff -= length($old_deferred) if defined $old_deferred; + $self->{deferred_s} += $len_diff; + $self->{cache}->adj_limit(-$len_diff); + if ($self->{deferred_s} > $self->{dw_size}) { + $self->_flush; + } elsif ($self->_cache_too_full) { + $self->_cache_flush; + } +} + +# Remove a single record from the deferred-write buffer without writing it +# The record need not be present +sub _delete_deferred { + my ($self, $n) = @_; + my $rec = delete $self->{deferred}{$n}; + return unless defined $rec; + + if (defined $self->{deferred_max} + && $n == $self->{deferred_max}) { + undef $self->{deferred_max}; + } + + $self->{deferred_s} -= length $rec; + $self->{cache}->adj_limit(length $rec); +} + +sub FETCHSIZE { + my $self = shift; + my $n = $self->{eof} ? $#{$self->{offsets}} : $self->_fill_offsets; + + my $top_deferred = $self->_defer_max; + $n = $top_deferred+1 if defined $top_deferred && $n < $top_deferred+1; + $n; +} + +sub STORESIZE { + my ($self, $len) = @_; + + if ($self->{autodefer}) { + $self->_annotate_ad_history('STORESIZE'); + } + + my $olen = $self->FETCHSIZE; + return if $len == $olen; # Woo-hoo! + + # file gets longer + if ($len > $olen) { + if ($self->_is_deferring) { + for ($olen .. $len-1) { + $self->_store_deferred($_, $self->{recsep}); + } + } else { + $self->_extend_file_to($len); + } + return; + } + + # file gets shorter + if ($self->_is_deferring) { + # TODO maybe replace this with map-plus-assignment? + for (grep $_ >= $len, keys %{$self->{deferred}}) { + $self->_delete_deferred($_); + } + $self->{deferred_max} = $len-1; + } + + $self->_seek($len); + $self->_chop_file; + $#{$self->{offsets}} = $len; +# $self->{offsets}[0] = 0; # in case we just chopped this + + $self->{cache}->remove(grep $_ >= $len, $self->{cache}->ckeys); +} + +### OPTIMIZE ME +### It should not be necessary to do FETCHSIZE +### Just seek to the end of the file. +sub PUSH { + my $self = shift; + $self->SPLICE($self->FETCHSIZE, scalar(@_), @_); + + # No need to return: + # $self->FETCHSIZE; # because av.c takes care of this for me +} + +sub POP { + my $self = shift; + my $size = $self->FETCHSIZE; + return if $size == 0; +# print STDERR "# POPPITY POP POP POP\n"; + scalar $self->SPLICE($size-1, 1); +} + +sub SHIFT { + my $self = shift; + scalar $self->SPLICE(0, 1); +} + +sub UNSHIFT { + my $self = shift; + $self->SPLICE(0, 0, @_); + # $self->FETCHSIZE; # av.c takes care of this for me +} + +sub CLEAR { + my $self = shift; + + if ($self->{autodefer}) { + $self->_annotate_ad_history('CLEAR'); + } + + $self->_seekb(0); + $self->_chop_file; + $self->{cache}->set_limit($self->{memory}); + $self->{cache}->empty; + @{$self->{offsets}} = (0); + %{$self->{deferred}}= (); + $self->{deferred_s} = 0; + $self->{deferred_max} = -1; +} + +sub EXTEND { + my ($self, $n) = @_; + + # No need to pre-extend anything in this case + return if $self->_is_deferring; + + $self->_fill_offsets_to($n); + $self->_extend_file_to($n); +} + +sub DELETE { + my ($self, $n) = @_; + + if ($self->{autodefer}) { + $self->_annotate_ad_history('DELETE'); + } + + my $lastrec = $self->FETCHSIZE-1; + my $rec = $self->FETCH($n); + $self->_delete_deferred($n) if $self->_is_deferring; + if ($n == $lastrec) { + $self->_seek($n); + $self->_chop_file; + $#{$self->{offsets}}--; + $self->{cache}->remove($n); + # perhaps in this case I should also remove trailing null records? + # 20020316 + # Note that delete @a[-3..-1] deletes the records in the wrong order, + # so we only chop the very last one out of the file. We could repair this + # by tracking deleted records inside the object. + } elsif ($n < $lastrec) { + $self->STORE($n, ""); + } + $rec; +} + +sub EXISTS { + my ($self, $n) = @_; + return 1 if exists $self->{deferred}{$n}; + $n < $self->FETCHSIZE; +} + +sub SPLICE { + my $self = shift; + + if ($self->{autodefer}) { + $self->_annotate_ad_history('SPLICE'); + } + + $self->_flush if $self->_is_deferring; # move this up? + if (wantarray) { + $self->_chomp(my @a = $self->_splice(@_)); + @a; + } else { + $self->_chomp1(scalar $self->_splice(@_)); + } +} + +sub DESTROY { + my $self = shift; + $self->flush if $self->_is_deferring; + $self->{cache}->delink if defined $self->{cache}; # break circular link + if ($self->{fh} and $self->{ourfh}) { + delete $self->{ourfh}; + close delete $self->{fh}; + } +} + +sub _splice { + my ($self, $pos, $nrecs, @data) = @_; + my @result; + + $pos = 0 unless defined $pos; + + # Deal with negative and other out-of-range positions + # Also set default for $nrecs + { + my $oldsize = $self->FETCHSIZE; + $nrecs = $oldsize unless defined $nrecs; + my $oldpos = $pos; + + if ($pos < 0) { + $pos += $oldsize; + if ($pos < 0) { + croak "Modification of non-creatable array value attempted, " . + "subscript $oldpos"; + } + } + + if ($pos > $oldsize) { + return unless @data; + $pos = $oldsize; # This is what perl does for normal arrays + } + + # The manual is very unclear here + if ($nrecs < 0) { + $nrecs = $oldsize - $pos + $nrecs; + $nrecs = 0 if $nrecs < 0; + } + + # nrecs is too big---it really means "until the end" + # 20030507 + if ($nrecs + $pos > $oldsize) { + $nrecs = $oldsize - $pos; + } + } + + $self->_fixrecs(@data); + my $data = join '', @data; + my $datalen = length $data; + my $oldlen = 0; + + # compute length of data being removed + for ($pos .. $pos+$nrecs-1) { + last unless defined $self->_fill_offsets_to($_); + my $rec = $self->_fetch($_); + last unless defined $rec; + push @result, $rec; + + # Why don't we just use length($rec) here? + # Because that record might have come from the cache. _splice + # might have been called to flush out the deferred-write records, + # and in this case length($rec) is the length of the record to be + # *written*, not the length of the actual record in the file. But + # the offsets are still true. 20020322 + $oldlen += $self->{offsets}[$_+1] - $self->{offsets}[$_] + if defined $self->{offsets}[$_+1]; + } + $self->_fill_offsets_to($pos+$nrecs); + + # Modify the file + $self->_mtwrite($data, $self->{offsets}[$pos], $oldlen); + # Adjust the offsets table + $self->_oadjust([$pos, $nrecs, @data]); + + { # Take this read cache stuff out into a separate function + # You made a half-attempt to put it into _oadjust. + # Finish something like that up eventually. + # STORE also needs to do something similarish + + # update the read cache, part 1 + # modified records + for ($pos .. $pos+$nrecs-1) { + my $new = $data[$_-$pos]; + if (defined $new) { + $self->{cache}->update($_, $new); + } else { + $self->{cache}->remove($_); + } + } + + # update the read cache, part 2 + # moved records - records past the site of the change + # need to be renumbered + # Maybe merge this with the previous block? + { + my @oldkeys = grep $_ >= $pos + $nrecs, $self->{cache}->ckeys; + my @newkeys = map $_-$nrecs+@data, @oldkeys; + $self->{cache}->rekey(\@oldkeys, \@newkeys); + } + + # Now there might be too much data in the cache, if we spliced out + # some short records and spliced in some long ones. If so, flush + # the cache. + $self->_cache_flush; + } + + # Yes, the return value of 'splice' *is* actually this complicated + wantarray ? @result : @result ? $result[-1] : undef; +} + + +# write data into the file +# $data is the data to be written. +# it should be written at position $pos, and should overwrite +# exactly $len of the following bytes. +# Note that if length($data) > $len, the subsequent bytes will have to +# be moved up, and if length($data) < $len, they will have to +# be moved down +sub _twrite { + my ($self, $data, $pos, $len) = @_; + + unless (defined $pos) { + die "\$pos was undefined in _twrite"; + } + + my $len_diff = length($data) - $len; + + if ($len_diff == 0) { # Woo-hoo! + my $fh = $self->{fh}; + $self->_seekb($pos); + $self->_write_record($data); + return; # well, that was easy. + } + + # the two records are of different lengths + # our strategy here: rewrite the tail of the file, + # reading ahead one buffer at a time + # $bufsize is required to be at least as large as the data we're overwriting + my $bufsize = _bufsize($len_diff); + my ($writepos, $readpos) = ($pos, $pos+$len); + my $next_block; + my $more_data; + + # Seems like there ought to be a way to avoid the repeated code + # and the special case here. The read(1) is also a little weird. + # Think about this. + do { + $self->_seekb($readpos); + my $br = read $self->{fh}, $next_block, $bufsize; + $more_data = read $self->{fh}, my($dummy), 1; + $self->_seekb($writepos); + $self->_write_record($data); + $readpos += $br; + $writepos += length $data; + $data = $next_block; + } while $more_data; + $self->_seekb($writepos); + $self->_write_record($next_block); + + # There might be leftover data at the end of the file + $self->_chop_file if $len_diff < 0; +} + +# _iwrite(D, S, E) +# Insert text D at position S. +# Let C = E-S-|D|. If C < 0; die. +# Data in [S,S+C) is copied to [S+D,S+D+C) = [S+D,E). +# Data in [S+C = E-D, E) is returned. Data in [E, oo) is untouched. +# +# In a later version, don't read the entire intervening area into +# memory at once; do the copying block by block. +sub _iwrite { + my $self = shift; + my ($D, $s, $e) = @_; + my $d = length $D; + my $c = $e-$s-$d; + local *FH = $self->{fh}; + confess "Not enough space to insert $d bytes between $s and $e" + if $c < 0; + confess "[$s,$e) is an invalid insertion range" if $e < $s; + + $self->_seekb($s); + read FH, my $buf, $e-$s; + + $D .= substr($buf, 0, $c, ""); + + $self->_seekb($s); + $self->_write_record($D); + + return $buf; +} + +# Like _twrite, but the data-pos-len triple may be repeated; you may +# write several chunks. All the writing will be done in +# one pass. Chunks SHALL be in ascending order and SHALL NOT overlap. +sub _mtwrite { + my $self = shift; + my $unwritten = ""; + my $delta = 0; + + @_ % 3 == 0 + or die "Arguments to _mtwrite did not come in groups of three"; + + while (@_) { + my ($data, $pos, $len) = splice @_, 0, 3; + my $end = $pos + $len; # The OLD end of the segment to be replaced + $data = $unwritten . $data; + $delta -= length($unwritten); + $unwritten = ""; + $pos += $delta; # This is where the data goes now + my $dlen = length $data; + $self->_seekb($pos); + if ($len >= $dlen) { # the data will fit + $self->_write_record($data); + $delta += ($dlen - $len); # everything following moves down by this much + $data = ""; # All the data in the buffer has been written + } else { # won't fit + my $writable = substr($data, 0, $len - $delta, ""); + $self->_write_record($writable); + $delta += ($dlen - $len); # everything following moves down by this much + } + + # At this point we've written some but maybe not all of the data. + # There might be a gap to close up, or $data might still contain a + # bunch of unwritten data that didn't fit. + my $ndlen = length $data; + if ($delta == 0) { + $self->_write_record($data); + } elsif ($delta < 0) { + # upcopy (close up gap) + if (@_) { + $self->_upcopy($end, $end + $delta, $_[1] - $end); + } else { + $self->_upcopy($end, $end + $delta); + } + } else { + # downcopy (insert data that didn't fit; replace this data in memory + # with _later_ data that doesn't fit) + if (@_) { + $unwritten = $self->_downcopy($data, $end, $_[1] - $end); + } else { + # Make the file longer to accommodate the last segment that doesn't + $unwritten = $self->_downcopy($data, $end); + } + } + } +} + +# Copy block of data of length $len from position $spos to position $dpos +# $dpos must be <= $spos +# +# If $len is undefined, go all the way to the end of the file +# and then truncate it ($spos - $dpos bytes will be removed) +sub _upcopy { + my $blocksize = 8192; + my ($self, $spos, $dpos, $len) = @_; + if ($dpos > $spos) { + die "source ($spos) was upstream of destination ($dpos) in _upcopy"; + } elsif ($dpos == $spos) { + return; + } + + while (! defined ($len) || $len > 0) { + my $readsize = ! defined($len) ? $blocksize + : $len > $blocksize ? $blocksize + : $len; + + my $fh = $self->{fh}; + $self->_seekb($spos); + my $bytes_read = read $fh, my($data), $readsize; + $self->_seekb($dpos); + if ($data eq "") { + $self->_chop_file; + last; + } + $self->_write_record($data); + $spos += $bytes_read; + $dpos += $bytes_read; + $len -= $bytes_read if defined $len; + } +} + +# Write $data into a block of length $len at position $pos, +# moving everything in the block forwards to make room. +# Instead of writing the last length($data) bytes from the block +# (because there isn't room for them any longer) return them. +# +# Undefined $len means 'until the end of the file' +sub _downcopy { + my $blocksize = 8192; + my ($self, $data, $pos, $len) = @_; + my $fh = $self->{fh}; + + while (! defined $len || $len > 0) { + my $readsize = ! defined($len) ? $blocksize + : $len > $blocksize? $blocksize : $len; + $self->_seekb($pos); + read $fh, my($old), $readsize; + my $last_read_was_short = length($old) < $readsize; + $data .= $old; + my $writable; + if ($last_read_was_short) { + # If last read was short, then $data now contains the entire rest + # of the file, so there's no need to write only one block of it + $writable = $data; + $data = ""; + } else { + $writable = substr($data, 0, $readsize, ""); + } + last if $writable eq ""; + $self->_seekb($pos); + $self->_write_record($writable); + last if $last_read_was_short && $data eq ""; + $len -= $readsize if defined $len; + $pos += $readsize; + } + return $data; +} + +# Adjust the object data structures following an '_mtwrite' +# Arguments are +# [$pos, $nrecs, @length] items +# indicating that $nrecs records were removed at $recpos (a record offset) +# and replaced with records of length @length... +# Arguments guarantee that $recpos is strictly increasing. +# No return value +sub _oadjust { + my $self = shift; + my $delta = 0; + my $delta_recs = 0; + my $prev_end = -1; + + for (@_) { + my ($pos, $nrecs, @data) = @$_; + $pos += $delta_recs; + + # Adjust the offsets of the records after the previous batch up + # to the first new one of this batch + for my $i ($prev_end+2 .. $pos - 1) { + $self->{offsets}[$i] += $delta; + } + + $prev_end = $pos + @data - 1; # last record moved on this pass + + # Remove the offsets for the removed records; + # replace with the offsets for the inserted records + my @newoff = ($self->{offsets}[$pos] + $delta); + for my $i (0 .. $#data) { + my $newlen = length $data[$i]; + push @newoff, $newoff[$i] + $newlen; + $delta += $newlen; + } + + for my $i ($pos .. $pos+$nrecs-1) { + last if $i+1 > $#{$self->{offsets}}; + my $oldlen = $self->{offsets}[$i+1] - $self->{offsets}[$i]; + $delta -= $oldlen; + } + + # replace old offsets with new + splice @{$self->{offsets}}, $pos, $nrecs+1, @newoff; + # What if we just spliced out the end of the offsets table? + # shouldn't we clear $self->{eof}? Test for this XXX BUG TODO + + $delta_recs += @data - $nrecs; # net change in total number of records + } + + # The trailing records at the very end of the file + if ($delta) { + for my $i ($prev_end+2 .. $#{$self->{offsets}}) { + $self->{offsets}[$i] += $delta; + } + } + + # If we scrubbed out all known offsets, regenerate the trivial table + # that knows that the file does indeed start at 0. + $self->{offsets}[0] = 0 unless @{$self->{offsets}}; + # If the file got longer, the offsets table is no longer complete + # $self->{eof} = 0 if $delta_recs > 0; + + # Now there might be too much data in the cache, if we spliced out + # some short records and spliced in some long ones. If so, flush + # the cache. + $self->_cache_flush; +} + +# If a record does not already end with the appropriate terminator +# string, append one. +sub _fixrecs { + my $self = shift; + for (@_) { + $_ = "" unless defined $_; + $_ .= $self->{recsep} + unless substr($_, - $self->{recseplen}) eq $self->{recsep}; + } +} + + +################################################################ +# +# Basic read, write, and seek +# + +# seek to the beginning of record #$n +# Assumes that the offsets table is already correctly populated +# +# Note that $n=-1 has a special meaning here: It means the start of +# the last known record; this may or may not be the very last record +# in the file, depending on whether the offsets table is fully populated. +# +sub _seek { + my ($self, $n) = @_; + my $o = $self->{offsets}[$n]; + defined($o) + or confess("logic error: undefined offset for record $n"); + seek $self->{fh}, $o, SEEK_SET + or confess "Couldn't seek filehandle: $!"; # "Should never happen." +} + +# seek to byte $b in the file +sub _seekb { + my ($self, $b) = @_; + seek $self->{fh}, $b, SEEK_SET + or die "Couldn't seek filehandle: $!"; # "Should never happen." +} + +# populate the offsets table up to the beginning of record $n +# return the offset of record $n +sub _fill_offsets_to { + my ($self, $n) = @_; + + return $self->{offsets}[$n] if $self->{eof}; + + my $fh = $self->{fh}; + local *OFF = $self->{offsets}; + my $rec; + + until ($#OFF >= $n) { + $self->_seek(-1); # tricky -- see comment at _seek + $rec = $self->_read_record; + if (defined $rec) { + push @OFF, int(tell $fh); # Tels says that int() saves memory here + } else { + $self->{eof} = 1; + return; # It turns out there is no such record + } + } + + # we have now read all the records up to record n-1, + # so we can return the offset of record n + $OFF[$n]; +} + +sub _fill_offsets { + my ($self) = @_; + + my $fh = $self->{fh}; + local *OFF = $self->{offsets}; + + $self->_seek(-1); # tricky -- see comment at _seek + + # Tels says that inlining read_record() would make this loop + # five times faster. 20030508 + while ( defined $self->_read_record()) { + # int() saves us memory here + push @OFF, int(tell $fh); + } + + $self->{eof} = 1; + $#OFF; +} + +# assumes that $rec is already suitably terminated +sub _write_record { + my ($self, $rec) = @_; + my $fh = $self->{fh}; + local $\ = ""; + print $fh $rec + or die "Couldn't write record: $!"; # "Should never happen." +# $self->{_written} += length($rec); +} + +sub _read_record { + my $self = shift; + my $rec; + { local $/ = $self->{recsep}; + my $fh = $self->{fh}; + $rec = <$fh>; + } + return unless defined $rec; + if (substr($rec, -$self->{recseplen}) ne $self->{recsep}) { + # improperly terminated final record --- quietly fix it. +# my $ac = substr($rec, -$self->{recseplen}); +# $ac =~ s/\n/\\n/g; + $self->{sawlastrec} = 1; + unless ($self->{rdonly}) { + local $\ = ""; + my $fh = $self->{fh}; + print $fh $self->{recsep}; + } + $rec .= $self->{recsep}; + } +# $self->{_read} += length($rec) if defined $rec; + $rec; +} + +sub _rw_stats { + my $self = shift; + @{$self}{'_read', '_written'}; +} + +################################################################ +# +# Read cache management + +sub _cache_flush { + my ($self) = @_; + $self->{cache}->reduce_size_to($self->{memory} - $self->{deferred_s}); +} + +sub _cache_too_full { + my $self = shift; + $self->{cache}->bytes + $self->{deferred_s} >= $self->{memory}; +} + +################################################################ +# +# File custodial services +# + + +# We have read to the end of the file and have the offsets table +# entirely populated. Now we need to write a new record beyond +# the end of the file. We prepare for this by writing +# empty records into the file up to the position we want +# +# assumes that the offsets table already contains the offset of record $n, +# if it exists, and extends to the end of the file if not. +sub _extend_file_to { + my ($self, $n) = @_; + $self->_seek(-1); # position after the end of the last record + my $pos = $self->{offsets}[-1]; + + # the offsets table has one entry more than the total number of records + my $extras = $n - $#{$self->{offsets}}; + + # Todo : just use $self->{recsep} x $extras here? + while ($extras-- > 0) { + $self->_write_record($self->{recsep}); + push @{$self->{offsets}}, int(tell $self->{fh}); + } +} + +# Truncate the file at the current position +sub _chop_file { + my $self = shift; + truncate $self->{fh}, tell($self->{fh}); +} + + +# compute the size of a buffer suitable for moving +# all the data in a file forward $n bytes +# ($n may be negative) +# The result should be at least $n. +sub _bufsize { + my $n = shift; + return 8192 if $n <= 0; + my $b = $n & ~8191; + $b += 8192 if $n & 8191; + $b; +} + +################################################################ +# +# Miscellaneous public methods +# + +# Lock the file +sub flock { + my ($self, $op) = @_; + unless (@_ <= 3) { + my $pack = ref $self; + croak "Usage: $pack\->flock([OPERATION])"; + } + my $fh = $self->{fh}; + $op = LOCK_EX unless defined $op; + my $locked = flock $fh, $op; + + if ($locked && ($op & (LOCK_EX | LOCK_SH))) { + # If you're locking the file, then presumably it's because + # there might have been a write access by another process. + # In that case, the read cache contents and the offsets table + # might be invalid, so discard them. 20030508 + $self->{offsets} = [0]; + $self->{cache}->empty; + } + + $locked; +} + +# Get/set autochomp option +sub autochomp { + my $self = shift; + if (@_) { + my $old = $self->{autochomp}; + $self->{autochomp} = shift; + $old; + } else { + $self->{autochomp}; + } +} + +# Get offset table entries; returns offset of nth record +sub offset { + my ($self, $n) = @_; + + if ($#{$self->{offsets}} < $n) { + return if $self->{eof}; # request for record beyond the end of file + my $o = $self->_fill_offsets_to($n); + # If it's still undefined, there is no such record, so return 'undef' + return unless defined $o; + } + + $self->{offsets}[$n]; +} + +sub discard_offsets { + my $self = shift; + $self->{offsets} = [0]; +} + +################################################################ +# +# Matters related to deferred writing +# + +# Defer writes +sub defer { + my $self = shift; + $self->_stop_autodeferring; + @{$self->{ad_history}} = (); + $self->{defer} = 1; +} + +# Flush deferred writes +# +# This could be better optimized to write the file in one pass, instead +# of one pass per block of records. But that will require modifications +# to _twrite, so I should have a good _twrite test suite first. +sub flush { + my $self = shift; + + $self->_flush; + $self->{defer} = 0; +} + +sub _old_flush { + my $self = shift; + my @writable = sort {$a<=>$b} (keys %{$self->{deferred}}); + + while (@writable) { + # gather all consecutive records from the front of @writable + my $first_rec = shift @writable; + my $last_rec = $first_rec+1; + ++$last_rec, shift @writable while @writable && $last_rec == $writable[0]; + --$last_rec; + $self->_fill_offsets_to($last_rec); + $self->_extend_file_to($last_rec); + $self->_splice($first_rec, $last_rec-$first_rec+1, + @{$self->{deferred}}{$first_rec .. $last_rec}); + } + + $self->_discard; # clear out defered-write-cache +} + +sub _flush { + my $self = shift; + my @writable = sort {$a<=>$b} (keys %{$self->{deferred}}); + my @args; + my @adjust; + + while (@writable) { + # gather all consecutive records from the front of @writable + my $first_rec = shift @writable; + my $last_rec = $first_rec+1; + ++$last_rec, shift @writable while @writable && $last_rec == $writable[0]; + --$last_rec; + my $end = $self->_fill_offsets_to($last_rec+1); + if (not defined $end) { + $self->_extend_file_to($last_rec); + $end = $self->{offsets}[$last_rec]; + } + my ($start) = $self->{offsets}[$first_rec]; + push @args, + join("", @{$self->{deferred}}{$first_rec .. $last_rec}), # data + $start, # position + $end-$start; # length + push @adjust, [$first_rec, # starting at this position... + $last_rec-$first_rec+1, # this many records... + # are replaced with these... + @{$self->{deferred}}{$first_rec .. $last_rec}, + ]; + } + + $self->_mtwrite(@args); # write multiple record groups + $self->_discard; # clear out defered-write-cache + $self->_oadjust(@adjust); +} + +# Discard deferred writes and disable future deferred writes +sub discard { + my $self = shift; + $self->_discard; + $self->{defer} = 0; +} + +# Discard deferred writes, but retain old deferred writing mode +sub _discard { + my $self = shift; + %{$self->{deferred}} = (); + $self->{deferred_s} = 0; + $self->{deferred_max} = -1; + $self->{cache}->set_limit($self->{memory}); +} + +# Deferred writing is enabled, either explicitly ($self->{defer}) +# or automatically ($self->{autodeferring}) +sub _is_deferring { + my $self = shift; + $self->{defer} || $self->{autodeferring}; +} + +# The largest record number of any deferred record +sub _defer_max { + my $self = shift; + return $self->{deferred_max} if defined $self->{deferred_max}; + my $max = -1; + for my $key (keys %{$self->{deferred}}) { + $max = $key if $key > $max; + } + $self->{deferred_max} = $max; + $max; +} + +################################################################ +# +# Matters related to autodeferment +# + +# Get/set autodefer option +sub autodefer { + my $self = shift; + if (@_) { + my $old = $self->{autodefer}; + $self->{autodefer} = shift; + if ($old) { + $self->_stop_autodeferring; + @{$self->{ad_history}} = (); + } + $old; + } else { + $self->{autodefer}; + } +} + +# The user is trying to store record #$n Record that in the history, +# and then enable (or disable) autodeferment if that seems useful. +# Note that it's OK for $n to be a non-number, as long as the function +# is prepared to deal with that. Nobody else looks at the ad_history. +# +# Now, what does the ad_history mean, and what is this function doing? +# Essentially, the idea is to enable autodeferring when we see that the +# user has made three consecutive STORE calls to three consecutive records. +# ("Three" is actually ->{autodefer_threshhold}.) +# A STORE call for record #$n inserts $n into the autodefer history, +# and if the history contains three consecutive records, we enable +# autodeferment. An ad_history of [X, Y] means that the most recent +# STOREs were for records X, X+1, ..., Y, in that order. +# +# Inserting a nonconsecutive number erases the history and starts over. +# +# Performing a special operation like SPLICE erases the history. +# +# There's one special case: CLEAR means that CLEAR was just called. +# In this case, we prime the history with [-2, -1] so that if the next +# write is for record 0, autodeferring goes on immediately. This is for +# the common special case of "@a = (...)". +# +sub _annotate_ad_history { + my ($self, $n) = @_; + return unless $self->{autodefer}; # feature is disabled + return if $self->{defer}; # already in explicit defer mode + return unless $self->{offsets}[-1] >= $self->{autodefer_filelen_threshhold}; + + local *H = $self->{ad_history}; + if ($n eq 'CLEAR') { + @H = (-2, -1); # prime the history with fake records + $self->_stop_autodeferring; + } elsif ($n =~ /^\d+$/) { + if (@H == 0) { + @H = ($n, $n); + } else { # @H == 2 + if ($H[1] == $n-1) { # another consecutive record + $H[1]++; + if ($H[1] - $H[0] + 1 >= $self->{autodefer_threshhold}) { + $self->{autodeferring} = 1; + } + } else { # nonconsecutive- erase and start over + @H = ($n, $n); + $self->_stop_autodeferring; + } + } + } else { # SPLICE or STORESIZE or some such + @H = (); + $self->_stop_autodeferring; + } +} + +# If autodeferring was enabled, cut it out and discard the history +sub _stop_autodeferring { + my $self = shift; + if ($self->{autodeferring}) { + $self->_flush; + } + $self->{autodeferring} = 0; +} + +################################################################ + + +# This is NOT a method. It is here for two reasons: +# 1. To factor a fairly complicated block out of the constructor +# 2. To provide access for the test suite, which need to be sure +# files are being written properly. +sub _default_recsep { + my $recsep = $/; + if ($^O eq 'MSWin32') { # Dos too? + # Windows users expect files to be terminated with \r\n + # But $/ is set to \n instead + # Note that this also transforms \n\n into \r\n\r\n. + # That is a feature. + $recsep =~ s/\n/\r\n/g; + } + $recsep; +} + +# Utility function for _check_integrity +sub _ci_warn { + my $msg = shift; + $msg =~ s/\n/\\n/g; + $msg =~ s/\r/\\r/g; + print "# $msg\n"; +} + +# Given a file, make sure the cache is consistent with the +# file contents and the internal data structures are consistent with +# each other. Returns true if everything checks out, false if not +# +# The $file argument is no longer used. It is retained for compatibility +# with the existing test suite. +sub _check_integrity { + my ($self, $file, $warn) = @_; + my $rsl = $self->{recseplen}; + my $rs = $self->{recsep}; + my $good = 1; + local *_; # local $_ does not work here + local $DIAGNOSTIC = 1; + + if (not defined $rs) { + _ci_warn("recsep is undef!"); + $good = 0; + } elsif ($rs eq "") { + _ci_warn("recsep is empty!"); + $good = 0; + } elsif ($rsl != length $rs) { + my $ln = length $rs; + _ci_warn("recsep <$rs> has length $ln, should be $rsl"); + $good = 0; + } + + if (not defined $self->{offsets}[0]) { + _ci_warn("offset 0 is missing!"); + $good = 0; + + } elsif ($self->{offsets}[0] != 0) { + _ci_warn("rec 0: offset <$self->{offsets}[0]> s/b 0!"); + $good = 0; + } + + my $cached = 0; + { + local *F = $self->{fh}; + seek F, 0, SEEK_SET; + local $. = 0; + local $/ = $rs; + + while () { + my $n = $. - 1; + my $cached = $self->{cache}->_produce($n); + my $offset = $self->{offsets}[$.]; + my $ao = tell F; + if (defined $offset && $offset != $ao) { + _ci_warn("rec $n: offset <$offset> actual <$ao>"); + $good = 0; + } + if (defined $cached && $_ ne $cached && ! $self->{deferred}{$n}) { + $good = 0; + _ci_warn("rec $n: cached <$cached> actual <$_>"); + } + if (defined $cached && substr($cached, -$rsl) ne $rs) { + $good = 0; + _ci_warn("rec $n in the cache is missing the record separator"); + } + if (! defined $offset && $self->{eof}) { + $good = 0; + _ci_warn("The offset table was marked complete, but it is missing " . + "element $."); + } + } + if (@{$self->{offsets}} > $.+1) { + $good = 0; + my $n = @{$self->{offsets}}; + _ci_warn("The offset table has $n items, but the file has only $."); + } + + my $deferring = $self->_is_deferring; + for my $n ($self->{cache}->ckeys) { + my $r = $self->{cache}->_produce($n); + $cached += length($r); + next if $n+1 <= $.; # checked this already + _ci_warn("spurious caching of record $n"); + $good = 0; + } + my $b = $self->{cache}->bytes; + if ($cached != $b) { + _ci_warn("cache size is $b, should be $cached"); + $good = 0; + } + } + + # That cache has its own set of tests + $good = 0 unless $self->{cache}->_check_integrity; + + # Now let's check the deferbuffer + # Unless deferred writing is enabled, it should be empty + if (! $self->_is_deferring && %{$self->{deferred}}) { + _ci_warn("deferred writing disabled, but deferbuffer nonempty"); + $good = 0; + } + + # Any record in the deferbuffer should *not* be present in the readcache + my $deferred_s = 0; + while (my ($n, $r) = each %{$self->{deferred}}) { + $deferred_s += length($r); + if (defined $self->{cache}->_produce($n)) { + _ci_warn("record $n is in the deferbuffer *and* the readcache"); + $good = 0; + } + if (substr($r, -$rsl) ne $rs) { + _ci_warn("rec $n in the deferbuffer is missing the record separator"); + $good = 0; + } + } + + # Total size of deferbuffer should match internal total + if ($deferred_s != $self->{deferred_s}) { + _ci_warn("buffer size is $self->{deferred_s}, should be $deferred_s"); + $good = 0; + } + + # Total size of deferbuffer should not exceed the specified limit + if ($deferred_s > $self->{dw_size}) { + _ci_warn("buffer size is $self->{deferred_s} which exceeds the limit " . + "of $self->{dw_size}"); + $good = 0; + } + + # Total size of cached data should not exceed the specified limit + if ($deferred_s + $cached > $self->{memory}) { + my $total = $deferred_s + $cached; + _ci_warn("total stored data size is $total which exceeds the limit " . + "of $self->{memory}"); + $good = 0; + } + + # Stuff related to autodeferment + if (!$self->{autodefer} && @{$self->{ad_history}}) { + _ci_warn("autodefer is disabled, but ad_history is nonempty"); + $good = 0; + } + if ($self->{autodeferring} && $self->{defer}) { + _ci_warn("both autodeferring and explicit deferring are active"); + $good = 0; + } + if (@{$self->{ad_history}} == 0) { + # That's OK, no additional tests required + } elsif (@{$self->{ad_history}} == 2) { + my @non_number = grep !/^-?\d+$/, @{$self->{ad_history}}; + if (@non_number) { + my $msg; + { local $" = ')('; + $msg = "ad_history contains non-numbers (@{$self->{ad_history}})"; + } + _ci_warn($msg); + $good = 0; + } elsif ($self->{ad_history}[1] < $self->{ad_history}[0]) { + _ci_warn("ad_history has nonsensical values @{$self->{ad_history}}"); + $good = 0; + } + } else { + _ci_warn("ad_history has bad length <@{$self->{ad_history}}>"); + $good = 0; + } + + $good; +} + +################################################################ +# +# Tie::File::Cache +# +# Read cache + +package Tie::File::Cache; +$Tie::File::Cache::VERSION = $Tie::File::VERSION; +use Carp ':DEFAULT', 'confess'; + +use constant { + HEAP => 0, + HASH => 1, + MAX => 2, + BYTES => 3, + #STAT => 4, # Array with request statistics for each record + #MISS => 5, # Total number of cache misses + #REQ => 6, # Total number of cache requests +}; + +sub new { + my ($pack, $max) = @_; + local *_; + croak "missing argument to ->new" unless defined $max; + my $self = []; + bless $self => $pack; + @$self = (Tie::File::Heap->new($self), {}, $max, 0); + $self; +} + +sub adj_limit { + my ($self, $n) = @_; + $self->[MAX] += $n; +} + +sub set_limit { + my ($self, $n) = @_; + $self->[MAX] = $n; +} + +# For internal use only +# Will be called by the heap structure to notify us that a certain +# piece of data has moved from one heap element to another. +# $k is the hash key of the item +# $n is the new index into the heap at which it is stored +# If $n is undefined, the item has been removed from the heap. +sub _heap_move { + my ($self, $k, $n) = @_; + if (defined $n) { + $self->[HASH]{$k} = $n; + } else { + delete $self->[HASH]{$k}; + } +} + +sub insert { + my ($self, $key, $val) = @_; + local *_; + croak "missing argument to ->insert" unless defined $key; + unless (defined $self->[MAX]) { + confess "undefined max" ; + } + confess "undefined val" unless defined $val; + return if length($val) > $self->[MAX]; + +# if ($self->[STAT]) { +# $self->[STAT][$key] = 1; +# return; +# } + + my $oldnode = $self->[HASH]{$key}; + if (defined $oldnode) { + my $oldval = $self->[HEAP]->set_val($oldnode, $val); + $self->[BYTES] -= length($oldval); + } else { + $self->[HEAP]->insert($key, $val); + } + $self->[BYTES] += length($val); + $self->flush if $self->[BYTES] > $self->[MAX]; +} + +sub expire { + my $self = shift; + my $old_data = $self->[HEAP]->popheap; + return unless defined $old_data; + $self->[BYTES] -= length $old_data; + $old_data; +} + +sub remove { + my ($self, @keys) = @_; + my @result; + +# if ($self->[STAT]) { +# for my $key (@keys) { +# $self->[STAT][$key] = 0; +# } +# return; +# } + + for my $key (@keys) { + next unless exists $self->[HASH]{$key}; + my $old_data = $self->[HEAP]->remove($self->[HASH]{$key}); + $self->[BYTES] -= length $old_data; + push @result, $old_data; + } + @result; +} + +sub lookup { + my ($self, $key) = @_; + local *_; + croak "missing argument to ->lookup" unless defined $key; + +# if ($self->[STAT]) { +# $self->[MISS]++ if $self->[STAT][$key]++ == 0; +# $self->[REQ]++; +# my $hit_rate = 1 - $self->[MISS] / $self->[REQ]; +# # Do some testing to determine this threshhold +# $#$self = STAT - 1 if $hit_rate > 0.20; +# } + + if (exists $self->[HASH]{$key}) { + $self->[HEAP]->lookup($self->[HASH]{$key}); + } else { + return; + } +} + +# For internal use only +sub _produce { + my ($self, $key) = @_; + my $loc = $self->[HASH]{$key}; + return unless defined $loc; + $self->[HEAP][$loc][2]; +} + +# For internal use only +sub _promote { + my ($self, $key) = @_; + $self->[HEAP]->promote($self->[HASH]{$key}); +} + +sub empty { + my ($self) = @_; + %{$self->[HASH]} = (); + $self->[BYTES] = 0; + $self->[HEAP]->empty; +# @{$self->[STAT]} = (); +# $self->[MISS] = 0; +# $self->[REQ] = 0; +} + +sub is_empty { + my ($self) = @_; + keys %{$self->[HASH]} == 0; +} + +sub update { + my ($self, $key, $val) = @_; + local *_; + croak "missing argument to ->update" unless defined $key; + if (length($val) > $self->[MAX]) { + my ($oldval) = $self->remove($key); + $self->[BYTES] -= length($oldval) if defined $oldval; + } elsif (exists $self->[HASH]{$key}) { + my $oldval = $self->[HEAP]->set_val($self->[HASH]{$key}, $val); + $self->[BYTES] += length($val); + $self->[BYTES] -= length($oldval) if defined $oldval; + } else { + $self->[HEAP]->insert($key, $val); + $self->[BYTES] += length($val); + } + $self->flush; +} + +sub rekey { + my ($self, $okeys, $nkeys) = @_; + local *_; + my %map; + @map{@$okeys} = @$nkeys; + croak "missing argument to ->rekey" unless defined $nkeys; + croak "length mismatch in ->rekey arguments" unless @$nkeys == @$okeys; + my %adjusted; # map new keys to heap indices + # You should be able to cut this to one loop TODO XXX + for (0 .. $#$okeys) { + $adjusted{$nkeys->[$_]} = delete $self->[HASH]{$okeys->[$_]}; + } + while (my ($nk, $ix) = each %adjusted) { + # @{$self->[HASH]}{keys %adjusted} = values %adjusted; + $self->[HEAP]->rekey($ix, $nk); + $self->[HASH]{$nk} = $ix; + } +} + +sub ckeys { + my $self = shift; + my @a = keys %{$self->[HASH]}; + @a; +} + +# Return total amount of cached data +sub bytes { + my $self = shift; + $self->[BYTES]; +} + +# Expire oldest item from cache until cache size is smaller than $max +sub reduce_size_to { + my ($self, $max) = @_; + until ($self->[BYTES] <= $max) { + # Note that Tie::File::Cache::expire has been inlined here + my $old_data = $self->[HEAP]->popheap; + return unless defined $old_data; + $self->[BYTES] -= length $old_data; + } +} + +# Why not just $self->reduce_size_to($self->[MAX])? +# Try this when things stabilize TODO XXX +# If the cache is too full, expire the oldest records +sub flush { + my $self = shift; + $self->reduce_size_to($self->[MAX]) if $self->[BYTES] > $self->[MAX]; +} + +# For internal use only +sub _produce_lru { + my $self = shift; + $self->[HEAP]->expire_order; +} + +BEGIN { *_ci_warn = \&Tie::File::_ci_warn } + +sub _check_integrity { # For CACHE + my $self = shift; + my $good = 1; + + # Test HEAP + $self->[HEAP]->_check_integrity or $good = 0; + + # Test HASH + my $bytes = 0; + for my $k (keys %{$self->[HASH]}) { + if ($k ne '0' && $k !~ /^[1-9][0-9]*$/) { + $good = 0; + _ci_warn "Cache hash key <$k> is non-numeric"; + } + + my $h = $self->[HASH]{$k}; + if (! defined $h) { + $good = 0; + _ci_warn "Heap index number for key $k is undefined"; + } elsif ($h == 0) { + $good = 0; + _ci_warn "Heap index number for key $k is zero"; + } else { + my $j = $self->[HEAP][$h]; + if (! defined $j) { + $good = 0; + _ci_warn "Heap contents key $k (=> $h) are undefined"; + } else { + $bytes += length($j->[2]); + if ($k ne $j->[1]) { + $good = 0; + _ci_warn "Heap contents key $k (=> $h) is $j->[1], should be $k"; + } + } + } + } + + # Test BYTES + if ($bytes != $self->[BYTES]) { + $good = 0; + _ci_warn "Total data in cache is $bytes, expected $self->[BYTES]"; + } + + # Test MAX + if ($bytes > $self->[MAX]) { + $good = 0; + _ci_warn "Total data in cache is $bytes, exceeds maximum $self->[MAX]"; + } + + return $good; +} + +sub delink { + my $self = shift; + $self->[HEAP] = undef; # Bye bye heap +} + +################################################################ +# +# Tie::File::Heap +# +# Heap data structure for use by cache LRU routines + +package Tie::File::Heap; +use Carp ':DEFAULT', 'confess'; +$Tie::File::Heap::VERSION = $Tie::File::Cache::VERSION; +use constant { + SEQ => 0, + KEY => 1, + DAT => 2, +}; + +sub new { + my ($pack, $cache) = @_; + die "$pack: Parent cache object $cache does not support _heap_move method" + unless eval { $cache->can('_heap_move') }; + my $self = [[0,$cache,0]]; + bless $self => $pack; +} + +# Allocate a new sequence number, larger than all previously allocated numbers +sub _nseq { + my $self = shift; + $self->[0][0]++; +} + +sub _cache { + my $self = shift; + $self->[0][1]; +} + +sub _nelts { + my $self = shift; + $self->[0][2]; +} + +sub _nelts_inc { + my $self = shift; + ++$self->[0][2]; +} + +sub _nelts_dec { + my $self = shift; + --$self->[0][2]; +} + +sub is_empty { + my $self = shift; + $self->_nelts == 0; +} + +sub empty { + my $self = shift; + $#$self = 0; + $self->[0][2] = 0; + $self->[0][0] = 0; # might as well reset the sequence numbers +} + +# notify the parent cache object that we moved something +sub _heap_move { + my $self = shift; + $self->_cache->_heap_move(@_); +} + +# Insert a piece of data into the heap with the indicated sequence number. +# The item with the smallest sequence number is always at the top. +# If no sequence number is specified, allocate a new one and insert the +# item at the bottom. +sub insert { + my ($self, $key, $data, $seq) = @_; + $seq = $self->_nseq unless defined $seq; + $self->_insert_new([$seq, $key, $data]); +} + +# Insert a new, fresh item at the bottom of the heap +sub _insert_new { + my ($self, $item) = @_; + my $i = @$self; + $i = int($i/2) until defined $self->[$i/2]; + $self->[$i] = $item; + $self->[0][1]->_heap_move($self->[$i][KEY], $i); + $self->_nelts_inc; +} + +# Insert [$data, $seq] pair at or below item $i in the heap. +# If $i is omitted, default to 1 (the top element.) +sub _insert { + my ($self, $item, $i) = @_; +# $self->_check_loc($i) if defined $i; + $i = 1 unless defined $i; + until (! defined $self->[$i]) { + if ($self->[$i][SEQ] > $item->[SEQ]) { # inserted item is older + ($self->[$i], $item) = ($item, $self->[$i]); + $self->[0][1]->_heap_move($self->[$i][KEY], $i); + } + # If either is undefined, go that way. Otherwise, choose at random + my $dir; + $dir = 0 if !defined $self->[2*$i]; + $dir = 1 if !defined $self->[2*$i+1]; + $dir = int(rand(2)) unless defined $dir; + $i = 2*$i + $dir; + } + $self->[$i] = $item; + $self->[0][1]->_heap_move($self->[$i][KEY], $i); + $self->_nelts_inc; +} + +# Remove the item at node $i from the heap, moving child items upwards. +# The item with the smallest sequence number is always at the top. +# Moving items upwards maintains this condition. +# Return the removed item. Return undef if there was no item at node $i. +sub remove { + my ($self, $i) = @_; + $i = 1 unless defined $i; + my $top = $self->[$i]; + return unless defined $top; + while (1) { + my $ii; + my ($L, $R) = (2*$i, 2*$i+1); + + # If either is undefined, go the other way. + # Otherwise, go towards the smallest. + last unless defined $self->[$L] || defined $self->[$R]; + $ii = $R if not defined $self->[$L]; + $ii = $L if not defined $self->[$R]; + unless (defined $ii) { + $ii = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R; + } + + $self->[$i] = $self->[$ii]; # Promote child to fill vacated spot + $self->[0][1]->_heap_move($self->[$i][KEY], $i); + $i = $ii; # Fill new vacated spot + } + $self->[0][1]->_heap_move($top->[KEY], undef); + undef $self->[$i]; + $self->_nelts_dec; + return $top->[DAT]; +} + +sub popheap { + my $self = shift; + $self->remove(1); +} + +# set the sequence number of the indicated item to a higher number +# than any other item in the heap, and bubble the item down to the +# bottom. +sub promote { + my ($self, $n) = @_; +# $self->_check_loc($n); + $self->[$n][SEQ] = $self->_nseq; + my $i = $n; + while (1) { + my ($L, $R) = (2*$i, 2*$i+1); + my $dir; + last unless defined $self->[$L] || defined $self->[$R]; + $dir = $R unless defined $self->[$L]; + $dir = $L unless defined $self->[$R]; + unless (defined $dir) { + $dir = $self->[$L][SEQ] < $self->[$R][SEQ] ? $L : $R; + } + @{$self}[$i, $dir] = @{$self}[$dir, $i]; + for ($i, $dir) { + $self->[0][1]->_heap_move($self->[$_][KEY], $_) if defined $self->[$_]; + } + $i = $dir; + } +} + +# Return item $n from the heap, promoting its LRU status +sub lookup { + my ($self, $n) = @_; +# $self->_check_loc($n); + my $val = $self->[$n]; + $self->promote($n); + $val->[DAT]; +} + + +# Assign a new value for node $n, promoting it to the bottom of the heap +sub set_val { + my ($self, $n, $val) = @_; +# $self->_check_loc($n); + my $oval = $self->[$n][DAT]; + $self->[$n][DAT] = $val; + $self->promote($n); + return $oval; +} + +# The hash key has changed for an item; +# alter the heap's record of the hash key +sub rekey { + my ($self, $n, $new_key) = @_; +# $self->_check_loc($n); + $self->[$n][KEY] = $new_key; +} + +sub _check_loc { + my ($self, $n) = @_; + unless (1 || defined $self->[$n]) { + confess "_check_loc($n) failed"; + } +} + +BEGIN { *_ci_warn = \&Tie::File::_ci_warn } + +sub _check_integrity { + my $self = shift; + my $good = 1; + my %seq; + + unless (eval {$self->[0][1]->isa("Tie::File::Cache")}) { + _ci_warn "Element 0 of heap corrupt"; + $good = 0; + } + $good = 0 unless $self->_satisfies_heap_condition(1); + for my $i (2 .. $#{$self}) { + my $p = int($i/2); # index of parent node + if (defined $self->[$i] && ! defined $self->[$p]) { + _ci_warn "Element $i of heap defined, but parent $p isn't"; + $good = 0; + } + + if (defined $self->[$i]) { + if ($seq{$self->[$i][SEQ]}) { + my $seq = $self->[$i][SEQ]; + _ci_warn "Nodes $i and $seq{$seq} both have SEQ=$seq"; + $good = 0; + } else { + $seq{$self->[$i][SEQ]} = $i; + } + } + } + + return $good; +} + +sub _satisfies_heap_condition { + my $self = shift; + my $n = shift || 1; + my $good = 1; + for (0, 1) { + my $c = $n*2 + $_; + next unless defined $self->[$c]; + if ($self->[$n][SEQ] >= $self->[$c]) { + _ci_warn "Node $n of heap does not predate node $c"; + $good = 0 ; + } + $good = 0 unless $self->_satisfies_heap_condition($c); + } + return $good; +} + +# Return a list of all the values, sorted by expiration order +sub expire_order { + my $self = shift; + my @nodes = sort {$a->[SEQ] <=> $b->[SEQ]} $self->_nodes; + map { $_->[KEY] } @nodes; +} + +sub _nodes { + my $self = shift; + my $i = shift || 1; + return unless defined $self->[$i]; + ($self->[$i], $self->_nodes($i*2), $self->_nodes($i*2+1)); +} + +1; + +__END__ + +=head1 NAME + +Tie::File - Access the lines of a disk file via a Perl array + +=head1 SYNOPSIS + + use Tie::File; + + tie @array, 'Tie::File', filename or die ...; + + $array[0] = 'blah'; # first line of the file is now 'blah' + # (line numbering starts at 0) + print $array[42]; # display line 43 of the file + + $n_recs = @array; # how many records are in the file? + $#array -= 2; # chop two records off the end + + + for (@array) { + s/PERL/Perl/g; # Replace PERL with Perl everywhere in the file + } + + # These are just like regular push, pop, unshift, shift, and splice + # Except that they modify the file in the way you would expect + + push @array, new recs...; + my $r1 = pop @array; + unshift @array, new recs...; + my $r2 = shift @array; + @old_recs = splice @array, 3, 7, new recs...; + + untie @array; # all finished + + +=head1 DESCRIPTION + +C represents a regular text file as a Perl array. Each +element in the array corresponds to a record in the file. The first +line of the file is element 0 of the array; the second line is element +1, and so on. + +The file is I loaded into memory, so this will work even for +gigantic files. + +Changes to the array are reflected in the file immediately. + +Lazy people and beginners may now stop reading the manual. + +=head2 C + +You can read a unicode (UTF-8) file by providing a file handle opened with +the desired encoding. It is not safe to write to one because +the length in bytes and in characters is often different, Tie::File +will miscalculate the length of writes, overwriting parts of other records. + +=head2 C + +What is a 'record'? By default, the meaning is the same as for the +C...E> operator: It's a string terminated by C<$/>, which is +probably C<"\n">. (Minor exception: on DOS and Win32 systems, a +'record' is a string terminated by C<"\r\n">.) You may change the +definition of "record" by supplying the C option in the C +call: + + tie @array, 'Tie::File', $file, recsep => 'es'; + +This says that records are delimited by the string C. If the file +contained the following data: + + Curse these pesky flies!\n + +then the C<@array> would appear to have four elements: + + "Curse th" + "e p" + "ky fli" + "!\n" + +An undefined value is not permitted as a record separator. Perl's +special "paragraph mode" semantics (E la C<$/ = "">) are not +emulated. + +Records read from the tied array do not have the record separator +string on the end; this is to allow + + $array[17] .= "extra"; + +to work as expected. + +(See L<"autochomp">, below.) Records stored into the array will have +the record separator string appended before they are written to the +file, if they don't have one already. For example, if the record +separator string is C<"\n">, then the following two lines do exactly +the same thing: + + $array[17] = "Cherry pie"; + $array[17] = "Cherry pie\n"; + +The result is that the contents of line 17 of the file will be +replaced with "Cherry pie"; a newline character will separate line 17 +from line 18. This means that this code will do nothing: + + chomp $array[17]; + +Because the Ced value will have the separator reattached when +it is written back to the file. There is no way to create a file +whose trailing record separator string is missing. + +Inserting records that I the record separator string is not +supported by this module. It will probably produce a reasonable +result, but what this result will be may change in a future version. +Use 'splice' to insert records or to replace one record with several. + +=head2 C + +Normally, array elements have the record separator removed, so that if +the file contains the text + + Gold + Frankincense + Myrrh + +the tied array will appear to contain C<("Gold", "Frankincense", +"Myrrh")>. If you set C to a false value, the record +separator will not be removed. If the file above was tied with + + tie @gifts, "Tie::File", $gifts, autochomp => 0; + +then the array C<@gifts> would appear to contain C<("Gold\n", +"Frankincense\n", "Myrrh\n")>, or (on Win32 systems) C<("Gold\r\n", +"Frankincense\r\n", "Myrrh\r\n")>. + +=head2 C + +Normally, the specified file will be opened for read and write access, +and will be created if it does not exist. (That is, the flags +C are supplied in the C call.) If you want to +change this, you may supply alternative flags in the C option. +See L for a listing of available flags. +For example: + + # open the file if it exists, but fail if it does not exist + use Fcntl 'O_RDWR'; + tie @array, 'Tie::File', $file, mode => O_RDWR; + + # create the file if it does not exist + use Fcntl 'O_RDWR', 'O_CREAT'; + tie @array, 'Tie::File', $file, mode => O_RDWR | O_CREAT; + + # open an existing file in read-only mode + use Fcntl 'O_RDONLY'; + tie @array, 'Tie::File', $file, mode => O_RDONLY; + +Opening the data file in write-only or append mode is not supported. + +=head2 C + +This is an upper limit on the amount of memory that C will +consume at any time while managing the file. This is used for two +things: managing the I and managing the I. + +Records read in from the file are cached, to avoid having to re-read +them repeatedly. If you read the same record twice, the first time it +will be stored in memory, and the second time it will be fetched from +the I. The amount of data in the read cache will not +exceed the value you specified for C. If C wants +to cache a new record, but the read cache is full, it will make room +by expiring the least-recently visited records from the read cache. + +The default memory limit is 2Mib. You can adjust the maximum read +cache size by supplying the C option. The argument is the +desired cache size, in bytes. + + # I have a lot of memory, so use a large cache to speed up access + tie @array, 'Tie::File', $file, memory => 20_000_000; + +Setting the memory limit to 0 will inhibit caching; records will be +fetched from disk every time you examine them. + +The C value is not an absolute or exact limit on the memory +used. C objects contains some structures besides the read +cache and the deferred write buffer, whose sizes are not charged +against C. + +The cache itself consumes about 310 bytes per cached record, so if +your file has many short records, you may want to decrease the cache +memory limit, or else the cache overhead may exceed the size of the +cached data. + + +=head2 C + +(This is an advanced feature. Skip this section on first reading.) + +If you use deferred writing (See L<"Deferred Writing">, below) then +data you write into the array will not be written directly to the +file; instead, it will be saved in the I to be +written out later. Data in the deferred write buffer is also charged +against the memory limit you set with the C option. + +You may set the C option to limit the amount of data that can +be saved in the deferred write buffer. This limit may not exceed the +total memory limit. For example, if you set C to 1000 and +C to 2500, that means that no more than 1000 bytes of deferred +writes will be saved up. The space available for the read cache will +vary, but it will always be at least 1500 bytes (if the deferred write +buffer is full) and it could grow as large as 2500 bytes (if the +deferred write buffer is empty.) + +If you don't specify a C, it defaults to the entire memory +limit. + +=head2 Option Format + +C<-mode> is a synonym for C. C<-recsep> is a synonym for +C. C<-memory> is a synonym for C. You get the +idea. + +=head1 Public Methods + +The C call returns an object, say C<$o>. You may call + + $rec = $o->FETCH($n); + $o->STORE($n, $rec); + +to fetch or store the record at line C<$n>, respectively; similarly +the other tied array methods. (See L for details.) You may +also call the following methods on this object: + +=head2 C + + $o->flock(MODE) + +will lock the tied file. C has the same meaning as the second +argument to the Perl built-in C function; for example +C or C. (These constants are provided by +the C declaration.) + +C is optional; the default is C. + +C maintains an internal table of the byte offset of each +record it has seen in the file. + +When you use C to lock the file, C assumes that the +read cache is no longer trustworthy, because another process might +have modified the file since the last time it was read. Therefore, a +successful call to C discards the contents of the read cache +and the internal record offset table. + +C promises that the following sequence of operations will +be safe: + + my $o = tie @array, "Tie::File", $filename; + $o->flock; + +In particular, C will I read or write the file during +the C call. (Exception: Using C O_TRUNC> will, of +course, erase the file during the C call. If you want to do this +safely, then open the file without C, lock the file, and use +C<@array = ()>.) + +The best way to unlock a file is to discard the object and untie the +array. It is probably unsafe to unlock the file without also untying +it, because if you do, changes may remain unwritten inside the object. +That is why there is no shortcut for unlocking. If you really want to +unlock the file prematurely, you know what to do; if you don't know +what to do, then don't do it. + +All the usual warnings about file locking apply here. In particular, +note that file locking in Perl is B, which means that +holding a lock will not prevent anyone else from reading, writing, or +erasing the file; it only prevents them from getting another lock at +the same time. Locks are analogous to green traffic lights: If you +have a green light, that does not prevent the idiot coming the other +way from plowing into you sideways; it merely guarantees to you that +the idiot does not also have a green light at the same time. + +=head2 C + + my $old_value = $o->autochomp(0); # disable autochomp option + my $old_value = $o->autochomp(1); # enable autochomp option + + my $ac = $o->autochomp(); # recover current value + +See L<"autochomp">, above. + +=head2 C, C, C, and C + +See L<"Deferred Writing">, below. + +=head2 C + + $off = $o->offset($n); + +This method returns the byte offset of the start of the C<$n>th record +in the file. If there is no such record, it returns an undefined +value. + +=head1 Tying to an already-opened filehandle + +If C<$fh> is a filehandle, such as is returned by C or one +of the other C modules, you may use: + + tie @array, 'Tie::File', $fh, ...; + +Similarly if you opened that handle C with regular C or +C, you may use: + + tie @array, 'Tie::File', \*FH, ...; + +Handles that were opened write-only won't work. Handles that were +opened read-only will work as long as you don't try to modify the +array. Handles must be attached to seekable sources of data---that +means no pipes or sockets. If C can detect that you +supplied a non-seekable handle, the C call will throw an +exception. (On Unix systems, it can detect this.) + +Note that Tie::File will only close any filehandles that it opened +internally. If you passed it a filehandle as above, you "own" the +filehandle, and are responsible for closing it after you have untied +the @array. + +Tie::File calls C on filehandles that it opens internally, +but not on filehandles passed in by the user. For consistency, +especially if using the tied files cross-platform, you may wish to +call C on the filehandle prior to tying the file. + +=head1 Deferred Writing + +(This is an advanced feature. Skip this section on first reading.) + +Normally, modifying a C array writes to the underlying file +immediately. Every assignment like C<$a[3] = ...> rewrites as much of +the file as is necessary; typically, everything from line 3 through +the end will need to be rewritten. This is the simplest and most +transparent behavior. Performance even for large files is reasonably +good. + +However, under some circumstances, this behavior may be excessively +slow. For example, suppose you have a million-record file, and you +want to do: + + for (@FILE) { + $_ = "> $_"; + } + +The first time through the loop, you will rewrite the entire file, +from line 0 through the end. The second time through the loop, you +will rewrite the entire file from line 1 through the end. The third +time through the loop, you will rewrite the entire file from line 2 to +the end. And so on. + +If the performance in such cases is unacceptable, you may defer the +actual writing, and then have it done all at once. The following loop +will perform much better for large files: + + (tied @a)->defer; + for (@a) { + $_ = "> $_"; + } + (tied @a)->flush; + +If C's memory limit is large enough, all the writing will +done in memory. Then, when you call C<-Eflush>, the entire file +will be rewritten in a single pass. + +(Actually, the preceding discussion is something of a fib. You don't +need to enable deferred writing to get good performance for this +common case, because C will do it for you automatically +unless you specifically tell it not to. See L, +below.) + +Calling C<-Eflush> returns the array to immediate-write mode. If +you wish to discard the deferred writes, you may call C<-Ediscard> +instead of C<-Eflush>. Note that in some cases, some of the data +will have been written already, and it will be too late for +C<-Ediscard> to discard all the changes. Support for +C<-Ediscard> may be withdrawn in a future version of C. + +Deferred writes are cached in memory up to the limit specified by the +C option (see above). If the deferred-write buffer is full +and you try to write still more deferred data, the buffer will be +flushed. All buffered data will be written immediately, the buffer +will be emptied, and the now-empty space will be used for future +deferred writes. + +If the deferred-write buffer isn't yet full, but the total size of the +buffer and the read cache would exceed the C limit, the oldest +records will be expired from the read cache until the total size is +under the limit. + +C, C, C, C, and C cannot be +deferred. When you perform one of these operations, any deferred data +is written to the file and the operation is performed immediately. +This may change in a future version. + +If you resize the array with deferred writing enabled, the file will +be resized immediately, but deferred records will not be written. +This has a surprising consequence: C<@a = (...)> erases the file +immediately, but the writing of the actual data is deferred. This +might be a bug. If it is a bug, it will be fixed in a future version. + +=head2 Autodeferring + +C tries to guess when deferred writing might be helpful, +and to turn it on and off automatically. + + for (@a) { + $_ = "> $_"; + } + +In this example, only the first two assignments will be done +immediately; after this, all the changes to the file will be deferred +up to the user-specified memory limit. + +You should usually be able to ignore this and just use the module +without thinking about deferring. However, special applications may +require fine control over which writes are deferred, or may require +that all writes be immediate. To disable the autodeferment feature, +use + + (tied @o)->autodefer(0); + +or + + tie @array, 'Tie::File', $file, autodefer => 0; + + +Similarly, C<-Eautodefer(1)> re-enables autodeferment, and +C<-Eautodefer()> recovers the current value of the autodefer setting. + + +=head1 CONCURRENT ACCESS TO FILES + +Caching and deferred writing are inappropriate if you want the same +file to be accessed simultaneously from more than one process. Other +optimizations performed internally by this module are also +incompatible with concurrent access. A future version of this module will +support a C 1> option that enables safe concurrent access. + +Previous versions of this documentation suggested using C 0> for safe concurrent access. This was mistaken. Tie::File +will not support safe concurrent access before version 0.96. + +=head1 CAVEATS + +(That's Latin for 'warnings'.) + +=over 4 + +=item * + +Reasonable effort was made to make this module efficient. Nevertheless, +changing the size of a record in the middle of a large file will +always be fairly slow, because everything after the new record must be +moved. + +=item * + +The behavior of tied arrays is not precisely the same as for regular +arrays. For example: + + # This DOES print "How unusual!" + undef $a[10]; print "How unusual!\n" if defined $a[10]; + +C-ing a C array element just blanks out the +corresponding record in the file. When you read it back again, you'll +get the empty string, so the supposedly-C'ed value will be +defined. Similarly, if you have C disabled, then + + # This DOES print "How unusual!" if 'autochomp' is disabled + undef $a[10]; + print "How unusual!\n" if $a[10]; + +Because when C is disabled, C<$a[10]> will read back as +C<"\n"> (or whatever the record separator string is.) + +There are other minor differences, particularly regarding C +and C, but in general, the correspondence is extremely close. + +=item * + +I have supposed that since this module is concerned with file I/O, +almost all normal use of it will be heavily I/O bound. This means +that the time to maintain complicated data structures inside the +module will be dominated by the time to actually perform the I/O. +When there was an opportunity to spend CPU time to avoid doing I/O, I +usually tried to take it. + +=item * + +You might be tempted to think that deferred writing is like +transactions, with C as C and C as +C, but it isn't, so don't. + +=item * + +There is a large memory overhead for each record offset and for each +cache entry: about 310 bytes per cached data record, and about 21 bytes +per offset table entry. + +The per-record overhead will limit the maximum number of records you +can access per file. Note that I the length of the array +via C<$x = scalar @tied_file> accesses B records and stores their +offsets. The same for C, even if you exit the +loop early. + +=back + +=head1 SUBCLASSING + +This version promises absolutely nothing about the internals, which +may change without notice. A future version of the module will have a +well-defined and stable subclassing API. + +=head1 WHAT ABOUT C? + +People sometimes point out that L will do something similar, +and ask why C module is necessary. + +There are a number of reasons that you might prefer C. +A list is available at C>. + +=head1 AUTHOR + +Mark Jason Dominus + +To contact the author, send email to: C + +To receive an announcement whenever a new version of this module is +released, send a blank email message to +C. + +The most recent version of this module, including documentation and +any news of importance, will be available at + + http://perl.plover.com/TieFile/ + + +=head1 LICENSE + +C version 0.96 is copyright (C) 2003 Mark Jason Dominus. + +This library is free software; you may redistribute it and/or modify +it under the same terms as Perl itself. + +These terms are your choice of any of (1) the Perl Artistic Licence, +or (2) version 2 of the GNU General Public License as published by the +Free Software Foundation, or (3) any later version of the GNU General +Public License. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this library program; it should be in the file C. +If not, see . + +For licensing inquiries, contact the author at: + + Mark Jason Dominus + 255 S. Warnock St. + Philadelphia, PA 19107 + +=head1 WARRANTY + +C version 0.98 comes with ABSOLUTELY NO WARRANTY. +For details, see the license. + +=head1 THANKS + +Gigantic thanks to Jarkko Hietaniemi, for agreeing to put this in the +core when I hadn't written it yet, and for generally being helpful, +supportive, and competent. (Usually the rule is "choose any one.") +Also big thanks to Abhijit Menon-Sen for all of the same things. + +Special thanks to Craig Berry and Peter Prymmer (for VMS portability +help), Randy Kobes (for Win32 portability help), Clinton Pierce and +Autrijus Tang (for heroic eleventh-hour Win32 testing above and beyond +the call of duty), Michael G Schwern (for testing advice), and the +rest of the CPAN testers (for testing generally). + +Special thanks to Tels for suggesting several speed and memory +optimizations. + +Additional thanks to: +Edward Avis / +Mattia Barbon / +Tom Christiansen / +Gerrit Haase / +Gurusamy Sarathy / +Jarkko Hietaniemi (again) / +Nikola Knezevic / +John Kominetz / +Nick Ing-Simmons / +Tassilo von Parseval / +H. Dieter Pearcey / +Slaven Rezic / +Eric Roode / +Peter Scott / +Peter Somu / +Autrijus Tang (again) / +Tels (again) / +Juerd Waalboer / +Todd Rinaldo + +=head1 TODO + +More tests. (Stuff I didn't think of yet.) + +Paragraph mode? + +Fixed-length mode. Leave-blanks mode. + +Maybe an autolocking mode? + +For many common uses of the module, the read cache is a liability. +For example, a program that inserts a single record, or that scans the +file once, will have a cache hit rate of zero. This suggests a major +optimization: The cache should be initially disabled. Here's a hybrid +approach: Initially, the cache is disabled, but the cache code +maintains statistics about how high the hit rate would be *if* it were +enabled. When it sees the hit rate get high enough, it enables +itself. The STAT comments in this code are the beginning of an +implementation of this. + +Record locking with fcntl()? Then the module might support an undo +log and get real transactions. What a tour de force that would be. + +Keeping track of the highest cached record. This would allow reads-in-a-row +to skip the cache lookup faster (if reading from 1..N with empty cache at +start, the last cached value will be always N-1). + +More tests. + +=cut + diff --git a/git/usr/share/perl5/core_perl/Tie/Handle.pm b/git/usr/share/perl5/core_perl/Tie/Handle.pm new file mode 100644 index 0000000000000000000000000000000000000000..e6aa34bc927d02e305de71950593d79ca4b84fb5 --- /dev/null +++ b/git/usr/share/perl5/core_perl/Tie/Handle.pm @@ -0,0 +1,201 @@ +package Tie::Handle; + +use 5.006_001; +our $VERSION = '4.3'; + +# Tie::StdHandle used to be inside Tie::Handle. For backwards compatibility +# loading Tie::Handle has to make Tie::StdHandle available. +use Tie::StdHandle; + +=head1 NAME + +Tie::Handle - base class definitions for tied handles + +=head1 SYNOPSIS + + package NewHandle; + require Tie::Handle; + + @ISA = qw(Tie::Handle); + + sub READ { ... } # Provide a needed method + sub TIEHANDLE { ... } # Overrides inherited method + + + package main; + + tie *FH, 'NewHandle'; + +=head1 DESCRIPTION + +This module provides some skeletal methods for handle-tying classes. See +L for a list of the functions required in tying a handle to a package. +The basic B package provides a C method, as well as methods +C, C, C and C. + +For developers wishing to write their own tied-handle classes, the methods +are summarized below. The L section not only documents these, but +has sample code as well: + +=over 4 + +=item TIEHANDLE classname, LIST + +The method invoked by the command C. Associates a new +glob instance with the specified class. C would represent additional +arguments (along the lines of L and compatriots) needed to +complete the association. + +=item WRITE this, scalar, length, offset + +Write I bytes of data from I starting at I. + +=item PRINT this, LIST + +Print the values in I + +=item PRINTF this, format, LIST + +Print the values in I using I + +=item READ this, scalar, length, offset + +Read I bytes of data into I starting at I. + +=item READLINE this + +Read a single line + +=item GETC this + +Get a single character + +=item CLOSE this + +Close the handle + +=item OPEN this, filename + +(Re-)open the handle + +=item BINMODE this + +Specify content is binary + +=item EOF this + +Test for end of file. + +=item TELL this + +Return position in the file. + +=item SEEK this, offset, whence + +Position the file. + +Test for end of file. + +=item DESTROY this + +Free the storage associated with the tied handle referenced by I. +This is rarely needed, as Perl manages its memory quite well. But the +option exists, should a class wish to perform specific actions upon the +destruction of an instance. + +=back + +=head1 MORE INFORMATION + +The L section contains an example of tying handles. + +=head1 COMPATIBILITY + +This version of Tie::Handle is neither related to nor compatible with +the Tie::Handle (3.0) module available on CPAN. It was due to an +accident that two modules with the same name appeared. The namespace +clash has been cleared in favor of this module that comes with the +perl core in September 2000 and accordingly the version number has +been bumped up to 4.0. + +=cut + +use Carp; +use warnings::register; + +sub new { + my $pkg = shift; + $pkg->TIEHANDLE(@_); +} + +# Legacy support for new(), a la Tie::Hash + +sub TIEHANDLE { + my $pkg = shift; + if (defined &{"{$pkg}::new"}) { + warnings::warnif("WARNING: calling ${pkg}->new since ${pkg}->TIEHANDLE is missing"); + $pkg->new(@_); + } + else { + croak "$pkg doesn't define a TIEHANDLE method"; + } +} + +sub PRINT { + my $self = shift; + if($self->can('WRITE') != \&WRITE) { + my $buf = join(defined $, ? $, : "",@_); + $buf .= $\ if defined $\; + $self->WRITE($buf,length($buf),0); + } + else { + croak ref($self)," doesn't define a PRINT method"; + } +} + +sub PRINTF { + my $self = shift; + + if($self->can('WRITE') != \&WRITE) { + my $buf = sprintf(shift,@_); + $self->WRITE($buf,length($buf),0); + } + else { + croak ref($self)," doesn't define a PRINTF method"; + } +} + +sub READLINE { + my $pkg = ref $_[0]; + croak "$pkg doesn't define a READLINE method"; +} + +sub GETC { + my $self = shift; + + if($self->can('READ') != \&READ) { + my $buf; + $self->READ($buf,1); + return $buf; + } + else { + croak ref($self)," doesn't define a GETC method"; + } +} + +sub READ { + my $pkg = ref $_[0]; + croak "$pkg doesn't define a READ method"; +} + +sub WRITE { + my $pkg = ref $_[0]; + croak "$pkg doesn't define a WRITE method"; +} + +sub CLOSE { + my $pkg = ref $_[0]; + croak "$pkg doesn't define a CLOSE method"; +} + +1; diff --git a/git/usr/share/perl5/core_perl/Tie/Hash.pm b/git/usr/share/perl5/core_perl/Tie/Hash.pm new file mode 100644 index 0000000000000000000000000000000000000000..03493e06509b1ee9b064587e1e107bd570d9b03b --- /dev/null +++ b/git/usr/share/perl5/core_perl/Tie/Hash.pm @@ -0,0 +1,270 @@ +package Tie::Hash; + +our $VERSION = '1.06'; + +=head1 NAME + +Tie::Hash, Tie::StdHash, Tie::ExtraHash - base class definitions for tied hashes + +=head1 SYNOPSIS + + package NewHash; + require Tie::Hash; + + @ISA = qw(Tie::Hash); + + sub DELETE { ... } # Provides needed method + sub CLEAR { ... } # Overrides inherited method + + + package NewStdHash; + require Tie::Hash; + + @ISA = qw(Tie::StdHash); + + # All methods provided by default, define + # only those needing overrides + # Accessors access the storage in %{$_[0]}; + # TIEHASH should return a reference to the actual storage + sub DELETE { ... } + + package NewExtraHash; + require Tie::Hash; + + @ISA = qw(Tie::ExtraHash); + + # All methods provided by default, define + # only those needing overrides + # Accessors access the storage in %{$_[0][0]}; + # TIEHASH should return an array reference with the first element + # being the reference to the actual storage + sub DELETE { + $_[0][1]->('del', $_[0][0], $_[1]); # Call the report writer + delete $_[0][0]->{$_[1]}; # $_[0]->SUPER::DELETE($_[1]) + } + + + package main; + + tie %new_hash, 'NewHash'; + tie %new_std_hash, 'NewStdHash'; + tie %new_extra_hash, 'NewExtraHash', + sub {warn "Doing \U$_[1]\E of $_[2].\n"}; + +=head1 DESCRIPTION + +This module provides some skeletal methods for hash-tying classes. See +L for a list of the functions required in order to tie a hash +to a package. The basic B package provides a C method, as well +as methods C, C and C. The B and +B packages +provide most methods for hashes described in L (the exceptions +are C and C). They cause tied hashes to behave exactly like standard hashes, +and allow for selective overwriting of methods. B has legacy support for the +C method: it is used if C is not defined +in the case a class forgets to include a C method. + +For developers wishing to write their own tied hashes, the required methods +are briefly defined below. See the L section for more detailed +descriptive, as well as example code: + +=over 4 + +=item TIEHASH classname, LIST + +The method invoked by the command C. Associates a new +hash instance with the specified class. C would represent additional +arguments (along the lines of L and compatriots) needed to +complete the association. + +=item STORE this, key, value + +Store datum I into I for the tied hash I. + +=item FETCH this, key + +Retrieve the datum in I for the tied hash I. + +=item FIRSTKEY this + +Return the first key in the hash. + +=item NEXTKEY this, lastkey + +Return the next key in the hash. + +=item EXISTS this, key + +Verify that I exists with the tied hash I. + +The B implementation is a stub that simply croaks. + +=item DELETE this, key + +Delete the key I from the tied hash I. + +=item CLEAR this + +Clear all values from the tied hash I. + +=item SCALAR this + +Returns what evaluating the hash in scalar context yields. + +B does not implement this method (but B +and B do). + +=back + +=head1 Inheriting from B + +The accessor methods assume that the actual storage for the data in the tied +hash is in the hash referenced by C. Thus overwritten +C method should return a hash reference, and the remaining methods +should operate on the hash referenced by the first argument: + + package ReportHash; + our @ISA = 'Tie::StdHash'; + + sub TIEHASH { + my $storage = bless {}, shift; + warn "New ReportHash created, stored in $storage.\n"; + $storage + } + sub STORE { + warn "Storing data with key $_[1] at $_[0].\n"; + $_[0]{$_[1]} = $_[2] + } + + +=head1 Inheriting from B + +The accessor methods assume that the actual storage for the data in the tied +hash is in the hash referenced by C<(tied(%tiedhash))-E[0]>. Thus overwritten +C method should return an array reference with the first +element being a hash reference, and the remaining methods should operate on the +hash C<< %{ $_[0]->[0] } >>: + + package ReportHash; + our @ISA = 'Tie::ExtraHash'; + + sub TIEHASH { + my $class = shift; + my $storage = bless [{}, @_], $class; + warn "New ReportHash created, stored in $storage.\n"; + $storage; + } + sub STORE { + warn "Storing data with key $_[1] at $_[0].\n"; + $_[0][0]{$_[1]} = $_[2] + } + +The default C method stores "extra" arguments to tie() starting +from offset 1 in the array referenced by C; this is the +same storage algorithm as in TIEHASH subroutine above. Hence, a typical +package inheriting from B does not need to overwrite this +method. + +=head1 C, C and C + +The methods C and C are not defined in B, +B, or B. Tied hashes do not require +presence of these methods, but if defined, the methods will be called in +proper time, see L. + +C is only defined in B and B. + +If needed, these methods should be defined by the package inheriting from +B, B, or B. See L +to find out what happens when C does not exist. + +=head1 MORE INFORMATION + +The packages relating to various DBM-related implementations (F, +F, etc.) show examples of general tied hashes, as does the +L module. While these do not utilize B, they serve as +good working examples. + +=cut + +use Carp; +use warnings::register; + +sub new { + my $pkg = shift; + $pkg->TIEHASH(@_); +} + +# Legacy support for new() + +sub TIEHASH { + my $pkg = shift; + my $pkg_new = $pkg -> can ('new'); + + if ($pkg_new and $pkg ne __PACKAGE__) { + my $my_new = __PACKAGE__ -> can ('new'); + if ($pkg_new == $my_new) { + # + # Prevent recursion + # + croak "$pkg must define either a TIEHASH() or a new() method"; + } + + warnings::warnif ("WARNING: calling ${pkg}->new since " . + "${pkg}->TIEHASH is missing"); + $pkg -> new (@_); + } + else { + croak "$pkg doesn't define a TIEHASH method"; + } +} + +sub EXISTS { + my $pkg = ref $_[0]; + croak "$pkg doesn't define an EXISTS method"; +} + +sub CLEAR { + my $self = shift; + my $key = $self->FIRSTKEY(@_); + my @keys; + + while (defined $key) { + push @keys, $key; + $key = $self->NEXTKEY(@_, $key); + } + foreach $key (@keys) { + $self->DELETE(@_, $key); + } +} + +# The Tie::StdHash package implements standard perl hash behaviour. +# It exists to act as a base class for classes which only wish to +# alter some parts of their behaviour. + +package Tie::StdHash; +# @ISA = qw(Tie::Hash); # would inherit new() only + +sub TIEHASH { bless {}, $_[0] } +sub STORE { $_[0]->{$_[1]} = $_[2] } +sub FETCH { $_[0]->{$_[1]} } +sub FIRSTKEY { my $a = scalar keys %{$_[0]}; each %{$_[0]} } +sub NEXTKEY { each %{$_[0]} } +sub EXISTS { exists $_[0]->{$_[1]} } +sub DELETE { delete $_[0]->{$_[1]} } +sub CLEAR { %{$_[0]} = () } +sub SCALAR { scalar %{$_[0]} } + +package Tie::ExtraHash; + +sub TIEHASH { my $p = shift; bless [{}, @_], $p } +sub STORE { $_[0][0]{$_[1]} = $_[2] } +sub FETCH { $_[0][0]{$_[1]} } +sub FIRSTKEY { my $a = scalar keys %{$_[0][0]}; each %{$_[0][0]} } +sub NEXTKEY { each %{$_[0][0]} } +sub EXISTS { exists $_[0][0]->{$_[1]} } +sub DELETE { delete $_[0][0]->{$_[1]} } +sub CLEAR { %{$_[0][0]} = () } +sub SCALAR { scalar %{$_[0][0]} } + +1;