max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
448 | //
// Created by lifujun on 2019/8/20.
//
#ifndef SOURCE_OESRENDER_H
#define SOURCE_OESRENDER_H
#include "platform/android/decoder_surface.h"
#include "GLRender.h"
class OESProgramContext : public IProgramContext , private DecoderSurfaceCallback{
public:
OESProgramContext();
~OESProgramContext() override;
private:
int initProgram() override;
void useProgram() override;
void createSurface() override;
void *getSurface() override;
void updateScale(IVideoRender::Scale scale) override;
void updateRotate(IVideoRender::Rotate rotate) override;
void updateWindowSize(int width, int height, bool windowChanged) override;
void updateFlip(IVideoRender::Flip flip) override ;
void updateBackgroundColor(uint32_t color) override;
int updateFrame(std::unique_ptr<IAFFrame> &frame) override;
private:
void getShaderLocations();
void updateFlipCoords();
void updateDrawRegion();
void onFrameAvailable() override ;
private:
IVideoRender::Rotate mRotate = IVideoRender::Rotate_None;
IVideoRender::Flip mFlip = IVideoRender::Flip_None;
IVideoRender::Scale mScale = IVideoRender::Scale_AspectFit;
int mWindowWidth = 0;
int mWindowHeight = 0;
bool mWindowChanged = false;
double mDar = 1;
int mFrameWidth = 0;
int mFrameHeight = 0;
GLuint mOutTextureId = 0;
Cicada::DecoderSurface *mDecoderSurface = nullptr;
GLuint mOESProgram = 0;
GLuint mVertShader = 0;
GLuint mFragmentShader = 0;
GLuint mPositionLocation = 0;
GLuint mTexCoordLocation = 0;
GLint mMVPMatrixLocation = 0;
GLint mSTMatrixLocation = 0;
GLint mTextureLocation = 0;
GLfloat mOESMVMatrix[16] = {1.0f, 0, 0, 0,
0, 1.0f, 0, 0,
0, 0, 1.0f, 0,
0, 0, 0, 1.0f};
float mOESSTMatrix[16] = {1.0f, 0, 0, 0,
0, 1.0f, 0, 0,
0, 0, 1.0f, 0,
0, 0, 0, 1.0f};
bool mCoordsChanged = false;
GLfloat mOESFlipCoords[8] = {0.0f};
bool mRegionChanged = false;
GLfloat mDrawRegion[12]={0.0f};
std::mutex mFrameAvailableMutex;
std::condition_variable mFrameAvailableCon;
bool mFrameAvailable = false;
uint32_t mBackgroundColor = 0xff000000;
bool mBackgroundColorChanged = true;
};
#endif //SOURCE_OESRENDER_H
| 1,082 |
23,901 | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tapped Delay Line handler."""
import torch
import torch.nn as nn
class OneStepDelayKernel(nn.Module):
"""Single slot queue OSD kernel."""
def __init__(self, *args, **kwargs):
"""Initialize OSD kernel."""
super().__init__()
self.reset()
def reset(self):
self.state = None
def forward(self, current_state):
if self.state is not None:
prev_state = self.state
else:
prev_state = torch.zeros_like(current_state)
prev_state.requires_grad = True
self.state = current_state.clone()
return prev_state
class ExponentiallyWeightedSmoothingKernel(nn.Module):
"""Exponentially Weighted Smoothing Kernel.
alpha=0.0
--> state(t) = current_state
Functionally equivalent to sequential ResNet
alpha=1.0
--> state(t) = prev_state
Functionally equivalent to tapped delay line for 1 timestep delay
0.0 < alpha < 1.0
Continuous interpolation between discrete 1 timestep TDL and sequential ResNet
"""
def __init__(self, alpha=0.0):
"""Initialize EWS kernel."""
super().__init__()
self._alpha = alpha
self.reset()
def reset(self):
self.state = None
def forward(self, current_state):
if self.state is not None:
prev_state = self.state
else:
prev_state = torch.zeros_like(current_state)
prev_state.requires_grad = True
self.state = self._alpha*prev_state + (1-self._alpha)*current_state.clone()
return self.state
def setup_tdl_kernel(tdl_mode, kwargs):
"""Temporal kernel interface."""
if tdl_mode == 'OSD':
tdline = OneStepDelayKernel()
elif tdl_mode == 'EWS':
tdline = ExponentiallyWeightedSmoothingKernel(kwargs['tdl_alpha'])
return tdline
| 772 |
521 | <gh_stars>100-1000
/*
Dokan : user-mode file system library for Windows
Copyright (C) 2015 - 2016 <NAME>. <<EMAIL>> and <NAME>. <<EMAIL>>
Copyright (C) 2007 - 2011 <NAME> <<EMAIL>>
http://dokan-dev.github.io
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your option) any
later version.
This program 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 Lesser General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dokan.h"
VOID DokanIrpCancelRoutine(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp) {
KIRQL oldIrql;
PIRP_ENTRY irpEntry;
ULONG serialNumber = 0;
PIO_STACK_LOCATION irpSp;
UNREFERENCED_PARAMETER(DeviceObject);
DDbgPrint("==> DokanIrpCancelRoutine\n");
// Release the cancel spinlock
IoReleaseCancelSpinLock(Irp->CancelIrql);
irpEntry = Irp->Tail.Overlay.DriverContext[DRIVER_CONTEXT_IRP_ENTRY];
if (irpEntry != NULL) {
PKSPIN_LOCK lock = &irpEntry->IrpList->ListLock;
// Acquire the queue spinlock
ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
KeAcquireSpinLock(lock, &oldIrql);
irpSp = IoGetCurrentIrpStackLocation(Irp);
ASSERT(irpSp != NULL);
serialNumber = irpEntry->SerialNumber;
RemoveEntryList(&irpEntry->ListEntry);
InitializeListHead(&irpEntry->ListEntry);
// If Write is canceld before completion and buffer that saves writing
// content is not freed, free it here
if (irpSp->MajorFunction == IRP_MJ_WRITE) {
PVOID eventContext =
Irp->Tail.Overlay.DriverContext[DRIVER_CONTEXT_EVENT];
if (eventContext != NULL) {
DokanFreeEventContext(eventContext);
}
Irp->Tail.Overlay.DriverContext[DRIVER_CONTEXT_EVENT] = NULL;
}
if (IsListEmpty(&irpEntry->IrpList->ListHead)) {
// DDbgPrint(" list is empty ClearEvent\n");
KeClearEvent(&irpEntry->IrpList->NotEmpty);
}
irpEntry->Irp = NULL;
if (irpEntry->CancelRoutineFreeMemory == FALSE) {
InitializeListHead(&irpEntry->ListEntry);
} else {
DokanFreeIrpEntry(irpEntry);
irpEntry = NULL;
}
Irp->Tail.Overlay.DriverContext[DRIVER_CONTEXT_IRP_ENTRY] = NULL;
KeReleaseSpinLock(lock, oldIrql);
}
DDbgPrint(" canceled IRP #%X\n", serialNumber);
DokanCompleteIrpRequest(Irp, STATUS_CANCELLED, 0);
DDbgPrint("<== DokanIrpCancelRoutine\n");
return;
}
VOID DokanOplockComplete(IN PVOID Context, IN PIRP Irp)
/*++
Routine Description:
This routine is called by the oplock package when an oplock break has
completed, allowing an Irp to resume execution. If the status in
the Irp is STATUS_SUCCESS, then we queue the Irp to the Fsp queue.
Otherwise we complete the Irp with the status in the Irp.
Arguments:
Context - Pointer to the EventContext to be queued to the Fsp
Irp - I/O Request Packet.
Return Value:
None.
--*/
{
PIO_STACK_LOCATION irpSp;
DDbgPrint("==> DokanOplockComplete\n");
PAGED_CODE();
irpSp = IoGetCurrentIrpStackLocation(Irp);
//
// Check on the return value in the Irp.
//
if (Irp->IoStatus.Status == STATUS_SUCCESS) {
DokanRegisterPendingIrp(irpSp->DeviceObject, Irp, (PEVENT_CONTEXT)Context,
0);
} else {
DokanCompleteIrpRequest(Irp, Irp->IoStatus.Status, 0);
}
DDbgPrint("<== DokanOplockComplete\n");
return;
}
VOID DokanPrePostIrp(IN PVOID Context, IN PIRP Irp)
/*++
Routine Description:
This routine performs any neccessary work before STATUS_PENDING is
returned with the Fsd thread. This routine is called within the
filesystem and by the oplock package.
Arguments:
Context - Pointer to the EventContext to be queued to the Fsp
Irp - I/O Request Packet.
Return Value:
None.
--*/
{
DDbgPrint("==> DokanPrePostIrp\n");
UNREFERENCED_PARAMETER(Context);
UNREFERENCED_PARAMETER(Irp);
DDbgPrint("<== DokanPrePostIrp\n");
}
NTSTATUS
RegisterPendingIrpMain(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp,
__in ULONG SerialNumber, __in PIRP_LIST IrpList,
__in ULONG Flags, __in ULONG CheckMount) {
PIRP_ENTRY irpEntry;
PIO_STACK_LOCATION irpSp;
KIRQL oldIrql;
PDokanVCB vcb = NULL;
DDbgPrint("==> DokanRegisterPendingIrpMain\n");
if (GetIdentifierType(DeviceObject->DeviceExtension) == VCB) {
vcb = DeviceObject->DeviceExtension;
if (CheckMount && IsUnmountPendingVcb(vcb)) {
DDbgPrint(" device is not mounted\n");
return STATUS_NO_SUCH_DEVICE;
}
}
irpSp = IoGetCurrentIrpStackLocation(Irp);
// Allocate a record and save all the event context.
irpEntry = DokanAllocateIrpEntry();
if (NULL == irpEntry) {
DDbgPrint(" can't allocate IRP_ENTRY\n");
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory(irpEntry, sizeof(IRP_ENTRY));
InitializeListHead(&irpEntry->ListEntry);
irpEntry->SerialNumber = SerialNumber;
irpEntry->FileObject = irpSp->FileObject;
irpEntry->Irp = Irp;
irpEntry->IrpSp = irpSp;
irpEntry->IrpList = IrpList;
irpEntry->Flags = Flags;
// Update the irp timeout for the entry
if (vcb) {
ExAcquireResourceExclusiveLite(&vcb->Dcb->Resource, TRUE);
DokanUpdateTimeout(&irpEntry->TickCount, vcb->Dcb->IrpTimeout);
ExReleaseResourceLite(&vcb->Dcb->Resource);
} else {
DokanUpdateTimeout(&irpEntry->TickCount, DOKAN_IRP_PENDING_TIMEOUT);
}
// DDbgPrint(" Lock IrpList.ListLock\n");
ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
KeAcquireSpinLock(&IrpList->ListLock, &oldIrql);
IoSetCancelRoutine(Irp, DokanIrpCancelRoutine);
if (Irp->Cancel) {
if (IoSetCancelRoutine(Irp, NULL) != NULL) {
// DDbgPrint(" Release IrpList.ListLock %d\n", __LINE__);
KeReleaseSpinLock(&IrpList->ListLock, oldIrql);
DokanFreeIrpEntry(irpEntry);
return STATUS_CANCELLED;
}
}
IoMarkIrpPending(Irp);
InsertTailList(&IrpList->ListHead, &irpEntry->ListEntry);
irpEntry->CancelRoutineFreeMemory = FALSE;
// save the pointer in order to be accessed by cancel routine
Irp->Tail.Overlay.DriverContext[DRIVER_CONTEXT_IRP_ENTRY] = irpEntry;
KeSetEvent(&IrpList->NotEmpty, IO_NO_INCREMENT, FALSE);
// DDbgPrint(" Release IrpList.ListLock\n");
KeReleaseSpinLock(&IrpList->ListLock, oldIrql);
DDbgPrint("<== DokanRegisterPendingIrpMain\n");
return STATUS_PENDING;
}
NTSTATUS
DokanRegisterPendingIrp(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp,
__in PEVENT_CONTEXT EventContext, __in ULONG Flags) {
PDokanVCB vcb = DeviceObject->DeviceExtension;
NTSTATUS status;
DDbgPrint("==> DokanRegisterPendingIrp\n");
if (GetIdentifierType(vcb) != VCB) {
DDbgPrint(" IdentifierType is not VCB\n");
return STATUS_INVALID_PARAMETER;
}
status = RegisterPendingIrpMain(DeviceObject, Irp, EventContext->SerialNumber,
&vcb->Dcb->PendingIrp, Flags, TRUE);
if (status == STATUS_PENDING) {
DokanEventNotification(&vcb->Dcb->NotifyEvent, EventContext);
} else {
DokanFreeEventContext(EventContext);
}
DDbgPrint("<== DokanRegisterPendingIrp\n");
return status;
}
NTSTATUS
DokanRegisterPendingIrpForEvent(__in PDEVICE_OBJECT DeviceObject,
__in PIRP Irp) {
PDokanVCB vcb = DeviceObject->DeviceExtension;
if (GetIdentifierType(vcb) != VCB) {
DDbgPrint(" IdentifierType is not VCB\n");
return STATUS_INVALID_PARAMETER;
}
if (IsUnmountPendingVcb(vcb)) {
DDbgPrint(" Volume is dismounted\n");
return STATUS_NO_SUCH_DEVICE;
}
// DDbgPrint("DokanRegisterPendingIrpForEvent\n");
vcb->HasEventWait = TRUE;
return RegisterPendingIrpMain(DeviceObject, Irp,
0, // SerialNumber
&vcb->Dcb->PendingEvent,
0, // Flags
TRUE);
}
NTSTATUS
DokanRegisterPendingIrpForService(__in PDEVICE_OBJECT DeviceObject,
__in PIRP Irp) {
PDOKAN_GLOBAL dokanGlobal;
DDbgPrint("DokanRegisterPendingIrpForService\n");
dokanGlobal = DeviceObject->DeviceExtension;
if (GetIdentifierType(dokanGlobal) != DGL) {
return STATUS_INVALID_PARAMETER;
}
return RegisterPendingIrpMain(DeviceObject, Irp,
0, // SerialNumber
&dokanGlobal->PendingService,
0, // Flags
FALSE);
}
// When user-mode file system application returns EventInformation,
// search corresponding pending IRP and complete it
NTSTATUS
DokanCompleteIrp(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp) {
KIRQL oldIrql;
PLIST_ENTRY thisEntry, nextEntry, listHead;
PIRP_ENTRY irpEntry;
PDokanVCB vcb;
PEVENT_INFORMATION eventInfo;
eventInfo = (PEVENT_INFORMATION)Irp->AssociatedIrp.SystemBuffer;
ASSERT(eventInfo != NULL);
// DDbgPrint("==> DokanCompleteIrp [EventInfo #%X]\n",
// eventInfo->SerialNumber);
vcb = DeviceObject->DeviceExtension;
if (GetIdentifierType(vcb) != VCB) {
return STATUS_INVALID_PARAMETER;
}
if (IsUnmountPendingVcb(vcb)) {
DDbgPrint(" Volume is not mounted\n");
return STATUS_NO_SUCH_DEVICE;
}
// DDbgPrint(" Lock IrpList.ListLock\n");
ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
KeAcquireSpinLock(&vcb->Dcb->PendingIrp.ListLock, &oldIrql);
// search corresponding IRP through pending IRP list
listHead = &vcb->Dcb->PendingIrp.ListHead;
for (thisEntry = listHead->Flink; thisEntry != listHead;
thisEntry = nextEntry) {
PIRP irp;
PIO_STACK_LOCATION irpSp;
nextEntry = thisEntry->Flink;
irpEntry = CONTAINING_RECORD(thisEntry, IRP_ENTRY, ListEntry);
// check whether this is corresponding IRP
// DDbgPrint("SerialNumber irpEntry %X eventInfo %X\n",
// irpEntry->SerialNumber, eventInfo->SerialNumber);
// this irpEntry must be freed in this if statement
if (irpEntry->SerialNumber != eventInfo->SerialNumber) {
continue;
}
RemoveEntryList(thisEntry);
irp = irpEntry->Irp;
if (irp == NULL) {
// this IRP is already canceled
ASSERT(irpEntry->CancelRoutineFreeMemory == FALSE);
DokanFreeIrpEntry(irpEntry);
irpEntry = NULL;
break;
}
if (IoSetCancelRoutine(irp, NULL) == NULL) {
// Cancel routine will run as soon as we release the lock
InitializeListHead(&irpEntry->ListEntry);
irpEntry->CancelRoutineFreeMemory = TRUE;
break;
}
// IRP is not canceled yet
irpSp = irpEntry->IrpSp;
ASSERT(irpSp != NULL);
// IrpEntry is saved here for CancelRoutine
// Clear it to prevent to be completed by CancelRoutine twice
irp->Tail.Overlay.DriverContext[DRIVER_CONTEXT_IRP_ENTRY] = NULL;
KeReleaseSpinLock(&vcb->Dcb->PendingIrp.ListLock, oldIrql);
if (IsUnmountPendingVcb(vcb)) {
DDbgPrint(" Volume is not mounted second check\n");
return STATUS_NO_SUCH_DEVICE;
}
if (eventInfo->Status == STATUS_PENDING) {
DDbgPrint(
" !!WARNING!! Do not return STATUS_PENDING DokanCompleteIrp!");
}
switch (irpSp->MajorFunction) {
case IRP_MJ_DIRECTORY_CONTROL:
DokanCompleteDirectoryControl(irpEntry, eventInfo);
break;
case IRP_MJ_READ:
DokanCompleteRead(irpEntry, eventInfo);
break;
case IRP_MJ_WRITE:
DokanCompleteWrite(irpEntry, eventInfo);
break;
case IRP_MJ_QUERY_INFORMATION:
DokanCompleteQueryInformation(irpEntry, eventInfo);
break;
case IRP_MJ_QUERY_VOLUME_INFORMATION:
DokanCompleteQueryVolumeInformation(irpEntry, eventInfo, DeviceObject);
break;
case IRP_MJ_CREATE:
DokanCompleteCreate(irpEntry, eventInfo);
break;
case IRP_MJ_CLEANUP:
DokanCompleteCleanup(irpEntry, eventInfo);
break;
case IRP_MJ_LOCK_CONTROL:
DokanCompleteLock(irpEntry, eventInfo);
break;
case IRP_MJ_SET_INFORMATION:
DokanCompleteSetInformation(irpEntry, eventInfo);
break;
case IRP_MJ_FLUSH_BUFFERS:
DokanCompleteFlush(irpEntry, eventInfo);
break;
case IRP_MJ_QUERY_SECURITY:
DokanCompleteQuerySecurity(irpEntry, eventInfo);
break;
case IRP_MJ_SET_SECURITY:
DokanCompleteSetSecurity(irpEntry, eventInfo);
break;
default:
DDbgPrint("Unknown IRP %d\n", irpSp->MajorFunction);
// TODO: in this case, should complete this IRP
break;
}
DokanFreeIrpEntry(irpEntry);
irpEntry = NULL;
return STATUS_SUCCESS;
}
KeReleaseSpinLock(&vcb->Dcb->PendingIrp.ListLock, oldIrql);
// DDbgPrint("<== AACompleteIrp [EventInfo #%X]\n", eventInfo->SerialNumber);
// TODO: should return error
return STATUS_SUCCESS;
}
// start event dispatching
NTSTATUS
DokanEventStart(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp) {
ULONG outBufferLen;
ULONG inBufferLen;
PIO_STACK_LOCATION irpSp;
EVENT_START eventStart;
PEVENT_DRIVER_INFO driverInfo;
PDOKAN_GLOBAL dokanGlobal;
PDokanDCB dcb;
NTSTATUS status;
DEVICE_TYPE deviceType;
ULONG deviceCharacteristics = 0;
WCHAR baseGuidString[64];
GUID baseGuid = DOKAN_BASE_GUID;
UNICODE_STRING unicodeGuid;
ULONG deviceNamePos;
BOOLEAN useMountManager = FALSE;
BOOLEAN mountGlobally = TRUE;
BOOLEAN fileLockUserMode = FALSE;
DDbgPrint("==> DokanEventStart\n");
dokanGlobal = DeviceObject->DeviceExtension;
if (GetIdentifierType(dokanGlobal) != DGL) {
return STATUS_INVALID_PARAMETER;
}
irpSp = IoGetCurrentIrpStackLocation(Irp);
outBufferLen = irpSp->Parameters.DeviceIoControl.OutputBufferLength;
inBufferLen = irpSp->Parameters.DeviceIoControl.InputBufferLength;
if (outBufferLen != sizeof(EVENT_DRIVER_INFO) ||
inBufferLen != sizeof(EVENT_START)) {
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlCopyMemory(&eventStart, Irp->AssociatedIrp.SystemBuffer,
sizeof(EVENT_START));
driverInfo = Irp->AssociatedIrp.SystemBuffer;
if (eventStart.UserVersion != DOKAN_DRIVER_VERSION) {
driverInfo->DriverVersion = DOKAN_DRIVER_VERSION;
driverInfo->Status = DOKAN_START_FAILED;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof(EVENT_DRIVER_INFO);
return STATUS_SUCCESS;
}
switch (eventStart.DeviceType) {
case DOKAN_DISK_FILE_SYSTEM:
deviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
break;
case DOKAN_NETWORK_FILE_SYSTEM:
deviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
deviceCharacteristics |= FILE_REMOTE_DEVICE;
break;
default:
DDbgPrint(" Unknown device type: %d\n", eventStart.DeviceType);
deviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
}
if (eventStart.Flags & DOKAN_EVENT_REMOVABLE) {
DDbgPrint(" DeviceCharacteristics |= FILE_REMOVABLE_MEDIA\n");
deviceCharacteristics |= FILE_REMOVABLE_MEDIA;
}
if (eventStart.Flags & DOKAN_EVENT_WRITE_PROTECT) {
DDbgPrint(" DeviceCharacteristics |= FILE_READ_ONLY_DEVICE\n");
deviceCharacteristics |= FILE_READ_ONLY_DEVICE;
}
if (eventStart.Flags & DOKAN_EVENT_MOUNT_MANAGER) {
DDbgPrint(" Using Mount Manager\n");
useMountManager = TRUE;
}
if (eventStart.Flags & DOKAN_EVENT_CURRENT_SESSION) {
DDbgPrint(" Mounting on current session only\n");
mountGlobally = FALSE;
}
if (eventStart.Flags & DOKAN_EVENT_FILELOCK_USER_MODE) {
DDbgPrint(" FileLock in User Mode\n");
fileLockUserMode = TRUE;
}
KeEnterCriticalRegion();
ExAcquireResourceExclusiveLite(&dokanGlobal->Resource, TRUE);
DOKAN_CONTROL dokanControl;
RtlZeroMemory(&dokanControl, sizeof(dokanControl));
RtlStringCchCopyW(dokanControl.MountPoint, MAXIMUM_FILENAME_LENGTH,
L"\\DosDevices\\");
if (wcslen(eventStart.MountPoint) == 1) {
dokanControl.MountPoint[12] = towupper(eventStart.MountPoint[0]);
dokanControl.MountPoint[13] = L':';
dokanControl.MountPoint[14] = L'\0';
} else {
RtlStringCchCatW(dokanControl.MountPoint, MAXIMUM_FILENAME_LENGTH,
eventStart.MountPoint);
}
DDbgPrint(" Checking for MountPoint %ls \n", dokanControl.MountPoint);
PMOUNT_ENTRY foundEntry = FindMountEntry(dokanGlobal, &dokanControl, FALSE);
if (foundEntry != NULL) {
DDbgPrint(" MountPoint exists already %ls \n", dokanControl.MountPoint);
driverInfo->DriverVersion = DOKAN_DRIVER_VERSION;
driverInfo->Status = DOKAN_START_FAILED;
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof(EVENT_DRIVER_INFO);
ExReleaseResourceLite(&dokanGlobal->Resource);
KeLeaveCriticalRegion();
return STATUS_SUCCESS;
}
baseGuid.Data2 = (USHORT)(dokanGlobal->MountId & 0xFFFF) ^ baseGuid.Data2;
baseGuid.Data3 = (USHORT)(dokanGlobal->MountId >> 16) ^ baseGuid.Data3;
status = RtlStringFromGUID(&baseGuid, &unicodeGuid);
if (!NT_SUCCESS(status)) {
ExReleaseResourceLite(&dokanGlobal->Resource);
KeLeaveCriticalRegion();
return status;
}
RtlZeroMemory(baseGuidString, sizeof(baseGuidString));
RtlStringCchCopyW(baseGuidString, sizeof(baseGuidString) / sizeof(WCHAR),
unicodeGuid.Buffer);
RtlFreeUnicodeString(&unicodeGuid);
InterlockedIncrement((LONG *)&dokanGlobal->MountId);
status = DokanCreateDiskDevice(
DeviceObject->DriverObject, dokanGlobal->MountId, eventStart.MountPoint,
eventStart.UNCName, baseGuidString, dokanGlobal, deviceType,
deviceCharacteristics, mountGlobally, useMountManager, &dcb);
if (!NT_SUCCESS(status)) {
ExReleaseResourceLite(&dokanGlobal->Resource);
KeLeaveCriticalRegion();
return status;
}
dcb->FileLockInUserMode = fileLockUserMode;
DDbgPrint(" MountId:%d\n", dcb->MountId);
driverInfo->DeviceNumber = dokanGlobal->MountId;
driverInfo->MountId = dokanGlobal->MountId;
driverInfo->Status = DOKAN_MOUNTED;
driverInfo->DriverVersion = DOKAN_DRIVER_VERSION;
// SymbolicName is
// \\DosDevices\\Global\\Volume{D6CC17C5-1734-4085-BCE7-964F1E9F5DE9}
// Finds the last '\' and copy into DeviceName.
// DeviceName is \Volume{D6CC17C5-1734-4085-BCE7-964F1E9F5DE9}
deviceNamePos = dcb->SymbolicLinkName->Length / sizeof(WCHAR) - 1;
for (; dcb->SymbolicLinkName->Buffer[deviceNamePos] != L'\\'; --deviceNamePos)
;
RtlStringCchCopyW(driverInfo->DeviceName,
sizeof(driverInfo->DeviceName) / sizeof(WCHAR),
&(dcb->SymbolicLinkName->Buffer[deviceNamePos]));
// Set the irp timeout in milliseconds
// If the IrpTimeout is 0, we assume that the value was not changed
dcb->IrpTimeout = DOKAN_IRP_PENDING_TIMEOUT;
if (eventStart.IrpTimeout > 0) {
if (eventStart.IrpTimeout > DOKAN_IRP_PENDING_TIMEOUT_RESET_MAX) {
eventStart.IrpTimeout = DOKAN_IRP_PENDING_TIMEOUT_RESET_MAX;
}
if (eventStart.IrpTimeout < DOKAN_IRP_PENDING_TIMEOUT) {
eventStart.IrpTimeout = DOKAN_IRP_PENDING_TIMEOUT;
}
dcb->IrpTimeout = eventStart.IrpTimeout;
}
DDbgPrint(" DeviceName:%ws\n", driverInfo->DeviceName);
dcb->UseAltStream = 0;
if (eventStart.Flags & DOKAN_EVENT_ALTERNATIVE_STREAM_ON) {
DDbgPrint(" ALT_STREAM_ON\n");
dcb->UseAltStream = 1;
}
DokanStartEventNotificationThread(dcb);
ExReleaseResourceLite(&dokanGlobal->Resource);
KeLeaveCriticalRegion();
IoVerifyVolume(dcb->DeviceObject, FALSE);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof(EVENT_DRIVER_INFO);
DDbgPrint("<== DokanEventStart\n");
return Irp->IoStatus.Status;
}
// user assinged bigger buffer that is enough to return WriteEventContext
NTSTATUS
DokanEventWrite(__in PDEVICE_OBJECT DeviceObject, __in PIRP Irp) {
KIRQL oldIrql;
PLIST_ENTRY thisEntry, nextEntry, listHead;
PIRP_ENTRY irpEntry;
PDokanVCB vcb;
PEVENT_INFORMATION eventInfo;
PIRP writeIrp;
eventInfo = (PEVENT_INFORMATION)Irp->AssociatedIrp.SystemBuffer;
ASSERT(eventInfo != NULL);
DDbgPrint("==> DokanEventWrite [EventInfo #%X]\n", eventInfo->SerialNumber);
vcb = DeviceObject->DeviceExtension;
if (GetIdentifierType(vcb) != VCB) {
return STATUS_INVALID_PARAMETER;
}
ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
KeAcquireSpinLock(&vcb->Dcb->PendingIrp.ListLock, &oldIrql);
// search corresponding write IRP through pending IRP list
listHead = &vcb->Dcb->PendingIrp.ListHead;
for (thisEntry = listHead->Flink; thisEntry != listHead;
thisEntry = nextEntry) {
PIO_STACK_LOCATION writeIrpSp, eventIrpSp;
PEVENT_CONTEXT eventContext;
ULONG info = 0;
NTSTATUS status;
nextEntry = thisEntry->Flink;
irpEntry = CONTAINING_RECORD(thisEntry, IRP_ENTRY, ListEntry);
// check whehter this is corresponding IRP
// DDbgPrint("SerialNumber irpEntry %X eventInfo %X\n",
// irpEntry->SerialNumber, eventInfo->SerialNumber);
if (irpEntry->SerialNumber != eventInfo->SerialNumber) {
continue;
}
// do NOT free irpEntry here
writeIrp = irpEntry->Irp;
if (writeIrp == NULL) {
// this IRP has already been canceled
ASSERT(irpEntry->CancelRoutineFreeMemory == FALSE);
DokanFreeIrpEntry(irpEntry);
continue;
}
if (IoSetCancelRoutine(writeIrp, DokanIrpCancelRoutine) == NULL) {
// if (IoSetCancelRoutine(writeIrp, NULL) != NULL) {
// Cancel routine will run as soon as we release the lock
InitializeListHead(&irpEntry->ListEntry);
irpEntry->CancelRoutineFreeMemory = TRUE;
continue;
}
writeIrpSp = irpEntry->IrpSp;
eventIrpSp = IoGetCurrentIrpStackLocation(Irp);
ASSERT(writeIrpSp != NULL);
ASSERT(eventIrpSp != NULL);
eventContext =
(PEVENT_CONTEXT)
writeIrp->Tail.Overlay.DriverContext[DRIVER_CONTEXT_EVENT];
ASSERT(eventContext != NULL);
// short of buffer length
if (eventIrpSp->Parameters.DeviceIoControl.OutputBufferLength <
eventContext->Length) {
DDbgPrint(" EventWrite: STATUS_INSUFFICIENT_RESOURCE\n");
status = STATUS_INSUFFICIENT_RESOURCES;
} else {
PVOID buffer;
// DDbgPrint(" EventWrite CopyMemory\n");
// DDbgPrint(" EventLength %d, BufLength %d\n", eventContext->Length,
// eventIrpSp->Parameters.DeviceIoControl.OutputBufferLength);
if (Irp->MdlAddress)
buffer = MmGetSystemAddressForMdlNormalSafe(Irp->MdlAddress);
else
buffer = Irp->AssociatedIrp.SystemBuffer;
ASSERT(buffer != NULL);
RtlCopyMemory(buffer, eventContext, eventContext->Length);
info = eventContext->Length;
status = STATUS_SUCCESS;
}
DokanFreeEventContext(eventContext);
writeIrp->Tail.Overlay.DriverContext[DRIVER_CONTEXT_EVENT] = 0;
KeReleaseSpinLock(&vcb->Dcb->PendingIrp.ListLock, oldIrql);
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = info;
// this IRP will be completed by caller function
return Irp->IoStatus.Status;
}
KeReleaseSpinLock(&vcb->Dcb->PendingIrp.ListLock, oldIrql);
return STATUS_SUCCESS;
}
| 9,480 |
335 | {
"word": "Pro",
"definitions": [
"(of a person or an event) professional."
],
"parts-of-speech": "Adjective"
} | 61 |
854 | <reponame>rakhi2001/ecom7<gh_stars>100-1000
__________________________________________________________________________________________________
sample 0 ms submission
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int n = rooms.size();
boolean[] seen = new boolean[n];
dfs(0, rooms, seen);
for(boolean x : seen) {
if(!x) {
return false;
}
}
return true;
}
private void dfs(int cur, List<List<Integer>> rooms, boolean[] seen) {
seen[cur] = true;
for(int next : rooms.get(cur)) {
if(!seen[next]) {
dfs(next, rooms, seen);
}
}
}
}
__________________________________________________________________________________________________
sample 37104 kb submission
class Solution {
Queue<Integer> roomToOpenQueue = new ArrayDeque<>();
HashSet<Integer> visitedRooms = new HashSet<>();
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
//pick up keys and add to key map
List<Integer> keysInRoom = rooms.get(0);
visitedRooms.add(0);
roomToOpenQueue.addAll(keysInRoom);
while (!roomToOpenQueue.isEmpty()) {
visitRoom(roomToOpenQueue.remove(), rooms);
}
return !(visitedRooms.size() < rooms.size());
}
public void visitRoom(Integer roomNumber, List<List<Integer>> rooms) {
if (!visitedRooms.contains(roomNumber)) {
System.out.print ("Visiting room " + roomNumber);
visitedRooms.add(roomNumber);
List<Integer> keysInRoom = rooms.get(roomNumber);
for (Integer key: keysInRoom) {
if (!visitedRooms.contains(key)) {
roomToOpenQueue.add(key);
}
}
}
roomToOpenQueue.remove(roomNumber);
}
}
__________________________________________________________________________________________________
| 850 |
4,612 | <reponame>Khymeira/twisted
#!/usr/bin/env python
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
This is a sample implementation of a Twisted push producer/consumer system. It
consists of a TCP server which asks the user how many random integers they
want, and it sends the result set back to the user, one result per line,
and finally closes the connection.
"""
from random import randrange
from sys import stdout
from zope.interface import implementer
from twisted.internet import interfaces, reactor
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.python.log import startLogging
@implementer(interfaces.IPushProducer)
class Producer:
"""
Send back the requested number of random integers to the client.
"""
def __init__(self, proto, count):
self._proto = proto
self._goal = count
self._produced = 0
self._paused = False
def pauseProducing(self):
"""
When we've produced data too fast, pauseProducing() will be called
(reentrantly from within resumeProducing's sendLine() method, most
likely), so set a flag that causes production to pause temporarily.
"""
self._paused = True
print(f"Pausing connection from {self._proto.transport.getPeer()}")
def resumeProducing(self):
"""
Resume producing integers.
This tells the push producer to (re-)add itself to the main loop and
produce integers for its consumer until the requested number of integers
were returned to the client.
"""
self._paused = False
while not self._paused and self._produced < self._goal:
next_int = randrange(0, 10000)
line = f"{next_int}"
self._proto.sendLine(line.encode("ascii"))
self._produced += 1
if self._produced == self._goal:
self._proto.transport.unregisterProducer()
self._proto.transport.loseConnection()
def stopProducing(self):
"""
When a consumer has died, stop producing data for good.
"""
self._produced = self._goal
class ServeRandom(LineReceiver):
"""
Serve up random integers.
"""
def connectionMade(self):
"""
Once the connection is made we ask the client how many random integers
the producer should return.
"""
print(f"Connection made from {self.transport.getPeer()}")
self.sendLine(b"How many random integers do you want?")
def lineReceived(self, line):
"""
This checks how many random integers the client expects in return and
tells the producer to start generating the data.
"""
count = int(line.strip())
print(f"Client requested {count} random integers!")
producer = Producer(self, count)
self.transport.registerProducer(producer, True)
producer.resumeProducing()
def connectionLost(self, reason):
print(f"Connection lost from {self.transport.getPeer()}")
startLogging(stdout)
factory = Factory()
factory.protocol = ServeRandom
reactor.listenTCP(1234, factory)
reactor.run()
| 1,167 |
30,023 | """Tests for the Tomorrow.io Weather API integration."""
| 14 |
3,732 | <reponame>teddywest32/guacamole-client
/*
* Copyright (C) 2013 Glyptodon LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.glyptodon.guacamole.net.event;
import org.glyptodon.guacamole.net.auth.Credentials;
import org.glyptodon.guacamole.net.auth.UserContext;
/**
* An event which is triggered whenever a user's credentials pass
* authentication. The credentials that passed authentication are included
* within this event, and can be retrieved using getCredentials().
*
* @author <NAME>
*/
public class AuthenticationSuccessEvent implements UserEvent, CredentialEvent {
/**
* The UserContext associated with the request that is connecting the
* tunnel, if any.
*/
private UserContext context;
/**
* The credentials which passed authentication.
*/
private Credentials credentials;
/**
* Creates a new AuthenticationSuccessEvent which represents a successful
* authentication attempt with the given credentials.
*
* @param context The UserContext created as a result of successful
* authentication.
* @param credentials The credentials which passed authentication.
*/
public AuthenticationSuccessEvent(UserContext context, Credentials credentials) {
this.context = context;
this.credentials = credentials;
}
@Override
public UserContext getUserContext() {
return context;
}
@Override
public Credentials getCredentials() {
return credentials;
}
}
| 748 |
330 | <reponame>vd-imran/Cucumberish
//
// CucumberFeatureSteps.h
// CucumberishExample
//
// Created by <NAME> on 7/26/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface CucumberFeatureSteps : NSObject
@end
| 98 |
3,651 | <filename>core/src/main/java/com/orientechnologies/orient/core/sql/executor/AggregationContext.java
package com.orientechnologies.orient.core.sql.executor;
import com.orientechnologies.orient.core.command.OCommandContext;
/** Created by luigidellaquila on 16/07/16. */
public interface AggregationContext {
public Object getFinalValue();
void apply(OResult next, OCommandContext ctx);
}
| 124 |
335 | {
"word": "Dickens",
"definitions": [
"Used for emphasis, or to express annoyance or surprise when asking questions."
],
"parts-of-speech": "Noun"
} | 66 |
1,402 | #pragma once
/**
* \file NETGeographicLib/UTMUPS.h
* \brief Header for NETGeographicLib::UTMUPS class
*
* NETGeographicLib is copyright (c) <NAME> (2013)
* GeographicLib is Copyright (c) <NAME> (2010-2012)
* <<EMAIL>> and licensed under the MIT/X11 License.
* For more information, see
* https://geographiclib.sourceforge.io/
**********************************************************************/
namespace NETGeographicLib
{
/**
* \brief .NET wrapper for GeographicLib::UTMUPS.
*
* This class allows .NET applications to access GeographicLib::UTMUPS.
*
* UTM and UPS are defined
* - <NAME>, <NAME>, and <NAME>,
* <a href="http://earth-info.nga.mil/GandG/publications/tm8358.2/TM8358_2.pdf">
* The Universal Grids: Universal Transverse Mercator (UTM) and Universal
* Polar Stereographic (UPS)</a>, Defense Mapping Agency, Technical Manual
* TM8358.2 (1989).
* .
* Section 2-3 defines UTM and section 3-2.4 defines UPS. This document also
* includes approximate algorithms for the computation of the underlying
* transverse Mercator and polar stereographic projections. Here we
* substitute much more accurate algorithms given by
* GeographicLib:TransverseMercator and GeographicLib:PolarStereographic.
*
* In this implementation, the conversions are closed, i.e., output from
* Forward is legal input for Reverse and vice versa. The error is about 5nm
* in each direction. However, the conversion from legal UTM/UPS coordinates
* to geographic coordinates and back might throw an error if the initial
* point is within 5nm of the edge of the allowed range for the UTM/UPS
* coordinates.
*
* The simplest way to guarantee the closed property is to define allowed
* ranges for the eastings and northings for UTM and UPS coordinates. The
* UTM boundaries are the same for all zones. (The only place the
* exceptional nature of the zone boundaries is evident is when converting to
* UTM/UPS coordinates requesting the standard zone.) The MGRS lettering
* scheme imposes natural limits on UTM/UPS coordinates which may be
* converted into MGRS coordinates. For the conversion to/from geographic
* coordinates these ranges have been extended by 100km in order to provide a
* generous overlap between UTM and UPS and between UTM zones.
*
* The <a href="http://www.nga.mil">NGA</a> software package
* <a href="http://earth-info.nga.mil/GandG/geotrans/index.html">geotrans</a>
* also provides conversions to and from UTM and UPS. Version 2.4.2 (and
* earlier) suffers from some drawbacks:
* - Inconsistent rules are used to determine the whether a particular UTM or
* UPS coordinate is legal. A more systematic approach is taken here.
* - The underlying projections are not very accurately implemented.
*
* C# Example:
* \include example-UTMUPS.cs
* Managed C++ Example:
* \include example-UTMUPS.cpp
* Visual Basic Example:
* \include example-UTMUPS.vb
*
**********************************************************************/
public ref class UTMUPS
{
private:
// hide the constructor since all members of the class are static.
UTMUPS() {}
public:
/**
* In this class we bring together the UTM and UPS coordinates systems.
* The UTM divides the earth between latitudes −80° and 84°
* into 60 zones numbered 1 thru 60. Zone assign zone number 0 to the UPS
* regions, covering the two poles. Within UTMUPS, non-negative zone
* numbers refer to one of the "physical" zones, 0 for UPS and [1, 60] for
* UTM. Negative "pseudo-zone" numbers are used to select one of the
* physical zones.
**********************************************************************/
enum class ZoneSpec {
/**
* The smallest pseudo-zone number.
**********************************************************************/
MINPSEUDOZONE = -4,
/**
* A marker for an undefined or invalid zone. Equivalent to NaN.
**********************************************************************/
INVALID = -4,
/**
* If a coordinate already include zone information (e.g., it is an MGRS
* coordinate), use that, otherwise apply the UTMUPS::STANDARD rules.
**********************************************************************/
MATCH = -3,
/**
* Apply the standard rules for UTM zone assigment extending the UTM zone
* to each pole to give a zone number in [1, 60]. For example, use UTM
* zone 38 for longitude in [42°, 48°). The rules include the
* Norway and Svalbard exceptions.
**********************************************************************/
UTM = -2,
/**
* Apply the standard rules for zone assignment to give a zone number in
* [0, 60]. If the latitude is not in [−80°, 84°), then
* use UTMUPS::UPS = 0, otherwise apply the rules for UTMUPS::UTM. The
* tests on latitudes and longitudes are all closed on the lower end open
* on the upper. Thus for UTM zone 38, latitude is in [−80°,
* 84°) and longitude is in [42°, 48°).
**********************************************************************/
STANDARD = -1,
/**
* The largest pseudo-zone number.
**********************************************************************/
MAXPSEUDOZONE = -1,
/**
* The smallest physical zone number.
**********************************************************************/
MINZONE = 0,
/**
* The zone number used for UPS
**********************************************************************/
UPS = 0,
/**
* The smallest UTM zone number.
**********************************************************************/
MINUTMZONE = 1,
/**
* The largest UTM zone number.
**********************************************************************/
MAXUTMZONE = 60,
/**
* The largest physical zone number.
**********************************************************************/
MAXZONE = 60,
};
/**
* The standard zone.
*
* @param[in] lat latitude (degrees).
* @param[in] lon longitude (degrees).
* @param[in] setzone zone override (use ZoneSpec.STANDARD as default). If
* omitted, use the standard rules for picking the zone. If \e setzone
* is given then use that zone if it is non-negative, otherwise apply the
* rules given in UTMUPS::zonespec.
* @exception GeographicErr if \e setzone is outside the range
* [UTMUPS::MINPSEUDOZONE, UTMUPS::MAXZONE] = [−4, 60].
*
* This is exact.
**********************************************************************/
static int StandardZone(double lat, double lon, int setzone);
/**
* Forward projection, from geographic to UTM/UPS.
*
* @param[in] lat latitude of point (degrees).
* @param[in] lon longitude of point (degrees).
* @param[out] zone the UTM zone (zero means UPS).
* @param[out] northp hemisphere (true means north, false means south).
* @param[out] x easting of point (meters).
* @param[out] y northing of point (meters).
* @param[out] gamma meridian convergence at point (degrees).
* @param[out] k scale of projection at point.
* @param[in] setzone zone override (use ZoneSpec.STANDARD as default).
* @param[in] mgrslimits if true enforce the stricter MGRS limits on the
* coordinates (default = false).
* @exception GeographicErr if \e lat is not in [−90°,
* 90°].
* @exception GeographicErr if the resulting \e x or \e y is out of allowed
* range (see Reverse); in this case, these arguments are unchanged.
*
* If \e setzone is omitted, use the standard rules for picking the zone.
* If \e setzone is given then use that zone if it is non-negative,
* otherwise apply the rules given in UTMUPS::zonespec. The accuracy of
* the conversion is about 5nm.
*
* The northing \e y jumps by UTMUPS::UTMShift() when crossing the equator
* in the southerly direction. Sometimes it is useful to remove this
* discontinuity in \e y by extending the "northern" hemisphere using
* UTMUPS::Transfer:
* \code
double lat = -1, lon = 123;
int zone;
bool northp;
double x, y, gamma, k;
GeographicLib::UTMUPS::Forward(lat, lon, zone, northp, x, y, gamma, k);
GeographicLib::UTMUPS::Transfer(zone, northp, x, y,
zone, true, x, y, zone);
northp = true;
\endcode
**********************************************************************/
static void Forward(double lat, double lon,
[System::Runtime::InteropServices::Out] int% zone,
[System::Runtime::InteropServices::Out] bool% northp,
[System::Runtime::InteropServices::Out] double% x,
[System::Runtime::InteropServices::Out] double% y,
[System::Runtime::InteropServices::Out] double% gamma,
[System::Runtime::InteropServices::Out] double% k,
int setzone, bool mgrslimits);
/**
* Reverse projection, from UTM/UPS to geographic.
*
* @param[in] zone the UTM zone (zero means UPS).
* @param[in] northp hemisphere (true means north, false means south).
* @param[in] x easting of point (meters).
* @param[in] y northing of point (meters).
* @param[out] lat latitude of point (degrees).
* @param[out] lon longitude of point (degrees).
* @param[out] gamma meridian convergence at point (degrees).
* @param[out] k scale of projection at point.
* @param[in] mgrslimits if true enforce the stricter MGRS limits on the
* coordinates (default = false).
* @exception GeographicErr if \e zone, \e x, or \e y is out of allowed
* range; this this case the arguments are unchanged.
*
* The accuracy of the conversion is about 5nm.
*
* UTM eastings are allowed to be in the range [0km, 1000km], northings are
* allowed to be in in [0km, 9600km] for the northern hemisphere and in
* [900km, 10000km] for the southern hemisphere. However UTM northings
* can be continued across the equator. So the actual limits on the
* northings are [-9100km, 9600km] for the "northern" hemisphere and
* [900km, 19600km] for the "southern" hemisphere.
*
* UPS eastings and northings are allowed to be in the range [1200km,
* 2800km] in the northern hemisphere and in [700km, 3100km] in the
* southern hemisphere.
*
* These ranges are 100km larger than allowed for the conversions to MGRS.
* (100km is the maximum extra padding consistent with eastings remaining
* non-negative.) This allows generous overlaps between zones and UTM and
* UPS. If \e mgrslimits = true, then all the ranges are shrunk by 100km
* so that they agree with the stricter MGRS ranges. No checks are
* performed besides these (e.g., to limit the distance outside the
* standard zone boundaries).
**********************************************************************/
static void Reverse(int zone, bool northp, double x, double y,
[System::Runtime::InteropServices::Out] double% lat,
[System::Runtime::InteropServices::Out] double% lon,
[System::Runtime::InteropServices::Out] double% gamma,
[System::Runtime::InteropServices::Out] double% k,
bool mgrslimits);
/**
* UTMUPS::Forward without returning convergence and scale.
**********************************************************************/
static void Forward(double lat, double lon,
[System::Runtime::InteropServices::Out] int% zone,
[System::Runtime::InteropServices::Out] bool% northp,
[System::Runtime::InteropServices::Out] double% x,
[System::Runtime::InteropServices::Out] double% y,
int setzone, bool mgrslimits );
/**
* UTMUPS::Reverse without returning convergence and scale.
**********************************************************************/
static void Reverse(int zone, bool northp, double x, double y,
[System::Runtime::InteropServices::Out] double% lat,
[System::Runtime::InteropServices::Out] double% lon,
bool mgrslimits);
/**
* Transfer UTM/UPS coordinated from one zone to another.
*
* @param[in] zonein the UTM zone for \e xin and \e yin (or zero for UPS).
* @param[in] northpin hemisphere for \e xin and \e yin (true means north,
* false means south).
* @param[in] xin easting of point (meters) in \e zonein.
* @param[in] yin northing of point (meters) in \e zonein.
* @param[in] zoneout the requested UTM zone for \e xout and \e yout (or
* zero for UPS).
* @param[in] northpout hemisphere for \e xout output and \e yout.
* @param[out] xout easting of point (meters) in \e zoneout.
* @param[out] yout northing of point (meters) in \e zoneout.
* @param[out] zone the actual UTM zone for \e xout and \e yout (or zero
* for UPS); this equals \e zoneout if \e zoneout ≥ 0.
* @exception GeographicErr if \e zonein is out of range (see below).
* @exception GeographicErr if \e zoneout is out of range (see below).
* @exception GeographicErr if \e xin or \e yin fall outside their allowed
* ranges (see UTMUPS::Reverse).
* @exception GeographicErr if \e xout or \e yout fall outside their
* allowed ranges (see UTMUPS::Reverse).
*
* \e zonein must be in the range [UTMUPS::MINZONE, UTMUPS::MAXZONE] = [0,
* 60] with \e zonein = UTMUPS::UPS, 0, indicating UPS. \e zonein may
* also be UTMUPS::INVALID.
*
* \e zoneout must be in the range [UTMUPS::MINPSEUDOZONE, UTMUPS::MAXZONE]
* = [-4, 60]. If \e zoneout < UTMUPS::MINZONE then the rules give in
* the documentation of UTMUPS::zonespec are applied, and \e zone is set to
* the actual zone used for output.
*
* (\e xout, \e yout) can overlap with (\e xin, \e yin).
**********************************************************************/
static void Transfer(int zonein, bool northpin, double xin, double yin,
int zoneout, bool northpout,
[System::Runtime::InteropServices::Out] double% xout,
[System::Runtime::InteropServices::Out] double% yout,
[System::Runtime::InteropServices::Out] int% zone);
/**
* Decode a UTM/UPS zone string.
*
* @param[in] zonestr string representation of zone and hemisphere.
* @param[out] zone the UTM zone (zero means UPS).
* @param[out] northp hemisphere (true means north, false means south).
* @exception GeographicErr if \e zonestr is malformed.
*
* For UTM, \e zonestr has the form of a zone number in the range
* [UTMUPS::MINUTMZONE, UTMUPS::MAXUTMZONE] = [1, 60] followed by a
* hemisphere letter, n or s (or "north" or "south" spelled out). For UPS,
* it consists just of the hemisphere letter (or the spelled out
* hemisphere). The returned value of \e zone is UTMUPS::UPS = 0 for UPS.
* Note well that "38s" indicates the southern hemisphere of zone 38 and
* not latitude band S, 32° ≤ \e lat < 40°. n, 01s, 2n, 38s,
* south, 3north are legal. 0n, 001s, +3n, 61n, 38P are illegal. INV is a
* special value for which the returned value of \e is UTMUPS::INVALID.
**********************************************************************/
static void DecodeZone(System::String^ zonestr,
[System::Runtime::InteropServices::Out] int% zone,
[System::Runtime::InteropServices::Out] bool% northp);
/**
* Encode a UTM/UPS zone string.
*
* @param[in] zone the UTM zone (zero means UPS).
* @param[in] northp hemisphere (true means north, false means south).
* @param[in] abbrev if true (the default) use abbreviated (n/s) notation
* for hemisphere; otherwise spell out the hemisphere (north/south)
* @exception GeographicErr if \e zone is out of range (see below).
* @exception std::bad_alloc if memoy for the string can't be allocated.
* @return string representation of zone and hemisphere.
*
* \e zone must be in the range [UTMUPS::MINZONE, UTMUPS::MAXZONE] = [0,
* 60] with \e zone = UTMUPS::UPS, 0, indicating UPS (but the resulting
* string does not contain "0"). \e zone may also be UTMUPS::INVALID, in
* which case the returned string is "inv". This reverses
* UTMUPS::DecodeZone.
**********************************************************************/
static System::String^ EncodeZone(int zone, bool northp, bool abbrev);
/**
* Decode EPSG.
*
* @param[in] epsg the EPSG code.
* @param[out] zone the UTM zone (zero means UPS).
* @param[out] northp hemisphere (true means north, false means south).
*
* EPSG (European Petroleum Survery Group) codes are a way to refer to many
* different projections. DecodeEPSG decodes those refering to UTM or UPS
* projections for the WGS84 ellipsoid. If the code does not refer to one
* of these projections, \e zone is set to UTMUPS::INVALID. See
* http://spatialreference.org/ref/epsg/
**********************************************************************/
static void DecodeEPSG(int epsg,
[System::Runtime::InteropServices::Out] int% zone,
[System::Runtime::InteropServices::Out] bool% northp);
/**
* Encode zone as EPSG.
*
* @param[in] zone the UTM zone (zero means UPS).
* @param[in] northp hemisphere (true means north, false means south).
* @return EPSG code (or -1 if \e zone is not in the range
* [UTMUPS::MINZONE, UTMUPS::MAXZONE] = [0, 60])
*
* Convert \e zone and \e northp to the corresponding EPSG (European
* Petroleum Survery Group) codes
**********************************************************************/
static int EncodeEPSG(int zone, bool northp);
/**
* @return shift (meters) necessary to align N and S halves of a UTM zone
* (10<sup>7</sup>).
**********************************************************************/
static double UTMShift();
/** \name Inspector functions
**********************************************************************/
///@{
/**
* @return \e a the equatorial radius of the WGS84 ellipsoid (meters).
*
* (The WGS84 value is returned because the UTM and UPS projections are
* based on this ellipsoid.)
**********************************************************************/
static double MajorRadius();
/**
* @return \e f the flattening of the WGS84 ellipsoid.
*
* (The WGS84 value is returned because the UTM and UPS projections are
* based on this ellipsoid.)
**********************************************************************/
static double Flattening();
///@}
};
} // namespace NETGeographicLib
| 8,061 |
1,233 | <filename>examples/plugins/transient/alerta_transient.py
import logging
from alerta.exceptions import RateLimit
from alerta.plugins import PluginBase
LOG = logging.getLogger('alerta.plugins.transient')
FLAPPING_WINDOW = 120 # seconds
FLAPPING_COUNT = 2 # threshold
class TransientAlert(PluginBase):
def pre_receive(self, alert, **kwargs):
LOG.info('Detecting transient alerts...')
if alert.is_flapping(window=FLAPPING_WINDOW, count=FLAPPING_COUNT):
raise RateLimit('Flapping alert received more than %s times in %s seconds' %
(FLAPPING_COUNT, FLAPPING_WINDOW))
return alert
def post_receive(self, alert, **kwargs):
return
def status_change(self, alert, status, text, **kwargs):
return
| 306 |
1,382 | <filename>lib/sandbox/python/check_all_process_names.py
#
# Checks all loaded process names, Python
# Module written by <NAME>
# Website: arvanaghi.com
# Twitter: @arvanaghi
# Edited for use in winpayloads
import win32pdh
import sys
EvidenceOfSandbox = []
sandboxProcesses = "vmsrvc", "tcpview", "wireshark", "visual basic", "fiddler", "vmware", "vbox", "process explorer", "autoit", "vboxtray", "vmtools", "vmrawdsk", "vmusbmouse", "vmvss", "vmscsi", "vmxnet", "vmx_svga", "vmmemctl", "df5serv", "vboxservice", "vmhgfs"
_, runningProcesses = win32pdh.EnumObjectItems(None,None,'process', win32pdh.PERF_DETAIL_WIZARD)
for process in runningProcesses:
for sandboxProcess in sandboxProcesses:
if sandboxProcess in str(process):
if process not in EvidenceOfSandbox:
EvidenceOfSandbox.append(process)
break
if not EvidenceOfSandbox:
pass
else:
sys.exit()
| 328 |
5,169 | <gh_stars>1000+
{
"name": "LookinServer",
"version": "0.9.2",
"summary": "The iOS framework of Lookin.",
"description": "Embed this framework into your iOS project to enable Lookin mac app.",
"homepage": "https://lookin.work",
"license": "GPL-3.0",
"authors": {
"QMUI Team": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/QMUI/LookinServer.git",
"tag": "0.9.2"
},
"vendored_frameworks": "LookinServer.framework",
"frameworks": "UIKit"
}
| 214 |
3,027 | #!/usr/bin/env python
import asyncio
import logging
import time
from collections import deque, defaultdict
from typing import (
Deque,
Dict,
List,
Optional
)
from hummingbot.core.data_type.order_book import OrderBook
from hummingbot.core.data_type.order_book_tracker import OrderBookTracker
from hummingbot.core.data_type.order_book_message import OrderBookMessage
from hummingbot.core.data_type.order_book_message import OrderBookMessageType
from hummingbot.connector.exchange.liquid.liquid_api_order_book_data_source import LiquidAPIOrderBookDataSource
from hummingbot.logger import HummingbotLogger
class LiquidOrderBookTracker(OrderBookTracker):
_lobt_logger: Optional[HummingbotLogger] = None
@classmethod
def logger(cls) -> (HummingbotLogger):
if cls._lobt_logger is None:
cls._lobt_logger = logging.getLogger(__name__)
return cls._lobt_logger
def __init__(self, trading_pairs: List[str]):
super().__init__(LiquidAPIOrderBookDataSource(trading_pairs), trading_pairs)
self._order_book_diff_stream: asyncio.Queue = asyncio.Queue()
self._order_book_snapshot_stream: asyncio.Queue = asyncio.Queue()
self._ev_loop: asyncio.BaseEventLoop = asyncio.get_event_loop()
self._saved_message_queues: Dict[str, Deque[OrderBookMessage]] = defaultdict(lambda: deque(maxlen=1000))
@property
def exchange_name(self) -> (str):
return "liquid"
async def _order_book_diff_router(self):
"""
Route the real-time order book diff messages to the correct order book.
"""
last_message_timestamp: float = time.time()
messages_queued: int = 0
messages_accepted: int = 0
messages_rejected: int = 0
while True:
try:
ob_message: OrderBookMessage = await self._order_book_diff_stream.get()
trading_pair: str = ob_message.trading_pair
if trading_pair not in self._tracking_message_queues:
messages_queued += 1
# Save diff messages received before snapshots are ready
self._saved_message_queues[trading_pair].append(ob_message)
continue
message_queue: asyncio.Queue = self._tracking_message_queues[trading_pair]
# Check the order book's initial update ID. If it's larger, don't bother.
order_book: OrderBook = self._order_books[trading_pair]
if order_book.snapshot_uid > ob_message.update_id:
messages_rejected += 1
continue
# Liquid order_book diff message does not contain entries to be deleted, it is actually a snapshot with
# just one side of the book (either bids or asks), we have to manually check for existing entries here
# and include them with 0 amount.
if "asks" in ob_message.content and len(ob_message.content["asks"]) > 0:
for price in order_book.snapshot[1].price:
if price not in [float(p[0]) for p in ob_message.content["asks"]]:
ob_message.content["asks"].append([str(price), str(0)])
elif "bids" in ob_message.content and len(ob_message.content["bids"]) > 0:
for price in order_book.snapshot[0].price:
if price not in [float(p[0]) for p in ob_message.content["bids"]]:
ob_message.content["bids"].append([str(price), str(0)])
await message_queue.put(ob_message)
messages_accepted += 1
# Log some statistics.
now: float = time.time()
if int(now / 60.0) > int(last_message_timestamp / 60.0):
self.logger().debug(f"Diff messages processed: {messages_accepted}, "
f"rejected: {messages_rejected}, queued: {messages_queued}")
messages_accepted = 0
messages_rejected = 0
messages_queued = 0
last_message_timestamp = now
except asyncio.CancelledError:
raise
except Exception:
self.logger().network(
"Unexpected error routing order book messages.",
exec_info=True,
app_warning_msg="Unexpected error routing order book messages. Retrying after 5 seconds."
)
await asyncio.sleep(5.0)
async def _order_book_snapshot_router(self):
"""
Route the real-time order book snapshot messages to the correct order book.
"""
while True:
try:
ob_message: OrderBookMessage = await self._order_book_snapshot_stream.get()
trading_pair: str = ob_message.trading_pair
if trading_pair not in self._tracking_message_queues:
continue
message_queue: asyncio.Queue = self._tracking_message_queues[trading_pair]
await message_queue.put(ob_message)
except asyncio.CancelledError:
raise
except Exception:
self.logger().error("Unknown error. Retrying after 5 seconds.", exc_info=True)
await asyncio.sleep(5.0)
async def _track_single_book(self, trading_pair: str):
past_diffs_window: Deque[OrderBookMessage] = deque()
self._past_diffs_windows[trading_pair] = past_diffs_window
message_queue: asyncio.Queue = self._tracking_message_queues[trading_pair]
order_book: OrderBook = self._order_books[trading_pair]
last_message_timestamp: float = time.time()
diff_messages_accepted: int = 0
while True:
try:
message: OrderBookMessage = None
saved_messages: Deque[OrderBookMessage] = self._saved_message_queues[trading_pair]
# Process saved messages first if there are any
if len(saved_messages) > 0:
message = saved_messages.popleft()
else:
message = await message_queue.get()
if message.type is OrderBookMessageType.DIFF:
order_book.apply_diffs(message.bids, message.asks, message.update_id)
past_diffs_window.append(message)
while len(past_diffs_window) > self.PAST_DIFF_WINDOW_SIZE:
past_diffs_window.popleft()
diff_messages_accepted += 1
# Output some statistics periodically.
now: float = time.time()
if int(now / 60.0) > int(last_message_timestamp / 60.0):
self.logger().debug(f"Processed {diff_messages_accepted} order book diffs for {trading_pair}.")
diff_messages_accepted = 0
last_message_timestamp = now
elif message.type is OrderBookMessageType.SNAPSHOT:
past_diffs: List[OrderBookMessage] = list(past_diffs_window)
past_diffs_window.append(message)
order_book.restore_from_snapshot_and_diffs(message, past_diffs)
self.logger().debug(f"Processed order book snapshot for {trading_pair}.")
except asyncio.CancelledError:
raise
except Exception:
self.logger().network(
f"Unexpected error tracking order book for {trading_pair}",
exec_info=True,
app_warning_msg="Unexpected error tracking order book. Retrying ater 5 seconds."
)
await asyncio.sleep(5.0)
| 3,707 |
945 | <gh_stars>100-1000
#include "vnl/vnl_sparse_matrix.hxx"
template class VNL_EXPORT vnl_sparse_matrix<double>;
| 49 |
480 | <reponame>weicao/galaxysql<gh_stars>100-1000
/*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.optimizer.core.profiler.memory;
import com.alibaba.polardbx.optimizer.memory.MemorySetting;
import java.util.ArrayList;
import java.util.List;
/**
* @author chenghui.lch
*/
public class MemoryStatAttribute {
// =======PoolName========
public static final String PARSER_POOL = "Parser";
public static final String PLANNER_POOL = "Planner";
public static final String PLAN_EXECUTOR_POOL = "PlanExecutor";
public static final String PLAN_BUILDER_POOL = "DistributedPlanBuilder";
public static final String OPERATOR_TMP_TABLE_POOL = "OperatorTmpTable";
public static final String SCALAR_SUBQUERY_POOL = "ScalarSubQuery";
public static final String APPLY_SUBQUERY_POOL = "ApplySubQuery";
// Use to init general pool for StmtMemPool
public static final List<String> normalPoolTypeNameList = new ArrayList<String>();
static {
normalPoolTypeNameList.add(MemorySetting.ENABLE_PARSER_POOL == true ? PARSER_POOL : null);
normalPoolTypeNameList.add(MemorySetting.ENABLE_PLANNER_POOL == true ? PLANNER_POOL : null);
normalPoolTypeNameList.add(MemorySetting.ENABLE_PLAN_EXECUTOR_POOL == true ? PLAN_EXECUTOR_POOL : null);
normalPoolTypeNameList.add(MemorySetting.ENABLE_PLAN_BUILDER_POOL == true ? PLAN_BUILDER_POOL : null);
normalPoolTypeNameList
.add(MemorySetting.ENABLE_OPERATOR_TMP_TABLE_POOL == true ? OPERATOR_TMP_TABLE_POOL : null);
}
// ========AllocationId=========
/**
* memory allocation id for logical sql
*/
public static final String PARSER_SQL = "SqlText";
/**
* memory allocation id for fast sql ast
*/
public static final String PARSER_FASTAST = "FastAst";
/**
*
*/
public static final String PARSER_FASTAST_PARAMS = "FastAstParams";
/**
* memory allocation id for calcite sql node
*/
public static final String PARSER_SQLNODE = "LogicalAst";
/**
* memory allocation id for calcite rel node
*/
public static final String OPTIMIZER_RELNODE = "LogicalPlan";
/**
* memory allocation id for open executor node
*/
public static final String POST_OPTIMIZER_CURSOR = "PhysicalCursor";
/**
* memory allocation id for all physical operators
*/
public static final String PHYSICAL_OPERATOR = "PhysicalOperators";
/**
* memory allocation id for all physical cursors
*/
public static final String PHYSICAL_EXECUTOR = "PhysicalExecutors";
/**
* memory allocation id for the tmp table of select vals of insert select
*/
public static final String INSERT_SELECT_VALUES = "InsertSelectValues";
}
| 1,146 |
335 | <reponame>Safal08/Hacktoberfest-1<filename>S/Supportive_adjective.json
{
"word": "Supportive",
"definitions": [
"Providing encouragement or emotional help."
],
"parts-of-speech": "Adjective"
} | 90 |
375 | /*
* Copyright 2017 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.rf.ide.core.execution.agent;
public enum PausingPoint {
PRE_START_KEYWORD,
START_KEYWORD,
PRE_END_KEYWORD,
END_KEYWORD
}
| 119 |
606 | package org.arend.term.prettyprint;
import org.arend.core.context.binding.Binding;
import org.arend.core.context.binding.TypedBinding;
import org.arend.core.context.param.DependentLink;
import org.arend.core.definition.ClassField;
import org.arend.core.expr.DefCallExpression;
import org.arend.core.expr.Expression;
import org.arend.core.expr.ProjExpression;
import org.arend.core.expr.ReferenceExpression;
import org.arend.core.expr.visitor.FreeVariablesCollector;
import org.arend.core.expr.visitor.VoidExpressionVisitor;
import org.arend.ext.concrete.ConcreteFactory;
import org.arend.ext.error.GeneralError;
import org.arend.ext.prettyprinting.DefinitionRenamer;
import org.arend.ext.prettyprinting.PrettyPrinterConfig;
import org.arend.ext.prettyprinting.PrettyPrinterFlag;
import org.arend.extImpl.ConcreteFactoryImpl;
import org.arend.naming.reference.Referable;
import org.arend.naming.reference.TCDefReferable;
import org.arend.term.concrete.Concrete;
import org.arend.term.concrete.SubstConcreteExpressionVisitor;
import org.arend.typechecking.error.local.GoalError;
import org.arend.typechecking.error.local.inference.ArgInferenceError;
import org.arend.typechecking.error.local.inference.FunctionArgInferenceError;
import org.arend.typechecking.error.local.inference.InstanceInferenceError;
import org.arend.typechecking.error.local.inference.LambdaInferenceError;
import org.arend.typechecking.instance.pool.GlobalInstancePool;
import org.arend.typechecking.instance.pool.LocalInstancePool;
import org.arend.typechecking.instance.provider.InstanceProvider;
import org.arend.typechecking.visitor.CheckTypeVisitor;
import org.arend.ext.util.Pair;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.stream.Collectors;
final public class MinimizedRepresentation {
private MinimizedRepresentation() {
}
/**
* Converts {@code expressionToPrint} to concrete, inserting as little additional information (like implicit arguments)
* as possible. Resulting concrete expression is intended to be type checkable, but not ground.
*/
public static @NotNull Concrete.Expression generateMinimizedRepresentation(
@NotNull Expression expressionToPrint,
@Nullable InstanceProvider instanceProvider,
@Nullable DefinitionRenamer definitionRenamer,
boolean mayUseReturnType) {
var pair = generateRepresentations(expressionToPrint, definitionRenamer, mayUseReturnType);
Concrete.Expression verboseRepresentation = pair.proj1;
Concrete.Expression incompleteRepresentation = pair.proj2;
List<GeneralError> errorsCollector = new ArrayList<>();
var typechecker = generateTypechecker(instanceProvider, errorsCollector);
induceContext(typechecker, verboseRepresentation, incompleteRepresentation, expressionToPrint);
int limit = 50;
Expression returnType = mayUseReturnType ? expressionToPrint.getType() : null;
while (true) {
var fixedExpression = tryFixError(typechecker, verboseRepresentation, incompleteRepresentation, errorsCollector, returnType);
if (fixedExpression == null) {
return incompleteRepresentation;
} else {
--limit;
if (limit == 0) {
throw new IllegalStateException("Minimization of expression (" + expressionToPrint + ") is likely diverged. Please report it to maintainers.\n " +
"Errors: \n" + errorsCollector);
}
incompleteRepresentation = fixedExpression;
}
}
}
private static void induceContext(CheckTypeVisitor typechecker, Concrete.Expression verboseRepresentation, Concrete.Expression incompleteRepresentation, Expression expressionToPrint) {
Map<String, List<Referable>> freeReferables = getFreeReferables(verboseRepresentation, incompleteRepresentation);
Map<String, Binding> freeBindings = collectFreeBindings(expressionToPrint);
for (var nameToBinding : freeBindings.entrySet()) {
var referables = freeReferables.get(nameToBinding.getKey());
if (referables == null) {
continue;
}
for (var referable : referables) {
typechecker.addBinding(referable, nameToBinding.getValue());
}
}
}
@NotNull
private static Map<String, List<Referable>> getFreeReferables(Concrete.Expression verboseRepresentation, Concrete.Expression incompleteRepresentation) {
var freeReferables = new LinkedHashSet<Referable>();
verboseRepresentation.accept(new FreeVariableCollectorConcrete(freeReferables), null);
incompleteRepresentation.accept(new FreeVariableCollectorConcrete(freeReferables), null);
Map<String, List<Referable>> mapping = new HashMap<>();
for (Referable freeReferable : freeReferables) {
mapping.computeIfAbsent(freeReferable.getRefName(), __ -> new ArrayList<>()).add(freeReferable);
}
return mapping;
}
private static Concrete.Expression addTrailingImplicitArguments(Concrete.Expression verboseRepresentation, Concrete.Expression incompleteRepresentation) {
if (!(verboseRepresentation instanceof Concrete.AppExpression)) {
return incompleteRepresentation;
}
List<Concrete.Argument> verboseArguments = ((Concrete.AppExpression) verboseRepresentation).getArguments();
List<Concrete.Argument> trailingImplicitArguments = new ArrayList<>();
for (var arg : verboseArguments) {
if (arg.isExplicit()) {
trailingImplicitArguments.clear();
} else {
trailingImplicitArguments.add(arg);
}
}
return Concrete.AppExpression.make(null, incompleteRepresentation, trailingImplicitArguments);
}
private static Pair<Concrete.Expression, Concrete.Expression> generateRepresentations(Expression core, @Nullable DefinitionRenamer definitionRenamer, boolean mayUseReturnType) {
var verboseConfig = new PrettyPrinterConfig() {
@Override
public @NotNull EnumSet<PrettyPrinterFlag> getExpressionFlags() {
return EnumSet.of(PrettyPrinterFlag.SHOW_TYPES_IN_LAM, PrettyPrinterFlag.SHOW_CASE_RESULT_TYPE, PrettyPrinterFlag.SHOW_CON_PARAMS, PrettyPrinterFlag.SHOW_BIN_OP_IMPLICIT_ARGS, PrettyPrinterFlag.SHOW_COERCE_DEFINITIONS, PrettyPrinterFlag.SHOW_GLOBAL_FIELD_INSTANCE, PrettyPrinterFlag.SHOW_IMPLICIT_ARGS, PrettyPrinterFlag.SHOW_LOCAL_FIELD_INSTANCE, PrettyPrinterFlag.SHOW_TUPLE_TYPE, PrettyPrinterFlag.SHOW_PROOFS);
}
@Override
public @Nullable DefinitionRenamer getDefinitionRenamer() {
return definitionRenamer;
}
};
var emptyConfig = new PrettyPrinterConfig() {
@Override
public @NotNull EnumSet<PrettyPrinterFlag> getExpressionFlags() {
return EnumSet.of(PrettyPrinterFlag.SHOW_LOCAL_FIELD_INSTANCE);
}
@Override
public @Nullable DefinitionRenamer getDefinitionRenamer() {
return definitionRenamer;
}
};
var verboseRepresentation = ToAbstractVisitor.convert(core, verboseConfig);
var incompleteRepresentation = ToAbstractVisitor.convert(core, emptyConfig)
.accept(new BiConcreteVisitor() {
@Override
public Concrete.Expression visitReference(Concrete.ReferenceExpression expr, Concrete.SourceNode params) {
if (params instanceof Concrete.AppExpression) {
return ((Concrete.AppExpression) params).getFunction();
} else {
return (Concrete.Expression) params;
}
}
@Override
protected Concrete.Parameter visitParameter(Concrete.Parameter parameter, Concrete.Parameter wideParameter) {
//noinspection DuplicatedCode
if (parameter.getType() == null) {
return (Concrete.Parameter) myFactory.param(parameter.isExplicit(), wideParameter.getRefList().get(0));
} else if (wideParameter.getRefList().stream().anyMatch(Objects::nonNull)) {
return (Concrete.Parameter) myFactory.param(parameter.isExplicit(), wideParameter.getRefList(), ((Concrete.TypeParameter) parameter).type.accept(this, ((Concrete.TypeParameter) wideParameter).type));
} else {
return (Concrete.Parameter) myFactory.param(parameter.isExplicit(), ((Concrete.TypeParameter) parameter).type.accept(this, ((Concrete.TypeParameter) wideParameter).type));
}
}
}, verboseRepresentation);
if (!mayUseReturnType) {
incompleteRepresentation = addTrailingImplicitArguments(verboseRepresentation, incompleteRepresentation);
}
return new Pair<>(verboseRepresentation, incompleteRepresentation);
}
private static Map<String, Binding> collectFreeBindings(Expression expr) {
var freeBindings = FreeVariablesCollector.getFreeVariables(expr);
expr.accept(new VoidExpressionVisitor<Void>() {
private Binding getBindingDeep(ProjExpression proj) {
if (proj.getExpression() instanceof ReferenceExpression) {
return ((ReferenceExpression) proj.getExpression()).getBinding();
} else if (proj.getExpression() instanceof ProjExpression) {
return getBindingDeep((ProjExpression) proj.getExpression());
} else {
return null;
}
}
@Override
public Void visitProj(ProjExpression expr, Void params) {
Binding deepBinding = getBindingDeep(expr);
if (deepBinding != null && freeBindings.contains(deepBinding)) {
expr.getType().accept(this, null);
freeBindings.add(new TypedBinding(expr.toString(), expr.getType()));
}
return super.visitProj(expr, params);
}
}, null);
Map<String, Binding> bindings = new HashMap<>();
for (Binding binding : freeBindings) {
bindings.putIfAbsent(binding.getName(), binding);
}
return bindings;
}
private static CheckTypeVisitor generateTypechecker(InstanceProvider instanceProvider, List<GeneralError> errorsCollector) {
var checkTypeVisitor = new CheckTypeVisitor(error -> {
if (!(error instanceof GoalError)) {
errorsCollector.add(error);
}
}, null, null);
checkTypeVisitor.setInstancePool(new GlobalInstancePool(instanceProvider, checkTypeVisitor, new LocalInstancePool(checkTypeVisitor)));
return checkTypeVisitor;
}
private static Concrete.Expression tryFixError(CheckTypeVisitor checkTypeVisitor, Concrete.Expression completeConcrete, Concrete.Expression minimizedConcrete, List<GeneralError> errorsCollector, Expression type) {
var factory = new ConcreteFactoryImpl(null);
checkTypeVisitor.finalCheckExpr(minimizedConcrete, type);
if (!errorsCollector.isEmpty()) {
return minimizedConcrete.accept(new ErrorFixingConcreteExpressionVisitor(errorsCollector, factory), completeConcrete);
} else {
return null;
}
}
}
/**
* Simultaneously traverses both incomplete and complete concrete expressions, attempting to fix errors encountered during the traverse.
*
* This visitor is meant to fix only one error. I consider errors not to be independent,
* therefore, after fixing one error, the rest may become irrelevant for the newly built expression.
*/
class ErrorFixingConcreteExpressionVisitor extends BiConcreteVisitor {
private final List<GeneralError> myErrors;
private final ConcreteFactory myFactory;
public ErrorFixingConcreteExpressionVisitor(List<GeneralError> myErrors, ConcreteFactory myFactory) {
this.myErrors = myErrors;
this.myFactory = myFactory;
}
private List<GeneralError> getErrorsForNode(Concrete.SourceNode node) {
return myErrors.stream().filter(err -> err.getCauseSourceNode() == node).collect(Collectors.toList());
}
@Override
public Concrete.Expression visitLam(Concrete.LamExpression expr, Concrete.SourceNode verbose) {
var errorList = getErrorsForNode(expr);
if (!errorList.isEmpty()) {
var error = errorList.get(0);
myErrors.clear();
return fixError(expr, (Concrete.LamExpression) verbose, error);
}
return super.visitLam(expr, verbose);
}
@Override
public Concrete.Expression visitApp(Concrete.AppExpression expr, Concrete.SourceNode verbose) {
Concrete.AppExpression verboseExpr = (Concrete.AppExpression) verbose;
if (expr.getFunction() instanceof Concrete.ReferenceExpression) {
var errorList = getErrorsForNode(expr.getFunction());
if (!errorList.isEmpty()) {
GeneralError mostImportantError = findMostImportantError(errorList);
myErrors.clear(); // no errors should be fixed afterwards
return fixError(expr, verboseExpr, mostImportantError);
}
}
return super.visitApp(expr, verboseExpr);
}
@Override
public Concrete.Expression visitReference(Concrete.ReferenceExpression expr, Concrete.SourceNode params) {
var errorList = myErrors.stream().filter(err -> err.getCauseSourceNode() == expr).collect(Collectors.toList());
if (!errorList.isEmpty()) {
var verboseExpr = (Concrete.Expression) params;
myErrors.clear();
return verboseExpr;
}
return expr;
}
private static GeneralError findMostImportantError(List<GeneralError> errors) {
return errors
.stream()
.filter(err -> err instanceof InstanceInferenceError)
.findFirst()
.orElse(errors
.stream()
.filter(err -> err instanceof ArgInferenceError)
.findFirst()
.orElse(errors.get(0))
);
}
private Concrete.AppExpression fixError(Concrete.AppExpression incomplete, Concrete.AppExpression complete, GeneralError error) {
if (error instanceof InstanceInferenceError) {
return fixInstanceInferenceError(incomplete, complete, (InstanceInferenceError) error);
} else if (error instanceof FunctionArgInferenceError) {
return fixFunctionArgInferenceError(incomplete, complete, (FunctionArgInferenceError) error);
} else {
return fixUnknownError(incomplete, complete);
}
}
private Concrete.LamExpression fixError(Concrete.LamExpression incomplete, Concrete.LamExpression complete, GeneralError error) {
if (error instanceof LambdaInferenceError) {
return fixLambdaInferenceError(incomplete, complete, (LambdaInferenceError)error);
} else {
throw new AssertionError("No other errors should have case source node of this kind");
}
}
private Concrete.LamExpression fixLambdaInferenceError(Concrete.LamExpression incomplete, Concrete.LamExpression complete, LambdaInferenceError error) {
var newParams = new ArrayList<Concrete.Parameter>();
for (int i = 0; i < incomplete.getParameters().size(); ++i) {
var incompleteParam = incomplete.getParameters().get(i);
if (incompleteParam.getRefList().size() != 1) {
newParams.add(incompleteParam);
} else if (incompleteParam.getRefList().get(0).equals(error.parameter)) {
newParams.add(complete.getParameters().get(i));
incomplete.body = incomplete.body.accept(new SubstConcreteExpressionVisitor(Map.of(incompleteParam.getRefList().get(0), new Concrete.ReferenceExpression(null, complete.getParameters().get(i).getRefList().get(0))), null), null);
}
}
return (Concrete.LamExpression) myFactory.lam(newParams, incomplete.body);
}
private Concrete.AppExpression fixUnknownError(Concrete.AppExpression incomplete, Concrete.AppExpression complete) {
ArrayList<Concrete.Argument> args = new ArrayList<>();
var incompleteArgumentsIterator = incomplete.getArguments().iterator();
var completeArgumentsIterator = complete.getArguments().iterator();
Concrete.Argument currentActualArg = incompleteArgumentsIterator.next();
while (completeArgumentsIterator.hasNext()) {
var currentProperArg = completeArgumentsIterator.next();
if (currentActualArg == null || (currentProperArg.isExplicit() == currentActualArg.isExplicit())) {
args.add(currentActualArg);
currentActualArg = incompleteArgumentsIterator.hasNext() ? incompleteArgumentsIterator.next() : null;
} else {
args.add(currentProperArg);
}
}
return (Concrete.AppExpression) myFactory.app(incomplete.getFunction(), args);
}
private Concrete.AppExpression fixFunctionArgInferenceError(Concrete.AppExpression incomplete, Concrete.AppExpression complete, FunctionArgInferenceError targetError) {
var definition = targetError.definition;
var args = new ArrayList<Concrete.Argument>();
var fullIterator = new ArgumentMappingIterator(definition, complete);
var incompleteIterator = new ArgumentMappingIterator(definition, incomplete);
var inserted = false;
var startIndex = definition instanceof ClassField ? 0 : 1;
while (fullIterator.hasNext()) {
var fullArg = fullIterator.next().proj2;
var incompleteArg = incompleteIterator.next().proj2;
if (startIndex == targetError.index) {
args.add((Concrete.Argument) fullArg);
inserted = true;
} else if (incompleteArg != null) {
args.add((Concrete.Argument) incompleteArg);
} else if (!inserted) {
args.add((Concrete.Argument) myFactory.arg(myFactory.hole(), fullArg.isExplicit()));
}
startIndex += 1;
}
return (Concrete.AppExpression) myFactory.app(incomplete.getFunction(), args);
}
private Concrete.AppExpression fixInstanceInferenceError(Concrete.AppExpression incomplete, Concrete.AppExpression complete, InstanceInferenceError targetError) {
var function = (Concrete.ReferenceExpression) incomplete.getFunction();
var definition = ((TCDefReferable) function.getReferent()).getTypechecked();
var args = new ArrayList<Concrete.Argument>();
var fullIterator = new ArgumentMappingIterator(definition, complete);
var incompleteIterator = new ArgumentMappingIterator(definition, incomplete);
var inserted = false;
while (fullIterator.hasNext()) {
var fullResult = fullIterator.next();
var incompleteArg = incompleteIterator.next().proj2;
var param = fullResult.proj1;
if (param instanceof DependentLink && ((DependentLink) param).getType() instanceof DefCallExpression && ((DefCallExpression) ((DependentLink) param).getType()).getDefinition() == targetError.classRef.getTypechecked()) {
args.add((Concrete.Argument) fullResult.proj2);
inserted = true;
} else if (incompleteArg != null) {
args.add((Concrete.Argument) incompleteArg);
} else if (!inserted) {
args.add((Concrete.Argument) myFactory.arg(myFactory.hole(), Objects.requireNonNull(fullResult.proj2).isExplicit()));
}
}
return (Concrete.AppExpression) myFactory.app(function, args);
}
}
| 7,987 |
674 | <reponame>slaveuser/honest-profiler20190422<gh_stars>100-1000
/**
* Copyright (c) 2014 <NAME> (<EMAIL>)
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**/
package com.insightfullogic.honest_profiler.ports.console;
import org.fusesource.jansi.Ansi;
import java.io.PrintStream;
import java.util.function.Function;
import static org.fusesource.jansi.Ansi.ansi;
public interface Console
{
PrintStream stream();
default void eraseScreen()
{
write(a -> a.eraseScreen().reset());
}
default void write(Function<Ansi, Ansi> func)
{
stream().println(func.apply(ansi()));
}
}
| 506 |
679 | <reponame>Grosskopf/openoffice
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sot.hxx"
#include <string.h> // memcpy()
#include <osl/file.hxx>
#include <tools/tempfile.hxx>
#include <tools/debug.hxx>
#include <set>
#include "sot/stg.hxx"
#include "stgelem.hxx"
#include "stgcache.hxx"
#include "stgstrms.hxx"
#include "stgdir.hxx"
#include "stgio.hxx"
#define __HUGE
///////////////////////////// class StgFAT ///////////////////////////////
// The FAT class performs FAT operations on an underlying storage stream.
// This stream is either the master FAT stream (m == sal_True ) or a normal
// storage stream, which then holds the FAT for small data allocations.
StgFAT::StgFAT( StgStrm& r, sal_Bool m ) : rStrm( r )
{
bPhys = m;
nPageSize = rStrm.GetIo().GetPhysPageSize();
nEntries = nPageSize >> 2;
nOffset = 0;
nMaxPage = 0;
nLimit = 0;
}
// Retrieve the physical page for a given byte offset.
StgPage* StgFAT::GetPhysPage( sal_Int32 nByteOff )
{
StgPage* pPg = NULL;
// Position within the underlying stream
// use the Pos2Page() method of the stream
if( rStrm.Pos2Page( nByteOff ) )
{
nOffset = rStrm.GetOffset();
sal_Int32 nPhysPage = rStrm.GetPage();
// get the physical page (must be present)
pPg = rStrm.GetIo().Get( nPhysPage, sal_True );
}
return pPg;
}
// Get the follow page for a certain FAT page.
sal_Int32 StgFAT::GetNextPage( sal_Int32 nPg )
{
if( nPg >= 0 )
{
StgPage* pPg = GetPhysPage( nPg << 2 );
nPg = pPg ? pPg->GetPage( nOffset >> 2 ) : STG_EOF;
}
return nPg;
}
// Find the best fit block for the given size. Return
// the starting block and its size or STG_EOF and 0.
// nLastPage is a stopper which tells the current
// underlying stream size. It is treated as a recommendation
// to abort the search to inhibit excessive file growth.
sal_Int32 StgFAT::FindBlock( sal_Int32& nPgs )
{
sal_Int32 nMinStart = STG_EOF, nMinLen = 0;
sal_Int32 nMaxStart = STG_EOF, nMaxLen = 0x7FFFFFFFL;
sal_Int32 nTmpStart = STG_EOF, nTmpLen = 0;
sal_Int32 nPages = rStrm.GetSize() >> 2;
sal_Bool bFound = sal_False;
StgPage* pPg = NULL;
short nEntry = 0;
for( sal_Int32 i = 0; i < nPages; i++, nEntry++ )
{
if( !( nEntry % nEntries ) )
{
// load the next page for that stream
nEntry = 0;
pPg = GetPhysPage( i << 2 );
if( !pPg )
return STG_EOF;
}
sal_Int32 nCur = pPg->GetPage( nEntry );
if( nCur == STG_FREE )
{
// count the size of this area
if( nTmpLen )
nTmpLen++;
else
nTmpStart = i,
nTmpLen = 1;
if( nTmpLen == nPgs
// If we already did find a block, stop when reaching the limit
|| ( bFound && ( nEntry >= nLimit ) ) )
break;
}
else if( nTmpLen )
{
if( nTmpLen > nPgs && nTmpLen < nMaxLen )
// block > requested size
nMaxLen = nTmpLen, nMaxStart = nTmpStart, bFound = sal_True;
else if( nTmpLen >= nMinLen )
{
// block < requested size
nMinLen = nTmpLen, nMinStart = nTmpStart;
bFound = sal_True;
if( nTmpLen == nPgs )
break;
}
nTmpStart = STG_EOF;
nTmpLen = 0;
}
}
// Determine which block to use.
if( nTmpLen )
{
if( nTmpLen > nPgs && nTmpLen < nMaxLen )
// block > requested size
nMaxLen = nTmpLen, nMaxStart = nTmpStart;
else if( nTmpLen >= nMinLen )
// block < requested size
nMinLen = nTmpLen, nMinStart = nTmpStart;
}
if( nMinStart != STG_EOF && nMaxStart != STG_EOF )
{
// two areas found; return the best fit area
sal_Int32 nMinDiff = nPgs - nMinLen;
sal_Int32 nMaxDiff = nMaxLen - nPgs;
if( nMinDiff > nMaxDiff )
nMinStart = STG_EOF;
}
if( nMinStart != STG_EOF )
{
nPgs = nMinLen; return nMinStart;
}
else
{
return nMaxStart;
}
}
// Set up the consecutive chain for a given block.
sal_Bool StgFAT::MakeChain( sal_Int32 nStart, sal_Int32 nPgs )
{
sal_Int32 nPos = nStart << 2;
StgPage* pPg = GetPhysPage( nPos );
if( !pPg || !nPgs )
return sal_False;
while( --nPgs )
{
if( nOffset >= nPageSize )
{
pPg = GetPhysPage( nPos );
if( !pPg )
return sal_False;
}
pPg->SetPage( nOffset >> 2, ++nStart );
nOffset += 4;
nPos += 4;
}
if( nOffset >= nPageSize )
{
pPg = GetPhysPage( nPos );
if( !pPg )
return sal_False;
}
pPg->SetPage( nOffset >> 2, STG_EOF );
return sal_True;
}
// Allocate a block of data from the given page number on.
// It the page number is != STG_EOF, chain the block.
sal_Int32 StgFAT::AllocPages( sal_Int32 nBgn, sal_Int32 nPgs )
{
sal_Int32 nOrig = nBgn;
sal_Int32 nLast = nBgn;
sal_Int32 nBegin = STG_EOF;
sal_Int32 nAlloc;
sal_Int32 nPages = rStrm.GetSize() >> 2;
short nPasses = 0;
// allow for two passes
while( nPasses < 2 )
{
// try to satisfy the request from the pool of free pages
while( nPgs )
{
nAlloc = nPgs;
nBegin = FindBlock( nAlloc );
// no more blocks left in present alloc chain
if( nBegin == STG_EOF )
break;
if( ( nBegin + nAlloc ) > nMaxPage )
nMaxPage = nBegin + nAlloc;
if( !MakeChain( nBegin, nAlloc ) )
return STG_EOF;
if( nOrig == STG_EOF )
nOrig = nBegin;
else
{
// Patch the chain
StgPage* pPg = GetPhysPage( nLast << 2 );
if( !pPg )
return STG_EOF;
pPg->SetPage( nOffset >> 2, nBegin );
}
nLast = nBegin + nAlloc - 1;
nPgs -= nAlloc;
}
if( nPgs && !nPasses )
{
// we need new, fresh space, so allocate and retry
if( !rStrm.SetSize( ( nPages + nPgs ) << 2 ) )
return STG_EOF;
if( !bPhys && !InitNew( nPages ) )
return sal_False;
nPages = rStrm.GetSize() >> 2;
nPasses++;
}
else
break;
}
// now we should have a chain for the complete block
if( nBegin == STG_EOF || nPgs )
{
rStrm.GetIo().SetError( SVSTREAM_FILEFORMAT_ERROR );
return STG_EOF; // bad structure
}
return nOrig;
}
// Initialize newly allocated pages for a standard FAT stream
// It can be assumed that the stream size is always on
// a page boundary
sal_Bool StgFAT::InitNew( sal_Int32 nPage1 )
{
sal_Int32 n = ( ( rStrm.GetSize() >> 2 ) - nPage1 ) / nEntries;
if ( n > 0 )
{
while( n-- )
{
StgPage* pPg = NULL;
// Position within the underlying stream
// use the Pos2Page() method of the stream
rStrm.Pos2Page( nPage1 << 2 );
// Initialize the page
pPg = rStrm.GetIo().Copy( rStrm.GetPage(), STG_FREE );
if ( !pPg )
return sal_False;
for( short i = 0; i < nEntries; i++ )
pPg->SetPage( i, STG_FREE );
nPage1++;
}
}
return sal_True;
}
// Release a chain
sal_Bool StgFAT::FreePages( sal_Int32 nStart, sal_Bool bAll )
{
while( nStart >= 0 )
{
StgPage* pPg = GetPhysPage( nStart << 2 );
if( !pPg )
return sal_False;
nStart = pPg->GetPage( nOffset >> 2 );
// The first released page is either set to EOF or FREE
pPg->SetPage( nOffset >> 2, bAll ? STG_FREE : STG_EOF );
bAll = sal_True;
}
return sal_True;
}
///////////////////////////// class StgStrm ////////////////////////////////
// The base stream class provides basic functionality for seeking
// and accessing the data on a physical basis. It uses the built-in
// FAT class for the page allocations.
StgStrm::StgStrm( StgIo& r ) : rIo( r )
{
pFat = NULL;
nStart = nPage = STG_EOF;
nOffset = 0;
pEntry = NULL;
nPos = nSize = 0;
nPageSize = rIo.GetPhysPageSize();
}
StgStrm::~StgStrm()
{
delete pFat;
}
// Attach the stream to the given entry.
void StgStrm::SetEntry( StgDirEntry& r )
{
r.aEntry.SetLeaf( STG_DATA, nStart );
r.aEntry.SetSize( nSize );
pEntry = &r;
r.SetDirty();
}
// Compute page number and offset for the given byte position.
// If the position is behind the size, set the stream right
// behind the EOF.
sal_Bool StgStrm::Pos2Page( sal_Int32 nBytePos )
{
if ( !pFat )
return sal_False;
sal_Int32 nRel, nBgn;
// Values < 0 seek to the end
if( nBytePos < 0 || nBytePos >= nSize )
nBytePos = nSize;
// Adjust the position back to offset 0
nPos -= nOffset;
sal_Int32 nMask = ~( nPageSize - 1 );
sal_Int32 nOld = nPos & nMask;
sal_Int32 nNew = nBytePos & nMask;
nOffset = (short) ( nBytePos & ~nMask );
nPos = nBytePos;
if( nOld == nNew )
return sal_True;
if( nNew > nOld )
{
// the new position is behind the current, so an incremental
// positioning is OK. Set the page relative position
nRel = nNew - nOld;
nBgn = nPage;
}
else
{
// the new position is before the current, so we have to scan
// the entire chain.
nRel = nNew;
nBgn = nStart;
}
// now, traverse the FAT chain.
nRel /= nPageSize;
sal_Int32 nLast = STG_EOF;
while( nRel && nBgn >= 0 )
{
nLast = nBgn;
nBgn = pFat->GetNextPage( nBgn );
nRel--;
}
// special case: seek to 1st byte of new, unallocated page
// (in case the file size is a multiple of the page size)
if( nBytePos == nSize && nBgn == STG_EOF && !nRel && !nOffset )
nBgn = nLast, nOffset = nPageSize;
if( nBgn < 0 && nBgn != STG_EOF )
{
rIo.SetError( SVSTREAM_FILEFORMAT_ERROR );
nBgn = STG_EOF;
nOffset = nPageSize;
}
nPage = nBgn;
return sal_Bool( nRel == 0 && nPage >= 0 );
}
// Retrieve the physical page for a given byte offset.
StgPage* StgStrm::GetPhysPage( sal_Int32 nBytePos, sal_Bool bForce )
{
if( !Pos2Page( nBytePos ) )
return NULL;
return rIo.Get( nPage, bForce );
}
// Copy an entire stream. Both streams are allocated in the FAT.
// The target stream is this stream.
sal_Bool StgStrm::Copy( sal_Int32 nFrom, sal_Int32 nBytes )
{
if ( !pFat )
return sal_False;
sal_Int32 nTo = nStart;
sal_Int32 nPgs = ( nBytes + nPageSize - 1 ) / nPageSize;
while( nPgs-- )
{
if( nTo < 0 )
{
rIo.SetError( SVSTREAM_FILEFORMAT_ERROR );
return sal_False;
}
rIo.Copy( nTo, nFrom );
if( nFrom >= 0 )
{
nFrom = pFat->GetNextPage( nFrom );
if( nFrom < 0 )
{
rIo.SetError( SVSTREAM_FILEFORMAT_ERROR );
return sal_False;
}
}
nTo = pFat->GetNextPage( nTo );
}
return sal_True;
}
sal_Bool StgStrm::SetSize( sal_Int32 nBytes )
{
if ( nBytes < 0 || !pFat )
return sal_False;
// round up to page size
sal_Int32 nOld = ( ( nSize + nPageSize - 1 ) / nPageSize ) * nPageSize;
sal_Int32 nNew = ( ( nBytes + nPageSize - 1 ) / nPageSize ) * nPageSize;
if( nNew > nOld )
{
if( !Pos2Page( nSize ) )
return sal_False;
sal_Int32 nBgn = pFat->AllocPages( nPage, ( nNew - nOld ) / nPageSize );
if( nBgn == STG_EOF )
return sal_False;
if( nStart == STG_EOF )
nStart = nPage = nBgn;
}
else if( nNew < nOld )
{
sal_Bool bAll = sal_Bool( nBytes == 0 );
if( !Pos2Page( nBytes ) || !pFat->FreePages( nPage, bAll ) )
return sal_False;
if( bAll )
nStart = nPage = STG_EOF;
}
if( pEntry )
{
// change the dir entry?
if( !nSize || !nBytes )
pEntry->aEntry.SetLeaf( STG_DATA, nStart );
pEntry->aEntry.SetSize( nBytes );
pEntry->SetDirty();
}
nSize = nBytes;
pFat->SetLimit( GetPages() );
return sal_True;
}
// Return the # of allocated pages
sal_Int32 StgStrm::GetPages()
{
return ( nSize + nPageSize - 1 ) / nPageSize;
}
//////////////////////////// class StgFATStrm //////////////////////////////
// The FAT stream class provides physical access to the master FAT.
// Since this access is implemented as a StgStrm, we can use the
// FAT allocator.
StgFATStrm::StgFATStrm( StgIo& r ) : StgStrm( r )
{
pFat = new StgFAT( *this, sal_True );
nSize = rIo.aHdr.GetFATSize() * nPageSize;
}
sal_Bool StgFATStrm::Pos2Page( sal_Int32 nBytePos )
{
// Values < 0 seek to the end
if( nBytePos < 0 || nBytePos >= nSize )
nBytePos = nSize ? nSize - 1 : 0;
nPage = nBytePos / nPageSize;
nOffset = (short) ( nBytePos % nPageSize );
nPos = nBytePos;
nPage = GetPage( (short) nPage, sal_False );
return sal_Bool( nPage >= 0 );
}
// Retrieve the physical page for a given byte offset.
// Since Pos2Page() already has computed the physical offset,
// use the byte offset directly.
StgPage* StgFATStrm::GetPhysPage( sal_Int32 nBytePos, sal_Bool bForce )
{
OSL_ENSURE( nBytePos >= 0, "The value may not be negative!" );
return rIo.Get( nBytePos / ( nPageSize >> 2 ), bForce );
}
// Get the page number entry for the given page offset.
sal_Int32 StgFATStrm::GetPage( short nOff, sal_Bool bMake, sal_uInt16 *pnMasterAlloc )
{
OSL_ENSURE( nOff >= 0, "The offset may not be negative!" );
if( pnMasterAlloc ) *pnMasterAlloc = 0;
if( nOff < rIo.aHdr.GetFAT1Size() )
return rIo.aHdr.GetFATPage( nOff );
sal_Int32 nMaxPage = nSize >> 2;
nOff = nOff - rIo.aHdr.GetFAT1Size();
// Anzahl der Masterpages, durch die wir iterieren muessen
sal_uInt16 nMasterCount = ( nPageSize >> 2 ) - 1;
sal_uInt16 nBlocks = nOff / nMasterCount;
// Offset in letzter Masterpage
nOff = nOff % nMasterCount;
StgPage* pOldPage = 0;
StgPage* pMaster = 0;
sal_Int32 nFAT = rIo.aHdr.GetFATChain();
for( sal_uInt16 nCount = 0; nCount <= nBlocks; nCount++ )
{
if( nFAT == STG_EOF || nFAT == STG_FREE )
{
if( bMake )
{
// create a new master page
nFAT = nMaxPage++;
pMaster = rIo.Copy( nFAT, STG_FREE );
if ( pMaster )
{
for( short k = 0; k < ( nPageSize >> 2 ); k++ )
pMaster->SetPage( k, STG_FREE );
// Verkettung herstellen
if( !pOldPage )
rIo.aHdr.SetFATChain( nFAT );
else
pOldPage->SetPage( nMasterCount, nFAT );
if( nMaxPage >= rIo.GetPhysPages() )
if( !rIo.SetSize( nMaxPage ) )
return STG_EOF;
// mark the page as used
// Platz fuer Masterpage schaffen
if( !pnMasterAlloc ) // Selbst Platz schaffen
{
if( !Pos2Page( nFAT << 2 ) )
return STG_EOF;
StgPage* pPg = rIo.Get( nPage, sal_True );
if( !pPg )
return STG_EOF;
pPg->SetPage( nOffset >> 2, STG_MASTER );
}
else
(*pnMasterAlloc)++;
rIo.aHdr.SetMasters( nCount + 1 );
pOldPage = pMaster;
}
}
}
else
{
pMaster = rIo.Get( nFAT, sal_True );
if ( pMaster )
{
nFAT = pMaster->GetPage( nMasterCount );
pOldPage = pMaster;
}
}
}
if( pMaster )
return pMaster->GetPage( nOff );
rIo.SetError( SVSTREAM_GENERALERROR );
return STG_EOF;
}
// Set the page number entry for the given page offset.
sal_Bool StgFATStrm::SetPage( short nOff, sal_Int32 nNewPage )
{
OSL_ENSURE( nOff >= 0, "The offset may not be negative!" );
sal_Bool bRes = sal_True;
if( nOff < rIo.aHdr.GetFAT1Size() )
rIo.aHdr.SetFATPage( nOff, nNewPage );
else
{
nOff = nOff - rIo.aHdr.GetFAT1Size();
// Anzahl der Masterpages, durch die wir iterieren muessen
sal_uInt16 nMasterCount = ( nPageSize >> 2 ) - 1;
sal_uInt16 nBlocks = nOff / nMasterCount;
// Offset in letzter Masterpage
nOff = nOff % nMasterCount;
StgPage* pMaster = 0;
sal_Int32 nFAT = rIo.aHdr.GetFATChain();
for( sal_uInt16 nCount = 0; nCount <= nBlocks; nCount++ )
{
if( nFAT == STG_EOF || nFAT == STG_FREE )
{
pMaster = 0;
break;
}
pMaster = rIo.Get( nFAT, sal_True );
if ( pMaster )
nFAT = pMaster->GetPage( nMasterCount );
}
if( pMaster )
pMaster->SetPage( nOff, nNewPage );
else
{
rIo.SetError( SVSTREAM_GENERALERROR );
bRes = sal_False;
}
}
// lock the page against access
if( bRes )
{
Pos2Page( nNewPage << 2 );
StgPage* pPg = rIo.Get( nPage, sal_True );
if( pPg )
pPg->SetPage( nOffset >> 2, STG_FAT );
else
bRes = sal_False;
}
return bRes;
}
sal_Bool StgFATStrm::SetSize( sal_Int32 nBytes )
{
if ( nBytes < 0 )
return sal_False;
// Set the number of entries to a multiple of the page size
short nOld = (short) ( ( nSize + ( nPageSize - 1 ) ) / nPageSize );
short nNew = (short) (
( nBytes + ( nPageSize - 1 ) ) / nPageSize ) ;
if( nNew < nOld )
{
// release master pages
for( short i = nNew; i < nOld; i++ )
SetPage( i, STG_FREE );
}
else
{
while( nOld < nNew )
{
// allocate master pages
// find a free master page slot
sal_Int32 nPg = 0;
sal_uInt16 nMasterAlloc = 0;
nPg = GetPage( nOld, sal_True, &nMasterAlloc );
if( nPg == STG_EOF )
return sal_False;
// 4 Bytes have been used for Allocation of each MegaMasterPage
nBytes += nMasterAlloc << 2;
// find a free page using the FAT allocator
sal_Int32 n = 1;
OSL_ENSURE( pFat, "The pointer is always initializer here!" );
sal_Int32 nNewPage = pFat->FindBlock( n );
if( nNewPage == STG_EOF )
{
// no free pages found; create a new page
// Since all pages are allocated, extend
// the file size for the next page!
nNewPage = nSize >> 2;
// if a MegaMasterPage was created avoid taking
// the same Page
nNewPage += nMasterAlloc;
// adjust the file size if necessary
if( nNewPage >= rIo.GetPhysPages() )
if( !rIo.SetSize( nNewPage + 1 ) )
return sal_False;
}
// Set up the page with empty entries
StgPage* pPg = rIo.Copy( nNewPage, STG_FREE );
if ( !pPg )
return sal_False;
for( short j = 0; j < ( nPageSize >> 2 ); j++ )
pPg->SetPage( j, STG_FREE );
// store the page number into the master FAT
// Set the size before so the correct FAT can be found
nSize = ( nOld + 1 ) * nPageSize;
SetPage( nOld, nNewPage );
// MegaMasterPages were created, mark it them as used
sal_uInt32 nMax = rIo.aHdr.GetMasters( );
sal_uInt32 nFAT = rIo.aHdr.GetFATChain();
if( nMasterAlloc )
for( sal_uInt16 nCount = 0; nCount < nMax; nCount++ )
{
if( !Pos2Page( nFAT << 2 ) )
return sal_False;
if( nMax - nCount <= nMasterAlloc )
{
StgPage* piPg = rIo.Get( nPage, sal_True );
if( !piPg )
return sal_False;
piPg->SetPage( nOffset >> 2, STG_MASTER );
}
StgPage* pPage = rIo.Get( nFAT, sal_True );
if( !pPage ) return sal_False;
nFAT = pPage->GetPage( (nPageSize >> 2 ) - 1 );
}
nOld++;
// We have used up 4 bytes for the STG_FAT entry
nBytes += 4;
nNew = (short) (
( nBytes + ( nPageSize - 1 ) ) / nPageSize );
}
}
nSize = nNew * nPageSize;
rIo.aHdr.SetFATSize( nNew );
return sal_True;
}
/////////////////////////// class StgDataStrm //////////////////////////////
// This class is a normal physical stream which can be initialized
// either with an existing dir entry or an existing FAT chain.
// The stream has a size increment which normally is 1, but which can be
// set to any value is you want the size to be incremented by certain values.
StgDataStrm::StgDataStrm( StgIo& r, sal_Int32 nBgn, sal_Int32 nLen ) : StgStrm( r )
{
Init( nBgn, nLen );
}
StgDataStrm::StgDataStrm( StgIo& r, StgDirEntry& p ) : StgStrm( r )
{
pEntry = &p;
Init( p.aEntry.GetLeaf( STG_DATA ),
p.aEntry.GetSize() );
}
void StgDataStrm::Init( sal_Int32 nBgn, sal_Int32 nLen )
{
if ( rIo.pFAT )
pFat = new StgFAT( *rIo.pFAT, sal_True );
OSL_ENSURE( pFat, "The pointer should not be empty!" );
nStart = nPage = nBgn;
nSize = nLen;
nIncr = 1;
nOffset = 0;
if( nLen < 0 && pFat )
{
// determine the actual size of the stream by scanning
// the FAT chain and counting the # of pages allocated
nSize = 0;
// there may be files with double page numbers or loops of page
// references. This is not allowed. To be able to track this and
// to exit with an error, track already scanned PageNumbers here
// and use them to see if an already counted page is re-visited
std::set< sal_Int32 > nUsedPageNumbers;
while(nBgn >= 0)
{
if(nUsedPageNumbers.find(nBgn) == nUsedPageNumbers.end())
{
nUsedPageNumbers.insert(nBgn);
nSize += nPageSize;
nBgn = pFat->GetNextPage(nBgn);
}
else
{
rIo.SetError(ERRCODE_IO_WRONGFORMAT);
nBgn = -1;
}
}
}
}
// Set the size of a physical stream.
sal_Bool StgDataStrm::SetSize( sal_Int32 nBytes )
{
if ( !pFat )
return sal_False;
nBytes = ( ( nBytes + nIncr - 1 ) / nIncr ) * nIncr;
sal_Int32 nOldSz = nSize;
if( ( nOldSz != nBytes ) )
{
if( !StgStrm::SetSize( nBytes ) )
return sal_False;
sal_Int32 nMaxPage = pFat->GetMaxPage();
if( nMaxPage > rIo.GetPhysPages() )
if( !rIo.SetSize( nMaxPage ) )
return sal_False;
// If we only allocated one page or less, create this
// page in the cache for faster throughput. The current
// position is the former EOF point.
if( ( nSize - 1 ) / nPageSize - ( nOldSz - 1 ) / nPageSize == 1 )
{
Pos2Page( nBytes );
if( nPage >= 0 )
rIo.Copy( nPage, STG_FREE );
}
}
return sal_True;
}
// Get the address of the data byte at a specified offset.
// If bForce = sal_True, a read of non-existent data causes
// a read fault.
void* StgDataStrm::GetPtr( sal_Int32 Pos, sal_Bool bForce, sal_Bool bDirty )
{
if( Pos2Page( Pos ) )
{
StgPage* pPg = rIo.Get( nPage, bForce );
if( pPg )
{
pPg->SetOwner( pEntry );
if( bDirty )
pPg->SetDirty();
return ((sal_uInt8 *)pPg->GetData()) + nOffset;
}
}
return NULL;
}
// This could easily be adapted to a better algorithm by determining
// the amount of consecutable blocks before doing a read. The result
// is the number of bytes read. No error is generated on EOF.
sal_Int32 StgDataStrm::Read( void* pBuf, sal_Int32 n )
{
if ( n < 0 )
return 0;
if( ( nPos + n ) > nSize )
n = nSize - nPos;
sal_Int32 nDone = 0;
while( n )
{
short nBytes = nPageSize - nOffset;
short nRes;
StgPage* pPg;
if( (sal_Int32) nBytes > n )
nBytes = (short) n;
if( nBytes )
{
void *p = (sal_uInt8 *) pBuf + nDone;
if( nBytes == nPageSize )
{
pPg = rIo.Find( nPage );
if( pPg )
{
// data is present, so use the cached data
pPg->SetOwner( pEntry );
memcpy( p, pPg->GetData(), nBytes );
nRes = nBytes;
}
else
// do a direct (unbuffered) read
nRes = (short) rIo.Read( nPage, p, 1 ) * nPageSize;
}
else
{
// partial block read thru the cache.
pPg = rIo.Get( nPage, sal_False );
if( !pPg )
break;
pPg->SetOwner( pEntry );
memcpy( p, (sal_uInt8*)pPg->GetData() + nOffset, nBytes );
nRes = nBytes;
}
nDone += nRes;
nPos += nRes;
n -= nRes;
nOffset = nOffset + nRes;
if( nRes != nBytes )
break; // read error or EOF
}
// Switch to next page if necessary
if( nOffset >= nPageSize && !Pos2Page( nPos ) )
break;
}
return nDone;
}
sal_Int32 StgDataStrm::Write( const void* pBuf, sal_Int32 n )
{
if ( n < 0 )
return 0;
sal_Int32 nDone = 0;
if( ( nPos + n ) > nSize )
{
sal_Int32 nOld = nPos;
if( !SetSize( nPos + n ) )
return 0;
Pos2Page( nOld );
}
while( n )
{
short nBytes = nPageSize - nOffset;
short nRes;
StgPage* pPg;
if( (sal_Int32) nBytes > n )
nBytes = (short) n;
if( nBytes )
{
const void *p = (const sal_uInt8 *) pBuf + nDone;
if( nBytes == nPageSize )
{
pPg = rIo.Find( nPage );
if( pPg )
{
// data is present, so use the cached data
pPg->SetOwner( pEntry );
memcpy( pPg->GetData(), p, nBytes );
pPg->SetDirty();
nRes = nBytes;
}
else
// do a direct (unbuffered) write
nRes = (short) rIo.Write( nPage, (void*) p, 1 ) * nPageSize;
}
else
{
// partial block read thru the cache.
pPg = rIo.Get( nPage, sal_False );
if( !pPg )
break;
pPg->SetOwner( pEntry );
memcpy( (sal_uInt8*)pPg->GetData() + nOffset, p, nBytes );
pPg->SetDirty();
nRes = nBytes;
}
nDone += nRes;
nPos += nRes;
n -= nRes;
nOffset = nOffset + nRes;
if( nRes != nBytes )
break; // read error
}
// Switch to next page if necessary
if( nOffset >= nPageSize && !Pos2Page( nPos ) )
break;
}
return nDone;
}
//////////////////////////// class StgSmallStream ///////////////////////////
// The small stream class provides access to streams with a size < 4096 bytes.
// This stream is a StgStream containing small pages. The FAT for this stream
// is also a StgStream. The start of the FAT is in the header at DataRootPage,
// the stream itself is pointed to by the root entry (it holds start & size).
StgSmallStrm::StgSmallStrm( StgIo& r, sal_Int32 nBgn, sal_Int32 nLen ) : StgStrm( r )
{
Init( nBgn, nLen );
}
StgSmallStrm::StgSmallStrm( StgIo& r, StgDirEntry& p ) : StgStrm( r )
{
pEntry = &p;
Init( p.aEntry.GetLeaf( STG_DATA ),
p.aEntry.GetSize() );
}
void StgSmallStrm::Init( sal_Int32 nBgn, sal_Int32 nLen )
{
if ( rIo.pDataFAT )
pFat = new StgFAT( *rIo.pDataFAT, sal_False );
pData = rIo.pDataStrm;
OSL_ENSURE( pFat && pData, "The pointers should not be empty!" );
nPageSize = rIo.GetDataPageSize();
nStart =
nPage = nBgn;
nSize = nLen;
}
// This could easily be adapted to a better algorithm by determining
// the amount of consecutable blocks before doing a read. The result
// is the number of bytes read. No error is generated on EOF.
sal_Int32 StgSmallStrm::Read( void* pBuf, sal_Int32 n )
{
// We can safely assume that reads are not huge, since the
// small stream is likely to be < 64 KBytes.
if( ( nPos + n ) > nSize )
n = nSize - nPos;
short nDone = 0;
while( n )
{
short nBytes = nPageSize - nOffset;
if( (sal_Int32) nBytes > n )
nBytes = (short) n;
if( nBytes )
{
if( !pData || !pData->Pos2Page( nPage * nPageSize + nOffset ) )
break;
// all reading thru the stream
short nRes = (short) pData->Read( (sal_uInt8*)pBuf + nDone, nBytes );
nDone = nDone + nRes;
nPos += nRes;
n -= nRes;
nOffset = nOffset + nRes;
// read problem?
if( nRes != nBytes )
break;
}
// Switch to next page if necessary
if( nOffset >= nPageSize && !Pos2Page( nPos ) )
break;
}
return nDone;
}
sal_Int32 StgSmallStrm::Write( const void* pBuf, sal_Int32 n )
{
// you can safely assume that reads are not huge, since the
// small stream is likely to be < 64 KBytes.
short nDone = 0;
if( ( nPos + n ) > nSize )
{
sal_Int32 nOld = nPos;
if( !SetSize( nPos + n ) )
return sal_False;
Pos2Page( nOld );
}
while( n )
{
short nBytes = nPageSize - nOffset;
if( (sal_Int32) nBytes > n )
nBytes = (short) n;
if( nBytes )
{
// all writing goes thru the stream
sal_Int32 nDataPos = nPage * nPageSize + nOffset;
if ( !pData
|| ( pData->GetSize() < ( nDataPos + nBytes )
&& !pData->SetSize( nDataPos + nBytes ) ) )
break;
if( !pData->Pos2Page( nDataPos ) )
break;
short nRes = (short) pData->Write( (sal_uInt8*)pBuf + nDone, nBytes );
nDone = nDone + nRes;
nPos += nRes;
n -= nRes;
nOffset = nOffset + nRes;
// write problem?
if( nRes != nBytes )
break;
}
// Switch to next page if necessary
if( nOffset >= nPageSize && !Pos2Page( nPos ) )
break;
}
return nDone;
}
/////////////////////////// class StgTmpStrm /////////////////////////////
// The temporary stream uses a memory stream if < 32K, otherwise a
// temporary file.
#define THRESHOLD 32768L
StgTmpStrm::StgTmpStrm( sal_uLong nInitSize )
: SvMemoryStream( nInitSize > THRESHOLD
? 16
: ( nInitSize ? nInitSize : 16 ), 4096 )
{
pStrm = NULL;
// this calls FlushData, so all members should be set by this time
SetBufferSize( 0 );
if( nInitSize > THRESHOLD )
SetSize( nInitSize );
}
sal_Bool StgTmpStrm::Copy( StgTmpStrm& rSrc )
{
sal_uLong n = rSrc.GetSize();
sal_uLong nCur = rSrc.Tell();
SetSize( n );
if( GetError() == SVSTREAM_OK )
{
sal_uInt8* p = new sal_uInt8[ 4096 ];
rSrc.Seek( 0L );
Seek( 0L );
while( n )
{
sal_uLong nn = n;
if( nn > 4096 )
nn = 4096;
if( rSrc.Read( p, nn ) != nn )
break;
if( Write( p, nn ) != nn )
break;
n -= nn;
}
delete [] p;
rSrc.Seek( nCur );
Seek( nCur );
return sal_Bool( n == 0 );
}
else
return sal_False;
}
StgTmpStrm::~StgTmpStrm()
{
if( pStrm )
{
pStrm->Close();
osl::File::remove( aName );
delete pStrm;
}
}
sal_uLong StgTmpStrm::GetSize() const
{
sal_uLong n;
if( pStrm )
{
sal_uLong old = pStrm->Tell();
n = pStrm->Seek( STREAM_SEEK_TO_END );
pStrm->Seek( old );
}
else
n = nEndOfData;
return n;
}
void StgTmpStrm::SetSize( sal_uLong n )
{
if( pStrm )
pStrm->SetStreamSize( n );
else
{
if( n > THRESHOLD )
{
aName = TempFile::CreateTempName();
SvFileStream* s = new SvFileStream( aName, STREAM_READWRITE );
sal_uLong nCur = Tell();
sal_uLong i = nEndOfData;
if( i )
{
sal_uInt8* p = new sal_uInt8[ 4096 ];
Seek( 0L );
while( i )
{
sal_uLong nb = ( i > 4096 ) ? 4096 : i;
if( Read( p, nb ) == nb
&& s->Write( p, nb ) == nb )
i -= nb;
else
break;
}
delete [] p;
}
if( !i && n > nEndOfData )
{
// We have to write one byte at the end of the file
// if the file is bigger than the memstream to see
// if it fits on disk
s->Seek( n - 1 );
s->Write( &i, 1 );
s->Flush();
if( s->GetError() != SVSTREAM_OK )
i = 1;
}
Seek( nCur );
s->Seek( nCur );
if( i )
{
SetError( s->GetError() );
delete s;
return;
}
pStrm = s;
// Shrink the memory to 16 bytes, which seems to be the minimum
ReAllocateMemory( - ( (long) nEndOfData - 16 ) );
}
else
{
if( n > nEndOfData )
{
sal_uLong nCur = Tell();
Seek( nEndOfData - 1 );
*this << (sal_uInt8) 0;
Seek( nCur );
}
else
nEndOfData = n;
}
}
}
sal_uLong StgTmpStrm::GetData( void* pData, sal_uLong n )
{
if( pStrm )
{
n = pStrm->Read( pData, n );
SetError( pStrm->GetError() );
return n;
}
else
return SvMemoryStream::GetData( (sal_Char *)pData, n );
}
sal_uLong StgTmpStrm::PutData( const void* pData, sal_uLong n )
{
sal_uInt32 nCur = Tell();
sal_uInt32 nNew = nCur + n;
if( nNew > THRESHOLD && !pStrm )
{
SetSize( nNew );
if( GetError() != SVSTREAM_OK )
return 0;
}
if( pStrm )
{
nNew = pStrm->Write( pData, n );
SetError( pStrm->GetError() );
}
else
nNew = SvMemoryStream::PutData( (sal_Char*)pData, n );
return nNew;
}
sal_uLong StgTmpStrm::SeekPos( sal_uLong n )
{
if( n == STREAM_SEEK_TO_END )
n = GetSize();
if( n && n > THRESHOLD && !pStrm )
{
SetSize( n );
if( GetError() != SVSTREAM_OK )
return Tell();
else
return n;
}
else if( pStrm )
{
n = pStrm->Seek( n );
SetError( pStrm->GetError() );
return n;
}
else
return SvMemoryStream::SeekPos( n );
}
void StgTmpStrm::FlushData()
{
if( pStrm )
{
pStrm->Flush();
SetError( pStrm->GetError() );
}
else
SvMemoryStream::FlushData();
}
| 17,117 |
1,144 | package de.metas.ui.web.session;
import com.google.common.base.MoreObjects;
import de.metas.i18n.Language;
import de.metas.organization.OrgId;
import de.metas.security.RoleId;
import de.metas.ui.web.session.json.WebuiSessionId;
import de.metas.user.UserId;
import org.adempiere.service.ClientId;
import org.compiere.util.Env;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import java.io.IOException;
import java.io.Serializable;
import java.util.Locale;
import java.util.Optional;
import java.util.Properties;
/*
* #%L
* metasfresh-webui-api
* %%
* Copyright (C) 2017 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program 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 program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
/**
* Internal {@link UserSession} data.
* <p>
* NOTE: it's here and not inside UserSession class because it seems spring could not discover it
*
* @author metas-dev <<EMAIL>>
*/
@Component
@Primary
@SessionScope(proxyMode = ScopedProxyMode.TARGET_CLASS)
@lombok.Data
/* package */ class InternalUserSessionData implements Serializable
{
private static final long serialVersionUID = 4046535476486036184L;
// ---------------------------------------------------------------------------------------------
// NOTE: make sure none of those fields are "final" because this will prevent deserialization
// ---------------------------------------------------------------------------------------------
//
// Actual session data
private volatile boolean initialized = false;
private WebuiSessionId sessionId;
private UserPreference userPreference;
private boolean loggedIn;
private Locale locale = null;
private Properties ctx;
//
// User info
private String userFullname;
private String userEmail;
private String avatarId;
//
// Defaults
@Value("${metasfresh.webui.debug.showColumnNamesForCaption:false}")
private boolean defaultShowColumnNamesForCaption;
private boolean showColumnNamesForCaption;
//
@Value("${metasfresh.webui.debug.allowDeprecatedRestAPI:false}")
private boolean defaultAllowDeprecatedRestAPI;
private boolean allowDeprecatedRestAPI;
@Value("${metasfresh.webui.http.cache.maxAge:60}")
private int defaultHttpCacheMaxAge;
private int httpCacheMaxAge;
// TODO: set default to "true" after https://github.com/metasfresh/metasfresh-webui-frontend/issues/819
@Value("${metasfresh.webui.http.use.AcceptLanguage:false}")
private boolean defaultUseHttpAcceptLanguage;
private boolean useHttpAcceptLanguage;
//
public InternalUserSessionData()
{
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
sessionId = WebuiSessionId.ofNullableString(requestAttributes.getSessionId());
userPreference = new UserPreference();
loggedIn = false;
// Context
ctx = new Properties();
Env.setContext(ctx, WebRestApiContextProvider.CTXNAME_IsServerContext, false);
Env.setContext(ctx, WebRestApiContextProvider.CTXNAME_IsWebUI, true);
UserSession.logger.trace("User session created: {}", this);
}
void initializeIfNeeded()
{
if (!initialized)
{
synchronized (this)
{
if (!initialized)
{
initializeNow();
initialized = true;
}
}
}
}
private void initializeNow()
{
//
// Set initial properties
setShowColumnNamesForCaption(defaultShowColumnNamesForCaption);
setAllowDeprecatedRestAPI(defaultAllowDeprecatedRestAPI);
setHttpCacheMaxAge(defaultHttpCacheMaxAge);
setUseHttpAcceptLanguage(defaultUseHttpAcceptLanguage);
//
// Set initial language
try
{
final Language language = findInitialLanguage();
verifyLanguageAndSet(language);
}
catch (final Throwable ex)
{
UserSession.logger.warn("Failed setting the language, but moving on", ex);
}
}
private static Language findInitialLanguage()
{
final Locale locale = LocaleContextHolder.getLocale();
if (locale != null)
{
final Language language = Language.findLanguageByLocale(locale);
if (language != null)
{
return language;
}
}
return Language.getBaseLanguage();
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("sessionId", sessionId)
.add("loggedIn", loggedIn)
.add("locale", locale)
.add("userPreferences", userPreference)
.add("defaultUseHttpAcceptLanguage", defaultUseHttpAcceptLanguage)
.toString();
}
private void writeObject(final java.io.ObjectOutputStream out) throws IOException
{
out.defaultWriteObject();
UserSession.logger.trace("User session serialized: {}", this);
}
private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
{
in.defaultReadObject();
UserSession.logger.trace("User session deserialized: {}", this);
}
Properties getCtx()
{
return ctx;
}
public ClientId getClientId()
{
return Env.getClientId(getCtx());
}
public OrgId getOrgId()
{
return Env.getOrgId(getCtx());
}
public UserId getLoggedUserId()
{
return Env.getLoggedUserId(getCtx());
}
public Optional<UserId> getLoggedUserIdIfExists()
{
return Env.getLoggedUserIdIfExists(getCtx());
}
public RoleId getLoggedRoleId()
{
return Env.getLoggedRoleId(getCtx());
}
public String getUserName()
{
return Env.getContext(getCtx(), Env.CTXNAME_AD_User_Name);
}
public String getRoleName()
{
return Env.getContext(getCtx(), Env.CTXNAME_AD_Role_Name);
}
String getAdLanguage()
{
return Env.getContext(getCtx(), Env.CTXNAME_AD_Language);
}
Language getLanguage()
{
return Env.getLanguage(getCtx());
}
/**
* @return previous language
*/
String verifyLanguageAndSet(final Language lang)
{
final Properties ctx = getCtx();
final String adLanguageOld = Env.getContext(ctx, Env.CTXNAME_AD_Language);
//
// Check the language (and update it if needed)
final Language validLang = Env.verifyLanguageFallbackToBase(lang);
//
// Actual update
final String adLanguageNew = validLang.getAD_Language();
Env.setContext(ctx, Env.CTXNAME_AD_Language, adLanguageNew);
this.locale = validLang.getLocale();
UserSession.logger.debug("Changed AD_Language: {} -> {}, {}", adLanguageOld, adLanguageNew, validLang);
return adLanguageOld;
}
}
| 2,335 |
465 | /*
* Copyright (c) 2018 Uber Technologies, Inc.
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package com.uber.marmaray.common.dataset;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Simple Java Bean used to construct {@link UtilTable} of {@ErrorRecord}
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class ErrorRecord extends UtilRecord {
private String table_name;
private String row_key;
private String column_name;
private String content;
private String error_type;
public ErrorRecord(@NotEmpty final String applicationId,
@NotEmpty final String jobName,
final long jobStartTimestamp,
final long timestamp,
@NotEmpty final String tableName,
@NotEmpty final String rowKey,
@NotEmpty final String columnName,
@NotEmpty final String content,
@NotEmpty final String errorType) {
super(applicationId, jobName, jobStartTimestamp, timestamp);
this.table_name = tableName;
this.row_key = rowKey;
this.column_name = columnName;
this.content = content;
this.error_type = errorType;
}
}
| 806 |
1,056 | package test;
public class ReadUseElseTernary191230 {
private String used = "test";
public String test(boolean p) {
return p ? (String) "true" : used;
}
}
| 74 |
14,668 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/unified_consent/pref_names.h"
namespace unified_consent {
namespace prefs {
const char kUnifiedConsentMigrationState[] = "unified_consent.migration_state";
const char kUrlKeyedAnonymizedDataCollectionEnabled[] =
"url_keyed_anonymized_data_collection.enabled";
} // namespace prefs
} // namespace unified_consent
| 155 |
3,223 | <reponame>kouvel/corert<gh_stars>1000+
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "common.h"
#include "gcenv.h"
#include "gcheaputilities.h"
#include "objecthandle.h"
#include "gcenv.ee.h"
#include "PalRedhawkCommon.h"
#include "gcrhinterface.h"
#include "slist.h"
#include "varint.h"
#include "regdisplay.h"
#include "StackFrameIterator.h"
#include "thread.h"
#include "shash.h"
#include "RWLock.h"
#include "RuntimeInstance.h"
#include "threadstore.h"
#include "threadstore.inl"
#include "thread.inl"
#include "DebuggerHook.h"
#ifndef DACCESS_COMPILE
void GcEnumObjectsConservatively(PTR_PTR_Object ppLowerBound, PTR_PTR_Object ppUpperBound, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc);
void EnumAllStaticGCRefs(EnumGcRefCallbackFunc * fn, EnumGcRefScanContext * sc)
{
GetRuntimeInstance()->EnumAllStaticGCRefs(reinterpret_cast<void*>(fn), sc);
}
/*
* Scan all stack and statics roots
*/
void GCToEEInterface::GcScanRoots(EnumGcRefCallbackFunc * fn, int condemned, int max_gen, EnumGcRefScanContext * sc)
{
DebuggerProtectedBufferListNode* cursor = DebuggerHook::s_debuggerProtectedBuffers;
while (cursor != nullptr)
{
GcEnumObjectsConservatively((PTR_PTR_Object)cursor->address, (PTR_PTR_Object)(cursor->address + cursor->size), fn, sc);
cursor = cursor->next;
}
// STRESS_LOG1(LF_GCROOTS, LL_INFO10, "GCScan: Phase = %s\n", sc->promotion ? "promote" : "relocate");
FOREACH_THREAD(pThread)
{
// Skip "GC Special" threads which are really background workers that will never have any roots.
if (pThread->IsGCSpecial())
continue;
#if !defined (ISOLATED_HEAPS)
// @TODO: it is very bizarre that this IsThreadUsingAllocationContextHeap takes a copy of the
// allocation context instead of a reference or a pointer to it. This seems very wasteful given how
// large the alloc_context is.
if (!GCHeapUtilities::GetGCHeap()->IsThreadUsingAllocationContextHeap(pThread->GetAllocContext(),
sc->thread_number))
{
// STRESS_LOG2(LF_GC|LF_GCROOTS, LL_INFO100, "{ Scan of Thread %p (ID = %x) declined by this heap\n",
// pThread, pThread->GetThreadId());
}
else
#endif
{
STRESS_LOG1(LF_GC|LF_GCROOTS, LL_INFO100, "{ Starting scan of Thread %p\n", pThread);
sc->thread_under_crawl = pThread;
#if defined(FEATURE_EVENT_TRACE) && !defined(DACCESS_COMPILE)
sc->dwEtwRootKind = kEtwGCRootKindStack;
#endif
pThread->GcScanRoots(reinterpret_cast<void*>(fn), sc);
#if defined(FEATURE_EVENT_TRACE) && !defined(DACCESS_COMPILE)
sc->dwEtwRootKind = kEtwGCRootKindOther;
#endif
STRESS_LOG1(LF_GC|LF_GCROOTS, LL_INFO100, "Ending scan of Thread %p }\n", pThread);
}
}
END_FOREACH_THREAD
sc->thread_under_crawl = NULL;
if ((!GCHeapUtilities::IsServerHeap() || sc->thread_number == 0) ||(condemned == max_gen && sc->promotion))
{
#if defined(FEATURE_EVENT_TRACE) && !defined(DACCESS_COMPILE)
sc->dwEtwRootKind = kEtwGCRootKindHandle;
#endif
EnumAllStaticGCRefs(fn, sc);
}
}
void GCToEEInterface::GcEnumAllocContexts (enum_alloc_context_func* fn, void* param)
{
FOREACH_THREAD(thread)
{
(*fn) (thread->GetAllocContext(), param);
}
END_FOREACH_THREAD
}
#endif //!DACCESS_COMPILE
void PromoteCarefully(PTR_PTR_Object obj, UInt32 flags, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc)
{
//
// Sanity check that the flags contain only these three values
//
assert((flags & ~(GC_CALL_INTERIOR|GC_CALL_PINNED|GC_CALL_CHECK_APP_DOMAIN)) == 0);
//
// Sanity check that GC_CALL_INTERIOR FLAG is set
//
assert(flags & GC_CALL_INTERIOR);
// If the object reference points into the stack, we
// must not promote it, the GC cannot handle these.
if (pSc->thread_under_crawl->IsWithinStackBounds(*obj))
return;
fnGcEnumRef(obj, pSc, flags);
}
void GcEnumObject(PTR_PTR_Object ppObj, UInt32 flags, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc)
{
//
// Sanity check that the flags contain only these three values
//
assert((flags & ~(GC_CALL_INTERIOR|GC_CALL_PINNED|GC_CALL_CHECK_APP_DOMAIN)) == 0);
// for interior pointers, we optimize the case in which
// it points into the current threads stack area
//
if (flags & GC_CALL_INTERIOR)
PromoteCarefully (ppObj, flags, fnGcEnumRef, pSc);
else
fnGcEnumRef(ppObj, pSc, flags);
}
void GcBulkEnumObjects(PTR_PTR_Object pObjs, UInt32 cObjs, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc)
{
PTR_PTR_Object ppObj = pObjs;
for (UInt32 i = 0; i < cObjs; i++)
fnGcEnumRef(ppObj++, pSc, 0);
}
// Scan a contiguous range of memory and report everything that looks like it could be a GC reference as a
// pinned interior reference. Pinned in case we are wrong (so the GC won't try to move the object and thus
// corrupt the original memory value by relocating it). Interior since we (a) can't easily tell whether a
// real reference is interior or not and interior is the more conservative choice that will work for both and
// (b) because it might not be a real GC reference at all and in that case falsely listing the reference as
// non-interior will cause the GC to make assumptions and crash quite quickly.
void GcEnumObjectsConservatively(PTR_PTR_Object ppLowerBound, PTR_PTR_Object ppUpperBound, EnumGcRefCallbackFunc * fnGcEnumRef, EnumGcRefScanContext * pSc)
{
// Only report potential references in the promotion phase. Since we report everything as pinned there
// should be no work to do in the relocation phase.
if (pSc->promotion)
{
for (PTR_PTR_Object ppObj = ppLowerBound; ppObj < ppUpperBound; ppObj++)
{
// Only report values that lie in the GC heap range. This doesn't conclusively guarantee that the
// value is a GC heap reference but it's a cheap check that weeds out a lot of spurious values.
PTR_Object pObj = *ppObj;
if (((PTR_UInt8)pObj >= g_lowest_address) && ((PTR_UInt8)pObj <= g_highest_address))
fnGcEnumRef(ppObj, pSc, GC_CALL_INTERIOR|GC_CALL_PINNED);
}
}
}
| 2,673 |
1,318 | <filename>Resources/Perl/perl.h
/* perl.h
*
* Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
* 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 by <NAME> and others
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file.
*
*/
#ifndef H_PERL
#define H_PERL 1
#ifdef PERL_FOR_X2P
/*
* This file is being used for x2p stuff.
* Above symbol is defined via -D in 'x2p/Makefile.SH'
* Decouple x2p stuff from some of perls more extreme eccentricities.
*/
#undef MULTIPLICITY
#undef USE_STDIO
#define USE_STDIO
#endif /* PERL_FOR_X2P */
#ifdef PERL_MICRO
# include "uconfig.h"
#else
# include "config.h"
#endif
/* this is used for functions which take a depth trailing
* argument under debugging */
#ifdef DEBUGGING
#define _pDEPTH ,U32 depth
#define _aDEPTH ,depth
#else
#define _pDEPTH
#define _aDEPTH
#endif
/* NOTE 1: that with gcc -std=c89 the __STDC_VERSION__ is *not* defined
* because the __STDC_VERSION__ became a thing only with C90. Therefore,
* with gcc, HAS_C99 will never become true as long as we use -std=c89.
* NOTE 2: headers lie. Do not expect that if HAS_C99 gets to be true,
* all the C99 features are there and are correct. */
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || \
defined(_STDC_C99) || defined(__c99)
# define HAS_C99 1
#endif
/* See L<perlguts/"The Perl API"> for detailed notes on
* PERL_IMPLICIT_CONTEXT and PERL_IMPLICIT_SYS */
/* XXX NOTE that from here --> to <-- the same logic is
* repeated in makedef.pl, so be certain to update
* both places when editing. */
#ifdef USE_ITHREADS
# if !defined(MULTIPLICITY)
# define MULTIPLICITY
# endif
#endif
#ifdef PERL_GLOBAL_STRUCT_PRIVATE
# ifndef PERL_GLOBAL_STRUCT
# define PERL_GLOBAL_STRUCT
# endif
#endif
#ifdef PERL_GLOBAL_STRUCT
# ifndef MULTIPLICITY
# define MULTIPLICITY
# endif
#endif
#ifdef MULTIPLICITY
# ifndef PERL_IMPLICIT_CONTEXT
# define PERL_IMPLICIT_CONTEXT
# endif
#endif
/* undef WIN32 when building on Cygwin (for libwin32) - gph */
#ifdef __CYGWIN__
# undef WIN32
# undef _WIN32
#endif
#if defined(__SYMBIAN32__) || (defined(__VC32__) && defined(WINS))
# ifndef SYMBIAN
# define SYMBIAN
# endif
#endif
#ifdef __SYMBIAN32__
# include "symbian/symbian_proto.h"
#endif
/* Any stack-challenged places. The limit varies (and often
* is configurable), but using more than a kilobyte of stack
* is usually dubious in these systems. */
#if defined(__SYMBIAN32__)
/* Symbian: need to work around the SDK features. *
* On WINS: MS VC5 generates calls to _chkstk, *
* if a "large" stack frame is allocated. *
* gcc on MARM does not generate calls like these. */
# define USE_HEAP_INSTEAD_OF_STACK
#endif
/* Use the reentrant APIs like localtime_r and getpwent_r */
/* Win32 has naturally threadsafe libraries, no need to use any _r variants.
* XXX KEEP makedef.pl copy of this code in sync */
#if defined(USE_ITHREADS) && !defined(USE_REENTRANT_API) && !defined(NETWARE) && !defined(WIN32)
# define USE_REENTRANT_API
#endif
/* <--- here ends the logic shared by perl.h and makedef.pl */
#undef START_EXTERN_C
#undef END_EXTERN_C
#undef EXTERN_C
#ifdef __cplusplus
# define START_EXTERN_C extern "C" {
# define END_EXTERN_C }
# define EXTERN_C extern "C"
#else
# define START_EXTERN_C
# define END_EXTERN_C
# define EXTERN_C extern
#endif
/* Fallback definitions in case we don't have definitions from config.h.
This should only matter for systems that don't use Configure and
haven't been modified to define PERL_STATIC_INLINE yet.
*/
#if !defined(PERL_STATIC_INLINE)
# ifdef HAS_STATIC_INLINE
# define PERL_STATIC_INLINE static inline
# else
# define PERL_STATIC_INLINE static
# endif
#endif
#if defined(PERL_GLOBAL_STRUCT) && !defined(PERL_GET_VARS)
# ifdef PERL_GLOBAL_STRUCT_PRIVATE
EXTERN_C struct perl_vars* Perl_GetVarsPrivate();
# define PERL_GET_VARS() Perl_GetVarsPrivate() /* see miniperlmain.c */
# else
# define PERL_GET_VARS() PL_VarsPtr
# endif
#endif
/* this used to be off by default, now its on, see perlio.h */
#define PERLIO_FUNCS_CONST
#define pVAR struct perl_vars* my_vars PERL_UNUSED_DECL
#ifdef PERL_GLOBAL_STRUCT
# define dVAR pVAR = (struct perl_vars*)PERL_GET_VARS()
#else
# define dVAR dNOOP
#endif
#ifdef PERL_IMPLICIT_CONTEXT
# ifndef MULTIPLICITY
# define MULTIPLICITY
# endif
# define tTHX PerlInterpreter*
# define pTHX tTHX my_perl PERL_UNUSED_DECL
# define aTHX my_perl
# define aTHXa(a) aTHX = (tTHX)a
# ifdef PERL_GLOBAL_STRUCT
# define dTHXa(a) dVAR; pTHX = (tTHX)a
# else
# define dTHXa(a) pTHX = (tTHX)a
# endif
# ifdef PERL_GLOBAL_STRUCT
# define dTHX dVAR; pTHX = PERL_GET_THX
# else
# define dTHX pTHX = PERL_GET_THX
# endif
# define pTHX_ pTHX,
# define aTHX_ aTHX,
# define pTHX_1 2
# define pTHX_2 3
# define pTHX_3 4
# define pTHX_4 5
# define pTHX_5 6
# define pTHX_6 7
# define pTHX_7 8
# define pTHX_8 9
# define pTHX_9 10
# define pTHX_12 13
# if defined(DEBUGGING) && !defined(PERL_TRACK_MEMPOOL)
# define PERL_TRACK_MEMPOOL
# endif
#else
# undef PERL_TRACK_MEMPOOL
#endif
#ifdef DEBUGGING
# define dTHX_DEBUGGING dTHX
#else
# define dTHX_DEBUGGING dNOOP
#endif
#define STATIC static
#ifndef PERL_CORE
/* Do not use these macros. They were part of PERL_OBJECT, which was an
* implementation of multiplicity using C++ objects. They have been left
* here solely for the sake of XS code which has incorrectly
* cargo-culted them.
*/
#define CPERLscope(x) x
#define CPERLarg void
#define CPERLarg_
#define _CPERLarg
#define PERL_OBJECT_THIS
#define _PERL_OBJECT_THIS
#define PERL_OBJECT_THIS_
#define CALL_FPTR(fptr) (*fptr)
#define MEMBER_TO_FPTR(name) name
#endif /* !PERL_CORE */
#define CALLRUNOPS PL_runops
#define CALLREGCOMP(sv, flags) Perl_pregcomp(aTHX_ (sv),(flags))
#define CALLREGCOMP_ENG(prog, sv, flags) (prog)->comp(aTHX_ sv, flags)
#define CALLREGEXEC(prog,stringarg,strend,strbeg,minend,sv,data,flags) \
RX_ENGINE(prog)->exec(aTHX_ (prog),(stringarg),(strend), \
(strbeg),(minend),(sv),(data),(flags))
#define CALLREG_INTUIT_START(prog,sv,strbeg,strpos,strend,flags,data) \
RX_ENGINE(prog)->intuit(aTHX_ (prog), (sv), (strbeg), (strpos), \
(strend),(flags),(data))
#define CALLREG_INTUIT_STRING(prog) \
RX_ENGINE(prog)->checkstr(aTHX_ (prog))
#define CALLREGFREE(prog) \
Perl_pregfree(aTHX_ (prog))
#define CALLREGFREE_PVT(prog) \
if(prog && RX_ENGINE(prog)) RX_ENGINE(prog)->rxfree(aTHX_ (prog))
#define CALLREG_NUMBUF_FETCH(rx,paren,usesv) \
RX_ENGINE(rx)->numbered_buff_FETCH(aTHX_ (rx),(paren),(usesv))
#define CALLREG_NUMBUF_STORE(rx,paren,value) \
RX_ENGINE(rx)->numbered_buff_STORE(aTHX_ (rx),(paren),(value))
#define CALLREG_NUMBUF_LENGTH(rx,sv,paren) \
RX_ENGINE(rx)->numbered_buff_LENGTH(aTHX_ (rx),(sv),(paren))
#define CALLREG_NAMED_BUFF_FETCH(rx, key, flags) \
RX_ENGINE(rx)->named_buff(aTHX_ (rx), (key), NULL, ((flags) | RXapif_FETCH))
#define CALLREG_NAMED_BUFF_STORE(rx, key, value, flags) \
RX_ENGINE(rx)->named_buff(aTHX_ (rx), (key), (value), ((flags) | RXapif_STORE))
#define CALLREG_NAMED_BUFF_DELETE(rx, key, flags) \
RX_ENGINE(rx)->named_buff(aTHX_ (rx),(key), NULL, ((flags) | RXapif_DELETE))
#define CALLREG_NAMED_BUFF_CLEAR(rx, flags) \
RX_ENGINE(rx)->named_buff(aTHX_ (rx), NULL, NULL, ((flags) | RXapif_CLEAR))
#define CALLREG_NAMED_BUFF_EXISTS(rx, key, flags) \
RX_ENGINE(rx)->named_buff(aTHX_ (rx), (key), NULL, ((flags) | RXapif_EXISTS))
#define CALLREG_NAMED_BUFF_FIRSTKEY(rx, flags) \
RX_ENGINE(rx)->named_buff_iter(aTHX_ (rx), NULL, ((flags) | RXapif_FIRSTKEY))
#define CALLREG_NAMED_BUFF_NEXTKEY(rx, lastkey, flags) \
RX_ENGINE(rx)->named_buff_iter(aTHX_ (rx), (lastkey), ((flags) | RXapif_NEXTKEY))
#define CALLREG_NAMED_BUFF_SCALAR(rx, flags) \
RX_ENGINE(rx)->named_buff(aTHX_ (rx), NULL, NULL, ((flags) | RXapif_SCALAR))
#define CALLREG_NAMED_BUFF_COUNT(rx) \
RX_ENGINE(rx)->named_buff(aTHX_ (rx), NULL, NULL, RXapif_REGNAMES_COUNT)
#define CALLREG_NAMED_BUFF_ALL(rx, flags) \
RX_ENGINE(rx)->named_buff(aTHX_ (rx), NULL, NULL, flags)
#define CALLREG_PACKAGE(rx) \
RX_ENGINE(rx)->qr_package(aTHX_ (rx))
#if defined(USE_ITHREADS)
#define CALLREGDUPE(prog,param) \
Perl_re_dup(aTHX_ (prog),(param))
#define CALLREGDUPE_PVT(prog,param) \
(prog ? RX_ENGINE(prog)->dupe(aTHX_ (prog),(param)) \
: (REGEXP *)NULL)
#endif
/* some compilers impersonate gcc */
#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
# define PERL_IS_GCC 1
#endif
/* In case Configure was not used (we are using a "canned config"
* such as Win32, or a cross-compilation setup, for example) try going
* by the gcc major and minor versions. One useful URL is
* http://www.ohse.de/uwe/articles/gcc-attributes.html,
* but contrary to this information warn_unused_result seems
* not to be in gcc 3.3.5, at least. --jhi
* Also, when building extensions with an installed perl, this allows
* the user to upgrade gcc and get the right attributes, rather than
* relying on the list generated at Configure time. --AD
* Set these up now otherwise we get confused when some of the <*thread.h>
* includes below indirectly pull in <perlio.h> (which needs to know if we
* have HASATTRIBUTE_FORMAT).
*/
#ifndef PERL_MICRO
#if defined __GNUC__ && !defined(__INTEL_COMPILER)
# if __GNUC__ == 3 && __GNUC_MINOR__ >= 1 || __GNUC__ > 3 /* 3.1 -> */
# define HASATTRIBUTE_DEPRECATED
# endif
# if __GNUC__ >= 3 /* 3.0 -> */ /* XXX Verify this version */
# define HASATTRIBUTE_FORMAT
# if defined __MINGW32__
# define PRINTF_FORMAT_NULL_OK
# endif
# endif
# if __GNUC__ >= 3 /* 3.0 -> */
# define HASATTRIBUTE_MALLOC
# endif
# if __GNUC__ == 3 && __GNUC_MINOR__ >= 3 || __GNUC__ > 3 /* 3.3 -> */
# define HASATTRIBUTE_NONNULL
# endif
# if __GNUC__ == 2 && __GNUC_MINOR__ >= 5 || __GNUC__ > 2 /* 2.5 -> */
# define HASATTRIBUTE_NORETURN
# endif
# if __GNUC__ >= 3 /* gcc 3.0 -> */
# define HASATTRIBUTE_PURE
# endif
# if __GNUC__ == 3 && __GNUC_MINOR__ >= 4 || __GNUC__ > 3 /* 3.4 -> */
# define HASATTRIBUTE_UNUSED
# endif
# if __GNUC__ == 3 && __GNUC_MINOR__ == 3 && !defined(__cplusplus)
# define HASATTRIBUTE_UNUSED /* gcc-3.3, but not g++-3.3. */
# endif
# if __GNUC__ == 3 && __GNUC_MINOR__ >= 4 || __GNUC__ > 3 /* 3.4 -> */
# define HASATTRIBUTE_WARN_UNUSED_RESULT
# endif
/* always_inline is buggy in gcc <= 4.6 and causes compilation errors */
# if __GNUC__ == 4 && __GNUC_MINOR__ >= 7 || __GNUC__ > 4 /* 4.7 -> */
# define HASATTRIBUTE_ALWAYS_INLINE
# endif
#endif
#endif /* #ifndef PERL_MICRO */
#ifdef HASATTRIBUTE_DEPRECATED
# define __attribute__deprecated__ __attribute__((deprecated))
#endif
#ifdef HASATTRIBUTE_FORMAT
# define __attribute__format__(x,y,z) __attribute__((format(x,y,z)))
#endif
#ifdef HASATTRIBUTE_MALLOC
# define __attribute__malloc__ __attribute__((__malloc__))
#endif
#ifdef HASATTRIBUTE_NONNULL
# define __attribute__nonnull__(a) __attribute__((nonnull(a)))
#endif
#ifdef HASATTRIBUTE_NORETURN
# define __attribute__noreturn__ __attribute__((noreturn))
#endif
#ifdef HASATTRIBUTE_PURE
# define __attribute__pure__ __attribute__((pure))
#endif
#ifdef HASATTRIBUTE_UNUSED
# define __attribute__unused__ __attribute__((unused))
#endif
#ifdef HASATTRIBUTE_WARN_UNUSED_RESULT
# define __attribute__warn_unused_result__ __attribute__((warn_unused_result))
#endif
#ifdef HASATTRIBUTE_ALWAYS_INLINE
/* always_inline is buggy in gcc <= 4.6 and causes compilation errors */
# if !defined(PERL_IS_GCC) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7 || __GNUC__ > 4)
# define __attribute__always_inline__ __attribute__((always_inline))
# endif
#endif
/* If we haven't defined the attributes yet, define them to blank. */
#ifndef __attribute__deprecated__
# define __attribute__deprecated__
#endif
#ifndef __attribute__format__
# define __attribute__format__(x,y,z)
#endif
#ifndef __attribute__malloc__
# define __attribute__malloc__
#endif
#ifndef __attribute__nonnull__
# define __attribute__nonnull__(a)
#endif
#ifndef __attribute__noreturn__
# define __attribute__noreturn__
#endif
#ifndef __attribute__pure__
# define __attribute__pure__
#endif
#ifndef __attribute__unused__
# define __attribute__unused__
#endif
#ifndef __attribute__warn_unused_result__
# define __attribute__warn_unused_result__
#endif
#ifndef __attribute__always_inline__
# define __attribute__always_inline__
#endif
/* Some OS warn on NULL format to printf */
#ifdef PRINTF_FORMAT_NULL_OK
# define __attribute__format__null_ok__(x,y,z) __attribute__format__(x,y,z)
#else
# define __attribute__format__null_ok__(x,y,z)
#endif
/*
* Because of backward compatibility reasons the PERL_UNUSED_DECL
* cannot be changed from postfix to PERL_UNUSED_DECL(x). Sigh.
*
* Note that there are C compilers such as MetroWerks CodeWarrior
* which do not have an "inlined" way (like the gcc __attribute__) of
* marking unused variables (they need e.g. a #pragma) and therefore
* cpp macros like PERL_UNUSED_DECL cannot work for this purpose, even
* if it were PERL_UNUSED_DECL(x), which it cannot be (see above).
*
*/
#ifndef PERL_UNUSED_DECL
# define PERL_UNUSED_DECL __attribute__unused__
#endif
/* gcc -Wall:
* for silencing unused variables that are actually used most of the time,
* but we cannot quite get rid of, such as "ax" in PPCODE+noargs xsubs,
* or variables/arguments that are used only in certain configurations.
*/
#ifndef PERL_UNUSED_ARG
# define PERL_UNUSED_ARG(x) ((void)sizeof(x))
#endif
#ifndef PERL_UNUSED_VAR
# define PERL_UNUSED_VAR(x) ((void)sizeof(x))
#endif
#if defined(USE_ITHREADS) || defined(PERL_GLOBAL_STRUCT)
# define PERL_UNUSED_CONTEXT PERL_UNUSED_ARG(my_perl)
#else
# define PERL_UNUSED_CONTEXT
#endif
/* gcc (-ansi) -pedantic doesn't allow gcc statement expressions,
* g++ allows them but seems to have problems with them
* (insane errors ensue).
* g++ does not give insane errors now (RMB 2008-01-30, gcc 4.2.2).
*/
#if defined(PERL_GCC_PEDANTIC) || \
(defined(__GNUC__) && defined(__cplusplus) && \
((__GNUC__ < 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ < 2))))
# ifndef PERL_GCC_BRACE_GROUPS_FORBIDDEN
# define PERL_GCC_BRACE_GROUPS_FORBIDDEN
# endif
#endif
/* Use PERL_UNUSED_RESULT() to suppress the warnings about unused results
* of function calls, e.g. PERL_UNUSED_RESULT(foo(a, b)).
*
* The main reason for this is that the combination of gcc -Wunused-result
* (part of -Wall) and the __attribute__((warn_unused_result)) cannot
* be silenced with casting to void. This causes trouble when the system
* header files use the attribute.
*
* Use PERL_UNUSED_RESULT sparingly, though, since usually the warning
* is there for a good reason: you might lose success/failure information,
* or leak resources, or changes in resources.
*
* But sometimes you just want to ignore the return value, e.g. on
* codepaths soon ending up in abort, or in "best effort" attempts,
* or in situations where there is no good way to handle failures.
*
* Sometimes PERL_UNUSED_RESULT might not be the most natural way:
* another possibility is that you can capture the return value
* and use PERL_UNUSED_VAR on that.
*
* The __typeof__() is used instead of typeof() since typeof() is not
* available under strict C89, and because of compilers masquerading
* as gcc (clang and icc), we want exactly the gcc extension
* __typeof__ and nothing else.
*/
#ifndef PERL_UNUSED_RESULT
# if defined(__GNUC__) && defined(HASATTRIBUTE_WARN_UNUSED_RESULT)
# define PERL_UNUSED_RESULT(v) STMT_START { __typeof__(v) z = (v); (void)sizeof(z); } STMT_END
# else
# define PERL_UNUSED_RESULT(v) ((void)(v))
# endif
#endif
#if defined(_MSC_VER)
/* XXX older MSVC versions have a smallish macro buffer */
#define PERL_SMALL_MACRO_BUFFER
#endif
/* on gcc (and clang), specify that a warning should be temporarily
* ignored; e.g.
*
* GCC_DIAG_IGNORE_DECL(-Wmultichar);
* char b = 'ab';
* GCC_DIAG_RESTORE_DECL;
*
* based on http://dbp-consulting.com/tutorials/SuppressingGCCWarnings.html
*
* Note that "pragma GCC diagnostic push/pop" was added in GCC 4.6, Mar 2011;
* clang only pretends to be GCC 4.2, but still supports push/pop.
*
* Note on usage: all macros must be used at a place where a declaration
* or statement can occur, i.e., not in the middle of an expression.
* *_DIAG_IGNORE() and *_DIAG_RESTORE can be used in any such place, but
* must be used without a following semicolon. *_DIAG_IGNORE_DECL() and
* *_DIAG_RESTORE_DECL must be used with a following semicolon, and behave
* syntactically as declarations (like dNOOP). *_DIAG_IGNORE_STMT()
* and *_DIAG_RESTORE_STMT must be used with a following semicolon,
* and behave syntactically as statements (like NOOP).
*
*/
#if defined(__clang__) || defined(__clang) || \
(defined( __GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406)
# define GCC_DIAG_PRAGMA(x) _Pragma (#x)
/* clang has "clang diagnostic" pragmas, but also understands gcc. */
# define GCC_DIAG_IGNORE(x) _Pragma("GCC diagnostic push") \
GCC_DIAG_PRAGMA(GCC diagnostic ignored #x)
# define GCC_DIAG_RESTORE _Pragma("GCC diagnostic pop")
#else
# define GCC_DIAG_IGNORE(w)
# define GCC_DIAG_RESTORE
#endif
#define GCC_DIAG_IGNORE_DECL(x) GCC_DIAG_IGNORE(x) dNOOP
#define GCC_DIAG_RESTORE_DECL GCC_DIAG_RESTORE dNOOP
#define GCC_DIAG_IGNORE_STMT(x) GCC_DIAG_IGNORE(x) NOOP
#define GCC_DIAG_RESTORE_STMT GCC_DIAG_RESTORE NOOP
/* for clang specific pragmas */
#if defined(__clang__) || defined(__clang)
# define CLANG_DIAG_PRAGMA(x) _Pragma (#x)
# define CLANG_DIAG_IGNORE(x) _Pragma("clang diagnostic push") \
CLANG_DIAG_PRAGMA(clang diagnostic ignored #x)
# define CLANG_DIAG_RESTORE _Pragma("clang diagnostic pop")
#else
# define CLANG_DIAG_IGNORE(w)
# define CLANG_DIAG_RESTORE
#endif
#define CLANG_DIAG_IGNORE_DECL(x) CLANG_DIAG_IGNORE(x) dNOOP
#define CLANG_DIAG_RESTORE_DECL CLANG_DIAG_RESTORE dNOOP
#define CLANG_DIAG_IGNORE_STMT(x) CLANG_DIAG_IGNORE(x) NOOP
#define CLANG_DIAG_RESTORE_STMT CLANG_DIAG_RESTORE NOOP
#if defined(_MSC_VER) && (_MSC_VER >= 1300)
# define MSVC_DIAG_IGNORE(x) __pragma(warning(push)) \
__pragma(warning(disable : x))
# define MSVC_DIAG_RESTORE __pragma(warning(pop))
#else
# define MSVC_DIAG_IGNORE(x)
# define MSVC_DIAG_RESTORE
#endif
#define MSVC_DIAG_IGNORE_DECL(x) MSVC_DIAG_IGNORE(x) dNOOP
#define MSVC_DIAG_RESTORE_DECL MSVC_DIAG_RESTORE dNOOP
#define MSVC_DIAG_IGNORE_STMT(x) MSVC_DIAG_IGNORE(x) NOOP
#define MSVC_DIAG_RESTORE_STMT MSVC_DIAG_RESTORE NOOP
#define NOOP /*EMPTY*/(void)0
#define dNOOP struct Perl___notused_struct
#ifndef pTHX
/* Don't bother defining tTHX ; using it outside
* code guarded by PERL_IMPLICIT_CONTEXT is an error.
*/
# define pTHX void
# define pTHX_
# define aTHX
# define aTHX_
# define aTHXa(a) NOOP
# define dTHXa(a) dNOOP
# define dTHX dNOOP
# define pTHX_1 1
# define pTHX_2 2
# define pTHX_3 3
# define pTHX_4 4
# define pTHX_5 5
# define pTHX_6 6
# define pTHX_7 7
# define pTHX_8 8
# define pTHX_9 9
# define pTHX_12 12
#endif
#ifndef dVAR
# define dVAR dNOOP
#endif
/* these are only defined for compatibility; should not be used internally */
#if !defined(pTHXo) && !defined(PERL_CORE)
# define pTHXo pTHX
# define pTHXo_ pTHX_
# define aTHXo aTHX
# define aTHXo_ aTHX_
# define dTHXo dTHX
# define dTHXoa(x) dTHXa(x)
#endif
#ifndef pTHXx
# define pTHXx PerlInterpreter *my_perl
# define pTHXx_ pTHXx,
# define aTHXx my_perl
# define aTHXx_ aTHXx,
# define dTHXx dTHX
#endif
/* Under PERL_IMPLICIT_SYS (used in Windows for fork emulation)
* PerlIO_foo() expands to PL_StdIO->pFOO(PL_StdIO, ...).
* dTHXs is therefore needed for all functions using PerlIO_foo(). */
#ifdef PERL_IMPLICIT_SYS
# ifdef PERL_GLOBAL_STRUCT_PRIVATE
# define dTHXs dVAR; dTHX
# else
# define dTHXs dTHX
# endif
#else
# ifdef PERL_GLOBAL_STRUCT_PRIVATE
# define dTHXs dVAR
# else
# define dTHXs dNOOP
# endif
#endif
#if defined(__GNUC__) && !defined(PERL_GCC_BRACE_GROUPS_FORBIDDEN) && !defined(__cplusplus)
# ifndef PERL_USE_GCC_BRACE_GROUPS
# define PERL_USE_GCC_BRACE_GROUPS
# endif
#endif
/*
=head1 Miscellaneous Functions
=for apidoc AmnUu|void|STMT_START
STMT_START { statements; } STMT_END;
can be used as a single statement, as in
if (x) STMT_START { ... } STMT_END; else ...
These are often used in macro definitions. Note that you can't return a value
out of them.
=for apidoc AmnUhu|void|STMT_END
=cut
Trying to select a version that gives no warnings...
*/
#if !(defined(STMT_START) && defined(STMT_END))
# ifdef PERL_USE_GCC_BRACE_GROUPS
# define STMT_START (void)( /* gcc supports "({ STATEMENTS; })" */
# define STMT_END )
# else
# define STMT_START do
# define STMT_END while (0)
# endif
#endif
#ifndef BYTEORDER /* Should never happen -- byteorder is in config.h */
# define BYTEORDER 0x1234
#endif
#if 'A' == 65 && 'I' == 73 && 'J' == 74 && 'Z' == 90
#define ASCIIish
#else
#undef ASCIIish
#endif
/*
* The following contortions are brought to you on behalf of all the
* standards, semi-standards, de facto standards, not-so-de-facto standards
* of the world, as well as all the other botches anyone ever thought of.
* The basic theory is that if we work hard enough here, the rest of the
* code can be a lot prettier. Well, so much for theory. Sorry, Henry...
*/
/* define this once if either system, instead of cluttering up the src */
#if defined(MSDOS) || defined(WIN32) || defined(NETWARE)
#define DOSISH 1
#endif
/* These exist only for back-compat with XS modules. */
#ifndef PERL_CORE
#define VOL volatile
#define CAN_PROTOTYPE
#define _(args) args
#define I_LIMITS
#define I_STDARG
#define STANDARD_C
#endif
/* By compiling a perl with -DNO_TAINT_SUPPORT or -DSILENT_NO_TAINT_SUPPORT,
* you get a perl without taint support, but doubtlessly with a lesser
* degree of support. Do not do so unless you know exactly what it means
* technically, have a good reason to do so, and know exactly how the
* perl will be used. perls with -DSILENT_NO_TAINT_SUPPORT are considered
* a potential security risk due to flat out ignoring the security-relevant
* taint flags. This being said, a perl without taint support compiled in
* has marginal run-time performance benefits.
* SILENT_NO_TAINT_SUPPORT implies NO_TAINT_SUPPORT.
* SILENT_NO_TAINT_SUPPORT is the same as NO_TAINT_SUPPORT except it
* silently ignores -t/-T instead of throwing an exception.
*
* DANGER! Using NO_TAINT_SUPPORT or SILENT_NO_TAINT_SUPPORT
* voids your nonexistent warranty!
*/
#if defined(SILENT_NO_TAINT_SUPPORT) && !defined(NO_TAINT_SUPPORT)
# define NO_TAINT_SUPPORT 1
#endif
/* NO_TAINT_SUPPORT can be set to transform virtually all taint-related
* operations into no-ops for a very modest speed-up. Enable only if you
* know what you're doing: tests and CPAN modules' tests are bound to fail.
*/
#ifdef NO_TAINT_SUPPORT
# define TAINT NOOP
# define TAINT_NOT NOOP
# define TAINT_IF(c) NOOP
# define TAINT_ENV() NOOP
# define TAINT_PROPER(s) NOOP
# define TAINT_set(s) NOOP
# define TAINT_get 0
# define TAINTING_get 0
# define TAINTING_set(s) NOOP
# define TAINT_WARN_get 0
# define TAINT_WARN_set(s) NOOP
#else
/* Set to tainted if we are running under tainting mode */
# define TAINT (PL_tainted = PL_tainting)
# define TAINT_NOT (PL_tainted = FALSE) /* Untaint */
# define TAINT_IF(c) if (UNLIKELY(c)) { TAINT; } /* Conditionally taint */
# define TAINT_ENV() if (UNLIKELY(PL_tainting)) { taint_env(); }
/* croak or warn if tainting */
# define TAINT_PROPER(s) if (UNLIKELY(PL_tainting)) { \
taint_proper(NULL, s); \
}
# define TAINT_set(s) (PL_tainted = (s))
# define TAINT_get (cBOOL(UNLIKELY(PL_tainted))) /* Is something tainted? */
# define TAINTING_get (cBOOL(UNLIKELY(PL_tainting))) /* Is taint checking enabled? */
# define TAINTING_set(s) (PL_tainting = (s))
# define TAINT_WARN_get (PL_taint_warn) /* FALSE => tainting violations
are fatal
TRUE => they're just
warnings */
# define TAINT_WARN_set(s) (PL_taint_warn = (s))
#endif
/* flags used internally only within pp_subst and pp_substcont */
#ifdef PERL_CORE
# define SUBST_TAINT_STR 1 /* string tainted */
# define SUBST_TAINT_PAT 2 /* pattern tainted */
# define SUBST_TAINT_REPL 4 /* replacement tainted */
# define SUBST_TAINT_RETAINT 8 /* use re'taint' in scope */
# define SUBST_TAINT_BOOLRET 16 /* return is boolean (don't taint) */
#endif
/* XXX All process group stuff is handled in pp_sys.c. Should these
defines move there? If so, I could simplify this a lot. --AD 9/96.
*/
/* Process group stuff changed from traditional BSD to POSIX.
perlfunc.pod documents the traditional BSD-style syntax, so we'll
try to preserve that, if possible.
*/
#ifdef HAS_SETPGID
# define BSD_SETPGRP(pid, pgrp) setpgid((pid), (pgrp))
#elif defined(HAS_SETPGRP) && defined(USE_BSD_SETPGRP)
# define BSD_SETPGRP(pid, pgrp) setpgrp((pid), (pgrp))
#elif defined(HAS_SETPGRP2)
# define BSD_SETPGRP(pid, pgrp) setpgrp2((pid), (pgrp))
#endif
#if defined(BSD_SETPGRP) && !defined(HAS_SETPGRP)
# define HAS_SETPGRP /* Well, effectively it does . . . */
#endif
/* getpgid isn't POSIX, but at least Solaris and Linux have it, and it makes
our life easier :-) so we'll try it.
*/
#ifdef HAS_GETPGID
# define BSD_GETPGRP(pid) getpgid((pid))
#elif defined(HAS_GETPGRP) && defined(USE_BSD_GETPGRP)
# define BSD_GETPGRP(pid) getpgrp((pid))
#elif defined(HAS_GETPGRP2)
# define BSD_GETPGRP(pid) getpgrp2((pid))
#endif
#if defined(BSD_GETPGRP) && !defined(HAS_GETPGRP)
# define HAS_GETPGRP /* Well, effectively it does . . . */
#endif
/* These are not exact synonyms, since setpgrp() and getpgrp() may
have different behaviors, but perl.h used to define USE_BSDPGRP
(prior to 5.003_05) so some extension might depend on it.
*/
#if defined(USE_BSD_SETPGRP) || defined(USE_BSD_GETPGRP)
# ifndef USE_BSDPGRP
# define USE_BSDPGRP
# endif
#endif
/* HP-UX 10.X CMA (Common Multithreaded Architecture) insists that
pthread.h must be included before all other header files.
*/
#if defined(USE_ITHREADS) && defined(PTHREAD_H_FIRST) && defined(I_PTHREAD)
# include <pthread.h>
#endif
#include <sys/types.h>
/* EVC 4 SDK headers includes a bad definition of MB_CUR_MAX in stdlib.h
which is included from stdarg.h. Bad definition not present in SD 2008
SDK headers. wince.h is not yet included, so we cant fix this from there
since by then MB_CUR_MAX will be defined from stdlib.h.
cewchar.h includes a correct definition of MB_CUR_MAX and it is copied here
since cewchar.h can't be included this early */
#if defined(UNDER_CE) && (_MSC_VER < 1300)
# define MB_CUR_MAX 1uL
#endif
# ifdef I_WCHAR
# include <wchar.h>
# endif
# include <stdarg.h>
#ifdef I_STDINT
# include <stdint.h>
#endif
#include <ctype.h>
#include <float.h>
#include <limits.h>
#ifdef METHOD /* Defined by OSF/1 v3.0 by ctype.h */
#undef METHOD
#endif
#ifdef PERL_MICRO
# define NO_LOCALE
#endif
#ifdef I_LOCALE
# include <locale.h>
#endif
#ifdef I_XLOCALE
# include <xlocale.h>
#endif
/* If not forbidden, we enable locale handling if either 1) the POSIX 2008
* functions are available, or 2) just the setlocale() function. This logic is
* repeated in t/loc_tools.pl and makedef.pl; The three should be kept in
* sync. */
#if ! defined(NO_LOCALE)
# if ! defined(NO_POSIX_2008_LOCALE) \
&& defined(HAS_NEWLOCALE) \
&& defined(HAS_USELOCALE) \
&& defined(HAS_DUPLOCALE) \
&& defined(HAS_FREELOCALE) \
&& defined(LC_ALL_MASK)
/* For simplicity, the code is written to assume that any platform advanced
* enough to have the Posix 2008 locale functions has LC_ALL. The final
* test above makes sure that assumption is valid */
# define HAS_POSIX_2008_LOCALE
# define USE_LOCALE
# elif defined(HAS_SETLOCALE)
# define USE_LOCALE
# endif
#endif
#ifdef USE_LOCALE
# define HAS_SKIP_LOCALE_INIT /* Solely for XS code to test for this
#define */
# if !defined(NO_LOCALE_COLLATE) && defined(LC_COLLATE) \
&& defined(HAS_STRXFRM)
# define USE_LOCALE_COLLATE
# endif
# if !defined(NO_LOCALE_CTYPE) && defined(LC_CTYPE)
# define USE_LOCALE_CTYPE
# endif
# if !defined(NO_LOCALE_NUMERIC) && defined(LC_NUMERIC)
# define USE_LOCALE_NUMERIC
# endif
# if !defined(NO_LOCALE_MESSAGES) && defined(LC_MESSAGES)
# define USE_LOCALE_MESSAGES
# endif
# if !defined(NO_LOCALE_MONETARY) && defined(LC_MONETARY)
# define USE_LOCALE_MONETARY
# endif
# if !defined(NO_LOCALE_TIME) && defined(LC_TIME)
# define USE_LOCALE_TIME
# endif
# if !defined(NO_LOCALE_ADDRESS) && defined(LC_ADDRESS)
# define USE_LOCALE_ADDRESS
# endif
# if !defined(NO_LOCALE_IDENTIFICATION) && defined(LC_IDENTIFICATION)
# define USE_LOCALE_IDENTIFICATION
# endif
# if !defined(NO_LOCALE_MEASUREMENT) && defined(LC_MEASUREMENT)
# define USE_LOCALE_MEASUREMENT
# endif
# if !defined(NO_LOCALE_PAPER) && defined(LC_PAPER)
# define USE_LOCALE_PAPER
# endif
# if !defined(NO_LOCALE_TELEPHONE) && defined(LC_TELEPHONE)
# define USE_LOCALE_TELEPHONE
# endif
/* XXX The next few defines are unfortunately duplicated in makedef.pl, and
* changes here MUST also be made there */
# if ! defined(HAS_SETLOCALE) && defined(HAS_POSIX_2008_LOCALE)
# define USE_POSIX_2008_LOCALE
# ifndef USE_THREAD_SAFE_LOCALE
# define USE_THREAD_SAFE_LOCALE
# endif
/* If compiled with
* -DUSE_THREAD_SAFE_LOCALE, will do so even
* on unthreaded builds */
# elif (defined(USE_ITHREADS) || defined(USE_THREAD_SAFE_LOCALE)) \
&& ( defined(HAS_POSIX_2008_LOCALE) \
|| (defined(WIN32) && defined(_MSC_VER) && _MSC_VER >= 1400)) \
&& ! defined(NO_THREAD_SAFE_LOCALE)
# ifndef USE_THREAD_SAFE_LOCALE
# define USE_THREAD_SAFE_LOCALE
# endif
# ifdef HAS_POSIX_2008_LOCALE
# define USE_POSIX_2008_LOCALE
# endif
# endif
#endif
/* Microsoft documentation reads in the change log for VS 2015:
* "The localeconv function declared in locale.h now works correctly when
* per-thread locale is enabled. In previous versions of the library, this
* function would return the lconv data for the global locale, not the
* thread's locale."
*/
#if defined(WIN32) && defined(USE_THREAD_SAFE_LOCALE) && _MSC_VER < 1900
# define TS_W32_BROKEN_LOCALECONV
#endif
#include <setjmp.h>
#ifdef I_SYS_PARAM
# ifdef PARAM_NEEDS_TYPES
# include <sys/types.h>
# endif
# include <sys/param.h>
#endif
/* On BSD-derived systems, <sys/param.h> defines BSD to a year-month
value something like 199306. This may be useful if no more-specific
feature test is available.
*/
#if defined(BSD)
# ifndef BSDish
# define BSDish
# endif
#endif
/* Use all the "standard" definitions */
#include <stdlib.h>
/* If this causes problems, set i_unistd=undef in the hint file. */
#ifdef I_UNISTD
# if defined(__amigaos4__)
# ifdef I_NETINET_IN
# include <netinet/in.h>
# endif
# endif
# include <unistd.h>
# if defined(__amigaos4__)
/* Under AmigaOS 4 newlib.library provides an environ. However using
* it doesn't give us enough control over inheritance of variables by
* subshells etc. so replace with custom version based on abc-shell
* code. */
extern char **myenviron;
# undef environ
# define environ myenviron
# endif
#endif
/* for WCOREDUMP */
#ifdef I_SYS_WAIT
# include <sys/wait.h>
#endif
#ifdef __SYMBIAN32__
# undef _SC_ARG_MAX /* Symbian has _SC_ARG_MAX but no sysconf() */
#endif
#if defined(HAS_SYSCALL) && !defined(HAS_SYSCALL_PROTO)
EXTERN_C int syscall(int, ...);
#endif
#if defined(HAS_USLEEP) && !defined(HAS_USLEEP_PROTO)
EXTERN_C int usleep(unsigned int);
#endif
/* macros for correct constant construction. These are in C99 <stdint.h>
* (so they will not be available in strict C89 mode), but they are nice, so
* let's define them if necessary. */
#ifndef UINT16_C
# if INTSIZE >= 2
# define UINT16_C(x) ((U16_TYPE)x##U)
# else
# define UINT16_C(x) ((U16_TYPE)x##UL)
# endif
#endif
#ifndef UINT32_C
# if INTSIZE >= 4
# define UINT32_C(x) ((U32_TYPE)x##U)
# else
# define UINT32_C(x) ((U32_TYPE)x##UL)
# endif
#endif
#ifdef I_STDINT
typedef intmax_t PERL_INTMAX_T;
typedef uintmax_t PERL_UINTMAX_T;
#endif
/* N.B. We use QUADKIND here instead of HAS_QUAD here, because that doesn't
* actually mean what it has always been documented to mean (see RT #119753)
* and is explicitly turned off outside of core with dire warnings about
* removing the undef. */
#if defined(QUADKIND)
# undef PeRl_INT64_C
# undef PeRl_UINT64_C
/* Prefer the native integer types (int and long) over long long
* (which is not C89) and Win32-specific __int64. */
# if QUADKIND == QUAD_IS_INT && INTSIZE == 8
# define PeRl_INT64_C(c) (c)
# define PeRl_UINT64_C(c) CAT2(c,U)
# endif
# if QUADKIND == QUAD_IS_LONG && LONGSIZE == 8
# define PeRl_INT64_C(c) CAT2(c,L)
# define PeRl_UINT64_C(c) CAT2(c,UL)
# endif
# if QUADKIND == QUAD_IS_LONG_LONG && defined(HAS_LONG_LONG)
# define PeRl_INT64_C(c) CAT2(c,LL)
# define PeRl_UINT64_C(c) CAT2(c,ULL)
# endif
# if QUADKIND == QUAD_IS___INT64
# define PeRl_INT64_C(c) CAT2(c,I64)
# define PeRl_UINT64_C(c) CAT2(c,UI64)
# endif
# ifndef PeRl_INT64_C
# define PeRl_INT64_C(c) ((I64)(c)) /* last resort */
# define PeRl_UINT64_C(c) ((U64TYPE)(c))
# endif
/* In OS X the INT64_C/UINT64_C are defined with LL/ULL, which will
* not fly with C89-pedantic gcc, so let's undefine them first so that
* we can redefine them with our native integer preferring versions. */
# if defined(PERL_DARWIN) && defined(PERL_GCC_PEDANTIC)
# undef INT64_C
# undef UINT64_C
# endif
# ifndef INT64_C
# define INT64_C(c) PeRl_INT64_C(c)
# endif
# ifndef UINT64_C
# define UINT64_C(c) PeRl_UINT64_C(c)
# endif
# ifndef I_STDINT
typedef I64TYPE PERL_INTMAX_T;
typedef U64TYPE PERL_UINTMAX_T;
# endif
# ifndef INTMAX_C
# define INTMAX_C(c) INT64_C(c)
# endif
# ifndef UINTMAX_C
# define UINTMAX_C(c) UINT64_C(c)
# endif
#else /* below QUADKIND is undefined */
/* Perl doesn't work on 16 bit systems, so must be 32 bit */
# ifndef I_STDINT
typedef I32TYPE PERL_INTMAX_T;
typedef U32TYPE PERL_UINTMAX_T;
# endif
# ifndef INTMAX_C
# define INTMAX_C(c) INT32_C(c)
# endif
# ifndef UINTMAX_C
# define UINTMAX_C(c) UINT32_C(c)
# endif
#endif /* no QUADKIND */
#ifdef PERL_CORE
/* byte-swapping functions for big-/little-endian conversion */
# define _swab_16_(x) ((U16)( \
(((U16)(x) & UINT16_C(0x00ff)) << 8) | \
(((U16)(x) & UINT16_C(0xff00)) >> 8) ))
# define _swab_32_(x) ((U32)( \
(((U32)(x) & UINT32_C(0x000000ff)) << 24) | \
(((U32)(x) & UINT32_C(0x0000ff00)) << 8) | \
(((U32)(x) & UINT32_C(0x00ff0000)) >> 8) | \
(((U32)(x) & UINT32_C(0xff000000)) >> 24) ))
# ifdef HAS_QUAD
# define _swab_64_(x) ((U64)( \
(((U64)(x) & UINT64_C(0x00000000000000ff)) << 56) | \
(((U64)(x) & UINT64_C(0x000000000000ff00)) << 40) | \
(((U64)(x) & UINT64_C(0x0000000000ff0000)) << 24) | \
(((U64)(x) & UINT64_C(0x00000000ff000000)) << 8) | \
(((U64)(x) & UINT64_C(0x000000ff00000000)) >> 8) | \
(((U64)(x) & UINT64_C(0x0000ff0000000000)) >> 24) | \
(((U64)(x) & UINT64_C(0x00ff000000000000)) >> 40) | \
(((U64)(x) & UINT64_C(0xff00000000000000)) >> 56) ))
# endif
/* The old value was hard coded at 1008. (4096-16) seems to be a bit faster,
at least on FreeBSD. YMMV, so experiment. */
#ifndef PERL_ARENA_SIZE
#define PERL_ARENA_SIZE 4080
#endif
/* Maximum level of recursion */
#ifndef PERL_SUB_DEPTH_WARN
#define PERL_SUB_DEPTH_WARN 100
#endif
#endif /* PERL_CORE */
/* Maximum number of args that may be passed to an OP_MULTICONCAT op.
* It determines the size of local arrays in S_maybe_multiconcat() and
* pp_multiconcat().
*/
#define PERL_MULTICONCAT_MAXARG 64
/* The indexes of fields of a multiconcat aux struct.
* The fixed fields are followed by nargs+1 const segment lengths,
* and if utf8 and non-utf8 differ, a second nargs+1 set for utf8.
*/
#define PERL_MULTICONCAT_IX_NARGS 0 /* number of arguments */
#define PERL_MULTICONCAT_IX_PLAIN_PV 1 /* non-utf8 constant string */
#define PERL_MULTICONCAT_IX_PLAIN_LEN 2 /* non-utf8 constant string length */
#define PERL_MULTICONCAT_IX_UTF8_PV 3 /* utf8 constant string */
#define PERL_MULTICONCAT_IX_UTF8_LEN 4 /* utf8 constant string length */
#define PERL_MULTICONCAT_IX_LENGTHS 5 /* first of nargs+1 const segment lens */
#define PERL_MULTICONCAT_HEADER_SIZE 5 /* The number of fields of a
multiconcat header */
/* We no longer default to creating a new SV for GvSV.
Do this before embed. */
#ifndef PERL_CREATE_GVSV
# ifndef PERL_DONT_CREATE_GVSV
# define PERL_DONT_CREATE_GVSV
# endif
#endif
#if !defined(HAS_WAITPID) && !defined(HAS_WAIT4) || defined(HAS_WAITPID_RUNTIME)
#define PERL_USES_PL_PIDSTATUS
#endif
#if !defined(OS2) && !defined(WIN32) && !defined(DJGPP) && !defined(__SYMBIAN32__)
#define PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
#endif
#define MEM_SIZE Size_t
/* Round all values passed to malloc up, by default to a multiple of
sizeof(size_t)
*/
#ifndef PERL_STRLEN_ROUNDUP_QUANTUM
#define PERL_STRLEN_ROUNDUP_QUANTUM Size_t_size
#endif
/* sv_grow() will expand strings by at least a certain percentage of
the previously *used* length to avoid excessive calls to realloc().
The default is 25% of the current length.
*/
#ifndef PERL_STRLEN_EXPAND_SHIFT
# define PERL_STRLEN_EXPAND_SHIFT 2
#endif
/* This use of offsetof() requires /Zc:offsetof- for VS2017 (and presumably
* onwards) when building Socket.xs, but we can just use a different definition
* for STRUCT_OFFSET instead. */
#if defined(WIN32) && defined(_MSC_VER) && _MSC_VER >= 1910
# define STRUCT_OFFSET(s,m) (Size_t)(&(((s *)0)->m))
#else
# include <stddef.h>
# define STRUCT_OFFSET(s,m) offsetof(s,m)
#endif
/* ptrdiff_t is C11, so undef it under pedantic builds. (Actually it is
* in C89, but apparently there are platforms where it doesn't exist. See
* thread beginning at http://nntp.perl.org/group/perl.perl5.porters/251541.)
* */
#ifdef PERL_GCC_PEDANTIC
# undef HAS_PTRDIFF_T
#endif
#ifdef HAS_PTRDIFF_T
# define Ptrdiff_t ptrdiff_t
#else
# define Ptrdiff_t SSize_t
#endif
#ifndef __SYMBIAN32__
# include <string.h>
#endif
/* This comes after <stdlib.h> so we don't try to change the standard
* library prototypes; we'll use our own in proto.h instead. */
#ifdef MYMALLOC
# ifdef PERL_POLLUTE_MALLOC
# ifndef PERL_EXTMALLOC_DEF
# define Perl_malloc malloc
# define Perl_calloc calloc
# define Perl_realloc realloc
# define Perl_mfree free
# endif
# else
# define EMBEDMYMALLOC /* for compatibility */
# endif
# define safemalloc Perl_malloc
# define safecalloc Perl_calloc
# define saferealloc Perl_realloc
# define safefree Perl_mfree
# define CHECK_MALLOC_TOO_LATE_FOR_(code) STMT_START { \
if (!TAINTING_get && MallocCfg_ptr[MallocCfg_cfg_env_read]) \
code; \
} STMT_END
# define CHECK_MALLOC_TOO_LATE_FOR(ch) \
CHECK_MALLOC_TOO_LATE_FOR_(MALLOC_TOO_LATE_FOR(ch))
# define panic_write2(s) write(2, s, strlen(s))
# define CHECK_MALLOC_TAINT(newval) \
CHECK_MALLOC_TOO_LATE_FOR_( \
if (newval) { \
PERL_UNUSED_RESULT(panic_write2("panic: tainting with $ENV{PERL_MALLOC_OPT}\n"));\
exit(1); })
# define MALLOC_CHECK_TAINT(argc,argv,env) STMT_START { \
if (doing_taint(argc,argv,env)) { \
MallocCfg_ptr[MallocCfg_skip_cfg_env] = 1; \
}} STMT_END;
#else /* MYMALLOC */
# define safemalloc safesysmalloc
# define safecalloc safesyscalloc
# define saferealloc safesysrealloc
# define safefree safesysfree
# define CHECK_MALLOC_TOO_LATE_FOR(ch) ((void)0)
# define CHECK_MALLOC_TAINT(newval) ((void)0)
# define MALLOC_CHECK_TAINT(argc,argv,env)
#endif /* MYMALLOC */
/* diag_listed_as: "-T" is on the #! line, it must also be used on the command line */
#define TOO_LATE_FOR_(ch,what) Perl_croak(aTHX_ "\"-%c\" is on the #! line, it must also be used on the command line%s", (char)(ch), what)
#define TOO_LATE_FOR(ch) TOO_LATE_FOR_(ch, "")
#define MALLOC_TOO_LATE_FOR(ch) TOO_LATE_FOR_(ch, " with $ENV{PERL_MALLOC_OPT}")
#define MALLOC_CHECK_TAINT2(argc,argv) MALLOC_CHECK_TAINT(argc,argv,NULL)
#ifndef memzero
# define memzero(d,l) memset(d,0,l)
#endif
#ifdef I_NETINET_IN
# include <netinet/in.h>
#endif
#ifdef I_ARPA_INET
# include <arpa/inet.h>
#endif
#ifdef I_SYS_STAT
# include <sys/stat.h>
#endif
/* Microsoft VC's sys/stat.h defines all S_Ixxx macros except S_IFIFO.
This definition should ideally go into win32/win32.h, but S_IFIFO is
used later here in perl.h before win32/win32.h is being included. */
#if !defined(S_IFIFO) && defined(_S_IFIFO)
# define S_IFIFO _S_IFIFO
#endif
/* The stat macros for Unisoft System V/88 (and derivatives
like UTekV) are broken, sometimes giving false positives. Undefine
them here and let the code below set them to proper values.
The ghs macro stands for GreenHills Software C-1.8.5 which
is the C compiler for sysV88 and the various derivatives.
This header file bug is corrected in gcc-2.5.8 and later versions.
--<NAME> (<EMAIL>) 10/3/94. */
#if defined(m88k) && defined(ghs)
# undef S_ISDIR
# undef S_ISCHR
# undef S_ISBLK
# undef S_ISREG
# undef S_ISFIFO
# undef S_ISLNK
#endif
#include <time.h>
#ifdef I_SYS_TIME
# ifdef I_SYS_TIME_KERNEL
# define KERNEL
# endif
# include <sys/time.h>
# ifdef I_SYS_TIME_KERNEL
# undef KERNEL
# endif
#endif
#if defined(HAS_TIMES) && defined(I_SYS_TIMES)
# include <sys/times.h>
#endif
#include <errno.h>
#if defined(WIN32) && defined(PERL_IMPLICIT_SYS)
# define WIN32SCK_IS_STDSCK /* don't pull in custom wsock layer */
#endif
#if defined(HAS_SOCKET) && !defined(WIN32) /* WIN32 handles sockets via win32.h */
# include <sys/socket.h>
# if defined(USE_SOCKS) && defined(I_SOCKS)
# if !defined(INCLUDE_PROTOTYPES)
# define INCLUDE_PROTOTYPES /* for <socks.h> */
# define PERL_SOCKS_NEED_PROTOTYPES
# endif
# include <socks.h>
# ifdef PERL_SOCKS_NEED_PROTOTYPES /* keep cpp space clean */
# undef INCLUDE_PROTOTYPES
# undef PERL_SOCKS_NEED_PROTOTYPES
# endif
# endif
# ifdef I_NETDB
# ifdef NETWARE
# include<stdio.h>
# endif
# include <netdb.h>
# endif
# ifndef ENOTSOCK
# ifdef I_NET_ERRNO
# include <net/errno.h>
# endif
# endif
#endif
/* sockatmark() is so new (2001) that many places might have it hidden
* behind some -D_BLAH_BLAH_SOURCE guard. The __THROW magic is required
* e.g. in Gentoo, see http://bugs.gentoo.org/show_bug.cgi?id=12605 */
#if defined(HAS_SOCKATMARK) && !defined(HAS_SOCKATMARK_PROTO)
# if defined(__THROW) && defined(__GLIBC__)
int sockatmark(int) __THROW;
# else
int sockatmark(int);
# endif
#endif
#if defined(__osf__) && defined(__cplusplus) && !defined(_XOPEN_SOURCE_EXTENDED) /* Tru64 "cxx" (C++), see hints/dec_osf.sh for why the _XOPEN_SOURCE_EXTENDED cannot be defined. */
EXTERN_C int fchdir(int);
EXTERN_C int flock(int, int);
EXTERN_C int fseeko(FILE *, off_t, int);
EXTERN_C off_t ftello(FILE *);
#endif
#if defined(__SUNPRO_CC) /* SUNWspro CC (C++) */
EXTERN_C char *crypt(const char *, const char *);
#endif
#if defined(__cplusplus) && defined(__CYGWIN__)
EXTERN_C char *crypt(const char *, const char *);
#endif
/*
=head1 Errno
=for apidoc m|void|SETERRNO|int errcode|int vmserrcode
Set C<errno>, and on VMS set C<vaxc$errno>.
=for apidoc mn|void|dSAVEDERRNO
Declare variables needed to save C<errno> and any operating system
specific error number.
=for apidoc mn|void|dSAVE_ERRNO
Declare variables needed to save C<errno> and any operating system
specific error number, and save them for optional later restoration
by C<RESTORE_ERRNO>.
=for apidoc mn|void|SAVE_ERRNO
Save C<errno> and any operating system specific error number for
optional later restoration by C<RESTORE_ERRNO>. Requires
C<dSAVEDERRNO> or C<dSAVE_ERRNO> in scope.
=for apidoc mn|void|RESTORE_ERRNO
Restore C<errno> and any operating system specific error number that
was saved by C<dSAVE_ERRNO> or C<RESTORE_ERRNO>.
=cut
*/
#ifdef SETERRNO
# undef SETERRNO /* SOCKS might have defined this */
#endif
#ifdef VMS
# define SETERRNO(errcode,vmserrcode) \
STMT_START { \
set_errno(errcode); \
set_vaxc_errno(vmserrcode); \
} STMT_END
# define dSAVEDERRNO int saved_errno; unsigned saved_vms_errno
# define dSAVE_ERRNO int saved_errno = errno; unsigned saved_vms_errno = vaxc$errno
# define SAVE_ERRNO ( saved_errno = errno, saved_vms_errno = vaxc$errno )
# define RESTORE_ERRNO SETERRNO(saved_errno, saved_vms_errno)
# define LIB_INVARG LIB$_INVARG
# define RMS_DIR RMS$_DIR
# define RMS_FAC RMS$_FAC
# define RMS_FEX RMS$_FEX
# define RMS_FNF RMS$_FNF
# define RMS_IFI RMS$_IFI
# define RMS_ISI RMS$_ISI
# define RMS_PRV RMS$_PRV
# define SS_ACCVIO SS$_ACCVIO
# define SS_DEVOFFLINE SS$_DEVOFFLINE
# define SS_IVCHAN SS$_IVCHAN
# define SS_NORMAL SS$_NORMAL
# define SS_NOPRIV SS$_NOPRIV
# define SS_BUFFEROVF SS$_BUFFEROVF
#else
# define LIB_INVARG 0
# define RMS_DIR 0
# define RMS_FAC 0
# define RMS_FEX 0
# define RMS_FNF 0
# define RMS_IFI 0
# define RMS_ISI 0
# define RMS_PRV 0
# define SS_ACCVIO 0
# define SS_DEVOFFLINE 0
# define SS_IVCHAN 0
# define SS_NORMAL 0
# define SS_NOPRIV 0
# define SS_BUFFEROVF 0
#endif
#ifdef WIN32
# define dSAVEDERRNO int saved_errno; DWORD saved_win32_errno
# define dSAVE_ERRNO int saved_errno = errno; DWORD saved_win32_errno = GetLastError()
# define SAVE_ERRNO ( saved_errno = errno, saved_win32_errno = GetLastError() )
# define RESTORE_ERRNO ( errno = saved_errno, SetLastError(saved_win32_errno) )
#endif
#ifdef OS2
# define dSAVEDERRNO int saved_errno; unsigned long saved_os2_errno
# define dSAVE_ERRNO int saved_errno = errno; unsigned long saved_os2_errno = Perl_rc
# define SAVE_ERRNO ( saved_errno = errno, saved_os2_errno = Perl_rc )
# define RESTORE_ERRNO ( errno = saved_errno, Perl_rc = saved_os2_errno )
#endif
#ifndef SETERRNO
# define SETERRNO(errcode,vmserrcode) (errno = (errcode))
#endif
#ifndef dSAVEDERRNO
# define dSAVEDERRNO int saved_errno
# define dSAVE_ERRNO int saved_errno = errno
# define SAVE_ERRNO (saved_errno = errno)
# define RESTORE_ERRNO (errno = saved_errno)
#endif
/*
=head1 Warning and Dieing
=for apidoc Amn|SV *|ERRSV
Returns the SV for C<$@>, creating it if needed.
=for apidoc Am|void|CLEAR_ERRSV
Clear the contents of C<$@>, setting it to the empty string.
This replaces any read-only SV with a fresh SV and removes any magic.
=for apidoc Am|void|SANE_ERRSV
Clean up ERRSV so we can safely set it.
This replaces any read-only SV with a fresh writable copy and removes
any magic.
=cut
*/
#define ERRSV GvSVn(PL_errgv)
/* contains inlined gv_add_by_type */
#define CLEAR_ERRSV() STMT_START { \
SV ** const svp = &GvSV(PL_errgv); \
if (!*svp) { \
*svp = newSVpvs(""); \
} else if (SvREADONLY(*svp)) { \
SvREFCNT_dec_NN(*svp); \
*svp = newSVpvs(""); \
} else { \
SV *const errsv = *svp; \
SvPVCLEAR(errsv); \
SvPOK_only(errsv); \
if (SvMAGICAL(errsv)) { \
mg_free(errsv); \
} \
} \
} STMT_END
/* contains inlined gv_add_by_type */
#define SANE_ERRSV() STMT_START { \
SV ** const svp = &GvSV(PL_errgv); \
if (!*svp) { \
*svp = newSVpvs(""); \
} else if (SvREADONLY(*svp)) { \
SV *dupsv = newSVsv(*svp); \
SvREFCNT_dec_NN(*svp); \
*svp = dupsv; \
} else { \
SV *const errsv = *svp; \
if (SvMAGICAL(errsv)) { \
mg_free(errsv); \
} \
} \
} STMT_END
#ifdef PERL_CORE
# define DEFSV (0 + GvSVn(PL_defgv))
# define DEFSV_set(sv) \
(SvREFCNT_dec(GvSV(PL_defgv)), GvSV(PL_defgv) = SvREFCNT_inc(sv))
# define SAVE_DEFSV \
( \
save_gp(PL_defgv, 0), \
GvINTRO_off(PL_defgv), \
SAVEGENERICSV(GvSV(PL_defgv)), \
GvSV(PL_defgv) = NULL \
)
#else
# define DEFSV GvSVn(PL_defgv)
# define DEFSV_set(sv) (GvSV(PL_defgv) = (sv))
# define SAVE_DEFSV SAVESPTR(GvSV(PL_defgv))
#endif
#ifndef errno
extern int errno; /* ANSI allows errno to be an lvalue expr.
* For example in multithreaded environments
* something like this might happen:
* extern int *_errno(void);
* #define errno (*_errno()) */
#endif
#define UNKNOWN_ERRNO_MSG "(unknown)"
#ifdef VMS
#define Strerror(e) strerror((e), vaxc$errno)
#else
#define Strerror(e) strerror(e)
#endif
#ifdef I_SYS_IOCTL
# ifndef _IOCTL_
# include <sys/ioctl.h>
# endif
#endif
#if defined(mc300) || defined(mc500) || defined(mc700) || defined(mc6000)
# ifdef HAS_SOCKETPAIR
# undef HAS_SOCKETPAIR
# endif
# ifdef I_NDBM
# undef I_NDBM
# endif
#endif
#ifndef HAS_SOCKETPAIR
# ifdef HAS_SOCKET
# define socketpair Perl_my_socketpair
# endif
#endif
#if INTSIZE == 2
# define htoni htons
# define ntohi ntohs
#else
# define htoni htonl
# define ntohi ntohl
#endif
/* Configure already sets Direntry_t */
#if defined(I_DIRENT)
# include <dirent.h>
#elif defined(I_SYS_NDIR)
# include <sys/ndir.h>
#elif defined(I_SYS_DIR)
# include <sys/dir.h>
#endif
/*
* The following gobbledygook brought to you on behalf of __STDC__.
* (I could just use #ifndef __STDC__, but this is more bulletproof
* in the face of half-implementations.)
*/
#if defined(I_SYSMODE)
#include <sys/mode.h>
#endif
#ifndef S_IFMT
# ifdef _S_IFMT
# define S_IFMT _S_IFMT
# else
# define S_IFMT 0170000
# endif
#endif
#ifndef S_ISDIR
# define S_ISDIR(m) ((m & S_IFMT) == S_IFDIR)
#endif
#ifndef S_ISCHR
# define S_ISCHR(m) ((m & S_IFMT) == S_IFCHR)
#endif
#ifndef S_ISBLK
# ifdef S_IFBLK
# define S_ISBLK(m) ((m & S_IFMT) == S_IFBLK)
# else
# define S_ISBLK(m) (0)
# endif
#endif
#ifndef S_ISREG
# define S_ISREG(m) ((m & S_IFMT) == S_IFREG)
#endif
#ifndef S_ISFIFO
# ifdef S_IFIFO
# define S_ISFIFO(m) ((m & S_IFMT) == S_IFIFO)
# else
# define S_ISFIFO(m) (0)
# endif
#endif
#ifndef S_ISLNK
# ifdef _S_ISLNK
# define S_ISLNK(m) _S_ISLNK(m)
# elif defined(_S_IFLNK)
# define S_ISLNK(m) ((m & S_IFMT) == _S_IFLNK)
# elif defined(S_IFLNK)
# define S_ISLNK(m) ((m & S_IFMT) == S_IFLNK)
# else
# define S_ISLNK(m) (0)
# endif
#endif
#ifndef S_ISSOCK
# ifdef _S_ISSOCK
# define S_ISSOCK(m) _S_ISSOCK(m)
# elif defined(_S_IFSOCK)
# define S_ISSOCK(m) ((m & S_IFMT) == _S_IFSOCK)
# elif defined(S_IFSOCK)
# define S_ISSOCK(m) ((m & S_IFMT) == S_IFSOCK)
# else
# define S_ISSOCK(m) (0)
# endif
#endif
#ifndef S_IRUSR
# ifdef S_IREAD
# define S_IRUSR S_IREAD
# define S_IWUSR S_IWRITE
# define S_IXUSR S_IEXEC
# else
# define S_IRUSR 0400
# define S_IWUSR 0200
# define S_IXUSR 0100
# endif
#endif
#ifndef S_IRGRP
# ifdef S_IRUSR
# define S_IRGRP (S_IRUSR>>3)
# define S_IWGRP (S_IWUSR>>3)
# define S_IXGRP (S_IXUSR>>3)
# else
# define S_IRGRP 0040
# define S_IWGRP 0020
# define S_IXGRP 0010
# endif
#endif
#ifndef S_IROTH
# ifdef S_IRUSR
# define S_IROTH (S_IRUSR>>6)
# define S_IWOTH (S_IWUSR>>6)
# define S_IXOTH (S_IXUSR>>6)
# else
# define S_IROTH 0040
# define S_IWOTH 0020
# define S_IXOTH 0010
# endif
#endif
#ifndef S_ISUID
# define S_ISUID 04000
#endif
#ifndef S_ISGID
# define S_ISGID 02000
#endif
#ifndef S_IRWXU
# define S_IRWXU (S_IRUSR|S_IWUSR|S_IXUSR)
#endif
#ifndef S_IRWXG
# define S_IRWXG (S_IRGRP|S_IWGRP|S_IXGRP)
#endif
#ifndef S_IRWXO
# define S_IRWXO (S_IROTH|S_IWOTH|S_IXOTH)
#endif
/* Haiku R1 seems to define S_IREAD and S_IWRITE in <posix/fcntl.h>
* which would get included through <sys/file.h >, but that is 3000
* lines in the future. --jhi */
#if !defined(S_IREAD) && !defined(__HAIKU__)
# define S_IREAD S_IRUSR
#endif
#if !defined(S_IWRITE) && !defined(__HAIKU__)
# define S_IWRITE S_IWUSR
#endif
#ifndef S_IEXEC
# define S_IEXEC S_IXUSR
#endif
#if defined(cray) || defined(gould) || defined(i860) || defined(pyr)
# define SLOPPYDIVIDE
#endif
#ifdef UV
#undef UV
#endif
/* This used to be conditionally defined based on whether we had a sprintf()
* that correctly returns the string length (as required by C89), but we no
* longer need that. XS modules can (and do) use this name, so it must remain
* a part of the API that's visible to modules.
=head1 Miscellaneous Functions
=for apidoc ATmD|int|my_sprintf|NN char *buffer|NN const char *pat|...
Do NOT use this due to the possibility of overflowing C<buffer>. Instead use
my_snprintf()
=cut
*/
#define my_sprintf sprintf
/*
* If we have v?snprintf() and the C99 variadic macros, we can just
* use just the v?snprintf(). It is nice to try to trap the buffer
* overflow, however, so if we are DEBUGGING, and we cannot use the
* gcc statement expressions, then use the function wrappers which try
* to trap the overflow. If we can use the gcc statement expressions,
* we can try that even with the version that uses the C99 variadic
* macros.
*/
/* Note that we do not check against snprintf()/vsnprintf() returning
* negative values because that is non-standard behaviour and we use
* snprintf/vsnprintf only iff HAS_VSNPRINTF has been defined, and
* that should be true only if the snprintf()/vsnprintf() are true
* to the standard. */
#define PERL_SNPRINTF_CHECK(len, max, api) STMT_START { if ((max) > 0 && (Size_t)len > (max)) Perl_croak_nocontext("panic: %s buffer overflow", STRINGIFY(api)); } STMT_END
#ifdef USE_QUADMATH
# define my_snprintf Perl_my_snprintf
# define PERL_MY_SNPRINTF_GUARDED
#elif defined(HAS_SNPRINTF) && defined(HAS_C99_VARIADIC_MACROS) && !(defined(DEBUGGING) && !defined(PERL_USE_GCC_BRACE_GROUPS)) && !defined(PERL_GCC_PEDANTIC)
# ifdef PERL_USE_GCC_BRACE_GROUPS
# define my_snprintf(buffer, max, ...) ({ int len = snprintf(buffer, max, __VA_ARGS__); PERL_SNPRINTF_CHECK(len, max, snprintf); len; })
# define PERL_MY_SNPRINTF_GUARDED
# else
# define my_snprintf(buffer, max, ...) snprintf(buffer, max, __VA_ARGS__)
# endif
#else
# define my_snprintf Perl_my_snprintf
# define PERL_MY_SNPRINTF_GUARDED
#endif
/* There is no quadmath_vsnprintf, and therefore my_vsnprintf()
* dies if called under USE_QUADMATH. */
#if defined(HAS_VSNPRINTF) && defined(HAS_C99_VARIADIC_MACROS) && !(defined(DEBUGGING) && !defined(PERL_USE_GCC_BRACE_GROUPS)) && !defined(PERL_GCC_PEDANTIC)
# ifdef PERL_USE_GCC_BRACE_GROUPS
# define my_vsnprintf(buffer, max, ...) ({ int len = vsnprintf(buffer, max, __VA_ARGS__); PERL_SNPRINTF_CHECK(len, max, vsnprintf); len; })
# define PERL_MY_VSNPRINTF_GUARDED
# else
# define my_vsnprintf(buffer, max, ...) vsnprintf(buffer, max, __VA_ARGS__)
# endif
#else
# define my_vsnprintf Perl_my_vsnprintf
# define PERL_MY_VSNPRINTF_GUARDED
#endif
/* You will definitely need to use the PERL_MY_SNPRINTF_POST_GUARD()
* or PERL_MY_VSNPRINTF_POST_GUARD() if you otherwise decide to ignore
* the result of my_snprintf() or my_vsnprintf(). (No, you should not
* completely ignore it: otherwise you cannot know whether your output
* was too long.)
*
* int len = my_sprintf(buf, max, ...);
* PERL_MY_SNPRINTF_POST_GUARD(len, max);
*
* The trick is that in certain platforms [a] the my_sprintf() already
* contains the sanity check, while in certain platforms [b] it needs
* to be done as a separate step. The POST_GUARD is that step-- in [a]
* platforms the POST_GUARD actually does nothing since the check has
* already been done. Watch out for the max being the same in both calls.
*
* If you actually use the snprintf/vsnprintf return value already,
* you assumedly are checking its validity somehow. But you can
* insert the POST_GUARD() also in that case. */
#ifndef PERL_MY_SNPRINTF_GUARDED
# define PERL_MY_SNPRINTF_POST_GUARD(len, max) PERL_SNPRINTF_CHECK(len, max, snprintf)
#else
# define PERL_MY_SNPRINTF_POST_GUARD(len, max) PERL_UNUSED_VAR(len)
#endif
#ifndef PERL_MY_VSNPRINTF_GUARDED
# define PERL_MY_VSNPRINTF_POST_GUARD(len, max) PERL_SNPRINTF_CHECK(len, max, vsnprintf)
#else
# define PERL_MY_VSNPRINTF_POST_GUARD(len, max) PERL_UNUSED_VAR(len)
#endif
#ifdef HAS_STRLCAT
# define my_strlcat strlcat
#endif
#if defined(PERL_CORE) || defined(PERL_EXT)
# ifdef HAS_MEMRCHR
# define my_memrchr memrchr
# else
# define my_memrchr S_my_memrchr
# endif
#endif
#ifdef HAS_STRLCPY
# define my_strlcpy strlcpy
#endif
#ifdef HAS_STRNLEN
# define my_strnlen strnlen
#endif
/*
The IV type is supposed to be long enough to hold any integral
value or a pointer.
--<NAME> August 1996
*/
typedef IVTYPE IV;
typedef UVTYPE UV;
#if defined(USE_64_BIT_INT) && defined(HAS_QUAD)
# if QUADKIND == QUAD_IS_INT64_T && defined(INT64_MAX)
# define IV_MAX ((IV)INT64_MAX)
# define IV_MIN ((IV)INT64_MIN)
# define UV_MAX ((UV)UINT64_MAX)
# ifndef UINT64_MIN
# define UINT64_MIN 0
# endif
# define UV_MIN ((UV)UINT64_MIN)
# else
# define IV_MAX PERL_QUAD_MAX
# define IV_MIN PERL_QUAD_MIN
# define UV_MAX PERL_UQUAD_MAX
# define UV_MIN PERL_UQUAD_MIN
# endif
# define IV_IS_QUAD
# define UV_IS_QUAD
#else
# if defined(INT32_MAX) && IVSIZE == 4
# define IV_MAX ((IV)INT32_MAX)
# define IV_MIN ((IV)INT32_MIN)
# ifndef UINT32_MAX_BROKEN /* e.g. HP-UX with gcc messes this up */
# define UV_MAX ((UV)UINT32_MAX)
# else
# define UV_MAX ((UV)4294967295U)
# endif
# ifndef UINT32_MIN
# define UINT32_MIN 0
# endif
# define UV_MIN ((UV)UINT32_MIN)
# else
# define IV_MAX PERL_LONG_MAX
# define IV_MIN PERL_LONG_MIN
# define UV_MAX PERL_ULONG_MAX
# define UV_MIN PERL_ULONG_MIN
# endif
# if IVSIZE == 8
# define IV_IS_QUAD
# define UV_IS_QUAD
# ifndef HAS_QUAD
# define HAS_QUAD
# endif
# else
# undef IV_IS_QUAD
# undef UV_IS_QUAD
#if !defined(PERL_CORE)
/* We think that removing this decade-old undef this will cause too much
breakage on CPAN for too little gain. (See RT #119753)
However, we do need HAS_QUAD in the core for use by the drand48 code. */
# undef HAS_QUAD
#endif
# endif
#endif
#define Size_t_MAX (~(Size_t)0)
#define SSize_t_MAX (SSize_t)(~(Size_t)0 >> 1)
#define IV_DIG (BIT_DIGITS(IVSIZE * 8))
#define UV_DIG (BIT_DIGITS(UVSIZE * 8))
#ifndef NO_PERL_PRESERVE_IVUV
#define PERL_PRESERVE_IVUV /* We like our integers to stay integers. */
#endif
/*
* The macros INT2PTR and NUM2PTR are (despite their names)
* bi-directional: they will convert int/float to or from pointers.
* However the conversion to int/float are named explicitly:
* PTR2IV, PTR2UV, PTR2NV.
*
* For int conversions we do not need two casts if pointers are
* the same size as IV and UV. Otherwise we need an explicit
* cast (PTRV) to avoid compiler warnings.
*/
#if (IVSIZE == PTRSIZE) && (UVSIZE == PTRSIZE)
# define PTRV UV
# define INT2PTR(any,d) (any)(d)
#elif PTRSIZE == LONGSIZE
# define PTRV unsigned long
# define PTR2ul(p) (unsigned long)(p)
#else
# define PTRV unsigned
#endif
#ifndef INT2PTR
# define INT2PTR(any,d) (any)(PTRV)(d)
#endif
#ifndef PTR2ul
# define PTR2ul(p) INT2PTR(unsigned long,p)
#endif
#define NUM2PTR(any,d) (any)(PTRV)(d)
#define PTR2IV(p) INT2PTR(IV,p)
#define PTR2UV(p) INT2PTR(UV,p)
#define PTR2NV(p) NUM2PTR(NV,p)
#define PTR2nat(p) (PTRV)(p) /* pointer to integer of PTRSIZE */
/* According to strict ANSI C89 one cannot freely cast between
* data pointers and function (code) pointers. There are at least
* two ways around this. One (used below) is to do two casts,
* first the other pointer to an (unsigned) integer, and then
* the integer to the other pointer. The other way would be
* to use unions to "overlay" the pointers. For an example of
* the latter technique, see union dirpu in struct xpvio in sv.h.
* The only feasible use is probably temporarily storing
* function pointers in a data pointer (such as a void pointer). */
#define DPTR2FPTR(t,p) ((t)PTR2nat(p)) /* data pointer to function pointer */
#define FPTR2DPTR(t,p) ((t)PTR2nat(p)) /* function pointer to data pointer */
#ifdef USE_LONG_DOUBLE
# if LONG_DOUBLESIZE == DOUBLESIZE
# define LONG_DOUBLE_EQUALS_DOUBLE
# undef USE_LONG_DOUBLE /* Ouch! */
# endif
#endif
/* The following is all to get LDBL_DIG, in order to pick a nice
default value for printing floating point numbers in Gconvert.
(see config.h)
*/
#ifndef HAS_LDBL_DIG
# if LONG_DOUBLESIZE == 10
# define LDBL_DIG 18 /* assume IEEE */
# elif LONG_DOUBLESIZE == 12
# define LDBL_DIG 18 /* gcc? */
# elif LONG_DOUBLESIZE == 16
# define LDBL_DIG 33 /* assume IEEE */
# elif LONG_DOUBLESIZE == DOUBLESIZE
# define LDBL_DIG DBL_DIG /* bummer */
# endif
#endif
typedef NVTYPE NV;
#ifdef I_IEEEFP
# include <ieeefp.h>
#endif
#if defined(__DECC) && defined(__osf__)
/* Also Tru64 cc has broken NaN comparisons. */
# define NAN_COMPARE_BROKEN
#endif
#if defined(__sgi)
# define NAN_COMPARE_BROKEN
#endif
#ifdef USE_LONG_DOUBLE
# ifdef I_SUNMATH
# include <sunmath.h>
# endif
# if defined(LDBL_DIG)
# define NV_DIG LDBL_DIG
# ifdef LDBL_MANT_DIG
# define NV_MANT_DIG LDBL_MANT_DIG
# endif
# ifdef LDBL_MIN
# define NV_MIN LDBL_MIN
# endif
# ifdef LDBL_MAX
# define NV_MAX LDBL_MAX
# endif
# ifdef LDBL_MIN_EXP
# define NV_MIN_EXP LDBL_MIN_EXP
# endif
# ifdef LDBL_MAX_EXP
# define NV_MAX_EXP LDBL_MAX_EXP
# endif
# ifdef LDBL_MIN_10_EXP
# define NV_MIN_10_EXP LDBL_MIN_10_EXP
# endif
# ifdef LDBL_MAX_10_EXP
# define NV_MAX_10_EXP LDBL_MAX_10_EXP
# endif
# ifdef LDBL_EPSILON
# define NV_EPSILON LDBL_EPSILON
# endif
# ifdef LDBL_MAX
# define NV_MAX LDBL_MAX
/* Having LDBL_MAX doesn't necessarily mean that we have LDBL_MIN... -Allen */
# elif defined(HUGE_VALL)
# define NV_MAX HUGE_VALL
# endif
# endif
# if defined(HAS_SQRTL)
# define Perl_acos acosl
# define Perl_asin asinl
# define Perl_atan atanl
# define Perl_atan2 atan2l
# define Perl_ceil ceill
# define Perl_cos cosl
# define Perl_cosh coshl
# define Perl_exp expl
/* no Perl_fabs, but there's PERL_ABS */
# define Perl_floor floorl
# define Perl_fmod fmodl
# define Perl_log logl
# define Perl_log10 log10l
# define Perl_pow powl
# define Perl_sin sinl
# define Perl_sinh sinhl
# define Perl_sqrt sqrtl
# define Perl_tan tanl
# define Perl_tanh tanhl
# endif
/* e.g. libsunmath doesn't have modfl and frexpl as of mid-March 2000 */
# ifndef Perl_modf
# ifdef HAS_MODFL
# define Perl_modf(x,y) modfl(x,y)
/* eg glibc 2.2 series seems to provide modfl on ppc and arm, but has no
prototype in <math.h> */
# ifndef HAS_MODFL_PROTO
EXTERN_C long double modfl(long double, long double *);
# endif
# elif (defined(HAS_TRUNCL) || defined(HAS_AINTL)) && defined(HAS_COPYSIGNL)
extern long double Perl_my_modfl(long double x, long double *ip);
# define Perl_modf(x,y) Perl_my_modfl(x,y)
# endif
# endif
# ifndef Perl_frexp
# ifdef HAS_FREXPL
# define Perl_frexp(x,y) frexpl(x,y)
# elif defined(HAS_ILOGBL) && defined(HAS_SCALBNL)
extern long double Perl_my_frexpl(long double x, int *e);
# define Perl_frexp(x,y) Perl_my_frexpl(x,y)
# endif
# endif
# ifndef Perl_ldexp
# ifdef HAS_LDEXPL
# define Perl_ldexp(x, y) ldexpl(x,y)
# elif defined(HAS_SCALBNL) && FLT_RADIX == 2
# define Perl_ldexp(x,y) scalbnl(x,y)
# endif
# endif
# ifndef Perl_isnan
# if defined(HAS_ISNANL) && !(defined(isnan) && defined(HAS_C99))
# define Perl_isnan(x) isnanl(x)
# elif defined(__sgi) && defined(__c99) /* XXX Configure test needed */
# define Perl_isnan(x) isnan(x)
# endif
# endif
# ifndef Perl_isinf
# if defined(HAS_ISINFL) && !(defined(isinf) && defined(HAS_C99))
# define Perl_isinf(x) isinfl(x)
# elif defined(__sgi) && defined(__c99) /* XXX Configure test needed */
# define Perl_isinf(x) isinf(x)
# elif defined(LDBL_MAX) && !defined(NAN_COMPARE_BROKEN)
# define Perl_isinf(x) ((x) > LDBL_MAX || (x) < -LDBL_MAX)
# endif
# endif
# ifndef Perl_isfinite
# define Perl_isfinite(x) Perl_isfinitel(x)
# endif
#elif defined(USE_QUADMATH) && defined(I_QUADMATH)
# include <quadmath.h>
# define NV_DIG FLT128_DIG
# define NV_MANT_DIG FLT128_MANT_DIG
# define NV_MIN FLT128_MIN
# define NV_MAX FLT128_MAX
# define NV_MIN_EXP FLT128_MIN_EXP
# define NV_MAX_EXP FLT128_MAX_EXP
# define NV_EPSILON FLT128_EPSILON
# define NV_MIN_10_EXP FLT128_MIN_10_EXP
# define NV_MAX_10_EXP FLT128_MAX_10_EXP
# define Perl_acos acosq
# define Perl_asin asinq
# define Perl_atan atanq
# define Perl_atan2 atan2q
# define Perl_ceil ceilq
# define Perl_cos cosq
# define Perl_cosh coshq
# define Perl_exp expq
/* no Perl_fabs, but there's PERL_ABS */
# define Perl_floor floorq
# define Perl_fmod fmodq
# define Perl_log logq
# define Perl_log10 log10q
# define Perl_signbit signbitq
# define Perl_pow powq
# define Perl_sin sinq
# define Perl_sinh sinhq
# define Perl_sqrt sqrtq
# define Perl_tan tanq
# define Perl_tanh tanhq
# define Perl_modf(x,y) modfq(x,y)
# define Perl_frexp(x,y) frexpq(x,y)
# define Perl_ldexp(x, y) ldexpq(x,y)
# define Perl_isinf(x) isinfq(x)
# define Perl_isnan(x) isnanq(x)
# define Perl_isfinite(x) !(isnanq(x) || isinfq(x))
# define Perl_fp_class(x) ((x) == 0.0Q ? 0 : isinfq(x) ? 3 : isnanq(x) ? 4 : PERL_ABS(x) < FLT128_MIN ? 2 : 1)
# define Perl_fp_class_inf(x) (Perl_fp_class(x) == 3)
# define Perl_fp_class_nan(x) (Perl_fp_class(x) == 4)
# define Perl_fp_class_norm(x) (Perl_fp_class(x) == 1)
# define Perl_fp_class_denorm(x) (Perl_fp_class(x) == 2)
# define Perl_fp_class_zero(x) (Perl_fp_class(x) == 0)
#else
# define NV_DIG DBL_DIG
# define NV_MANT_DIG DBL_MANT_DIG
# define NV_MIN DBL_MIN
# define NV_MAX DBL_MAX
# define NV_MIN_EXP DBL_MIN_EXP
# define NV_MAX_EXP DBL_MAX_EXP
# define NV_MIN_10_EXP DBL_MIN_10_EXP
# define NV_MAX_10_EXP DBL_MAX_10_EXP
# define NV_EPSILON DBL_EPSILON
# define NV_MAX DBL_MAX
# define NV_MIN DBL_MIN
/* These math interfaces are C89. */
# define Perl_acos acos
# define Perl_asin asin
# define Perl_atan atan
# define Perl_atan2 atan2
# define Perl_ceil ceil
# define Perl_cos cos
# define Perl_cosh cosh
# define Perl_exp exp
/* no Perl_fabs, but there's PERL_ABS */
# define Perl_floor floor
# define Perl_fmod fmod
# define Perl_log log
# define Perl_log10 log10
# define Perl_pow pow
# define Perl_sin sin
# define Perl_sinh sinh
# define Perl_sqrt sqrt
# define Perl_tan tan
# define Perl_tanh tanh
# define Perl_modf(x,y) modf(x,y)
# define Perl_frexp(x,y) frexp(x,y)
# define Perl_ldexp(x,y) ldexp(x,y)
# ifndef Perl_isnan
# ifdef HAS_ISNAN
# define Perl_isnan(x) isnan(x)
# endif
# endif
# ifndef Perl_isinf
# if defined(HAS_ISINF)
# define Perl_isinf(x) isinf(x)
# elif defined(DBL_MAX) && !defined(NAN_COMPARE_BROKEN)
# define Perl_isinf(x) ((x) > DBL_MAX || (x) < -DBL_MAX)
# endif
# endif
# ifndef Perl_isfinite
# ifdef HAS_ISFINITE
# define Perl_isfinite(x) isfinite(x)
# elif defined(HAS_FINITE)
# define Perl_isfinite(x) finite(x)
# endif
# endif
#endif
/* fpclassify(): C99. It is supposed to be a macro that switches on
* the sizeof() of its argument, so there's no need for e.g. fpclassifyl().*/
#if !defined(Perl_fp_class) && defined(HAS_FPCLASSIFY)
# include <math.h>
# if defined(FP_INFINITE) && defined(FP_NAN)
# define Perl_fp_class(x) fpclassify(x)
# define Perl_fp_class_inf(x) (Perl_fp_class(x)==FP_INFINITE)
# define Perl_fp_class_nan(x) (Perl_fp_class(x)==FP_NAN)
# define Perl_fp_class_norm(x) (Perl_fp_class(x)==FP_NORMAL)
# define Perl_fp_class_denorm(x) (Perl_fp_class(x)==FP_SUBNORMAL)
# define Perl_fp_class_zero(x) (Perl_fp_class(x)==FP_ZERO)
# elif defined(FP_PLUS_INF) && defined(FP_QNAN)
/* Some versions of HP-UX (10.20) have (only) fpclassify() but which is
* actually not the C99 fpclassify, with its own set of return defines. */
# define Perl_fp_class(x) fpclassify(x)
# define Perl_fp_class_pinf(x) (Perl_fp_class(x)==FP_PLUS_INF)
# define Perl_fp_class_ninf(x) (Perl_fp_class(x)==FP_MINUS_INF)
# define Perl_fp_class_snan(x) (Perl_fp_class(x)==FP_SNAN)
# define Perl_fp_class_qnan(x) (Perl_fp_class(x)==FP_QNAN)
# define Perl_fp_class_pnorm(x) (Perl_fp_class(x)==FP_PLUS_NORM)
# define Perl_fp_class_nnorm(x) (Perl_fp_class(x)==FP_MINUS_NORM)
# define Perl_fp_class_pdenorm(x) (Perl_fp_class(x)==FP_PLUS_DENORM)
# define Perl_fp_class_ndenorm(x) (Perl_fp_class(x)==FP_MINUS_DENORM)
# define Perl_fp_class_pzero(x) (Perl_fp_class(x)==FP_PLUS_ZERO)
# define Perl_fp_class_nzero(x) (Perl_fp_class(x)==FP_MINUS_ZERO)
# else
# undef Perl_fp_class /* Unknown set of defines */
# endif
#endif
/* fp_classify(): Legacy: VMS, maybe Unicos? The values, however,
* are identical to the C99 fpclassify(). */
#if !defined(Perl_fp_class) && defined(HAS_FP_CLASSIFY)
# include <math.h>
# ifdef __VMS
/* FP_INFINITE and others are here rather than in math.h as C99 stipulates */
# include <fp.h>
/* oh, and the isnormal macro has a typo in it! */
# undef isnormal
# define isnormal(x) Perl_fp_class_norm(x)
# endif
# if defined(FP_INFINITE) && defined(FP_NAN)
# define Perl_fp_class(x) fp_classify(x)
# define Perl_fp_class_inf(x) (Perl_fp_class(x)==FP_INFINITE)
# define Perl_fp_class_nan(x) (Perl_fp_class(x)==FP_NAN)
# define Perl_fp_class_norm(x) (Perl_fp_class(x)==FP_NORMAL)
# define Perl_fp_class_denorm(x) (Perl_fp_class(x)==FP_SUBNORMAL)
# define Perl_fp_class_zero(x) (Perl_fp_class(x)==FP_ZERO)
# else
# undef Perl_fp_class /* Unknown set of defines */
# endif
#endif
/* Feel free to check with me for the SGI manpages, SGI testing,
* etcetera, if you want to try getting this to work with IRIX.
*
* - Allen <<EMAIL>> */
/* fpclass(): SysV, at least Solaris and some versions of IRIX. */
#if !defined(Perl_fp_class) && (defined(HAS_FPCLASS)||defined(HAS_FPCLASSL))
/* Solaris and IRIX have fpclass/fpclassl, but they are using
* an enum typedef, not cpp symbols, and Configure doesn't detect that.
* Define some symbols also as cpp symbols so we can detect them. */
# if defined(__sun) || defined(__sgi) /* XXX Configure test instead */
# define FP_PINF FP_PINF
# define FP_QNAN FP_QNAN
# endif
# include <math.h>
# ifdef I_IEEFP
# include <ieeefp.h>
# endif
# ifdef I_FP
# include <fp.h>
# endif
# if defined(USE_LONG_DOUBLE) && defined(HAS_FPCLASSL)
# define Perl_fp_class(x) fpclassl(x)
# else
# define Perl_fp_class(x) fpclass(x)
# endif
# if defined(FP_CLASS_PINF) && defined(FP_CLASS_SNAN)
# define Perl_fp_class_snan(x) (Perl_fp_class(x)==FP_CLASS_SNAN)
# define Perl_fp_class_qnan(x) (Perl_fp_class(x)==FP_CLASS_QNAN)
# define Perl_fp_class_ninf(x) (Perl_fp_class(x)==FP_CLASS_NINF)
# define Perl_fp_class_pinf(x) (Perl_fp_class(x)==FP_CLASS_PINF)
# define Perl_fp_class_nnorm(x) (Perl_fp_class(x)==FP_CLASS_NNORM)
# define Perl_fp_class_pnorm(x) (Perl_fp_class(x)==FP_CLASS_PNORM)
# define Perl_fp_class_ndenorm(x) (Perl_fp_class(x)==FP_CLASS_NDENORM)
# define Perl_fp_class_pdenorm(x) (Perl_fp_class(x)==FP_CLASS_PDENORM)
# define Perl_fp_class_nzero(x) (Perl_fp_class(x)==FP_CLASS_NZERO)
# define Perl_fp_class_pzero(x) (Perl_fp_class(x)==FP_CLASS_PZERO)
# elif defined(FP_PINF) && defined(FP_QNAN)
# define Perl_fp_class_snan(x) (Perl_fp_class(x)==FP_SNAN)
# define Perl_fp_class_qnan(x) (Perl_fp_class(x)==FP_QNAN)
# define Perl_fp_class_ninf(x) (Perl_fp_class(x)==FP_NINF)
# define Perl_fp_class_pinf(x) (Perl_fp_class(x)==FP_PINF)
# define Perl_fp_class_nnorm(x) (Perl_fp_class(x)==FP_NNORM)
# define Perl_fp_class_pnorm(x) (Perl_fp_class(x)==FP_PNORM)
# define Perl_fp_class_ndenorm(x) (Perl_fp_class(x)==FP_NDENORM)
# define Perl_fp_class_pdenorm(x) (Perl_fp_class(x)==FP_PDENORM)
# define Perl_fp_class_nzero(x) (Perl_fp_class(x)==FP_NZERO)
# define Perl_fp_class_pzero(x) (Perl_fp_class(x)==FP_PZERO)
# else
# undef Perl_fp_class /* Unknown set of defines */
# endif
#endif
/* fp_class(): Legacy: at least Tru64, some versions of IRIX. */
#if !defined(Perl_fp_class) && (defined(HAS_FP_CLASS)||defined(HAS_FP_CLASSL))
# include <math.h>
# if !defined(FP_SNAN) && defined(I_FP_CLASS)
# include <fp_class.h>
# endif
# if defined(FP_POS_INF) && defined(FP_QNAN)
# ifdef __sgi /* XXX Configure test instead */
# ifdef USE_LONG_DOUBLE
# define Perl_fp_class(x) fp_class_l(x)
# else
# define Perl_fp_class(x) fp_class_d(x)
# endif
# else
# if defined(USE_LONG_DOUBLE) && defined(HAS_FP_CLASSL)
# define Perl_fp_class(x) fp_classl(x)
# else
# define Perl_fp_class(x) fp_class(x)
# endif
# endif
# if defined(FP_POS_INF) && defined(FP_QNAN)
# define Perl_fp_class_snan(x) (Perl_fp_class(x)==FP_SNAN)
# define Perl_fp_class_qnan(x) (Perl_fp_class(x)==FP_QNAN)
# define Perl_fp_class_ninf(x) (Perl_fp_class(x)==FP_NEG_INF)
# define Perl_fp_class_pinf(x) (Perl_fp_class(x)==FP_POS_INF)
# define Perl_fp_class_nnorm(x) (Perl_fp_class(x)==FP_NEG_NORM)
# define Perl_fp_class_pnorm(x) (Perl_fp_class(x)==FP_POS_NORM)
# define Perl_fp_class_ndenorm(x) (Perl_fp_class(x)==FP_NEG_DENORM)
# define Perl_fp_class_pdenorm(x) (Perl_fp_class(x)==FP_POS_DENORM)
# define Perl_fp_class_nzero(x) (Perl_fp_class(x)==FP_NEG_ZERO)
# define Perl_fp_class_pzero(x) (Perl_fp_class(x)==FP_POS_ZERO)
# else
# undef Perl_fp_class /* Unknown set of defines */
# endif
# endif
#endif
/* class(), _class(): Legacy: AIX. */
#if !defined(Perl_fp_class) && defined(HAS_CLASS)
# include <math.h>
# if defined(FP_PLUS_NORM) && defined(FP_PLUS_INF)
# ifndef _cplusplus
# define Perl_fp_class(x) class(x)
# else
# define Perl_fp_class(x) _class(x)
# endif
# if defined(FP_PLUS_INF) && defined(FP_NANQ)
# define Perl_fp_class_snan(x) (Perl_fp_class(x)==FP_NANS)
# define Perl_fp_class_qnan(x) (Perl_fp_class(x)==FP_NANQ)
# define Perl_fp_class_ninf(x) (Perl_fp_class(x)==FP_MINUS_INF)
# define Perl_fp_class_pinf(x) (Perl_fp_class(x)==FP_PLUS_INF)
# define Perl_fp_class_nnorm(x) (Perl_fp_class(x)==FP_MINUS_NORM)
# define Perl_fp_class_pnorm(x) (Perl_fp_class(x)==FP_PLUS_NORM)
# define Perl_fp_class_ndenorm(x) (Perl_fp_class(x)==FP_MINUS_DENORM)
# define Perl_fp_class_pdenorm(x) (Perl_fp_class(x)==FP_PLUS_DENORM)
# define Perl_fp_class_nzero(x) (Perl_fp_class(x)==FP_MINUS_ZERO)
# define Perl_fp_class_pzero(x) (Perl_fp_class(x)==FP_PLUS_ZERO)
# else
# undef Perl_fp_class /* Unknown set of defines */
# endif
# endif
#endif
/* Win32: _fpclass(), _isnan(), _finite(). */
#ifdef _MSC_VER
# ifndef Perl_isnan
# define Perl_isnan(x) _isnan(x)
# endif
# ifndef Perl_isfinite
# define Perl_isfinite(x) _finite(x)
# endif
# ifndef Perl_fp_class_snan
/* No simple way to #define Perl_fp_class because _fpclass()
* returns a set of bits. */
# define Perl_fp_class_snan(x) (_fpclass(x) & _FPCLASS_SNAN)
# define Perl_fp_class_qnan(x) (_fpclass(x) & _FPCLASS_QNAN)
# define Perl_fp_class_nan(x) (_fpclass(x) & (_FPCLASS_SNAN|_FPCLASS_QNAN))
# define Perl_fp_class_ninf(x) (_fpclass(x) & _FPCLASS_NINF))
# define Perl_fp_class_pinf(x) (_fpclass(x) & _FPCLASS_PINF))
# define Perl_fp_class_inf(x) (_fpclass(x) & (_FPCLASS_NINF|_FPCLASS_PINF))
# define Perl_fp_class_nnorm(x) (_fpclass(x) & _FPCLASS_NN)
# define Perl_fp_class_pnorm(x) (_fpclass(x) & _FPCLASS_PN)
# define Perl_fp_class_norm(x) (_fpclass(x) & (_FPCLASS_NN|_FPCLASS_PN))
# define Perl_fp_class_ndenorm(x) (_fpclass(x) & _FPCLASS_ND)
# define Perl_fp_class_pdenorm(x) (_fpclass(x) & _FPCLASS_PD)
# define Perl_fp_class_denorm(x) (_fpclass(x) & (_FPCLASS_ND|_FPCLASS_PD))
# define Perl_fp_class_nzero(x) (_fpclass(x) & _FPCLASS_NZ)
# define Perl_fp_class_pzero(x) (_fpclass(x) & _FPCLASS_PZ)
# define Perl_fp_class_zero(x) (_fpclass(x) & (_FPCLASS_NZ|_FPCLASS_PZ))
# endif
#endif
#if !defined(Perl_fp_class_inf) && \
defined(Perl_fp_class_pinf) && defined(Perl_fp_class_ninf)
# define Perl_fp_class_inf(x) \
(Perl_fp_class_pinf(x) || Perl_fp_class_ninf(x))
#endif
#if !defined(Perl_fp_class_nan) && \
defined(Perl_fp_class_snan) && defined(Perl_fp_class_qnan)
# define Perl_fp_class_nan(x) \
(Perl_fp_class_snan(x) || Perl_fp_class_qnan(x))
#endif
#if !defined(Perl_fp_class_zero) && \
defined(Perl_fp_class_pzero) && defined(Perl_fp_class_nzero)
# define Perl_fp_class_zero(x) \
(Perl_fp_class_pzero(x) || Perl_fp_class_nzero(x))
#endif
#if !defined(Perl_fp_class_norm) && \
defined(Perl_fp_class_pnorm) && defined(Perl_fp_class_nnorm)
# define Perl_fp_class_norm(x) \
(Perl_fp_class_pnorm(x) || Perl_fp_class_nnorm(x))
#endif
#if !defined(Perl_fp_class_denorm) && \
defined(Perl_fp_class_pdenorm) && defined(Perl_fp_class_ndenorm)
# define Perl_fp_class_denorm(x) \
(Perl_fp_class_pdenorm(x) || Perl_fp_class_ndenorm(x))
#endif
#ifndef Perl_isnan
# ifdef Perl_fp_class_nan
# define Perl_isnan(x) Perl_fp_class_nan(x)
# elif defined(HAS_UNORDERED)
# define Perl_isnan(x) unordered((x), 0.0)
# else
# define Perl_isnan(x) ((x)!=(x))
# endif
#endif
#ifndef Perl_isinf
# ifdef Perl_fp_class_inf
# define Perl_isinf(x) Perl_fp_class_inf(x)
# endif
#endif
#ifndef Perl_isfinite
# if defined(HAS_ISFINITE) && !defined(isfinite)
# define Perl_isfinite(x) isfinite((double)(x))
# elif defined(HAS_FINITE)
# define Perl_isfinite(x) finite((double)(x))
# elif defined(Perl_fp_class_finite)
# define Perl_isfinite(x) Perl_fp_class_finite(x)
# else
/* For the infinities the multiplication returns nan,
* for the nan the multiplication also returns nan,
* for everything else (that is, finite) zero should be returned. */
# define Perl_isfinite(x) (((x) * 0) == 0)
# endif
#endif
#ifndef Perl_isinf
# if defined(Perl_isfinite) && defined(Perl_isnan)
# define Perl_isinf(x) !(Perl_isfinite(x)||Perl_isnan(x))
# endif
#endif
/* We need Perl_isfinitel (ends with ell) (if available) even when
* not USE_LONG_DOUBLE because the printf code (sv_catpvfn_flags)
* needs that. */
#if defined(HAS_LONG_DOUBLE) && !defined(Perl_isfinitel)
/* If isfinite() is a macro and looks like we have C99,
* we assume it's the type-aware C99 isfinite(). */
# if defined(HAS_ISFINITE) && defined(isfinite) && defined(HAS_C99)
# define Perl_isfinitel(x) isfinite(x)
# elif defined(HAS_ISFINITEL)
# define Perl_isfinitel(x) isfinitel(x)
# elif defined(HAS_FINITEL)
# define Perl_isfinitel(x) finitel(x)
# elif defined(HAS_INFL) && defined(HAS_NANL)
# define Perl_isfinitel(x) !(isinfl(x)||isnanl(x))
# else
# define Perl_isfinitel(x) ((x) * 0 == 0) /* See Perl_isfinite. */
# endif
#endif
/* The default is to use Perl's own atof() implementation (in numeric.c).
* Usually that is the one to use but for some platforms (e.g. UNICOS)
* it is however best to use the native implementation of atof.
* You can experiment with using your native one by -DUSE_PERL_ATOF=0.
* Some good tests to try out with either setting are t/base/num.t,
* t/op/numconvert.t, and t/op/pack.t. Note that if using long doubles
* you may need to be using a different function than atof! */
#ifndef USE_PERL_ATOF
# ifndef _UNICOS
# define USE_PERL_ATOF
# endif
#else
# if USE_PERL_ATOF == 0
# undef USE_PERL_ATOF
# endif
#endif
#ifdef USE_PERL_ATOF
# define Perl_atof(s) Perl_my_atof(s)
# define Perl_atof2(s, n) Perl_my_atof3(aTHX_ (s), &(n), 0)
#else
# define Perl_atof(s) (NV)atof(s)
# define Perl_atof2(s, n) ((n) = atof(s))
#endif
#define my_atof2(a,b) my_atof3(a,b,0)
/*
* CHAR_MIN and CHAR_MAX are not included here, as the (char) type may be
* ambiguous. It may be equivalent to (signed char) or (unsigned char)
* depending on local options. Until Configure detects this (or at least
* detects whether the "signed" keyword is available) the CHAR ranges
* will not be included. UCHAR functions normally.
* - kja
*/
#define PERL_UCHAR_MIN ((unsigned char)0)
#define PERL_UCHAR_MAX ((unsigned char)UCHAR_MAX)
#define PERL_USHORT_MIN ((unsigned short)0)
#define PERL_USHORT_MAX ((unsigned short)USHRT_MAX)
#define PERL_SHORT_MAX ((short)SHRT_MAX)
#define PERL_SHORT_MIN ((short)SHRT_MIN)
#define PERL_UINT_MAX ((unsigned int)UINT_MAX)
#define PERL_UINT_MIN ((unsigned int)0)
#define PERL_INT_MAX ((int)INT_MAX)
#define PERL_INT_MIN ((int)INT_MIN)
#define PERL_ULONG_MAX ((unsigned long)ULONG_MAX)
#define PERL_ULONG_MIN ((unsigned long)0L)
#define PERL_LONG_MAX ((long)LONG_MAX)
#define PERL_LONG_MIN ((long)LONG_MIN)
#ifdef UV_IS_QUAD
# define PERL_UQUAD_MAX (~(UV)0)
# define PERL_UQUAD_MIN ((UV)0)
# define PERL_QUAD_MAX ((IV) (PERL_UQUAD_MAX >> 1))
# define PERL_QUAD_MIN (-PERL_QUAD_MAX - ((3 & -1) == 3))
#endif
/*
=head1 Numeric functions
=for apidoc AmnUh||PERL_INT_MIN
=for apidoc AmnUh||PERL_LONG_MAX
=for apidoc AmnUh||PERL_LONG_MIN
=for apidoc AmnUh||PERL_QUAD_MAX
=for apidoc AmnUh||PERL_SHORT_MAX
=for apidoc AmnUh||PERL_SHORT_MIN
=for apidoc AmnUh||PERL_UCHAR_MAX
=for apidoc AmnUh||PERL_UCHAR_MIN
=for apidoc AmnUh||PERL_UINT_MAX
=for apidoc AmnUh||PERL_ULONG_MAX
=for apidoc AmnUh||PERL_ULONG_MIN
=for apidoc AmnUh||PERL_UQUAD_MAX
=for apidoc AmnUh||PERL_UQUAD_MIN
=for apidoc AmnUh||PERL_USHORT_MAX
=for apidoc AmnUh||PERL_USHORT_MIN
=for apidoc AmnUh||PERL_QUAD_MIN
=for apidoc AmnU||PERL_INT_MAX
This and
C<PERL_INT_MIN>,
C<PERL_LONG_MAX>,
C<PERL_LONG_MIN>,
C<PERL_QUAD_MAX>,
C<PERL_SHORT_MAX>,
C<PERL_SHORT_MIN>,
C<PERL_UCHAR_MAX>,
C<PERL_UCHAR_MIN>,
C<PERL_UINT_MAX>,
C<PERL_ULONG_MAX>,
C<PERL_ULONG_MIN>,
C<PERL_UQUAD_MAX>,
C<PERL_UQUAD_MIN>,
C<PERL_USHORT_MAX>,
C<PERL_USHORT_MIN>,
C<PERL_QUAD_MIN>
give the largest and smallest number representable in the current
platform in variables of the corresponding types.
For signed types, the smallest representable number is the most negative
number, the one furthest away from zero.
For C99 and later compilers, these correspond to things like C<INT_MAX>, which
are available to the C code. But these constants, furnished by Perl,
allow code compiled on earlier compilers to portably have access to the same
constants.
=cut
*/
typedef MEM_SIZE STRLEN;
typedef struct op OP;
typedef struct cop COP;
typedef struct unop UNOP;
typedef struct unop_aux UNOP_AUX;
typedef struct binop BINOP;
typedef struct listop LISTOP;
typedef struct logop LOGOP;
typedef struct pmop PMOP;
typedef struct svop SVOP;
typedef struct padop PADOP;
typedef struct pvop PVOP;
typedef struct loop LOOP;
typedef struct methop METHOP;
#ifdef PERL_CORE
typedef struct opslab OPSLAB;
typedef struct opslot OPSLOT;
#endif
typedef struct block_hooks BHK;
typedef struct custom_op XOP;
typedef struct interpreter PerlInterpreter;
/* SGI's <sys/sema.h> has struct sv */
#if defined(__sgi)
# define STRUCT_SV perl_sv
#else
# define STRUCT_SV sv
#endif
typedef struct STRUCT_SV SV;
typedef struct av AV;
typedef struct hv HV;
typedef struct cv CV;
typedef struct p5rx REGEXP;
typedef struct gp GP;
typedef struct gv GV;
typedef struct io IO;
typedef struct context PERL_CONTEXT;
typedef struct block BLOCK;
typedef struct magic MAGIC;
typedef struct xpv XPV;
typedef struct xpviv XPVIV;
typedef struct xpvuv XPVUV;
typedef struct xpvnv XPVNV;
typedef struct xpvmg XPVMG;
typedef struct xpvlv XPVLV;
typedef struct xpvinvlist XINVLIST;
typedef struct xpvav XPVAV;
typedef struct xpvhv XPVHV;
typedef struct xpvgv XPVGV;
typedef struct xpvcv XPVCV;
typedef struct xpvbm XPVBM;
typedef struct xpvfm XPVFM;
typedef struct xpvio XPVIO;
typedef struct mgvtbl MGVTBL;
typedef union any ANY;
typedef struct ptr_tbl_ent PTR_TBL_ENT_t;
typedef struct ptr_tbl PTR_TBL_t;
typedef struct clone_params CLONE_PARAMS;
/* a pad is currently just an AV; but that might change,
* so hide the type. */
typedef struct padlist PADLIST;
typedef AV PAD;
typedef struct padnamelist PADNAMELIST;
typedef struct padname PADNAME;
/* always enable PERL_OP_PARENT */
#if !defined(PERL_OP_PARENT)
# define PERL_OP_PARENT
#endif
/* enable PERL_COPY_ON_WRITE by default */
#if !defined(PERL_COPY_ON_WRITE) && !defined(PERL_NO_COW)
# define PERL_COPY_ON_WRITE
#endif
#ifdef PERL_COPY_ON_WRITE
# define PERL_ANY_COW
#else
# define PERL_SAWAMPERSAND
#endif
#if defined(PERL_DEBUG_READONLY_OPS) && !defined(USE_ITHREADS)
# error PERL_DEBUG_READONLY_OPS only works with ithreads
#endif
#include "handy.h"
#include "charclass_invlists.h"
#if defined(USE_LARGE_FILES) && !defined(NO_64_BIT_RAWIO)
# if LSEEKSIZE == 8 && !defined(USE_64_BIT_RAWIO)
# define USE_64_BIT_RAWIO /* implicit */
# endif
#endif
/* Notice the use of HAS_FSEEKO: now we are obligated to always use
* fseeko/ftello if possible. Don't go #defining ftell to ftello yourself,
* however, because operating systems like to do that themself. */
#ifndef FSEEKSIZE
# ifdef HAS_FSEEKO
# define FSEEKSIZE LSEEKSIZE
# else
# define FSEEKSIZE LONGSIZE
# endif
#endif
#if defined(USE_LARGE_FILES) && !defined(NO_64_BIT_STDIO)
# if FSEEKSIZE == 8 && !defined(USE_64_BIT_STDIO)
# define USE_64_BIT_STDIO /* implicit */
# endif
#endif
#ifdef USE_64_BIT_RAWIO
# ifdef HAS_OFF64_T
# undef Off_t
# define Off_t off64_t
# undef LSEEKSIZE
# define LSEEKSIZE 8
# endif
/* Most 64-bit environments have defines like _LARGEFILE_SOURCE that
* will trigger defines like the ones below. Some 64-bit environments,
* however, do not. Therefore we have to explicitly mix and match. */
# if defined(USE_OPEN64)
# define open open64
# endif
# if defined(USE_LSEEK64)
# define lseek lseek64
# else
# if defined(USE_LLSEEK)
# define lseek llseek
# endif
# endif
# if defined(USE_STAT64)
# define stat stat64
# endif
# if defined(USE_FSTAT64)
# define fstat fstat64
# endif
# if defined(USE_LSTAT64)
# define lstat lstat64
# endif
# if defined(USE_FLOCK64)
# define flock flock64
# endif
# if defined(USE_LOCKF64)
# define lockf lockf64
# endif
# if defined(USE_FCNTL64)
# define fcntl fcntl64
# endif
# if defined(USE_TRUNCATE64)
# define truncate truncate64
# endif
# if defined(USE_FTRUNCATE64)
# define ftruncate ftruncate64
# endif
#endif
#ifdef USE_64_BIT_STDIO
# ifdef HAS_FPOS64_T
# undef Fpos_t
# define Fpos_t fpos64_t
# endif
/* Most 64-bit environments have defines like _LARGEFILE_SOURCE that
* will trigger defines like the ones below. Some 64-bit environments,
* however, do not. */
# if defined(USE_FOPEN64)
# define fopen fopen64
# endif
# if defined(USE_FSEEK64)
# define fseek fseek64 /* don't do fseeko here, see perlio.c */
# endif
# if defined(USE_FTELL64)
# define ftell ftell64 /* don't do ftello here, see perlio.c */
# endif
# if defined(USE_FSETPOS64)
# define fsetpos fsetpos64
# endif
# if defined(USE_FGETPOS64)
# define fgetpos fgetpos64
# endif
# if defined(USE_TMPFILE64)
# define tmpfile tmpfile64
# endif
# if defined(USE_FREOPEN64)
# define freopen freopen64
# endif
#endif
#if defined(OS2)
# include "iperlsys.h"
#endif
#ifdef DOSISH
# if defined(OS2)
# include "os2ish.h"
# else
# include "dosish.h"
# endif
#elif defined(VMS)
# include "vmsish.h"
#elif defined(PLAN9)
# include "./plan9/plan9ish.h"
#elif defined(__VOS__)
# ifdef __GNUC__
# include "./vos/vosish.h"
# else
# include "vos/vosish.h"
# endif
#elif defined(__SYMBIAN32__)
# include "symbian/symbianish.h"
#elif defined(__HAIKU__)
# include "haiku/haikuish.h"
#else
# include "unixish.h"
#endif
#ifdef __amigaos4__
# include "amigaos.h"
# undef FD_CLOEXEC /* a lie in AmigaOS */
#endif
/* NSIG logic from Configure --> */
#ifndef NSIG
# ifdef _NSIG
# define NSIG (_NSIG)
# elif defined(SIGMAX)
# define NSIG (SIGMAX+1)
# elif defined(SIG_MAX)
# define NSIG (SIG_MAX+1)
# elif defined(_SIG_MAX)
# define NSIG (_SIG_MAX+1)
# elif defined(MAXSIG)
# define NSIG (MAXSIG+1)
# elif defined(MAX_SIG)
# define NSIG (MAX_SIG+1)
# elif defined(SIGARRAYSIZE)
# define NSIG SIGARRAYSIZE /* Assume ary[SIGARRAYSIZE] */
# elif defined(_sys_nsig)
# define NSIG (_sys_nsig) /* Solaris 2.5 */
# else
/* Default to some arbitrary number that's big enough to get most
* of the common signals. */
# define NSIG 50
# endif
#endif
/* <-- NSIG logic from Configure */
#ifndef NO_ENVIRON_ARRAY
# define USE_ENVIRON_ARRAY
#endif
#ifdef USE_ITHREADS
/* On some platforms it would be safe to use a read/write mutex with many
* readers possible at the same time. On other platforms, notably IBM ones,
* subsequent getenv calls destroy earlier ones. Those platforms would not
* be able to handle simultaneous getenv calls */
# define ENV_LOCK MUTEX_LOCK(&PL_env_mutex)
# define ENV_UNLOCK MUTEX_UNLOCK(&PL_env_mutex)
# define ENV_INIT MUTEX_INIT(&PL_env_mutex);
# define ENV_TERM MUTEX_DESTROY(&PL_env_mutex);
#else
# define ENV_LOCK NOOP;
# define ENV_UNLOCK NOOP;
# define ENV_INIT NOOP;
# define ENV_TERM NOOP;
#endif
/* Some critical sections need to lock both the locale and the environment.
* XXX khw intends to change this to lock both mutexes, but that brings up
* issues of potential deadlock, so should be done at the beginning of a
* development cycle. So for now, it just locks the environment. Note that
* many modern platforms are locale-thread-safe anyway, so locking the locale
* mutex is a no-op anyway */
#define ENV_LOCALE_LOCK ENV_LOCK
#define ENV_LOCALE_UNLOCK ENV_UNLOCK
/* And some critical sections care only that no one else is writing either the
* locale nor the environment. XXX Again this is for the future. This can be
* simulated with using COND_WAIT in thread.h */
#define ENV_LOCALE_READ_LOCK ENV_LOCALE_LOCK
#define ENV_LOCALE_READ_UNLOCK ENV_LOCALE_UNLOCK
#if defined(HAS_SIGACTION) && defined(SA_SIGINFO)
/* having sigaction(2) means that the OS supports both 1-arg and 3-arg
* signal handlers. But the perl core itself only fully supports 1-arg
* handlers, so don't enable for now.
* NB: POSIX::sigaction() supports both.
*
* # define PERL_USE_3ARG_SIGHANDLER
*/
#endif
/* Siginfo_t:
* This is an alias for the OS's siginfo_t, except that where the OS
* doesn't support it, declare a dummy version instead. This allows us to
* have signal handler functions which always have a Siginfo_t parameter
* regardless of platform, (and which will just be passed a NULL value
* where the OS doesn't support HAS_SIGACTION).
*/
#if defined(HAS_SIGACTION) && defined(SA_SIGINFO)
typedef siginfo_t Siginfo_t;
#else
#ifdef si_signo /* minix */
#undef si_signo
#endif
typedef struct {
int si_signo;
} Siginfo_t;
#endif
/*
* initialise to avoid floating-point exceptions from overflow, etc
*/
#ifndef PERL_FPU_INIT
# ifdef HAS_FPSETMASK
# if HAS_FLOATINGPOINT_H
# include <floatingpoint.h>
# endif
/* Some operating systems have this as a macro, which in turn expands to a comma
expression, and the last sub-expression is something that gets calculated,
and then they have the gall to warn that a value computed is not used. Hence
cast to void. */
# define PERL_FPU_INIT (void)fpsetmask(0)
# elif defined(SIGFPE) && defined(SIG_IGN) && !defined(PERL_MICRO)
# define PERL_FPU_INIT PL_sigfpe_saved = (Sighandler_t) signal(SIGFPE, SIG_IGN)
# define PERL_FPU_PRE_EXEC { Sigsave_t xfpe; rsignal_save(SIGFPE, PL_sigfpe_saved, &xfpe);
# define PERL_FPU_POST_EXEC rsignal_restore(SIGFPE, &xfpe); }
# else
# define PERL_FPU_INIT
# endif
#endif
#ifndef PERL_FPU_PRE_EXEC
# define PERL_FPU_PRE_EXEC {
# define PERL_FPU_POST_EXEC }
#endif
/* In Tru64 the cc -ieee enables the IEEE math but disables traps.
* We need to reenable the "invalid" trap because otherwise generation
* of NaN values leaves the IEEE fp flags in bad state, leaving any further
* fp ops behaving strangely (Inf + 1 resulting in zero, for example). */
#ifdef __osf__
# include <machine/fpu.h>
# define PERL_SYS_FPU_INIT \
STMT_START { \
ieee_set_fp_control(IEEE_TRAP_ENABLE_INV); \
signal(SIGFPE, SIG_IGN); \
} STMT_END
#endif
/* In IRIX the default for Flush to Zero bit is true,
* which means that results going below the minimum of normal
* floating points go to zero, instead of going denormal/subnormal.
* This is unlike almost any other system running Perl, so let's clear it.
* [perl #123767] IRIX64 blead (ddce084a) opbasic/arith.t failure, originally
* [perl #120426] small numbers shouldn't round to zero if they have extra floating digits
*
* XXX The flush-to-zero behaviour should be a Configure scan.
* To change the behaviour usually requires some system-specific
* incantation, though, like the below. */
#ifdef __sgi
# include <sys/fpu.h>
# define PERL_SYS_FPU_INIT \
STMT_START { \
union fpc_csr csr; \
csr.fc_word = get_fpc_csr(); \
csr.fc_struct.flush = 0; \
set_fpc_csr(csr.fc_word); \
} STMT_END
#endif
#ifndef PERL_SYS_FPU_INIT
# define PERL_SYS_FPU_INIT NOOP
#endif
#ifndef PERL_SYS_INIT3_BODY
# define PERL_SYS_INIT3_BODY(argvp,argcp,envp) PERL_SYS_INIT_BODY(argvp,argcp)
#endif
/*
=head1 Miscellaneous Functions
=for apidoc Am|void|PERL_SYS_INIT|int *argc|char*** argv
Provides system-specific tune up of the C runtime environment necessary to
run Perl interpreters. This should be called only once, before creating
any Perl interpreters.
=for apidoc Am|void|PERL_SYS_INIT3|int *argc|char*** argv|char*** env
Provides system-specific tune up of the C runtime environment necessary to
run Perl interpreters. This should be called only once, before creating
any Perl interpreters.
=for apidoc Am|void|PERL_SYS_TERM|
Provides system-specific clean up of the C runtime environment after
running Perl interpreters. This should be called only once, after
freeing any remaining Perl interpreters.
=cut
*/
#define PERL_SYS_INIT(argc, argv) Perl_sys_init(argc, argv)
#define PERL_SYS_INIT3(argc, argv, env) Perl_sys_init3(argc, argv, env)
#define PERL_SYS_TERM() Perl_sys_term()
#ifndef PERL_WRITE_MSG_TO_CONSOLE
# define PERL_WRITE_MSG_TO_CONSOLE(io, msg, len) PerlIO_write(io, msg, len)
#endif
#ifndef MAXPATHLEN
# ifdef PATH_MAX
# ifdef _POSIX_PATH_MAX
# if PATH_MAX > _POSIX_PATH_MAX
/* POSIX 1990 (and pre) was ambiguous about whether PATH_MAX
* included the null byte or not. Later amendments of POSIX,
* XPG4, the Austin Group, and the Single UNIX Specification
* all explicitly include the null byte in the PATH_MAX.
* Ditto for _POSIX_PATH_MAX. */
# define MAXPATHLEN PATH_MAX
# else
# define MAXPATHLEN _POSIX_PATH_MAX
# endif
# else
# define MAXPATHLEN (PATH_MAX+1)
# endif
# else
# define MAXPATHLEN 1024 /* Err on the large side. */
# endif
#endif
/* USE_5005THREADS needs to be after unixish.h as <pthread.h> includes
* <sys/signal.h> which defines NSIG - which will stop inclusion of <signal.h>
* this results in many functions being undeclared which bothers C++
* May make sense to have threads after "*ish.h" anyway
*/
/* clang Thread Safety Analysis/Annotations/Attributes
* http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
*
* Available since clang 3.6-ish (appeared in 3.4, but shaky still in 3.5).
* Apple XCode hijacks __clang_major__ and __clang_minor__
* (6.1 means really clang 3.6), so needs extra hijinks
* (could probably also test the contents of __apple_build_version__).
*/
#if defined(USE_ITHREADS) && defined(I_PTHREAD) && \
defined(__clang__) && \
!defined(PERL_GLOBAL_STRUCT) && \
!defined(PERL_GLOBAL_STRUCT_PRIVATE) && \
!defined(SWIG) && \
((!defined(__apple_build_version__) && \
((__clang_major__ == 3 && __clang_minor__ >= 6) || \
(__clang_major__ >= 4))) || \
(defined(__apple_build_version__) && \
((__clang_major__ == 6 && __clang_minor__ >= 1) || \
(__clang_major__ >= 7))))
# define PERL_TSA__(x) __attribute__((x))
# define PERL_TSA_ACTIVE
#else
# define PERL_TSA__(x) /* No TSA, make TSA attributes no-ops. */
# undef PERL_TSA_ACTIVE
#endif
/* PERL_TSA_CAPABILITY() is used to annotate typedefs.
* typedef old_type PERL_TSA_CAPABILITY("mutex") new_type;
*/
#define PERL_TSA_CAPABILITY(x) \
PERL_TSA__(capability(x))
/* In the below examples the mutex must be lexically visible, usually
* either as global variables, or as function arguments. */
/* PERL_TSA_GUARDED_BY() is used to annotate global variables.
*
* Foo foo PERL_TSA_GUARDED_BY(mutex);
*/
#define PERL_TSA_GUARDED_BY(x) \
PERL_TSA__(guarded_by(x))
/* PERL_TSA_PT_GUARDED_BY() is used to annotate global pointers.
* The data _behind_ the pointer is guarded.
*
* Foo* ptr PERL_TSA_PT_GUARDED_BY(mutex);
*/
#define PERL_TSA_PT_GUARDED_BY(x) \
PERL_TSA__(pt_guarded_by(x))
/* PERL_TSA_REQUIRES() is used to annotate functions.
* The caller MUST hold the resource when calling the function.
*
* void Foo() PERL_TSA_REQUIRES(mutex);
*/
#define PERL_TSA_REQUIRES(x) \
PERL_TSA__(requires_capability(x))
/* PERL_TSA_EXCLUDES() is used to annotate functions.
* The caller MUST NOT hold resource when calling the function.
*
* EXCLUDES should be used when the function first acquires
* the resource and then releases it. Use to avoid deadlock.
*
* void Foo() PERL_TSA_EXCLUDES(mutex);
*/
#define PERL_TSA_EXCLUDES(x) \
PERL_TSA__(locks_excluded(x))
/* PERL_TSA_ACQUIRE() is used to annotate functions.
* The caller MUST NOT hold the resource when calling the function,
* and the function will acquire the resource.
*
* void Foo() PERL_TSA_ACQUIRE(mutex);
*/
#define PERL_TSA_ACQUIRE(x) \
PERL_TSA__(acquire_capability(x))
/* PERL_TSA_RELEASE() is used to annotate functions.
* The caller MUST hold the resource when calling the function,
* and the function will release the resource.
*
* void Foo() PERL_TSA_RELEASE(mutex);
*/
#define PERL_TSA_RELEASE(x) \
PERL_TSA__(release_capability(x))
/* PERL_TSA_NO_TSA is used to annotate functions.
* Used when being intentionally unsafe, or when the code is too
* complicated for the analysis. Use sparingly.
*
* void Foo() PERL_TSA_NO_TSA;
*/
#define PERL_TSA_NO_TSA \
PERL_TSA__(no_thread_safety_analysis)
/* There are more annotations/attributes available, see the clang
* documentation for details. */
#if defined(USE_ITHREADS)
# ifdef NETWARE
# include <nw5thread.h>
# elif defined(WIN32)
# include <win32thread.h>
# elif defined(OS2)
# include "os2thread.h"
# elif defined(I_MACH_CTHREADS)
# include <mach/cthreads.h>
typedef cthread_t perl_os_thread;
typedef mutex_t perl_mutex;
typedef condition_t perl_cond;
typedef void * perl_key;
# elif defined(I_PTHREAD) /* Posix threads */
# include <pthread.h>
typedef pthread_t perl_os_thread;
typedef pthread_mutex_t PERL_TSA_CAPABILITY("mutex") perl_mutex;
typedef pthread_cond_t perl_cond;
typedef pthread_key_t perl_key;
# endif
#endif /* USE_ITHREADS */
#ifdef PERL_TSA_ACTIVE
/* Since most pthread mutex interfaces have not been annotated, we
* need to have these wrappers. The NO_TSA annotation is quite ugly
* but it cannot be avoided in plain C, unlike in C++, where one could
* e.g. use ACQUIRE() with no arg on a mutex lock method.
*
* The bodies of these wrappers are in util.c
*
* TODO: however, some platforms are starting to get these clang
* thread safety annotations for pthreads, for example FreeBSD.
* Do we need a way to a bypass these wrappers? */
EXTERN_C int perl_tsa_mutex_lock(perl_mutex* mutex)
PERL_TSA_ACQUIRE(*mutex)
PERL_TSA_NO_TSA;
EXTERN_C int perl_tsa_mutex_unlock(perl_mutex* mutex)
PERL_TSA_RELEASE(*mutex)
PERL_TSA_NO_TSA;
#endif
#if defined(WIN32)
# include "win32.h"
#endif
#ifdef NETWARE
# include "netware.h"
#endif
#define STATUS_UNIX PL_statusvalue
#ifdef VMS
# define STATUS_NATIVE PL_statusvalue_vms
/*
* vaxc$errno is only guaranteed to be valid if errno == EVMSERR, otherwise
* its contents can not be trusted. Unfortunately, Perl seems to check
* it on exit, so it when PL_statusvalue_vms is updated, vaxc$errno should
* be updated also.
*/
# include <stsdef.h>
# include <ssdef.h>
/* Presume this because if VMS changes it, it will require a new
* set of APIs for waiting on children for binary compatibility.
*/
# define child_offset_bits (8)
# ifndef C_FAC_POSIX
# define C_FAC_POSIX 0x35A000
# endif
/* STATUS_EXIT - validates and returns a NATIVE exit status code for the
* platform from the existing UNIX or Native status values.
*/
# define STATUS_EXIT \
(((I32)PL_statusvalue_vms == -1 ? SS$_ABORT : PL_statusvalue_vms) | \
(VMSISH_HUSHED ? STS$M_INHIB_MSG : 0))
/* STATUS_NATIVE_CHILD_SET - Calculate UNIX status that matches the child
* exit code and shifts the UNIX value over the correct number of bits to
* be a child status. Usually the number of bits is 8, but that could be
* platform dependent. The NATIVE status code is presumed to have either
* from a child process.
*/
/* This is complicated. The child processes return a true native VMS
status which must be saved. But there is an assumption in Perl that
the UNIX child status has some relationship to errno values, so
Perl tries to translate it to text in some of the tests.
In order to get the string translation correct, for the error, errno
must be EVMSERR, but that generates a different text message
than what the test programs are expecting. So an errno value must
be derived from the native status value when an error occurs.
That will hide the true native status message. With this version of
perl, the true native child status can always be retrieved so that
is not a problem. But in this case, Pl_statusvalue and errno may
have different values in them.
*/
# define STATUS_NATIVE_CHILD_SET(n) \
STMT_START { \
I32 evalue = (I32)n; \
if (evalue == EVMSERR) { \
PL_statusvalue_vms = vaxc$errno; \
PL_statusvalue = evalue; \
} else { \
PL_statusvalue_vms = evalue; \
if (evalue == -1) { \
PL_statusvalue = -1; \
PL_statusvalue_vms = SS$_ABORT; /* Should not happen */ \
} else \
PL_statusvalue = Perl_vms_status_to_unix(evalue, 1); \
set_vaxc_errno(evalue); \
if ((PL_statusvalue_vms & C_FAC_POSIX) == C_FAC_POSIX) \
set_errno(EVMSERR); \
else set_errno(Perl_vms_status_to_unix(evalue, 0)); \
PL_statusvalue = PL_statusvalue << child_offset_bits; \
} \
} STMT_END
# ifdef VMSISH_STATUS
# define STATUS_CURRENT (VMSISH_STATUS ? STATUS_NATIVE : STATUS_UNIX)
# else
# define STATUS_CURRENT STATUS_UNIX
# endif
/* STATUS_UNIX_SET - takes a UNIX/POSIX errno value and attempts to update
* the NATIVE status to an equivalent value. Can not be used to translate
* exit code values as exit code values are not guaranteed to have any
* relationship at all to errno values.
* This is used when Perl is forcing errno to have a specific value.
*/
# define STATUS_UNIX_SET(n) \
STMT_START { \
I32 evalue = (I32)n; \
PL_statusvalue = evalue; \
if (PL_statusvalue != -1) { \
if (PL_statusvalue != EVMSERR) { \
PL_statusvalue &= 0xFFFF; \
if (MY_POSIX_EXIT) \
PL_statusvalue_vms=PL_statusvalue ? SS$_ABORT : SS$_NORMAL;\
else PL_statusvalue_vms = Perl_unix_status_to_vms(evalue); \
} \
else { \
PL_statusvalue_vms = vaxc$errno; \
} \
} \
else PL_statusvalue_vms = SS$_ABORT; \
set_vaxc_errno(PL_statusvalue_vms); \
} STMT_END
/* STATUS_UNIX_EXIT_SET - Takes a UNIX/POSIX exit code and sets
* the NATIVE error status based on it.
*
* When in the default mode to comply with the Perl VMS documentation,
* 0 is a success and any other code sets the NATIVE status to a failure
* code of SS$_ABORT.
*
* In the new POSIX EXIT mode, native status will be set so that the
* actual exit code will can be retrieved by the calling program or
* shell.
*
* If the exit code is not clearly a UNIX parent or child exit status,
* it will be passed through as a VMS status.
*/
# define STATUS_UNIX_EXIT_SET(n) \
STMT_START { \
I32 evalue = (I32)n; \
PL_statusvalue = evalue; \
if (MY_POSIX_EXIT) { \
if (evalue <= 0xFF00) { \
if (evalue > 0xFF) \
evalue = (evalue >> child_offset_bits) & 0xFF; \
PL_statusvalue_vms = \
(C_FAC_POSIX | (evalue << 3 ) | \
((evalue == 1) ? (STS$K_ERROR | STS$M_INHIB_MSG) : 1)); \
} else /* forgive them Perl, for they have sinned */ \
PL_statusvalue_vms = evalue; \
} else { \
if (evalue == 0) \
PL_statusvalue_vms = SS$_NORMAL; \
else if (evalue <= 0xFF00) \
PL_statusvalue_vms = SS$_ABORT; \
else { /* forgive them Perl, for they have sinned */ \
if (evalue != EVMSERR) PL_statusvalue_vms = evalue; \
else PL_statusvalue_vms = vaxc$errno; \
/* And obviously used a VMS status value instead of UNIX */ \
PL_statusvalue = EVMSERR; \
} \
set_vaxc_errno(PL_statusvalue_vms); \
} \
} STMT_END
/* STATUS_EXIT_SET - Takes a NATIVE/UNIX/POSIX exit code
* and sets the NATIVE error status based on it. This special case
* is needed to maintain compatibility with past VMS behavior.
*
* In the default mode on VMS, this number is passed through as
* both the NATIVE and UNIX status. Which makes it different
* that the STATUS_UNIX_EXIT_SET.
*
* In the new POSIX EXIT mode, native status will be set so that the
* actual exit code will can be retrieved by the calling program or
* shell.
*
* A POSIX exit code is from 0 to 255. If the exit code is higher
* than this, it needs to be assumed that it is a VMS exit code and
* passed through.
*/
# define STATUS_EXIT_SET(n) \
STMT_START { \
I32 evalue = (I32)n; \
PL_statusvalue = evalue; \
if (MY_POSIX_EXIT) \
if (evalue > 255) PL_statusvalue_vms = evalue; else { \
PL_statusvalue_vms = \
(C_FAC_POSIX | (evalue << 3 ) | \
((evalue == 1) ? (STS$K_ERROR | STS$M_INHIB_MSG) : 1));} \
else \
PL_statusvalue_vms = evalue ? evalue : SS$_NORMAL; \
set_vaxc_errno(PL_statusvalue_vms); \
} STMT_END
/* This macro forces a success status */
# define STATUS_ALL_SUCCESS \
(PL_statusvalue = 0, PL_statusvalue_vms = SS$_NORMAL)
/* This macro forces a failure status */
# define STATUS_ALL_FAILURE (PL_statusvalue = 1, \
vaxc$errno = PL_statusvalue_vms = MY_POSIX_EXIT ? \
(C_FAC_POSIX | (1 << 3) | STS$K_ERROR | STS$M_INHIB_MSG) : SS$_ABORT)
#elif defined(__amigaos4__)
/* A somewhat experimental attempt to simulate posix return code values */
# define STATUS_NATIVE PL_statusvalue_posix
# define STATUS_NATIVE_CHILD_SET(n) \
STMT_START { \
PL_statusvalue_posix = (n); \
if (PL_statusvalue_posix < 0) { \
PL_statusvalue = -1; \
} \
else { \
PL_statusvalue = n << 8; \
} \
} STMT_END
# define STATUS_UNIX_SET(n) \
STMT_START { \
PL_statusvalue = (n); \
if (PL_statusvalue != -1) \
PL_statusvalue &= 0xFFFF; \
} STMT_END
# define STATUS_UNIX_EXIT_SET(n) STATUS_UNIX_SET(n)
# define STATUS_EXIT_SET(n) STATUS_UNIX_SET(n)
# define STATUS_CURRENT STATUS_UNIX
# define STATUS_EXIT STATUS_UNIX
# define STATUS_ALL_SUCCESS (PL_statusvalue = 0, PL_statusvalue_posix = 0)
# define STATUS_ALL_FAILURE (PL_statusvalue = 1, PL_statusvalue_posix = 1)
#else
# define STATUS_NATIVE PL_statusvalue_posix
# if defined(WCOREDUMP)
# define STATUS_NATIVE_CHILD_SET(n) \
STMT_START { \
PL_statusvalue_posix = (n); \
if (PL_statusvalue_posix == -1) \
PL_statusvalue = -1; \
else { \
PL_statusvalue = \
(WIFEXITED(PL_statusvalue_posix) ? (WEXITSTATUS(PL_statusvalue_posix) << 8) : 0) | \
(WIFSIGNALED(PL_statusvalue_posix) ? (WTERMSIG(PL_statusvalue_posix) & 0x7F) : 0) | \
(WIFSIGNALED(PL_statusvalue_posix) && WCOREDUMP(PL_statusvalue_posix) ? 0x80 : 0); \
} \
} STMT_END
# elif defined(WIFEXITED)
# define STATUS_NATIVE_CHILD_SET(n) \
STMT_START { \
PL_statusvalue_posix = (n); \
if (PL_statusvalue_posix == -1) \
PL_statusvalue = -1; \
else { \
PL_statusvalue = \
(WIFEXITED(PL_statusvalue_posix) ? (WEXITSTATUS(PL_statusvalue_posix) << 8) : 0) | \
(WIFSIGNALED(PL_statusvalue_posix) ? (WTERMSIG(PL_statusvalue_posix) & 0x7F) : 0); \
} \
} STMT_END
# else
# define STATUS_NATIVE_CHILD_SET(n) \
STMT_START { \
PL_statusvalue_posix = (n); \
if (PL_statusvalue_posix == -1) \
PL_statusvalue = -1; \
else { \
PL_statusvalue = \
PL_statusvalue_posix & 0xFFFF; \
} \
} STMT_END
# endif
# define STATUS_UNIX_SET(n) \
STMT_START { \
PL_statusvalue = (n); \
if (PL_statusvalue != -1) \
PL_statusvalue &= 0xFFFF; \
} STMT_END
# define STATUS_UNIX_EXIT_SET(n) STATUS_UNIX_SET(n)
# define STATUS_EXIT_SET(n) STATUS_UNIX_SET(n)
# define STATUS_CURRENT STATUS_UNIX
# define STATUS_EXIT STATUS_UNIX
# define STATUS_ALL_SUCCESS (PL_statusvalue = 0, PL_statusvalue_posix = 0)
# define STATUS_ALL_FAILURE (PL_statusvalue = 1, PL_statusvalue_posix = 1)
#endif
/* flags in PL_exit_flags for nature of exit() */
#define PERL_EXIT_EXPECTED 0x01
#define PERL_EXIT_DESTRUCT_END 0x02 /* Run END in perl_destruct */
#define PERL_EXIT_WARN 0x04 /* Warn if Perl_my_exit() or Perl_my_failure_exit() called */
#define PERL_EXIT_ABORT 0x08 /* Call abort() if Perl_my_exit() or Perl_my_failure_exit() called */
#ifndef PERL_CORE
/* format to use for version numbers in file/directory names */
/* XXX move to Configure? */
/* This was only ever used for the current version, and that can be done at
compile time, as PERL_FS_VERSION, so should we just delete it? */
# ifndef PERL_FS_VER_FMT
# define PERL_FS_VER_FMT "%d.%d.%d"
# endif
#endif
#ifndef PERL_FS_VERSION
# define PERL_FS_VERSION PERL_VERSION_STRING
#endif
/* This defines a way to flush all output buffers. This may be a
* performance issue, so we allow people to disable it. Also, if
* we are using stdio, there are broken implementations of fflush(NULL)
* out there, Solaris being the most prominent.
*/
#ifndef PERL_FLUSHALL_FOR_CHILD
# if defined(USE_PERLIO) || defined(FFLUSH_NULL)
# define PERL_FLUSHALL_FOR_CHILD PerlIO_flush((PerlIO*)NULL)
# elif defined(FFLUSH_ALL)
# define PERL_FLUSHALL_FOR_CHILD my_fflush_all()
# else
# define PERL_FLUSHALL_FOR_CHILD NOOP
# endif
#endif
#ifndef PERL_WAIT_FOR_CHILDREN
# define PERL_WAIT_FOR_CHILDREN NOOP
#endif
/* the traditional thread-unsafe notion of "current interpreter". */
#ifndef PERL_SET_INTERP
# define PERL_SET_INTERP(i) (PL_curinterp = (PerlInterpreter*)(i))
#endif
#ifndef PERL_GET_INTERP
# define PERL_GET_INTERP (PL_curinterp)
#endif
#if defined(PERL_IMPLICIT_CONTEXT) && !defined(PERL_GET_THX)
# ifdef MULTIPLICITY
# define PERL_GET_THX ((PerlInterpreter *)PERL_GET_CONTEXT)
# endif
# define PERL_SET_THX(t) PERL_SET_CONTEXT(t)
#endif
/*
This replaces the previous %_ "hack" by the "%p" hacks.
All that is required is that the perl source does not
use "%-p" or "%-<number>p" or "%<number>p" formats.
These formats will still work in perl code.
See comments in sv.c for further details.
<NAME> 2005-07-14
No longer use %1p for VDf = %vd. RMB 2007-10-19
*/
#ifndef SVf_
# define SVf_(n) "-" STRINGIFY(n) "p"
#endif
#ifndef SVf
# define SVf "-p"
#endif
#ifndef SVf32
# define SVf32 SVf_(32)
#endif
#ifndef SVf256
# define SVf256 SVf_(256)
#endif
#define SVfARG(p) ((void*)(p))
#ifndef HEKf
# define HEKf "2p"
#endif
/* Not ideal, but we cannot easily include a number in an already-numeric
* format sequence. */
#ifndef HEKf256
# define HEKf256 "3p"
#endif
#define HEKfARG(p) ((void*)(p))
/*
=for apidoc Amnh||UTF8f
=for apidoc Amh||UTF8fARG|bool is_utf8|Size_t byte_len|char *str
=cut
* %4p is a custom format
*/
#ifndef UTF8f
# define UTF8f "d%" UVuf "%4p"
#endif
#define UTF8fARG(u,l,p) (int)cBOOL(u), (UV)(l), (void*)(p)
#define PNf UTF8f
#define PNfARG(pn) (int)1, (UV)PadnameLEN(pn), (void *)PadnamePV(pn)
#ifdef PERL_CORE
/* not used; but needed for backward compatibility with XS code? - RMB */
# undef UVf
#elif !defined(UVf)
# define UVf UVuf
#endif
#if !defined(DEBUGGING) && !defined(NDEBUG)
# define NDEBUG 1
#endif
#include <assert.h>
/* For functions that are marked as __attribute__noreturn__, it's not
appropriate to call return. In either case, include the lint directive.
*/
#ifdef HASATTRIBUTE_NORETURN
# define NORETURN_FUNCTION_END NOT_REACHED;
#else
# define NORETURN_FUNCTION_END NOT_REACHED; return 0
#endif
#ifdef HAS_BUILTIN_EXPECT
# define EXPECT(expr,val) __builtin_expect(expr,val)
#else
# define EXPECT(expr,val) (expr)
#endif
/*
=head1 Miscellaneous Functions
=for apidoc AmU|bool|LIKELY|const bool expr
Returns the input unchanged, but at the same time it gives a branch prediction
hint to the compiler that this condition is likely to be true.
=for apidoc AmU|bool|UNLIKELY|const bool expr
Returns the input unchanged, but at the same time it gives a branch prediction
hint to the compiler that this condition is likely to be false.
=cut
*/
#define LIKELY(cond) EXPECT(cBOOL(cond),TRUE)
#define UNLIKELY(cond) EXPECT(cBOOL(cond),FALSE)
#ifdef HAS_BUILTIN_CHOOSE_EXPR
/* placeholder */
#endif
/* STATIC_ASSERT_DECL/STATIC_ASSERT_STMT are like assert(), but for compile
time invariants. That is, their argument must be a constant expression that
can be verified by the compiler. This expression can contain anything that's
known to the compiler, e.g. #define constants, enums, or sizeof (...). If
the expression evaluates to 0, compilation fails.
Because they generate no runtime code (i.e. their use is "free"), they're
always active, even under non-DEBUGGING builds.
STATIC_ASSERT_DECL expands to a declaration and is suitable for use at
file scope (outside of any function).
STATIC_ASSERT_STMT expands to a statement and is suitable for use inside a
function.
*/
#if (! defined(__IBMC__) || __IBMC__ >= 1210) \
&& (( defined(static_assert) && ( defined(_ISOC11_SOURCE) \
|| (__STDC_VERSION__ - 0) >= 201101L)) \
|| (defined(__cplusplus) && __cplusplus >= 201103L))
/* XXX static_assert is a macro defined in <assert.h> in C11 or a compiler
builtin in C++11. But IBM XL C V11 does not support _Static_assert, no
matter what <assert.h> says.
*/
# define STATIC_ASSERT_DECL(COND) static_assert(COND, #COND)
#else
/* We use a bit-field instead of an array because gcc accepts
'typedef char x[n]' where n is not a compile-time constant.
We want to enforce constantness.
*/
# define STATIC_ASSERT_2(COND, SUFFIX) \
typedef struct { \
unsigned int _static_assertion_failed_##SUFFIX : (COND) ? 1 : -1; \
} _static_assertion_failed_##SUFFIX PERL_UNUSED_DECL
# define STATIC_ASSERT_1(COND, SUFFIX) STATIC_ASSERT_2(COND, SUFFIX)
# define STATIC_ASSERT_DECL(COND) STATIC_ASSERT_1(COND, __LINE__)
#endif
/* We need this wrapper even in C11 because 'case X: static_assert(...);' is an
error (static_assert is a declaration, and only statements can have labels).
*/
#define STATIC_ASSERT_STMT(COND) STMT_START { STATIC_ASSERT_DECL(COND); } STMT_END
#ifndef __has_builtin
# define __has_builtin(x) 0 /* not a clang style compiler */
#endif
/* ASSUME is like assert(), but it has a benefit in a release build. It is a
hint to a compiler about a statement of fact in a function call free
expression, which allows the compiler to generate better machine code.
In a debug build, ASSUME(x) is a synonym for assert(x). ASSUME(0) means
the control path is unreachable. In a for loop, ASSUME can be used to hint
that a loop will run at least X times. ASSUME is based off MSVC's __assume
intrinsic function, see its documents for more details.
*/
#ifndef DEBUGGING
# if __has_builtin(__builtin_unreachable) \
|| (__GNUC__ == 4 && __GNUC_MINOR__ >= 5 || __GNUC__ > 4) /* 4.5 -> */
# define ASSUME(x) ((x) ? (void) 0 : __builtin_unreachable())
# elif defined(_MSC_VER)
# define ASSUME(x) __assume(x)
# elif defined(__ARMCC_VERSION) /* untested */
# define ASSUME(x) __promise(x)
# else
/* a random compiler might define assert to its own special optimization token
so pass it through to C lib as a last resort */
# define ASSUME(x) assert(x)
# endif
#else
# define ASSUME(x) assert(x)
#endif
#if defined(__sun) /* ASSUME() generates warnings on Solaris */
# define NOT_REACHED
#elif defined(DEBUGGING) && (__has_builtin(__builtin_unreachable) \
|| (__GNUC__ == 4 && __GNUC_MINOR__ >= 5 || __GNUC__ > 4)) /* 4.5 -> */
# define NOT_REACHED STMT_START { ASSUME(!"UNREACHABLE"); __builtin_unreachable(); } STMT_END
#else
# define NOT_REACHED ASSUME(!"UNREACHABLE")
#endif
/* Some unistd.h's give a prototype for pause() even though
HAS_PAUSE ends up undefined. This causes the #define
below to be rejected by the compiler. Sigh.
*/
#ifdef HAS_PAUSE
#define Pause pause
#else
#define Pause() sleep((32767<<16)+32767)
#endif
#ifndef IOCPARM_LEN
# ifdef IOCPARM_MASK
/* on BSDish systems we're safe */
# define IOCPARM_LEN(x) (((x) >> 16) & IOCPARM_MASK)
# elif defined(_IOC_SIZE) && defined(__GLIBC__)
/* on Linux systems we're safe; except when we're not [perl #38223] */
# define IOCPARM_LEN(x) (_IOC_SIZE(x) < 256 ? 256 : _IOC_SIZE(x))
# else
/* otherwise guess at what's safe */
# define IOCPARM_LEN(x) 256
# endif
#endif
#if defined(__CYGWIN__)
/* USEMYBINMODE
* This symbol, if defined, indicates that the program should
* use the routine my_binmode(FILE *fp, char iotype, int mode) to insure
* that a file is in "binary" mode -- that is, that no translation
* of bytes occurs on read or write operations.
*/
# define USEMYBINMODE /**/
# include <io.h> /* for setmode() prototype */
# define my_binmode(fp, iotype, mode) \
cBOOL(PerlLIO_setmode(fileno(fp), mode) != -1)
#endif
#ifdef __CYGWIN__
void init_os_extras(void);
#endif
#ifdef UNION_ANY_DEFINITION
UNION_ANY_DEFINITION;
#else
union any {
void* any_ptr;
SV* any_sv;
SV** any_svp;
GV* any_gv;
AV* any_av;
HV* any_hv;
OP* any_op;
char* any_pv;
char** any_pvp;
I32 any_i32;
U32 any_u32;
IV any_iv;
UV any_uv;
long any_long;
bool any_bool;
void (*any_dptr) (void*);
void (*any_dxptr) (pTHX_ void*);
};
#endif
typedef I32 (*filter_t) (pTHX_ int, SV *, int);
#define FILTER_READ(idx, sv, len) filter_read(idx, sv, len)
#define FILTER_DATA(idx) \
(PL_parser ? AvARRAY(PL_parser->rsfp_filters)[idx] : NULL)
#define FILTER_ISREADER(idx) \
(PL_parser && PL_parser->rsfp_filters \
&& idx >= AvFILLp(PL_parser->rsfp_filters))
#define PERL_FILTER_EXISTS(i) \
(PL_parser && PL_parser->rsfp_filters \
&& (i) <= av_tindex(PL_parser->rsfp_filters))
#if defined(_AIX) && !defined(_AIX43)
#if defined(USE_REENTRANT) || defined(_REENTRANT) || defined(_THREAD_SAFE)
/* We cannot include <crypt.h> to get the struct crypt_data
* because of setkey prototype problems when threading */
typedef struct crypt_data { /* straight from /usr/include/crypt.h */
/* From OSF, Not needed in AIX
char C[28], D[28];
*/
char E[48];
char KS[16][48];
char block[66];
char iobuf[16];
} CRYPTD;
#endif /* threading */
#endif /* AIX */
#ifndef PERL_CALLCONV
# ifdef __cplusplus
# define PERL_CALLCONV extern "C"
# else
# define PERL_CALLCONV
# endif
#endif
#ifndef PERL_CALLCONV_NO_RET
# define PERL_CALLCONV_NO_RET PERL_CALLCONV
#endif
/* PERL_STATIC_NO_RET is supposed to be equivalent to STATIC on builds that
dont have a noreturn as a declaration specifier
*/
#ifndef PERL_STATIC_NO_RET
# define PERL_STATIC_NO_RET STATIC
#endif
/* PERL_STATIC_NO_RET is supposed to be equivalent to PERL_STATIC_INLINE on
builds that dont have a noreturn as a declaration specifier
*/
#ifndef PERL_STATIC_INLINE_NO_RET
# define PERL_STATIC_INLINE_NO_RET PERL_STATIC_INLINE
#endif
#ifndef PERL_STATIC_FORCE_INLINE
# define PERL_STATIC_FORCE_INLINE PERL_STATIC_INLINE
#endif
#ifndef PERL_STATIC_FORCE_INLINE_NO_RET
# define PERL_STATIC_FORCE_INLINE_NO_RET PERL_STATIC_INLINE
#endif
/* Must be included before iperlsys */
#include <TargetConditionals.h>
#if TARGET_OS_IPHONE
#include "ios_error.h"
#define isatty ios_isatty
#endif
#if !defined(OS2)
# include "iperlsys.h"
#endif
#ifdef __LIBCATAMOUNT__
#undef HAS_PASSWD /* unixish.h but not unixish enough. */
#undef HAS_GROUP
#define FAKE_BIT_BUCKET
#endif
/* [perl #22371] Algorimic Complexity Attack on Perl 5.6.1, 5.8.0.
* Note that the USE_HASH_SEED and similar defines are *NOT* defined by
* Configure, despite their names being similar to other defines like
* USE_ITHREADS. Configure in fact knows nothing about the randomised
* hashes. Therefore to enable/disable the hash randomisation defines
* use the Configure -Accflags=... instead. */
#if !defined(NO_HASH_SEED) && !defined(USE_HASH_SEED)
# define USE_HASH_SEED
#endif
#include "perly.h"
/* macros to define bit-fields in structs. */
#ifndef PERL_BITFIELD8
# define PERL_BITFIELD8 U8
#endif
#ifndef PERL_BITFIELD16
# define PERL_BITFIELD16 U16
#endif
#ifndef PERL_BITFIELD32
# define PERL_BITFIELD32 U32
#endif
#include "sv.h"
#include "regexp.h"
#include "util.h"
#include "form.h"
#include "gv.h"
#include "pad.h"
#include "cv.h"
#include "opnames.h"
#include "op.h"
#include "hv.h"
#include "cop.h"
#include "av.h"
#include "mg.h"
#include "scope.h"
#include "warnings.h"
#include "utf8.h"
/* these would be in doio.h if there was such a file */
#define my_stat() my_stat_flags(SV_GMAGIC)
#define my_lstat() my_lstat_flags(SV_GMAGIC)
/* defined in sv.c, but also used in [ach]v.c */
#undef _XPV_HEAD
#undef _XPVMG_HEAD
#undef _XPVCV_COMMON
#include "parser.h"
typedef struct magic_state MGS; /* struct magic_state defined in mg.c */
#if defined(PERL_IN_REGCOMP_C) || defined(PERL_IN_REGEXEC_C)
/* These have to be predeclared, as they are used in proto.h which is #included
* before their definitions in regcomp.h. */
struct scan_data_t;
typedef struct regnode_charclass regnode_charclass;
/* A hopefully less confusing name. The sub-classes are all Posix classes only
* used under /l matching */
typedef struct regnode_charclass_posixl regnode_charclass_class;
typedef struct regnode_charclass_posixl regnode_charclass_posixl;
typedef struct regnode_ssc regnode_ssc;
typedef struct RExC_state_t RExC_state_t;
struct _reg_trie_data;
#endif
struct ptr_tbl_ent {
struct ptr_tbl_ent* next;
const void* oldval;
void* newval;
};
struct ptr_tbl {
struct ptr_tbl_ent** tbl_ary;
UV tbl_max;
UV tbl_items;
struct ptr_tbl_arena *tbl_arena;
struct ptr_tbl_ent *tbl_arena_next;
struct ptr_tbl_ent *tbl_arena_end;
};
#if defined(htonl) && !defined(HAS_HTONL)
#define HAS_HTONL
#endif
#if defined(htons) && !defined(HAS_HTONS)
#define HAS_HTONS
#endif
#if defined(ntohl) && !defined(HAS_NTOHL)
#define HAS_NTOHL
#endif
#if defined(ntohs) && !defined(HAS_NTOHS)
#define HAS_NTOHS
#endif
#ifndef HAS_HTONL
#define HAS_HTONS
#define HAS_HTONL
#define HAS_NTOHS
#define HAS_NTOHL
# if (BYTEORDER & 0xffff) == 0x4321
/* Big endian system, so ntohl, ntohs, htonl and htons do not need to
re-order their values. However, to behave identically to the alternative
implementations, they should truncate to the correct size. */
# define ntohl(x) ((x)&0xFFFFFFFF)
# define htonl(x) ntohl(x)
# define ntohs(x) ((x)&0xFFFF)
# define htons(x) ntohs(x)
# elif BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
/* Note that we can't straight out declare our own htonl and htons because
the Win32 build process forcibly undefines HAS_HTONL etc for its miniperl,
to avoid the overhead of initialising the socket subsystem, but the headers
that *declare* the various functions are still seen. If we declare our own
htonl etc they will clash with the declarations in the Win32 headers. */
PERL_STATIC_INLINE U32
my_swap32(const U32 x) {
return ((x & 0xFF) << 24) | ((x >> 24) & 0xFF)
| ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8);
}
PERL_STATIC_INLINE U16
my_swap16(const U16 x) {
return ((x & 0xFF) << 8) | ((x >> 8) & 0xFF);
}
# define htonl(x) my_swap32(x)
# define ntohl(x) my_swap32(x)
# define ntohs(x) my_swap16(x)
# define htons(x) my_swap16(x)
# else
# error "Unsupported byteorder"
/* The C pre-processor doesn't let us return the value of BYTEORDER as part of
the error message. Please check the value of the macro BYTEORDER, as defined
in config.h. The values of BYTEORDER we expect are
big endian little endian
32 bit 0x4321 0x1234
64 bit 0x87654321 0x12345678
If you have a system with a different byte order, please see
pod/perlhack.pod for how to submit a patch to add supporting code.
*/
# endif
#endif
/*
* Little-endian byte order functions - 'v' for 'VAX', or 'reVerse'.
* -DWS
*/
#if BYTEORDER == 0x1234 || BYTEORDER == 0x12345678
/* Little endian system, so vtohl, vtohs, htovl and htovs do not need to
re-order their values. However, to behave identically to the alternative
implementations, they should truncate to the correct size. */
# define vtohl(x) ((x)&0xFFFFFFFF)
# define vtohs(x) ((x)&0xFFFF)
# define htovl(x) vtohl(x)
# define htovs(x) vtohs(x)
#elif BYTEORDER == 0x4321 || BYTEORDER == 0x87654321
# define vtohl(x) ((((x)&0xFF)<<24) \
+(((x)>>24)&0xFF) \
+(((x)&0x0000FF00)<<8) \
+(((x)&0x00FF0000)>>8) )
# define vtohs(x) ((((x)&0xFF)<<8) + (((x)>>8)&0xFF))
# define htovl(x) vtohl(x)
# define htovs(x) vtohs(x)
#else
# error "Unsupported byteorder"
/* If you have need for current perl on PDP-11 or similar, and can help test
that blead keeps working on a mixed-endian system, then see
pod/perlhack.pod for how to submit patches to things working again. */
#endif
/* *MAX Plus 1. A floating point value.
Hopefully expressed in a way that dodgy floating point can't mess up.
>> 2 rather than 1, so that value is safely less than I32_MAX after 1
is added to it
May find that some broken compiler will want the value cast to I32.
[after the shift, as signed >> may not be as secure as unsigned >>]
*/
#define I32_MAX_P1 (2.0 * (1 + (((U32)I32_MAX) >> 1)))
#define U32_MAX_P1 (4.0 * (1 + ((U32_MAX) >> 2)))
/* For compilers that can't correctly cast NVs over 0x7FFFFFFF (or
0x7FFFFFFFFFFFFFFF) to an unsigned integer. In the future, sizeof(UV)
may be greater than sizeof(IV), so don't assume that half max UV is max IV.
*/
#define U32_MAX_P1_HALF (2.0 * (1 + ((U32_MAX) >> 2)))
#define UV_MAX_P1 (4.0 * (1 + ((UV_MAX) >> 2)))
#define IV_MAX_P1 (2.0 * (1 + (((UV)IV_MAX) >> 1)))
#define UV_MAX_P1_HALF (2.0 * (1 + ((UV_MAX) >> 2)))
/* This may look like unnecessary jumping through hoops, but converting
out of range floating point values to integers *is* undefined behaviour,
and it is starting to bite.
*/
#ifndef CAST_INLINE
#define I_32(what) (cast_i32((NV)(what)))
#define U_32(what) (cast_ulong((NV)(what)))
#define I_V(what) (cast_iv((NV)(what)))
#define U_V(what) (cast_uv((NV)(what)))
#else
#define I_32(n) ((n) < I32_MAX_P1 ? ((n) < I32_MIN ? I32_MIN : (I32) (n)) \
: ((n) < U32_MAX_P1 ? (I32)(U32) (n) \
: ((n) > 0 ? (I32) U32_MAX : 0 /* NaN */)))
#define U_32(n) ((n) < 0.0 ? ((n) < I32_MIN ? (UV) I32_MIN : (U32)(I32) (n)) \
: ((n) < U32_MAX_P1 ? (U32) (n) \
: ((n) > 0 ? U32_MAX : 0 /* NaN */)))
#define I_V(n) (LIKELY((n) < IV_MAX_P1) ? (UNLIKELY((n) < IV_MIN) ? IV_MIN : (IV) (n)) \
: (LIKELY((n) < UV_MAX_P1) ? (IV)(UV) (n) \
: ((n) > 0 ? (IV)UV_MAX : 0 /* NaN */)))
#define U_V(n) ((n) < 0.0 ? (UNLIKELY((n) < IV_MIN) ? (UV) IV_MIN : (UV)(IV) (n)) \
: (LIKELY((n) < UV_MAX_P1) ? (UV) (n) \
: ((n) > 0 ? UV_MAX : 0 /* NaN */)))
#endif
#define U_S(what) ((U16)U_32(what))
#define U_I(what) ((unsigned int)U_32(what))
#define U_L(what) U_32(what)
#ifdef HAS_SIGNBIT
# ifndef Perl_signbit
# define Perl_signbit signbit
# endif
#endif
/* These do not care about the fractional part, only about the range. */
#define NV_WITHIN_IV(nv) (I_V(nv) >= IV_MIN && I_V(nv) <= IV_MAX)
#define NV_WITHIN_UV(nv) ((nv)>=0.0 && U_V(nv) >= UV_MIN && U_V(nv) <= UV_MAX)
/* Used with UV/IV arguments: */
/* XXXX: need to speed it up */
#define CLUMP_2UV(iv) ((iv) < 0 ? 0 : (UV)(iv))
#define CLUMP_2IV(uv) ((uv) > (UV)IV_MAX ? IV_MAX : (IV)(uv))
#ifndef MAXSYSFD
# define MAXSYSFD 2
#endif
#ifndef __cplusplus
#if !(defined(WIN32) || defined(SYMBIAN))
Uid_t getuid (void);
Uid_t geteuid (void);
Gid_t getgid (void);
Gid_t getegid (void);
#endif
#endif
#ifndef Perl_debug_log
# define Perl_debug_log PerlIO_stderr()
#endif
#ifndef Perl_error_log
# define Perl_error_log (PL_stderrgv \
&& isGV(PL_stderrgv) \
&& GvIOp(PL_stderrgv) \
&& IoOFP(GvIOp(PL_stderrgv)) \
? IoOFP(GvIOp(PL_stderrgv)) \
: PerlIO_stderr())
#endif
#define DEBUG_p_FLAG 0x00000001 /* 1 */
#define DEBUG_s_FLAG 0x00000002 /* 2 */
#define DEBUG_l_FLAG 0x00000004 /* 4 */
#define DEBUG_t_FLAG 0x00000008 /* 8 */
#define DEBUG_o_FLAG 0x00000010 /* 16 */
#define DEBUG_c_FLAG 0x00000020 /* 32 */
#define DEBUG_P_FLAG 0x00000040 /* 64 */
#define DEBUG_m_FLAG 0x00000080 /* 128 */
#define DEBUG_f_FLAG 0x00000100 /* 256 */
#define DEBUG_r_FLAG 0x00000200 /* 512 */
#define DEBUG_x_FLAG 0x00000400 /* 1024 */
#define DEBUG_u_FLAG 0x00000800 /* 2048 */
/* U is reserved for Unofficial, exploratory hacking */
#define DEBUG_U_FLAG 0x00001000 /* 4096 */
/* spare 8192 */
#define DEBUG_X_FLAG 0x00004000 /* 16384 */
#define DEBUG_D_FLAG 0x00008000 /* 32768 */
#define DEBUG_S_FLAG 0x00010000 /* 65536 */
#define DEBUG_T_FLAG 0x00020000 /* 131072 */
#define DEBUG_R_FLAG 0x00040000 /* 262144 */
#define DEBUG_J_FLAG 0x00080000 /* 524288 */
#define DEBUG_v_FLAG 0x00100000 /*1048576 */
#define DEBUG_C_FLAG 0x00200000 /*2097152 */
#define DEBUG_A_FLAG 0x00400000 /*4194304 */
#define DEBUG_q_FLAG 0x00800000 /*8388608 */
#define DEBUG_M_FLAG 0x01000000 /*16777216*/
#define DEBUG_B_FLAG 0x02000000 /*33554432*/
#define DEBUG_L_FLAG 0x04000000 /*67108864*/
#define DEBUG_i_FLAG 0x08000000 /*134217728*/
#define DEBUG_y_FLAG 0x10000000 /*268435456*/
#define DEBUG_MASK 0x1FFFEFFF /* mask of all the standard flags */
#define DEBUG_DB_RECURSE_FLAG 0x40000000
#define DEBUG_TOP_FLAG 0x80000000 /* -D was given --> PL_debug |= FLAG */
# define DEBUG_p_TEST_ UNLIKELY(PL_debug & DEBUG_p_FLAG)
# define DEBUG_s_TEST_ UNLIKELY(PL_debug & DEBUG_s_FLAG)
# define DEBUG_l_TEST_ UNLIKELY(PL_debug & DEBUG_l_FLAG)
# define DEBUG_t_TEST_ UNLIKELY(PL_debug & DEBUG_t_FLAG)
# define DEBUG_o_TEST_ UNLIKELY(PL_debug & DEBUG_o_FLAG)
# define DEBUG_c_TEST_ UNLIKELY(PL_debug & DEBUG_c_FLAG)
# define DEBUG_P_TEST_ UNLIKELY(PL_debug & DEBUG_P_FLAG)
# define DEBUG_m_TEST_ UNLIKELY(PL_debug & DEBUG_m_FLAG)
# define DEBUG_f_TEST_ UNLIKELY(PL_debug & DEBUG_f_FLAG)
# define DEBUG_r_TEST_ UNLIKELY(PL_debug & DEBUG_r_FLAG)
# define DEBUG_x_TEST_ UNLIKELY(PL_debug & DEBUG_x_FLAG)
# define DEBUG_u_TEST_ UNLIKELY(PL_debug & DEBUG_u_FLAG)
# define DEBUG_U_TEST_ UNLIKELY(PL_debug & DEBUG_U_FLAG)
# define DEBUG_X_TEST_ UNLIKELY(PL_debug & DEBUG_X_FLAG)
# define DEBUG_D_TEST_ UNLIKELY(PL_debug & DEBUG_D_FLAG)
# define DEBUG_S_TEST_ UNLIKELY(PL_debug & DEBUG_S_FLAG)
# define DEBUG_T_TEST_ UNLIKELY(PL_debug & DEBUG_T_FLAG)
# define DEBUG_R_TEST_ UNLIKELY(PL_debug & DEBUG_R_FLAG)
# define DEBUG_J_TEST_ UNLIKELY(PL_debug & DEBUG_J_FLAG)
# define DEBUG_v_TEST_ UNLIKELY(PL_debug & DEBUG_v_FLAG)
# define DEBUG_C_TEST_ UNLIKELY(PL_debug & DEBUG_C_FLAG)
# define DEBUG_A_TEST_ UNLIKELY(PL_debug & DEBUG_A_FLAG)
# define DEBUG_q_TEST_ UNLIKELY(PL_debug & DEBUG_q_FLAG)
# define DEBUG_M_TEST_ UNLIKELY(PL_debug & DEBUG_M_FLAG)
# define DEBUG_B_TEST_ UNLIKELY(PL_debug & DEBUG_B_FLAG)
# define DEBUG_L_TEST_ UNLIKELY(PL_debug & DEBUG_L_FLAG)
# define DEBUG_i_TEST_ UNLIKELY(PL_debug & DEBUG_i_FLAG)
# define DEBUG_y_TEST_ UNLIKELY(PL_debug & DEBUG_y_FLAG)
# define DEBUG_Xv_TEST_ (DEBUG_X_TEST_ && DEBUG_v_TEST_)
# define DEBUG_Uv_TEST_ (DEBUG_U_TEST_ && DEBUG_v_TEST_)
# define DEBUG_Pv_TEST_ (DEBUG_P_TEST_ && DEBUG_v_TEST_)
# define DEBUG_Lv_TEST_ (DEBUG_L_TEST_ && DEBUG_v_TEST_)
# define DEBUG_yv_TEST_ (DEBUG_y_TEST_ && DEBUG_v_TEST_)
#ifdef DEBUGGING
# define DEBUG_p_TEST DEBUG_p_TEST_
# define DEBUG_s_TEST DEBUG_s_TEST_
# define DEBUG_l_TEST DEBUG_l_TEST_
# define DEBUG_t_TEST DEBUG_t_TEST_
# define DEBUG_o_TEST DEBUG_o_TEST_
# define DEBUG_c_TEST DEBUG_c_TEST_
# define DEBUG_P_TEST DEBUG_P_TEST_
# define DEBUG_m_TEST DEBUG_m_TEST_
# define DEBUG_f_TEST DEBUG_f_TEST_
# define DEBUG_r_TEST DEBUG_r_TEST_
# define DEBUG_x_TEST DEBUG_x_TEST_
# define DEBUG_u_TEST DEBUG_u_TEST_
# define DEBUG_U_TEST DEBUG_U_TEST_
# define DEBUG_X_TEST DEBUG_X_TEST_
# define DEBUG_D_TEST DEBUG_D_TEST_
# define DEBUG_S_TEST DEBUG_S_TEST_
# define DEBUG_T_TEST DEBUG_T_TEST_
# define DEBUG_R_TEST DEBUG_R_TEST_
# define DEBUG_J_TEST DEBUG_J_TEST_
# define DEBUG_v_TEST DEBUG_v_TEST_
# define DEBUG_C_TEST DEBUG_C_TEST_
# define DEBUG_A_TEST DEBUG_A_TEST_
# define DEBUG_q_TEST DEBUG_q_TEST_
# define DEBUG_M_TEST DEBUG_M_TEST_
# define DEBUG_B_TEST DEBUG_B_TEST_
# define DEBUG_L_TEST DEBUG_L_TEST_
# define DEBUG_i_TEST DEBUG_i_TEST_
# define DEBUG_y_TEST DEBUG_y_TEST_
# define DEBUG_Xv_TEST DEBUG_Xv_TEST_
# define DEBUG_Uv_TEST DEBUG_Uv_TEST_
# define DEBUG_Pv_TEST DEBUG_Pv_TEST_
# define DEBUG_Lv_TEST DEBUG_Lv_TEST_
# define DEBUG_yv_TEST DEBUG_yv_TEST_
# define PERL_DEB(a) a
# define PERL_DEB2(a,b) a
# define PERL_DEBUG(a) if (PL_debug) a
# define DEBUG_p(a) if (DEBUG_p_TEST) a
# define DEBUG_s(a) if (DEBUG_s_TEST) a
# define DEBUG_l(a) if (DEBUG_l_TEST) a
# define DEBUG_t(a) if (DEBUG_t_TEST) a
# define DEBUG_o(a) if (DEBUG_o_TEST) a
# define DEBUG_c(a) if (DEBUG_c_TEST) a
# define DEBUG_P(a) if (DEBUG_P_TEST) a
/* Temporarily turn off memory debugging in case the a
* does memory allocation, either directly or indirectly. */
# define DEBUG_m(a) \
STMT_START { \
if (PERL_GET_INTERP) { \
dTHX; \
if (DEBUG_m_TEST) { \
PL_debug &= ~DEBUG_m_FLAG; \
a; \
PL_debug |= DEBUG_m_FLAG; \
} \
} \
} STMT_END
# define DEBUG__(t, a) \
STMT_START { \
if (t) STMT_START {a;} STMT_END; \
} STMT_END
# define DEBUG_f(a) DEBUG__(DEBUG_f_TEST, a)
/* For re_comp.c, re_exec.c, assume -Dr has been specified */
# ifdef PERL_EXT_RE_BUILD
# define DEBUG_r(a) STMT_START {a;} STMT_END
# else
# define DEBUG_r(a) DEBUG__(DEBUG_r_TEST, a)
# endif /* PERL_EXT_RE_BUILD */
# define DEBUG_x(a) DEBUG__(DEBUG_x_TEST, a)
# define DEBUG_u(a) DEBUG__(DEBUG_u_TEST, a)
# define DEBUG_U(a) DEBUG__(DEBUG_U_TEST, a)
# define DEBUG_X(a) DEBUG__(DEBUG_X_TEST, a)
# define DEBUG_D(a) DEBUG__(DEBUG_D_TEST, a)
# define DEBUG_Xv(a) DEBUG__(DEBUG_Xv_TEST, a)
# define DEBUG_Uv(a) DEBUG__(DEBUG_Uv_TEST, a)
# define DEBUG_Pv(a) DEBUG__(DEBUG_Pv_TEST, a)
# define DEBUG_Lv(a) DEBUG__(DEBUG_Lv_TEST, a)
# define DEBUG_yv(a) DEBUG__(DEBUG_yv_TEST, a)
# define DEBUG_S(a) DEBUG__(DEBUG_S_TEST, a)
# define DEBUG_T(a) DEBUG__(DEBUG_T_TEST, a)
# define DEBUG_R(a) DEBUG__(DEBUG_R_TEST, a)
# define DEBUG_v(a) DEBUG__(DEBUG_v_TEST, a)
# define DEBUG_C(a) DEBUG__(DEBUG_C_TEST, a)
# define DEBUG_A(a) DEBUG__(DEBUG_A_TEST, a)
# define DEBUG_q(a) DEBUG__(DEBUG_q_TEST, a)
# define DEBUG_M(a) DEBUG__(DEBUG_M_TEST, a)
# define DEBUG_B(a) DEBUG__(DEBUG_B_TEST, a)
# define DEBUG_L(a) DEBUG__(DEBUG_L_TEST, a)
# define DEBUG_i(a) DEBUG__(DEBUG_i_TEST, a)
# define DEBUG_y(a) DEBUG__(DEBUG_y_TEST, a)
#else /* ! DEBUGGING below */
# define DEBUG_p_TEST (0)
# define DEBUG_s_TEST (0)
# define DEBUG_l_TEST (0)
# define DEBUG_t_TEST (0)
# define DEBUG_o_TEST (0)
# define DEBUG_c_TEST (0)
# define DEBUG_P_TEST (0)
# define DEBUG_m_TEST (0)
# define DEBUG_f_TEST (0)
# define DEBUG_r_TEST (0)
# define DEBUG_x_TEST (0)
# define DEBUG_u_TEST (0)
# define DEBUG_U_TEST (0)
# define DEBUG_X_TEST (0)
# define DEBUG_D_TEST (0)
# define DEBUG_S_TEST (0)
# define DEBUG_T_TEST (0)
# define DEBUG_R_TEST (0)
# define DEBUG_J_TEST (0)
# define DEBUG_v_TEST (0)
# define DEBUG_C_TEST (0)
# define DEBUG_A_TEST (0)
# define DEBUG_q_TEST (0)
# define DEBUG_M_TEST (0)
# define DEBUG_B_TEST (0)
# define DEBUG_L_TEST (0)
# define DEBUG_i_TEST (0)
# define DEBUG_y_TEST (0)
# define DEBUG_Xv_TEST (0)
# define DEBUG_Uv_TEST (0)
# define DEBUG_Pv_TEST (0)
# define DEBUG_Lv_TEST (0)
# define DEBUG_yv_TEST (0)
# define PERL_DEB(a)
# define PERL_DEB2(a,b) b
# define PERL_DEBUG(a)
# define DEBUG_p(a)
# define DEBUG_s(a)
# define DEBUG_l(a)
# define DEBUG_t(a)
# define DEBUG_o(a)
# define DEBUG_c(a)
# define DEBUG_P(a)
# define DEBUG_m(a)
# define DEBUG_f(a)
# define DEBUG_r(a)
# define DEBUG_x(a)
# define DEBUG_u(a)
# define DEBUG_U(a)
# define DEBUG_X(a)
# define DEBUG_D(a)
# define DEBUG_S(a)
# define DEBUG_T(a)
# define DEBUG_R(a)
# define DEBUG_v(a)
# define DEBUG_C(a)
# define DEBUG_A(a)
# define DEBUG_q(a)
# define DEBUG_M(a)
# define DEBUG_B(a)
# define DEBUG_L(a)
# define DEBUG_i(a)
# define DEBUG_y(a)
# define DEBUG_Xv(a)
# define DEBUG_Uv(a)
# define DEBUG_Pv(a)
# define DEBUG_Lv(a)
# define DEBUG_yv(a)
#endif /* DEBUGGING */
#define DEBUG_SCOPE(where) \
DEBUG_l( \
Perl_deb(aTHX_ "%s scope %ld (savestack=%ld) at %s:%d\n", \
where, (long)PL_scopestack_ix, (long)PL_savestack_ix, \
__FILE__, __LINE__));
/* Keep the old croak based assert for those who want it, and as a fallback if
the platform is so heretically non-ANSI that it can't assert. */
#define Perl_assert(what) PERL_DEB2( \
((what) ? ((void) 0) : \
(Perl_croak_nocontext("Assertion %s failed: file \"" __FILE__ \
"\", line %d", STRINGIFY(what), __LINE__), \
(void) 0)), ((void)0))
/* assert() gets defined if DEBUGGING.
* If no DEBUGGING, the <assert.h> has not been included. */
#ifndef assert
# define assert(what) Perl_assert(what)
#endif
#ifdef DEBUGGING
# define assert_(what) assert(what),
#else
# define assert_(what)
#endif
struct ufuncs {
I32 (*uf_val)(pTHX_ IV, SV*);
I32 (*uf_set)(pTHX_ IV, SV*);
IV uf_index;
};
/* In pre-5.7-Perls the PERL_MAGIC_uvar magic didn't get the thread context.
* XS code wanting to be backward compatible can do something
* like the following:
#ifndef PERL_MG_UFUNC
#define PERL_MG_UFUNC(name,ix,sv) I32 name(IV ix, SV *sv)
#endif
static PERL_MG_UFUNC(foo_get, index, val)
{
sv_setsv(val, ...);
return TRUE;
}
-- <NAME>
*/
#ifndef PERL_MG_UFUNC
#define PERL_MG_UFUNC(name,ix,sv) I32 name(pTHX_ IV ix, SV *sv)
#endif
#include <math.h>
#ifdef __VMS
/* isfinite and others are here rather than in math.h as C99 stipulates */
# include <fp.h>
#endif
#ifndef __cplusplus
# if !defined(WIN32) && !defined(VMS)
#ifndef crypt
char *crypt (const char*, const char*);
#endif
# endif /* !WIN32 */
# ifndef WIN32
# ifndef getlogin
char *getlogin (void);
# endif
# endif /* !WIN32 */
#endif /* !__cplusplus */
/* Fixme on VMS. This needs to be a run-time, not build time options */
/* Also rename() is affected by this */
#ifdef UNLINK_ALL_VERSIONS /* Currently only makes sense for VMS */
#define UNLINK unlnk
I32 unlnk (pTHX_ const char*);
#else
#define UNLINK PerlLIO_unlink
#endif
/* some versions of glibc are missing the setresuid() proto */
#if defined(HAS_SETRESUID) && !defined(HAS_SETRESUID_PROTO)
int setresuid(uid_t ruid, uid_t euid, uid_t suid);
#endif
/* some versions of glibc are missing the setresgid() proto */
#if defined(HAS_SETRESGID) && !defined(HAS_SETRESGID_PROTO)
int setresgid(gid_t rgid, gid_t egid, gid_t sgid);
#endif
#ifndef HAS_SETREUID
# ifdef HAS_SETRESUID
# define setreuid(r,e) setresuid(r,e,(Uid_t)-1)
# define HAS_SETREUID
# endif
#endif
#ifndef HAS_SETREGID
# ifdef HAS_SETRESGID
# define setregid(r,e) setresgid(r,e,(Gid_t)-1)
# define HAS_SETREGID
# endif
#endif
/* Sighandler_t defined in iperlsys.h */
#ifdef HAS_SIGACTION
typedef struct sigaction Sigsave_t;
#else
typedef Sighandler_t Sigsave_t;
#endif
#define SCAN_DEF 0
#define SCAN_TR 1
#define SCAN_REPL 2
#ifdef DEBUGGING
# ifndef register
# define register
# endif
# define RUNOPS_DEFAULT Perl_runops_debug
#else
# define RUNOPS_DEFAULT Perl_runops_standard
#endif
#if defined(USE_PERLIO)
EXTERN_C void PerlIO_teardown(void);
# ifdef USE_ITHREADS
# define PERLIO_INIT MUTEX_INIT(&PL_perlio_mutex)
# define PERLIO_TERM \
STMT_START { \
PerlIO_teardown(); \
MUTEX_DESTROY(&PL_perlio_mutex);\
} STMT_END
# else
# define PERLIO_INIT
# define PERLIO_TERM PerlIO_teardown()
# endif
#else
# define PERLIO_INIT
# define PERLIO_TERM
#endif
#ifdef MYMALLOC
# ifdef MUTEX_INIT_CALLS_MALLOC
# define MALLOC_INIT \
STMT_START { \
PL_malloc_mutex = NULL; \
MUTEX_INIT(&PL_malloc_mutex); \
} STMT_END
# define MALLOC_TERM \
STMT_START { \
perl_mutex tmp = PL_malloc_mutex; \
PL_malloc_mutex = NULL; \
MUTEX_DESTROY(&tmp); \
} STMT_END
# else
# define MALLOC_INIT MUTEX_INIT(&PL_malloc_mutex)
# define MALLOC_TERM MUTEX_DESTROY(&PL_malloc_mutex)
# endif
#else
# define MALLOC_INIT
# define MALLOC_TERM
#endif
#if defined(PERL_IMPLICIT_CONTEXT)
struct perl_memory_debug_header;
struct perl_memory_debug_header {
tTHX interpreter;
# if defined(PERL_POISON) || defined(PERL_DEBUG_READONLY_COW)
MEM_SIZE size;
# endif
struct perl_memory_debug_header *prev;
struct perl_memory_debug_header *next;
# ifdef PERL_DEBUG_READONLY_COW
bool readonly;
# endif
};
#elif defined(PERL_DEBUG_READONLY_COW)
struct perl_memory_debug_header;
struct perl_memory_debug_header {
MEM_SIZE size;
};
#endif
#if defined (PERL_TRACK_MEMPOOL) || defined (PERL_DEBUG_READONLY_COW)
# define PERL_MEMORY_DEBUG_HEADER_SIZE \
(sizeof(struct perl_memory_debug_header) + \
(MEM_ALIGNBYTES - sizeof(struct perl_memory_debug_header) \
%MEM_ALIGNBYTES) % MEM_ALIGNBYTES)
#else
# define PERL_MEMORY_DEBUG_HEADER_SIZE 0
#endif
#ifdef PERL_TRACK_MEMPOOL
# ifdef PERL_DEBUG_READONLY_COW
# define INIT_TRACK_MEMPOOL(header, interp) \
STMT_START { \
(header).interpreter = (interp); \
(header).prev = (header).next = &(header); \
(header).readonly = 0; \
} STMT_END
# else
# define INIT_TRACK_MEMPOOL(header, interp) \
STMT_START { \
(header).interpreter = (interp); \
(header).prev = (header).next = &(header); \
} STMT_END
# endif
# else
# define INIT_TRACK_MEMPOOL(header, interp)
#endif
#ifdef I_MALLOCMALLOC
/* Needed for malloc_size(), malloc_good_size() on some systems */
# include <malloc/malloc.h>
#endif
#ifdef MYMALLOC
# define Perl_safesysmalloc_size(where) Perl_malloced_size(where)
#else
# if defined(HAS_MALLOC_SIZE) && !defined(PERL_DEBUG_READONLY_COW)
# ifdef PERL_TRACK_MEMPOOL
# define Perl_safesysmalloc_size(where) \
(malloc_size(((char *)(where)) - PERL_MEMORY_DEBUG_HEADER_SIZE) - PERL_MEMORY_DEBUG_HEADER_SIZE)
# else
# define Perl_safesysmalloc_size(where) malloc_size(where)
# endif
# endif
# ifdef HAS_MALLOC_GOOD_SIZE
# ifdef PERL_TRACK_MEMPOOL
# define Perl_malloc_good_size(how_much) \
(malloc_good_size((how_much) + PERL_MEMORY_DEBUG_HEADER_SIZE) - PERL_MEMORY_DEBUG_HEADER_SIZE)
# else
# define Perl_malloc_good_size(how_much) malloc_good_size(how_much)
# endif
# else
/* Having this as the identity operation makes some code simpler. */
# define Perl_malloc_good_size(how_much) (how_much)
# endif
#endif
typedef int (*runops_proc_t)(pTHX);
typedef void (*share_proc_t) (pTHX_ SV *sv);
typedef int (*thrhook_proc_t) (pTHX);
typedef OP* (*PPADDR_t[]) (pTHX);
typedef bool (*destroyable_proc_t) (pTHX_ SV *sv);
typedef void (*despatch_signals_proc_t) (pTHX);
#if defined(__DYNAMIC__) && defined(PERL_DARWIN) && defined(PERL_CORE)
# include <crt_externs.h> /* for the env array */
# define environ (*_NSGetEnviron())
#elif defined(USE_ENVIRON_ARRAY) && !defined(environ)
/* VMS and some other platforms don't use the environ array */
EXTERN_C char **environ; /* environment variables supplied via exec */
#endif
#define PERL_PATCHLEVEL_H_IMPLICIT
#include "patchlevel.h"
#undef PERL_PATCHLEVEL_H_IMPLICIT
#define PERL_VERSION_STRING STRINGIFY(PERL_REVISION) "." \
STRINGIFY(PERL_VERSION) "." \
STRINGIFY(PERL_SUBVERSION)
#define PERL_API_VERSION_STRING STRINGIFY(PERL_API_REVISION) "." \
STRINGIFY(PERL_API_VERSION) "." \
STRINGIFY(PERL_API_SUBVERSION)
START_EXTERN_C
/* handy constants */
EXTCONST char PL_warn_uninit[]
INIT("Use of uninitialized value%s%s%s");
EXTCONST char PL_warn_uninit_sv[]
INIT("Use of uninitialized value%" SVf "%s%s");
EXTCONST char PL_warn_nosemi[]
INIT("Semicolon seems to be missing");
EXTCONST char PL_warn_reserved[]
INIT("Unquoted string \"%s\" may clash with future reserved word");
EXTCONST char PL_warn_nl[]
INIT("Unsuccessful %s on filename containing newline");
EXTCONST char PL_no_wrongref[]
INIT("Can't use %s ref as %s ref");
/* The core no longer needs this here. If you require the string constant,
please inline a copy into your own code. */
EXTCONST char PL_no_symref[] __attribute__deprecated__
INIT("Can't use string (\"%.32s\") as %s ref while \"strict refs\" in use");
EXTCONST char PL_no_symref_sv[]
INIT("Can't use string (\"%" SVf32 "\"%s) as %s ref while \"strict refs\" in use");
EXTCONST char PL_no_usym[]
INIT("Can't use an undefined value as %s reference");
EXTCONST char PL_no_aelem[]
INIT("Modification of non-creatable array value attempted, subscript %d");
EXTCONST char PL_no_helem_sv[]
INIT("Modification of non-creatable hash value attempted, subscript \"%" SVf "\"");
EXTCONST char PL_no_modify[]
INIT("Modification of a read-only value attempted");
EXTCONST char PL_no_mem[sizeof("Out of memory!\n")]
INIT("Out of memory!\n");
EXTCONST char PL_no_security[]
INIT("Insecure dependency in %s%s");
EXTCONST char PL_no_sock_func[]
INIT("Unsupported socket function \"%s\" called");
EXTCONST char PL_no_dir_func[]
INIT("Unsupported directory function \"%s\" called");
EXTCONST char PL_no_func[]
INIT("The %s function is unimplemented");
EXTCONST char PL_no_myglob[]
INIT("\"%s\" %s %s can't be in a package");
EXTCONST char PL_no_localize_ref[]
INIT("Can't localize through a reference");
EXTCONST char PL_memory_wrap[]
INIT("panic: memory wrap");
EXTCONST char PL_extended_cp_format[]
INIT("Code point 0x%" UVXf " is not Unicode, requires a Perl extension,"
" and so is not portable");
EXTCONST char PL_Yes[]
INIT("1");
EXTCONST char PL_No[]
INIT("");
EXTCONST char PL_Zero[]
INIT("0");
EXTCONST char PL_hexdigit[]
INIT("0123456789abcdef0123456789ABCDEF");
EXTCONST STRLEN PL_WARN_ALL
INIT(0);
EXTCONST STRLEN PL_WARN_NONE
INIT(0);
/* This is constant on most architectures, a global on OS/2 */
#ifndef OS2
EXTCONST char PL_sh_path[]
INIT(SH_PATH); /* full path of shell */
#endif
#ifdef CSH
EXTCONST char PL_cshname[]
INIT(CSH);
# define PL_cshlen (sizeof(CSH "") - 1)
#endif
/* These are baked at compile time into any shared perl library.
In future releases this will allow us in main() to sanity test the
library we're linking against. */
EXTCONST U8 PL_revision
INIT(PERL_REVISION);
EXTCONST U8 PL_version
INIT(PERL_VERSION);
EXTCONST U8 PL_subversion
INIT(PERL_SUBVERSION);
EXTCONST char PL_uuemap[65]
INIT("`!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_");
/* a special string address whose value is "isa", but which perl knows
* to treat as if it were really "DOES" when printing the method name in
* the "Can't call method '%s'" error message */
EXTCONST char PL_isa_DOES[]
INIT("isa");
#ifdef DOINIT
EXTCONST char PL_uudmap[256] =
# ifdef PERL_MICRO
# include "uuudmap.h"
# else
# include "uudmap.h"
# endif
;
EXTCONST char PL_bitcount[256] =
# ifdef PERL_MICRO
# include "ubitcount.h"
#else
# include "bitcount.h"
# endif
;
EXTCONST char* const PL_sig_name[] = { SIG_NAME };
EXTCONST int PL_sig_num[] = { SIG_NUM };
#else
EXTCONST char PL_uudmap[256];
EXTCONST char PL_bitcount[256];
EXTCONST char* const PL_sig_name[];
EXTCONST int PL_sig_num[];
#endif
/* fast conversion and case folding tables. The folding tables complement the
* fold, so that 'a' maps to 'A' and 'A' maps to 'a', ignoring more complicated
* folds such as outside the range or to multiple characters. */
#ifdef DOINIT
#ifndef EBCDIC
/* The EBCDIC fold table depends on the code page, and hence is found in
* utfebcdic.h */
EXTCONST unsigned char PL_fold[] = {
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 91, 92, 93, 94, 95,
96, 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135,
136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151,
152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167,
168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199,
200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 213, 214, 215,
216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231,
232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247,
248, 249, 250, 251, 252, 253, 254, 255
};
EXTCONST unsigned char PL_fold_latin1[] = {
/* Full latin1 complement folding, except for three problematic code points:
* Micro sign (181 = 0xB5) and y with diearesis (255 = 0xFF) have their
* fold complements outside the Latin1 range, so can't match something
* that isn't in utf8.
* German lower case sharp s (223 = 0xDF) folds to two characters, 'ss',
* not one, so can't be represented in this table.
*
* All have to be specially handled */
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 91, 92, 93, 94, 95,
96, 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135,
136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151,
152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167,
168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181 /*micro */, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191,
192+32, 193+32, 194+32, 195+32, 196+32, 197+32, 198+32, 199+32,
200+32, 201+32, 202+32, 203+32, 204+32, 205+32, 206+32, 207+32,
208+32, 209+32, 210+32, 211+32, 212+32, 213+32, 214+32, 215,
216+32, 217+32, 218+32, 219+32, 220+32, 221+32, 222+32, 223 /* ss */,
224-32, 225-32, 226-32, 227-32, 228-32, 229-32, 230-32, 231-32,
232-32, 233-32, 234-32, 235-32, 236-32, 237-32, 238-32, 239-32,
240-32, 241-32, 242-32, 243-32, 244-32, 245-32, 246-32, 247,
248-32, 249-32, 250-32, 251-32, 252-32, 253-32, 254-32,
255 /* y with diaeresis */
};
/* If these tables are accessed through ebcdic, the access will be converted to
* latin1 first */
EXTCONST unsigned char PL_latin1_lc[] = { /* lowercasing */
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135,
136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151,
152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167,
168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191,
192+32, 193+32, 194+32, 195+32, 196+32, 197+32, 198+32, 199+32,
200+32, 201+32, 202+32, 203+32, 204+32, 205+32, 206+32, 207+32,
208+32, 209+32, 210+32, 211+32, 212+32, 213+32, 214+32, 215,
216+32, 217+32, 218+32, 219+32, 220+32, 221+32, 222+32, 223,
224, 225, 226, 227, 228, 229, 230, 231,
232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247,
248, 249, 250, 251, 252, 253, 254, 255
};
/* upper and title case of latin1 characters, modified so that the three tricky
* ones are mapped to 255 (which is one of the three) */
EXTCONST unsigned char PL_mod_latin1_uc[] = {
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71,
72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95,
96, 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135,
136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151,
152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167,
168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 255 /*micro*/, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199,
200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 213, 214, 215,
216, 217, 218, 219, 220, 221, 222,
#if UNICODE_MAJOR_VERSION > 2 \
|| (UNICODE_MAJOR_VERSION == 2 && UNICODE_DOT_VERSION >= 1 \
&& UNICODE_DOT_DOT_VERSION >= 8)
255 /*sharp s*/,
#else /* uc(sharp s) is 'sharp s' itself in early unicode */
223,
#endif
224-32, 225-32, 226-32, 227-32, 228-32, 229-32, 230-32, 231-32,
232-32, 233-32, 234-32, 235-32, 236-32, 237-32, 238-32, 239-32,
240-32, 241-32, 242-32, 243-32, 244-32, 245-32, 246-32, 247,
248-32, 249-32, 250-32, 251-32, 252-32, 253-32, 254-32, 255
};
#endif /* !EBCDIC, but still in DOINIT */
#else /* ! DOINIT */
# ifndef EBCDIC
EXTCONST unsigned char PL_fold[];
EXTCONST unsigned char PL_fold_latin1[];
EXTCONST unsigned char PL_mod_latin1_uc[];
EXTCONST unsigned char PL_latin1_lc[];
# endif
#endif
#ifndef PERL_GLOBAL_STRUCT /* or perlvars.h */
#ifdef DOINIT
EXT unsigned char PL_fold_locale[256] = { /* Unfortunately not EXTCONST. */
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63,
64, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 91, 92, 93, 94, 95,
96, 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135,
136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151,
152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167,
168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199,
200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 213, 214, 215,
216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231,
232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247,
248, 249, 250, 251, 252, 253, 254, 255
};
#else
EXT unsigned char PL_fold_locale[256]; /* Unfortunately not EXTCONST. */
#endif
#endif /* !PERL_GLOBAL_STRUCT */
#ifdef DOINIT
#ifdef EBCDIC
EXTCONST unsigned char PL_freq[] = {/* EBCDIC frequencies for mixed English/C */
1, 2, 84, 151, 154, 155, 156, 157,
165, 246, 250, 3, 158, 7, 18, 29,
40, 51, 62, 73, 85, 96, 107, 118,
129, 140, 147, 148, 149, 150, 152, 153,
255, 6, 8, 9, 10, 11, 12, 13,
14, 15, 24, 25, 26, 27, 28, 226,
29, 30, 31, 32, 33, 43, 44, 45,
46, 47, 48, 49, 50, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86,
87, 94, 95, 234, 181, 233, 187, 190,
180, 96, 97, 98, 99, 100, 101, 102,
104, 112, 182, 174, 236, 232, 229, 103,
228, 226, 114, 115, 116, 117, 118, 119,
120, 121, 122, 235, 176, 230, 194, 162,
130, 131, 132, 133, 134, 135, 136, 137,
138, 139, 201, 205, 163, 217, 220, 224,
5, 248, 227, 244, 242, 255, 241, 231,
240, 253, 16, 197, 19, 20, 21, 187,
23, 169, 210, 245, 237, 249, 247, 239,
168, 252, 34, 196, 36, 37, 38, 39,
41, 42, 251, 254, 238, 223, 221, 213,
225, 177, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 74, 75,
205, 208, 186, 202, 200, 218, 198, 179,
178, 214, 88, 89, 90, 91, 92, 93,
217, 166, 170, 207, 199, 209, 206, 204,
160, 212, 105, 106, 108, 109, 110, 111,
203, 113, 216, 215, 192, 175, 193, 243,
172, 161, 123, 124, 125, 126, 127, 128,
222, 219, 211, 195, 188, 193, 185, 184,
191, 183, 141, 142, 143, 144, 145, 146
};
#else /* ascii rather than ebcdic */
EXTCONST unsigned char PL_freq[] = { /* letter frequencies for mixed English/C */
1, 2, 84, 151, 154, 155, 156, 157,
165, 246, 250, 3, 158, 7, 18, 29,
40, 51, 62, 73, 85, 96, 107, 118,
129, 140, 147, 148, 149, 150, 152, 153,
255, 182, 224, 205, 174, 176, 180, 217,
233, 232, 236, 187, 235, 228, 234, 226,
222, 219, 211, 195, 188, 193, 185, 184,
191, 183, 201, 229, 181, 220, 194, 162,
163, 208, 186, 202, 200, 218, 198, 179,
178, 214, 166, 170, 207, 199, 209, 206,
204, 160, 212, 216, 215, 192, 175, 173,
243, 172, 161, 190, 203, 189, 164, 230,
167, 248, 227, 244, 242, 255, 241, 231,
240, 253, 169, 210, 245, 237, 249, 247,
239, 168, 252, 251, 254, 238, 223, 221,
213, 225, 177, 197, 171, 196, 159, 4,
5, 6, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39,
41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 74, 75,
76, 77, 78, 79, 80, 81, 82, 83,
86, 87, 88, 89, 90, 91, 92, 93,
94, 95, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 119, 120,
121, 122, 123, 124, 125, 126, 127, 128,
130, 131, 132, 133, 134, 135, 136, 137,
138, 139, 141, 142, 143, 144, 145, 146
};
#endif
#else
EXTCONST unsigned char PL_freq[];
#endif
/* Although only used for debugging, these constants must be available in
* non-debugging builds too, since they're used in ext/re/re_exec.c,
* which has DEBUGGING enabled always */
#ifdef DOINIT
EXTCONST char* const PL_block_type[] = {
"NULL",
"WHEN",
"BLOCK",
"GIVEN",
"LOOP_ARY",
"LOOP_LAZYSV",
"LOOP_LAZYIV",
"LOOP_LIST",
"LOOP_PLAIN",
"SUB",
"FORMAT",
"EVAL",
"SUBST"
};
#else
EXTCONST char* PL_block_type[];
#endif
/* These are all the compile time options that affect binary compatibility.
Other compile time options that are binary compatible are in perl.c
(in S_Internals_V()). Both are combined for the output of perl -V
However, this string will be embedded in any shared perl library, which will
allow us add a comparison check in perlmain.c in the near future. */
#ifdef DOINIT
EXTCONST char PL_bincompat_options[] =
# ifdef DEBUG_LEAKING_SCALARS
" DEBUG_LEAKING_SCALARS"
# endif
# ifdef DEBUG_LEAKING_SCALARS_FORK_DUMP
" DEBUG_LEAKING_SCALARS_FORK_DUMP"
# endif
# ifdef FCRYPT
" FCRYPT"
# endif
# ifdef HAS_TIMES
" HAS_TIMES"
# endif
# ifdef HAVE_INTERP_INTERN
" HAVE_INTERP_INTERN"
# endif
# ifdef MULTIPLICITY
" MULTIPLICITY"
# endif
# ifdef MYMALLOC
" MYMALLOC"
# endif
# ifdef PERLIO_LAYERS
" PERLIO_LAYERS"
# endif
# ifdef PERL_DEBUG_READONLY_COW
" PERL_DEBUG_READONLY_COW"
# endif
# ifdef PERL_DEBUG_READONLY_OPS
" PERL_DEBUG_READONLY_OPS"
# endif
# ifdef PERL_GLOBAL_STRUCT
" PERL_GLOBAL_STRUCT"
# endif
# ifdef PERL_GLOBAL_STRUCT_PRIVATE
" PERL_GLOBAL_STRUCT_PRIVATE"
# endif
# ifdef PERL_IMPLICIT_CONTEXT
" PERL_IMPLICIT_CONTEXT"
# endif
# ifdef PERL_IMPLICIT_SYS
" PERL_IMPLICIT_SYS"
# endif
# ifdef PERL_MICRO
" PERL_MICRO"
# endif
# ifdef PERL_NEED_APPCTX
" PERL_NEED_APPCTX"
# endif
# ifdef PERL_NEED_TIMESBASE
" PERL_NEED_TIMESBASE"
# endif
# ifdef PERL_POISON
" PERL_POISON"
# endif
# ifdef PERL_SAWAMPERSAND
" PERL_SAWAMPERSAND"
# endif
# ifdef PERL_TRACK_MEMPOOL
" PERL_TRACK_MEMPOOL"
# endif
# ifdef PERL_USES_PL_PIDSTATUS
" PERL_USES_PL_PIDSTATUS"
# endif
# ifdef USE_64_BIT_ALL
" USE_64_BIT_ALL"
# endif
# ifdef USE_64_BIT_INT
" USE_64_BIT_INT"
# endif
# ifdef USE_IEEE
" USE_IEEE"
# endif
# ifdef USE_ITHREADS
" USE_ITHREADS"
# endif
# ifdef USE_LARGE_FILES
" USE_LARGE_FILES"
# endif
# ifdef USE_LOCALE_COLLATE
" USE_LOCALE_COLLATE"
# endif
# ifdef USE_LOCALE_NUMERIC
" USE_LOCALE_NUMERIC"
# endif
# ifdef USE_LOCALE_TIME
" USE_LOCALE_TIME"
# endif
# ifdef USE_LONG_DOUBLE
" USE_LONG_DOUBLE"
# endif
# ifdef USE_PERLIO
" USE_PERLIO"
# endif
# ifdef USE_QUADMATH
" USE_QUADMATH"
# endif
# ifdef USE_REENTRANT_API
" USE_REENTRANT_API"
# endif
# ifdef USE_SOCKS
" USE_SOCKS"
# endif
# ifdef VMS_DO_SOCKETS
" VMS_DO_SOCKETS"
# endif
# ifdef VMS_SHORTEN_LONG_SYMBOLS
" VMS_SHORTEN_LONG_SYMBOLS"
# endif
# ifdef VMS_WE_ARE_CASE_SENSITIVE
" VMS_SYMBOL_CASE_AS_IS"
# endif
"";
#else
EXTCONST char PL_bincompat_options[];
#endif
#ifndef PERL_SET_PHASE
# define PERL_SET_PHASE(new_phase) \
PERL_DTRACE_PROBE_PHASE(new_phase); \
PL_phase = new_phase;
#endif
/* The interpreter phases. If these ever change, PL_phase_names right below will
* need to be updated accordingly. */
enum perl_phase {
PERL_PHASE_CONSTRUCT = 0,
PERL_PHASE_START = 1,
PERL_PHASE_CHECK = 2,
PERL_PHASE_INIT = 3,
PERL_PHASE_RUN = 4,
PERL_PHASE_END = 5,
PERL_PHASE_DESTRUCT = 6
};
#ifdef DOINIT
EXTCONST char *const PL_phase_names[] = {
"CONSTRUCT",
"START",
"CHECK",
"INIT",
"RUN",
"END",
"DESTRUCT"
};
#else
EXTCONST char *const PL_phase_names[];
#endif
#ifndef PERL_CORE
/* Do not use this macro. It only exists for extensions that rely on PL_dirty
* instead of using the newer PL_phase, which provides everything PL_dirty
* provided, and more. */
# define PL_dirty cBOOL(PL_phase == PERL_PHASE_DESTRUCT)
# define PL_amagic_generation PL_na
# define PL_encoding ((SV *)NULL)
#endif /* !PERL_CORE */
#define PL_hints PL_compiling.cop_hints
#define PL_maxo MAXO
END_EXTERN_C
/*****************************************************************************/
/* This lexer/parser stuff is currently global since yacc is hard to reenter */
/*****************************************************************************/
/* XXX This needs to be revisited, since BEGIN makes yacc re-enter... */
#ifdef __Lynx__
/* LynxOS defines these in scsi.h which is included via ioctl.h */
#ifdef FORMAT
#undef FORMAT
#endif
#ifdef SPACE
#undef SPACE
#endif
#endif
#define LEX_NOTPARSING 11 /* borrowed from toke.c */
typedef enum {
XOPERATOR,
XTERM,
XREF,
XSTATE,
XBLOCK,
XATTRBLOCK, /* next token should be an attribute or block */
XATTRTERM, /* next token should be an attribute, or block in a term */
XTERMBLOCK,
XBLOCKTERM,
XPOSTDEREF,
XTERMORDORDOR /* evil hack */
/* update exp_name[] in toke.c if adding to this enum */
} expectation;
#define KEY_sigvar 0xFFFF /* fake keyword representing a signature var */
/* Hints are now stored in a dedicated U32, so the bottom 8 bits are no longer
special and there is no need for HINT_PRIVATE_MASK for COPs
However, bitops store HINT_INTEGER in their op_private.
NOTE: The typical module using these has the bit value hard-coded, so don't
blindly change the values of these.
If we run out of bits, the 2 locale ones could be combined. The PARTIAL one
is for "use locale 'FOO'" which excludes some categories. It requires going
to %^H to find out which are in and which are out. This could be extended
for the normal case of a plain HINT_LOCALE, so that %^H would be used for
any locale form. */
#define HINT_INTEGER 0x00000001 /* integer pragma */
#define HINT_STRICT_REFS 0x00000002 /* strict pragma */
#define HINT_LOCALE 0x00000004 /* locale pragma */
#define HINT_BYTES 0x00000008 /* bytes pragma */
#define HINT_LOCALE_PARTIAL 0x00000010 /* locale, but a subset of categories */
#define HINT_EXPLICIT_STRICT_REFS 0x00000020 /* strict.pm */
#define HINT_EXPLICIT_STRICT_SUBS 0x00000040 /* strict.pm */
#define HINT_EXPLICIT_STRICT_VARS 0x00000080 /* strict.pm */
#define HINT_BLOCK_SCOPE 0x00000100
#define HINT_STRICT_SUBS 0x00000200 /* strict pragma */
#define HINT_STRICT_VARS 0x00000400 /* strict pragma */
#define HINT_UNI_8_BIT 0x00000800 /* unicode_strings feature */
/* The HINT_NEW_* constants are used by the overload pragma */
#define HINT_NEW_INTEGER 0x00001000
#define HINT_NEW_FLOAT 0x00002000
#define HINT_NEW_BINARY 0x00004000
#define HINT_NEW_STRING 0x00008000
#define HINT_NEW_RE 0x00010000
#define HINT_LOCALIZE_HH 0x00020000 /* %^H needs to be copied */
#define HINT_LEXICAL_IO_IN 0x00040000 /* ${^OPEN} is set for input */
#define HINT_LEXICAL_IO_OUT 0x00080000 /* ${^OPEN} is set for output */
#define HINT_RE_TAINT 0x00100000 /* re pragma */
#define HINT_RE_EVAL 0x00200000 /* re pragma */
#define HINT_FILETEST_ACCESS 0x00400000 /* filetest pragma */
#define HINT_UTF8 0x00800000 /* utf8 pragma */
#define HINT_NO_AMAGIC 0x01000000 /* overloading pragma */
#define HINT_RE_FLAGS 0x02000000 /* re '/xism' pragma */
#define HINT_FEATURE_MASK 0x1c000000 /* 3 bits for feature bundles */
/* Note: Used for HINT_M_VMSISH_*,
currently defined by vms/vmsish.h:
0x40000000
0x80000000
*/
/* The following are stored in $^H{sort}, not in PL_hints */
#define HINT_SORT_STABLE 0x00000100 /* sort styles */
#define HINT_SORT_UNSTABLE 0x00000200
/* flags for PL_sawampersand */
#define SAWAMPERSAND_LEFT 1 /* saw $` */
#define SAWAMPERSAND_MIDDLE 2 /* saw $& */
#define SAWAMPERSAND_RIGHT 4 /* saw $' */
#ifndef PERL_SAWAMPERSAND
# define PL_sawampersand \
(SAWAMPERSAND_LEFT|SAWAMPERSAND_MIDDLE|SAWAMPERSAND_RIGHT)
#endif
/* Used for debugvar magic */
#define DBVARMG_SINGLE 0
#define DBVARMG_TRACE 1
#define DBVARMG_SIGNAL 2
#define DBVARMG_COUNT 3
#define PL_DBsingle_iv (PL_DBcontrol[DBVARMG_SINGLE])
#define PL_DBtrace_iv (PL_DBcontrol[DBVARMG_TRACE])
#define PL_DBsignal_iv (PL_DBcontrol[DBVARMG_SIGNAL])
/* Various states of the input record separator SV (rs) */
#define RsSNARF(sv) (! SvOK(sv))
#define RsSIMPLE(sv) (SvOK(sv) && (! SvPOK(sv) || SvCUR(sv)))
#define RsPARA(sv) (SvPOK(sv) && ! SvCUR(sv))
#define RsRECORD(sv) (SvROK(sv) && (SvIV(SvRV(sv)) > 0))
/* A struct for keeping various DEBUGGING related stuff,
* neatly packed. Currently only scratch variables for
* constructing debug output are included. Needed always,
* not just when DEBUGGING, though, because of the re extension. c*/
struct perl_debug_pad {
SV pad[3];
};
#define PERL_DEBUG_PAD(i) &(PL_debug_pad.pad[i])
#define PERL_DEBUG_PAD_ZERO(i) (SvPVX(PERL_DEBUG_PAD(i))[0] = 0, \
(((XPV*) SvANY(PERL_DEBUG_PAD(i)))->xpv_cur = 0), \
PERL_DEBUG_PAD(i))
/* Enable variables which are pointers to functions */
typedef void (*peep_t)(pTHX_ OP* o);
typedef regexp* (*regcomp_t) (pTHX_ char* exp, char* xend, PMOP* pm);
typedef I32 (*regexec_t) (pTHX_ regexp* prog, char* stringarg,
char* strend, char* strbeg, I32 minend,
SV* screamer, void* data, U32 flags);
typedef char* (*re_intuit_start_t) (pTHX_ regexp *prog, SV *sv,
char *strpos, char *strend,
U32 flags,
re_scream_pos_data *d);
typedef SV* (*re_intuit_string_t) (pTHX_ regexp *prog);
typedef void (*regfree_t) (pTHX_ struct regexp* r);
typedef regexp* (*regdupe_t) (pTHX_ const regexp* r, CLONE_PARAMS *param);
typedef I32 (*re_fold_t)(const char *, char const *, I32);
typedef void (*DESTRUCTORFUNC_NOCONTEXT_t) (void*);
typedef void (*DESTRUCTORFUNC_t) (pTHX_ void*);
typedef void (*SVFUNC_t) (pTHX_ SV* const);
typedef I32 (*SVCOMPARE_t) (pTHX_ SV* const, SV* const);
typedef void (*XSINIT_t) (pTHX);
typedef void (*ATEXIT_t) (pTHX_ void*);
typedef void (*XSUBADDR_t) (pTHX_ CV *);
typedef OP* (*Perl_ppaddr_t)(pTHX);
typedef OP* (*Perl_check_t) (pTHX_ OP*);
typedef void(*Perl_ophook_t)(pTHX_ OP*);
typedef int (*Perl_keyword_plugin_t)(pTHX_ char*, STRLEN, OP**);
typedef void(*Perl_cpeep_t)(pTHX_ OP *, OP *);
typedef void(*globhook_t)(pTHX);
#define KEYWORD_PLUGIN_DECLINE 0
#define KEYWORD_PLUGIN_STMT 1
#define KEYWORD_PLUGIN_EXPR 2
/* Interpreter exitlist entry */
typedef struct exitlistentry {
void (*fn) (pTHX_ void*);
void *ptr;
} PerlExitListEntry;
/* if you only have signal() and it resets on each signal, FAKE_PERSISTENT_SIGNAL_HANDLERS fixes */
/* These have to be before perlvars.h */
#if !defined(HAS_SIGACTION) && defined(VMS)
# define FAKE_PERSISTENT_SIGNAL_HANDLERS
#endif
/* if we're doing kill() with sys$sigprc on VMS, FAKE_DEFAULT_SIGNAL_HANDLERS */
#if defined(KILL_BY_SIGPRC)
# define FAKE_DEFAULT_SIGNAL_HANDLERS
#endif
#if !defined(MULTIPLICITY)
struct interpreter {
char broiled;
};
#else
/* If we have multiple interpreters define a struct
holding variables which must be per-interpreter
If we don't have threads anything that would have
be per-thread is per-interpreter.
*/
/* Set up PERLVAR macros for populating structs */
# define PERLVAR(prefix,var,type) type prefix##var;
/* 'var' is an array of length 'n' */
# define PERLVARA(prefix,var,n,type) type prefix##var[n];
/* initialize 'var' to init' */
# define PERLVARI(prefix,var,type,init) type prefix##var;
/* like PERLVARI, but make 'var' a const */
# define PERLVARIC(prefix,var,type,init) type prefix##var;
struct interpreter {
# include "intrpvar.h"
};
EXTCONST U16 PL_interp_size
INIT(sizeof(struct interpreter));
# define PERL_INTERPRETER_SIZE_UPTO_MEMBER(member) \
STRUCT_OFFSET(struct interpreter, member) + \
sizeof(((struct interpreter*)0)->member)
/* This will be useful for subsequent releases, because this has to be the
same in your libperl as in main(), else you have a mismatch and must abort.
*/
EXTCONST U16 PL_interp_size_5_18_0
INIT(PERL_INTERPRETER_SIZE_UPTO_MEMBER(PERL_LAST_5_18_0_INTERP_MEMBER));
# ifdef PERL_GLOBAL_STRUCT
/* MULTIPLICITY is automatically defined when PERL_GLOBAL_STRUCT is defined,
hence it's safe and sane to nest this within #ifdef MULTIPLICITY */
struct perl_vars {
# include "perlvars.h"
};
EXTCONST U16 PL_global_struct_size
INIT(sizeof(struct perl_vars));
# ifdef PERL_CORE
# ifndef PERL_GLOBAL_STRUCT_PRIVATE
EXT struct perl_vars PL_Vars;
EXT struct perl_vars *PL_VarsPtr INIT(&PL_Vars);
# undef PERL_GET_VARS
# define PERL_GET_VARS() PL_VarsPtr
# endif /* !PERL_GLOBAL_STRUCT_PRIVATE */
# else /* PERL_CORE */
# if !defined(__GNUC__) || !defined(WIN32)
EXT
# endif /* WIN32 */
struct perl_vars *PL_VarsPtr;
# define PL_Vars (*((PL_VarsPtr) \
? PL_VarsPtr : (PL_VarsPtr = Perl_GetVars(aTHX))))
# endif /* PERL_CORE */
# endif /* PERL_GLOBAL_STRUCT */
/* Done with PERLVAR macros for now ... */
# undef PERLVAR
# undef PERLVARA
# undef PERLVARI
# undef PERLVARIC
#endif /* MULTIPLICITY */
struct tempsym; /* defined in pp_pack.c */
#include "thread.h"
#include "pp.h"
#undef PERL_CKDEF
#undef PERL_PPDEF
#define PERL_CKDEF(s) PERL_CALLCONV OP *s (pTHX_ OP *o);
#define PERL_PPDEF(s) PERL_CALLCONV OP *s (pTHX);
#ifdef MYMALLOC
# include "malloc_ctl.h"
#endif
/*
* This provides a layer of functions and macros to ensure extensions will
* get to use the same RTL functions as the core.
*/
#if defined(WIN32)
# include "win32iop.h"
#endif
#include "proto.h"
/* this has structure inits, so it cannot be included before here */
#include "opcode.h"
/* The following must follow proto.h as #defines mess up syntax */
#if !defined(PERL_FOR_X2P)
# include "embedvar.h"
#endif
/* Now include all the 'global' variables
* If we don't have threads or multiple interpreters
* these include variables that would have been their struct-s
*/
#define PERLVAR(prefix,var,type) EXT type PL_##var;
#define PERLVARA(prefix,var,n,type) EXT type PL_##var[n];
#define PERLVARI(prefix,var,type,init) EXT type PL_##var INIT(init);
#define PERLVARIC(prefix,var,type,init) EXTCONST type PL_##var INIT(init);
#if !defined(MULTIPLICITY)
START_EXTERN_C
# include "intrpvar.h"
END_EXTERN_C
# define PL_sv_yes (PL_sv_immortals[0])
# define PL_sv_undef (PL_sv_immortals[1])
# define PL_sv_no (PL_sv_immortals[2])
# define PL_sv_zero (PL_sv_immortals[3])
#endif
#ifdef PERL_CORE
/* All core uses now exterminated. Ensure no zombies can return: */
# undef PL_na
#endif
/* Now all the config stuff is setup we can include embed.h
In particular, need the relevant *ish file included already, as it may
define HAVE_INTERP_INTERN */
#include "embed.h"
#ifndef PERL_GLOBAL_STRUCT
START_EXTERN_C
# include "perlvars.h"
END_EXTERN_C
#endif
#undef PERLVAR
#undef PERLVARA
#undef PERLVARI
#undef PERLVARIC
#if !defined(MULTIPLICITY)
/* Set up PERLVAR macros for populating structs */
# define PERLVAR(prefix,var,type) type prefix##var;
/* 'var' is an array of length 'n' */
# define PERLVARA(prefix,var,n,type) type prefix##var[n];
/* initialize 'var' to init' */
# define PERLVARI(prefix,var,type,init) type prefix##var;
/* like PERLVARI, but make 'var' a const */
# define PERLVARIC(prefix,var,type,init) type prefix##var;
/* this is never instantiated, is it just used for sizeof(struct PerlHandShakeInterpreter) */
struct PerlHandShakeInterpreter {
# include "intrpvar.h"
};
# undef PERLVAR
# undef PERLVARA
# undef PERLVARI
# undef PERLVARIC
#endif
START_EXTERN_C
/* dummy variables that hold pointers to both runops functions, thus forcing
* them *both* to get linked in (useful for Peek.xs, debugging etc) */
EXTCONST runops_proc_t PL_runops_std
INIT(Perl_runops_standard);
EXTCONST runops_proc_t PL_runops_dbg
INIT(Perl_runops_debug);
#define EXT_MGVTBL EXTCONST MGVTBL
#define PERL_MAGIC_READONLY_ACCEPTABLE 0x40
#define PERL_MAGIC_VALUE_MAGIC 0x80
#define PERL_MAGIC_VTABLE_MASK 0x3F
#define PERL_MAGIC_TYPE_READONLY_ACCEPTABLE(t) \
(PL_magic_data[(U8)(t)] & PERL_MAGIC_READONLY_ACCEPTABLE)
#define PERL_MAGIC_TYPE_IS_VALUE_MAGIC(t) \
(PL_magic_data[(U8)(t)] & PERL_MAGIC_VALUE_MAGIC)
#include "mg_vtable.h"
#ifdef DOINIT
EXTCONST U8 PL_magic_data[256] =
# ifdef PERL_MICRO
# include "umg_data.h"
# else
# include "mg_data.h"
# endif
;
#else
EXTCONST U8 PL_magic_data[256];
#endif
#ifdef DOINIT
/* NL IV NV PV INV PI PN MG RX GV LV AV HV CV FM IO */
EXTCONST bool
PL_valid_types_IVX[] = { 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0 };
EXTCONST bool
PL_valid_types_NVX[] = { 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0 };
EXTCONST bool
PL_valid_types_PVX[] = { 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 };
EXTCONST bool
PL_valid_types_RV[] = { 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1 };
EXTCONST bool
PL_valid_types_IV_set[] = { 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1 };
EXTCONST bool
PL_valid_types_NV_set[] = { 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
#else
EXTCONST bool PL_valid_types_IVX[];
EXTCONST bool PL_valid_types_NVX[];
EXTCONST bool PL_valid_types_PVX[];
EXTCONST bool PL_valid_types_RV[];
EXTCONST bool PL_valid_types_IV_set[];
EXTCONST bool PL_valid_types_NV_set[];
#endif
/* In C99 we could use designated (named field) union initializers.
* In C89 we need to initialize the member declared first.
* In C++ we need extern C initializers.
*
* With the U8_NV version you will want to have inner braces,
* while with the NV_U8 use just the NV. */
#define INFNAN_U8_NV_DECL EXTCONST union { U8 u8[NVSIZE]; NV nv; }
#define INFNAN_NV_U8_DECL EXTCONST union { NV nv; U8 u8[NVSIZE]; }
/* if these never got defined, they need defaults */
#ifndef PERL_SET_CONTEXT
# define PERL_SET_CONTEXT(i) PERL_SET_INTERP(i)
#endif
#ifndef PERL_GET_CONTEXT
# define PERL_GET_CONTEXT PERL_GET_INTERP
#endif
#ifndef PERL_GET_THX
# define PERL_GET_THX ((void*)NULL)
#endif
#ifndef PERL_SET_THX
# define PERL_SET_THX(t) NOOP
#endif
#ifndef EBCDIC
/* The tables below are adapted from
* https://bjoern.hoehrmann.de/utf-8/decoder/dfa/, which requires this copyright
* notice:
Copyright (c) 2008-2009 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
# ifdef DOINIT
# if 0 /* This is the original table given in
https://bjoern.hoehrmann.de/utf-8/decoder/dfa/ */
static U8 utf8d_C9[] = {
/* The first part of the table maps bytes to character classes that
* to reduce the size of the transition table and create bitmasks. */
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*-1F*/
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*-3F*/
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*-5F*/
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*-7F*/
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, /*-9F*/
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, /*-BF*/
8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, /*-DF*/
10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, /*-FF*/
/* The second part is a transition table that maps a combination
* of a state of the automaton and a character class to a state. */
0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12,
12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12,
12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12,
12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12,
12,36,12,12,12,12,12,12,12,12,12,12
};
# endif
/* This is a version of the above table customized for Perl that doesn't
* exclude surrogates and accepts start bytes up through FD (FE on 64-bit
* machines). The classes have been renumbered so that the patterns are more
* evident in the table. The class numbers for start bytes are constrained so
* that they can be used as a shift count for masking off the leading one bits.
* It would make the code simpler if start byte FF could also be handled, but
* doing so would mean adding nodes for each of continuation bytes 6-12
* remaining, and two more nodes for overlong detection (a total of 9), and
* there is room only for 4 more nodes unless we make the array U16 instead of
* U8.
*
* The classes are
* 00-7F 0
* 80-81 7 Not legal immediately after start bytes E0 F0 F8 FC
* FE
* 82-83 8 Not legal immediately after start bytes E0 F0 F8 FC
* 84-87 9 Not legal immediately after start bytes E0 F0 F8
* 88-8F 10 Not legal immediately after start bytes E0 F0
* 90-9F 11 Not legal immediately after start byte E0
* A0-BF 12
* C0,C1 1
* C2-DF 2
* E0 13
* E1-EF 3
* F0 14
* F1-F7 4
* F8 15
* F9-FB 5
* FC 16
* FD 6
* FE 17 (or 1 on 32-bit machines, since it overflows)
* FF 1
*/
EXTCONST U8 PL_extended_utf8_dfa_tab[] = {
/* The first part of the table maps bytes to character classes to reduce
* the size of the transition table and create bitmasks. */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*00-0F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*10-1F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*20-2F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*30-3F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*40-4F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*50-5F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*60-6F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*70-7F*/
7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10, /*80-8F*/
11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11, /*90-9F*/
12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, /*A0-AF*/
12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, /*B0-BF*/
1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*C0-CF*/
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*D0-DF*/
13, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /*E0-EF*/
14, 4, 4, 4, 4, 4, 4, 4,15, 5, 5, 5,16, 6, /*F0-FD*/
# ifdef UV_IS_QUAD
17, /*FE*/
# else
1, /*FE*/
# endif
1, /*FF*/
/* The second part is a transition table that maps a combination
* of a state of the automaton and a character class to a new state, called a
* node. The nodes are:
* N0 The initial state, and final accepting one.
* N1 Any one continuation byte (80-BF) left. This is transitioned to
* immediately when the start byte indicates a two-byte sequence
* N2 Any two continuation bytes left.
* N3 Any three continuation bytes left.
* N4 Any four continuation bytes left.
* N5 Any five continuation bytes left.
* N6 Start byte is E0. Continuation bytes 80-9F are illegal (overlong);
* the other continuations transition to N1
* N7 Start byte is F0. Continuation bytes 80-8F are illegal (overlong);
* the other continuations transition to N2
* N8 Start byte is F8. Continuation bytes 80-87 are illegal (overlong);
* the other continuations transition to N3
* N9 Start byte is FC. Continuation bytes 80-83 are illegal (overlong);
* the other continuations transition to N4
* N10 Start byte is FE. Continuation bytes 80-81 are illegal (overlong);
* the other continuations transition to N5
* 1 Reject. All transitions not mentioned above (except the single
* byte ones (as they are always legal) are to this state.
*/
# define NUM_CLASSES 18
# define N0 0
# define N1 ((N0) + NUM_CLASSES)
# define N2 ((N1) + NUM_CLASSES)
# define N3 ((N2) + NUM_CLASSES)
# define N4 ((N3) + NUM_CLASSES)
# define N5 ((N4) + NUM_CLASSES)
# define N6 ((N5) + NUM_CLASSES)
# define N7 ((N6) + NUM_CLASSES)
# define N8 ((N7) + NUM_CLASSES)
# define N9 ((N8) + NUM_CLASSES)
# define N10 ((N9) + NUM_CLASSES)
/*Class: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 */
/*N0*/ 0, 1,N1,N2,N3,N4,N5, 1, 1, 1, 1, 1, 1,N6,N7,N8,N9,N10,
/*N1*/ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
/*N2*/ 1, 1, 1, 1, 1, 1, 1,N1,N1,N1,N1,N1,N1, 1, 1, 1, 1, 1,
/*N3*/ 1, 1, 1, 1, 1, 1, 1,N2,N2,N2,N2,N2,N2, 1, 1, 1, 1, 1,
/*N4*/ 1, 1, 1, 1, 1, 1, 1,N3,N3,N3,N3,N3,N3, 1, 1, 1, 1, 1,
/*N5*/ 1, 1, 1, 1, 1, 1, 1,N4,N4,N4,N4,N4,N4, 1, 1, 1, 1, 1,
/*N6*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,N1, 1, 1, 1, 1, 1,
/*N7*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,N2,N2, 1, 1, 1, 1, 1,
/*N8*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,N3,N3,N3, 1, 1, 1, 1, 1,
/*N9*/ 1, 1, 1, 1, 1, 1, 1, 1, 1,N4,N4,N4,N4, 1, 1, 1, 1, 1,
/*N10*/ 1, 1, 1, 1, 1, 1, 1, 1,N5,N5,N5,N5,N5, 1, 1, 1, 1, 1,
};
/* And below is a version of the above table that accepts only strict UTF-8.
* Hence no surrogates nor non-characters, nor non-Unicode. Thus, if the input
* passes this dfa, it will be for a well-formed, non-problematic code point
* that can be returned immediately.
*
* The "Implementation details" portion of
* https://bjoern.hoehrmann.de/utf-8/decoder/dfa/ shows how
* the first portion of the table maps each possible byte into a character
* class. And that the classes for those bytes which are start bytes have been
* carefully chosen so they serve as well to be used as a shift value to mask
* off the leading 1 bits of the start byte. Unfortunately the addition of
* being able to distinguish non-characters makes this not fully work. This is
* because, now, the start bytes E1-EF have to be broken into 3 classes instead
* of 2:
* 1) ED because it could be a surrogate
* 2) EF because it could be a non-character
* 3) the rest, which can never evaluate to a problematic code point.
*
* Each of E1-EF has three leading 1 bits, then a 0. That means we could use a
* shift (and hence class number) of either 3 or 4 to get a mask that works.
* But that only allows two categories, and we need three. khw made the
* decision to therefore treat the ED start byte as an error, so that the dfa
* drops out immediately for that. In the dfa, classes 3 and 4 are used to
* distinguish EF vs the rest. Then special code is used to deal with ED,
* that's executed only when the dfa drops out. The code points started by ED
* are half surrogates, and half hangul syllables. This means that 2048 of
* the hangul syllables (about 18%) take longer than all other non-problematic
* code points to handle.
*
* The changes to handle non-characters requires the addition of states and
* classes to the dfa. (See the section on "Mapping bytes to character
* classes" in the linked-to document for further explanation of the original
* dfa.)
*
* The classes are
* 00-7F 0
* 80-8E 9
* 8F 10
* 90-9E 11
* 9F 12
* A0-AE 13
* AF 14
* B0-B6 15
* B7 16
* B8-BD 15
* BE 17
* BF 18
* C0,C1 1
* C2-DF 2
* E0 7
* E1-EC 3
* ED 1
* EE 3
* EF 4
* F0 8
* F1-F3 6 (6 bits can be stripped)
* F4 5 (only 5 can be stripped)
* F5-FF 1
*/
EXTCONST U8 PL_strict_utf8_dfa_tab[] = {
/* The first part of the table maps bytes to character classes to reduce
* the size of the transition table and create bitmasks. */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*00-0F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*10-1F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*20-2F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*30-3F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*40-4F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*50-5F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*60-6F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*70-7F*/
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, /*80-8F*/
11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12, /*90-9F*/
13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14, /*A0-AF*/
15,15,15,15,15,15,15,16,15,15,15,15,15,15,17,18, /*B0-BF*/
1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*C0-CF*/
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*D0-DF*/
7, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 4, /*E0-EF*/
8, 6, 6, 6, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /*F0-FF*/
/* The second part is a transition table that maps a combination
* of a state of the automaton and a character class to a new state, called a
* node. The nodes are:
* N0 The initial state, and final accepting one.
* N1 Any one continuation byte (80-BF) left. This is transitioned to
* immediately when the start byte indicates a two-byte sequence
* N2 Any two continuation bytes left.
* N3 Start byte is E0. Continuation bytes 80-9F are illegal (overlong);
* the other continuations transition to state N1
* N4 Start byte is EF. Continuation byte B7 transitions to N8; BF to N9;
* the other continuations transitions to N1
* N5 Start byte is F0. Continuation bytes 80-8F are illegal (overlong);
* [9AB]F transition to N10; the other continuations to N2.
* N6 Start byte is F[123]. Continuation bytes [89AB]F transition
* to N10; the other continuations to N2.
* N7 Start byte is F4. Continuation bytes 90-BF are illegal
* (non-unicode); 8F transitions to N10; the other continuations to N2
* N8 Initial sequence is EF B7. Continuation bytes 90-AF are illegal
* (non-characters); the other continuations transition to N0.
* N9 Initial sequence is EF BF. Continuation bytes BE and BF are illegal
* (non-characters); the other continuations transition to N0.
* N10 Initial sequence is one of: F0 [9-B]F; F[123] [8-B]F; or F4 8F.
* Continuation byte BF transitions to N11; the other continuations to
* N1
* N11 Initial sequence is the two bytes given in N10 followed by BF.
* Continuation bytes BE and BF are illegal (non-characters); the other
* continuations transition to N0.
* 1 Reject. All transitions not mentioned above (except the single
* byte ones (as they are always legal) are to this state.
*/
# undef N0
# undef N1
# undef N2
# undef N3
# undef N4
# undef N5
# undef N6
# undef N7
# undef N8
# undef N9
# undef NUM_CLASSES
# define NUM_CLASSES 19
# define N0 0
# define N1 ((N0) + NUM_CLASSES)
# define N2 ((N1) + NUM_CLASSES)
# define N3 ((N2) + NUM_CLASSES)
# define N4 ((N3) + NUM_CLASSES)
# define N5 ((N4) + NUM_CLASSES)
# define N6 ((N5) + NUM_CLASSES)
# define N7 ((N6) + NUM_CLASSES)
# define N8 ((N7) + NUM_CLASSES)
# define N9 ((N8) + NUM_CLASSES)
# define N10 ((N9) + NUM_CLASSES)
# define N11 ((N10) + NUM_CLASSES)
/*Class: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 */
/*N0*/ 0, 1, N1, N2, N4, N7, N6, N3, N5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/*N1*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/*N2*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, N1, N1, N1, N1, N1, N1, N1, N1, N1, N1,
/*N3*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, N1, N1, N1, N1, N1, N1,
/*N4*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, N1, N1, N1, N1, N1, N1, N1, N8, N1, N9,
/*N5*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, N2,N10, N2,N10, N2, N2, N2,N10,
/*N6*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, N2,N10, N2,N10, N2,N10, N2, N2, N2,N10,
/*N7*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, N2,N10, 1, 1, 1, 1, 1, 1, 1, 1,
/*N8*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0,
/*N9*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
/*N10*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, N1, N1, N1, N1, N1, N1, N1, N1, N1,N11,
/*N11*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
};
/* And below is yet another version of the above tables that accepts only UTF-8
* as defined by Corregidum #9. Hence no surrogates nor non-Unicode, but
* it allows non-characters. This is isomorphic to the original table
* in https://bjoern.hoehrmann.de/utf-8/decoder/dfa/
*
* The classes are
* 00-7F 0
* 80-8F 9
* 90-9F 10
* A0-BF 11
* C0,C1 1
* C2-DF 2
* E0 7
* E1-EC 3
* ED 4
* EE-EF 3
* F0 8
* F1-F3 6 (6 bits can be stripped)
* F4 5 (only 5 can be stripped)
* F5-FF 1
*/
EXTCONST U8 PL_c9_utf8_dfa_tab[] = {
/* The first part of the table maps bytes to character classes to reduce
* the size of the transition table and create bitmasks. */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*00-0F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*10-1F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*20-2F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*30-3F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*40-4F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*50-5F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*60-6F*/
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*70-7F*/
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, /*80-8F*/
10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, /*90-9F*/
11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11, /*A0-AF*/
11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11, /*B0-BF*/
1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*C0-CF*/
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /*D0-DF*/
7, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, /*E0-EF*/
8, 6, 6, 6, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /*F0-FF*/
/* The second part is a transition table that maps a combination
* of a state of the automaton and a character class to a new state, called a
* node. The nodes are:
* N0 The initial state, and final accepting one.
* N1 Any one continuation byte (80-BF) left. This is transitioned to
* immediately when the start byte indicates a two-byte sequence
* N2 Any two continuation bytes left.
* N3 Any three continuation bytes left.
* N4 Start byte is E0. Continuation bytes 80-9F are illegal (overlong);
* the other continuations transition to state N1
* N5 Start byte is ED. Continuation bytes A0-BF all lead to surrogates,
* so are illegal. The other continuations transition to state N1.
* N6 Start byte is F0. Continuation bytes 80-8F are illegal (overlong);
* the other continuations transition to N2
* N7 Start byte is F4. Continuation bytes 90-BF are illegal
* (non-unicode); the other continuations transition to N2
* 1 Reject. All transitions not mentioned above (except the single
* byte ones (as they are always legal) are to this state.
*/
# undef N0
# undef N1
# undef N2
# undef N3
# undef N4
# undef N5
# undef N6
# undef N7
# undef NUM_CLASSES
# define NUM_CLASSES 12
# define N0 0
# define N1 ((N0) + NUM_CLASSES)
# define N2 ((N1) + NUM_CLASSES)
# define N3 ((N2) + NUM_CLASSES)
# define N4 ((N3) + NUM_CLASSES)
# define N5 ((N4) + NUM_CLASSES)
# define N6 ((N5) + NUM_CLASSES)
# define N7 ((N6) + NUM_CLASSES)
/*Class: 0 1 2 3 4 5 6 7 8 9 10 11 */
/*N0*/ 0, 1, N1, N2, N5, N7, N3, N4, N6, 1, 1, 1,
/*N1*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
/*N2*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, N1, N1, N1,
/*N3*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, N2, N2, N2,
/*N4*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, N1,
/*N5*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, N1, N1, 1,
/*N6*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, N2, N2,
/*N7*/ 1, 1, 1, 1, 1, 1, 1, 1, 1, N2, 1, 1,
};
# else /* End of is DOINIT */
EXTCONST U8 PL_extended_utf8_dfa_tab[];
EXTCONST U8 PL_strict_utf8_dfa_tab[];
EXTCONST U8 PL_c9_utf8_dfa_tab[];
# endif
#endif /* end of isn't EBCDIC */
#ifndef PERL_NO_INLINE_FUNCTIONS
/* Static inline funcs that depend on includes and declarations above.
Some of these reference functions in the perl object files, and some
compilers aren't smart enough to eliminate unused static inline
functions, so including this file in source code can cause link errors
even if the source code uses none of the functions. Hence including these
can be suppressed by setting PERL_NO_INLINE_FUNCTIONS. Doing this will
(obviously) result in unworkable XS code, but allows simple probing code
to continue to work, because it permits tests to include the perl headers
for definitions without creating a link dependency on the perl library
(which may not exist yet).
*/
# include "inline.h"
#endif
#include "overload.h"
END_EXTERN_C
struct am_table {
U8 flags;
U8 fallback;
U16 spare;
U32 was_ok_sub;
CV* table[NofAMmeth];
};
struct am_table_short {
U8 flags;
U8 fallback;
U16 spare;
U32 was_ok_sub;
};
typedef struct am_table AMT;
typedef struct am_table_short AMTS;
#define AMGfallNEVER 1
#define AMGfallNO 2
#define AMGfallYES 3
#define AMTf_AMAGIC 1
#define AMT_AMAGIC(amt) ((amt)->flags & AMTf_AMAGIC)
#define AMT_AMAGIC_on(amt) ((amt)->flags |= AMTf_AMAGIC)
#define AMT_AMAGIC_off(amt) ((amt)->flags &= ~AMTf_AMAGIC)
#define StashHANDLER(stash,meth) gv_handler((stash),CAT2(meth,_amg))
/*
* some compilers like to redefine cos et alia as faster
* (and less accurate?) versions called F_cos et cetera (Quidquid
* latine dictum sit, altum viditur.) This trick collides with
* the Perl overloading (amg). The following #defines fool both.
*/
#ifdef _FASTMATH
# ifdef atan2
# define F_atan2_amg atan2_amg
# endif
# ifdef cos
# define F_cos_amg cos_amg
# endif
# ifdef exp
# define F_exp_amg exp_amg
# endif
# ifdef log
# define F_log_amg log_amg
# endif
# ifdef pow
# define F_pow_amg pow_amg
# endif
# ifdef sin
# define F_sin_amg sin_amg
# endif
# ifdef sqrt
# define F_sqrt_amg sqrt_amg
# endif
#endif /* _FASTMATH */
#define PERLDB_ALL (PERLDBf_SUB | PERLDBf_LINE | \
PERLDBf_NOOPT | PERLDBf_INTER | \
PERLDBf_SUBLINE| PERLDBf_SINGLE| \
PERLDBf_NAMEEVAL| PERLDBf_NAMEANON | \
PERLDBf_SAVESRC)
/* No _NONAME, _GOTO */
#define PERLDBf_SUB 0x01 /* Debug sub enter/exit */
#define PERLDBf_LINE 0x02 /* Keep line # */
#define PERLDBf_NOOPT 0x04 /* Switch off optimizations */
#define PERLDBf_INTER 0x08 /* Preserve more data for
later inspections */
#define PERLDBf_SUBLINE 0x10 /* Keep subr source lines */
#define PERLDBf_SINGLE 0x20 /* Start with single-step on */
#define PERLDBf_NONAME 0x40 /* For _SUB: no name of the subr */
#define PERLDBf_GOTO 0x80 /* Report goto: call DB::goto */
#define PERLDBf_NAMEEVAL 0x100 /* Informative names for evals */
#define PERLDBf_NAMEANON 0x200 /* Informative names for anon subs */
#define PERLDBf_SAVESRC 0x400 /* Save source lines into @{"_<$filename"} */
#define PERLDBf_SAVESRC_NOSUBS 0x800 /* Including evals that generate no subroutines */
#define PERLDBf_SAVESRC_INVALID 0x1000 /* Save source that did not compile */
#define PERLDB_SUB (PL_perldb & PERLDBf_SUB)
#define PERLDB_LINE (PL_perldb & PERLDBf_LINE)
#define PERLDB_NOOPT (PL_perldb & PERLDBf_NOOPT)
#define PERLDB_INTER (PL_perldb & PERLDBf_INTER)
#define PERLDB_SUBLINE (PL_perldb & PERLDBf_SUBLINE)
#define PERLDB_SINGLE (PL_perldb & PERLDBf_SINGLE)
#define PERLDB_SUB_NN (PL_perldb & PERLDBf_NONAME)
#define PERLDB_GOTO (PL_perldb & PERLDBf_GOTO)
#define PERLDB_NAMEEVAL (PL_perldb & PERLDBf_NAMEEVAL)
#define PERLDB_NAMEANON (PL_perldb & PERLDBf_NAMEANON)
#define PERLDB_SAVESRC (PL_perldb & PERLDBf_SAVESRC)
#define PERLDB_SAVESRC_NOSUBS (PL_perldb & PERLDBf_SAVESRC_NOSUBS)
#define PERLDB_SAVESRC_INVALID (PL_perldb & PERLDBf_SAVESRC_INVALID)
#define PERLDB_LINE_OR_SAVESRC (PL_perldb & (PERLDBf_LINE | PERLDBf_SAVESRC))
#ifdef USE_ITHREADS
# define KEYWORD_PLUGIN_MUTEX_INIT MUTEX_INIT(&PL_keyword_plugin_mutex)
# define KEYWORD_PLUGIN_MUTEX_LOCK MUTEX_LOCK(&PL_keyword_plugin_mutex)
# define KEYWORD_PLUGIN_MUTEX_UNLOCK MUTEX_UNLOCK(&PL_keyword_plugin_mutex)
# define KEYWORD_PLUGIN_MUTEX_TERM MUTEX_DESTROY(&PL_keyword_plugin_mutex)
# define USER_PROP_MUTEX_INIT MUTEX_INIT(&PL_user_prop_mutex)
# define USER_PROP_MUTEX_LOCK MUTEX_LOCK(&PL_user_prop_mutex)
# define USER_PROP_MUTEX_UNLOCK MUTEX_UNLOCK(&PL_user_prop_mutex)
# define USER_PROP_MUTEX_TERM MUTEX_DESTROY(&PL_user_prop_mutex)
#else
# define KEYWORD_PLUGIN_MUTEX_INIT NOOP
# define KEYWORD_PLUGIN_MUTEX_LOCK NOOP
# define KEYWORD_PLUGIN_MUTEX_UNLOCK NOOP
# define KEYWORD_PLUGIN_MUTEX_TERM NOOP
# define USER_PROP_MUTEX_INIT NOOP
# define USER_PROP_MUTEX_LOCK NOOP
# define USER_PROP_MUTEX_UNLOCK NOOP
# define USER_PROP_MUTEX_TERM NOOP
#endif
#ifdef USE_LOCALE /* These locale things are all subject to change */
/* Returns TRUE if the plain locale pragma without a parameter is in effect.
* */
# define IN_LOCALE_RUNTIME (PL_curcop \
&& CopHINTS_get(PL_curcop) & HINT_LOCALE)
/* Returns TRUE if either form of the locale pragma is in effect */
# define IN_SOME_LOCALE_FORM_RUNTIME \
cBOOL(CopHINTS_get(PL_curcop) & (HINT_LOCALE|HINT_LOCALE_PARTIAL))
# define IN_LOCALE_COMPILETIME cBOOL(PL_hints & HINT_LOCALE)
# define IN_SOME_LOCALE_FORM_COMPILETIME \
cBOOL(PL_hints & (HINT_LOCALE|HINT_LOCALE_PARTIAL))
/*
=head1 Locale-related functions and macros
=for apidoc Amn|bool|IN_LOCALE
Evaluates to TRUE if the plain locale pragma without a parameter (S<C<use
locale>>) is in effect.
=for apidoc Amn|bool|IN_LOCALE_COMPILETIME
Evaluates to TRUE if, when compiling a perl program (including an C<eval>) if
the plain locale pragma without a parameter (S<C<use locale>>) is in effect.
=for apidoc Amn|bool|IN_LOCALE_RUNTIME
Evaluates to TRUE if, when executing a perl program (including an C<eval>) if
the plain locale pragma without a parameter (S<C<use locale>>) is in effect.
=cut
*/
# define IN_LOCALE \
(IN_PERL_COMPILETIME ? IN_LOCALE_COMPILETIME : IN_LOCALE_RUNTIME)
# define IN_SOME_LOCALE_FORM \
(IN_PERL_COMPILETIME ? IN_SOME_LOCALE_FORM_COMPILETIME \
: IN_SOME_LOCALE_FORM_RUNTIME)
# define IN_LC_ALL_COMPILETIME IN_LOCALE_COMPILETIME
# define IN_LC_ALL_RUNTIME IN_LOCALE_RUNTIME
# define IN_LC_PARTIAL_COMPILETIME cBOOL(PL_hints & HINT_LOCALE_PARTIAL)
# define IN_LC_PARTIAL_RUNTIME \
(PL_curcop && CopHINTS_get(PL_curcop) & HINT_LOCALE_PARTIAL)
# define IN_LC_COMPILETIME(category) \
( IN_LC_ALL_COMPILETIME \
|| ( IN_LC_PARTIAL_COMPILETIME \
&& Perl__is_in_locale_category(aTHX_ TRUE, (category))))
# define IN_LC_RUNTIME(category) \
(IN_LC_ALL_RUNTIME || (IN_LC_PARTIAL_RUNTIME \
&& Perl__is_in_locale_category(aTHX_ FALSE, (category))))
# define IN_LC(category) \
(IN_LC_COMPILETIME(category) || IN_LC_RUNTIME(category))
# if defined (PERL_CORE) || defined (PERL_IN_XSUB_RE)
/* This internal macro should be called from places that operate under
* locale rules. If there is a problem with the current locale that
* hasn't been raised yet, it will output a warning this time. Because
* this will so rarely be true, there is no point to optimize for time;
* instead it makes sense to minimize space used and do all the work in
* the rarely called function */
# ifdef USE_LOCALE_CTYPE
# define _CHECK_AND_WARN_PROBLEMATIC_LOCALE \
STMT_START { \
if (UNLIKELY(PL_warn_locale)) { \
Perl__warn_problematic_locale(); \
} \
} STMT_END
# else
# define _CHECK_AND_WARN_PROBLEMATIC_LOCALE
# endif
/* These two internal macros are called when a warning should be raised,
* and will do so if enabled. The first takes a single code point
* argument; the 2nd, is a pointer to the first byte of the UTF-8 encoded
* string, and an end position which it won't try to read past */
# define _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(cp) \
STMT_START { \
if (! PL_in_utf8_CTYPE_locale && ckWARN(WARN_LOCALE)) { \
Perl_warner(aTHX_ packWARN(WARN_LOCALE), \
"Wide character (U+%" UVXf ") in %s",\
(UV) cp, OP_DESC(PL_op)); \
} \
} STMT_END
# define _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(s, send) \
STMT_START { /* Check if to warn before doing the conversion work */\
if (! PL_in_utf8_CTYPE_locale && ckWARN(WARN_LOCALE)) { \
UV cp = utf8_to_uvchr_buf((U8 *) (s), (U8 *) (send), NULL); \
Perl_warner(aTHX_ packWARN(WARN_LOCALE), \
"Wide character (U+%" UVXf ") in %s", \
(cp == 0) \
? UNICODE_REPLACEMENT \
: (UV) cp, \
OP_DESC(PL_op)); \
} \
} STMT_END
# endif /* PERL_CORE or PERL_IN_XSUB_RE */
#else /* No locale usage */
# define IN_LOCALE_RUNTIME 0
# define IN_SOME_LOCALE_FORM_RUNTIME 0
# define IN_LOCALE_COMPILETIME 0
# define IN_SOME_LOCALE_FORM_COMPILETIME 0
# define IN_LOCALE 0
# define IN_SOME_LOCALE_FORM 0
# define IN_LC_ALL_COMPILETIME 0
# define IN_LC_ALL_RUNTIME 0
# define IN_LC_PARTIAL_COMPILETIME 0
# define IN_LC_PARTIAL_RUNTIME 0
# define IN_LC_COMPILETIME(category) 0
# define IN_LC_RUNTIME(category) 0
# define IN_LC(category) 0
# define _CHECK_AND_WARN_PROBLEMATIC_LOCALE
# define _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(s, send)
# define _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c)
#endif
/* Locale/thread synchronization macros. These aren't needed if using
* thread-safe locale operations, except if something is broken */
#if defined(USE_LOCALE) \
&& defined(USE_ITHREADS) \
&& (! defined(USE_THREAD_SAFE_LOCALE) || defined(TS_W32_BROKEN_LOCALECONV))
/* We have a locale object holding the 'C' locale for Posix 2008 */
# ifndef USE_POSIX_2008_LOCALE
# define _LOCALE_TERM_POSIX_2008 NOOP
# else
# define _LOCALE_TERM_POSIX_2008 \
STMT_START { \
if (PL_C_locale_obj) { \
/* Make sure we aren't using the locale \
* space we are about to free */ \
uselocale(LC_GLOBAL_LOCALE); \
freelocale(PL_C_locale_obj); \
PL_C_locale_obj = (locale_t) NULL; \
} \
} STMT_END
# endif
/* This is used as a generic lock for locale operations. For example this is
* used when calling nl_langinfo() so that another thread won't zap the
* contents of its buffer before it gets saved; and it's called when changing
* the locale of LC_MESSAGES. On some systems the latter can cause the
* nl_langinfo buffer to be zapped under a race condition.
*
* If combined with LC_NUMERIC_LOCK, calls to this and its corresponding unlock
* should be contained entirely within the locked portion of LC_NUMERIC. This
* mutex should be used only in very short sections of code, while
* LC_NUMERIC_LOCK may span more operations. By always following this
* convention, deadlock should be impossible. But if necessary, the two
* mutexes could be combined.
*
* Actually, the two macros just below with the '_V' suffixes are used in just
* a few places where there is a broken localeconv(), but otherwise things are
* thread safe, and hence don't need locking. Just below LOCALE_LOCK and
* LOCALE_UNLOCK are defined in terms of these for use everywhere else */
# define LOCALE_LOCK_V \
STMT_START { \
DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
"%s: %d: locking locale\n", __FILE__, __LINE__)); \
MUTEX_LOCK(&PL_locale_mutex); \
} STMT_END
# define LOCALE_UNLOCK_V \
STMT_START { \
DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
"%s: %d: unlocking locale\n", __FILE__, __LINE__)); \
MUTEX_UNLOCK(&PL_locale_mutex); \
} STMT_END
/* On windows, we just need the mutex for LOCALE_LOCK */
# ifdef TS_W32_BROKEN_LOCALECONV
# define LOCALE_LOCK NOOP
# define LOCALE_UNLOCK NOOP
# define LOCALE_INIT MUTEX_INIT(&PL_locale_mutex);
# define LOCALE_TERM MUTEX_DESTROY(&PL_locale_mutex)
# define LC_NUMERIC_LOCK(cond)
# define LC_NUMERIC_UNLOCK
# else
# define LOCALE_LOCK LOCALE_LOCK_V
# define LOCALE_UNLOCK LOCALE_UNLOCK_V
/* We also need to lock LC_NUMERIC for non-windows (hence Posix 2008)
* systems */
# define LOCALE_INIT STMT_START { \
MUTEX_INIT(&PL_locale_mutex); \
MUTEX_INIT(&PL_lc_numeric_mutex); \
} STMT_END
# define LOCALE_TERM STMT_START { \
MUTEX_DESTROY(&PL_locale_mutex); \
MUTEX_DESTROY(&PL_lc_numeric_mutex); \
_LOCALE_TERM_POSIX_2008; \
} STMT_END
/* This mutex is used to create critical sections where we want the
* LC_NUMERIC locale to be locked into either the C (standard) locale, or
* the underlying locale, so that other threads interrupting this one don't
* change it to the wrong state before we've had a chance to complete our
* operation. It can stay locked over an entire printf operation, for
* example. And so is made distinct from the LOCALE_LOCK mutex.
*
* This simulates kind of a general semaphore. The current thread will
* lock the mutex if the per-thread variable is zero, and then increments
* that variable. Each corresponding UNLOCK decrements the variable until
* it is 0, at which point it actually unlocks the mutex. Since the
* variable is per-thread, there is no race with other threads.
*
* The single argument is a condition to test for, and if true, to panic,
* as this would be an attempt to complement the LC_NUMERIC state, and
* we're not supposed to because it's locked.
*
* Clang improperly gives warnings for this, if not silenced:
* https://clang.llvm.org/docs/ThreadSafetyAnalysis.html#conditional-locks
* */
# define LC_NUMERIC_LOCK(cond_to_panic_if_already_locked) \
CLANG_DIAG_IGNORE(-Wthread-safety) \
STMT_START { \
if (PL_lc_numeric_mutex_depth <= 0) { \
MUTEX_LOCK(&PL_lc_numeric_mutex); \
PL_lc_numeric_mutex_depth = 1; \
DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
"%s: %d: locking lc_numeric; depth=1\n", \
__FILE__, __LINE__)); \
} \
else { \
PL_lc_numeric_mutex_depth++; \
DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
"%s: %d: avoided lc_numeric_lock; new depth=%d\n", \
__FILE__, __LINE__, PL_lc_numeric_mutex_depth)); \
if (cond_to_panic_if_already_locked) { \
Perl_croak_nocontext("panic: %s: %d: Trying to change" \
" LC_NUMERIC incompatibly", \
__FILE__, __LINE__); \
} \
} \
} STMT_END
# define LC_NUMERIC_UNLOCK \
STMT_START { \
if (PL_lc_numeric_mutex_depth <= 1) { \
MUTEX_UNLOCK(&PL_lc_numeric_mutex); \
PL_lc_numeric_mutex_depth = 0; \
DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
"%s: %d: unlocking lc_numeric; depth=0\n", \
__FILE__, __LINE__)); \
} \
else { \
PL_lc_numeric_mutex_depth--; \
DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
"%s: %d: avoided lc_numeric_unlock; new depth=%d\n",\
__FILE__, __LINE__, PL_lc_numeric_mutex_depth)); \
} \
} STMT_END \
CLANG_DIAG_RESTORE
# endif /* End of needs locking LC_NUMERIC */
#else /* Below is no locale sync needed */
# define LOCALE_INIT
# define LOCALE_LOCK
# define LOCALE_LOCK_V
# define LOCALE_UNLOCK
# define LOCALE_UNLOCK_V
# define LC_NUMERIC_LOCK(cond)
# define LC_NUMERIC_UNLOCK
# define LOCALE_TERM
#endif
#ifdef USE_LOCALE_NUMERIC
/* These macros are for toggling between the underlying locale (UNDERLYING or
* LOCAL) and the C locale (STANDARD). (Actually we don't have to use the C
* locale if the underlying locale is indistinguishable from it in the numeric
* operations used by Perl, namely the decimal point, and even the thousands
* separator.)
=head1 Locale-related functions and macros
=for apidoc Amn|void|DECLARATION_FOR_LC_NUMERIC_MANIPULATION
This macro should be used as a statement. It declares a private variable
(whose name begins with an underscore) that is needed by the other macros in
this section. Failing to include this correctly should lead to a syntax error.
For compatibility with C89 C compilers it should be placed in a block before
any executable statements.
=for apidoc Am|void|STORE_LC_NUMERIC_FORCE_TO_UNDERLYING
This is used by XS code that is C<LC_NUMERIC> locale-aware to force the
locale for category C<LC_NUMERIC> to be what perl thinks is the current
underlying locale. (The perl interpreter could be wrong about what the
underlying locale actually is if some C or XS code has called the C library
function L<setlocale(3)> behind its back; calling L</sync_locale> before calling
this macro will update perl's records.)
A call to L</DECLARATION_FOR_LC_NUMERIC_MANIPULATION> must have been made to
declare at compile time a private variable used by this macro. This macro
should be called as a single statement, not an expression, but with an empty
argument list, like this:
{
DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
...
STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
...
RESTORE_LC_NUMERIC();
...
}
The private variable is used to save the current locale state, so
that the requisite matching call to L</RESTORE_LC_NUMERIC> can restore it.
On threaded perls not operating with thread-safe functionality, this macro uses
a mutex to force a critical section. Therefore the matching RESTORE should be
close by, and guaranteed to be called.
=for apidoc Am|void|STORE_LC_NUMERIC_SET_TO_NEEDED
This is used to help wrap XS or C code that is C<LC_NUMERIC> locale-aware.
This locale category is generally kept set to a locale where the decimal radix
character is a dot, and the separator between groups of digits is empty. This
is because most XS code that reads floating point numbers is expecting them to
have this syntax.
This macro makes sure the current C<LC_NUMERIC> state is set properly, to be
aware of locale if the call to the XS or C code from the Perl program is
from within the scope of a S<C<use locale>>; or to ignore locale if the call is
instead from outside such scope.
This macro is the start of wrapping the C or XS code; the wrap ending is done
by calling the L</RESTORE_LC_NUMERIC> macro after the operation. Otherwise
the state can be changed that will adversely affect other XS code.
A call to L</DECLARATION_FOR_LC_NUMERIC_MANIPULATION> must have been made to
declare at compile time a private variable used by this macro. This macro
should be called as a single statement, not an expression, but with an empty
argument list, like this:
{
DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
...
STORE_LC_NUMERIC_SET_TO_NEEDED();
...
RESTORE_LC_NUMERIC();
...
}
On threaded perls not operating with thread-safe functionality, this macro uses
a mutex to force a critical section. Therefore the matching RESTORE should be
close by, and guaranteed to be called; see L</WITH_LC_NUMERIC_SET_TO_NEEDED>
for a more contained way to ensure that.
=for apidoc Am|void|STORE_LC_NUMERIC_SET_TO_NEEDED_IN|bool in_lc_numeric
Same as L</STORE_LC_NUMERIC_SET_TO_NEEDED> with in_lc_numeric provided
as the precalculated value of C<IN_LC(LC_NUMERIC)>. It is the caller's
responsibility to ensure that the status of C<PL_compiling> and C<PL_hints>
cannot have changed since the precalculation.
=for apidoc Am|void|RESTORE_LC_NUMERIC
This is used in conjunction with one of the macros
L</STORE_LC_NUMERIC_SET_TO_NEEDED>
and L</STORE_LC_NUMERIC_FORCE_TO_UNDERLYING> to properly restore the
C<LC_NUMERIC> state.
A call to L</DECLARATION_FOR_LC_NUMERIC_MANIPULATION> must have been made to
declare at compile time a private variable used by this macro and the two
C<STORE> ones. This macro should be called as a single statement, not an
expression, but with an empty argument list, like this:
{
DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
...
RESTORE_LC_NUMERIC();
...
}
=for apidoc Am|void|WITH_LC_NUMERIC_SET_TO_NEEDED|block
This macro invokes the supplied statement or block within the context
of a L</STORE_LC_NUMERIC_SET_TO_NEEDED> .. L</RESTORE_LC_NUMERIC> pair
if required, so eg:
WITH_LC_NUMERIC_SET_TO_NEEDED(
SNPRINTF_G(fv, ebuf, sizeof(ebuf), precis)
);
is equivalent to:
{
#ifdef USE_LOCALE_NUMERIC
DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
STORE_LC_NUMERIC_SET_TO_NEEDED();
#endif
SNPRINTF_G(fv, ebuf, sizeof(ebuf), precis);
#ifdef USE_LOCALE_NUMERIC
RESTORE_LC_NUMERIC();
#endif
}
=for apidoc Am|void|WITH_LC_NUMERIC_SET_TO_NEEDED_IN|bool in_lc_numeric|block
Same as L</WITH_LC_NUMERIC_SET_TO_NEEDED> with in_lc_numeric provided
as the precalculated value of C<IN_LC(LC_NUMERIC)>. It is the caller's
responsibility to ensure that the status of C<PL_compiling> and C<PL_hints>
cannot have changed since the precalculation.
=cut
*/
/* If the underlying numeric locale has a non-dot decimal point or has a
* non-empty floating point thousands separator, the current locale is instead
* generally kept in the C locale instead of that underlying locale. The
* current status is known by looking at two words. One is non-zero if the
* current numeric locale is the standard C/POSIX one or is indistinguishable
* from C. The other is non-zero if the current locale is the underlying
* locale. Both can be non-zero if, as often happens, the underlying locale is
* C or indistinguishable from it.
*
* khw believes the reason for the variables instead of the bits in a single
* word is to avoid having to have masking instructions. */
# define _NOT_IN_NUMERIC_STANDARD (! PL_numeric_standard)
/* We can lock the category to stay in the C locale, making requests to the
* contrary be noops, in the dynamic scope by setting PL_numeric_standard to 2.
* */
# define _NOT_IN_NUMERIC_UNDERLYING \
(! PL_numeric_underlying && PL_numeric_standard < 2)
# define DECLARATION_FOR_LC_NUMERIC_MANIPULATION \
void (*_restore_LC_NUMERIC_function)(pTHX) = NULL
# define STORE_LC_NUMERIC_SET_TO_NEEDED_IN(in) \
STMT_START { \
bool _in_lc_numeric = (in); \
LC_NUMERIC_LOCK( \
( ( _in_lc_numeric && _NOT_IN_NUMERIC_UNDERLYING) \
|| (! _in_lc_numeric && _NOT_IN_NUMERIC_STANDARD))); \
if (_in_lc_numeric) { \
if (_NOT_IN_NUMERIC_UNDERLYING) { \
Perl_set_numeric_underlying(aTHX); \
_restore_LC_NUMERIC_function \
= &Perl_set_numeric_standard; \
} \
} \
else { \
if (_NOT_IN_NUMERIC_STANDARD) { \
Perl_set_numeric_standard(aTHX); \
_restore_LC_NUMERIC_function \
= &Perl_set_numeric_underlying; \
} \
} \
} STMT_END
# define STORE_LC_NUMERIC_SET_TO_NEEDED() \
STORE_LC_NUMERIC_SET_TO_NEEDED_IN(IN_LC(LC_NUMERIC))
# define RESTORE_LC_NUMERIC() \
STMT_START { \
if (_restore_LC_NUMERIC_function) { \
_restore_LC_NUMERIC_function(aTHX); \
} \
LC_NUMERIC_UNLOCK; \
} STMT_END
/* The next two macros set unconditionally. These should be rarely used, and
* only after being sure that this is what is needed */
# define SET_NUMERIC_STANDARD() \
STMT_START { \
DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
"%s: %d: lc_numeric standard=%d\n", \
__FILE__, __LINE__, PL_numeric_standard)); \
Perl_set_numeric_standard(aTHX); \
DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
"%s: %d: lc_numeric standard=%d\n", \
__FILE__, __LINE__, PL_numeric_standard)); \
} STMT_END
# define SET_NUMERIC_UNDERLYING() \
STMT_START { \
if (_NOT_IN_NUMERIC_UNDERLYING) { \
Perl_set_numeric_underlying(aTHX); \
} \
} STMT_END
/* The rest of these LC_NUMERIC macros toggle to one or the other state, with
* the RESTORE_foo ones called to switch back, but only if need be */
# define STORE_LC_NUMERIC_SET_STANDARD() \
STMT_START { \
LC_NUMERIC_LOCK(_NOT_IN_NUMERIC_STANDARD); \
if (_NOT_IN_NUMERIC_STANDARD) { \
_restore_LC_NUMERIC_function = &Perl_set_numeric_underlying;\
Perl_set_numeric_standard(aTHX); \
} \
} STMT_END
/* Rarely, we want to change to the underlying locale even outside of 'use
* locale'. This is principally in the POSIX:: functions */
# define STORE_LC_NUMERIC_FORCE_TO_UNDERLYING() \
STMT_START { \
LC_NUMERIC_LOCK(_NOT_IN_NUMERIC_UNDERLYING); \
if (_NOT_IN_NUMERIC_UNDERLYING) { \
Perl_set_numeric_underlying(aTHX); \
_restore_LC_NUMERIC_function = &Perl_set_numeric_standard; \
} \
} STMT_END
/* Lock/unlock to the C locale until unlock is called. This needs to be
* recursively callable. [perl #128207] */
# define LOCK_LC_NUMERIC_STANDARD() \
STMT_START { \
DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
"%s: %d: lock lc_numeric_standard: new depth=%d\n", \
__FILE__, __LINE__, PL_numeric_standard + 1)); \
__ASSERT_(PL_numeric_standard) \
PL_numeric_standard++; \
} STMT_END
# define UNLOCK_LC_NUMERIC_STANDARD() \
STMT_START { \
if (PL_numeric_standard > 1) { \
PL_numeric_standard--; \
} \
else { \
assert(0); \
} \
DEBUG_Lv(PerlIO_printf(Perl_debug_log, \
"%s: %d: lc_numeric_standard decrement lock, new depth=%d\n", \
__FILE__, __LINE__, PL_numeric_standard)); \
} STMT_END
# define WITH_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric, block) \
STMT_START { \
DECLARATION_FOR_LC_NUMERIC_MANIPULATION; \
STORE_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric); \
block; \
RESTORE_LC_NUMERIC(); \
} STMT_END;
# define WITH_LC_NUMERIC_SET_TO_NEEDED(block) \
WITH_LC_NUMERIC_SET_TO_NEEDED_IN(IN_LC(LC_NUMERIC), block)
#else /* !USE_LOCALE_NUMERIC */
# define SET_NUMERIC_STANDARD()
# define SET_NUMERIC_UNDERLYING()
# define IS_NUMERIC_RADIX(a, b) (0)
# define DECLARATION_FOR_LC_NUMERIC_MANIPULATION dNOOP
# define STORE_LC_NUMERIC_SET_STANDARD()
# define STORE_LC_NUMERIC_FORCE_TO_UNDERLYING()
# define STORE_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric)
# define STORE_LC_NUMERIC_SET_TO_NEEDED()
# define RESTORE_LC_NUMERIC()
# define LOCK_LC_NUMERIC_STANDARD()
# define UNLOCK_LC_NUMERIC_STANDARD()
# define WITH_LC_NUMERIC_SET_TO_NEEDED_IN(in_lc_numeric, block) \
STMT_START { block; } STMT_END
# define WITH_LC_NUMERIC_SET_TO_NEEDED(block) \
STMT_START { block; } STMT_END
#endif /* !USE_LOCALE_NUMERIC */
#define Atof my_atof
/*
=head1 Numeric functions
=for apidoc AmTR|NV|Strtod|NN const char * const s|NULLOK char ** e
This is a synonym for L</my_strtod>.
=for apidoc AmTR|NV|Strtol|NN const char * const s|NULLOK char ** e|int base
Platform and configuration independent C<strtol>. This expands to the
appropriate C<strotol>-like function based on the platform and F<Configure>
options>. For example it could expand to C<strtoll> or C<strtoq> instead of
C<strtol>.
=for apidoc AmTR|NV|Strtoul|NN const char * const s|NULLOK char ** e|int base
Platform and configuration independent C<strtoul>. This expands to the
appropriate C<strotoul>-like function based on the platform and F<Configure>
options>. For example it could expand to C<strtoull> or C<strtouq> instead of
C<strtoul>.
=cut
*/
#define Strtod my_strtod
#if defined(HAS_STRTOD) \
|| defined(USE_QUADMATH) \
|| (defined(HAS_STRTOLD) && defined(HAS_LONG_DOUBLE) \
&& defined(USE_LONG_DOUBLE))
# define Perl_strtod Strtod
#endif
#if !defined(Strtol) && defined(USE_64_BIT_INT) && defined(IV_IS_QUAD) && \
(QUADKIND == QUAD_IS_LONG_LONG || QUADKIND == QUAD_IS___INT64)
# ifdef __hpux
# define strtoll __strtoll /* secret handshake */
# endif
# if defined(WIN64) && defined(_MSC_VER)
# define strtoll _strtoi64 /* secret handshake */
# endif
# if !defined(Strtol) && defined(HAS_STRTOLL)
# define Strtol strtoll
# endif
# if !defined(Strtol) && defined(HAS_STRTOQ)
# define Strtol strtoq
# endif
/* is there atoq() anywhere? */
#endif
#if !defined(Strtol) && defined(HAS_STRTOL)
# define Strtol strtol
#endif
#ifndef Atol
/* It would be more fashionable to use Strtol() to define atol()
* (as is done for Atoul(), see below) but for backward compatibility
* we just assume atol(). */
# if defined(USE_64_BIT_INT) && defined(IV_IS_QUAD) && defined(HAS_ATOLL) && \
(QUADKIND == QUAD_IS_LONG_LONG || QUADKIND == QUAD_IS___INT64)
# ifdef WIN64
# define atoll _atoi64 /* secret handshake */
# endif
# define Atol atoll
# else
# define Atol atol
# endif
#endif
#if !defined(Strtoul) && defined(USE_64_BIT_INT) && defined(UV_IS_QUAD) && \
(QUADKIND == QUAD_IS_LONG_LONG || QUADKIND == QUAD_IS___INT64)
# ifdef __hpux
# define strtoull __strtoull /* secret handshake */
# endif
# if defined(WIN64) && defined(_MSC_VER)
# define strtoull _strtoui64 /* secret handshake */
# endif
# if !defined(Strtoul) && defined(HAS_STRTOULL)
# define Strtoul strtoull
# endif
# if !defined(Strtoul) && defined(HAS_STRTOUQ)
# define Strtoul strtouq
# endif
/* is there atouq() anywhere? */
#endif
#if !defined(Strtoul) && defined(HAS_STRTOUL)
# define Strtoul strtoul
#endif
#if !defined(Strtoul) && defined(HAS_STRTOL) /* Last resort. */
# define Strtoul(s, e, b) strchr((s), '-') ? ULONG_MAX : (unsigned long)strtol((s), (e), (b))
#endif
#ifndef Atoul
# define Atoul(s) Strtoul(s, NULL, 10)
#endif
#define grok_bin(s,lp,fp,rp) \
grok_bin_oct_hex(s, lp, fp, rp, 1, _CC_BINDIGIT, 'b')
#define grok_oct(s,lp,fp,rp) \
(*(fp) |= PERL_SCAN_DISALLOW_PREFIX, \
grok_bin_oct_hex(s, lp, fp, rp, 3, _CC_OCTDIGIT, '\0'))
#define grok_hex(s,lp,fp,rp) \
grok_bin_oct_hex(s, lp, fp, rp, 4, _CC_XDIGIT, 'x')
#ifndef PERL_SCRIPT_MODE
#define PERL_SCRIPT_MODE "r"
#endif
/* not used. Kept as a NOOP for backcompat */
#define PERL_STACK_OVERFLOW_CHECK() NOOP
/*
* Some nonpreemptive operating systems find it convenient to
* check for asynchronous conditions after each op execution.
* Keep this check simple, or it may slow down execution
* massively.
*/
#ifndef PERL_MICRO
# ifndef PERL_ASYNC_CHECK
# define PERL_ASYNC_CHECK() if (UNLIKELY(PL_sig_pending)) PL_signalhook(aTHX)
# endif
#endif
#ifndef PERL_ASYNC_CHECK
# define PERL_ASYNC_CHECK() NOOP
#endif
/*
* On some operating systems, a memory allocation may succeed,
* but put the process too close to the system's comfort limit.
* In this case, PERL_ALLOC_CHECK frees the pointer and sets
* it to NULL.
*/
#ifndef PERL_ALLOC_CHECK
#define PERL_ALLOC_CHECK(p) NOOP
#endif
#ifdef HAS_SEM
# include <sys/ipc.h>
# include <sys/sem.h>
# ifndef HAS_UNION_SEMUN /* Provide the union semun. */
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
};
# endif
# ifdef USE_SEMCTL_SEMUN
# ifdef IRIX32_SEMUN_BROKEN_BY_GCC
union gccbug_semun {
int val;
struct semid_ds *buf;
unsigned short *array;
char __dummy[5];
};
# define semun gccbug_semun
# endif
# define Semctl(id, num, cmd, semun) semctl(id, num, cmd, semun)
# elif defined(USE_SEMCTL_SEMID_DS)
# ifdef EXTRA_F_IN_SEMUN_BUF
# define Semctl(id, num, cmd, semun) semctl(id, num, cmd, semun.buff)
# else
# define Semctl(id, num, cmd, semun) semctl(id, num, cmd, semun.buf)
# endif
# endif
#endif
/*
* Boilerplate macros for initializing and accessing interpreter-local
* data from C. All statics in extensions should be reworked to use
* this, if you want to make the extension thread-safe. See
* ext/XS/APItest/APItest.xs for an example of the use of these macros,
* and perlxs.pod for more.
*
* Code that uses these macros is responsible for the following:
* 1. #define MY_CXT_KEY to a unique string, e.g.
* "DynaLoader::_guts" XS_VERSION
* XXX in the current implementation, this string is ignored.
* 2. Declare a typedef named my_cxt_t that is a structure that contains
* all the data that needs to be interpreter-local.
* 3. Use the START_MY_CXT macro after the declaration of my_cxt_t.
* 4. Use the MY_CXT_INIT macro such that it is called exactly once
* (typically put in the BOOT: section).
* 5. Use the members of the my_cxt_t structure everywhere as
* MY_CXT.member.
* 6. Use the dMY_CXT macro (a declaration) in all the functions that
* access MY_CXT.
*/
#if defined(PERL_IMPLICIT_CONTEXT)
/* START_MY_CXT must appear in all extensions that define a my_cxt_t structure,
* right after the definition (i.e. at file scope). The non-threads
* case below uses it to declare the data as static. */
# ifdef PERL_GLOBAL_STRUCT_PRIVATE
# define START_MY_CXT
# define MY_CXT_INDEX Perl_my_cxt_index(aTHX_ MY_CXT_KEY)
# define MY_CXT_INIT_ARG MY_CXT_KEY
# else
# define START_MY_CXT static int my_cxt_index = -1;
# define MY_CXT_INDEX my_cxt_index
# define MY_CXT_INIT_ARG &my_cxt_index
# endif /* #ifdef PERL_GLOBAL_STRUCT_PRIVATE */
/* Creates and zeroes the per-interpreter data.
* (We allocate my_cxtp in a Perl SV so that it will be released when
* the interpreter goes away.) */
# define MY_CXT_INIT \
my_cxt_t *my_cxtp = \
(my_cxt_t*)Perl_my_cxt_init(aTHX_ MY_CXT_INIT_ARG, sizeof(my_cxt_t)); \
PERL_UNUSED_VAR(my_cxtp)
# define MY_CXT_INIT_INTERP(my_perl) \
my_cxt_t *my_cxtp = \
(my_cxt_t*)Perl_my_cxt_init(my_perl, MY_CXT_INIT_ARG, sizeof(my_cxt_t)); \
PERL_UNUSED_VAR(my_cxtp)
/* This declaration should be used within all functions that use the
* interpreter-local data. */
# define dMY_CXT \
my_cxt_t *my_cxtp = (my_cxt_t *)PL_my_cxt_list[MY_CXT_INDEX]
# define dMY_CXT_INTERP(my_perl) \
my_cxt_t *my_cxtp = (my_cxt_t *)(my_perl)->Imy_cxt_list[MY_CXT_INDEX]
/* Clones the per-interpreter data. */
# define MY_CXT_CLONE \
my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1));\
void * old_my_cxtp = PL_my_cxt_list[MY_CXT_INDEX]; \
PL_my_cxt_list[MY_CXT_INDEX] = my_cxtp; \
Copy(old_my_cxtp, my_cxtp, 1, my_cxt_t);
/* This macro must be used to access members of the my_cxt_t structure.
* e.g. MY_CXT.some_data */
# define MY_CXT (*my_cxtp)
/* Judicious use of these macros can reduce the number of times dMY_CXT
* is used. Use is similar to pTHX, aTHX etc. */
# define pMY_CXT my_cxt_t *my_cxtp
# define pMY_CXT_ pMY_CXT,
# define _pMY_CXT ,pMY_CXT
# define aMY_CXT my_cxtp
# define aMY_CXT_ aMY_CXT,
# define _aMY_CXT ,aMY_CXT
#else /* PERL_IMPLICIT_CONTEXT */
# define START_MY_CXT static my_cxt_t my_cxt;
# define dMY_CXT_SV dNOOP
# define dMY_CXT dNOOP
# define dMY_CXT_INTERP(my_perl) dNOOP
# define MY_CXT_INIT NOOP
# define MY_CXT_CLONE NOOP
# define MY_CXT my_cxt
# define pMY_CXT void
# define pMY_CXT_
# define _pMY_CXT
# define aMY_CXT
# define aMY_CXT_
# define _aMY_CXT
#endif /* !defined(PERL_IMPLICIT_CONTEXT) */
#ifdef I_FCNTL
# include <fcntl.h>
#endif
#ifdef __Lynx__
# include <fcntl.h>
#endif
#ifdef __amigaos4__
# undef FD_CLOEXEC /* a lie in AmigaOS */
#endif
#ifdef I_SYS_FILE
# include <sys/file.h>
#endif
#if defined(HAS_FLOCK) && !defined(HAS_FLOCK_PROTO)
EXTERN_C int flock(int fd, int op);
#endif
#ifndef O_RDONLY
/* Assume UNIX defaults */
# define O_RDONLY 0000
# define O_WRONLY 0001
# define O_RDWR 0002
# define O_CREAT 0100
#endif
#ifndef O_BINARY
# define O_BINARY 0
#endif
#ifndef O_TEXT
# define O_TEXT 0
#endif
#if O_TEXT != O_BINARY
/* If you have different O_TEXT and O_BINARY and you are a CRLF shop,
* that is, you are somehow DOSish. */
# if defined(__HAIKU__) || defined(__VOS__) || defined(__CYGWIN__)
/* Haiku has O_TEXT != O_BINARY but O_TEXT and O_BINARY have no effect;
* Haiku is always UNIXoid (LF), not DOSish (CRLF). */
/* VOS has O_TEXT != O_BINARY, and they have effect,
* but VOS always uses LF, never CRLF. */
/* If you have O_TEXT different from your O_BINARY but you still are
* not a CRLF shop. */
# undef PERLIO_USING_CRLF
# else
/* If you really are DOSish. */
# define PERLIO_USING_CRLF 1
# endif
#endif
#ifdef I_LIBUTIL
# include <libutil.h> /* setproctitle() in some FreeBSDs */
#endif
#ifndef EXEC_ARGV_CAST
#define EXEC_ARGV_CAST(x) (char **)x
#endif
#define IS_NUMBER_IN_UV 0x01 /* number within UV range (maybe not
int). value returned in pointed-
to UV */
#define IS_NUMBER_GREATER_THAN_UV_MAX 0x02 /* pointed to UV undefined */
#define IS_NUMBER_NOT_INT 0x04 /* saw . or E notation or infnan */
#define IS_NUMBER_NEG 0x08 /* leading minus sign */
#define IS_NUMBER_INFINITY 0x10 /* this is big */
#define IS_NUMBER_NAN 0x20 /* this is not */
#define IS_NUMBER_TRAILING 0x40 /* number has trailing trash */
/*
=head1 Numeric functions
=for apidoc AmdR|bool|GROK_NUMERIC_RADIX|NN const char **sp|NN const char *send
A synonym for L</grok_numeric_radix>
=cut
*/
#define GROK_NUMERIC_RADIX(sp, send) grok_numeric_radix(sp, send)
/* Number scan flags. All are used for input, the ones used for output are so
* marked */
#define PERL_SCAN_ALLOW_UNDERSCORES 0x01 /* grok_??? accept _ in numbers */
#define PERL_SCAN_DISALLOW_PREFIX 0x02 /* grok_??? reject 0x in hex etc */
/* grok_??? input: ignored; output: found overflow */
#define PERL_SCAN_GREATER_THAN_UV_MAX 0x04
/* grok_??? don't warn about illegal digits. To preserve total backcompat,
* this isn't set on output if one is found. Instead, see
* PERL_SCAN_NOTIFY_ILLDIGIT. */
#define PERL_SCAN_SILENT_ILLDIGIT 0x08
#define PERL_SCAN_TRAILING 0x10 /* grok_number_flags() allow trailing
and set IS_NUMBER_TRAILING */
/* These are considered experimental, so not exposed publicly */
#if defined(PERL_CORE) || defined(PERL_EXT)
/* grok_??? don't warn about very large numbers which are <= UV_MAX;
* output: found such a number */
# define PERL_SCAN_SILENT_NON_PORTABLE 0x20
/* If this is set on input, and no illegal digit is found, it will be cleared
* on output; otherwise unchanged */
# define PERL_SCAN_NOTIFY_ILLDIGIT 0x40
/* Don't warn on overflow; output flag still set */
# define PERL_SCAN_SILENT_OVERFLOW 0x80
/* Forbid a leading underscore, which the other one doesn't */
# define PERL_SCAN_ALLOW_MEDIAL_UNDERSCORES (0x100|PERL_SCAN_ALLOW_UNDERSCORES)
#endif
/* to let user control profiling */
#ifdef PERL_GPROF_CONTROL
extern void moncontrol(int);
#define PERL_GPROF_MONCONTROL(x) moncontrol(x)
#else
#define PERL_GPROF_MONCONTROL(x)
#endif
/* ISO 6429 NEL - C1 control NExt Line */
/* See https://www.unicode.org/unicode/reports/tr13/ */
#define NEXT_LINE_CHAR NEXT_LINE_NATIVE
#ifndef PIPESOCK_MODE
# define PIPESOCK_MODE
#endif
#ifndef SOCKET_OPEN_MODE
# define SOCKET_OPEN_MODE PIPESOCK_MODE
#endif
#ifndef PIPE_OPEN_MODE
# define PIPE_OPEN_MODE PIPESOCK_MODE
#endif
#define PERL_MAGIC_UTF8_CACHESIZE 2
#define PERL_UNICODE_STDIN_FLAG 0x0001
#define PERL_UNICODE_STDOUT_FLAG 0x0002
#define PERL_UNICODE_STDERR_FLAG 0x0004
#define PERL_UNICODE_IN_FLAG 0x0008
#define PERL_UNICODE_OUT_FLAG 0x0010
#define PERL_UNICODE_ARGV_FLAG 0x0020
#define PERL_UNICODE_LOCALE_FLAG 0x0040
#define PERL_UNICODE_WIDESYSCALLS_FLAG 0x0080 /* for Sarathy */
#define PERL_UNICODE_UTF8CACHEASSERT_FLAG 0x0100
#define PERL_UNICODE_STD_FLAG \
(PERL_UNICODE_STDIN_FLAG | \
PERL_UNICODE_STDOUT_FLAG | \
PERL_UNICODE_STDERR_FLAG)
#define PERL_UNICODE_INOUT_FLAG \
(PERL_UNICODE_IN_FLAG | \
PERL_UNICODE_OUT_FLAG)
#define PERL_UNICODE_DEFAULT_FLAGS \
(PERL_UNICODE_STD_FLAG | \
PERL_UNICODE_INOUT_FLAG | \
PERL_UNICODE_LOCALE_FLAG)
#define PERL_UNICODE_ALL_FLAGS 0x01ff
#define PERL_UNICODE_STDIN 'I'
#define PERL_UNICODE_STDOUT 'O'
#define PERL_UNICODE_STDERR 'E'
#define PERL_UNICODE_STD 'S'
#define PERL_UNICODE_IN 'i'
#define PERL_UNICODE_OUT 'o'
#define PERL_UNICODE_INOUT 'D'
#define PERL_UNICODE_ARGV 'A'
#define PERL_UNICODE_LOCALE 'L'
#define PERL_UNICODE_WIDESYSCALLS 'W'
#define PERL_UNICODE_UTF8CACHEASSERT 'a'
#define PERL_SIGNALS_UNSAFE_FLAG 0x0001
/*
=head1 Numeric functions
=for apidoc Am|int|PERL_ABS|int
Typeless C<abs> or C<fabs>, I<etc>. (The usage below indicates it is for
integers, but it works for any type.) Use instead of these, since the C
library ones force their argument to be what it is expecting, potentially
leading to disaster. But also beware that this evaluates its argument twice,
so no C<x++>.
=cut
*/
#define PERL_ABS(x) ((x) < 0 ? -(x) : (x))
#if defined(__DECC) && defined(__osf__)
#pragma message disable (mainparm) /* Perl uses the envp in main(). */
#endif
#define do_open(g, n, l, a, rm, rp, sf) \
do_openn(g, n, l, a, rm, rp, sf, (SV **) NULL, 0)
#ifdef PERL_DEFAULT_DO_EXEC3_IMPLEMENTATION
# define do_exec(cmd) do_exec3(cmd,0,0)
#endif
#ifdef OS2
# define do_aexec Perl_do_aexec
#else
# define do_aexec(really, mark,sp) do_aexec5(really, mark, sp, 0, 0)
#endif
/*
=head1 Miscellaneous Functions
=for apidoc Am|bool|IS_SAFE_SYSCALL|NN const char *pv|STRLEN len|NN const char *what|NN const char *op_name
Same as L</is_safe_syscall>.
=cut
Allows one ending \0
*/
#define IS_SAFE_SYSCALL(p, len, what, op_name) (Perl_is_safe_syscall(aTHX_ (p), (len), (what), (op_name)))
#define IS_SAFE_PATHNAME(p, len, op_name) IS_SAFE_SYSCALL((p), (len), "pathname", (op_name))
#if defined(OEMVS) || defined(__amigaos4__)
#define NO_ENV_ARRAY_IN_MAIN
#endif
/* These are used by Perl_pv_escape() and Perl_pv_pretty()
* are here so that they are available throughout the core
* NOTE that even though some are for _escape and some for _pretty
* there must not be any clashes as the flags from _pretty are
* passed straight through to _escape.
*/
#define PERL_PV_ESCAPE_QUOTE 0x000001
#define PERL_PV_PRETTY_QUOTE PERL_PV_ESCAPE_QUOTE
#define PERL_PV_PRETTY_ELLIPSES 0x000002
#define PERL_PV_PRETTY_LTGT 0x000004
#define PERL_PV_PRETTY_EXACTSIZE 0x000008
#define PERL_PV_ESCAPE_UNI 0x000100
#define PERL_PV_ESCAPE_UNI_DETECT 0x000200
#define PERL_PV_ESCAPE_NONASCII 0x000400
#define PERL_PV_ESCAPE_FIRSTCHAR 0x000800
#define PERL_PV_ESCAPE_ALL 0x001000
#define PERL_PV_ESCAPE_NOBACKSLASH 0x002000
#define PERL_PV_ESCAPE_NOCLEAR 0x004000
#define PERL_PV_PRETTY_NOCLEAR PERL_PV_ESCAPE_NOCLEAR
#define PERL_PV_ESCAPE_RE 0x008000
#define PERL_PV_ESCAPE_DWIM 0x010000
/* used by pv_display in dump.c*/
#define PERL_PV_PRETTY_DUMP PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE
#define PERL_PV_PRETTY_REGPROP PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_LTGT|PERL_PV_ESCAPE_RE|PERL_PV_ESCAPE_NONASCII
#if DOUBLEKIND == DOUBLE_IS_VAX_F_FLOAT || \
DOUBLEKIND == DOUBLE_IS_VAX_D_FLOAT || \
DOUBLEKIND == DOUBLE_IS_VAX_G_FLOAT
# define DOUBLE_IS_VAX_FLOAT
#else
# define DOUBLE_IS_IEEE_FORMAT
#endif
#if DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_LITTLE_ENDIAN || \
DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_LITTLE_ENDIAN || \
DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
# define DOUBLE_LITTLE_ENDIAN
#endif
#if DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_BIG_ENDIAN || \
DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_BIG_ENDIAN || \
DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
# define DOUBLE_BIG_ENDIAN
#endif
#if DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_LE_BE || \
DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_BE_LE
# define DOUBLE_MIX_ENDIAN
#endif
/* The VAX fp formats are neither consistently little-endian nor
* big-endian, and neither are they really IEEE-mixed endian like
* the mixed-endian ARM IEEE formats (with swapped bytes).
* Ultimately, the VAX format came from the PDP-11.
*
* The ordering of the parts in VAX floats is quite vexing.
* In the below the fraction_n are the mantissa bits.
*
* The fraction_1 is the most significant (numbering as by DEC/Digital),
* while the rightmost bit in each fraction is the least significant:
* in other words, big-endian bit order within the fractions.
*
* The fraction segments themselves would be big-endianly, except that
* within 32 bit segments the less significant half comes first, the more
* significant after, except that in the format H (used for long doubles)
* the first fraction segment is alone, because the exponent is wider.
* This means for example that both the most and the least significant
* bits can be in the middle of the floats, not at either end.
*
* References:
* http://nssdc.gsfc.nasa.gov/nssdc/formats/VAXFloatingPoint.htm
* http://www.quadibloc.com/comp/cp0201.htm
* http://h71000.www7.hp.com/doc/82final/6443/6443pro_028.html
* (somebody at HP should be fired for the URLs)
*
* F fraction_2:16 sign:1 exp:8 fraction_1:7
* (exponent bias 128, hidden first one-bit)
*
* D fraction_2:16 sign:1 exp:8 fraction_1:7
* fraction_4:16 fraction_3:16
* (exponent bias 128, hidden first one-bit)
*
* G fraction_2:16 sign:1 exp:11 fraction_1:4
* fraction_4:16 fraction_3:16
* (exponent bias 1024, hidden first one-bit)
*
* H fraction_1:16 sign:1 exp:15
* fraction_3:16 fraction_2:16
* fraction_5:16 fraction_4:16
* fraction_7:16 fraction_6:16
* (exponent bias 16384, hidden first one-bit)
* (available only on VAX, and only on Fortran?)
*
* The formats S, T and X are available on the Alpha (and Itanium,
* also known as I64/IA64) and are equivalent with the IEEE-754 formats
* binary32, binary64, and binary128 (commonly: float, double, long double).
*
* S sign:1 exp:8 mantissa:23
* (exponent bias 127, hidden first one-bit)
*
* T sign:1 exp:11 mantissa:52
* (exponent bias 1022, hidden first one-bit)
*
* X sign:1 exp:15 mantissa:112
* (exponent bias 16382, hidden first one-bit)
*
*/
#ifdef DOUBLE_IS_VAX_FLOAT
# define DOUBLE_VAX_ENDIAN
#endif
#ifdef DOUBLE_IS_IEEE_FORMAT
/* All the basic IEEE formats have the implicit bit,
* except for the x86 80-bit extended formats, which will undef this.
* Also note that the IEEE 754 subnormals (formerly known as denormals)
* do not have the implicit bit of one. */
# define NV_IMPLICIT_BIT
#endif
#if defined(LONG_DOUBLEKIND) && LONG_DOUBLEKIND != LONG_DOUBLE_IS_DOUBLE
# if LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE
# define LONGDOUBLE_LITTLE_ENDIAN
# endif
# if LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE
# define LONGDOUBLE_BIG_ENDIAN
# endif
# if LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE
# define LONGDOUBLE_MIX_ENDIAN
# endif
# if LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
# define LONGDOUBLE_X86_80_BIT
# ifdef USE_LONG_DOUBLE
# undef NV_IMPLICIT_BIT
# define NV_X86_80_BIT
# endif
# endif
# if LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE
# define LONGDOUBLE_DOUBLEDOUBLE
# endif
# if LONG_DOUBLEKIND == LONG_DOUBLE_IS_VAX_H_FLOAT
# define LONGDOUBLE_VAX_ENDIAN
# endif
#endif /* LONG_DOUBLEKIND */
#ifdef USE_QUADMATH /* assume quadmath endianness == native double endianness */
# if defined(DOUBLE_LITTLE_ENDIAN)
# define NV_LITTLE_ENDIAN
# elif defined(DOUBLE_BIG_ENDIAN)
# define NV_BIG_ENDIAN
# elif defined(DOUBLE_MIX_ENDIAN) /* stretch */
# define NV_MIX_ENDIAN
# endif
#elif NVSIZE == DOUBLESIZE
# ifdef DOUBLE_LITTLE_ENDIAN
# define NV_LITTLE_ENDIAN
# endif
# ifdef DOUBLE_BIG_ENDIAN
# define NV_BIG_ENDIAN
# endif
# ifdef DOUBLE_MIX_ENDIAN
# define NV_MIX_ENDIAN
# endif
# ifdef DOUBLE_VAX_ENDIAN
# define NV_VAX_ENDIAN
# endif
#elif NVSIZE == LONG_DOUBLESIZE
# ifdef LONGDOUBLE_LITTLE_ENDIAN
# define NV_LITTLE_ENDIAN
# endif
# ifdef LONGDOUBLE_BIG_ENDIAN
# define NV_BIG_ENDIAN
# endif
# ifdef LONGDOUBLE_MIX_ENDIAN
# define NV_MIX_ENDIAN
# endif
# ifdef LONGDOUBLE_VAX_ENDIAN
# define NV_VAX_ENDIAN
# endif
#endif
/* We have somehow managed not to define the denormal/subnormal
* detection.
*
* This may happen if the compiler doesn't expose the C99 math like
* the fpclassify() without some special switches. Perl tries to
* stay C89, so for example -std=c99 is not an option.
*
* The Perl_isinf() and Perl_isnan() should have been defined even if
* the C99 isinf() and isnan() are unavailable, and the NV_MIN becomes
* from the C89 DBL_MIN or moral equivalent. */
#if !defined(Perl_fp_class_denorm) && defined(Perl_isinf) && defined(Perl_isnan) && defined(NV_MIN)
# define Perl_fp_class_denorm(x) ((x) != 0.0 && !Perl_isinf(x) && !Perl_isnan(x) && PERL_ABS(x) < NV_MIN)
#endif
/* This is not a great fallback: subnormals tests will fail,
* but at least Perl will link and 99.999% of tests will work. */
#if !defined(Perl_fp_class_denorm)
# define Perl_fp_class_denorm(x) FALSE
#endif
#ifdef DOUBLE_IS_IEEE_FORMAT
# define DOUBLE_HAS_INF
# define DOUBLE_HAS_NAN
#endif
#ifdef DOUBLE_HAS_NAN
START_EXTERN_C
#ifdef DOINIT
/* PL_inf and PL_nan initialization.
*
* For inf and nan initialization the ultimate fallback is dividing
* one or zero by zero: however, some compilers will warn or even fail
* on divide-by-zero, but hopefully something earlier will work.
*
* If you are thinking of using HUGE_VAL for infinity, or using
* <math.h> functions to generate NV_INF (e.g. exp(1e9), log(-1.0)),
* stop. Neither will work portably: HUGE_VAL can be just DBL_MAX,
* and the math functions might be just generating DBL_MAX, or even zero.
*
* Also, do NOT try doing NV_NAN based on NV_INF and trying (NV_INF-NV_INF).
* Though logically correct, some compilers (like Visual C 2003)
* falsely misoptimize that to zero (x-x is always zero, right?)
*
* Finally, note that not all floating point formats define Inf (or NaN).
* For the infinity a large number may be used instead. Operations that
* under the IEEE floating point would return Inf or NaN may return
* either large numbers (positive or negative), or they may cause
* a floating point exception or some other fault.
*/
/* The quadmath literals are anon structs which -Wc++-compat doesn't like. */
# ifndef USE_CPLUSPLUS
GCC_DIAG_IGNORE_DECL(-Wc++-compat);
# endif
# ifdef USE_QUADMATH
/* Cannot use HUGE_VALQ for PL_inf because not a compile-time
* constant. */
INFNAN_NV_U8_DECL PL_inf = { 1.0Q/0.0Q };
# elif NVSIZE == LONG_DOUBLESIZE && defined(LONGDBLINFBYTES)
INFNAN_U8_NV_DECL PL_inf = { { LONGDBLINFBYTES } };
# elif NVSIZE == DOUBLESIZE && defined(DOUBLEINFBYTES)
INFNAN_U8_NV_DECL PL_inf = { { DOUBLEINFBYTES } };
# else
# if NVSIZE == LONG_DOUBLESIZE && defined(USE_LONG_DOUBLE)
# if defined(LDBL_INFINITY)
INFNAN_NV_U8_DECL PL_inf = { LDBL_INFINITY };
# elif defined(LDBL_INF)
INFNAN_NV_U8_DECL PL_inf = { LDBL_INF };
# elif defined(INFINITY)
INFNAN_NV_U8_DECL PL_inf = { (NV)INFINITY };
# elif defined(INF)
INFNAN_NV_U8_DECL PL_inf = { (NV)INF };
# else
INFNAN_NV_U8_DECL PL_inf = { 1.0L/0.0L }; /* keep last */
# endif
# else
# if defined(DBL_INFINITY)
INFNAN_NV_U8_DECL PL_inf = { DBL_INFINITY };
# elif defined(DBL_INF)
INFNAN_NV_U8_DECL PL_inf = { DBL_INF };
# elif defined(INFINITY) /* C99 */
INFNAN_NV_U8_DECL PL_inf = { (NV)INFINITY };
# elif defined(INF)
INFNAN_NV_U8_DECL PL_inf = { (NV)INF };
# else
INFNAN_NV_U8_DECL PL_inf = { 1.0/0.0 }; /* keep last */
# endif
# endif
# endif
# ifdef USE_QUADMATH
/* Cannot use nanq("0") for PL_nan because not a compile-time
* constant. */
INFNAN_NV_U8_DECL PL_nan = { 0.0Q/0.0Q };
# elif NVSIZE == LONG_DOUBLESIZE && defined(LONGDBLNANBYTES)
INFNAN_U8_NV_DECL PL_nan = { { LONGDBLNANBYTES } };
# elif NVSIZE == DOUBLESIZE && defined(DOUBLENANBYTES)
INFNAN_U8_NV_DECL PL_nan = { { DOUBLENANBYTES } };
# else
# if NVSIZE == LONG_DOUBLESIZE && defined(USE_LONG_DOUBLE)
# if defined(LDBL_NAN)
INFNAN_NV_U8_DECL PL_nan = { LDBL_NAN };
# elif defined(LDBL_QNAN)
INFNAN_NV_U8_DECL PL_nan = { LDBL_QNAN };
# elif defined(NAN)
INFNAN_NV_U8_DECL PL_nan = { (NV)NAN };
# else
INFNAN_NV_U8_DECL PL_nan = { 0.0L/0.0L }; /* keep last */
# endif
# else
# if defined(DBL_NAN)
INFNAN_NV_U8_DECL PL_nan = { DBL_NAN };
# elif defined(DBL_QNAN)
INFNAN_NV_U8_DECL PL_nan = { DBL_QNAN };
# elif defined(NAN) /* C99 */
INFNAN_NV_U8_DECL PL_nan = { (NV)NAN };
# else
INFNAN_NV_U8_DECL PL_nan = { 0.0/0.0 }; /* keep last */
# endif
# endif
# endif
# ifndef USE_CPLUSPLUS
GCC_DIAG_RESTORE_DECL;
# endif
#else
INFNAN_NV_U8_DECL PL_inf;
INFNAN_NV_U8_DECL PL_nan;
#endif
END_EXTERN_C
/* If you have not defined NV_INF/NV_NAN (like for example win32/win32.h),
* we will define NV_INF/NV_NAN as the nv part of the global const
* PL_inf/PL_nan. Note, however, that the preexisting NV_INF/NV_NAN
* might not be a compile-time constant, in which case it cannot be
* used to initialize PL_inf/PL_nan above. */
#ifndef NV_INF
# define NV_INF PL_inf.nv
#endif
#ifndef NV_NAN
# define NV_NAN PL_nan.nv
#endif
/* NaNs (not-a-numbers) can carry payload bits, in addition to
* "nan-ness". Part of the payload is the quiet/signaling bit.
* To back up a bit (harhar):
*
* For IEEE 754 64-bit formats [1]:
*
* s 000 (mantissa all-zero) zero
* s 000 (mantissa non-zero) subnormals (denormals)
* s 001 ... 7fe normals
* s 7ff q nan
*
* For IEEE 754 128-bit formats:
*
* s 0000 (mantissa all-zero) zero
* s 0000 (mantissa non-zero) subnormals (denormals)
* s 0001 ... 7ffe normals
* s 7fff q nan
*
* [1] this looks like big-endian, but applies equally to little-endian.
*
* s = Sign bit. Yes, zeros and nans can have negative sign,
* the interpretation is application-specific.
*
* q = Quietness bit, the interpretation is platform-specific.
* Most platforms have the most significant bit being one
* meaning quiet, but some (older mips, hppa) have the msb
* being one meaning signaling. Note that the above means
* that on most platforms there cannot be signaling nan with
* zero payload because that is identical with infinity;
* while conversely on older mips/hppa there cannot be a quiet nan
* because that is identical with infinity.
*
* Moreover, whether there is any behavioral difference
* between quiet and signaling NaNs, depends on the platform.
*
* x86 80-bit extended precision is different, the mantissa bits:
*
* 63 62 61 30387+ pre-387 visual c
* -------- ---- -------- --------
* 0 0 0 invalid infinity
* 0 0 1 invalid snan
* 0 1 0 invalid snan
* 0 1 1 invalid snan
* 1 0 0 infinity snan 1.#INF
* 1 0 1 snan 1.#SNAN
* 1 1 0 qnan -1.#IND (x86 chooses this to negative)
* 1 1 1 qnan 1.#QNAN
*
* This means that in this format there are 61 bits available
* for the nan payload.
*
* Note that the 32-bit x86 ABI cannot do signaling nans: the x87
* simply cannot preserve the bit. You can either use the 80-bit
* extended precision (long double, -Duselongdouble), or use x86-64.
*
* In all platforms, the payload bytes (and bits, some of them are
* often in a partial byte) themselves can be either all zero (x86),
* all one (sparc or mips), or a mixture: in IEEE 754 128-bit double
* or in a double-double, the first half of the payload can follow the
* native double, while in the second half the payload can be all
* zeros. (Therefore the mask for payload bits is not necessarily
* identical to bit complement of the NaN.) Another way of putting
* this: the payload for the default NaN might not be zero.
*
* For the x86 80-bit long doubles, the trailing bytes (the 80 bits
* being 'packaged' in either 12 or 16 bytes) can be whatever random
* garbage.
*
* Furthermore, the semantics of the sign bit on NaNs are platform-specific.
* On normal floats, the sign bit being on means negative. But this may,
* or may not, be reverted on NaNs: in other words, the default NaN might
* have the sign bit on, and therefore look like negative if you look
* at it at the bit level.
*
* NaN payloads are not propagated even on copies, or in arithmetics.
* They *might* be, according to some rules, on your particular
* cpu/os/compiler/libraries, but no guarantees.
*
* To summarize, on most platforms, and for 64-bit doubles
* (using big-endian ordering here):
*
* [7FF8000000000000..7FFFFFFFFFFFFFFF] quiet
* [FFF8000000000000..FFFFFFFFFFFFFFFF] quiet
* [7FF0000000000001..7FF7FFFFFFFFFFFF] signaling
* [FFF0000000000001..FFF7FFFFFFFFFFFF] signaling
*
* The C99 nan() is supposed to generate *quiet* NaNs.
*
* Note the asymmetry:
* The 7FF0000000000000 is positive infinity,
* the FFF0000000000000 is negative infinity.
*/
/* NVMANTBITS is the number of _real_ mantissa bits in an NV.
* For the standard IEEE 754 fp this number is usually one less that
* *DBL_MANT_DIG because of the implicit (aka hidden) bit, which isn't
* real. For the 80-bit extended precision formats (x86*), the number
* of mantissa bits... depends. For normal floats, it's 64. But for
* the inf/nan, it's different (zero for inf, 61 for nan).
* NVMANTBITS works for normal floats. */
/* We do not want to include the quiet/signaling bit. */
#define NV_NAN_BITS (NVMANTBITS - 1)
#if defined(USE_LONG_DOUBLE) && NVSIZE > DOUBLESIZE
# if LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 13
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 2
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 7
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 2
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE
# define NV_NAN_QS_BYTE_OFFSET 13
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE
# define NV_NAN_QS_BYTE_OFFSET 1
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE
# define NV_NAN_QS_BYTE_OFFSET 9
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE
# define NV_NAN_QS_BYTE_OFFSET 6
# else
# error "Unexpected long double format"
# endif
#else
# ifdef USE_QUADMATH
# ifdef NV_LITTLE_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 13
# elif defined(NV_BIG_ENDIAN)
# define NV_NAN_QS_BYTE_OFFSET 2
# else
# error "Unexpected quadmath format"
# endif
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_LITTLE_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 2
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_BIG_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 1
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_LITTLE_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 6
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_BIG_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 1
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 13
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
# define NV_NAN_QS_BYTE_OFFSET 2
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_LE_BE
# define NV_NAN_QS_BYTE_OFFSET 2 /* bytes 4 5 6 7 0 1 2 3 (MSB 7) */
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_BE_LE
# define NV_NAN_QS_BYTE_OFFSET 5 /* bytes 3 2 1 0 7 6 5 4 (MSB 7) */
# else
/* For example the VAX formats should never
* get here because they do not have NaN. */
# error "Unexpected double format"
# endif
#endif
/* NV_NAN_QS_BYTE is the byte to test for the quiet/signaling */
#define NV_NAN_QS_BYTE(nvp) (((U8*)(nvp))[NV_NAN_QS_BYTE_OFFSET])
/* NV_NAN_QS_BIT is the bit to test in the NV_NAN_QS_BYTE_OFFSET
* for the quiet/signaling */
#if defined(USE_LONG_DOUBLE) && \
(LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN)
# define NV_NAN_QS_BIT_SHIFT 6 /* 0x40 */
#elif defined(USE_LONG_DOUBLE) && \
(LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE || \
LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE)
# define NV_NAN_QS_BIT_SHIFT 3 /* 0x08, but not via NV_NAN_BITS */
#else
# define NV_NAN_QS_BIT_SHIFT ((NV_NAN_BITS) % 8) /* usually 3, or 0x08 */
#endif
#define NV_NAN_QS_BIT (1 << (NV_NAN_QS_BIT_SHIFT))
/* NV_NAN_QS_BIT_OFFSET is the bit offset from the beginning of a NV
* (bytes ordered big-endianly) for the quiet/signaling bit
* for the quiet/signaling */
#define NV_NAN_QS_BIT_OFFSET \
(8 * (NV_NAN_QS_BYTE_OFFSET) + (NV_NAN_QS_BIT_SHIFT))
/* NV_NAN_QS_QUIET (always defined) is true if the NV_NAN_QS_QS_BIT being
* on indicates quiet NaN. NV_NAN_QS_SIGNALING (also always defined)
* is true if the NV_NAN_QS_BIT being on indicates signaling NaN. */
#define NV_NAN_QS_QUIET \
((NV_NAN_QS_BYTE(PL_nan.u8) & NV_NAN_QS_BIT) == NV_NAN_QS_BIT)
#define NV_NAN_QS_SIGNALING (!(NV_NAN_QS_QUIET))
#define NV_NAN_QS_TEST(nvp) (NV_NAN_QS_BYTE(nvp) & NV_NAN_QS_BIT)
/* NV_NAN_IS_QUIET() returns true if the NV behind nvp is a NaN,
* whether it is a quiet NaN, NV_NAN_IS_SIGNALING() if a signaling NaN.
* Note however that these do not check whether the nvp is a NaN. */
#define NV_NAN_IS_QUIET(nvp) \
(NV_NAN_QS_TEST(nvp) == (NV_NAN_QS_QUIET ? NV_NAN_QS_BIT : 0))
#define NV_NAN_IS_SIGNALING(nvp) \
(NV_NAN_QS_TEST(nvp) == (NV_NAN_QS_QUIET ? 0 : NV_NAN_QS_BIT))
#define NV_NAN_SET_QUIET(nvp) \
(NV_NAN_QS_QUIET ? \
(NV_NAN_QS_BYTE(nvp) |= NV_NAN_QS_BIT) : \
(NV_NAN_QS_BYTE(nvp) &= ~NV_NAN_QS_BIT))
#define NV_NAN_SET_SIGNALING(nvp) \
(NV_NAN_QS_QUIET ? \
(NV_NAN_QS_BYTE(nvp) &= ~NV_NAN_QS_BIT) : \
(NV_NAN_QS_BYTE(nvp) |= NV_NAN_QS_BIT))
#define NV_NAN_QS_XOR(nvp) (NV_NAN_QS_BYTE(nvp) ^= NV_NAN_QS_BIT)
/* NV_NAN_PAYLOAD_MASK: masking the nan payload bits.
*
* NV_NAN_PAYLOAD_PERM: permuting the nan payload bytes.
* 0xFF means "don't go here".*/
/* Shorthands to avoid typoses. */
#define NV_NAN_PAYLOAD_MASK_SKIP_EIGHT \
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
#define NV_NAN_PAYLOAD_PERM_SKIP_EIGHT \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
#define NV_NAN_PAYLOAD_PERM_0_TO_7 \
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7
#define NV_NAN_PAYLOAD_PERM_7_TO_0 \
0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0
#define NV_NAN_PAYLOAD_MASK_IEEE_754_128_LE \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00
#define NV_NAN_PAYLOAD_PERM_IEEE_754_128_LE \
NV_NAN_PAYLOAD_PERM_0_TO_7, \
0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xFF, 0xFF
#define NV_NAN_PAYLOAD_MASK_IEEE_754_128_BE \
0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
#define NV_NAN_PAYLOAD_PERM_IEEE_754_128_BE \
0xFF, 0xFF, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, \
NV_NAN_PAYLOAD_PERM_7_TO_0
#define NV_NAN_PAYLOAD_MASK_IEEE_754_64_LE \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00
#define NV_NAN_PAYLOAD_PERM_IEEE_754_64_LE \
0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xFF
#define NV_NAN_PAYLOAD_MASK_IEEE_754_64_BE \
0x00, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
#define NV_NAN_PAYLOAD_PERM_IEEE_754_64_BE \
0xFF, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0
#if defined(USE_LONG_DOUBLE) && NVSIZE > DOUBLESIZE
# if LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
# define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_LE
# define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_LE
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
# define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_BE
# define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_BE
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN
# if LONG_DOUBLESIZE == 10
# define NV_NAN_PAYLOAD_MASK \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, \
0x00, 0x00
# define NV_NAN_PAYLOAD_PERM \
NV_NAN_PAYLOAD_PERM_0_TO_7, 0xFF, 0xFF
# elif LONG_DOUBLESIZE == 12
# define NV_NAN_PAYLOAD_MASK \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, \
0x00, 0x00, 0x00, 0x00
# define NV_NAN_PAYLOAD_PERM \
NV_NAN_PAYLOAD_PERM_0_TO_7, 0xFF, 0xFF, 0xFF, 0xFF
# elif LONG_DOUBLESIZE == 16
# define NV_NAN_PAYLOAD_MASK \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
# define NV_NAN_PAYLOAD_PERM \
NV_NAN_PAYLOAD_PERM_0_TO_7, \
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
# else
# error "Unexpected x86 80-bit little-endian long double format"
# endif
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
# if LONG_DOUBLESIZE == 10
# define NV_NAN_PAYLOAD_MASK \
0x00, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff
# define NV_NAN_PAYLOAD_PERM \
NV_NAN_PAYLOAD_PERM_7_TO_0, 0xFF, 0xFF
# elif LONG_DOUBLESIZE == 12
# define NV_NAN_PAYLOAD_MASK \
0x00, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0x00, 0x00
# define NV_NAN_PAYLOAD_PERM \
NV_NAN_PAYLOAD_PERM_7_TO_0, 0xFF, 0xFF, 0xFF, 0xFF
# elif LONG_DOUBLESIZE == 16
# define NV_NAN_PAYLOAD_MASK \
0x00, 0x00, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
# define NV_NAN_PAYLOAD_PERM \
NV_NAN_PAYLOAD_PERM_7_TO_0, \
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
# else
# error "Unexpected x86 80-bit big-endian long double format"
# endif
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE
/* For double-double we assume only the first double (in LE or BE terms)
* is used for NaN. */
# define NV_NAN_PAYLOAD_MASK \
NV_NAN_PAYLOAD_MASK_SKIP_EIGHT, NV_NAN_PAYLOAD_MASK_IEEE_754_64_LE
# define NV_NAN_PAYLOAD_PERM \
NV_NAN_PAYLOAD_PERM_SKIP_EIGHT, NV_NAN_PAYLOAD_PERM_IEEE_754_64_LE
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE
# define NV_NAN_PAYLOAD_MASK \
NV_NAN_PAYLOAD_MASK_IEEE_754_64_BE
# define NV_NAN_PAYLOAD_PERM \
NV_NAN_PAYLOAD_PERM_IEEE_754_64_BE
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE
# define NV_NAN_PAYLOAD_MASK \
NV_NAN_PAYLOAD_MASK_IEEE_754_64_LE
# define NV_NAN_PAYLOAD_PERM \
NV_NAN_PAYLOAD_PERM_IEEE_754_64_LE
# elif LONG_DOUBLEKIND == LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE
# define NV_NAN_PAYLOAD_MASK \
NV_NAN_PAYLOAD_MASK_SKIP_EIGHT, NV_NAN_PAYLOAD_MASK_IEEE_754_64_BE
# define NV_NAN_PAYLOAD_PERM \
NV_NAN_PAYLOAD_PERM_SKIP_EIGHT, NV_NAN_PAYLOAD_PERM_IEEE_754_64_BE
# else
# error "Unexpected long double format"
# endif
#else
# ifdef USE_QUADMATH /* quadmath is not long double */
# ifdef NV_LITTLE_ENDIAN
# define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_LE
# define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_LE
# elif defined(NV_BIG_ENDIAN)
# define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_BE
# define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_BE
# else
# error "Unexpected quadmath format"
# endif
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_LITTLE_ENDIAN
# define NV_NAN_PAYLOAD_MASK 0xff, 0xff, 0x07, 0x00
# define NV_NAN_PAYLOAD_PERM 0x0, 0x1, 0x2, 0xFF
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_32_BIT_BIG_ENDIAN
# define NV_NAN_PAYLOAD_MASK 0x00, 0x07, 0xff, 0xff
# define NV_NAN_PAYLOAD_PERM 0xFF, 0x2, 0x1, 0x0
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_LITTLE_ENDIAN
# define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_64_LE
# define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_64_LE
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_BIG_ENDIAN
# define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_64_BE
# define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_64_BE
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
# define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_LE
# define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_LE
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
# define NV_NAN_PAYLOAD_MASK NV_NAN_PAYLOAD_MASK_IEEE_754_128_BE
# define NV_NAN_PAYLOAD_PERM NV_NAN_PAYLOAD_PERM_IEEE_754_128_BE
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_LE_BE
# define NV_NAN_PAYLOAD_MASK 0xff, 0xff, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff
# define NV_NAN_PAYLOAD_PERM 0x4, 0x5, 0x6, 0xFF, 0x0, 0x1, 0x2, 0x3
# elif DOUBLEKIND == DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_BE_LE
# define NV_NAN_PAYLOAD_MASK 0xff, 0xff, 0xff, 0xff, 0x00, 0x07, 0xff, 0xff
# define NV_NAN_PAYLOAD_PERM 0x3, 0x2, 0x1, 0x0, 0xFF, 0x6, 0x5, 0x4
# else
# error "Unexpected double format"
# endif
#endif
#endif /* DOUBLE_HAS_NAN */
/*
(KEEP THIS LAST IN perl.h!)
Mention
NV_PRESERVES_UV
HAS_MKSTEMP
HAS_MKSTEMPS
HAS_MKDTEMP
HAS_GETCWD
HAS_MMAP
HAS_MPROTECT
HAS_MSYNC
HAS_MADVISE
HAS_MUNMAP
I_SYSMMAN
Mmap_t
NVef
NVff
NVgf
HAS_UALARM
HAS_USLEEP
HAS_SETITIMER
HAS_GETITIMER
HAS_SENDMSG
HAS_RECVMSG
HAS_READV
HAS_WRITEV
I_SYSUIO
HAS_STRUCT_MSGHDR
HAS_STRUCT_CMSGHDR
HAS_NL_LANGINFO
HAS_DIRFD
so that Configure picks them up.
(KEEP THIS LAST IN perl.h!)
*/
#endif /* Include guard */
/*
* ex: set ts=8 sts=4 sw=4 et:
*/
| 133,297 |
1,083 | //===--- LLVMTypePHPRCIdentity.cpp - LLVM RCIdentity Analysis for Swift -----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "polarphp/llvmpasses/Passes.h"
#include "polarphp/llvmpasses/internal/LLVMARCOpts.h"
#include "llvm/IR/Module.h"
using namespace llvm;
using polar::TypePHPRCIdentity;
// Register this pass...
char TypePHPRCIdentity::ID = 0;
INITIALIZE_PASS(TypePHPRCIdentity, "typephp-rc-identity",
"polarphp RC Identity Analysis", false, true)
bool TypePHPRCIdentity::doInitialization(Module &M) {
return true;
}
llvm::Value *
TypePHPRCIdentity::stripPointerCasts(llvm::Value *Val) {
return Val->stripPointerCasts();
}
llvm::Value *
TypePHPRCIdentity::stripReferenceForwarding(llvm::Value *Val) {
auto Inst = dyn_cast<Instruction>(Val);
if (!Inst)
return Val;
auto Kind = classifyInstruction(*Inst);
switch(Kind) {
case RT_RetainN:
case RT_UnknownObjectRetainN:
case RT_BridgeRetainN:
case RT_ReleaseN:
case RT_UnknownObjectReleaseN:
case RT_BridgeReleaseN:
case RT_FixLifetime:
case RT_Retain:
case RT_UnknownObjectRetain:
case RT_Release:
case RT_UnknownObjectRelease:
case RT_Unknown:
case RT_AllocObject:
case RT_NoMemoryAccessed:
case RT_BridgeRelease:
case RT_BridgeRetain:
case RT_RetainUnowned:
case RT_CheckUnowned:
// case RT_ObjCRelease:
case RT_EndBorrow:
break;
// ObjC forwards references.
// case RT_ObjCRetain:
// Val = cast<CallInst>(Inst)->getArgOperand(0);
// break;
}
return Val;
}
llvm::Value *
TypePHPRCIdentity::getTypePHPRCIdentityRoot(llvm::Value *Val) {
// Only allow this method to go up a fixed number of levels to make sure
// we don't explode compile time.
llvm::Value *OldVal = Val;
unsigned levels = 0;
do {
llvm::Value *NewVal = Val;
// Try to strip off pointer casts and reference forwarding.
Val = stripPointerCasts(Val);
Val = stripReferenceForwarding(Val);
// Nothing was stripped off.
if (NewVal == Val)
break;
// Hit max number of levels.
if (++levels > MaxRecursionDepth)
return OldVal;
} while (true);
return Val;
}
llvm::ImmutablePass *polar::createTypePHPRCIdentityPass() {
initializeTypePHPRCIdentityPass(*PassRegistry::getPassRegistry());
return new TypePHPRCIdentity();
}
| 1,066 |
302 | #include "tty.h"
#define NR_PTY_MAX (1 << MINORBITS)
struct tty_driver *ptm_driver, *pts_driver;
volatile int next_pty_number = 0;
int get_next_pty_number()
{
// TODO: MQ 2020-09-04 Use bitmap to get/check next an unused number, release/uncheck a number
return next_pty_number++;
}
static int pty_open(struct tty_struct *tty, struct vfs_file *filp)
{
return 0;
}
static int pty_write(struct tty_struct *tty, const char *buf, int count)
{
struct tty_struct *to = tty->link;
if (!to)
return 0;
int c = to->ldisc->receive_room(to);
if (c > count)
c = count;
to->ldisc->receive_buf(to, buf, c);
return c;
}
static int pty_write_room(struct tty_struct *tty)
{
struct tty_struct *to = tty->link;
if (!to)
return 0;
return to->ldisc->receive_room(to);
}
static struct tty_operations pty_ops = {
.open = pty_open,
.write = pty_write,
.write_room = pty_write_room,
};
void pty_init()
{
ptm_driver = alloc_tty_driver(NR_PTY_MAX);
ptm_driver->driver_name = "pty_master";
ptm_driver->name = "ptm";
ptm_driver->major = UNIX98_PTY_MASTER_MAJOR;
ptm_driver->minor_start = 0;
ptm_driver->type = TTY_DRIVER_TYPE_PTY;
ptm_driver->subtype = PTY_TYPE_MASTER;
ptm_driver->init_termios = tty_std_termios;
ptm_driver->init_termios.c_iflag = 0;
ptm_driver->init_termios.c_oflag = 0;
ptm_driver->init_termios.c_cflag = B38400 | CS8 | CREAD;
ptm_driver->init_termios.c_lflag = 0;
ptm_driver->flags = TTY_DRIVER_RESET_TERMIOS | TTY_DRIVER_REAL_RAW |
TTY_DRIVER_NO_DEVFS | TTY_DRIVER_DEVPTS_MEM;
ptm_driver->tops = &pty_ops;
ptm_driver->other = pts_driver;
INIT_LIST_HEAD(&ptm_driver->ttys);
tty_register_driver(ptm_driver);
pts_driver = alloc_tty_driver(NR_PTY_MAX);
pts_driver->driver_name = "pty_slave";
pts_driver->name = "pts";
pts_driver->major = UNIX98_PTY_SLAVE_MAJOR;
pts_driver->minor_start = 0;
pts_driver->type = TTY_DRIVER_TYPE_PTY;
pts_driver->subtype = PTY_TYPE_SLAVE;
pts_driver->init_termios = tty_std_termios;
pts_driver->init_termios.c_cflag = B38400 | CS8 | CREAD;
pts_driver->flags = TTY_DRIVER_RESET_TERMIOS | TTY_DRIVER_REAL_RAW |
TTY_DRIVER_NO_DEVFS | TTY_DRIVER_DEVPTS_MEM;
pts_driver->tops = &pty_ops;
pts_driver->other = ptm_driver;
INIT_LIST_HEAD(&pts_driver->ttys);
tty_register_driver(pts_driver);
}
| 1,030 |
9,959 | package com.fasterxml.jackson.databind.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonDeserialize {
public Class<?> builder() default Void.class;
}
| 142 |
1,514 | <filename>src/libtomcrypt/src/modes/ctr/ctr_decrypt.c
/* LibTomCrypt, modular cryptographic library -- <NAME>
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#include "tomcrypt.h"
/**
@file ctr_decrypt.c
CTR implementation, decrypt data, <NAME>
*/
#ifdef LTC_CTR_MODE
/**
CTR decrypt
@param ct Ciphertext
@param pt [out] Plaintext
@param len Length of ciphertext (octets)
@param ctr CTR state
@return CRYPT_OK if successful
*/
int ctr_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CTR *ctr)
{
LTC_ARGCHK(pt != NULL);
LTC_ARGCHK(ct != NULL);
LTC_ARGCHK(ctr != NULL);
return ctr_encrypt(ct, pt, len, ctr);
}
#endif
/* ref: HEAD -> master, tag: v1.18.2 */
/* git commit: <PASSWORD> */
/* commit time: 2018-07-01 22:49:01 +0200 */
| 373 |
408 | import json
prev = json.load(open('data/enriched.json'))
curr = json.load(open('data/pages_parsed.json'))
exts_id = set(ext['ext_id'] for ext in curr)
for ext in prev:
if ext['ext_id'] not in exts_id:
ext['deleted'] = True
curr.append(ext)
json.dump(curr, open('data/_merged.json','w'), indent=2) | 129 |
14,668 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_PUBLIC_GOOGLE_ACCOUNT_ACCESS_TOKEN_FETCH_DELEGATE_H_
#define WEBLAYER_PUBLIC_GOOGLE_ACCOUNT_ACCESS_TOKEN_FETCH_DELEGATE_H_
#include <set>
#include <string>
#include "base/callback_forward.h"
namespace weblayer {
using OnTokenFetchedCallback =
base::OnceCallback<void(const std::string& token)>;
// An interface that allows clients to handle access token requests for Google
// accounts originating in the browser.
class GoogleAccountAccessTokenFetchDelegate {
public:
// Called when the WebLayer implementation wants to fetch an access token for
// the embedder's current GAIA account (if any) and the given scopes. The
// client should invoke |onTokenFetchedCallback| when its internal token fetch
// is complete, passing either the fetched access token or the empty string in
// the case of failure (e.g., if there is no current GAIA account or there was
// an error in the token fetch).
//
// NOTE: WebLayer will not perform any caching of the returned token but will
// instead make a new request each time that it needs to use an access token.
// The expectation is that the client will use caching internally to minimize
// latency of these requests.
virtual void FetchAccessToken(const std::set<std::string>& scopes,
OnTokenFetchedCallback callback) = 0;
// Called when a token previously obtained via a call to
// FetchAccessToken(|scopes|) is identified as invalid, so the embedder can
// take appropriate action (e.g., dropping the token from its cache and/or
// force-fetching a new token).
virtual void OnAccessTokenIdentifiedAsInvalid(
const std::set<std::string>& scopes,
const std::string& token) = 0;
protected:
virtual ~GoogleAccountAccessTokenFetchDelegate() {}
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_GOOGLE_ACCOUNT_ACCESS_TOKEN_FETCH_DELEGATE_H_
| 635 |
1,016 | <filename>services/field-policy-service/field-policy-core/src/test/java/com/thinkbiganalytics/standardization/TestStandardizationTransform.java
package com.thinkbiganalytics.standardization;
/*-
* #%L
* thinkbig-field-policy-core
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.google.common.collect.Iterables;
import com.thinkbiganalytics.guava.PredicateImpl;
import com.thinkbiganalytics.policy.AvailablePolicies;
import com.thinkbiganalytics.policy.PolicyTransformException;
import com.thinkbiganalytics.policy.rest.model.FieldStandardizationRule;
import com.thinkbiganalytics.policy.standardization.DateTimeStandardizer;
import com.thinkbiganalytics.policy.standardization.DefaultValueStandardizer;
import com.thinkbiganalytics.policy.standardization.MaskLeavingLastFourDigitStandardizer;
import com.thinkbiganalytics.policy.standardization.RemoveControlCharsStandardizer;
import com.thinkbiganalytics.policy.standardization.SimpleRegexReplacer;
import com.thinkbiganalytics.policy.standardization.StandardizationPolicy;
import com.thinkbiganalytics.policy.standardization.StripNonNumeric;
import com.thinkbiganalytics.policy.standardization.UppercaseStandardizer;
import com.thinkbiganalytics.standardization.transform.StandardizationAnnotationTransformer;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
/**
*/
public class TestStandardizationTransform {
@Test
public void testDefaultValue() throws IOException {
String INPUT = "My Default";
DefaultValueStandardizer standardizer = new DefaultValueStandardizer(INPUT);
FieldStandardizationRule uiModel = StandardizationAnnotationTransformer.instance().toUIModel(standardizer);
DefaultValueStandardizer convertedPolicy = fromUI(uiModel, DefaultValueStandardizer.class);
Assert.assertEquals(INPUT, convertedPolicy.getDefaultStr());
}
@Test
public void testDateTime() throws IOException {
String FORMAT = "MM/dd/YYYY";
DateTimeStandardizer standardizer = new DateTimeStandardizer(FORMAT, DateTimeStandardizer.OutputFormats.DATETIME_NOMILLIS);
FieldStandardizationRule uiModel = StandardizationAnnotationTransformer.instance().toUIModel(standardizer);
DateTimeStandardizer convertedPolicy = fromUI(uiModel, DateTimeStandardizer.class);
Assert.assertEquals(FORMAT, convertedPolicy.getInputDateFormat());
Assert.assertEquals(DateTimeStandardizer.OutputFormats.DATETIME_NOMILLIS, convertedPolicy.getOutputFormat());
}
@Test
public void testRemoveControlCharsStandardizer() throws IOException {
RemoveControlCharsStandardizer standardizer = RemoveControlCharsStandardizer.instance();
FieldStandardizationRule uiModel = StandardizationAnnotationTransformer.instance().toUIModel(standardizer);
RemoveControlCharsStandardizer convertedPolicy = fromUI(uiModel, RemoveControlCharsStandardizer.class);
Assert.assertEquals(standardizer, convertedPolicy);
}
@Test
public void testUppercaseStandardizer() throws IOException {
UppercaseStandardizer standardizer = UppercaseStandardizer.instance();
FieldStandardizationRule uiModel = StandardizationAnnotationTransformer.instance().toUIModel(standardizer);
UppercaseStandardizer convertedPolicy = fromUI(uiModel, UppercaseStandardizer.class);
Assert.assertEquals(standardizer, convertedPolicy);
}
@Test
public void testStripNonNumeric() throws IOException {
StripNonNumeric standardizer = StripNonNumeric.instance();
FieldStandardizationRule uiModel = StandardizationAnnotationTransformer.instance().toUIModel(standardizer);
StripNonNumeric convertedPolicy = fromUI(uiModel, StripNonNumeric.class);
Assert.assertEquals(standardizer, convertedPolicy);
}
@Test
public void testMaskLeavingLastFourDigitStandardizer() throws IOException {
MaskLeavingLastFourDigitStandardizer standardizer = MaskLeavingLastFourDigitStandardizer.instance();
FieldStandardizationRule uiModel = StandardizationAnnotationTransformer.instance().toUIModel(standardizer);
MaskLeavingLastFourDigitStandardizer convertedPolicy = fromUI(uiModel, MaskLeavingLastFourDigitStandardizer.class);
Assert.assertEquals(standardizer, convertedPolicy);
}
@Test
public void testSimpleRegexReplacer() throws IOException {
String regex = "\\p{Cc}";
String replace = "REPLACE";
SimpleRegexReplacer standardizer = new SimpleRegexReplacer(regex, replace);
FieldStandardizationRule uiModel = StandardizationAnnotationTransformer.instance().toUIModel(standardizer);
SimpleRegexReplacer convertedPolicy = fromUI(uiModel, SimpleRegexReplacer.class);
Assert.assertEquals(regex, convertedPolicy.getPattern().pattern());
Assert.assertEquals(replace, convertedPolicy.getReplacement());
Assert.assertEquals(true, convertedPolicy.isValid());
}
@Test
public void testUiCreation() {
List<FieldStandardizationRule> standardizationRules = AvailablePolicies.discoverStandardizationRules();
FieldStandardizationRule defaultValue = Iterables.tryFind(standardizationRules, new PredicateImpl<FieldStandardizationRule>() {
@Override
public boolean test(FieldStandardizationRule fieldStandardizationRule) {
return fieldStandardizationRule.getName().equalsIgnoreCase("Default Value");
}
}).orNull();
defaultValue.getProperty("Default Value").setValue("a new default value");
DefaultValueStandardizer convertedPolicy = fromUI(defaultValue, DefaultValueStandardizer.class);
Assert.assertEquals("a new default value", convertedPolicy.getDefaultStr());
}
private <T extends StandardizationPolicy> T fromUI(FieldStandardizationRule uiModel, Class<T> policyClass) {
try {
StandardizationPolicy policy = StandardizationAnnotationTransformer.instance().fromUiModel(uiModel);
return (T) policy;
} catch (PolicyTransformException e) {
e.printStackTrace();
;
}
return null;
}
}
| 2,177 |
416 | //
// QuickLookThumbnailing.h
// Quick Look Thumbnailing
//
// Copyright (c) 2018 Apple. All rights reserved.
//
#import <TargetConditionals.h>
#import <QuickLookThumbnailing/QLThumbnailRepresentation.h>
#import <QuickLookThumbnailing/QLThumbnailProvider.h>
#import <QuickLookThumbnailing/QLThumbnailReply.h>
#import <QuickLookThumbnailing/QLThumbnailRequest.h>
#import <QuickLookThumbnailing/QLThumbnailGenerationRequest.h>
#import <QuickLookThumbnailing/QLThumbnailErrors.h>
#import <QuickLookThumbnailing/QLThumbnailGenerator.h>
| 167 |
1,244 | <gh_stars>1000+
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <iterator>
// istreambuf_iterator
// pointer operator->() const;
#include <iostream>
#include <sstream>
#include <streambuf>
typedef char C;
int main ()
{
std::istringstream s("filename");
std::istreambuf_iterator<char> i(s);
(*i).~C(); // This is well-formed...
i->~C(); // ... so this should be supported!
}
| 213 |
621 | <filename>iguana/reflection.hpp
//
// Created by Qiyu on 17-6-5.
//
#ifndef IGUANA_REFLECTION_HPP
#define IGUANA_REFLECTION_HPP
#include <iostream>
#include <sstream>
#include <string>
#include <tuple>
#include <iomanip>
#include <map>
#include <vector>
#include <array>
#include <type_traits>
#include <functional>
#include <string_view>
#include "detail/itoa.hpp"
#include "detail/traits.hpp"
#include "detail/string_stream.hpp"
namespace iguana::detail {
/******************************************/
/* arg list expand macro, now support 120 args */
#define MAKE_ARG_LIST_1(op, arg, ...) op(arg)
#define MAKE_ARG_LIST_2(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_1(op, __VA_ARGS__))
#define MAKE_ARG_LIST_3(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_2(op, __VA_ARGS__))
#define MAKE_ARG_LIST_4(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_3(op, __VA_ARGS__))
#define MAKE_ARG_LIST_5(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_4(op, __VA_ARGS__))
#define MAKE_ARG_LIST_6(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_5(op, __VA_ARGS__))
#define MAKE_ARG_LIST_7(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_6(op, __VA_ARGS__))
#define MAKE_ARG_LIST_8(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_7(op, __VA_ARGS__))
#define MAKE_ARG_LIST_9(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_8(op, __VA_ARGS__))
#define MAKE_ARG_LIST_10(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_9(op, __VA_ARGS__))
#define MAKE_ARG_LIST_11(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_10(op, __VA_ARGS__))
#define MAKE_ARG_LIST_12(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_11(op, __VA_ARGS__))
#define MAKE_ARG_LIST_13(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_12(op, __VA_ARGS__))
#define MAKE_ARG_LIST_14(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_13(op, __VA_ARGS__))
#define MAKE_ARG_LIST_15(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_14(op, __VA_ARGS__))
#define MAKE_ARG_LIST_16(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_15(op, __VA_ARGS__))
#define MAKE_ARG_LIST_17(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_16(op, __VA_ARGS__))
#define MAKE_ARG_LIST_18(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_17(op, __VA_ARGS__))
#define MAKE_ARG_LIST_19(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_18(op, __VA_ARGS__))
#define MAKE_ARG_LIST_20(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_19(op, __VA_ARGS__))
#define MAKE_ARG_LIST_21(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_20(op, __VA_ARGS__))
#define MAKE_ARG_LIST_22(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_21(op, __VA_ARGS__))
#define MAKE_ARG_LIST_23(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_22(op, __VA_ARGS__))
#define MAKE_ARG_LIST_24(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_23(op, __VA_ARGS__))
#define MAKE_ARG_LIST_25(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_24(op, __VA_ARGS__))
#define MAKE_ARG_LIST_26(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_25(op, __VA_ARGS__))
#define MAKE_ARG_LIST_27(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_26(op, __VA_ARGS__))
#define MAKE_ARG_LIST_28(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_27(op, __VA_ARGS__))
#define MAKE_ARG_LIST_29(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_28(op, __VA_ARGS__))
#define MAKE_ARG_LIST_30(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_29(op, __VA_ARGS__))
#define MAKE_ARG_LIST_31(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_30(op, __VA_ARGS__))
#define MAKE_ARG_LIST_32(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_31(op, __VA_ARGS__))
#define MAKE_ARG_LIST_33(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_32(op, __VA_ARGS__))
#define MAKE_ARG_LIST_34(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_33(op, __VA_ARGS__))
#define MAKE_ARG_LIST_35(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_34(op, __VA_ARGS__))
#define MAKE_ARG_LIST_36(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_35(op, __VA_ARGS__))
#define MAKE_ARG_LIST_37(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_36(op, __VA_ARGS__))
#define MAKE_ARG_LIST_38(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_37(op, __VA_ARGS__))
#define MAKE_ARG_LIST_39(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_38(op, __VA_ARGS__))
#define MAKE_ARG_LIST_40(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_39(op, __VA_ARGS__))
#define MAKE_ARG_LIST_41(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_40(op, __VA_ARGS__))
#define MAKE_ARG_LIST_42(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_41(op, __VA_ARGS__))
#define MAKE_ARG_LIST_43(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_42(op, __VA_ARGS__))
#define MAKE_ARG_LIST_44(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_43(op, __VA_ARGS__))
#define MAKE_ARG_LIST_45(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_44(op, __VA_ARGS__))
#define MAKE_ARG_LIST_46(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_45(op, __VA_ARGS__))
#define MAKE_ARG_LIST_47(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_46(op, __VA_ARGS__))
#define MAKE_ARG_LIST_48(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_47(op, __VA_ARGS__))
#define MAKE_ARG_LIST_49(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_48(op, __VA_ARGS__))
#define MAKE_ARG_LIST_50(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_49(op, __VA_ARGS__))
#define MAKE_ARG_LIST_51(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_50(op, __VA_ARGS__))
#define MAKE_ARG_LIST_52(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_51(op, __VA_ARGS__))
#define MAKE_ARG_LIST_53(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_52(op, __VA_ARGS__))
#define MAKE_ARG_LIST_54(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_53(op, __VA_ARGS__))
#define MAKE_ARG_LIST_55(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_54(op, __VA_ARGS__))
#define MAKE_ARG_LIST_56(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_55(op, __VA_ARGS__))
#define MAKE_ARG_LIST_57(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_56(op, __VA_ARGS__))
#define MAKE_ARG_LIST_58(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_57(op, __VA_ARGS__))
#define MAKE_ARG_LIST_59(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_58(op, __VA_ARGS__))
#define MAKE_ARG_LIST_60(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_59(op, __VA_ARGS__))
#define MAKE_ARG_LIST_61(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_60(op, __VA_ARGS__))
#define MAKE_ARG_LIST_62(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_61(op, __VA_ARGS__))
#define MAKE_ARG_LIST_63(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_62(op, __VA_ARGS__))
#define MAKE_ARG_LIST_64(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_63(op, __VA_ARGS__))
#define MAKE_ARG_LIST_65(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_64(op, __VA_ARGS__))
#define MAKE_ARG_LIST_66(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_65(op, __VA_ARGS__))
#define MAKE_ARG_LIST_67(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_66(op, __VA_ARGS__))
#define MAKE_ARG_LIST_68(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_67(op, __VA_ARGS__))
#define MAKE_ARG_LIST_69(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_68(op, __VA_ARGS__))
#define MAKE_ARG_LIST_70(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_69(op, __VA_ARGS__))
#define MAKE_ARG_LIST_71(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_70(op, __VA_ARGS__))
#define MAKE_ARG_LIST_72(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_71(op, __VA_ARGS__))
#define MAKE_ARG_LIST_73(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_72(op, __VA_ARGS__))
#define MAKE_ARG_LIST_74(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_73(op, __VA_ARGS__))
#define MAKE_ARG_LIST_75(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_74(op, __VA_ARGS__))
#define MAKE_ARG_LIST_76(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_75(op, __VA_ARGS__))
#define MAKE_ARG_LIST_77(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_76(op, __VA_ARGS__))
#define MAKE_ARG_LIST_78(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_77(op, __VA_ARGS__))
#define MAKE_ARG_LIST_79(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_78(op, __VA_ARGS__))
#define MAKE_ARG_LIST_80(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_79(op, __VA_ARGS__))
#define MAKE_ARG_LIST_81(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_80(op, __VA_ARGS__))
#define MAKE_ARG_LIST_82(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_81(op, __VA_ARGS__))
#define MAKE_ARG_LIST_83(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_82(op, __VA_ARGS__))
#define MAKE_ARG_LIST_84(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_83(op, __VA_ARGS__))
#define MAKE_ARG_LIST_85(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_84(op, __VA_ARGS__))
#define MAKE_ARG_LIST_86(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_85(op, __VA_ARGS__))
#define MAKE_ARG_LIST_87(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_86(op, __VA_ARGS__))
#define MAKE_ARG_LIST_88(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_87(op, __VA_ARGS__))
#define MAKE_ARG_LIST_89(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_88(op, __VA_ARGS__))
#define MAKE_ARG_LIST_90(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_89(op, __VA_ARGS__))
#define MAKE_ARG_LIST_91(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_90(op, __VA_ARGS__))
#define MAKE_ARG_LIST_92(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_91(op, __VA_ARGS__))
#define MAKE_ARG_LIST_93(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_92(op, __VA_ARGS__))
#define MAKE_ARG_LIST_94(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_93(op, __VA_ARGS__))
#define MAKE_ARG_LIST_95(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_94(op, __VA_ARGS__))
#define MAKE_ARG_LIST_96(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_95(op, __VA_ARGS__))
#define MAKE_ARG_LIST_97(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_96(op, __VA_ARGS__))
#define MAKE_ARG_LIST_98(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_97(op, __VA_ARGS__))
#define MAKE_ARG_LIST_99(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_98(op, __VA_ARGS__))
#define MAKE_ARG_LIST_100(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_99(op, __VA_ARGS__))
#define MAKE_ARG_LIST_101(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_100(op, __VA_ARGS__))
#define MAKE_ARG_LIST_102(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_101(op, __VA_ARGS__))
#define MAKE_ARG_LIST_103(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_102(op, __VA_ARGS__))
#define MAKE_ARG_LIST_104(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_103(op, __VA_ARGS__))
#define MAKE_ARG_LIST_105(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_104(op, __VA_ARGS__))
#define MAKE_ARG_LIST_106(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_105(op, __VA_ARGS__))
#define MAKE_ARG_LIST_107(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_106(op, __VA_ARGS__))
#define MAKE_ARG_LIST_108(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_107(op, __VA_ARGS__))
#define MAKE_ARG_LIST_109(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_108(op, __VA_ARGS__))
#define MAKE_ARG_LIST_110(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_109(op, __VA_ARGS__))
#define MAKE_ARG_LIST_111(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_110(op, __VA_ARGS__))
#define MAKE_ARG_LIST_112(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_111(op, __VA_ARGS__))
#define MAKE_ARG_LIST_113(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_112(op, __VA_ARGS__))
#define MAKE_ARG_LIST_114(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_113(op, __VA_ARGS__))
#define MAKE_ARG_LIST_115(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_114(op, __VA_ARGS__))
#define MAKE_ARG_LIST_116(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_115(op, __VA_ARGS__))
#define MAKE_ARG_LIST_117(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_116(op, __VA_ARGS__))
#define MAKE_ARG_LIST_118(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_117(op, __VA_ARGS__))
#define MAKE_ARG_LIST_119(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_118(op, __VA_ARGS__))
#define MAKE_ARG_LIST_120(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_119(op, __VA_ARGS__))
#define ADD_VIEW(str) std::string_view(#str, sizeof(#str)-1)
#define SEPERATOR ,
#define CON_STR_1(element, ...) ADD_VIEW(element)
#define CON_STR_2(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_1(__VA_ARGS__))
#define CON_STR_3(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_2(__VA_ARGS__))
#define CON_STR_4(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_3(__VA_ARGS__))
#define CON_STR_5(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_4(__VA_ARGS__))
#define CON_STR_6(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_5(__VA_ARGS__))
#define CON_STR_7(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_6(__VA_ARGS__))
#define CON_STR_8(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_7(__VA_ARGS__))
#define CON_STR_9(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_8(__VA_ARGS__))
#define CON_STR_10(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_9(__VA_ARGS__))
#define CON_STR_11(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_10(__VA_ARGS__))
#define CON_STR_12(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_11(__VA_ARGS__))
#define CON_STR_13(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_12(__VA_ARGS__))
#define CON_STR_14(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_13(__VA_ARGS__))
#define CON_STR_15(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_14(__VA_ARGS__))
#define CON_STR_16(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_15(__VA_ARGS__))
#define CON_STR_17(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_16(__VA_ARGS__))
#define CON_STR_18(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_17(__VA_ARGS__))
#define CON_STR_19(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_18(__VA_ARGS__))
#define CON_STR_20(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_19(__VA_ARGS__))
#define CON_STR_21(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_20(__VA_ARGS__))
#define CON_STR_22(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_21(__VA_ARGS__))
#define CON_STR_23(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_22(__VA_ARGS__))
#define CON_STR_24(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_23(__VA_ARGS__))
#define CON_STR_25(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_24(__VA_ARGS__))
#define CON_STR_26(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_25(__VA_ARGS__))
#define CON_STR_27(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_26(__VA_ARGS__))
#define CON_STR_28(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_27(__VA_ARGS__))
#define CON_STR_29(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_28(__VA_ARGS__))
#define CON_STR_30(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_29(__VA_ARGS__))
#define CON_STR_31(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_30(__VA_ARGS__))
#define CON_STR_32(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_31(__VA_ARGS__))
#define CON_STR_33(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_32(__VA_ARGS__))
#define CON_STR_34(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_33(__VA_ARGS__))
#define CON_STR_35(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_34(__VA_ARGS__))
#define CON_STR_36(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_35(__VA_ARGS__))
#define CON_STR_37(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_36(__VA_ARGS__))
#define CON_STR_38(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_37(__VA_ARGS__))
#define CON_STR_39(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_38(__VA_ARGS__))
#define CON_STR_40(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_39(__VA_ARGS__))
#define CON_STR_41(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_40(__VA_ARGS__))
#define CON_STR_42(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_41(__VA_ARGS__))
#define CON_STR_43(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_42(__VA_ARGS__))
#define CON_STR_44(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_43(__VA_ARGS__))
#define CON_STR_45(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_44(__VA_ARGS__))
#define CON_STR_46(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_45(__VA_ARGS__))
#define CON_STR_47(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_46(__VA_ARGS__))
#define CON_STR_48(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_47(__VA_ARGS__))
#define CON_STR_49(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_48(__VA_ARGS__))
#define CON_STR_50(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_49(__VA_ARGS__))
#define CON_STR_51(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_50(__VA_ARGS__))
#define CON_STR_52(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_51(__VA_ARGS__))
#define CON_STR_53(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_52(__VA_ARGS__))
#define CON_STR_54(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_53(__VA_ARGS__))
#define CON_STR_55(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_54(__VA_ARGS__))
#define CON_STR_56(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_55(__VA_ARGS__))
#define CON_STR_57(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_56(__VA_ARGS__))
#define CON_STR_58(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_57(__VA_ARGS__))
#define CON_STR_59(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_58(__VA_ARGS__))
#define CON_STR_60(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_59(__VA_ARGS__))
#define CON_STR_61(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_60(__VA_ARGS__))
#define CON_STR_62(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_61(__VA_ARGS__))
#define CON_STR_63(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_62(__VA_ARGS__))
#define CON_STR_64(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_63(__VA_ARGS__))
#define CON_STR_65(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_64(__VA_ARGS__))
#define CON_STR_66(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_65(__VA_ARGS__))
#define CON_STR_67(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_66(__VA_ARGS__))
#define CON_STR_68(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_67(__VA_ARGS__))
#define CON_STR_69(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_68(__VA_ARGS__))
#define CON_STR_70(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_69(__VA_ARGS__))
#define CON_STR_71(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_70(__VA_ARGS__))
#define CON_STR_72(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_71(__VA_ARGS__))
#define CON_STR_73(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_72(__VA_ARGS__))
#define CON_STR_74(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_73(__VA_ARGS__))
#define CON_STR_75(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_74(__VA_ARGS__))
#define CON_STR_76(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_75(__VA_ARGS__))
#define CON_STR_77(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_76(__VA_ARGS__))
#define CON_STR_78(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_77(__VA_ARGS__))
#define CON_STR_79(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_78(__VA_ARGS__))
#define CON_STR_80(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_79(__VA_ARGS__))
#define CON_STR_81(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_80(__VA_ARGS__))
#define CON_STR_82(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_81(__VA_ARGS__))
#define CON_STR_83(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_82(__VA_ARGS__))
#define CON_STR_84(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_83(__VA_ARGS__))
#define CON_STR_85(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_84(__VA_ARGS__))
#define CON_STR_86(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_85(__VA_ARGS__))
#define CON_STR_87(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_86(__VA_ARGS__))
#define CON_STR_88(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_87(__VA_ARGS__))
#define CON_STR_89(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_88(__VA_ARGS__))
#define CON_STR_90(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_89(__VA_ARGS__))
#define CON_STR_91(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_90(__VA_ARGS__))
#define CON_STR_92(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_91(__VA_ARGS__))
#define CON_STR_93(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_92(__VA_ARGS__))
#define CON_STR_94(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_93(__VA_ARGS__))
#define CON_STR_95(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_94(__VA_ARGS__))
#define CON_STR_96(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_95(__VA_ARGS__))
#define CON_STR_97(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_96(__VA_ARGS__))
#define CON_STR_98(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_97(__VA_ARGS__))
#define CON_STR_99(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_98(__VA_ARGS__))
#define CON_STR_100(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_99(__VA_ARGS__))
#define CON_STR_101(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_100(__VA_ARGS__))
#define CON_STR_102(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_101(__VA_ARGS__))
#define CON_STR_103(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_102(__VA_ARGS__))
#define CON_STR_104(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_103(__VA_ARGS__))
#define CON_STR_105(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_104(__VA_ARGS__))
#define CON_STR_106(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_105(__VA_ARGS__))
#define CON_STR_107(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_106(__VA_ARGS__))
#define CON_STR_108(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_107(__VA_ARGS__))
#define CON_STR_109(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_108(__VA_ARGS__))
#define CON_STR_110(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_109(__VA_ARGS__))
#define CON_STR_111(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_110(__VA_ARGS__))
#define CON_STR_112(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_111(__VA_ARGS__))
#define CON_STR_113(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_112(__VA_ARGS__))
#define CON_STR_114(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_113(__VA_ARGS__))
#define CON_STR_115(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_114(__VA_ARGS__))
#define CON_STR_116(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_115(__VA_ARGS__))
#define CON_STR_117(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_116(__VA_ARGS__))
#define CON_STR_118(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_117(__VA_ARGS__))
#define CON_STR_119(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_118(__VA_ARGS__))
#define CON_STR_120(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_119(__VA_ARGS__))
#define RSEQ_N() \
119,118,117,116,115,114,113,112,111,110,\
109,108,107,106,105,104,103,102,101,100,\
99,98,97,96,95,94,93,92,91,90, \
89,88,87,86,85,84,83,82,81,80, \
79,78,77,76,75,74,73,72,71,70, \
69,68,67,66,65,64,63,62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
#define ARG_N(\
_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, \
_11, _12, _13, _14, _15, _16, _17, _18, _19, _20, \
_21, _22, _23, _24, _25, _26, _27, _28, _29, _30, \
_31, _32, _33, _34, _35, _36, _37, _38, _39, _40, \
_41, _42, _43, _44, _45, _46, _47, _48, _49, _50, \
_51, _52, _53, _54, _55, _56, _57, _58, _59, _60, \
_61, _62, _63, _64, _65, _66, _67, _68, _69, _70, \
_71, _72, _73, _74, _75, _76, _77, _78, _79, _80, \
_81, _82, _83, _84, _85, _86, _87, _88, _89, _90, \
_91, _92, _93, _94, _95, _96, _97, _98, _99, _100, \
_101, _102, _103, _104, _105, _106, _107, _108, _109, _110, \
_111, _112, _113, _114, _115, _116, _117, _118, _119, N, ...) N
#define MARCO_EXPAND(...) __VA_ARGS__
#define APPLY_VARIADIC_MACRO(macro, ...) MARCO_EXPAND(macro(__VA_ARGS__))
#define ADD_REFERENCE(t) std::reference_wrapper<decltype(t)>(t)
#define ADD_REFERENCE_CONST(t) std::reference_wrapper<std::add_const_t<decltype(t)>>(t)
#define FIELD(t) t
#define MAKE_NAMES(...) #__VA_ARGS__,
//note use MACRO_CONCAT like A##_##B direct may cause marco expand error
#define MACRO_CONCAT(A, B) MACRO_CONCAT1(A, B)
#define MACRO_CONCAT1(A, B) A##_##B
#define MAKE_ARG_LIST(N, op, arg, ...) \
MACRO_CONCAT(MAKE_ARG_LIST, N)(op, arg, __VA_ARGS__)
#define GET_ARG_COUNT_INNER(...) MARCO_EXPAND(ARG_N(__VA_ARGS__))
#define GET_ARG_COUNT(...) GET_ARG_COUNT_INNER(__VA_ARGS__, RSEQ_N())
#define MAKE_STR_LIST(...) \
MACRO_CONCAT(CON_STR, GET_ARG_COUNT(__VA_ARGS__))(__VA_ARGS__)
#define MAKE_META_DATA_IMPL(STRUCT_NAME, ...) \
static auto iguana_reflect_members(STRUCT_NAME const&) \
{ \
struct reflect_members \
{ \
constexpr decltype(auto) static apply_impl(){\
return std::make_tuple(__VA_ARGS__);\
}\
using type = void;\
using size_type = std::integral_constant<size_t, GET_ARG_COUNT(__VA_ARGS__)>; \
constexpr static std::string_view name() { return std::string_view(#STRUCT_NAME, sizeof(#STRUCT_NAME)-1); }\
constexpr static size_t value() { return size_type::value; }\
constexpr static std::array<std::string_view, size_type::value> arr() { return arr_##STRUCT_NAME; }\
}; \
return reflect_members{}; \
}
#define MAKE_META_DATA(STRUCT_NAME, N, ...) \
constexpr inline std::array<std::string_view, N> arr_##STRUCT_NAME = { MARCO_EXPAND(MACRO_CONCAT(CON_STR, N)(__VA_ARGS__)) };\
MAKE_META_DATA_IMPL(STRUCT_NAME, MAKE_ARG_LIST(N, &STRUCT_NAME::FIELD, __VA_ARGS__))
}
namespace iguana
{
#define REFLECTION(STRUCT_NAME, ...) \
MAKE_META_DATA(STRUCT_NAME, GET_ARG_COUNT(__VA_ARGS__), __VA_ARGS__)
template<typename T>
using Reflect_members = decltype(iguana_reflect_members(std::declval<T>()));
template <typename T, typename = void>
struct is_reflection : std::false_type
{
};
template <typename T>
struct is_reflection<T, std::void_t<typename Reflect_members<T>::type>> : std::true_type
{
};
template<typename T>
inline constexpr bool is_reflection_v = is_reflection<T>::value;
template<size_t I, typename T>
constexpr decltype(auto) get(T&& t)
{
using M = decltype(iguana_reflect_members(std::forward<T>(t)));
using U = decltype(std::forward<T>(t).*(std::get<I>(M::apply_impl())));
if constexpr(std::is_array_v<U>) {
auto s = std::forward<T>(t).*(std::get<I>(M::apply_impl()));
std::array<char, sizeof(U)> arr;
memcpy(arr.data(), s, arr.size());
return arr;
}
else
return std::forward<T>(t).*(std::get<I>(M::apply_impl()));
}
template <typename T, size_t ... Is>
constexpr auto get_impl(T const& t, std::index_sequence<Is...>)
{
return std::make_tuple(get<Is>(t)...);
}
template <typename T, size_t ... Is>
constexpr auto get_impl(T& t, std::index_sequence<Is...>)
{
return std::make_tuple(std::ref(get<Is>(t))...);
}
template <typename T>
constexpr auto get(T const& t)
{
using M = decltype(iguana_reflect_members(t));
return get_impl(t, std::make_index_sequence<M::value()>{});
}
template <typename T>
constexpr auto get_ref(T& t)
{
using M = decltype(iguana_reflect_members(t));
return get_impl(t, std::make_index_sequence<M::value()>{});
}
template<typename T, size_t I>
constexpr const std::string_view get_name()
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
static_assert(I<M::value(), "out of range");
return M::arr()[I];
}
template<typename T>
constexpr const std::string_view get_name(size_t i)
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
// static_assert(I<M::value(), "out of range");
return M::arr()[i];
}
template<typename T>
constexpr const std::string_view get_name()
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
return M::name();
}
template<typename T>
constexpr std::enable_if_t<is_reflection<T>::value, size_t> get_value()
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
return M::value();
}
template<typename T>
constexpr std::enable_if_t<!is_reflection<T>::value, size_t> get_value()
{
return 1;
}
template<typename T>
constexpr auto get_array()
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
return M::arr();
}
template<typename T>
constexpr auto get_index(std::string_view name)
{
using M = decltype(iguana_reflect_members(std::declval<T>()));
constexpr auto arr = M::arr();
auto it = std::find_if(arr.begin(), arr.end(), [name](auto str){
return (str==name);
});
return std::distance(arr.begin(), it);
}
template <class Tuple, class F, std::size_t...Is>
void tuple_switch(std::size_t i, Tuple&& t, F&& f, std::index_sequence<Is...>) {
((i == Is && ((std::forward<F>(f)(std::get<Is>(std::forward<Tuple>(t)))), false)), ...);
}
//-------------------------------------------------------------------------------------------------------------//
//-------------------------------------------------------------------------------------------------------------//
template <typename... Args, typename F, std::size_t... Idx>
constexpr void for_each(std::tuple<Args...>& t, F&& f, std::index_sequence<Idx...>)
{
(std::forward<F>(f)(std::get<Idx>(t), std::integral_constant<size_t, Idx>{}), ...);
}
template <typename... Args, typename F, std::size_t... Idx>
constexpr void for_each(const std::tuple<Args...>& t, F&& f, std::index_sequence<Idx...>)
{
(std::forward<F>(f)(std::get<Idx>(t), std::integral_constant<size_t, Idx>{}), ...);
}
template<typename T, typename F>
constexpr std::enable_if_t<is_reflection<T>::value> for_each(T&& t, F&& f)
{
using M = decltype(iguana_reflect_members(std::forward<T>(t)));
for_each(M::apply_impl(), std::forward<F>(f), std::make_index_sequence<M::value()>{});
}
template<typename T, typename F>
constexpr std::enable_if_t<is_tuple<std::decay_t<T>>::value> for_each(T&& t, F&& f)
{
//using M = decltype(iguana_reflect_members(std::forward<T>(t)));
constexpr const size_t SIZE = std::tuple_size_v<std::decay_t<T>>;
for_each(std::forward<T>(t), std::forward<F>(f), std::make_index_sequence<SIZE>{});
}
}
#endif //IGUANA_REFLECTION_HPP | 14,742 |
620 | <reponame>LLLjun/learn-to-cluster<gh_stars>100-1000
from .test_gcn_v import test_gcn_v
from .test_gcn_e import test_gcn_e
from .train_gcn_v import train_gcn_v
from .train_gcn_e import train_gcn_e
__factory__ = {
'test_gcn_v': test_gcn_v,
'test_gcn_e': test_gcn_e,
'train_gcn_v': train_gcn_v,
'train_gcn_e': train_gcn_e,
}
def build_handler(phase, model):
key_handler = '{}_{}'.format(phase, model)
if key_handler not in __factory__:
raise KeyError("Unknown op:", key_handler)
return __factory__[key_handler]
| 254 |
884 | /*
* Copyright 2014 - 2021 Blazebit.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blazebit.persistence.examples.deltaspike.data.rest.controller;
import com.blazebit.persistence.deltaspike.data.KeysetPageable;
import com.blazebit.persistence.deltaspike.data.Page;
import com.blazebit.persistence.deltaspike.data.Specification;
import com.blazebit.persistence.deltaspike.data.rest.KeysetConfig;
import com.blazebit.persistence.examples.deltaspike.data.rest.filter.Filter;
import com.blazebit.persistence.examples.deltaspike.data.rest.model.Cat;
import com.blazebit.persistence.examples.deltaspike.data.rest.repository.CatRepository;
import com.blazebit.persistence.examples.deltaspike.data.rest.repository.CatViewRepository;
import com.blazebit.persistence.examples.deltaspike.data.rest.view.CatCreateView;
import com.blazebit.persistence.examples.deltaspike.data.rest.view.CatUpdateView;
import com.blazebit.persistence.examples.deltaspike.data.rest.view.CatWithOwnerView;
import com.blazebit.text.FormatUtils;
import com.blazebit.text.ParserContext;
import com.blazebit.text.SerializableFormat;
import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author <NAME>
* @since 1.2.0
*/
@Path("")
public class CatRestController {
private static final Map<String, SerializableFormat<?>> FILTER_ATTRIBUTES;
static {
Map<String, SerializableFormat<?>> filterAttributes = new HashMap<>();
filterAttributes.put("id", FormatUtils.getAvailableFormatters().get(Long.class));
filterAttributes.put("name", FormatUtils.getAvailableFormatters().get(String.class));
filterAttributes.put("age", FormatUtils.getAvailableFormatters().get(Integer.class));
filterAttributes.put("owner.name", FormatUtils.getAvailableFormatters().get(String.class));
FILTER_ATTRIBUTES = Collections.unmodifiableMap(filterAttributes);
}
@Inject
private CatRepository catRepository;
@Inject
private CatViewRepository catViewRepository;
@POST
@Path("/cats")
@Consumes(MediaType.APPLICATION_JSON)
public Response createCat(CatCreateView catCreateView) {
catViewRepository.save(catCreateView);
return Response.ok(catCreateView.getId().toString()).build();
}
@PUT
@Path("/cats/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateCat(@PathParam("id") long id, CatUpdateView catUpdateView) {
catViewRepository.save(catUpdateView);
return Response.ok(catUpdateView.getId().toString()).build();
}
@GET
@Path("/cats")
@Produces(MediaType.APPLICATION_JSON)
public Page<Cat> findPaginated(
@KeysetConfig(Cat.class) KeysetPageable keysetPageable,
@QueryParam("filter") final Filter[] filters) {
Specification<Cat> specification = getSpecificationForFilter(filters);
Page<Cat> resultPage = catRepository.findAll(specification, keysetPageable);
if (keysetPageable.getPageNumber() > resultPage.getTotalPages()) {
throw new RuntimeException("Invalid page number!");
}
return resultPage;
}
@GET
@Path("/cat-views")
@Produces(MediaType.APPLICATION_JSON)
public Page<CatWithOwnerView> findPaginatedViews(
@KeysetConfig(Cat.class) KeysetPageable keysetPageable,
@QueryParam("filter") final Filter[] filters) {
Specification<Cat> specification = getSpecificationForFilter(filters);
Page<CatWithOwnerView> resultPage = catViewRepository.findAll(specification, keysetPageable);
if (keysetPageable.getPageNumber() > resultPage.getTotalPages()) {
throw new RuntimeException("Invalid page number!");
}
return resultPage;
}
private Specification<Cat> getSpecificationForFilter(final Filter[] filters) {
if (filters == null || filters.length == 0) {
return null;
}
return new Specification<Cat>() {
@Override
public Predicate toPredicate(Root<Cat> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
ParserContext parserContext = new ParserContextImpl();
try {
for (Filter f : filters) {
SerializableFormat<?> format = FILTER_ATTRIBUTES.get(f.getField());
if (format != null) {
String[] fieldParts = f.getField().split("\\.");
javax.persistence.criteria.Path<?> path = root.get(fieldParts[0]);
for (int i = 1; i < fieldParts.length; i++) {
path = path.get(fieldParts[i]);
}
switch (f.getKind()) {
case EQ:
predicates.add(criteriaBuilder.equal(path, format.parse(f.getValue(), parserContext)));
break;
case GT:
predicates.add(criteriaBuilder.greaterThan((Expression<Comparable>) path, (Comparable) format.parse(f.getValue(), parserContext)));
break;
case LT:
predicates.add(criteriaBuilder.lessThan((Expression<Comparable>) path, (Comparable) format.parse(f.getValue(), parserContext)));
break;
case GTE:
predicates.add(criteriaBuilder.greaterThanOrEqualTo((Expression<Comparable>) path, (Comparable) format.parse(f.getValue(), parserContext)));
break;
case LTE:
predicates.add(criteriaBuilder.lessThanOrEqualTo((Expression<Comparable>) path, (Comparable) format.parse(f.getValue(), parserContext)));
break;
case IN:
List<String> values = f.getValues();
List<Object> filterValues = new ArrayList<>(values.size());
for (String value : values) {
filterValues.add(format.parse(value, parserContext));
}
predicates.add(path.in(filterValues));
break;
case BETWEEN:
predicates.add(criteriaBuilder.between((Expression<Comparable>) path, (Comparable) format.parse(f.getLow(), parserContext), (Comparable) format.parse(f.getHigh(), parserContext)));
break;
case STARTS_WITH:
predicates.add(criteriaBuilder.like((Expression<String>) path, format.parse(f.getValue(), parserContext) + "%"));
break;
case ENDS_WITH:
predicates.add(criteriaBuilder.like((Expression<String>) path, "%" + format.parse(f.getValue(), parserContext)));
break;
case CONTAINS:
predicates.add(criteriaBuilder.like((Expression<String>) path, "%" + format.parse(f.getValue(), parserContext) + "%"));
break;
default:
throw new UnsupportedOperationException("Unsupported kind: " + f.getKind());
}
}
}
} catch (ParseException ex) {
throw new RuntimeException(ex);
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}
private static class ParserContextImpl implements ParserContext {
private final Map<String, Object> contextMap;
private ParserContextImpl() {
this.contextMap = new HashMap();
}
public Object getAttribute(String name) {
return this.contextMap.get(name);
}
public void setAttribute(String name, Object value) {
this.contextMap.put(name, value);
}
}
}
| 4,522 |
721 | <filename>nucleus/io/gfile.py<gh_stars>100-1000
# Copyright 2018 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A Python interface for files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from nucleus.io.python import gfile
def Exists(filename):
return gfile.Exists(filename)
def Glob(pattern):
return gfile.Glob(pattern)
class ReadableFile(six.Iterator):
"""Wraps gfile.ReadableFile to add iteration, enter/exit and readlines."""
def __init__(self, filename):
self._file = gfile.ReadableFile.New(filename)
def __enter__(self):
return self
def __exit__(self, type_, value, traceback):
self._file.__exit__()
def __iter__(self):
return self
def __next__(self):
ok, line = self._file.Readline()
if ok:
return line
else:
raise StopIteration
def readlines(self):
lines = []
while True:
ok, line = self._file.Readline()
if ok:
lines.append(line)
else:
break
return lines
def Open(filename, mode="r"):
if mode.startswith("r"):
return ReadableFile(filename)
elif mode.startswith("w"):
return gfile.WritableFile.New(filename)
else:
raise ValueError("Unsupported mode '{}' for Open".format(mode))
| 611 |
428 | package org.test;
import loon.Stage;
import loon.action.sprite.Entity;
import loon.component.LLayer;
import loon.component.LSlider;
public class SliderTest extends Stage {
@Override
public void create() {
// 构建一个Layer
LLayer layer = new LLayer(500, 500);
// 不锁定拖拽
layer.setLocked(false);
LSlider slider = new LSlider(22, 22, 40, 150, true);
layer.add(slider);
LSlider slider2 = new LSlider(122, 122, 150, 40);
//slider2.setMaxValue(1000f);
//slider2.setValue(70);
layer.add(slider2);
layer.addSpriteAt(new Entity("ccc.png"), 150, 0);
layer.addSpriteAt(new Entity("ccc.png"), 200, 350);
layer.add(MultiScreenTest.getBackButton(this, 1));
add(layer);
}
}
| 295 |
763 | <gh_stars>100-1000
package org.batfish.representation.cisco_xr;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import org.batfish.common.Warnings;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.routing_policy.expr.BooleanExpr;
import org.batfish.datamodel.routing_policy.expr.BooleanExprs;
/** Stand-in for unimplemented route-policy boolean constructs */
@ParametersAreNonnullByDefault
public final class UnimplementedBoolean extends RoutePolicyBoolean {
public static @Nonnull UnimplementedBoolean instance() {
return INSTANCE;
}
@Override
public BooleanExpr toBooleanExpr(CiscoXrConfiguration cc, Configuration c, Warnings w) {
return BooleanExprs.FALSE;
}
@Override
public boolean equals(Object obj) {
return this == obj || obj instanceof UnimplementedBoolean;
}
@Override
public int hashCode() {
// randomly generated
return 0x1D6E93B2;
}
private static @Nonnull UnimplementedBoolean INSTANCE = new UnimplementedBoolean();
}
| 343 |
2,577 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.model.xml.impl.type.child;
import org.camunda.bpm.model.xml.Model;
import org.camunda.bpm.model.xml.impl.ModelBuildOperation;
import org.camunda.bpm.model.xml.impl.type.ModelElementTypeImpl;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;
import org.camunda.bpm.model.xml.type.child.ChildElementBuilder;
import org.camunda.bpm.model.xml.type.child.ChildElementCollectionBuilder;
import org.camunda.bpm.model.xml.type.child.SequenceBuilder;
import java.util.ArrayList;
import java.util.List;
/**
* @author <NAME>
*
*/
public class SequenceBuilderImpl implements SequenceBuilder, ModelBuildOperation {
private final ModelElementTypeImpl elementType;
private final List<ModelBuildOperation> modelBuildOperations = new ArrayList<ModelBuildOperation>();
public SequenceBuilderImpl(ModelElementTypeImpl modelType) {
this.elementType = modelType;
}
public <T extends ModelElementInstance> ChildElementBuilder<T> element(Class<T> childElementType) {
ChildElementBuilderImpl<T> builder = new ChildElementBuilderImpl<T>(childElementType, elementType);
modelBuildOperations.add(builder);
return builder;
}
public <T extends ModelElementInstance> ChildElementCollectionBuilder<T> elementCollection(Class<T> childElementType) {
ChildElementCollectionBuilderImpl<T> builder = new ChildElementCollectionBuilderImpl<T>(childElementType, elementType);
modelBuildOperations.add(builder);
return builder;
}
public void performModelBuild(Model model) {
for (ModelBuildOperation operation : modelBuildOperations) {
operation.performModelBuild(model);
}
}
}
| 686 |
324 | /*
* Copyright 2018 <NAME>. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.meituan.octo.mns.scanner.util.heartbeat;
import com.google.common.util.concurrent.SettableFuture;
import com.meituan.dorado.codec.octo.meta.Header;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HeartbeatHandler extends SimpleChannelInboundHandler<Header> {
private static final Logger log = LoggerFactory.getLogger(HeartbeatHandler.class);
private final SettableFuture<Integer> result;
public HeartbeatHandler(SettableFuture<Integer> result) {
this.result = result;
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Header header) throws Exception {
result.set(header.getHeartbeatInfo().getStatus());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("", cause);
ctx.close();
}
}
| 487 |
1,750 | ////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Typhoon Framework Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
#import <Foundation/Foundation.h>
#import "TyphoonResource.h"
@interface TyphoonPathResource : NSObject<TyphoonResource>
+ (id <TyphoonResource>)withPath:(NSString *)filePath;
- (instancetype)initWithContentsOfFile:(NSString *)filePath;
@end
| 160 |
1,338 | /*
* Copyright 2008 Haiku Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Julun, <<EMAIL>
*/
#include <PrintPanel.h>
#include <Button.h>
#include <GroupLayoutBuilder.h>
#include <GroupView.h>
#include <Screen.h>
namespace BPrivate {
namespace Print {
// #pragma mark -- _BPrintPanelFilter_
BPrintPanel::_BPrintPanelFilter_::_BPrintPanelFilter_(BPrintPanel* panel)
: BMessageFilter(B_KEY_DOWN)
, fPrintPanel(panel)
{
}
filter_result
BPrintPanel::_BPrintPanelFilter_::Filter(BMessage* msg, BHandler** target)
{
int32 key;
filter_result result = B_DISPATCH_MESSAGE;
if (msg->FindInt32("key", &key) == B_OK && key == 1) {
fPrintPanel->PostMessage(B_QUIT_REQUESTED);
result = B_SKIP_MESSAGE;
}
return result;
}
// #pragma mark -- BPrintPanel
BPrintPanel::BPrintPanel(const BString& title)
: BWindow(BRect(0, 0, 640, 480), title.String(), B_TITLED_WINDOW_LOOK,
B_MODAL_APP_WINDOW_FEEL, B_NOT_ZOOMABLE | B_NOT_RESIZABLE |
B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS | B_CLOSE_ON_ESCAPE)
, fPanel(new BGroupView)
, fPrintPanelSem(-1)
, fPrintPanelResult(B_CANCEL)
{
BButton* ok = new BButton("OK", new BMessage('_ok_'));
BButton* cancel = new BButton("Cancel", new BMessage('_cl_'));
BGroupLayout *layout = new BGroupLayout(B_HORIZONTAL);
SetLayout(layout);
AddChild(BGroupLayoutBuilder(B_VERTICAL, 10.0)
.Add(fPanel)
.Add(BGroupLayoutBuilder(B_HORIZONTAL, 10.0)
.AddGlue()
.Add(cancel)
.Add(ok)
.SetInsets(0.0, 0.0, 0.0, 0.0))
.SetInsets(10.0, 10.0, 10.0, 10.0)
);
ok->MakeDefault(true);
AddCommonFilter(new _BPrintPanelFilter_(this));
}
BPrintPanel::~BPrintPanel()
{
if (fPrintPanelSem > 0)
delete_sem(fPrintPanelSem);
}
BPrintPanel::BPrintPanel(BMessage* data)
: BWindow(data)
{
// TODO: implement
}
BArchivable*
BPrintPanel::Instantiate(BMessage* data)
{
// TODO: implement
return NULL;
}
status_t
BPrintPanel::Archive(BMessage* data, bool deep) const
{
// TODO: implement
return B_ERROR;
}
BView*
BPrintPanel::Panel() const
{
return fPanel->ChildAt(0);
}
void
BPrintPanel::AddPanel(BView* panel)
{
BView* child = Panel();
if (child) {
RemovePanel(child);
delete child;
}
fPanel->AddChild(panel);
BSize size = GetLayout()->PreferredSize();
ResizeTo(size.Width(), size.Height());
}
bool
BPrintPanel::RemovePanel(BView* child)
{
BView* panel = Panel();
if (child == panel)
return fPanel->RemoveChild(child);
return false;
}
void
BPrintPanel::MessageReceived(BMessage* message)
{
switch (message->what) {
case '_ok_': {
fPrintPanelResult = B_OK;
// fall through
case '_cl_':
delete_sem(fPrintPanelSem);
fPrintPanelSem = -1;
} break;
default:
BWindow::MessageReceived(message);
}
}
void
BPrintPanel::FrameResized(float newWidth, float newHeight)
{
BWindow::FrameResized(newWidth, newHeight);
}
BHandler*
BPrintPanel::ResolveSpecifier(BMessage* message, int32 index, BMessage* specifier,
int32 form, const char* property)
{
return BWindow::ResolveSpecifier(message, index, specifier, form, property);
}
status_t
BPrintPanel::GetSupportedSuites(BMessage* data)
{
return BWindow::GetSupportedSuites(data);
}
status_t
BPrintPanel::Perform(perform_code d, void* arg)
{
return BWindow::Perform(d, arg);
}
void
BPrintPanel::Quit()
{
BWindow::Quit();
}
bool
BPrintPanel::QuitRequested()
{
return BWindow::QuitRequested();
}
void
BPrintPanel::DispatchMessage(BMessage* message, BHandler* handler)
{
BWindow::DispatchMessage(message, handler);
}
status_t
BPrintPanel::ShowPanel()
{
fPrintPanelSem = create_sem(0, "PrintPanel");
if (fPrintPanelSem < 0) {
Quit();
return B_CANCEL;
}
BWindow* window = dynamic_cast<BWindow*> (BLooper::LooperForThread(find_thread(NULL)));
{
BRect bounds(Bounds());
BRect frame(BScreen(B_MAIN_SCREEN_ID).Frame());
MoveTo((frame.Width() - bounds.Width()) / 2.0,
(frame.Height() - bounds.Height()) / 2.0);
}
Show();
if (window) {
status_t err;
while (true) {
do {
err = acquire_sem_etc(fPrintPanelSem, 1, B_RELATIVE_TIMEOUT, 50000);
} while (err == B_INTERRUPTED);
if (err == B_BAD_SEM_ID)
break;
window->UpdateIfNeeded();
}
} else {
while (acquire_sem(fPrintPanelSem) == B_INTERRUPTED) {}
}
return fPrintPanelResult;
}
void
BPrintPanel::AddChild(BView* child, BView* before)
{
BWindow::AddChild(child, before);
}
bool
BPrintPanel::RemoveChild(BView* child)
{
return BWindow::RemoveChild(child);
}
BView*
BPrintPanel::ChildAt(int32 index) const
{
return BWindow::ChildAt(index);
}
void BPrintPanel::_ReservedBPrintPanel1() {}
void BPrintPanel::_ReservedBPrintPanel2() {}
void BPrintPanel::_ReservedBPrintPanel3() {}
void BPrintPanel::_ReservedBPrintPanel4() {}
void BPrintPanel::_ReservedBPrintPanel5() {}
} // namespace Print
} // namespace BPrivate
| 1,940 |
435 | <gh_stars>100-1000
{
"copyright_text": "This video is licensed under the CC BY-NC-SA 3.0 license: https://creativecommons.org/licenses/by-nc-sa/3.0/\nPlease see our speaker release agreement for details: https://ep2020.europython.eu/events/speaker-release-agreement/\n",
"description": "How Python can be used in IoT/infrastructure automation tasks\n\nThe talk will be a getting start guide on controlling hardware devices with Python. We know Python users are very keen on multitasking and always wish to know more about how it can be used in different tasks. This talk will help audiences exploring new Python skillset. Audiences may be inspired by this talk and apply it to many scenarios, e.g., IoT and infrastructure automation.\r\n\r\nIntended audiences include:\r\n1. wish to know how Python can be used beyond data analysis and web dev\r\n2. a Pythonista who interested in craft some touchable things \r\n3. want to acquire something new into your Python skillset\r\n\r\nAudiences are expected to have basic knowledge about:\r\n1. Python syntax and control flow\r\n2. Computer and operating system (especially UNIX)\r\n\r\nAfter this talk, audiences will have:\r\n1. The basic idea of controlling devices with Python\r\n2. Expanding their Python skillset. Know how to use Python in another interesting and useful task besides ML, web scrapping, etc.",
"duration": 1281.0,
"language": "eng",
"recorded": "2020-07-23",
"related_urls": [
{
"label": "Conference schedule",
"url": "https://ep2020.europython.eu/schedule/"
},
{
"label": "Conference Website",
"url": "https://ep2020.europython.eu/"
},
{
"label": "https://creativecommons.org/licenses/by-nc-sa/3.0/",
"url": "https://creativecommons.org/licenses/by-nc-sa/3.0/"
},
{
"label": "https://ep2020.europython.eu/events/speaker-release-agreement/",
"url": "https://ep2020.europython.eu/events/speaker-release-agreement/"
},
{
"label": "Talk URL",
"url": "https://ep2020.europython.eu/schedule/24-july?selected=7kfqf76-speak-python-with-devices"
},
{
"label": "Slides",
"url": "/media/conference/slides/7kfqf76-speak-python-with-devices.pdf"
}
],
"speakers": [
"<NAME>"
],
"tags": [
"europython",
"europython-2020",
"europython-online",
"CPython",
"Hardware/IoT",
"Other Hardware",
"Unix",
"python"
],
"thumbnail_url": "https://i.ytimg.com/vi/BpgtN8GK1M8/hqdefault.jpg?sqp=-oaymwEZCNACELwBSFXyq4qpAwsIARUAAIhCGAFwAQ==&rs=AOn4CLCR5GpYhgdJzF_6zobcVe-so2ec4g",
"title": "Speak Python with Devices",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=BpgtN8GK1M8"
}
]
}
| 1,038 |
437 | package io.nuls.ledger.rpc.model;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/**
* @author: <NAME>
* @date: 2018/10/11
*/
public class TokenInfoDto {
@ApiModelProperty(name = "totalNuls", value = "总的nuls数量")
private String totalNuls;
@ApiModelProperty(name = "totalNuls", value = "总的nuls数量")
private String lockedNuls;
@ApiModelProperty(name = "addressList", value = "持币明细")
private List<HolderDto> addressList;
public String getTotalNuls() {
return totalNuls;
}
public void setTotalNuls(String totalNuls) {
this.totalNuls = totalNuls;
}
public String getLockedNuls() {
return lockedNuls;
}
public void setLockedNuls(String lockedNuls) {
this.lockedNuls = lockedNuls;
}
public List<HolderDto> getAddressList() {
return addressList;
}
public void setAddressList(List<HolderDto> addressList) {
this.addressList = addressList;
}
}
| 416 |
376 | <reponame>mruz/framework
extern zend_class_entry *ice_validation_validator_same_ce;
ZEPHIR_INIT_CLASS(Ice_Validation_Validator_Same);
PHP_METHOD(Ice_Validation_Validator_Same, validate);
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_validation_validator_same_validate, 0, 0, 2)
ZEND_ARG_OBJ_INFO(0, validation, Ice\\Validation, 0)
ZEND_ARG_INFO(0, field)
ZEND_END_ARG_INFO()
ZEPHIR_INIT_FUNCS(ice_validation_validator_same_method_entry) {
PHP_ME(Ice_Validation_Validator_Same, validate, arginfo_ice_validation_validator_same_validate, ZEND_ACC_PUBLIC)
PHP_FE_END
};
| 243 |
1,338 | <reponame>Kirishikesan/haiku<filename>src/preferences/network/ServiceView.cpp<gh_stars>1000+
/*
* Copyright 2015 Haiku, Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* <NAME>, <<EMAIL>>
*/
#include "ServiceView.h"
#include <Button.h>
#include <Catalog.h>
#include <LayoutBuilder.h>
#include <MessageRunner.h>
#include <StringView.h>
#include <TextView.h>
static const uint32 kMsgToggleService = 'tgls';
static const uint32 kMsgEnableToggleButton = 'entg';
static const bigtime_t kDisableDuration = 500000;
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "ServiceView"
ServiceView::ServiceView(const char* name, const char* executable,
const char* title, const char* description, BNetworkSettings& settings)
:
BView("service", 0),
fName(name),
fExecutable(executable),
fSettings(settings)
{
BStringView* titleView = new BStringView("service", title);
titleView->SetFont(be_bold_font);
titleView->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));
BTextView* descriptionView = new BTextView("description");
descriptionView->SetText(description);
descriptionView->SetViewUIColor(B_PANEL_BACKGROUND_COLOR);
descriptionView->MakeEditable(false);
fEnableButton = new BButton("toggler", B_TRANSLATE("Enable"),
new BMessage(kMsgToggleService));
BLayoutBuilder::Group<>(this, B_VERTICAL)
.Add(titleView)
.Add(descriptionView)
.AddGlue()
.AddGroup(B_HORIZONTAL)
.AddGlue()
.Add(fEnableButton);
SetExplicitMinSize(BSize(200, B_SIZE_UNSET));
_UpdateEnableButton();
fWasEnabled = IsEnabled();
}
ServiceView::~ServiceView()
{
}
bool
ServiceView::IsRevertable() const
{
return IsEnabled() != fWasEnabled;
}
status_t
ServiceView::Revert()
{
if (IsRevertable())
_Toggle();
return B_OK;
}
void
ServiceView::SettingsUpdated(uint32 which)
{
if (which == BNetworkSettings::kMsgServiceSettingsUpdated)
_UpdateEnableButton();
}
void
ServiceView::AttachedToWindow()
{
fEnableButton->SetTarget(this);
}
void
ServiceView::MessageReceived(BMessage* message)
{
switch (message->what) {
case kMsgToggleService:
_Toggle();
break;
case kMsgEnableToggleButton:
fEnableButton->SetEnabled(true);
_UpdateEnableButton();
break;
default:
BView::MessageReceived(message);
break;
}
}
bool
ServiceView::IsEnabled() const
{
return fSettings.Service(fName).IsRunning();
}
void
ServiceView::Enable()
{
BNetworkServiceSettings settings;
settings.SetName(fName);
settings.AddArgument(fExecutable);
BMessage service;
if (settings.GetMessage(service) == B_OK)
fSettings.AddService(service);
}
void
ServiceView::Disable()
{
fSettings.RemoveService(fName);
}
void
ServiceView::_Toggle()
{
if (IsEnabled())
Disable();
else
Enable();
fEnableButton->SetEnabled(false);
BMessage reenable(kMsgEnableToggleButton);
BMessageRunner::StartSending(this, &reenable, kDisableDuration, 1);
}
void
ServiceView::_UpdateEnableButton()
{
fEnableButton->SetLabel(IsEnabled()
? B_TRANSLATE("Disable") : B_TRANSLATE("Enable"));
}
| 1,101 |
594 | #ifndef QTESTUPDATERBACKEND_H
#define QTESTUPDATERBACKEND_H
#include <QtCore/QTimer>
#include <QtCore/QTimer>
#include <QtAutoUpdaterCore/UpdaterBackend>
class QTestUpdaterBackend : public QtAutoUpdater::UpdaterBackend
{
Q_OBJECT
public:
explicit QTestUpdaterBackend(QString &&key, QObject *parent = nullptr);
Features features() const override;
SecondaryInfo secondaryInfo() const override;
void checkForUpdates() override;
void abort(bool force) override;
bool triggerUpdates(const QList<QtAutoUpdater::UpdateInfo> &infos, bool track) override;
QtAutoUpdater::UpdateInstaller *createInstaller() override;
protected:
bool initialize() override;
private Q_SLOTS:
void timerTriggered();
private:
QTimer *_timer;
bool _updating = false;
quint8 _tCounter = 0;
};
Q_DECLARE_LOGGING_CATEGORY(logTestPlugin)
#endif // QTESTUPDATERBACKEND_H
| 315 |
335 | <reponame>Safal08/Hacktoberfest-1
{
"word": "Compassion",
"definitions": [
"Sympathetic pity and concern for the sufferings or misfortunes of others."
],
"parts-of-speech": "Noun"
} | 87 |
1,544 | from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
from evennia.accounts.models import AccountDB
import re
class EvenniaUsernameAvailabilityValidator:
"""
Checks to make sure a given username is not taken or otherwise reserved.
"""
def __call__(self, username):
"""
Validates a username to make sure it is not in use or reserved.
Args:
username (str): Username to validate
Returns:
None (None): None if password successfully validated,
raises ValidationError otherwise.
"""
# Check guest list
if settings.GUEST_LIST and username.lower() in (
guest.lower() for guest in settings.GUEST_LIST
):
raise ValidationError(
_("Sorry, that username is reserved."), code="evennia_username_reserved"
)
# Check database
exists = AccountDB.objects.filter(username__iexact=username).exists()
if exists:
raise ValidationError(
_("Sorry, that username is already taken."), code="evennia_username_taken"
)
class EvenniaPasswordValidator:
def __init__(
self,
regex=r"^[\w. @+\-',]+$",
policy="Password should contain a mix of letters, "
"spaces, digits and @/./+/-/_/'/, only.",
):
"""
Constructs a standard Django password validator.
Args:
regex (str): Regex pattern of valid characters to allow.
policy (str): Brief explanation of what the defined regex permits.
"""
self.regex = regex
self.policy = policy
def validate(self, password, user=None):
"""
Validates a password string to make sure it meets predefined Evennia
acceptable character policy.
Args:
password (str): Password to validate
user (None): Unused argument but required by Django
Returns:
None (None): None if password successfully validated,
raises ValidationError otherwise.
"""
# Check complexity
if not re.findall(self.regex, password):
raise ValidationError(_(self.policy), code="evennia_password_policy")
def get_help_text(self):
"""
Returns a user-facing explanation of the password policy defined
by this validator.
Returns:
text (str): Explanation of password policy.
"""
return _(
"%s From a terminal client, you can also use a phrase of multiple words if "
"you enclose the password in double quotes." % self.policy
)
| 1,109 |
653 | package org.itstack.naive.chat.client.infrastructure.util;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 博 客:http://bugstack.cn
* 公众号:bugstack虫洞栈 | 沉淀、分享、成长,让自己和他人都能有所收获!
* create by 小傅哥 on @2020
*/
public class BeanUtil {
private static Map<String, Object> cacheMap = new ConcurrentHashMap<>();
public static synchronized void addBean(String name, Object obj) {
cacheMap.put(name, obj);
}
public static <T> T getBean(String name, Class<T> t) {
return (T) cacheMap.get(name);
}
}
| 276 |
554 | /*
* Copyright (c) 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.nick.eventbus.internal;
import android.support.annotation.NonNull;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import dev.nick.eventbus.Event;
import dev.nick.eventbus.EventReceiver;
import dev.nick.eventbus.annotation.CallInMainThread;
import dev.nick.eventbus.annotation.Events;
import dev.nick.eventbus.annotation.ReceiverMethod;
import dev.nick.eventbus.utils.ReflectionUtils;
/**
* Created by nick on 16-4-1.
* Email: <EMAIL>
*/
public class EventsWirer implements ClassWirer {
private final List<TaggedEventsReceiver> mReceivers;
private Subscriber mSubscriber;
public EventsWirer(Subscriber subscriber) {
this.mSubscriber = subscriber;
this.mReceivers = new ArrayList<>();
}
@Override
public void wire(final Object o) {
Class clz = o.getClass();
int[] events = null;
if (clz.isAnnotationPresent(Events.class)) {
Events annotation = (Events) clz.getAnnotation(Events.class);
events = annotation.value();
}
Method[] methods = clz.getDeclaredMethods();
for (final Method m : methods) {
ReflectionUtils.makeAccessible(m);
int modifier = m.getModifiers();
boolean isPublic = Modifier.isPublic(modifier);
if (!isPublic) continue;
String methodName = m.getName();
boolean isHandle = methodName.startsWith("handle")
|| m.isAnnotationPresent(ReceiverMethod.class);
if (!isHandle) continue;
boolean noParam;
Class[] params = m.getParameterTypes();
noParam = params.length == 0;
final boolean eventParam = params.length == 1 && params[0] == Event.class;
if (!noParam && !eventParam) continue;
int[] usingEvents = events;
if (m.isAnnotationPresent(Events.class)) {
Events methodAnno = m.getAnnotation(Events.class);
usingEvents = methodAnno.value();
}
if (usingEvents == null) continue;
final boolean callInMain = m.isAnnotationPresent(CallInMainThread.class);
TaggedEventsReceiver receiver = new TaggedEventsReceiver(usingEvents, o, methodName) {
@Override
public void onReceive(@NonNull Event event) {
if (eventParam)
ReflectionUtils.invokeMethod(m, o, event);
else ReflectionUtils.invokeMethod(m, o);
}
@Override
public boolean callInMainThread() {
return callInMain;
}
};
mSubscriber.subscribe(receiver);
saveReceiver(receiver);
}
}
public void unWire(Object o) {
List<EventReceiver> receivers = findReceiversByTag(o);
for (EventReceiver receiver : receivers) {
mSubscriber.unSubscribe(receiver);
}
}
private void saveReceiver(TaggedEventsReceiver receiver) {
synchronized (mReceivers) {
mReceivers.add(receiver);
}
}
private List<EventReceiver> findReceiversByTag(Object tag) {
List<EventReceiver> outs = new ArrayList<>();
synchronized (mReceivers) {
for (TaggedEventsReceiver receiver : mReceivers) {
if (receiver.from == tag) {
outs.add(receiver);
}
}
}
return outs;
}
@Override
public Class<? extends Annotation> annotationClass() {
return Events.class;
}
abstract class TaggedEventsReceiver extends EventReceiver {
int[] events;
Object from;
// For debug.
String methodName;
TaggedEventsReceiver(int[] events, Object from, String methodName) {
this.events = events;
this.from = from;
this.methodName = methodName;
}
@Override
public int[] events() {
return events;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaggedEventsReceiver that = (TaggedEventsReceiver) o;
if (!Arrays.equals(events, that.events)) return false;
if (!from.equals(that.from)) return false;
return methodName.equals(that.methodName);
}
@Override
public int hashCode() {
int result = Arrays.hashCode(events);
result = 31 * result + from.hashCode();
result = 31 * result + methodName.hashCode();
return result;
}
@Override
public String toString() {
return "TaggedEventsReceiver{" +
"events=" + Arrays.toString(events) +
", from=" + from +
", methodName='" + methodName + '\'' +
'}';
}
}
}
| 2,520 |
326 | <reponame>tristansgray/simian
#!/usr/bin/env python
#
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Shared resources for App Engine."""
import logging
from google.appengine.ext import blobstore
from google.appengine.ext import db
from simian.mac.common import datastore_locks
def BatchDatastoreOp(op, entities_or_keys, batch_size=25):
"""Performs a batch Datastore operation on a sequence of keys or entities.
Args:
op: func, Datastore operation to perform, i.e. db.put or db.delete.
entities_or_keys: sequence, db.Key or db.Model instances.
batch_size: int, number of keys or entities to batch per operation.
"""
for i in xrange(0, len(entities_or_keys), batch_size):
op(entities_or_keys[i:i + batch_size])
def SafeBlobDel(blobstore_key):
"""Helper method to delete a blob by its key.
Args:
blobstore_key: str, a blob key
"""
try:
blobstore.delete_async(blobstore_key)
except blobstore.Error, e:
logging.warning((
'blobstore.delete(%s) failed: %s. '
'this key is now probably orphaned.'), blobstore_key, str(e))
def SafeEntityDel(entity):
"""Helper method to delete an entity.
Args:
entity: App Engine db.Model instance.
"""
try:
entity.delete_async()
except db.Error, e:
logging.warning((
'Model.delete(%s) failed: %s. '
'this entity is now probably empty.'), entity.key().name(), str(e))
def GetBlobAndDel(blobstore_key):
"""Get a blob, delete it and return what was its contents.
Note: Only for use with SMALL Blobs (under 1024x1024 bytes).
Args:
blobstore_key: str, a blob key
Returns:
str, the blob data
"""
blob_reader = blobstore.BlobReader(blobstore_key)
blob_str = blob_reader.read(1024 * 1024) # bigger than any pkginfo
blob_reader.close()
SafeBlobDel(blobstore_key)
return blob_str
class QueryIterator(object):
"""Class to assist with iterating over big App Engine Datastore queries.
NOTE: this class is not compatible with queries using filters with IN or !=.
"""
def __init__(self, query, step=1000):
self._query = query
self._step = step
def __iter__(self):
"""Iterate over query results safely avoiding 30s query limitations."""
while True:
entities = self._query.fetch(self._step)
if not entities:
raise StopIteration
for entity in entities:
yield entity
self._query.with_cursor(self._query.cursor())
def LockExists(name):
"""Returns True if a lock with the given str name exists, False otherwise."""
e = datastore_locks._DatastoreLockEntity.get_by_id(name) # pylint: disable=protected-access
if e:
return e.lock_held
return False
| 1,092 |
585 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.schema;
import java.io.IOException;
import java.util.Map;
import org.apache.lucene.document.FeatureField;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.IndexableFieldType;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.solr.common.SolrException;
import org.apache.solr.response.TextResponseWriter;
import org.apache.solr.search.QParser;
import org.apache.solr.search.RankQParserPlugin;
import org.apache.solr.uninverting.UninvertingReader.Type;
/**
* <p>
* {@code RankField}s can be used to store scoring factors to improve document ranking. They should be used
* in combination with {@link RankQParserPlugin}. To use:
* </p>
* <p>
* Define the {@code RankField} {@code fieldType} in your schema:
* </p>
* <pre class="prettyprint">
* <fieldType name="rank" class="solr.RankField" />
* </pre>
* <p>
* Add fields to the schema, i.e.:
* </p>
* <pre class="prettyprint">
* <field name="pagerank" type="rank" />
* </pre>
*
* Query using the {@link RankQParserPlugin}, for example
* <pre class="prettyprint">
* http://localhost:8983/solr/techproducts?q=memory _query_:{!rank f='pagerank', function='log' scalingFactor='1.2'}
* </pre>
*
* @see RankQParserPlugin
* @lucene.experimental
* @since 8.6
*/
public class RankField extends FieldType {
/*
* While the user can create multiple RankFields, internally we use a single Lucene field,
* and we map the Solr field name to the "feature" in Lucene's FeatureField. This is mainly
* to simplify the user experience.
*/
public static final String INTERNAL_RANK_FIELD_NAME = "_rank_";
@Override
public Type getUninversionType(SchemaField sf) {
throw new UnsupportedOperationException();
}
@Override
public void write(TextResponseWriter writer, String name, IndexableField f) throws IOException {
}
@Override
protected void init(IndexSchema schema, Map<String,String> args) {
super.init(schema, args);
if (schema.getFieldOrNull(INTERNAL_RANK_FIELD_NAME) != null) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "A field named \"" + INTERNAL_RANK_FIELD_NAME + "\" can't be defined in the schema");
}
for (int prop:new int[] {STORED, DOC_VALUES, OMIT_TF_POSITIONS, SORT_MISSING_FIRST, SORT_MISSING_LAST}) {
if ((trueProperties & prop) != 0) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Property \"" + getPropertyName(prop) + "\" can't be set to true in RankFields");
}
}
for (int prop:new int[] {UNINVERTIBLE, INDEXED, MULTIVALUED}) {
if ((falseProperties & prop) != 0) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Property \"" + getPropertyName(prop) + "\" can't be set to false in RankFields");
}
}
properties &= ~(UNINVERTIBLE | STORED | DOC_VALUES);
}
@Override
protected IndexableField createField(String name, String val, IndexableFieldType type) {
if (val == null || val.isEmpty()) {
return null;
}
float featureValue;
try {
featureValue = Float.parseFloat(val);
} catch (NumberFormatException nfe) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error while creating field '" + name + "' from value '" + val + "'. Expecting float.", nfe);
}
// Internally, we always use the same field
return new FeatureField(INTERNAL_RANK_FIELD_NAME, name, featureValue);
}
@Override
public Query getExistenceQuery(QParser parser, SchemaField field) {
return new TermQuery(new Term(INTERNAL_RANK_FIELD_NAME, field.getName()));
}
@Override
public Query getFieldQuery(QParser parser, SchemaField field, String externalVal) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"Only a \"*\" term query can be done on RankFields");
}
@Override
protected Query getSpecializedRangeQuery(QParser parser, SchemaField field, String part1, String part2,
boolean minInclusive, boolean maxInclusive) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"Range queries not supported on RankFields");
}
@Override
public SortField getSortField(SchemaField field, boolean top) {
// We could use FeatureField.newFeatureSort()
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"can not sort on a rank field: " + field.getName());
}
}
| 1,773 |
4,223 | /*
* Copyright 2001-2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joda.time.chrono;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeFieldType;
import org.joda.time.DurationField;
import org.joda.time.ReadablePartial;
import org.joda.time.field.PreciseDurationDateTimeField;
/**
* Provides time calculations for the week of a week based year component of time.
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @since 1.1, refactored from GJWeekOfWeekyearDateTimeField
*/
final class BasicWeekOfWeekyearDateTimeField extends PreciseDurationDateTimeField {
@SuppressWarnings("unused")
private static final long serialVersionUID = -1587436826395135328L;
private final BasicChronology iChronology;
/**
* Restricted constructor
*/
BasicWeekOfWeekyearDateTimeField(BasicChronology chronology, DurationField weeks) {
super(DateTimeFieldType.weekOfWeekyear(), weeks);
iChronology = chronology;
}
/**
* Get the week of a week based year component of the specified time instant.
*
* @see org.joda.time.DateTimeField#get(long)
* @param instant the time instant in millis to query.
* @return the week of the year extracted from the input.
*/
public int get(long instant) {
return iChronology.getWeekOfWeekyear(instant);
}
public DurationField getRangeDurationField() {
return iChronology.weekyears();
}
// 1970-01-01 is day of week 4, Thursday. The rounding methods need to
// apply a corrective alignment since weeks begin on day of week 1, Monday.
public long roundFloor(long instant) {
return super.roundFloor(instant + 3 * DateTimeConstants.MILLIS_PER_DAY)
- 3 * DateTimeConstants.MILLIS_PER_DAY;
}
public long roundCeiling(long instant) {
return super.roundCeiling(instant + 3 * DateTimeConstants.MILLIS_PER_DAY)
- 3 * DateTimeConstants.MILLIS_PER_DAY;
}
public long remainder(long instant) {
return super.remainder(instant + 3 * DateTimeConstants.MILLIS_PER_DAY);
}
public int getMinimumValue() {
return 1;
}
public int getMaximumValue() {
return 53;
}
public int getMaximumValue(long instant) {
int weekyear = iChronology.getWeekyear(instant);
return iChronology.getWeeksInYear(weekyear);
}
public int getMaximumValue(ReadablePartial partial) {
if (partial.isSupported(DateTimeFieldType.weekyear())) {
int weekyear = partial.get(DateTimeFieldType.weekyear());
return iChronology.getWeeksInYear(weekyear);
}
return 53;
}
public int getMaximumValue(ReadablePartial partial, int[] values) {
int size = partial.size();
for (int i = 0; i < size; i++) {
if (partial.getFieldType(i) == DateTimeFieldType.weekyear()) {
int weekyear = values[i];
return iChronology.getWeeksInYear(weekyear);
}
}
return 53;
}
protected int getMaximumValueForSet(long instant, int value) {
return value > 52 ? getMaximumValue(instant) : 52;
}
/**
* Serialization singleton
*/
private Object readResolve() {
return iChronology.weekOfWeekyear();
}
}
| 1,434 |
598 | <reponame>thedrow/eliot<gh_stars>100-1000
"""
TAI64N encoding and decoding.
TAI64N encodes nanosecond-accuracy timestamps and is supported by logstash.
@see: U{http://cr.yp.to/libtai/tai64.html}.
"""
from __future__ import unicode_literals
import struct
from binascii import b2a_hex, a2b_hex
_STRUCTURE = b">QI"
_OFFSET = (2 ** 62) + 10 # last 10 are leap seconds
def encode(timestamp):
"""
Convert seconds since epoch to TAI64N string.
@param timestamp: Seconds since UTC Unix epoch as C{float}.
@return: TAI64N-encoded time, as C{unicode}.
"""
seconds = int(timestamp)
nanoseconds = int((timestamp - seconds) * 1000000000)
seconds = seconds + _OFFSET
encoded = b2a_hex(struct.pack(_STRUCTURE, seconds, nanoseconds))
return "@" + encoded.decode("ascii")
def decode(tai64n):
"""
Convert TAI64N string to seconds since epoch.
Note that dates before 2013 may not decode accurately due to leap second
issues. If you need correct decoding for earlier dates you can try the
tai64n package available from PyPI (U{https://pypi.python.org/pypi/tai64n}).
@param tai64n: TAI64N-encoded time, as C{unicode}.
@return: Seconds since UTC Unix epoch as C{float}.
"""
seconds, nanoseconds = struct.unpack(_STRUCTURE, a2b_hex(tai64n[1:]))
seconds -= _OFFSET
return seconds + (nanoseconds / 1000000000.0)
| 514 |
335 | package com.kalvin.kvf.common.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Create by Kalvin on 2020/3/16.
*/
@Configuration
public class LocalDateTimeSerializerConfig {
@Bean
public ObjectMapper serializingObjectMapper() {
JavaTimeModule javaTimeModule = new JavaTimeModule();
LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTimeSerializer serializer = new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
javaTimeModule.addDeserializer(LocalDateTime.class, deserializer);
javaTimeModule.addSerializer(serializer);
return Jackson2ObjectMapperBuilder.json()
.modules(javaTimeModule)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
}
| 526 |
598 | <gh_stars>100-1000
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from .error_code import ERROR_CODE
class MAROException(Exception):
"""The base exception class for MARO.
Args:
error_code (int): the predefined MARO error code. You can find the
detailed definition in: `maro.utils.exception.error_code.py`.
msg (str): Description of the error. Defaults to None, which will
show the base error information.
"""
def __init__(self, error_code: int = 1000, msg: str = None):
self.error_code = error_code
self.strerror = msg if msg else ERROR_CODE[self.error_code]
def __str__(self):
return self.strerror if isinstance(self.strerror, str) else str(self.strerror)
def __repr__(self):
return f"{self.__class__.__name__}({str(self)})"
| 328 |
349 | """Sciter platform-dependent types."""
import sys
import ctypes
from ctypes import (POINTER,
c_char, c_byte, c_ubyte,
c_void_p, c_char_p,
c_int32, c_uint32, c_int64, c_uint64,
c_longlong, c_ulonglong, c_double,
sizeof, c_size_t, c_ssize_t)
# 'win32', 'darwin', 'linux'
SCITER_OS = sys.platform
SCITER_WIN = SCITER_OS == 'win32'
SCITER_OSX = SCITER_OS == 'darwin'
SCITER_LNX = SCITER_OS == 'linux'
def utf16tostr(addr, size=-1):
"""Read UTF-16 string from memory and encode as python string."""
if addr is None:
return None
cb = size if size > 0 else 32
bstr = ctypes.string_at(addr, cb)
if size >= 0:
return bstr.decode('utf-16le')
# lookup zero char
chunks = []
while True:
found = cb
for i in range(0, cb, 2):
c = bstr[i]
if c == 0x00:
found = i
break
pass
assert found % 2 == 0, "truncated string with len " + str(found)
chunks.append(bstr[0:found].decode('utf-16le'))
if found != cb:
break
addr = addr + cb
bstr = ctypes.string_at(addr, cb)
continue
return "".join(chunks)
class c_utf16_p(ctypes.c_char_p):
"""A ctypes wrapper for UTF-16 string pointer."""
# Taken from https://stackoverflow.com/a/35507014/736762, thanks to @eryksun.
def __init__(self, value=None):
super(c_utf16_p, self).__init__()
if value is not None:
self.value = value
@property
def value(self,
c_void_p=ctypes.c_void_p):
addr = c_void_p.from_buffer(self).value
return utf16tostr(addr)
@value.setter
def value(self, value,
c_char_p=ctypes.c_char_p):
value = value.encode('utf-16le') + b'\x00'
c_char_p.value.__set__(self, value)
@classmethod
def from_param(cls, obj):
if isinstance(obj, str):
obj = obj.encode('utf-16le') + b'\x00'
return super(c_utf16_p, cls).from_param(obj)
@classmethod
def _check_retval_(cls, result):
return result.value
pass
class UTF16LEField(object):
"""Structure member wrapper for UTF-16 string pointers."""
# Taken from https://stackoverflow.com/a/35507014/736762, thanks to @eryksun.
def __init__(self, name):
self.name = name
def __get__(self, obj, cls,
c_void_p=ctypes.c_void_p,
addressof=ctypes.addressof):
field_addr = addressof(obj) + getattr(cls, self.name).offset
addr = c_void_p.from_address(field_addr).value
return utf16tostr(addr)
def __set__(self, obj, value):
value = value.encode('utf-16le') + b'\x00'
setattr(obj, self.name, value)
pass
if SCITER_WIN:
# sciter.dll since 4.0.0.0
SCITER_DLL_NAME = "sciter"
SCITER_DLL_EXT = ".dll"
SCFN = ctypes.WINFUNCTYPE
SC_CALLBACK = ctypes.WINFUNCTYPE
HWINDOW = c_void_p # HWND
HDC = c_void_p # HDC
BOOL = c_int32
LPCWSTR = LPWSTR = ctypes.c_wchar_p
ID2D1RenderTarget = c_void_p
ID2D1Factory = c_void_p
IDWriteFactory = c_void_p
IDXGISwapChain = c_void_p
IDXGISurface = c_void_p
elif SCITER_OSX:
# sciter-osx-32 since 3.3.1.8
# libsciter since 4.4.6.3
SCITER_DLL_NAME = "libsciter"
SCITER_DLL_EXT = ".dylib"
SCFN = ctypes.CFUNCTYPE
SC_CALLBACK = ctypes.CFUNCTYPE
HWINDOW = c_void_p # NSView*
HDC = c_void_p # CGContextRef
BOOL = c_byte
LPCWSTR = LPWSTR = c_utf16_p
elif SCITER_LNX:
# libsciter since 3.3.1.7
# libsciter-gtk.so instead of libsciter-gtk-64.so since 4.1.4
SCITER_DLL_NAME = "libsciter-gtk"
SCITER_DLL_EXT = ".so"
SCFN = ctypes.CFUNCTYPE
SC_CALLBACK = ctypes.CFUNCTYPE
HWINDOW = c_void_p # GtkWidget*
HDC = c_void_p # cairo_t
BOOL = c_byte
LPCWSTR = LPWSTR = c_utf16_p
# Common types
VOID = None
nullptr = POINTER(c_int32)()
BYTE = c_byte
INT = c_int32
UINT = c_uint32
INT64 = c_int64
tiscript_value = c_uint64
# must be pointer-wide
# WPARAM is defined as UINT_PTR (unsigned type)
# LPARAM is defined as LONG_PTR (signed type)
WPARAM = c_size_t
LPARAM = c_ssize_t
UINT_PTR = c_size_t
LRESULT = c_ssize_t
PBOOL = LPBOOL = POINTER(BOOL)
LPCBYTE = c_char_p
LPCSTR = LPSTR = c_char_p
LPCVOID = LPVOID = c_void_p
LPUINT = POINTER(UINT)
class RECT(ctypes.Structure):
"""Rectangle coordinates structure."""
_fields_ = [("left", c_int32),
("top", c_int32),
("right", c_int32),
("bottom", c_int32)]
tagRECT = _RECTL = RECTL = RECT
PRECT = LPRECT = POINTER(RECT)
class POINT(ctypes.Structure):
"""Point coordinates structure."""
_fields_ = [("x", c_int32),
("y", c_int32)]
tagPOINT = _POINTL = POINTL = POINT
PPOINT = LPPOINT = POINTER(POINT)
class SIZE(ctypes.Structure):
"""SIZE structure for width and height."""
_fields_ = [("cx", c_int32),
("cy", c_int32)]
tagSIZE = SIZEL = SIZE
PSIZE = LPSIZE = POINTER(SIZE)
class MSG(ctypes.Structure):
"""MSG structure for windows message queue."""
_fields_ = [("hWnd", HWINDOW),
("message", c_uint32),
("wParam", WPARAM),
("lParam", LPARAM),
("time", c_uint32),
("pt", POINT)]
PMSG = LPMSG = POINTER(MSG)
| 2,770 |
1,831 | /**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <folly/dynamic.h>
namespace facebook { namespace logdevice { namespace ldbench {
/**
* Base class for target of storing stats
* StatsStore is not thread-safe and should only be invoked from a single
* thread. Users could use a stats collection thread that collects stats
* from all relevant threads and write the results to the StatsStore.
*/
class StatsStore {
public:
virtual ~StatsStore() {}
/**
* Return True if StatsStore is ready to receive stats
*/
virtual bool isReady() = 0;
/**
* Persist the current stats into StatsStore.
*
* @param stats_obj
* A folly::dynamic object (a container of key-value pairs) of timeseries
* name to a numeric value. The values are the current value of the
* timeseries--aggregation happens downstream of StatsStore.
* E.g.,
* folly::dynamic::object("timestamp", 123)("succeed", 1000)("failed",
* 200);
*/
virtual void writeCurrentStats(const folly::dynamic& stats_obj) = 0;
};
}}} // namespace facebook::logdevice::ldbench
| 382 |
486 | <reponame>Mivik/jflex
package edu.tum.cup2.precedences;
import java.util.List;
import edu.tum.cup2.grammar.Terminal;
/**
* Left associativity of terminals.
*
* @author <NAME>
*/
public class LeftAssociativity
extends Associativity
{
/**
* Creates a left associativity for the given list of {@link Terminal}s.
*/
public LeftAssociativity(List<Terminal> terminals)
{
super(terminals);
}
}
| 155 |
349 | <gh_stars>100-1000
import sys
import os
import re
import colorama
colorama.init()
import refactoring # Note: refactoring.py need to be in the current working directory
paths = ["C:/inviwo-dev", "C:/inviwo-research/modules"]
# Step 1:
# replace:
# InviwoProcessorInfo();
# with:
# virtual const ProcessorInfo getProcessorInfo() const override;
# static const ProcessorInfo processorInfo_;
n = refactoring.find_files(paths, ['*.h'], excludes=["*/ext/*", "*moc_*", "*cmake*", "*/proteindocking/*", "*/proteindocking2/*", "*/genetree/*"])
err = refactoring.check_file_type(n, "UTF-8")
if len(err)>0: sys.exit("Encoding errors")
n2 = refactoring.find_files(paths, ['*.cpp'], excludes=["*/ext/*", "*moc_*", "*cmake*", "*/proteindocking/*", "*/proteindocking2/*", "*/genetree/*"])
err2 = refactoring.check_file_type(n2, "UTF-8")
if len(err2)>0: sys.exit("Encoding errors")
pattern = r"(\s*)InviwoProcessorInfo\(\);"
replacement = r"\1virtual const ProcessorInfo getProcessorInfo() const override;\n\1static const ProcessorInfo processorInfo_;"
print("Matches:")
matches = refactoring.find_matches(n, pattern)
print("\n")
print("Replacing:")
refactoring.replace_matches(matches, pattern, replacement)
# Step 2:
# replace:
# ProcessorDisplayName(VolumeRaycaster, "Volume Raycaster");
# ProcessorTags(VolumeRaycaster, Tags::GL);
# ProcessorCategory(VolumeRaycaster, "Volume Rendering");
# ProcessorCodeState(VolumeRaycaster, CODE_STATE_STABLE);
# with:
# const ProcessorInfo VolumeRaycaster::processorInfo_{
# "org.inviwo.VolumeRaycaster", // Class identifer
# "Volume Raycaster", // Display name
# "Volume Rendering", // Category
# CODE_STATE_STABLE, // Code state
# Tags::GL // Tags
# };
# const ProcessorInfo VolumeRaycaster::getProcessorInfo() const {
# return processorInfo_;
# }
def cs(var):
if var == "CODE_STATE_STABLE":
return "CodeState::Stable"
elif var == "CODE_STATE_EXPERIMENTAL":
return "CodeState::Experimental"
elif var == "CODE_STATE_BROKEN":
return "CodeState::Broken"
else:
return var
def updatecpp(files):
patterns = {
"cid" : r"""[ ]*ProcessorClassIdentifier\((\w+),\s+("[-&\.\w]+")\);?""",
"name" : r"""[ ]*ProcessorDisplayName\((\w+),\s*("[-& \.\w]+")\);?""",
"tags" : r"""[ ]*ProcessorTags\((\w+),\s+([",/:\w]+)\);?""",
"cat" : r"""[ ]*ProcessorCategory\((\w+),\s+("[ \.\w]+")\);?""",
"state" : r"""[ ]*ProcessorCodeState\((\w+),\s+([_:\w]+)\);?"""
}
rs = {k : re.compile(v, re.MULTILINE) for k,v in patterns.items()}
repl = lambda x : r"""const ProcessorInfo {0:s}::processorInfo_{{
{cid:""" +str(x)+ """s} // Class identifier
{name:""" +str(x)+ """s} // Display name
{cat:""" +str(x)+ """s} // Category
{state:""" +str(x)+ """s} // Code state
{tags:""" +str(x)+ """s} // Tags
}};
const ProcessorInfo {0:s}::getProcessorInfo() const {{
return processorInfo_;
}}
"""
matching_files = []
for file in files:
with open(file, "r") as f:
text = f.read()
matches = {k : v.search(text) for k,v in rs.items()}
if all(matches.values()):
refactoring.print_warn("Match in: " + file)
matching_files.append(file)
for m in matches.values():
matched = "-->" + colorama.Fore.YELLOW + m.group(0) + colorama.Style.RESET_ALL +"<--"
print("{0:s}".format(matched))
cname = {k : (v.group(1) if k != "state" else cs(v.group(1))) for k,v in matches.items()}
data = {k : (v.group(2) if k != "state" else cs(v.group(2)))+"," for k,v in matches.items()}
slen = max([len(s) for s in data.values()])
template = repl(slen)
with open(file, "w") as f:
for (i,line) in enumerate(text.split("\n")):
ms = {k : v.search(line) for k,v in rs.items()}
if ms["cid"]:
f.write(template.format(cname["cid"], **data))
elif any(ms.values()):
continue
else:
f.write(line +"\n")
print("Updating cppfiles")
updatecpp(n2)
| 1,688 |
1,108 | <gh_stars>1000+
#include "SDL.h"
#include "SDL_gpu.h"
#include "compat.h"
#include "common.h"
int main(int argc, char* argv[])
{
GPU_Target* screen;
printRenderers();
screen = GPU_Init(800, 600, GPU_DEFAULT_INIT_FLAGS);
if(screen == NULL)
return -1;
printCurrentRenderer();
{
Uint32 startTime;
long frameCount;
Uint8 done;
SDL_Event event;
float dt;
const Uint8* keystates;
#define MAX_SPRITES 50
int numSprites = 1;
float x[MAX_SPRITES];
float y[MAX_SPRITES];
float velx[MAX_SPRITES];
float vely[MAX_SPRITES];
int i;
GPU_Rect buffer_viewport = GPU_MakeRect(400, 20, 400, 580);
GPU_Rect buffer_screen_viewport = GPU_MakeRect(20, 20, 100, 100);
GPU_Rect small_viewport = GPU_MakeRect(600, 20, 100, 100);
GPU_Rect viewport = GPU_MakeRect(100, 100, 600, 400);
GPU_Image* buffer;
GPU_Image* image = GPU_LoadImage("data/test.bmp");
if(image == NULL)
return -1;
buffer = GPU_CreateImage(800, 600, GPU_FORMAT_RGB);
GPU_LoadTarget(buffer);
startTime = SDL_GetTicks();
frameCount = 0;
for(i = 0; i < MAX_SPRITES; i++)
{
x[i] = rand()%screen->w;
y[i] = rand()%screen->h;
velx[i] = 10 + rand()%screen->w/10;
vely[i] = 10 + rand()%screen->h/10;
}
keystates = SDL_GetKeyState(NULL);
dt = 0.010f;
done = 0;
while(!done)
{
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
done = 1;
else if(event.type == SDL_KEYDOWN)
{
if(event.key.keysym.sym == SDLK_ESCAPE)
done = 1;
else if(event.key.keysym.sym == SDLK_r)
{
viewport = GPU_MakeRect(0.0f, 0.0f, screen->w, screen->h);
}
else if(event.key.keysym.sym == SDLK_EQUALS || event.key.keysym.sym == SDLK_PLUS)
{
if(numSprites < MAX_SPRITES)
numSprites++;
}
else if(event.key.keysym.sym == SDLK_MINUS)
{
if(numSprites > 0)
numSprites--;
}
}
}
if(keystates[KEY_UP])
viewport.y -= 100*dt;
else if(keystates[KEY_DOWN])
viewport.y += 100*dt;
if(keystates[KEY_LEFT])
viewport.x -= 100*dt;
else if(keystates[KEY_RIGHT])
viewport.x += 100*dt;
if(keystates[KEY_w])
viewport.h -= 100*dt;
else if(keystates[KEY_s])
viewport.h += 100*dt;
if(keystates[KEY_a])
viewport.w -= 100*dt;
else if(keystates[KEY_d])
viewport.w += 100*dt;
for(i = 0; i < numSprites; i++)
{
x[i] += velx[i]*dt;
y[i] += vely[i]*dt;
if(x[i] < 0)
{
x[i] = 0;
velx[i] = -velx[i];
}
else if(x[i]> screen->w)
{
x[i] = screen->w;
velx[i] = -velx[i];
}
if(y[i] < 0)
{
y[i] = 0;
vely[i] = -vely[i];
}
else if(y[i]> screen->h)
{
y[i] = screen->h;
vely[i] = -vely[i];
}
}
GPU_UnsetClip(screen);
GPU_Clear(screen);
// Draw on buffer
GPU_ClearRGBA(buffer->target, 100, 0, 0, 0);
GPU_SetViewport(buffer->target, buffer_viewport);
for(i = 0; i < numSprites; i++)
{
GPU_Blit(image, NULL, buffer->target, x[i], y[i]);
}
// Draw buffer to screen
GPU_SetViewport(screen, buffer_screen_viewport);
GPU_Blit(buffer, NULL, screen, screen->w/2, screen->h/2);
GPU_SetClipRect(screen, small_viewport);
GPU_ClearRGBA(screen, 0, 100, 0, 0);
GPU_SetViewport(screen, small_viewport);
for(i = 0; i < numSprites; i++)
{
GPU_Blit(image, NULL, screen, x[i], y[i]);
}
GPU_SetClipRect(screen, viewport);
GPU_ClearRGBA(screen, 0, 0, 100, 0);
GPU_SetViewport(screen, viewport);
for(i = 0; i < numSprites; i++)
{
GPU_Blit(image, NULL, screen, x[i], y[i]);
}
GPU_Flip(screen);
frameCount++;
if(frameCount%500 == 0)
printf("Average FPS: %.2f\n", 1000.0f*frameCount/(SDL_GetTicks() - startTime));
}
printf("Average FPS: %.2f\n", 1000.0f*frameCount/(SDL_GetTicks() - startTime));
GPU_FreeImage(image);
}
GPU_Quit();
return 0;
}
| 3,201 |
314 | <reponame>timgates42/theanets<filename>test/recurrent_test.py
import numpy as np
import pytest
import theanets
import util as u
AE_LAYERS = [u.NUM_INPUTS, (u.NUM_HID1, 'rnn'), (u.NUM_HID2, 'rnn'), u.NUM_INPUTS]
CLF_LAYERS = [u.NUM_INPUTS, (u.NUM_HID1, 'rnn'), (u.NUM_HID2, 'rnn'), u.NUM_CLASSES]
REG_LAYERS = [u.NUM_INPUTS, (u.NUM_HID1, 'rnn'), (u.NUM_HID2, 'rnn'), u.NUM_OUTPUTS]
def assert_shape(actual, expected):
if not isinstance(expected, tuple):
expected = (u.NUM_EXAMPLES, u.RNN.NUM_TIMES, expected)
assert actual == expected
@pytest.mark.parametrize('Model, layers, weighted, data', [
(theanets.recurrent.Regressor, REG_LAYERS, False, u.RNN.REG_DATA),
(theanets.recurrent.Classifier, CLF_LAYERS, False, u.RNN.CLF_DATA),
(theanets.recurrent.Autoencoder, AE_LAYERS, False, u.RNN.AE_DATA),
(theanets.recurrent.Regressor, REG_LAYERS, True, u.RNN.WREG_DATA),
(theanets.recurrent.Classifier, CLF_LAYERS, True, u.RNN.WCLF_DATA),
(theanets.recurrent.Autoencoder, AE_LAYERS, True, u.RNN.WAE_DATA),
])
def test_sgd(Model, layers, weighted, data):
u.assert_progress(Model(layers, weighted=weighted), data)
@pytest.mark.parametrize('Model, layers', [
(theanets.recurrent.Regressor, REG_LAYERS),
(theanets.recurrent.Classifier, CLF_LAYERS),
(theanets.recurrent.Autoencoder, AE_LAYERS),
])
def test_predict(Model, layers):
assert_shape(Model(layers).predict(u.INPUTS).shape, output)
@pytest.mark.parametrize('Model, layers, target, score', [
(theanets.recurrent.Regressor, REG_LAYERS, u.RNN.OUTPUTS, -0.73883247375488281),
(theanets.recurrent.Classifier, CLF_LAYERS, u.RNN.CLASSES, 0.0020161290322580645),
(theanets.recurrent.Autoencoder, AE_LAYERS, u.RNN.INPUTS, 81.411415100097656),
])
def test_score(Model, layers, target, score):
assert Model(layers).score(u.RNN.INPUTS, target) == score
@pytest.mark.parametrize('Model, layers, target', [
(theanets.recurrent.Regressor, REG_LAYERS, u.NUM_OUTPUTS),
(theanets.recurrent.Classifier, CLF_LAYERS, u.NUM_CLASSES),
(theanets.recurrent.Autoencoder, AE_LAYERS, u.NUM_INPUTS),
])
def test_predict(Model, layers, target):
outs = Model(layers).feed_forward(u.RNN.INPUTS)
assert len(list(outs)) == 7
assert_shape(outs['in:out'].shape, u.NUM_INPUTS)
assert_shape(outs['hid1:out'].shape, u.NUM_HID1)
assert_shape(outs['hid2:out'].shape, u.NUM_HID2)
assert_shape(outs['out:out'].shape, target)
def test_symbolic_initial_state():
net = theanets.recurrent.Regressor([
dict(size=u.NUM_INPUTS, form='input', name='h0', ndim=2),
dict(size=u.NUM_INPUTS, form='input', name='in'),
dict(size=u.NUM_HID1, form='rnn', name='rnn', h_0='h0'),
dict(size=u.NUM_OUTPUTS, form='ff', name='out'),
])
H0 = np.random.randn(u.NUM_EXAMPLES, u.NUM_HID1).astype('f')
u.assert_progress(net, [H0, u.RNN.INPUTS, u.RNN.OUTPUTS])
class TestClassifier:
@pytest.fixture
def net(self):
return theanets.recurrent.Classifier(CLF_LAYERS)
def test_predict_proba(self, net):
assert_shape(net.predict_proba(u.RNN.INPUTS).shape, u.NUM_CLASSES)
def test_predict_logit(self, net):
assert_shape(net.predict_logit(u.RNN.INPUTS).shape, u.NUM_CLASSES)
def test_score(self, net):
w = 0.5 * np.ones(u.CLASSES.shape, 'f')
assert 0 <= net.score(u.RNN.INPUTS, u.CLASSES, w) <= 1
def test_predict_sequence(self, net):
assert list(net.predict_sequence([0, 1, 2], 5, rng=13)) == [4, 5, 1, 3, 1]
class TestAutoencoder:
@pytest.fixture
def net(self):
return theanets.recurrent.Autoencoder(AE_LAYERS)
def test_encode_hid1(self, net):
z = net.encode(u.RNN.INPUTS, 'hid1')
assert_shape(z.shape, u.NUM_HID1)
def test_encode_hid2(self, net):
z = net.encode(u.RNN.INPUTS, 'hid2')
assert_shape(z.shape, u.NUM_HID2)
def test_decode_hid1(self, net):
x = net.decode(net.encode(u.RNN.INPUTS))
assert_shape(x.shape, u.NUM_INPUTS)
def test_decode_hid2(self, net):
x = net.decode(net.encode(u.RNN.INPUTS, 'hid2'), 'hid2')
assert_shape(x.shape, u.NUM_INPUTS)
def test_score(self, net):
labels = np.random.randint(0, 2, size=u.RNN.INPUTS.shape)
assert net.score(u.RNN.INPUTS, labels) < 0
class TestFunctions:
@pytest.fixture
def samples(self):
return np.random.randn(2 * u.RNN.NUM_TIMES, u.NUM_INPUTS)
@pytest.fixture
def labels(self):
return np.random.randn(2 * u.RNN.NUM_TIMES, u.NUM_OUTPUTS)
def test_batches_labeled(self, samples, labels):
f = theanets.recurrent.batches(
[samples, labels], steps=u.RNN.NUM_TIMES, batch_size=u.NUM_EXAMPLES)
assert len(f()) == 2
assert_shape(f()[0].shape, u.NUM_INPUTS)
assert_shape(f()[1].shape, u.NUM_OUTPUTS)
def test_batches_unlabeled(self, samples):
f = theanets.recurrent.batches(
[samples], steps=u.RNN.NUM_TIMES, batch_size=u.NUM_EXAMPLES)
assert len(f()) == 1
assert_shape(f()[0].shape, u.NUM_INPUTS)
class TestText:
TXT = 'hello world, how are you!'
def test_min_count(self):
txt = theanets.recurrent.Text(self.TXT, min_count=2, unknown='_')
assert txt.text == 'hello worl__ how _re _o__'
assert txt.alpha == ' ehlorw'
txt = theanets.recurrent.Text(self.TXT, min_count=3, unknown='_')
assert txt.text == '__llo _o_l__ _o_ ___ _o__'
assert txt.alpha == ' lo'
@pytest.fixture
def txt(self):
return theanets.recurrent.Text(self.TXT, alpha='helo wrd,!', unknown='_')
def test_alpha(self, txt):
assert txt.text == 'hello world, how _re _o_!'
assert txt.alpha == 'helo wrd,!'
def test_encode(self, txt):
assert txt.encode('hello!') == [1, 2, 3, 3, 4, 10]
assert txt.encode('you!') == [0, 4, 0, 10]
def test_decode(self, txt):
assert txt.decode([1, 2, 3, 3, 4, 10]) == 'hello!'
assert txt.decode([0, 4, 0, 10]) == '_o_!'
def test_classifier_batches(self, txt):
b = txt.classifier_batches(steps=8, batch_size=5)
assert len(b()) == 2
assert b()[0].shape == (5, 8, 1 + len(txt.alpha))
assert b()[1].shape == (5, 8)
assert not np.allclose(b()[0], b()[0])
| 3,032 |
2,757 | /** @file
This protocol provides services to register a platform specific handler for
ResetSystem(). The registered handlers are called after the UEFI 2.7 Reset
Notifications are processed
Copyright (c) 2017 Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available under
the terms and conditions of the BSD License that accompanies this distribution.
The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef _PLATFORM_SPECIFIC_RESET_HANDLER_PROTOCOL_H_
#define _PLATFORM_SPECIFIC_RESET_HANDLER_PROTOCOL_H_
#include <Protocol/ResetNotification.h>
#define EDKII_PLATFORM_SPECIFIC_RESET_HANDLER_PROTOCOL_GUID \
{ 0x2df6ba0b, 0x7092, 0x440d, { 0xbd, 0x4, 0xfb, 0x9, 0x1e, 0xc3, 0xf3, 0xc1 } }
typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_HANDLER_PROTOCOL;
extern EFI_GUID gEdkiiPlatformSpecificResetHandlerProtocolGuid;
#endif
| 427 |
14,668 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/secure_channel/nearby_endpoint_finder_impl.h"
#include "base/base64.h"
#include "base/memory/ptr_util.h"
#include "base/rand_util.h"
#include "chrome/browser/ash/secure_channel/util/histogram_util.h"
#include "chromeos/components/multidevice/logging/logging.h"
#include "chromeos/services/secure_channel/public/mojom/nearby_connector.mojom.h"
namespace ash {
namespace secure_channel {
namespace {
// TODO(https://crbug.com/1164001): remove after
// chromeos/services/secure_channel is moved to namespace ash.
namespace mojom = ::chromeos::secure_channel::mojom;
using ::location::nearby::connections::mojom::DiscoveredEndpointInfoPtr;
using ::location::nearby::connections::mojom::DiscoveryOptions;
using ::location::nearby::connections::mojom::MediumSelection;
using ::location::nearby::connections::mojom::Status;
using ::location::nearby::connections::mojom::Strategy;
NearbyEndpointFinderImpl::Factory* g_test_factory = nullptr;
const size_t kEndpointIdLength = 4u;
const size_t kEndpointInfoLength = 4u;
void OnStopDiscoveryDestructorResult(Status status) {
util::RecordStopDiscoveryResult(status);
if (status != Status::kSuccess)
PA_LOG(WARNING) << "Failed to stop discovery as part of destructor";
}
std::vector<uint8_t> GenerateRandomByteArray(size_t length) {
std::string endpoint_info = base::RandBytesAsString(length);
return std::vector<uint8_t>(endpoint_info.begin(), endpoint_info.end());
}
std::string GenerateEndpointId() {
// Generate a random array of bytes; as long as it is of size of at least
// 3/4 kEndpointInfoLength, the final substring of the Base64-encoded array
// will be of size kEndpointInfoLength.
std::vector<uint8_t> raw_endpoint_info =
GenerateRandomByteArray(kEndpointIdLength);
// Return the first kEndpointIdLength characters of the Base64-encoded string.
return base::Base64Encode(raw_endpoint_info).substr(0, kEndpointIdLength);
}
std::vector<uint8_t> GenerateEndpointInfo(const std::vector<uint8_t>& eid) {
if (eid.size() < 2) {
return GenerateRandomByteArray(kEndpointInfoLength);
}
std::vector<uint8_t> endpoint_info = {
// version number
1,
// 2 bytes indicating the EID
eid[0],
eid[1],
};
return endpoint_info;
}
} // namespace
// static
std::unique_ptr<NearbyEndpointFinder> NearbyEndpointFinderImpl::Factory::Create(
const mojo::SharedRemote<
location::nearby::connections::mojom::NearbyConnections>&
nearby_connections) {
if (g_test_factory)
return g_test_factory->CreateInstance(nearby_connections);
return base::WrapUnique(new NearbyEndpointFinderImpl(nearby_connections));
}
// static
void NearbyEndpointFinderImpl::Factory::SetFactoryForTesting(
Factory* test_factory) {
g_test_factory = test_factory;
}
NearbyEndpointFinderImpl::NearbyEndpointFinderImpl(
const mojo::SharedRemote<
location::nearby::connections::mojom::NearbyConnections>&
nearby_connections)
: nearby_connections_(nearby_connections),
endpoint_id_(GenerateEndpointId()) {}
NearbyEndpointFinderImpl::~NearbyEndpointFinderImpl() {
if (is_discovery_active_) {
nearby_connections_->StopDiscovery(
mojom::kServiceId, base::BindOnce(&OnStopDiscoveryDestructorResult));
}
}
void NearbyEndpointFinderImpl::PerformFindEndpoint() {
is_discovery_active_ = true;
endpoint_info_ = GenerateEndpointInfo(eid());
nearby_connections_->StartDiscovery(
mojom::kServiceId,
DiscoveryOptions::New(Strategy::kP2pPointToPoint,
MediumSelection::New(/*bluetooth=*/true,
/*ble=*/false,
/*webrtc=*/false,
/*wifi_lan=*/false),
/*fast_advertisement_service_uuid=*/absl::nullopt,
/*is_out_of_band_connection=*/true),
endpoint_discovery_listener_receiver_.BindNewPipeAndPassRemote(),
base::BindOnce(&NearbyEndpointFinderImpl::OnStartDiscoveryResult,
weak_ptr_factory_.GetWeakPtr()));
}
void NearbyEndpointFinderImpl::OnEndpointFound(const std::string& endpoint_id,
DiscoveredEndpointInfoPtr info) {
// Only look for endpoints whose endpoint metadata field matches the
// parameters passed to the InjectEndpoint() call.
if (endpoint_id_ != endpoint_id || endpoint_info_ != info->endpoint_info)
return;
PA_LOG(VERBOSE) << "Found endpoint with ID " << endpoint_id_
<< ", stopping discovery";
nearby_connections_->StopDiscovery(
mojom::kServiceId,
base::BindOnce(&NearbyEndpointFinderImpl::OnStopDiscoveryResult,
weak_ptr_factory_.GetWeakPtr(), std::move(info)));
}
void NearbyEndpointFinderImpl::OnStartDiscoveryResult(Status status) {
util::RecordStartDiscoveryResult(status);
if (status != Status::kSuccess) {
PA_LOG(WARNING) << "Failed to start Nearby discovery: " << status;
is_discovery_active_ = false;
NotifyEndpointDiscoveryFailure();
return;
}
PA_LOG(VERBOSE) << "Started Nearby discovery";
nearby_connections_->InjectBluetoothEndpoint(
mojom::kServiceId, endpoint_id_, endpoint_info_,
remote_device_bluetooth_address(),
base::BindOnce(&NearbyEndpointFinderImpl::OnInjectBluetoothEndpointResult,
weak_ptr_factory_.GetWeakPtr()));
}
void NearbyEndpointFinderImpl::OnInjectBluetoothEndpointResult(Status status) {
util::RecordInjectEndpointResult(status);
if (status != Status::kSuccess) {
PA_LOG(WARNING) << "Failed to inject Bluetooth endpoint: " << status;
NotifyEndpointDiscoveryFailure();
return;
}
PA_LOG(VERBOSE) << "Injected Bluetooth endpoint";
}
void NearbyEndpointFinderImpl::OnStopDiscoveryResult(
location::nearby::connections::mojom::DiscoveredEndpointInfoPtr info,
Status status) {
util::RecordStopDiscoveryResult(status);
is_discovery_active_ = false;
if (status != Status::kSuccess) {
PA_LOG(WARNING) << "Failed to stop Nearby discovery: " << status;
NotifyEndpointDiscoveryFailure();
return;
}
NotifyEndpointFound(endpoint_id_, std::move(info));
}
} // namespace secure_channel
} // namespace ash
| 2,488 |
5,169 | {
"name": "MRMemoryDetect",
"version": "0.0.3",
"summary": "MRMemoryDetect",
"description": "MRMemoryDetect is design for iOS detect memory change",
"homepage": "https://github.com/GitTrandy/MRMemoryDetect",
"authors": {
"GitTrandy": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/GitTrandy/MRMemoryDetect.git",
"tag": "0.0.3"
},
"source_files": [
"MRMemoryDetect",
"MRMemoryDetect/**/*.{h,m}"
],
"requires_arc": true
}
| 212 |
310 | {
"name": "TERTIAL",
"description": "A desk lamp.",
"url": "https://www.ikea.com/us/en/catalog/products/20370383/"
} | 51 |
3,850 | <filename>AndroidAnnotations/androidannotations-core/androidannotations-api/src/main/java/org/androidannotations/annotations/FocusChange.java
/**
* Copyright (C) 2010-2016 eBusiness Information, Excilys Group
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed To in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.androidannotations.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>
* This annotation is intended to be used on methods to receive events defined
* by
* {@link android.view.View.OnFocusChangeListener#onFocusChange(android.view.View, boolean)}
* after focus is changed on the targeted View or subclass of View.
* </p>
* <p>
* The annotation value should be one or several R.id.* fields that refers to
* View or subclasses of View. If not set, the method name will be used as the
* R.id.* field name.
* </p>
* <p>
* The method MAY have multiple parameter:
* </p>
* <ul>
* <li>A {@link android.view.View} (or a subclass) parameter to know which view
* has targeted this event</li>
* <li>An {@link boolean} to know the view has focus.</li>
* </ul>
*
* <blockquote>
*
* Example :
*
* <pre>
* @FocusChange(<b>R.id.myButton</b>)
* void focusChangedOnMyButton(boolean isChecked, View button) {
* // Something Here
* }
*
* @FocusChange
* void <b>myButton</b>FocusChanged(View button) {
* // Something Here
* }
*
* @FocusChange
* void <b>myText</b>FocusChanged(EditText button) {
* // Something Here
* }
*
* @FocusChange(<b>{R.id.myButton, R.id.myButton1}</b>)
* void focusChangedOnSomeButtons(View button, boolean isChecked) {
* // Something Here
* }
*
* @FocusChange(<b>R.id.myButton</b>)
* void focusChangedOnMyButton() {
* // Something Here
* }
* </pre>
*
* </blockquote>
*/
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface FocusChange {
/**
* The R.id.* fields which refer to the Views.
*
* @return the ids of the Views
*/
int[] value() default ResId.DEFAULT_VALUE;
/**
* The resource names as strings which refer to the Views.
*
* @return the resource names of the Views
*/
String[] resName() default "";
}
| 878 |
4,012 | <reponame>etseidl/cudf
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <benchmark/benchmark.h>
#include <benchmarks/common/generate_benchmark_input.hpp>
#include <benchmarks/fixture/benchmark_fixture.hpp>
#include <benchmarks/synchronization/synchronization.hpp>
#include <cudf/column/column.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/replace.hpp>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/table/table.hpp>
#include <cudf/types.hpp>
class ReplaceNans : public cudf::benchmark {
};
template <typename type>
static void BM_replace_nans(benchmark::State& state, bool include_nulls)
{
cudf::size_type const n_rows{(cudf::size_type)state.range(0)};
auto const dtype = cudf::type_to_id<type>();
auto const table = create_random_table({dtype}, 1, row_count{n_rows});
if (!include_nulls) { table->get_column(0).set_null_mask(rmm::device_buffer{}, 0); }
cudf::column_view input(table->view().column(0));
auto zero = cudf::make_fixed_width_scalar<type>(0);
for (auto _ : state) {
cuda_event_timer timer(state, true);
auto result = cudf::replace_nans(input, *zero);
}
}
#define NANS_BENCHMARK_DEFINE(name, type, nulls) \
BENCHMARK_DEFINE_F(ReplaceNans, name) \
(::benchmark::State & state) { BM_replace_nans<type>(state, nulls); } \
BENCHMARK_REGISTER_F(ReplaceNans, name) \
->UseManualTime() \
->Arg(10000) /* 10k */ \
->Arg(100000) /* 100k */ \
->Arg(1000000) /* 1M */ \
->Arg(10000000) /* 10M */ \
->Arg(100000000); /* 100M */
NANS_BENCHMARK_DEFINE(float32_nulls, float, true);
NANS_BENCHMARK_DEFINE(float64_nulls, double, true);
NANS_BENCHMARK_DEFINE(float32_no_nulls, float, false);
NANS_BENCHMARK_DEFINE(float64_no_nulls, double, false);
| 1,176 |
1,724 | #pragma once
#include "system/devices/DeviceAddress.h"
Iter unix_scan(IterFunc<UNIXAddress> callback);
| 38 |
1,041 | package io.ebeaninternal.server.type;
import io.ebeaninternal.server.type.ScalarTypeEnumStandard.OrdinalEnum;
import io.ebeaninternal.server.type.ScalarTypeEnumStandard.StringEnum;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.Customer;
import org.tests.model.basic.Order;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestEnumToBeanType {
@Test
public void test() {
StringEnum stringEnum = new ScalarTypeEnumStandard.StringEnum(Order.Status.class);
OrdinalEnum ordinalEnum = new ScalarTypeEnumStandard.OrdinalEnum(Order.Status.class);
EnumToDbValueMap<?> beanDbMap = EnumToDbValueMap.create(false);
beanDbMap.add(Customer.Status.ACTIVE, "A", Customer.Status.ACTIVE.name());
beanDbMap.add(Customer.Status.NEW, "N", Customer.Status.NEW.name());
beanDbMap.add(Customer.Status.INACTIVE, "I", Customer.Status.INACTIVE.name());
ScalarTypeEnumWithMapping withMapping = new ScalarTypeEnumWithMapping(beanDbMap, Customer.Status.class, 1);
Object approved = stringEnum.toBeanType(Order.Status.APPROVED);
assertEquals(approved, Order.Status.APPROVED);
approved = ordinalEnum.toBeanType(Order.Status.APPROVED);
assertEquals(approved, Order.Status.APPROVED);
Object active = withMapping.toBeanType(Customer.Status.ACTIVE);
assertEquals(active, Customer.Status.ACTIVE);
}
}
| 489 |
665 | <reponame>gamblor21/Adafruit_Learning_System_Guides<gh_stars>100-1000
import board
import storage
from analogio import AnalogIn
def read_buttons():
with AnalogIn(board.A3) as ain:
reading = ain.value / 65535
if reading > 0.75:
return None
if reading > 0.4:
return 4
if reading > 0.25:
return 3
if reading > 0.13:
return 2
return 1
readonly = True
# if a button is pressed while booting up, CircuitPython can write to the drive
button = read_buttons()
if button != None:
readonly = False
if readonly:
print("OS has write access to CircuitPython drive")
else:
print("CircuitPython has write access to drive")
storage.remount("/", readonly)
| 304 |
456 | <reponame>belzecue/DJV
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2004-2020 <NAME>
// All rights reserved.
#include <djvGeom/Shape.h>
#include <djvGeom/TriangleMesh.h>
#include <djvMath/Math.h>
#include <djvMath/Math.h>
using namespace djv::Core;
namespace djv
{
namespace Geom
{
IShape::~IShape()
{}
Square::Square(float radius) :
_radius(radius)
{}
void Square::setRadius(float value)
{
_radius = value;
}
namespace
{
const size_t offset = 1;
}
void Square::triangulate(TriangleMesh& mesh) const
{
mesh.v.push_back(glm::vec3(-_radius, 0.F, _radius));
mesh.v.push_back(glm::vec3(_radius, 0.F, _radius));
mesh.v.push_back(glm::vec3(_radius, 0.F, -_radius));
mesh.v.push_back(glm::vec3(-_radius, 0.F, -_radius));
mesh.t.push_back(glm::vec3(0.F, 0.F, 0.F));
mesh.t.push_back(glm::vec3(1.F, 0.F, 0.F));
mesh.t.push_back(glm::vec3(1.F, 1.F, 0.F));
mesh.t.push_back(glm::vec3(0.F, 1.F, 0.F));
TriangleMesh::Triangle triangle;
triangle.v0.v = triangle.v0.t = 0 + offset;
triangle.v1.v = triangle.v1.t = 1 + offset;
triangle.v2.v = triangle.v2.t = 2 + offset;
mesh.triangles.push_back(triangle);
triangle.v0.v = triangle.v0.t = 2 + offset;
triangle.v1.v = triangle.v1.t = 3 + offset;
triangle.v2.v = triangle.v2.t = 0 + offset;
mesh.triangles.push_back(triangle);
TriangleMesh::calcNormals(mesh);
}
Circle::Circle(float radius, size_t resolution) :
_radius(radius)
{
setResolution(resolution);
}
void Circle::setRadius(float value)
{
_radius = value;
}
void Circle::setResolution(size_t value)
{
_resolution = std::max(value, size_t(3));
}
void Circle::triangulate(TriangleMesh& mesh) const
{
for (size_t i = 0; i < _resolution; ++i)
{
const float v = static_cast<float>(i) / static_cast<float>(_resolution);
const float c = cosf(v * Math::pi2);
const float s = sinf(v * Math::pi2);
mesh.v.push_back(glm::vec3(c * _radius, 0.F, s * _radius));
mesh.t.push_back(glm::vec3((c + 1.F) / 2.F, (s + 1.F) / 2.F, 0.F));
}
TriangleMesh::Triangle triangle;
const size_t resolutionMinusOne = static_cast<size_t>(_resolution - 1);
for (size_t i = 1; i < resolutionMinusOne; ++i)
{
triangle.v0.v = triangle.v0.t = 0 + offset;
triangle.v1.v = triangle.v1.t = i + offset;
triangle.v2.v = triangle.v2.t = i + 1 + offset;
mesh.triangles.push_back(triangle);
}
TriangleMesh::calcNormals(mesh);
}
Cube::Cube(float radius) :
_radius(radius)
{}
void Cube::setRadius(float value)
{
_radius = value;
}
void Cube::triangulate(TriangleMesh& mesh) const
{
Math::BBox3f bbox;
bbox.min = glm::vec3(-_radius, -_radius, -_radius);
bbox.max = glm::vec3(_radius, _radius, _radius);
TriangleMesh::triangulateBBox(bbox, mesh);
}
Sphere::Sphere(float radius, const Resolution& resolution) :
_radius(radius)
{
setResolution(resolution);
}
void Sphere::setRadius(float value)
{
_radius = value;
}
void Sphere::setResolution(const Resolution& value)
{
_resolution.first = std::max(value.first, size_t(3));
_resolution.second = std::max(value.second, size_t(3));
}
void Sphere::setUSpan(const Span& value)
{
_uSpan = value;
}
void Sphere::setVSpan(const Span& value)
{
_vSpan = value;
}
void Sphere::setTextureSpan(bool value)
{
_textureSpan = value;
}
void Sphere::triangulate(TriangleMesh& mesh) const
{
//! \bug Use only a single vertex at each pole.
for (size_t v = 0; v <= _resolution.second; ++v)
{
const float v1 = static_cast<float>(v) / static_cast<float>(_resolution.second);
const float v2 = Math::lerp(v1, _vSpan.first, _vSpan.second);
for (size_t u = 0; u <= _resolution.first; ++u)
{
const float u1 = static_cast<float>(u) / static_cast<float>(_resolution.first);
const float u2 = Math::lerp(u1, _uSpan.first, _uSpan.second);
const float x = _radius * sinf(v2 * Math::pi) * cosf(u2 * Math::pi2);
const float y = _radius * cosf(v2 * Math::pi);
const float z = _radius * sinf(v2 * Math::pi) * sinf(u2 * Math::pi2);
mesh.v.push_back(glm::vec3(x, y, z));
if (_textureSpan)
{
mesh.t.push_back(glm::vec3(u1, 1.F - v1, 0.F));
}
else
{
mesh.t.push_back(glm::vec3(u2, 1.F - v2, 0.F));
}
}
}
TriangleMesh::Triangle triangle;
for (size_t v = 0; v < _resolution.second; ++v)
{
for (size_t u = 0; u < _resolution.first; ++u)
{
const size_t i = u + v * (_resolution.first + 1);
const size_t j = u + (v + 1) * (_resolution.first + 1);
triangle.v0.v = triangle.v0.t = j + 1 + offset;
triangle.v1.v = triangle.v1.t = j + offset;
triangle.v2.v = triangle.v2.t = i + offset;
mesh.triangles.push_back(triangle);
triangle.v0.v = triangle.v0.t = i + offset;
triangle.v1.v = triangle.v1.t = i + 1 + offset;
triangle.v2.v = triangle.v2.t = j + 1 + offset;
mesh.triangles.push_back(triangle);
}
}
TriangleMesh::calcNormals(mesh);
}
Cylinder::Cylinder(float radius, float length, size_t resolution) :
_radius(radius),
_length(length)
{
setResolution(resolution);
}
void Cylinder::setRadius(float value)
{
_radius = value;
}
void Cylinder::setLength(float value)
{
_length = value;
}
void Cylinder::setResolution(size_t value)
{
_resolution = std::max(value, size_t(3));
}
void Cylinder::setSpan(const Span& value)
{
_span = value;
}
void Cylinder::setCapped(bool value)
{
_capped = value;
}
void Cylinder::setTextureSpan(bool value)
{
_textureSpan = value;
}
void Cylinder::triangulate(TriangleMesh& mesh) const
{
const float l = _length / 2.F;
for (size_t u = 0; u <= _resolution; ++u)
{
const float u1 = static_cast<float>(u) / static_cast<float>(_resolution);
const float u2 = Math::lerp(u1, _span.first, _span.second);
const float c = cosf(u2 * Math::pi2);
const float s = sinf(u2 * Math::pi2);
glm::vec3 v(c * _radius, -l, s * _radius);
mesh.v.push_back(v);
if (_textureSpan)
{
mesh.t.push_back(glm::vec3(u1, 0.F, 0.F));
}
else
{
mesh.t.push_back(glm::vec3(u2, 0.F, 0.F));
}
v.y = l;
mesh.v.push_back(v);
if (_textureSpan)
{
mesh.t.push_back(glm::vec3(u1, 1.F, 0.F));
}
else
{
mesh.t.push_back(glm::vec3(u2, 1.F, 0.F));
}
}
TriangleMesh::Triangle triangle;
for (size_t i = 0; i < _resolution; ++i)
{
triangle.v0.v = triangle.v0.t = i * 2 + 0 + offset;
triangle.v1.v = triangle.v1.t = i * 2 + 1 + offset;
triangle.v2.v = triangle.v2.t = i * 2 + 3 + offset;
mesh.triangles.push_back(triangle);
triangle.v0.v = triangle.v0.t = i * 2 + 3 + offset;
triangle.v1.v = triangle.v1.t = i * 2 + 2 + offset;
triangle.v2.v = triangle.v2.t = i * 2 + 0 + offset;
mesh.triangles.push_back(triangle);
}
if (_capped)
{
for (size_t i = 1; i < _resolution - 1; ++i)
{
triangle.v0.v = triangle.v0.t = 0 + offset;
triangle.v1.v = triangle.v1.t = i * 2 + 0 + offset;
triangle.v2.v = triangle.v2.t = i * 2 + 2 + offset;
mesh.triangles.push_back(triangle);
triangle.v0.v = triangle.v0.t = 1 + offset;
triangle.v1.v = triangle.v1.t = i * 2 + 3 + offset;
triangle.v2.v = triangle.v2.t = i * 2 + 1 + offset;
mesh.triangles.push_back(triangle);
}
}
TriangleMesh::calcNormals(mesh);
}
} // namespace Geom
} // namespace djv
| 5,648 |
450 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef _KEY_VALUE_PROPERTIES_PROCESSOR_H
#define _KEY_VALUE_PROPERTIES_PROCESSOR_H
#include "resourcemanager/envswitch.h"
#include "resourcemanager/utils/linkedlist.h"
#include "resourcemanager/utils/simplestring.h"
struct KVPropertyData {
SimpString Key;
SimpString Val;
};
typedef struct KVPropertyData KVPropertyData;
typedef struct KVPropertyData *KVProperty;
int processXMLPropertyFile( const char *filename,
MCTYPE context,
List **properties);
int findPropertyValue(List *properties, const char *key, SimpStringPtr *value);
void cleanPropertyList(MCTYPE context, List **properties);
int PropertyKeySubstring( SimpStringPtr key,
int index,
char **start,
int *length);
KVProperty createPropertyEmpty(MCTYPE context);
KVProperty createPropertyOID(MCTYPE context,
const char *tag1,
const char *tag2,
int *index,
Oid value);
KVProperty createPropertyName(MCTYPE context,
const char *tag1,
const char *tag2,
int *index,
Name value);
KVProperty createPropertyInt8(MCTYPE context,
const char *tag1,
const char *tag2,
int *index,
int8_t value);
KVProperty createPropertyInt32(MCTYPE context,
const char *tag1,
const char *tag2,
int *index,
int32_t value);
KVProperty createPropertyBool(MCTYPE context,
const char *tag1,
const char *tag2,
int *index,
Oid value);
KVProperty createPropertyString(MCTYPE context,
const char *tag1,
const char *tag2,
int *index,
const char *value);
KVProperty createPropertyFloat(MCTYPE context,
const char *tag1,
const char *tag2,
int *index,
float value);
void buildDottedPropertyNameString(SimpStringPtr string,
const char *tag1,
const char *tag2,
int *index);
#endif /* _KEY_VALUE_PROPERTIES_PROCESSOR_H */
| 1,248 |
471 | <filename>forest-core/src/test/java/com/dtflys/test/model/AmapLocation.java
package com.dtflys.test.model;
import java.util.List;
/**
* Created by Administrator on 2016/6/20.
*/
public class AmapLocation<T> {
private String timestamp;
private Boolean result;
private String message;
private String version;
private String desc;
private String pos;
private String districtadcode;
private String district;
private String adcode;
private String areacode;
private String city;
private String cityadcode;
private String tel;
private Integer code;
private String province;
private String provinceadcode;
private String country;
private List<T> cross_list;
private List road_list;
private List poi_list;
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public Boolean getResult() {
return result;
}
public void setResult(Boolean result) {
this.result = result;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public String getDistrictadcode() {
return districtadcode;
}
public void setDistrictadcode(String districtadcode) {
this.districtadcode = districtadcode;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getTel() {
return tel;
}
public String getAdcode() {
return adcode;
}
public void setAdcode(String adcode) {
this.adcode = adcode;
}
public String getAreacode() {
return areacode;
}
public void setAreacode(String areacode) {
this.areacode = areacode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getCityadcode() {
return cityadcode;
}
public void setCityadcode(String cityadcode) {
this.cityadcode = cityadcode;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getProvinceadcode() {
return provinceadcode;
}
public void setProvinceadcode(String provinceadcode) {
this.provinceadcode = provinceadcode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public List<T> getCross_list() {
return cross_list;
}
public void setCross_list(List<T> cross_list) {
this.cross_list = cross_list;
}
public List getRoad_list() {
return road_list;
}
public void setRoad_list(List road_list) {
this.road_list = road_list;
}
public List getPoi_list() {
return poi_list;
}
public void setPoi_list(List poi_list) {
this.poi_list = poi_list;
}
public static class AmapCross {
private String distance;
private String level;
private String latitude;
private String crossid;
private String name;
private String width;
private String weight;
private String direction;
private String longitude;
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getCrossid() {
return crossid;
}
public void setCrossid(String crossid) {
this.crossid = crossid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
}
| 2,415 |
799 | <filename>ext/iodine/iodine_store.h
#ifndef H_IODINE_STORAGE_H
#define H_IODINE_STORAGE_H
#include "ruby.h"
extern struct IodineStorage_s {
/** Adds an object to the storage (or increases it's reference count). */
VALUE (*add)(VALUE);
/** Removes an object from the storage (or decreases it's reference count). */
VALUE (*remove)(VALUE);
/** Should be called after forking to reset locks */
void (*after_fork)(void);
/** Prints debugging information to the console. */
void (*print)(void);
} IodineStore;
/** Initializes the storage unit for first use. */
void iodine_storage_init(void);
#endif
| 198 |
2,260 | // Autogenerated by gameplay-luagen
#include "Base.h"
#include "ScriptController.h"
#include "lua_Script.h"
#include "Base.h"
#include "Game.h"
#include "Ref.h"
#include "Script.h"
#include "ScriptController.h"
#include "Ref.h"
namespace gameplay
{
extern void luaGlobal_Register_Conversion_Function(const char* className, void*(*func)(void*, const char*));
static Script* getInstance(lua_State* state)
{
void* userdata = luaL_checkudata(state, 1, "Script");
luaL_argcheck(state, userdata != NULL, 1, "'Script' expected.");
return (Script*)((gameplay::ScriptUtil::LuaObject*)userdata)->instance;
}
static int lua_Script__gc(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
void* userdata = luaL_checkudata(state, 1, "Script");
luaL_argcheck(state, userdata != NULL, 1, "'Script' expected.");
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)userdata;
if (object->owns)
{
Script* instance = (Script*)object->instance;
SAFE_RELEASE(instance);
}
return 0;
}
lua_pushstring(state, "lua_Script__gc - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Script_addRef(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Script* instance = getInstance(state);
instance->addRef();
return 0;
}
lua_pushstring(state, "lua_Script_addRef - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Script_functionExists(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
Script* instance = getInstance(state);
bool result = instance->functionExists(param1);
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_Script_functionExists - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Script_getPath(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Script* instance = getInstance(state);
const char* result = instance->getPath();
// Push the return value onto the stack.
lua_pushstring(state, result);
return 1;
}
lua_pushstring(state, "lua_Script_getPath - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Script_getRefCount(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Script* instance = getInstance(state);
unsigned int result = instance->getRefCount();
// Push the return value onto the stack.
lua_pushunsigned(state, result);
return 1;
}
lua_pushstring(state, "lua_Script_getRefCount - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Script_getScope(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Script* instance = getInstance(state);
Script::Scope result = instance->getScope();
// Push the return value onto the stack.
lua_pushnumber(state, (int)result);
return 1;
}
lua_pushstring(state, "lua_Script_getScope - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Script_release(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Script* instance = getInstance(state);
instance->release();
return 0;
}
lua_pushstring(state, "lua_Script_release - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
static int lua_Script_reload(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
Script* instance = getInstance(state);
bool result = instance->reload();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_Script_reload - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
// Provides support for conversion to all known relative types of Script
static void* __convertTo(void* ptr, const char* typeName)
{
Script* ptrObject = reinterpret_cast<Script*>(ptr);
if (strcmp(typeName, "Ref") == 0)
{
return reinterpret_cast<void*>(static_cast<Ref*>(ptrObject));
}
// No conversion available for 'typeName'
return NULL;
}
static int lua_Script_to(lua_State* state)
{
// There should be only a single parameter (this instance)
if (lua_gettop(state) != 2 || lua_type(state, 1) != LUA_TUSERDATA || lua_type(state, 2) != LUA_TSTRING)
{
lua_pushstring(state, "lua_Script_to - Invalid number of parameters (expected 2).");
lua_error(state);
return 0;
}
Script* instance = getInstance(state);
const char* typeName = gameplay::ScriptUtil::getString(2, false);
void* result = __convertTo((void*)instance, typeName);
if (result)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = (void*)result;
object->owns = false;
luaL_getmetatable(state, typeName);
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
void luaRegister_Script()
{
const luaL_Reg lua_members[] =
{
{"addRef", lua_Script_addRef},
{"functionExists", lua_Script_functionExists},
{"getPath", lua_Script_getPath},
{"getRefCount", lua_Script_getRefCount},
{"getScope", lua_Script_getScope},
{"release", lua_Script_release},
{"reload", lua_Script_reload},
{"to", lua_Script_to},
{NULL, NULL}
};
const luaL_Reg* lua_statics = NULL;
std::vector<std::string> scopePath;
gameplay::ScriptUtil::registerClass("Script", lua_members, NULL, lua_Script__gc, lua_statics, scopePath);
luaGlobal_Register_Conversion_Function("Script", __convertTo);
}
}
| 4,921 |
348 | <reponame>chamberone/Leaflet.PixiOverlay<filename>docs/data/leg-t2/063/06305431.json
{"nom":"Thiolières","circ":"5ème circonscription","dpt":"Puy-de-Dôme","inscrits":136,"abs":59,"votants":77,"blancs":1,"nuls":2,"exp":74,"res":[{"nuance":"COM","nom":"M. <NAME>","voix":52},{"nuance":"REM","nom":"<NAME>","voix":22}]} | 138 |
1,521 | /**
* Copyright 2020 Alibaba Group Holding Limited.
*
* <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.maxgraph.tests.coordinator;
import com.alibaba.maxgraph.proto.groot.GetTailOffsetsRequest;
import com.alibaba.maxgraph.proto.groot.GetTailOffsetsResponse;
import com.alibaba.graphscope.groot.coordinator.IngestProgressService;
import com.alibaba.graphscope.groot.coordinator.SnapshotManager;
import io.grpc.stub.StreamObserver;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
public class IngestProgressServiceTest {
@Test
void testIngestProgressService() {
SnapshotManager snapshotManager = mock(SnapshotManager.class);
when(snapshotManager.getTailOffsets(Arrays.asList(1))).thenReturn(Arrays.asList(10L));
IngestProgressService ingestProgressService = new IngestProgressService(snapshotManager);
GetTailOffsetsRequest request = GetTailOffsetsRequest.newBuilder().addQueueId(1).build();
ingestProgressService.getTailOffsets(
request,
new StreamObserver<GetTailOffsetsResponse>() {
@Override
public void onNext(GetTailOffsetsResponse response) {
List<Long> offsetsList = response.getOffsetsList();
assertEquals(offsetsList.size(), 1);
assertEquals(offsetsList.get(0), 10L);
}
@Override
public void onError(Throwable t) {
throw new RuntimeException(t);
}
@Override
public void onCompleted() {}
});
verify(snapshotManager).getTailOffsets(Arrays.asList(1));
}
}
| 953 |
377 | //------------------------------------------------------------------------------
// typeregistry.cc
// (C) 2020 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "foundation/stdneb.h"
#include "typeregistry.h"
namespace MemDb
{
TypeRegistry* TypeRegistry::Singleton = 0;
//------------------------------------------------------------------------------
/**
The registry's constructor is called by the Instance() method, and
nobody else.
*/
TypeRegistry*
TypeRegistry::Instance()
{
if (0 == Singleton)
{
Singleton = n_new(TypeRegistry);
n_assert(0 != Singleton);
}
return Singleton;
}
//------------------------------------------------------------------------------
/**
This static method is used to destroy the registry object and should be
called right before the main function exits. It will make sure that
no accidential memory leaks are reported by the debug heap.
*/
void
TypeRegistry::Destroy()
{
if (0 != Singleton)
{
n_delete(Singleton);
Singleton = 0;
}
}
//------------------------------------------------------------------------------
/**
*/
TypeRegistry::TypeRegistry()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
TypeRegistry::~TypeRegistry()
{
// empty
}
} // namespace MemDb
| 374 |
2,177 | <filename>test/org/nutz/dao/test/mapping/Issue1206Test.java
package org.nutz.dao.test.mapping;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.nutz.dao.test.DaoCase;
import org.nutz.dao.test.meta.issue1206.Issue1206Master;
import org.nutz.dao.test.meta.issue1206.Issue1206Pet;
import org.nutz.lang.random.R;
public class Issue1206Test extends DaoCase {
@Test
public void test_issue_1206() {
dao.drop(Issue1206Master.class);
dao.drop(Issue1206Pet.class);
dao.create(Issue1206Master.class, false);
dao.create(Issue1206Pet.class, false);
Issue1206Master master = new Issue1206Master();
master.setName("wendal");
List<Issue1206Pet> pets = new ArrayList<Issue1206Pet>();
for (int i = 0; i < 10; i++) {
Issue1206Pet pet = new Issue1206Pet();
pet.setName(R.UU32());
pets.add(pet);
}
master.setPets(pets);
dao.insertWith(master, null);
assertTrue(master.getId() >= 0);
master = dao.fetch(Issue1206Master.class);
assertNotNull(master);
dao.fetchLinks(master, null);
assertNotNull(master.getPets());
assertEquals(10, master.getPets().size());
}
}
| 598 |
5,079 | <gh_stars>1000+
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import unittest
from nose.plugins.skip import SkipTest
from nose.tools import assert_equal, assert_false, assert_true, assert_raises
from desktop.conf import RAZ
from desktop.lib.raz.clients import S3RazClient, AdlsRazClient
if sys.version_info[0] > 2:
from unittest.mock import patch, Mock
else:
from mock import patch, Mock
class S3RazClientLiveTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if not RAZ.IS_ENABLED.get():
raise SkipTest
def test_check_access_s3_list_buckets(self):
url = S3RazClient().get_url()
assert_true('AWSAccessKeyId=' in url)
assert_true('Signature=' in url)
assert_true('Expires=' in url)
def test_check_acccess_s3_list_file(self):
# e.g. 'https://gethue-test.s3.amazonaws.com/data/query-hive-weblogs.csv?AWSAccessKeyId=<KEY>&'
# 'Signature=3lhK%2BwtQ9Q2u5VDIqb4MEpoY3X4%3D&Expires=1617207304'
url = S3RazClient().get_url(bucket='gethue-test', path='/data/query-hive-weblogs.csv')
assert_true('data/query-hive-weblogs.csv' in url)
assert_true('AWSAccessKeyId=' in url)
assert_true('Signature=' in url)
assert_true('Expires=' in url)
url = S3RazClient().get_url(bucket='gethue-test', path='/data/query-hive-weblogs.csv', perm='read', action='write')
assert_true('data/query-hive-weblogs.csv' in url)
assert_true('AWSAccessKeyId=' in url)
assert_true('Signature=' in url)
assert_true('Expires=' in url)
def test_check_acccess_s3_list_file_no_access(self): pass
class AdlsRazClientTest(unittest.TestCase):
def setUp(self):
self.username = 'csso_hueuser'
def test_check_rename_operation(self):
with patch('desktop.lib.raz.raz_client.RazToken.get_delegation_token') as raz_token:
with patch('desktop.lib.raz.raz_client.requests.post') as requests_post:
with patch('desktop.lib.raz.raz_client.uuid.uuid4') as uuid:
with patch('desktop.lib.raz.raz_client.RazClient.check_access') as check_access:
reset = RAZ.API_URL.set_for_testing('https://raz_url:8000')
check_access.return_value = {'token': 'some_random_sas_token'}
try:
sas_token = AdlsRazClient(
username=self.username
).get_url(
action='PUT',
path='https://gethuestorage.dfs.core.windows.net/data/user/csso_hueuser/rename_destination_dir',
headers={'x-ms-version': '2019-12-12', 'x-ms-rename-source': '/data/user/csso_hueuser/rename_source_dir'})
check_access.assert_called_with(
headers={
'x-ms-version': '2019-12-12',
'x-ms-rename-source': '/data/user/csso_hueuser/rename_source_dir?some_random_sas_token'
},
method='PUT',
url='https://gethuestorage.dfs.core.windows.net/data/user/csso_hueuser/rename_destination_dir'
)
finally:
reset()
| 1,556 |
529 | <gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.flink.ml.tensorflow.util;
import com.alibaba.flink.ml.cluster.node.MLContext;
import com.alibaba.flink.ml.util.ContextService;
import com.alibaba.flink.ml.util.IpHostUtil;
import com.alibaba.flink.ml.util.ShellExec;
import com.google.common.base.Joiner;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.FutureTask;
public class JavaInferenceUtil {
private static final Logger LOG = LoggerFactory.getLogger(JavaInferenceUtil.class);
private JavaInferenceUtil() {
}
/**
* start a rpc server: support query machine learning context.
* @param mlContext machine learning node context.
* @return rpc server.
* @throws Exception
*/
public static Server startTFContextService(MLContext mlContext) throws Exception {
ContextService service = new ContextService();
Server server = ServerBuilder.forPort(0).addService(service).build();
server.start();
mlContext.setNodeServerIP(IpHostUtil.getIpAddress());
mlContext.setNodeServerPort(server.getPort());
service.setMlContext(mlContext);
return server;
}
public static FutureTask<Void> startInferenceProcessWatcher(Process process, MLContext mlContext) {
Thread inLogger = new Thread(new ShellExec.ProcessLogger(process.getInputStream(),
new ShellExec.StdOutConsumer()));
Thread errLogger = new Thread(new ShellExec.ProcessLogger(process.getErrorStream(),
new ShellExec.StdOutConsumer()));
inLogger.setName(mlContext.getIdentity() + "-JavaInferenceProcess-in-logger");
inLogger.setDaemon(true);
errLogger.setName(mlContext.getIdentity() + "-JavaInferenceProcess-err-logger");
errLogger.setDaemon(true);
inLogger.start();
errLogger.start();
FutureTask<Void> res = new FutureTask<>(() -> {
try {
int r = process.waitFor();
inLogger.join();
errLogger.join();
if (r != 0) {
throw new RuntimeException("Java inference process exited with " + r);
}
LOG.info("{} Java inference process finished successfully", mlContext.getIdentity());
} catch (InterruptedException e) {
LOG.info("{} Java inference process watcher interrupted, killing the process", mlContext.getIdentity());
} finally {
process.destroyForcibly();
}
}, null);
Thread t = new Thread(res);
t.setName(mlContext.getIdentity() + "-JavaInferenceWatcher");
t.setDaemon(true);
t.start();
return res;
}
/**
* start tensorflow inference java process.
* @param mlContext machine learning node context.
* @param inRowType input row TypeInformation.
* @param outRowType output row TypeInformation.
* @return java inference process.
* @throws IOException
*/
public static Process launchInferenceProcess(MLContext mlContext, RowTypeInfo inRowType, RowTypeInfo outRowType)
throws IOException {
List<String> args = new ArrayList<>();
String javaHome = System.getProperty("java.home");
args.add(Joiner.on(File.separator).join(javaHome, "bin", "java"));
// set classpath
List<String> cpElements = new ArrayList<>();
// add sys classpath
cpElements.add(System.getProperty("java.class.path"));
// add user code classpath
if (Thread.currentThread().getContextClassLoader() instanceof URLClassLoader) {
for (URL url : ((URLClassLoader) Thread.currentThread().getContextClassLoader()).getURLs()) {
cpElements.add(url.toString());
}
}
args.add("-cp");
args.add(Joiner.on(File.pathSeparator).join(cpElements));
args.add(JavaInferenceRunner.class.getCanonicalName());
// set TF service IP & port
args.add(String.format("%s:%d", mlContext.getNodeServerIP(), mlContext.getNodeServerPort()));
// serialize RowType
args.add(serializeRowType(mlContext, inRowType).toString());
args.add(serializeRowType(mlContext, outRowType).toString());
LOG.info("Java Inference Cmd: " + Joiner.on(" ").join(args));
ProcessBuilder builder = new ProcessBuilder(args);
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
return builder.start();
}
private static URI serializeRowType(MLContext mlContext, RowTypeInfo rowType) throws IOException {
File file = mlContext.createTempFile("RowType", null);
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file))) {
outputStream.writeObject(rowType);
}
return file.toURI();
}
}
| 1,772 |
1,131 | {
"parent": "create:block/gantry_shaft/block_start",
"textures": {
"2": "create:block/gantry_shaft_powered_flipped"
}
} | 56 |
675 | <reponame>bigplayszn/nCine<filename>benchmarks/gbench_bighashset.cpp
#include "benchmark/benchmark.h"
#include <nctl/HashSet.h>
#define TEST_WITH_NCTL
#include "test_movable.h"
const unsigned int Capacity = 1024;
using SaxHashSet = nctl::HashSet<Movable, nctl::SaxHashFunc<Movable>>;
using JenkinsHashSet = nctl::HashSet<Movable, nctl::JenkinsHashFunc<Movable>>;
using FNV1aHashSet = nctl::HashSet<Movable, nctl::FNV1aHashFunc<Movable>>;
using HashSetTestType = FNV1aHashSet;
static void BM_BigHashSetCopy(benchmark::State &state)
{
state.counters["Capacity"] = Capacity;
HashSetTestType initSet(Capacity);
for (unsigned int i = 0; i < state.range(0); i++)
initSet.insert(nctl::move(Movable(Movable::Construction::INITIALIZED)));
HashSetTestType set(Capacity);
for (auto _ : state)
{
set = initSet;
benchmark::DoNotOptimize(set);
state.PauseTiming();
set.clear();
state.ResumeTiming();
}
}
BENCHMARK(BM_BigHashSetCopy)->Arg(Capacity / 4)->Arg(Capacity / 2)->Arg(Capacity / 4 * 3);
static void BM_BigHashSetMove(benchmark::State &state)
{
state.counters["Capacity"] = Capacity;
HashSetTestType initSet(Capacity);
for (unsigned int i = 0; i < state.range(0); i++)
initSet.insert(nctl::move(Movable(Movable::Construction::INITIALIZED)));
HashSetTestType set(Capacity);
for (auto _ : state)
{
set = nctl::move(initSet);
benchmark::DoNotOptimize(set);
state.PauseTiming();
set.clear();
state.ResumeTiming();
}
}
BENCHMARK(BM_BigHashSetMove)->Arg(Capacity / 4)->Arg(Capacity / 2)->Arg(Capacity / 4 * 3);
static void BM_BigHashSetOperatorInsert(benchmark::State &state)
{
state.counters["Capacity"] = Capacity;
HashSetTestType set(Capacity);
for (auto _ : state)
{
for (unsigned int i = 0; i < state.range(0); i++)
{
Movable movable(Movable::Construction::INITIALIZED);
set.insert(movable);
}
state.PauseTiming();
set.clear();
state.ResumeTiming();
}
}
BENCHMARK(BM_BigHashSetOperatorInsert)->Arg(Capacity / 4)->Arg(Capacity / 2)->Arg(Capacity / 4 * 3);
static void BM_BigHashSetOperatorMoveInsert(benchmark::State &state)
{
state.counters["Capacity"] = Capacity;
HashSetTestType set(Capacity);
for (auto _ : state)
{
for (unsigned int i = 0; i < state.range(0); i++)
{
Movable movable(Movable::Construction::INITIALIZED);
set.insert(nctl::move(movable));
}
state.PauseTiming();
set.clear();
state.ResumeTiming();
}
}
BENCHMARK(BM_BigHashSetOperatorMoveInsert)->Arg(Capacity / 4)->Arg(Capacity / 2)->Arg(Capacity / 4 * 3);
static void BM_BigHashSetInsert(benchmark::State &state)
{
state.counters["Capacity"] = Capacity;
HashSetTestType set(Capacity);
for (auto _ : state)
{
for (unsigned int i = 0; i < state.range(0); i++)
{
Movable movable(Movable::Construction::INITIALIZED);
set.insert(movable);
}
state.PauseTiming();
set.clear();
state.ResumeTiming();
}
}
BENCHMARK(BM_BigHashSetInsert)->Arg(Capacity / 4)->Arg(Capacity / 2)->Arg(Capacity / 4 * 3);
static void BM_BigHashSetMoveInsert(benchmark::State &state)
{
state.counters["Capacity"] = Capacity;
HashSetTestType set(Capacity);
for (auto _ : state)
{
for (unsigned int i = 0; i < state.range(0); i++)
{
Movable movable(Movable::Construction::INITIALIZED);
set.insert(nctl::move(movable));
}
state.PauseTiming();
set.clear();
state.ResumeTiming();
}
}
BENCHMARK(BM_BigHashSetMoveInsert)->Arg(Capacity / 4)->Arg(Capacity / 2)->Arg(Capacity / 4 * 3);
BENCHMARK_MAIN();
| 1,388 |
1,863 | //
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2018 NVIDIA Corporation. All rights reserved.
#ifndef MODULE_CONVERSIONDESTRUCTIBLEASSETPARAMETERS_0P15_0P16H_H
#define MODULE_CONVERSIONDESTRUCTIBLEASSETPARAMETERS_0P15_0P16H_H
#include "NvParamConversionTemplate.h"
#include "DestructibleAssetParameters_0p15.h"
#include "DestructibleAssetParameters_0p16.h"
namespace nvidia {
namespace apex {
namespace legacy {
typedef NvParameterized::ParamConversionTemplate<nvidia::parameterized::DestructibleAssetParameters_0p15,
nvidia::parameterized::DestructibleAssetParameters_0p16,
nvidia::parameterized::DestructibleAssetParameters_0p15::ClassVersion,
nvidia::parameterized::DestructibleAssetParameters_0p16::ClassVersion>
ConversionDestructibleAssetParameters_0p15_0p16Parent;
class ConversionDestructibleAssetParameters_0p15_0p16: public ConversionDestructibleAssetParameters_0p15_0p16Parent
{
public:
static NvParameterized::Conversion* Create(NvParameterized::Traits* t)
{
void* buf = t->alloc(sizeof(ConversionDestructibleAssetParameters_0p15_0p16));
return buf ? PX_PLACEMENT_NEW(buf, ConversionDestructibleAssetParameters_0p15_0p16)(t) : 0;
}
protected:
ConversionDestructibleAssetParameters_0p15_0p16(NvParameterized::Traits* t) : ConversionDestructibleAssetParameters_0p15_0p16Parent(t) {}
const NvParameterized::PrefVer* getPreferredVersions() const
{
static NvParameterized::PrefVer prefVers[] =
{
//TODO:
// Add your preferred versions for included references here.
// Entry format is
// { (const char*)longName, (uint32_t)preferredVersion }
{ 0, 0 } // Terminator (do not remove!)
};
return prefVers;
}
bool convert()
{
// Convert default behavior group's damage spread function parameters
mNewData->defaultBehaviorGroup.damageSpread.minimumRadius = mLegacyData->defaultBehaviorGroup.minimumDamageRadius;
mNewData->defaultBehaviorGroup.damageSpread.radiusMultiplier = mLegacyData->defaultBehaviorGroup.damageRadiusMultiplier;
mNewData->defaultBehaviorGroup.damageSpread.falloffExponent = mLegacyData->defaultBehaviorGroup.damageFalloffExponent;
// Convert user-defined behavior group's damage spread function parameters
const int32_t behaviorGroupCount = mLegacyData->behaviorGroups.arraySizes[0];
PX_ASSERT(mNewData->behaviorGroups.arraySizes[0] == behaviorGroupCount);
for (int32_t i = 0; i < physx::PxMin(behaviorGroupCount, mNewData->behaviorGroups.arraySizes[0]); ++i)
{
mNewData->behaviorGroups.buf[i].damageSpread.minimumRadius = mLegacyData->behaviorGroups.buf[i].minimumDamageRadius;
mNewData->behaviorGroups.buf[i].damageSpread.radiusMultiplier = mLegacyData->behaviorGroups.buf[i].damageRadiusMultiplier;
mNewData->behaviorGroups.buf[i].damageSpread.falloffExponent = mLegacyData->behaviorGroups.buf[i].damageFalloffExponent;
}
return true;
}
};
}
}
} //nvidia::apex::legacy
#endif
| 1,408 |
1,177 | /*
* Copyright (c) 2020 <NAME>, and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <graphene/protocol/base.hpp>
#include <graphene/protocol/asset.hpp>
namespace graphene { namespace protocol {
/**
* @brief Create a new liquidity pool
* @ingroup operations
*/
struct liquidity_pool_create_operation : public base_operation
{
struct fee_parameters_type { uint64_t fee = 50 * GRAPHENE_BLOCKCHAIN_PRECISION; };
asset fee; ///< Operation fee
account_id_type account; ///< The account who creates the liquidity pool
asset_id_type asset_a; ///< Type of the first asset in the pool
asset_id_type asset_b; ///< Type of the second asset in the pool
asset_id_type share_asset; ///< Type of the share asset aka the LP token
uint16_t taker_fee_percent = 0; ///< Taker fee percent
uint16_t withdrawal_fee_percent = 0; ///< Withdrawal fee percent
extensions_type extensions; ///< Unused. Reserved for future use.
account_id_type fee_payer()const { return account; }
void validate()const;
};
/**
* @brief Delete a liquidity pool
* @ingroup operations
*/
struct liquidity_pool_delete_operation : public base_operation
{
struct fee_parameters_type { uint64_t fee = 0; };
asset fee; ///< Operation fee
account_id_type account; ///< The account who owns the liquidity pool
liquidity_pool_id_type pool; ///< ID of the liquidity pool
extensions_type extensions; ///< Unused. Reserved for future use.
account_id_type fee_payer()const { return account; }
void validate()const;
};
/**
* @brief Deposit to a liquidity pool
* @ingroup operations
*/
struct liquidity_pool_deposit_operation : public base_operation
{
struct fee_parameters_type { uint64_t fee = GRAPHENE_BLOCKCHAIN_PRECISION / 10; };
asset fee; ///< Operation fee
account_id_type account; ///< The account who deposits to the liquidity pool
liquidity_pool_id_type pool; ///< ID of the liquidity pool
asset amount_a; ///< The amount of the first asset to deposit
asset amount_b; ///< The amount of the second asset to deposit
extensions_type extensions; ///< Unused. Reserved for future use.
account_id_type fee_payer()const { return account; }
void validate()const;
};
/**
* @brief Withdraw from a liquidity pool
* @ingroup operations
*/
struct liquidity_pool_withdraw_operation : public base_operation
{
struct fee_parameters_type { uint64_t fee = 5 * GRAPHENE_BLOCKCHAIN_PRECISION; };
asset fee; ///< Operation fee
account_id_type account; ///< The account who withdraws from the liquidity pool
liquidity_pool_id_type pool; ///< ID of the liquidity pool
asset share_amount; ///< The amount of the share asset to use
extensions_type extensions; ///< Unused. Reserved for future use.
account_id_type fee_payer()const { return account; }
void validate()const;
};
/**
* @brief Exchange with a liquidity pool
* @ingroup operations
* @note The result of this operation is a @ref generic_exchange_operation_result.
* There are 3 fees in the result, stored in this order:
* * maker market fee
* * taker market fee
* * liquidity pool taker fee
*/
struct liquidity_pool_exchange_operation : public base_operation
{
struct fee_parameters_type { uint64_t fee = 1 * GRAPHENE_BLOCKCHAIN_PRECISION; };
asset fee; ///< Operation fee
account_id_type account; ///< The account who exchanges with the liquidity pool
liquidity_pool_id_type pool; ///< ID of the liquidity pool
asset amount_to_sell; ///< The amount of one asset type to sell
asset min_to_receive; ///< The minimum amount of the other asset type to receive
extensions_type extensions; ///< Unused. Reserved for future use.
account_id_type fee_payer()const { return account; }
void validate()const;
};
} } // graphene::protocol
FC_REFLECT( graphene::protocol::liquidity_pool_create_operation::fee_parameters_type, (fee) )
FC_REFLECT( graphene::protocol::liquidity_pool_delete_operation::fee_parameters_type, (fee) )
FC_REFLECT( graphene::protocol::liquidity_pool_deposit_operation::fee_parameters_type, (fee) )
FC_REFLECT( graphene::protocol::liquidity_pool_withdraw_operation::fee_parameters_type, (fee) )
FC_REFLECT( graphene::protocol::liquidity_pool_exchange_operation::fee_parameters_type, (fee) )
FC_REFLECT( graphene::protocol::liquidity_pool_create_operation,
(fee)(account)(asset_a)(asset_b)(share_asset)
(taker_fee_percent)(withdrawal_fee_percent)(extensions) )
FC_REFLECT( graphene::protocol::liquidity_pool_delete_operation,
(fee)(account)(pool)(extensions) )
FC_REFLECT( graphene::protocol::liquidity_pool_deposit_operation,
(fee)(account)(pool)(amount_a)(amount_b)(extensions) )
FC_REFLECT( graphene::protocol::liquidity_pool_withdraw_operation,
(fee)(account)(pool)(share_amount)(extensions) )
FC_REFLECT( graphene::protocol::liquidity_pool_exchange_operation,
(fee)(account)(pool)(amount_to_sell)(min_to_receive)(extensions) )
GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::liquidity_pool_create_operation::fee_parameters_type )
GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::liquidity_pool_delete_operation::fee_parameters_type )
GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::liquidity_pool_deposit_operation::fee_parameters_type )
GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::liquidity_pool_withdraw_operation::fee_parameters_type )
GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::liquidity_pool_exchange_operation::fee_parameters_type )
GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::liquidity_pool_create_operation )
GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::liquidity_pool_delete_operation )
GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::liquidity_pool_deposit_operation )
GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::liquidity_pool_withdraw_operation )
GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::protocol::liquidity_pool_exchange_operation )
| 3,078 |
443 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.autofill.service.data.source.local;
import android.content.SharedPreferences;
import android.service.autofill.Dataset;
import com.example.android.autofill.service.data.DataCallback;
import com.example.android.autofill.service.data.source.AutofillDataSource;
import com.example.android.autofill.service.data.source.local.dao.AutofillDao;
import com.example.android.autofill.service.model.AutofillDataset;
import com.example.android.autofill.service.model.AutofillHint;
import com.example.android.autofill.service.model.DatasetWithFilledAutofillFields;
import com.example.android.autofill.service.model.FieldType;
import com.example.android.autofill.service.model.FieldTypeWithHeuristics;
import com.example.android.autofill.service.model.FilledAutofillField;
import com.example.android.autofill.service.model.ResourceIdHeuristic;
import com.example.android.autofill.service.util.AppExecutors;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import static com.example.android.autofill.service.util.Util.logw;
public class LocalAutofillDataSource implements AutofillDataSource {
public static final String SHARED_PREF_KEY = "com.example.android.autofill"
+ ".service.datasource.LocalAutofillDataSource";
private static final String DATASET_NUMBER_KEY = "datasetNumber";
private static final Object sLock = new Object();
private static LocalAutofillDataSource sInstance;
private final AutofillDao mAutofillDao;
private final SharedPreferences mSharedPreferences;
private final AppExecutors mAppExecutors;
private LocalAutofillDataSource(SharedPreferences sharedPreferences, AutofillDao autofillDao,
AppExecutors appExecutors) {
mSharedPreferences = sharedPreferences;
mAutofillDao = autofillDao;
mAppExecutors = appExecutors;
}
public static LocalAutofillDataSource getInstance(SharedPreferences sharedPreferences,
AutofillDao autofillDao, AppExecutors appExecutors) {
synchronized (sLock) {
if (sInstance == null) {
sInstance = new LocalAutofillDataSource(sharedPreferences, autofillDao,
appExecutors);
}
return sInstance;
}
}
public static void clearInstance() {
synchronized (sLock) {
sInstance = null;
}
}
@Override
public void getAutofillDatasets(List<String> allAutofillHints,
DataCallback<List<DatasetWithFilledAutofillFields>> datasetsCallback) {
mAppExecutors.diskIO().execute(() -> {
final List<String> typeNames = getFieldTypesForAutofillHints(allAutofillHints)
.stream()
.map(FieldTypeWithHeuristics::getFieldType)
.map(FieldType::getTypeName)
.collect(Collectors.toList());
List<DatasetWithFilledAutofillFields> datasetsWithFilledAutofillFields =
mAutofillDao.getDatasets(typeNames);
mAppExecutors.mainThread().execute(() ->
datasetsCallback.onLoaded(datasetsWithFilledAutofillFields)
);
});
}
@Override
public void getAllAutofillDatasets(
DataCallback<List<DatasetWithFilledAutofillFields>> datasetsCallback) {
mAppExecutors.diskIO().execute(() -> {
List<DatasetWithFilledAutofillFields> datasetsWithFilledAutofillFields =
mAutofillDao.getAllDatasets();
mAppExecutors.mainThread().execute(() ->
datasetsCallback.onLoaded(datasetsWithFilledAutofillFields)
);
});
}
@Override
public void getAutofillDataset(List<String> allAutofillHints, String datasetName,
DataCallback<DatasetWithFilledAutofillFields> datasetsCallback) {
mAppExecutors.diskIO().execute(() -> {
// Room does not support TypeConverters for collections.
List<DatasetWithFilledAutofillFields> autofillDatasetFields =
mAutofillDao.getDatasetsWithName(allAutofillHints, datasetName);
if (autofillDatasetFields != null && !autofillDatasetFields.isEmpty()) {
if (autofillDatasetFields.size() > 1) {
logw("More than 1 dataset with name %s", datasetName);
}
DatasetWithFilledAutofillFields dataset = autofillDatasetFields.get(0);
mAppExecutors.mainThread().execute(() ->
datasetsCallback.onLoaded(dataset)
);
} else {
mAppExecutors.mainThread().execute(() ->
datasetsCallback.onDataNotAvailable("No data found.")
);
}
});
}
@Override
public void saveAutofillDatasets(List<DatasetWithFilledAutofillFields>
datasetsWithFilledAutofillFields) {
mAppExecutors.diskIO().execute(() -> {
for (DatasetWithFilledAutofillFields datasetWithFilledAutofillFields :
datasetsWithFilledAutofillFields) {
List<FilledAutofillField> filledAutofillFields =
datasetWithFilledAutofillFields.filledAutofillFields;
AutofillDataset autofillDataset = datasetWithFilledAutofillFields.autofillDataset;
mAutofillDao.insertAutofillDataset(autofillDataset);
mAutofillDao.insertFilledAutofillFields(filledAutofillFields);
}
});
incrementDatasetNumber();
}
@Override
public void saveResourceIdHeuristic(ResourceIdHeuristic resourceIdHeuristic) {
mAppExecutors.diskIO().execute(() -> {
mAutofillDao.insertResourceIdHeuristic(resourceIdHeuristic);
});
}
@Override
public void getFieldTypes(DataCallback<List<FieldTypeWithHeuristics>> fieldTypesCallback) {
mAppExecutors.diskIO().execute(() -> {
List<FieldTypeWithHeuristics> fieldTypeWithHints = mAutofillDao.getFieldTypesWithHints();
mAppExecutors.mainThread().execute(() -> {
if (fieldTypeWithHints != null) {
fieldTypesCallback.onLoaded(fieldTypeWithHints);
} else {
fieldTypesCallback.onDataNotAvailable("Field Types not found.");
}
});
});
}
@Override
public void getFieldTypeByAutofillHints(
DataCallback<HashMap<String, FieldTypeWithHeuristics>> fieldTypeMapCallback) {
mAppExecutors.diskIO().execute(() -> {
HashMap<String, FieldTypeWithHeuristics> hintMap = getFieldTypeByAutofillHints();
mAppExecutors.mainThread().execute(() -> {
if (hintMap != null) {
fieldTypeMapCallback.onLoaded(hintMap);
} else {
fieldTypeMapCallback.onDataNotAvailable("FieldTypes not found");
}
});
});
}
@Override
public void getFilledAutofillField(String datasetId, String fieldTypeName, DataCallback<FilledAutofillField> fieldCallback) {
mAppExecutors.diskIO().execute(() -> {
FilledAutofillField filledAutofillField = mAutofillDao.getFilledAutofillField(datasetId, fieldTypeName);
mAppExecutors.mainThread().execute(() -> {
fieldCallback.onLoaded(filledAutofillField);
});
});
}
@Override
public void getFieldType(String fieldTypeName, DataCallback<FieldType> fieldTypeCallback) {
mAppExecutors.diskIO().execute(() -> {
FieldType fieldType = mAutofillDao.getFieldType(fieldTypeName);
mAppExecutors.mainThread().execute(() -> {
fieldTypeCallback.onLoaded(fieldType);
});
});
}
public void getAutofillDatasetWithId(String datasetId,
DataCallback<DatasetWithFilledAutofillFields> callback) {
mAppExecutors.diskIO().execute(() -> {
DatasetWithFilledAutofillFields dataset =
mAutofillDao.getAutofillDatasetWithId(datasetId);
mAppExecutors.mainThread().execute(() -> {
callback.onLoaded(dataset);
});
});
}
private HashMap<String, FieldTypeWithHeuristics> getFieldTypeByAutofillHints() {
HashMap<String, FieldTypeWithHeuristics> hintMap = new HashMap<>();
List<FieldTypeWithHeuristics> fieldTypeWithHints =
mAutofillDao.getFieldTypesWithHints();
if (fieldTypeWithHints != null) {
for (FieldTypeWithHeuristics fieldType : fieldTypeWithHints) {
for (AutofillHint hint : fieldType.autofillHints) {
hintMap.put(hint.mAutofillHint, fieldType);
}
}
return hintMap;
} else {
return null;
}
}
private List<FieldTypeWithHeuristics> getFieldTypesForAutofillHints(List<String> autofillHints) {
return mAutofillDao.getFieldTypesForAutofillHints(autofillHints);
}
@Override
public void clear() {
mAppExecutors.diskIO().execute(() -> {
mAutofillDao.clearAll();
mSharedPreferences.edit().putInt(DATASET_NUMBER_KEY, 0).apply();
});
}
/**
* For simplicity, {@link Dataset}s will be named in the form {@code dataset-X.P} where
* {@code X} means this was the Xth group of datasets saved, and {@code P} refers to the dataset
* partition number. This method returns the appropriate {@code X}.
*/
public int getDatasetNumber() {
return mSharedPreferences.getInt(DATASET_NUMBER_KEY, 0);
}
/**
* Every time a dataset is saved, this should be called to increment the dataset number.
* (only important for this service's dataset naming scheme).
*/
private void incrementDatasetNumber() {
mSharedPreferences.edit().putInt(DATASET_NUMBER_KEY, getDatasetNumber() + 1).apply();
}
}
| 4,642 |
2,649 | <gh_stars>1000+
"""
ESPNet-C for image segmentation, implemented in PyTorch.
Original paper: 'ESPNet: Efficient Spatial Pyramid of Dilated Convolutions for Semantic Segmentation,'
https://arxiv.org/abs/1803.06815.
"""
__all__ = ['ESPCNet', 'espcnet_cityscapes', 'ESPBlock']
import os
import torch
import torch.nn as nn
from .common import NormActivation, conv1x1, conv3x3, conv3x3_block, DualPathSequential, InterpolationBlock
class HierarchicalConcurrent(nn.Sequential):
"""
A container for hierarchical concatenation of modules on the base of the sequential container.
Parameters:
----------
exclude_first : bool, default False
Whether to exclude the first branch in the intermediate sum.
axis : int, default 1
The axis on which to concatenate the outputs.
"""
def __init__(self,
exclude_first=False,
axis=1):
super(HierarchicalConcurrent, self).__init__()
self.exclude_first = exclude_first
self.axis = axis
def forward(self, x):
out = []
y_prev = None
for i, module in enumerate(self._modules.values()):
y = module(x)
if y_prev is not None:
y += y_prev
out.append(y)
if (not self.exclude_first) or (i > 0):
y_prev = y
out = torch.cat(tuple(out), dim=self.axis)
return out
class ESPBlock(nn.Module):
"""
ESPNet block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
downsample : bool
Whether to downsample image.
residual : bool
Whether to use residual connection.
bn_eps : float
Small float added to variance in Batch norm.
"""
def __init__(self,
in_channels,
out_channels,
downsample,
residual,
bn_eps):
super(ESPBlock, self).__init__()
self.residual = residual
dilations = [1, 2, 4, 8, 16]
num_branches = len(dilations)
mid_channels = out_channels // num_branches
extra_mid_channels = out_channels - (num_branches - 1) * mid_channels
if downsample:
self.reduce_conv = conv3x3(
in_channels=in_channels,
out_channels=mid_channels,
stride=2)
else:
self.reduce_conv = conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.branches = HierarchicalConcurrent(exclude_first=True)
for i in range(num_branches):
out_channels_i = extra_mid_channels if i == 0 else mid_channels
self.branches.add_module("branch{}".format(i + 1), conv3x3(
in_channels=mid_channels,
out_channels=out_channels_i,
padding=dilations[i],
dilation=dilations[i]))
self.norm_activ = NormActivation(
in_channels=out_channels,
bn_eps=bn_eps,
activation=(lambda: nn.PReLU(out_channels)))
def forward(self, x):
y = self.reduce_conv(x)
y = self.branches(y)
if self.residual:
y = y + x
y = self.norm_activ(y)
return y
class ESPUnit(nn.Module):
"""
ESPNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
layers : int
Number of layers.
bn_eps : float
Small float added to variance in Batch norm.
"""
def __init__(self,
in_channels,
out_channels,
layers,
bn_eps):
super(ESPUnit, self).__init__()
mid_channels = out_channels // 2
self.down = ESPBlock(
in_channels=in_channels,
out_channels=mid_channels,
downsample=True,
residual=False,
bn_eps=bn_eps)
self.blocks = nn.Sequential()
for i in range(layers - 1):
self.blocks.add_module("block{}".format(i + 1), ESPBlock(
in_channels=mid_channels,
out_channels=mid_channels,
downsample=False,
residual=True,
bn_eps=bn_eps))
def forward(self, x):
x = self.down(x)
y = self.blocks(x)
x = torch.cat((y, x), dim=1) # NB: This differs from the original implementation.
return x
class ESPStage(nn.Module):
"""
ESPNet stage.
Parameters:
----------
x_channels : int
Number of input/output channels for x.
y_in_channels : int
Number of input channels for y.
y_out_channels : int
Number of output channels for y.
layers : int
Number of layers in the unit.
bn_eps : float
Small float added to variance in Batch norm.
"""
def __init__(self,
x_channels,
y_in_channels,
y_out_channels,
layers,
bn_eps):
super(ESPStage, self).__init__()
self.use_x = (x_channels > 0)
self.use_unit = (layers > 0)
if self.use_x:
self.x_down = nn.AvgPool2d(
kernel_size=3,
stride=2,
padding=1)
if self.use_unit:
self.unit = ESPUnit(
in_channels=y_in_channels,
out_channels=(y_out_channels - x_channels),
layers=layers,
bn_eps=bn_eps)
self.norm_activ = NormActivation(
in_channels=y_out_channels,
bn_eps=bn_eps,
activation=(lambda: nn.PReLU(y_out_channels)))
def forward(self, y, x=None):
if self.use_unit:
y = self.unit(y)
if self.use_x:
x = self.x_down(x)
y = torch.cat((y, x), dim=1)
y = self.norm_activ(y)
return y, x
class ESPCNet(nn.Module):
"""
ESPNet-C model from 'ESPNet: Efficient Spatial Pyramid of Dilated Convolutions for Semantic Segmentation,'
https://arxiv.org/abs/1803.06815.
Parameters:
----------
layers : list of int
Number of layers for each unit.
channels : list of int
Number of output channels for each unit (for y-branch).
init_block_channels : int
Number of output channels for the initial unit.
cut_x : list of int
Whether to concatenate with x-branch for each unit.
bn_eps : float, default 1e-5
Small float added to variance in Batch norm.
aux : bool, default False
Whether to output an auxiliary result.
fixed_size : bool, default False
Whether to expect fixed spatial size of input image.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (1024, 2048)
Spatial size of the expected input image.
num_classes : int, default 19
Number of segmentation classes.
"""
def __init__(self,
layers,
channels,
init_block_channels,
cut_x,
bn_eps=1e-5,
aux=False,
fixed_size=False,
in_channels=3,
in_size=(1024, 2048),
num_classes=19):
super(ESPCNet, self).__init__()
assert (aux is not None)
assert (fixed_size is not None)
assert ((in_size[0] % 8 == 0) and (in_size[1] % 8 == 0))
self.in_size = in_size
self.num_classes = num_classes
self.fixed_size = fixed_size
self.features = DualPathSequential(
return_two=False,
first_ordinals=1,
last_ordinals=0)
self.features.add_module("init_block", conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
stride=2,
bn_eps=bn_eps,
activation=(lambda: nn.PReLU(init_block_channels))))
y_in_channels = init_block_channels
for i, (layers_i, y_out_channels) in enumerate(zip(layers, channels)):
self.features.add_module("stage{}".format(i + 1), ESPStage(
x_channels=in_channels if cut_x[i] == 1 else 0,
y_in_channels=y_in_channels,
y_out_channels=y_out_channels,
layers=layers_i,
bn_eps=bn_eps))
y_in_channels = y_out_channels
self.head = conv1x1(
in_channels=y_in_channels,
out_channels=num_classes)
self.up = InterpolationBlock(
scale_factor=8,
align_corners=False)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
nn.init.kaiming_uniform_(module.weight)
if module.bias is not None:
nn.init.constant_(module.bias, 0)
def forward(self, x):
in_size = self.in_size if self.fixed_size else x.shape[2:]
y = self.features(x, x)
y = self.head(y)
y = self.up(y, size=in_size)
return y
def get_espcnet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create ESPNet-C model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
init_block_channels = 16
layers = [0, 6, 4]
channels = [19, 131, 256]
cut_x = [1, 1, 0]
bn_eps = 1e-3
net = ESPCNet(
layers=layers,
channels=channels,
init_block_channels=init_block_channels,
cut_x=cut_x,
bn_eps=bn_eps,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def espcnet_cityscapes(num_classes=19, **kwargs):
"""
ESPNet-C model for Cityscapes from 'ESPNet: Efficient Spatial Pyramid of Dilated Convolutions for Semantic
Segmentation,' https://arxiv.org/abs/1803.06815.
Parameters:
----------
num_classes : int, default 19
Number of segmentation classes.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_espcnet(num_classes=num_classes, model_name="espcnet_cityscapes", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
pretrained = False
fixed_size = True
in_size = (1024, 2048)
classes = 19
models = [
espcnet_cityscapes,
]
for model in models:
net = model(pretrained=pretrained, in_size=in_size, fixed_size=fixed_size)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != espcnet_cityscapes or weight_count == 210889)
batch = 4
x = torch.randn(batch, 3, in_size[0], in_size[1])
y = net(x)
# y.sum().backward()
assert (tuple(y.size()) == (batch, classes, in_size[0], in_size[1]))
if __name__ == "__main__":
_test()
| 5,918 |
1,103 | /*
* Created by dengshiwei on 2021/08/19.
* Copyright 2015-2021 Sensors Data Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sensorsdata.analytics.android.sdk.advert.utils;
import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import com.sensorsdata.analytics.android.sdk.SALog;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class OaidHelper {
private static final String TAG = "SA.DeviceUtils";
// OAID
private static String mOAID = "";
private static CountDownLatch mCountDownLatch;
private static Class<?> mIdentifyListener;
private static Class<?> mIdSupplier;
private static Class<?> jLibrary;
private static Class<?> mMidSDKHelper;
/**
* 自定义 oaid 证书文件在 assets 中的路径
*/
private static String mOidCertFilePath;
private static final List<String> mBlackOAIDs = new LinkedList<String>() {
{
add("00000000-0000-0000-0000-000000000000");
add("00000000000000000000000000000000");
}
};
private static final List<String> mLoadLibrary = new LinkedList<String>() {
{
add("nllvm1630571663641560568"); // v1.0.27
add("nllvm1623827671"); // v1.0.26
}
};
static {
initSDKLibrary();
}
/**
* 获取 OAID 接口,注意该接口是同步接口,可能会导致线程阻塞,建议在子线程中使用
*
* @param context Context
* @return OAID
*/
public static String getOAID(final Context context) {
String romOAID = getRomOAID(context);
SALog.i(TAG, "romOAID is " + romOAID);
if (mBlackOAIDs.contains(romOAID)) {
romOAID = "";
}
return romOAID;
}
private static String getRomOAID(final Context context) {
try {
mCountDownLatch = new CountDownLatch(1);
initInvokeListener();
if (mMidSDKHelper == null || mIdentifyListener == null || mIdSupplier == null) {
SALog.d(TAG, "OAID 读取类创建失败");
return "";
}
if (TextUtils.isEmpty(mOAID)) {
getOAIDReflect(context, 2);
} else {
return mOAID;
}
try {
mCountDownLatch.await();
} catch (InterruptedException e) {
SALog.printStackTrace(e);
}
SALog.d(TAG, "CountDownLatch await");
return mOAID;
} catch (Throwable ex) {
SALog.d(TAG, ex.getMessage());
}
return "";
}
/**
* 通过反射获取 OAID,结果返回的 ErrorCode 如下:
* 1008611:不支持的设备厂商
* 1008612:不支持的设备
* 1008613:加载配置文件出错
* 1008614:获取接口是异步的,结果会在回调中返回,回调执行的回调可能在工作线程
* 1008615:反射调用出错
*
* @param context Context
* @param retryCount 重试次数
*/
private static void getOAIDReflect(Context context, int retryCount) {
try {
if (retryCount == 0) {
return;
}
final int INIT_ERROR_RESULT_DELAY = 1008614; //获取接口是异步的,结果会在回调中返回,回调执行的回调可能在工作线程
final int INIT_ERROR_RESULT_OK = 1008610; //获取成功
// 初始化证书
initPemCert(context);
// 初始化 Library
if (jLibrary != null) {
Method initEntry = jLibrary.getDeclaredMethod("InitEntry", Context.class);
initEntry.invoke(null, context);
}
IdentifyListenerHandler handler = new IdentifyListenerHandler();
Method initSDK = mMidSDKHelper.getDeclaredMethod("InitSdk", Context.class, boolean.class, mIdentifyListener);
int errCode = (int) initSDK.invoke(null, context, true, Proxy.newProxyInstance(context.getClassLoader(), new Class[]{mIdentifyListener}, handler));
SALog.d(TAG, "MdidSdkHelper ErrorCode : " + errCode);
if (errCode != INIT_ERROR_RESULT_DELAY && errCode != INIT_ERROR_RESULT_OK) {
getOAIDReflect(context, --retryCount);
if (retryCount == 0) {
mCountDownLatch.countDown();
}
}
/*
* 此处是为了适配三星部分手机,根据 MSA 工作人员反馈,对于三星部分机型的支持有 bug,导致
* 返回 1008614 错误码,但是不会触发回调。所以此处的逻辑是,两秒之后主动放弃阻塞。
*/
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
//ignore
}
mCountDownLatch.countDown();
}
}).start();
} catch (Throwable ex) {
SALog.d(TAG, ex.getMessage());
getOAIDReflect(context, --retryCount);
if (retryCount == 0) {
mCountDownLatch.countDown();
}
}
}
static class IdentifyListenerHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if ("OnSupport".equalsIgnoreCase(method.getName())) {
Method getOAID = mIdSupplier.getDeclaredMethod("getOAID");
if (args.length == 1) {// v1.0.26 版本只有 1 个参数
mOAID = (String) getOAID.invoke(args[0]);
} else {
mOAID = (String) getOAID.invoke(args[1]);
}
SALog.d(TAG, "oaid:" + mOAID);
mCountDownLatch.countDown();
}
} catch (Throwable ex) {
mCountDownLatch.countDown();
}
return null;
}
}
private static void initInvokeListener() {
try {
mMidSDKHelper = Class.forName("com.bun.miitmdid.core.MdidSdkHelper");
} catch (ClassNotFoundException e) {
SALog.d(TAG, e.getMessage());
return;
}
// 尝试 1.0.22 版本
try {
mIdentifyListener = Class.forName("com.bun.miitmdid.interfaces.IIdentifierListener");
mIdSupplier = Class.forName("com.bun.miitmdid.interfaces.IdSupplier");
return;
} catch (Exception ex) {
// ignore
}
// 尝试 1.0.13 - 1.0.21 版本
try {
mIdentifyListener = Class.forName("com.bun.supplier.IIdentifierListener");
mIdSupplier = Class.forName("com.bun.supplier.IdSupplier");
jLibrary = Class.forName("com.bun.miitmdid.core.JLibrary");
return;
} catch (Exception ex) {
// ignore
}
// 尝试 1.0.5 - 1.0.13 版本
try {
mIdentifyListener = Class.forName("com.bun.miitmdid.core.IIdentifierListener");
mIdSupplier = Class.forName("com.bun.miitmdid.supplier.IdSupplier");
jLibrary = Class.forName("com.bun.miitmdid.core.JLibrary");
} catch (Exception ex) {
// ignore
}
}
private static void initSDKLibrary() {
for (String library : mLoadLibrary) {
try {
System.loadLibrary(library); // 加载 SDK 安全库
break;
} catch (Throwable throwable) {
// ignore
}
}
}
/**
* 初始化证书
*
* @param context Context
*/
private static void initPemCert(Context context) {
try {
String oaidCert = loadPemFromAssetFile(context);
if (!TextUtils.isEmpty(oaidCert)) {
Method initCert = mMidSDKHelper.getDeclaredMethod("InitCert", Context.class, String.class);
initCert.invoke(null, context, oaidCert);
}
} catch (Throwable e) {
SALog.d(TAG, e.getMessage());
}
}
/**
* 从asset文件读取证书内容
*
* @param context Context
* @return 证书字符串
*/
private static String loadPemFromAssetFile(Context context) {
try {
String defaultPemCert = context.getPackageName() + ".cert.pem";
InputStream is;
AssetManager assetManager = context.getAssets();
if (!TextUtils.isEmpty(mOidCertFilePath)) {
try {
is = assetManager.open(mOidCertFilePath);
} catch (IOException e) {
is = assetManager.open(defaultPemCert);
}
} else {
is = assetManager.open(defaultPemCert);
}
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
builder.append(line);
builder.append('\n');
}
return builder.toString();
} catch (IOException e) {
SALog.d(TAG, "loadPemFromAssetFile failed");
return "";
}
}
/**
* 定义 oaid 证书在 assets 中的文件相对路径
*
* @param filePath oaid 证书在 assets 中的相对路径,eg:"file/test.cert.pom"
*/
public static void setOaidCertFilePath(String filePath) {
mOidCertFilePath = filePath;
}
} | 5,504 |
8,428 | # stdlib
from typing import List
from typing import Optional
from typing import Type
# third party
from nacl.signing import VerifyKey
# relative
from ....abstract.node_service_interface import NodeServiceInterface
from ..auth import service_auth
from ..node_service import ImmediateNodeServiceWithReply
from .user_auth_messages import UserLoginMessage
from .user_auth_messages import UserLoginMessageWithReply
from .user_auth_messages import UserLoginReplyMessage
class UserLoginService(ImmediateNodeServiceWithReply):
@staticmethod
@service_auth(guests_welcome=True)
def process(
node: NodeServiceInterface,
msg: UserLoginMessage,
verify_key: Optional[VerifyKey] = None,
) -> UserLoginReplyMessage:
# this service requires no verify_key because its currently public
result = msg.payload.run(node=node, verify_key=verify_key)
return UserLoginMessageWithReply(kwargs=result).back_to(address=msg.reply_to)
@staticmethod
def message_handler_types() -> List[Type[UserLoginMessage]]:
return [UserLoginMessage]
| 345 |
640 | <gh_stars>100-1000
#ifndef __KERN_SCHEDULE_SCHED_MULTI_H__
#define __KERN_SCHEDULE_SCHED_MULTI_H__
#include <sched.h>
extern struct sched_class multi_sched_class;
#endif /* !__KERN_SCHEDULE_SCHED_MULTI_H__ */
| 106 |
360 | <gh_stars>100-1000
import numpy as np
from yt.testing import assert_almost_equal, fake_random_ds
from yt.utilities.math_utils import euclidean_dist, periodic_dist
def setup():
from yt.config import ytcfg
ytcfg["yt", "internals", "within_testing"] = True
def test_periodicity():
# First test the simple case were we find the distance between two points
a = [0.1, 0.1, 0.1]
b = [0.9, 0.9, 0.9]
period = 1.0
dist = periodic_dist(a, b, period)
assert_almost_equal(dist, 0.34641016151377535)
dist = periodic_dist(a, b, period, (True, False, False))
assert_almost_equal(dist, 1.1489125293076059)
dist = periodic_dist(a, b, period, (False, True, False))
assert_almost_equal(dist, 1.1489125293076059)
dist = periodic_dist(a, b, period, (False, False, True))
assert_almost_equal(dist, 1.1489125293076059)
dist = periodic_dist(a, b, period, (True, True, False))
assert_almost_equal(dist, 0.84852813742385713)
dist = periodic_dist(a, b, period, (True, False, True))
assert_almost_equal(dist, 0.84852813742385713)
dist = periodic_dist(a, b, period, (False, True, True))
assert_almost_equal(dist, 0.84852813742385713)
dist = euclidean_dist(a, b)
assert_almost_equal(dist, 1.3856406460551021)
# Now test the more complicated cases where we're calculating radii based
# on data objects
ds = fake_random_ds(64)
# First we test flattened data
data = ds.all_data()
positions = np.array([data[("index", ax)] for ax in "xyz"])
c = [0.1, 0.1, 0.1]
n_tup = tuple(1 for i in range(positions.ndim - 1))
center = np.tile(
np.reshape(np.array(c), (positions.shape[0],) + n_tup),
(1,) + positions.shape[1:],
)
dist = periodic_dist(positions, center, period, ds.periodicity)
assert_almost_equal(dist.min(), 0.00270632938683)
assert_almost_equal(dist.max(), 0.863319074398)
dist = euclidean_dist(positions, center)
assert_almost_equal(dist.min(), 0.00270632938683)
assert_almost_equal(dist.max(), 1.54531407988)
# Then grid-like data
data = ds.index.grids[0]
positions = np.array([data[("index", ax)] for ax in "xyz"])
c = [0.1, 0.1, 0.1]
n_tup = tuple(1 for i in range(positions.ndim - 1))
center = np.tile(
np.reshape(np.array(c), (positions.shape[0],) + n_tup),
(1,) + positions.shape[1:],
)
dist = periodic_dist(positions, center, period, ds.periodicity)
assert_almost_equal(dist.min(), 0.00270632938683)
assert_almost_equal(dist.max(), 0.863319074398)
dist = euclidean_dist(positions, center)
assert_almost_equal(dist.min(), 0.00270632938683)
assert_almost_equal(dist.max(), 1.54531407988)
| 1,147 |
2,338 | // RUN: %clang_cc1 -fxray-instrument -fxray-instruction-threshold=1 -fxray-function-groups=3 -fxray-selected-function-group=0 \
// RUN: -emit-llvm -o - %s -triple x86_64-unknown-linux-gnu | FileCheck --check-prefix=GROUP0 %s
// RUN: %clang_cc1 -fxray-instrument -fxray-instruction-threshold=1 -fxray-function-groups=3 -fxray-selected-function-group=1 \
// RUN: -emit-llvm -o - %s -triple x86_64-unknown-linux-gnu | FileCheck --check-prefix=GROUP1 %s
// RUN: %clang_cc1 -fxray-instrument -fxray-instruction-threshold=1 -fxray-function-groups=3 -fxray-selected-function-group=2 \
// RUN: -emit-llvm -o - %s -triple x86_64-unknown-linux-gnu | FileCheck --check-prefix=GROUP2 %s
static int foo() { // part of group 0
return 1;
}
int bar() { // part of group 2
return 1;
}
int yarr() { // part of group 1
foo();
return 1;
}
[[clang::xray_always_instrument]] int always() { // part of group 0
return 1;
}
[[clang::xray_never_instrument]] int never() { // part of group 1
return 1;
}
// GROUP0: define{{.*}} i32 @_Z3barv() #[[ATTRS_BAR:[0-9]+]] {
// GROUP0: define{{.*}} i32 @_Z4yarrv() #[[ATTRS_BAR]] {
// GROUP0: define{{.*}} i32 @_ZL3foov() #[[ATTRS_FOO:[0-9]+]] {
// GROUP0: define{{.*}} i32 @_Z6alwaysv() #[[ATTRS_ALWAYS:[0-9]+]] {
// GROUP0: define{{.*}} i32 @_Z5neverv() #[[ATTRS_NEVER:[0-9]+]] {
// GROUP0-DAG: attributes #[[ATTRS_BAR]] = {{.*}} "function-instrument"="xray-never" {{.*}}
// GROUP0-DAG: attributes #[[ATTRS_ALWAYS]] = {{.*}} "function-instrument"="xray-always" {{.*}}
// GROUP0-DAG: attributes #[[ATTRS_NEVER]] = {{.*}} "function-instrument"="xray-never" {{.*}}
// GROUP1: define{{.*}} i32 @_Z3barv() #[[ATTRS_BAR:[0-9]+]] {
// GROUP1: define{{.*}} i32 @_Z4yarrv() #[[ATTRS_YARR:[0-9]+]] {
// GROUP1: define{{.*}} i32 @_ZL3foov() #[[ATTRS_BAR]] {
// GROUP1: define{{.*}} i32 @_Z6alwaysv() #[[ATTRS_ALWAYS:[0-9]+]] {
// GROUP1: define{{.*}} i32 @_Z5neverv() #[[ATTRS_NEVER:[0-9]+]] {
// GROUP1-DAG: attributes #[[ATTRS_BAR]] = {{.*}} "function-instrument"="xray-never" {{.*}}
// GROUP1-DAG: attributes #[[ATTRS_ALWAYS]] = {{.*}} "function-instrument"="xray-always" {{.*}}
// GROUP1-DAG: attributes #[[ATTRS_NEVER]] = {{.*}} "function-instrument"="xray-never" {{.*}}
// GROUP2: define{{.*}} i32 @_Z3barv() #[[ATTRS_BAR:[0-9]+]] {
// GROUP2: define{{.*}} i32 @_Z4yarrv() #[[ATTRS_YARR:[0-9]+]] {
// GROUP2: define{{.*}} i32 @_ZL3foov() #[[ATTRS_YARR]] {
// GROUP2: define{{.*}} i32 @_Z6alwaysv() #[[ATTRS_ALWAYS:[0-9]+]] {
// GROUP2: define{{.*}} i32 @_Z5neverv() #[[ATTRS_NEVER:[0-9]+]] {
// GROUP2-DAG: attributes #[[ATTRS_YARR]] = {{.*}} "function-instrument"="xray-never" {{.*}}
// GROUP2-DAG: attributes #[[ATTRS_ALWAYS]] = {{.*}} "function-instrument"="xray-always" {{.*}}
// GROUP2-DAG: attributes #[[ATTRS_NEVER]] = {{.*}} "function-instrument"="xray-never" {{.*}}
| 1,241 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.