blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
721
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 5
91
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 321
values | visit_date
timestamp[ns]date 2016-08-12 09:31:09
2023-09-06 10:45:07
| revision_date
timestamp[ns]date 2010-09-28 14:01:40
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 2010-09-28 14:01:40
2023-09-06 06:22:19
| github_id
int64 426
681M
| star_events_count
int64 101
243k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[ns]date 2012-06-28 18:51:49
2023-09-14 21:59:16
⌀ | gha_created_at
timestamp[ns]date 2008-02-11 22:55:26
2023-08-10 11:14:58
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 26
values | language
stringclasses 2
values | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 6
10.2M
| extension
stringclasses 115
values | filename
stringlengths 3
113
| content
stringlengths 6
10.2M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
71f8bc791bebbf7978f1518e01a6728a7b0529f6
|
6d54a7b26d0eb82152a549a6a9dfde656687752c
|
/examples/platform/openiotsdk/tf-m/targets/an552/cmsis_drivers/Driver_SSE300_PPC.c
|
03bdf106ec1b95d3377b3b4de6f791ded451c2b2
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
project-chip/connectedhomeip
|
81a123d675cf527773f70047d1ed1c43be5ffe6d
|
ea3970a7f11cd227ac55917edaa835a2a9bc4fc8
|
refs/heads/master
| 2023-09-01T11:43:37.546040
| 2023-09-01T08:01:32
| 2023-09-01T08:01:32
| 244,694,174
| 6,409
| 1,789
|
Apache-2.0
| 2023-09-14T20:56:31
| 2020-03-03T17:05:10
|
C++
|
UTF-8
|
C
| false
| false
| 41,617
|
c
|
Driver_SSE300_PPC.c
|
/*
* Copyright (c) 2019-2020 Arm 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.
*/
#include "Driver_SSE300_PPC.h"
#include "Driver_Common.h"
#include "RTE_Device.h"
#include "cmsis.h"
#include "cmsis_driver_config.h"
#include "ppc_sse300_drv.h"
/* Driver version */
#define ARM_PPC_DRV_VERSION ARM_DRIVER_VERSION_MAJOR_MINOR(1, 0)
/* Driver Version */
static const ARM_DRIVER_VERSION DriverVersion = { ARM_PPC_API_VERSION, ARM_PPC_DRV_VERSION };
ARM_DRIVER_VERSION PPC_SSE300_GetVersion(void)
{
return DriverVersion;
}
typedef struct _SSE300_PPC_Resources
{
struct ppc_sse300_dev_t * dev; /* PPC device structure */
} SSE300_PPC_Resources;
#if (RTE_PPC_SSE300_MAIN0)
static SSE300_PPC_Resources MAIN0_PPC_DEV = {
.dev = &PPC_SSE300_MAIN0_DEV,
};
/* MAIN0 PPC Driver wrapper functions */
static int32_t PPC_SSE300_MAIN0_Initialize(void)
{
ppc_sse300_init(MAIN0_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_MAIN0_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_MAIN0_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(MAIN0_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_MAIN0_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(MAIN0_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_MAIN0_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(MAIN0_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_MAIN0_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(MAIN0_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_MAIN0_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(MAIN0_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_MAIN0_DisableInterrupt(void)
{
ppc_sse300_irq_disable(MAIN0_PPC_DEV.dev);
}
static void PPC_SSE300_MAIN0_ClearInterrupt(void)
{
ppc_sse300_clear_irq(MAIN0_PPC_DEV.dev);
}
static bool PPC_SSE300_MAIN0_InterruptState(void)
{
return ppc_sse300_irq_state(MAIN0_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 MAIN0 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_MAIN0 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_MAIN0_Initialize,
.Uninitialize = PPC_SSE300_MAIN0_Uninitialize,
.ConfigPrivilege = PPC_SSE300_MAIN0_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_MAIN0_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_MAIN0_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_MAIN0_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_MAIN0_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_MAIN0_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_MAIN0_ClearInterrupt,
.InterruptState = PPC_SSE300_MAIN0_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_MAIN0 */
#if (RTE_PPC_SSE300_MAIN_EXP0)
static SSE300_PPC_Resources MAIN_EXP0_PPC_DEV = {
.dev = &PPC_SSE300_MAIN_EXP0_DEV,
};
/* MAIN PPCEXP0 Driver wrapper functions */
static int32_t PPC_SSE300_MAIN_EXP0_Initialize(void)
{
ppc_sse300_init(MAIN_EXP0_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_MAIN_EXP0_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_MAIN_EXP0_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(MAIN_EXP0_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_MAIN_EXP0_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(MAIN_EXP0_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_MAIN_EXP0_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(MAIN_EXP0_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_MAIN_EXP0_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(MAIN_EXP0_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_MAIN_EXP0_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(MAIN_EXP0_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_MAIN_EXP0_DisableInterrupt(void)
{
ppc_sse300_irq_disable(MAIN_EXP0_PPC_DEV.dev);
}
static void PPC_SSE300_MAIN_EXP0_ClearInterrupt(void)
{
ppc_sse300_clear_irq(MAIN_EXP0_PPC_DEV.dev);
}
static bool PPC_SSE300_MAIN_EXP0_InterruptState(void)
{
return ppc_sse300_irq_state(MAIN_EXP0_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 MAIN EXP0 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_MAIN_EXP0 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_MAIN_EXP0_Initialize,
.Uninitialize = PPC_SSE300_MAIN_EXP0_Uninitialize,
.ConfigPrivilege = PPC_SSE300_MAIN_EXP0_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_MAIN_EXP0_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_MAIN_EXP0_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_MAIN_EXP0_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_MAIN_EXP0_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_MAIN_EXP0_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_MAIN_EXP0_ClearInterrupt,
.InterruptState = PPC_SSE300_MAIN_EXP0_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_MAIN_EXP0 */
#if (RTE_PPC_SSE300_MAIN_EXP1)
static SSE300_PPC_Resources MAIN_EXP1_PPC_DEV = {
.dev = &PPC_SSE300_MAIN_EXP1_DEV,
};
/* MAIN PPCEXP1 Driver wrapper functions */
static int32_t PPC_SSE300_MAIN_EXP1_Initialize(void)
{
ppc_sse300_init(MAIN_EXP1_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_MAIN_EXP1_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_MAIN_EXP1_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(MAIN_EXP1_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_MAIN_EXP1_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(MAIN_EXP1_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_MAIN_EXP1_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(MAIN_EXP1_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_MAIN_EXP1_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(MAIN_EXP1_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_MAIN_EXP1_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(MAIN_EXP1_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_MAIN_EXP1_DisableInterrupt(void)
{
ppc_sse300_irq_disable(MAIN_EXP1_PPC_DEV.dev);
}
static void PPC_SSE300_MAIN_EXP1_ClearInterrupt(void)
{
ppc_sse300_clear_irq(MAIN_EXP1_PPC_DEV.dev);
}
static bool PPC_SSE300_MAIN_EXP1_InterruptState(void)
{
return ppc_sse300_irq_state(MAIN_EXP1_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 MAIN EXP1 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_MAIN_EXP1 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_MAIN_EXP1_Initialize,
.Uninitialize = PPC_SSE300_MAIN_EXP1_Uninitialize,
.ConfigPrivilege = PPC_SSE300_MAIN_EXP1_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_MAIN_EXP1_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_MAIN_EXP1_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_MAIN_EXP1_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_MAIN_EXP1_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_MAIN_EXP1_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_MAIN_EXP1_ClearInterrupt,
.InterruptState = PPC_SSE300_MAIN_EXP1_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_MAIN_EXP1 */
#if (RTE_PPC_SSE300_MAIN_EXP2)
static SSE300_PPC_Resources MAIN_EXP2_PPC_DEV = {
.dev = &PPC_SSE300_MAIN_EXP2_DEV,
};
/* MAIN PPCEXP2 Driver wrapper functions */
static int32_t PPC_SSE300_MAIN_EXP2_Initialize(void)
{
ppc_sse300_init(MAIN_EXP2_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_MAIN_EXP2_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_MAIN_EXP2_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(MAIN_EXP2_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_MAIN_EXP2_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(MAIN_EXP2_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_MAIN_EXP2_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(MAIN_EXP2_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_MAIN_EXP2_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(MAIN_EXP2_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_MAIN_EXP2_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(MAIN_EXP2_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_MAIN_EXP2_DisableInterrupt(void)
{
ppc_sse300_irq_disable(MAIN_EXP2_PPC_DEV.dev);
}
static void PPC_SSE300_MAIN_EXP2_ClearInterrupt(void)
{
ppc_sse300_clear_irq(MAIN_EXP2_PPC_DEV.dev);
}
static bool PPC_SSE300_MAIN_EXP2_InterruptState(void)
{
return ppc_sse300_irq_state(MAIN_EXP2_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 MAIN EXP2 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_MAIN_EXP2 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_MAIN_EXP2_Initialize,
.Uninitialize = PPC_SSE300_MAIN_EXP2_Uninitialize,
.ConfigPrivilege = PPC_SSE300_MAIN_EXP2_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_MAIN_EXP2_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_MAIN_EXP2_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_MAIN_EXP2_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_MAIN_EXP2_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_MAIN_EXP2_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_MAIN_EXP2_ClearInterrupt,
.InterruptState = PPC_SSE300_MAIN_EXP2_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_MAIN_EXP2 */
#if (RTE_PPC_SSE300_MAIN_EXP3)
static SSE300_PPC_Resources MAIN_EXP3_PPC_DEV = {
.dev = &PPC_SSE300_MAIN_EXP3_DEV,
};
/* MAIN PPCEXP3 Driver wrapper functions */
static int32_t PPC_SSE300_MAIN_EXP3_Initialize(void)
{
ppc_sse300_init(MAIN_EXP3_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_MAIN_EXP3_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_MAIN_EXP3_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(MAIN_EXP3_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_MAIN_EXP3_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(MAIN_EXP3_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_MAIN_EXP3_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(MAIN_EXP3_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_MAIN_EXP3_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(MAIN_EXP3_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_MAIN_EXP3_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(MAIN_EXP3_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_MAIN_EXP3_DisableInterrupt(void)
{
ppc_sse300_irq_disable(MAIN_EXP3_PPC_DEV.dev);
}
static void PPC_SSE300_MAIN_EXP3_ClearInterrupt(void)
{
ppc_sse300_clear_irq(MAIN_EXP3_PPC_DEV.dev);
}
static bool PPC_SSE300_MAIN_EXP3_InterruptState(void)
{
return ppc_sse300_irq_state(MAIN_EXP3_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 MAIN EXP3 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_MAIN_EXP3 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_MAIN_EXP3_Initialize,
.Uninitialize = PPC_SSE300_MAIN_EXP3_Uninitialize,
.ConfigPrivilege = PPC_SSE300_MAIN_EXP3_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_MAIN_EXP3_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_MAIN_EXP3_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_MAIN_EXP3_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_MAIN_EXP3_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_MAIN_EXP3_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_MAIN_EXP3_ClearInterrupt,
.InterruptState = PPC_SSE300_MAIN_EXP3_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_MAIN_EXP3 */
#if (RTE_PPC_SSE300_PERIPH0)
static SSE300_PPC_Resources PERIPH0_PPC_DEV = {
.dev = &PPC_SSE300_PERIPH0_DEV,
};
/* PERIPH0 Driver wrapper functions */
static int32_t PPC_SSE300_PERIPH0_Initialize(void)
{
ppc_sse300_init(PERIPH0_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH0_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH0_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(PERIPH0_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH0_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(PERIPH0_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_PERIPH0_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(PERIPH0_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH0_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(PERIPH0_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_PERIPH0_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(PERIPH0_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_PERIPH0_DisableInterrupt(void)
{
ppc_sse300_irq_disable(PERIPH0_PPC_DEV.dev);
}
static void PPC_SSE300_PERIPH0_ClearInterrupt(void)
{
ppc_sse300_clear_irq(PERIPH0_PPC_DEV.dev);
}
static bool PPC_SSE300_PERIPH0_InterruptState(void)
{
return ppc_sse300_irq_state(PERIPH0_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 PERIPH0 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_PERIPH0 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_PERIPH0_Initialize,
.Uninitialize = PPC_SSE300_PERIPH0_Uninitialize,
.ConfigPrivilege = PPC_SSE300_PERIPH0_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_PERIPH0_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_PERIPH0_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_PERIPH0_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_PERIPH0_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_PERIPH0_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_PERIPH0_ClearInterrupt,
.InterruptState = PPC_SSE300_PERIPH0_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_PERIPH0 */
#if (RTE_PPC_SSE300_PERIPH1)
static SSE300_PPC_Resources PERIPH1_PPC_DEV = {
.dev = &PPC_SSE300_PERIPH1_DEV,
};
/* PERIPH1 Driver wrapper functions */
static int32_t PPC_SSE300_PERIPH1_Initialize(void)
{
ppc_sse300_init(PERIPH1_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH1_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH1_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(PERIPH1_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH1_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(PERIPH1_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_PERIPH1_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(PERIPH1_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH1_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(PERIPH1_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_PERIPH1_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(PERIPH1_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_PERIPH1_DisableInterrupt(void)
{
ppc_sse300_irq_disable(PERIPH1_PPC_DEV.dev);
}
static void PPC_SSE300_PERIPH1_ClearInterrupt(void)
{
ppc_sse300_clear_irq(PERIPH1_PPC_DEV.dev);
}
static bool PPC_SSE300_PERIPH1_InterruptState(void)
{
return ppc_sse300_irq_state(PERIPH1_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 PERIPH1 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_PERIPH1 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_PERIPH1_Initialize,
.Uninitialize = PPC_SSE300_PERIPH1_Uninitialize,
.ConfigPrivilege = PPC_SSE300_PERIPH1_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_PERIPH1_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_PERIPH1_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_PERIPH1_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_PERIPH1_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_PERIPH1_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_PERIPH1_ClearInterrupt,
.InterruptState = PPC_SSE300_PERIPH1_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_PERIPH1 */
#if (RTE_PPC_SSE300_PERIPH_EXP0)
static SSE300_PPC_Resources PERIPH_EXP0_PPC_DEV = {
.dev = &PPC_SSE300_PERIPH_EXP0_DEV,
};
/* PERIPH PPCEXP0 Driver wrapper functions */
static int32_t PPC_SSE300_PERIPH_EXP0_Initialize(void)
{
ppc_sse300_init(PERIPH_EXP0_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH_EXP0_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH_EXP0_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(PERIPH_EXP0_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH_EXP0_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(PERIPH_EXP0_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_PERIPH_EXP0_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(PERIPH_EXP0_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH_EXP0_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(PERIPH_EXP0_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_PERIPH_EXP0_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(PERIPH_EXP0_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_PERIPH_EXP0_DisableInterrupt(void)
{
ppc_sse300_irq_disable(PERIPH_EXP0_PPC_DEV.dev);
}
static void PPC_SSE300_PERIPH_EXP0_ClearInterrupt(void)
{
ppc_sse300_clear_irq(PERIPH_EXP0_PPC_DEV.dev);
}
static bool PPC_SSE300_PERIPH_EXP0_InterruptState(void)
{
return ppc_sse300_irq_state(PERIPH_EXP0_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 PERIPH EXP0 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_PERIPH_EXP0 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_PERIPH_EXP0_Initialize,
.Uninitialize = PPC_SSE300_PERIPH_EXP0_Uninitialize,
.ConfigPrivilege = PPC_SSE300_PERIPH_EXP0_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_PERIPH_EXP0_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_PERIPH_EXP0_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_PERIPH_EXP0_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_PERIPH_EXP0_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_PERIPH_EXP0_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_PERIPH_EXP0_ClearInterrupt,
.InterruptState = PPC_SSE300_PERIPH_EXP0_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_PERIPH_EXP0 */
#if (RTE_PPC_SSE300_PERIPH_EXP1)
static SSE300_PPC_Resources PERIPH_EXP1_PPC_DEV = {
.dev = &PPC_SSE300_PERIPH_EXP1_DEV,
};
/* PERIPH PPCEXP1 Driver wrapper functions */
static int32_t PPC_SSE300_PERIPH_EXP1_Initialize(void)
{
ppc_sse300_init(PERIPH_EXP1_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH_EXP1_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH_EXP1_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(PERIPH_EXP1_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH_EXP1_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(PERIPH_EXP1_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_PERIPH_EXP1_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(PERIPH_EXP1_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH_EXP1_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(PERIPH_EXP1_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_PERIPH_EXP1_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(PERIPH_EXP1_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_PERIPH_EXP1_DisableInterrupt(void)
{
ppc_sse300_irq_disable(PERIPH_EXP1_PPC_DEV.dev);
}
static void PPC_SSE300_PERIPH_EXP1_ClearInterrupt(void)
{
ppc_sse300_clear_irq(PERIPH_EXP1_PPC_DEV.dev);
}
static bool PPC_SSE300_PERIPH_EXP1_InterruptState(void)
{
return ppc_sse300_irq_state(PERIPH_EXP1_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 PERIPH EXP1 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_PERIPH_EXP1 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_PERIPH_EXP1_Initialize,
.Uninitialize = PPC_SSE300_PERIPH_EXP1_Uninitialize,
.ConfigPrivilege = PPC_SSE300_PERIPH_EXP1_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_PERIPH_EXP1_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_PERIPH_EXP1_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_PERIPH_EXP1_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_PERIPH_EXP1_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_PERIPH_EXP1_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_PERIPH_EXP1_ClearInterrupt,
.InterruptState = PPC_SSE300_PERIPH_EXP1_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_PERIPH_EXP1 */
#if (RTE_PPC_SSE300_PERIPH_EXP2)
static SSE300_PPC_Resources PERIPH_EXP2_PPC_DEV = {
.dev = &PPC_SSE300_PERIPH_EXP2_DEV,
};
/* PERIPH PPCEXP2 Driver wrapper functions */
static int32_t PPC_SSE300_PERIPH_EXP2_Initialize(void)
{
ppc_sse300_init(PERIPH_EXP2_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH_EXP2_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH_EXP2_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(PERIPH_EXP2_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH_EXP2_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(PERIPH_EXP2_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_PERIPH_EXP2_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(PERIPH_EXP2_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH_EXP2_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(PERIPH_EXP2_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_PERIPH_EXP2_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(PERIPH_EXP2_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_PERIPH_EXP2_DisableInterrupt(void)
{
ppc_sse300_irq_disable(PERIPH_EXP2_PPC_DEV.dev);
}
static void PPC_SSE300_PERIPH_EXP2_ClearInterrupt(void)
{
ppc_sse300_clear_irq(PERIPH_EXP2_PPC_DEV.dev);
}
static bool PPC_SSE300_PERIPH_EXP2_InterruptState(void)
{
return ppc_sse300_irq_state(PERIPH_EXP2_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 PERIPH EXP2 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_PERIPH_EXP2 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_PERIPH_EXP2_Initialize,
.Uninitialize = PPC_SSE300_PERIPH_EXP2_Uninitialize,
.ConfigPrivilege = PPC_SSE300_PERIPH_EXP2_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_PERIPH_EXP2_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_PERIPH_EXP2_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_PERIPH_EXP2_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_PERIPH_EXP2_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_PERIPH_EXP2_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_PERIPH_EXP2_ClearInterrupt,
.InterruptState = PPC_SSE300_PERIPH_EXP2_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_PERIPH_EXP2 */
#if (RTE_PPC_SSE300_PERIPH_EXP3)
static SSE300_PPC_Resources PERIPH_EXP3_PPC_DEV = {
.dev = &PPC_SSE300_PERIPH_EXP3_DEV,
};
/* PERIPH PPCEXP3 Driver wrapper functions */
static int32_t PPC_SSE300_PERIPH_EXP3_Initialize(void)
{
ppc_sse300_init(PERIPH_EXP3_PPC_DEV.dev);
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH_EXP3_Uninitialize(void)
{
/* Nothing to do */
return ARM_DRIVER_OK;
}
static int32_t PPC_SSE300_PERIPH_EXP3_ConfigPrivilege(uint32_t periph, PPC_SSE300_SecAttr sec_attr, PPC_SSE300_PrivAttr priv_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_privilege(PERIPH_EXP3_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr,
(enum ppc_sse300_priv_attr_t) priv_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH_EXP3_IsPeriphPrivOnly(uint32_t periph)
{
return ppc_sse300_is_periph_priv_only(PERIPH_EXP3_PPC_DEV.dev, periph);
}
/* Secure only functions */
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
static int32_t PPC_SSE300_PERIPH_EXP3_ConfigSecurity(uint32_t periph, PPC_SSE300_SecAttr sec_attr)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_config_security(PERIPH_EXP3_PPC_DEV.dev, periph, (enum ppc_sse300_sec_attr_t) sec_attr);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static bool PPC_SSE300_PERIPH_EXP3_IsPeriphSecure(uint32_t periph)
{
return ppc_sse300_is_periph_secure(PERIPH_EXP3_PPC_DEV.dev, periph);
}
static int32_t PPC_SSE300_PERIPH_EXP3_EnableInterrupt(void)
{
enum ppc_sse300_error_t ret;
ret = ppc_sse300_irq_enable(PERIPH_EXP3_PPC_DEV.dev);
if (ret != PPC_SSE300_ERR_NONE)
{
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
static void PPC_SSE300_PERIPH_EXP3_DisableInterrupt(void)
{
ppc_sse300_irq_disable(PERIPH_EXP3_PPC_DEV.dev);
}
static void PPC_SSE300_PERIPH_EXP3_ClearInterrupt(void)
{
ppc_sse300_clear_irq(PERIPH_EXP3_PPC_DEV.dev);
}
static bool PPC_SSE300_PERIPH_EXP3_InterruptState(void)
{
return ppc_sse300_irq_state(PERIPH_EXP3_PPC_DEV.dev);
}
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
/* PPC SSE-300 PERIPH EXP3 Driver CMSIS access structure */
DRIVER_PPC_SSE300 Driver_PPC_SSE300_PERIPH_EXP3 = { .GetVersion = PPC_SSE300_GetVersion,
.Initialize = PPC_SSE300_PERIPH_EXP3_Initialize,
.Uninitialize = PPC_SSE300_PERIPH_EXP3_Uninitialize,
.ConfigPrivilege = PPC_SSE300_PERIPH_EXP3_ConfigPrivilege,
.IsPeriphPrivOnly = PPC_SSE300_PERIPH_EXP3_IsPeriphPrivOnly,
#if (defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U))
.ConfigSecurity = PPC_SSE300_PERIPH_EXP3_ConfigSecurity,
.IsPeriphSecure = PPC_SSE300_PERIPH_EXP3_IsPeriphSecure,
.EnableInterrupt = PPC_SSE300_PERIPH_EXP3_EnableInterrupt,
.DisableInterrupt = PPC_SSE300_PERIPH_EXP3_DisableInterrupt,
.ClearInterrupt = PPC_SSE300_PERIPH_EXP3_ClearInterrupt,
.InterruptState = PPC_SSE300_PERIPH_EXP3_InterruptState
#endif /* (defined (__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE == 3U)) */
};
#endif /* RTE_PPC_SSE300_PERIPH_EXP3 */
|
aefda6c6d8486eb57c5dcc317359494cd2540e83
|
a8194cf6ffd12f7551eaba53572744080a0bfef3
|
/examples/blob/hello_world/hello_blob.c
|
8a237c0945e7e89dc59aff5b5190c250311ff8e6
|
[
"Intel",
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
spdk/spdk
|
51294f67104b8c3d18f19147d63a212e9486c687
|
d62a3810364cb87be352c66acf7c7f968508ca17
|
refs/heads/master
| 2023-08-08T16:07:41.263000
| 2023-08-02T09:06:56
| 2023-08-08T07:01:20
| 39,042,157
| 2,708
| 1,158
|
NOASSERTION
| 2023-08-11T09:50:50
| 2015-07-13T23:15:15
|
C
|
UTF-8
|
C
| false
| false
| 12,077
|
c
|
hello_blob.c
|
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright (C) 2017 Intel Corporation.
* All rights reserved.
*/
#include "spdk/stdinc.h"
#include "spdk/bdev.h"
#include "spdk/env.h"
#include "spdk/event.h"
#include "spdk/blob_bdev.h"
#include "spdk/blob.h"
#include "spdk/log.h"
#include "spdk/string.h"
/*
* We'll use this struct to gather housekeeping hello_context to pass between
* our events and callbacks.
*/
struct hello_context_t {
struct spdk_blob_store *bs;
struct spdk_blob *blob;
spdk_blob_id blobid;
struct spdk_io_channel *channel;
uint8_t *read_buff;
uint8_t *write_buff;
uint64_t io_unit_size;
int rc;
};
/*
* Free up memory that we allocated.
*/
static void
hello_cleanup(struct hello_context_t *hello_context)
{
spdk_free(hello_context->read_buff);
spdk_free(hello_context->write_buff);
free(hello_context);
}
/*
* Callback routine for the blobstore unload.
*/
static void
unload_complete(void *cb_arg, int bserrno)
{
struct hello_context_t *hello_context = cb_arg;
SPDK_NOTICELOG("entry\n");
if (bserrno) {
SPDK_ERRLOG("Error %d unloading the bobstore\n", bserrno);
hello_context->rc = bserrno;
}
spdk_app_stop(hello_context->rc);
}
/*
* Unload the blobstore, cleaning up as needed.
*/
static void
unload_bs(struct hello_context_t *hello_context, char *msg, int bserrno)
{
if (bserrno) {
SPDK_ERRLOG("%s (err %d)\n", msg, bserrno);
hello_context->rc = bserrno;
}
if (hello_context->bs) {
if (hello_context->channel) {
spdk_bs_free_io_channel(hello_context->channel);
}
spdk_bs_unload(hello_context->bs, unload_complete, hello_context);
} else {
spdk_app_stop(bserrno);
}
}
/*
* Callback routine for the deletion of a blob.
*/
static void
delete_complete(void *arg1, int bserrno)
{
struct hello_context_t *hello_context = arg1;
SPDK_NOTICELOG("entry\n");
if (bserrno) {
unload_bs(hello_context, "Error in delete completion",
bserrno);
return;
}
/* We're all done, we can unload the blobstore. */
unload_bs(hello_context, "", 0);
}
/*
* Function for deleting a blob.
*/
static void
delete_blob(void *arg1, int bserrno)
{
struct hello_context_t *hello_context = arg1;
SPDK_NOTICELOG("entry\n");
if (bserrno) {
unload_bs(hello_context, "Error in close completion",
bserrno);
return;
}
spdk_bs_delete_blob(hello_context->bs, hello_context->blobid,
delete_complete, hello_context);
}
/*
* Callback function for reading a blob.
*/
static void
read_complete(void *arg1, int bserrno)
{
struct hello_context_t *hello_context = arg1;
int match_res = -1;
SPDK_NOTICELOG("entry\n");
if (bserrno) {
unload_bs(hello_context, "Error in read completion",
bserrno);
return;
}
/* Now let's make sure things match. */
match_res = memcmp(hello_context->write_buff, hello_context->read_buff,
hello_context->io_unit_size);
if (match_res) {
unload_bs(hello_context, "Error in data compare", -1);
return;
} else {
SPDK_NOTICELOG("read SUCCESS and data matches!\n");
}
/* Now let's close it and delete the blob in the callback. */
spdk_blob_close(hello_context->blob, delete_blob, hello_context);
}
/*
* Function for reading a blob.
*/
static void
read_blob(struct hello_context_t *hello_context)
{
SPDK_NOTICELOG("entry\n");
hello_context->read_buff = spdk_malloc(hello_context->io_unit_size,
0x1000, NULL, SPDK_ENV_LCORE_ID_ANY,
SPDK_MALLOC_DMA);
if (hello_context->read_buff == NULL) {
unload_bs(hello_context, "Error in memory allocation",
-ENOMEM);
return;
}
/* Issue the read and compare the results in the callback. */
spdk_blob_io_read(hello_context->blob, hello_context->channel,
hello_context->read_buff, 0, 1, read_complete,
hello_context);
}
/*
* Callback function for writing a blob.
*/
static void
write_complete(void *arg1, int bserrno)
{
struct hello_context_t *hello_context = arg1;
SPDK_NOTICELOG("entry\n");
if (bserrno) {
unload_bs(hello_context, "Error in write completion",
bserrno);
return;
}
/* Now let's read back what we wrote and make sure it matches. */
read_blob(hello_context);
}
/*
* Function for writing to a blob.
*/
static void
blob_write(struct hello_context_t *hello_context)
{
SPDK_NOTICELOG("entry\n");
/*
* Buffers for data transfer need to be allocated via SPDK. We will
* transfer 1 io_unit of 4K aligned data at offset 0 in the blob.
*/
hello_context->write_buff = spdk_malloc(hello_context->io_unit_size,
0x1000, NULL, SPDK_ENV_LCORE_ID_ANY,
SPDK_MALLOC_DMA);
if (hello_context->write_buff == NULL) {
unload_bs(hello_context, "Error in allocating memory",
-ENOMEM);
return;
}
memset(hello_context->write_buff, 0x5a, hello_context->io_unit_size);
/* Now we have to allocate a channel. */
hello_context->channel = spdk_bs_alloc_io_channel(hello_context->bs);
if (hello_context->channel == NULL) {
unload_bs(hello_context, "Error in allocating channel",
-ENOMEM);
return;
}
/* Let's perform the write, 1 io_unit at offset 0. */
spdk_blob_io_write(hello_context->blob, hello_context->channel,
hello_context->write_buff,
0, 1, write_complete, hello_context);
}
/*
* Callback function for syncing metadata.
*/
static void
sync_complete(void *arg1, int bserrno)
{
struct hello_context_t *hello_context = arg1;
SPDK_NOTICELOG("entry\n");
if (bserrno) {
unload_bs(hello_context, "Error in sync callback",
bserrno);
return;
}
/* Blob has been created & sized & MD sync'd, let's write to it. */
blob_write(hello_context);
}
static void
resize_complete(void *cb_arg, int bserrno)
{
struct hello_context_t *hello_context = cb_arg;
uint64_t total = 0;
if (bserrno) {
unload_bs(hello_context, "Error in blob resize", bserrno);
return;
}
total = spdk_blob_get_num_clusters(hello_context->blob);
SPDK_NOTICELOG("resized blob now has USED clusters of %" PRIu64 "\n",
total);
/*
* Metadata is stored in volatile memory for performance
* reasons and therefore needs to be synchronized with
* non-volatile storage to make it persistent. This can be
* done manually, as shown here, or if not it will be done
* automatically when the blob is closed. It is always a
* good idea to sync after making metadata changes unless
* it has an unacceptable impact on application performance.
*/
spdk_blob_sync_md(hello_context->blob, sync_complete, hello_context);
}
/*
* Callback function for opening a blob.
*/
static void
open_complete(void *cb_arg, struct spdk_blob *blob, int bserrno)
{
struct hello_context_t *hello_context = cb_arg;
uint64_t free = 0;
SPDK_NOTICELOG("entry\n");
if (bserrno) {
unload_bs(hello_context, "Error in open completion",
bserrno);
return;
}
hello_context->blob = blob;
free = spdk_bs_free_cluster_count(hello_context->bs);
SPDK_NOTICELOG("blobstore has FREE clusters of %" PRIu64 "\n",
free);
/*
* Before we can use our new blob, we have to resize it
* as the initial size is 0. For this example we'll use the
* full size of the blobstore but it would be expected that
* there'd usually be many blobs of various sizes. The resize
* unit is a cluster.
*/
spdk_blob_resize(hello_context->blob, free, resize_complete, hello_context);
}
/*
* Callback function for creating a blob.
*/
static void
blob_create_complete(void *arg1, spdk_blob_id blobid, int bserrno)
{
struct hello_context_t *hello_context = arg1;
SPDK_NOTICELOG("entry\n");
if (bserrno) {
unload_bs(hello_context, "Error in blob create callback",
bserrno);
return;
}
hello_context->blobid = blobid;
SPDK_NOTICELOG("new blob id %" PRIu64 "\n", hello_context->blobid);
/* We have to open the blob before we can do things like resize. */
spdk_bs_open_blob(hello_context->bs, hello_context->blobid,
open_complete, hello_context);
}
/*
* Function for creating a blob.
*/
static void
create_blob(struct hello_context_t *hello_context)
{
SPDK_NOTICELOG("entry\n");
spdk_bs_create_blob(hello_context->bs, blob_create_complete, hello_context);
}
/*
* Callback function for initializing the blobstore.
*/
static void
bs_init_complete(void *cb_arg, struct spdk_blob_store *bs,
int bserrno)
{
struct hello_context_t *hello_context = cb_arg;
SPDK_NOTICELOG("entry\n");
if (bserrno) {
unload_bs(hello_context, "Error initing the blobstore",
bserrno);
return;
}
hello_context->bs = bs;
SPDK_NOTICELOG("blobstore: %p\n", hello_context->bs);
/*
* We will use the io_unit size in allocating buffers, etc., later
* so we'll just save it in out context buffer here.
*/
hello_context->io_unit_size = spdk_bs_get_io_unit_size(hello_context->bs);
/*
* The blobstore has been initialized, let's create a blob.
* Note that we could pass a message back to ourselves using
* spdk_thread_send_msg() if we wanted to keep our processing
* time limited.
*/
create_blob(hello_context);
}
static void
base_bdev_event_cb(enum spdk_bdev_event_type type, struct spdk_bdev *bdev,
void *event_ctx)
{
SPDK_WARNLOG("Unsupported bdev event: type %d\n", type);
}
/*
* Our initial event that kicks off everything from main().
*/
static void
hello_start(void *arg1)
{
struct hello_context_t *hello_context = arg1;
struct spdk_bs_dev *bs_dev = NULL;
int rc;
SPDK_NOTICELOG("entry\n");
/*
* In this example, use our malloc (RAM) disk configured via
* hello_blob.json that was passed in when we started the
* SPDK app framework.
*
* spdk_bs_init() requires us to fill out the structure
* spdk_bs_dev with a set of callbacks. These callbacks
* implement read, write, and other operations on the
* underlying disks. As a convenience, a utility function
* is provided that creates an spdk_bs_dev that implements
* all of the callbacks by forwarding the I/O to the
* SPDK bdev layer. Other helper functions are also
* available in the blob lib in blob_bdev.c that simply
* make it easier to layer blobstore on top of a bdev.
* However blobstore can be more tightly integrated into
* any lower layer, such as NVMe for example.
*/
rc = spdk_bdev_create_bs_dev_ext("Malloc0", base_bdev_event_cb, NULL, &bs_dev);
if (rc != 0) {
SPDK_ERRLOG("Could not create blob bdev, %s!!\n",
spdk_strerror(-rc));
spdk_app_stop(-1);
return;
}
spdk_bs_init(bs_dev, NULL, bs_init_complete, hello_context);
}
int
main(int argc, char **argv)
{
struct spdk_app_opts opts = {};
int rc = 0;
struct hello_context_t *hello_context = NULL;
SPDK_NOTICELOG("entry\n");
/* Set default values in opts structure. */
spdk_app_opts_init(&opts, sizeof(opts));
/*
* Setup a few specifics before we init, for most SPDK cmd line
* apps, the config file will be passed in as an arg but to make
* this example super simple we just hardcode it. We also need to
* specify a name for the app.
*/
opts.name = "hello_blob";
opts.json_config_file = argv[1];
/*
* Now we'll allocate and initialize the blobstore itself. We
* can pass in an spdk_bs_opts if we want something other than
* the defaults (cluster size, etc), but here we'll just take the
* defaults. We'll also pass in a struct that we'll use for
* callbacks so we've got efficient bookkeeping of what we're
* creating. This is an async operation and bs_init_complete()
* will be called when it is complete.
*/
hello_context = calloc(1, sizeof(struct hello_context_t));
if (hello_context != NULL) {
/*
* spdk_app_start() will block running hello_start() until
* spdk_app_stop() is called by someone (not simply when
* hello_start() returns), or if an error occurs during
* spdk_app_start() before hello_start() runs.
*/
rc = spdk_app_start(&opts, hello_start, hello_context);
if (rc) {
SPDK_NOTICELOG("ERROR!\n");
} else {
SPDK_NOTICELOG("SUCCESS!\n");
}
/* Free up memory that we allocated */
hello_cleanup(hello_context);
} else {
SPDK_ERRLOG("Could not alloc hello_context struct!!\n");
rc = -ENOMEM;
}
/* Gracefully close out all of the SPDK subsystems. */
spdk_app_fini();
return rc;
}
|
00ec2116941c5a900a479a6e9acdfe97b4d13dc9
|
f61a792b07b5d8150f35b646a4af44bfee8086dd
|
/DBKKernel/kfiles.h
|
5f232f7c6e157a056560662c00c9d90a095f3072
|
[] |
no_license
|
cheat-engine/cheat-engine
|
9ba690f25cf53a4c375ca11bd0ae19123731a775
|
6a0c8253a9b596f0aa216574e7a9bf4a390e409a
|
refs/heads/master
| 2023-08-31T05:49:43.507423
| 2023-08-30T14:15:24
| 2023-08-30T14:15:24
| 34,163,206
| 12,899
| 2,821
| null | 2023-09-04T02:15:43
| 2015-04-18T11:21:57
|
Pascal
|
UTF-8
|
C
| false
| false
| 217
|
h
|
kfiles.h
|
NTSTATUS CETC_CreateFile(PHANDLE file, PCWSTR filename);
NTSTATUS CETC_OpenFile(PHANDLE file, PCWSTR filename);
#define CETC_Write(file,buffer,size,iosb) ZwWriteFile(file,NULL,NULL,NULL,iosb,buffer,size,NULL,NULL)
|
6cbf2e86f7611791effa1f2ae8824879b770659d
|
77861deda8b3046bdda221d3cb80b77e84b14523
|
/sse4-mandelbrot/sse4-proc-64-bit.c
|
b36c7c87bc37010d23cd295290f353d47fae45b1
|
[
"BSD-2-Clause"
] |
permissive
|
WojciechMula/toys
|
b73f09212ca19f1e76bbf2afaa5ad2efcea95175
|
6110b59de45dc1ce44388b21c6437eff49a7655c
|
refs/heads/master
| 2023-08-18T12:54:25.919406
| 2023-08-05T09:20:14
| 2023-08-05T09:20:14
| 14,905,115
| 302
| 44
|
BSD-2-Clause
| 2020-04-17T17:10:42
| 2013-12-03T20:35:37
|
C++
|
UTF-8
|
C
| false
| false
| 2,426
|
c
|
sse4-proc-64-bit.c
|
//=== SSE4 implementation - 64-bit code ==================================
#include <immintrin.h>
void SSE_mandelbrot(
float Re_min, float Re_max,
float Im_min, float Im_max,
float threshold,
int maxiters,
int width, int height,
uint8_t *data)
{
float dRe, dIm;
int x, y;
uint32_t* ptr = (uint32_t*)data;
// step on Re and Im axis
dRe = (Re_max - Re_min)/width;
dIm = (Im_max - Im_min)/height;
// prepare vectors
// 1. threshold
const __m128 vec_threshold = _mm_set1_ps(threshold);
// 2. Cim
__m128 Cim = _mm_set1_ps(Im_min);
// 3. Re advance every x iteration
const __m128 vec_dRe = _mm_set1_ps(4*dRe);
// 4. Im advance every y iteration
const __m128 vec_dIm = _mm_set1_ps(dIm);
// calculations
for (y=0; y < height; y++) {
__m128 Cre = _mm_setr_ps(Re_min, Re_min + dRe, Re_min + 2*dRe, Re_min + 3*dRe);
for (x=0; x < width; x+=4) {
__m128 Xre = _mm_setzero_ps();
__m128 Xim = _mm_setzero_ps();
__m128i itercount = _mm_setzero_si128();
int i;
for (i=0; i < maxiters; i++) {
// Tre = Xre^2 - Xim^2 + Cim
const __m128 Xre2 = _mm_mul_ps(Xre, Xre);
const __m128 Xim2 = _mm_mul_ps(Xim, Xim);
const __m128 Tre = _mm_add_ps(Cre, _mm_sub_ps(Xre2, Xim2));
// Tim = 2*Xre*Xim + Cre
const __m128 t1 = _mm_mul_ps(Xre, Xim);
const __m128 Tim = _mm_add_ps(Cim, _mm_add_ps(t1, t1));
// sqr_dist = Tre^2 + Tim^2
__m128 Tre2 = _mm_mul_ps(Tre, Tre);
__m128 Tim2 = _mm_mul_ps(Tim, Tim);
__m128 sqr_dist = _mm_add_ps(Tre2, Tim2);
// sqr_dist < threshold => 4 elements vector
__m128 cmp = _mm_cmple_ps(sqr_dist, vec_threshold);
const unsigned mask = _mm_movemask_ps(cmp);
if (mask == 0) {
break;
}
itercount = _mm_sub_epi32(itercount, (__m128i)cmp);
Xre = Tre;
Xim = Tim;
} // for
const __m128i t1 = _mm_packus_epi16(itercount, itercount);
const __m128i t2 = _mm_packus_epi16(t1, t1);
*ptr++ = _mm_cvtsi128_si32(t2);
// advance Cre vector
Cre = _mm_add_ps(Cre, vec_dRe);
}
// advance Cim vector
Cim = _mm_add_ps(Cim, vec_dIm);
}
}
|
94464458601138a2f8c0406ac4e7460a58dbdac6
|
2cecd7697c8dc6f56fb32cf6d38056feb5f0c000
|
/benchmarks/aes/api_aes.h
|
1d4929522331a1f70928963aacf417cfb0b2c737
|
[
"CC-BY-4.0"
] |
permissive
|
riscv/riscv-crypto
|
8e387ff056f374294e32580e814e3af68d9f04f0
|
c8ddeb7e64a3444dda0438316af1238aeed72041
|
refs/heads/main
| 2023-08-30T01:59:12.781043
| 2023-08-25T19:10:19
| 2023-08-25T19:10:19
| 227,585,452
| 316
| 99
|
CC-BY-4.0
| 2023-09-12T01:59:44
| 2019-12-12T10:57:09
|
C
|
UTF-8
|
C
| false
| false
| 4,851
|
h
|
api_aes.h
|
#include <stdint.h>
/*!
@defgroup crypto_block_aes Crypto Block AES
@{
AES | Nk | Nb | Nr
-----|-------|------|---------------
128 | 4 | 4 | 10
192 | 6 | 4 | 12
256 | 8 | 4 | 14
*/
#ifndef __API_AES_H__
#define __API_AES_H__
//! Number of bytes in a single AES block
#define AES_BLOCK_BYTES 16
//! Block size in 4-byte words for AES 128
#define AES_128_NB 4
#define AES_192_NB 4
#define AES_256_NB 4
//! Words in AES 128 cipher key
#define AES_128_NK 4
#define AES_192_NK 6
#define AES_256_NK 8
//! Number of rounds for AES 128
#define AES_128_NR 10
#define AES_192_NR 12
#define AES_256_NR 14
//! Bytes in an AES 128 Cipher key
#define AES_128_KEY_BYTES (4*AES_128_NK)
#define AES_192_KEY_BYTES (4*AES_192_NK)
#define AES_256_KEY_BYTES (4*AES_256_NK)
#define AES_128_RK_WORDS 44
#define AES_192_RK_WORDS 52
#define AES_256_RK_WORDS 60
//! Number of bytes in the expanded AES 128 key
#define AES_128_RK_BYTES (4*AES_128_RK_WORDS)
#define AES_192_RK_BYTES (4*AES_192_RK_WORDS)
#define AES_256_RK_BYTES (4*AES_256_RK_WORDS)
/*!
@brief Key expansion function for the AES 128 parameterisation - encrypt
@param [out] rk - The expanded key schedule
@param [in] ck - The cipher key to expand
*/
void aes_128_enc_key_schedule (
uint32_t * const rk,
uint8_t * const ck
);
/*!
@brief Key expansion function for the AES 192 parameterisation - encrypt
@param [out] rk - The expanded key schedule
@param [in] ck - The cipher key to expand
*/
void aes_192_enc_key_schedule (
uint32_t * const rk,
uint8_t * const ck
);
/*!
@brief Key expansion function for the AES 256 parameterisation - encrypt
@param [out] rk - The expanded key schedule
@param [in] ck - The cipher key to expand
*/
void aes_256_enc_key_schedule (
uint32_t * const rk,
uint8_t * const ck
);
/*!
@brief Key expansion function for the AES 128 parameterisation - decrypt
@param [out] rk - The expanded key schedule
@param [in] ck - The cipher key to expand
*/
void aes_128_dec_key_schedule (
uint32_t * const rk,
uint8_t * const ck
);
/*!
@brief Key expansion function for the AES 192 parameterisation - decrypt
@param [out] rk - The expanded key schedule
@param [in] ck - The cipher key to expand
*/
void aes_192_dec_key_schedule (
uint32_t * const rk,
uint8_t * const ck
);
/*!
@brief Key expansion function for the AES 256 parameterisation - decrypt
@param [out] rk - The expanded key schedule
@param [in] ck - The cipher key to expand
*/
void aes_256_dec_key_schedule (
uint32_t * const rk,
uint8_t * const ck
);
/*!
@brief single-block AES 128 encrypt function
@param [out] ct - Output cipher text
@param [in] pt - Input plaintext
@param [in] rk - The expanded key schedule
@param [in] nr - Number of encryption rounds to perform.
*/
void aes_128_ecb_encrypt (
uint8_t ct [AES_BLOCK_BYTES],
uint8_t pt [AES_BLOCK_BYTES],
uint32_t * rk
);
/*!
@brief single-block AES 192 encrypt function
@param [out] ct - Output cipher text
@param [in] pt - Input plaintext
@param [in] rk - The expanded key schedule
@param [in] nr - Number of encryption rounds to perform.
*/
void aes_192_ecb_encrypt (
uint8_t ct [AES_BLOCK_BYTES],
uint8_t pt [AES_BLOCK_BYTES],
uint32_t * rk
);
/*!
@brief single-block AES 256 encrypt function
@param [out] ct - Output cipher text
@param [in] pt - Input plaintext
@param [in] rk - The expanded key schedule
@param [in] nr - Number of encryption rounds to perform.
*/
void aes_256_ecb_encrypt (
uint8_t ct [AES_BLOCK_BYTES],
uint8_t pt [AES_BLOCK_BYTES],
uint32_t * rk
);
/*!
@brief single-block AES 128 decrypt function
@param [out] pt - Output plaintext
@param [in] ct - Input cipher text
@param [in] rk - The expanded key schedule
@param [in] nr - Number of decryption rounds to perform.
*/
void aes_128_ecb_decrypt (
uint8_t pt [AES_BLOCK_BYTES],
uint8_t ct [AES_BLOCK_BYTES],
uint32_t * rk
);
/*!
@brief single-block AES 192 decrypt function
@param [out] pt - Output plaintext
@param [in] ct - Input cipher text
@param [in] rk - The expanded key schedule
@param [in] nr - Number of decryption rounds to perform.
*/
void aes_192_ecb_decrypt (
uint8_t pt [AES_BLOCK_BYTES],
uint8_t ct [AES_BLOCK_BYTES],
uint32_t * rk
);
/*!
@brief single-block AES 256 decrypt function
@param [out] pt - Output plaintext
@param [in] ct - Input cipher text
@param [in] rk - The expanded key schedule
@param [in] nr - Number of decryption rounds to perform.
*/
void aes_256_ecb_decrypt (
uint8_t pt [AES_BLOCK_BYTES],
uint8_t ct [AES_BLOCK_BYTES],
uint32_t * rk
);
#endif
//! @}
|
dc511fe0e2e6ba939ea33d99b563492642911e2b
|
3fb927c4e75708324ca65835d7f108cc809936c0
|
/book/code/c_163_01.c
|
7c303560b86209f902f3984423d46e7fd5428efb
|
[
"LicenseRef-scancode-public-domain",
"CC-BY-4.0",
"Apache-2.0"
] |
permissive
|
csev/cc4e
|
f5d355ab37e495d7807916a031bcbec9e2d77b23
|
8ea00f27dfcb9c080263b9a87cbb2a833ce758ae
|
refs/heads/master
| 2023-08-09T21:55:53.990191
| 2023-08-01T08:11:24
| 2023-08-01T08:11:24
| 226,528,307
| 170
| 60
|
NOASSERTION
| 2023-08-02T15:55:02
| 2019-12-07T14:37:23
|
C++
|
UTF-8
|
C
| false
| false
| 728
|
c
|
c_163_01.c
|
#include <stdio.h>
#include <stdlib.h>
#define BUFSIZE 512
#define PMODE 0644 /* RW for owner, R for group, others */
main(argc, argv) /* cp: copy f1 to f2 */
int argc;
char *argv[];
{
int f1, f2, n;
char buf[BUFSIZE];
if (argc != 3)
error("Usage: cp from to", NULL);
if ((f1 = open(argv[1], 0)) == -1)
error("cp: can't open %s", argv[1]);
if ((f2 = creat(argv[2], PMODE)) == -1)
error("cp: can't create %s", argv[2]);
while ((n = read(f1, buf, BUFSIZE)) > 0)
if (write(f2, buf, n) != n)
error("cp: write error", NULL);
exit(0);
}
error(s1, s2) /* print error message and die */
char *s1, *s2;
{
printf(s1, s2);
printf("\n");
exit(1);
}
|
8c2d7de55335381a3f6908d4d90a01663bbbfb40
|
e910318d01528d82040507a49eeeb8dade45b31f
|
/ports/nrf/boards/microbit/modules/microbitimage.h
|
41a6aff4ccd145fd41828c5eac1134cbbbe5305d
|
[
"MIT"
] |
permissive
|
pfalcon/pycopy
|
e844480a5e5cd463530328889daed2ba87552b8a
|
3ac90ae9c3c6bbebfba9cada2d37025e35c62796
|
refs/heads/pfalcon
| 2023-08-30T09:39:52.290147
| 2022-09-08T16:42:38
| 2022-09-08T16:42:38
| 15,507,576
| 753
| 71
|
MIT
| 2021-05-08T04:59:21
| 2013-12-29T11:38:47
|
C
|
UTF-8
|
C
| false
| false
| 3,843
|
h
|
microbitimage.h
|
#ifndef __MICROPY_INCLUDED_MICROBIT_IMAGE_H__
#define __MICROPY_INCLUDED_MICROBIT_IMAGE_H__
#include "py/runtime.h"
#define MAX_BRIGHTNESS 9
/** Monochrome images are immutable, which means that
* we only need one bit per pixel which saves quite a lot
* of memory */
/* we reserve a couple of bits, so we won't need to modify the
* layout if we need to add more functionality or subtypes. */
#define TYPE_AND_FLAGS \
mp_obj_base_t base; \
uint8_t five:1; \
uint8_t reserved1:1; \
uint8_t reserved2:1
typedef struct _image_base_t {
TYPE_AND_FLAGS;
} image_base_t;
typedef struct _monochrome_5by5_t {
TYPE_AND_FLAGS;
uint8_t pixel44: 1;
uint8_t bits24[3];
} monochrome_5by5_t;
/* This is an internal method it is up to the caller to validate the inputs */
uint8_t monochromeGetPixelValue(monochrome_5by5_t * p_mono, mp_int_t x, mp_int_t y);
typedef struct _greyscale_t {
TYPE_AND_FLAGS;
uint8_t height;
uint8_t width;
uint8_t byte_data[]; /* Static initializer for this will have to be C, not C++ */
} greyscale_t;
#if 1
void clear(greyscale_t * p_greyscale);
/* Thiese are internal methods and it is up to the caller to validate the inputs */
uint8_t greyscaleGetPixelValue(greyscale_t * p_greyscale, mp_int_t x, mp_int_t y);
void greyscaleSetPixelValue(greyscale_t * p_greyscale, mp_int_t x, mp_int_t y, mp_int_t val);
void greyscaleFill(greyscale_t * p_greyscale, mp_int_t val);
#endif
typedef union _microbit_image_obj_t {
image_base_t base;
monochrome_5by5_t monochrome_5by5;
greyscale_t greyscale;
} microbit_image_obj_t;
#if 1
mp_int_t imageHeight(microbit_image_obj_t * p_image_obj);
mp_int_t imageWidth(microbit_image_obj_t * p_image_obj);
greyscale_t * imageCopy(microbit_image_obj_t * p_image_obj);
greyscale_t * imageInvert(microbit_image_obj_t * p_image_obj);
/* This is an internal method it is up to the caller to validate the inputs */
uint8_t imageGetPixelValue(microbit_image_obj_t * p_image_obj, mp_int_t x, mp_int_t y);
#endif
/** Return a facade object that presents the string as a sequence of images */
mp_obj_t microbit_string_facade(mp_obj_t string);
void microbit_image_set_from_char(greyscale_t *img, char c);
microbit_image_obj_t *microbit_image_for_char(char c);
mp_obj_t microbit_image_slice(microbit_image_obj_t *img, mp_int_t start, mp_int_t width, mp_int_t stride);
/* ref exists so that we can pull a string out of an object and not have it GC'ed while oterating over it */
mp_obj_t scrolling_string_image_iterable(const char* str, mp_uint_t len, mp_obj_t ref, bool monospace, bool repeat);
#define SMALL_IMAGE(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p44) \
{ \
{ µbit_image_type }, \
1, 0, 0, (p44), \
{ \
(p0)|((p1)<<1)|((p2)<<2)|((p3)<<3)|((p4)<<4)|((p5)<<5)|((p6)<<6)|((p7)<<7), \
(p8)|((p9)<<1)|((p10)<<2)|((p11)<<3)|((p12)<<4)|((p13)<<5)|((p14)<<6)|((p15)<<7), \
(p16)|((p17)<<1)|((p18)<<2)|((p19)<<3)|((p20)<<4)|((p21)<<5)|((p22)<<6)|((p23)<<7) \
} \
}
extern const monochrome_5by5_t microbit_blank_image;
extern const monochrome_5by5_t microbit_const_image_heart_obj;
extern const mp_obj_type_t microbit_image_type;
#define BLANK_IMAGE (microbit_image_obj_t *)(µbit_blank_image)
#define HEART_IMAGE (microbit_image_obj_t *)(µbit_const_image_heart_obj)
#define HAPPY_IMAGE (microbit_image_obj_t *)(µbit_const_image_happy_obj)
#if MICROPY_PY_BUILTINS_FLOAT
microbit_image_obj_t *microbit_image_dim(microbit_image_obj_t *lhs, mp_float_t fval);
#else
microbit_image_obj_t *microbit_image_dim(microbit_image_obj_t *lhs, mp_int_t val);
#endif
microbit_image_obj_t *microbit_image_sum(microbit_image_obj_t *lhs, microbit_image_obj_t *rhs, bool add);
#endif // __MICROPY_INCLUDED_MICROBIT_IMAGE_H__
|
1de31d47c9636326a13a966b5928bbf0217f91a3
|
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
|
/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusTest_AOD.C
|
3ad0dee80e1e942ebc8fee3a115880dc970b8883
|
[] |
permissive
|
alisw/AliPhysics
|
91bf1bd01ab2af656a25ff10b25e618a63667d3e
|
5df28b2b415e78e81273b0d9bf5c1b99feda3348
|
refs/heads/master
| 2023-08-31T20:41:44.927176
| 2023-08-31T14:51:12
| 2023-08-31T14:51:12
| 61,661,378
| 129
| 1,150
|
BSD-3-Clause
| 2023-09-14T18:48:45
| 2016-06-21T19:31:29
|
C++
|
UTF-8
|
C
| false
| false
| 39,957
|
c
|
ConfigKStarPlusMinusTest_AOD.C
|
/*=================================================================================
Dukhishyam Mallick - last modified 02, 2021 (mallick.dukhishyam@cern.ch)
*** Configuration script for K*+-->K0Short-Pi analysis ***
=======================================================================================*/
// A configuration script for RSN package needs to define the followings:
//
// (1) decay tree of each resonance to be studied, which is needed to select
// true pairs and to assign the right mass to all candidate daughters
// (2) cuts at all levels: single daughters, tracks, events
// (3) output objects: histograms or trees
#ifdef __CLING__
R__ADD_INCLUDE_PATH($ALICE_PHYSICS)
#include <PWGLF/RESONANCES/macros/mini/AddMonitorOutput.C>
#endif
Bool_t ConfigKStarPlusMinusTest_AOD
(
AliRsnMiniAnalysisTask *task,
Bool_t isMC,
Float_t piPIDCut,
Float_t nsigmaTOF,
Int_t customQualityCutsID=AliRsnCutSetDaughterParticle::kDisableCustom,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
Float_t pi_k0s_PIDCut,
Bool_t enableMonitor=kTRUE,
TString monitorOpt="",
Bool_t UseArmentousCut,
Float_t ArmentousParameter,
Float_t massTol,
Float_t massTolVeto,
Int_t tol_switch,
Double_t tol_sigma,
Float_t pLife,
Float_t radiuslow,
Bool_t Switch,
Float_t k0sDCA,
Float_t k0sCosPoinAn,
Float_t k0sDaughDCA,
Int_t NTPCcluster,
const char *suffix,
AliRsnCutSet *PairCutsSame,
AliRsnCutSet *PairCutsMix,
Float_t DCAxy,
Bool_t enableSys,
Float_t crossedRows,
Float_t rowsbycluster,
Int_t Sys,
Int_t imbin,
Float_t limbin,
Float_t himbin,
Int_t ptbin,
Float_t lptbin,
Float_t hptbin,
Int_t multbin,
Float_t lmultbin,
Float_t hmultbin,
Int_t aodFilterBit=5
//UInt_t triggerMask=AliVEvent::kINT7
)
//kTPCpidphipp2015
{
// manage suffix
if (strlen(suffix) > 0) suffix = Form("_%s", suffix);
Bool_t isRotate=1;
Float_t v0rapidity=0.5;
if (isMC)
Bool_t isDATA=kFALSE;
else
Bool_t isDATA=kTRUE;
/////////////////////////////////////////////////////
// selections for the pion from the decay of KStarPlusMinus*
/////////////////////////////////////////////////////
//
AliRsnCutSetDaughterParticle* cutSetQ;
AliRsnCutSetDaughterParticle* cutSetPi;
AliRsnCutTrackQuality* trkQualityCut= new AliRsnCutTrackQuality("myQualityCut");
// cout<<"Value of custom quality--------------------"<<customQualityCutsID<<endl;
if(SetCustomQualityCut(trkQualityCut,customQualityCutsID,aodFilterBit)){
//Set custom quality cuts for systematic checks
cutSetQ=new AliRsnCutSetDaughterParticle(Form("cutQ_bit%i",aodFilterBit),trkQualityCut,AliRsnCutSetDaughterParticle::kQualityStd2011,AliPID::kPion,-1.);
cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigma",cutPiCandidate, piPIDCut,nsigmaTOF),trkQualityCut,cutPiCandidate,AliPID::kPion,piPIDCut,nsigmaTOF);
}else{
//use default quality cuts std 2010 with crossed rows TPC
Bool_t useCrossedRows = 1;
cutSetQ=new AliRsnCutSetDaughterParticle(Form("cutQ_bit%i",aodFilterBit),AliRsnCutSetDaughterParticle::kQualityStd2011,AliPID::kPion,-1.,aodFilterBit,kTRUE);
cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigma",cutPiCandidate,piPIDCut,nsigmaTOF),cutPiCandidate,AliPID::kPion,piPIDCut,nsigmaTOF,aodFilterBit, kTRUE);
}
Int_t iCutQ=task->AddTrackCuts(cutSetQ);
Int_t iCutPi=task->AddTrackCuts(cutSetPi);
/////////////////////////////////////////////////////////////
// selections for K0s and for the daughters of K0s
/////////////////////////////////////////////////////////////
//
// selections for pion daugthers of K0s
AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("qualityDaughterK0s");
esdTrackCuts->SetEtaRange(-0.8,0.8);
esdTrackCuts->SetRequireTPCRefit();
esdTrackCuts->SetAcceptKinkDaughters(0); //
esdTrackCuts->SetMinNCrossedRowsTPC(crossedRows);
esdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(rowsbycluster);
esdTrackCuts->SetMaxChi2PerClusterTPC(100);
esdTrackCuts->SetMinDCAToVertexXY(DCAxy); //Use one of the two - pt dependent or fixed value cut.
//
/////////////////////////////////////////////////
// selections for K0s
AliRsnCutV0 *cutK0s = new AliRsnCutV0("cutK0s", kK0Short, AliPID::kPion, AliPID::kPion);
cutK0s->SetPIDCutPion(pi_k0s_PIDCut); // PID for the pion daughter of K0s
cutK0s->SetESDtrackCuts(esdTrackCuts);
cutK0s->SetMaxDaughtersDCA(k0sDaughDCA);
cutK0s->SetMaxDCAVertex(k0sDCA);
cutK0s->SetMinCosPointingAngle(k0sCosPoinAn);
cutK0s->SetfLife(pLife);
cutK0s->SetfLowRadius(radiuslow);
cutK0s->SetfHighRadius(100);
cutK0s->SetMaxRapidity(v0rapidity);
if (!UseArmentousCut)
{
cutK0s->SetTolerance(massTol);
cutK0s->SetToleranceVeto(massTolVeto); //Rejection range for Competing V0 Rejection
cutK0s->SetSwitch(Switch);
cutK0s->SetpT_Tolerance(tol_switch);
cutK0s->SetMassTolSigma(tol_sigma);
}
else
{
cutK0s->SetMaxArmentousCut(ArmentousParameter);
// cout<<"Get Input Value Of Armentous cut-------->:"<<cutK0s->GetMaxArmentousCut()<<endl;
}
if(enableSys)
{
if(Sys==1){cutK0s->SetPIDCutPion(pi_k0s_PIDCut-0.5);}
else if(Sys==2){cutK0s->SetPIDCutPion(pi_k0s_PIDCut-1.0);}
else if(Sys==3){cutK0s->SetMaxDaughtersDCA(k0sDaughDCA-0.25);}
else if(Sys==4){cutK0s->SetMaxDaughtersDCA(k0sDaughDCA+0.25);}
else if(Sys==5){cutK0s->SetMinCosPointingAngle(k0sCosPoinAn-0.02);}
else if(Sys==6){cutK0s->SetMinCosPointingAngle(k0sCosPoinAn+0.02);}
else if(Sys==7){cutK0s->SetTolerance(massTol+1);}
else if(Sys==8){cutK0s->SetTolerance(massTol+2);}
else if(Sys==9){cutK0s->SetTolerance(massTol-1);}
else if(Sys==10){cutK0s->SetfLife(pLife-8);}
else if(Sys==11){cutK0s->SetfLowRadius(radiuslow-0.2);}
else if(Sys==12){cutK0s->SetfLowRadius(radiuslow+0.2);}
else if(Sys==13){cutK0s->SetMaxRapidity(v0rapidity-0.1);}
else if(Sys==14){cutK0s->SetMaxRapidity(v0rapidity+0.1);}
else if(Sys==15){cutK0s->SetToleranceVeto(massTolVeto-0.0011);}
else if(Sys==16){cutK0s->SetToleranceVeto(massTolVeto+0.0011);}
else if(Sys==17){esdTrackCuts->SetMinDCAToVertexXY(DCAxy-0.01);}
else if(Sys==18){esdTrackCuts->SetMinDCAToVertexXY(DCAxy+0.01);}
else if(Sys==19){esdTrackCuts->SetMinNCrossedRowsTPC(crossedRows+10);}
else if(Sys==20){esdTrackCuts->SetMinNCrossedRowsTPC(crossedRows+30);}
else if(Sys==21){esdTrackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(rowsbycluster+0.1);}
}
AliRsnCutSet *cutSetK0s = new AliRsnCutSet("setK0s", AliRsnTarget::kDaughter);
cutSetK0s->AddCut(cutK0s);
cutSetK0s->SetCutScheme(cutK0s->GetName());
Int_t iCutK0s = task->AddTrackCuts(cutSetK0s);
//
if(enableMonitor){
Printf("======== Cut monitoring enabled");
#ifdef __CINT__
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/AddMonitorOutput.C");
#endif
AddMonitorOutput(isMC, cutSetQ->GetMonitorOutput(), monitorOpt.Data());
AddMonitorOutput(isMC, cutSetPi->GetMonitorOutput(), monitorOpt.Data());
}
//
// -- Values ------------------------------------------------------------------------------------
//
/// -- Values ------------------------------------------------------------------------------------
/* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE);
/* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE);
/* centrality */ Int_t centID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
/* pseudorapidity */ Int_t etaID = task->CreateValue(AliRsnMiniValue::kEta, kFALSE);
/* rapidity */ Int_t yID = task->CreateValue(AliRsnMiniValue::kY, kFALSE);
/* CosThetaStar */ Int_t cosThStarID = task->CreateValue(AliRsnMiniValue::kCosThetaStar,kFALSE);
/* 1st daughter pt */ Int_t fdpt = task->CreateValue(AliRsnMiniValue::kFirstDaughterPt,kFALSE);
/* 2nd daughter pt */ Int_t sdpt = task->CreateValue(AliRsnMiniValue::kSecondDaughterPt,kFALSE);
/* 1st daughter p */ Int_t fdp = task->CreateValue(AliRsnMiniValue::kFirstDaughterP,kFALSE);
/* 2nd daughter p */ Int_t sdp = task->CreateValue(AliRsnMiniValue::kSecondDaughterP,kFALSE);
/* cos(theta) J */ Int_t ctjID = task->CreateValue(AliRsnMiniValue::kCosThetaJackson,kFALSE);
/* cos(theta) J (MC)*/ Int_t ctjmID = task->CreateValue(AliRsnMiniValue::kCosThetaJackson,kTRUE);
/* cos(theta) T */ Int_t cttID = task->CreateValue(AliRsnMiniValue::kCosThetaTransversity,kFALSE);
/* cos(theta) T (MC)*/ Int_t cttmID = task->CreateValue(AliRsnMiniValue::kCosThetaTransversity,kTRUE);
//
// -- Create all needed outputs -----------------------------------------------------------------
//
Bool_t use [10] = {isDATA ,isDATA ,isDATA ,isDATA ,isMC ,isMC ,isMC , isMC ,isMC ,isMC};
Bool_t useIM [10] = {1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 };
TString name [10] = {"KStarPlusMinus","AKStarPlusMinus","KStarPlusMinusmix","AKStarPlusMinusmix","KStarPlusMinust","AKStarPlusMinust", "KStarPlusMinusMotherMC", "AKStarPlusMinusMotherMC", "KStarPlusMinusMotherMCNOPU", "AKStarPlusMinusMotherMCNOPU" };
TString comp [10] = {"PAIR" ,"PAIR" ,"MIX" ,"MIX" ,"TRUE" ,"TRUE", "MOTHER", "MOTHER", "MOTHER_NO_PILEUP", "MOTHER_NO_PILEUP" };
TString output [10] = {"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" ,"SPARSE" , "SPARSE" ,"SPARSE" };
Char_t charge1 [10] = {'0' ,'0' ,'0' ,'0' ,'0' ,'0' ,'0' ,'0' ,'0' ,'0'};
Char_t charge2 [10] = {'0' ,'0' ,'0' ,'0' ,'0' ,'0' , '0' ,'0' , '0' ,'0'};
Int_t cutID1 [10] = { iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s};
Int_t cutID2 [10] = { iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s ,iCutK0s };
Int_t ipdg [10] = {10331 ,10331 ,10331 ,10331 ,10331 ,10331 ,10331 ,10331 ,10331 ,10331 };
Double_t mass [10] = { 1.710 ,1.710 ,1.710 ,1.710 ,1.710 ,1.710 ,1.710 ,1.710 ,1.710 ,1.710 };
AliRsnCutSet* paircuts[10] = {PairCutsSame, PairCutsSame, PairCutsMix, PairCutsMix, PairCutsSame, PairCutsSame ,PairCutsSame ,PairCutsSame ,PairCutsSame ,PairCutsSame };
for (Int_t i = 0; i < 10; i++) {
if (!use[i]) continue;
// create output
AliRsnMiniOutput *out = task->CreateOutput(Form("ChargeKstar_%s%s", name[i].Data(), suffix), output[i].Data(), comp[i].Data());
// selection settings
out->SetCutID(0, cutID1[i]);
out->SetCutID(1, cutID2[i]);
out->SetDaughter(0, AliRsnDaughter::kKaon0);
out->SetDaughter(1, AliRsnDaughter::kKaon0);
out->SetCharge(0, charge1[i]);
out->SetCharge(1, charge2[i]);
out->SetMotherPDG(ipdg[i]);
out->SetMotherMass(mass[i]);
// pair cuts
out->SetPairCuts(paircuts[i]);
// axis X: invmass
if (useIM[i])
out->AddAxis(imID, imbin, limbin, himbin);
// axis Y: transverse momentum
out->AddAxis(ptID, ptbin, lptbin, hptbin);
// axis W: Centrality
out->AddAxis(centID, multbin, lmultbin, hmultbin);
}
// AddMonitorOutput_K0sP(cutSetK0s->GetMonitorOutput());
******************commentout*******************************/
if (!isMC)
{
AddMonitorOutput_K0sPt(cutSetK0s->GetMonitorOutput());
AddMonitorOutput_K0sNegDaughPt(cutSetK0s->GetMonitorOutput());
AddMonitorOutput_K0sPosDaughPt(cutSetK0s->GetMonitorOutput());
AddMonitorOutput_K0sMass(cutSetK0s->GetMonitorOutput());
AddMonitorOutput_K0sDCA(cutSetK0s->GetMonitorOutput());
AddMonitorOutput_K0sRadius(cutSetK0s->GetMonitorOutput());
AddMonitorOutput_K0sDaughterDCA(cutSetK0s->GetMonitorOutput());
AddMonitorOutput_K0sCosPointAngle(cutSetK0s->GetMonitorOutput());
//added by me/////////
//AddMonitorOutput_ArmentousCut(cutSetK0s->GetMonitorOutput());
////////////////////////
// AddMonitorOutput_K0sProtonPID(cutSetK0s->GetMonitorOutput());
AddMonitorOutput_K0sPionPID(cutSetK0s->GetMonitorOutput());
AddMonitorOutput_K0sfpLife(cutSetK0s->GetMonitorOutput());
AddMonitorOutput_K0sMass_Pt(cutSetK0s->GetMonitorOutput());
}
//cutK0s->Print();
if (isDATA)
{
if(isRotate){
for (Int_t i = 0; i < 2; i++)
{ if (!use[i]) continue;
//if (collSyst) output[i] = "SPARSE";
AliRsnMiniOutput *out = task->CreateOutput(Form("ChargeKstar_Rotated_%s%s", name[i].Data(), suffix), output[i].Data(), "ROTATE2");
out->SetCutID(0, cutID1[i]);
out->SetCutID(1, cutID2[i]);
out->SetDaughter(0, AliRsnDaughter::kKaon0);
out->SetDaughter(1, AliRsnDaughter::kKaon0);
out->SetCharge(0, charge1[i]);
out->SetCharge(1, charge2[i]);
out->SetMotherPDG(ipdg[i]);
out->SetMotherMass(mass[i]);
// pair cuts
out->SetPairCuts(PairCutsSame);
if (useIM[i]) out->AddAxis(imID, imbin, limbin, himbin);
out->AddAxis(ptID, ptbin, lptbin, hptbin);
out->AddAxis(centID, multbin, lmultbin, hmultbin);
}
}
}
return kTRUE;
}
Bool_t SetCustomQualityCut(AliRsnCutTrackQuality * trkQualityCut, Int_t customQualityCutsID = 0, Int_t customFilterBit = 0)
{
//Sets configuration for track quality object different from std quality cuts.
//Returns kTRUE if track quality cut object is successfully defined,
//returns kFALSE if an invalid set of cuts (customQualityCutsID) is chosen or if the
//object to be configured does not exist.
if ((!trkQualityCut)){
Printf("::::: SetCustomQualityCut:: use default quality cuts specified in task configuration.");
return kFALSE;
}
// cout<<"************value of customQualityCutsID and customFilterBit*************:"<<customQualityCutsID<<" "<<customFilterBit<<endl;
if(customQualityCutsID>=1 && customQualityCutsID<100 && customQualityCutsID!=2){
trkQualityCut->SetDefaults2011(kTRUE,kTRUE);
Printf(Form("::::: SetCustomQualityCut:: using standard 2011 track quality cuts"));
if(!customFilterBit){//ESD
if(customQualityCutsID==3){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.0150+0.0500/pt^1.1");}
else if(customQualityCutsID==4){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXYPtDep("0.006+0.0200/pt^1.1");}
else if(customQualityCutsID==5){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(5.);}
else if(customQualityCutsID==6){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(0.2);}
else if(customQualityCutsID==7){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(5.);}
else if(customQualityCutsID==8){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(2.3);}
else if(customQualityCutsID==9){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(60);}
else if(customQualityCutsID==10){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(100);}
else if(customQualityCutsID==11){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.7);}
else if(customQualityCutsID==12){trkQualityCut->GetESDtrackCuts()->SetMinRatioCrossedRowsOverFindableClustersTPC(0.9);}
else if(customQualityCutsID==13){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(49.);}
else if(customQualityCutsID==14){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(4.);}
else if(customQualityCutsID==15){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(49.);}
else if(customQualityCutsID==16){trkQualityCut->GetESDtrackCuts()->SetMaxChi2TPCConstrainedGlobal(25.);}
else if(customQualityCutsID==17){trkQualityCut->GetESDtrackCuts()->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kOff);}
else if(customQualityCutsID==56){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(1.);}
else if(customQualityCutsID==58){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(3.);}
else if(customQualityCutsID==60){trkQualityCut->GetESDtrackCuts()->SetMinNCrossedRowsTPC(80);}
else if(customQualityCutsID==64){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterITS(25.);}
}else{//AOD
trkQualityCut->SetCheckOnlyFilterBit(kFALSE);
if(customQualityCutsID==4){trkQualityCut->SetDCARPtFormula("0.006+0.0200/pt^1.1");}
else if(customQualityCutsID==6){trkQualityCut->SetDCAZmax(0.2);}
else if(customQualityCutsID==8){trkQualityCut->SetTrackMaxChi2(2.3);}
else if(customQualityCutsID==10){trkQualityCut->SetMinNCrossedRowsTPC(100,kTRUE);}
else if(customQualityCutsID==12){trkQualityCut->SetMinNCrossedRowsOverFindableClsTPC(0.9,kTRUE);}
else if(customQualityCutsID==56){trkQualityCut->SetDCAZmax(1.);}
else if(customQualityCutsID==58){trkQualityCut->SetTrackMaxChi2(3.5);}
else if(customQualityCutsID==60){trkQualityCut->SetMinNCrossedRowsTPC(80,kTRUE);}
}
trkQualityCut->Print();
return kTRUE;
}else if(customQualityCutsID==2 || (customQualityCutsID>=100 && customQualityCutsID<200)){
trkQualityCut->SetDefaultsTPCOnly(kTRUE);
Printf(Form("::::: SetCustomQualityCut:: using TPC-only track quality cuts"));
if(customQualityCutsID==103){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXY(3.);}
else if(customQualityCutsID==104){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexXY(1.);}
else if(customQualityCutsID==105){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(4.);}
else if(customQualityCutsID==106){trkQualityCut->GetESDtrackCuts()->SetMaxDCAToVertexZ(1.);}
else if(customQualityCutsID==107){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(7.);}
else if(customQualityCutsID==108){trkQualityCut->GetESDtrackCuts()->SetMaxChi2PerClusterTPC(2.5);}
else if(customQualityCutsID==109){trkQualityCut->GetESDtrackCuts()->SetMinNClustersTPC(30);}
else if(customQualityCutsID==110){trkQualityCut->GetESDtrackCuts()->SetMinNClustersTPC(85);}
trkQualityCut->Print();
return kTRUE;
}else{
Printf("::::: SetCustomQualityCut:: use default quality cuts specified in task configuration.");
return kFALSE;
}
//for pA 2013
//trkQualityCut->SetDefaults2011();//with filter bit=10
//reset filter bit to very loose cuts
trkQualityCut->SetAODTestFilterBit(customFilterBit);
//apply all other cuts "by hand"
trkQualityCut->SetCheckOnlyFilterBit(kFALSE);
trkQualityCut->SetMinNCrossedRowsTPC(70, kTRUE);
trkQualityCut->SetMinNCrossedRowsOverFindableClsTPC(0.8, kTRUE);
trkQualityCut->SetMaxChi2TPCConstrainedGlobal(36);//used for ESD only - for AOD does not correspond to any cut
trkQualityCut->SetTPCmaxChi2(4.0); //already in filter bit 0
trkQualityCut->SetRejectKinkDaughters(kTRUE); //already in filter bit 0
trkQualityCut->SetSPDminNClusters(AliESDtrackCuts::kAny);
trkQualityCut->SetITSmaxChi2(36);
trkQualityCut->AddStatusFlag(AliESDtrack::kTPCin , kTRUE);//already in defaults 2011
trkQualityCut->AddStatusFlag(AliESDtrack::kTPCrefit, kTRUE);//already in defaults 2011
trkQualityCut->AddStatusFlag(AliESDtrack::kITSrefit, kTRUE);//already in defaults 2011
if (customQualityCutsID==AliRsnCutSetDaughterParticle::kFilterBitCustom) {
trkQualityCut->SetCheckOnlyFilterBit(kTRUE);
}
if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdLooserDCAXY){
trkQualityCut->SetDCARmax(2.4);
} else {
trkQualityCut->SetDCARPtFormula("0.0105+0.0350/pt^1.1");
}
if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdLooserDCAZ){
trkQualityCut->SetDCAZmax(3.2);
} else {
trkQualityCut->SetDCAZmax(2.0);
}
if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdCrossedRows60){
trkQualityCut->SetMinNCrossedRowsTPC(60, kTRUE);
}
if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdCrossedRows80){
trkQualityCut->SetMinNCrossedRowsTPC(80, kTRUE);
}
if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdRowsToCls075){
trkQualityCut->SetMinNCrossedRowsOverFindableClsTPC(0.75, kTRUE);
}
if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdRowsToCls085){
trkQualityCut->SetMinNCrossedRowsOverFindableClsTPC(0.85, kTRUE);
}
if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdCls70){
trkQualityCut->SetAODTestFilterBit(10);
trkQualityCut->SetTPCminNClusters(70);
}
if (customQualityCutsID==AliRsnCutSetDaughterParticle::kStdChi2TPCCls35){
trkQualityCut->SetTPCmaxChi2(3.5);
}
trkQualityCut->SetPtRange(0.15, 30.0);
trkQualityCut->SetEtaRange(-0.8, 0.8);
Printf(Form("::::: SetCustomQualityCut:: using custom track quality cuts #%i",customQualityCutsID));
trkQualityCut->Print();
return kTRUE;
}
void AddMonitorOutput_PionPt(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *ppt=0)
{
// PionPt
AliRsnValueDaughter *axisPionPt = new AliRsnValueDaughter("pion_pt", AliRsnValueDaughter::kPt);
axisPionPt->SetBins(0.,10.0,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorPionPt = new AliRsnListOutput("Pion_Pt", AliRsnListOutput::kHistoDefault);
outMonitorPionPt->AddValue(axisPionPt);
// add outputs to loop
if (mon) mon->Add(outMonitorPionPt);
if (ppt) ppt->AddOutput(outMonitorPionPt);
}
void AddMonitorOutput_PionEta(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *peta=0)
{
// PionDCA
AliRsnValueDaughter *axisPionEta = new AliRsnValueDaughter("pion_eta", AliRsnValueDaughter::kEta);
axisPionEta->SetBins(-2.,2.,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorPionEta = new AliRsnListOutput("Pion_Eta", AliRsnListOutput::kHistoDefault);
outMonitorPionEta->AddValue(axisPionEta);
// add outputs to loop
if (mon) mon->Add(outMonitorPionEta);
if (peta) peta->AddOutput(outMonitorPionEta);
}
void AddMonitorOutput_PionDCAxy(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *pdcaxy=0)
{
// PionDCA
AliRsnValueDaughter *axisPionDCAxy = new AliRsnValueDaughter("pion_dcaxy", AliRsnValueDaughter::kDCAXY);
axisPionDCAxy->SetBins(-0.5,0.5,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorPionDCAxy = new AliRsnListOutput("Pion_DCAxy", AliRsnListOutput::kHistoDefault);
outMonitorPionDCAxy->AddValue(axisPionDCAxy);
// add outputs to loop
if (mon) mon->Add(outMonitorPionDCAxy);
if (pdcaxy) pdcaxy->AddOutput(outMonitorPionDCAxy);
}
void AddMonitorOutput_PionDCAz(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *pdcaz=0)
{
// PionDCA
AliRsnValueDaughter *axisPionDCAz = new AliRsnValueDaughter("pion_dcaz", AliRsnValueDaughter::kDCAZ);
axisPionDCAz->SetBins(-2.5,2.5,0.005);
// output: 2D histogram
AliRsnListOutput *outMonitorPionDCAz = new AliRsnListOutput("Pion_DCAz", AliRsnListOutput::kHistoDefault);
outMonitorPionDCAz->AddValue(axisPionDCAz);
// add outputs to loop
if (mon) mon->Add(outMonitorPionDCAz);
if (pdcaz) pdcaz->AddOutput(outMonitorPionDCAz);
}
void AddMonitorOutput_PionPIDCut(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *piPID=0)
{
// Pion PID Cut
AliRsnValueDaughter *axisPionPIDCut = new AliRsnValueDaughter("pionPID", AliRsnValueDaughter::kTPCnsigmaPi);
axisPionPIDCut->SetBins(0.0,5,0.01);
// output: 2D histogram
AliRsnListOutput *outMonitorPionPIDCut = new AliRsnListOutput("Pion_PID_Cut", AliRsnListOutput::kHistoDefault);
outMonitorPionPIDCut->AddValue(axisPionPIDCut);
// add outputs to loop
if (mon) mon->Add(outMonitorPionPIDCut);
if (piPID) piPID->AddOutput(outMonitorPionPIDCut);
}
void AddMonitorOutput_PionNTPC(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *piNTPC=0)
{
// Pion PID Cut
AliRsnValueDaughter *axisPionNTPC = new AliRsnValueDaughter("pionNTPC", AliRsnValueDaughter::kNTPCclusters);
axisPionNTPC->SetBins(0.0,200,1);
// output: 2D histogram
AliRsnListOutput *outMonitorPionNTPC = new AliRsnListOutput("Pion_NTPC", AliRsnListOutput::kHistoDefault);
outMonitorPionNTPC->AddValue(axisPionNTPC);
// add outputs to loop
if (mon) mon->Add(outMonitorPionNTPC);
if (piNTPC) pNTPC->AddOutput(outMonitorPionNTPC);
}
void AddMonitorOutput_PionTPCchi2(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *piTPCchi2=0)
{
// Pion PID Cut
AliRsnValueDaughter *axisPionTPCchi2 = new AliRsnValueDaughter("pionTPCchi2", AliRsnValueDaughter::kTPCchi2);
axisPionTPCchi2->SetBins(0.0,6,.1);
// output: 2D histogram
AliRsnListOutput *outMonitorPionTPCchi2 = new AliRsnListOutput("Pion_TPCchi2", AliRsnListOutput::kHistoDefault);
outMonitorPionTPCchi2->AddValue(axisPionTPCchi2);
// add outputs to loop
if (mon) mon->Add(outMonitorPionTPCchi2);
if (piTPCchi2) pTPCchi2->AddOutput(outMonitorPionTPCchi2);
}
void AddMonitorOutput_K0sP(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lp=0)
{
AliRsnValueDaughter *axisK0sP = new AliRsnValueDaughter("k0s_momentum", AliRsnValueDaughter::kP);
axisK0sP->SetBins(0.,15.,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorMom = new AliRsnListOutput("K0s_Momentum", AliRsnListOutput::kHistoDefault);
outMonitorMom->AddValue(axisK0sP);
// add outputs to loop
if (mon) mon->Add(outMonitorMom);
if (lp) lp->AddOutput(outMonitorMom);
}
void AddMonitorOutput_K0sPt(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lpt=0)
{
// Pt
AliRsnValueDaughter *axisK0sPt = new AliRsnValueDaughter("k0s_transversemomentum", AliRsnValueDaughter::kV0Pt);
axisK0sPt->SetBins(0.,15.,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorTrMom = new AliRsnListOutput("K0s_TransverseMomentum", AliRsnListOutput::kHistoDefault);
outMonitorTrMom->AddValue(axisK0sPt);
// add outputs to loop
if (mon) mon->Add(outMonitorTrMom);
if (lpt) lpt->AddOutput(outMonitorTrMom);
}
void AddMonitorOutput_K0sNegDaughPt(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lnpt=0)
{
// Pt
AliRsnValueDaughter *axisK0sNegDaughPt = new AliRsnValueDaughter("k0s_negdaugh_transversemomentum", AliRsnValueDaughter::kV0NPt);
axisK0sNegDaughPt->SetBins(0.,15.,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorK0sNegDaughTrMom = new AliRsnListOutput("K0s_NegDaugh_TransverseMomentum", AliRsnListOutput::kHistoDefault);
outMonitorK0sNegDaughTrMom->AddValue(axisK0sNegDaughPt);
// add outputs to loop
if (mon) mon->Add(outMonitorK0sNegDaughTrMom);
if (lnpt) lnpt->AddOutput(outMonitorK0sNegDaughTrMom);
}
void AddMonitorOutput_K0sPosDaughPt(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lppt=0)
{
// Mass
AliRsnValueDaughter *axisK0sPosDaughPt = new AliRsnValueDaughter("k0s_posdaugh_transversemomentum", AliRsnValueDaughter::kV0PPt);
axisK0sPosDaughPt->SetBins(0.,15.,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorK0sPosDaughTrMom = new AliRsnListOutput("K0s_PosDaugh_TransverseMomentum", AliRsnListOutput::kHistoDefault);
outMonitorK0sPosDaughTrMom->AddValue(axisK0sPosDaughPt);
// add outputs to loop
if (mon) mon->Add(outMonitorK0sPosDaughTrMom);
if (lppt) lppt->AddOutput(outMonitorK0sPosDaughTrMom);
}
void AddMonitorOutput_K0sMass(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lm=0)
{
// Mass
AliRsnValueDaughter *axisMass = new AliRsnValueDaughter("k0s_mass", AliRsnValueDaughter::kV0Mass);
axisMass->SetBins(0.4,0.6,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorM = new AliRsnListOutput("K0s_Mass", AliRsnListOutput::kHistoDefault);
outMonitorM->AddValue(axisMass);
// add outputs to loop
if (mon) mon->Add(outMonitorM);
if (lm) lm->AddOutput(outMonitorM);
}
void AddMonitorOutput_K0sDCA(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *ldca=0)
{
// K0s DCA
AliRsnValueDaughter *axisK0sDCA = new AliRsnValueDaughter("k0s_dca", AliRsnValueDaughter::kV0DCA);
axisK0sDCA->SetBins(0.0,0.4,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorK0sDCA = new AliRsnListOutput("K0s_DCA", AliRsnListOutput::kHistoDefault);
outMonitorK0sDCA->AddValue(axisK0sDCA);
// add outputs to loop
if (mon) mon->Add(outMonitorK0sDCA);
if (ldca) ldca->AddOutput(outMonitorK0sDCA);
}
void AddMonitorOutput_K0sRadius(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *ldca=0)
{
// K0s Radius
AliRsnValueDaughter *axisK0sRadius = new AliRsnValueDaughter("k0s_radius", AliRsnValueDaughter::kV0Radius);
axisK0sRadius->SetBins(0.0,200,0.2);
// output: 2D histogram
AliRsnListOutput *outMonitorK0sRadius = new AliRsnListOutput("K0s_Radius", AliRsnListOutput::kHistoDefault);
outMonitorK0sRadius->AddValue(axisK0sRadius);
// add outputs to loop
if (mon) mon->Add(outMonitorK0sRadius);
if (ldca) ldca->AddOutput(outMonitorK0sRadius);
}
void AddMonitorOutput_K0sDaughterDCA(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *ldaugdca=0)
{
// K0s Daughter DCA
AliRsnValueDaughter *axisK0sDDCA = new AliRsnValueDaughter("k0s_daughterDCA", AliRsnValueDaughter::kDaughterDCA);
axisK0sDDCA->SetBins(0.0,2,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorK0sDDCA = new AliRsnListOutput("K0s_DaughterDCA", AliRsnListOutput::kHistoDefault);
outMonitorK0sDDCA->AddValue(axisK0sDDCA);
// add outputs to loop
if (mon) mon->Add(outMonitorK0sDDCA);
if (ldaugdca) ldaugdca->AddOutput(outMonitorK0sDDCA);
}
void AddMonitorOutput_K0sCosPointAngle(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lcpa=0)
{
// K0s Cosine of the Pointing Angle
AliRsnValueDaughter *axisK0sCPA = new AliRsnValueDaughter("k0s_cospointang", AliRsnValueDaughter::kCosPointAng);
//axisK0sCPA->SetBins(0.97,1.,0.0001);
axisK0sCPA->SetBins(0.9,1.,0.0001);
// output: 2D histogram
AliRsnListOutput *outMonitorK0sCPA = new AliRsnListOutput("K0s_CosineOfPointingAngle", AliRsnListOutput::kHistoDefault);
outMonitorK0sCPA->AddValue(axisK0sCPA);
// add outputs to loop
if (mon) mon->Add(outMonitorK0sCPA);
if (lcpa) lcpa->AddOutput(outMonitorK0sCPA);
}
//added by me /////////////////////////////////////////////////
/*
void AddMonitorOutput_ArmentousCut(TO
{
// K0s Arm Cut
AliRsnValueDaughter *axisK0sAC = new AliRsnValueDaughter("K0s_ArmCut", AliRsnValueDaughter::Armentous);
axisK0sAC->SetBins(-10.0,10.0,0.1);
// output: 2D histogram
AliRsnListOutput *outMonitorK0sAC = new AliRsnListOutput("K0s_ArmentousCut", AliRsnListOutput::kHistoDefault);
outMonitorK0sAC->AddValue(axisK0sAC);
// add outputs to loop
if (mon) mon->Add(outMonitorK0sAC);
if (lac) lac->AddOutput(outMonitorK0sAC);
}
*/
///////////////////////////////////////////////////////////////////
void AddMonitorOutput_K0sPionPID(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lpiPID=0)
{
AliRsnValueDaughter *axisK0sPionPID = new AliRsnValueDaughter("k0s_pionPID", AliRsnValueDaughter::kLambdaPionPIDCut);
axisK0sPionPID->SetBins(0.0,5,0.01);
// output: 2D histogram
AliRsnListOutput *outMonitorK0sPionPID = new AliRsnListOutput("K0s_PionPID", AliRsnListOutput::kHistoDefault);
outMonitorK0sPionPID->AddValue(axisK0sPionPID);
// add outputs to loop
if (mon) mon->Add(outMonitorK0sPionPID);
if (lpiPID) lpiPID->AddOutput(outMonitorK0sPionPID);
}
void AddMonitorOutput_K0sAntiPionPID(TObjArray *mon=0,TString opt="",AliRsnLoopDaughter *lapiPID=0)
{
AliRsnValueDaughter *axisK0sAntiPionPID = new AliRsnValueDaughter("k0s_antipionPID", AliRsnValueDaughter::kAntiLambdaAntiPionPIDCut);
axisK0sAntiPionPID->SetBins(0.0,5,0.01);
// output: 2D histogram
AliRsnListOutput *outMonitorK0sAntiPionPID = new AliRsnListOutput("K0s_AntiPionPID", AliRsnListOutput::kHistoDefault);
outMonitorK0sAntiPionPID->AddValue(axisK0sAntiPionPID);
// add outputs to loop
if (mon) mon->Add(outMonitorK0sAntiPionPID);
if (lapiPID) lpiPID->AddOutput(outMonitorK0sAntiPionPID);
}
void AddMonitorOutput_MinDCAToVertexXYPtDep(TObjArray *mon=0, TString opt="", AliRsnLoopDaughter *trackDCAXY=0)
{
// DCAXY of Tracks
AliRsnValueDaughter *axisDCATracks = new AliRsnValueDaughter("dcaXY_tracks", AliRsnValueDaughter::kV0DCAXY);
axisDCATracks->SetBins(0.0,2,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorDCATracks = new AliRsnListOutput("DCAXY_Tracks", AliRsnListOutput::kHistoDefault);
outMonitorDCATracks->AddValue(axisDCATracks);
// add outputs to loop
if (mon) mon->Add(outMonitorDCATracks);
if (trackDCAXY) trackDCAXY->AddOutput(outMonitorDCATracks);
}
// DCA V0 Secondary Tracks to Primary Vertex
void AddMonitorOutput_MinDCAToVertexXY(TObjArray *mon=0, TString opt="", AliRsnLoopDaughter *trackDCAXY=0)
{
// DCAXY of Tracks
AliRsnValueDaughter *axisDCATracks = new AliRsnValueDaughter("dcaXY_tracks", AliRsnValueDaughter::kV0DCAXY);
axisDCATracks->SetBins(0.0,2,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorDCATracks = new AliRsnListOutput("DCAXY_Tracks", AliRsnListOutput::kHistoDefault);
outMonitorDCATracks->AddValue(axisDCATracks);
// add outputs to loop
if (mon) mon->Add(outMonitorDCATracks);
if (trackDCAXY) trackDCAXY->AddOutput(outMonitorDCATracks);
}
// Lifetime of V0 particle.
void AddMonitorOutput_K0sfpLife(TObjArray *mon=0, TString opt="", AliRsnLoopDaughter *llifetime=0)
{
AliRsnValueDaughter *k0slifetime = new AliRsnValueDaughter("lifetime", AliRsnValueDaughter::kV0Lifetime);
k0slifetime->SetBins(0.0,200,0.1);
// output: 2D histogram
AliRsnListOutput *outMonitork0sLifetime = new AliRsnListOutput("k0s", AliRsnListOutput::kHistoDefault);
outMonitork0sLifetime->AddValue(k0slifetime);
// add outputs to loop
if (mon) mon->Add(outMonitork0sLifetime);
if (llifetime) llifetime->AddOutput(outMonitork0sLifetime);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void AddMonitorOutput_K0sMass_Pt(TObjArray *mon=0, TString opt="", AliRsnLoopDaughter *lMass=0, AliRsnLoopDaughter *lPt=0)
{
AliRsnValueDaughter *axisMass = new AliRsnValueDaughter("K0s_Mass", AliRsnValueDaughter::kV0Mass);
axisMass->SetBins(0.4,0.6,0.001);
AliRsnValueDaughter *axisK0sPt = new AliRsnValueDaughter("K0s_Pt", AliRsnValueDaughter::kV0Pt);
axisK0sPt->SetBins(0.,30.,0.001);
// output: 2D histogram
AliRsnListOutput *outMonitorTrMom = new AliRsnListOutput("K0s_Mass_Pt", AliRsnListOutput::kHistoDefault);
outMonitorTrMom->AddValue(axisK0sPt);
outMonitorTrMom->AddValue(axisMass);
// add outputs to loop
if (mon) mon->Add(outMonitorTrMom);
if (lPt) lpt->AddOutput(outMonitorTrMom);
//if (mon) mon->Add(outMonitorM);
//if (lMass) lm->AddOutput(outMonitorM);
}
|
6770c9e73a2d2326c8acab48ff9a1f32e26a5027
|
340cc5d8ba77fbbafefb8a1755ae4dacbfb6953e
|
/src/netflow/netflow_v5_v7.c
|
acab7c05425ef234f8e4f7ab48d254ef1efc9c19
|
[
"BSD-3-Clause"
] |
permissive
|
phaag/nfdump
|
1899c1b376c62040acdc994892949310cf85b32a
|
584453e6e3b4d6f23cf6c83cd2a7298cf0b5c44a
|
refs/heads/master
| 2023-08-31T06:53:13.565444
| 2023-08-20T12:22:46
| 2023-08-20T12:22:46
| 40,435,192
| 703
| 200
|
NOASSERTION
| 2023-08-20T18:40:33
| 2015-08-09T12:12:03
|
C
|
UTF-8
|
C
| false
| false
| 19,649
|
c
|
netflow_v5_v7.c
|
/*
* Copyright (c) 2009-2022, Peter Haag
* Copyright (c) 2004-2008, SWITCH - Teleinformatikdienste fuer Lehre und Forschung
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "netflow_v5_v7.h"
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "bookkeeper.h"
#include "collector.h"
#include "exporter.h"
#include "metric.h"
#include "nfdump.h"
#include "nffile.h"
#include "nfnet.h"
#include "nfxV3.h"
#include "output_short.h"
#include "util.h"
#define NETFLOW_V5_HEADER_LENGTH 24
#define NETFLOW_V5_RECORD_LENGTH 48
#define NETFLOW_V5_MAX_RECORDS 30
#define NETFLOW_V7_HEADER_LENGTH 24
#define NETFLOW_V7_RECORD_LENGTH 52
#define NETFLOW_V7_MAX_RECORDS 28
/* v5 structures */
typedef struct netflow_v5_header {
uint16_t version;
uint16_t count;
uint32_t SysUptime;
uint32_t unix_secs;
uint32_t unix_nsecs;
uint32_t flow_sequence;
uint16_t engine_tag;
uint16_t sampling_interval;
} netflow_v5_header_t;
typedef struct netflow_v5_record {
uint32_t srcaddr;
uint32_t dstaddr;
uint32_t nexthop;
uint16_t input;
uint16_t output;
uint32_t dPkts;
uint32_t dOctets;
uint32_t First;
uint32_t Last;
uint16_t srcPort;
uint16_t dstPort;
uint8_t pad1;
uint8_t tcp_flags;
uint8_t prot;
uint8_t tos;
uint16_t src_as;
uint16_t dst_as;
uint8_t src_mask;
uint8_t dst_mask;
uint16_t pad2;
} netflow_v5_record_t;
/* v7 structures */
typedef struct netflow_v7_header {
uint16_t version;
uint16_t count;
uint32_t SysUptime;
uint32_t unix_secs;
uint32_t unix_nsecs;
uint32_t flow_sequence;
uint32_t reserved;
} netflow_v7_header_t;
typedef struct netflow_v7_record {
uint32_t srcaddr;
uint32_t dstaddr;
uint32_t nexthop;
uint16_t input;
uint16_t output;
uint32_t dPkts;
uint32_t dOctets;
uint32_t First;
uint32_t Last;
uint16_t srcPort;
uint16_t dstPort;
uint8_t flags;
uint8_t tcp_flags;
uint8_t prot;
uint8_t tos;
uint16_t src_as;
uint16_t dst_as;
uint8_t src_mask;
uint8_t dst_mask;
uint16_t pad;
uint32_t router_sc;
} netflow_v7_record_t;
// v5 exporter type
typedef struct exporter_v5_s {
// struct exporter_s
struct exporter_v5_s *next;
// exporter information
exporter_info_record_t info; // exporter record nffile
uint64_t packets; // number of packets sent by this exporter
uint64_t flows; // number of flow records sent by this exporter
uint32_t sequence_failure; // number of sequence failures
uint32_t padding_errors; // number of sequence failures
sampler_t *sampler; // list of samplers associated with this exporter
// end of struct exporter_s
// sequence vars
int first;
int64_t last_sequence;
int64_t sequence, distance;
int64_t last_count;
uint32_t outRecordSize;
} exporter_v5_t;
/* module limited globals */
static int printRecord;
static int32_t defaultSampling;
static uint32_t baseRecordSize;
// function prototypes
static exporter_v5_t *getExporter(FlowSource_t *fs, netflow_v5_header_t *header);
#include "nffile_inline.c"
int Init_v5_v7(int verbose, int32_t sampling) {
assert(sizeof(netflow_v5_header_t) == NETFLOW_V5_HEADER_LENGTH);
assert(sizeof(netflow_v5_record_t) == NETFLOW_V5_RECORD_LENGTH);
printRecord = verbose > 2;
defaultSampling = sampling;
if (sampling < 0) {
LogInfo("Init v5/v7: Overwrite sampling: %d", -defaultSampling);
} else {
LogInfo("Init v5/v7: Default sampling: %d", defaultSampling);
}
baseRecordSize = sizeof(recordHeaderV3_t) + EXgenericFlowSize + EXipv4FlowSize + EXflowMiscSize + EXasRoutingSize + EXipNextHopV4Size;
return 1;
} // End of Init_v5_input
static inline exporter_v5_t *getExporter(FlowSource_t *fs, netflow_v5_header_t *header) {
exporter_v5_t **e = (exporter_v5_t **)&(fs->exporter_data);
sampler_t *sampler;
uint16_t engine_tag = ntohs(header->engine_tag);
uint16_t version = ntohs(header->version);
// search the matching v5 exporter
while (*e) {
if ((*e)->info.version == version && (*e)->info.id == engine_tag && (*e)->info.ip.V6[0] == fs->ip.V6[0] &&
(*e)->info.ip.V6[1] == fs->ip.V6[1])
return *e;
e = &((*e)->next);
}
// nothing found
*e = (exporter_v5_t *)calloc(1, sizeof(exporter_v5_t));
if (!(*e)) {
LogError("Process_v5: malloc() error in %s line %d: %s\n", __FILE__, __LINE__, strerror(errno));
return NULL;
}
(*e)->next = NULL;
(*e)->info.header.type = ExporterInfoRecordType;
(*e)->info.header.size = sizeof(exporter_info_record_t);
(*e)->info.version = version;
(*e)->info.id = engine_tag;
(*e)->info.ip = fs->ip;
(*e)->info.sa_family = fs->sa_family;
(*e)->info.sysid = 0;
(*e)->sequence_failure = 0;
(*e)->packets = 0;
(*e)->flows = 0;
(*e)->first = 1;
char *ipstr = GetExporterIP(fs);
if (fs->sa_family == PF_INET6) {
(*e)->outRecordSize = baseRecordSize + EXipReceivedV6Size;
dbg_printf("Process_v5: New IPv6 exporter %s - add EXipReceivedV6\n", ipstr);
} else {
(*e)->outRecordSize = baseRecordSize + EXipReceivedV4Size;
dbg_printf("Process_v5: New IPv4 exporter %s - add EXipReceivedV4\n", ipstr);
}
FlushInfoExporter(fs, &((*e)->info));
// sampling
int32_t id = 0;
uint32_t algorithm = 0;
uint32_t interval = 0x3fff & ntohs(header->sampling_interval);
dbg_printf("Extracted header sampling: algorithm: %u, interval: %u\n", algorithm, interval);
if (defaultSampling < 0) {
id = SAMPLER_OVERWRITE;
interval = -defaultSampling;
dbg_printf("Use overwrite sampling: %u\n", interval);
} else if (interval > 0) {
id = SAMPLER_GENERIC;
algorithm = (0xC000 & ntohs(header->sampling_interval)) >> 14;
dbg_printf("Use generic sampling: %u\n", interval);
} else if (defaultSampling > 1) {
id = SAMPLER_DEFAULT;
interval = defaultSampling;
dbg_printf("Use default sampling: %u\n", interval);
}
// sampler assigned ?
if (id != 0) {
interval--;
sampler = (sampler_t *)malloc(sizeof(sampler_t));
if (!sampler) {
LogError("Process_v5: malloc() error in %s line %d: %s\n", __FILE__, __LINE__, strerror(errno));
return NULL;
}
(*e)->sampler = sampler;
sampler->next = NULL;
sampler->record.type = SamplerRecordType;
sampler->record.size = sizeof(sampler_record_t);
sampler->record.exporter_sysid = (*e)->info.sysid;
sampler->record.id = id;
sampler->record.packetInterval = 1;
sampler->record.algorithm = algorithm;
sampler->record.spaceInterval = interval;
AppendToBuffer(fs->nffile, &(sampler->record), sampler->record.size);
LogInfo(
"Process_v5: New exporter: SysID: %u, engine id %u, type %u, IP: %s, algorithm: %i, "
"packet interval: 1, packet space: %u\n",
(*e)->info.sysid, (engine_tag & 0xFF), ((engine_tag >> 8) & 0xFF), ipstr, algorithm, interval);
} else {
(*e)->sampler = NULL;
LogInfo("Process_v5: New exporter: SysID: %u, engine id %u, type %u, IP: %s", (*e)->info.sysid, (engine_tag & 0xFF),
((engine_tag >> 8) & 0xFF), ipstr);
}
return (*e);
} // End of getExporter
void Process_v5_v7(void *in_buff, ssize_t in_buff_cnt, FlowSource_t *fs) {
// v7 is treated as v5. it differs by the sequencer skip count only
// map v5 data structure to input buffer
netflow_v5_header_t *v5_header = (netflow_v5_header_t *)in_buff;
exporter_v5_t *exporter = getExporter(fs, v5_header);
if (!exporter) {
LogError("Process_v5: Exporter NULL: Abort v5/v7 record processing");
return;
}
exporter->packets++;
uint16_t version = ntohs(v5_header->version);
int rawRecordSize = version == 5 ? NETFLOW_V5_RECORD_LENGTH : NETFLOW_V7_RECORD_LENGTH;
// this many data to process
ssize_t size_left = in_buff_cnt;
// time received for this packet
uint64_t msecReceived = ((uint64_t)fs->received.tv_sec * 1000LL) + (uint64_t)((uint64_t)fs->received.tv_usec / 1000LL);
// set output buffer memory
void *outBuff = fs->nffile->buff_ptr;
int done = 0;
while (!done) {
netflow_v5_record_t *v5_record;
/* Process header */
// count check
uint16_t count = ntohs(v5_header->count);
// input buffer size check for all expected records
if (size_left < (NETFLOW_V5_HEADER_LENGTH + count * rawRecordSize)) {
LogError("Process_v5: Exporter: %s Not enough data to process v5 record. Abort v5/v7 record processing", GetExporterIP(fs));
fs->nffile->buff_ptr = outBuff;
return;
}
// output buffer size check for all expected records
if (!CheckBufferSpace(fs->nffile, count * exporter->outRecordSize)) {
// fishy! - should never happen. maybe disk full?
LogError("Process_v5: output buffer size error. Abort v5/v7 record processing");
return;
}
// map output memory buffer
outBuff = fs->nffile->buff_ptr;
// sequence check
if (exporter->first) {
exporter->last_sequence = ntohl(v5_header->flow_sequence);
exporter->sequence = exporter->last_sequence;
exporter->first = 0;
} else {
exporter->last_sequence = exporter->sequence;
exporter->sequence = ntohl(v5_header->flow_sequence);
exporter->distance = exporter->sequence - exporter->last_sequence;
// handle overflow
if (exporter->distance < 0) {
exporter->distance = 0xffffffff + exporter->distance + 1;
}
if (exporter->distance != exporter->last_count) {
fs->nffile->stat_record->sequence_failure++;
exporter->sequence_failure++;
}
}
exporter->last_count = count;
v5_header->SysUptime = ntohl(v5_header->SysUptime);
v5_header->unix_secs = ntohl(v5_header->unix_secs);
v5_header->unix_nsecs = ntohl(v5_header->unix_nsecs);
/* calculate boot time in msec */
uint64_t msecBoot =
((uint64_t)(v5_header->unix_secs) * 1000 + ((uint64_t)(v5_header->unix_nsecs) / 1000000)) - (uint64_t)(v5_header->SysUptime);
// process all records
v5_record = (netflow_v5_record_t *)((pointer_addr_t)v5_header + NETFLOW_V5_HEADER_LENGTH);
uint16_t engine_tag = ntohs(v5_header->engine_tag);
uint8_t engineType = (engine_tag >> 8) & 0xFF;
uint8_t engineID = (engine_tag & 0xFF);
/* loop over each records associated with this header */
uint32_t outSize = 0;
for (int i = 0; i < count; i++) {
// header data gets initialized by macro
AddV3Header(outBuff, recordHeader);
// header data
recordHeader->engineType = engineType;
recordHeader->engineID = engineID;
recordHeader->exporterID = exporter->info.sysid;
recordHeader->nfversion = 5;
// Add v5 specific data
PushExtension(recordHeader, EXgenericFlow, genericFlow);
genericFlow->msecReceived = msecReceived;
genericFlow->inPackets = ntohl(v5_record->dPkts);
genericFlow->inBytes = ntohl(v5_record->dOctets);
genericFlow->srcPort = ntohs(v5_record->srcPort);
genericFlow->dstPort = ntohs(v5_record->dstPort);
genericFlow->proto = v5_record->prot;
genericFlow->srcTos = v5_record->tos;
genericFlow->tcpFlags = v5_record->tcp_flags;
PushExtension(recordHeader, EXipv4Flow, ipv4Flow);
ipv4Flow->srcAddr = ntohl(v5_record->srcaddr);
ipv4Flow->dstAddr = ntohl(v5_record->dstaddr);
// add these extensions only if they have non zero values
if (v5_record->input || v5_record->output) {
PushExtension(recordHeader, EXflowMisc, flowMisc);
flowMisc->input = ntohs(v5_record->input);
flowMisc->output = ntohs(v5_record->output);
}
if (v5_record->src_as || v5_record->dst_as) {
PushExtension(recordHeader, EXasRouting, asRouting);
asRouting->srcAS = ntohs(v5_record->src_as);
asRouting->dstAS = ntohs(v5_record->dst_as);
}
if (v5_record->nexthop) {
PushExtension(recordHeader, EXipNextHopV4, ipNextHopV4);
ipNextHopV4->ip = ntohl(v5_record->nexthop);
}
// post process required data
// calculate msec values first/last
uint64_t First = ntohl(v5_record->First);
uint64_t Last = ntohl(v5_record->Last);
uint64_t msecStart, msecEnd;
if (First > Last) {
/* First in msec, in case of msec overflow, between start and end */
msecStart = msecBoot - 0x100000000LL + First;
} else {
msecStart = msecBoot + First;
}
/* end time in msecs */
msecEnd = Last + msecBoot;
// if overflow happened after flow ended but before got exported
// the additional check > 100000 is required due to a CISCO IOS bug
// CSCei12353 - thanks to Bojan
if (Last > v5_header->SysUptime && ((Last - v5_header->SysUptime) > 100000)) {
msecStart -= 0x100000000LL;
msecEnd -= 0x100000000LL;
}
genericFlow->msecFirst = msecStart;
genericFlow->msecLast = msecEnd;
UpdateFirstLast(fs, msecStart, msecEnd);
// add router IP
if (fs->sa_family == PF_INET6) {
PushExtension(recordHeader, EXipReceivedV6, ipReceivedV6);
ipReceivedV6->ip[0] = fs->ip.V6[0];
ipReceivedV6->ip[1] = fs->ip.V6[1];
} else {
PushExtension(recordHeader, EXipReceivedV4, ipReceivedV4);
ipReceivedV4->ip = fs->ip.V4;
}
// sampling
if (exporter->sampler && exporter->sampler->record.spaceInterval > 1) {
genericFlow->inPackets *= (uint64_t)(exporter->sampler->record.spaceInterval + 1);
genericFlow->inBytes *= (uint64_t)(exporter->sampler->record.spaceInterval + 1);
SetFlag(recordHeader->flags, V3_FLAG_SAMPLED);
}
// Update stats
switch (genericFlow->proto) {
case IPPROTO_ICMP:
fs->nffile->stat_record->numflows_icmp++;
fs->nffile->stat_record->numpackets_icmp += genericFlow->inPackets;
fs->nffile->stat_record->numbytes_icmp += genericFlow->inBytes;
// fix odd CISCO behaviour for ICMP port/type in src port
if (genericFlow->srcPort != 0) {
uint8_t *s1 = (uint8_t *)&(genericFlow->srcPort);
uint8_t *s2 = (uint8_t *)&(genericFlow->dstPort);
s2[0] = s1[1];
s2[1] = s1[0];
genericFlow->srcPort = 0;
}
break;
case IPPROTO_TCP:
fs->nffile->stat_record->numflows_tcp++;
fs->nffile->stat_record->numpackets_tcp += genericFlow->inPackets;
fs->nffile->stat_record->numbytes_tcp += genericFlow->inBytes;
break;
case IPPROTO_UDP:
fs->nffile->stat_record->numflows_udp++;
fs->nffile->stat_record->numpackets_udp += genericFlow->inPackets;
fs->nffile->stat_record->numbytes_udp += genericFlow->inBytes;
break;
default:
fs->nffile->stat_record->numflows_other++;
fs->nffile->stat_record->numpackets_other += genericFlow->inPackets;
fs->nffile->stat_record->numbytes_other += genericFlow->inBytes;
}
exporter->flows++;
fs->nffile->stat_record->numflows++;
fs->nffile->stat_record->numpackets += genericFlow->inPackets;
fs->nffile->stat_record->numbytes += genericFlow->inBytes;
uint32_t exporterIdent = MetricExpporterID(recordHeader);
UpdateMetric(fs->nffile->ident, exporterIdent, genericFlow);
if (printRecord) {
flow_record_short(stdout, recordHeader);
}
// advance to next input flow record
outBuff += recordHeader->size;
outSize += recordHeader->size;
v5_record = (netflow_v5_record_t *)((pointer_addr_t)v5_record + rawRecordSize);
if (recordHeader->size > exporter->outRecordSize) {
LogError("Process_v5: Record size check failed! Expected: %u, counted: %u\n", exporter->outRecordSize, recordHeader->size);
return;
}
} // End of foreach v5 record
// update file record size ( -> output buffer size )
fs->nffile->block_header->NumRecords += count;
fs->nffile->block_header->size += outSize;
fs->nffile->buff_ptr = (void *)outBuff;
// still to go for this many input bytes
size_left -= NETFLOW_V5_HEADER_LENGTH + count * rawRecordSize;
// next header
v5_header = (netflow_v5_header_t *)v5_record;
// should never be < 0
done = size_left <= 0;
} // End of while !done
return;
} // End of Process_v5
|
a7baab7bc66b26bb864904978c04fcb45b412cc2
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/contrib/python/scipy/py3/scipy/optimize/_highs/src/lp_data/HighsSolve.h
|
c1b3302c42af5f00ce0951490a990204b7dc0295
|
[
"Apache-2.0",
"MIT",
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference",
"Qhull",
"BSD-3-Clause",
"BSL-1.0",
"BSD-2-Clause"
] |
permissive
|
catboost/catboost
|
854c1a1f439a96f1ae6b48e16644be20aa04dba2
|
f5042e35b945aded77b23470ead62d7eacefde92
|
refs/heads/master
| 2023-09-01T12:14:14.174108
| 2023-09-01T10:01:01
| 2023-09-01T10:22:12
| 97,556,265
| 8,012
| 1,425
|
Apache-2.0
| 2023-09-11T03:32:32
| 2017-07-18T05:29:04
|
Python
|
UTF-8
|
C
| false
| false
| 1,122
|
h
|
HighsSolve.h
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the HiGHS linear optimization suite */
/* */
/* Written and engineered 2008-2020 at the University of Edinburgh */
/* */
/* Available as open-source under the MIT License */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file lp_data/HighsSolve.h
* @brief Class-independent utilities for HiGHS
* @author Julian Hall, Ivet Galabova, Qi Huangfu and Michael Feldmeier
*/
#ifndef LP_DATA_HIGHSSOLVE_H_
#define LP_DATA_HIGHSSOLVE_H_
#include "lp_data/HighsModelUtils.h"
HighsStatus solveLp(HighsModelObject& highs_model_object, const string message);
HighsStatus solveUnconstrainedLp(HighsModelObject& highs_model_object);
#endif // LP_DATA_HIGHSSOLVE_H_
|
ce73985fe63a2eb8f873713fa34fa96d1c21d25c
|
18333497cc6db4a990a5f5e7b0dca14e9a517a73
|
/include/cmt/resource.h
|
eede4a3209ef768c39ea60de9b3669a782e79367
|
[
"MIT"
] |
permissive
|
recp/cmt
|
6ecbca0a356ec044257285ab58e062ee6af55c7c
|
e2730ade077345b389213d6695d0d7a6c4e93264
|
refs/heads/master
| 2023-05-25T16:32:50.511305
| 2023-05-14T11:40:55
| 2023-05-14T11:40:55
| 137,069,724
| 138
| 12
|
MIT
| 2023-05-14T11:40:56
| 2018-06-12T12:39:37
|
C
|
UTF-8
|
C
| false
| false
| 2,142
|
h
|
resource.h
|
/*
* Copyright (c), Recep Aslantas.
* MIT License (MIT), http://opensource.org/licenses/MIT
*/
#ifndef cmt_resource_h
#define cmt_resource_h
#ifdef __cplusplus
extern "C" {
#endif
#include "common.h"
typedef enum MtCPUCacheMode {
MtCPUCacheModeDefaultCache = 0,
MtCPUCacheModeWriteCombined = 1
} MtCPUCacheMode;
typedef enum MtHazardTrackingMode {
MtHazardTrackingModeDefault = 0,
MtHazardTrackingModeUntracked = 1,
MtHazardTrackingModeTracked = 2
} MtHazardTrackingMode;
typedef enum MtStorageMode {
MtStorageModeShared = 0,
MtStorageModeManaged = 1,
MtStorageModePrivate = 2,
MtStorageModeMemoryless = 3
} MtStorageMode;
typedef enum MtResourceOptions {
MtResourceCPUCacheModeDefaultCache = MtCPUCacheModeDefaultCache,
MtResourceCPUCacheModeWriteCombined = MtCPUCacheModeWriteCombined,
MtResourceStorageModeShared = MtStorageModeShared << 4,
MtResourceStorageModeManaged = MtStorageModeManaged << 4,
MtResourceStorageModePrivate = MtStorageModePrivate << 4,
MtResourceStorageModeMemoryless = MtStorageModeMemoryless << 4,
MtResourceHazardTrackingModeDefault = MtHazardTrackingModeDefault << 8,
MtResourceHazardTrackingModeUntracked = MtHazardTrackingModeUntracked << 8,
MtResourceHazardTrackingModeTracked = MtHazardTrackingModeTracked << 8
} MtResourceOptions;
MT_EXPORT
MT_API_AVAILABLE(mt_macos(10.11), mt_ios(8.0))
MtDevice*
mtResourceDevice(MtResource *res);
MT_EXPORT
MT_API_AVAILABLE(mt_macos(10.11), mt_ios(8.0))
const char*
mtResourceLabel(MtResource *res);
MT_EXPORT
MT_API_AVAILABLE(mt_macos(10.11), mt_ios(8.0))
MtCPUCacheMode
mtResourceCPUCacheMode(MtResource *res);
MT_EXPORT
MT_API_AVAILABLE(mt_macos(10.11), mt_ios(8.0))
MtStorageMode
mtResourceStorageMode(MtResource *res);
MT_EXPORT
MT_API_AVAILABLE(mt_macos(10.15), mt_ios(13.0))
MtHazardTrackingMode
mtResourceHazardTrackingMode(MtResource *res);
MT_EXPORT
MT_API_AVAILABLE(mt_macos(10.15), mt_ios(13.0))
MtResourceOptions
mtResourceOptions(MtResource *res);
#ifdef __cplusplus
}
#endif
#endif /* cmt_resource_h */
|
bf1242bfb0a46f3790016b8b832f9b967dd93d1a
|
a5a99f646e371b45974a6fb6ccc06b0a674818f2
|
/CondFormats/Serialization/src/SerializationManual.h
|
586125cb6a49ca2a23c7ce359340f40405bebb84
|
[
"Apache-2.0"
] |
permissive
|
cms-sw/cmssw
|
4ecd2c1105d59c66d385551230542c6615b9ab58
|
19c178740257eb48367778593da55dcad08b7a4f
|
refs/heads/master
| 2023-08-23T21:57:42.491143
| 2023-08-22T20:22:40
| 2023-08-22T20:22:40
| 10,969,551
| 1,006
| 3,696
|
Apache-2.0
| 2023-09-14T19:14:28
| 2013-06-26T14:09:07
|
C++
|
UTF-8
|
C
| false
| false
| 57
|
h
|
SerializationManual.h
|
#include "CondFormats/Serialization/interface/Archive.h"
|
2203220fece3c07b8a5ef1ffb7cab0f216f5c2c0
|
2df81d3d8ce680d6861a4711c94ab226e59935cf
|
/vendor/github.com/bearsh/hid/libusb/libusb/os/threads_posix.c
|
0e0e22134ebfcf6844cdb3006ab0545b35ef7b5f
|
[
"LGPL-2.1-only",
"LGPL-3.0-only",
"BSD-3-Clause",
"BSD-2-Clause",
"LGPL-2.1-or-later",
"Apache-2.0"
] |
permissive
|
convox/convox
|
6832d844f24e606e24957ecdd790c708665da27e
|
b486f8d4c7f0d47c0850f0124c440f1374590807
|
refs/heads/master
| 2023-08-22T21:01:28.118465
| 2023-08-07T14:40:44
| 2023-08-08T20:40:05
| 202,789,481
| 130
| 57
|
Apache-2.0
| 2023-09-12T20:44:12
| 2019-08-16T19:44:55
|
Go
|
UTF-8
|
C
| false
| false
| 3,359
|
c
|
threads_posix.c
|
/*
* libusb synchronization using POSIX Threads
*
* Copyright © 2011 Vitali Lovich <vlovich@aliph.com>
* Copyright © 2011 Peter Stuge <peter@stuge.se>
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libusbi.h"
#include <errno.h>
#if defined(__ANDROID__)
# include <unistd.h>
#elif defined(__HAIKU__)
# include <os/kernel/OS.h>
#elif defined(__linux__)
# include <sys/syscall.h>
# include <unistd.h>
#elif defined(__NetBSD__)
# include <lwp.h>
#elif defined(__OpenBSD__)
# define _BSD_SOURCE
# include <sys/syscall.h>
# include <unistd.h>
#elif defined(__sun__)
# include <sys/lwp.h>
#endif
void usbi_cond_init(pthread_cond_t *cond)
{
#ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
pthread_condattr_t condattr;
PTHREAD_CHECK(pthread_condattr_init(&condattr));
PTHREAD_CHECK(pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC));
PTHREAD_CHECK(pthread_cond_init(cond, &condattr));
PTHREAD_CHECK(pthread_condattr_destroy(&condattr));
#else
PTHREAD_CHECK(pthread_cond_init(cond, NULL));
#endif
}
int usbi_cond_timedwait(pthread_cond_t *cond,
pthread_mutex_t *mutex, const struct timeval *tv)
{
struct timespec timeout;
int r;
#ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
usbi_get_monotonic_time(&timeout);
#else
usbi_get_real_time(&timeout);
#endif
timeout.tv_sec += tv->tv_sec;
timeout.tv_nsec += tv->tv_usec * 1000L;
if (timeout.tv_nsec >= NSEC_PER_SEC) {
timeout.tv_nsec -= NSEC_PER_SEC;
timeout.tv_sec++;
}
r = pthread_cond_timedwait(cond, mutex, &timeout);
if (r == 0)
return 0;
else if (r == ETIMEDOUT)
return LIBUSB_ERROR_TIMEOUT;
else
return LIBUSB_ERROR_OTHER;
}
unsigned int usbi_get_tid(void)
{
static _Thread_local unsigned int tl_tid;
int tid;
if (tl_tid)
return tl_tid;
#if defined(__ANDROID__)
tid = gettid();
#elif defined(__APPLE__)
#ifdef HAVE_PTHREAD_THREADID_NP
uint64_t thread_id;
if (pthread_threadid_np(NULL, &thread_id) == 0)
tid = (int)thread_id;
else
tid = -1;
#else
tid = (int)pthread_mach_thread_np(pthread_self());
#endif
#elif defined(__HAIKU__)
tid = get_pthread_thread_id(pthread_self());
#elif defined(__linux__)
tid = (int)syscall(SYS_gettid);
#elif defined(__NetBSD__)
tid = _lwp_self();
#elif defined(__OpenBSD__)
/* The following only works with OpenBSD > 5.1 as it requires
* real thread support. For 5.1 and earlier, -1 is returned. */
tid = syscall(SYS_getthrid);
#elif defined(__sun__)
tid = _lwp_self();
#else
tid = -1;
#endif
if (tid == -1) {
/* If we don't have a thread ID, at least return a unique
* value that can be used to distinguish individual
* threads. */
tid = (int)(intptr_t)pthread_self();
}
return tl_tid = (unsigned int)tid;
}
|
128844258a7080911204a5f763d5ffcc11210a7b
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/src/world/common/complete/LetterDelivery.inc.c
|
a825c4d8d5c7791460d00ec1b7ea705b5887fac7
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 7,894
|
c
|
LetterDelivery.inc.c
|
#include "common.h"
#include "sprite/npc/WorldParakarry.h"
#include "world/common/complete/GiveReward.inc.c"
#include "world/common/complete/KeyItemChoice.inc.c"
enum DeliveryResult {
DELIVERY_NOT_POSSIBLE = 0,
DELIVERY_REJECTED = 1,
DELIVERY_ACCEPTED = 2,
};
BSS s32 N(LetterDelivery_SavedNpcAnim);
API_CALLABLE(N(LetterDelivery_Init)) {
Bytecode* args = script->ptrReadPos;
script->varTable[2] = evt_get_variable(script, *args++);
script->varTable[3] = evt_get_variable(script, *args++);
script->varTable[4] = evt_get_variable(script, *args++);
script->varTable[5] = evt_get_variable(script, *args++);
script->varTable[6] = evt_get_variable(script, *args++);
script->varTable[7] = evt_get_variable(script, *args++);
script->varTable[8] = evt_get_variable(script, *args++);
script->varTable[9] = evt_get_variable(script, *args++);
script->varTable[10] = evt_get_variable(script, *args++);
script->varTable[11] = evt_get_variable(script, *args++);
return ApiStatus_DONE2;
}
API_CALLABLE(N(LetterDelivery_CalcLetterPos)) {
Bytecode* args = script->ptrReadPos;
s32 varX = *args++;
f32 x = evt_get_variable(script, varX);
s32 varY = *args++;
f32 y = evt_get_variable(script, varY);
s32 varZ = *args++;
f32 z = evt_get_variable(script, varZ);
Npc* partner = get_npc_unsafe(NPC_PARTNER);
f32 currentCamYaw = clamp_angle(gCameras[gCurrentCameraID].curYaw + 180.0f);
add_vec2D_polar(&x, &z, 15.0f, partner->yaw);
add_vec2D_polar(&x, &z, 10.0f, currentCamYaw);
evt_set_variable(script, varX, x);
evt_set_variable(script, varY, y);
evt_set_variable(script, varZ, z);
return ApiStatus_DONE2;
}
API_CALLABLE(N(LetterDelivery_SaveNpcAnim)) {
Npc* npc = get_npc_unsafe(script->varTable[2]);
N(LetterDelivery_SavedNpcAnim) = npc->curAnim;
npc->curAnim = script->varTable[4];
return ApiStatus_DONE2;
}
API_CALLABLE(N(LetterDelivery_RestoreNpcAnim)) {
Npc* npc = get_npc_unsafe(script->varTable[2]);
npc->curAnim = N(LetterDelivery_SavedNpcAnim);
return ApiStatus_DONE2;
}
EvtScript N(EVS_LetterDelivery_CarryLetter) = {
EVT_LOOP(0)
EVT_CALL(GetNpcPos, NPC_PARTNER, LVar3, LVar4, LVar5)
EVT_CALL(N(LetterDelivery_CalcLetterPos), LVar3, LVar4, LVar5)
EVT_CALL(SetItemPos, LVar0, LVar3, LVar4, LVar5)
EVT_WAIT(1)
EVT_END_LOOP
EVT_RETURN
EVT_END
};
EvtScript N(EVS_LetterDelivery_ItemPrompt) = {
EVT_SET(LVar9, LVar1)
EVT_CALL(ShowKeyChoicePopup)
EVT_SET(LVarA, LVar0)
EVT_SWITCH(LVar0)
EVT_CASE_EQ(0)
EVT_CASE_EQ(-1)
EVT_CASE_DEFAULT
EVT_CALL(RemoveKeyItemAt, LVar1)
EVT_CALL(DisablePartnerAI, 0)
EVT_CALL(GetNpcPos, NPC_PARTNER, LVar3, LVar4, LVar5)
EVT_CALL(N(LetterDelivery_CalcLetterPos), LVar3, LVar4, LVar5)
EVT_BITWISE_OR_CONST(LVar0, VIS_GROUP_5 << 16)
EVT_CALL(MakeItemEntity, LVar0, LVar3, LVar4, LVar5, ITEM_SPAWN_MODE_DECORATION, 0)
EVT_EXEC_GET_TID(N(EVS_LetterDelivery_CarryLetter), LVarA)
EVT_CALL(SetNpcAnimation, NPC_PARTNER, ANIM_WorldParakarry_Walk)
EVT_CALL(GetAngleBetweenNPCs, LVar9, NPC_PARTNER, LVarB)
EVT_CALL(GetNpcPos, NPC_PARTNER, LVar3, LVar4, LVar5)
EVT_CALL(GetNpcPos, LVar9, LVar6, LVar7, LVar8)
EVT_CALL(SetNpcFlagBits, NPC_PARTNER, NPC_FLAG_IGNORE_PLAYER_COLLISION, TRUE)
EVT_IF_LE(LVarB, 180)
EVT_ADD(LVar6, 20)
EVT_ELSE
EVT_ADD(LVar6, -20)
EVT_END_IF
EVT_ADD(LVar7, 10)
EVT_CALL(SetNpcJumpscale, NPC_PARTNER, EVT_FLOAT(0.0))
EVT_CALL(NpcJump1, NPC_PARTNER, LVar6, LVar7, LVar8, 20)
EVT_KILL_THREAD(LVarA)
EVT_CALL(RemoveItemEntity, LVar0)
EVT_WAIT(20)
EVT_CALL(GetNpcYaw, NPC_PARTNER, LVarA)
EVT_ADD(LVarA, 180)
EVT_CALL(InterpNpcYaw, NPC_PARTNER, LVarA, 0)
EVT_WAIT(5)
EVT_CALL(NpcJump1, NPC_PARTNER, LVar3, LVar4, LVar5, 20)
EVT_CALL(SetNpcAnimation, NPC_PARTNER, ANIM_WorldParakarry_Idle)
EVT_CALL(NpcFaceNpc, NPC_PARTNER, LVar9, 0)
EVT_WAIT(5)
EVT_CALL(SetNpcFlagBits, NPC_PARTNER, NPC_FLAG_IGNORE_PLAYER_COLLISION, FALSE)
EVT_CALL(EnablePartnerAI)
EVT_WAIT(5)
EVT_END_SWITCH
EVT_CALL(N(ItemChoice_SaveSelected), LVarA)
EVT_CALL(CloseChoicePopup)
EVT_UNBIND
EVT_RETURN
EVT_END
};
EvtScript N(EVS_ShowLetterChoice) = {
EVT_SET(LVar0, LVarB)
EVT_SET(LVar1, LVar2)
EVT_CALL(N(BuildKeyItemChoiceList), LVar0)
EVT_BIND_PADLOCK(N(EVS_LetterDelivery_ItemPrompt), TRIGGER_FORCE_ACTIVATE, 0, EVT_PTR(N(KeyItemChoiceList)), 0, 1)
EVT_CALL(N(ItemChoice_WaitForSelection), LVar0)
EVT_RETURN
EVT_END
};
// returns DeliveryResult on LVarC
EvtScript N(EVS_DoLetterDelivery) = {
EVT_SET(LVarC, DELIVERY_NOT_POSSIBLE)
EVT_IF_LT(GB_StoryProgress, STORY_CH2_PARAKARRY_JOINED_PARTY)
EVT_RETURN
EVT_END_IF
EVT_CALL(N(LetterDelivery_SaveNpcAnim))
EVT_CALL(GetCurrentPartnerID, LVar0)
EVT_CALL(FindKeyItem, LVar5, LVar1)
EVT_IF_EQ(LVar0, PARTNER_PARAKARRY)
EVT_IF_NE(LVar1, -1)
EVT_CALL(DisablePartnerAI, 0)
EVT_CALL(PlayerFaceNpc, LVar2, FALSE)
EVT_WAIT(1)
EVT_CALL(GetNpcPos, LVar2, LVarD, LVar0, LVarE)
EVT_CALL(GetNpcPos, NPC_PARTNER, LVarD, LVarE, LVarF)
EVT_CALL(SetNpcJumpscale, NPC_PARTNER, EVT_FLOAT(0.0))
EVT_ADD(LVar0, 10)
EVT_CALL(NpcJump1, NPC_PARTNER, LVarD, LVar0, LVarF, 10)
EVT_CALL(SpeakToNpc, NPC_PARTNER, ANIM_WorldParakarry_Talk, ANIM_WorldParakarry_Idle, 0, LVar2, LVar7)
EVT_CALL(EnablePartnerAI)
EVT_EXEC_WAIT(N(EVS_ShowLetterChoice))
EVT_SWITCH(LVar0)
EVT_CASE_EQ(-1)
EVT_CALL(DisablePartnerAI, 0)
EVT_WAIT(1)
EVT_CALL(SpeakToPlayer, NPC_PARTNER, ANIM_WorldParakarry_Talk, ANIM_WorldParakarry_Idle, 5, LVar8)
EVT_CALL(EnablePartnerAI)
EVT_SET(LVarC, DELIVERY_REJECTED)
EVT_CASE_DEFAULT
EVT_CALL(DisablePartnerAI, 0)
EVT_WAIT(1)
EVT_CALL(SpeakToPlayer, NPC_PARTNER, ANIM_WorldParakarry_Talk, ANIM_WorldParakarry_Idle, 5, LVar9)
EVT_IF_NE(LVarA, 0)
EVT_CALL(SpeakToPlayer, LVar2, LVar3, LVar4, 0, LVarA)
EVT_END_IF
EVT_CALL(EnablePartnerAI)
EVT_IF_NE(LVar6, ITEM_NONE)
EVT_GIVE_KEY_REWARD(LVar6)
EVT_END_IF
EVT_SET(LVarC, DELIVERY_ACCEPTED)
EVT_END_SWITCH
EVT_END_IF
EVT_END_IF
EVT_CALL(N(LetterDelivery_RestoreNpcAnim))
EVT_RETURN
EVT_END
};
#define EVT_LETTER_PROMPT(npcName, npcID, animTalk, animIdle, msg1, msg2, ms3, msg4, itemID, itemList) \
EvtScript N(EVS_LetterPrompt_##npcName) = { \
EVT_CALL(N(LetterDelivery_Init), \
npcID, animTalk, animIdle, \
itemID, ITEM_NONE, \
msg1, msg2, ms3, msg4, \
EVT_PTR(itemList)) \
EVT_EXEC_WAIT(N(EVS_DoLetterDelivery)) \
EVT_RETURN \
EVT_END \
}
#define EVT_LETTER_REWARD(npcName) \
EvtScript N(EVS_LetterReward_##npcName) = { \
EVT_IF_EQ(LVarC, DELIVERY_ACCEPTED) \
EVT_GIVE_STAR_PIECE() \
EVT_END_IF \
EVT_RETURN \
EVT_END \
}
#define EVT_LETTER_CHECK(npcName) \
EVT_EXEC_WAIT(N(EVS_LetterPrompt_##npcName)) \
EVT_EXEC_WAIT(N(EVS_LetterReward_##npcName))
|
ea8f2a000a9b7e9889a15743172b3ef5156b5794
|
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
|
/x11-toolkits/gnome-pty-helper/files/patch-gnome-pty-helper_gnome-pty-helper.c
|
ab80c5364b55ffda455f1f1af7735266d685543b
|
[
"BSD-2-Clause"
] |
permissive
|
freebsd/freebsd-ports
|
86f2e89d43913412c4f6b2be3e255bc0945eac12
|
605a2983f245ac63f5420e023e7dce56898ad801
|
refs/heads/main
| 2023-08-30T21:46:28.720924
| 2023-08-30T19:33:44
| 2023-08-30T19:33:44
| 1,803,961
| 916
| 918
|
NOASSERTION
| 2023-09-08T04:06:26
| 2011-05-26T11:15:35
| null |
UTF-8
|
C
| false
| false
| 255
|
c
|
patch-gnome-pty-helper_gnome-pty-helper.c
|
--- gnome-pty-helper/gnome-pty-helper.c
+++ gnome-pty-helper/gnome-pty-helper.c
@@ -51,7 +51,6 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
-#include <utmp.h>
#include <grp.h>
#include "gnome-pty.h"
#include "gnome-login-support.h"
|
06cddb0540a3471fe2c8d5ae5b063522a796f550
|
bf32556b2db7a22556869a9b69cffa3d51852489
|
/kernel/console.c
|
c00b9c0e77d8940a7a6c9e5b45e84bdbbca82fed
|
[
"MIT"
] |
permissive
|
jserv/xv6-x86_64
|
235372b64618814b1e287a47efe263cb38775c67
|
117208b3cc1df650af9bafca33b1f26ee60cb6fc
|
refs/heads/64bit
| 2023-07-22T22:09:56.335477
| 2023-07-22T07:34:13
| 2023-07-22T07:34:13
| 36,936,955
| 159
| 48
|
NOASSERTION
| 2023-07-22T07:34:14
| 2015-06-05T14:25:04
|
C
|
UTF-8
|
C
| false
| false
| 5,439
|
c
|
console.c
|
// Console input and output.
// Input is from the keyboard or serial port.
// Output is written to the screen and serial port.
#include <stdarg.h>
#include "types.h"
#include "defs.h"
#include "param.h"
#include "traps.h"
#include "spinlock.h"
#include "fs.h"
#include "file.h"
#include "memlayout.h"
#include "mmu.h"
#include "proc.h"
#include "x86.h"
static void consputc(int);
static int panicked = 0;
static struct {
struct spinlock lock;
int locking;
} cons;
static char digits[] = "0123456789abcdef";
static void
printptr(uintp x) {
int i;
for (i = 0; i < (sizeof(uintp) * 2); i++, x <<= 4)
consputc(digits[x >> (sizeof(uintp) * 8 - 4)]);
}
static void
printint(int xx, int base, int sign)
{
char buf[16];
int i;
uint x;
if(sign && (sign = xx < 0))
x = -xx;
else
x = xx;
i = 0;
do{
buf[i++] = digits[x % base];
}while((x /= base) != 0);
if(sign)
buf[i++] = '-';
while(--i >= 0)
consputc(buf[i]);
}
//PAGEBREAK: 50
// Print to the console. only understands %d, %x, %p, %s.
void
cprintf(char *fmt, ...)
{
va_list ap;
int i, c, locking;
char *s;
va_start(ap, fmt);
locking = cons.locking;
if(locking)
acquire(&cons.lock);
if (fmt == 0)
panic("null fmt");
for(i = 0; (c = fmt[i] & 0xff) != 0; i++){
if(c != '%'){
consputc(c);
continue;
}
c = fmt[++i] & 0xff;
if(c == 0)
break;
switch(c){
case 'd':
printint(va_arg(ap, int), 10, 1);
break;
case 'x':
printint(va_arg(ap, int), 16, 0);
break;
case 'p':
printptr(va_arg(ap, uintp));
break;
case 's':
if((s = va_arg(ap, char*)) == 0)
s = "(null)";
for(; *s; s++)
consputc(*s);
break;
case '%':
consputc('%');
break;
default:
// Print unknown % sequence to draw attention.
consputc('%');
consputc(c);
break;
}
}
if(locking)
release(&cons.lock);
}
void
panic(char *s)
{
int i;
uintp pcs[10];
cli();
cons.locking = 0;
cprintf("cpu%d: panic: ", cpu->id);
cprintf(s);
cprintf("\n");
getcallerpcs(&s, pcs);
for(i=0; i<10; i++)
cprintf(" %p", pcs[i]);
panicked = 1; // freeze other CPU
for(;;)
;
}
//PAGEBREAK: 50
#define BACKSPACE 0x100
#define CRTPORT 0x3d4
static ushort *crt = (ushort*)P2V(0xb8000); // CGA memory
static void
cgaputc(int c)
{
int pos;
// Cursor position: col + 80*row.
outb(CRTPORT, 14);
pos = inb(CRTPORT+1) << 8;
outb(CRTPORT, 15);
pos |= inb(CRTPORT+1);
if(c == '\n')
pos += 80 - pos%80;
else if(c == BACKSPACE){
if(pos > 0) --pos;
} else
crt[pos++] = (c&0xff) | 0x0700; // black on white
if((pos/80) >= 24){ // Scroll up.
memmove(crt, crt+80, sizeof(crt[0])*23*80);
pos -= 80;
memset(crt+pos, 0, sizeof(crt[0])*(24*80 - pos));
}
outb(CRTPORT, 14);
outb(CRTPORT+1, pos>>8);
outb(CRTPORT, 15);
outb(CRTPORT+1, pos);
crt[pos] = ' ' | 0x0700;
}
void
consputc(int c)
{
if(panicked){
cli();
for(;;)
;
}
if(c == BACKSPACE){
uartputc('\b'); uartputc(' '); uartputc('\b');
} else
uartputc(c);
cgaputc(c);
}
#define INPUT_BUF 128
struct {
struct spinlock lock;
char buf[INPUT_BUF];
uint r; // Read index
uint w; // Write index
uint e; // Edit index
} input;
#define C(x) ((x)-'@') // Control-x
void
consoleintr(int (*getc)(void))
{
int c;
acquire(&input.lock);
while((c = getc()) >= 0){
switch(c){
case C('Z'): // reboot
lidt(0,0);
break;
case C('P'): // Process listing.
procdump();
break;
case C('U'): // Kill line.
while(input.e != input.w &&
input.buf[(input.e-1) % INPUT_BUF] != '\n'){
input.e--;
consputc(BACKSPACE);
}
break;
case C('H'): case '\x7f': // Backspace
if(input.e != input.w){
input.e--;
consputc(BACKSPACE);
}
break;
default:
if(c != 0 && input.e-input.r < INPUT_BUF){
c = (c == '\r') ? '\n' : c;
input.buf[input.e++ % INPUT_BUF] = c;
consputc(c);
if(c == '\n' || c == C('D') || input.e == input.r+INPUT_BUF){
input.w = input.e;
wakeup(&input.r);
}
}
break;
}
}
release(&input.lock);
}
int
consoleread(struct inode *ip, char *dst, int n)
{
uint target;
int c;
iunlock(ip);
target = n;
acquire(&input.lock);
while(n > 0){
while(input.r == input.w){
if(proc->killed){
release(&input.lock);
ilock(ip);
return -1;
}
sleep(&input.r, &input.lock);
}
c = input.buf[input.r++ % INPUT_BUF];
if(c == C('D')){ // EOF
if(n < target){
// Save ^D for next time, to make sure
// caller gets a 0-byte result.
input.r--;
}
break;
}
*dst++ = c;
--n;
if(c == '\n')
break;
}
release(&input.lock);
ilock(ip);
return target - n;
}
int
consolewrite(struct inode *ip, char *buf, int n)
{
int i;
iunlock(ip);
acquire(&cons.lock);
for(i = 0; i < n; i++)
consputc(buf[i] & 0xff);
release(&cons.lock);
ilock(ip);
return n;
}
void
consoleinit(void)
{
initlock(&cons.lock, "console");
initlock(&input.lock, "input");
devsw[CONSOLE].write = consolewrite;
devsw[CONSOLE].read = consoleread;
cons.locking = 1;
picenable(IRQ_KBD);
ioapicenable(IRQ_KBD, 0);
}
|
15315574eab52ec3dac5d80a7af06842a8f0ae7e
|
03666e5f961946fc1a0ac67781ac1425562ef0d7
|
/src/mdserver/rpc/SaveSessionRPC.C
|
76de3bc1fa31b08c0663b6c9ee3e032ef0f1b036
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
visit-dav/visit
|
e9f81b4d4b9b9930a0db9d5282cd1bcabf465e2e
|
601ae46e0bef2e18425b482a755d03490ade0493
|
refs/heads/develop
| 2023-09-06T08:19:38.397058
| 2023-09-05T21:29:32
| 2023-09-05T21:29:32
| 165,565,988
| 335
| 120
|
BSD-3-Clause
| 2023-09-14T00:53:37
| 2019-01-13T23:27:26
|
C
|
UTF-8
|
C
| false
| false
| 4,006
|
c
|
SaveSessionRPC.C
|
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
#include <SaveSessionRPC.h>
#include <DebugStream.h>
// *******************************************************************
// Constructor: SaveSessionRPC::SaveSessionRPC
//
// Purpose:
// This is the constructor.
//
// Arguments:
//
// Note:
//
// Programmer: David Camp
// Creation: Tue Jul 7 07:56:12 PDT 2015
//
// Modifications:
//
// *******************************************************************
SaveSessionRPC::SaveSessionRPC() : BlockingRPC("ss",NULL)
{
}
// *******************************************************************
// Denstructor: SaveSessionRPC::~SaveSessionRPC
//
// Purpose:
// This is the destructor.
//
// Arguments:
//
// Note:
//
// Programmer: David Camp
// Creation: Tue Jul 7 07:56:12 PDT 2015
//
// Modifications:
//
// *******************************************************************
SaveSessionRPC::~SaveSessionRPC()
{
}
// *******************************************************************
// Method: SaveSessionRPC::operator()
//
// Purpose:
// This is the RPC's invocation method.
//
// Arguments:
// filename : Filename to save session too.
// sessionFile : Session file to save.
//
// Note:
// If the RPC returned an error, throw an exception.
//
// Programmer: David Camp
// Creation: Tue Jul 7 07:56:12 PDT 2015
//
// Modifications:
//
// *******************************************************************
void
SaveSessionRPC::operator()(const std::string &_filename,
const std::string &_sessionFile)
{
if (DebugStream::Level3())
{
debug3 << "Executing SaveSessionRPC RPC"
<< "\n\t In Filename ='" << _filename.c_str() << "'"
<< endl;
}
filename = _filename;
sessionFile = _sessionFile;
Execute();
}
// *******************************************************************
// Method: SaveSessionRPC::SelectAll
//
// Purpose:
// Select all attributes for sending as parameters.
//
// Arguments:
//
// Note:
//
// Programmer: David Camp
// Creation: Tue Jul 7 07:56:12 PDT 2015
//
// Modifications:
//
// *******************************************************************
void
SaveSessionRPC::SelectAll()
{
Select(0, (void*)&filename);
Select(1, (void*)&sessionFile);
}
// ****************************************************************************
// Method: SaveSessionRPC::TypeName
//
// Purpose:
// Returns the name of the RPC.
//
// Arguments:
//
// Returns:
//
// Note:
//
// Programmer: David Camp
// Creation: Tue Jul 7 07:56:12 PDT 2015
//
// Modifications:
//
// ****************************************************************************
const std::string
SaveSessionRPC::TypeName() const
{
return "SaveSessionRPC";
}
// ****************************************************************************
// Method: SaveSessionRPC::SaveSessionFile
//
// Purpose:
// Save session file to file system.
//
// Arguments:
//
// Returns:
//
// Note:
//
// Programmer: David Camp
// Creation: Tue Jul 7 07:56:12 PDT 2015
//
// Modifications:
//
// ****************************************************************************
bool
SaveSessionRPC::SaveSessionFile()
{
if (DebugStream::Level3())
{
debug3 << "Executing SaveSessionFile" << endl;
}
ofstream sFile(filename.c_str(), (ios::out | ios::trunc));
if (sFile.is_open())
{
sFile << sessionFile;
sFile.close();
}
else
{
// Send error message with filename.
std::string errMessage("Failed to save remote session file: ");
errMessage += filename;
debug1 << errMessage << endl;
SendError(errMessage);
return( false );
}
return( true );
}
|
2e21b6b566a561dc8f1e3e2230d165adade47d3d
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/games/warp/score.h
|
97da045347f93d9adb83d1e37364f8e69d75d43a
|
[
"BSD-2-Clause"
] |
permissive
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 986
|
h
|
score.h
|
/* Header: score.h,v 7.0 86/10/08 15:13:21 lwall Exp */
/* Log: score.h,v
* Revision 7.0 86/10/08 15:13:21 lwall
* Split into separate files. Added amoebas and pirates.
*
*/
#define ENTBOUNDARY 100000 /* point boundary across which a new E is
awarded */
#define BASEBOUNDARY 250000 /* point boundary across which a new B is
awarded */
EXT int oldstatus;
EXT int oldetorp;
EXT int oldbtorp;
EXT int oldstrs;
EXT int oldenemies;
EXT long totalscore;
EXT long lastscore INIT(0);
EXT long curscore;
EXT long possiblescore;
EXT long oldeenergy;
EXT long oldbenergy;
EXT long oldcurscore;
EXT char savefilename[512];
#ifdef SCOREFULL
#define COMPOFF 0
#define COMPNAME longlognam
#define COMPLEN 24
#else
#define COMPOFF 24
#define COMPNAME longlognam
#define COMPLEN 8
#endif
EXT char longlognam[128];
EXT char c INIT(' ');
void score_init(void);
__dead void wscore(void);
void display_status(void);
void wavescore(void);
void score(void);
void save_game(void);
|
8f895e8491aec7d126c018e8fc7541075255e9ac
|
635a81339db4dc4ce21e72f2d77faa92461404d9
|
/include/perfetto/public/protos/trace/track_event/debug_annotation.pzc.h
|
d4152aec0aac4726eb64b55f01dfe2573f90c202
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
google/perfetto
|
b3fee34767174ca8c9e8e501eeec6f73fb3e0cda
|
4201d29ef8ce94a064dfbba6d9c9518b297dbc3f
|
refs/heads/master
| 2023-09-04T07:16:27.954459
| 2023-09-03T01:33:19
| 2023-09-03T01:33:19
| 227,091,502
| 1,920
| 274
|
Apache-2.0
| 2023-09-13T18:18:23
| 2019-12-10T10:32:44
|
C++
|
UTF-8
|
C
| false
| false
| 6,471
|
h
|
debug_annotation.pzc.h
|
/*
* Copyright (C) 2023 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.
*/
#ifndef INCLUDE_PERFETTO_PUBLIC_PROTOS_TRACE_TRACK_EVENT_DEBUG_ANNOTATION_PZC_H_
#define INCLUDE_PERFETTO_PUBLIC_PROTOS_TRACE_TRACK_EVENT_DEBUG_ANNOTATION_PZC_H_
#include <stdbool.h>
#include <stdint.h>
#include "perfetto/public/pb_macros.h"
PERFETTO_PB_MSG_DECL(perfetto_protos_DebugAnnotation);
PERFETTO_PB_MSG_DECL(perfetto_protos_DebugAnnotation_NestedValue);
PERFETTO_PB_ENUM_IN_MSG(perfetto_protos_DebugAnnotation_NestedValue,
NestedType){
PERFETTO_PB_ENUM_IN_MSG_ENTRY(perfetto_protos_DebugAnnotation_NestedValue,
UNSPECIFIED) = 0,
PERFETTO_PB_ENUM_IN_MSG_ENTRY(perfetto_protos_DebugAnnotation_NestedValue,
DICT) = 1,
PERFETTO_PB_ENUM_IN_MSG_ENTRY(perfetto_protos_DebugAnnotation_NestedValue,
ARRAY) = 2,
};
PERFETTO_PB_MSG(perfetto_protos_DebugAnnotationValueTypeName);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotationValueTypeName,
VARINT,
uint64_t,
iid,
1);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotationValueTypeName,
STRING,
const char*,
name,
2);
PERFETTO_PB_MSG(perfetto_protos_DebugAnnotationName);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotationName,
VARINT,
uint64_t,
iid,
1);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotationName,
STRING,
const char*,
name,
2);
PERFETTO_PB_MSG(perfetto_protos_DebugAnnotation);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
VARINT,
uint64_t,
name_iid,
1);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
STRING,
const char*,
name,
10);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation, VARINT, bool, bool_value, 2);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
VARINT,
uint64_t,
uint_value,
3);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
VARINT,
int64_t,
int_value,
4);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
FIXED64,
double,
double_value,
5);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
VARINT,
uint64_t,
pointer_value,
7);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
MSG,
perfetto_protos_DebugAnnotation_NestedValue,
nested_value,
8);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
STRING,
const char*,
legacy_json_value,
9);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
STRING,
const char*,
string_value,
6);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
VARINT,
uint64_t,
string_value_iid,
17);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
STRING,
const char*,
proto_type_name,
16);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
VARINT,
uint64_t,
proto_type_name_iid,
13);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
STRING,
const char*,
proto_value,
14);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
MSG,
perfetto_protos_DebugAnnotation,
dict_entries,
11);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation,
MSG,
perfetto_protos_DebugAnnotation,
array_values,
12);
PERFETTO_PB_MSG(perfetto_protos_DebugAnnotation_NestedValue);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation_NestedValue,
VARINT,
enum perfetto_protos_DebugAnnotation_NestedValue_NestedType,
nested_type,
1);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation_NestedValue,
STRING,
const char*,
dict_keys,
2);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation_NestedValue,
MSG,
perfetto_protos_DebugAnnotation_NestedValue,
dict_values,
3);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation_NestedValue,
MSG,
perfetto_protos_DebugAnnotation_NestedValue,
array_values,
4);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation_NestedValue,
VARINT,
int64_t,
int_value,
5);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation_NestedValue,
FIXED64,
double,
double_value,
6);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation_NestedValue,
VARINT,
bool,
bool_value,
7);
PERFETTO_PB_FIELD(perfetto_protos_DebugAnnotation_NestedValue,
STRING,
const char*,
string_value,
8);
#endif // INCLUDE_PERFETTO_PUBLIC_PROTOS_TRACE_TRACK_EVENT_DEBUG_ANNOTATION_PZC_H_
|
a457564b77c38a3d579ec205389282269c36ad35
|
a831bb046bdc40567682f01f2dc8e73a3803120e
|
/modules/mrcp-sofiasip/include/mrcp_sofiasip_task.h
|
dda068ff72f5383278cc510dc07d1e64d9879c5d
|
[
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-or-later"
] |
permissive
|
unispeech/unimrcp
|
5d9567c63d849c0e50bf0ee7b11259a798648d3e
|
9913f23691b3a1b8a7e84be5ba25478031352158
|
refs/heads/master
| 2023-08-05T08:22:40.918060
| 2023-08-01T17:35:29
| 2023-08-01T17:35:29
| 38,894,063
| 363
| 159
|
Apache-2.0
| 2023-05-17T12:50:27
| 2015-07-10T17:49:42
|
C
|
UTF-8
|
C
| false
| false
| 2,871
|
h
|
mrcp_sofiasip_task.h
|
/*
* Copyright 2008-2015 Arsen Chaloyan
*
* 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.
*/
#ifndef MRCP_SOFIASIP_TASK_H
#define MRCP_SOFIASIP_TASK_H
/**
* @file mrcp_sofiasip_task.h
* @brief Sofia-SIP Task
*/
#include "apt_task.h"
APT_BEGIN_EXTERN_C
/** Opaque Sofia-SIP task declaration */
typedef struct mrcp_sofia_task_t mrcp_sofia_task_t;
/** Function prototype to create a nua instance */
typedef nua_t* (*create_nua_f)(void *obj, su_root_t *root);
/**
* Create Sofia-SIP task.
* @param nua_creator the nua creator method
* @param obj the external object to pass to nua creator method
* @param msg_pool the pool of task messages
* @param pool the pool to allocate memory from
*/
APT_DECLARE(mrcp_sofia_task_t*) mrcp_sofia_task_create(
create_nua_f nua_creator,
void *obj,
apt_task_msg_pool_t *msg_pool,
apr_pool_t *pool);
/**
* Destroy Sofia-SIP task.
* @param task the task to destroy
*/
APT_DECLARE(apt_bool_t) mrcp_sofia_task_destroy(mrcp_sofia_task_t *task);
/**
* Start Sofia-SIP task.
* @param task the task to start
*/
APT_DECLARE(apt_bool_t) mrcp_sofia_task_start(mrcp_sofia_task_t *task);
/**
* Terminate Sofia-SIP task.
* @param task the task to terminate
*/
APT_DECLARE(apt_bool_t) mrcp_sofia_task_terminate(mrcp_sofia_task_t *task);
/**
* Break main loop of Sofia-SIP task.
* @param task the task to break
*/
APT_DECLARE(void) mrcp_sofia_task_break(mrcp_sofia_task_t *task);
/**
* Get task base.
* @param task the Sofia-SIP task to get task base from
*/
APT_DECLARE(apt_task_t*) mrcp_sofia_task_base_get(const mrcp_sofia_task_t *task);
/**
* Get task vtable.
* @param task the Sofia-SIP task to get vtable from
*/
APT_DECLARE(apt_task_vtable_t*) mrcp_sofia_task_vtable_get(const mrcp_sofia_task_t *task);
/**
* Get external object.
* @param task the Sofia-SIP task to get object from
*/
APT_DECLARE(void*) mrcp_sofia_task_object_get(const mrcp_sofia_task_t *task);
/**
* Get su_root object.
* @param task the Sofia-SIP task to get su_root object from
*/
APT_DECLARE(su_root_t*) mrcp_sofia_task_su_root_get(const mrcp_sofia_task_t *task);
/**
* Get nua object.
* @param task the Sofia-SIP task to get nua object from
*/
APT_DECLARE(nua_t*) mrcp_sofia_task_nua_get(const mrcp_sofia_task_t *task);
APT_END_EXTERN_C
#endif /* MRCP_SOFIASIP_TASK_H */
|
d1f35c4e077e77f8da1bba69792adf456d3d6081
|
56905dd2144fd3c6af5e437b54ce17bcef842be9
|
/src/modules/tag_header.private.h
|
011e39c199b960265f9a5b0d05fab124d6414bb3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
larsbs/id3v2lib
|
ba58231b7c541154422697ea9ce6c896a46d729a
|
26e2c38ee2be2fadd4e4b15301dd3beee94f63a2
|
refs/heads/dev
| 2023-06-09T23:51:11.050373
| 2023-05-29T18:04:14
| 2023-05-29T18:04:14
| 10,605,783
| 125
| 51
|
BSD-2-Clause
| 2023-05-29T18:04:14
| 2013-06-10T17:31:59
|
C
|
UTF-8
|
C
| false
| false
| 634
|
h
|
tag_header.private.h
|
/*
* This file is part of id3v2lib library
*
* Copyright (c) Lars Ruiz
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#ifndef id3v2lib_tag_header_private_h
#define id3v2lib_tag_header_private_h
#include "modules/tag_header.h"
typedef struct _CharStream CharStream;
ID3v2_TagHeader* TagHeader_new(
const int major_version,
const int minor_version,
const int flags,
const int tag_size,
const int extended_header_size
);
ID3v2_TagHeader* TagHeader_new_empty();
ID3v2_TagHeader* TagHeader_parse(CharStream* stream);
#endif
|
88081dcefcef756e9cd9557dbe636e312e3cefe9
|
3d144a23e67c839a4df1c073c6a2c842508f16b2
|
/test/Inputs/clang-importer-sdk/usr/include/macros_impl.h
|
d0eb54e7385a64cdfaaba863d6ca4a39a58e4bcc
|
[
"Apache-2.0",
"Swift-exception"
] |
permissive
|
apple/swift
|
c2724e388959f6623cf6e4ad6dc1cdd875fd0592
|
98ada1b200a43d090311b72eb45fe8ecebc97f81
|
refs/heads/main
| 2023-08-16T10:48:25.985330
| 2023-08-16T09:00:42
| 2023-08-16T09:00:42
| 44,838,949
| 78,897
| 15,074
|
Apache-2.0
| 2023-09-14T21:19:23
| 2015-10-23T21:15:07
|
C++
|
UTF-8
|
C
| false
| false
| 27
|
h
|
macros_impl.h
|
#define MACRO_FROM_IMPL 42
|
52236278c62ef57001c6b79c4a3b9dd04fc21bf3
|
84f1ce4838c39cec710818d69005f8919ec39994
|
/src/platform/fvp-a/fvpa_desc.c
|
7cad46adc7bd6140499c6bffe90d401753355f35
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
bao-project/bao-hypervisor
|
adb2689fdd690d10ea11fa693375c4043a9f9309
|
291cac3df9d5e0b4704006376196cd2231105704
|
refs/heads/main
| 2023-08-31T05:50:21.845457
| 2023-07-25T19:46:28
| 2023-08-22T12:09:57
| 233,099,706
| 231
| 78
|
Apache-2.0
| 2023-09-14T13:58:26
| 2020-01-10T17:42:11
|
C
|
UTF-8
|
C
| false
| false
| 708
|
c
|
fvpa_desc.c
|
/**
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) Bao Project and Contributors. All rights reserved.
*/
#include <platform.h>
struct platform platform = {
.cpu_num = 4,
.region_num = 1,
.regions = (struct mem_region[]) {
{
// DRAM, 0GB-2GB
.base = 0x80000000,
.size = 0x80000000
}
},
.console = {
.base = 0x1C090000 // UART0 (PL011)
},
.arch = {
.gic = {
.gicd_addr = 0x2F000000,
.gicc_addr = 0x2C000000,
.gich_addr = 0x2C010000,
.gicv_addr = 0x2C02F000,
.gicr_addr = 0x2F100000,
.maintenance_id = 25
},
}
};
|
c31cd9c129fc5707e1f787335a4d9d13628fe252
|
3e8f16e18eb953456ca399192ea8c54c1a218376
|
/src/cl_dll/in_defs.h
|
ad2a566769e05bce78b382d35e6b9d62cc631838
|
[] |
no_license
|
maxvollmer/Half-Life-VR
|
6437ffb3f6b098c0387b70c6e674572d94c0f190
|
f05957aa919765a1f53e54f3727e2c64ac1ec65f
|
refs/heads/main
| 2023-05-14T02:29:24.136125
| 2023-05-07T19:48:18
| 2023-05-07T19:48:18
| 102,905,323
| 241
| 42
| null | 2023-05-07T19:48:19
| 2017-09-08T21:19:41
|
C++
|
UTF-8
|
C
| false
| false
| 389
|
h
|
in_defs.h
|
//========= Copyright � 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#if !defined(IN_DEFSH)
#define IN_DEFSH
#pragma once
// up / down
#define PITCH 0
// left / right
#define YAW 1
// fall over
#define ROLL 2
#define DLLEXPORT __declspec(dllexport)
#endif
|
026cc131ba10a84ea8614876dbd94dd814e576da
|
2f60633ec3120ebf07e458f9ad196c75c15c90ca
|
/examples/common/nanovg/nanovg.cpp
|
3a0af013e6130197af15a04635fc0d0c7407c92b
|
[
"MIT",
"LicenseRef-scancode-free-unknown",
"BSD-2-Clause"
] |
permissive
|
bkaradzic/bgfx
|
1f51d0222c4428e87e36a99d788fb909027ad504
|
98f16cd1252e62e9fc76c3b41ab86fcc0fe149a7
|
refs/heads/master
| 2023-08-31T18:00:06.315091
| 2023-08-29T03:07:37
| 2023-08-29T03:07:37
| 3,925,242
| 13,956
| 2,454
|
BSD-2-Clause
| 2023-09-11T03:52:45
| 2012-04-04T03:39:04
|
C++
|
UTF-8
|
C
| false
| false
| 76,242
|
cpp
|
nanovg.cpp
|
//
// Copyright (c) 2013 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <memory.h>
#include "nanovg.h"
#include <bx/bx.h>
BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4701) // error C4701: potentially uninitialized local variable 'cint' used
// -Wunused-function and 4505 must be file scope, can't be disabled between push/pop.
BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-function");
BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4505) // error C4505: '' : unreferenced local function has been removed
BX_PRAGMA_DIAGNOSTIC_PUSH();
BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-parameter");
BX_PRAGMA_DIAGNOSTIC_IGNORED_GCC("-Wunused-result");
#define FONTSTASH_IMPLEMENTATION
#include "fontstash.h"
BX_PRAGMA_DIAGNOSTIC_POP();
#ifdef _MSC_VER
#pragma warning(disable: 4100) // unreferenced formal parameter
#pragma warning(disable: 4127) // conditional expression is constant
#pragma warning(disable: 4204) // nonstandard extension used : non-constant aggregate initializer
#pragma warning(disable: 4706) // assignment within conditional expression
#endif
#define NVG_INIT_FONTIMAGE_SIZE 512
#define NVG_MAX_FONTIMAGE_SIZE 2048
#define NVG_MAX_FONTIMAGES 4
#define NVG_INIT_COMMANDS_SIZE 256
#define NVG_INIT_POINTS_SIZE 128
#define NVG_INIT_PATHS_SIZE 16
#define NVG_INIT_VERTS_SIZE 256
#define NVG_MAX_STATES 32
#define NVG_KAPPA90 0.5522847493f // Length proportional to radius of a cubic bezier handle for 90deg arcs.
#define NVG_COUNTOF(arr) (sizeof(arr) / sizeof(0[arr]))
enum NVGcommands {
NVG_MOVETO = 0,
NVG_LINETO = 1,
NVG_BEZIERTO = 2,
NVG_CLOSE = 3,
NVG_WINDING = 4,
};
enum NVGpointFlags
{
NVG_PT_CORNER = 0x01,
NVG_PT_LEFT = 0x02,
NVG_PT_BEVEL = 0x04,
NVG_PR_INNERBEVEL = 0x08,
};
struct NVGstate {
NVGcompositeOperationState compositeOperation;
int shapeAntiAlias;
NVGpaint fill;
NVGpaint stroke;
float strokeWidth;
float miterLimit;
int lineJoin;
int lineCap;
float alpha;
float xform[6];
NVGscissor scissor;
float fontSize;
float letterSpacing;
float lineHeight;
float fontBlur;
int textAlign;
int fontId;
};
typedef struct NVGstate NVGstate;
struct NVGpoint {
float x,y;
float dx, dy;
float len;
float dmx, dmy;
unsigned char flags;
};
typedef struct NVGpoint NVGpoint;
struct NVGpathCache {
NVGpoint* points;
int npoints;
int cpoints;
NVGpath* paths;
int npaths;
int cpaths;
NVGvertex* verts;
int nverts;
int cverts;
float bounds[4];
};
typedef struct NVGpathCache NVGpathCache;
struct NVGcontext {
NVGparams params;
float* commands;
int ccommands;
int ncommands;
float commandx, commandy;
NVGstate states[NVG_MAX_STATES];
int nstates;
NVGpathCache* cache;
float tessTol;
float distTol;
float fringeWidth;
float devicePxRatio;
struct FONScontext* fs;
int fontImages[NVG_MAX_FONTIMAGES];
int fontImageIdx;
int drawCallCount;
int fillTriCount;
int strokeTriCount;
int textTriCount;
};
static float nvg__sqrtf(float a) { return sqrtf(a); }
static float nvg__modf(float a, float b) { return fmodf(a, b); }
static float nvg__sinf(float a) { return sinf(a); }
static float nvg__cosf(float a) { return cosf(a); }
static float nvg__tanf(float a) { return tanf(a); }
static float nvg__atan2f(float a,float b) { return atan2f(a, b); }
static float nvg__acosf(float a) { return acosf(a); }
static int nvg__mini(int a, int b) { return a < b ? a : b; }
static int nvg__maxi(int a, int b) { return a > b ? a : b; }
static int nvg__clampi(int a, int mn, int mx) { return a < mn ? mn : (a > mx ? mx : a); }
static float nvg__minf(float a, float b) { return a < b ? a : b; }
static float nvg__maxf(float a, float b) { return a > b ? a : b; }
static float nvg__absf(float a) { return a >= 0.0f ? a : -a; }
static float nvg__signf(float a) { return a >= 0.0f ? 1.0f : -1.0f; }
static float nvg__clampf(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); }
static float nvg__cross(float dx0, float dy0, float dx1, float dy1) { return dx1*dy0 - dx0*dy1; }
static float nvg__normalize(float *x, float* y)
{
float d = nvg__sqrtf((*x)*(*x) + (*y)*(*y));
if (d > 1e-6f) {
float id = 1.0f / d;
*x *= id;
*y *= id;
}
return d;
}
static void nvg__deletePathCache(NVGpathCache* c)
{
if (c == NULL) return;
if (c->points != NULL) free(c->points);
if (c->paths != NULL) free(c->paths);
if (c->verts != NULL) free(c->verts);
free(c);
}
static NVGpathCache* nvg__allocPathCache(void)
{
NVGpathCache* c = (NVGpathCache*)malloc(sizeof(NVGpathCache));
if (c == NULL) goto error;
memset(c, 0, sizeof(NVGpathCache));
c->points = (NVGpoint*)malloc(sizeof(NVGpoint)*NVG_INIT_POINTS_SIZE);
if (!c->points) goto error;
c->npoints = 0;
c->cpoints = NVG_INIT_POINTS_SIZE;
c->paths = (NVGpath*)malloc(sizeof(NVGpath)*NVG_INIT_PATHS_SIZE);
if (!c->paths) goto error;
c->npaths = 0;
c->cpaths = NVG_INIT_PATHS_SIZE;
c->verts = (NVGvertex*)malloc(sizeof(NVGvertex)*NVG_INIT_VERTS_SIZE);
if (!c->verts) goto error;
c->nverts = 0;
c->cverts = NVG_INIT_VERTS_SIZE;
return c;
error:
nvg__deletePathCache(c);
return NULL;
}
static void nvg__setDevicePixelRatio(NVGcontext* ctx, float ratio)
{
ctx->tessTol = 0.25f / ratio;
ctx->distTol = 0.01f / ratio;
ctx->fringeWidth = 1.0f / ratio;
ctx->devicePxRatio = ratio;
}
static NVGcompositeOperationState nvg__compositeOperationState(int op)
{
int sfactor, dfactor;
if (op == NVG_SOURCE_OVER)
{
sfactor = NVG_ONE;
dfactor = NVG_ONE_MINUS_SRC_ALPHA;
}
else if (op == NVG_SOURCE_IN)
{
sfactor = NVG_DST_ALPHA;
dfactor = NVG_ZERO;
}
else if (op == NVG_SOURCE_OUT)
{
sfactor = NVG_ONE_MINUS_DST_ALPHA;
dfactor = NVG_ZERO;
}
else if (op == NVG_ATOP)
{
sfactor = NVG_DST_ALPHA;
dfactor = NVG_ONE_MINUS_SRC_ALPHA;
}
else if (op == NVG_DESTINATION_OVER)
{
sfactor = NVG_ONE_MINUS_DST_ALPHA;
dfactor = NVG_ONE;
}
else if (op == NVG_DESTINATION_IN)
{
sfactor = NVG_ZERO;
dfactor = NVG_SRC_ALPHA;
}
else if (op == NVG_DESTINATION_OUT)
{
sfactor = NVG_ZERO;
dfactor = NVG_ONE_MINUS_SRC_ALPHA;
}
else if (op == NVG_DESTINATION_ATOP)
{
sfactor = NVG_ONE_MINUS_DST_ALPHA;
dfactor = NVG_SRC_ALPHA;
}
else if (op == NVG_LIGHTER)
{
sfactor = NVG_ONE;
dfactor = NVG_ONE;
}
else if (op == NVG_COPY)
{
sfactor = NVG_ONE;
dfactor = NVG_ZERO;
}
else if (op == NVG_XOR)
{
sfactor = NVG_ONE_MINUS_DST_ALPHA;
dfactor = NVG_ONE_MINUS_SRC_ALPHA;
}
else
{
sfactor = NVG_ONE;
dfactor = NVG_ZERO;
}
NVGcompositeOperationState state;
state.srcRGB = sfactor;
state.dstRGB = dfactor;
state.srcAlpha = sfactor;
state.dstAlpha = dfactor;
return state;
}
static NVGstate* nvg__getState(NVGcontext* ctx)
{
return &ctx->states[ctx->nstates-1];
}
NVGcontext* nvgCreateInternal(NVGparams* params)
{
FONSparams fontParams;
NVGcontext* ctx = (NVGcontext*)malloc(sizeof(NVGcontext));
int i;
if (ctx == NULL) goto error;
memset(ctx, 0, sizeof(NVGcontext));
ctx->params = *params;
for (i = 0; i < NVG_MAX_FONTIMAGES; i++)
ctx->fontImages[i] = 0;
ctx->commands = (float*)malloc(sizeof(float)*NVG_INIT_COMMANDS_SIZE);
if (!ctx->commands) goto error;
ctx->ncommands = 0;
ctx->ccommands = NVG_INIT_COMMANDS_SIZE;
ctx->cache = nvg__allocPathCache();
if (ctx->cache == NULL) goto error;
nvgSave(ctx);
nvgReset(ctx);
nvg__setDevicePixelRatio(ctx, 1.0f);
if (ctx->params.renderCreate(ctx->params.userPtr) == 0) goto error;
// Init font rendering
memset(&fontParams, 0, sizeof(fontParams));
fontParams.width = NVG_INIT_FONTIMAGE_SIZE;
fontParams.height = NVG_INIT_FONTIMAGE_SIZE;
fontParams.flags = FONS_ZERO_TOPLEFT;
fontParams.renderCreate = NULL;
fontParams.renderUpdate = NULL;
fontParams.renderDraw = NULL;
fontParams.renderDelete = NULL;
fontParams.userPtr = NULL;
ctx->fs = fonsCreateInternal(&fontParams);
if (ctx->fs == NULL) goto error;
// Create font texture
ctx->fontImages[0] = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, fontParams.width, fontParams.height, 0, NULL);
if (ctx->fontImages[0] == 0) goto error;
ctx->fontImageIdx = 0;
return ctx;
error:
nvgDeleteInternal(ctx);
return 0;
}
NVGparams* nvgInternalParams(NVGcontext* ctx)
{
return &ctx->params;
}
void nvgDeleteInternal(NVGcontext* ctx)
{
int i;
if (ctx == NULL) return;
if (ctx->commands != NULL) free(ctx->commands);
if (ctx->cache != NULL) nvg__deletePathCache(ctx->cache);
if (ctx->fs)
fonsDeleteInternal(ctx->fs);
for (i = 0; i < NVG_MAX_FONTIMAGES; i++) {
if (ctx->fontImages[i] != 0) {
nvgDeleteImage(ctx, ctx->fontImages[i]);
ctx->fontImages[i] = 0;
}
}
if (ctx->params.renderDelete != NULL)
ctx->params.renderDelete(ctx->params.userPtr);
free(ctx);
}
void nvgBeginFrame(NVGcontext* ctx, float windowWidth, float windowHeight, float devicePixelRatio)
{
/* printf("Tris: draws:%d fill:%d stroke:%d text:%d TOT:%d\n",
ctx->drawCallCount, ctx->fillTriCount, ctx->strokeTriCount, ctx->textTriCount,
ctx->fillTriCount+ctx->strokeTriCount+ctx->textTriCount);*/
ctx->nstates = 0;
nvgSave(ctx);
nvgReset(ctx);
nvg__setDevicePixelRatio(ctx, devicePixelRatio);
ctx->params.renderViewport(ctx->params.userPtr, windowWidth, windowHeight, devicePixelRatio);
ctx->drawCallCount = 0;
ctx->fillTriCount = 0;
ctx->strokeTriCount = 0;
ctx->textTriCount = 0;
}
void nvgCancelFrame(NVGcontext* ctx)
{
ctx->params.renderCancel(ctx->params.userPtr);
}
void nvgEndFrame(NVGcontext* ctx)
{
ctx->params.renderFlush(ctx->params.userPtr);
if (ctx->fontImageIdx != 0) {
int fontImage = ctx->fontImages[ctx->fontImageIdx];
int i, j, iw, ih;
// delete images that smaller than current one
if (fontImage == 0)
return;
nvgImageSize(ctx, fontImage, &iw, &ih);
for (i = j = 0; i < ctx->fontImageIdx; i++) {
if (ctx->fontImages[i] != 0) {
int nw, nh;
nvgImageSize(ctx, ctx->fontImages[i], &nw, &nh);
if (nw < iw || nh < ih)
nvgDeleteImage(ctx, ctx->fontImages[i]);
else
ctx->fontImages[j++] = ctx->fontImages[i];
}
}
// make current font image to first
ctx->fontImages[j++] = ctx->fontImages[0];
ctx->fontImages[0] = fontImage;
ctx->fontImageIdx = 0;
// clear all images after j
for (i = j; i < NVG_MAX_FONTIMAGES; i++)
ctx->fontImages[i] = 0;
}
}
NVGcolor nvgRGB(unsigned char r, unsigned char g, unsigned char b)
{
return nvgRGBA(r,g,b,255);
}
NVGcolor nvgRGBf(float r, float g, float b)
{
return nvgRGBAf(r,g,b,1.0f);
}
NVGcolor nvgRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
{
NVGcolor color;
// Use longer initialization to suppress warning.
color.r = r / 255.0f;
color.g = g / 255.0f;
color.b = b / 255.0f;
color.a = a / 255.0f;
return color;
}
NVGcolor nvgRGBAf(float r, float g, float b, float a)
{
NVGcolor color;
// Use longer initialization to suppress warning.
color.r = r;
color.g = g;
color.b = b;
color.a = a;
return color;
}
NVGcolor nvgTransRGBA(NVGcolor c, unsigned char a)
{
c.a = a / 255.0f;
return c;
}
NVGcolor nvgTransRGBAf(NVGcolor c, float a)
{
c.a = a;
return c;
}
NVGcolor nvgLerpRGBA(NVGcolor c0, NVGcolor c1, float u)
{
int i;
float oneminu;
NVGcolor cint = {{{0}}};
u = nvg__clampf(u, 0.0f, 1.0f);
oneminu = 1.0f - u;
for( i = 0; i <4; i++ )
{
cint.rgba[i] = c0.rgba[i] * oneminu + c1.rgba[i] * u;
}
return cint;
}
NVGcolor nvgHSL(float h, float s, float l)
{
return nvgHSLA(h,s,l,255);
}
static float nvg__hue(float h, float m1, float m2)
{
if (h < 0) h += 1;
if (h > 1) h -= 1;
if (h < 1.0f/6.0f)
return m1 + (m2 - m1) * h * 6.0f;
else if (h < 3.0f/6.0f)
return m2;
else if (h < 4.0f/6.0f)
return m1 + (m2 - m1) * (2.0f/3.0f - h) * 6.0f;
return m1;
}
NVGcolor nvgHSLA(float h, float s, float l, unsigned char a)
{
float m1, m2;
NVGcolor col;
h = nvg__modf(h, 1.0f);
if (h < 0.0f) h += 1.0f;
s = nvg__clampf(s, 0.0f, 1.0f);
l = nvg__clampf(l, 0.0f, 1.0f);
m2 = l <= 0.5f ? (l * (1 + s)) : (l + s - l * s);
m1 = 2 * l - m2;
col.r = nvg__clampf(nvg__hue(h + 1.0f/3.0f, m1, m2), 0.0f, 1.0f);
col.g = nvg__clampf(nvg__hue(h, m1, m2), 0.0f, 1.0f);
col.b = nvg__clampf(nvg__hue(h - 1.0f/3.0f, m1, m2), 0.0f, 1.0f);
col.a = a/255.0f;
return col;
}
void nvgTransformIdentity(float* t)
{
t[0] = 1.0f; t[1] = 0.0f;
t[2] = 0.0f; t[3] = 1.0f;
t[4] = 0.0f; t[5] = 0.0f;
}
void nvgTransformTranslate(float* t, float tx, float ty)
{
t[0] = 1.0f; t[1] = 0.0f;
t[2] = 0.0f; t[3] = 1.0f;
t[4] = tx; t[5] = ty;
}
void nvgTransformScale(float* t, float sx, float sy)
{
t[0] = sx; t[1] = 0.0f;
t[2] = 0.0f; t[3] = sy;
t[4] = 0.0f; t[5] = 0.0f;
}
void nvgTransformRotate(float* t, float a)
{
float cs = nvg__cosf(a), sn = nvg__sinf(a);
t[0] = cs; t[1] = sn;
t[2] = -sn; t[3] = cs;
t[4] = 0.0f; t[5] = 0.0f;
}
void nvgTransformSkewX(float* t, float a)
{
t[0] = 1.0f; t[1] = 0.0f;
t[2] = nvg__tanf(a); t[3] = 1.0f;
t[4] = 0.0f; t[5] = 0.0f;
}
void nvgTransformSkewY(float* t, float a)
{
t[0] = 1.0f; t[1] = nvg__tanf(a);
t[2] = 0.0f; t[3] = 1.0f;
t[4] = 0.0f; t[5] = 0.0f;
}
void nvgTransformMultiply(float* t, const float* s)
{
float t0 = t[0] * s[0] + t[1] * s[2];
float t2 = t[2] * s[0] + t[3] * s[2];
float t4 = t[4] * s[0] + t[5] * s[2] + s[4];
t[1] = t[0] * s[1] + t[1] * s[3];
t[3] = t[2] * s[1] + t[3] * s[3];
t[5] = t[4] * s[1] + t[5] * s[3] + s[5];
t[0] = t0;
t[2] = t2;
t[4] = t4;
}
void nvgTransformPremultiply(float* t, const float* s)
{
float s2[6];
memcpy(s2, s, sizeof(float)*6);
nvgTransformMultiply(s2, t);
memcpy(t, s2, sizeof(float)*6);
}
int nvgTransformInverse(float* inv, const float* t)
{
double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1];
if (det > -1e-6 && det < 1e-6) {
nvgTransformIdentity(inv);
return 0;
}
invdet = 1.0 / det;
inv[0] = (float)(t[3] * invdet);
inv[2] = (float)(-t[2] * invdet);
inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet);
inv[1] = (float)(-t[1] * invdet);
inv[3] = (float)(t[0] * invdet);
inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet);
return 1;
}
void nvgTransformPoint(float* dx, float* dy, const float* t, float sx, float sy)
{
*dx = sx*t[0] + sy*t[2] + t[4];
*dy = sx*t[1] + sy*t[3] + t[5];
}
float nvgDegToRad(float deg)
{
return deg / 180.0f * NVG_PI;
}
float nvgRadToDeg(float rad)
{
return rad / NVG_PI * 180.0f;
}
static void nvg__setPaintColor(NVGpaint* p, NVGcolor color)
{
memset(p, 0, sizeof(*p));
nvgTransformIdentity(p->xform);
p->radius = 0.0f;
p->feather = 1.0f;
p->innerColor = color;
p->outerColor = color;
}
// State handling
void nvgSave(NVGcontext* ctx)
{
if (ctx->nstates >= NVG_MAX_STATES)
return;
if (ctx->nstates > 0)
memcpy(&ctx->states[ctx->nstates], &ctx->states[ctx->nstates-1], sizeof(NVGstate));
ctx->nstates++;
}
void nvgRestore(NVGcontext* ctx)
{
if (ctx->nstates <= 1)
return;
ctx->nstates--;
}
void nvgReset(NVGcontext* ctx)
{
NVGstate* state = nvg__getState(ctx);
memset(state, 0, sizeof(*state));
nvg__setPaintColor(&state->fill, nvgRGBA(255,255,255,255));
nvg__setPaintColor(&state->stroke, nvgRGBA(0,0,0,255));
state->compositeOperation = nvg__compositeOperationState(NVG_SOURCE_OVER);
state->shapeAntiAlias = 1;
state->strokeWidth = 1.0f;
state->miterLimit = 10.0f;
state->lineCap = NVG_BUTT;
state->lineJoin = NVG_MITER;
state->alpha = 1.0f;
nvgTransformIdentity(state->xform);
state->scissor.extent[0] = -1.0f;
state->scissor.extent[1] = -1.0f;
state->fontSize = 16.0f;
state->letterSpacing = 0.0f;
state->lineHeight = 1.0f;
state->fontBlur = 0.0f;
state->textAlign = NVG_ALIGN_LEFT | NVG_ALIGN_BASELINE;
state->fontId = 0;
}
// State setting
void nvgShapeAntiAlias(NVGcontext* ctx, int enabled)
{
NVGstate* state = nvg__getState(ctx);
state->shapeAntiAlias = enabled;
}
void nvgStrokeWidth(NVGcontext* ctx, float width)
{
NVGstate* state = nvg__getState(ctx);
state->strokeWidth = width;
}
void nvgMiterLimit(NVGcontext* ctx, float limit)
{
NVGstate* state = nvg__getState(ctx);
state->miterLimit = limit;
}
void nvgLineCap(NVGcontext* ctx, int cap)
{
NVGstate* state = nvg__getState(ctx);
state->lineCap = cap;
}
void nvgLineJoin(NVGcontext* ctx, int join)
{
NVGstate* state = nvg__getState(ctx);
state->lineJoin = join;
}
void nvgGlobalAlpha(NVGcontext* ctx, float alpha)
{
NVGstate* state = nvg__getState(ctx);
state->alpha = alpha;
}
void nvgTransform(NVGcontext* ctx, float a, float b, float c, float d, float e, float f)
{
NVGstate* state = nvg__getState(ctx);
float t[6] = { a, b, c, d, e, f };
nvgTransformPremultiply(state->xform, t);
}
void nvgResetTransform(NVGcontext* ctx)
{
NVGstate* state = nvg__getState(ctx);
nvgTransformIdentity(state->xform);
}
void nvgTranslate(NVGcontext* ctx, float x, float y)
{
NVGstate* state = nvg__getState(ctx);
float t[6];
nvgTransformTranslate(t, x,y);
nvgTransformPremultiply(state->xform, t);
}
void nvgRotate(NVGcontext* ctx, float angle)
{
NVGstate* state = nvg__getState(ctx);
float t[6];
nvgTransformRotate(t, angle);
nvgTransformPremultiply(state->xform, t);
}
void nvgSkewX(NVGcontext* ctx, float angle)
{
NVGstate* state = nvg__getState(ctx);
float t[6];
nvgTransformSkewX(t, angle);
nvgTransformPremultiply(state->xform, t);
}
void nvgSkewY(NVGcontext* ctx, float angle)
{
NVGstate* state = nvg__getState(ctx);
float t[6];
nvgTransformSkewY(t, angle);
nvgTransformPremultiply(state->xform, t);
}
void nvgScale(NVGcontext* ctx, float x, float y)
{
NVGstate* state = nvg__getState(ctx);
float t[6];
nvgTransformScale(t, x,y);
nvgTransformPremultiply(state->xform, t);
}
void nvgCurrentTransform(NVGcontext* ctx, float* xform)
{
NVGstate* state = nvg__getState(ctx);
if (xform == NULL) return;
memcpy(xform, state->xform, sizeof(float)*6);
}
void nvgStrokeColor(NVGcontext* ctx, NVGcolor color)
{
NVGstate* state = nvg__getState(ctx);
nvg__setPaintColor(&state->stroke, color);
}
void nvgStrokePaint(NVGcontext* ctx, NVGpaint paint)
{
NVGstate* state = nvg__getState(ctx);
state->stroke = paint;
nvgTransformMultiply(state->stroke.xform, state->xform);
}
void nvgFillColor(NVGcontext* ctx, NVGcolor color)
{
NVGstate* state = nvg__getState(ctx);
nvg__setPaintColor(&state->fill, color);
}
void nvgFillPaint(NVGcontext* ctx, NVGpaint paint)
{
NVGstate* state = nvg__getState(ctx);
state->fill = paint;
nvgTransformMultiply(state->fill.xform, state->xform);
}
int nvgCreateImageRGBA(NVGcontext* ctx, int w, int h, int imageFlags, const unsigned char* data)
{
return ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_RGBA, w, h, imageFlags, data);
}
void nvgUpdateImage(NVGcontext* ctx, int image, const unsigned char* data)
{
int w, h;
ctx->params.renderGetTextureSize(ctx->params.userPtr, image, &w, &h);
ctx->params.renderUpdateTexture(ctx->params.userPtr, image, 0,0, w,h, data);
}
void nvgImageSize(NVGcontext* ctx, int image, int* w, int* h)
{
ctx->params.renderGetTextureSize(ctx->params.userPtr, image, w, h);
}
void nvgDeleteImage(NVGcontext* ctx, int image)
{
ctx->params.renderDeleteTexture(ctx->params.userPtr, image);
}
NVGpaint nvgLinearGradient(NVGcontext* ctx,
float sx, float sy, float ex, float ey,
NVGcolor icol, NVGcolor ocol)
{
NVGpaint p;
float dx, dy, d;
const float large = 1e5;
NVG_NOTUSED(ctx);
memset(&p, 0, sizeof(p));
// Calculate transform aligned to the line
dx = ex - sx;
dy = ey - sy;
d = sqrtf(dx*dx + dy*dy);
if (d > 0.0001f) {
dx /= d;
dy /= d;
} else {
dx = 0;
dy = 1;
}
p.xform[0] = dy; p.xform[1] = -dx;
p.xform[2] = dx; p.xform[3] = dy;
p.xform[4] = sx - dx*large; p.xform[5] = sy - dy*large;
p.extent[0] = large;
p.extent[1] = large + d*0.5f;
p.radius = 0.0f;
p.feather = nvg__maxf(1.0f, d);
p.innerColor = icol;
p.outerColor = ocol;
return p;
}
NVGpaint nvgRadialGradient(NVGcontext* ctx,
float cx, float cy, float inr, float outr,
NVGcolor icol, NVGcolor ocol)
{
NVGpaint p;
float r = (inr+outr)*0.5f;
float f = (outr-inr);
NVG_NOTUSED(ctx);
memset(&p, 0, sizeof(p));
nvgTransformIdentity(p.xform);
p.xform[4] = cx;
p.xform[5] = cy;
p.extent[0] = r;
p.extent[1] = r;
p.radius = r;
p.feather = nvg__maxf(1.0f, f);
p.innerColor = icol;
p.outerColor = ocol;
return p;
}
NVGpaint nvgBoxGradient(NVGcontext* ctx,
float x, float y, float w, float h, float r, float f,
NVGcolor icol, NVGcolor ocol)
{
NVGpaint p;
NVG_NOTUSED(ctx);
memset(&p, 0, sizeof(p));
nvgTransformIdentity(p.xform);
p.xform[4] = x+w*0.5f;
p.xform[5] = y+h*0.5f;
p.extent[0] = w*0.5f;
p.extent[1] = h*0.5f;
p.radius = r;
p.feather = nvg__maxf(1.0f, f);
p.innerColor = icol;
p.outerColor = ocol;
return p;
}
NVGpaint nvgImagePattern(NVGcontext* ctx,
float cx, float cy, float w, float h, float angle,
int image, float alpha)
{
NVGpaint p;
NVG_NOTUSED(ctx);
memset(&p, 0, sizeof(p));
nvgTransformRotate(p.xform, angle);
p.xform[4] = cx;
p.xform[5] = cy;
p.extent[0] = w;
p.extent[1] = h;
p.image = image;
p.innerColor = p.outerColor = nvgRGBAf(1,1,1,alpha);
return p;
}
// Scissoring
void nvgScissor(NVGcontext* ctx, float x, float y, float w, float h)
{
NVGstate* state = nvg__getState(ctx);
w = nvg__maxf(0.0f, w);
h = nvg__maxf(0.0f, h);
nvgTransformIdentity(state->scissor.xform);
state->scissor.xform[4] = x+w*0.5f;
state->scissor.xform[5] = y+h*0.5f;
nvgTransformMultiply(state->scissor.xform, state->xform);
state->scissor.extent[0] = w*0.5f;
state->scissor.extent[1] = h*0.5f;
}
static void nvg__isectRects(float* dst,
float ax, float ay, float aw, float ah,
float bx, float by, float bw, float bh)
{
float minx = nvg__maxf(ax, bx);
float miny = nvg__maxf(ay, by);
float maxx = nvg__minf(ax+aw, bx+bw);
float maxy = nvg__minf(ay+ah, by+bh);
dst[0] = minx;
dst[1] = miny;
dst[2] = nvg__maxf(0.0f, maxx - minx);
dst[3] = nvg__maxf(0.0f, maxy - miny);
}
void nvgIntersectScissor(NVGcontext* ctx, float x, float y, float w, float h)
{
NVGstate* state = nvg__getState(ctx);
float pxform[6], invxorm[6];
float rect[4];
float ex, ey, tex, tey;
// If no previous scissor has been set, set the scissor as current scissor.
if (state->scissor.extent[0] < 0) {
nvgScissor(ctx, x, y, w, h);
return;
}
// Transform the current scissor rect into current transform space.
// If there is difference in rotation, this will be approximation.
memcpy(pxform, state->scissor.xform, sizeof(float)*6);
ex = state->scissor.extent[0];
ey = state->scissor.extent[1];
nvgTransformInverse(invxorm, state->xform);
nvgTransformMultiply(pxform, invxorm);
tex = ex*nvg__absf(pxform[0]) + ey*nvg__absf(pxform[2]);
tey = ex*nvg__absf(pxform[1]) + ey*nvg__absf(pxform[3]);
// Intersect rects.
nvg__isectRects(rect, pxform[4]-tex,pxform[5]-tey,tex*2,tey*2, x,y,w,h);
nvgScissor(ctx, rect[0], rect[1], rect[2], rect[3]);
}
void nvgResetScissor(NVGcontext* ctx)
{
NVGstate* state = nvg__getState(ctx);
memset(state->scissor.xform, 0, sizeof(state->scissor.xform));
state->scissor.extent[0] = -1.0f;
state->scissor.extent[1] = -1.0f;
}
// Global composite operation.
void nvgGlobalCompositeOperation(NVGcontext* ctx, int op)
{
NVGstate* state = nvg__getState(ctx);
state->compositeOperation = nvg__compositeOperationState(op);
}
void nvgGlobalCompositeBlendFunc(NVGcontext* ctx, int sfactor, int dfactor)
{
nvgGlobalCompositeBlendFuncSeparate(ctx, sfactor, dfactor, sfactor, dfactor);
}
void nvgGlobalCompositeBlendFuncSeparate(NVGcontext* ctx, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha)
{
NVGcompositeOperationState op;
op.srcRGB = srcRGB;
op.dstRGB = dstRGB;
op.srcAlpha = srcAlpha;
op.dstAlpha = dstAlpha;
NVGstate* state = nvg__getState(ctx);
state->compositeOperation = op;
}
static int nvg__ptEquals(float x1, float y1, float x2, float y2, float tol)
{
float dx = x2 - x1;
float dy = y2 - y1;
return dx*dx + dy*dy < tol*tol;
}
static float nvg__distPtSeg(float x, float y, float px, float py, float qx, float qy)
{
float pqx, pqy, dx, dy, d, t;
pqx = qx-px;
pqy = qy-py;
dx = x-px;
dy = y-py;
d = pqx*pqx + pqy*pqy;
t = pqx*dx + pqy*dy;
if (d > 0) t /= d;
if (t < 0) t = 0;
else if (t > 1) t = 1;
dx = px + t*pqx - x;
dy = py + t*pqy - y;
return dx*dx + dy*dy;
}
static void nvg__appendCommands(NVGcontext* ctx, float* vals, int nvals)
{
NVGstate* state = nvg__getState(ctx);
int i;
if (ctx->ncommands+nvals > ctx->ccommands) {
float* commands;
int ccommands = ctx->ncommands+nvals + ctx->ccommands/2;
commands = (float*)realloc(ctx->commands, sizeof(float)*ccommands);
if (commands == NULL) return;
ctx->commands = commands;
ctx->ccommands = ccommands;
}
if ((int)vals[0] != NVG_CLOSE && (int)vals[0] != NVG_WINDING) {
ctx->commandx = vals[nvals-2];
ctx->commandy = vals[nvals-1];
}
// transform commands
i = 0;
while (i < nvals) {
int cmd = (int)vals[i];
switch (cmd) {
case NVG_MOVETO:
nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
i += 3;
break;
case NVG_LINETO:
nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
i += 3;
break;
case NVG_BEZIERTO:
nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
nvgTransformPoint(&vals[i+3],&vals[i+4], state->xform, vals[i+3],vals[i+4]);
nvgTransformPoint(&vals[i+5],&vals[i+6], state->xform, vals[i+5],vals[i+6]);
i += 7;
break;
case NVG_CLOSE:
i++;
break;
case NVG_WINDING:
i += 2;
break;
default:
i++;
}
}
memcpy(&ctx->commands[ctx->ncommands], vals, nvals*sizeof(float));
ctx->ncommands += nvals;
}
static void nvg__clearPathCache(NVGcontext* ctx)
{
ctx->cache->npoints = 0;
ctx->cache->npaths = 0;
}
static NVGpath* nvg__lastPath(NVGcontext* ctx)
{
if (ctx->cache->npaths > 0)
return &ctx->cache->paths[ctx->cache->npaths-1];
return NULL;
}
static void nvg__addPath(NVGcontext* ctx)
{
NVGpath* path;
if (ctx->cache->npaths+1 > ctx->cache->cpaths) {
NVGpath* paths;
int cpaths = ctx->cache->npaths+1 + ctx->cache->cpaths/2;
paths = (NVGpath*)realloc(ctx->cache->paths, sizeof(NVGpath)*cpaths);
if (paths == NULL) return;
ctx->cache->paths = paths;
ctx->cache->cpaths = cpaths;
}
path = &ctx->cache->paths[ctx->cache->npaths];
memset(path, 0, sizeof(*path));
path->first = ctx->cache->npoints;
path->winding = NVG_CCW;
ctx->cache->npaths++;
}
static NVGpoint* nvg__lastPoint(NVGcontext* ctx)
{
if (ctx->cache->npoints > 0)
return &ctx->cache->points[ctx->cache->npoints-1];
return NULL;
}
static void nvg__addPoint(NVGcontext* ctx, float x, float y, int flags)
{
NVGpath* path = nvg__lastPath(ctx);
NVGpoint* pt;
if (path == NULL) return;
if (path->count > 0 && ctx->cache->npoints > 0) {
pt = nvg__lastPoint(ctx);
if (nvg__ptEquals(pt->x,pt->y, x,y, ctx->distTol)) {
pt->flags |= flags;
return;
}
}
if (ctx->cache->npoints+1 > ctx->cache->cpoints) {
NVGpoint* points;
int cpoints = ctx->cache->npoints+1 + ctx->cache->cpoints/2;
points = (NVGpoint*)realloc(ctx->cache->points, sizeof(NVGpoint)*cpoints);
if (points == NULL) return;
ctx->cache->points = points;
ctx->cache->cpoints = cpoints;
}
pt = &ctx->cache->points[ctx->cache->npoints];
memset(pt, 0, sizeof(*pt));
pt->x = x;
pt->y = y;
pt->flags = (unsigned char)flags;
ctx->cache->npoints++;
path->count++;
}
static void nvg__closePath(NVGcontext* ctx)
{
NVGpath* path = nvg__lastPath(ctx);
if (path == NULL) return;
path->closed = 1;
}
static void nvg__pathWinding(NVGcontext* ctx, int winding)
{
NVGpath* path = nvg__lastPath(ctx);
if (path == NULL) return;
path->winding = winding;
}
static float nvg__getAverageScale(float *t)
{
float sx = sqrtf(t[0]*t[0] + t[2]*t[2]);
float sy = sqrtf(t[1]*t[1] + t[3]*t[3]);
return (sx + sy) * 0.5f;
}
static NVGvertex* nvg__allocTempVerts(NVGcontext* ctx, int nverts)
{
if (nverts > ctx->cache->cverts) {
NVGvertex* verts;
int cverts = (nverts + 0xff) & ~0xff; // Round up to prevent allocations when things change just slightly.
verts = (NVGvertex*)realloc(ctx->cache->verts, sizeof(NVGvertex)*cverts);
if (verts == NULL) return NULL;
ctx->cache->verts = verts;
ctx->cache->cverts = cverts;
}
return ctx->cache->verts;
}
static float nvg__triarea2(float ax, float ay, float bx, float by, float cx, float cy)
{
float abx = bx - ax;
float aby = by - ay;
float acx = cx - ax;
float acy = cy - ay;
return acx*aby - abx*acy;
}
static float nvg__polyArea(NVGpoint* pts, int npts)
{
int i;
float area = 0;
for (i = 2; i < npts; i++) {
NVGpoint* a = &pts[0];
NVGpoint* b = &pts[i-1];
NVGpoint* c = &pts[i];
area += nvg__triarea2(a->x,a->y, b->x,b->y, c->x,c->y);
}
return area * 0.5f;
}
static void nvg__polyReverse(NVGpoint* pts, int npts)
{
NVGpoint tmp;
int i = 0, j = npts-1;
while (i < j) {
tmp = pts[i];
pts[i] = pts[j];
pts[j] = tmp;
i++;
j--;
}
}
static void nvg__vset(NVGvertex* vtx, float x, float y, float u, float v)
{
vtx->x = x;
vtx->y = y;
vtx->u = u;
vtx->v = v;
}
static void nvg__tesselateBezier(NVGcontext* ctx,
float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4,
int level, int type)
{
float x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234;
float dx,dy,d2,d3;
if (level > 10) return;
x12 = (x1+x2)*0.5f;
y12 = (y1+y2)*0.5f;
x23 = (x2+x3)*0.5f;
y23 = (y2+y3)*0.5f;
x34 = (x3+x4)*0.5f;
y34 = (y3+y4)*0.5f;
x123 = (x12+x23)*0.5f;
y123 = (y12+y23)*0.5f;
dx = x4 - x1;
dy = y4 - y1;
d2 = nvg__absf(((x2 - x4) * dy - (y2 - y4) * dx));
d3 = nvg__absf(((x3 - x4) * dy - (y3 - y4) * dx));
if ((d2 + d3)*(d2 + d3) < ctx->tessTol * (dx*dx + dy*dy)) {
nvg__addPoint(ctx, x4, y4, type);
return;
}
/* if (nvg__absf(x1+x3-x2-x2) + nvg__absf(y1+y3-y2-y2) + nvg__absf(x2+x4-x3-x3) + nvg__absf(y2+y4-y3-y3) < ctx->tessTol) {
nvg__addPoint(ctx, x4, y4, type);
return;
}*/
x234 = (x23+x34)*0.5f;
y234 = (y23+y34)*0.5f;
x1234 = (x123+x234)*0.5f;
y1234 = (y123+y234)*0.5f;
nvg__tesselateBezier(ctx, x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0);
nvg__tesselateBezier(ctx, x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type);
}
static void nvg__flattenPaths(NVGcontext* ctx)
{
NVGpathCache* cache = ctx->cache;
// NVGstate* state = nvg__getState(ctx);
NVGpoint* last;
NVGpoint* p0;
NVGpoint* p1;
NVGpoint* pts;
NVGpath* path;
int i, j;
float* cp1;
float* cp2;
float* p;
float area;
if (cache->npaths > 0)
return;
// Flatten
i = 0;
while (i < ctx->ncommands) {
int cmd = (int)ctx->commands[i];
switch (cmd) {
case NVG_MOVETO:
nvg__addPath(ctx);
p = &ctx->commands[i+1];
nvg__addPoint(ctx, p[0], p[1], NVG_PT_CORNER);
i += 3;
break;
case NVG_LINETO:
p = &ctx->commands[i+1];
nvg__addPoint(ctx, p[0], p[1], NVG_PT_CORNER);
i += 3;
break;
case NVG_BEZIERTO:
last = nvg__lastPoint(ctx);
if (last != NULL) {
cp1 = &ctx->commands[i+1];
cp2 = &ctx->commands[i+3];
p = &ctx->commands[i+5];
nvg__tesselateBezier(ctx, last->x,last->y, cp1[0],cp1[1], cp2[0],cp2[1], p[0],p[1], 0, NVG_PT_CORNER);
}
i += 7;
break;
case NVG_CLOSE:
nvg__closePath(ctx);
i++;
break;
case NVG_WINDING:
nvg__pathWinding(ctx, (int)ctx->commands[i+1]);
i += 2;
break;
default:
i++;
}
}
cache->bounds[0] = cache->bounds[1] = 1e6f;
cache->bounds[2] = cache->bounds[3] = -1e6f;
// Calculate the direction and length of line segments.
for (j = 0; j < cache->npaths; j++) {
path = &cache->paths[j];
pts = &cache->points[path->first];
// If the first and last points are the same, remove the last, mark as closed path.
p0 = &pts[path->count-1];
p1 = &pts[0];
if (nvg__ptEquals(p0->x,p0->y, p1->x,p1->y, ctx->distTol)) {
path->count--;
p0 = &pts[path->count-1];
path->closed = 1;
}
// Enforce winding.
if (path->count > 2) {
area = nvg__polyArea(pts, path->count);
if (path->winding == NVG_CCW && area < 0.0f)
nvg__polyReverse(pts, path->count);
if (path->winding == NVG_CW && area > 0.0f)
nvg__polyReverse(pts, path->count);
}
for(i = 0; i < path->count; i++) {
// Calculate segment direction and length
p0->dx = p1->x - p0->x;
p0->dy = p1->y - p0->y;
p0->len = nvg__normalize(&p0->dx, &p0->dy);
// Update bounds
cache->bounds[0] = nvg__minf(cache->bounds[0], p0->x);
cache->bounds[1] = nvg__minf(cache->bounds[1], p0->y);
cache->bounds[2] = nvg__maxf(cache->bounds[2], p0->x);
cache->bounds[3] = nvg__maxf(cache->bounds[3], p0->y);
// Advance
p0 = p1++;
}
}
}
static int nvg__curveDivs(float r, float arc, float tol)
{
float da = acosf(r / (r + tol)) * 2.0f;
return nvg__maxi(2, (int)ceilf(arc / da));
}
static void nvg__chooseBevel(int bevel, NVGpoint* p0, NVGpoint* p1, float w,
float* x0, float* y0, float* x1, float* y1)
{
if (bevel) {
*x0 = p1->x + p0->dy * w;
*y0 = p1->y - p0->dx * w;
*x1 = p1->x + p1->dy * w;
*y1 = p1->y - p1->dx * w;
} else {
*x0 = p1->x + p1->dmx * w;
*y0 = p1->y + p1->dmy * w;
*x1 = p1->x + p1->dmx * w;
*y1 = p1->y + p1->dmy * w;
}
}
static NVGvertex* nvg__roundJoin(NVGvertex* dst, NVGpoint* p0, NVGpoint* p1,
float lw, float rw, float lu, float ru, int ncap,
float fringe)
{
int i, n;
float dlx0 = p0->dy;
float dly0 = -p0->dx;
float dlx1 = p1->dy;
float dly1 = -p1->dx;
NVG_NOTUSED(fringe);
if (p1->flags & NVG_PT_LEFT) {
float lx0,ly0,lx1,ly1,a0,a1;
nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1);
a0 = atan2f(-dly0, -dlx0);
a1 = atan2f(-dly1, -dlx1);
if (a1 > a0) a1 -= NVG_PI*2;
nvg__vset(dst, lx0, ly0, lu,1); dst++;
nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
n = nvg__clampi((int)ceilf(((a0 - a1) / NVG_PI) * ncap), 2, ncap);
for (i = 0; i < n; i++) {
float u = i/(float)(n-1);
float a = a0 + u*(a1-a0);
float rx = p1->x + cosf(a) * rw;
float ry = p1->y + sinf(a) * rw;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
nvg__vset(dst, rx, ry, ru,1); dst++;
}
nvg__vset(dst, lx1, ly1, lu,1); dst++;
nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
} else {
float rx0,ry0,rx1,ry1,a0,a1;
nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1);
a0 = atan2f(dly0, dlx0);
a1 = atan2f(dly1, dlx1);
if (a1 < a0) a1 += NVG_PI*2;
nvg__vset(dst, p1->x + dlx0*rw, p1->y + dly0*rw, lu,1); dst++;
nvg__vset(dst, rx0, ry0, ru,1); dst++;
n = nvg__clampi((int)ceilf(((a1 - a0) / NVG_PI) * ncap), 2, ncap);
for (i = 0; i < n; i++) {
float u = i/(float)(n-1);
float a = a0 + u*(a1-a0);
float lx = p1->x + cosf(a) * lw;
float ly = p1->y + sinf(a) * lw;
nvg__vset(dst, lx, ly, lu,1); dst++;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
}
nvg__vset(dst, p1->x + dlx1*rw, p1->y + dly1*rw, lu,1); dst++;
nvg__vset(dst, rx1, ry1, ru,1); dst++;
}
return dst;
}
static NVGvertex* nvg__bevelJoin(NVGvertex* dst, NVGpoint* p0, NVGpoint* p1,
float lw, float rw, float lu, float ru, float fringe)
{
float rx0,ry0,rx1,ry1;
float lx0,ly0,lx1,ly1;
float dlx0 = p0->dy;
float dly0 = -p0->dx;
float dlx1 = p1->dy;
float dly1 = -p1->dx;
NVG_NOTUSED(fringe);
if (p1->flags & NVG_PT_LEFT) {
nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1);
nvg__vset(dst, lx0, ly0, lu,1); dst++;
nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
if (p1->flags & NVG_PT_BEVEL) {
nvg__vset(dst, lx0, ly0, lu,1); dst++;
nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
nvg__vset(dst, lx1, ly1, lu,1); dst++;
nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
} else {
rx0 = p1->x - p1->dmx * rw;
ry0 = p1->y - p1->dmy * rw;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
nvg__vset(dst, rx0, ry0, ru,1); dst++;
nvg__vset(dst, rx0, ry0, ru,1); dst++;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
}
nvg__vset(dst, lx1, ly1, lu,1); dst++;
nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
} else {
nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1);
nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
nvg__vset(dst, rx0, ry0, ru,1); dst++;
if (p1->flags & NVG_PT_BEVEL) {
nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
nvg__vset(dst, rx0, ry0, ru,1); dst++;
nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
nvg__vset(dst, rx1, ry1, ru,1); dst++;
} else {
lx0 = p1->x + p1->dmx * lw;
ly0 = p1->y + p1->dmy * lw;
nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
nvg__vset(dst, lx0, ly0, lu,1); dst++;
nvg__vset(dst, lx0, ly0, lu,1); dst++;
nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
}
nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
nvg__vset(dst, rx1, ry1, ru,1); dst++;
}
return dst;
}
static NVGvertex* nvg__buttCapStart(NVGvertex* dst, NVGpoint* p,
float dx, float dy, float w, float d,
float aa, float u0, float u1)
{
float px = p->x - dx*d;
float py = p->y - dy*d;
float dlx = dy;
float dly = -dx;
nvg__vset(dst, px + dlx*w - dx*aa, py + dly*w - dy*aa, u0,0); dst++;
nvg__vset(dst, px - dlx*w - dx*aa, py - dly*w - dy*aa, u1,0); dst++;
nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
return dst;
}
static NVGvertex* nvg__buttCapEnd(NVGvertex* dst, NVGpoint* p,
float dx, float dy, float w, float d,
float aa, float u0, float u1)
{
float px = p->x + dx*d;
float py = p->y + dy*d;
float dlx = dy;
float dly = -dx;
nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
nvg__vset(dst, px + dlx*w + dx*aa, py + dly*w + dy*aa, u0,0); dst++;
nvg__vset(dst, px - dlx*w + dx*aa, py - dly*w + dy*aa, u1,0); dst++;
return dst;
}
static NVGvertex* nvg__roundCapStart(NVGvertex* dst, NVGpoint* p,
float dx, float dy, float w, int ncap,
float aa, float u0, float u1)
{
int i;
float px = p->x;
float py = p->y;
float dlx = dy;
float dly = -dx;
NVG_NOTUSED(aa);
for (i = 0; i < ncap; i++) {
float a = i/(float)(ncap-1)*NVG_PI;
float ax = cosf(a) * w, ay = sinf(a) * w;
nvg__vset(dst, px - dlx*ax - dx*ay, py - dly*ax - dy*ay, u0,1); dst++;
nvg__vset(dst, px, py, 0.5f,1); dst++;
}
nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
return dst;
}
static NVGvertex* nvg__roundCapEnd(NVGvertex* dst, NVGpoint* p,
float dx, float dy, float w, int ncap,
float aa, float u0, float u1)
{
int i;
float px = p->x;
float py = p->y;
float dlx = dy;
float dly = -dx;
NVG_NOTUSED(aa);
nvg__vset(dst, px + dlx*w, py + dly*w, u0,1); dst++;
nvg__vset(dst, px - dlx*w, py - dly*w, u1,1); dst++;
for (i = 0; i < ncap; i++) {
float a = i/(float)(ncap-1)*NVG_PI;
float ax = cosf(a) * w, ay = sinf(a) * w;
nvg__vset(dst, px, py, 0.5f,1); dst++;
nvg__vset(dst, px - dlx*ax + dx*ay, py - dly*ax + dy*ay, u0,1); dst++;
}
return dst;
}
static void nvg__calculateJoins(NVGcontext* ctx, float w, int lineJoin, float miterLimit)
{
NVGpathCache* cache = ctx->cache;
int i, j;
float iw = 0.0f;
if (w > 0.0f) iw = 1.0f / w;
// Calculate which joins needs extra vertices to append, and gather vertex count.
for (i = 0; i < cache->npaths; i++) {
NVGpath* path = &cache->paths[i];
NVGpoint* pts = &cache->points[path->first];
NVGpoint* p0 = &pts[path->count-1];
NVGpoint* p1 = &pts[0];
int nleft = 0;
path->nbevel = 0;
for (j = 0; j < path->count; j++) {
float dlx0, dly0, dlx1, dly1, dmr2, cross, limit;
dlx0 = p0->dy;
dly0 = -p0->dx;
dlx1 = p1->dy;
dly1 = -p1->dx;
// Calculate extrusions
p1->dmx = (dlx0 + dlx1) * 0.5f;
p1->dmy = (dly0 + dly1) * 0.5f;
dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy;
if (dmr2 > 0.000001f) {
float scale = 1.0f / dmr2;
if (scale > 600.0f) {
scale = 600.0f;
}
p1->dmx *= scale;
p1->dmy *= scale;
}
// Clear flags, but keep the corner.
p1->flags = (p1->flags & NVG_PT_CORNER) ? NVG_PT_CORNER : 0;
// Keep track of left turns.
cross = p1->dx * p0->dy - p0->dx * p1->dy;
if (cross > 0.0f) {
nleft++;
p1->flags |= NVG_PT_LEFT;
}
// Calculate if we should use bevel or miter for inner join.
limit = nvg__maxf(1.01f, nvg__minf(p0->len, p1->len) * iw);
if ((dmr2 * limit*limit) < 1.0f)
p1->flags |= NVG_PR_INNERBEVEL;
// Check to see if the corner needs to be beveled.
if (p1->flags & NVG_PT_CORNER) {
if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == NVG_BEVEL || lineJoin == NVG_ROUND) {
p1->flags |= NVG_PT_BEVEL;
}
}
if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0)
path->nbevel++;
p0 = p1++;
}
path->convex = (nleft == path->count) ? 1 : 0;
}
}
static int nvg__expandStroke(NVGcontext* ctx, float w, float fringe, int lineCap, int lineJoin, float miterLimit)
{
NVGpathCache* cache = ctx->cache;
NVGvertex* verts;
NVGvertex* dst;
int cverts, i, j;
float aa = fringe;//ctx->fringeWidth;
float u0 = 0.0f, u1 = 1.0f;
int ncap = nvg__curveDivs(w, NVG_PI, ctx->tessTol); // Calculate divisions per half circle.
w += aa * 0.5f;
// Disable the gradient used for antialiasing when antialiasing is not used.
if (aa == 0.0f) {
u0 = 0.5f;
u1 = 0.5f;
}
nvg__calculateJoins(ctx, w, lineJoin, miterLimit);
// Calculate max vertex usage.
cverts = 0;
for (i = 0; i < cache->npaths; i++) {
NVGpath* path = &cache->paths[i];
int loop = (path->closed == 0) ? 0 : 1;
if (lineJoin == NVG_ROUND)
cverts += (path->count + path->nbevel*(ncap+2) + 1) * 2; // plus one for loop
else
cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop
if (loop == 0) {
// space for caps
if (lineCap == NVG_ROUND) {
cverts += (ncap*2 + 2)*2;
} else {
cverts += (3+3)*2;
}
}
}
verts = nvg__allocTempVerts(ctx, cverts);
if (verts == NULL) return 0;
for (i = 0; i < cache->npaths; i++) {
NVGpath* path = &cache->paths[i];
NVGpoint* pts = &cache->points[path->first];
NVGpoint* p0;
NVGpoint* p1;
int s, e, loop;
float dx, dy;
path->fill = 0;
path->nfill = 0;
// Calculate fringe or stroke
loop = (path->closed == 0) ? 0 : 1;
dst = verts;
path->stroke = dst;
if (loop) {
// Looping
p0 = &pts[path->count-1];
p1 = &pts[0];
s = 0;
e = path->count;
} else {
// Add cap
p0 = &pts[0];
p1 = &pts[1];
s = 1;
e = path->count-1;
}
if (loop == 0) {
// Add cap
dx = p1->x - p0->x;
dy = p1->y - p0->y;
nvg__normalize(&dx, &dy);
if (lineCap == NVG_BUTT)
dst = nvg__buttCapStart(dst, p0, dx, dy, w, -aa*0.5f, aa, u0, u1);
else if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE)
dst = nvg__buttCapStart(dst, p0, dx, dy, w, w-aa, aa, u0, u1);
else if (lineCap == NVG_ROUND)
dst = nvg__roundCapStart(dst, p0, dx, dy, w, ncap, aa, u0, u1);
}
for (j = s; j < e; ++j) {
if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) {
if (lineJoin == NVG_ROUND) {
dst = nvg__roundJoin(dst, p0, p1, w, w, u0, u1, ncap, aa);
} else {
dst = nvg__bevelJoin(dst, p0, p1, w, w, u0, u1, aa);
}
} else {
nvg__vset(dst, p1->x + (p1->dmx * w), p1->y + (p1->dmy * w), u0,1); dst++;
nvg__vset(dst, p1->x - (p1->dmx * w), p1->y - (p1->dmy * w), u1,1); dst++;
}
p0 = p1++;
}
if (loop) {
// Loop it
nvg__vset(dst, verts[0].x, verts[0].y, u0,1); dst++;
nvg__vset(dst, verts[1].x, verts[1].y, u1,1); dst++;
} else {
// Add cap
dx = p1->x - p0->x;
dy = p1->y - p0->y;
nvg__normalize(&dx, &dy);
if (lineCap == NVG_BUTT)
dst = nvg__buttCapEnd(dst, p1, dx, dy, w, -aa*0.5f, aa, u0, u1);
else if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE)
dst = nvg__buttCapEnd(dst, p1, dx, dy, w, w-aa, aa, u0, u1);
else if (lineCap == NVG_ROUND)
dst = nvg__roundCapEnd(dst, p1, dx, dy, w, ncap, aa, u0, u1);
}
path->nstroke = (int)(dst - verts);
verts = dst;
}
return 1;
}
static int nvg__expandFill(NVGcontext* ctx, float w, int lineJoin, float miterLimit)
{
NVGpathCache* cache = ctx->cache;
NVGvertex* verts;
NVGvertex* dst;
int cverts, convex, i, j;
float aa = ctx->fringeWidth;
int fringe = w > 0.0f;
nvg__calculateJoins(ctx, w, lineJoin, miterLimit);
// Calculate max vertex usage.
cverts = 0;
for (i = 0; i < cache->npaths; i++) {
NVGpath* path = &cache->paths[i];
cverts += path->count + path->nbevel + 1;
if (fringe)
cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop
}
verts = nvg__allocTempVerts(ctx, cverts);
if (verts == NULL) return 0;
convex = cache->npaths == 1 && cache->paths[0].convex;
for (i = 0; i < cache->npaths; i++) {
NVGpath* path = &cache->paths[i];
NVGpoint* pts = &cache->points[path->first];
NVGpoint* p0;
NVGpoint* p1;
float rw, lw, woff;
float ru, lu;
// Calculate shape vertices.
woff = 0.5f*aa;
dst = verts;
path->fill = dst;
if (fringe) {
// Looping
p0 = &pts[path->count-1];
p1 = &pts[0];
for (j = 0; j < path->count; ++j) {
if (p1->flags & NVG_PT_BEVEL) {
float dlx0 = p0->dy;
float dly0 = -p0->dx;
float dlx1 = p1->dy;
float dly1 = -p1->dx;
if (p1->flags & NVG_PT_LEFT) {
float lx = p1->x + p1->dmx * woff;
float ly = p1->y + p1->dmy * woff;
nvg__vset(dst, lx, ly, 0.5f,1); dst++;
} else {
float lx0 = p1->x + dlx0 * woff;
float ly0 = p1->y + dly0 * woff;
float lx1 = p1->x + dlx1 * woff;
float ly1 = p1->y + dly1 * woff;
nvg__vset(dst, lx0, ly0, 0.5f,1); dst++;
nvg__vset(dst, lx1, ly1, 0.5f,1); dst++;
}
} else {
nvg__vset(dst, p1->x + (p1->dmx * woff), p1->y + (p1->dmy * woff), 0.5f,1); dst++;
}
p0 = p1++;
}
} else {
for (j = 0; j < path->count; ++j) {
nvg__vset(dst, pts[j].x, pts[j].y, 0.5f,1);
dst++;
}
}
path->nfill = (int)(dst - verts);
verts = dst;
// Calculate fringe
if (fringe) {
lw = w + woff;
rw = w - woff;
lu = 0;
ru = 1;
dst = verts;
path->stroke = dst;
// Create only half a fringe for convex shapes so that
// the shape can be rendered without stenciling.
if (convex) {
lw = woff; // This should generate the same vertex as fill inset above.
lu = 0.5f; // Set outline fade at middle.
}
// Looping
p0 = &pts[path->count-1];
p1 = &pts[0];
for (j = 0; j < path->count; ++j) {
if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) {
dst = nvg__bevelJoin(dst, p0, p1, lw, rw, lu, ru, ctx->fringeWidth);
} else {
nvg__vset(dst, p1->x + (p1->dmx * lw), p1->y + (p1->dmy * lw), lu,1); dst++;
nvg__vset(dst, p1->x - (p1->dmx * rw), p1->y - (p1->dmy * rw), ru,1); dst++;
}
p0 = p1++;
}
// Loop it
nvg__vset(dst, verts[0].x, verts[0].y, lu,1); dst++;
nvg__vset(dst, verts[1].x, verts[1].y, ru,1); dst++;
path->nstroke = (int)(dst - verts);
verts = dst;
} else {
path->stroke = NULL;
path->nstroke = 0;
}
}
return 1;
}
// Draw
void nvgBeginPath(NVGcontext* ctx)
{
ctx->ncommands = 0;
nvg__clearPathCache(ctx);
}
void nvgMoveTo(NVGcontext* ctx, float x, float y)
{
float vals[] = { NVG_MOVETO, x, y };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgLineTo(NVGcontext* ctx, float x, float y)
{
float vals[] = { NVG_LINETO, x, y };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgBezierTo(NVGcontext* ctx, float c1x, float c1y, float c2x, float c2y, float x, float y)
{
float vals[] = { NVG_BEZIERTO, c1x, c1y, c2x, c2y, x, y };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgQuadTo(NVGcontext* ctx, float cx, float cy, float x, float y)
{
float x0 = ctx->commandx;
float y0 = ctx->commandy;
float vals[] = { NVG_BEZIERTO,
x0 + 2.0f/3.0f*(cx - x0), y0 + 2.0f/3.0f*(cy - y0),
x + 2.0f/3.0f*(cx - x), y + 2.0f/3.0f*(cy - y),
x, y };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgArcTo(NVGcontext* ctx, float x1, float y1, float x2, float y2, float radius)
{
float x0 = ctx->commandx;
float y0 = ctx->commandy;
float dx0,dy0, dx1,dy1, a, d, cx,cy, a0,a1;
int dir;
if (ctx->ncommands == 0) {
return;
}
// Handle degenerate cases.
if (nvg__ptEquals(x0,y0, x1,y1, ctx->distTol) ||
nvg__ptEquals(x1,y1, x2,y2, ctx->distTol) ||
nvg__distPtSeg(x1,y1, x0,y0, x2,y2) < ctx->distTol*ctx->distTol ||
radius < ctx->distTol) {
nvgLineTo(ctx, x1,y1);
return;
}
// Calculate tangential circle to lines (x0,y0)-(x1,y1) and (x1,y1)-(x2,y2).
dx0 = x0-x1;
dy0 = y0-y1;
dx1 = x2-x1;
dy1 = y2-y1;
nvg__normalize(&dx0,&dy0);
nvg__normalize(&dx1,&dy1);
a = nvg__acosf(dx0*dx1 + dy0*dy1);
d = radius / nvg__tanf(a/2.0f);
// printf("a=%f° d=%f\n", a/NVG_PI*180.0f, d);
if (d > 10000.0f) {
nvgLineTo(ctx, x1,y1);
return;
}
if (nvg__cross(dx0,dy0, dx1,dy1) > 0.0f) {
cx = x1 + dx0*d + dy0*radius;
cy = y1 + dy0*d + -dx0*radius;
a0 = nvg__atan2f(dx0, -dy0);
a1 = nvg__atan2f(-dx1, dy1);
dir = NVG_CW;
// printf("CW c=(%f, %f) a0=%f° a1=%f°\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f);
} else {
cx = x1 + dx0*d + -dy0*radius;
cy = y1 + dy0*d + dx0*radius;
a0 = nvg__atan2f(-dx0, dy0);
a1 = nvg__atan2f(dx1, -dy1);
dir = NVG_CCW;
// printf("CCW c=(%f, %f) a0=%f° a1=%f°\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f);
}
nvgArc(ctx, cx, cy, radius, a0, a1, dir);
}
void nvgClosePath(NVGcontext* ctx)
{
float vals[] = { NVG_CLOSE };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgPathWinding(NVGcontext* ctx, int dir)
{
float vals[] = { NVG_WINDING, (float)dir };
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgArc(NVGcontext* ctx, float cx, float cy, float r, float a0, float a1, int dir)
{
float a = 0, da = 0, hda = 0, kappa = 0;
float dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0;
float px = 0, py = 0, ptanx = 0, ptany = 0;
float vals[3 + 5*7 + 100];
int i, ndivs, nvals;
int move = ctx->ncommands > 0 ? NVG_LINETO : NVG_MOVETO;
// Clamp angles
da = a1 - a0;
if (dir == NVG_CW) {
if (nvg__absf(da) >= NVG_PI*2) {
da = NVG_PI*2;
} else {
while (da < 0.0f) da += NVG_PI*2;
}
} else {
if (nvg__absf(da) >= NVG_PI*2) {
da = -NVG_PI*2;
} else {
while (da > 0.0f) da -= NVG_PI*2;
}
}
// Split arc into max 90 degree segments.
ndivs = nvg__maxi(1, nvg__mini((int)(nvg__absf(da) / (NVG_PI*0.5f) + 0.5f), 5));
hda = (da / (float)ndivs) / 2.0f;
kappa = nvg__absf(4.0f / 3.0f * (1.0f - nvg__cosf(hda)) / nvg__sinf(hda));
if (dir == NVG_CCW)
kappa = -kappa;
nvals = 0;
for (i = 0; i <= ndivs; i++) {
a = a0 + da * (i/(float)ndivs);
dx = nvg__cosf(a);
dy = nvg__sinf(a);
x = cx + dx*r;
y = cy + dy*r;
tanx = -dy*r*kappa;
tany = dx*r*kappa;
if (i == 0) {
vals[nvals++] = (float)move;
vals[nvals++] = x;
vals[nvals++] = y;
} else {
vals[nvals++] = NVG_BEZIERTO;
vals[nvals++] = px+ptanx;
vals[nvals++] = py+ptany;
vals[nvals++] = x-tanx;
vals[nvals++] = y-tany;
vals[nvals++] = x;
vals[nvals++] = y;
}
px = x;
py = y;
ptanx = tanx;
ptany = tany;
}
nvg__appendCommands(ctx, vals, nvals);
}
void nvgRect(NVGcontext* ctx, float x, float y, float w, float h)
{
float vals[] = {
NVG_MOVETO, x,y,
NVG_LINETO, x,y+h,
NVG_LINETO, x+w,y+h,
NVG_LINETO, x+w,y,
NVG_CLOSE
};
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgRoundedRect(NVGcontext* ctx, float x, float y, float w, float h, float r)
{
nvgRoundedRectVarying(ctx, x, y, w, h, r, r, r, r);
}
void nvgRoundedRectVarying(NVGcontext* ctx, float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft)
{
if(radTopLeft < 0.1f && radTopRight < 0.1f && radBottomRight < 0.1f && radBottomLeft < 0.1f) {
nvgRect(ctx, x, y, w, h);
return;
} else {
float halfw = nvg__absf(w)*0.5f;
float halfh = nvg__absf(h)*0.5f;
float rxBL = nvg__minf(radBottomLeft, halfw) * nvg__signf(w), ryBL = nvg__minf(radBottomLeft, halfh) * nvg__signf(h);
float rxBR = nvg__minf(radBottomRight, halfw) * nvg__signf(w), ryBR = nvg__minf(radBottomRight, halfh) * nvg__signf(h);
float rxTR = nvg__minf(radTopRight, halfw) * nvg__signf(w), ryTR = nvg__minf(radTopRight, halfh) * nvg__signf(h);
float rxTL = nvg__minf(radTopLeft, halfw) * nvg__signf(w), ryTL = nvg__minf(radTopLeft, halfh) * nvg__signf(h);
float vals[] = {
NVG_MOVETO, x, y + ryTL,
NVG_LINETO, x, y + h - ryBL,
NVG_BEZIERTO, x, y + h - ryBL*(1 - NVG_KAPPA90), x + rxBL*(1 - NVG_KAPPA90), y + h, x + rxBL, y + h,
NVG_LINETO, x + w - rxBR, y + h,
NVG_BEZIERTO, x + w - rxBR*(1 - NVG_KAPPA90), y + h, x + w, y + h - ryBR*(1 - NVG_KAPPA90), x + w, y + h - ryBR,
NVG_LINETO, x + w, y + ryTR,
NVG_BEZIERTO, x + w, y + ryTR*(1 - NVG_KAPPA90), x + w - rxTR*(1 - NVG_KAPPA90), y, x + w - rxTR, y,
NVG_LINETO, x + rxTL, y,
NVG_BEZIERTO, x + rxTL*(1 - NVG_KAPPA90), y, x, y + ryTL*(1 - NVG_KAPPA90), x, y + ryTL,
NVG_CLOSE
};
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
}
void nvgEllipse(NVGcontext* ctx, float cx, float cy, float rx, float ry)
{
float vals[] = {
NVG_MOVETO, cx-rx, cy,
NVG_BEZIERTO, cx-rx, cy+ry*NVG_KAPPA90, cx-rx*NVG_KAPPA90, cy+ry, cx, cy+ry,
NVG_BEZIERTO, cx+rx*NVG_KAPPA90, cy+ry, cx+rx, cy+ry*NVG_KAPPA90, cx+rx, cy,
NVG_BEZIERTO, cx+rx, cy-ry*NVG_KAPPA90, cx+rx*NVG_KAPPA90, cy-ry, cx, cy-ry,
NVG_BEZIERTO, cx-rx*NVG_KAPPA90, cy-ry, cx-rx, cy-ry*NVG_KAPPA90, cx-rx, cy,
NVG_CLOSE
};
nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
}
void nvgCircle(NVGcontext* ctx, float cx, float cy, float r)
{
nvgEllipse(ctx, cx,cy, r,r);
}
void nvgDebugDumpPathCache(NVGcontext* ctx)
{
const NVGpath* path;
int i, j;
printf("Dumping %d cached paths\n", ctx->cache->npaths);
for (i = 0; i < ctx->cache->npaths; i++) {
path = &ctx->cache->paths[i];
printf(" - Path %d\n", i);
if (path->nfill) {
printf(" - fill: %d\n", path->nfill);
for (j = 0; j < path->nfill; j++)
printf("%f\t%f\n", path->fill[j].x, path->fill[j].y);
}
if (path->nstroke) {
printf(" - stroke: %d\n", path->nstroke);
for (j = 0; j < path->nstroke; j++)
printf("%f\t%f\n", path->stroke[j].x, path->stroke[j].y);
}
}
}
void nvgFill(NVGcontext* ctx)
{
NVGstate* state = nvg__getState(ctx);
const NVGpath* path;
NVGpaint fillPaint = state->fill;
int i;
nvg__flattenPaths(ctx);
if (ctx->params.edgeAntiAlias && state->shapeAntiAlias)
nvg__expandFill(ctx, ctx->fringeWidth, NVG_MITER, 2.4f);
else
nvg__expandFill(ctx, 0.0f, NVG_MITER, 2.4f);
// Apply global alpha
fillPaint.innerColor.a *= state->alpha;
fillPaint.outerColor.a *= state->alpha;
ctx->params.renderFill(ctx->params.userPtr, &fillPaint, state->compositeOperation, &state->scissor, ctx->fringeWidth,
ctx->cache->bounds, ctx->cache->paths, ctx->cache->npaths);
// Count triangles
for (i = 0; i < ctx->cache->npaths; i++) {
path = &ctx->cache->paths[i];
ctx->fillTriCount += path->nfill-2;
ctx->fillTriCount += path->nstroke-2;
ctx->drawCallCount += 2;
}
}
void nvgStroke(NVGcontext* ctx)
{
NVGstate* state = nvg__getState(ctx);
float scale = nvg__getAverageScale(state->xform);
float strokeWidth = nvg__clampf(state->strokeWidth * scale, 0.0f, 200.0f);
NVGpaint strokePaint = state->stroke;
const NVGpath* path;
int i;
if (strokeWidth < ctx->fringeWidth) {
// If the stroke width is less than pixel size, use alpha to emulate coverage.
// Since coverage is area, scale by alpha*alpha.
float alpha = nvg__clampf(strokeWidth / ctx->fringeWidth, 0.0f, 1.0f);
strokePaint.innerColor.a *= alpha*alpha;
strokePaint.outerColor.a *= alpha*alpha;
strokeWidth = ctx->fringeWidth;
}
// Apply global alpha
strokePaint.innerColor.a *= state->alpha;
strokePaint.outerColor.a *= state->alpha;
nvg__flattenPaths(ctx);
if (ctx->params.edgeAntiAlias && state->shapeAntiAlias)
nvg__expandStroke(ctx, strokeWidth*0.5f, ctx->fringeWidth, state->lineCap, state->lineJoin, state->miterLimit);
else
nvg__expandStroke(ctx, strokeWidth*0.5f, 0.0f, state->lineCap, state->lineJoin, state->miterLimit);
ctx->params.renderStroke(ctx->params.userPtr, &strokePaint, state->compositeOperation, &state->scissor, ctx->fringeWidth,
strokeWidth, ctx->cache->paths, ctx->cache->npaths);
// Count triangles
for (i = 0; i < ctx->cache->npaths; i++) {
path = &ctx->cache->paths[i];
ctx->strokeTriCount += path->nstroke-2;
ctx->drawCallCount++;
}
}
// Add fonts
int nvgCreateFont(NVGcontext* ctx, const char* name, const char* path)
{
return fonsAddFont(ctx->fs, name, path);
}
int nvgCreateFontMem(NVGcontext* ctx, const char* name, unsigned char* data, int ndata, int freeData)
{
return fonsAddFontMem(ctx->fs, name, data, ndata, freeData);
}
int nvgFindFont(NVGcontext* ctx, const char* name)
{
if (name == NULL) return -1;
return fonsGetFontByName(ctx->fs, name);
}
int nvgAddFallbackFontId(NVGcontext* ctx, int baseFont, int fallbackFont)
{
if(baseFont == -1 || fallbackFont == -1) return 0;
return fonsAddFallbackFont(ctx->fs, baseFont, fallbackFont);
}
int nvgAddFallbackFont(NVGcontext* ctx, const char* baseFont, const char* fallbackFont)
{
return nvgAddFallbackFontId(ctx, nvgFindFont(ctx, baseFont), nvgFindFont(ctx, fallbackFont));
}
// State setting
void nvgFontSize(NVGcontext* ctx, float size)
{
NVGstate* state = nvg__getState(ctx);
state->fontSize = size;
}
void nvgFontBlur(NVGcontext* ctx, float blur)
{
NVGstate* state = nvg__getState(ctx);
state->fontBlur = blur;
}
void nvgTextLetterSpacing(NVGcontext* ctx, float spacing)
{
NVGstate* state = nvg__getState(ctx);
state->letterSpacing = spacing;
}
void nvgTextLineHeight(NVGcontext* ctx, float lineHeight)
{
NVGstate* state = nvg__getState(ctx);
state->lineHeight = lineHeight;
}
void nvgTextAlign(NVGcontext* ctx, int align)
{
NVGstate* state = nvg__getState(ctx);
state->textAlign = align;
}
void nvgFontFaceId(NVGcontext* ctx, int font)
{
NVGstate* state = nvg__getState(ctx);
state->fontId = font;
}
void nvgFontFace(NVGcontext* ctx, const char* font)
{
NVGstate* state = nvg__getState(ctx);
state->fontId = fonsGetFontByName(ctx->fs, font);
}
static float nvg__quantize(float a, float d)
{
return ((int)(a / d + 0.5f)) * d;
}
static float nvg__getFontScale(NVGstate* state)
{
return nvg__minf(nvg__quantize(nvg__getAverageScale(state->xform), 0.01f), 4.0f);
}
static void nvg__flushTextTexture(NVGcontext* ctx)
{
int dirty[4];
if (fonsValidateTexture(ctx->fs, dirty)) {
int fontImage = ctx->fontImages[ctx->fontImageIdx];
// Update texture
if (fontImage != 0) {
int iw, ih;
const unsigned char* data = fonsGetTextureData(ctx->fs, &iw, &ih);
int x = dirty[0];
int y = dirty[1];
int w = dirty[2] - dirty[0];
int h = dirty[3] - dirty[1];
ctx->params.renderUpdateTexture(ctx->params.userPtr, fontImage, x,y, w,h, data);
}
}
}
static int nvg__allocTextAtlas(NVGcontext* ctx)
{
int iw, ih;
nvg__flushTextTexture(ctx);
if (ctx->fontImageIdx >= NVG_MAX_FONTIMAGES-1)
return 0;
// if next fontImage already have a texture
if (ctx->fontImages[ctx->fontImageIdx+1] != 0)
nvgImageSize(ctx, ctx->fontImages[ctx->fontImageIdx+1], &iw, &ih);
else { // calculate the new font image size and create it.
nvgImageSize(ctx, ctx->fontImages[ctx->fontImageIdx], &iw, &ih);
if (iw > ih)
ih *= 2;
else
iw *= 2;
if (iw > NVG_MAX_FONTIMAGE_SIZE || ih > NVG_MAX_FONTIMAGE_SIZE)
iw = ih = NVG_MAX_FONTIMAGE_SIZE;
ctx->fontImages[ctx->fontImageIdx+1] = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, iw, ih, 0, NULL);
}
++ctx->fontImageIdx;
fonsResetAtlas(ctx->fs, iw, ih);
return 1;
}
static void nvg__renderText(NVGcontext* ctx, NVGvertex* verts, int nverts)
{
NVGstate* state = nvg__getState(ctx);
NVGpaint paint = state->fill;
// Render triangles.
paint.image = ctx->fontImages[ctx->fontImageIdx];
// Apply global alpha
paint.innerColor.a *= state->alpha;
paint.outerColor.a *= state->alpha;
ctx->params.renderTriangles(ctx->params.userPtr, &paint, state->compositeOperation, &state->scissor, verts, nverts);
ctx->drawCallCount++;
ctx->textTriCount += nverts/3;
}
float nvgText(NVGcontext* ctx, float x, float y, const char* string, const char* end)
{
NVGstate* state = nvg__getState(ctx);
FONStextIter iter, prevIter;
FONSquad q;
NVGvertex* verts;
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
int cverts = 0;
int nverts = 0;
if (end == NULL)
end = string + strlen(string);
if (state->fontId == FONS_INVALID) return x;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
cverts = nvg__maxi(2, (int)(end - string)) * 6; // conservative estimate.
verts = nvg__allocTempVerts(ctx, cverts);
if (verts == NULL) return x;
fonsTextIterInit(ctx->fs, &iter, x*scale, y*scale, string, end, FONS_GLYPH_BITMAP_REQUIRED);
prevIter = iter;
while (fonsTextIterNext(ctx->fs, &iter, &q)) {
float c[4*2];
if (iter.prevGlyphIndex == -1) { // can not retrieve glyph?
if (nverts != 0) {
nvg__renderText(ctx, verts, nverts);
nverts = 0;
}
if (!nvg__allocTextAtlas(ctx))
break; // no memory :(
iter = prevIter;
fonsTextIterNext(ctx->fs, &iter, &q); // try again
if (iter.prevGlyphIndex == -1) // still can not find glyph?
break;
}
prevIter = iter;
// Transform corners.
nvgTransformPoint(&c[0],&c[1], state->xform, q.x0*invscale, q.y0*invscale);
nvgTransformPoint(&c[2],&c[3], state->xform, q.x1*invscale, q.y0*invscale);
nvgTransformPoint(&c[4],&c[5], state->xform, q.x1*invscale, q.y1*invscale);
nvgTransformPoint(&c[6],&c[7], state->xform, q.x0*invscale, q.y1*invscale);
// Create triangles
if (nverts+6 <= cverts) {
nvg__vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++;
nvg__vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++;
nvg__vset(&verts[nverts], c[2], c[3], q.s1, q.t0); nverts++;
nvg__vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++;
nvg__vset(&verts[nverts], c[6], c[7], q.s0, q.t1); nverts++;
nvg__vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++;
}
}
// TODO: add back-end bit to do this just once per frame.
nvg__flushTextTexture(ctx);
nvg__renderText(ctx, verts, nverts);
return iter.nextx / scale;
}
void nvgTextBox(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end)
{
NVGstate* state = nvg__getState(ctx);
NVGtextRow rows[2];
int nrows = 0, i;
int oldAlign = state->textAlign;
int haling = state->textAlign & (NVG_ALIGN_LEFT | NVG_ALIGN_CENTER | NVG_ALIGN_RIGHT);
int valign = state->textAlign & (NVG_ALIGN_TOP | NVG_ALIGN_MIDDLE | NVG_ALIGN_BOTTOM | NVG_ALIGN_BASELINE);
float lineh = 0;
if (state->fontId == FONS_INVALID) return;
nvgTextMetrics(ctx, NULL, NULL, &lineh);
state->textAlign = NVG_ALIGN_LEFT | valign;
while ((nrows = nvgTextBreakLines(ctx, string, end, breakRowWidth, rows, 2))) {
for (i = 0; i < nrows; i++) {
NVGtextRow* row = &rows[i];
if (haling & NVG_ALIGN_LEFT)
nvgText(ctx, x, y, row->start, row->end);
else if (haling & NVG_ALIGN_CENTER)
nvgText(ctx, x + breakRowWidth*0.5f - row->width*0.5f, y, row->start, row->end);
else if (haling & NVG_ALIGN_RIGHT)
nvgText(ctx, x + breakRowWidth - row->width, y, row->start, row->end);
y += lineh * state->lineHeight;
}
string = rows[nrows-1].next;
}
state->textAlign = oldAlign;
}
int nvgTextGlyphPositions(NVGcontext* ctx, float x, float y, const char* string, const char* end, NVGglyphPosition* positions, int maxPositions)
{
NVGstate* state = nvg__getState(ctx);
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
FONStextIter iter, prevIter;
FONSquad q;
int npos = 0;
if (state->fontId == FONS_INVALID) return 0;
if (end == NULL)
end = string + strlen(string);
if (string == end)
return 0;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
fonsTextIterInit(ctx->fs, &iter, x*scale, y*scale, string, end, FONS_GLYPH_BITMAP_OPTIONAL);
prevIter = iter;
while (fonsTextIterNext(ctx->fs, &iter, &q)) {
if (iter.prevGlyphIndex < 0 && nvg__allocTextAtlas(ctx)) { // can not retrieve glyph?
iter = prevIter;
fonsTextIterNext(ctx->fs, &iter, &q); // try again
}
prevIter = iter;
positions[npos].str = iter.str;
positions[npos].x = iter.x * invscale;
positions[npos].minx = nvg__minf(iter.x, q.x0) * invscale;
positions[npos].maxx = nvg__maxf(iter.nextx, q.x1) * invscale;
npos++;
if (npos >= maxPositions)
break;
}
return npos;
}
enum NVGcodepointType {
NVG_SPACE,
NVG_NEWLINE,
NVG_CHAR,
NVG_CJK_CHAR,
};
int nvgTextBreakLines(NVGcontext* ctx, const char* string, const char* end, float breakRowWidth, NVGtextRow* rows, int maxRows)
{
NVGstate* state = nvg__getState(ctx);
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
FONStextIter iter, prevIter;
FONSquad q;
int nrows = 0;
float rowStartX = 0;
float rowWidth = 0;
float rowMinX = 0;
float rowMaxX = 0;
const char* rowStart = NULL;
const char* rowEnd = NULL;
const char* wordStart = NULL;
float wordStartX = 0;
float wordMinX = 0;
const char* breakEnd = NULL;
float breakWidth = 0;
float breakMaxX = 0;
int type = NVG_SPACE, ptype = NVG_SPACE;
unsigned int pcodepoint = 0;
if (maxRows == 0) return 0;
if (state->fontId == FONS_INVALID) return 0;
if (end == NULL)
end = string + strlen(string);
if (string == end) return 0;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
breakRowWidth *= scale;
fonsTextIterInit(ctx->fs, &iter, 0, 0, string, end, FONS_GLYPH_BITMAP_OPTIONAL);
prevIter = iter;
while (fonsTextIterNext(ctx->fs, &iter, &q)) {
if (iter.prevGlyphIndex < 0 && nvg__allocTextAtlas(ctx)) { // can not retrieve glyph?
iter = prevIter;
fonsTextIterNext(ctx->fs, &iter, &q); // try again
}
prevIter = iter;
switch (iter.codepoint) {
case 9: // \t
case 11: // \v
case 12: // \f
case 32: // space
case 0x00a0: // NBSP
type = NVG_SPACE;
break;
case 10: // \n
type = pcodepoint == 13 ? NVG_SPACE : NVG_NEWLINE;
break;
case 13: // \r
type = pcodepoint == 10 ? NVG_SPACE : NVG_NEWLINE;
break;
case 0x0085: // NEL
type = NVG_NEWLINE;
break;
default:
if ((iter.codepoint >= 0x4E00 && iter.codepoint <= 0x9FFF) ||
(iter.codepoint >= 0x3000 && iter.codepoint <= 0x30FF) ||
(iter.codepoint >= 0xFF00 && iter.codepoint <= 0xFFEF) ||
(iter.codepoint >= 0x1100 && iter.codepoint <= 0x11FF) ||
(iter.codepoint >= 0x3130 && iter.codepoint <= 0x318F) ||
(iter.codepoint >= 0xAC00 && iter.codepoint <= 0xD7AF))
type = NVG_CJK_CHAR;
else
type = NVG_CHAR;
break;
}
if (type == NVG_NEWLINE) {
// Always handle new lines.
rows[nrows].start = rowStart != NULL ? rowStart : iter.str;
rows[nrows].end = rowEnd != NULL ? rowEnd : iter.str;
rows[nrows].width = rowWidth * invscale;
rows[nrows].minx = rowMinX * invscale;
rows[nrows].maxx = rowMaxX * invscale;
rows[nrows].next = iter.next;
nrows++;
if (nrows >= maxRows)
return nrows;
// Set null break point
breakEnd = rowStart;
breakWidth = 0.0;
breakMaxX = 0.0;
// Indicate to skip the white space at the beginning of the row.
rowStart = NULL;
rowEnd = NULL;
rowWidth = 0;
rowMinX = rowMaxX = 0;
} else {
if (rowStart == NULL) {
// Skip white space until the beginning of the line
if (type == NVG_CHAR || type == NVG_CJK_CHAR) {
// The current char is the row so far
rowStartX = iter.x;
rowStart = iter.str;
rowEnd = iter.next;
rowWidth = iter.nextx - rowStartX; // q.x1 - rowStartX;
rowMinX = q.x0 - rowStartX;
rowMaxX = q.x1 - rowStartX;
wordStart = iter.str;
wordStartX = iter.x;
wordMinX = q.x0 - rowStartX;
// Set null break point
breakEnd = rowStart;
breakWidth = 0.0;
breakMaxX = 0.0;
}
} else {
float nextWidth = iter.nextx - rowStartX;
// track last non-white space character
if (type == NVG_CHAR || type == NVG_CJK_CHAR) {
rowEnd = iter.next;
rowWidth = iter.nextx - rowStartX;
rowMaxX = q.x1 - rowStartX;
}
// track last end of a word
if (((ptype == NVG_CHAR || ptype == NVG_CJK_CHAR) && type == NVG_SPACE) || type == NVG_CJK_CHAR) {
breakEnd = iter.str;
breakWidth = rowWidth;
breakMaxX = rowMaxX;
}
// track last beginning of a word
if ((ptype == NVG_SPACE && (type == NVG_CHAR || type == NVG_CJK_CHAR)) || type == NVG_CJK_CHAR) {
wordStart = iter.str;
wordStartX = iter.x;
wordMinX = q.x0 - rowStartX;
}
// Break to new line when a character is beyond break width.
if ((type == NVG_CHAR || type == NVG_CJK_CHAR) && nextWidth > breakRowWidth) {
// The run length is too long, need to break to new line.
if (breakEnd == rowStart) {
// The current word is longer than the row length, just break it from here.
rows[nrows].start = rowStart;
rows[nrows].end = iter.str;
rows[nrows].width = rowWidth * invscale;
rows[nrows].minx = rowMinX * invscale;
rows[nrows].maxx = rowMaxX * invscale;
rows[nrows].next = iter.str;
nrows++;
if (nrows >= maxRows)
return nrows;
rowStartX = iter.x;
rowStart = iter.str;
rowEnd = iter.next;
rowWidth = iter.nextx - rowStartX;
rowMinX = q.x0 - rowStartX;
rowMaxX = q.x1 - rowStartX;
wordStart = iter.str;
wordStartX = iter.x;
wordMinX = q.x0 - rowStartX;
} else {
// Break the line from the end of the last word, and start new line from the beginning of the new.
rows[nrows].start = rowStart;
rows[nrows].end = breakEnd;
rows[nrows].width = breakWidth * invscale;
rows[nrows].minx = rowMinX * invscale;
rows[nrows].maxx = breakMaxX * invscale;
rows[nrows].next = wordStart;
nrows++;
if (nrows >= maxRows)
return nrows;
rowStartX = wordStartX;
rowStart = wordStart;
rowEnd = iter.next;
rowWidth = iter.nextx - rowStartX;
rowMinX = wordMinX;
rowMaxX = q.x1 - rowStartX;
// No change to the word start
}
// Set null break point
breakEnd = rowStart;
breakWidth = 0.0;
breakMaxX = 0.0;
}
}
}
pcodepoint = iter.codepoint;
ptype = type;
}
// Break the line from the end of the last word, and start new line from the beginning of the new.
if (rowStart != NULL) {
rows[nrows].start = rowStart;
rows[nrows].end = rowEnd;
rows[nrows].width = rowWidth * invscale;
rows[nrows].minx = rowMinX * invscale;
rows[nrows].maxx = rowMaxX * invscale;
rows[nrows].next = end;
nrows++;
}
return nrows;
}
float nvgTextBounds(NVGcontext* ctx, float x, float y, const char* string, const char* end, float* bounds)
{
NVGstate* state = nvg__getState(ctx);
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
float width;
if (state->fontId == FONS_INVALID) return 0;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
width = fonsTextBounds(ctx->fs, x*scale, y*scale, string, end, bounds);
if (bounds != NULL) {
// Use line bounds for height.
fonsLineBounds(ctx->fs, y*scale, &bounds[1], &bounds[3]);
bounds[0] *= invscale;
bounds[1] *= invscale;
bounds[2] *= invscale;
bounds[3] *= invscale;
}
return width * invscale;
}
void nvgTextBoxBounds(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds)
{
NVGstate* state = nvg__getState(ctx);
NVGtextRow rows[2];
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
int nrows = 0, i;
int oldAlign = state->textAlign;
int haling = state->textAlign & (NVG_ALIGN_LEFT | NVG_ALIGN_CENTER | NVG_ALIGN_RIGHT);
int valign = state->textAlign & (NVG_ALIGN_TOP | NVG_ALIGN_MIDDLE | NVG_ALIGN_BOTTOM | NVG_ALIGN_BASELINE);
float lineh = 0, rminy = 0, rmaxy = 0;
float minx, miny, maxx, maxy;
if (state->fontId == FONS_INVALID) {
if (bounds != NULL)
bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0f;
return;
}
nvgTextMetrics(ctx, NULL, NULL, &lineh);
state->textAlign = NVG_ALIGN_LEFT | valign;
minx = maxx = x;
miny = maxy = y;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
fonsLineBounds(ctx->fs, 0, &rminy, &rmaxy);
rminy *= invscale;
rmaxy *= invscale;
while ((nrows = nvgTextBreakLines(ctx, string, end, breakRowWidth, rows, 2))) {
for (i = 0; i < nrows; i++) {
NVGtextRow* row = &rows[i];
float rminx, rmaxx, dx = 0;
// Horizontal bounds
if (haling & NVG_ALIGN_LEFT)
dx = 0;
else if (haling & NVG_ALIGN_CENTER)
dx = breakRowWidth*0.5f - row->width*0.5f;
else if (haling & NVG_ALIGN_RIGHT)
dx = breakRowWidth - row->width;
rminx = x + row->minx + dx;
rmaxx = x + row->maxx + dx;
minx = nvg__minf(minx, rminx);
maxx = nvg__maxf(maxx, rmaxx);
// Vertical bounds.
miny = nvg__minf(miny, y + rminy);
maxy = nvg__maxf(maxy, y + rmaxy);
y += lineh * state->lineHeight;
}
string = rows[nrows-1].next;
}
state->textAlign = oldAlign;
if (bounds != NULL) {
bounds[0] = minx;
bounds[1] = miny;
bounds[2] = maxx;
bounds[3] = maxy;
}
}
void nvgTextMetrics(NVGcontext* ctx, float* ascender, float* descender, float* lineh)
{
NVGstate* state = nvg__getState(ctx);
float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
float invscale = 1.0f / scale;
if (state->fontId == FONS_INVALID) return;
fonsSetSize(ctx->fs, state->fontSize*scale);
fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
fonsSetBlur(ctx->fs, state->fontBlur*scale);
fonsSetAlign(ctx->fs, state->textAlign);
fonsSetFont(ctx->fs, state->fontId);
fonsVertMetrics(ctx->fs, ascender, descender, lineh);
if (ascender != NULL)
*ascender *= invscale;
if (descender != NULL)
*descender *= invscale;
if (lineh != NULL)
*lineh *= invscale;
}
// vim: ft=c nu noet ts=4
|
93847ca8337c17d446cce86111afe03275294782
|
5efe877bf5ebc9da1e7edb8efabb66b88a78cee4
|
/DcpmPkg/driver/Utils/AcpiParsing.h
|
4f60f58e9e2e7ef3c8737a5b2fff2e119caf7337
|
[
"BSD-3-Clause"
] |
permissive
|
intel/ipmctl
|
342996a882ea7f4d3abf06fd175ec5d5673829b3
|
c75bd840ea7820c8f93a5488fcff75d08beedd51
|
refs/heads/master
| 2023-08-11T03:49:16.000607
| 2023-05-05T02:26:49
| 2023-05-05T02:26:49
| 133,425,750
| 176
| 64
|
BSD-3-Clause
| 2023-03-20T23:15:23
| 2018-05-14T21:53:46
|
C
|
UTF-8
|
C
| false
| false
| 20,555
|
h
|
AcpiParsing.h
|
/*
* Copyright (c) 2018, Intel Corporation.
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _ACPI_PARSING_H_
#define _ACPI_PARSING_H_
#include <Debug.h>
#include <Utility.h>
#include <Types.h>
#include <NvmTables.h>
extern GUID gSpaRangeVolatileRegionGuid;
extern GUID gSpaRangePmRegionGuid;
extern GUID gSpaRangeControlRegionGuid;
extern GUID gSpaRangeBlockDataWindowRegionGuid;
extern GUID gSpaRangeRawVolatileRegionGuid;
extern GUID gSpaRangeIsoVolatileRegionGuid;
extern GUID gSpaRangeRawPmRegionGuid;
extern GUID gSpaRangeIsoPmRegionGuid;
extern GUID gAppDirectPmTypeGuid;
extern GUID gSpaRangeMailboxCustomGuid;
#define SPA_RANGE_VOLATILE_REGION_GUID \
{ 0x7305944F, 0xFDDA, 0x44E3, {0xB1, 0x6C, 0x3F, 0x22, 0xD2, 0x52, 0xE5, 0xD0} }
#define SPA_RANGE_PM_REGION_GUID \
{ 0x66F0D379, 0xB4F3, 0x4074, {0xAC, 0x43, 0x0D, 0x33, 0x18, 0xB7, 0x8C, 0xDB} }
#define SPA_RANGE_CONTROL_REGION_GUID \
{ 0x92F701F6, 0x13B4, 0x405D, {0x91, 0x0B, 0x29, 0x93, 0x67, 0xE8, 0x23, 0x4C} }
#define SPA_RANGE_BLOCK_DATA_WINDOW_REGION_GUID \
{ 0x91AF0530, 0x5D86, 0x470E, {0xA6, 0xB0, 0x0A, 0x2D, 0xB9, 0x40, 0x82, 0x49} }
#define SPA_RANGE_RAW_VOLATILE \
{ 0x77AB535A, 0x45FC, 0x624B, {0x55, 0x60, 0xF7, 0xB2, 0x81, 0xD1, 0xF9, 0x6E} }
#define SPA_RANGE_ISO_VOLATILE \
{ 0x3D5ABD30, 0x4175, 0x87CE, {0x6D, 0x64, 0xD2, 0xAD, 0xE5, 0x23, 0xC4, 0xBB} }
#define SPA_RANGE_RAW_PM \
{ 0x5CEA02C9, 0x4D07, 0x69D3, {0x26, 0x9F, 0x44, 0x96, 0xFB, 0xE0, 0x96, 0xF9} }
#define SPA_RANGE_ISO_PM \
{ 0x08018188, 0x42CD, 0xBB48, {0x10, 0x0F, 0x53, 0x87, 0xD5, 0x3D, 0xED, 0x3D} }
#define APPDIRECT_PM_TYPE \
{ 0x66F0D379, 0xB4F3, 0x4074, {0xAC, 0x43, 0x0D, 0x33, 0x18, 0xB7, 0x8C, 0xDB} }
/*
* SPA_RANGE_CONTROL_REGION_GUID above should only be used for block windows.
* This is a custom GUID so that we can find the mailbox spa range structs.
*/
#define SPA_RANGE_MAILBOX_CUSTOM_GUID \
{ 0x48D7624D, 0x5CD8, 0x4924, {0xAF, 0xD5, 0xDB, 0xCB, 0xF8, 0x50, 0xCC, 0x2B} }
#define NFIT_ACPI_NAMESPACE_ID SIGNATURE_64('A', 'C', 'P', 'I', '0', '0', '1', '0')
#define NFIT_TABLE_SIG SIGNATURE_32('N', 'F', 'I', 'T') //!< NFIT Table signature
#define PCAT_TABLE_SIG SIGNATURE_32('P', 'C', 'A', 'T') //!< PCAT Table signature
#define PMTT_TABLE_SIG SIGNATURE_32('P', 'M', 'T', 'T') //!< PMTT Table signature
/**
Offset of the MinFixed field in the Nfit Acpi Namespace.
This field contains the pointer to the NFIT table.
**/
#define NFIT_POINTER_OFFSET 0x2A
typedef enum {
MEMORY_MODE_1LM = 0,
MEMORY_MODE_2LM = 1,
MEMORY_MODE_1LM_PLUS_2LM = 2
} MEMORY_MODE;
typedef SUPPORTED_MEMORY_MODE3 MEMORY_MODE_CAPABILITIES;
#define IS_BIOS_VOLATILE_MEMORY_MODE_2LM(VolatileMemoryMode) ((MEMORY_MODE_2LM == VolatileMemoryMode) || (MEMORY_MODE_1LM_PLUS_2LM == VolatileMemoryMode))
/**
ACPI Related Functions
**/
/**
ParseNfitTable - Performs deserialization from binary memory block into parsed structure of pointers.
@param[in] pTable pointer to the memory containing the NFIT binary representation.
@param[out] ppParsedNfit Pointer to a pointer where the allocated and parsed NFIT table will be stored
@retval EFI_INVALID_PARAMETER One of the provided parameters is invalid
@retval EFI_VOLUME_CORRUPTED If the table checksum is invalid
@retval EFI_INCOMPATIBLE_VERSION If the table is not compatible with this ipmctl version
@retval EFI_SUCCESS
**/
EFI_STATUS
ParseNfitTable(
IN VOID *pTable,
OUT ParsedFitHeader **ppParsedNfit
);
/**
Performs deserialization from binary memory block, containing PCAT tables, into parsed structure of pointers.
@param[in] pTable pointer to the memory containing the PCAT binary representation.
@param[out] ppParsedPcat Pointer to a pointer where the allocated and parsed PCAT table will be stored
@retval EFI_INVALID_PARAMETER One of the provided parameters is invalid
@retval EFI_VOLUME_CORRUPTED If the table checksum is invalid
@retval EFI_INCOMPATIBLE_VERSION If the table is not compatible with this ipmctl version
@retval EFI_SUCCESS
**/
EFI_STATUS
ParsePcatTable (
IN VOID *pTable,
OUT ParsedPcatHeader **ppParsedPcat
);
/**
Performs deserialization from binary memory block, containing PMTT tables, into parsed structure of pointers.
@param[in] pTable pointer to the memory containing the PMTT binary representation.
@param[out] ppParsedPmtt Pointer to a pointer where the allocated and parsed PMTT table will be stored
@retval EFI_INVALID_PARAMETER One of the provided parameters is invalid
@retval EFI_VOLUME_CORRUPTED If the table checksum is invalid
@retval EFI_INCOMPATIBLE_VERSION If the table is not compatible with this ipmctl version
@retval EFI_SUCCESS
**/
EFI_STATUS
ParsePmttTable(
IN VOID *pTable,
OUT ParsedPmttHeader **ppParsedPmtt
);
/**
Get PMTT Dimm Module by Dimm ID
Scan the dimm list for a dimm identified by Dimm ID
@param[in] DimmID: The SMBIOS Type 17 handle of the dimm
@param[in] pPmttHead: Parsed PMTT Table
@retval PMTT_MODULE_INFO struct pointer if matching dimm has been found
@retval NULL pointer if not found
**/
PMTT_MODULE_INFO *
GetDimmModuleByPidFromPmtt(
IN UINT32 DimmID,
IN ParsedPmttHeader *pPmttHead
);
/**
Retrieve the Logical Socket ID from PMTT Table
@param[in] SocketId SocketID
@param[in] DieId DieID
@param[out] pLogicalSocketId Logical socket ID based on Dimm socket ID & Die ID
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER Input parameter is NULL
@retval EFI_NOT_FOUND PCAT socket sku info table not found for given socketID
**/
EFI_STATUS
GetLogicalSocketIdFromPmtt(
IN UINT32 SocketId,
IN UINT32 DieId,
OUT UINT32 *pLogicalSocketId
);
/**
Check if the current population is a special non-por config supported when cross-tiling is enabled
@param[out] pNonPorCrossTileSupportedConfig pointer to non-por config supported boolean flag
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER pNonPorCrossTileSupportedConfig is NULL
@retval EFI_NOT_FOUND Parsed PMTT table is NULL
**/
EFI_STATUS
CheckIsNonPorCrossTileSupportedConfig(
OUT BOOLEAN *pNonPorCrossTileSupportedConfig
);
/**
Retrieve the platform topology information (iMCs per die, Channels per iMc)
@param[out] piMCsNumPerDie Pointer to number of iMCs per die
@param[out] pChannelsNumPeriMC Pointer to number of channels per iMC
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER Input parameter is NULL
@retval EFI_NOT_FOUND Parsed PMTT table pointer is NULL
**/
EFI_STATUS
RetrievePlatformTopologyFromPmtt(
OUT UINT32 *piMCsNumPerDie,
OUT UINT32 *pChannelsNumPeriMC
);
/**
Conversion Functions
**/
/**
Returns the FlushHint table associated with the provided NVDIMM region table.
@param[in] pFitHead pointer to the parsed NFit Header structure.
@param[in] pNvDimmRegionMappingStructure the NVDIMM region table that contains the index.
@param[out] ppFlushHintTable pointer to a pointer where the table will be stored.
@retval EFI_SUCCESS if the table was found and is properly returned.
@retval EFI_INVALID_PARAMETER if one or more parameters equal NULL.
@retval EFI_NOT_FOUND if there is no Interleave table with the provided index.
**/
EFI_STATUS
GetFlushHintTableForNvDimmRegionTable(
IN ParsedFitHeader *pFitHead,
IN NvDimmRegionMappingStructure *pNvDimmRegionMappingStructure,
OUT FlushHintTbl **ppFlushHintTable
);
/**
GetBlockDataWindowRegDescTabl - returns the Block Data Window Table associated with the provided Control Region Table.
@param[in] pFitHead pointer to the parsed NFit Header structure.
@param[in] pControlRegionTable the Control Region table that contains the index.
@param[out] ppBlockDataWindowTable pointer to a pointer where the table will be stored.
@retval EFI_SUCCESS if the table was found and is properly returned.
@retval EFI_INVALID_PARAMETER if pFitHead or ControlRegionTbl or BWRegionTbl equals NULL.
@retval EFI_NOT_FOUND if there is no Block Data Window Descriptor table with the provided index.
**/
EFI_STATUS
GetBlockDataWindowRegDescTabl(
IN ParsedFitHeader *pFitHead,
IN ControlRegionTbl *pControlRegTbl,
OUT BWRegionTbl **ppBlockDataWindowTable
);
/**
Returns the ControlRegion table associated with the provided NVDIMM region table.
@param[in] pFitHead pointer to the parsed NFit Header structure.
@param[in] pNvDimmRegionMappingStructure the NVDIMM region table that contains the index.
@param[out] ppControlRegionTable pointer to a pointer where the table will be stored.
@retval EFI_SUCCESS if the table was found and is properly returned.
@retval EFI_INVALID_PARAMETER if one or more input parameters equal NULL.
@retval EFI_NOT_FOUND if there is no Control Region table with the provided index.
**/
EFI_STATUS
GetControlRegionTableForNvDimmRegionTable(
IN ParsedFitHeader *pFitHead,
IN NvDimmRegionMappingStructure *pNvDimmRegionMappingStructure,
OUT ControlRegionTbl **ppControlRegionTable
);
/**
Get Control Region table for provided PhysicalID
@param[in] pFitHead pointer to the parsed NFit Header structure
@param[in] Pid Dimm PhysicalID
@param[out] pControlRegionTables array to store Control Region tables pointers
@param[in, out] pControlRegionTablesNum size of array on input, number of items stored in the array on output
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER One or more parameters are NULL
@retval EFI_BUFFER_TOO_SMALL There is more Control Region tables in NFIT than size of provided array
**/
EFI_STATUS
GetControlRegionTablesForPID(
IN ParsedFitHeader *pFitHead,
IN UINT16 Pid,
OUT ControlRegionTbl *pControlRegionTables[],
IN OUT UINT32 *pControlRegionTablesNum
);
/**
GetSpaRangeTable - returns the SpaRange Table with the provided Index.
@param[in] pFitHead pointer to the parsed NFit Header structure.
@param[in] SpaRangeTblIndex index of the table to be found.
@param[out] ppSpaRangeTbl pointer to a pointer where the table will be stored.
@retval EFI_SUCCESS if the table was found and is properly returned.
@retval EFI_INVALID_PARAMETER if pFitHead or ppInterleaveTbl equals NULL.
@retval EFI_NOT_FOUND if there is no Interleave table with the provided index.
**/
EFI_STATUS
GetSpaRangeTable(
IN ParsedFitHeader *pFitHead,
IN UINT16 SpaRangeTblIndex,
OUT SpaRangeTbl **ppSpaRangeTbl
);
/**
Finds in the provided Nfit structure the requested NVDIMM region.
If the pAddrRangeTypeGuid equals NULL, the first table matching the Pid will be returned.
@param[in] pFitHead pointer to the parsed NFit Header structure.
@param[in] Pid the Dimm ID that the NVDIMM region must be for.
@param[in] pAddrRangeTypeGuid pointer to GUID type of the range that we are looking for. OPTIONAL
@param[in] SpaRangeIndexProvided Determine if SpaRangeIndex is provided
@param[in] SpaRangeIndex Looking for NVDIMM region table that is related with provided SPA table. OPTIONAL
@param[out] ppNvDimmRegionMappingStructure pointer to a pointer for the return NVDIMM region.
@retval EFI_SUCCESS if the table was found and was returned.
@retval EFI_INVALID_PARAMETER if one or more input parameters equal NULL.
@retval EFI_NOT_FOUND if there is no NVDIMM region for the provided Dimm PID and AddrRangeType.
**/
EFI_STATUS
GetNvDimmRegionMappingStructureForPid(
IN ParsedFitHeader *pFitHead,
IN UINT16 Pid,
IN GUID *pAddrRangeTypeGuid OPTIONAL,
IN BOOLEAN SpaRangeIndexProvided,
IN UINT16 SpaRangeIndex OPTIONAL,
OUT NvDimmRegionMappingStructure **ppNvDimmRegionMappingStructure
);
/**
GetInterleaveTable - returns the Interleave Table with the provided Index.
@param[in] pFitHead pointer to the parsed NFit Header structure.
@param[in] InterleaveTblIndex index of the table to be found.
@param[out] ppInterleaveTbl pointer to a pointer where the table will be stored.
@retval EFI_SUCCESS if the table was found and is properly returned.
@retval EFI_INVALID_PARAMETER if pFitHead or ppInterleaveTbl equals NULL.
@retval EFI_NOT_FOUND if there is no Interleave table with the provided index.
**/
EFI_STATUS
GetInterleaveTable(
IN ParsedFitHeader *pFitHead,
IN UINT16 InterleaveTblIndex,
OUT InterleaveStruct **ppInterleaveTbl
);
/**
RdpaToSpa() - Convert Device Region Physical to System Physical Address
@param[in] Rdpa Device Region Physical Address to convert
@param[in] pNvDimmRegionTable The NVDIMM region that helps describe this region of memory
@param[in] pInterleaveTable Interleave table referenced by the MemDevToSpaRangeTable
@param[out] SpaAddr output for SPA address
A memory device could have multiple regions. As such we cannot convert
to a device physical address. Instead we refer to the address for a region
within the device as device region physical address (RDPA), where Rdpa is
a zero based address from the start of the region within the device.
@retval EFI_SUCCESS on success
@retval EFI_INVALID_PARAMETER on a divide by zero error
**/
EFI_STATUS
RdpaToSpa(
IN UINT64 Rdpa,
IN NvDimmRegionMappingStructure *pNvDimmRegionTable,
IN SpaRangeTbl *pSpaRangeTable,
IN InterleaveStruct *pInterleaveTable OPTIONAL,
OUT UINT64 *pSpaAddr
);
/**
Return the current memory mode chosen by the BIOS during boot-up. 1LM is
the fallback option and will always be available. 2LM will only be enabled
if the AllowedMemoryMode is 2LM, there is memory configured for 2LM, and
it is in a BIOS-supported configuration. We read this information from the
PCAT table provided by BIOS.
@param[out] pResult The current memory mode chosen by BIOS
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER Input parameter is NULL
@retval EFI_ABORTED PCAT tables not found
**/
EFI_STATUS
CurrentMemoryMode(
OUT MEMORY_MODE *pResult
);
/**
Return the allowed memory mode selected in the BIOS setup menu under
Socket Configuration -> Memory Configuration -> Memory Map -> Volatile Memory Mode.
Even if 2LM is allowed, it implies that 1LM is allowed as well (even
though the memory mode doesn't indicate this).
We read this information from the PCAT table provided by BIOS.
@param[out] pResult The allowed memory mode setting in BIOS
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER Input parameter is NULL
@retval EFI_ABORTED PCAT tables not found
**/
EFI_STATUS
AllowedMemoryMode(
OUT MEMORY_MODE *pResult
);
/**
Check if BIOS supports changing configuration through management software
@param[out] pConfigChangeSupported The Config Change support in BIOS
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER Input parameter is NULL
@retval EFI_LOAD_ERROR PCAT tables not found
**/
EFI_STATUS
CheckIfBiosSupportsConfigChange(
OUT BOOLEAN *pConfigChangeSupported
);
/**
Check Memory Mode Capabilities from PCAT table type 0
@param[out] pMemoryModeCapabilities pointer to memory mode capabilities
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER Input parameter is NULL
@retval EFI_LOAD_ERROR PCAT tables not found
**/
EFI_STATUS
CheckMemModeCapabilities(
OUT MEMORY_MODE_CAPABILITIES *pMemoryModeCapabilities
);
/**
Retrieve the PCAT Socket SKU Mapped Memory Limit for a given socket
@param[in] SocketId SocketID to retrieve the table for
@param[out] pMappedMemoryLimit Pointer to Mapped Memory Limit
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER Input parameter is NULL
@retval EFI_NOT_FOUND PCAT socket sku mapped memory limit not found for given socketID
**/
EFI_STATUS
RetrievePcatSocketSkuMappedMemoryLimit(
IN UINT32 SocketId,
OUT UINT64 *pMappedMemoryLimit
);
/**
Retrieve the PCAT Socket SKU Total Mapped Memory for a given socket
@param[in] SocketId SocketID, 0xFFFF indicates all sockets
@param[out] pTotalMappedMemory Pointer to Total Mapped Memory
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER Input parameter is NULL
@retval EFI_NOT_FOUND PCAT socket sku total mapped memory not found for given socketID
**/
EFI_STATUS
RetrievePcatSocketSkuTotalMappedMemory(
IN UINT32 SocketId,
OUT UINT64 *pTotalMappedMemory
);
/**
Retrieve the PCAT Socket SKU Cached Memory for a given socket
@param[in] SocketId SocketID, 0xFFFF indicates all sockets
@param[out] pCachedMemory Pointer to Cached Memory Size
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER Input parameter is NULL
@retval EFI_NOT_FOUND PCAT socket sku cached memory size not found for given socketID
**/
EFI_STATUS
RetrievePcatSocketSkuCachedMemory(
IN UINT32 SocketId,
OUT UINT64 *pCachedMemory
);
/**
Retrieve the list of supported Channel & iMC Interleave sizes
@param[out] ppChannelInterleaveSize Array of supported Channel Interleave sizes
@param[out] ppiMCInterleaveSize Array of supported iMC Interleave sizes
@param[out] ppRecommendedFormats Array of recommended formats
@param[out] ppChannelWays Array of supported channel ways
@param[out] pLength Length of the array
@param[out] pInterleaveAlignmentSize Interleave Alignment Size
@param[out] pRevision PCAT Table revision
@retval EFI_SUCCESS Success
@retval EFI_OUT_OF_RESOURCES Memory Allocation failure
@retval EFI_INVALID_PARAMETER ppChannelInterleaveSize, ppiMCInterleaveSize or pLength is NULL
@retval EFI_NOT_FOUND Interleave size info not found
**/
EFI_STATUS
RetrieveSupportediMcAndChannelInterleaveSizes(
OUT UINT32 **ppChannelInterleaveSize,
OUT UINT32 **ppiMCInterleaveSize,
OUT UINT32 **ppRecommendedFormats,
OUT UINT32 **ppChannelWays,
OUT UINT32 *pLength,
OUT UINT32 *pInterleaveAlignmentSize,
OUT ACPI_REVISION *pRevision
);
/**
Retrieve InterleaveSetMap Info
@param[out] ppInterleaveMap Info List used to determine the best interleave based on requested DCPMMs
@param[out] pInterleaveMapListLength Pointer to the InterleaveSetMap Length
@retval EFI_SUCCESS Success
@retval EFI_OUT_OF_RESOURCES Memory Allocation failure
@retval EFI_INVALID_PARAMETER ppInterleaveSetMap or InterleaveMapListLength is NULL
@retval EFI_NOT_FOUND InterleaveSetMap Info not found
**/
EFI_STATUS
RetrieveInterleaveSetMap(
OUT UINT32 **ppInterleaveMap,
OUT UINT32 *pInterleaveMapListLength
);
/**
Retrieve Channel ways from InterleaveSetMap Info
@param[out] ppChannelWays Array of channel ways supported
@param[out] pChannelWaysListLength Pointer to the ppChannelWays array Length
@retval EFI_SUCCESS Success
@retval EFI_OUT_OF_RESOURCES Memory Allocation failure
@retval EFI_INVALID_PARAMETER ppInterleaveSetMap or InterleaveMapListLength is NULL
@retval EFI_NOT_FOUND InterleaveSetMap Info not found
**/
EFI_STATUS
RetrieveChannelWaysFromInterleaveSetMap(
OUT UINT32 **ppChannelWays,
OUT UINT32 *pChannelWaysListLength
);
/**
Performs deserialization from binary memory block containing PMTT table and checks if memory mode can be configured.
@param[in] pTable pointer to the memory containing the PMTT binary representation.
@retval false if topology does NOT allows MM.
@retval true if topology allows MM.
**/
BOOLEAN
CheckIsMemoryModeAllowed(
IN TABLE_HEADER *pPMTT
);
/**
Retrieve Maximum PM Interleave Sets per Die & DCPMM
@param[out] pMaxPMInterleaveSets Pointer to Maximum PM Interleave Sets per Die & Dcpmm
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER pMaxPMInterleaveSetsPerDie or pMaxPMInterleaveSetsPerDcpmm is NULL
@retval EFI_NOT_FOUND InterleaveSetMap Info not found
**/
EFI_STATUS
RetrieveMaxPMInterleaveSets(
OUT MAX_PMINTERLEAVE_SETS *pMaxPMInterleaveSets
);
/**
Retrieve PCAT DDR Cache Size per channel in bytes from PCAT PlatformCapabilityInfo table
@param[out] pDDRCacheSize pointer to DDR Cache Size
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER pDDRCacheSize is NULL
@retval EFI_NOT_FOUND DDRCacheSize not found
**/
EFI_STATUS
RetrievePcatDDRCacheSize(
OUT UINT64 *pDDRCacheSize
);
/**
Check PCAT Cache Capabilities to see if cross-tile caching is supported
@param[out] pCrossTileCachingSupported pointer to cross-tile supported boolean flag
@retval EFI_SUCCESS Success
@retval EFI_INVALID_PARAMETER pCrossTileCachingSupported is NULL
@retval EFI_NOT_FOUND CrossTileCachingSupport not found
**/
EFI_STATUS
CheckIsCrossTileCachingSupported(
OUT BOOLEAN *pCrossTileCachingSupported
);
#endif
|
4746338d03c31d55c1f9e5ef5e54f4498150189b
|
331640994b1b6f66c1639278571ddbdc6c8c0751
|
/src/java/nxt_jni_Context.c
|
589e1c5bf88993003d2b812444fed36159667bc3
|
[
"Apache-2.0"
] |
permissive
|
nginx/unit
|
eabcd067eaa60f4bdcf0cfaffe7d9932add2c66a
|
9b22b6957bc87b3df002d0bc691fdae6a20abdac
|
refs/heads/master
| 2023-09-04T02:02:13.581700
| 2023-08-30T16:07:24
| 2023-08-30T16:07:24
| 102,627,638
| 4,649
| 452
|
Apache-2.0
| 2023-09-12T01:28:22
| 2017-09-06T15:45:30
|
C
|
UTF-8
|
C
| false
| false
| 4,173
|
c
|
nxt_jni_Context.c
|
/*
* Copyright (C) NGINX, Inc.
*/
#include <nxt_auto_config.h>
#include <nxt_unit.h>
#include <jni.h>
#include "nxt_jni.h"
#include "nxt_jni_Context.h"
#include "nxt_jni_URLClassLoader.h"
static jclass nxt_java_Context_class;
static jmethodID nxt_java_Context_start;
static jmethodID nxt_java_Context_service;
static jmethodID nxt_java_Context_stop;
static void JNICALL nxt_java_Context_log(JNIEnv *env, jclass cls,
jlong ctx_ptr, jstring msg, jint msg_len);
static void JNICALL nxt_java_Context_trace(JNIEnv *env, jclass cls,
jlong ctx_ptr, jstring msg, jint msg_len);
int
nxt_java_initContext(JNIEnv *env, jobject cl)
{
int res;
jclass cls;
cls = nxt_java_loadClass(env, cl, "nginx.unit.Context");
if (cls == NULL) {
nxt_unit_warn(NULL, "nginx.unit.Context not found");
return NXT_UNIT_ERROR;
}
nxt_java_Context_class = (*env)->NewGlobalRef(env, cls);
(*env)->DeleteLocalRef(env, cls);
cls = nxt_java_Context_class;
nxt_java_Context_start = (*env)->GetStaticMethodID(env, cls, "start",
"(Ljava/lang/String;[Ljava/net/URL;)Lnginx/unit/Context;");
if (nxt_java_Context_start == NULL) {
nxt_unit_warn(NULL, "nginx.unit.Context.start() not found");
goto failed;
}
nxt_java_Context_service = (*env)->GetMethodID(env, cls, "service",
"(Lnginx/unit/Request;Lnginx/unit/Response;)V");
if (nxt_java_Context_service == NULL) {
nxt_unit_warn(NULL, "nginx.unit.Context.service() not found");
goto failed;
}
nxt_java_Context_stop = (*env)->GetMethodID(env, cls, "stop", "()V");
if (nxt_java_Context_stop == NULL) {
nxt_unit_warn(NULL, "nginx.unit.Context.stop() not found");
goto failed;
}
JNINativeMethod context_methods[] = {
{ (char *) "log",
(char *) "(JLjava/lang/String;I)V",
nxt_java_Context_log },
{ (char *) "trace",
(char *) "(JLjava/lang/String;I)V",
nxt_java_Context_trace },
};
res = (*env)->RegisterNatives(env, nxt_java_Context_class,
context_methods,
sizeof(context_methods)
/ sizeof(context_methods[0]));
nxt_unit_debug(NULL, "registered Context methods: %d", res);
if (res != 0) {
nxt_unit_warn(NULL, "registering natives for Context failed");
goto failed;
}
return NXT_UNIT_OK;
failed:
(*env)->DeleteGlobalRef(env, cls);
return NXT_UNIT_ERROR;
}
jobject
nxt_java_startContext(JNIEnv *env, const char *webapp, jobject classpaths)
{
jstring webapp_str;
webapp_str = (*env)->NewStringUTF(env, webapp);
if (webapp_str == NULL) {
return NULL;
}
return (*env)->CallStaticObjectMethod(env, nxt_java_Context_class,
nxt_java_Context_start, webapp_str,
classpaths);
}
void
nxt_java_service(JNIEnv *env, jobject ctx, jobject jreq, jobject jresp)
{
(*env)->CallVoidMethod(env, ctx, nxt_java_Context_service, jreq, jresp);
}
void
nxt_java_stopContext(JNIEnv *env, jobject ctx)
{
(*env)->CallVoidMethod(env, ctx, nxt_java_Context_stop);
}
static void JNICALL
nxt_java_Context_log(JNIEnv *env, jclass cls, jlong ctx_ptr, jstring msg,
jint msg_len)
{
const char *msg_str;
nxt_unit_ctx_t *ctx;
ctx = nxt_jlong2ptr(ctx_ptr);
msg_str = (*env)->GetStringUTFChars(env, msg, NULL);
if (msg_str == NULL) {
return;
}
nxt_unit_log(ctx, NXT_UNIT_LOG_INFO, "%.*s", msg_len, msg_str);
(*env)->ReleaseStringUTFChars(env, msg, msg_str);
}
static void JNICALL
nxt_java_Context_trace(JNIEnv *env, jclass cls, jlong ctx_ptr, jstring msg,
jint msg_len)
{
#if (NXT_DEBUG)
const char *msg_str;
nxt_unit_ctx_t *ctx;
ctx = nxt_jlong2ptr(ctx_ptr);
msg_str = (*env)->GetStringUTFChars(env, msg, NULL);
if (msg_str == NULL) {
return;
}
nxt_unit_debug(ctx, "%.*s", msg_len, msg_str);
(*env)->ReleaseStringUTFChars(env, msg, msg_str);
#endif
}
|
f5ca46ed0f9914282c4a67e1010acbfca09ff449
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/mm32f327x/Libraries/MM32F327x/HAL_Lib/Src/hal_ver.c
|
9d771396cffa27da5fba3b12a0ec2ea72d695e9e
|
[
"Apache-2.0",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"MIT",
"BSD-3-Clause",
"X11",
"BSD-4-Clause-UC",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 5,426
|
c
|
hal_ver.c
|
////////////////////////////////////////////////////////////////////////////////
/// @file hal_ver.c
/// @author AE TEAM
/// @brief THIS FILE PROVIDES ALL THE LIB AND THE CHIPSET INFORMATION.
////////////////////////////////////////////////////////////////////////////////
/// @attention
///
/// THE EXISTING FIRMWARE IS ONLY FOR REFERENCE, WHICH IS DESIGNED TO PROVIDE
/// CUSTOMERS WITH CODING INFORMATION ABOUT THEIR PRODUCTS SO THEY CAN SAVE
/// TIME. THEREFORE, MINDMOTION SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
/// CONSEQUENTIAL DAMAGES ABOUT ANY CLAIMS ARISING OUT OF THE CONTENT OF SUCH
/// HARDWARE AND/OR THE USE OF THE CODING INFORMATION CONTAINED HEREIN IN
/// CONNECTION WITH PRODUCTS MADE BY CUSTOMERS.
///
/// <H2><CENTER>© COPYRIGHT MINDMOTION </CENTER></H2>
////////////////////////////////////////////////////////////////////////////////
// Define to prevent recursive inclusion
#define _HAL_VER_C_
// Files includes
#include "hal_ver.h"
// MM32 Library version is 0.90
#define __MM32_LIB_VERSION_MAIN (0x0U) //!< [31:24] main version
#define __MM32_LIB_VERSION_SUB1 (0x9U) //!< [23:16] sub1 version
#define __MM32_LIB_VERSION_SUB2 (0x0U) //!< [15:8] sub2 version
#define __MM32_LIB_VERSION_RC (0x00U) //!< [7:0] release candidate
#define __MM32_LIB_VERSION ((__MM32_LIB_VERSION_MAIN << 24U)\
|(__MM32_LIB_VERSION_SUB1 << 16U)\
|(__MM32_LIB_VERSION_SUB2 << 8U )\
|(__MM32_LIB_VERSION_RC))
// MM32 Library release date is 2021-05-10 (YYYY-MM-DD)
#define __MM32_LIB_RELESE_YEARH (0x20U) //!< [31:24] release year high
#define __MM32_LIB_RELESE_YEARL (0x21U) //!< [23:16] release year low
#define __MM32_LIB_RELESE_MONTH (0x05U) //!< [15:8] release month
#define __MM32_LIB_RELESE_DAY (0x10U) //!< [7:0] release day
#define __MM32_LIB_RELESE_DATE ((__MM32_LIB_RELESE_YEARH << 24U)\
|(__MM32_LIB_RELESE_YEARL << 16U)\
|(__MM32_LIB_RELESE_MONTH << 8U )\
|(__MM32_LIB_RELESE_DAY))
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MM32_Hardware_Abstract_Layer
/// @{
////////////////////////////////////////////////////////////////////////////////
///@addtogroup VER_HAL
///@{
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Lib and chipset_Exported_Functions
/// @{
////////////////////////////////////////////////////////////////////////////////
/// @brief This method returns the Lib revision.
/// @param None.
/// @retval return the Lib version.
////////////////////////////////////////////////////////////////////////////////
u32 Get_MM32LibVersion(void)
{
return __MM32_LIB_VERSION;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief This method returns the Lib release date.
/// @param None.
/// @retval return the Lib release date.
////////////////////////////////////////////////////////////////////////////////
u32 Get_MM32LibReleaseDate(void)
{
return __MM32_LIB_RELESE_DATE;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Returns the device revision identifier.
/// @param None.
/// @retval return the device revision identifier.
////////////////////////////////////////////////////////////////////////////////
u32 Get_ChipsetREVID(void)
{
return((DBGMCU->IDCODE) & 0xF );
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Returns the device identifier..
/// @param None.
/// @retval return the device Device identifier.
////////////////////////////////////////////////////////////////////////////////
u32 Get_ChipsetDEVID(void)
{
return((DBGMCU->IDCODE) );
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Returns first word of the unique device identifier (UID based on 96 bits)
/// @param None.
/// @retval Device identifier
////////////////////////////////////////////////////////////////////////////////
u32 Get_ChipsetUIDw0(void)
{
return(READ_REG(*((vu32*)UID_BASE)));
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Returns second word of the unique device identifier (UID based on 96 bits)
/// @param None.
/// @retval Device identifier
////////////////////////////////////////////////////////////////////////////////
u32 Get_ChipsetUIDw1(void)
{
return(READ_REG(*((vu32*)(UID_BASE + 4U))));
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Returns third word of the unique device identifier (UID based on 96 bits)
/// @param None.
/// @retval Device identifier
////////////////////////////////////////////////////////////////////////////////
u32 Get_ChipsetUIDw2(void)
{
return(READ_REG(*((vu32*)(UID_BASE + 8U))));
}
/// @}
/// @}
/// @}
|
cad1e897d367b2674d09ea80e34725e5a9783dcb
|
b4d1fc90b1c88f355c0cc165d73eebca4727d09b
|
/include/wrapper/cef_closure_task.h
|
95dde6a81b1bd062fc0a525b2648162298d1b6fa
|
[
"BSD-3-Clause"
] |
permissive
|
chromiumembedded/cef
|
f03bee5fbd8745500490ac90fcba45616a29be6e
|
f808926fbda17c7678e21f1403d6f996e9a95138
|
refs/heads/master
| 2023-09-01T20:37:38.750882
| 2023-08-31T17:16:46
| 2023-08-31T17:28:27
| 87,006,077
| 2,600
| 454
|
NOASSERTION
| 2023-07-21T11:39:49
| 2017-04-02T18:19:23
|
C++
|
UTF-8
|
C
| false
| false
| 4,543
|
h
|
cef_closure_task.h
|
// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---------------------------------------------------------------------------
//
// The contents of this file are only available to applications that link
// against the libcef_dll_wrapper target.
//
#ifndef CEF_INCLUDE_WRAPPER_CEF_CLOSURE_TASK_H_
#define CEF_INCLUDE_WRAPPER_CEF_CLOSURE_TASK_H_
#pragma once
#include "include/base/cef_callback_forward.h"
#include "include/cef_task.h"
///
/// \file
/// Helpers for asynchronously executing a base::[Once|Repeating]Closure (bound
/// function or method) on a CEF thread. Creation of a
/// base::[Once|Repeating]Closure can be facilitated using
/// base::Bind[Once|Repeating]. See include/base/cef_callback.h for complete
/// usage instructions.
///
/// To use these helpers you should include this header and the header that
/// defines base::Bind[Once|Repeating].
///
/// <pre>
/// #include "include/base/cef_callback.h"
/// #include "include/wrapper/cef_closure_task.h"
/// </pre>
///
/// Example of executing a bound function:
///
/// <pre>
/// // Define a function.
/// void MyFunc(int arg) { /* do something with |arg| on the UI thread */ }
///
/// // Post a task that will execute MyFunc on the UI thread and pass an |arg|
/// // value of 5.
/// CefPostTask(TID_UI, base::BindOnce(&MyFunc, 5));
/// </pre>
///
/// Example of executing a bound method:
///
/// <pre>
/// // Define a class.
/// class MyClass : public CefBaseRefCounted {
/// public:
/// MyClass() {}
/// void MyMethod(int arg) { /* do something with |arg| on the UI thread */
/// }
/// private:
/// IMPLEMENT_REFCOUNTING(MyClass);
/// };
///
/// // Create an instance of MyClass.
/// CefRefPtr<MyClass> instance = new MyClass();
///
/// // Post a task that will execute MyClass::MyMethod on the UI thread and
/// // pass an |arg| value of 5. |instance| will be kept alive until after the
/// // task completes.
/// CefPostTask(TID_UI, base::BindOnce(&MyClass::MyMethod, instance, 5));
/// </pre>
///
///
/// Create a CefTask that wraps a base::[Once|Repeating]Closure. Can be used in
/// combination with CefTaskRunner.
///
CefRefPtr<CefTask> CefCreateClosureTask(base::OnceClosure closure);
CefRefPtr<CefTask> CefCreateClosureTask(const base::RepeatingClosure& closure);
///
/// Post a base::[Once|Repeating]Closure for execution on the specified thread.
///
bool CefPostTask(CefThreadId threadId, base::OnceClosure closure);
bool CefPostTask(CefThreadId threadId, const base::RepeatingClosure& closure);
///
/// Post a base::[Once|Repeating]Closure for delayed execution on the specified
/// thread.
///
bool CefPostDelayedTask(CefThreadId threadId,
base::OnceClosure closure,
int64_t delay_ms);
bool CefPostDelayedTask(CefThreadId threadId,
const base::RepeatingClosure& closure,
int64_t delay_ms);
#endif // CEF_INCLUDE_WRAPPER_CEF_CLOSURE_TASK_H_
|
26dc4fbc3175180c362d85cb92268e329151bb18
|
6ff85b80c6fe1b3ad5416a304b93551a5e80de10
|
/C/IO/Scanf.c
|
56bf347ebfe5d755bc61c41c4f558e2a01283fee
|
[
"MIT"
] |
permissive
|
maniero/SOpt
|
c600cc2333e0a47ce013be3516bbb8080502ff2a
|
5d17e1a9cbf115eaea6d30af2079d0c92ffff7a3
|
refs/heads/master
| 2023-08-10T16:48:46.058739
| 2023-08-10T13:42:17
| 2023-08-10T13:42:17
| 78,631,930
| 1,002
| 136
|
MIT
| 2023-01-28T12:10:01
| 2017-01-11T11:19:24
|
C#
|
UTF-8
|
C
| false
| false
| 371
|
c
|
Scanf.c
|
#include <stdio.h>
int main() {
int num1, num2;
printf("Digite o numero A e numero B para saber o resto da divisao resultante da divisao entre eles:\n");
printf("NumeroA: "); scanf("%d", &num1);
printf("\n");
printf("NumeroB: "); scanf("%d", &num2);
printf("O resto da divisao e: %d", num1 % num2);
}
//https://pt.stackoverflow.com/q/252692/101
|
f5e8cc87476ff5592440828df23e8f505b55d004
|
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
|
/PWGPP/EMCAL/ECPi0Macros/CheckNoisePeakVariationWithTimeCut.C
|
98a45b833953850d0ece3ad9e244510ca64aadac
|
[] |
permissive
|
alisw/AliPhysics
|
91bf1bd01ab2af656a25ff10b25e618a63667d3e
|
5df28b2b415e78e81273b0d9bf5c1b99feda3348
|
refs/heads/master
| 2023-08-31T20:41:44.927176
| 2023-08-31T14:51:12
| 2023-08-31T14:51:12
| 61,661,378
| 129
| 1,150
|
BSD-3-Clause
| 2023-09-14T18:48:45
| 2016-06-21T19:31:29
|
C++
|
UTF-8
|
C
| false
| false
| 4,019
|
c
|
CheckNoisePeakVariationWithTimeCut.C
|
///
/// \file CheckNoisePeakVariationWithTimeCut
/// \ingroup EMCALOfflineMacrosCalibPi0
/// \brief study noise peak and time cut correlation
///
/// Study noise peak variation with time cut.
///
/// \author Astrid Vauthier, <Astrid.Vauthier@cern.ch>, (LPSC-CNRS)
///
#include <stdio.h>
#include <TSystem.h>
#include <TString.h>
#include <TH1.h>
#include "TPostScript.h"
#include "TH2.h"
#include "TStyle.h"
#include "TCanvas.h"
#include "TFile.h"
#include "TMath.h"
#include "TList.h"
#include "TAxis.h"
#include "TPad.h"
#include "TLegend.h"
#include "TLatex.h"
#include "TF1.h"
#include "TList.h"
#include "TLine.h"
//#include "/Users/vauthier/root/macros/myMacros/MyPaletteColor.c" //------------->Have a nice "colz" plot
//#include "/Users/vauthier/root/macros/myMacros/ErrorPropagation.c" //------------->Implemented formula for error propagation
//#include "/Users/vauthier/root/macros/myMacros/SettingsUtils.cpp" //------------->Settings for canvas and histos
void CheckNoisePeakVariationWithTimeCut()
{
//Declare needed variables - histos - files
const int nTimeCut = 2;
TString TimeCut[nTimeCut] = {"LooseTimeCut_NoNegCoeffs","_NoNegCoeffs"};
const int nSM = 20;
const int nCol = 48;
const int nRow = 24;
int nColForSM = 48;
int nRowForSM = 24;
TFile *file[nTimeCut];
TList *list[nTimeCut];
TH1F *hMgg[nSM][nCol][nRow][nTimeCut];
// TFile *rootFileOut = new TFile("output_calibPi0.root","RECREATE");
char psfile[100];
sprintf(psfile,"NoisePeakVariationNoTimeCut.ps");
const int cWidth=500;
const int cHeight=(int)(500*(29./21.));
TCanvas *c1 = new TCanvas("c1","Noise peaks variation as a function of time cuts",cWidth,cHeight);
TPostScript *ps = new TPostScript(psfile,111);
Color_t HistoColor[nTimeCut] = {kMagenta,kBlack};
for(int iTimeCut = 0; iTimeCut < nTimeCut; iTimeCut++)
{
printf("--\nOPEN FILE %sTimeCutApplied\n",TimeCut[iTimeCut].Data());
file[iTimeCut] = new TFile(Form("/cebaf/cebaf/EMCAL/calibPi0_run2/calibPi0_4_with2015data/input/pass4/AnalysisResults_LHC15sumijMaskTowersByHand24Nov2016_pass4%s.root",TimeCut[iTimeCut].Data()));
list[iTimeCut] = (TList*) file[iTimeCut]->Get("Pi0Calibration_Trig");
}//End loop on time cut
TFile *fOut = new TFile("/cebaf/cebaf/EMCAL/calibPi0_run2/calibPi0_4_with2015data/output/pass4_DCALandEMCALThirds/NoisePeakVariationNoTimeCut.root","RECREATE");
for(int iSM = 0; iSM < nSM; iSM++)
{
printf("\nProcessing SM %i ...\n",iSM);
if((iSM == 10) || (iSM == 11) || (iSM == 18) || (iSM == 19)) nRowForSM = 8;
else nRowForSM = 24;
if((iSM > 11) && ((iSM != 18) && (iSM != 19))) nColForSM = 32;
else nColForSM = 48;
for(int iCol = 0; iCol < nColForSM; iCol++)
{
for(int iRow = 0; iRow < nRowForSM; iRow++)
{
if(iRow%(nRow/2) == 0)
{
ps->NewPage();
c1->Clear();
c1->Divide(3,4);
}
c1->cd(iRow%(nRow/2)+1);
for(int iTimeCut = 0; iTimeCut < nTimeCut; iTimeCut++)
{
hMgg[iSM][iCol][iRow][iTimeCut] = (TH1F*) list[iTimeCut]->FindObject(Form("%i_%i_%i",iSM,iCol,iRow));
hMgg[iSM][iCol][iRow][iTimeCut]->SetLineColor(HistoColor[iTimeCut]);
hMgg[iSM][iCol][iRow][iTimeCut]->SetMarkerColor(HistoColor[iTimeCut]);
hMgg[iSM][iCol][iRow][iTimeCut]->SetXTitle("m_{#gamma#gamma} (MeV/c^{2})");
// SetHisto(hMgg[iSM][iCol][iRow][iTimeCut],HistoColor[iTimeCut],20,"","m_{#gamma#gamma} (MeV/c^{2})","");
if(iTimeCut == 0)hMgg[iSM][iCol][iRow][iTimeCut]->Draw("");
else hMgg[iSM][iCol][iRow][iTimeCut]->Draw("same");
hMgg[iSM][iCol][iRow][iTimeCut]->Write(Form("%i_%i_%i_%s",iSM,iCol,iRow,TimeCut[iTimeCut].Data()));
}//End loop on time cut
c1->Update();
}//End loop on row
}//End loop on column
printf("... SM %i done\n",iSM);
}//End loop on SM
fOut->Write();
fOut->Close();
ps->Close();
return;
}
|
78ccf308e7991b71d66ff171211a3799324571b5
|
459e7d1ca537569a53cbeaa2269c63020ea4f747
|
/Example/Pods/Headers/Public/FBAnnotationClustering/FBQuadTreeNode.h
|
20179e8804b5505d756345383151dbc3a435dedf
|
[
"MIT"
] |
permissive
|
infinum/FBAnnotationClustering
|
838eb53ff69388a00197df794e83bb0bb82847c0
|
15c5533cd516bdc1e471a9a6a7a031c0727f09bd
|
refs/heads/master
| 2022-07-11T09:53:43.715958
| 2021-07-26T11:38:39
| 2021-07-26T11:38:39
| 18,653,648
| 436
| 85
|
MIT
| 2021-07-22T05:14:05
| 2014-04-10T22:11:37
|
Objective-C
|
UTF-8
|
C
| false
| false
| 54
|
h
|
FBQuadTreeNode.h
|
../../../../../FBAnnotationClustering/FBQuadTreeNode.h
|
aedef774409bceb75d6aab2cbb52fcdeeff8834e
|
7f6c235b0598353549959c18f69eefd20b766907
|
/include/_DEVELOPMENT/proto/freertos/projdefs.h
|
63d227ddca0b4d61eca46847af60db13118e49a3
|
[
"ClArtistic"
] |
permissive
|
z88dk/z88dk
|
46dfd4905f36d99333173cadd0a660839befc9f0
|
8b07f37cc43c5d9ffe69b563c80763491d8faff7
|
refs/heads/master
| 2023-09-04T19:29:49.254958
| 2023-09-03T20:51:24
| 2023-09-03T20:51:24
| 54,035,569
| 820
| 263
|
NOASSERTION
| 2023-09-05T11:09:04
| 2016-03-16T13:48:16
|
Assembly
|
UTF-8
|
C
| false
| false
| 3,720
|
h
|
projdefs.h
|
/*
* FreeRTOS Kernel V10.5.1+
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
include(__link__.m4)
#ifndef PROJDEFS_H
#define PROJDEFS_H
/*
* Defines the prototype to which task functions must conform. Defined in this
* file to ensure the type is known before portable.h is included.
*/
typedef void (* TaskFunction_t)( void * );
/* Converts a time in milliseconds to a time in ticks. This macro can be
* overridden by a macro of the same name defined in FreeRTOSConfig.h in case the
* definition here is not suitable for your application. */
#ifndef pdMS_TO_TICKS
#if configUSE_16_BIT_TICKS == TICK_TYPE_WIDTH_16_BITS
#define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( uint32_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000U ) )
#else
#define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000U ) )
#endif
#endif
#define pdFALSE ( ( BaseType_t ) 0 )
#define pdTRUE ( ( BaseType_t ) 1 )
#define pdFALSE_SIGNED ( ( BaseType_t ) 0 )
#define pdTRUE_SIGNED ( ( BaseType_t ) 1 )
#define pdFALSE_UNSIGNED ( ( UBaseType_t ) 0 )
#define pdTRUE_UNSIGNED ( ( UBaseType_t ) 1 )
#define pdPASS ( pdTRUE )
#define pdFAIL ( pdFALSE )
#define errQUEUE_EMPTY ( ( BaseType_t ) 0 )
#define errQUEUE_FULL ( ( BaseType_t ) 0 )
/* FreeRTOS error definitions. */
#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 )
#define errQUEUE_BLOCKED ( -4 )
#define errQUEUE_YIELD ( -5 )
/* Macros used for basic data corruption checks. */
#ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES
#define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0
#endif
#if ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_16_BITS )
#define pdINTEGRITY_CHECK_VALUE 0x5a5a
#elif ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_32_BITS )
#define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL
#elif ( configTICK_TYPE_WIDTH_IN_BITS == TICK_TYPE_WIDTH_64_BITS )
#define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5a5a5a5a5aULL
#else
#error configTICK_TYPE_WIDTH_IN_BITS set to unsupported tick type width.
#endif
#endif /* PROJDEFS_H */
|
e5380d42fc40096cfcc40337273afa90951b0ec5
|
e814383d36a10839104efaa4df277996ab220fa3
|
/ompi/mpi/fortran/mpif-h/status_f082f_f.c
|
83ac4d56727363794820ac909450cf888f28b8ef
|
[
"mpich2",
"BSD-3-Clause-Open-MPI"
] |
permissive
|
open-mpi/ompi
|
a1d7483ae1d83dd8fd8ae3ee95e832e0a0ee04e3
|
1edfdb025c4450f694600083ad871cf06c8d45cd
|
refs/heads/main
| 2023-09-01T01:30:02.040705
| 2023-08-29T17:32:18
| 2023-08-29T17:32:18
| 24,107,001
| 2,008
| 973
|
NOASSERTION
| 2023-09-14T20:59:26
| 2014-09-16T16:08:30
|
C
|
UTF-8
|
C
| false
| false
| 2,208
|
c
|
status_f082f_f.c
|
/*
* Copyright (c) 2020 Research Organization for Information Science
* and Technology (RIST). All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "ompi_config.h"
#include "ompi/mpi/fortran/mpif-h/bindings.h"
#include "ompi/mpi/fortran/base/constants.h"
#if OMPI_BUILD_MPI_PROFILING
#if OPAL_HAVE_WEAK_SYMBOLS
#pragma weak PMPI_STATUS_F082F = ompi_status_f082f_f
#pragma weak pmpi_status_f082f = ompi_status_f082f_f
#pragma weak pmpi_status_f082f_ = ompi_status_f082f_f
#pragma weak pmpi_status_f082f__ = ompi_status_f082f_f
#pragma weak PMPI_Status_f082f_f = ompi_status_f082f_f
#pragma weak PMPI_Status_f082f_f08 = ompi_status_f082f_f
#else
OMPI_GENERATE_F77_BINDINGS(PMPI_STATUS_F082F,
pmpi_status_f082f,
pmpi_status_f082f_,
pmpi_status_f082f__,
pompi_status_f082f_f,
(const MPI_F08_status *f08_status, MPI_Fint *f_status, MPI_Fint *ierr),
(f08_status, f_status, ierr) )
#endif
#endif
#if OPAL_HAVE_WEAK_SYMBOLS
#pragma weak MPI_STATUS_F082F = ompi_status_f082f_f
#pragma weak mpi_status_f082f = ompi_status_f082f_f
#pragma weak mpi_status_f082f_ = ompi_status_f082f_f
#pragma weak mpi_status_f082f__ = ompi_status_f082f_f
#pragma weak MPI_Status_f082f_f = ompi_status_f082f_f
#pragma weak MPI_Status_f082f_f08 = ompi_status_f082f_f
#else
#if ! OMPI_BUILD_MPI_PROFILING
OMPI_GENERATE_F77_BINDINGS(MPI_STATUS_F082F,
mpi_status_f082f,
mpi_status_f082f_,
mpi_status_f082f__,
ompi_status_f082f_f,
(const MPI_F08_status *f08_status, MPI_Fint *f_status, MPI_Fint *ierr),
(f08_status, f_status, ierr) )
#else
#define ompi_status_f082f_f pompi_status_f082f_f
#endif
#endif
void ompi_status_f082f_f(const MPI_F08_status *f08_status, MPI_Fint *f_status, MPI_Fint *ierr)
{
int c_ierr;
c_ierr = PMPI_Status_f082f(f08_status, f_status);
if (NULL != ierr) *ierr = OMPI_INT_2_FINT(c_ierr);
}
|
23c8738078e7b5579fe8adcd7ca6b92193c58089
|
f6a5dfd5172e50ba030bfd89a0554f7f71916a80
|
/build/luasocket/select.h
|
677578625ef103cf94cc065920903abd81a03f28
|
[
"MIT"
] |
permissive
|
chexiongsheng/build_xlua_with_libs
|
c9bc62da2457ff49fcca89791694a2ba4eb16632
|
909a0769bf43369b0031499f74dfe99ab89ed661
|
refs/heads/master
| 2023-08-31T07:05:16.276471
| 2023-08-31T06:49:21
| 2023-08-31T06:49:21
| 86,566,149
| 559
| 242
|
MIT
| 2023-08-31T06:49:23
| 2017-03-29T09:56:16
|
C
|
UTF-8
|
C
| false
| false
| 586
|
h
|
select.h
|
#ifndef SELECT_H
#define SELECT_H
/*=========================================================================*\
* Select implementation
* LuaSocket toolkit
*
* Each object that can be passed to the select function has to export
* method getfd() which returns the descriptor to be passed to the
* underlying select function. Another method, dirty(), should return
* true if there is data ready for reading (required for buffered input).
\*=========================================================================*/
int select_open(lua_State *L);
#endif /* SELECT_H */
|
c0e5f7256767c58018edbb830da34abdb34932c1
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/src/world/area_kpa/kpa_112/kpa_112.h
|
a2fc69aa546ebc6d9cee45144add06939d140005
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 308
|
h
|
kpa_112.h
|
/// @file kpa_112.h
/// @brief Bowser's Castle - Hidden Passage 1
#include "common.h"
#include "message_ids.h"
#include "map.h"
#include "../kpa.h"
#include "mapfs/kpa_112_shape.h"
#include "mapfs/kpa_112_hit.h"
#define NAMESPACE kpa_112
extern EvtScript N(EVS_Main);
extern EvtScript N(EVS_SetupMusic);
|
578d27ada8678a8f4ff0093cddd9a4fa0405f9f4
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/libs/libnx/nxtk/nxtk_setsubwindows.c
|
01358c7fa3a8c11587640bdf6b5e22d209bca4c4
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 4,025
|
c
|
nxtk_setsubwindows.c
|
/****************************************************************************
* libs/libnx/nxtk/nxtk_setsubwindows.c
*
* 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdlib.h>
#include <debug.h>
#include <errno.h>
#include <nuttx/nx/nx.h>
#include "nxtk.h"
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: nxtk_setsubwindows
*
* Description:
* Give the window dimensions, border width, and toolbar height,
* calculate the new dimensions of the toolbar region and client window
* region
*
****************************************************************************/
void nxtk_setsubwindows(FAR struct nxtk_framedwindow_s *fwnd)
{
nxgl_coord_t fullheight;
nxgl_coord_t bdrheight = 0;
nxgl_coord_t tbtop = fwnd->wnd.bounds.pt1.y;
nxgl_coord_t tbheight = 0;
nxgl_coord_t fwtop = fwnd->wnd.bounds.pt1.y;
nxgl_coord_t fwheight = 0;
nxgl_coord_t fullwidth;
nxgl_coord_t bdrwidth;
nxgl_coord_t fwwidth;
nxgl_coord_t fwleft;
/* Divide up the vertical dimension of the window */
fullheight = fwnd->wnd.bounds.pt2.y - fwnd->wnd.bounds.pt1.y + 1;
/* Is it tall enough for a border? */
if (fullheight > 0)
{
/* Get the border height */
bdrheight = ngl_min(2 * CONFIG_NXTK_BORDERWIDTH, fullheight);
/* Position the toolbar and client window just under the top border */
#if CONFIG_NXTK_BORDERWIDTH > 1
tbtop += CONFIG_NXTK_BORDERWIDTH - 1;
fwtop = tbtop + 1;
#else
tbtop += CONFIG_NXTK_BORDERWIDTH;
fwtop = tbtop;
#endif
/* Is it big enough for any part of the toolbar? */
if (fullheight > 2 * CONFIG_NXTK_BORDERWIDTH)
{
/* Yes.. get the height of the toolbar */
tbheight = fwnd->tbheight;
if (tbheight >= fullheight - bdrheight)
{
tbheight = fullheight - bdrheight;
}
else
{
/* And the client window gets whatever is left */
fwheight = fullheight - bdrheight - tbheight;
}
/* Position the client window just under the toolbar */
fwtop += tbheight;
}
}
/* Divide up the horizontal dimensions of the window */
fullwidth = fwnd->wnd.bounds.pt2.x - fwnd->wnd.bounds.pt1.x + 1;
bdrwidth = ngl_min(2 * CONFIG_NXTK_BORDERWIDTH, fullwidth);
fwwidth = fullwidth - bdrwidth;
fwleft = fwnd->wnd.bounds.pt1.x + bdrwidth / 2;
/* Realize the positions/dimensions */
fwnd->tbrect.pt1.x = fwleft;
fwnd->tbrect.pt1.y = tbtop;
fwnd->tbrect.pt2.x = fwleft + fwwidth - 1;
fwnd->tbrect.pt2.y = tbtop + tbheight - 1;
fwnd->fwrect.pt1.x = fwleft;
fwnd->fwrect.pt1.y = fwtop;
fwnd->fwrect.pt2.x = fwleft + fwwidth - 1;
fwnd->fwrect.pt2.y = fwtop + fwheight - 1;
}
|
8a76962bdea68419dab143285facf05ed78ad157
|
b0f08154e3eebc7d8465efc57597e52d08d69c18
|
/src/executables/esql_declare.c
|
18db5520eda14f3e33eb4cdfeab7b8ec5623ee3d
|
[
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
CUBRID/cubrid
|
8f71a0010243b72e43ba887d229210650f4e901e
|
3b952af33230839a1b561a78ecd4b773374b66f8
|
refs/heads/develop
| 2023-08-18T19:16:30.987583
| 2023-08-18T08:18:05
| 2023-08-18T08:18:05
| 52,080,367
| 287
| 294
|
NOASSERTION
| 2023-09-14T21:29:09
| 2016-02-19T10:25:32
|
C
|
UTF-8
|
C
| false
| false
| 33,660
|
c
|
esql_declare.c
|
/*
* Copyright 2008 Search Solution Corporation
* Copyright 2016 CUBRID 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.
*
*/
/*
* esql_declare.c - Declaration-handling code for esql preprocessor.
*/
#ident "$Id$"
#include "config.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "esql_grammar.h"
#include "esql_misc.h"
#include "memory_alloc.h"
#include "esql_translate.h"
#include "variable_string.h"
#define NFRAMES 8
#define MAX_LONGS_ALLOWED 1
typedef struct spec_state SPEC_STATE;
typedef struct scope SCOPE;
extern "C"
{
extern FILE *esql_yyout;
}
struct spec_state
{
int noun_seen; /* 1 iff a type noun has been seen */
int longs_seen; /* # of longs seen */
int shorts_seen; /* # of shorts seen */
int signed_seen; /* 1 iff signed or unsigned " " */
int storage_class_seen; /* 1 iff a storage class " " */
int typedef_seen; /* 1 iff typedef is in progress */
int sc_allowed; /* 1 iff storage class specs are allowed */
int volatile_seen; /* 1 iff volatile keyword seen */
int const_seen; /* 1 iff const keyword seen */
LINK *spec; /* The specifier under construction */
};
struct scope
{
int recognizing_typedef_names;
SYMBOL *sym_chain;
STRUCTDEF *struct_chain;
CURSOR *cursor_chain;
WHENEVER_SCOPE whenever;
};
enum
{
MSG_BAD_STORAGE_CLASS = 1,
MSG_MALFORMED_CHAIN = 2,
MSG_SPECIFIER_NOT_ALLOWED = 3,
MSG_ILLEGAL_CLASS_COMBO = 4,
MSG_ILLEGAL_TYPE_COMBO = 5,
MSG_ILLEGAL_MODIFIER_COMBO = 6,
MSG_TYPE_SPEC_UNEXPECTED_CASE = 7,
MSG_TYPE_ADJ_UNEXPECTED_CASE = 8,
MSG_BAD_PSEUDO_DECL = 9
};
/* space and C token literal defs */
#define TOK_SPACE " "
#define TOK_COMMA ","
#define TOK_LB "{"
#define TOK_RB "}"
#define TOK_LP "("
#define TOK_RP ")"
#define TOK_SC ";"
#define TOK_STAR "*"
#define TOK_AUTO "auto"
#define TOK_CONST "const"
#define TOK_EXTERN "extern"
#define TOK_CHAR "char"
#define TOK_DOUBLE "double"
#define TOK_FLOAT "float"
#define TOK_INT "int"
#define TOK_LONG "long"
#define TOK_REGISTER "register"
#define TOK_SHORT "short"
#define TOK_STATIC "static"
#define TOK_TYPEDEF "typedef"
#define TOK_UNSIGNED "unsigned"
#define TOK_VOID "void"
#define TOK_VOLATILE "volatile"
#define TOK_INVALID "whoknows"
int pp_recognizing_typedef_names = 1;
int pp_nesting_level = 0;
static SCOPE *pp_current_name_scope;
static SPEC_STATE *pp_current_spec_scope;
static SCOPE *pp_name_scope_base, *pp_name_scope_limit;
static SPEC_STATE *pp_spec_scope_base, *pp_spec_scope_limit;
static void pp_set_class_bit (int storage_class, LINK * p);
static LINK *pp_new_type_spec (void);
static void pp_remove_structdefs_from_table (STRUCTDEF * struct_chain);
static void pp_print_link (LINK * p, varstring * buf, int context, int preechoed);
static void pp_print_decl (SYMBOL * sym, varstring * buf, int preechoed);
/*
* pp_set_class_bit() - Change the class of the specifier pointed to by p
* as indicated by storage_class.
* return : void
* storage_class(in): The new storage class for the specifier p.
* p(out): The specifier to be changed.
* note :The TYPEDEF class is used here only to remember that the input
* storage class was a typedef.
*/
static void
pp_set_class_bit (int storage_class, LINK * p)
{
switch (storage_class)
{
case 0:
{
p->decl.s.sclass = C_FIXED;
p->decl.s.is_static = 0;
p->decl.s.is_extern = 0;
p->decl.s.is_const = 0;
p->decl.s.is_volatile = 0;
}
break;
case TYPEDEF_:
p->decl.s.sclass = C_TYPEDEF;
break;
case REGISTER_:
p->decl.s.is_register = 1;
break;
case AUTO_:
p->decl.s.is_auto = 1;
break;
case EXTERN_:
p->decl.s.is_extern = 1;
break;
case STATIC_:
p->decl.s.is_static = 1;
break;
default:
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_BAD_STORAGE_CLASS), storage_class);
exit (1);
}
break;
}
}
/*
* pp_new_type_spec() - Return a new, initialized specifier structure.
* return : LINK *
*/
static LINK *
pp_new_type_spec (void)
{
LINK *p = pp_new_link ();
if (p == NULL)
{
return NULL;
}
p->class_ = SPECIFIER;
p->decl.s.noun = N_INT;
p->decl.s.sclass = C_AUTO;
return p;
}
/*
* pp_add_spec_to_decl() - Add the specifier to each of the declarators in
* decl_chain. This is accomplished by cloning p_spec and then tacking it
* onto the end of every declaration chain in decl_chain.
* return : void
* p_spec(in): A pointer to a specifier/declarator chain created by a previous
* typedef, or to a single specifier. It is cloned and then tacked onto
* the end of every declaration chain in the list pointed to by decl_chain.
* decl_chain(out): A chain of declarators, each of which is to receive the
* p_spec specifier.
*/
void
pp_add_spec_to_decl (LINK * p_spec, SYMBOL * decl_chain)
{
LINK *clone_start, *clone_end;
for (; decl_chain; decl_chain = decl_chain->next)
{
clone_start = pp_clone_type (p_spec, &clone_end);
if (clone_start == NULL)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_MALFORMED_CHAIN));
exit (1);
}
if (IS_PSEUDO_TYPE (clone_start) && clone_start->decl.s.val.v_struct == NULL)
{
LINK *old_etype;
char tmp[32];
old_etype = decl_chain->etype;
if (old_etype == NULL || (IS_VAR_TYPE (clone_start) && IS_ARRAY (old_etype) == 0))
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_BAD_PSEUDO_DECL), pp_type_str (clone_start));
exit (1);
}
clone_start->decl.s.val.v_struct = pp_new_pseudo_def (clone_start->decl.s.noun, old_etype->decl.d.num_ele);
if (clone_start->decl.s.noun == N_VARCHAR)
{
sprintf (tmp, " = { %s, \"\" }", old_etype->decl.d.num_ele);
}
else
{
sprintf (tmp, " = { ((%s)+7)/8, \"\" }", old_etype->decl.d.num_ele);
}
decl_chain->args = pp_new_symbol (tmp, decl_chain->level);
pp_discard_link (old_etype);
if (decl_chain->type == old_etype)
{
decl_chain->type = NULL;
}
else
{
LINK *parent;
for (parent = decl_chain->type; parent->next != old_etype; parent = parent->next)
{
;
}
parent->next = NULL;
decl_chain->etype = parent;
}
}
if (decl_chain->type == NULL) /* No declarators */
{
decl_chain->type = clone_start;
}
else
{
decl_chain->etype->next = clone_start;
}
decl_chain->etype = clone_end;
/*
* If the declaration we're looking at is really a typedef,
* record the symbol itself within the specifier. This will
* make it easier to point back to the symbol from other
* declarations, which will make it easier to print out
* later declarations using the typedef name rather than its
* expansion.
*/
if (IS_TYPEDEF (clone_end))
{
pp_set_class_bit (0, clone_end);
decl_chain->type->tdef = decl_chain;
decl_chain->type->from_tdef = decl_chain;
}
}
}
/*
* pp_add_symbols_to_table() - Add declarations to the symbol table. Removes
* duplicate declarations, complaining if they are not harmless. All
* declarations that are retained are accessible through
* current->scope->sym_chain.
* sym(in): A chain of symbols to be added to the symbol table.
* return : void
*/
void
pp_add_symbols_to_table (SYMBOL * sym)
{
SYMBOL *exists, *pnew, *next = NULL;
for (pnew = sym; pnew; pnew = next)
{
next = pnew->next;
if (sym->name == NULL)
{
continue;
}
exists = (SYMBOL *) pp_findsym (pp_Symbol_table, pnew->name);
if (exists == NULL || exists->level != pnew->level)
{
pp_Symbol_table->add_symbol (pp_Symbol_table, pnew);
pnew->next = pp_current_name_scope->sym_chain;
pp_current_name_scope->sym_chain = pnew;
}
else
{
int harmless = 0;
if (pp_the_same_type (exists->type, pnew->type, 0))
{
if (exists->etype->decl.s.is_extern || pnew->etype->decl.s.is_extern)
{
harmless = 1;
if (pnew->etype->decl.s.is_extern == 0)
{
exists->etype->decl.s.sclass = pnew->etype->decl.s.sclass;
exists->etype->decl.s.is_static = pnew->etype->decl.s.is_static;
exists->etype->decl.s.is_extern = pnew->etype->decl.s.is_extern;
}
}
}
if (harmless == 0)
{
esql_yyredef ((char *) pnew->name);
}
pp_discard_symbol (pnew);
}
}
}
/*
* pp_remove_symbols_from_table() - Remove all of the symbols on the chain
* from the table.
* return : void
* sym_chain(in): A pointer to a linked chain of symbols to be removed from
* the table.
*/
void
pp_remove_symbols_from_table (SYMBOL * sym_chain)
{
SYMBOL *sym;
for (sym = sym_chain; sym; sym = sym->next)
{
pp_Symbol_table->remove_symbol (pp_Symbol_table, sym);
}
}
/*
* pp_remove_structdefs_from_table() - Remove all of the structs on the chain
* from the table.
* return : void
* struct_chain(in): A pointer to a linked chain of structdefs to be removed
* from the struct table.
*/
static void
pp_remove_structdefs_from_table (STRUCTDEF * struct_chain)
{
STRUCTDEF *sdef;
for (sdef = struct_chain; sdef; sdef = sdef->next)
{
pp_Struct_table->remove_symbol (pp_Struct_table, sdef);
}
}
/*
* pp_do_enum() - Enter the symbol as an enumerated constant with type int.
* We don't care about its actual value.
* return : void
* sym(in): A symbol being defined as an enumerated constant.
*/
void
pp_do_enum (SYMBOL * sym)
{
if (sym->type)
{
esql_yyredef ((char *) sym->name);
}
else
{
LINK *p = pp_new_type_spec ();
p->decl.s.sclass = C_CONSTANT;
p->decl.s.val.v_int = 0; /* We don't care about the value. */
sym->type = p;
pp_Symbol_table->add_symbol (pp_Symbol_table, sym);
}
}
/*
* pp_push_name_scope() - Push a new symbol table scope.
* return : void
*/
void
pp_push_name_scope (void)
{
SCOPE *new_scope;
new_scope = pp_current_name_scope ? (pp_current_name_scope + 1) : pp_name_scope_base;
if (new_scope >= pp_name_scope_limit)
{
int nframes = (int) (pp_name_scope_limit - pp_name_scope_base);
SCOPE *const realloc_pp_name_scope_base
= (SCOPE *) realloc (pp_name_scope_base, sizeof (SCOPE) * (nframes + NFRAMES));
if (realloc_pp_name_scope_base == NULL)
{
esql_yyverror (pp_get_msg (EX_MISC_SET, MSG_OUT_OF_MEMORY));
exit (1);
return;
}
else
{
pp_name_scope_base = realloc_pp_name_scope_base;
}
pp_name_scope_limit = pp_name_scope_base + nframes + NFRAMES;
if (pp_current_name_scope)
{
pp_current_name_scope = pp_name_scope_base + nframes - 1;
}
new_scope = pp_name_scope_base + nframes;
}
new_scope->recognizing_typedef_names = 1;
new_scope->sym_chain = NULL;
new_scope->struct_chain = NULL;
new_scope->cursor_chain = NULL;
pp_init_whenever_scope (&new_scope->whenever, pp_current_name_scope ? &pp_current_name_scope->whenever : NULL);
pp_current_name_scope = new_scope;
++pp_nesting_level;
pp_make_typedef_names_visible (1);
}
/*
* pp_pop_name_scope() - Pop the current symbol table scope.
* return : void
*/
void
pp_pop_name_scope (void)
{
SCOPE *current, *next;
#if !defined(NDEBUG)
if (pp_dump_scope_info)
{
fprintf (esql_yyout, "\n/*\n * Exiting scope level %d\n", pp_nesting_level);
pp_print_syms (esql_yyout);
pp_print_cursors (esql_yyout);
fputs (" */\n", esql_yyout);
}
#endif
current = pp_current_name_scope;
if (pp_current_name_scope == pp_name_scope_base)
{
next = NULL;
}
else
{
next = pp_current_name_scope - 1;
}
pp_remove_symbols_from_table (current->sym_chain);
pp_discard_symbol_chain (current->sym_chain);
pp_remove_structdefs_from_table (current->struct_chain);
pp_discard_structdef_chain (current->struct_chain);
pp_remove_cursors_from_table (current->cursor_chain);
pp_discard_cursor_chain (current->cursor_chain);
pp_finish_whenever_scope (¤t->whenever, next ? &next->whenever : NULL);
pp_current_name_scope = next;
--pp_nesting_level;
pp_make_typedef_names_visible (pp_current_name_scope == NULL || pp_current_name_scope->recognizing_typedef_names);
}
/*
* pp_make_typedef_names_visible() - Alter current scope so that typedef names
* are treated as such, rather than as ordinary identifiers, (if sense is 1)
* or vice versa (if sense is 0).
* return : void
* sense: 1 if names should be visible, 0 if not.
*/
void
pp_make_typedef_names_visible (int sense)
{
if (pp_current_name_scope)
{
pp_current_name_scope->recognizing_typedef_names = sense;
}
pp_recognizing_typedef_names = sense;
}
/*
* pp_decl_init() - Set up various initial conditions for the module.
* return : void
*/
void
pp_decl_init (void)
{
pp_nesting_level = -1; /* It will get bumped by push_name_scope(). */
pp_name_scope_base = (SCOPE *) pp_malloc (NFRAMES * sizeof (SCOPE));
memset (pp_name_scope_base, 0, NFRAMES * sizeof (SCOPE));
pp_name_scope_limit = pp_name_scope_base + NFRAMES;
pp_current_name_scope = NULL;
pp_push_name_scope ();
pp_spec_scope_base = (SPEC_STATE *) pp_malloc (NFRAMES * sizeof (SPEC_STATE));
memset (pp_spec_scope_base, 0, NFRAMES * sizeof (SPEC_STATE));
pp_spec_scope_limit = pp_spec_scope_base + NFRAMES;
pp_current_spec_scope = NULL;
pp_push_spec_scope ();
pp_make_typedef_names_visible (1);
}
/*
* pp_decl_finish() - Tear down various module structures.
* return : void
*/
void
pp_decl_finish (void)
{
while (pp_current_name_scope)
{
pp_pop_name_scope ();
}
while (pp_current_spec_scope)
{
pp_pop_spec_scope ();
}
free_and_init (pp_name_scope_base);
free_and_init (pp_spec_scope_base);
}
/*
* pp_push_spec_scope() - Start a new scope for type specifiers. This type of
* scoped behavior is necessary for processing struct definitions correctly.
* return : void
*/
void
pp_push_spec_scope (void)
{
SPEC_STATE *p;
p = pp_current_spec_scope ? (pp_current_spec_scope + 1) : pp_spec_scope_base;
if (p >= pp_spec_scope_limit)
{
int nframes = (int) (pp_spec_scope_limit - pp_spec_scope_base);
SPEC_STATE *const realloc_pp_spec_scope_base
= (SPEC_STATE *) realloc (pp_spec_scope_base, sizeof (SPEC_STATE) * (nframes + NFRAMES));
if (realloc_pp_spec_scope_base == NULL)
{
esql_yyverror (pp_get_msg (EX_MISC_SET, MSG_OUT_OF_MEMORY));
exit (1);
return;
}
else
{
pp_spec_scope_base = realloc_pp_spec_scope_base;
}
pp_spec_scope_limit = pp_spec_scope_base + nframes + NFRAMES;
if (pp_current_spec_scope)
{
pp_current_spec_scope = pp_spec_scope_base + nframes - 1;
}
p = pp_spec_scope_base + nframes;
}
p->noun_seen = false;
p->longs_seen = 0;
p->shorts_seen = 0;
p->signed_seen = false;
p->storage_class_seen = false;
p->typedef_seen = false;
p->sc_allowed = true;
p->volatile_seen = false;
p->const_seen = false;
p->spec = NULL;
pp_current_spec_scope = p;
}
/*
* pp_pop_spec_scope() - Return to a previous scope for type specifiers.
* return : void
*/
void
pp_pop_spec_scope (void)
{
assert (pp_current_spec_scope != NULL);
pp_current_spec_scope = (pp_current_spec_scope == pp_spec_scope_base ? NULL : (pp_current_spec_scope - 1));
}
/*
* pp_reset_current_type_spec() - Reset the working variables for
* the current type spec.
* return : void
*/
void
pp_reset_current_type_spec (void)
{
SPEC_STATE *p = pp_current_spec_scope;
p->noun_seen = false;
p->longs_seen = 0;
p->shorts_seen = 0;
p->signed_seen = false;
p->storage_class_seen = false;
p->typedef_seen = false;
p->sc_allowed = true;
p->volatile_seen = false;
p->const_seen = false;
p->spec = pp_new_type_spec ();
}
/*
* pp_current_type_spec() - Return the type specifier currently
* under construction.
* return : LINK *
*/
LINK *
pp_current_type_spec (void)
{
return pp_current_spec_scope->spec;
}
/*
* pp_add_storage_class() -
* return : void
* sc(in): The storage class to be added to the current type specifier.
*
* note : Side effects pp_current_spec_scope.
*/
void
pp_add_storage_class (int sc)
{
SPEC_STATE *p = pp_current_spec_scope;
if (!p->sc_allowed)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_SPECIFIER_NOT_ALLOWED));
return;
}
if (p->storage_class_seen)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_CLASS_COMBO));
return;
}
p->storage_class_seen = sc != TYPEDEF_;
p->typedef_seen = sc == TYPEDEF_;
pp_set_class_bit (sc, p->spec);
}
/*
* pp_add_struct_spec() -
* return : void
* sdef(in): The struct definition that serves as the type noun of the
* current type spec.
*
* note : Side effects pp_current_spec_scope.
*/
void
pp_add_struct_spec (STRUCTDEF * sdef)
{
SPEC_STATE *p = pp_current_spec_scope;
if (sdef == NULL)
{
/*
* There was already some sort of error during parsing, and we've
* wound up here in a sort of no-op mode. Just ignore it.
*/
return;
}
if (p->noun_seen)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_TYPE_COMBO));
pp_discard_structdef (sdef);
return;
}
if ((p->longs_seen > 0) || (p->shorts_seen > 0) || p->signed_seen)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
pp_discard_structdef (sdef);
return;
}
p->spec->decl.s.noun = N_STRUCTURE;
p->spec->decl.s.val.v_struct = sdef;
p->spec->decl.s.is_by_name = sdef->by_name;
p->noun_seen = true;
p->longs_seen = 1;
p->shorts_seen = 1;
p->signed_seen = true;
sdef->by_name = false;
}
/*
* pp_add_type_noun() - Add the appropriate type to the current type specifier.
* return : void
* type(in): The type specifier to be added.
*
* note : Side effects pp_current_spec_scope.
*/
void
pp_add_type_noun (int type)
{
SPEC_STATE *p = pp_current_spec_scope;
if (p->noun_seen)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_TYPE_COMBO));
return;
}
switch (type)
{
case VOID_:
{
if ((p->longs_seen > 0) || (p->shorts_seen > 0) || p->signed_seen)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
p->longs_seen = 1;
p->shorts_seen = 1;
p->signed_seen = true;
p->spec->decl.s.noun = N_VOID;
}
break;
case CHAR_:
{
if ((p->longs_seen > 0) || (p->shorts_seen > 0))
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_TYPE_COMBO));
return;
}
p->longs_seen = 1;
p->spec->decl.s.noun = N_CHR;
}
break;
case INT_:
{
p->spec->decl.s.noun = N_INT;
p->spec->decl.s.is_long = (p->longs_seen > 0);
p->spec->decl.s.is_short = (p->shorts_seen > 0);
}
break;
case FLOAT_:
{
p->spec->decl.s.noun = N_FLOAT;
p->spec->decl.s.is_long = (p->longs_seen > 0) && p->spec->decl.s.is_long;
}
break;
case DOUBLE_:
{
if ((p->longs_seen > 0) && !p->spec->decl.s.is_long)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
p->longs_seen = 1;
p->spec->decl.s.noun = N_FLOAT;
p->spec->decl.s.is_long = 1;
}
break;
case VARCHAR_:
case BIT_:
case VARBIT_:
{
if ((p->longs_seen > 0) || (p->shorts_seen) || (p->signed_seen))
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
p->spec->decl.s.noun = (type == VARCHAR_) ? N_VARCHAR : (type == BIT_) ? N_BIT : N_VARBIT;
p->spec->decl.s.val.v_struct = NULL;
}
break;
default:
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_TYPE_SPEC_UNEXPECTED_CASE), "pp_add_type_spec", type);
exit (1);
}
break;
}
p->spec->decl.s.is_volatile = p->volatile_seen;
p->spec->decl.s.is_const = p->const_seen;
p->noun_seen = true;
}
/*
* pp_add_type_adj() - Add the indicated modifier to the current type
* specifier, if appropriate.
* return : void
* adj(in): The type modifier to be applied.
*
* note : Side effects pp_current_spec_scope.
*/
void
pp_add_type_adj (int adj)
{
SPEC_STATE *p = pp_current_spec_scope;
switch (adj)
{
/* Used for ENUM */
case INT_:
if (p->noun_seen && (p->spec->decl.s.noun == N_INT))
{
p->spec->decl.s.is_long = 0;
p->spec->decl.s.is_short = 0;
}
else
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
case SHORT_:
{
if ((p->shorts_seen > 1) || (p->longs_seen > 0))
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
if (p->noun_seen)
{
switch (p->spec->decl.s.noun)
{
case N_INT:
case N_FLOAT:
break;
default:
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
}
++p->shorts_seen;
p->spec->decl.s.is_short = 1;
p->spec->decl.s.is_long = 0;
}
break;
case LONG_:
{
if ((p->longs_seen > MAX_LONGS_ALLOWED) || p->shorts_seen > 0)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
if (p->noun_seen)
{
switch (p->spec->decl.s.noun)
{
case N_INT:
case N_FLOAT:
break;
default:
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
}
++p->longs_seen;
p->spec->decl.s.is_long = 1;
p->spec->decl.s.is_short = 0;
}
break;
case SIGNED_:
case UNSIGNED_:
{
if (p->signed_seen)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
if (p->noun_seen)
{
switch (p->spec->decl.s.noun)
{
case N_INT:
case N_CHR:
break;
default:
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
}
p->signed_seen = true;
p->spec->decl.s.is_unsigned = adj == UNSIGNED_;
}
break;
case CONST_:
{
if (p->volatile_seen)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
p->const_seen = true;
}
break;
case VOLATILE_:
{
if (p->volatile_seen)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
p->volatile_seen = true;
}
break;
default:
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_TYPE_ADJ_UNEXPECTED_CASE), "pp_add_type_adj", adj);
exit (1);
}
break;
}
}
/*
* pp_add_typedefed_spec() - Set the type of the current definition
* (i.e., the specifier being built in pp_current_spec_scope) to a copy
* of the specifier/declarator chain associated with the given typedef.
* return : void
* spec(in): The type descriptor provided from a typedef definition.
*
* note : Side effects pp_current_spec_scope.
*/
void
pp_add_typedefed_spec (LINK * spec)
{
SPEC_STATE *p = pp_current_spec_scope;
LINK *q;
if (p->noun_seen)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_TYPE_COMBO));
return;
}
if ((p->longs_seen > 0) || (p->shorts_seen > 0) || p->signed_seen)
{
esql_yyverror (pp_get_msg (EX_DECL_SET, MSG_ILLEGAL_MODIFIER_COMBO));
return;
}
/*
* Reset any class info in the new spec; this is ok since this spec
* will be cloned onto every declarator that it modifies, and then
* reset before every future use. The clones will keep any specific
* changes that they need.
*/
for (q = spec; q->next; q = q->next)
{
;
}
if (p->spec->decl.s.sclass)
{
q->decl.s.sclass = p->spec->decl.s.sclass;
}
q->decl.s.is_static = p->spec->decl.s.is_static;
q->decl.s.is_extern = p->spec->decl.s.is_extern;
q->decl.s.is_const = p->spec->decl.s.is_const;
q->decl.s.is_volatile = p->spec->decl.s.is_volatile;
if (p->spec->tdef == NULL)
{
pp_discard_link_chain (p->spec);
}
p->spec = spec;
p->noun_seen = true;
p->longs_seen = 1;
p->shorts_seen = 1;
p->signed_seen = true;
}
/*
* pp_add_initializer() - Record the fact that this symbol has an initializer.
* At present, this is interesting only for array declarators. it lets us
* know if sizeof(array) is meaningful or not. It works a little bit by
* accident. at the point where it is called from the parser, sym doesn't
* yet have a specifier (so sym->type might be NULL), but in that case we
* don't care about recording the initializer anyway. If that ever changes
* the initializer stuff probably ought to be put in the SYMBOL structure
* itself.
* return : void
* sym(in): A pointer to a symbol.
*/
void
pp_add_initializer (SYMBOL * sym)
{
if (sym == NULL)
{
return;
}
if (sym->type && IS_ARRAY (sym->type))
{
sym->type->decl.d.num_ele = NULL;
}
}
/*
* pp_disallow_storage_classes() - Disallow storage class specifiers in
* specifier lists.
* return : void
*/
void
pp_disallow_storage_classes (void)
{
pp_current_spec_scope->sc_allowed = false;
}
/*
* pp_add_cursor_to_scope() - Add the cursor to the current name scope.
* The cursor will be deleted when the scope is exited.
* return : void
* cursor: A pointer to a cursor structure to be added to the current
* name scope.
*/
void
pp_add_cursor_to_scope (CURSOR * cursor)
{
cursor->next = pp_current_name_scope->cursor_chain;
pp_current_name_scope->cursor_chain = cursor;
}
/*
* pp_add_whenever_to_scope() - Establish the action to be taken when the
* specified condition is detected. This condition/action pair remains
* in effect until overridden by another assignment or until the current
* block is exited.
* return : void
* when(in): The condition to be monitored.
* action(in): The action to be taken when the condition is detected.
* name(in): An optional name to be used by the action.
*/
void
pp_add_whenever_to_scope (WHEN_CONDITION when, WHEN_ACTION action, char *name)
{
WHENEVER_ACTION *p = &pp_current_name_scope->whenever.cond[when];
p->action = action;
p->name = name ? strdup (name) : NULL;
esql_Translate_table.tr_whenever (when, action, p->name);
}
/*
* pp_print_link() -
* return:
* p(in) :
* buf(out) :
* context(in) :
* preechoed(in) :
*/
static void
pp_print_link (LINK * p, varstring * buf, int context, int preechoed)
{
if (p == NULL)
{
return;
}
if (p->from_tdef && p->tdef == NULL)
{
vs_prepend (buf, TOK_SPACE);
vs_prepend (buf, (char *) p->from_tdef->name);
/*
* Now find the terminal specifier in the link chain and extract
* any information about storage class specifiers.
*/
while (p->next)
{
p = p->next;
}
if (preechoed == 0)
{
if (p->decl.s.is_extern)
{
vs_prepend (buf, TOK_EXTERN TOK_SPACE);
}
if (p->decl.s.is_static)
{
vs_prepend (buf, TOK_STATIC TOK_SPACE);
}
if (p->decl.s.is_volatile)
{
vs_prepend (buf, TOK_VOLATILE TOK_SPACE);
}
if (p->decl.s.is_const)
{
vs_prepend (buf, TOK_CONST TOK_SPACE);
}
if (p->decl.s.is_register)
{
vs_prepend (buf, TOK_REGISTER TOK_SPACE);
}
if (p->decl.s.is_auto)
{
vs_prepend (buf, TOK_AUTO TOK_SPACE);
}
}
}
else if (IS_SPECIFIER (p))
{
switch (p->decl.s.noun)
{
case N_INT:
{
if (p->decl.s.is_unsigned)
{
vs_prepend (buf, TOK_UNSIGNED TOK_SPACE);
}
if (p->decl.s.is_long)
{
vs_prepend (buf, TOK_LONG TOK_SPACE);
}
if (p->decl.s.is_short)
{
vs_prepend (buf, TOK_SHORT TOK_SPACE);
}
vs_prepend (buf, TOK_INT TOK_SPACE);
}
break;
case N_CHR:
{
if (p->decl.s.is_unsigned)
{
vs_prepend (buf, TOK_UNSIGNED TOK_SPACE);
}
vs_prepend (buf, TOK_CHAR TOK_SPACE);
}
break;
case N_VOID:
vs_prepend (buf, TOK_VOID TOK_SPACE);
break;
case N_FLOAT:
vs_prepend (buf, p->decl.s.is_long ? TOK_DOUBLE TOK_SPACE : TOK_FLOAT TOK_SPACE);
break;
case N_VARCHAR:
case N_BIT:
case N_VARBIT:
case N_STRUCTURE:
{
if (p->decl.s.val.v_struct->fields && !p->decl.s.is_by_name)
{
varstring fields, tmp;
SYMBOL *field;
vs_new (&fields);
vs_new (&tmp);
vs_strcpy (&fields, TOK_LB TOK_SPACE);
for (field = p->decl.s.val.v_struct->fields; field; field = field->next)
{
pp_print_decl (field, &tmp, preechoed);
vs_strcat (&fields, vs_str (&tmp));
vs_strcat (&fields, TOK_SC TOK_SPACE);
}
vs_strcat (&fields, TOK_RB TOK_SPACE);
vs_prepend (buf, vs_str (&fields));
vs_free (&fields);
vs_free (&tmp);
}
/*
* Don't print the tags that we have invented for "anonymous"
* structs. Probably ought to encapsulate this better.
*/
if (p->decl.s.val.v_struct->tag && p->decl.s.val.v_struct->tag[0] != '$')
{
vs_prepend (buf, TOK_SPACE);
vs_prepend (buf, (char *) p->decl.s.val.v_struct->tag);
}
vs_prepend (buf, TOK_SPACE);
vs_prepend (buf, (char *) p->decl.s.val.v_struct->type_string);
}
break;
case N_LABEL:
default:
vs_prepend (buf, TOK_INVALID TOK_SPACE);
break;
}
if (preechoed == 0)
{
if (p->decl.s.is_extern)
{
vs_prepend (buf, TOK_EXTERN TOK_SPACE);
}
if (p->decl.s.is_static)
{
vs_prepend (buf, TOK_STATIC TOK_SPACE);
}
if (p->decl.s.is_volatile)
{
vs_prepend (buf, TOK_VOLATILE TOK_SPACE);
}
if (p->decl.s.is_const)
{
vs_prepend (buf, TOK_CONST TOK_SPACE);
}
if (p->decl.s.is_register)
{
vs_prepend (buf, TOK_REGISTER TOK_SPACE);
}
if (p->decl.s.is_auto)
{
vs_prepend (buf, TOK_AUTO TOK_SPACE);
}
}
}
else
{
switch (p->decl.d.dcl_type)
{
case D_POINTER:
{
vs_prepend (buf, TOK_STAR);
pp_print_link (p->next, buf, D_POINTER, preechoed);
}
break;
case D_ARRAY:
{
if (context == D_POINTER)
{
vs_prepend (buf, TOK_LP);
vs_append (buf, TOK_RP);
}
vs_sprintf (buf, "[%s]", p->decl.d.num_ele ? p->decl.d.num_ele : "");
pp_print_link (p->next, buf, D_ARRAY, preechoed);
}
break;
case D_FUNCTION:
{
SYMBOL *arg;
varstring tmp;
/*
* If this is a complex declaration like
*
* int (*f)(int);
*
* then we'll need parens around the inner declarators.
* If not (i.e., the next link is a specifier) we won't
* need anything.
*/
if (context == D_POINTER)
{
vs_prepend (buf, TOK_LP);
vs_append (buf, TOK_RP);
}
vs_append (buf, TOK_LP);
vs_new (&tmp);
for (arg = p->decl.d.args; arg; arg = arg->next)
{
vs_clear (&tmp);
pp_print_decl (arg, &tmp, preechoed);
vs_append (buf, vs_str (&tmp));
if (arg->next)
{
vs_append (buf, TOK_COMMA TOK_SPACE);
}
}
vs_free (&tmp);
vs_append (buf, TOK_RP);
pp_print_link (p->next, buf, D_FUNCTION, preechoed);
}
break;
default:
vs_prepend (buf, TOK_INVALID);
break;
}
}
}
/*
* pp_print_decl() -
* return:
* sym(in) :
* buf(out) :
* preechoed(in) :
*/
static void
pp_print_decl (SYMBOL * sym, varstring * buf, int preechoed)
{
vs_clear (buf);
vs_strcpy (buf, (char *) sym->name);
pp_print_link (sym->type, buf, D_ARRAY, preechoed);
if (preechoed == 0)
{
if (sym->type->tdef)
{
vs_prepend (buf, TOK_TYPEDEF TOK_SPACE);
}
}
}
/*
* pp_print_decls() - Print out C text for the declarations represented in
* decl_chain.
* return : void
* decl_chain(in): a list of symbols to be printed.
* preechoed(in): true if called from esql parser, false otherwise.
*
* note : Because we echo most declarations while parsing them, this
* implementation currently concerns itself ONLY with VARCHAR declarations.
* The esql parser sees and echoes storage class specifiers (auto,
* register, static, extern) and type qualifiers (const, volatile) before
* noting the VARCHAR token. therefore we don't want to reprint them and
* preechoed will always be true. If pp_print_decls is called from anywhere
* other than the esql parser (e.g. test programs), preechoed should be
* specified as false.
*/
void
pp_print_decls (SYMBOL * decl_chain, int preechoed)
{
varstring buf;
vs_new (&buf);
for (; decl_chain; decl_chain = decl_chain->next)
{
pp_print_decl (decl_chain, &buf, preechoed);
fputs (vs_str (&buf), esql_yyout);
if (IS_PSEUDO_TYPE (decl_chain->type) && !pp_disable_varchar_length)
{
fputs ((char *) decl_chain->args->name, esql_yyout);
}
fputs (TOK_SC TOK_SPACE, esql_yyout);
}
vs_free (&buf);
}
/*
* pp_print_specs() -
* return:
* link(in) :
*/
void
pp_print_specs (LINK * link)
{
varstring buf;
vs_new (&buf);
pp_print_link (link, &buf, D_ARRAY, true);
fputs (vs_str (&buf), esql_yyout);
vs_free (&buf);
}
|
a1e41853cad5fa52474c86b9985c6903fb4b44b6
|
26a21b96e849fbcee0e3e5071998d522581a6f91
|
/tests/variable_length_stack_buffer.c
|
c08f387a66767223cd8c138e6c62dc5a721fcc00
|
[
"Apache-2.0"
] |
permissive
|
ant4g0nist/lisa.py
|
6dae187c47960e7933b3677fe44498325f03733f
|
fb74a309a314d041d4902944a8d449650afc76db
|
refs/heads/dev
| 2022-01-01T21:55:20.235720
| 2021-12-15T06:16:06
| 2021-12-15T06:16:06
| 29,593,225
| 736
| 128
|
Apache-2.0
| 2021-12-15T06:17:07
| 2015-01-21T14:27:23
|
Python
|
UTF-8
|
C
| false
| false
| 273
|
c
|
variable_length_stack_buffer.c
|
#define SIZE (1 << 30)
int main() {
char buf[SIZE];
//even a read from this buffer should be considered exploitable
//because the stack pointer is pointing outside of the stack boundaries,
//some evil stuff is possible.
char c = buf[0];
}
|
221d886057a1a4076069fe7876f5123e944258de
|
d61b532db0d3e08818338cfaac530a1ced1ffe3b
|
/util/ceg/ce_back/as_back/init_back.c
|
28687dbb20e0eea630819c77c09124d792619a41
|
[
"LicenseRef-scancode-other-permissive"
] |
permissive
|
davidgiven/ack
|
61049c7a8e95ff61a77b1edd3c22bb290720e276
|
db5a32c68c4a60ca26a3927a799ea662b5b2b0e5
|
refs/heads/default
| 2023-08-29T07:33:12.771205
| 2023-07-08T20:17:27
| 2023-07-08T20:17:27
| 37,686,316
| 376
| 74
|
NOASSERTION
| 2023-07-08T20:17:28
| 2015-06-18T21:33:42
|
C
|
UTF-8
|
C
| false
| false
| 37
|
c
|
init_back.c
|
#include "header.h"
init_back()
{
}
|
1818ce0d8c835f75a7c402ed5a304c2cf4aca754
|
badb70a0b235c98ac034cfe5b4bfafda36647831
|
/Legacy/BootPlatform/BlockIoDxe/BiosBlkIo.h
|
b8bb04ea669b376ca97a9d303ceea722afeba8d2
|
[
"BSD-3-Clause"
] |
permissive
|
acidanthera/OpenCorePkg
|
f34a7d67b22c74fb5ab559e48519e5f5855b6751
|
1d5b1736fe5a5ef7662b5c076c6d11aac96fd5d6
|
refs/heads/master
| 2023-08-30T21:03:02.993659
| 2023-08-28T23:30:43
| 2023-08-28T23:30:43
| 179,354,282
| 13,212
| 2,999
|
BSD-3-Clause
| 2023-09-10T18:29:53
| 2019-04-03T19:14:29
|
C
|
UTF-8
|
C
| false
| false
| 15,637
|
h
|
BiosBlkIo.h
|
/** @file
Copyright (c) 1999 - 2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#ifndef _BIOS_BLOCK_IO_H_
#define _BIOS_BLOCK_IO_H_
#include <Uefi.h>
#include <Protocol/BlockIo.h>
#include <Protocol/PciIo.h>
#include <Protocol/Legacy8259.h>
#include <Protocol/LegacyBios.h>
#include <Protocol/DevicePath.h>
#include <Guid/LegacyBios.h>
#include <Guid/BlockIoVendor.h>
#include <Library/UefiDriverEntryPoint.h>
#include <Library/DebugLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/DevicePathLib.h>
#include <Library/MemoryAllocationLib.h>
#include <IndustryStandard/Pci.h>
#include "Edd.h"
#define LEGACY_REGION_BASE 0x0C0000
//
// Global Variables
//
extern EFI_COMPONENT_NAME_PROTOCOL gBiosBlockIoComponentName;
extern EFI_COMPONENT_NAME2_PROTOCOL gBiosBlockIoComponentName2;
//
// Define the I2O class code
//
#define PCI_BASE_CLASS_INTELLIGENT 0x0e
#define PCI_SUB_CLASS_INTELLIGENT 0x00
//
// Number of pages needed for our buffer under 1MB
//
#define BLOCK_IO_BUFFER_PAGE_SIZE (((sizeof (EDD_DEVICE_ADDRESS_PACKET) + sizeof (BIOS_LEGACY_DRIVE) + MAX_EDD11_XFER) / EFI_PAGE_SIZE) + 1\
)
//
// Driver Binding Protocol functions
//
/**
Check whether the driver supports this device.
@param This The Udriver binding protocol.
@param Controller The controller handle to check.
@param RemainingDevicePath The remaining device path.
@retval EFI_SUCCESS The driver supports this controller.
@retval other This device isn't supported.
**/
EFI_STATUS
EFIAPI
BiosBlockIoDriverBindingSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
);
/**
Starts the device with this driver.
@param This The driver binding instance.
@param Controller Handle of device to bind driver to.
@param RemainingDevicePath Optional parameter use to pick a specific child
device to start.
@retval EFI_SUCCESS The controller is controlled by the driver.
@retval Other This controller cannot be started.
**/
EFI_STATUS
EFIAPI
BiosBlockIoDriverBindingStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath
);
/**
Stop the device handled by this driver.
@param This The driver binding protocol.
@param Controller The controller to release.
@param NumberOfChildren The number of handles in ChildHandleBuffer.
@param ChildHandleBuffer The array of child handle.
@retval EFI_SUCCESS The device was stopped.
@retval EFI_DEVICE_ERROR The device could not be stopped due to a device error.
@retval Others Fail to uninstall protocols attached on the device.
**/
EFI_STATUS
EFIAPI
BiosBlockIoDriverBindingStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE Controller,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer
);
//
// Other internal functions
//
/**
Build device path for EDD 3.0.
@param BaseDevicePath Base device path.
@param Drive Legacy drive.
@param DevicePath Device path for output.
@retval EFI_SUCCESS The device path is built successfully.
@retval EFI_UNSUPPORTED It is failed to built device path.
**/
EFI_STATUS
BuildEdd30DevicePath (
IN EFI_DEVICE_PATH_PROTOCOL *BaseDevicePath,
IN BIOS_LEGACY_DRIVE *Drive,
IN EFI_DEVICE_PATH_PROTOCOL **DevicePath
);
/**
Initialize block I/O device instance
@param Dev Instance of block I/O device instance
@retval TRUE Initialization succeeds.
@retval FALSE Initialization fails.
**/
BOOLEAN
BiosInitBlockIo (
IN BIOS_BLOCK_IO_DEV *Dev
);
/**
Read BufferSize bytes from Lba into Buffer.
@param This Indicates a pointer to the calling context.
@param MediaId Id of the media, changes every time the media is replaced.
@param Lba The starting Logical Block Address to read from
@param BufferSize Size of Buffer, must be a multiple of device block size.
@param Buffer A pointer to the destination buffer for the data. The caller is
responsible for either having implicit or explicit ownership of the buffer.
@retval EFI_SUCCESS The data was read correctly from the device.
@retval EFI_DEVICE_ERROR The device reported an error while performing the read.
@retval EFI_NO_MEDIA There is no media in the device.
@retval EFI_MEDIA_CHANGED The MediaId does not matched the current device.
@retval EFI_BAD_BUFFER_SIZE The Buffer was not a multiple of the block size of the device.
@retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
or the buffer is not on proper alignment.
**/
EFI_STATUS
EFIAPI
Edd30BiosReadBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
);
/**
Write BufferSize bytes from Lba into Buffer.
@param This Indicates a pointer to the calling context.
@param MediaId The media ID that the write request is for.
@param Lba The starting logical block address to be written. The caller is
responsible for writing to only legitimate locations.
@param BufferSize Size of Buffer, must be a multiple of device block size.
@param Buffer A pointer to the source buffer for the data.
@retval EFI_SUCCESS The data was written correctly to the device.
@retval EFI_WRITE_PROTECTED The device can not be written to.
@retval EFI_DEVICE_ERROR The device reported an error while performing the write.
@retval EFI_NO_MEDIA There is no media in the device.
@retval EFI_MEDIA_CHNAGED The MediaId does not matched the current device.
@retval EFI_BAD_BUFFER_SIZE The Buffer was not a multiple of the block size of the device.
@retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
or the buffer is not on proper alignment.
**/
EFI_STATUS
EFIAPI
Edd30BiosWriteBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
);
/**
Flush the Block Device.
@param This Indicates a pointer to the calling context.
@retval EFI_SUCCESS All outstanding data was written to the device
@retval EFI_DEVICE_ERROR The device reported an error while writting back the data
@retval EFI_NO_MEDIA There is no media in the device.
**/
EFI_STATUS
EFIAPI
BiosBlockIoFlushBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This
);
/**
Reset the Block Device.
@param This Indicates a pointer to the calling context.
@param ExtendedVerification Driver may perform diagnostics on reset.
@retval EFI_SUCCESS The device was reset.
@retval EFI_DEVICE_ERROR The device is not functioning properly and could
not be reset.
**/
EFI_STATUS
EFIAPI
BiosBlockIoReset (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN BOOLEAN ExtendedVerification
);
/**
Read BufferSize bytes from Lba into Buffer.
@param This Indicates a pointer to the calling context.
@param MediaId Id of the media, changes every time the media is replaced.
@param Lba The starting Logical Block Address to read from
@param BufferSize Size of Buffer, must be a multiple of device block size.
@param Buffer A pointer to the destination buffer for the data. The caller is
responsible for either having implicit or explicit ownership of the buffer.
@retval EFI_SUCCESS The data was read correctly from the device.
@retval EFI_DEVICE_ERROR The device reported an error while performing the read.
@retval EFI_NO_MEDIA There is no media in the device.
@retval EFI_MEDIA_CHANGED The MediaId does not matched the current device.
@retval EFI_BAD_BUFFER_SIZE The Buffer was not a multiple of the block size of the device.
@retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
or the buffer is not on proper alignment.
**/
EFI_STATUS
EFIAPI
Edd11BiosReadBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
);
/**
Write BufferSize bytes from Lba into Buffer.
@param This Indicates a pointer to the calling context.
@param MediaId The media ID that the write request is for.
@param Lba The starting logical block address to be written. The caller is
responsible for writing to only legitimate locations.
@param BufferSize Size of Buffer, must be a multiple of device block size.
@param Buffer A pointer to the source buffer for the data.
@retval EFI_SUCCESS The data was written correctly to the device.
@retval EFI_WRITE_PROTECTED The device can not be written to.
@retval EFI_DEVICE_ERROR The device reported an error while performing the write.
@retval EFI_NO_MEDIA There is no media in the device.
@retval EFI_MEDIA_CHNAGED The MediaId does not matched the current device.
@retval EFI_BAD_BUFFER_SIZE The Buffer was not a multiple of the block size of the device.
@retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
or the buffer is not on proper alignment.
**/
EFI_STATUS
EFIAPI
Edd11BiosWriteBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
);
/**
Read BufferSize bytes from Lba into Buffer.
@param This Indicates a pointer to the calling context.
@param MediaId Id of the media, changes every time the media is replaced.
@param Lba The starting Logical Block Address to read from
@param BufferSize Size of Buffer, must be a multiple of device block size.
@param Buffer A pointer to the destination buffer for the data. The caller is
responsible for either having implicit or explicit ownership of the buffer.
@retval EFI_SUCCESS The data was read correctly from the device.
@retval EFI_DEVICE_ERROR The device reported an error while performing the read.
@retval EFI_NO_MEDIA There is no media in the device.
@retval EFI_MEDIA_CHANGED The MediaId does not matched the current device.
@retval EFI_BAD_BUFFER_SIZE The Buffer was not a multiple of the block size of the device.
@retval EFI_INVALID_PARAMETER The read request contains LBAs that are not valid,
or the buffer is not on proper alignment.
**/
EFI_STATUS
EFIAPI
BiosReadLegacyDrive (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
);
/**
Write BufferSize bytes from Lba into Buffer.
@param This Indicates a pointer to the calling context.
@param MediaId The media ID that the write request is for.
@param Lba The starting logical block address to be written. The caller is
responsible for writing to only legitimate locations.
@param BufferSize Size of Buffer, must be a multiple of device block size.
@param Buffer A pointer to the source buffer for the data.
@retval EFI_SUCCESS The data was written correctly to the device.
@retval EFI_WRITE_PROTECTED The device can not be written to.
@retval EFI_DEVICE_ERROR The device reported an error while performing the write.
@retval EFI_NO_MEDIA There is no media in the device.
@retval EFI_MEDIA_CHNAGED The MediaId does not matched the current device.
@retval EFI_BAD_BUFFER_SIZE The Buffer was not a multiple of the block size of the device.
@retval EFI_INVALID_PARAMETER The write request contains LBAs that are not valid,
or the buffer is not on proper alignment.
**/
EFI_STATUS
EFIAPI
BiosWriteLegacyDrive (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
);
/**
Gets parameters of block I/O device.
@param BiosBlockIoDev Instance of block I/O device.
@param Drive Legacy drive.
@return Result of device parameter retrieval.
**/
UINTN
Int13GetDeviceParameters (
IN BIOS_BLOCK_IO_DEV *BiosBlockIoDev,
IN BIOS_LEGACY_DRIVE *Drive
);
/**
Extension of INT13 call.
@param BiosBlockIoDev Instance of block I/O device.
@param Drive Legacy drive.
@return Result of this extension.
**/
UINTN
Int13Extensions (
IN BIOS_BLOCK_IO_DEV *BiosBlockIoDev,
IN BIOS_LEGACY_DRIVE *Drive
);
/**
Gets parameters of legacy drive.
@param BiosBlockIoDev Instance of block I/O device.
@param Drive Legacy drive.
@return Result of drive parameter retrieval.
**/
UINTN
GetDriveParameters (
IN BIOS_BLOCK_IO_DEV *BiosBlockIoDev,
IN BIOS_LEGACY_DRIVE *Drive
);
/**
Build device path for device.
@param BaseDevicePath Base device path.
@param Drive Legacy drive.
@param DevicePath Device path for output.
**/
VOID
SetBiosInitBlockIoDevicePath (
IN EFI_DEVICE_PATH_PROTOCOL *BaseDevicePath,
IN BIOS_LEGACY_DRIVE *Drive,
OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath
);
/**
Initialize legacy environment for BIOS INI caller.
@param ThunkContext the instance pointer of THUNK_CONTEXT
**/
VOID
InitializeBiosIntCaller (
THUNK_CONTEXT *ThunkContext
);
/**
Initialize interrupt redirection code and entries, because
IDT Vectors 0x68-0x6f must be redirected to IDT Vectors 0x08-0x0f.
Or the interrupt will lost when we do thunk.
NOTE: We do not reset 8259 vector base, because it will cause pending
interrupt lost.
@param Legacy8259 Instance pointer for EFI_LEGACY_8259_PROTOCOL.
**/
VOID
InitializeInterruptRedirection (
IN EFI_LEGACY_8259_PROTOCOL *Legacy8259
);
/**
Thunk to 16-bit real mode and execute a software interrupt with a vector
of BiosInt. Regs will contain the 16-bit register context on entry and
exit.
@param This Protocol instance pointer.
@param BiosInt Processor interrupt vector to invoke
@param Reg Register contexted passed into (and returned) from thunk to 16-bit mode
@retval TRUE Thunk completed, and there were no BIOS errors in the target code.
See Regs for status.
@retval FALSE There was a BIOS erro in the target code.
**/
BOOLEAN
EFIAPI
LegacyBiosInt86 (
IN BIOS_BLOCK_IO_DEV *BiosDev,
IN UINT8 BiosInt,
IN IA32_REGISTER_SET *Regs
);
#endif
|
570b691d11c55f32baa63aaab57cbf550e6c5235
|
2d07a646d50c6cc1547b069ecd27c512623d8574
|
/src/core/zip.c
|
b49542125c58bfaa724cde2d2d557d16f23d6cd7
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
bjornbytes/lovr
|
da40e59eb9c42debbc6e22356d55194283740323
|
072452a4dafb466e8af9a4bc546b60ae077f8566
|
refs/heads/master
| 2023-08-16T13:42:30.581144
| 2023-07-29T10:37:18
| 2023-07-29T10:37:18
| 62,519,414
| 1,699
| 164
|
MIT
| 2023-09-13T22:21:32
| 2016-07-03T23:36:45
|
C
|
UTF-8
|
C
| false
| false
| 2,705
|
c
|
zip.c
|
#include "zip.h"
#include <string.h>
static uint16_t readu16(const uint8_t* p) { uint16_t x; memcpy(&x, p, sizeof(x)); return x; }
static uint32_t readu32(const uint8_t* p) { uint32_t x; memcpy(&x, p, sizeof(x)); return x; }
bool zip_open(zip_state* zip) {
const uint8_t* p = zip->data + zip->size - 22;
if (zip->size < 22 || readu32(p) != 0x06054b50) {
return false;
}
zip->count = readu16(p + 10);
zip->cursor = readu32(p + 16);
zip->base = 0;
if (zip->cursor + 4 > zip->size) {
return false;
}
// See if the central directory starts where the endOfCentralDirectory said it would.
// If it doesn't, then it might be a self-extracting archive with broken offsets (common).
// In this case, assume the central directory is directly adjacent to the endOfCentralDirectory,
// located at (offsetOfEndOfCentralDirectory (aka size - 22) - sizeOfCentralDirectory).
// If we find a central directory there, then compute a "base" offset that equals the difference
// between where it is and where it was supposed to be, and apply this offset to everything else.
if (readu32(zip->data + zip->cursor) != 0x02014b50) {
size_t offsetOfEndOfCentralDirectory = zip->size - 22;
size_t sizeOfCentralDirectory = readu32(p + 12);
size_t centralDirectoryOffset = offsetOfEndOfCentralDirectory - sizeOfCentralDirectory;
if (sizeOfCentralDirectory > offsetOfEndOfCentralDirectory || centralDirectoryOffset + 4 > zip->size) {
return false;
}
if (readu32(zip->data + centralDirectoryOffset) != 0x02014b50) {
return false;
}
zip->base = centralDirectoryOffset - zip->cursor;
zip->cursor = centralDirectoryOffset;
}
return true;
}
bool zip_next(zip_state* zip, zip_file* file) {
const uint8_t* p = zip->data + zip->cursor;
if (zip->cursor + 46 > zip->size || readu32(p) != 0x02014b50) {
return false;
}
file->mtime = readu16(p + 12);
file->mdate = readu16(p + 14);
file->csize = readu32(p + 20);
file->size = readu32(p + 24);
file->length = readu16(p + 28);
file->offset = readu32(p + 42) + zip->base;
file->name = (const char*) (p + 46);
zip->cursor += 46 + file->length + readu16(p + 30) + readu16(p + 32);
return zip->cursor < zip->size;
}
void* zip_load(zip_state* zip, size_t offset, bool* compressed) {
if (zip->size < 30 || offset > zip->size - 30) {
return NULL;
}
uint8_t* p = zip->data + offset;
if (readu32(p) != 0x04034b50) {
return NULL;
}
uint16_t compression = readu16(p + 8);
if (compression != 0 && compression != 8) {
return false;
}
*compressed = (compression == 8);
uint32_t skip = readu16(p + 26) + readu16(p + 28);
return p + 30 + skip;
}
|
1c565cd8fd06072dcc00bf2ded52fb969bd6dbce
|
f7dc806f341ef5dbb0e11252a4693003a66853d5
|
/thirdparty/mbedtls/include/mbedtls/oid.h
|
a64eaebef2f2879c9c29dd86eab2373aa7c9c2a5
|
[
"LicenseRef-scancode-free-unknown",
"MIT",
"CC-BY-4.0",
"OFL-1.1",
"Bison-exception-2.2",
"CC0-1.0",
"LicenseRef-scancode-nvidia-2002",
"LicenseRef-scancode-other-permissive",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unicode",
"BSD-2-Clause",
"FTL",
"GPL-3.0-or-later",
"Bitstream-Vera",
"Zlib",
"MPL-2.0",
"MIT-Modern-Variant",
"JSON",
"Libpng"
] |
permissive
|
godotengine/godot
|
8a2419750f4851d1426a8f3bcb52cac5c86f23c2
|
970be7afdc111ccc7459d7ef3560de70e6d08c80
|
refs/heads/master
| 2023-08-21T14:37:00.262883
| 2023-08-21T06:26:15
| 2023-08-21T06:26:15
| 15,634,981
| 68,852
| 18,388
|
MIT
| 2023-09-14T21:42:16
| 2014-01-04T16:05:36
|
C++
|
UTF-8
|
C
| false
| false
| 34,757
|
h
|
oid.h
|
/**
* \file oid.h
*
* \brief Object Identifier (OID) database
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#ifndef MBEDTLS_OID_H
#define MBEDTLS_OID_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "mbedtls/asn1.h"
#include "mbedtls/pk.h"
#include <stddef.h>
#if defined(MBEDTLS_CIPHER_C)
#include "mbedtls/cipher.h"
#endif
#if defined(MBEDTLS_MD_C)
#include "mbedtls/md.h"
#endif
/** OID is not found. */
#define MBEDTLS_ERR_OID_NOT_FOUND -0x002E
/** output buffer is too small */
#define MBEDTLS_ERR_OID_BUF_TOO_SMALL -0x000B
/* This is for the benefit of X.509, but defined here in order to avoid
* having a "backwards" include of x.509.h here */
/*
* X.509 extension types (internal, arbitrary values for bitsets)
*/
#define MBEDTLS_OID_X509_EXT_AUTHORITY_KEY_IDENTIFIER (1 << 0)
#define MBEDTLS_OID_X509_EXT_SUBJECT_KEY_IDENTIFIER (1 << 1)
#define MBEDTLS_OID_X509_EXT_KEY_USAGE (1 << 2)
#define MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES (1 << 3)
#define MBEDTLS_OID_X509_EXT_POLICY_MAPPINGS (1 << 4)
#define MBEDTLS_OID_X509_EXT_SUBJECT_ALT_NAME (1 << 5)
#define MBEDTLS_OID_X509_EXT_ISSUER_ALT_NAME (1 << 6)
#define MBEDTLS_OID_X509_EXT_SUBJECT_DIRECTORY_ATTRS (1 << 7)
#define MBEDTLS_OID_X509_EXT_BASIC_CONSTRAINTS (1 << 8)
#define MBEDTLS_OID_X509_EXT_NAME_CONSTRAINTS (1 << 9)
#define MBEDTLS_OID_X509_EXT_POLICY_CONSTRAINTS (1 << 10)
#define MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE (1 << 11)
#define MBEDTLS_OID_X509_EXT_CRL_DISTRIBUTION_POINTS (1 << 12)
#define MBEDTLS_OID_X509_EXT_INIHIBIT_ANYPOLICY (1 << 13)
#define MBEDTLS_OID_X509_EXT_FRESHEST_CRL (1 << 14)
#define MBEDTLS_OID_X509_EXT_NS_CERT_TYPE (1 << 16)
/*
* Top level OID tuples
*/
#define MBEDTLS_OID_ISO_MEMBER_BODIES "\x2a" /* {iso(1) member-body(2)} */
#define MBEDTLS_OID_ISO_IDENTIFIED_ORG "\x2b" /* {iso(1) identified-organization(3)} */
#define MBEDTLS_OID_ISO_CCITT_DS "\x55" /* {joint-iso-ccitt(2) ds(5)} */
#define MBEDTLS_OID_ISO_ITU_COUNTRY "\x60" /* {joint-iso-itu-t(2) country(16)} */
/*
* ISO Member bodies OID parts
*/
#define MBEDTLS_OID_COUNTRY_US "\x86\x48" /* {us(840)} */
#define MBEDTLS_OID_ORG_RSA_DATA_SECURITY "\x86\xf7\x0d" /* {rsadsi(113549)} */
#define MBEDTLS_OID_RSA_COMPANY MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \
MBEDTLS_OID_ORG_RSA_DATA_SECURITY /* {iso(1) member-body(2) us(840) rsadsi(113549)} */
#define MBEDTLS_OID_ORG_ANSI_X9_62 "\xce\x3d" /* ansi-X9-62(10045) */
#define MBEDTLS_OID_ANSI_X9_62 MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \
MBEDTLS_OID_ORG_ANSI_X9_62
/*
* ISO Identified organization OID parts
*/
#define MBEDTLS_OID_ORG_DOD "\x06" /* {dod(6)} */
#define MBEDTLS_OID_ORG_OIW "\x0e"
#define MBEDTLS_OID_OIW_SECSIG MBEDTLS_OID_ORG_OIW "\x03"
#define MBEDTLS_OID_OIW_SECSIG_ALG MBEDTLS_OID_OIW_SECSIG "\x02"
#define MBEDTLS_OID_OIW_SECSIG_SHA1 MBEDTLS_OID_OIW_SECSIG_ALG "\x1a"
#define MBEDTLS_OID_ORG_CERTICOM "\x81\x04" /* certicom(132) */
#define MBEDTLS_OID_CERTICOM MBEDTLS_OID_ISO_IDENTIFIED_ORG \
MBEDTLS_OID_ORG_CERTICOM
#define MBEDTLS_OID_ORG_TELETRUST "\x24" /* teletrust(36) */
#define MBEDTLS_OID_TELETRUST MBEDTLS_OID_ISO_IDENTIFIED_ORG \
MBEDTLS_OID_ORG_TELETRUST
/*
* ISO ITU OID parts
*/
#define MBEDTLS_OID_ORGANIZATION "\x01" /* {organization(1)} */
#define MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ISO_ITU_COUNTRY MBEDTLS_OID_COUNTRY_US \
MBEDTLS_OID_ORGANIZATION /* {joint-iso-itu-t(2) country(16) us(840) organization(1)} */
#define MBEDTLS_OID_ORG_GOV "\x65" /* {gov(101)} */
#define MBEDTLS_OID_GOV MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_GOV /* {joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101)} */
#define MBEDTLS_OID_ORG_NETSCAPE "\x86\xF8\x42" /* {netscape(113730)} */
#define MBEDTLS_OID_NETSCAPE MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_NETSCAPE /* Netscape OID {joint-iso-itu-t(2) country(16) us(840) organization(1) netscape(113730)} */
/* ISO arc for standard certificate and CRL extensions */
#define MBEDTLS_OID_ID_CE MBEDTLS_OID_ISO_CCITT_DS "\x1D" /**< id-ce OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 29} */
#define MBEDTLS_OID_NIST_ALG MBEDTLS_OID_GOV "\x03\x04" /** { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) */
/**
* Private Internet Extensions
* { iso(1) identified-organization(3) dod(6) internet(1)
* security(5) mechanisms(5) pkix(7) }
*/
#define MBEDTLS_OID_INTERNET MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_DOD \
"\x01"
#define MBEDTLS_OID_PKIX MBEDTLS_OID_INTERNET "\x05\x05\x07"
/*
* Arc for standard naming attributes
*/
#define MBEDTLS_OID_AT MBEDTLS_OID_ISO_CCITT_DS "\x04" /**< id-at OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 4} */
#define MBEDTLS_OID_AT_CN MBEDTLS_OID_AT "\x03" /**< id-at-commonName AttributeType:= {id-at 3} */
#define MBEDTLS_OID_AT_SUR_NAME MBEDTLS_OID_AT "\x04" /**< id-at-surName AttributeType:= {id-at 4} */
#define MBEDTLS_OID_AT_SERIAL_NUMBER MBEDTLS_OID_AT "\x05" /**< id-at-serialNumber AttributeType:= {id-at 5} */
#define MBEDTLS_OID_AT_COUNTRY MBEDTLS_OID_AT "\x06" /**< id-at-countryName AttributeType:= {id-at 6} */
#define MBEDTLS_OID_AT_LOCALITY MBEDTLS_OID_AT "\x07" /**< id-at-locality AttributeType:= {id-at 7} */
#define MBEDTLS_OID_AT_STATE MBEDTLS_OID_AT "\x08" /**< id-at-state AttributeType:= {id-at 8} */
#define MBEDTLS_OID_AT_ORGANIZATION MBEDTLS_OID_AT "\x0A" /**< id-at-organizationName AttributeType:= {id-at 10} */
#define MBEDTLS_OID_AT_ORG_UNIT MBEDTLS_OID_AT "\x0B" /**< id-at-organizationalUnitName AttributeType:= {id-at 11} */
#define MBEDTLS_OID_AT_TITLE MBEDTLS_OID_AT "\x0C" /**< id-at-title AttributeType:= {id-at 12} */
#define MBEDTLS_OID_AT_POSTAL_ADDRESS MBEDTLS_OID_AT "\x10" /**< id-at-postalAddress AttributeType:= {id-at 16} */
#define MBEDTLS_OID_AT_POSTAL_CODE MBEDTLS_OID_AT "\x11" /**< id-at-postalCode AttributeType:= {id-at 17} */
#define MBEDTLS_OID_AT_GIVEN_NAME MBEDTLS_OID_AT "\x2A" /**< id-at-givenName AttributeType:= {id-at 42} */
#define MBEDTLS_OID_AT_INITIALS MBEDTLS_OID_AT "\x2B" /**< id-at-initials AttributeType:= {id-at 43} */
#define MBEDTLS_OID_AT_GENERATION_QUALIFIER MBEDTLS_OID_AT "\x2C" /**< id-at-generationQualifier AttributeType:= {id-at 44} */
#define MBEDTLS_OID_AT_UNIQUE_IDENTIFIER MBEDTLS_OID_AT "\x2D" /**< id-at-uniqueIdentifier AttributeType:= {id-at 45} */
#define MBEDTLS_OID_AT_DN_QUALIFIER MBEDTLS_OID_AT "\x2E" /**< id-at-dnQualifier AttributeType:= {id-at 46} */
#define MBEDTLS_OID_AT_PSEUDONYM MBEDTLS_OID_AT "\x41" /**< id-at-pseudonym AttributeType:= {id-at 65} */
#define MBEDTLS_OID_DOMAIN_COMPONENT "\x09\x92\x26\x89\x93\xF2\x2C\x64\x01\x19" /** id-domainComponent AttributeType:= {itu-t(0) data(9) pss(2342) ucl(19200300) pilot(100) pilotAttributeType(1) domainComponent(25)} */
/*
* OIDs for standard certificate extensions
*/
#define MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER MBEDTLS_OID_ID_CE "\x23" /**< id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 } */
#define MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER MBEDTLS_OID_ID_CE "\x0E" /**< id-ce-subjectKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 14 } */
#define MBEDTLS_OID_KEY_USAGE MBEDTLS_OID_ID_CE "\x0F" /**< id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } */
#define MBEDTLS_OID_CERTIFICATE_POLICIES MBEDTLS_OID_ID_CE "\x20" /**< id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 } */
#define MBEDTLS_OID_POLICY_MAPPINGS MBEDTLS_OID_ID_CE "\x21" /**< id-ce-policyMappings OBJECT IDENTIFIER ::= { id-ce 33 } */
#define MBEDTLS_OID_SUBJECT_ALT_NAME MBEDTLS_OID_ID_CE "\x11" /**< id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 } */
#define MBEDTLS_OID_ISSUER_ALT_NAME MBEDTLS_OID_ID_CE "\x12" /**< id-ce-issuerAltName OBJECT IDENTIFIER ::= { id-ce 18 } */
#define MBEDTLS_OID_SUBJECT_DIRECTORY_ATTRS MBEDTLS_OID_ID_CE "\x09" /**< id-ce-subjectDirectoryAttributes OBJECT IDENTIFIER ::= { id-ce 9 } */
#define MBEDTLS_OID_BASIC_CONSTRAINTS MBEDTLS_OID_ID_CE "\x13" /**< id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } */
#define MBEDTLS_OID_NAME_CONSTRAINTS MBEDTLS_OID_ID_CE "\x1E" /**< id-ce-nameConstraints OBJECT IDENTIFIER ::= { id-ce 30 } */
#define MBEDTLS_OID_POLICY_CONSTRAINTS MBEDTLS_OID_ID_CE "\x24" /**< id-ce-policyConstraints OBJECT IDENTIFIER ::= { id-ce 36 } */
#define MBEDTLS_OID_EXTENDED_KEY_USAGE MBEDTLS_OID_ID_CE "\x25" /**< id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } */
#define MBEDTLS_OID_CRL_DISTRIBUTION_POINTS MBEDTLS_OID_ID_CE "\x1F" /**< id-ce-cRLDistributionPoints OBJECT IDENTIFIER ::= { id-ce 31 } */
#define MBEDTLS_OID_INIHIBIT_ANYPOLICY MBEDTLS_OID_ID_CE "\x36" /**< id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-ce 54 } */
#define MBEDTLS_OID_FRESHEST_CRL MBEDTLS_OID_ID_CE "\x2E" /**< id-ce-freshestCRL OBJECT IDENTIFIER ::= { id-ce 46 } */
/*
* Certificate policies
*/
#define MBEDTLS_OID_ANY_POLICY MBEDTLS_OID_CERTIFICATE_POLICIES "\x00" /**< anyPolicy OBJECT IDENTIFIER ::= { id-ce-certificatePolicies 0 } */
/*
* Netscape certificate extensions
*/
#define MBEDTLS_OID_NS_CERT MBEDTLS_OID_NETSCAPE "\x01"
#define MBEDTLS_OID_NS_CERT_TYPE MBEDTLS_OID_NS_CERT "\x01"
#define MBEDTLS_OID_NS_BASE_URL MBEDTLS_OID_NS_CERT "\x02"
#define MBEDTLS_OID_NS_REVOCATION_URL MBEDTLS_OID_NS_CERT "\x03"
#define MBEDTLS_OID_NS_CA_REVOCATION_URL MBEDTLS_OID_NS_CERT "\x04"
#define MBEDTLS_OID_NS_RENEWAL_URL MBEDTLS_OID_NS_CERT "\x07"
#define MBEDTLS_OID_NS_CA_POLICY_URL MBEDTLS_OID_NS_CERT "\x08"
#define MBEDTLS_OID_NS_SSL_SERVER_NAME MBEDTLS_OID_NS_CERT "\x0C"
#define MBEDTLS_OID_NS_COMMENT MBEDTLS_OID_NS_CERT "\x0D"
#define MBEDTLS_OID_NS_DATA_TYPE MBEDTLS_OID_NETSCAPE "\x02"
#define MBEDTLS_OID_NS_CERT_SEQUENCE MBEDTLS_OID_NS_DATA_TYPE "\x05"
/*
* OIDs for CRL extensions
*/
#define MBEDTLS_OID_PRIVATE_KEY_USAGE_PERIOD MBEDTLS_OID_ID_CE "\x10"
#define MBEDTLS_OID_CRL_NUMBER MBEDTLS_OID_ID_CE "\x14" /**< id-ce-cRLNumber OBJECT IDENTIFIER ::= { id-ce 20 } */
/*
* X.509 v3 Extended key usage OIDs
*/
#define MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE MBEDTLS_OID_EXTENDED_KEY_USAGE "\x00" /**< anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } */
#define MBEDTLS_OID_KP MBEDTLS_OID_PKIX "\x03" /**< id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } */
#define MBEDTLS_OID_SERVER_AUTH MBEDTLS_OID_KP "\x01" /**< id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } */
#define MBEDTLS_OID_CLIENT_AUTH MBEDTLS_OID_KP "\x02" /**< id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } */
#define MBEDTLS_OID_CODE_SIGNING MBEDTLS_OID_KP "\x03" /**< id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } */
#define MBEDTLS_OID_EMAIL_PROTECTION MBEDTLS_OID_KP "\x04" /**< id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } */
#define MBEDTLS_OID_TIME_STAMPING MBEDTLS_OID_KP "\x08" /**< id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } */
#define MBEDTLS_OID_OCSP_SIGNING MBEDTLS_OID_KP "\x09" /**< id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } */
/**
* Wi-SUN Alliance Field Area Network
* { iso(1) identified-organization(3) dod(6) internet(1)
* private(4) enterprise(1) WiSUN(45605) FieldAreaNetwork(1) }
*/
#define MBEDTLS_OID_WISUN_FAN MBEDTLS_OID_INTERNET "\x04\x01\x82\xe4\x25\x01"
#define MBEDTLS_OID_ON MBEDTLS_OID_PKIX "\x08" /**< id-on OBJECT IDENTIFIER ::= { id-pkix 8 } */
#define MBEDTLS_OID_ON_HW_MODULE_NAME MBEDTLS_OID_ON "\x04" /**< id-on-hardwareModuleName OBJECT IDENTIFIER ::= { id-on 4 } */
/*
* PKCS definition OIDs
*/
#define MBEDTLS_OID_PKCS MBEDTLS_OID_RSA_COMPANY "\x01" /**< pkcs OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) 1 } */
#define MBEDTLS_OID_PKCS1 MBEDTLS_OID_PKCS "\x01" /**< pkcs-1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } */
#define MBEDTLS_OID_PKCS5 MBEDTLS_OID_PKCS "\x05" /**< pkcs-5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 } */
#define MBEDTLS_OID_PKCS9 MBEDTLS_OID_PKCS "\x09" /**< pkcs-9 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 } */
#define MBEDTLS_OID_PKCS12 MBEDTLS_OID_PKCS "\x0c" /**< pkcs-12 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 } */
/*
* PKCS#1 OIDs
*/
#define MBEDTLS_OID_PKCS1_RSA MBEDTLS_OID_PKCS1 "\x01" /**< rsaEncryption OBJECT IDENTIFIER ::= { pkcs-1 1 } */
#define MBEDTLS_OID_PKCS1_MD2 MBEDTLS_OID_PKCS1 "\x02" /**< md2WithRSAEncryption ::= { pkcs-1 2 } */
#define MBEDTLS_OID_PKCS1_MD4 MBEDTLS_OID_PKCS1 "\x03" /**< md4WithRSAEncryption ::= { pkcs-1 3 } */
#define MBEDTLS_OID_PKCS1_MD5 MBEDTLS_OID_PKCS1 "\x04" /**< md5WithRSAEncryption ::= { pkcs-1 4 } */
#define MBEDTLS_OID_PKCS1_SHA1 MBEDTLS_OID_PKCS1 "\x05" /**< sha1WithRSAEncryption ::= { pkcs-1 5 } */
#define MBEDTLS_OID_PKCS1_SHA224 MBEDTLS_OID_PKCS1 "\x0e" /**< sha224WithRSAEncryption ::= { pkcs-1 14 } */
#define MBEDTLS_OID_PKCS1_SHA256 MBEDTLS_OID_PKCS1 "\x0b" /**< sha256WithRSAEncryption ::= { pkcs-1 11 } */
#define MBEDTLS_OID_PKCS1_SHA384 MBEDTLS_OID_PKCS1 "\x0c" /**< sha384WithRSAEncryption ::= { pkcs-1 12 } */
#define MBEDTLS_OID_PKCS1_SHA512 MBEDTLS_OID_PKCS1 "\x0d" /**< sha512WithRSAEncryption ::= { pkcs-1 13 } */
#define MBEDTLS_OID_RSA_SHA_OBS "\x2B\x0E\x03\x02\x1D"
#define MBEDTLS_OID_PKCS9_EMAIL MBEDTLS_OID_PKCS9 "\x01" /**< emailAddress AttributeType ::= { pkcs-9 1 } */
/* RFC 4055 */
#define MBEDTLS_OID_RSASSA_PSS MBEDTLS_OID_PKCS1 "\x0a" /**< id-RSASSA-PSS ::= { pkcs-1 10 } */
#define MBEDTLS_OID_MGF1 MBEDTLS_OID_PKCS1 "\x08" /**< id-mgf1 ::= { pkcs-1 8 } */
/*
* Digest algorithms
*/
#define MBEDTLS_OID_DIGEST_ALG_MD2 MBEDTLS_OID_RSA_COMPANY "\x02\x02" /**< id-mbedtls_md2 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 2 } */
#define MBEDTLS_OID_DIGEST_ALG_MD4 MBEDTLS_OID_RSA_COMPANY "\x02\x04" /**< id-mbedtls_md4 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 4 } */
#define MBEDTLS_OID_DIGEST_ALG_MD5 MBEDTLS_OID_RSA_COMPANY "\x02\x05" /**< id-mbedtls_md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 5 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA1 MBEDTLS_OID_ISO_IDENTIFIED_ORG \
MBEDTLS_OID_OIW_SECSIG_SHA1 /**< id-mbedtls_sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_NIST_ALG "\x02\x04" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_NIST_ALG "\x02\x01" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_NIST_ALG "\x02\x02" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */
#define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_NIST_ALG "\x02\x03" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */
#define MBEDTLS_OID_DIGEST_ALG_RIPEMD160 MBEDTLS_OID_TELETRUST "\x03\x02\x01" /**< id-ripemd160 OBJECT IDENTIFIER :: { iso(1) identified-organization(3) teletrust(36) algorithm(3) hashAlgorithm(2) ripemd160(1) } */
#define MBEDTLS_OID_HMAC_SHA1 MBEDTLS_OID_RSA_COMPANY "\x02\x07" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */
#define MBEDTLS_OID_HMAC_SHA224 MBEDTLS_OID_RSA_COMPANY "\x02\x08" /**< id-hmacWithSHA224 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 8 } */
#define MBEDTLS_OID_HMAC_SHA256 MBEDTLS_OID_RSA_COMPANY "\x02\x09" /**< id-hmacWithSHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 9 } */
#define MBEDTLS_OID_HMAC_SHA384 MBEDTLS_OID_RSA_COMPANY "\x02\x0A" /**< id-hmacWithSHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 10 } */
#define MBEDTLS_OID_HMAC_SHA512 MBEDTLS_OID_RSA_COMPANY "\x02\x0B" /**< id-hmacWithSHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 11 } */
/*
* Encryption algorithms
*/
#define MBEDTLS_OID_DES_CBC MBEDTLS_OID_ISO_IDENTIFIED_ORG \
MBEDTLS_OID_OIW_SECSIG_ALG "\x07" /**< desCBC OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 7 } */
#define MBEDTLS_OID_DES_EDE3_CBC MBEDTLS_OID_RSA_COMPANY "\x03\x07" /**< des-ede3-cbc OBJECT IDENTIFIER ::= { iso(1) member-body(2) -- us(840) rsadsi(113549) encryptionAlgorithm(3) 7 } */
#define MBEDTLS_OID_AES MBEDTLS_OID_NIST_ALG "\x01" /** aes OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) 1 } */
/*
* Key Wrapping algorithms
*/
/*
* RFC 5649
*/
#define MBEDTLS_OID_AES128_KW MBEDTLS_OID_AES "\x05" /** id-aes128-wrap OBJECT IDENTIFIER ::= { aes 5 } */
#define MBEDTLS_OID_AES128_KWP MBEDTLS_OID_AES "\x08" /** id-aes128-wrap-pad OBJECT IDENTIFIER ::= { aes 8 } */
#define MBEDTLS_OID_AES192_KW MBEDTLS_OID_AES "\x19" /** id-aes192-wrap OBJECT IDENTIFIER ::= { aes 25 } */
#define MBEDTLS_OID_AES192_KWP MBEDTLS_OID_AES "\x1c" /** id-aes192-wrap-pad OBJECT IDENTIFIER ::= { aes 28 } */
#define MBEDTLS_OID_AES256_KW MBEDTLS_OID_AES "\x2d" /** id-aes256-wrap OBJECT IDENTIFIER ::= { aes 45 } */
#define MBEDTLS_OID_AES256_KWP MBEDTLS_OID_AES "\x30" /** id-aes256-wrap-pad OBJECT IDENTIFIER ::= { aes 48 } */
/*
* PKCS#5 OIDs
*/
#define MBEDTLS_OID_PKCS5_PBKDF2 MBEDTLS_OID_PKCS5 "\x0c" /**< id-PBKDF2 OBJECT IDENTIFIER ::= {pkcs-5 12} */
#define MBEDTLS_OID_PKCS5_PBES2 MBEDTLS_OID_PKCS5 "\x0d" /**< id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} */
#define MBEDTLS_OID_PKCS5_PBMAC1 MBEDTLS_OID_PKCS5 "\x0e" /**< id-PBMAC1 OBJECT IDENTIFIER ::= {pkcs-5 14} */
/*
* PKCS#5 PBES1 algorithms
*/
#define MBEDTLS_OID_PKCS5_PBE_MD2_DES_CBC MBEDTLS_OID_PKCS5 "\x01" /**< pbeWithMD2AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 1} */
#define MBEDTLS_OID_PKCS5_PBE_MD2_RC2_CBC MBEDTLS_OID_PKCS5 "\x04" /**< pbeWithMD2AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 4} */
#define MBEDTLS_OID_PKCS5_PBE_MD5_DES_CBC MBEDTLS_OID_PKCS5 "\x03" /**< pbeWithMD5AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 3} */
#define MBEDTLS_OID_PKCS5_PBE_MD5_RC2_CBC MBEDTLS_OID_PKCS5 "\x06" /**< pbeWithMD5AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 6} */
#define MBEDTLS_OID_PKCS5_PBE_SHA1_DES_CBC MBEDTLS_OID_PKCS5 "\x0a" /**< pbeWithSHA1AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 10} */
#define MBEDTLS_OID_PKCS5_PBE_SHA1_RC2_CBC MBEDTLS_OID_PKCS5 "\x0b" /**< pbeWithSHA1AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 11} */
/*
* PKCS#8 OIDs
*/
#define MBEDTLS_OID_PKCS9_CSR_EXT_REQ MBEDTLS_OID_PKCS9 "\x0e" /**< extensionRequest OBJECT IDENTIFIER ::= {pkcs-9 14} */
/*
* PKCS#12 PBE OIDs
*/
#define MBEDTLS_OID_PKCS12_PBE MBEDTLS_OID_PKCS12 "\x01" /**< pkcs-12PbeIds OBJECT IDENTIFIER ::= {pkcs-12 1} */
#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128 MBEDTLS_OID_PKCS12_PBE "\x01" /**< pbeWithSHAAnd128BitRC4 OBJECT IDENTIFIER ::= {pkcs-12PbeIds 1} */
#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_40 MBEDTLS_OID_PKCS12_PBE "\x02" /**< pbeWithSHAAnd40BitRC4 OBJECT IDENTIFIER ::= {pkcs-12PbeIds 2} */
#define MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC MBEDTLS_OID_PKCS12_PBE "\x03" /**< pbeWithSHAAnd3-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 3} */
#define MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC MBEDTLS_OID_PKCS12_PBE "\x04" /**< pbeWithSHAAnd2-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 4} */
#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_128_CBC MBEDTLS_OID_PKCS12_PBE "\x05" /**< pbeWithSHAAnd128BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 5} */
#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_40_CBC MBEDTLS_OID_PKCS12_PBE "\x06" /**< pbeWithSHAAnd40BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 6} */
/*
* EC key algorithms from RFC 5480
*/
/* id-ecPublicKey OBJECT IDENTIFIER ::= {
* iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } */
#define MBEDTLS_OID_EC_ALG_UNRESTRICTED MBEDTLS_OID_ANSI_X9_62 "\x02\01"
/* id-ecDH OBJECT IDENTIFIER ::= {
* iso(1) identified-organization(3) certicom(132)
* schemes(1) ecdh(12) } */
#define MBEDTLS_OID_EC_ALG_ECDH MBEDTLS_OID_CERTICOM "\x01\x0c"
/*
* ECParameters namedCurve identifiers, from RFC 5480, RFC 5639, and SEC2
*/
/* secp192r1 OBJECT IDENTIFIER ::= {
* iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 1 } */
#define MBEDTLS_OID_EC_GRP_SECP192R1 MBEDTLS_OID_ANSI_X9_62 "\x03\x01\x01"
/* secp224r1 OBJECT IDENTIFIER ::= {
* iso(1) identified-organization(3) certicom(132) curve(0) 33 } */
#define MBEDTLS_OID_EC_GRP_SECP224R1 MBEDTLS_OID_CERTICOM "\x00\x21"
/* secp256r1 OBJECT IDENTIFIER ::= {
* iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 7 } */
#define MBEDTLS_OID_EC_GRP_SECP256R1 MBEDTLS_OID_ANSI_X9_62 "\x03\x01\x07"
/* secp384r1 OBJECT IDENTIFIER ::= {
* iso(1) identified-organization(3) certicom(132) curve(0) 34 } */
#define MBEDTLS_OID_EC_GRP_SECP384R1 MBEDTLS_OID_CERTICOM "\x00\x22"
/* secp521r1 OBJECT IDENTIFIER ::= {
* iso(1) identified-organization(3) certicom(132) curve(0) 35 } */
#define MBEDTLS_OID_EC_GRP_SECP521R1 MBEDTLS_OID_CERTICOM "\x00\x23"
/* secp192k1 OBJECT IDENTIFIER ::= {
* iso(1) identified-organization(3) certicom(132) curve(0) 31 } */
#define MBEDTLS_OID_EC_GRP_SECP192K1 MBEDTLS_OID_CERTICOM "\x00\x1f"
/* secp224k1 OBJECT IDENTIFIER ::= {
* iso(1) identified-organization(3) certicom(132) curve(0) 32 } */
#define MBEDTLS_OID_EC_GRP_SECP224K1 MBEDTLS_OID_CERTICOM "\x00\x20"
/* secp256k1 OBJECT IDENTIFIER ::= {
* iso(1) identified-organization(3) certicom(132) curve(0) 10 } */
#define MBEDTLS_OID_EC_GRP_SECP256K1 MBEDTLS_OID_CERTICOM "\x00\x0a"
/* RFC 5639 4.1
* ecStdCurvesAndGeneration OBJECT IDENTIFIER::= {iso(1)
* identified-organization(3) teletrust(36) algorithm(3) signature-
* algorithm(3) ecSign(2) 8}
* ellipticCurve OBJECT IDENTIFIER ::= {ecStdCurvesAndGeneration 1}
* versionOne OBJECT IDENTIFIER ::= {ellipticCurve 1} */
#define MBEDTLS_OID_EC_BRAINPOOL_V1 MBEDTLS_OID_TELETRUST "\x03\x03\x02\x08\x01\x01"
/* brainpoolP256r1 OBJECT IDENTIFIER ::= {versionOne 7} */
#define MBEDTLS_OID_EC_GRP_BP256R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x07"
/* brainpoolP384r1 OBJECT IDENTIFIER ::= {versionOne 11} */
#define MBEDTLS_OID_EC_GRP_BP384R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x0B"
/* brainpoolP512r1 OBJECT IDENTIFIER ::= {versionOne 13} */
#define MBEDTLS_OID_EC_GRP_BP512R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x0D"
/*
* SEC1 C.1
*
* prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 }
* id-fieldType OBJECT IDENTIFIER ::= { ansi-X9-62 fieldType(1)}
*/
#define MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE MBEDTLS_OID_ANSI_X9_62 "\x01"
#define MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE "\x01"
/*
* ECDSA signature identifiers, from RFC 5480
*/
#define MBEDTLS_OID_ANSI_X9_62_SIG MBEDTLS_OID_ANSI_X9_62 "\x04" /* signatures(4) */
#define MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 MBEDTLS_OID_ANSI_X9_62_SIG "\x03" /* ecdsa-with-SHA2(3) */
/* ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
* iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) 1 } */
#define MBEDTLS_OID_ECDSA_SHA1 MBEDTLS_OID_ANSI_X9_62_SIG "\x01"
/* ecdsa-with-SHA224 OBJECT IDENTIFIER ::= {
* iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
* ecdsa-with-SHA2(3) 1 } */
#define MBEDTLS_OID_ECDSA_SHA224 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x01"
/* ecdsa-with-SHA256 OBJECT IDENTIFIER ::= {
* iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
* ecdsa-with-SHA2(3) 2 } */
#define MBEDTLS_OID_ECDSA_SHA256 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x02"
/* ecdsa-with-SHA384 OBJECT IDENTIFIER ::= {
* iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
* ecdsa-with-SHA2(3) 3 } */
#define MBEDTLS_OID_ECDSA_SHA384 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x03"
/* ecdsa-with-SHA512 OBJECT IDENTIFIER ::= {
* iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
* ecdsa-with-SHA2(3) 4 } */
#define MBEDTLS_OID_ECDSA_SHA512 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x04"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Base OID descriptor structure
*/
typedef struct mbedtls_oid_descriptor_t {
const char *asn1; /*!< OID ASN.1 representation */
size_t asn1_len; /*!< length of asn1 */
const char *name; /*!< official name (e.g. from RFC) */
const char *description; /*!< human friendly description */
} mbedtls_oid_descriptor_t;
/**
* \brief Translate an ASN.1 OID into its numeric representation
* (e.g. "\x2A\x86\x48\x86\xF7\x0D" into "1.2.840.113549")
*
* \param buf buffer to put representation in
* \param size size of the buffer
* \param oid OID to translate
*
* \return Length of the string written (excluding final NULL) or
* MBEDTLS_ERR_OID_BUF_TOO_SMALL in case of error
*/
int mbedtls_oid_get_numeric_string(char *buf, size_t size, const mbedtls_asn1_buf *oid);
/**
* \brief Translate an X.509 extension OID into local values
*
* \param oid OID to use
* \param ext_type place to store the extension type
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_x509_ext_type(const mbedtls_asn1_buf *oid, int *ext_type);
/**
* \brief Translate an X.509 attribute type OID into the short name
* (e.g. the OID for an X520 Common Name into "CN")
*
* \param oid OID to use
* \param short_name place to store the string pointer
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_attr_short_name(const mbedtls_asn1_buf *oid, const char **short_name);
/**
* \brief Translate PublicKeyAlgorithm OID into pk_type
*
* \param oid OID to use
* \param pk_alg place to store public key algorithm
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_pk_alg(const mbedtls_asn1_buf *oid, mbedtls_pk_type_t *pk_alg);
/**
* \brief Translate pk_type into PublicKeyAlgorithm OID
*
* \param pk_alg Public key type to look for
* \param oid place to store ASN.1 OID string pointer
* \param olen length of the OID
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_oid_by_pk_alg(mbedtls_pk_type_t pk_alg,
const char **oid, size_t *olen);
#if defined(MBEDTLS_ECP_C)
/**
* \brief Translate NamedCurve OID into an EC group identifier
*
* \param oid OID to use
* \param grp_id place to store group id
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_ec_grp(const mbedtls_asn1_buf *oid, mbedtls_ecp_group_id *grp_id);
/**
* \brief Translate EC group identifier into NamedCurve OID
*
* \param grp_id EC group identifier
* \param oid place to store ASN.1 OID string pointer
* \param olen length of the OID
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_oid_by_ec_grp(mbedtls_ecp_group_id grp_id,
const char **oid, size_t *olen);
#endif /* MBEDTLS_ECP_C */
#if defined(MBEDTLS_MD_C)
/**
* \brief Translate SignatureAlgorithm OID into md_type and pk_type
*
* \param oid OID to use
* \param md_alg place to store message digest algorithm
* \param pk_alg place to store public key algorithm
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_sig_alg(const mbedtls_asn1_buf *oid,
mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg);
/**
* \brief Translate SignatureAlgorithm OID into description
*
* \param oid OID to use
* \param desc place to store string pointer
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_sig_alg_desc(const mbedtls_asn1_buf *oid, const char **desc);
/**
* \brief Translate md_type and pk_type into SignatureAlgorithm OID
*
* \param md_alg message digest algorithm
* \param pk_alg public key algorithm
* \param oid place to store ASN.1 OID string pointer
* \param olen length of the OID
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_oid_by_sig_alg(mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,
const char **oid, size_t *olen);
/**
* \brief Translate hash algorithm OID into md_type
*
* \param oid OID to use
* \param md_alg place to store message digest algorithm
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_md_alg(const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg);
/**
* \brief Translate hmac algorithm OID into md_type
*
* \param oid OID to use
* \param md_hmac place to store message hmac algorithm
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_md_hmac(const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_hmac);
#endif /* MBEDTLS_MD_C */
/**
* \brief Translate Extended Key Usage OID into description
*
* \param oid OID to use
* \param desc place to store string pointer
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_extended_key_usage(const mbedtls_asn1_buf *oid, const char **desc);
/**
* \brief Translate certificate policies OID into description
*
* \param oid OID to use
* \param desc place to store string pointer
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_certificate_policies(const mbedtls_asn1_buf *oid, const char **desc);
/**
* \brief Translate md_type into hash algorithm OID
*
* \param md_alg message digest algorithm
* \param oid place to store ASN.1 OID string pointer
* \param olen length of the OID
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_oid_by_md(mbedtls_md_type_t md_alg, const char **oid, size_t *olen);
#if defined(MBEDTLS_CIPHER_C)
/**
* \brief Translate encryption algorithm OID into cipher_type
*
* \param oid OID to use
* \param cipher_alg place to store cipher algorithm
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_cipher_alg(const mbedtls_asn1_buf *oid, mbedtls_cipher_type_t *cipher_alg);
#endif /* MBEDTLS_CIPHER_C */
#if defined(MBEDTLS_PKCS12_C)
/**
* \brief Translate PKCS#12 PBE algorithm OID into md_type and
* cipher_type
*
* \param oid OID to use
* \param md_alg place to store message digest algorithm
* \param cipher_alg place to store cipher algorithm
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_pkcs12_pbe_alg(const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg,
mbedtls_cipher_type_t *cipher_alg);
#endif /* MBEDTLS_PKCS12_C */
#ifdef __cplusplus
}
#endif
#endif /* oid.h */
|
7cfabeb5002077919db747d43d3aecbf8bc900e8
|
7bc80998b4d500cf1c430a427248d6db3352f2d4
|
/rosette/isode/rbllookup/PasswordLookup-ops.c
|
47575547f4870669f99f614ebb588864b30c0176
|
[
"Apache-2.0"
] |
permissive
|
rchain/rchain
|
a75295b197bfbb8cb1c4b3bad039b09820a6bd9b
|
25e523580a339db9ce2e8abdc9dcab44618d4c5c
|
refs/heads/dev
| 2023-04-02T13:59:39.091866
| 2022-08-30T12:13:56
| 2022-08-30T12:13:56
| 84,493,691
| 822
| 280
|
NOASSERTION
| 2023-03-19T14:52:45
| 2017-03-09T22:15:35
|
Scala
|
UTF-8
|
C
| false
| false
| 2,286
|
c
|
PasswordLookup-ops.c
|
/* automatically generated by rosy 7.0 #14 (nanook.mcc.com), do not edit! */
#include <stdio.h>
#include "PasswordLookup-ops.h"
#include "PasswordLookup-types.h"
/* OPERATIONS */
/* OPERATION lookupUser */
int encode_PasswordLookup_UserName (),
decode_PasswordLookup_UserName (),
free_PasswordLookup_UserName ();
int encode_PasswordLookup_Passwd (),
decode_PasswordLookup_Passwd (),
free_PasswordLookup_Passwd ();
static struct RyError *errors_PasswordLookup_lookupUser[] = {
&table_PasswordLookup_Errors[0],
&table_PasswordLookup_Errors[1]
};
/* OPERATION lookupUID */
int encode_PasswordLookup_UserID (),
decode_PasswordLookup_UserID (),
free_PasswordLookup_UserID ();
int encode_PasswordLookup_Passwd (),
decode_PasswordLookup_Passwd (),
free_PasswordLookup_Passwd ();
static struct RyError *errors_PasswordLookup_lookupUID[] = {
&table_PasswordLookup_Errors[0],
&table_PasswordLookup_Errors[1]
};
struct RyOperation table_PasswordLookup_Operations[] = {
/* OPERATION lookupUser */
"lookupUser", operation_PasswordLookup_lookupUser,
encode_PasswordLookup_lookupUser_argument,
decode_PasswordLookup_lookupUser_argument,
free_PasswordLookup_lookupUser_argument,
1, encode_PasswordLookup_lookupUser_result,
decode_PasswordLookup_lookupUser_result,
free_PasswordLookup_lookupUser_result,
errors_PasswordLookup_lookupUser,
/* OPERATION lookupUID */
"lookupUID", operation_PasswordLookup_lookupUID,
encode_PasswordLookup_lookupUID_argument,
decode_PasswordLookup_lookupUID_argument,
free_PasswordLookup_lookupUID_argument,
1, encode_PasswordLookup_lookupUID_result,
decode_PasswordLookup_lookupUID_result,
free_PasswordLookup_lookupUID_result,
errors_PasswordLookup_lookupUID,
NULL
};
/* ERRORS */
struct RyError table_PasswordLookup_Errors[] = {
/* ERROR noSuchUser */
"noSuchUser", error_PasswordLookup_noSuchUser,
encode_PasswordLookup_noSuchUser_parameter,
decode_PasswordLookup_noSuchUser_parameter,
free_PasswordLookup_noSuchUser_parameter,
/* ERROR congested */
"congested", error_PasswordLookup_congested,
encode_PasswordLookup_congested_parameter,
decode_PasswordLookup_congested_parameter,
free_PasswordLookup_congested_parameter,
NULL
};
|
fe53ca6c12f0a1ae8a1f1ea22c3da8998e7501fd
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/gator/gator.h
|
5cc73a388c4f71a13fd5baecf4a42e68c36f3922
|
[
"GPL-2.0-only",
"Linux-syscall-note",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 5,454
|
h
|
gator.h
|
/**
* Copyright (C) ARM Limited 2010-2014. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#ifndef GATOR_H_
#define GATOR_H_
#include <linux/version.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/list.h>
#define GATOR_PERF_SUPPORT (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 0, 0))
#define GATOR_PERF_PMU_SUPPORT (GATOR_PERF_SUPPORT && defined(CONFIG_PERF_EVENTS) && (!(defined(__arm__) || defined(__aarch64__)) || defined(CONFIG_HW_PERF_EVENTS)))
#define GATOR_NO_PERF_SUPPORT (!(GATOR_PERF_SUPPORT))
#define GATOR_CPU_FREQ_SUPPORT ((LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 38)) && defined(CONFIG_CPU_FREQ))
#define GATOR_IKS_SUPPORT defined(CONFIG_BL_SWITCHER)
/* cpu ids */
#define ARM1136 0xb36
#define ARM1156 0xb56
#define ARM1176 0xb76
#define ARM11MPCORE 0xb02
#define CORTEX_A5 0xc05
#define CORTEX_A7 0xc07
#define CORTEX_A8 0xc08
#define CORTEX_A9 0xc09
#define CORTEX_A15 0xc0f
#define CORTEX_A17 0xc0e
#define SCORPION 0x00f
#define SCORPIONMP 0x02d
#define KRAITSIM 0x049
#define KRAIT 0x04d
#define KRAIT_S4_PRO 0x06f
#define CORTEX_A53 0xd03
#define CORTEX_A57 0xd07
#define AARCH64 0xd0f
#define OTHER 0xfff
/* gpu enums */
#define MALI_4xx 1
#define MALI_MIDGARD 2
#define MAXSIZE_CORE_NAME 32
struct gator_cpu {
const int cpuid;
/* Human readable name */
const char core_name[MAXSIZE_CORE_NAME];
/* gatorfs event and Perf PMU name */
const char *const pmnc_name;
/* compatible from Documentation/devicetree/bindings/arm/cpus.txt */
const char *const dt_name;
const int pmnc_counters;
};
const struct gator_cpu *gator_find_cpu_by_cpuid(const u32 cpuid);
const struct gator_cpu *gator_find_cpu_by_pmu_name(const char *const name);
/******************************************************************************
* Filesystem
******************************************************************************/
struct dentry *gatorfs_mkdir(struct super_block *sb, struct dentry *root,
char const *name);
int gatorfs_create_ulong(struct super_block *sb, struct dentry *root,
char const *name, unsigned long *val);
int gatorfs_create_ro_ulong(struct super_block *sb, struct dentry *root,
char const *name, unsigned long *val);
/******************************************************************************
* Tracepoints
******************************************************************************/
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 32)
# error Kernels prior to 2.6.32 not supported
#elif LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 35)
# define GATOR_DEFINE_PROBE(probe_name, proto) \
static void probe_##probe_name(PARAMS(proto))
# define GATOR_REGISTER_TRACE(probe_name) \
register_trace_##probe_name(probe_##probe_name)
# define GATOR_UNREGISTER_TRACE(probe_name) \
unregister_trace_##probe_name(probe_##probe_name)
#elif LINUX_VERSION_CODE < KERNEL_VERSION(3, 15, 0)
# define GATOR_DEFINE_PROBE(probe_name, proto) \
static void probe_##probe_name(void *data, PARAMS(proto))
# define GATOR_REGISTER_TRACE(probe_name) \
register_trace_##probe_name(probe_##probe_name, NULL)
# define GATOR_UNREGISTER_TRACE(probe_name) \
unregister_trace_##probe_name(probe_##probe_name, NULL)
#else
# define GATOR_DEFINE_PROBE(probe_name, proto) \
extern struct tracepoint *gator_tracepoint_##probe_name; \
static void probe_##probe_name(void *data, PARAMS(proto))
# define GATOR_REGISTER_TRACE(probe_name) \
((gator_tracepoint_##probe_name == NULL) || tracepoint_probe_register(gator_tracepoint_##probe_name, probe_##probe_name, NULL))
# define GATOR_UNREGISTER_TRACE(probe_name) \
tracepoint_probe_unregister(gator_tracepoint_##probe_name, probe_##probe_name, NULL)
#endif
/******************************************************************************
* Events
******************************************************************************/
struct gator_interface {
/* Complementary function to init */
void (*shutdown)(void);
int (*create_files)(struct super_block *sb, struct dentry *root);
int (*start)(void);
/* Complementary function to start */
void (*stop)(void);
int (*online)(int **buffer, bool migrate);
int (*offline)(int **buffer, bool migrate);
/* called in process context but may not be running on core 'cpu' */
void (*online_dispatch)(int cpu, bool migrate);
/* called in process context but may not be running on core 'cpu' */
void (*offline_dispatch)(int cpu, bool migrate);
int (*read)(int **buffer, bool sched_switch);
int (*read64)(long long **buffer);
int (*read_proc)(long long **buffer, struct task_struct *);
struct list_head list;
};
int gator_events_install(struct gator_interface *interface);
int gator_events_get_key(void);
u32 gator_cpuid(void);
void gator_backtrace_handler(struct pt_regs *const regs);
void gator_marshal_activity_switch(int core, int key, int activity, int pid);
#if !GATOR_IKS_SUPPORT
#define get_physical_cpu() smp_processor_id()
#define lcpu_to_pcpu(lcpu) lcpu
#define pcpu_to_lcpu(pcpu) pcpu
#else
#define get_physical_cpu() lcpu_to_pcpu(get_logical_cpu())
int lcpu_to_pcpu(const int lcpu);
int pcpu_to_lcpu(const int pcpu);
#endif
#define get_logical_cpu() smp_processor_id()
#define on_primary_core() (get_logical_cpu() == 0)
#endif /* GATOR_H_ */
|
18f1ecc5c18ece62db5880b86639ab0f60af7414
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/wayland-protocols/gtk/gdk/gdktoplevelsize.h
|
882bd8ba436e8bc7cd5b531e3cc067ce35821eb1
|
[
"LGPL-2.0-only",
"Apache-2.0",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 2,576
|
h
|
gdktoplevelsize.h
|
/* GDK - The GIMP Drawing Kit
* Copyright (C) 2020 Red Hat
*
* This library 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 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef __GDK_TOPLEVEL_SIZE_H__
#define __GDK_TOPLEVEL_SIZE_H__
#if !defined(__GDK_H_INSIDE__) && !defined(GTK_COMPILATION)
#error "Only <gdk/gdk.h> can be included directly."
#endif
#include <gdk/gdktypes.h>
#include <gdk/gdkversionmacros.h>
G_BEGIN_DECLS
typedef struct _GdkToplevelSize GdkToplevelSize;
#define GDK_TYPE_TOPLEVEL_SIZE (gdk_toplevel_size_get_type ())
GDK_AVAILABLE_IN_ALL
GType gdk_toplevel_size_get_type (void);
GDK_AVAILABLE_IN_ALL
void gdk_toplevel_size_get_bounds (GdkToplevelSize *size,
int *bounds_width,
int *bounds_height);
GDK_AVAILABLE_IN_ALL
void gdk_toplevel_size_set_size (GdkToplevelSize *size,
int width,
int height);
GDK_AVAILABLE_IN_ALL
void gdk_toplevel_size_set_min_size (GdkToplevelSize *size,
int min_width,
int min_height);
GDK_AVAILABLE_IN_ALL
void gdk_toplevel_size_set_shadow_width (GdkToplevelSize *size,
int left,
int right,
int top,
int bottom);
G_END_DECLS
#endif /* __GDK_TOPLEVEL_SIZE_H__ */
|
f82d39fb99cf1935a2460552c4bf367136e5afdc
|
3f55217e912141e04815bc8bcb6fbd5638d0896e
|
/src/meta/psplot.h
|
a7e519caa9ad1e0f38f267dbf7dde349335d98d7
|
[
"BSD-2-Clause"
] |
permissive
|
NREL/Radiance
|
bfbb93c99d86368ad0f27052a2a5504aeced47f8
|
2fcca99ace2f2435f32a09525ad31f2b3be3c1bc
|
refs/heads/master
| 2021-12-26T12:42:04.586614
| 2021-12-18T00:43:56
| 2021-12-18T00:43:56
| 8,210,805
| 164
| 68
|
NOASSERTION
| 2019-06-06T19:57:11
| 2013-02-15T00:47:56
|
C
|
UTF-8
|
C
| false
| false
| 479
|
h
|
psplot.h
|
/* RCSid: $Id: psplot.h,v 1.1 2003/11/15 02:13:37 schorsch Exp $ */
/*
* Structures for line segment output to dot matrix printers
*/
#ifndef _RAD_PSPLOT_H_
#define _RAD_PSPLOT_H_
#ifdef __cplusplus
extern "C" {
#endif
extern void init(char *s);
extern void done(void);
extern void segopen(char *s);
extern void segclose(void);
extern void doseg(register PRIMITIVE *p);
extern void plotvstr(register PRIMITIVE *p);
#ifdef __cplusplus
}
#endif
#endif /* _RAD_PSPLOT_H_ */
|
0f21d1998c5ada521f305d171b8df6f684610509
|
7c0ef026c73e74bfcddcb8487a529b9743154fd9
|
/source/main.c
|
859d7fbe2443cfa25dfe282429657ec73a08704e
|
[] |
no_license
|
nedwill/fasthax
|
7a4ae24dd0a1020025a69435bd913e5e2412d53d
|
e039509aa1075f37d02b53b6fcc2ac64d81a1e9a
|
refs/heads/master
| 2021-01-12T04:36:17.501889
| 2017-03-07T15:51:09
| 2017-03-07T15:51:09
| 77,686,809
| 205
| 41
| null | 2017-03-07T15:51:11
| 2016-12-30T13:07:27
|
C
|
UTF-8
|
C
| false
| false
| 473
|
c
|
main.c
|
/* 3ds fasthax kernel exploit
* 11.2 USA N3DS
* Ned Williamson 2016
*/
#include <3ds.h>
#include <stdio.h>
#include "util.h"
#include "exploit.h"
int main() {
gfxInitDefault();
PrintConsole *print_console = consoleInit(GFX_TOP, NULL);
consoleSelect(print_console);
gspWaitForVBlank();
if (k11_exploit()) {
printf("[+] k11_exploit succeeded!\n");
} else {
printf("[-] k11_exploit failed!\n");
}
wait_for_user();
gfxExit();
return 0;
}
|
1b45e21801fd3c842e0c2dad3027464b08f0de87
|
1901bdbaf57584e7c5ec21643db340f9d98d6807
|
/compute/blas_enhance/src/cpu/arm/fp16/mvm_common.h
|
4d9e16ce895026fb21b7ae661c18ab257bacf78a
|
[
"MIT"
] |
permissive
|
huawei-noah/bolt
|
2a4febe5f5cce64e3589c2782c489d59975eb6a3
|
cf4ca8f8646a8e30ddf91c29a18743d75ac1c172
|
refs/heads/master
| 2023-08-28T13:36:34.815244
| 2023-06-12T01:24:41
| 2023-06-12T01:24:41
| 225,365,905
| 889
| 168
|
MIT
| 2023-06-12T01:24:42
| 2019-12-02T12:06:12
|
C++
|
UTF-8
|
C
| false
| false
| 8,621
|
h
|
mvm_common.h
|
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
// 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.
#ifndef _H_MVM_COMMON
#define _H_MVM_COMMON
#include "data_type.h"
#include "arm_neon_expand.h"
#include "affinity_policy.h"
inline void mvm_row_tail(U32 N, U32 K, F16 *matrix, F16 *vector, F16 *result)
{
float16x8_t vec, res, mat;
U32 KTail = K % 8;
U32 KInner = K - KTail;
for (U32 i = 0; i < N; i += 1) {
res = vdupq_n_f16(0);
for (U32 j = 0; j < KInner; j += 8) {
vec = vld1q_f16(&vector[j]);
mat = vld1q_f16(&matrix[j + K * i]);
res = vfmaq_f16(res, vec, mat);
}
result[i] += vaddvq_f16(res);
if (KTail != 0) {
for (U32 p = 0; p < KTail; p += 1) {
result[i] += vector[p + KInner] * matrix[KInner + p + K * i];
}
}
}
}
inline void mvm_col_tail(U32 N, U32 K, F16 *matrix, F16 *vector, F16 *result)
{
float16x8_t tmp, res, mat;
U32 NTail = N % 8;
U32 NInner = N - NTail;
for (U32 i = 0; i < K; i += 1) {
for (U32 j = 0; j < NInner; j += 8) {
tmp = vld1q_f16(result + j);
mat = vld1q_f16(&matrix[j + N * i]);
res = vfmaq_n_f16(tmp, mat, vector[i]);
vst1q_f16(result + j, res);
}
if (NTail != 0) {
for (U32 p = 0; p < NTail; p += 1) {
result[NInner + p] += vector[i] * matrix[NInner + N * i + p];
}
}
}
}
inline void mvm_col_kernel(U32 N, U32 K, F16 *matrix, F16 *vector, F16 *result)
{
float16x8_t mat[4] = {0};
F16 *w0 = matrix;
F16 *w1 = matrix + K * N;
F16 *w2 = matrix + 2 * K * N;
F16 *w3 = matrix + 3 * K * N;
U32 N_tail = N % 8;
U32 N_inner = N - N_tail;
for (U32 i = 0; i < K; i += 1) {
for (U32 j = 0; j < N_inner; j += 8) {
float16x8_t res[4] = {0};
res[3] = vld1q_f16(result + j);
mat[0] = vld1q_f16(w0);
mat[1] = vld1q_f16(w1);
mat[2] = vld1q_f16(w2);
mat[3] = vld1q_f16(w3);
res[0] = vfmaq_n_f16(res[3], mat[0], vector[i]);
res[1] = vfmaq_n_f16(res[0], mat[1], vector[K + i]);
res[2] = vfmaq_n_f16(res[1], mat[2], vector[2 * K + i]);
res[3] = vfmaq_n_f16(res[2], mat[3], vector[3 * K + i]);
w0 += 8;
w1 += 8;
w2 += 8;
w3 += 8;
vst1q_f16(result + j, res[3]);
}
if (N_tail != 0) {
for (U32 p = 0; p < N_tail; p += 1) {
result[N_inner + p] += vector[i] * *w0++;
result[N_inner + p] += vector[i + K] * *w1++;
result[N_inner + p] += vector[i + 2 * K] * *w2++;
result[N_inner + p] += vector[i + 3 * K] * *w3++;
}
}
}
}
inline void mvm_col_kernel_4x8(U32 N, U32 K, F16 *matrix, F16 *vector, F16 *result)
{
F16 *result_end8 = result + N / 8 * 8;
F16 *result_end = result + N;
asm volatile("mov x20, %0\n"
"add x21, x20, %5\n"
"add x22, x21, %5\n"
"add x23, x22, %5\n"
"mov x24, %1\n"
"add x25, x24, %6\n"
"add x26, x25, %6\n"
"add x27, x26, %6\n"
"mov x2, x21\n"
"00:\n"
"cmp x20, x2\n"
"bge 01f\n"
"ldr h0, [x20], 2\n"
"dup v0.8h, v0.h[0]\n"
"ldr h1, [x21], 2\n"
"dup v1.8h, v1.h[0]\n"
"ldr h2, [x22], 2\n"
"dup v2.8h, v2.h[0]\n"
"ldr h3, [x23], 2\n"
"dup v3.8h, v3.h[0]\n"
"mov x28, %2\n"
"10:\n"
"cmp x28, %3\n"
"bge 11f\n"
"ldr q4, [x28]\n"
"ldr q8, [x24], 16\n"
"ldr q9, [x25], 16\n"
"ldr q10, [x26], 16\n"
"fmla v4.8h, v8.8h, v0.8h\n"
"ldr q11, [x27], 16\n"
"fmla v4.8h, v9.8h, v1.8h\n"
"fmla v4.8h, v10.8h, v2.8h\n"
"fmla v4.8h, v11.8h, v3.8h\n"
"str q4, [x28], 16\n"
"b 10b\n"
"11:\n"
"cmp x28, %4\n"
"bge 12f\n"
"ldr h4, [x28]\n"
"ldr h8, [x24], 2\n"
"ldr h9, [x25], 2\n"
"ldr h10, [x26], 2\n"
"fmla h4, h8, v0.h[0]\n"
"ldr h11, [x27], 2\n"
"fmla h4, h9, v1.h[0]\n"
"fmla h4, h10, v2.h[0]\n"
"fmla h4, h11, v3.h[0]\n"
"str h4, [x28], 2\n"
"b 11b\n"
"12:\n"
"b 00b\n"
"01:\n"
: "+r"(vector), "+r"(matrix), "+r"(result), "+r"(result_end8), "+r"(result_end)
: "r"((I64)K * 2), "r"((I64)K * N * 2)
: "memory", "cc", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28",
"x2", "v0", "v1", "v2", "v3", "v4", "v8", "v9", "v10", "v11");
}
inline void mvm_row_kernel(U32 N, U32 K, F16 *matrix, F16 *vector, F16 *result)
{
float16x8_t res[4] = {0}, mat[4] = {0}, vec;
float16x8_t tmp[6] = {0};
F16 *w0 = matrix;
F16 *w1 = matrix + K * N;
F16 *w2 = matrix + 2 * K * N;
F16 *w3 = matrix + 3 * K * N;
U32 K_tail = K % 8;
U32 K_inner = K - K_tail;
for (U32 i = 0; i < N; i += 1) {
for (U32 j = 0; j < K_inner; j += 8) {
vec = vld1q_f16(&vector[j]);
mat[0] = vld1q_f16(w0);
mat[1] = vld1q_f16(w1);
mat[2] = vld1q_f16(w2);
mat[3] = vld1q_f16(w3);
for (U32 k = 0; k < 4; k++) {
res[k] = vfmaq_f16(res[k], vec, mat[k]);
}
w0 += 8;
w1 += 8;
w2 += 8;
w3 += 8;
}
for (U32 m = 0; m < 2; m++) {
tmp[m] = vpaddq_f16(res[m * 2], res[m * 2 + 1]);
}
tmp[4] = vpaddq_f16(tmp[0], tmp[1]);
tmp[5] = vpaddq_f16(tmp[4], tmp[3]);
F16 addbias;
for (U32 n = 0; n < 4; n++) {
vst1q_lane_f16_builtin(&addbias, tmp[5], n);
result[i + N * n] += addbias;
res[n] = vdupq_n_f16(0);
}
if (K_tail != 0) {
for (U32 p = 0; p < K_tail; p += 1) {
*(result + i) += vector[p + K_inner] * *w0++;
*(result + N + i) += vector[p + K_inner] * *w1++;
*(result + 2 * N + i) += vector[p + K_inner] * *w2++;
*(result + 3 * N + i) += vector[p + K_inner] * *w3++;
}
}
}
}
inline void mvm_col(U32 numRows, U32 numColumns, F16 *matrix, F16 *vector, F16 *result)
{
// Actual layout is KN, and vector is K
U32 N = numRows;
U32 K = numColumns;
U32 KInner = K / 4;
U32 KTail = K % 4;
mvm_col_kernel_4x8(N, KInner, matrix, vector, result);
if (KTail != 0) {
mvm_col_tail(N, KTail, matrix + (K - KTail) * N, vector + (K - KTail), result);
}
}
// N is number of rows, K for columns
inline void mvm_row(U32 N, U32 K, F16 *matrix, F16 *vector, F16 *result)
{
U32 NInner = (N / 4);
U32 NTail = N % 4;
mvm_row_kernel(NInner, K, matrix, vector, result);
if (NTail != 0) {
mvm_row_tail(NTail, K, matrix + (N - NTail) * K, vector, result + N - NTail);
}
}
#endif
|
83277434041f916f4d9fffd083e800dee674fd8a
|
e411638b54e787befdb813c7bc03f6c29797bd6b
|
/samples/SampleApp/ios/Pods/Headers/Public/SDWebImage/NSImage+Compatibility.h
|
dde4c7e611145bf2303c0ffaa5089fc52e2ee59e
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
vovkasm/react-native-web-image
|
955e18df8687b82575ca1e83a728f7d0e97eb826
|
e269cc5f8aad06e6e7429ddc6de95bd20ff82407
|
refs/heads/develop
| 2023-01-06T23:18:04.703154
| 2019-08-03T07:11:53
| 2019-08-03T07:11:53
| 74,192,763
| 159
| 35
|
MIT
| 2023-01-03T15:13:59
| 2016-11-19T06:56:55
|
Java
|
UTF-8
|
C
| false
| false
| 54
|
h
|
NSImage+Compatibility.h
|
../../../SDWebImage/SDWebImage/NSImage+Compatibility.h
|
0b7ca74371a38f8e8147a3a309eafa43af1f8428
|
aa5c1a530f95d629e686ac9124caf1a49a9f23e9
|
/runtime/src/iree/vm/bytecode/archive.c
|
1348e2d89efb5351612461c2d937737725606351
|
[
"Apache-2.0",
"LLVM-exception",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
openxla/iree
|
eacf5b239559e1d3b40c38039ac4c26315b523f7
|
13ef677e556d0a1d154e45b052fe016256057f65
|
refs/heads/main
| 2023-09-06T01:19:49.598662
| 2023-09-04T07:01:30
| 2023-09-04T07:01:30
| 208,145,128
| 387
| 110
|
Apache-2.0
| 2023-09-14T20:48:00
| 2019-09-12T20:57:39
|
C++
|
UTF-8
|
C
| false
| false
| 6,149
|
c
|
archive.c
|
// Copyright 2023 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/vm/bytecode/archive.h"
#include "iree/vm/bytecode/utils/isa.h"
// ZIP local file header (comes immediately before each file in the archive).
// In order to find the starting offset of the FlatBuffer in a polyglot archive
// we need to parse this given the variable-length nature of it (we want to
// be robust to file name and alignment changes).
//
// NOTE: all fields are little-endian.
// NOTE: we don't care about the actual module size here; since we support
// streaming archives trying to recover it would require much more
// involved processing (we'd need to reference the central directory).
// If we wanted to support users repacking ZIPs we'd probably want to
// rewrite everything as we store offsets in the FlatBuffer that are
// difficult to update after the archive has been produced.
#define ZIP_LOCAL_FILE_HEADER_SIGNATURE 0x04034B50u
#if defined(IREE_COMPILER_MSVC)
#pragma pack(push, 1)
#endif // IREE_COMPILER_MSVC
typedef struct {
uint32_t signature; // ZIP_LOCAL_FILE_HEADER_SIGNATURE
uint16_t version;
uint16_t general_purpose_flag;
uint16_t compression_method;
uint16_t last_modified_time;
uint16_t last_modified_date;
uint32_t crc32; // 0 for us
uint32_t compressed_size; // 0 for us
uint32_t uncompressed_size; // 0 for us
uint16_t file_name_length;
uint16_t extra_field_length;
// file name (variable size)
// extra field (variable size)
} IREE_ATTRIBUTE_PACKED zip_local_file_header_t;
#if defined(IREE_COMPILER_MSVC)
#pragma pack(pop)
#endif // IREE_COMPILER_MSVC
static_assert(sizeof(zip_local_file_header_t) == 30, "bad packing");
#if !defined(IREE_ENDIANNESS_LITTLE) || !IREE_ENDIANNESS_LITTLE
#error "little endian required for zip header parsing"
#endif // IREE_ENDIANNESS_LITTLE
// Strips any ZIP local file header from |contents| and stores the remaining
// range in |out_stripped|.
static iree_status_t iree_vm_bytecode_module_strip_zip_header(
iree_const_byte_span_t contents, iree_const_byte_span_t* out_stripped) {
// Ensure there's at least some bytes we can check for the header.
// Since we're only looking to strip zip stuff here we can check on that.
if (!contents.data ||
contents.data_length < sizeof(zip_local_file_header_t)) {
memmove(out_stripped, &contents, sizeof(contents));
return iree_ok_status();
}
// Check to see if there's a zip local header signature.
// For a compliant zip file this is expected to start at offset 0.
const zip_local_file_header_t* header =
(const zip_local_file_header_t*)contents.data;
if (header->signature != ZIP_LOCAL_FILE_HEADER_SIGNATURE) {
// No signature found, probably not a ZIP.
memmove(out_stripped, &contents, sizeof(contents));
return iree_ok_status();
}
// Compute the starting offset of the file.
// Note that we still don't know (or care) if it's the file we want; actual
// FlatBuffer verification happens later on.
uint32_t offset =
sizeof(*header) + header->file_name_length + header->extra_field_length;
if (offset > contents.data_length) {
// Is a ZIP but doesn't have enough data; error out with something more
// useful than the FlatBuffer verification failing later on given that here
// we know this isn't a FlatBuffer.
return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
"archive self-reports as a zip but does not have "
"enough data to contain a module");
}
*out_stripped = iree_make_const_byte_span(contents.data + offset,
contents.data_length - offset);
return iree_ok_status();
}
IREE_API_EXPORT iree_status_t iree_vm_bytecode_archive_parse_header(
iree_const_byte_span_t archive_contents,
iree_const_byte_span_t* out_flatbuffer_contents,
iree_host_size_t* out_rodata_offset) {
// Slice off any polyglot zip header we have prior to the base of the module.
iree_const_byte_span_t module_contents = iree_const_byte_span_empty();
IREE_RETURN_IF_ERROR(iree_vm_bytecode_module_strip_zip_header(
archive_contents, &module_contents));
// Verify there's enough data to safely check the FlatBuffer header.
if (!module_contents.data || module_contents.data_length < 16) {
return iree_make_status(
IREE_STATUS_INVALID_ARGUMENT,
"FlatBuffer data is not present or less than 16 bytes (%" PRIhsz
" total)",
module_contents.data_length);
}
// Read the size prefix from the head of the module contents; this should be
// a 4 byte value indicating the total size of the FlatBuffer data.
size_t length_prefix = 0;
flatbuffers_read_size_prefix((void*)module_contents.data, &length_prefix);
// Verify the length prefix is within bounds (always <= the remaining module
// bytes).
size_t length_remaining =
module_contents.data_length - sizeof(flatbuffers_uoffset_t);
if (length_prefix > length_remaining) {
return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
"FlatBuffer length prefix out of bounds (prefix is "
"%zu but only %zu available)",
length_prefix, length_remaining);
}
// Form the range of bytes containing just the FlatBuffer data.
iree_const_byte_span_t flatbuffer_contents = iree_make_const_byte_span(
module_contents.data + sizeof(flatbuffers_uoffset_t), length_prefix);
if (out_flatbuffer_contents) {
*out_flatbuffer_contents = flatbuffer_contents;
}
if (out_rodata_offset) {
// rodata begins immediately following the FlatBuffer in memory.
iree_host_size_t rodata_offset = iree_host_align(
(iree_host_size_t)(flatbuffer_contents.data - archive_contents.data) +
length_prefix,
IREE_VM_ARCHIVE_SEGMENT_ALIGNMENT);
*out_rodata_offset = rodata_offset;
}
return iree_ok_status();
}
|
78f17ed42f4b850b82d08aa6ed660c8f749167a2
|
e8b04bef9aa1ac8e2c109dd315f133c8f4d28ae6
|
/projects/robots/epfl/lis/plugins/physics/blimp_physics/blimp_physics.c
|
9d593ed3f3372544e78541ca303e38fb17e1f35a
|
[
"Apache-2.0"
] |
permissive
|
cyberbotics/webots
|
f075dacf4067e8dcebbfd89e8690df8525f6d745
|
8aba6eaae76989facf3442305c8089d3cc366bcf
|
refs/heads/master
| 2023-08-31T09:41:13.205940
| 2023-08-18T10:48:30
| 2023-08-18T10:48:30
| 156,228,018
| 2,495
| 1,525
|
Apache-2.0
| 2023-08-28T16:30:33
| 2018-11-05T14:09:10
|
C++
|
UTF-8
|
C
| false
| false
| 5,090
|
c
|
blimp_physics.c
|
/****************************************************************************
blimp_physics -- A blimp physics model for Webots.
Copyright (C) 2006 Laboratory of Intelligent Systems, EPFL, Lausanne
Authors: Alexis Guanella guanella@ini.phys.ethz.ch
Antoine Beyeler antoine.beyeler@epfl.ch
Jean-Christophe Zufferey jean-christophe.zufferey@epfl.ch
Dario Floreano dario.floreano@epfl.ch
Web: http://lis.epfl.ch
The authors of any publication arising from research using this software are
kindly requested to add the following reference:
Zufferey, J.C., Guanella, A., Beyeler, A., Floreano, D. (2006) Flying over
the Reality Gap: From Simulated to Real Indoor Airships. Autonomous Robots,
Springer US.
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
/*------------------------------------------------------------------------------
Author: Antoine Beyeler (ab)
------------------------------------------------------------------------------*/
#include <plugins/physics.h>
#include "blimp2b.h"
#include "blimpmodel.h"
#include "utils.h"
// constants
const char kRobotName[] = "blimp_lis";
const dReal kRotWebotsToAeroBody[] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
const dReal kRotAeroToWebotsBody[] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
// globals
static dBodyID gRobotBody = NULL;
//-----------------------------------------------------------------
// Physics plug-in implementation
DLLEXPORT void webots_physics_init() {
// init global variables
gRobotBody = dWebotsGetBodyFromDEF(kRobotName);
if (gRobotBody == NULL)
dWebotsConsolePrintf("!!! blimp_physics :: webots_physics_init :: error : could not get body of robot.\r\n");
else {
// disable gravity for the blimp: buoyancy counteract gravity.
dBodySetGravityMode(gRobotBody, 0);
}
}
DLLEXPORT void webots_physics_step() {
Matrix33 rotBodyToFrame;
Matrix33 rotFrameToBody;
Matrix33 rotFrameToAeroBody;
Matrix33 tmp1, tmp2;
dReal *ode;
Vector6 genPos, genSpeed, genForce;
dVector3 propThrusts;
double *controls;
int size;
// we return if we have no robot to actuate.
if (gRobotBody == NULL)
return;
// read control surfaces values
controls = (double *)dWebotsReceive(&size);
if (size != 3 * sizeof(double)) {
// physics plugin and controller run with different frequencies therefore it is not
// guarantied that control value are present in the buffer for each webots_physics_step()
return;
}
b2b_commandsToThrust(controls[0], controls[1], controls[2], propThrusts);
// get rotation matrix from webots frame coordinate to aero body coordinate
ode = (dReal *)dBodyGetRotation(gRobotBody);
rotBodyToFrame[0] = ode[0];
rotBodyToFrame[1] = ode[1];
rotBodyToFrame[2] = ode[2];
rotBodyToFrame[3] = ode[4];
rotBodyToFrame[4] = ode[5];
rotBodyToFrame[5] = ode[6];
rotBodyToFrame[6] = ode[8];
rotBodyToFrame[7] = ode[9];
rotBodyToFrame[8] = ode[10];
utils_Assign(rotFrameToBody, rotBodyToFrame, 9);
utils_InvertMatrix33(rotFrameToBody);
utils_Multiply(rotFrameToAeroBody, kRotWebotsToAeroBody, rotFrameToBody, 3, 3, 3);
// get the velocity in aero body coordinate...
utils_Multiply(genSpeed, rotFrameToAeroBody, dBodyGetLinearVel(gRobotBody), 3, 3, 1);
utils_Multiply(&genSpeed[3], rotFrameToAeroBody, dBodyGetAngularVel(gRobotBody), 3, 3, 1);
// get the body position...
utils_Multiply(genPos, kRotWebotsToAeroBody, dBodyGetPosition(gRobotBody), 3, 3, 1);
// ...and rotation.
utils_Multiply(tmp1, rotFrameToBody, kRotAeroToWebotsBody, 3, 3, 3);
utils_Multiply(tmp2, kRotWebotsToAeroBody, tmp1, 3, 3, 3);
genPos[3] = dAtan2(tmp2[5], tmp2[8]);
genPos[4] = dAsin(-tmp2[2]);
genPos[5] = dAtan2(tmp2[1], tmp2[0]);
// run blimp model
bmod_ComputeGenForces(genPos, genSpeed, propThrusts, tmp1);
// convert back to webots coordinate...
utils_Multiply(genForce, kRotAeroToWebotsBody, tmp1, 3, 3, 1);
utils_Multiply(&genForce[3], kRotAeroToWebotsBody, &tmp1[3], 3, 3, 1);
// ...and apply to body.
dBodyAddRelForce(gRobotBody, genForce[0], genForce[1], genForce[2]);
dBodyAddRelTorque(gRobotBody, genForce[3], genForce[4], genForce[5]);
}
DLLEXPORT int webots_physics_collide(dGeomID g1, dGeomID g2) {
// We don't want to handle collisions
return 0;
}
DLLEXPORT void webots_physics_cleanup() {
}
|
ff362d0c01f899be6ff97805e3b3ad1db87ee25c
|
e48198ffea7b0b80669253fb970fdcc1d2f4c518
|
/src/message.c
|
98a362411ea3752fe36693a7176f8e6535d914e3
|
[
"GPL-1.0-or-later",
"Vim",
"GPL-2.0-only"
] |
permissive
|
vim/vim
|
f9ea5913ff884c87bc11f7826b1fc277fba8a2b5
|
816fbcc262687b81fc46f82f7bbeb1453addfe0c
|
refs/heads/master
| 2023-09-01T16:01:56.964678
| 2023-08-31T21:52:30
| 2023-08-31T21:52:30
| 40,997,482
| 37,589
| 7,920
|
Vim
| 2023-09-14T20:57:43
| 2015-08-18T21:03:56
|
Vim Script
|
UTF-8
|
C
| false
| false
| 102,482
|
c
|
message.c
|
/* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* message.c: functions for displaying messages on the command line
*/
#define MESSAGE_FILE // don't include prototype for smsg()
#include "vim.h"
static void add_msg_hist(char_u *s, int len, int attr);
static void hit_return_msg(void);
static void msg_home_replace_attr(char_u *fname, int attr);
static void msg_puts_attr_len(char *str, int maxlen, int attr);
static void msg_puts_display(char_u *str, int maxlen, int attr, int recurse);
static void msg_scroll_up(void);
static void inc_msg_scrolled(void);
static void store_sb_text(char_u **sb_str, char_u *s, int attr, int *sb_col, int finish);
static void t_puts(int *t_col, char_u *t_s, char_u *s, int attr);
static void msg_puts_printf(char_u *str, int maxlen);
static int do_more_prompt(int typed_char);
static void msg_screen_putchar(int c, int attr);
static void msg_moremsg(int full);
static int msg_check_screen(void);
static void redir_write(char_u *s, int maxlen);
#ifdef FEAT_CON_DIALOG
static char_u *msg_show_console_dialog(char_u *message, char_u *buttons, int dfltbutton);
static int confirm_msg_used = FALSE; // displaying confirm_msg
static char_u *confirm_msg = NULL; // ":confirm" message
static char_u *confirm_msg_tail; // tail of confirm_msg
static void display_confirm_msg(void);
#endif
#ifdef FEAT_EVAL
static int emsg_to_channel_log = FALSE;
#endif
struct msg_hist
{
struct msg_hist *next;
char_u *msg;
int attr;
};
static struct msg_hist *first_msg_hist = NULL;
static struct msg_hist *last_msg_hist = NULL;
static int msg_hist_len = 0;
static FILE *verbose_fd = NULL;
static int verbose_did_open = FALSE;
/*
* When writing messages to the screen, there are many different situations.
* A number of variables is used to remember the current state:
* msg_didany TRUE when messages were written since the last time the
* user reacted to a prompt.
* Reset: After hitting a key for the hit-return prompt,
* hitting <CR> for the command line or input().
* Set: When any message is written to the screen.
* msg_didout TRUE when something was written to the current line.
* Reset: When advancing to the next line, when the current
* text can be overwritten.
* Set: When any message is written to the screen.
* msg_nowait No extra delay for the last drawn message.
* Used in normal_cmd() before the mode message is drawn.
* emsg_on_display There was an error message recently. Indicates that there
* should be a delay before redrawing.
* msg_scroll The next message should not overwrite the current one.
* msg_scrolled How many lines the screen has been scrolled (because of
* messages). Used in update_screen() to scroll the screen
* back. Incremented each time the screen scrolls a line.
* msg_scrolled_ign TRUE when msg_scrolled is non-zero and msg_puts_attr()
* writes something without scrolling should not make
* need_wait_return to be set. This is a hack to make ":ts"
* work without an extra prompt.
* lines_left Number of lines available for messages before the
* more-prompt is to be given. -1 when not set.
* need_wait_return TRUE when the hit-return prompt is needed.
* Reset: After giving the hit-return prompt, when the user
* has answered some other prompt.
* Set: When the ruler or typeahead display is overwritten,
* scrolling the screen for some message.
* keep_msg Message to be displayed after redrawing the screen, in
* main_loop().
* This is an allocated string or NULL when not used.
*/
/*
* msg(s) - displays the string 's' on the status line
* When terminal not initialized (yet) mch_errmsg(..) is used.
* return TRUE if wait_return() not called
*/
int
msg(char *s)
{
return msg_attr_keep(s, 0, FALSE);
}
/*
* Like msg() but keep it silent when 'verbosefile' is set.
*/
int
verb_msg(char *s)
{
int n;
verbose_enter();
n = msg_attr_keep(s, 0, FALSE);
verbose_leave();
return n;
}
int
msg_attr(char *s, int attr)
{
return msg_attr_keep(s, attr, FALSE);
}
int
msg_attr_keep(
char *s,
int attr,
int keep) // TRUE: set keep_msg if it doesn't scroll
{
static int entered = 0;
int retval;
char_u *buf = NULL;
// Skip messages not matching ":filter pattern".
// Don't filter when there is an error.
if (!emsg_on_display && message_filtered((char_u *)s))
return TRUE;
#ifdef FEAT_EVAL
if (attr == 0)
set_vim_var_string(VV_STATUSMSG, (char_u *)s, -1);
#endif
/*
* It is possible that displaying a messages causes a problem (e.g.,
* when redrawing the window), which causes another message, etc.. To
* break this loop, limit the recursiveness to 3 levels.
*/
if (entered >= 3)
return TRUE;
++entered;
// Add message to history (unless it's a repeated kept message or a
// truncated message)
if ((char_u *)s != keep_msg
|| (*s != '<'
&& last_msg_hist != NULL
&& last_msg_hist->msg != NULL
&& STRCMP(s, last_msg_hist->msg)))
add_msg_hist((char_u *)s, -1, attr);
#ifdef FEAT_EVAL
if (emsg_to_channel_log)
// Write message in the channel log.
ch_log(NULL, "ERROR: %s", s);
#endif
// Truncate the message if needed.
msg_start();
buf = msg_strtrunc((char_u *)s, FALSE);
if (buf != NULL)
s = (char *)buf;
msg_outtrans_attr((char_u *)s, attr);
msg_clr_eos();
retval = msg_end();
if (keep && retval && vim_strsize((char_u *)s)
< (int)(Rows - cmdline_row - 1) * Columns + sc_col)
set_keep_msg((char_u *)s, 0);
need_fileinfo = FALSE;
vim_free(buf);
--entered;
return retval;
}
/*
* Truncate a string such that it can be printed without causing a scroll.
* Returns an allocated string or NULL when no truncating is done.
*/
char_u *
msg_strtrunc(
char_u *s,
int force) // always truncate
{
char_u *buf = NULL;
int len;
int room;
// May truncate message to avoid a hit-return prompt
if ((!msg_scroll && !need_wait_return && shortmess(SHM_TRUNCALL)
&& !exmode_active && msg_silent == 0) || force)
{
len = vim_strsize(s);
if (msg_scrolled != 0
#ifdef HAS_MESSAGE_WINDOW
|| in_echowindow
#endif
)
// Use all the columns.
room = (int)(Rows - msg_row) * Columns - 1;
else
// Use up to 'showcmd' column.
room = (int)(Rows - msg_row - 1) * Columns + sc_col - 1;
if (len > room && room > 0)
{
if (enc_utf8)
// may have up to 18 bytes per cell (6 per char, up to two
// composing chars)
len = (room + 2) * 18;
else if (enc_dbcs == DBCS_JPNU)
// may have up to 2 bytes per cell for euc-jp
len = (room + 2) * 2;
else
len = room + 2;
buf = alloc(len);
if (buf != NULL)
trunc_string(s, buf, room, len);
}
}
return buf;
}
/*
* Truncate a string "s" to "buf" with cell width "room".
* "s" and "buf" may be equal.
*/
void
trunc_string(
char_u *s,
char_u *buf,
int room_in,
int buflen)
{
size_t room = room_in - 3; // "..." takes 3 chars
size_t half;
size_t len = 0;
int e;
int i;
int n;
if (*s == NUL)
{
if (buflen > 0)
*buf = NUL;
return;
}
if (room_in < 3)
room = 0;
half = room / 2;
// First part: Start of the string.
for (e = 0; len < half && e < buflen; ++e)
{
if (s[e] == NUL)
{
// text fits without truncating!
buf[e] = NUL;
return;
}
n = ptr2cells(s + e);
if (len + n > half)
break;
len += n;
buf[e] = s[e];
if (has_mbyte)
for (n = (*mb_ptr2len)(s + e); --n > 0; )
{
if (++e == buflen)
break;
buf[e] = s[e];
}
}
// Last part: End of the string.
i = e;
if (enc_dbcs != 0)
{
// For DBCS going backwards in a string is slow, but
// computing the cell width isn't too slow: go forward
// until the rest fits.
n = vim_strsize(s + i);
while (len + n > room)
{
n -= ptr2cells(s + i);
i += (*mb_ptr2len)(s + i);
}
}
else if (enc_utf8)
{
// For UTF-8 we can go backwards easily.
half = i = (int)STRLEN(s);
for (;;)
{
do
half = half - utf_head_off(s, s + half - 1) - 1;
while (half > 0 && utf_iscomposing(utf_ptr2char(s + half)));
n = ptr2cells(s + half);
if (len + n > room || half == 0)
break;
len += n;
i = (int)half;
}
}
else
{
for (i = (int)STRLEN(s);
i - 1 >= 0 && len + (n = ptr2cells(s + i - 1)) <= room; --i)
len += n;
}
if (i <= e + 3)
{
// text fits without truncating
if (s != buf)
{
len = STRLEN(s);
if (len >= (size_t)buflen)
len = buflen - 1;
len = len - e + 1;
if (len < 1)
buf[e - 1] = NUL;
else
mch_memmove(buf + e, s + e, len);
}
}
else if (e + 3 < buflen)
{
// set the middle and copy the last part
mch_memmove(buf + e, "...", (size_t)3);
len = STRLEN(s + i) + 1;
if (len >= (size_t)buflen - e - 3)
len = buflen - e - 3 - 1;
mch_memmove(buf + e + 3, s + i, len);
buf[e + 3 + len - 1] = NUL;
}
else
{
// can't fit in the "...", just truncate it
buf[e - 1] = NUL;
}
}
/*
* Automatic prototype generation does not understand this function.
* Note: Caller of smsg() and smsg_attr() must check the resulting string is
* shorter than IOSIZE!!!
*/
#ifndef PROTO
int vim_snprintf(char *str, size_t str_m, const char *fmt, ...);
int
smsg(const char *s, ...)
{
if (IObuff == NULL)
{
// Very early in initialisation and already something wrong, just
// give the raw message so the user at least gets a hint.
return msg((char *)s);
}
va_list arglist;
va_start(arglist, s);
vim_vsnprintf((char *)IObuff, IOSIZE, s, arglist);
va_end(arglist);
return msg((char *)IObuff);
}
int
smsg_attr(int attr, const char *s, ...)
{
if (IObuff == NULL)
{
// Very early in initialisation and already something wrong, just
// give the raw message so the user at least gets a hint.
return msg_attr((char *)s, attr);
}
va_list arglist;
va_start(arglist, s);
vim_vsnprintf((char *)IObuff, IOSIZE, s, arglist);
va_end(arglist);
return msg_attr((char *)IObuff, attr);
}
int
smsg_attr_keep(int attr, const char *s, ...)
{
if (IObuff == NULL)
{
// Very early in initialisation and already something wrong, just
// give the raw message so the user at least gets a hint.
return msg_attr_keep((char *)s, attr, TRUE);
}
va_list arglist;
va_start(arglist, s);
vim_vsnprintf((char *)IObuff, IOSIZE, s, arglist);
va_end(arglist);
return msg_attr_keep((char *)IObuff, attr, TRUE);
}
#endif
/*
* Remember the last sourcing name/lnum used in an error message, so that it
* isn't printed each time when it didn't change.
*/
static int last_sourcing_lnum = 0;
static char_u *last_sourcing_name = NULL;
/*
* Reset the last used sourcing name/lnum. Makes sure it is displayed again
* for the next error message;
*/
void
reset_last_sourcing(void)
{
VIM_CLEAR(last_sourcing_name);
last_sourcing_lnum = 0;
}
/*
* Return TRUE if "SOURCING_NAME" differs from "last_sourcing_name".
*/
static int
other_sourcing_name(void)
{
if (HAVE_SOURCING_INFO && SOURCING_NAME != NULL)
{
if (last_sourcing_name != NULL)
return STRCMP(SOURCING_NAME, last_sourcing_name) != 0;
return TRUE;
}
return FALSE;
}
/*
* Get the message about the source, as used for an error message.
* Returns an allocated string with room for one more character.
* Returns NULL when no message is to be given.
*/
static char_u *
get_emsg_source(void)
{
char_u *Buf, *p;
if (HAVE_SOURCING_INFO && SOURCING_NAME != NULL && other_sourcing_name())
{
char_u *sname = estack_sfile(ESTACK_NONE);
char_u *tofree = sname;
if (sname == NULL)
sname = SOURCING_NAME;
#ifdef FEAT_EVAL
if (estack_compiling)
p = (char_u *)_("Error detected while compiling %s:");
else
#endif
p = (char_u *)_("Error detected while processing %s:");
Buf = alloc(STRLEN(sname) + STRLEN(p));
if (Buf != NULL)
sprintf((char *)Buf, (char *)p, sname);
vim_free(tofree);
return Buf;
}
return NULL;
}
/*
* Get the message about the source lnum, as used for an error message.
* Returns an allocated string with room for one more character.
* Returns NULL when no message is to be given.
*/
static char_u *
get_emsg_lnum(void)
{
char_u *Buf, *p;
// lnum is 0 when executing a command from the command line
// argument, we don't want a line number then
if (SOURCING_NAME != NULL
&& (other_sourcing_name() || SOURCING_LNUM != last_sourcing_lnum)
&& SOURCING_LNUM != 0)
{
p = (char_u *)_("line %4ld:");
Buf = alloc(STRLEN(p) + 20);
if (Buf != NULL)
sprintf((char *)Buf, (char *)p, (long)SOURCING_LNUM);
return Buf;
}
return NULL;
}
/*
* Display name and line number for the source of an error.
* Remember the file name and line number, so that for the next error the info
* is only displayed if it changed.
*/
void
msg_source(int attr)
{
char_u *p;
static int recursive = FALSE;
// Bail out if something called here causes an error.
if (recursive)
return;
recursive = TRUE;
++no_wait_return;
p = get_emsg_source();
if (p != NULL)
{
msg_scroll = TRUE; // this will take more than one line
msg_attr((char *)p, attr);
vim_free(p);
}
p = get_emsg_lnum();
if (p != NULL)
{
msg_attr((char *)p, HL_ATTR(HLF_N));
vim_free(p);
last_sourcing_lnum = SOURCING_LNUM; // only once for each line
}
// remember the last sourcing name printed, also when it's empty
if (SOURCING_NAME == NULL || other_sourcing_name())
{
VIM_CLEAR(last_sourcing_name);
if (SOURCING_NAME != NULL)
last_sourcing_name = vim_strsave(SOURCING_NAME);
}
--no_wait_return;
recursive = FALSE;
}
/*
* Return TRUE if not giving error messages right now:
* If "emsg_off" is set: no error messages at the moment.
* If "msg" is in 'debug': do error message but without side effects.
* If "emsg_skip" is set: never do error messages.
*/
static int
emsg_not_now(void)
{
if ((emsg_off > 0 && vim_strchr(p_debug, 'm') == NULL
&& vim_strchr(p_debug, 't') == NULL)
#ifdef FEAT_EVAL
|| emsg_skip > 0
#endif
)
return TRUE;
return FALSE;
}
#if defined(FEAT_EVAL) || defined(PROTO)
static garray_T ignore_error_list = GA_EMPTY;
void
ignore_error_for_testing(char_u *error)
{
if (ignore_error_list.ga_itemsize == 0)
ga_init2(&ignore_error_list, sizeof(char_u *), 1);
if (STRCMP("RESET", error) == 0)
ga_clear_strings(&ignore_error_list);
else
ga_copy_string(&ignore_error_list, error);
}
static int
ignore_error(const char *msg)
{
int i;
for (i = 0; i < ignore_error_list.ga_len; ++i)
if (strstr(msg,
(char *)((char_u **)(ignore_error_list.ga_data))[i]) != NULL)
return TRUE;
return FALSE;
}
#endif
#if !defined(HAVE_STRERROR) || defined(PROTO)
/*
* Replacement for perror() that behaves more or less like emsg() was called.
* v:errmsg will be set and called_emsg will be incremented.
*/
void
do_perror(char *msg)
{
perror(msg);
++emsg_silent;
emsg(msg);
--emsg_silent;
}
#endif
/*
* emsg_core() - display an error message
*
* Rings the bell, if appropriate, and calls message() to do the real work
* When terminal not initialized (yet) mch_errmsg(..) is used.
*
* Return TRUE if wait_return() not called.
* Note: caller must check 'emsg_not_now()' before calling this.
*/
static int
emsg_core(const char *s)
{
int attr;
char_u *p;
int r;
#ifdef FEAT_EVAL
int ignore = FALSE;
int severe;
#endif
#ifdef FEAT_EVAL
// When testing some errors are turned into a normal message.
if (ignore_error(s))
// don't call msg() if it results in a dialog
return msg_use_printf() ? FALSE : msg((char *)s);
#endif
++called_emsg;
#ifdef FEAT_EVAL
// If "emsg_severe" is TRUE: When an error exception is to be thrown,
// prefer this message over previous messages for the same command.
severe = emsg_severe;
emsg_severe = FALSE;
#endif
if (!emsg_off || vim_strchr(p_debug, 't') != NULL)
{
#ifdef FEAT_EVAL
/*
* Cause a throw of an error exception if appropriate. Don't display
* the error message in this case. (If no matching catch clause will
* be found, the message will be displayed later on.) "ignore" is set
* when the message should be ignored completely (used for the
* interrupt message).
*/
if (cause_errthrow((char_u *)s, severe, &ignore) == TRUE)
{
if (!ignore)
++did_emsg;
return TRUE;
}
if (in_assert_fails && emsg_assert_fails_msg == NULL)
{
emsg_assert_fails_msg = vim_strsave((char_u *)s);
emsg_assert_fails_lnum = SOURCING_LNUM;
vim_free(emsg_assert_fails_context);
emsg_assert_fails_context = vim_strsave(
SOURCING_NAME == NULL ? (char_u *)"" : SOURCING_NAME);
}
// set "v:errmsg", also when using ":silent! cmd"
set_vim_var_string(VV_ERRMSG, (char_u *)s, -1);
#endif
/*
* When using ":silent! cmd" ignore error messages.
* But do write it to the redirection file.
*/
if (emsg_silent != 0)
{
#ifdef FEAT_EVAL
++did_emsg_silent;
#endif
if (emsg_noredir == 0)
{
msg_start();
p = get_emsg_source();
if (p != NULL)
{
STRCAT(p, "\n");
redir_write(p, -1);
vim_free(p);
}
p = get_emsg_lnum();
if (p != NULL)
{
STRCAT(p, "\n");
redir_write(p, -1);
vim_free(p);
}
redir_write((char_u *)s, -1);
}
#ifdef FEAT_EVAL
// Only increment did_emsg_def when :silent! wasn't used inside the
// :def function.
if (emsg_silent == emsg_silent_def)
++did_emsg_def;
#endif
#ifdef FEAT_EVAL
ch_log(NULL, "ERROR silent: %s", s);
#endif
return TRUE;
}
ex_exitval = 1;
// Reset msg_silent, an error causes messages to be switched back on.
msg_silent = 0;
cmd_silent = FALSE;
if (global_busy) // break :global command
++global_busy;
if (p_eb)
beep_flush(); // also includes flush_buffers()
else
flush_buffers(FLUSH_MINIMAL); // flush internal buffers
++did_emsg; // flag for DoOneCmd()
#ifdef FEAT_EVAL
++uncaught_emsg;
#endif
}
#ifdef HAS_MESSAGE_WINDOW
if (!in_echowindow)
#endif
emsg_on_display = TRUE; // remember there is an error message
attr = HL_ATTR(HLF_E); // set highlight mode for error messages
if (msg_scrolled != 0)
need_wait_return = TRUE; // needed in case emsg() is called after
// wait_return() has reset need_wait_return
// and a redraw is expected because
// msg_scrolled is non-zero
#ifdef FEAT_JOB_CHANNEL
emsg_to_channel_log = TRUE;
#endif
/*
* Display name and line number for the source of the error.
*/
msg_scroll = TRUE;
msg_source(attr);
/*
* Display the error message itself.
*/
msg_nowait = FALSE; // wait for this msg
r = msg_attr((char *)s, attr);
#ifdef FEAT_JOB_CHANNEL
emsg_to_channel_log = FALSE;
#endif
return r;
}
/*
* Print error message "s". Should already be translated.
* Return TRUE if wait_return() not called.
*/
int
emsg(char *s)
{
// Skip this if not giving error messages at the moment.
if (emsg_not_now())
return TRUE;
return emsg_core(s);
}
#ifndef PROTO // manual proto with __attribute__
/*
* Print error message "s" with format string and variable arguments.
* "s" should already be translated.
* Note: caller must not use "IObuff" for "s"!
* Return TRUE if wait_return() not called.
*/
int
semsg(const char *s, ...)
{
// Skip this if not giving error messages at the moment.
if (emsg_not_now())
return TRUE;
if (IObuff == NULL)
// Very early in initialisation and already something wrong, just
// give the raw message so the user at least gets a hint.
return emsg_core(s);
va_list ap;
va_start(ap, s);
vim_vsnprintf((char *)IObuff, IOSIZE, s, ap);
va_end(ap);
return emsg_core((char *)IObuff);
}
#endif
/*
* Same as emsg(...), but abort on error when ABORT_ON_INTERNAL_ERROR is
* defined. It is used for internal errors only, so that they can be
* detected when fuzzing vim.
*/
void
iemsg(char *s)
{
if (emsg_not_now())
return;
// Give a generic error which is translated. The error itself may not be
// translated, it almost never shows.
emsg_core(_(e_internal_error_please_report_a_bug));
emsg_core(s);
#if defined(ABORT_ON_INTERNAL_ERROR) && defined(FEAT_EVAL)
set_vim_var_string(VV_ERRMSG, (char_u *)s, -1);
msg_putchar('\n'); // avoid overwriting the error message
out_flush();
abort();
#endif
}
#ifndef PROTO // manual proto with __attribute__
/*
* Same as semsg(...) but abort on error when ABORT_ON_INTERNAL_ERROR is
* defined. It is used for internal errors only, so that they can be
* detected when fuzzing vim.
* Note: caller must not pass 'IObuff' as 1st argument.
*/
void
siemsg(const char *s, ...)
{
if (emsg_not_now())
return;
// Give a generic error which is translated. The error itself may not be
// translated, it almost never shows.
emsg_core(_(e_internal_error_please_report_a_bug));
if (IObuff == NULL)
{
// Very early in initialisation and already something wrong, just
// give the raw message so the user at least gets a hint.
emsg_core(s);
}
else
{
va_list ap;
va_start(ap, s);
vim_vsnprintf((char *)IObuff, IOSIZE, s, ap);
va_end(ap);
emsg_core((char *)IObuff);
}
# ifdef ABORT_ON_INTERNAL_ERROR
msg_putchar('\n'); // avoid overwriting the error message
out_flush();
abort();
# endif
}
#endif
/*
* Give an "Internal error" message.
*/
void
internal_error(char *where)
{
// Give a generic error which is translated. The error itself may not be
// translated, it almost never shows.
emsg_core(_(e_internal_error_please_report_a_bug));
siemsg(_(e_internal_error_str), where);
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Like internal_error() but do not call abort(), to avoid tests using
* test_unknown() and test_void() causing Vim to exit.
*/
void
internal_error_no_abort(char *where)
{
// Give a generic error which is translated. The error itself may not be
// translated, it almost never shows.
emsg_core(_(e_internal_error_please_report_a_bug));
semsg(_(e_internal_error_str), where);
}
#endif
// emsg3() and emsgn() are in misc2.c to avoid warnings for the prototypes.
void
emsg_invreg(int name)
{
semsg(_(e_invalid_register_name_str), transchar_buf(NULL, name));
}
#if defined(FEAT_EVAL) || defined(PROTO)
/*
* Give an error message which contains %s for "name[len]".
*/
void
emsg_namelen(char *msg, char_u *name, int len)
{
char_u *copy = vim_strnsave(name, len);
semsg(msg, copy == NULL ? "NULL" : (char *)copy);
vim_free(copy);
}
#endif
/*
* Like msg(), but truncate to a single line if p_shm contains 't', or when
* "force" is TRUE. This truncates in another way as for normal messages.
* Careful: The string may be changed by msg_may_trunc()!
* Returns a pointer to the printed message, if wait_return() not called.
*/
char *
msg_trunc_attr(char *s, int force, int attr)
{
int n;
char *ts;
// Add message to history before truncating
add_msg_hist((char_u *)s, -1, attr);
ts = (char *)msg_may_trunc(force, (char_u *)s);
msg_hist_off = TRUE;
n = msg_attr(ts, attr);
msg_hist_off = FALSE;
if (n)
return ts;
return NULL;
}
/*
* Check if message "s" should be truncated at the start (for filenames).
* Return a pointer to where the truncated message starts.
* Note: May change the message by replacing a character with '<'.
*/
char_u *
msg_may_trunc(int force, char_u *s)
{
int n;
int room;
// If 'cmdheight' is zero or something unexpected happened "room" may be
// negative.
room = (int)(Rows - cmdline_row - 1) * Columns + sc_col - 1;
if (room > 0 && (force || (shortmess(SHM_TRUNC) && !exmode_active))
&& (n = (int)STRLEN(s) - room) > 0)
{
if (has_mbyte)
{
int size = vim_strsize(s);
// There may be room anyway when there are multibyte chars.
if (size <= room)
return s;
for (n = 0; size >= room; )
{
size -= (*mb_ptr2cells)(s + n);
n += (*mb_ptr2len)(s + n);
}
--n;
}
s += n;
*s = '<';
}
return s;
}
static void
add_msg_hist(
char_u *s,
int len, // -1 for undetermined length
int attr)
{
struct msg_hist *p;
if (msg_hist_off || msg_silent != 0)
return;
// Don't let the message history get too big
while (msg_hist_len > MAX_MSG_HIST_LEN)
(void)delete_first_msg();
// allocate an entry and add the message at the end of the history
p = ALLOC_ONE(struct msg_hist);
if (p == NULL)
return;
if (len < 0)
len = (int)STRLEN(s);
// remove leading and trailing newlines
while (len > 0 && *s == '\n')
{
++s;
--len;
}
while (len > 0 && s[len - 1] == '\n')
--len;
p->msg = vim_strnsave(s, len);
p->next = NULL;
p->attr = attr;
if (last_msg_hist != NULL)
last_msg_hist->next = p;
last_msg_hist = p;
if (first_msg_hist == NULL)
first_msg_hist = last_msg_hist;
++msg_hist_len;
}
/*
* Delete the first (oldest) message from the history.
* Returns FAIL if there are no messages.
*/
int
delete_first_msg(void)
{
struct msg_hist *p;
if (msg_hist_len <= 0)
return FAIL;
p = first_msg_hist;
first_msg_hist = p->next;
if (first_msg_hist == NULL)
last_msg_hist = NULL; // history is empty
vim_free(p->msg);
vim_free(p);
--msg_hist_len;
return OK;
}
/*
* ":messages" command.
*/
void
ex_messages(exarg_T *eap)
{
struct msg_hist *p;
char_u *s;
int c = 0;
if (STRCMP(eap->arg, "clear") == 0)
{
int keep = eap->addr_count == 0 ? 0 : eap->line2;
while (msg_hist_len > keep)
(void)delete_first_msg();
return;
}
if (*eap->arg != NUL)
{
emsg(_(e_invalid_argument));
return;
}
msg_hist_off = TRUE;
p = first_msg_hist;
if (eap->addr_count != 0)
{
// Count total messages
for (; p != NULL && !got_int; p = p->next)
c++;
c -= eap->line2;
// Skip without number of messages specified
for (p = first_msg_hist; p != NULL && !got_int && c > 0;
p = p->next, c--);
}
if (p == first_msg_hist)
{
#ifdef FEAT_MULTI_LANG
s = get_mess_lang();
#else
s = mch_getenv((char_u *)"LANG");
#endif
if (s != NULL && *s != NUL)
// The next comment is extracted by xgettext and put in po file for
// translators to read.
msg_attr(
// Translator: Please replace the name and email address
// with the appropriate text for your translation.
_("Messages maintainer: The Vim Project"),
HL_ATTR(HLF_T));
}
// Display what was not skipped.
for (; p != NULL && !got_int; p = p->next)
if (p->msg != NULL)
msg_attr((char *)p->msg, p->attr);
msg_hist_off = FALSE;
}
#if defined(FEAT_CON_DIALOG) || defined(FIND_REPLACE_DIALOG) || defined(PROTO)
/*
* Call this after prompting the user. This will avoid a hit-return message
* and a delay.
*/
void
msg_end_prompt(void)
{
need_wait_return = FALSE;
emsg_on_display = FALSE;
cmdline_row = msg_row;
msg_col = 0;
msg_clr_eos();
lines_left = -1;
}
#endif
/*
* Wait for the user to hit a key (normally Enter).
* If "redraw" is TRUE, clear and redraw the screen.
* If "redraw" is FALSE, just redraw the screen.
* If "redraw" is -1, don't redraw at all.
*/
void
wait_return(int redraw)
{
int c;
int oldState;
int tmpState;
int had_got_int;
int save_reg_recording;
FILE *save_scriptout;
if (redraw == TRUE)
set_must_redraw(UPD_CLEAR);
// If using ":silent cmd", don't wait for a return. Also don't set
// need_wait_return to do it later.
if (msg_silent != 0)
return;
#ifdef HAS_MESSAGE_WINDOW
if (in_echowindow)
return;
#endif
/*
* When inside vgetc(), we can't wait for a typed character at all.
* With the global command (and some others) we only need one return at
* the end. Adjust cmdline_row to avoid the next message overwriting the
* last one.
*/
if (vgetc_busy > 0)
return;
need_wait_return = TRUE;
if (no_wait_return)
{
if (!exmode_active)
cmdline_row = msg_row;
return;
}
redir_off = TRUE; // don't redirect this message
oldState = State;
if (quit_more)
{
c = CAR; // just pretend CR was hit
quit_more = FALSE;
got_int = FALSE;
}
else if (exmode_active)
{
msg_puts(" "); // make sure the cursor is on the right line
c = CAR; // no need for a return in ex mode
got_int = FALSE;
}
else
{
// Make sure the hit-return prompt is on screen when 'guioptions' was
// just changed.
screenalloc(FALSE);
State = MODE_HITRETURN;
setmouse();
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; // disallow scrolling here
#endif
cmdline_row = msg_row;
// Avoid the sequence that the user types ":" at the hit-return prompt
// to start an Ex command, but the file-changed dialog gets in the
// way.
if (need_check_timestamps)
check_timestamps(FALSE);
hit_return_msg();
do
{
// Remember "got_int", if it is set vgetc() probably returns a
// CTRL-C, but we need to loop then.
had_got_int = got_int;
// Don't do mappings here, we put the character back in the
// typeahead buffer.
++no_mapping;
++allow_keys;
// Temporarily disable Recording. If Recording is active, the
// character will be recorded later, since it will be added to the
// typebuf after the loop
save_reg_recording = reg_recording;
save_scriptout = scriptout;
reg_recording = 0;
scriptout = NULL;
c = safe_vgetc();
if (had_got_int && !global_busy)
got_int = FALSE;
--no_mapping;
--allow_keys;
reg_recording = save_reg_recording;
scriptout = save_scriptout;
#ifdef FEAT_CLIPBOARD
// Strange way to allow copying (yanking) a modeless selection at
// the hit-enter prompt. Use CTRL-Y, because the same is used in
// Cmdline-mode and it's harmless when there is no selection.
if (c == Ctrl_Y && clip_star.state == SELECT_DONE)
{
clip_copy_modeless_selection(TRUE);
c = K_IGNORE;
}
#endif
/*
* Allow scrolling back in the messages.
* Also accept scroll-down commands when messages fill the screen,
* to avoid that typing one 'j' too many makes the messages
* disappear.
*/
if (p_more && !p_cp)
{
if (c == 'b' || c == 'k' || c == 'u' || c == 'g'
|| c == K_UP || c == K_PAGEUP)
{
if (msg_scrolled > Rows)
// scroll back to show older messages
do_more_prompt(c);
else
{
msg_didout = FALSE;
c = K_IGNORE;
msg_col =
#ifdef FEAT_RIGHTLEFT
cmdmsg_rl ? Columns - 1 :
#endif
0;
}
if (quit_more)
{
c = CAR; // just pretend CR was hit
quit_more = FALSE;
got_int = FALSE;
}
else if (c != K_IGNORE)
{
c = K_IGNORE;
hit_return_msg();
}
}
else if (msg_scrolled > Rows - 2
&& (c == 'j' || c == 'd' || c == 'f'
|| c == K_DOWN || c == K_PAGEDOWN))
c = K_IGNORE;
}
} while ((had_got_int && c == Ctrl_C)
|| c == K_IGNORE
#ifdef FEAT_GUI
|| c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR
#endif
|| c == K_LEFTDRAG || c == K_LEFTRELEASE
|| c == K_MIDDLEDRAG || c == K_MIDDLERELEASE
|| c == K_RIGHTDRAG || c == K_RIGHTRELEASE
|| c == K_MOUSELEFT || c == K_MOUSERIGHT
|| c == K_MOUSEDOWN || c == K_MOUSEUP
|| c == K_MOUSEMOVE
|| (!mouse_has(MOUSE_RETURN)
&& mouse_row < msg_row
&& (c == K_LEFTMOUSE
|| c == K_MIDDLEMOUSE
|| c == K_RIGHTMOUSE
|| c == K_X1MOUSE
|| c == K_X2MOUSE))
);
ui_breakcheck();
// Avoid that the mouse-up event causes Visual mode to start.
if (c == K_LEFTMOUSE || c == K_MIDDLEMOUSE || c == K_RIGHTMOUSE
|| c == K_X1MOUSE || c == K_X2MOUSE)
(void)jump_to_mouse(MOUSE_SETPOS, NULL, 0);
else if (vim_strchr((char_u *)"\r\n ", c) == NULL && c != Ctrl_C)
{
// Put the character back in the typeahead buffer. Don't use the
// stuff buffer, because lmaps wouldn't work.
ins_char_typebuf(vgetc_char, vgetc_mod_mask);
do_redraw = TRUE; // need a redraw even though there is
// typeahead
}
}
redir_off = FALSE;
/*
* If the user hits ':', '?' or '/' we get a command line from the next
* line.
*/
if (c == ':' || c == '?' || c == '/')
{
if (!exmode_active)
cmdline_row = msg_row;
skip_redraw = TRUE; // skip redraw once
do_redraw = FALSE;
#ifdef FEAT_TERMINAL
skip_term_loop = TRUE;
#endif
}
/*
* If the window size changed set_shellsize() will redraw the screen.
* Otherwise the screen is only redrawn if 'redraw' is set and no ':'
* typed.
*/
tmpState = State;
State = oldState; // restore State before set_shellsize
setmouse();
msg_check();
#if defined(UNIX) || defined(VMS)
/*
* When switching screens, we need to output an extra newline on exit.
*/
if (swapping_screen() && !termcap_active)
newline_on_exit = TRUE;
#endif
need_wait_return = FALSE;
did_wait_return = TRUE;
emsg_on_display = FALSE; // can delete error message now
lines_left = -1; // reset lines_left at next msg_start()
reset_last_sourcing();
if (keep_msg != NULL && vim_strsize(keep_msg) >=
(Rows - cmdline_row - 1) * Columns + sc_col)
VIM_CLEAR(keep_msg); // don't redisplay message, it's too long
if (tmpState == MODE_SETWSIZE) // got resize event while in vgetc()
{
starttermcap(); // start termcap before redrawing
shell_resized();
}
else if (!skip_redraw
&& (redraw == TRUE || (msg_scrolled != 0 && redraw != -1)))
{
starttermcap(); // start termcap before redrawing
redraw_later(UPD_VALID);
}
}
/*
* Write the hit-return prompt.
*/
static void
hit_return_msg(void)
{
int save_p_more = p_more;
p_more = FALSE; // don't want to see this message when scrolling back
if (msg_didout) // start on a new line
msg_putchar('\n');
if (got_int)
msg_puts(_("Interrupt: "));
msg_puts_attr(_("Press ENTER or type command to continue"), HL_ATTR(HLF_R));
if (!msg_use_printf())
msg_clr_eos();
p_more = save_p_more;
}
/*
* Set "keep_msg" to "s". Free the old value and check for NULL pointer.
*/
void
set_keep_msg(char_u *s, int attr)
{
vim_free(keep_msg);
if (s != NULL && msg_silent == 0)
keep_msg = vim_strsave(s);
else
keep_msg = NULL;
keep_msg_more = FALSE;
keep_msg_attr = attr;
}
/*
* If there currently is a message being displayed, set "keep_msg" to it, so
* that it will be displayed again after redraw.
*/
void
set_keep_msg_from_hist(void)
{
if (keep_msg == NULL && last_msg_hist != NULL && msg_scrolled == 0
&& (State & MODE_NORMAL))
set_keep_msg(last_msg_hist->msg, last_msg_hist->attr);
}
/*
* Prepare for outputting characters in the command line.
*/
void
msg_start(void)
{
int did_return = FALSE;
if (!msg_silent)
{
VIM_CLEAR(keep_msg);
need_fileinfo = FALSE;
}
#ifdef FEAT_EVAL
if (need_clr_eos)
{
// Halfway an ":echo" command and getting an (error) message: clear
// any text from the command.
need_clr_eos = FALSE;
msg_clr_eos();
}
#endif
#ifdef HAS_MESSAGE_WINDOW
if (in_echowindow)
{
if (popup_message_win_visible()
&& ((msg_col > 0 && (msg_scroll || !full_screen))
|| in_echowindow))
{
win_T *wp = popup_get_message_win();
// start a new line
curbuf = wp->w_buffer;
ml_append(wp->w_buffer->b_ml.ml_line_count,
(char_u *)"", (colnr_T)0, FALSE);
curbuf = curwin->w_buffer;
}
msg_col = 0;
}
else
#endif
if (!msg_scroll && full_screen) // overwrite last message
{
msg_row = cmdline_row;
msg_col =
#ifdef FEAT_RIGHTLEFT
cmdmsg_rl ? Columns - 1 :
#endif
0;
}
else if (msg_didout || in_echowindow)
{
// start message on next line
msg_putchar('\n');
did_return = TRUE;
if (exmode_active != EXMODE_NORMAL)
cmdline_row = msg_row;
}
if (!msg_didany || lines_left < 0)
msg_starthere();
if (msg_silent == 0)
{
msg_didout = FALSE; // no output on current line yet
cursor_off();
}
// when redirecting, may need to start a new line.
if (!did_return)
redir_write((char_u *)"\n", -1);
}
/*
* Note that the current msg position is where messages start.
*/
void
msg_starthere(void)
{
lines_left = cmdline_row;
msg_didany = FALSE;
}
void
msg_putchar(int c)
{
msg_putchar_attr(c, 0);
}
void
msg_putchar_attr(int c, int attr)
{
char_u buf[MB_MAXBYTES + 1];
if (IS_SPECIAL(c))
{
buf[0] = K_SPECIAL;
buf[1] = K_SECOND(c);
buf[2] = K_THIRD(c);
buf[3] = NUL;
}
else
buf[(*mb_char2bytes)(c, buf)] = NUL;
msg_puts_attr((char *)buf, attr);
}
void
msg_outnum(long n)
{
char buf[20];
sprintf(buf, "%ld", n);
msg_puts(buf);
}
void
msg_home_replace(char_u *fname)
{
msg_home_replace_attr(fname, 0);
}
#if defined(FEAT_FIND_ID) || defined(PROTO)
void
msg_home_replace_hl(char_u *fname)
{
msg_home_replace_attr(fname, HL_ATTR(HLF_D));
}
#endif
static void
msg_home_replace_attr(char_u *fname, int attr)
{
char_u *name;
name = home_replace_save(NULL, fname);
if (name != NULL)
msg_outtrans_attr(name, attr);
vim_free(name);
}
/*
* Output 'len' characters in 'str' (including NULs) with translation
* if 'len' is -1, output up to a NUL character.
* Use attributes 'attr'.
* Return the number of characters it takes on the screen.
*/
int
msg_outtrans(char_u *str)
{
return msg_outtrans_attr(str, 0);
}
int
msg_outtrans_attr(char_u *str, int attr)
{
return msg_outtrans_len_attr(str, (int)STRLEN(str), attr);
}
int
msg_outtrans_len(char_u *str, int len)
{
return msg_outtrans_len_attr(str, len, 0);
}
/*
* Output one character at "p". Return pointer to the next character.
* Handles multi-byte characters.
*/
char_u *
msg_outtrans_one(char_u *p, int attr)
{
int l;
if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
{
msg_outtrans_len_attr(p, l, attr);
return p + l;
}
msg_puts_attr((char *)transchar_byte_buf(NULL, *p), attr);
return p + 1;
}
int
msg_outtrans_len_attr(char_u *msgstr, int len, int attr)
{
int retval = 0;
char_u *str = msgstr;
char_u *plain_start = msgstr;
char_u *s;
int mb_l;
int c;
int save_got_int = got_int;
// Only quit when got_int was set in here.
got_int = FALSE;
// if MSG_HIST flag set, add message to history
if (attr & MSG_HIST)
{
add_msg_hist(str, len, attr);
attr &= ~MSG_HIST;
}
// When drawing over the command line no need to clear it later or remove
// the mode message.
if (msg_row >= cmdline_row && msg_col == 0)
{
clear_cmdline = FALSE;
mode_displayed = FALSE;
}
// If the string starts with a composing character first draw a space on
// which the composing char can be drawn.
if (enc_utf8 && utf_iscomposing(utf_ptr2char(msgstr)))
msg_puts_attr(" ", attr);
/*
* Go over the string. Special characters are translated and printed.
* Normal characters are printed several at a time.
*/
while (--len >= 0 && !got_int)
{
if (enc_utf8)
// Don't include composing chars after the end.
mb_l = utfc_ptr2len_len(str, len + 1);
else if (has_mbyte)
mb_l = (*mb_ptr2len)(str);
else
mb_l = 1;
if (has_mbyte && mb_l > 1)
{
c = (*mb_ptr2char)(str);
if (vim_isprintc(c))
// printable multi-byte char: count the cells.
retval += (*mb_ptr2cells)(str);
else
{
// unprintable multi-byte char: print the printable chars so
// far and the translation of the unprintable char.
if (str > plain_start)
msg_puts_attr_len((char *)plain_start,
(int)(str - plain_start), attr);
plain_start = str + mb_l;
msg_puts_attr((char *)transchar_buf(NULL, c),
attr == 0 ? HL_ATTR(HLF_8) : attr);
retval += char2cells(c);
}
len -= mb_l - 1;
str += mb_l;
}
else
{
s = transchar_byte_buf(NULL, *str);
if (s[1] != NUL)
{
// unprintable char: print the printable chars so far and the
// translation of the unprintable char.
if (str > plain_start)
msg_puts_attr_len((char *)plain_start,
(int)(str - plain_start), attr);
plain_start = str + 1;
msg_puts_attr((char *)s, attr == 0 ? HL_ATTR(HLF_8) : attr);
retval += (int)STRLEN(s);
}
else
++retval;
++str;
}
}
if (str > plain_start && !got_int)
// print the printable chars at the end
msg_puts_attr_len((char *)plain_start, (int)(str - plain_start), attr);
got_int |= save_got_int;
return retval;
}
#if defined(FEAT_QUICKFIX) || defined(PROTO)
void
msg_make(char_u *arg)
{
int i;
static char_u *str = (char_u *)"eeffoc", *rs = (char_u *)"Plon#dqg#vxjduB";
arg = skipwhite(arg);
for (i = 5; *arg && i >= 0; --i)
if (*arg++ != str[i])
break;
if (i < 0)
{
msg_putchar('\n');
for (i = 0; rs[i]; ++i)
msg_putchar(rs[i] - 3);
}
}
#endif
/*
* Output the string 'str' up to a NUL character.
* Return the number of characters it takes on the screen.
*
* If K_SPECIAL is encountered, then it is taken in conjunction with the
* following character and shown as <F1>, <S-Up> etc. Any other character
* which is not printable shown in <> form.
* If 'from' is TRUE (lhs of a mapping), a space is shown as <Space>.
* If a character is displayed in one of these special ways, is also
* highlighted (its highlight name is '8' in the p_hl variable).
* Otherwise characters are not highlighted.
* This function is used to show mappings, where we want to see how to type
* the character/string -- webb
*/
int
msg_outtrans_special(
char_u *strstart,
int from, // TRUE for lhs of a mapping
int maxlen) // screen columns, 0 for unlimited
{
char_u *str = strstart;
int retval = 0;
char *text;
int attr;
int len;
attr = HL_ATTR(HLF_8);
while (*str != NUL)
{
// Leading and trailing spaces need to be displayed in <> form.
if ((str == strstart || str[1] == NUL) && *str == ' ')
{
text = "<Space>";
++str;
}
else
text = (char *)str2special(&str, from, FALSE);
if (text[0] != NUL && text[1] == NUL)
// single-byte character or illegal byte
text = (char *)transchar_byte_buf(NULL, (char_u)text[0]);
len = vim_strsize((char_u *)text);
if (maxlen > 0 && retval + len >= maxlen)
break;
// Highlight special keys
msg_puts_attr(text, len > 1
&& (*mb_ptr2len)((char_u *)text) <= 1 ? attr : 0);
retval += len;
}
return retval;
}
#if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
/*
* Return the lhs or rhs of a mapping, with the key codes turned into printable
* strings, in an allocated string.
*/
char_u *
str2special_save(
char_u *str,
int replace_spaces, // TRUE to replace " " with "<Space>".
// used for the lhs of mapping and keytrans().
int replace_lt) // TRUE to replace "<" with "<lt>".
{
garray_T ga;
char_u *p = str;
ga_init2(&ga, 1, 40);
while (*p != NUL)
ga_concat(&ga, str2special(&p, replace_spaces, replace_lt));
ga_append(&ga, NUL);
return (char_u *)ga.ga_data;
}
#endif
/*
* Return the printable string for the key codes at "*sp".
* On illegal byte return a string with only that byte.
* Used for translating the lhs or rhs of a mapping to printable chars.
* Advances "sp" to the next code.
*/
char_u *
str2special(
char_u **sp,
int replace_spaces, // TRUE to replace " " with "<Space>".
// used for the lhs of mapping and keytrans().
int replace_lt) // TRUE to replace "<" with "<lt>".
{
int c;
static char_u buf[7];
char_u *str = *sp;
int modifiers = 0;
int special = FALSE;
if (has_mbyte)
{
char_u *p;
// Try to un-escape a multi-byte character. Return the un-escaped
// string if it is a multi-byte character.
p = mb_unescape(sp);
if (p != NULL)
return p;
}
c = *str;
if ((c == K_SPECIAL
#ifdef FEAT_GUI
|| c == CSI
#endif
) && str[1] != NUL && str[2] != NUL)
{
if (str[1] == KS_MODIFIER)
{
modifiers = str[2];
str += 3;
c = *str;
}
if ((c == K_SPECIAL
#ifdef FEAT_GUI
|| c == CSI
#endif
) && str[1] != NUL && str[2] != NUL)
{
c = TO_SPECIAL(str[1], str[2]);
str += 2;
}
if (IS_SPECIAL(c) || modifiers) // special key
special = TRUE;
}
if (has_mbyte && !IS_SPECIAL(c) && MB_BYTE2LEN(c) > 1)
{
char_u *p;
*sp = str;
// Try to un-escape a multi-byte character after modifiers.
p = mb_unescape(sp);
if (p != NULL)
// Since 'special' is TRUE the multi-byte character 'c' will be
// processed by get_special_key_name()
c = (*mb_ptr2char)(p);
else
// illegal byte
*sp = str + 1;
}
else
// single-byte character, NUL or illegal byte
*sp = str + (*str == NUL ? 0 : 1);
// Make special keys and C0 control characters in <> form, also <M-Space>.
if (special
|| c < ' '
|| (replace_spaces && c == ' ')
|| (replace_lt && c == '<'))
return get_special_key_name(c, modifiers);
buf[0] = c;
buf[1] = NUL;
return buf;
}
/*
* Translate a key sequence into special key names.
*/
void
str2specialbuf(char_u *sp, char_u *buf, int len)
{
char_u *s;
*buf = NUL;
while (*sp)
{
s = str2special(&sp, FALSE, FALSE);
if ((int)(STRLEN(s) + STRLEN(buf)) < len)
STRCAT(buf, s);
}
}
/*
* print line for :print or :list command
*/
void
msg_prt_line(char_u *s, int list)
{
int c;
int col = 0;
int n_extra = 0;
int c_extra = 0;
int c_final = 0;
char_u *p_extra = NULL; // init to make SASC shut up
int n;
int attr = 0;
char_u *trail = NULL;
char_u *lead = NULL;
int in_multispace = FALSE;
int multispace_pos = 0;
int l;
char_u buf[MB_MAXBYTES + 1];
if (curwin->w_p_list)
list = TRUE;
if (list)
{
// find start of trailing whitespace
if (curwin->w_lcs_chars.trail)
{
trail = s + STRLEN(s);
while (trail > s && VIM_ISWHITE(trail[-1]))
--trail;
}
// find end of leading whitespace
if (curwin->w_lcs_chars.lead
|| curwin->w_lcs_chars.leadmultispace != NULL)
{
lead = s;
while (VIM_ISWHITE(lead[0]))
lead++;
// in a line full of spaces all of them are treated as trailing
if (*lead == NUL)
lead = NULL;
}
}
// output a space for an empty line, otherwise the line will be
// overwritten
if (*s == NUL && !(list && curwin->w_lcs_chars.eol != NUL))
msg_putchar(' ');
while (!got_int)
{
if (n_extra > 0)
{
--n_extra;
if (n_extra == 0 && c_final)
c = c_final;
else if (c_extra)
c = c_extra;
else
c = *p_extra++;
}
else if (has_mbyte && (l = (*mb_ptr2len)(s)) > 1)
{
col += (*mb_ptr2cells)(s);
if (l >= MB_MAXBYTES)
{
STRCPY(buf, "?");
}
else if (curwin->w_lcs_chars.nbsp != NUL && list
&& (mb_ptr2char(s) == 160
|| mb_ptr2char(s) == 0x202f))
{
int len = mb_char2bytes(curwin->w_lcs_chars.nbsp, buf);
buf[len] = NUL;
}
else
{
mch_memmove(buf, s, (size_t)l);
buf[l] = NUL;
}
msg_puts((char *)buf);
s += l;
continue;
}
else
{
attr = 0;
c = *s++;
in_multispace = c == ' '
&& ((col > 0 && s[-2] == ' ') || *s == ' ');
if (!in_multispace)
multispace_pos = 0;
if (c == TAB && (!list || curwin->w_lcs_chars.tab1))
{
// tab amount depends on current column
#ifdef FEAT_VARTABS
n_extra = tabstop_padding(col, curbuf->b_p_ts,
curbuf->b_p_vts_array) - 1;
#else
n_extra = curbuf->b_p_ts - col % curbuf->b_p_ts - 1;
#endif
if (!list)
{
c = ' ';
c_extra = ' ';
c_final = NUL;
}
else
{
c = (n_extra == 0 && curwin->w_lcs_chars.tab3)
? curwin->w_lcs_chars.tab3
: curwin->w_lcs_chars.tab1;
c_extra = curwin->w_lcs_chars.tab2;
c_final = curwin->w_lcs_chars.tab3;
attr = HL_ATTR(HLF_8);
}
}
else if (c == 160 && list && curwin->w_lcs_chars.nbsp != NUL)
{
c = curwin->w_lcs_chars.nbsp;
attr = HL_ATTR(HLF_8);
}
else if (c == NUL && list && curwin->w_lcs_chars.eol != NUL)
{
p_extra = (char_u *)"";
c_extra = NUL;
c_final = NUL;
n_extra = 1;
c = curwin->w_lcs_chars.eol;
attr = HL_ATTR(HLF_AT);
--s;
}
else if (c != NUL && (n = byte2cells(c)) > 1)
{
n_extra = n - 1;
p_extra = transchar_byte_buf(NULL, c);
c_extra = NUL;
c_final = NUL;
c = *p_extra++;
// Use special coloring to be able to distinguish <hex> from
// the same in plain text.
attr = HL_ATTR(HLF_8);
}
else if (c == ' ')
{
if (list && lead != NULL && s <= lead && in_multispace
&& curwin->w_lcs_chars.leadmultispace != NULL)
{
c = curwin->w_lcs_chars.leadmultispace[multispace_pos++];
if (curwin->w_lcs_chars.leadmultispace[multispace_pos]
== NUL)
multispace_pos = 0;
attr = HL_ATTR(HLF_8);
}
else if (lead != NULL && s <= lead
&& curwin->w_lcs_chars.lead != NUL)
{
c = curwin->w_lcs_chars.lead;
attr = HL_ATTR(HLF_8);
}
else if (trail != NULL && s > trail)
{
c = curwin->w_lcs_chars.trail;
attr = HL_ATTR(HLF_8);
}
else if (list && in_multispace
&& curwin->w_lcs_chars.multispace != NULL)
{
c = curwin->w_lcs_chars.multispace[multispace_pos++];
if (curwin->w_lcs_chars.multispace[multispace_pos] == NUL)
multispace_pos = 0;
attr = HL_ATTR(HLF_8);
}
else if (list && curwin->w_lcs_chars.space != NUL)
{
c = curwin->w_lcs_chars.space;
attr = HL_ATTR(HLF_8);
}
}
}
if (c == NUL)
break;
msg_putchar_attr(c, attr);
col++;
}
msg_clr_eos();
}
/*
* Use screen_puts() to output one multi-byte character.
* Return the pointer "s" advanced to the next character.
*/
static char_u *
screen_puts_mbyte(char_u *s, int l, int attr)
{
int cw;
msg_didout = TRUE; // remember that line is not empty
cw = (*mb_ptr2cells)(s);
if (cw > 1 && (
#ifdef FEAT_RIGHTLEFT
cmdmsg_rl ? msg_col <= 1 :
#endif
msg_col == Columns - 1))
{
// Doesn't fit, print a highlighted '>' to fill it up.
msg_screen_putchar('>', HL_ATTR(HLF_AT));
return s;
}
screen_puts_len(s, l, msg_row, msg_col, attr);
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
{
msg_col -= cw;
if (msg_col == 0)
{
msg_col = Columns;
++msg_row;
}
}
else
#endif
{
msg_col += cw;
if (msg_col >= Columns)
{
msg_col = 0;
++msg_row;
}
}
return s + l;
}
/*
* Output a string to the screen at position msg_row, msg_col.
* Update msg_row and msg_col for the next message.
*/
void
msg_puts(char *s)
{
msg_puts_attr(s, 0);
}
void
msg_puts_title(char *s)
{
msg_puts_attr(s, HL_ATTR(HLF_T));
}
/*
* Show a message in such a way that it always fits in the line. Cut out a
* part in the middle and replace it with "..." when necessary.
* Does not handle multi-byte characters!
*/
static void
msg_outtrans_long_len_attr(char_u *longstr, int len, int attr)
{
int slen = len;
int room;
room = Columns - msg_col;
if (len > room && room >= 20)
{
slen = (room - 3) / 2;
msg_outtrans_len_attr(longstr, slen, attr);
msg_puts_attr("...", HL_ATTR(HLF_8));
}
msg_outtrans_len_attr(longstr + len - slen, slen, attr);
}
void
msg_outtrans_long_attr(char_u *longstr, int attr)
{
msg_outtrans_long_len_attr(longstr, (int)STRLEN(longstr), attr);
}
/*
* Basic function for writing a message with highlight attributes.
*/
void
msg_puts_attr(char *s, int attr)
{
msg_puts_attr_len(s, -1, attr);
}
/*
* Like msg_puts_attr(), but with a maximum length "maxlen" (in bytes).
* When "maxlen" is -1 there is no maximum length.
* When "maxlen" is >= 0 the message is not put in the history.
*/
static void
msg_puts_attr_len(char *str, int maxlen, int attr)
{
/*
* If redirection is on, also write to the redirection file.
*/
redir_write((char_u *)str, maxlen);
/*
* Don't print anything when using ":silent cmd".
*/
if (msg_silent != 0)
return;
// if MSG_HIST flag set, add message to history
if ((attr & MSG_HIST) && maxlen < 0)
{
add_msg_hist((char_u *)str, -1, attr);
attr &= ~MSG_HIST;
}
// When writing something to the screen after it has scrolled, requires a
// wait-return prompt later. Needed when scrolling, resetting
// need_wait_return after some prompt, and then outputting something
// without scrolling
// Not needed when only using CR to move the cursor.
if (msg_scrolled != 0 && !msg_scrolled_ign && STRCMP(str, "\r") != 0)
need_wait_return = TRUE;
msg_didany = TRUE; // remember that something was outputted
/*
* If there is no valid screen, use fprintf so we can see error messages.
* If termcap is not active, we may be writing in an alternate console
* window, cursor positioning may not work correctly (window size may be
* different, e.g. for Win32 console) or we just don't know where the
* cursor is.
*/
if (msg_use_printf())
msg_puts_printf((char_u *)str, maxlen);
else
msg_puts_display((char_u *)str, maxlen, attr, FALSE);
need_fileinfo = FALSE;
}
// values for "where"
#define PUT_APPEND 0 // append to "lnum"
#define PUT_TRUNC 1 // replace "lnum"
#define PUT_BELOW 2 // add below "lnum"
//
#ifdef HAS_MESSAGE_WINDOW
/*
* Put text "t_s" until "end" in the message window.
* "where" specifies where to put the text.
*/
static void
put_msg_win(win_T *wp, int where, char_u *t_s, char_u *end, linenr_T lnum)
{
char_u *p;
if (where == PUT_BELOW)
{
if (*end != NUL)
{
p = vim_strnsave(t_s, end - t_s);
if (p == NULL)
return;
}
else
p = t_s;
ml_append_buf(wp->w_buffer, lnum, p, (colnr_T)0, FALSE);
if (p != t_s)
vim_free(p);
}
else
{
char_u *newp;
curbuf = wp->w_buffer;
if (where == PUT_APPEND)
{
newp = concat_str(ml_get(lnum), t_s);
if (newp == NULL)
return;
if (*end != NUL)
newp[STRLEN(ml_get(lnum)) + (end - t_s)] = NUL;
}
else
{
newp = vim_strnsave(t_s, end - t_s);
if (newp == NULL)
return;
}
ml_replace(lnum, newp, FALSE);
curbuf = curwin->w_buffer;
}
redraw_win_later(wp, UPD_NOT_VALID);
// set msg_col so that a newline is written if needed
msg_col += (int)(end - t_s);
}
#endif
/*
* The display part of msg_puts_attr_len().
* May be called recursively to display scroll-back text.
*/
static void
msg_puts_display(
char_u *str,
int maxlen,
int attr,
int recurse)
{
char_u *s = str;
char_u *t_s = str; // string from "t_s" to "s" is still todo
int t_col = 0; // screen cells todo, 0 when "t_s" not used
int l;
int cw;
char_u *sb_str = str;
int sb_col = msg_col;
int wrap;
int did_last_char;
#ifdef HAS_MESSAGE_WINDOW
int where = PUT_APPEND;
win_T *msg_win = NULL;
linenr_T lnum = 1;
if (in_echowindow)
{
msg_win = popup_get_message_win();
if (msg_win != NULL)
{
if (!popup_message_win_visible())
{
if (*str == NL)
{
// When not showing the message window and the output
// starts with a NL show the message normally.
msg_win = NULL;
}
else
{
// currently hidden, make it empty
curbuf = msg_win->w_buffer;
while ((curbuf->b_ml.ml_flags & ML_EMPTY) == 0)
ml_delete(1);
curbuf = curwin->w_buffer;
}
}
else
{
lnum = msg_win->w_buffer->b_ml.ml_line_count;
if (msg_col == 0)
where = PUT_TRUNC;
}
}
}
#endif
did_wait_return = FALSE;
while ((maxlen < 0 || (int)(s - str) < maxlen) && *s != NUL)
{
/*
* We are at the end of the screen line when:
* - When outputting a newline.
* - When outputting a character in the last column.
*/
if (!recurse && msg_row >= Rows - 1 && (*s == '\n' || (
#ifdef FEAT_RIGHTLEFT
cmdmsg_rl
? (
msg_col <= 1
|| (*s == TAB && msg_col <= 7)
|| (has_mbyte && (*mb_ptr2cells)(s) > 1 && msg_col <= 2))
:
#endif
((*s != '\r' && msg_col + t_col >= Columns - 1)
|| (*s == TAB && msg_col + t_col >= ((Columns - 1) & ~7))
|| (has_mbyte && (*mb_ptr2cells)(s) > 1
&& msg_col + t_col >= Columns - 2)))))
{
/*
* The screen is scrolled up when at the last row (some terminals
* scroll automatically, some don't. To avoid problems we scroll
* ourselves).
*/
if (t_col > 0)
{
// output postponed text
#ifdef HAS_MESSAGE_WINDOW
if (msg_win != NULL)
{
put_msg_win(msg_win, where, t_s, s, lnum);
t_col = 0;
where = PUT_BELOW;
}
else
#endif
t_puts(&t_col, t_s, s, attr);
}
// When no more prompt and no more room, truncate here
if (msg_no_more && lines_left == 0)
break;
#ifdef HAS_MESSAGE_WINDOW
if (msg_win == NULL)
#endif
// Scroll the screen up one line.
msg_scroll_up();
msg_row = Rows - 2;
if (msg_col >= Columns) // can happen after screen resize
msg_col = Columns - 1;
// Display char in last column before showing more-prompt.
if (*s >= ' '
#ifdef FEAT_RIGHTLEFT
&& !cmdmsg_rl
#endif
)
{
if (has_mbyte)
{
if (enc_utf8 && maxlen >= 0)
// avoid including composing chars after the end
l = utfc_ptr2len_len(s, (int)((str + maxlen) - s));
else
l = (*mb_ptr2len)(s);
s = screen_puts_mbyte(s, l, attr);
}
else
msg_screen_putchar(*s++, attr);
did_last_char = TRUE;
}
else
did_last_char = FALSE;
if (p_more)
// store text for scrolling back
store_sb_text(&sb_str, s, attr, &sb_col, TRUE);
#ifdef HAS_MESSAGE_WINDOW
if (msg_win == NULL)
{
#endif
inc_msg_scrolled();
need_wait_return = TRUE; // may need wait_return() in main()
redraw_cmdline = TRUE;
if (cmdline_row > 0 && !exmode_active)
--cmdline_row;
/*
* If screen is completely filled and 'more' is set then wait
* for a character.
*/
if (lines_left > 0)
--lines_left;
#ifdef HAS_MESSAGE_WINDOW
}
#endif
if (p_more && lines_left == 0 && State != MODE_HITRETURN
&& !msg_no_more && !exmode_active)
{
#ifdef FEAT_CON_DIALOG
if (do_more_prompt(NUL))
s = confirm_msg_tail;
#else
(void)do_more_prompt(NUL);
#endif
if (quit_more)
return;
}
// When we displayed a char in last column need to check if there
// is still more.
if (did_last_char)
continue;
}
wrap = *s == '\n'
|| msg_col + t_col >= Columns
|| (has_mbyte && (*mb_ptr2cells)(s) > 1
&& msg_col + t_col >= Columns - 1);
if (t_col > 0 && (wrap || *s == '\r' || *s == '\b'
|| *s == '\t' || *s == BELL))
{
// output any postponed text
#ifdef HAS_MESSAGE_WINDOW
if (msg_win != NULL)
{
put_msg_win(msg_win, where, t_s, s, lnum);
t_col = 0;
where = PUT_BELOW;
}
else
#endif
t_puts(&t_col, t_s, s, attr);
}
if (wrap && p_more && !recurse)
// store text for scrolling back
store_sb_text(&sb_str, s, attr, &sb_col, TRUE);
if (*s == '\n') // go to next line
{
#ifdef HAS_MESSAGE_WINDOW
if (msg_win != NULL)
{
// Ignore a NL when the buffer is empty, it is used to scroll
// up the text.
if ((msg_win->w_buffer->b_ml.ml_flags & ML_EMPTY) == 0)
{
put_msg_win(msg_win, PUT_BELOW, t_s, t_s, lnum);
++lnum;
}
}
else
#endif
msg_didout = FALSE; // remember that line is empty
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
msg_col = Columns - 1;
else
#endif
msg_col = 0;
if (++msg_row >= Rows) // safety check
msg_row = Rows - 1;
}
else if (*s == '\r') // go to column 0
{
msg_col = 0;
#ifdef HAS_MESSAGE_WINDOW
where = PUT_TRUNC;
#endif
}
else if (*s == '\b') // go to previous char
{
if (msg_col)
--msg_col;
}
else if (*s == TAB) // translate Tab into spaces
{
#ifdef HAS_MESSAGE_WINDOW
if (msg_win != NULL)
msg_col = (msg_col + 7) % 8;
else
#endif
do
msg_screen_putchar(' ', attr);
while (msg_col & 7);
}
else if (*s == BELL) // beep (from ":sh")
vim_beep(BO_SH);
else
{
if (has_mbyte)
{
cw = (*mb_ptr2cells)(s);
if (enc_utf8 && maxlen >= 0)
// avoid including composing chars after the end
l = utfc_ptr2len_len(s, (int)((str + maxlen) - s));
else
l = (*mb_ptr2len)(s);
}
else
{
cw = 1;
l = 1;
}
// When drawing from right to left or when a double-wide character
// doesn't fit, draw a single character here. Otherwise collect
// characters and draw them all at once later.
if (
# ifdef FEAT_RIGHTLEFT
cmdmsg_rl ||
# endif
(cw > 1 && msg_col + t_col >= Columns - 1))
{
if (l > 1)
s = screen_puts_mbyte(s, l, attr) - 1;
else
msg_screen_putchar(*s, attr);
}
else
{
// postpone this character until later
if (t_col == 0)
t_s = s;
t_col += cw;
s += l - 1;
}
}
++s;
}
// output any postponed text
if (t_col > 0)
{
#ifdef HAS_MESSAGE_WINDOW
if (msg_win != NULL)
put_msg_win(msg_win, where, t_s, s, lnum);
else
#endif
t_puts(&t_col, t_s, s, attr);
}
#ifdef HAS_MESSAGE_WINDOW
if (msg_win != NULL)
popup_show_message_win();
#endif
// Store the text for scroll back, unless it's a newline by itself.
if (p_more && !recurse && !(s == sb_str + 1 && *sb_str == '\n'))
store_sb_text(&sb_str, s, attr, &sb_col, FALSE);
msg_check();
}
/*
* Return TRUE when ":filter pattern" was used and "msg" does not match
* "pattern".
*/
int
message_filtered(char_u *msg)
{
int match;
if (cmdmod.cmod_filter_regmatch.regprog == NULL)
return FALSE;
match = vim_regexec(&cmdmod.cmod_filter_regmatch, msg, (colnr_T)0);
return cmdmod.cmod_filter_force ? match : !match;
}
/*
* Scroll the screen up one line for displaying the next message line.
*/
static void
msg_scroll_up(void)
{
#ifdef HAS_MESSAGE_WINDOW
if (in_echowindow)
return;
#endif
#ifdef FEAT_GUI
// Remove the cursor before scrolling, ScreenLines[] is going
// to become invalid.
if (gui.in_use)
gui_undraw_cursor();
#endif
// scrolling up always works
mch_disable_flush();
screen_del_lines(0, 0, 1, (int)Rows, TRUE, 0, NULL);
mch_enable_flush();
if (!can_clear((char_u *)" "))
{
// Scrolling up doesn't result in the right background. Set the
// background here. It's not efficient, but avoids that we have to do
// it all over the code.
screen_fill((int)Rows - 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
// Also clear the last char of the last but one line if it was not
// cleared before to avoid a scroll-up.
if (ScreenAttrs[LineOffset[Rows - 2] + Columns - 1] == (sattr_T)-1)
screen_fill((int)Rows - 2, (int)Rows - 1,
(int)Columns - 1, (int)Columns, ' ', ' ', 0);
}
}
/*
* Increment "msg_scrolled".
*/
static void
inc_msg_scrolled(void)
{
#ifdef FEAT_EVAL
if (*get_vim_var_str(VV_SCROLLSTART) == NUL)
{
char_u *p = SOURCING_NAME;
char_u *tofree = NULL;
int len;
// v:scrollstart is empty, set it to the script/function name and line
// number
if (p == NULL)
p = (char_u *)_("Unknown");
else
{
len = (int)STRLEN(p) + 40;
tofree = alloc(len);
if (tofree != NULL)
{
vim_snprintf((char *)tofree, len, _("%s line %ld"),
p, (long)SOURCING_LNUM);
p = tofree;
}
}
set_vim_var_string(VV_SCROLLSTART, p, -1);
vim_free(tofree);
}
#endif
++msg_scrolled;
set_must_redraw(UPD_VALID);
}
/*
* To be able to scroll back at the "more" and "hit-enter" prompts we need to
* store the displayed text and remember where screen lines start.
*/
typedef struct msgchunk_S msgchunk_T;
struct msgchunk_S
{
msgchunk_T *sb_next;
msgchunk_T *sb_prev;
char sb_eol; // TRUE when line ends after this text
int sb_msg_col; // column in which text starts
int sb_attr; // text attributes
char_u sb_text[1]; // text to be displayed, actually longer
};
static msgchunk_T *last_msgchunk = NULL; // last displayed text
static msgchunk_T *msg_sb_start(msgchunk_T *mps);
typedef enum {
SB_CLEAR_NONE = 0,
SB_CLEAR_ALL,
SB_CLEAR_CMDLINE_BUSY,
SB_CLEAR_CMDLINE_DONE
} sb_clear_T;
// When to clear text on next msg.
static sb_clear_T do_clear_sb_text = SB_CLEAR_NONE;
/*
* Store part of a printed message for displaying when scrolling back.
*/
static void
store_sb_text(
char_u **sb_str, // start of string
char_u *s, // just after string
int attr,
int *sb_col,
int finish) // line ends
{
msgchunk_T *mp;
if (do_clear_sb_text == SB_CLEAR_ALL
|| do_clear_sb_text == SB_CLEAR_CMDLINE_DONE)
{
clear_sb_text(do_clear_sb_text == SB_CLEAR_ALL);
msg_sb_eol(); // prevent messages from overlapping
do_clear_sb_text = SB_CLEAR_NONE;
}
if (s > *sb_str)
{
mp = alloc(offsetof(msgchunk_T, sb_text) + (s - *sb_str) + 1);
if (mp != NULL)
{
mp->sb_eol = finish;
mp->sb_msg_col = *sb_col;
mp->sb_attr = attr;
vim_strncpy(mp->sb_text, *sb_str, s - *sb_str);
if (last_msgchunk == NULL)
{
last_msgchunk = mp;
mp->sb_prev = NULL;
}
else
{
mp->sb_prev = last_msgchunk;
last_msgchunk->sb_next = mp;
last_msgchunk = mp;
}
mp->sb_next = NULL;
}
}
else if (finish && last_msgchunk != NULL)
last_msgchunk->sb_eol = TRUE;
*sb_str = s;
*sb_col = 0;
}
/*
* Finished showing messages, clear the scroll-back text on the next message.
*/
void
may_clear_sb_text(void)
{
do_clear_sb_text = SB_CLEAR_ALL;
}
/*
* Starting to edit the command line: do not clear messages now.
*/
void
sb_text_start_cmdline(void)
{
if (do_clear_sb_text == SB_CLEAR_CMDLINE_BUSY)
// Invoking command line recursively: the previous-level command line
// doesn't need to be remembered as it will be redrawn when returning
// to that level.
sb_text_restart_cmdline();
else
{
msg_sb_eol();
do_clear_sb_text = SB_CLEAR_CMDLINE_BUSY;
}
}
/*
* Redrawing the command line: clear the last unfinished line.
*/
void
sb_text_restart_cmdline(void)
{
msgchunk_T *tofree;
// Needed when returning from nested command line.
do_clear_sb_text = SB_CLEAR_CMDLINE_BUSY;
if (last_msgchunk == NULL || last_msgchunk->sb_eol)
// No unfinished line: don't clear anything.
return;
tofree = msg_sb_start(last_msgchunk);
last_msgchunk = tofree->sb_prev;
if (last_msgchunk != NULL)
last_msgchunk->sb_next = NULL;
while (tofree != NULL)
{
msgchunk_T *tofree_next = tofree->sb_next;
vim_free(tofree);
tofree = tofree_next;
}
}
/*
* Ending to edit the command line: clear old lines but the last one later.
*/
void
sb_text_end_cmdline(void)
{
do_clear_sb_text = SB_CLEAR_CMDLINE_DONE;
}
/*
* Clear any text remembered for scrolling back.
* When "all" is FALSE keep the last line.
* Called when redrawing the screen.
*/
void
clear_sb_text(int all)
{
msgchunk_T *mp;
msgchunk_T **lastp;
if (all)
lastp = &last_msgchunk;
else
{
if (last_msgchunk == NULL)
return;
lastp = &msg_sb_start(last_msgchunk)->sb_prev;
}
while (*lastp != NULL)
{
mp = (*lastp)->sb_prev;
vim_free(*lastp);
*lastp = mp;
}
}
/*
* "g<" command.
*/
void
show_sb_text(void)
{
msgchunk_T *mp;
// Only show something if there is more than one line, otherwise it looks
// weird, typing a command without output results in one line.
mp = msg_sb_start(last_msgchunk);
if (mp == NULL || mp->sb_prev == NULL)
vim_beep(BO_MESS);
else
{
do_more_prompt('G');
wait_return(FALSE);
}
}
/*
* Move to the start of screen line in already displayed text.
*/
static msgchunk_T *
msg_sb_start(msgchunk_T *mps)
{
msgchunk_T *mp = mps;
while (mp != NULL && mp->sb_prev != NULL && !mp->sb_prev->sb_eol)
mp = mp->sb_prev;
return mp;
}
/*
* Mark the last message chunk as finishing the line.
*/
void
msg_sb_eol(void)
{
if (last_msgchunk != NULL)
last_msgchunk->sb_eol = TRUE;
}
/*
* Display a screen line from previously displayed text at row "row".
* When "clear_to_eol" is set clear the rest of the screen line.
* Returns a pointer to the text for the next line (can be NULL).
*/
static msgchunk_T *
disp_sb_line(int row, msgchunk_T *smp, int clear_to_eol)
{
msgchunk_T *mp = smp;
char_u *p;
for (;;)
{
msg_row = row;
msg_col = mp->sb_msg_col;
p = mp->sb_text;
if (*p == '\n') // don't display the line break
++p;
msg_puts_display(p, -1, mp->sb_attr, TRUE);
// If clearing the screen did not work (e.g. because of a background
// color and t_ut isn't set) clear until the last column here.
if (clear_to_eol)
screen_fill(row, row + 1, msg_col, (int)Columns, ' ', ' ', 0);
if (mp->sb_eol || mp->sb_next == NULL)
break;
mp = mp->sb_next;
}
return mp->sb_next;
}
/*
* Output any postponed text for msg_puts_attr_len().
*/
static void
t_puts(
int *t_col,
char_u *t_s,
char_u *s,
int attr)
{
// output postponed text
msg_didout = TRUE; // remember that line is not empty
screen_puts_len(t_s, (int)(s - t_s), msg_row, msg_col, attr);
msg_col += *t_col;
*t_col = 0;
// If the string starts with a composing character don't increment the
// column position for it.
if (enc_utf8 && utf_iscomposing(utf_ptr2char(t_s)))
--msg_col;
if (msg_col >= Columns)
{
msg_col = 0;
++msg_row;
}
}
/*
* Returns TRUE when messages should be printed with mch_errmsg().
* This is used when there is no valid screen, so we can see error messages.
* If termcap is not active, we may be writing in an alternate console
* window, cursor positioning may not work correctly (window size may be
* different, e.g. for Win32 console) or we just don't know where the
* cursor is.
*/
int
msg_use_printf(void)
{
return (!msg_check_screen()
#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
# ifdef VIMDLL
|| (!gui.in_use && !termcap_active)
# else
|| !termcap_active
# endif
#endif
|| (swapping_screen() && !termcap_active)
);
}
/*
* Print a message when there is no valid screen.
*/
static void
msg_puts_printf(char_u *str, int maxlen)
{
char_u *s = str;
char_u *buf = NULL;
char_u *p = s;
#ifdef MSWIN
if (!(silent_mode && p_verbose == 0))
mch_settmode(TMODE_COOK); // handle CR and NL correctly
#endif
while ((maxlen < 0 || (int)(s - str) < maxlen) && *s != NUL)
{
if (!(silent_mode && p_verbose == 0))
{
// NL --> CR NL translation (for Unix, not for "--version")
if (*s == NL)
{
int n = (int)(s - p);
buf = alloc(n + 3);
if (buf != NULL)
{
memcpy(buf, p, n);
if (!info_message)
buf[n++] = CAR;
buf[n++] = NL;
buf[n++] = NUL;
if (info_message) // informative message, not an error
mch_msg((char *)buf);
else
mch_errmsg((char *)buf);
vim_free(buf);
}
p = s + 1;
}
}
// primitive way to compute the current column
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
{
if (*s == CAR || *s == NL)
msg_col = Columns - 1;
else
--msg_col;
}
else
#endif
{
if (*s == CAR || *s == NL)
msg_col = 0;
else
++msg_col;
}
++s;
}
if (*p != NUL && !(silent_mode && p_verbose == 0))
{
char_u *tofree = NULL;
if (maxlen > 0 && vim_strlen_maxlen((char *)p, (size_t)maxlen)
>= (size_t)maxlen)
{
tofree = vim_strnsave(p, (size_t)maxlen);
p = tofree;
}
if (p != NULL)
{
if (info_message)
mch_msg((char *)p);
else
mch_errmsg((char *)p);
vim_free(tofree);
}
}
msg_didout = TRUE; // assume that line is not empty
#ifdef MSWIN
if (!(silent_mode && p_verbose == 0))
mch_settmode(TMODE_RAW);
#endif
}
/*
* Show the more-prompt and handle the user response.
* This takes care of scrolling back and displaying previously displayed text.
* When at hit-enter prompt "typed_char" is the already typed character,
* otherwise it's NUL.
* Returns TRUE when jumping ahead to "confirm_msg_tail".
*/
static int
do_more_prompt(int typed_char)
{
static int entered = FALSE;
int used_typed_char = typed_char;
int oldState = State;
int c;
#ifdef FEAT_CON_DIALOG
int retval = FALSE;
#endif
int toscroll;
msgchunk_T *mp_last = NULL;
msgchunk_T *mp;
int i;
// We get called recursively when a timer callback outputs a message. In
// that case don't show another prompt. Also when at the hit-Enter prompt
// and nothing was typed.
if (entered || (State == MODE_HITRETURN && typed_char == 0))
return FALSE;
entered = TRUE;
if (typed_char == 'G')
{
// "g<": Find first line on the last page.
mp_last = msg_sb_start(last_msgchunk);
for (i = 0; i < Rows - 2 && mp_last != NULL
&& mp_last->sb_prev != NULL; ++i)
mp_last = msg_sb_start(mp_last->sb_prev);
}
State = MODE_ASKMORE;
setmouse();
if (typed_char == NUL)
msg_moremsg(FALSE);
for (;;)
{
/*
* Get a typed character directly from the user.
*/
if (used_typed_char != NUL)
{
c = used_typed_char; // was typed at hit-enter prompt
used_typed_char = NUL;
}
else
c = get_keystroke();
#if defined(FEAT_MENU) && defined(FEAT_GUI)
if (c == K_MENU)
{
int idx = get_menu_index(current_menu, MODE_ASKMORE);
// Used a menu. If it starts with CTRL-Y, it must
// be a "Copy" for the clipboard. Otherwise
// assume that we end
if (idx == MENU_INDEX_INVALID)
continue;
c = *current_menu->strings[idx];
if (c != NUL && current_menu->strings[idx][1] != NUL)
ins_typebuf(current_menu->strings[idx] + 1,
current_menu->noremap[idx], 0, TRUE,
current_menu->silent[idx]);
}
#endif
toscroll = 0;
switch (c)
{
case BS: // scroll one line back
case K_BS:
case 'k':
case K_UP:
toscroll = -1;
break;
case CAR: // one extra line
case NL:
case 'j':
case K_DOWN:
toscroll = 1;
break;
case 'u': // Up half a page
toscroll = -(Rows / 2);
break;
case 'd': // Down half a page
toscroll = Rows / 2;
break;
case 'b': // one page back
case K_PAGEUP:
toscroll = -(Rows - 1);
break;
case ' ': // one extra page
case 'f':
case K_PAGEDOWN:
case K_LEFTMOUSE:
toscroll = Rows - 1;
break;
case 'g': // all the way back to the start
toscroll = -999999;
break;
case 'G': // all the way to the end
toscroll = 999999;
lines_left = 999999;
break;
case ':': // start new command line
#ifdef FEAT_CON_DIALOG
if (!confirm_msg_used)
#endif
{
// Since got_int is set all typeahead will be flushed, but we
// want to keep this ':', remember that in a special way.
typeahead_noflush(':');
#ifdef FEAT_TERMINAL
skip_term_loop = TRUE;
#endif
cmdline_row = Rows - 1; // put ':' on this line
skip_redraw = TRUE; // skip redraw once
need_wait_return = FALSE; // don't wait in main()
}
// FALLTHROUGH
case 'q': // quit
case Ctrl_C:
case ESC:
#ifdef FEAT_CON_DIALOG
if (confirm_msg_used)
{
// Jump to the choices of the dialog.
retval = TRUE;
}
else
#endif
{
got_int = TRUE;
quit_more = TRUE;
}
// When there is some more output (wrapping line) display that
// without another prompt.
lines_left = Rows - 1;
break;
#ifdef FEAT_CLIPBOARD
case Ctrl_Y:
// Strange way to allow copying (yanking) a modeless
// selection at the more prompt. Use CTRL-Y,
// because the same is used in Cmdline-mode and at the
// hit-enter prompt. However, scrolling one line up
// might be expected...
if (clip_star.state == SELECT_DONE)
clip_copy_modeless_selection(TRUE);
continue;
#endif
default: // no valid response
msg_moremsg(TRUE);
continue;
}
if (toscroll != 0)
{
if (toscroll < 0)
{
// go to start of last line
if (mp_last == NULL)
mp = msg_sb_start(last_msgchunk);
else if (mp_last->sb_prev != NULL)
mp = msg_sb_start(mp_last->sb_prev);
else
mp = NULL;
// go to start of line at top of the screen
for (i = 0; i < Rows - 2 && mp != NULL && mp->sb_prev != NULL;
++i)
mp = msg_sb_start(mp->sb_prev);
if (mp != NULL && mp->sb_prev != NULL)
{
// Find line to be displayed at top.
for (i = 0; i > toscroll; --i)
{
if (mp == NULL || mp->sb_prev == NULL)
break;
mp = msg_sb_start(mp->sb_prev);
if (mp_last == NULL)
mp_last = msg_sb_start(last_msgchunk);
else
mp_last = msg_sb_start(mp_last->sb_prev);
}
if (toscroll == -1 && screen_ins_lines(0, 0, 1,
(int)Rows, 0, NULL) == OK)
{
// display line at top
(void)disp_sb_line(0, mp, FALSE);
}
else
{
int did_clear = screenclear();
// redisplay all lines
for (i = 0; mp != NULL && i < Rows - 1; ++i)
{
mp = disp_sb_line(i, mp, !did_clear);
++msg_scrolled;
}
}
toscroll = 0;
}
}
else
{
// First display any text that we scrolled back.
while (toscroll > 0 && mp_last != NULL)
{
// scroll up, display line at bottom
msg_scroll_up();
inc_msg_scrolled();
screen_fill((int)Rows - 2, (int)Rows - 1, 0,
(int)Columns, ' ', ' ', 0);
mp_last = disp_sb_line((int)Rows - 2, mp_last, FALSE);
--toscroll;
}
}
if (toscroll <= 0)
{
// displayed the requested text, more prompt again
screen_fill((int)Rows - 1, (int)Rows, 0,
(int)Columns, ' ', ' ', 0);
msg_moremsg(FALSE);
continue;
}
// display more text, return to caller
lines_left = toscroll;
}
break;
}
// clear the --more-- message
screen_fill((int)Rows - 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
State = oldState;
setmouse();
if (quit_more)
{
msg_row = Rows - 1;
msg_col = 0;
}
#ifdef FEAT_RIGHTLEFT
else if (cmdmsg_rl)
msg_col = Columns - 1;
#endif
entered = FALSE;
#ifdef FEAT_CON_DIALOG
return retval;
#else
return FALSE;
#endif
}
#if defined(USE_MCH_ERRMSG) || defined(PROTO)
#ifdef mch_errmsg
# undef mch_errmsg
#endif
#ifdef mch_msg
# undef mch_msg
#endif
#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
static void
mch_errmsg_c(char *str)
{
int len = (int)STRLEN(str);
DWORD nwrite = 0;
DWORD mode = 0;
HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
if (GetConsoleMode(h, &mode) && enc_codepage >= 0
&& (int)GetConsoleCP() != enc_codepage)
{
WCHAR *w = enc_to_utf16((char_u *)str, &len);
WriteConsoleW(h, w, len, &nwrite, NULL);
vim_free(w);
}
else
{
fprintf(stderr, "%s", str);
}
}
#endif
/*
* Give an error message. To be used when the screen hasn't been initialized
* yet. When stderr can't be used, collect error messages until the GUI has
* started and they can be displayed in a message box.
*/
void
mch_errmsg(char *str)
{
#if !defined(MSWIN) || defined(FEAT_GUI_MSWIN)
int len;
#endif
#if (defined(UNIX) || defined(FEAT_GUI)) && !defined(ALWAYS_USE_GUI) && !defined(VIMDLL)
// On Unix use stderr if it's a tty.
// When not going to start the GUI also use stderr.
// On Mac, when started from Finder, stderr is the console.
if (
# ifdef UNIX
# ifdef MACOS_X
(isatty(2) && strcmp("/dev/console", ttyname(2)) != 0)
# else
isatty(2)
# endif
# ifdef FEAT_GUI
||
# endif
# endif
# ifdef FEAT_GUI
!(gui.in_use || gui.starting)
# endif
)
{
fprintf(stderr, "%s", str);
return;
}
#endif
#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
# ifdef VIMDLL
if (!(gui.in_use || gui.starting))
# endif
{
mch_errmsg_c(str);
return;
}
#endif
#if !defined(MSWIN) || defined(FEAT_GUI_MSWIN)
// avoid a delay for a message that isn't there
emsg_on_display = FALSE;
len = (int)STRLEN(str) + 1;
if (error_ga.ga_growsize == 0)
{
error_ga.ga_growsize = 80;
error_ga.ga_itemsize = 1;
}
if (ga_grow(&error_ga, len) == OK)
{
mch_memmove((char_u *)error_ga.ga_data + error_ga.ga_len,
(char_u *)str, len);
# ifdef UNIX
// remove CR characters, they are displayed
{
char_u *p;
p = (char_u *)error_ga.ga_data + error_ga.ga_len;
for (;;)
{
p = vim_strchr(p, '\r');
if (p == NULL)
break;
*p = ' ';
}
}
# endif
--len; // don't count the NUL at the end
error_ga.ga_len += len;
}
#endif
}
#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
static void
mch_msg_c(char *str)
{
int len = (int)STRLEN(str);
DWORD nwrite = 0;
DWORD mode;
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
if (GetConsoleMode(h, &mode) && enc_codepage >= 0
&& (int)GetConsoleCP() != enc_codepage)
{
WCHAR *w = enc_to_utf16((char_u *)str, &len);
WriteConsoleW(h, w, len, &nwrite, NULL);
vim_free(w);
}
else
{
printf("%s", str);
}
}
#endif
/*
* Give a message. To be used when the screen hasn't been initialized yet.
* When there is no tty, collect messages until the GUI has started and they
* can be displayed in a message box.
*/
void
mch_msg(char *str)
{
#if (defined(UNIX) || defined(FEAT_GUI)) && !defined(ALWAYS_USE_GUI) && !defined(VIMDLL)
// On Unix use stdout if we have a tty. This allows "vim -h | more" and
// uses mch_errmsg() when started from the desktop.
// When not going to start the GUI also use stdout.
// On Mac, when started from Finder, stderr is the console.
if (
# ifdef UNIX
# ifdef MACOS_X
(isatty(2) && strcmp("/dev/console", ttyname(2)) != 0)
# else
isatty(2)
# endif
# ifdef FEAT_GUI
||
# endif
# endif
# ifdef FEAT_GUI
!(gui.in_use || gui.starting)
# endif
)
{
printf("%s", str);
return;
}
#endif
#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
# ifdef VIMDLL
if (!(gui.in_use || gui.starting))
# endif
{
mch_msg_c(str);
return;
}
#endif
#if !defined(MSWIN) || defined(FEAT_GUI_MSWIN)
mch_errmsg(str);
#endif
}
#endif // USE_MCH_ERRMSG
/*
* Put a character on the screen at the current message position and advance
* to the next position. Only for printable ASCII!
*/
static void
msg_screen_putchar(int c, int attr)
{
msg_didout = TRUE; // remember that line is not empty
screen_putchar(c, msg_row, msg_col, attr);
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
{
if (--msg_col == 0)
{
msg_col = Columns;
++msg_row;
}
}
else
#endif
{
if (++msg_col >= Columns)
{
msg_col = 0;
++msg_row;
}
}
}
static void
msg_moremsg(int full)
{
int attr;
char_u *s = (char_u *)_("-- More --");
attr = HL_ATTR(HLF_M);
screen_puts(s, (int)Rows - 1, 0, attr);
if (full)
screen_puts((char_u *)
_(" SPACE/d/j: screen/page/line down, b/u/k: up, q: quit "),
(int)Rows - 1, vim_strsize(s), attr);
}
/*
* Repeat the message for the current mode: MODE_ASKMORE, MODE_EXTERNCMD,
* MODE_CONFIRM or exmode_active.
*/
void
repeat_message(void)
{
if (State == MODE_ASKMORE)
{
msg_moremsg(TRUE); // display --more-- message again
msg_row = Rows - 1;
}
#ifdef FEAT_CON_DIALOG
else if (State == MODE_CONFIRM)
{
display_confirm_msg(); // display ":confirm" message again
msg_row = Rows - 1;
}
#endif
else if (State == MODE_EXTERNCMD)
{
windgoto(msg_row, msg_col); // put cursor back
}
else if (State == MODE_HITRETURN || State == MODE_SETWSIZE)
{
if (msg_row == Rows - 1)
{
// Avoid drawing the "hit-enter" prompt below the previous one,
// overwrite it. Esp. useful when regaining focus and a
// FocusGained autocmd exists but didn't draw anything.
msg_didout = FALSE;
msg_col = 0;
msg_clr_eos();
}
hit_return_msg();
msg_row = Rows - 1;
}
}
/*
* msg_check_screen - check if the screen is initialized.
* Also check msg_row and msg_col, if they are too big it may cause a crash.
* While starting the GUI the terminal codes will be set for the GUI, but the
* output goes to the terminal. Don't use the terminal codes then.
*/
static int
msg_check_screen(void)
{
if (!full_screen || !screen_valid(FALSE))
return FALSE;
if (msg_row >= Rows)
msg_row = Rows - 1;
if (msg_col >= Columns)
msg_col = Columns - 1;
return TRUE;
}
/*
* Clear from current message position to end of screen.
* Skip this when ":silent" was used, no need to clear for redirection.
*/
void
msg_clr_eos(void)
{
if (msg_silent == 0)
msg_clr_eos_force();
}
/*
* Clear from current message position to end of screen.
* Note: msg_col is not updated, so we remember the end of the message
* for msg_check().
*/
void
msg_clr_eos_force(void)
{
#ifdef HAS_MESSAGE_WINDOW
if (in_echowindow)
return; // messages go into a popup
#endif
if (msg_use_printf())
{
if (full_screen) // only when termcap codes are valid
{
if (*T_CD)
out_str(T_CD); // clear to end of display
else if (*T_CE)
out_str(T_CE); // clear to end of line
}
}
else
{
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
{
screen_fill(msg_row, msg_row + 1, 0, msg_col + 1, ' ', ' ', 0);
screen_fill(msg_row + 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
}
else
#endif
{
screen_fill(msg_row, msg_row + 1, msg_col, (int)Columns,
' ', ' ', 0);
screen_fill(msg_row + 1, (int)Rows, 0, (int)Columns, ' ', ' ', 0);
}
}
}
/*
* Clear the command line.
*/
void
msg_clr_cmdline(void)
{
msg_row = cmdline_row;
msg_col = 0;
msg_clr_eos_force();
}
/*
* end putting a message on the screen
* call wait_return() if the message does not fit in the available space
* return TRUE if wait_return() not called.
*/
int
msg_end(void)
{
/*
* If the string is larger than the window,
* or the ruler option is set and we run into it,
* we have to redraw the window.
* Do not do this if we are abandoning the file or editing the command line.
*/
if (!exiting && need_wait_return && !(State & MODE_CMDLINE))
{
wait_return(FALSE);
return FALSE;
}
out_flush();
return TRUE;
}
/*
* If the written message runs into the shown command or ruler, we have to
* wait for hit-return and redraw the window later.
*/
void
msg_check(void)
{
if (msg_row == Rows - 1 && msg_col >= sc_col
#ifdef HAS_MESSAGE_WINDOW
&& !in_echowindow
#endif
)
{
need_wait_return = TRUE;
redraw_cmdline = TRUE;
}
}
/*
* May write a string to the redirection file.
* When "maxlen" is -1 write the whole string, otherwise up to "maxlen" bytes.
*/
static void
redir_write(char_u *str, int maxlen)
{
char_u *s = str;
static int cur_col = 0;
// Don't do anything for displaying prompts and the like.
if (redir_off)
return;
// If 'verbosefile' is set prepare for writing in that file.
if (*p_vfile != NUL && verbose_fd == NULL)
verbose_open();
if (redirecting())
{
// If the string doesn't start with CR or NL, go to msg_col
if (*s != '\n' && *s != '\r')
{
while (cur_col < msg_col)
{
#ifdef FEAT_EVAL
if (redir_execute)
execute_redir_str((char_u *)" ", -1);
else if (redir_reg)
write_reg_contents(redir_reg, (char_u *)" ", -1, TRUE);
else if (redir_vname)
var_redir_str((char_u *)" ", -1);
else
#endif
if (redir_fd != NULL)
fputs(" ", redir_fd);
if (verbose_fd != NULL)
fputs(" ", verbose_fd);
++cur_col;
}
}
#ifdef FEAT_EVAL
if (redir_execute)
execute_redir_str(s, maxlen);
else if (redir_reg)
write_reg_contents(redir_reg, s, maxlen, TRUE);
else if (redir_vname)
var_redir_str(s, maxlen);
#endif
// Write and adjust the current column.
while (*s != NUL && (maxlen < 0 || (int)(s - str) < maxlen))
{
#ifdef FEAT_EVAL
if (!redir_reg && !redir_vname && !redir_execute)
#endif
if (redir_fd != NULL)
putc(*s, redir_fd);
if (verbose_fd != NULL)
putc(*s, verbose_fd);
if (*s == '\r' || *s == '\n')
cur_col = 0;
else if (*s == '\t')
cur_col += (8 - cur_col % 8);
else
++cur_col;
++s;
}
if (msg_silent != 0) // should update msg_col
msg_col = cur_col;
}
}
int
redirecting(void)
{
return redir_fd != NULL || *p_vfile != NUL
#ifdef FEAT_EVAL
|| redir_reg || redir_vname || redir_execute
#endif
;
}
/*
* Before giving verbose message.
* Must always be called paired with verbose_leave()!
*/
void
verbose_enter(void)
{
if (*p_vfile != NUL)
++msg_silent;
}
/*
* After giving verbose message.
* Must always be called paired with verbose_enter()!
*/
void
verbose_leave(void)
{
if (*p_vfile != NUL)
if (--msg_silent < 0)
msg_silent = 0;
}
/*
* Like verbose_enter() and set msg_scroll when displaying the message.
*/
void
verbose_enter_scroll(void)
{
if (*p_vfile != NUL)
++msg_silent;
else
// always scroll up, don't overwrite
msg_scroll = TRUE;
}
/*
* Like verbose_leave() and set cmdline_row when displaying the message.
*/
void
verbose_leave_scroll(void)
{
if (*p_vfile != NUL)
{
if (--msg_silent < 0)
msg_silent = 0;
}
else
cmdline_row = msg_row;
}
/*
* Called when 'verbosefile' is set: stop writing to the file.
*/
void
verbose_stop(void)
{
if (verbose_fd != NULL)
{
fclose(verbose_fd);
verbose_fd = NULL;
}
verbose_did_open = FALSE;
}
/*
* Open the file 'verbosefile'.
* Return FAIL or OK.
*/
int
verbose_open(void)
{
if (verbose_fd == NULL && !verbose_did_open)
{
// Only give the error message once.
verbose_did_open = TRUE;
verbose_fd = mch_fopen((char *)p_vfile, "a");
if (verbose_fd == NULL)
{
semsg(_(e_cant_open_file_str), p_vfile);
return FAIL;
}
}
return OK;
}
/*
* Give a warning message (for searching).
* Use 'w' highlighting and may repeat the message after redrawing
*/
void
give_warning(char_u *message, int hl)
{
give_warning_with_source(message, hl, FALSE);
}
void
give_warning_with_source(char_u *message, int hl, int with_source)
{
// Don't do this for ":silent".
if (msg_silent != 0)
return;
// Don't want a hit-enter prompt here.
++no_wait_return;
#ifdef FEAT_EVAL
set_vim_var_string(VV_WARNINGMSG, message, -1);
#endif
VIM_CLEAR(keep_msg);
if (hl)
keep_msg_attr = HL_ATTR(HLF_W);
else
keep_msg_attr = 0;
if (with_source)
{
// Do what msg() does, but with a column offset if the warning should
// be after the mode message.
msg_start();
msg_source(HL_ATTR(HLF_W));
msg_puts(" ");
msg_puts_attr((char *)message, HL_ATTR(HLF_W) | MSG_HIST);
msg_clr_eos();
(void)msg_end();
}
else if (msg_attr((char *)message, keep_msg_attr) && msg_scrolled == 0)
set_keep_msg(message, keep_msg_attr);
msg_didout = FALSE; // overwrite this message
msg_nowait = TRUE; // don't wait for this message
msg_col = 0;
--no_wait_return;
}
#if defined(FEAT_EVAL) || defined(PROTO)
void
give_warning2(char_u *message, char_u *a1, int hl)
{
if (IObuff == NULL)
{
// Very early in initialisation and already something wrong, just give
// the raw message so the user at least gets a hint.
give_warning(message, hl);
}
else
{
vim_snprintf((char *)IObuff, IOSIZE, (char *)message, a1);
give_warning(IObuff, hl);
}
}
#endif
/*
* Advance msg cursor to column "col".
*/
void
msg_advance(int col)
{
if (msg_silent != 0) // nothing to advance to
{
msg_col = col; // for redirection, may fill it up later
return;
}
if (col >= Columns) // not enough room
col = Columns - 1;
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl)
while (msg_col > Columns - col)
msg_putchar(' ');
else
#endif
while (msg_col < col)
msg_putchar(' ');
}
#if defined(FEAT_CON_DIALOG) || defined(PROTO)
/*
* Used for "confirm()" function, and the :confirm command prefix.
* Versions which haven't got flexible dialogs yet, and console
* versions, get this generic handler which uses the command line.
*
* type = one of:
* VIM_QUESTION, VIM_INFO, VIM_WARNING, VIM_ERROR or VIM_GENERIC
* title = title string (can be NULL for default)
* (neither used in console dialogs at the moment)
*
* Format of the "buttons" string:
* "Button1Name\nButton2Name\nButton3Name"
* The first button should normally be the default/accept
* The second button should be the 'Cancel' button
* Other buttons- use your imagination!
* A '&' in a button name becomes a shortcut, so each '&' should be before a
* different letter.
*
* Returns 0 if cancelled, otherwise the nth button (1-indexed).
*/
int
do_dialog(
int type UNUSED,
char_u *title UNUSED,
char_u *message,
char_u *buttons,
int dfltbutton,
char_u *textfield UNUSED, // IObuff for inputdialog(), NULL
// otherwise
int ex_cmd) // when TRUE pressing : accepts default and starts
// Ex command
{
int oldState;
int retval = 0;
char_u *hotkeys;
int c;
int i;
tmode_T save_tmode;
#ifndef NO_CONSOLE
// Don't output anything in silent mode ("ex -s")
if (silent_mode)
return dfltbutton; // return default option
#endif
#ifdef FEAT_GUI_DIALOG
// When GUI is running and 'c' not in 'guioptions', use the GUI dialog
if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
{
// --gui-dialog-file: write text to a file
if (gui_dialog_log(title, message))
c = dfltbutton;
else
c = gui_mch_dialog(type, title, message, buttons, dfltbutton,
textfield, ex_cmd);
// avoid a hit-enter prompt without clearing the cmdline
need_wait_return = FALSE;
emsg_on_display = FALSE;
cmdline_row = msg_row;
// Flush output to avoid that further messages and redrawing is done
// in the wrong order.
out_flush();
gui_mch_update();
return c;
}
#endif
oldState = State;
State = MODE_CONFIRM;
setmouse();
// Ensure raw mode here.
save_tmode = cur_tmode;
settmode(TMODE_RAW);
/*
* Since we wait for a keypress, don't make the
* user press RETURN as well afterwards.
*/
++no_wait_return;
hotkeys = msg_show_console_dialog(message, buttons, dfltbutton);
if (hotkeys != NULL)
{
for (;;)
{
// Get a typed character directly from the user.
c = get_keystroke();
switch (c)
{
case CAR: // User accepts default option
case NL:
retval = dfltbutton;
break;
case Ctrl_C: // User aborts/cancels
case ESC:
retval = 0;
break;
default: // Could be a hotkey?
if (c < 0) // special keys are ignored here
continue;
if (c == ':' && ex_cmd)
{
retval = dfltbutton;
ins_char_typebuf(':', 0);
break;
}
// Make the character lowercase, as chars in "hotkeys" are.
c = MB_TOLOWER(c);
retval = 1;
for (i = 0; hotkeys[i]; ++i)
{
if (has_mbyte)
{
if ((*mb_ptr2char)(hotkeys + i) == c)
break;
i += (*mb_ptr2len)(hotkeys + i) - 1;
}
else
if (hotkeys[i] == c)
break;
++retval;
}
if (hotkeys[i])
break;
// No hotkey match, so keep waiting
continue;
}
break;
}
vim_free(hotkeys);
}
settmode(save_tmode);
State = oldState;
setmouse();
--no_wait_return;
msg_end_prompt();
return retval;
}
/*
* Copy one character from "*from" to "*to", taking care of multi-byte
* characters. Return the length of the character in bytes.
*/
static int
copy_char(
char_u *from,
char_u *to,
int lowercase) // make character lower case
{
int len;
int c;
if (has_mbyte)
{
if (lowercase)
{
c = MB_TOLOWER((*mb_ptr2char)(from));
return (*mb_char2bytes)(c, to);
}
else
{
len = (*mb_ptr2len)(from);
mch_memmove(to, from, (size_t)len);
return len;
}
}
else
{
if (lowercase)
*to = (char_u)TOLOWER_LOC(*from);
else
*to = *from;
return 1;
}
}
/*
* Format the dialog string, and display it at the bottom of
* the screen. Return a string of hotkey chars (if defined) for
* each 'button'. If a button has no hotkey defined, the first character of
* the button is used.
* The hotkeys can be multi-byte characters, but without combining chars.
*
* Returns an allocated string with hotkeys, or NULL for error.
*/
static char_u *
msg_show_console_dialog(
char_u *message,
char_u *buttons,
int dfltbutton)
{
int len = 0;
#define HOTK_LEN (has_mbyte ? MB_MAXBYTES : 1)
int lenhotkey = HOTK_LEN; // count first button
char_u *hotk = NULL;
char_u *msgp = NULL;
char_u *hotkp = NULL;
char_u *r;
int copy;
#define HAS_HOTKEY_LEN 30
char_u has_hotkey[HAS_HOTKEY_LEN];
int first_hotkey = FALSE; // first char of button is hotkey
int idx;
has_hotkey[0] = FALSE;
/*
* First loop: compute the size of memory to allocate.
* Second loop: copy to the allocated memory.
*/
for (copy = 0; copy <= 1; ++copy)
{
r = buttons;
idx = 0;
while (*r)
{
if (*r == DLG_BUTTON_SEP)
{
if (copy)
{
*msgp++ = ',';
*msgp++ = ' '; // '\n' -> ', '
// advance to next hotkey and set default hotkey
if (has_mbyte)
hotkp += STRLEN(hotkp);
else
++hotkp;
hotkp[copy_char(r + 1, hotkp, TRUE)] = NUL;
if (dfltbutton)
--dfltbutton;
// If no hotkey is specified first char is used.
if (idx < HAS_HOTKEY_LEN - 1 && !has_hotkey[++idx])
first_hotkey = TRUE;
}
else
{
len += 3; // '\n' -> ', '; 'x' -> '(x)'
lenhotkey += HOTK_LEN; // each button needs a hotkey
if (idx < HAS_HOTKEY_LEN - 1)
has_hotkey[++idx] = FALSE;
}
}
else if (*r == DLG_HOTKEY_CHAR || first_hotkey)
{
if (*r == DLG_HOTKEY_CHAR)
++r;
first_hotkey = FALSE;
if (copy)
{
if (*r == DLG_HOTKEY_CHAR) // '&&a' -> '&a'
*msgp++ = *r;
else
{
// '&a' -> '[a]'
*msgp++ = (dfltbutton == 1) ? '[' : '(';
msgp += copy_char(r, msgp, FALSE);
*msgp++ = (dfltbutton == 1) ? ']' : ')';
// redefine hotkey
hotkp[copy_char(r, hotkp, TRUE)] = NUL;
}
}
else
{
++len; // '&a' -> '[a]'
if (idx < HAS_HOTKEY_LEN - 1)
has_hotkey[idx] = TRUE;
}
}
else
{
// everything else copy literally
if (copy)
msgp += copy_char(r, msgp, FALSE);
}
// advance to the next character
MB_PTR_ADV(r);
}
if (copy)
{
*msgp++ = ':';
*msgp++ = ' ';
*msgp = NUL;
}
else
{
len += (int)(STRLEN(message)
+ 2 // for the NL's
+ STRLEN(buttons)
+ 3); // for the ": " and NUL
lenhotkey++; // for the NUL
// If no hotkey is specified first char is used.
if (!has_hotkey[0])
{
first_hotkey = TRUE;
len += 2; // "x" -> "[x]"
}
/*
* Now allocate and load the strings
*/
vim_free(confirm_msg);
confirm_msg = alloc(len);
if (confirm_msg == NULL)
return NULL;
*confirm_msg = NUL;
hotk = alloc(lenhotkey);
if (hotk == NULL)
return NULL;
*confirm_msg = '\n';
STRCPY(confirm_msg + 1, message);
msgp = confirm_msg + 1 + STRLEN(message);
hotkp = hotk;
// Define first default hotkey. Keep the hotkey string NUL
// terminated to avoid reading past the end.
hotkp[copy_char(buttons, hotkp, TRUE)] = NUL;
// Remember where the choices start, displaying starts here when
// "hotkp" typed at the more prompt.
confirm_msg_tail = msgp;
*msgp++ = '\n';
}
}
display_confirm_msg();
return hotk;
}
/*
* Display the ":confirm" message. Also called when screen resized.
*/
static void
display_confirm_msg(void)
{
// avoid that 'q' at the more prompt truncates the message here
++confirm_msg_used;
if (confirm_msg != NULL)
msg_puts_attr((char *)confirm_msg, HL_ATTR(HLF_M));
--confirm_msg_used;
}
#endif // FEAT_CON_DIALOG
#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
int
vim_dialog_yesno(
int type,
char_u *title,
char_u *message,
int dflt)
{
if (do_dialog(type,
title == NULL ? (char_u *)_("Question") : title,
message,
(char_u *)_("&Yes\n&No"), dflt, NULL, FALSE) == 1)
return VIM_YES;
return VIM_NO;
}
int
vim_dialog_yesnocancel(
int type,
char_u *title,
char_u *message,
int dflt)
{
switch (do_dialog(type,
title == NULL ? (char_u *)_("Question") : title,
message,
(char_u *)_("&Yes\n&No\n&Cancel"), dflt, NULL, FALSE))
{
case 1: return VIM_YES;
case 2: return VIM_NO;
}
return VIM_CANCEL;
}
int
vim_dialog_yesnoallcancel(
int type,
char_u *title,
char_u *message,
int dflt)
{
switch (do_dialog(type,
title == NULL ? (char_u *)"Question" : title,
message,
(char_u *)_("&Yes\n&No\nSave &All\n&Discard All\n&Cancel"),
dflt, NULL, FALSE))
{
case 1: return VIM_YES;
case 2: return VIM_NO;
case 3: return VIM_ALL;
case 4: return VIM_DISCARDALL;
}
return VIM_CANCEL;
}
#endif // FEAT_GUI_DIALOG || FEAT_CON_DIALOG
|
95c34aedb4f11d150f001584adf437f07fab3282
|
3bba62bf3fcfc582f63fd79c70ee2475d279618d
|
/src/rdtsc.c
|
932ef59e350656b356704e9067b23b7d5424318a
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
sidkshatriya/rd
|
00b1cef0c162908e3a3a37de2dc3c62a034d516a
|
723046ad66e777313389c79e817dd0fa43a067c5
|
refs/heads/master
| 2022-08-04T03:45:53.742136
| 2022-06-03T18:52:18
| 2022-06-03T18:52:18
| 234,113,527
| 988
| 17
|
NOASSERTION
| 2021-07-06T19:10:31
| 2020-01-15T15:40:48
|
Rust
|
UTF-8
|
C
| false
| false
| 332
|
c
|
rdtsc.c
|
#define _GNU_SOURCE
#include <x86intrin.h>
// Definition of rdtsc() as in https://github.com/rr-debugger/rr `src/record_signal.cc`
// e.g. see that file as of rr git revision abd344288878c9b4046e0b8664927992947a46eb
// NOTE: static and __inline__ annotations removed though
unsigned long long rdtsc(void) { return __rdtsc(); }
|
0c6a3ff46ad5cd6debc81959f019b74983c09106
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/lpc55sxx/Libraries/LPC55S36/LPC55S36/drivers/mem_interface/fsl_mem_interface.h
|
6d99e708fc61f34ed10c9eeefaf6b4e9c9fec02c
|
[
"Zlib",
"LicenseRef-scancode-proprietary-license",
"MIT",
"BSD-3-Clause",
"X11",
"BSD-4-Clause-UC",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 16,058
|
h
|
fsl_mem_interface.h
|
/*
* Copyright 2021 NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _FSL_MEM_INTERFACE_H_
#define _FSL_MEM_INTERFACE_H_
#include "fsl_sbloader.h"
#include "fsl_common.h"
/*!
* @addtogroup memory_interface
* @{
*/
/*******************************************************************************
* Definitions
******************************************************************************/
/*! @brief Bit mask for device ID. */
#define DEVICE_ID_MASK (0xffU)
/*! @brief Bit position of device ID. */
#define DEVICE_ID_SHIFT 0U
/*! @brief Bit mask for group ID. */
#define GROUP_ID_MASK (0xf00U)
/*! @brief Bit position of group ID. */
#define GROUP_ID_SHIFT 8U
/*! @brief Construct a memory ID from a given group ID and device ID. */
#define MAKE_MEMORYID(group, device) \
((((group) << GROUP_ID_SHIFT) & GROUP_ID_MASK) | (((device) << DEVICE_ID_SHIFT) & DEVICE_ID_MASK))
/*! @brief Get group ID from a given memory ID. */
#define GROUPID(memoryId) (((memoryId)&GROUP_ID_MASK) >> GROUP_ID_SHIFT)
/*! @brief Get device ID from a given memory ID. */
#define DEVICEID(memoryId) (((memoryId)&DEVICE_ID_MASK) >> DEVICE_ID_SHIFT)
/*! @brief Memory group definition. */
enum
{
kMemoryGroup_Internal = 0U, /*!< Memory belongs internal 4G memory region. */
kMemoryGroup_External = 1U, /*!< Memory belongs external memory region. */
};
/*! @brief Memory device ID definition. */
enum
{
/* Memory ID bitfiled definition.
| 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| Reserved | INT/EXT | Type | Sub-Type |
| | 0: INT | INT: | |
| | 1: EXT | 0: NorFlash0 | 0: Internal Flash(FTFX) |
| | | | 1: QSPI |
| | | | 4: IFR |
| | | | 5: LPC FFR |
| | | | 8: SEMC |
| | | | 9: FlexSPI |
| | | | others: Unused |
| | | | |
| | | 1: ExecuteOnlyRegion | 0: Internal Flash(FTFX) |
| | | | others: Unused |
| | | | |
| | | others: Unused | |
| | | | |
| | | EXT: | |
| | | 0: NandFlash | 0: SEMC |
| | | | 1: FlexSPI |
| | | | others: Unused |
| | | | |
| | | 1: NorFlash/EEPROM | 0: LPSPI |
| | | | 1: LPI2C |
| | | | others: Unused |
| | | | |
| | | 2: SD/SDHC/SDXC/MMC/eMMC | 0: uSDHC SD |
| | | | 1: uSDHC MMC |
| | | | others: Unused |
| | | others: Unused | |
INT : Internal 4G memory, including internal memory modules, and XIP external memory modules.
EXT : Non-XIP external memory modules.
*/
kMemoryInternal = MAKE_MEMORYID(kMemoryGroup_Internal, 0U), /*!< Internal memory (include all on chip memory) */
kMemoryQuadSpi0 = MAKE_MEMORYID(kMemoryGroup_Internal, 1U), /*!< Qsuad SPI memory 0 */
kMemoryIFR0 =
MAKE_MEMORYID(kMemoryGroup_Internal, 4U), /*!< Nonvolatile information register 0. Only used by SB loader. */
kMemoryFFR = MAKE_MEMORYID(kMemoryGroup_Internal, 5U), /*!< LPCc040hd flash FFR region. */
kMemorySemcNor = MAKE_MEMORYID(kMemoryGroup_Internal, 8U), /*!< SEMC Nor memory */
kMemoryFlexSpiNor = MAKE_MEMORYID(kMemoryGroup_Internal, 9U), /*!< Flex SPI Nor memory */
kMemorySpifiNor = MAKE_MEMORYID(kMemoryGroup_Internal, 0xAU), /*!< SPIFI Nor memory */
kMemoryFlashExecuteOnly = MAKE_MEMORYID(kMemoryGroup_Internal, 0x10U), /*!< Execute-only region on internal Flash */
kMemorySemcNand = MAKE_MEMORYID(kMemoryGroup_External, 0U), /*!< SEMC NAND memory */
kMemorySpiNand = MAKE_MEMORYID(kMemoryGroup_External, 1U), /*!< SPI NAND memory */
kMemorySpiNorEeprom = MAKE_MEMORYID(kMemoryGroup_External, 0x10U), /*!< SPI NOR/EEPROM memory */
kMemoryI2cNorEeprom = MAKE_MEMORYID(kMemoryGroup_External, 0x11U), /*!< I2C NOR/EEPROM memory */
kMemorySDCard = MAKE_MEMORYID(kMemoryGroup_External, 0x20U), /*!< eSD, SD, SDHC, SDXC memory Card */
kMemoryMMCCard = MAKE_MEMORYID(kMemoryGroup_External, 0x21U), /*!< MMC, eMMC memory Card */
};
/*! @brief Bootloader status group numbers.
*
* @ingroup bl_core
*/
enum
{
kStatusGroup_Bootloader = 100, /*!< Bootloader status group number (100). */
kStatusGroup_MemoryInterface = 102, /*!< Memory interface status group number (102). */
};
/*! @brief Memory interface status codes. */
enum
{
kStatusMemoryRangeInvalid = MAKE_STATUS(kStatusGroup_MemoryInterface, 0),
kStatusMemoryReadFailed = MAKE_STATUS(kStatusGroup_MemoryInterface, 1),
kStatusMemoryWriteFailed = MAKE_STATUS(kStatusGroup_MemoryInterface, 2),
kStatusMemoryCumulativeWrite = MAKE_STATUS(kStatusGroup_MemoryInterface, 3),
kStatusMemoryAppOverlapWithExecuteOnlyRegion = MAKE_STATUS(kStatusGroup_MemoryInterface, 4),
kStatusMemoryNotConfigured = MAKE_STATUS(kStatusGroup_MemoryInterface, 5),
kStatusMemoryAlignmentError = MAKE_STATUS(kStatusGroup_MemoryInterface, 6),
kStatusMemoryVerifyFailed = MAKE_STATUS(kStatusGroup_MemoryInterface, 7),
kStatusMemoryWriteProtected = MAKE_STATUS(kStatusGroup_MemoryInterface, 8),
kStatusMemoryAddressError = MAKE_STATUS(kStatusGroup_MemoryInterface, 9),
kStatusMemoryBlankCheckFailed = MAKE_STATUS(kStatusGroup_MemoryInterface, 10),
kStatusMemoryBlankPageReadDisallowed = MAKE_STATUS(kStatusGroup_MemoryInterface, 11),
kStatusMemoryProtectedPageReadDisallowed = MAKE_STATUS(kStatusGroup_MemoryInterface, 12),
kStatusMemoryFfrSpecRegionWriteBroken = MAKE_STATUS(kStatusGroup_MemoryInterface, 13),
kStatusMemoryUnsupportedCommand = MAKE_STATUS(kStatusGroup_MemoryInterface, 14),
};
/*! @brief Bootloader status codes. */
enum
{
kStatus_UnknownCommand = MAKE_STATUS(kStatusGroup_Bootloader, 0),
kStatus_SecurityViolation = MAKE_STATUS(kStatusGroup_Bootloader, 1),
kStatus_AbortDataPhase = MAKE_STATUS(kStatusGroup_Bootloader, 2),
kStatus_Ping = MAKE_STATUS(kStatusGroup_Bootloader, 3),
kStatus_NoResponse = MAKE_STATUS(kStatusGroup_Bootloader, 4),
kStatus_NoResponseExpected = MAKE_STATUS(kStatusGroup_Bootloader, 5),
kStatus_CommandUnsupported = MAKE_STATUS(kStatusGroup_Bootloader, 6),
};
/*!
* @brief Interface to memory operations.
*
* This is the main abstract interface to all memory operations.
*/
typedef struct
{
status_t (*init)(void);
status_t (*read)(uint32_t address, uint32_t length, uint8_t *buffer, uint32_t memoryId);
status_t (*write)(uint32_t address, uint32_t length, const uint8_t *buffer, uint32_t memoryId);
status_t (*fill)(uint32_t address, uint32_t length, uint32_t pattern);
status_t (*flush)(void);
status_t (*finalize)(void);
status_t (*erase)(uint32_t address, uint32_t length, uint32_t memoryId);
} memory_interface_t;
/*! @brief Interface to memory operations for one region of memory. */
typedef struct
{
status_t (*init)(void);
status_t (*read)(uint32_t address, uint32_t length, uint8_t *buffer);
status_t (*write)(uint32_t address, uint32_t length, const uint8_t *buffer);
status_t (*fill)(uint32_t address, uint32_t length, uint32_t pattern);
status_t (*flush)(void);
status_t (*erase)(uint32_t address, uint32_t length);
status_t (*config)(uint32_t *buffer);
status_t (*erase_all)(void);
} memory_region_interface_t;
//! @brief Structure of a memory map entry.
typedef struct
{
uint32_t startAddress;
uint32_t endAddress;
uint32_t memoryProperty;
uint32_t memoryId;
const memory_region_interface_t *memoryInterface;
} memory_map_entry_t;
/*! @brief Structure of version property. */
typedef union StandardVersion
{
struct
{
uint8_t bugfix; /*!< bugfix version [7:0] */
uint8_t minor; /*!< minor version [15:8] */
uint8_t major; /*!< major version [23:16] */
char name; /*!< name [31:24] */
};
uint32_t version; /*!< combined version numbers */
} standard_version_t;
/*! @brief API initialization data structure */
typedef struct kb_api_parameter_struct
{
uint32_t allocStart;
uint32_t allocSize;
} kp_api_init_param_t;
#ifdef __cplusplus
extern "C" {
#endif
/*******************************************************************************
* API
******************************************************************************/
standard_version_t API_Version(void);
/*! @brief Initialize the IAP API runtime environment */
status_t API_Init(api_core_context_t *coreCtx, const kp_api_init_param_t *param);
/*! @brief Deinitialize the IAP API runtime environment */
status_t API_Deinit(api_core_context_t *coreCtx);
/*!
* @brief Initialize memory interface.
*
* @retval #kStatus_Fail
* @retval #kStatus_Success
*/
status_t MEM_Init(api_core_context_t *coreCtx);
/*!
* @brief Configure memory interface
*
* @param config A pointer to the storage for the driver runtime state.
* @param memoryId Indicates the index of the memory type. Please refer to "Memory group definition"
* @retval #kStatus_Success
* @retval #kStatus_CommandUnsupported
* @retval #kStatus_InvalidArgument
* @retval #kStatus_FLASH_ModifyProtectedAreaDisallowed
* @retval #kStatusMemoryRangeInvalid
* @retval #kStatus_Fail
* @retval #kStatus_OutOfRange
* @retval #kStatus_SPI_BaudrateNotSupport
*/
status_t MEM_Config(api_core_context_t *coreCtx, uint32_t *config, uint32_t memoryId);
/*!
* @brief Write memory.
*
* @param address The start address of the desired flash memory to be programmed.
For internal flash the address need to be 512bytes-aligned.
* @param length Number of bytes to be programmed.
* @param buffer A pointer to the source buffer of data that is to be programmed into the flash.
* @param memoryId Indicates the index of the memory type. Please refer to "Memory group definition"
*
* @retval #kStatus_Success
* @retval #kStatus_Fail
* @retval #kStatusMemoryRangeInvalid
* @retval #kStatus_CommandUnsupported
* @retval #kStatus_FLASH_AlignmentError
* @retval #kStatusMemoryCumulativeWrite
* @retval #kStatus_FLASH_InvalidArgument
* @retval #kStatus_FLASH_AddressError
* @retval #kStatus_FLASH_ModifyProtectedAreaDisallowed
* @retval #kStatus_FLASH_CommandFailure
* @retval #kStatus_FLASH_CommandNotSupported
* @retval #kStatus_FLASH_EccError
* @retval #kStatus_FLASH_RegulationLoss
* @retval #kStatus_FLASH_Success
* @retval #kStatus_FLASH_ReadHidingAreaDisallowed
* @retval #kStatus_FLASH_CompareError
* @retval #kStatusMemoryNotConfigured
* @retval #kStatusMemoryVerifyFailed
*/
status_t MEM_Write(
api_core_context_t *coreCtx, uint32_t start, uint32_t lengthInBytes, const uint8_t *buf, uint32_t memoryId);
/*!
* @brief Fill memory with a word pattern.
*
* @param address The start address of the desired flash memory to be programmed.
* For internal flash the address need to be 512bytes-aligned.
* @param length Number of bytes to be programmed.
* @param pattern The data to be written into the specified memory area.
*
* @retval #kStatus_CommandUnsupported
* @retval #kStatus_Success
* @retval #kStatus_FLASH_AlignmentError
* @retval #kStatusMemoryCumulativeWrite
* @retval #kStatus_Fail
* @retval #kStatus_FLASH_InvalidArgument
* @retval #kStatus_FLASH_AddressError
* @retval #kStatus_FLASH_Success
* @retval #kStatus_FLASH_ModifyProtectedAreaDisallowed
* @retval #kStatus_FLASH_CommandFailure
* @retval #kStatus_FLASH_CommandNotSupported
* @retval #kStatus_FLASH_EccError
* @retval #kStatus_FLASH_RegulationLoss
* @retval #kStatus_FLASH_ReadHidingAreaDisallowed
*/
status_t MEM_Fill(
api_core_context_t *coreCtx, uint32_t start, uint32_t lengthInBytes, uint32_t pattern, uint32_t memoryId);
/*!
* @brief Flush memory.
*
* @retval #kStatus_Success
* @retval #kStatus_Fail
* @retval #kStatusMemoryCumulativeWrite
* @retval #kStatus_FLASH_InvalidArgument
* @retval #kStatus_FLASH_AlignmentError
* @retval #kStatus_FLASH_Success
* @retval #kStatus_FLASH_AddressError
* @retval #kStatus_FLASH_ModifyProtectedAreaDisallowed
* @retval #kStatus_FLASH_CommandFailure
* @retval #kStatus_FLASH_CommandNotSupported
* @retval #kStatus_FLASH_EccError
* @retval #kStatus_FLASH_RegulationLoss
* @retval #kStatus_FLASH_ReadHidingAreaDisallowed
* @retval #kStatusMemoryVerifyFailed
*/
status_t MEM_Flush(api_core_context_t *coreCtx);
/*!
* @brief Erase memory.
*
* @param address The start address of the desired flash memory to be erased.
* @param length Number of bytes to be read.
* @param memoryId Indicates the index of the memory type. Please refer to "Memory group definition"
*
* @retval #kStatus_Success
* @retval #kStatusMemoryRangeInvalid
* @retval #kStatusMemoryAddressError
* @retval #kStatus_FLASH_InvalidArgument
* @retval #kStatus_FLASH_AlignmentError
* @retval #kStatus_FLASH_Success
* @retval #kStatus_FLASH_AddressError
* @retval #kStatus_FLASH_EraseKeyError
* @retval #kStatus_FLASH_ModifyProtectedAreaDisallowed
* @retval #kStatus_Fail
* @retval #kStatus_FLASH_CommandFailure
* @retval #kStatus_FLASH_CommandNotSupported
* @retval #kStatus_FLASH_EccError
* @retval #kStatus_FLASH_RegulationLoss
* @retval #kStatusMemoryNotConfigured
* @retval #kStatusMemoryVerifyFailed
*/
status_t MEM_Erase(api_core_context_t *coreCtx, uint32_t start, uint32_t lengthInBytes, uint32_t memoryId);
/*!
* @brief Erase entire memory based on memoryId
*
* @param memoryId Indicates the index of the memory type. Please refer to "Memory group definition"
*
* @retval #kStatus_Success
* @retval #kStatus_Fail
* @retval #kStatus_CommandUnsupported
* @retval #kStatus_FLASH_InvalidArgument
* @retval #kStatus_FLASH_AlignmentError
* @retval #kStatus_FLASH_Success
* @retval #kStatus_FLASH_AddressError
* @retval #kStatus_FLASH_EraseKeyError
* @retval #kStatus_FLASH_CommandFailure
* @retval #kStatus_FLASH_CommandNotSupported
* @retval #kStatus_FLASH_EccError
* @retval #kStatus_FLASH_RegulationLoss
* @retval #kStatus_FLASH_ModifyProtectedAreaDisallowed
* @retval #kStatusMemoryVerifyFailed
* @retval #kStatusMemoryNotConfigured
* @retval #kStatus_InvalidArgument
*/
status_t MEM_EraseAll(api_core_context_t *coreCtx, uint32_t memoryId);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* _FSL_MEM_INTERFACE_H_ */
|
0db1c17a9fbfc7f604f17cde78e03034b568ef69
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/usr.bin/spell/spellprog/spellprog.c
|
d11598b452a133507fe3666513e55352755ece62
|
[] |
no_license
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 20,613
|
c
|
spellprog.c
|
/* $NetBSD: spellprog.c,v 1.10 2021/11/09 09:41:05 nia Exp $ */
/* derived from OpenBSD: spellprog.c,v 1.4 2003/06/03 02:56:16 millert Exp */
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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.
*
* @(#)spell.h 8.1 (Berkeley) 6/6/93
*/
/*
* Copyright (C) Caldera International Inc. 2001-2002.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code and documentation must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed or owned by Caldera
* International, Inc.
* 4. Neither the name of Caldera International, Inc. nor the names of other
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
* INTERNATIONAL, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE LIABLE FOR ANY DIRECT,
* INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/cdefs.h>
#ifndef lint
static const char copyright[] =
"@(#) Copyright (c) 1991, 1993\n\
The Regents of the University of California. All rights reserved.\n";
#endif /* not lint */
#ifndef lint
#if 0
static const char sccsid[] = "@(#)spell.c 8.1 (Berkeley) 6/6/93";
#else
#endif
static const char rcsid[] = "$OpenBSD: spellprog.c,v 1.4 2003/06/03 02:56:16 millert Exp $";
#endif /* not lint */
#include <sys/param.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <util.h>
#include "extern.h"
#define DLEV 2
static int dict(char *, char *);
static int trypref(char *, const char *, size_t);
static int tryword(char *, char *, size_t);
static int suffix(char *, size_t);
static int vowel(int);
static const char *lookuppref(char **, char *);
static char *skipv(char *);
static void ise(void);
static void print_word(FILE *);
static void ztos(char *);
static int monosyl(char *, char *);
static void usage(void) __dead;
static void getderiv(size_t);
static int an(char *, const char *, const char *, size_t);
static int bility(char *, const char *, const char *, size_t);
static int es(char *, const char *, const char *, size_t);
static int i_to_y(char *, const char *, const char *, size_t);
static int ily(char *, const char *, const char *, size_t);
static int ize(char *, const char *, const char *, size_t);
static int metry(char *, const char *, const char *, size_t);
static int ncy(char *, const char *, const char *, size_t);
static int nop(char *, const char *, const char *, size_t);
static int s(char *, const char *, const char *, size_t);
static int strip(char *, const char *, const char *, size_t);
static int tion(char *, const char *, const char *, size_t);
static int y_to_e(char *, const char *, const char *, size_t);
static int CCe(char *, const char *, const char *, size_t);
static int VCe(char *, const char *, const char *, size_t);
/*
* This cannot be const because we modify it when we choose british
* spelling.
*/
static struct suftab {
const char *suf;
int (*p1)(char *, const char *, const char *, size_t);
int n1;
const char *d1;
const char *a1;
int (*p2)(char *, const char *, const char *, size_t);
int n2;
const char *d2;
const char *a2;
} suftab[] = {
{ .suf = "ssen", .p1 = ily, .n1 = 4,
.d1 = "-y+iness", .a1 = "+ness" },
{ .suf = "ssel", .p1 = ily, .n1 = 4,
.d1 = "-y+i+less", .a1 = "+less" },
{ .suf = "se", .p1 = s, .n1 = 1,
.d1 = "", .a1 = "+s", .p2 = es,
.n2 = 2, .d2 = "-y+ies", .a2 = "+es" },
{ .suf = "s'", .p1 = s, .n1 = 2,
.d1 = "", .a1 = "+'s" },
{ .suf = "s", .p1 = s, .n1 = 1,
.d1 = "", .a1 = "+s" },
{ .suf = "ecn", .p1 = ncy, .n1 = 1,
.d1 = "", .a1 = "-t+ce" },
{ .suf = "ycn", .p1 = ncy, .n1 = 1,
.d1 = "", .a1 = "-cy+t" },
{ .suf = "ytilb", .p1 = nop, .n1 = 0,
.d1 = "", .a1 = "" },
{ .suf = "ytilib", .p1 = bility, .n1 = 5,
.d1 = "-le+ility", .a1 = "" },
{ .suf = "elbaif", .p1 = i_to_y, .n1 = 4,
.d1 = "-y+iable", .a1 = "" },
{ .suf = "elba", .p1 = CCe, .n1 = 4,
.d1 = "-e+able", .a1 = "+able" },
{ .suf = "yti", .p1 = CCe, .n1 = 3,
.d1 = "-e+ity", .a1 = "+ity" },
{ .suf = "ylb", .p1 = y_to_e, .n1 = 1,
.d1 = "-e+y", .a1 = "" },
{ .suf = "yl", .p1 = ily, .n1 = 2,
.d1 = "-y+ily", .a1 = "+ly" },
{ .suf = "laci", .p1 = strip, .n1 = 2,
.d1 = "", .a1 = "+al" },
{ .suf = "latnem", .p1 = strip, .n1 = 2,
.d1 = "", .a1 = "+al" },
{ .suf = "lanoi", .p1 = strip, .n1 = 2,
.d1 = "", .a1 = "+al" },
{ .suf = "tnem", .p1 = strip, .n1 = 4,
.d1 = "", .a1 = "+ment" },
{ .suf = "gni", .p1 = CCe, .n1 = 3,
.d1 = "-e+ing", .a1 = "+ing" },
{ .suf = "reta", .p1 = nop, .n1 = 0,
.d1 = "", .a1 = "" },
{ .suf = "re", .p1 = strip, .n1 = 1,
.d1 = "", .a1 = "+r", .p2 = i_to_y,
.n2 = 2, .d2 = "-y+ier", .a2 = "+er" },
{ .suf = "de", .p1 = strip, .n1 = 1,
.d1 = "", .a1 = "+d", .p2 = i_to_y,
.n2 = 2, .d2 = "-y+ied", .a2 = "+ed" },
{ .suf = "citsi", .p1 = strip, .n1 = 2,
.d1 = "", .a1 = "+ic" },
{ .suf = "cihparg", .p1 = i_to_y, .n1 = 1,
.d1 = "-y+ic", .a1 = "" },
{ .suf = "tse", .p1 = strip, .n1 = 2,
.d1 = "", .a1 = "+st", .p2 = i_to_y,
.n2 = 3, .d2 = "-y+iest",.a2 = "+est" },
{ .suf = "cirtem", .p1 = i_to_y, .n1 = 1,
.d1 = "-y+ic", .a1 = "" },
{ .suf = "yrtem", .p1 = metry, .n1 = 0,
.d1 = "-ry+er", .a1 = "" },
{ .suf = "cigol", .p1 = i_to_y, .n1 = 1,
.d1 = "-y+ic", .a1 = "" },
{ .suf = "tsigol", .p1 = i_to_y, .n1 = 2,
.d1 = "-y+ist", .a1 = "" },
{ .suf = "tsi", .p1 = VCe, .n1 = 3,
.d1 = "-e+ist", .a1 = "+ist" },
{ .suf = "msi", .p1 = VCe, .n1 = 3,
.d1 = "-e+ism", .a1 = "+ist" },
{ .suf = "noitacif", .p1 = i_to_y, .n1 = 6,
.d1 = "-y+ication", .a1 = "" },
{ .suf = "noitazi", .p1 = ize, .n1 = 5,
.d1 = "-e+ation", .a1 = "" },
{ .suf = "rota", .p1 = tion, .n1 = 2,
.d1 = "-e+or", .a1 = "" },
{ .suf = "noit", .p1 = tion, .n1 = 3,
.d1 = "-e+ion", .a1 = "+ion" },
{ .suf = "naino", .p1 = an, .n1 = 3,
.d1 = "", .a1 = "+ian" },
{ .suf = "na", .p1 = an, .n1 = 1,
.d1 = "", .a1 = "+n" },
{ .suf = "evit", .p1 = tion, .n1 = 3,
.d1 = "-e+ive", .a1 = "+ive" },
{ .suf = "ezi", .p1 = CCe, .n1 = 3,
.d1 = "-e+ize", .a1 = "+ize" },
{ .suf = "pihs", .p1 = strip, .n1 = 4,
.d1 = "", .a1 = "+ship" },
{ .suf = "dooh", .p1 = ily, .n1 = 4,
.d1 = "-y+hood", .a1 = "+hood" },
{ .suf = "ekil", .p1 = strip, .n1 = 4,
.d1 = "", .a1 = "+like" },
{ .suf = NULL, }
};
static const char *preftab[] = {
"anti",
"bio",
"dis",
"electro",
"en",
"fore",
"hyper",
"intra",
"inter",
"iso",
"kilo",
"magneto",
"meta",
"micro",
"milli",
"mis",
"mono",
"multi",
"non",
"out",
"over",
"photo",
"poly",
"pre",
"pseudo",
"re",
"semi",
"stereo",
"sub",
"super",
"thermo",
"ultra",
"under", /* must precede un */
"un",
NULL
};
static struct wlist {
int fd;
unsigned char *front;
unsigned char *back;
} *wlists;
static int vflag;
static int xflag;
static char word[LINE_MAX];
static char original[LINE_MAX];
static char affix[LINE_MAX];
static struct {
const char **buf;
size_t maxlev;
} deriv;
/*
* The spellprog utility accepts a newline-delimited list of words
* on stdin. For arguments it expects the path to a word list and
* the path to a file in which to store found words.
*
* In normal usage, spell is called twice. The first time it is
* called with a stop list to flag commonly mispelled words. The
* remaining words are then passed to spell again, this time with
* the dictionary file as the first (non-flag) argument.
*
* Unlike historic versions of spellprog, this one does not use
* hashed files. Instead it simply requires that files be sorted
* lexigraphically and uses the same algorithm as the look utility.
*
* Note that spellprog should be called via the spell shell script
* and is not meant to be invoked directly by the user.
*/
int
main(int argc, char **argv)
{
char *ep, *cp, *dp;
char *outfile;
int ch, fold, i;
struct stat sb;
FILE *file, *found;
setlocale(LC_ALL, "");
outfile = NULL;
while ((ch = getopt(argc, argv, "bvxo:")) != -1) {
switch (ch) {
case 'b':
/* Use British dictionary and convert ize -> ise. */
ise();
break;
case 'o':
outfile = optarg;
break;
case 'v':
/* Also write derivations to "found" file. */
vflag++;
break;
case 'x':
/* Print plausible stems to stdout. */
xflag++;
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (argc < 1)
usage();
/* Open and mmap the word/stop lists. */
if ((wlists = malloc(sizeof(struct wlist) * (argc + 1))) == NULL)
err(1, "malloc");
for (i = 0; argc--; i++) {
wlists[i].fd = open(argv[i], O_RDONLY, 0);
if (wlists[i].fd == -1 || fstat(wlists[i].fd, &sb) != 0)
err(1, "%s", argv[i]);
if (sb.st_size > SIZE_T_MAX)
errx(1, "%s: %s", argv[i], strerror(EFBIG));
wlists[i].front = mmap(NULL, (size_t)sb.st_size, PROT_READ,
MAP_PRIVATE, wlists[i].fd, (off_t)0);
if (wlists[i].front == MAP_FAILED)
err(1, "%s", argv[i]);
wlists[i].back = wlists[i].front + (size_t)sb.st_size;
}
wlists[i].fd = -1;
/* Open file where found words are to be saved. */
if (outfile == NULL)
found = NULL;
else if ((found = fopen(outfile, "w")) == NULL)
err(1, "cannot open %s", outfile);
for (;; print_word(file)) {
affix[0] = '\0';
file = found;
for (ep = word; (*ep = ch = getchar()) != '\n'; ep++) {
if (ep - word == sizeof(word) - 1) {
*ep = '\0';
warnx("word too long (%s)", word);
while ((ch = getchar()) != '\n')
; /* slurp until EOL */
}
if (ch == EOF) {
if (found != NULL)
fclose(found);
exit(0);
}
}
for (cp = word, dp = original; cp < ep; )
*dp++ = *cp++;
*dp = '\0';
fold = 0;
for (cp = word; cp < ep; cp++)
if (islower((unsigned char)*cp))
goto lcase;
if (trypref(ep, ".", 0))
continue;
++fold;
for (cp = original + 1, dp = word + 1; dp < ep; dp++, cp++)
*dp = tolower((unsigned char)*cp);
lcase:
if (trypref(ep, ".", 0) || suffix(ep, 0))
continue;
if (isupper((unsigned char)word[0])) {
for (cp = original, dp = word; (*dp = *cp++); dp++) {
if (fold)
*dp = tolower((unsigned char)*dp);
}
word[0] = tolower((unsigned char)word[0]);
goto lcase;
}
file = stdout;
}
}
static void
print_word(FILE *f)
{
if (f != NULL) {
if (vflag && affix[0] != '\0' && affix[0] != '.')
fprintf(f, "%s\t%s\n", affix, original);
else
fprintf(f, "%s\n", original);
}
}
/*
* For each matching suffix in suftab, call the function associated
* with that suffix (p1 and p2).
*/
static int
suffix(char *ep, size_t lev)
{
const struct suftab *t;
char *cp;
const char *sp;
lev += DLEV;
getderiv(lev + 1);
deriv.buf[lev] = deriv.buf[lev - 1] = 0;
for (t = suftab; (sp = t->suf) != NULL; t++) {
cp = ep;
while (*sp) {
if (*--cp != *sp++)
goto next;
}
for (sp = cp; --sp >= word && !vowel(*sp);)
; /* nothing */
if (sp < word)
return 0;
if ((*t->p1)(ep - t->n1, t->d1, t->a1, lev + 1))
return 1;
if (t->p2 != NULL) {
deriv.buf[lev] = deriv.buf[lev + 1] = NULL;
return (*t->p2)(ep - t->n2, t->d2, t->a2, lev);
}
return 0;
next: ;
}
return 0;
}
static int
/*ARGSUSED*/
nop(char *ep, const char *d, const char *a, size_t lev)
{
return 0;
}
static int
/*ARGSUSED*/
strip(char *ep, const char *d, const char *a, size_t lev)
{
return trypref(ep, a, lev) || suffix(ep, lev);
}
static int
s(char *ep, const char *d, const char *a, const size_t lev)
{
if (lev > DLEV + 1)
return 0;
if (*ep == 's' && ep[-1] == 's')
return 0;
return strip(ep, d, a, lev);
}
static int
/*ARGSUSED*/
an(char *ep, const char *d, const char *a, size_t lev)
{
if (!isupper((unsigned char)*word)) /* must be proper name */
return 0;
return trypref(ep, a, lev);
}
static int
/*ARGSUSED*/
ize(char *ep, const char *d, const char *a, size_t lev)
{
*ep++ = 'e';
return strip(ep ,"", d, lev);
}
static int
/*ARGSUSED*/
y_to_e(char *ep, const char *d, const char *a, size_t lev)
{
char c = *ep;
*ep++ = 'e';
if (strip(ep, "", d, lev))
return 1;
ep[-1] = c;
return 0;
}
static int
ily(char *ep, const char *d, const char *a, size_t lev)
{
if (ep[-1] == 'i')
return i_to_y(ep, d, a, lev);
else
return strip(ep, d, a, lev);
}
static int
ncy(char *ep, const char *d, const char *a, size_t lev)
{
if (skipv(skipv(ep - 1)) < word)
return 0;
ep[-1] = 't';
return strip(ep, d, a, lev);
}
static int
bility(char *ep, const char *d, const char *a, size_t lev)
{
*ep++ = 'l';
return y_to_e(ep, d, a, lev);
}
static int
i_to_y(char *ep, const char *d, const char *a, size_t lev)
{
if (ep[-1] == 'i') {
ep[-1] = 'y';
a = d;
}
return strip(ep, "", a, lev);
}
static int
es(char *ep, const char *d, const char *a, size_t lev)
{
if (lev > DLEV)
return 0;
switch (ep[-1]) {
default:
return 0;
case 'i':
return i_to_y(ep, d, a, lev);
case 's':
case 'h':
case 'z':
case 'x':
return strip(ep, d, a, lev);
}
}
static int
metry(char *ep, const char *d, const char *a, size_t lev)
{
ep[-2] = 'e';
ep[-1] = 'r';
return strip(ep, d, a, lev);
}
static int
tion(char *ep, const char *d, const char *a, size_t lev)
{
switch (ep[-2]) {
case 'c':
case 'r':
return trypref(ep, a, lev);
case 'a':
return y_to_e(ep, d, a, lev);
}
return 0;
}
/*
* Possible consonant-consonant-e ending.
*/
static int
CCe(char *ep, const char *d, const char *a, size_t lev)
{
switch (ep[-1]) {
case 'l':
if (vowel(ep[-2]))
break;
switch (ep[-2]) {
case 'l':
case 'r':
case 'w':
break;
default:
return y_to_e(ep, d, a, lev);
}
break;
case 's':
if (ep[-2] == 's')
break;
/*FALLTHROUGH*/
case 'c':
case 'g':
if (*ep == 'a')
return 0;
/*FALLTHROUGH*/
case 'v':
case 'z':
if (vowel(ep[-2]))
break;
/*FALLTHROUGH*/
case 'u':
if (y_to_e(ep, d, a, lev))
return 1;
if (!(ep[-2] == 'n' && ep[-1] == 'g'))
return 0;
}
return VCe(ep, d, a, lev);
}
/*
* Possible consonant-vowel-consonant-e ending.
*/
static int
VCe(char *ep, const char *d, const char *a, size_t lev)
{
char c;
c = ep[-1];
if (c == 'e')
return 0;
if (!vowel(c) && vowel(ep[-2])) {
c = *ep;
*ep++ = 'e';
if (trypref(ep, d, lev) || suffix(ep, lev))
return 1;
ep--;
*ep = c;
}
return strip(ep, d, a, lev);
}
static const char *
lookuppref(char **wp, char *ep)
{
const char **sp, *cp;
char *bp;
for (sp = preftab; *sp; sp++) {
bp = *wp;
for (cp = *sp; *cp; cp++, bp++) {
if (tolower((unsigned char)*bp) != *cp)
goto next;
}
for (cp = bp; cp < ep; cp++) {
if (vowel(*cp)) {
*wp = bp;
return *sp;
}
}
next: ;
}
return 0;
}
/*
* If the word is not in the dictionary, try stripping off prefixes
* until the word is found or we run out of prefixes to check.
*/
static int
trypref(char *ep, const char *a, size_t lev)
{
const char *cp;
char *bp;
char *pp;
int val = 0;
char space[20];
getderiv(lev + 2);
deriv.buf[lev] = a;
if (tryword(word, ep, lev))
return 1;
bp = word;
pp = space;
deriv.buf[lev + 1] = pp;
while ((cp = lookuppref(&bp, ep)) != NULL) {
*pp++ = '+';
while ((*pp = *cp++))
pp++;
if (tryword(bp, ep, lev + 1)) {
val = 1;
break;
}
if (pp - space >= sizeof(space))
return 0;
}
deriv.buf[lev + 1] = deriv.buf[lev + 2] = NULL;
return val;
}
static int
tryword(char *bp, char *ep, size_t lev)
{
size_t i, j;
char duple[3];
if (ep-bp <= 1)
return 0;
if (vowel(*ep) && monosyl(bp, ep))
return 0;
i = dict(bp, ep);
if (i == 0 && vowel(*ep) && ep[-1] == ep[-2] &&
monosyl(bp, ep - 1)) {
ep--;
getderiv(++lev);
deriv.buf[lev] = duple;
duple[0] = '+';
duple[1] = *ep;
duple[2] = '\0';
i = dict(bp, ep);
}
if (vflag == 0 || i == 0)
return i;
/* Also tack on possible derivations. (XXX - warn on truncation?) */
for (j = lev; j > 0; j--) {
if (deriv.buf[j])
(void)strlcat(affix, deriv.buf[j], sizeof(affix));
}
return i;
}
static int
monosyl(char *bp, char *ep)
{
if (ep < bp + 2)
return 0;
if (vowel(*--ep) || !vowel(*--ep) || ep[1] == 'x' || ep[1] == 'w')
return 0;
while (--ep >= bp)
if (vowel(*ep))
return 0;
return 1;
}
static char *
skipv(char *st)
{
if (st >= word && vowel(*st))
st--;
while (st >= word && !vowel(*st))
st--;
return st;
}
static int
vowel(int c)
{
switch (tolower(c)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
return 1;
}
return 0;
}
/*
* Crummy way to Britishise.
*/
static void
ise(void)
{
struct suftab *tab;
char *cp;
for (tab = suftab; tab->suf; tab++) {
/* Assume that suffix will contain 'z' if a1 or d1 do */
if (strchr(tab->suf, 'z')) {
tab->suf = cp = estrdup(tab->suf);
ztos(cp);
if (strchr(tab->d1, 'z')) {
tab->d1 = cp = estrdup(tab->d1);
ztos(cp);
}
if (strchr(tab->a1, 'z')) {
tab->a1 = cp = estrdup(tab->a1);
ztos(cp);
}
}
}
}
static void
ztos(char *st)
{
for (; *st; st++)
if (*st == 'z')
*st = 's';
}
/*
* Look up a word in the dictionary.
* Returns 1 if found, 0 if not.
*/
static int
dict(char *bp, char *ep)
{
char c;
int i, rval;
c = *ep;
*ep = '\0';
if (xflag)
printf("=%s\n", bp);
for (i = rval = 0; wlists[i].fd != -1; i++) {
if ((rval = look((unsigned char *)bp, wlists[i].front,
wlists[i].back)) == 1)
break;
}
*ep = c;
return rval;
}
static void
getderiv(size_t lev)
{
if (deriv.maxlev < lev) {
if (reallocarr(&deriv.buf, lev, sizeof(*deriv.buf)) != 0)
err(1, "Cannot grow array");
deriv.maxlev = lev;
}
}
static void
usage(void)
{
(void)fprintf(stderr,
"Usage: %s [-bvx] [-o found-words] word-list ...\n",
getprogname());
exit(1);
}
|
7fbe4e6cb0138917b71da68f0d50438a140796cf
|
de21f9075f55640514c29ef0f1fe3f0690845764
|
/regression/cprover/float/basic-float1.c
|
90a781ffcdb52d0cff0d3be7ef96b4f8dc304816
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause"
] |
permissive
|
diffblue/cbmc
|
975a074ac445febb3b5715f8792beb545522dc18
|
decd2839c2f51a54b2ad0f3e89fdc1b4bf78cd16
|
refs/heads/develop
| 2023-08-31T05:52:05.342195
| 2023-08-30T13:31:51
| 2023-08-30T13:31:51
| 51,877,056
| 589
| 309
|
NOASSERTION
| 2023-09-14T18:49:17
| 2016-02-16T23:03:52
|
C++
|
UTF-8
|
C
| false
| false
| 94
|
c
|
basic-float1.c
|
int main()
{
float f = 1.0;
__CPROVER_assert(f + 0.5f == 1.5f, "addition");
return 0;
}
|
caebced1b76c5e49c07da41fef89443c84eee4c9
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/bsp/Infineon/libraries/IFX_PSOC6_HAL/mtb-pdl-cat1/drivers/include/cy_cryptolite.h
|
1883842da7858551b9b5c92530aab22f2a47f16b
|
[
"Apache-2.0",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"MIT",
"BSD-3-Clause",
"X11",
"BSD-4-Clause-UC",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 4,489
|
h
|
cy_cryptolite.h
|
/***************************************************************************//**
* \file cy_cryptolite.h
* \version 2.0
*
* \brief
* This file provides interface header
* for the Cryptolite PDL driver.
*
********************************************************************************
* \copyright
* Copyright (c) (2020-2022), Cypress Semiconductor Corporation (an Infineon company) or
* an affiliate of Cypress Semiconductor Corporation.
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*******************************************************************************/
/**
* \addtogroup group_cryptolite
* \{
* \note IP Supported: CRYPTOLITE
* \note Device Categories: CAT1B. Please refer <a href="usergroup1.html">Device Catalog</a>.
*
* The Cryptolite driver provides a public API to perform SHA256 hash
* calculation, using a cryptolite hardware IP block to accelerate operation.
*
* The functions and other declarations used in this driver are in cy_cryptolite.h.
* You can also include cy_pdl.h to get access to all functions and declarations in the PDL.
*
* The Cryptolite driver supports only SHA256.
*
* \section group_cryptolite_sha256_configuration_considerations Configuration Considerations
*
* Firmware sets up a cryptographic operation by passing in the required data as
* parameters in the function call.
*
* Cryptolite SHA256 function require a context. A context is a data
* structure that the driver uses for its operations. Firmware declares a
* context (allocates memory) but does not write or read the values in that
* context. In effect, the context is a scratch pad you provide to the driver.
* The driver uses the context to store and manipulate data during cryptographic
* operations. The Cryptolite driver header file declare all the required structures
* for context.
*
* Note: Cryptolite works only with SAHB mapped address, User must map any CBUS mapped
* address to SAHB address before using the API.
*
* \section group_cryptolite_sha256_definitions Definitions
*
* <table class="doxtable">
* <tr>
* <th>Term</th>
* <th>Definition</th>
* </tr>
*
* <tr>
* <td>Secure Hash Algorithm (SHA)</td>
* <td>A cryptographic hash function.
* This function takes a message of an arbitrary length and reduces it to a
* fixed-length residue or message digest after performing a series of
* mathematically defined operations that practically guarantee that any
* change in the message will change the hash value. It is used for message
* authentication by transmitting a message with a hash value appended to it
* and recalculating the message hash value using the same algorithm at the
* recipient's end. If the hashes differ, then the message is corrupted.
* For more information see [Secure Hash standard description]
* (https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2.pdf).
* </td>
* </tr>
*
* </table>
*
* \section group_cryptolite_changelog Changelog
* <table class="doxtable">
* <tr><th>Version</th><th>Changes</th><th>Reason for Change</th></tr>
* <tr>
* <td>2.0</td>
* <td>Renamed the sha256 context structure from cy_stc_cryptolite_context_sha_t to cy_stc_cryptolite_context_sha256_t </td>
* <td></td>
* </tr>
* <tr>
* <td>1.0</td>
* <td>Initial Version</td>
* <td></td>
* </tr>
* </table>
* \defgroup group_cryptolite_lld_sha Hash operations (SHA)
* \{
* \defgroup group_cryptolite_lld_sha_functions Functions
* \}
* \defgroup group_cryptolite_data_structures Common Data Structures
* \defgroup group_cryptolite_enums Common Enumerated Types
* \defgroup group_cryptolite_macros Macros
*/
#if !defined (CY_CRYPTOLITE_H)
#define CY_CRYPTOLITE_H
#include "cy_device.h"
#if defined (CY_IP_MXCRYPTOLITE)
#include "cy_cryptolite_sha256.h"
#endif /* CY_IP_MXCRYPTOLITE */
#endif /* #if !defined (CY_CRYPTOLITE_H) */
/** \} group_cryptolite */
/* [] END OF FILE */
|
d26dd72620a82c1ff562dc08700de76a346229c7
|
58fe7cb3949dd1930e709696659a0296500b64a6
|
/tls/s2n_cipher_preferences.c
|
cd3406d2a92ae646a39ca82c1914ac1c91c9a467
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
aws/s2n-tls
|
3344638a6a69c6f20665cf6847e1bc4b85f2e558
|
62dc7a6d4876e5eee0dea3690d528a4c7080a1d5
|
refs/heads/main
| 2023-08-31T23:26:33.780048
| 2023-08-31T05:17:33
| 2023-08-31T05:17:33
| 21,287,076
| 513
| 213
|
Apache-2.0
| 2023-09-13T23:52:29
| 2014-06-27T19:37:59
|
C
|
UTF-8
|
C
| false
| false
| 77,368
|
c
|
s2n_cipher_preferences.c
|
/*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 "tls/s2n_cipher_preferences.h"
#include <stdint.h>
#include <strings.h>
#include "api/s2n.h"
#include "error/s2n_errno.h"
#include "tls/s2n_config.h"
#include "tls/s2n_kem.h"
#include "tls/s2n_kex.h"
#include "utils/s2n_safety.h"
/* clang-format off */
/* TLS 1.3 cipher suites, in order of preference.
* Can be added to other ciphers suite lists to enable
* TLS1.3 compatibility. */
#define S2N_TLS13_CIPHER_SUITES_20190801 \
&s2n_tls13_aes_256_gcm_sha384, \
&s2n_tls13_aes_128_gcm_sha256, \
&s2n_tls13_chacha20_poly1305_sha256
#define S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716 \
&s2n_tls13_aes_128_gcm_sha256, \
&s2n_tls13_aes_256_gcm_sha384, \
&s2n_tls13_chacha20_poly1305_sha256
/* s2n's list of cipher suites, in order of preferences, as of 2019-08-01 */
struct s2n_cipher_suite *cipher_suites_20190801[] = {
S2N_TLS13_CIPHER_SUITES_20190801,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_20190801 = {
.count = s2n_array_len(cipher_suites_20190801),
.suites = cipher_suites_20190801,
.allow_chacha20_boosting = false,
};
/* Same as 20190801, but with ECDSA for TLS 1.2 added */
struct s2n_cipher_suite *cipher_suites_20210831[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_20210831 = {
.count = s2n_array_len(cipher_suites_20210831),
.suites = cipher_suites_20210831,
.allow_chacha20_boosting = false,
};
/*
* These cipher suites were chosen based on the following specification:
* https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-52r2.pdf
*/
struct s2n_cipher_suite *cipher_suites_default_fips[] = {
/* tls1.2 with ECDSA */
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
/* tls1.2 with RSA */
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
};
const struct s2n_cipher_preferences cipher_preferences_default_fips = {
.count = s2n_array_len(cipher_suites_default_fips),
.suites = cipher_suites_default_fips,
.allow_chacha20_boosting = false,
};
/* s2n's list of cipher suites, in order of preference, as of 2014-06-01 */
struct s2n_cipher_suite *cipher_suites_20140601[] = {
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_rc4_128_sha,
&s2n_rsa_with_rc4_128_md5
};
const struct s2n_cipher_preferences cipher_preferences_20140601 = {
.count = s2n_array_len(cipher_suites_20140601),
.suites = cipher_suites_20140601,
.allow_chacha20_boosting = false,
};
/* Disable SSLv3 due to POODLE */
const struct s2n_cipher_preferences cipher_preferences_20141001 = {
.count = s2n_array_len(cipher_suites_20140601),
.suites = cipher_suites_20140601,
.allow_chacha20_boosting = false,
};
/* Disable RC4 */
struct s2n_cipher_suite *cipher_suites_20150202[] = {
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_20150202 = {
.count = s2n_array_len(cipher_suites_20150202),
.suites = cipher_suites_20150202,
.allow_chacha20_boosting = false,
};
/* Support AES-GCM modes */
struct s2n_cipher_suite *cipher_suites_20150214[] = {
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_20150214 = {
.count = s2n_array_len(cipher_suites_20150214),
.suites = cipher_suites_20150214,
.allow_chacha20_boosting = false,
};
/* Make a CBC cipher #1 to avoid negotiating GCM with buggy Java clients */
struct s2n_cipher_suite *cipher_suites_20160411[] = {
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_20160411 = {
.count = s2n_array_len(cipher_suites_20160411),
.suites = cipher_suites_20160411,
.allow_chacha20_boosting = false,
};
/* Use ECDHE instead of plain DHE. Prioritize ECDHE in favour of non ECDHE; GCM in favour of CBC; AES128 in favour of AES256. */
struct s2n_cipher_suite *cipher_suites_20150306[] = {
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_3des_ede_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_20150306 = {
.count = s2n_array_len(cipher_suites_20150306),
.suites = cipher_suites_20150306,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_20160804[] = {
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_20160804 = {
.count = s2n_array_len(cipher_suites_20160804),
.suites = cipher_suites_20160804,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_20160824[] = {
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_20160824 = {
.count = s2n_array_len(cipher_suites_20160824),
.suites = cipher_suites_20160824,
.allow_chacha20_boosting = false,
};
/* Add ChaCha20 suite */
struct s2n_cipher_suite *cipher_suites_20170210[] = {
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_20170210 = {
.count = s2n_array_len(cipher_suites_20170210),
.suites = cipher_suites_20170210,
.allow_chacha20_boosting = false,
};
/*
* TLS1.3 support.
* FIPS compliant.
* No DHE (would require extra setup with s2n_config_add_dhparams)
*/
struct s2n_cipher_suite *cipher_suites_20230317[] = {
/* TLS1.2 with ECDSA */
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
/* TLS1.2 with RSA */
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
/* TLS1.3 */
&s2n_tls13_aes_128_gcm_sha256,
&s2n_tls13_aes_256_gcm_sha384,
};
const struct s2n_cipher_preferences cipher_preferences_20230317 = {
.count = s2n_array_len(cipher_suites_20230317),
.suites = cipher_suites_20230317,
.allow_chacha20_boosting = false,
};
/* Same as 20160411, but with ChaCha20 added as 1st in Preference List */
struct s2n_cipher_suite *cipher_suites_20190122[] = {
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_20190122 = {
.count = s2n_array_len(cipher_suites_20190122),
.suites = cipher_suites_20190122,
.allow_chacha20_boosting = false,
};
/* Same as 20160804, but with ChaCha20 added as 2nd in Preference List */
struct s2n_cipher_suite *cipher_suites_20190121[] = {
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_20190121 = {
.count = s2n_array_len(cipher_suites_20190121),
.suites = cipher_suites_20190121,
.allow_chacha20_boosting = false,
};
/* Same as 20160411, but with ChaCha20 in 3rd Place after CBC and GCM */
struct s2n_cipher_suite *cipher_suites_20190120[] = {
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_20190120 = {
.count = s2n_array_len(cipher_suites_20190120),
.suites = cipher_suites_20190120,
.allow_chacha20_boosting = false,
};
/* Preferences optimized for interop, includes ECDSA priortitized. DHE and 3DES are added(at the lowest preference). */
struct s2n_cipher_suite *cipher_suites_20190214[] = {
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_20190214 = {
.count = s2n_array_len(cipher_suites_20190214),
.suites = cipher_suites_20190214,
.allow_chacha20_boosting = false,
};
/* 20190214 with aes-gcm prioritized above aes-cbc */
struct s2n_cipher_suite *cipher_suites_20190214_gcm[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_20190214_gcm = {
.count = s2n_array_len(cipher_suites_20190214_gcm),
.suites = cipher_suites_20190214_gcm,
.allow_chacha20_boosting = false,
};
/* Same as cipher_suites_20190214, but with TLS 1.3 Ciphers */
struct s2n_cipher_suite *cipher_suites_20210825[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_20210825 = {
.count = s2n_array_len(cipher_suites_20210825),
.suites = cipher_suites_20210825,
.allow_chacha20_boosting = false,
};
/* Same as cipher_suites_20190214_gcm, but with TLS 1.3 Ciphers */
struct s2n_cipher_suite *cipher_suites_20210825_gcm[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_20210825_gcm = {
.count = s2n_array_len(cipher_suites_20210825_gcm),
.suites = cipher_suites_20210825_gcm,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_null[] = {
&s2n_null_cipher_suite
};
const struct s2n_cipher_preferences cipher_preferences_null = {
.count = s2n_array_len(cipher_suites_null),
.suites = cipher_suites_null,
.allow_chacha20_boosting = false,
};
/* Preferences optimized for interop. DHE and 3DES are added(at the lowest preference). */
struct s2n_cipher_suite *cipher_suites_20170328[] = {
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_20170328 = {
.count = s2n_array_len(cipher_suites_20170328),
.suites = cipher_suites_20170328,
.allow_chacha20_boosting = false,
};
/* Equivalent to cipher_suites_20170328 with aes-gcm prioritized above aes-cbc */
struct s2n_cipher_suite *cipher_suites_20170328_gcm[] = {
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_20170328_gcm = {
.count = s2n_array_len(cipher_suites_20170328_gcm),
.suites = cipher_suites_20170328_gcm,
.allow_chacha20_boosting = false,
};
/* Preferences optimized for FIPS compatibility. */
struct s2n_cipher_suite *cipher_suites_20170405[] = {
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_20170405 = {
.count = s2n_array_len(cipher_suites_20170405),
.suites = cipher_suites_20170405,
.allow_chacha20_boosting = false,
};
/* Preferences optimized for FIPS compatibility with GCM prioritized */
struct s2n_cipher_suite *cipher_suites_20170405_gcm[] = {
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_20170405_gcm = {
.count = s2n_array_len(cipher_suites_20170405_gcm),
.suites = cipher_suites_20170405_gcm,
.allow_chacha20_boosting = false,
};
/* Equivalent to cipher_suite_20160411 with 3DES removed.
* Make a CBC cipher #1 to avoid negotiating GCM with buggy Java clients. */
struct s2n_cipher_suite *cipher_suites_20170718[] = {
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_20170718 = {
.count = s2n_array_len(cipher_suites_20170718),
.suites = cipher_suites_20170718,
.allow_chacha20_boosting = false,
};
/* Equivalent to cipher_suites_20170718 with aes-gcm prioritized above aes-cbc */
struct s2n_cipher_suite *cipher_suites_20170718_gcm[] = {
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_20170718_gcm = {
.count = s2n_array_len(cipher_suites_20170718_gcm),
.suites = cipher_suites_20170718_gcm,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_elb_security_policy_2015_04[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
};
const struct s2n_cipher_preferences elb_security_policy_2015_04 = {
.count = s2n_array_len(cipher_suites_elb_security_policy_2015_04),
.suites = cipher_suites_elb_security_policy_2015_04,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_elb_security_policy_2016_08[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences elb_security_policy_2016_08 = {
.count = s2n_array_len(cipher_suites_elb_security_policy_2016_08),
.suites = cipher_suites_elb_security_policy_2016_08,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_elb_security_policy_tls_1_2_2017_01[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences elb_security_policy_tls_1_2_2017_01 = {
.count = s2n_array_len(cipher_suites_elb_security_policy_tls_1_2_2017_01),
.suites = cipher_suites_elb_security_policy_tls_1_2_2017_01,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_elb_security_policy_tls_1_1_2017_01[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences elb_security_policy_tls_1_1_2017_01 = {
.count = s2n_array_len(cipher_suites_elb_security_policy_tls_1_1_2017_01),
.suites = cipher_suites_elb_security_policy_tls_1_1_2017_01,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_elb_security_policy_tls_1_2_ext_2018_06[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences elb_security_policy_tls_1_2_ext_2018_06 = {
.count = s2n_array_len(cipher_suites_elb_security_policy_tls_1_2_ext_2018_06),
.suites = cipher_suites_elb_security_policy_tls_1_2_ext_2018_06,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_elb_security_policy_fs_2018_06[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences elb_security_policy_fs_2018_06 = {
.count = s2n_array_len(cipher_suites_elb_security_policy_fs_2018_06),
.suites = cipher_suites_elb_security_policy_fs_2018_06,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_elb_security_policy_fs_1_2_2019_08[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences elb_security_policy_fs_1_2_2019_08 = {
.count = s2n_array_len(cipher_suites_elb_security_policy_fs_1_2_2019_08),
.suites = cipher_suites_elb_security_policy_fs_1_2_2019_08,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_elb_security_policy_fs_1_1_2019_08[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences elb_security_policy_fs_1_1_2019_08 = {
.count = s2n_array_len(cipher_suites_elb_security_policy_fs_1_1_2019_08),
.suites = cipher_suites_elb_security_policy_fs_1_1_2019_08,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_elb_security_policy_fs_1_2_Res_2019_08[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
};
const struct s2n_cipher_preferences elb_security_policy_fs_1_2_Res_2019_08 = {
.count = s2n_array_len(cipher_suites_elb_security_policy_fs_1_2_Res_2019_08),
.suites = cipher_suites_elb_security_policy_fs_1_2_Res_2019_08,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_upstream[] = {
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_rc4_128_md5
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_upstream = {
.count = s2n_array_len(cipher_suites_cloudfront_upstream),
.suites = cipher_suites_cloudfront_upstream,
.allow_chacha20_boosting = false,
};
/* CloudFront viewer facing (with TLS 1.3) */
struct s2n_cipher_suite *cipher_suites_cloudfront_ssl_v_3[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_rc4_128_md5
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_ssl_v_3 = {
.count = s2n_array_len(cipher_suites_cloudfront_ssl_v_3),
.suites = cipher_suites_cloudfront_ssl_v_3,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_0_2014[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_0_2014 = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_0_2014),
.suites = cipher_suites_cloudfront_tls_1_0_2014,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_0_2016[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_0_2016 = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_0_2016),
.suites = cipher_suites_cloudfront_tls_1_0_2016,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_1_2016[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_1_2016 = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_1_2016),
.suites = cipher_suites_cloudfront_tls_1_1_2016,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_2_2017[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_2_2017 = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_2_2017),
.suites = cipher_suites_cloudfront_tls_1_2_2017,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_2_2018[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_2_2018 = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_2_2018),
.suites = cipher_suites_cloudfront_tls_1_2_2018,
.allow_chacha20_boosting = false,
};
/* CloudFront viewer facing legacy TLS 1.2 policies */
struct s2n_cipher_suite *cipher_suites_cloudfront_ssl_v_3_legacy[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_rc4_128_md5
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_ssl_v_3_legacy = {
.count = s2n_array_len(cipher_suites_cloudfront_ssl_v_3_legacy),
.suites = cipher_suites_cloudfront_ssl_v_3_legacy,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_0_2014_legacy[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_0_2014_legacy = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_0_2014_legacy),
.suites = cipher_suites_cloudfront_tls_1_0_2014_legacy,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_0_2016_legacy[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_0_2016_legacy = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_0_2016_legacy),
.suites = cipher_suites_cloudfront_tls_1_0_2016_legacy,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_1_2016_legacy[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_1_2016_legacy = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_1_2016_legacy),
.suites = cipher_suites_cloudfront_tls_1_1_2016_legacy,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_2_2018_legacy[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_2_2018_legacy = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_2_2018_legacy),
.suites = cipher_suites_cloudfront_tls_1_2_2018_legacy,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_2_2019_legacy[] = {
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_2_2019_legacy = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_2_2019_legacy),
.suites = cipher_suites_cloudfront_tls_1_2_2019_legacy,
.allow_chacha20_boosting = false,
};
/* CloudFront upstream */
struct s2n_cipher_suite *cipher_suites_cloudfront_upstream_tls10[] = {
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_rc4_128_md5
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_upstream_tls10 = {
.count = s2n_array_len(cipher_suites_cloudfront_upstream_tls10),
.suites = cipher_suites_cloudfront_upstream_tls10,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_upstream_tls11[] = {
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_rc4_128_md5
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_upstream_tls11 = {
.count = s2n_array_len(cipher_suites_cloudfront_upstream_tls11),
.suites = cipher_suites_cloudfront_upstream_tls11,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_upstream_tls12[] = {
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_rc4_128_md5
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_upstream_tls12 = {
.count = s2n_array_len(cipher_suites_cloudfront_upstream_tls12),
.suites = cipher_suites_cloudfront_upstream_tls12,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_2_2019[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_2_2019 = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_2_2019),
.suites = cipher_suites_cloudfront_tls_1_2_2019,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_cloudfront_tls_1_2_2021[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256
};
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_2_2021 = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_2_2021),
.suites = cipher_suites_cloudfront_tls_1_2_2021,
.allow_chacha20_boosting = false,
};
/* Duplicate of cipher_preferences_cloudfront_tls_1_2_2021 but with allow_chacha20_boosting enabled */
const struct s2n_cipher_preferences cipher_preferences_cloudfront_tls_1_2_2021_chacha20_boosted = {
.count = s2n_array_len(cipher_suites_cloudfront_tls_1_2_2021),
.suites = cipher_suites_cloudfront_tls_1_2_2021,
.allow_chacha20_boosting = true,
};
/* Based on cipher_preferences_cloudfront_tls_1_0_2016, but with ordering changed and AES256-SHA256, DES-CBC3-SHA, and
* RC4-MD5 added for compatibility. */
struct s2n_cipher_suite *cipher_suites_aws_crt_sdk_ssl_v3[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_rsa_with_rc4_128_md5
};
const struct s2n_cipher_preferences cipher_preferences_aws_crt_sdk_ssl_v3 = {
.count = s2n_array_len(cipher_suites_aws_crt_sdk_ssl_v3),
.suites = cipher_suites_aws_crt_sdk_ssl_v3,
.allow_chacha20_boosting = false,
};
/* Based on cipher_preferences_cloudfront_tls_1_0_2016, but with ordering changed and AES256-SHA256 added for
* compatibility. */
struct s2n_cipher_suite *cipher_suites_aws_crt_sdk_default[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_rsa_with_chacha20_poly1305_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_aws_crt_sdk_default = {
.count = s2n_array_len(cipher_suites_aws_crt_sdk_default),
.suites = cipher_suites_aws_crt_sdk_default,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_aws_crt_sdk_tls_13[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716
};
const struct s2n_cipher_preferences cipher_preferences_aws_crt_sdk_tls_13 = {
.count = s2n_array_len(cipher_suites_aws_crt_sdk_tls_13),
.suites = cipher_suites_aws_crt_sdk_tls_13,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_kms_tls_1_0_2018_10[] = {
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_kms_tls_1_0_2018_10 = {
.count = s2n_array_len(cipher_suites_kms_tls_1_0_2018_10),
.suites = cipher_suites_kms_tls_1_0_2018_10,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_kms_tls_1_0_2021_08[] = {
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_kms_tls_1_0_2021_08 = {
.count = s2n_array_len(cipher_suites_kms_tls_1_0_2021_08),
.suites = cipher_suites_kms_tls_1_0_2021_08,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_kms_pq_tls_1_0_2019_06[] = {
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
};
/* Includes only round 1 PQ KEM params */
const struct s2n_cipher_preferences cipher_preferences_kms_pq_tls_1_0_2019_06 = {
.count = s2n_array_len(cipher_suites_kms_pq_tls_1_0_2019_06),
.suites = cipher_suites_kms_pq_tls_1_0_2019_06,
.allow_chacha20_boosting = false,
};
/* Includes round 1 and round 2 PQ KEM params. The cipher suite list is the same
* as in cipher_preferences_kms_pq_tls_1_0_2019_06.*/
const struct s2n_cipher_preferences cipher_preferences_kms_pq_tls_1_0_2020_02 = {
.count = s2n_array_len(cipher_suites_kms_pq_tls_1_0_2019_06),
.suites = cipher_suites_kms_pq_tls_1_0_2019_06,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_pq_sike_test_tls_1_0_2019_11[] = {
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
};
/* Previously included only SIKE round 1 (for integration tests) */
const struct s2n_cipher_preferences cipher_preferences_pq_sike_test_tls_1_0_2019_11 = {
.count = s2n_array_len(cipher_suites_pq_sike_test_tls_1_0_2019_11),
.suites = cipher_suites_pq_sike_test_tls_1_0_2019_11,
.allow_chacha20_boosting = false,
};
/* Previously included SIKE round 1 and round 2 (for integration tests). The cipher suite list
* is the same as in cipher_preferences_pq_sike_test_tls_1_0_2019_11. */
const struct s2n_cipher_preferences cipher_preferences_pq_sike_test_tls_1_0_2020_02 = {
.count = s2n_array_len(cipher_suites_pq_sike_test_tls_1_0_2019_11),
.suites = cipher_suites_pq_sike_test_tls_1_0_2019_11,
.allow_chacha20_boosting = false,
};
/* Includes Kyber PQ algorithm */
struct s2n_cipher_suite *cipher_suites_kms_pq_tls_1_0_2020_07[] = {
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_kms_pq_tls_1_0_2020_07 = {
.count = s2n_array_len(cipher_suites_kms_pq_tls_1_0_2020_07),
.suites = cipher_suites_kms_pq_tls_1_0_2020_07,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_pq_tls_1_0_2020_12[] = {
S2N_TLS13_CIPHER_SUITES_20190801,
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_0_2020_12 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_0_2020_12),
.suites = cipher_suites_pq_tls_1_0_2020_12,
.allow_chacha20_boosting = false,
};
/* Same as ELBSecurityPolicy-TLS-1-1-2017-01, but with PQ Ciphers appended to top of preference list */
struct s2n_cipher_suite *cipher_suites_pq_tls_1_1_2021_05_17[] = {
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_1_2021_05_17 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_1_2021_05_17),
.suites = cipher_suites_pq_tls_1_1_2021_05_17,
.allow_chacha20_boosting = false,
};
/* Same as cipher_preferences_20190214, but with PQ Ciphers appended to top of preference list */
struct s2n_cipher_suite *cipher_suites_pq_tls_1_0_2021_05_18[] = {
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_0_2021_05_18 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_0_2021_05_18),
.suites = cipher_suites_pq_tls_1_0_2021_05_18,
.allow_chacha20_boosting = false,
};
/* Same as ELBSecurityPolicy-2016-08, but with PQ Ciphers appended to top of preference list */
struct s2n_cipher_suite *cipher_suites_pq_tls_1_0_2021_05_19[] = {
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_0_2021_05_19 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_0_2021_05_19),
.suites = cipher_suites_pq_tls_1_0_2021_05_19,
.allow_chacha20_boosting = false,
};
/* Same as ELBSecurityPolicy-TLS-1-1-2017-01, but with TLS 1.3 and PQ Ciphers appended to top of preference list */
struct s2n_cipher_suite *cipher_suites_pq_tls_1_1_2021_05_21[] = {
/* TLS 1.3 Ciphers don't specify their Key exchange method, allowing for Hybrid PQ KEMs to be negotiated separately */
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_1_2021_05_21 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_1_2021_05_21),
.suites = cipher_suites_pq_tls_1_1_2021_05_21,
.allow_chacha20_boosting = false,
};
/* Same as cipher_preferences_20190214, but with TLS 1.3 and PQ Ciphers appended to top of preference list */
struct s2n_cipher_suite *cipher_suites_pq_tls_1_0_2021_05_22[] = {
/* TLS 1.3 Ciphers don't specify their Key exchange method, allowing for Hybrid PQ KEMs to be negotiated separately */
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_0_2021_05_22 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_0_2021_05_22),
.suites = cipher_suites_pq_tls_1_0_2021_05_22,
.allow_chacha20_boosting = false,
};
/* Same as ELBSecurityPolicy-2016-08, but with TLS 1.3 and PQ Ciphers appended to top of preference list */
struct s2n_cipher_suite *cipher_suites_pq_tls_1_0_2021_05_23[] = {
/* TLS 1.3 Ciphers don't specify their Key exchange method, allowing for Hybrid PQ KEMs to be negotiated separately */
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_0_2021_05_23 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_0_2021_05_23),
.suites = cipher_suites_pq_tls_1_0_2021_05_23,
.allow_chacha20_boosting = false,
};
/* Same as cipher_preferences_kms_pq_tls_1_0_2020_07, but with TLS 1.3 appended to top of preference list */
struct s2n_cipher_suite *cipher_suites_pq_tls_1_0_2021_05_24[] = {
/* TLS 1.3 Ciphers don't specify their Key exchange method, allowing for Hybrid PQ KEMs to be negotiated separately */
S2N_TLS13_CIPHER_SUITES_20190801,
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_0_2021_05_24 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_0_2021_05_24),
.suites = cipher_suites_pq_tls_1_0_2021_05_24,
.allow_chacha20_boosting = false,
};
/* Same as 20190214_gcm, but with PQ Ciphers appended to top of preference list */
struct s2n_cipher_suite *cipher_suites_pq_tls_1_0_2021_05_25[] = {
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_0_2021_05_25 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_0_2021_05_25),
.suites = cipher_suites_pq_tls_1_0_2021_05_25,
.allow_chacha20_boosting = false,
};
/* Same as 20190214_gcm, but with TLS 1.3 and PQ Ciphers appended to top of preference list */
struct s2n_cipher_suite *cipher_suites_pq_tls_1_0_2021_05_26[] = {
/* TLS 1.3 Ciphers don't specify their Key exchange method, allowing for Hybrid PQ KEMs to be negotiated separately */
S2N_TLS13_CLOUDFRONT_CIPHER_SUITES_20200716,
&s2n_ecdhe_kyber_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_0_2021_05_26 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_0_2021_05_26),
.suites = cipher_suites_pq_tls_1_0_2021_05_26,
.allow_chacha20_boosting = false,
};
/* Same as 2021_05_26 except:
*
* 1. TLSv1.2 Kyber KEM cipher suites are removed
* 2. AES 256 is preferred for TLS 1.3
* 3. AES 128 is preferred for TLS 1.2 which has no PQ support in PQ-TLS-1-3-2023-06-01
*/
struct s2n_cipher_suite *cipher_suites_pq_tls_1_3_2023_06_01[] = {
S2N_TLS13_CIPHER_SUITES_20190801,
&s2n_ecdhe_ecdsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_rsa_with_aes_128_gcm_sha256,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_128_cbc_sha,
&s2n_rsa_with_aes_128_cbc_sha256,
&s2n_rsa_with_aes_256_cbc_sha,
&s2n_rsa_with_aes_256_cbc_sha256,
&s2n_rsa_with_3des_ede_cbc_sha,
&s2n_dhe_rsa_with_aes_128_gcm_sha256,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_128_cbc_sha,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_pq_tls_1_3_2023_06_01 = {
.count = s2n_array_len(cipher_suites_pq_tls_1_3_2023_06_01),
.suites = cipher_suites_pq_tls_1_3_2023_06_01,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_kms_fips_tls_1_2_2018_10[] = {
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_kms_fips_tls_1_2_2018_10 = {
.count = s2n_array_len(cipher_suites_kms_fips_tls_1_2_2018_10),
.suites = cipher_suites_kms_fips_tls_1_2_2018_10,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_kms_fips_tls_1_2_2021_08[] = {
&s2n_tls13_aes_128_gcm_sha256,
&s2n_tls13_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_128_gcm_sha256,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_128_cbc_sha256,
&s2n_dhe_rsa_with_aes_256_cbc_sha256,
&s2n_dhe_rsa_with_aes_128_cbc_sha256,
};
const struct s2n_cipher_preferences cipher_preferences_kms_fips_tls_1_2_2021_08 = {
.count = s2n_array_len(cipher_suites_kms_fips_tls_1_2_2021_08),
.suites = cipher_suites_kms_fips_tls_1_2_2021_08,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_20210816[] = {
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
};
const struct s2n_cipher_preferences cipher_preferences_20210816 = {
.count = s2n_array_len(cipher_suites_20210816),
.suites = cipher_suites_20210816,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_20210816_gcm[] = {
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_ecdsa_with_aes_256_cbc_sha384,
&s2n_ecdhe_rsa_with_aes_256_cbc_sha384,
};
const struct s2n_cipher_preferences cipher_preferences_20210816_gcm = {
.count = s2n_array_len(cipher_suites_20210816_gcm),
.suites = cipher_suites_20210816_gcm,
.allow_chacha20_boosting = false,
};
struct s2n_cipher_suite *cipher_suites_rfc9151[] = {
/* TLS1.2 */
&s2n_ecdhe_ecdsa_with_aes_256_gcm_sha384,
&s2n_ecdhe_rsa_with_aes_256_gcm_sha384,
&s2n_rsa_with_aes_256_gcm_sha384,
&s2n_dhe_rsa_with_aes_256_gcm_sha384,
/* TLS1.3 */
&s2n_tls13_aes_256_gcm_sha384,
};
const struct s2n_cipher_preferences cipher_preferences_rfc9151 = {
.count = s2n_array_len(cipher_suites_rfc9151),
.suites = cipher_suites_rfc9151,
.allow_chacha20_boosting = false,
};
/* clang-format on */
|
cf08c6e5a38b720f8637ca91905e4c5ae411bdf2
|
bb82a5f977bef455714c16e24e2d8254e2d0faa5
|
/src/vendor/cget/cget/pkg/pqrs-org__cpp-osx-process_info/install/include/pqrs/osx/process_info/impl/impl.h
|
2a21265428e16e1888d236832a598946ceff4dea
|
[
"Unlicense"
] |
permissive
|
pqrs-org/Karabiner-Elements
|
4ae307d82f8b67547c161c7d46d2083a0fd07630
|
d05057d7c769e2ff35638282e888a6d5eca566be
|
refs/heads/main
| 2023-09-01T03:11:08.474417
| 2023-09-01T00:44:19
| 2023-09-01T00:44:19
| 63,037,806
| 8,197
| 389
|
Unlicense
| 2023-09-01T00:11:00
| 2016-07-11T04:57:55
|
C++
|
UTF-8
|
C
| false
| false
| 538
|
h
|
impl.h
|
#pragma once
// (C) Copyright Takayama Fumihiko 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See https://www.boost.org/LICENSE_1_0.txt)
#ifdef __cplusplus
extern "C" {
#endif
// Do not use these functions directly.
void pqrs_osx_process_info_create_globally_unique_string(char* buffer, int buffer_size);
int pqrs_osx_process_info_process_identifier(void);
void pqrs_osx_process_info_disable_sudden_termination(void);
void pqrs_osx_process_info_enable_sudden_termination(void);
#ifdef __cplusplus
}
#endif
|
3302f9904616948b58df1f03a6b3b7eb3c5f6b12
|
4e366db41b2bb755c5a1d8fa8149bf619ac7c970
|
/components/x11/dispswitch/src/dispswitch.c
|
15e6efe4bf37bad935814dfc6478f99f1d37cbce
|
[
"HPND-sell-variant",
"MIT"
] |
permissive
|
OpenIndiana/oi-userland
|
0af05f09a04dc95d814fce1d56ff1d74f07fd042
|
a40cd6c757239bcf4e1f0d5943a65d9b57fbc3f7
|
refs/heads/oi/hipster
| 2023-09-04T04:41:58.585774
| 2023-09-03T18:00:28
| 2023-09-03T18:00:28
| 10,007,731
| 220
| 334
| null | 2023-09-14T21:48:26
| 2013-05-12T01:29:19
|
C
|
UTF-8
|
C
| false
| false
| 49,593
|
c
|
dispswitch.c
|
/*
* Copyright © 2001 Keith Packard, member of The XFree86 Project, Inc.
* Copyright © 2002 Hewlett Packard Company, Inc.
* Copyright © 2006 Intel Corporation
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting documentation, and
* that the name of the copyright holders not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no representations
* about the suitability of this software for any purpose. It is provided "as
* is" without express or implied warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*
*/
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
*
* 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 (including the next
* paragraph) 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.
*/
#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xlibint.h>
#include <X11/Xproto.h>
#include <X11/extensions/Xrandr.h>
#include <X11/Xos.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/proc.h>
#include <unistd.h>
static char *program_name;
static Display *dpy = NULL;
static Window root, win;
static int screen;
static Bool nosideview = False;
static Bool verbose = False;
static Bool testrun = False;
static int had_error = 0;
static XErrorHandler prev_handler;
static int cur_keycode;
static struct timeval time_val;
static Rotation init_rotation;
static int init_x;
static int init_y;
static Bool use_init_pos = False;
static Bool need_off_deferred = False;
static void
usage(void)
{
fprintf(stderr, "usage: %s [options]\n", program_name);
fprintf(stderr, " where options are:\n");
fprintf(stderr, " -toggle or -t\n");
fprintf(stderr, " -listen or -l\n");
fprintf(stderr, " -display <display> or -d <display>\n");
fprintf(stderr, " -key <key> or -k <key>\n");
fprintf(stderr, " -mod <modifier> or -m <modifier>\n");
fprintf(stderr, " -help\n");
fprintf(stderr, " -nosideview\n");
fprintf(stderr, " -verbose or -v\n");
fprintf(stderr, " -testrun\n");
exit(1);
/*NOTREACHED*/
}
static void
fatal (const char *format, ...)
{
va_list ap;
va_start (ap, format);
fprintf (stderr, "%s exiting: ", program_name);
vfprintf (stderr, format, ap);
va_end (ap);
exit (1);
/*NOTREACHED*/
}
static int
cur_handler (
Display *const err_display,
XErrorEvent *const err_event)
{
had_error = err_event -> error_code;
return (0);
}
typedef enum _relation {
left_of, right_of, above, below, same_as,
} relation_t;
typedef enum _changes {
changes_none = 0,
changes_crtc = (1 << 0),
changes_mode = (1 << 1),
changes_relation = (1 << 2),
changes_position = (1 << 3),
} changes_t;
typedef enum _name_kind {
name_none = 0,
name_string = (1 << 0),
name_xid = (1 << 1),
name_index = (1 << 2),
} name_kind_t;
typedef struct {
name_kind_t kind;
char *string;
XID xid;
int index;
} name_t;
typedef struct _crtc crtc_t;
typedef struct _output output_t;
struct _crtc {
name_t crtc;
XRRCrtcInfo *crtc_info;
XRRModeInfo *mode_info;
int x;
int y;
Rotation rotation;
output_t **outputs;
int noutput;
};
struct _output {
struct _output *next;
changes_t changes;
name_t output;
XRROutputInfo *output_info;
name_t crtc;
crtc_t *crtc_info;
crtc_t *current_crtc_info;
name_t mode;
float refresh;
XRRModeInfo *mode_info;
name_t addmode;
relation_t relation;
struct _output *relative_to;
int x, y;
Rotation rotation;
};
static output_t *outputs = NULL;
static output_t **outputs_tail = &outputs;
static crtc_t *crtcs = NULL;
static int num_crtcs;
static XRRScreenResources *res = NULL;
static int fb_width = 0, fb_height = 0;
static int fb_width_mm = 0, fb_height_mm = 0;
static float dpi = 0.0;
static Bool dryrun = False;
static int minWidth, maxWidth, minHeight, maxHeight;
#define MAX_OUTPUT 3
#define MAX_MODIFIERS 10
typedef struct _con_output con_output_t;
struct _con_output {
output_t *output;
XRRModeInfo **smodes;
int nsmodes;
Bool on;
};
typedef struct _mod_key_table mod_key_table_t;
struct _mod_key_table {
char *modname;
unsigned int mod;
};
static con_output_t con_outputs[MAX_OUTPUT];
static con_output_t dis_con_outputs[MAX_OUTPUT];
static XRRModeInfo *start_mode[MAX_OUTPUT];
static XRRModeInfo *new_mode[MAX_OUTPUT];
static int start = 0;
static int ncon;
static int dis_ncon;
static Bool do_not_switch = False;
static Bool did_init = False;
static mod_key_table_t mod_key_table [MAX_MODIFIERS] = {
{"none", 0},
{"shift", ShiftMask},
{"lock", LockMask},
{"control", ControlMask},
{"mod1", Mod1Mask},
{"mod2", Mod2Mask},
{"mod3", Mod3Mask},
{"mod4", Mod4Mask},
{"mod5", Mod5Mask},
{"any", AnyModifier}
};
static int
mode_height (XRRModeInfo *mode_info, Rotation rotation)
{
switch (rotation & 0xf) {
case RR_Rotate_0:
case RR_Rotate_180:
return mode_info->height;
case RR_Rotate_90:
case RR_Rotate_270:
return mode_info->width;
default:
return 0;
}
}
static int
mode_width (XRRModeInfo *mode_info, Rotation rotation)
{
switch (rotation & 0xf) {
case RR_Rotate_0:
case RR_Rotate_180:
return mode_info->width;
case RR_Rotate_90:
case RR_Rotate_270:
return mode_info->height;
default:
return 0;
}
}
/* v refresh frequency in Hz */
static float
mode_refresh (XRRModeInfo *mode_info)
{
float rate;
if (mode_info->hTotal && mode_info->vTotal)
rate = ((float) mode_info->dotClock /
((float) mode_info->hTotal * (float) mode_info->vTotal));
else
rate = 0;
return rate;
}
static void
init_name (name_t *name)
{
name->kind = name_none;
}
static void
set_name_string (name_t *name, char *string)
{
name->kind |= name_string;
name->string = string;
}
static void
set_name_xid (name_t *name, XID xid)
{
name->kind |= name_xid;
name->xid = xid;
}
static void
set_name_index (name_t *name, int index)
{
name->kind |= name_index;
name->index = index;
}
static void
set_name_all (name_t *name, name_t *old)
{
if (old->kind & name_xid)
name->xid = old->xid;
if (old->kind & name_string)
name->string = old->string;
if (old->kind & name_index)
name->index = old->index;
name->kind |= old->kind;
}
static output_t *
add_output (void)
{
output_t *output = calloc (1, sizeof (output_t));
if (!output)
fatal ("out of memory");
output->next = NULL;
*outputs_tail = output;
outputs_tail = &output->next;
return output;
}
static output_t *
find_output (name_t *name)
{
output_t *output;
for (output = outputs; output; output = output->next)
{
name_kind_t common = name->kind & output->output.kind;
if ((common & name_xid) && name->xid == output->output.xid)
break;
if ((common & name_string) && !strcmp (name->string, output->output.string))
break;
if ((common & name_index) && name->index == output->output.index)
break;
}
return output;
}
static output_t *
find_output_by_xid (RROutput output)
{
name_t output_name;
init_name (&output_name);
set_name_xid (&output_name, output);
return find_output (&output_name);
}
static crtc_t *
find_crtc (name_t *name)
{
int c;
crtc_t *crtc = NULL;
for (c = 0; c < num_crtcs; c++)
{
name_kind_t common;
crtc = &crtcs[c];
common = name->kind & crtc->crtc.kind;
if ((common & name_xid) && name->xid == crtc->crtc.xid)
break;
if ((common & name_string) && !strcmp (name->string, crtc->crtc.string))
break;
if ((common & name_index) && name->index == crtc->crtc.index)
break;
crtc = NULL;
}
return crtc;
}
static crtc_t *
find_crtc_by_xid (RRCrtc crtc)
{
name_t crtc_name;
init_name (&crtc_name);
set_name_xid (&crtc_name, crtc);
return find_crtc (&crtc_name);
}
static XRRModeInfo *
find_mode (name_t *name)
{
int m;
XRRModeInfo *best = NULL;
for (m = 0; m < res->nmode; m++)
{
XRRModeInfo *mode = &res->modes[m];
if ((name->kind & name_xid) && name->xid == mode->id)
{
best = mode;
break;
}
}
return best;
}
static XRRModeInfo *
find_mode_by_xid (RRMode mode)
{
name_t mode_name;
init_name (&mode_name);
set_name_xid (&mode_name, mode);
return find_mode (&mode_name);
}
static void
set_output_info (output_t *output, RROutput xid, XRROutputInfo *output_info)
{
crtc_t *crtc;
/* sanity check output info */
if (output_info->connection != RR_Disconnected && !output_info->nmode)
fatal ("Output %s is not disconnected but has no modes\n",
output_info->name);
/* set output name and info */
if (!(output->output.kind & name_xid))
set_name_xid (&output->output, xid);
if (!(output->output.kind & name_string))
set_name_string (&output->output, output_info->name);
output->output_info = output_info;
crtc = find_crtc_by_xid (output->output_info->crtc);
/* set position */
if (crtc && crtc->crtc_info) {
output->x = crtc->crtc_info->x;
output->y = crtc->crtc_info->y;
}
/* set rotation */
output->rotation &= ~0xf;
if (crtc && crtc->crtc_info)
output->rotation |= (crtc->crtc_info->rotation & 0xf);
else
output->rotation = RR_Rotate_0;
}
static void
get_crtcs (void)
{
int c;
num_crtcs = res->ncrtc;
if (crtcs)
{
for (c = 0; c < res->ncrtc; c++)
{
if (crtcs[c].crtc_info)
XRRFreeCrtcInfo (crtcs[c].crtc_info);
}
free (crtcs);
crtcs = NULL;
}
crtcs = calloc (num_crtcs, sizeof (crtc_t));
if (!crtcs) fatal ("out of memory");
for (c = 0; c < res->ncrtc; c++)
{
XRRCrtcInfo *crtc_info = XRRGetCrtcInfo (dpy, res, res->crtcs[c]);
set_name_xid (&crtcs[c].crtc, res->crtcs[c]);
set_name_index (&crtcs[c].crtc, c);
if (!crtc_info) fatal ("could not get crtc 0x%x information", res->crtcs[c]);
crtcs[c].crtc_info = crtc_info;
if (crtc_info->mode == None)
{
crtcs[c].mode_info = NULL;
crtcs[c].x = 0;
crtcs[c].y = 0;
crtcs[c].rotation = RR_Rotate_0;
}
}
}
static void
crtc_add_output (crtc_t *crtc, output_t *output)
{
if (crtc->outputs)
crtc->outputs = realloc (crtc->outputs, (crtc->noutput + 1) * sizeof (output_t *));
else
{
crtc->outputs = calloc (1, sizeof (output_t *));
crtc->x = output->x;
crtc->y = output->y;
crtc->rotation = output->rotation;
crtc->mode_info = output->mode_info;
}
if (!crtc->outputs) fatal ("out of memory");
crtc->outputs[crtc->noutput++] = output;
}
static void
set_crtcs (void)
{
output_t *output;
int i;
for (i = 0; i < ncon; i++) {
output = con_outputs[i].output;
if (!output->mode_info) continue;
if (output->crtc_info)
crtc_add_output (output->crtc_info, output);
}
}
static void
reset_crtcs_for_outputs (void)
{
output_t *output;
for (output = outputs; output; output = output->next)
{
if ((output->crtc_info) && (output->crtc_info->outputs)) {
free (output->crtc_info->outputs);
output->crtc_info = NULL;
}
}
}
static Status
crtc_disable (crtc_t *crtc)
{
if (verbose)
fprintf (stderr, "crtc %d (0x%lx) : disable\n", crtc->crtc.index, crtc->crtc.xid);
if (dryrun)
return RRSetConfigSuccess;
return XRRSetCrtcConfig (dpy, res, crtc->crtc.xid, CurrentTime,
0, 0, None, RR_Rotate_0, NULL, 0);
}
static Status
crtc_revert (crtc_t *crtc)
{
XRRCrtcInfo *crtc_info = crtc->crtc_info;
if (verbose)
fprintf (stderr, "crtc %d: revert\n", crtc->crtc.index);
if (dryrun)
return RRSetConfigSuccess;
return XRRSetCrtcConfig (dpy, res, crtc->crtc.xid, CurrentTime,
crtc_info->x, crtc_info->y,
crtc_info->mode, crtc_info->rotation,
crtc_info->outputs, crtc_info->noutput);
}
static Status
crtc_apply (crtc_t *crtc)
{
RROutput *rr_outputs;
int o;
Status s;
RRMode mode = None;
if (!crtc->mode_info)
return RRSetConfigSuccess;
rr_outputs = calloc (crtc->noutput, sizeof (RROutput));
if (!rr_outputs)
return BadAlloc;
for (o = 0; o < crtc->noutput; o++)
rr_outputs[o] = crtc->outputs[o]->output.xid;
mode = crtc->mode_info->id;
if (verbose) {
fprintf (stderr, "crtc %d (0x%lx) : %12s %6.1f +%d+%d", crtc->crtc.index,
crtc->crtc.xid,
crtc->mode_info->name, mode_refresh (crtc->mode_info),
crtc->x, crtc->y);
for (o = 0; o < crtc->noutput; o++)
fprintf (stderr, " \"%s\"", crtc->outputs[o]->output.string);
fprintf (stderr, "\n");
}
if (dryrun)
s = RRSetConfigSuccess;
else
s = XRRSetCrtcConfig (dpy, res, crtc->crtc.xid, CurrentTime,
crtc->x, crtc->y, mode, crtc->rotation,
rr_outputs, crtc->noutput);
free (rr_outputs);
return s;
}
static void
screen_revert (void)
{
if (verbose)
fprintf (stderr, "screen %d: revert\n", screen);
if (dryrun)
return;
XRRSetScreenSize (dpy, root,
DisplayWidth (dpy, screen),
DisplayHeight (dpy, screen),
DisplayWidthMM (dpy, screen),
DisplayHeightMM (dpy, screen));
}
static void
screen_apply (void)
{
/* comment it out because DisplayWidth() does not reflect the
change of fb_width and fb_height previously set by
XRRSetScreenSize()
*/
/*
if (fb_width == DisplayWidth (dpy, screen) &&
fb_height == DisplayHeight (dpy, screen) &&
fb_width_mm == DisplayWidthMM (dpy, screen) &&
fb_height_mm == DisplayHeightMM (dpy, screen))
{
return;
}
*/
if (verbose)
fprintf (stderr, "screen %d: %dx%d %dx%d mm %6.2fdpi\n", screen,
fb_width, fb_height, fb_width_mm, fb_height_mm, dpi);
if (dryrun)
return;
XRRSetScreenSize (dpy, root, fb_width, fb_height,
fb_width_mm, fb_height_mm);
}
static void
revert (void)
{
int c;
/* first disable all crtcs */
for (c = 0; c < res->ncrtc; c++)
crtc_disable (&crtcs[c]);
/* next reset screen size */
screen_revert ();
/* now restore all crtcs */
for (c = 0; c < res->ncrtc; c++)
crtc_revert (&crtcs[c]);
}
/*
* uh-oh, something bad happened in the middle of changing
* the configuration. Revert to the previous configuration
* and bail
*/
static void
panic (Status s, crtc_t *crtc)
{
int c = crtc->crtc.index;
char *message;
switch (s) {
case RRSetConfigSuccess: message = "succeeded"; break;
case BadAlloc: message = "out of memory"; break;
case RRSetConfigFailed: message = "failed"; break;
case RRSetConfigInvalidConfigTime: message = "invalid config time"; break;
case RRSetConfigInvalidTime: message = "invalid time"; break;
default: message = "unknown failure"; break;
}
fprintf (stderr, "%s: Configure crtc %d %s\n", program_name, c, message);
revert ();
exit (1);
}
static void
apply (void)
{
Status s;
int c;
/*
* Turn off any crtcs which are to be disabled or which are
* larger than the target size
*/
for (c = 0; c < res->ncrtc; c++)
{
crtc_t *crtc = &crtcs[c];
XRRCrtcInfo *crtc_info = crtc->crtc_info;
/*
* if this crtc is already disabled, skip it
* Note server sets crtc_info->mode (before change)
*/
if (crtc_info->mode == None)
continue;
/*
* If this crtc is to be left enabled, make
* sure the old size fits then new screen
* When crtc->mode_info is null, the crtc is to be
* disabled. Note set_crtcs () sets crtc->mode_info for
* new mode (to be changed to).
*/
if (crtc->mode_info)
{
XRRModeInfo *old_mode = find_mode_by_xid (crtc_info->mode);
int x, y, w, h;
if (!old_mode)
panic (RRSetConfigFailed, crtc);
/* old position and size information */
x = crtc_info->x;
y = crtc_info->y;
w = mode_width (old_mode, crtc_info->rotation);
h = mode_height (old_mode, crtc_info->rotation);
/* if it fits, skip it */
if (x + w <= fb_width && y + h <= fb_height)
continue;
}
if (need_off_deferred)
/* Defer taking off */
continue;
s = crtc_disable (crtc);
if (s != RRSetConfigSuccess)
panic (s, crtc);
}
/*
* Hold the server grabbed while messing with
* the screen so that apps which notice the resize
* event and ask for xinerama information from the server
* receive up-to-date information
*/
XGrabServer (dpy);
/*
* Set the screen size
*/
screen_apply ();
/*
* Set crtcs
*/
for (c = 0; c < res->ncrtc; c++)
{
crtc_t *crtc = &crtcs[c];
s = crtc_apply (crtc);
if (s != RRSetConfigSuccess)
panic (s, crtc);
}
/*
* Release the server grab and let all clients
* respond to the updated state
*/
XUngrabServer (dpy);
}
/*
* Use current output state to complete the output list
*/
static void
get_outputs (void)
{
int o;
for (o = 0; o < res->noutput; o++)
{
XRROutputInfo *output_info = XRRGetOutputInfo (dpy, res, res->outputs[o]);
output_t *output;
name_t output_name;
if (!output_info) fatal ("could not get output 0x%x information", res->outputs[o]);
set_name_xid (&output_name, res->outputs[o]);
set_name_index (&output_name, o);
set_name_string (&output_name, output_info->name);
output = find_output (&output_name);
if (!output)
{
output = add_output ();
set_name_all (&output->output, &output_name);
}
set_output_info (output, res->outputs[o], output_info);
}
}
/*
* Test whether 'crtc' can be used for 'output'
*/
static Bool
check_crtc_for_output (crtc_t *crtc, output_t *output)
{
int i;
int l;
output_t *other;
for (i = 0; i < ncon; i++)
{
other = con_outputs[i].output;
if (other == output)
continue;
if (other->mode_info == NULL)
continue;
if (other->crtc_info != crtc)
continue;
/* see if the output connected to the crtc can clone to this output */
for (l = 0; l < output->output_info->nclone; l++)
if (output->output_info->clones[l] == other->output.xid)
break;
/* not on the list, can't clone */
if (l == output->output_info->nclone)
return False;
}
if (crtc->noutput)
{
for (i = 0; i < crtc->noutput; i++)
/* Check if the output is to be turned on */
if (crtc->outputs[i]->mode_info) {
/* make sure the state matches */
if (crtc->mode_info != output->mode_info)
return False;
if (crtc->x != output->x)
return False;
if (crtc->y != output->y)
return False;
if (crtc->rotation != output->rotation)
return False;
}
}
return True;
}
static crtc_t *
find_crtc_for_output (output_t *output)
{
int c;
for (c = 0; c < output->output_info->ncrtc; c++)
{
crtc_t *crtc;
crtc = find_crtc_by_xid (output->output_info->crtcs[c]);
if (!crtc) fatal ("cannot find crtc 0x%x\n", output->output_info->crtcs[c]);
if (check_crtc_for_output (crtc, output))
return crtc;
}
return NULL;
}
static void
set_positions (void)
{
Bool keep_going;
Bool any_set;
int min_x, min_y;
int i;
for (;;)
{
any_set = False;
keep_going = False;
for (i = 0; i < ncon; i++)
{
output_t *output = con_outputs[i].output;
output_t *relation;
if (!(output->changes & changes_relation)) continue;
if (output->mode_info == NULL) continue;
relation = output->relative_to;
if (relation->mode_info == NULL)
{
output->x = 0;
output->y = 0;
output->changes |= changes_position;
any_set = True;
continue;
}
/*
* Make sure the dependent object has been set in place
*/
if ((relation->changes & changes_relation) &&
!(relation->changes & changes_position))
{
keep_going = True;
continue;
}
switch (output->relation) {
case left_of:
output->y = relation->y;
output->x = relation->x - mode_width (output->mode_info, output->rotation);
break;
case right_of:
output->y = relation->y;
output->x = relation->x + mode_width (relation->mode_info, relation->rotation);
break;
case above:
output->x = relation->x;
output->y = relation->y - mode_height (output->mode_info, output->rotation);
break;
case below:
output->x = relation->x;
output->y = relation->y + mode_height (relation->mode_info, relation->rotation);
break;
case same_as:
output->x = relation->x;
output->y = relation->y;
}
output->changes |= changes_position;
relation->changes |= changes_position;
any_set = True;
}
if (!keep_going)
break;
if (!any_set)
fatal ("loop in relative position specifications\n");
}
/*
* Now normalize positions so the upper left corner of all outputs is at 0,0
*/
min_x = 32768;
min_y = 32768;
for (i = 0; i < ncon; i++)
{
output_t *output = con_outputs[i].output;
if (output->mode_info == NULL) continue;
if (output->x < min_x) min_x = output->x;
if (output->y < min_y) min_y = output->y;
}
if (min_x || min_y)
{
/* move all outputs */
for (i = 0; i < ncon; i++)
{
output_t *output = con_outputs[i].output;
if (output->mode_info == NULL) continue;
output->x -= min_x;
output->y -= min_y;
output->changes |= changes_position;
}
}
}
static Bool
set_screen_size (void)
{
int i;
fb_width = fb_height = 0;
for (i = 0; i < ncon; i++)
{
output_t *output = con_outputs[i].output;
XRRModeInfo *mode_info = output->mode_info;
int x, y, w, h;
if (!mode_info) continue;
x = output->x;
y = output->y;
w = mode_width (mode_info, output->rotation);
h = mode_height (mode_info, output->rotation);
if (x + w > fb_width) fb_width = x + w;
if (y + h > fb_height) fb_height = y + h;
}
if (fb_width > maxWidth || fb_height > maxHeight) {
if (verbose)
fprintf (stderr, "screen cannot be larger than %dx%d (desired size %dx%d)\n",
maxWidth, maxHeight, fb_width, fb_height);
return False;
}
if (fb_width < minWidth) fb_width = minWidth;
if (fb_height < minHeight) fb_height = minHeight;
return True;
}
static void
disable_outputs (output_t *outputs)
{
while (outputs)
{
outputs->crtc_info = NULL;
outputs = outputs->next;
}
}
/*
* find the best mapping from output to crtc available
*/
static int
pick_crtcs_score (output_t *outputs)
{
output_t *output;
int best_score;
int my_score;
int score;
crtc_t *best_crtc;
int c;
if (!outputs)
return 0;
output = outputs;
outputs = outputs->next;
/*
* Score with this output disabled
*/
output->crtc_info = NULL;
best_score = pick_crtcs_score (outputs);
if (output->mode_info == NULL)
return best_score;
best_crtc = NULL;
/*
* Now score with this output any valid crtc
*/
for (c = 0; c < output->output_info->ncrtc; c++)
{
crtc_t *crtc;
crtc = find_crtc_by_xid (output->output_info->crtcs[c]);
if (!crtc)
fatal ("cannot find crtc 0x%x\n", output->output_info->crtcs[c]);
/* reset crtc allocation for following outputs */
disable_outputs (outputs);
if (!check_crtc_for_output (crtc, output))
continue;
my_score = 1000;
/* slight preference for existing connections */
if (crtc == output->current_crtc_info)
my_score++;
output->crtc_info = crtc;
score = my_score + pick_crtcs_score (outputs);
if (score > best_score)
{
best_crtc = crtc;
best_score = score;
}
}
if (output->crtc_info != best_crtc)
output->crtc_info = best_crtc;
/*
* Reset other outputs based on this one using the best crtc
*/
(void) pick_crtcs_score (outputs);
return best_score;
}
/*
* Pick crtcs for any changing outputs that don't have one
*/
static Bool
pick_crtcs (void)
{
output_t *output;
int i;
/*
* First try to match up newly enabled outputs with spare crtcs
*/
for (i = 0; i < ncon; i++)
{
output = con_outputs[i].output;
if (output->mode_info)
{
if (output->crtc_info) {
if (output->crtc_info->crtc_info->noutput > 0 &&
(output->crtc_info->crtc_info->noutput > 1 ||
output != find_output_by_xid (output->crtc_info->crtc_info->outputs[0])))
break;
} else {
output->crtc_info = find_crtc_for_output (output);
if (!output->crtc_info)
break;
else {
if (verbose)
fprintf(stderr, "picked crtc 0x%lx for output %d (%s)\n",
output->crtc_info->crtc.xid, i, output->output_info->name);
}
}
}
}
/*
* Everyone is happy
*/
if (i == ncon)
return True;
/*
* When the simple way fails, see if there is a way
* to swap crtcs around and make things work
*/
for (output = outputs; output; output = output->next)
output->current_crtc_info = output->crtc_info;
pick_crtcs_score (outputs);
for (output = outputs; output; output = output->next)
{
if (output->mode_info && !output->crtc_info) {
if (verbose)
fprintf (stderr, "cannot find crtc for output %s\n",
output->output.string);
return False;
}
}
return True;
}
static Bool
probe_and_check_output_changes (void) {
XRRScreenResources *new_res = NULL;
int changed = False;
int i;
new_res = XRRGetScreenResources (dpy, root);
if (!new_res)
fatal ("could not get screen resources");
if ((new_res->noutput != res->noutput) || (new_res->nmode != res->nmode) ||
(new_res->ncrtc != res->ncrtc))
changed = True;
else {
for (i = 0; i < new_res->noutput; i++)
if (new_res->outputs[i] != res->outputs[i]) {
changed = True;
break;
}
for (i = 0; i < new_res->nmode; i++)
if (new_res->modes[i].id != res->modes[i].id) {
changed = True;
break;
}
for (i = 0; i < new_res->ncrtc; i++) {
crtc_t *crtc = NULL; /* old */
XRRCrtcInfo *crtc_info = NULL; /* new */
crtc = find_crtc_by_xid (res->crtcs[i]);
crtc_info = XRRGetCrtcInfo (dpy, new_res,
new_res->crtcs[i]);
if (!crtc || !crtc_info) {
changed = True;
break;
}
if (!crtc->mode_info && !find_mode_by_xid (crtc_info->mode))
continue;
if ((crtc_info->x != crtc->x) ||
(crtc_info->y != crtc->y) ||
(find_mode_by_xid (crtc_info->mode) != crtc->mode_info) ||
(crtc_info->rotation != crtc->rotation)) {
changed = True;
break;
}
}
}
if (changed) {
if (res)
XRRFreeScreenResources(res);
res = new_res;
if (verbose)
fprintf(stderr, "probed: output status changed\n");
return True;
}
if (verbose)
fprintf(stderr, "probed: no output status change\n");
return False;
}
static Bool
need_probe (void) {
struct timeval cur_time_val;
long long cur, prev;
X_GETTIMEOFDAY(&cur_time_val);
cur = (long long) cur_time_val.tv_sec * 1000000 + cur_time_val.tv_usec;
prev =(long long) time_val.tv_sec * 1000000 + time_val.tv_usec;
if (((cur - prev) < 0) || ((cur - prev) > 5000000))
return True;
else
return False;
}
static int
mode_sort (const void *p1, void *p2)
{
XRRModeInfo *mi1 = * (XRRModeInfo **) p1;
XRRModeInfo *mi2 = * (XRRModeInfo **) p2;
if ((mi1->width == mi2->width) && (mi1->height == mi2->height)) {
if (mode_refresh(mi1) && mode_refresh(mi2)) {
if (mode_refresh(mi1) < mode_refresh(mi2))
return 1;
if (mode_refresh(mi1) > mode_refresh(mi2))
return -1;
} else
return 0;
}
if ((mi1->width == mi2->width) && (mi1->height < mi2->height))
return 1;
if ((mi1->width == mi2->width) && (mi1->height > mi2->height))
return -1;
if (mi1->width < mi2->width)
return 1;
if (mi1->width > mi2->width)
return -1;
return 0;
}
static int
output_sort (const void *p1, const void *p2) {
con_output_t co1 = * (con_output_t *) p1;
con_output_t co2 = * (con_output_t *) p2;
int ncrtc1 = co1.output->output_info->ncrtc;
int ncrtc2 = co2.output->output_info->ncrtc;
char *name1 = co1.output->output_info->name;
char *name2 = co2.output->output_info->name;
if (ncrtc1 == ncrtc2)
return (strcmp(name1, name2));
if (ncrtc1 < ncrtc2)
return -1;
return 1;
}
static Bool
get_common_mode(con_output_t *c0, con_output_t *c1, int *m0, int *m1) {
int i, j;
int i1 = -1, j1 = -1, i2 = -1, j2 = -1;
int x, y, w, h;
output_t *output = c0->output;
*m0 = -1;
*m0 = -1;
if (!c0 ||!c1 || !c0->smodes || !c1->smodes)
return False;
/* first try to find mode with common same size */
for (i = 0; i < c0->nsmodes; i ++) {
for (j = 0; j < c1->nsmodes; j ++)
if ((c0->smodes[i]->width == c1->smodes[j]->width) &&
(c0->smodes[i]->height == c1->smodes[j]->height)) {
x = output->x;
y = output->y;
w = mode_width (c0->smodes[i], output->rotation);
h = mode_height (c0->smodes[i], output->rotation);
if ((x + w <= maxWidth) && (y + h <= maxHeight)) {
i1 = i; j1 = j;
break;
}
}
if ((i1 != -1) && (j1 != -1))
break;
}
if ((i1 == -1) && (j1 == -1))
return False;
/* then try to find mode with common id for possible cloning */
for (i = 0; i < c0->nsmodes; i ++) {
for (j = 0; j < c1->nsmodes; j ++)
if (c0->smodes[i] == c1->smodes[j]) {
x = output->x;
y = output->y;
w = mode_width (c0->smodes[i], output->rotation);
h = mode_height (c0->smodes[i], output->rotation);
if ((x + w <= maxWidth) && (y + h <= maxHeight)) {
i2 = i; j2 = j;
break;
}
}
if ((i2 != -1) && (j2 != -1))
break;
}
if ((i2 == -1) && (j2 == -1)) {
*m0 = i1;
*m1 = j1;
} else {
/* use common id if it is not smaller */
if ((mode_width (c0->smodes[i1], output->rotation) >
mode_width (c0->smodes[i2], output->rotation)) &&
(mode_height (c0->smodes[i1], output->rotation) >
mode_height (c0->smodes[i2], output->rotation))) {
*m0 = i1;
*m1 = j1;
} else {
*m0 = i2;
*m1 = j2;
}
}
return True;
}
static XRRModeInfo *
get_largest_mode (con_output_t *c, XRRModeInfo *start_mode) {
int i, found = False;
output_t *output = c->output;
for (i = 0; i < c->nsmodes; i++) {
XRRModeInfo *mode_info = c->smodes[i];
int x, y, w, h;
if (!found && (start_mode != mode_info))
continue;
else
found = True;
if (mode_info) {
x = output->x;
y = output->y;
w = mode_width (mode_info, output->rotation);
h = mode_height (mode_info, output->rotation);
if ((x + w <= maxWidth) && (y + h <= maxHeight))
break;
}
}
if (i < c->nsmodes)
return c->smodes[i];
else
fatal("cannot find mode");
}
static Bool
valid_mode(con_output_t *con, XRRModeInfo *mode) {
int i;
for (i = 0; i < con->nsmodes; i++)
if (con->smodes[i] == mode)
return True;
return False;
}
static void
do_init (void)
{
int i, j;
output_t *output;
/* Initialize con_outputs array */
for (i = 0; i < MAX_OUTPUT; i++) {
con_outputs[i].output = NULL;
con_outputs[i].on = False;
start_mode[i] = NULL;
new_mode[i] = NULL;
}
ncon = 0;
dis_ncon = 0;
init_rotation = RR_Rotate_0;
init_x = 0;
init_y = 0;
get_crtcs ();
get_outputs ();
for (output = outputs; output; output = output->next) {
XRROutputInfo *output_info = output->output_info;
if (output_info->connection == RR_Connected) {
con_outputs[ncon].output = output;
con_outputs[ncon].nsmodes = 0;
for (j = 0; j < output_info->nmode; j++) {
XRRModeInfo *rmode = find_mode_by_xid (output_info->modes[j]);
con_outputs[ncon].smodes =
realloc(con_outputs[ncon].smodes,
(con_outputs[ncon].nsmodes + 1) * sizeof (XRRModeInfo *));
con_outputs[ncon].smodes[j] = rmode;
con_outputs[ncon].nsmodes ++;
}
/* Sort the modes */
qsort((void *) con_outputs[ncon].smodes,
con_outputs[ncon].nsmodes, sizeof(XRRModeInfo *),
(int (*) (const void *, const void *)) mode_sort);
if (output_info->crtc) {
crtc_t *crtc;
con_outputs[ncon].on = True;
for (j = 0; j < output_info->ncrtc; j++) {
if (output_info->crtcs[j] == output_info->crtc)
break;
if (j == output_info->ncrtc) {
if (verbose)
fatal ("crtc does not match for output\n");
}
}
/* set initial mode_info */
crtc = find_crtc_by_xid (output_info->crtc);
if (crtc)
con_outputs[ncon].output->mode_info =
find_mode_by_xid (crtc->crtc_info->mode);
}
else
con_outputs[ncon].on = False;
ncon ++;
} else if (output_info->connection == RR_Disconnected) {
dis_con_outputs[dis_ncon].output = output;
dis_ncon ++;
}
}
qsort((void **) con_outputs, ncon,
sizeof(con_output_t), (int (*) (const void *, const void *)) output_sort);
if (verbose) {
fprintf(stderr, "Total connected outputs = %d :\n", ncon);
for (j = 0; j < ncon; j++) {
fprintf(stderr, "%d (%s): top mode = %s, rotation = %d, crtcs =", j,
con_outputs[j].output->output_info->name,
con_outputs[j].smodes[0]->name,
con_outputs[j].output->rotation);
for (i = 0; i < con_outputs[j].output->output_info->ncrtc; i++)
fprintf(stderr, " 0x%lx", con_outputs[j].output->output_info->crtcs[i]);
fprintf(stderr, ", using 0x%lx", con_outputs[j].output->output_info->crtc);
fprintf(stderr, "\n");
}
fprintf(stderr, "Total disconnected outputs = %d :\n", dis_ncon);
for (j = 0; j < dis_ncon; j++) {
fprintf(stderr, "%d (%s) : number of crtcs %d =", j,
dis_con_outputs[j].output->output_info->name,
dis_con_outputs[j].output->output_info->ncrtc);
for (i = 0; i < dis_con_outputs[j].output->output_info->ncrtc; i++)
fprintf(stderr, " 0x%lx", dis_con_outputs[j].output->output_info->crtcs[i]);
fprintf(stderr, ", using 0x%lx", dis_con_outputs[j].output->output_info->crtc);
fprintf(stderr, "\n");
}
}
i = con_outputs[2].on * 4 + con_outputs[1].on * 2 + con_outputs[0].on;
if ((i == 1) || (i == 2) || (i == 4)) {
use_init_pos = True;
j = i >> 1;
/* remember position and mode info in single state */
start_mode[j] = con_outputs[j].output->mode_info;
init_rotation = con_outputs[j].output->rotation;
init_x = con_outputs[j].output->x;
init_y = con_outputs[j].output->y;
} else
use_init_pos = False;
if ((ncon != 2) || (start < 3))
start = i;
if ((ncon < 1) || (ncon > 3)) {
if ((ncon < 1) && verbose)
fprintf (stderr, "warn: no connection\n");
else if ((ncon > 3) && verbose)
fprintf (stderr, "warn: too many (more than 3) connections: %d: can't switch\n", ncon);
do_not_switch = True;
}
did_init = True;
return;
}
static int
grab_key (Display *dpy, int keysym, unsigned int modifier,
Window grab_window)
{
char msg[256];
int keycode = XKeysymToKeycode(dpy, keysym);
if (keycode == NoSymbol)
fatal ("grab_key: keycode not defined for keysym 0x%x\n", keysym);
had_error = 0;
prev_handler = XSetErrorHandler (cur_handler);
if (!testrun) {
XGrabKey(dpy,
keycode,
modifier,
root, True, GrabModeAsync, GrabModeAsync);
XSync (dpy, False);
}
XSetErrorHandler (prev_handler);
if (had_error) {
XGetErrorText (dpy, had_error, msg, sizeof (msg));
fatal ("XGrabKey: %s\n", msg);
}
if (verbose)
fprintf(stderr, "keycode to grab: %d\n", keycode);
return keycode;
}
static Bool
do_switch (void)
{
int i, j;
int single;
int save = -1;
if (ncon <= 0)
return True;
for (i = 0; i < ncon; i++) {
output_t *output = con_outputs[i].output;
new_mode[i] = NULL;
output->relation = same_as;
output->relative_to = NULL;
if (use_init_pos) {
output->x = init_x;
output->y = init_y;
output->rotation = init_rotation;
} else {
output->x = 0;
output->y = 0;
}
}
if (ncon == 2) {
if (!nosideview) {
if (++start > 5) start = 1;
}
else {
if (++start > 3) start = 1;
}
if (verbose)
fprintf(stderr, "current state = %d\n", start);
if (start >= 3) {
int m0, m1;
if (get_common_mode(&con_outputs[0], &con_outputs[1], &m0, &m1)) {
new_mode[0] = con_outputs[0].smodes[m0];
new_mode[1] = con_outputs[1].smodes[m1];
} else {
new_mode[0] = get_largest_mode (&con_outputs[0],
con_outputs[0].smodes[0]);
new_mode[1] = get_largest_mode (&con_outputs[1],
con_outputs[1].smodes[0]);
}
} else {
if (start_mode[start -1] && valid_mode(&con_outputs[start -1],
start_mode[start -1]))
new_mode[start -1] = start_mode[start -1];
else {
if (con_outputs[start -1].smodes[0])
new_mode[start -1] =
get_largest_mode (&con_outputs[start-1],
con_outputs[start -1].smodes[0]);
}
}
}
if (ncon == 3) {
if (++start > 6) start = 1;
if (verbose)
fprintf(stderr, "current state = %d\n", start);
if ((start == 1) || (start == 2) || (start == 4)) {
single = 1;
i = start >> 1;
j = 0;
}
else {
single = 0;
if (start > 4)
j = 2;
else
j = 1;
if (start > 5)
i = 1;
else
i = 0;
}
if (single) {
if (start_mode[i] && valid_mode(&con_outputs[i], start_mode[i]))
new_mode[i] = start_mode[i];
else {
if (con_outputs[i].smodes[0])
new_mode[i] = get_largest_mode (&con_outputs[i],
con_outputs[i].smodes[0]);
}
}
else {
int m0, m1;
if (get_common_mode(&con_outputs[i], &con_outputs[j], &m0, &m1)) {
new_mode[i] = con_outputs[i].smodes[m0];
new_mode[j] = con_outputs[j].smodes[m1];
} else {
new_mode[i] = get_largest_mode (&con_outputs[i],
con_outputs[i].smodes[0]);
new_mode[j] = get_largest_mode (&con_outputs[j],
con_outputs[j].smodes[0]);
}
}
}
if (ncon == 1) {
if (start_mode[0] && valid_mode(&con_outputs[0], start_mode[0]))
new_mode[0] = start_mode[0];
else {
if (con_outputs[0].smodes[0])
new_mode[0] = get_largest_mode (&con_outputs[0],
con_outputs[0].smodes[0]);
}
}
/* Set mode */
for (i = 0; i < ncon; i++) {
output_t *output;
output = con_outputs[i].output;
if (new_mode[i]) {
if ((!output->mode_info) || (output->mode_info != new_mode[i])) {
output->mode_info = new_mode[i];
con_outputs[i].on = True;
if (verbose)
fprintf(stderr, "set output %d (%s) to mode %s rotation %d\n", i,
con_outputs[i].output->output_info->name,
con_outputs[i].output->mode_info->name,
con_outputs[i].output->rotation);
}
} else if (con_outputs[i].on ) {
if (!need_off_deferred) {
output->mode_info = NULL;
con_outputs[i].on = False;
if (verbose)
fprintf(stderr, "turn off output %d (%s) \n",
i, con_outputs[i].output->output_info->name);
} else
save = i;
}
}
if ((ncon == 2) && (start >= 4)) {
if (start == 4) {
con_outputs[1].output->relative_to = con_outputs[0].output;
con_outputs[1].output->relation = right_of;
con_outputs[1].output->changes = changes_relation;
con_outputs[0].output->changes = 0;
}
else if (start == 5) {
con_outputs[0].output->relative_to = con_outputs[1].output;
con_outputs[0].output->relation = right_of;
con_outputs[0].output->changes = changes_relation;
con_outputs[1].output->changes = 0;
}
set_positions();
}
if (!set_screen_size ())
return False;
/* reset crtcs before allocation */
reset_crtcs_for_outputs();
if (!did_init)
get_crtcs();
if (!pick_crtcs()) {
if (verbose)
fprintf(stderr, "pick_crtcs failed\n");
return True;
}
set_crtcs ();
apply();
if (need_off_deferred && (save != -1)) {
/* Now, take the deferred output off */
output_t *output;
crtc_t *crtc;
Status s;
output = con_outputs[save].output;
output->mode_info = NULL;
con_outputs[save].on = False;
if (verbose)
fprintf(stderr, "turn off output %d (%s) \n",
save, con_outputs[save].output->output_info->name);
crtc = output->crtc_info;
s = crtc_disable (crtc);
if (s != RRSetConfigSuccess)
panic (s, crtc);
}
XSync (dpy, False);
did_init = False;
return True;
}
static Bool
do_toggle (void)
{
Atom atom;
XEvent xev;
int ret;
atom = XInternAtom (dpy, "DISPLAYSWITCH_DAEMON", True);
if (!atom) {
fprintf(stderr, "dispswitch daemon not running\n");
return False;
}
win = XGetSelectionOwner (dpy, atom);
if (!win) {
fprintf(stderr, "dispswitch: No owner of dispswitch daemon is found\n");
return False;
}
bzero (&xev, sizeof (XEvent));
xev.xkey.type = KeyPress;
xev.xkey.send_event = True;
xev.xkey.display = dpy;
/* Any keycode */
xev.xkey.keycode = 71;
/*
* Send another instance of dispswitch (a daemon) an event to
* request a switch
*/
ret = XSendEvent(dpy, win, False, KeyPressMask, &xev);
XFlush(dpy);
if (!ret)
fprintf(stderr, "dispswitch: XSendEvent error\n");
return (!ret);
}
int
main (int argc, char **argv)
{
char *display_name = NULL;
int major, minor;
int i;
char msg[256];
XEvent ev;
unsigned int modifier = 0;
Bool key_given = False;
Bool mod_given = False;
int keysym = 0, toggle = False, listen = False;
Atom atom;
program_name = argv[0];
for (i = 1; i < argc; i++) {
if (!strcmp ("-display", argv[i]) || !strcmp ("-d", argv[i])) {
if (++i>=argc) usage ();
display_name = argv[i];
continue;
}
if (!strcmp ("-key", argv[i]) || !strcmp ("-k", argv[i])) {
if (++i>=argc) usage ();
if ((keysym = XStringToKeysym(argv[i])) == NoSymbol) {
fprintf(stderr, "invalid keysym: -key %s\n", argv[i]);
usage();
}
key_given = True;
continue;
}
if (!strcmp ("-mod", argv[i]) || !strcmp ("-m", argv[i])) {
int j;
char *s, *p, *q;
int end = 0;
if (++i>=argc) usage ();
s = strdup (argv[i]);
if (!s) {
if (verbose)
fprintf(stderr, "modifier failed, will use default modifier\n");
continue;
}
while (*s == ' ') s++;
p = s + strlen(s) - 1;
while (*p == ' ') *p-- = 0;
q = s;
for (; ;) {
if (p = strchr(s, '+')) {
*p = ' ';
while ((p > s) && (*(p-1) == ' ')) p--;
*p = 0;
}
else
end = 1;
for (j = 0; j < MAX_MODIFIERS; j++) {
if (!strcmp(mod_key_table[j].modname, s)) {
modifier |= mod_key_table[j].mod;
break;
}
}
if (j == MAX_MODIFIERS) {
fprintf(stderr, "invalid modifier: -mod %s\n", q);
usage();
}
if (end)
break;
else {
s = ++p;
while (*s == ' ') s++;
}
}
mod_given = True;
free (q);
continue;
}
if (!strcmp ("-nosideview", argv[i])) {
nosideview = True;
continue;
}
if (!strcmp ("-verbose", argv[i]) || !strcmp ("-v", argv[i])) {
verbose = True;
continue;
}
if (!strcmp ("-testrun", argv[i])) {
testrun = True;
verbose = True;
continue;
}
if (!strcmp ("-toggle", argv[i]) || !strcmp ("-t", argv[i])) {
toggle = True;
continue;
}
if (!strcmp ("-listen", argv[i]) || !strcmp ("-l", argv[i])) {
listen = True;
continue;
}
usage();
}
dpy = XOpenDisplay (display_name);
if (dpy == NULL)
fatal ("can't open display %s\n", XDisplayName(display_name));
screen = DefaultScreen (dpy);
root = RootWindow (dpy, screen);
if (!XRRQueryVersion (dpy, &major, &minor))
fatal ("randr extension missing\n");
if ((major <= 1) && (major != 1 || minor < 2))
fatal ("wrong randr version: %d.%d\n", major, minor);
if (toggle)
exit (do_toggle());
/*
* Create an atom, a trivial window, and make it selection owner.
* Ready to accept a client event request for switch
*/
atom = XInternAtom(dpy, "DISPLAYSWITCH_DAEMON", False);
if (!atom) {
if (verbose)
fprintf(stderr, "cannot create Atom\n");
}
else {
if (XGetSelectionOwner (dpy, atom)) {
if (verbose)
fprintf(stderr, "dispswitch daemon is already running, quit\n");
exit (1);
}
win = XCreateSimpleWindow(dpy, root, 0, 0, 10, 10, 0, 10, 0);
if (!win) {
if (verbose)
fprintf(stderr, "cannot create window\n");
}
else {
XSetSelectionOwner(dpy, atom, win, CurrentTime);
if (XGetSelectionOwner(dpy, atom) != win) {
if (verbose)
fprintf(stderr, "set selection owner failed\n");
} else
XSelectInput(dpy, win, KeyPressMask);
}
}
/* set default key and modifier if not given in command */
if (!key_given)
keysym = XStringToKeysym ("F5");
if (!mod_given)
modifier = ShiftMask;
if (!listen)
cur_keycode = grab_key (dpy, keysym, modifier, root);
XRRGetScreenSizeRange (dpy, root, &minWidth, &minHeight,
&maxWidth, &maxHeight);
fb_width_mm = DisplayWidthMM (dpy, screen);
fb_height_mm = DisplayHeightMM (dpy, screen);
dpi = (25.4 * DisplayHeight (dpy, screen)) / DisplayHeightMM(dpy, screen);
res = XRRGetScreenResources (dpy, root);
if (!res)
fatal ("could not get screen resources\n");
if (res->ncrtc < 2)
fatal ("too few crtcs: %d\n", res->ncrtc);
do_init();
X_GETTIMEOFDAY(&time_val);
for(;;)
{
need_off_deferred = False;
if (testrun) {
usleep(4000000);
fprintf(stderr, "\n");
} else
XNextEvent(dpy, &ev);
if (!listen && !testrun && (ev.type == MappingNotify) &&
((ev.xmapping.request == MappingKeyboard) ||
(ev.xmapping.request == MappingModifier))) {
/* keyboard/modifier mapping changed */
if (verbose)
fprintf(stderr, "\nkeyboard/modifier mapping changed ...\n");
XUngrabKey(dpy, cur_keycode, modifier, root);
cur_keycode = grab_key (dpy, keysym, modifier, root);
}
if (testrun || (ev.type == KeyPress)) {
if (verbose)
fprintf(stderr, "\na key press event was grabbed ...\n");
do_not_switch = False;
if (testrun || need_probe()) {
/* Too long since last switch, need to check output changes */
if (probe_and_check_output_changes ()) {
output_t *output, *next;
output = outputs;
while (output) {
if (output->output_info)
XRRFreeOutputInfo (output->output_info);
if (output->crtc_info && output->crtc_info->outputs) {
free(output->crtc_info->outputs);
output->crtc_info->outputs = NULL;
}
next = output->next;
free(output);
output = next;
}
outputs = NULL;
outputs_tail = &outputs;
for (i = 0; i < ncon; i++) {
con_outputs[i].output = NULL;
con_outputs[i].on = False;
if (con_outputs[i].smodes) {
free(con_outputs[i].smodes);
con_outputs[i].smodes = NULL;
}
con_outputs[i].nsmodes = 0;
}
do_init();
} else if (ncon == 1)
do_not_switch = True;
} else if (ncon == 1)
do_not_switch = True;
if (!do_not_switch) {
if ((ncon == 2) && (start == 1))
/*
* Workaround for intel based graphics: in switching from
* LVDS to VGA, off on LVDS needs to be deferred.
*/
need_off_deferred = True;
if (!do_switch()) {
if ((ncon == 2) && (start == 4)) {
start = 5;
if (verbose)
fprintf(stderr, "too small screen, skipping side view\n");
(void) do_switch();
}
}
}
X_GETTIMEOFDAY(&time_val);
}
}
}
|
1a333cc76a26d57e87a7d9ec921c9850760c51f3
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/contrib/python/numpy/py2/numpy/core/src/umath/reduction.c
|
65489351183aef30eda65844c76757b8085544e8
|
[
"Apache-2.0"
] |
permissive
|
catboost/catboost
|
854c1a1f439a96f1ae6b48e16644be20aa04dba2
|
f5042e35b945aded77b23470ead62d7eacefde92
|
refs/heads/master
| 2023-09-01T12:14:14.174108
| 2023-09-01T10:01:01
| 2023-09-01T10:22:12
| 97,556,265
| 8,012
| 1,425
|
Apache-2.0
| 2023-09-11T03:32:32
| 2017-07-18T05:29:04
|
Python
|
UTF-8
|
C
| false
| false
| 20,415
|
c
|
reduction.c
|
/*
* This file implements generic methods for computing reductions on arrays.
*
* Written by Mark Wiebe (mwwiebe@gmail.com)
* Copyright (c) 2011 by Enthought, Inc.
*
* See LICENSE.txt for the license.
*/
#define _UMATHMODULE
#define _MULTIARRAYMODULE
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "npy_config.h"
#include <numpy/arrayobject.h>
#include "npy_config.h"
#include "npy_pycompat.h"
#include "numpy/ufuncobject.h"
#include "lowlevel_strided_loops.h"
#include "reduction.h"
#include "extobj.h" /* for _check_ufunc_fperr */
/*
* Allocates a result array for a reduction operation, with
* dimensions matching 'arr' except set to 1 with 0 stride
* wherever axis_flags is True. Dropping the reduction axes
* from the result must be done later by the caller once the
* computation is complete.
*
* This function always allocates a base class ndarray.
*
* If 'dtype' isn't NULL, this function steals its reference.
*/
static PyArrayObject *
allocate_reduce_result(PyArrayObject *arr, npy_bool *axis_flags,
PyArray_Descr *dtype, int subok)
{
npy_intp strides[NPY_MAXDIMS], stride;
npy_intp shape[NPY_MAXDIMS], *arr_shape = PyArray_DIMS(arr);
npy_stride_sort_item strideperm[NPY_MAXDIMS];
int idim, ndim = PyArray_NDIM(arr);
if (dtype == NULL) {
dtype = PyArray_DTYPE(arr);
Py_INCREF(dtype);
}
PyArray_CreateSortedStridePerm(PyArray_NDIM(arr),
PyArray_STRIDES(arr), strideperm);
/* Build the new strides and shape */
stride = dtype->elsize;
if (ndim) {
memcpy(shape, arr_shape, ndim * sizeof(shape[0]));
}
for (idim = ndim-1; idim >= 0; --idim) {
npy_intp i_perm = strideperm[idim].perm;
if (axis_flags[i_perm]) {
strides[i_perm] = 0;
shape[i_perm] = 1;
}
else {
strides[i_perm] = stride;
stride *= shape[i_perm];
}
}
/* Finally, allocate the array */
return (PyArrayObject *)PyArray_NewFromDescr(
subok ? Py_TYPE(arr) : &PyArray_Type,
dtype, ndim, shape, strides,
NULL, 0, subok ? (PyObject *)arr : NULL);
}
/*
* Conforms an output parameter 'out' to have 'ndim' dimensions
* with dimensions of size one added in the appropriate places
* indicated by 'axis_flags'.
*
* The return value is a view into 'out'.
*/
static PyArrayObject *
conform_reduce_result(int ndim, npy_bool *axis_flags,
PyArrayObject *out, int keepdims, const char *funcname,
int need_copy)
{
npy_intp strides[NPY_MAXDIMS], shape[NPY_MAXDIMS];
npy_intp *strides_out = PyArray_STRIDES(out);
npy_intp *shape_out = PyArray_DIMS(out);
int idim, idim_out, ndim_out = PyArray_NDIM(out);
PyArray_Descr *dtype;
PyArrayObject_fields *ret;
/*
* If the 'keepdims' parameter is true, do a simpler validation and
* return a new reference to 'out'.
*/
if (keepdims) {
if (PyArray_NDIM(out) != ndim) {
PyErr_Format(PyExc_ValueError,
"output parameter for reduction operation %s "
"has the wrong number of dimensions (must match "
"the operand's when keepdims=True)", funcname);
return NULL;
}
for (idim = 0; idim < ndim; ++idim) {
if (axis_flags[idim]) {
if (shape_out[idim] != 1) {
PyErr_Format(PyExc_ValueError,
"output parameter for reduction operation %s "
"has a reduction dimension not equal to one "
"(required when keepdims=True)", funcname);
return NULL;
}
}
}
Py_INCREF(out);
return out;
}
/* Construct the strides and shape */
idim_out = 0;
for (idim = 0; idim < ndim; ++idim) {
if (axis_flags[idim]) {
strides[idim] = 0;
shape[idim] = 1;
}
else {
if (idim_out >= ndim_out) {
PyErr_Format(PyExc_ValueError,
"output parameter for reduction operation %s "
"does not have enough dimensions", funcname);
return NULL;
}
strides[idim] = strides_out[idim_out];
shape[idim] = shape_out[idim_out];
++idim_out;
}
}
if (idim_out != ndim_out) {
PyErr_Format(PyExc_ValueError,
"output parameter for reduction operation %s "
"has too many dimensions", funcname);
return NULL;
}
/* Allocate the view */
dtype = PyArray_DESCR(out);
Py_INCREF(dtype);
/* TODO: use PyArray_NewFromDescrAndBase here once multiarray and umath
* are merged
*/
ret = (PyArrayObject_fields *)PyArray_NewFromDescr(
&PyArray_Type, dtype,
ndim, shape, strides, PyArray_DATA(out),
PyArray_FLAGS(out), NULL);
if (ret == NULL) {
return NULL;
}
Py_INCREF(out);
if (PyArray_SetBaseObject((PyArrayObject *)ret, (PyObject *)out) < 0) {
Py_DECREF(ret);
return NULL;
}
if (need_copy) {
PyArrayObject *ret_copy;
ret_copy = (PyArrayObject *)PyArray_NewLikeArray(
(PyArrayObject *)ret, NPY_ANYORDER, NULL, 0);
if (ret_copy == NULL) {
Py_DECREF(ret);
return NULL;
}
if (PyArray_CopyInto(ret_copy, (PyArrayObject *)ret) != 0) {
Py_DECREF(ret);
Py_DECREF(ret_copy);
return NULL;
}
if (PyArray_SetWritebackIfCopyBase(ret_copy, (PyArrayObject *)ret) < 0) {
Py_DECREF(ret);
Py_DECREF(ret_copy);
return NULL;
}
return ret_copy;
}
else {
return (PyArrayObject *)ret;
}
}
/*
* Creates a result for reducing 'operand' along the axes specified
* in 'axis_flags'. If 'dtype' isn't NULL, this function steals a
* reference to 'dtype'.
*
* If 'out' isn't NULL, this function creates a view conforming
* to the number of dimensions of 'operand', adding a singleton dimension
* for each reduction axis specified. In this case, 'dtype' is ignored
* (but its reference is still stolen), and the caller must handle any
* type conversion/validity check for 'out'
*
* If 'subok' is true, creates a result with the subtype of 'operand',
* otherwise creates on with the base ndarray class.
*
* If 'out' is NULL, it allocates a new array whose shape matches that of
* 'operand', except for at the reduction axes. If 'dtype' is NULL, the dtype
* of 'operand' is used for the result.
*/
NPY_NO_EXPORT PyArrayObject *
PyArray_CreateReduceResult(PyArrayObject *operand, PyArrayObject *out,
PyArray_Descr *dtype, npy_bool *axis_flags,
int keepdims, int subok,
const char *funcname)
{
PyArrayObject *result;
if (out == NULL) {
/* This function steals the reference to 'dtype' */
result = allocate_reduce_result(operand, axis_flags, dtype, subok);
}
else {
int need_copy = 0;
if (solve_may_share_memory(operand, out, 1) != 0) {
need_copy = 1;
}
/* Steal the dtype reference */
Py_XDECREF(dtype);
result = conform_reduce_result(PyArray_NDIM(operand), axis_flags,
out, keepdims, funcname, need_copy);
}
return result;
}
/*
* Count the number of dimensions selected in 'axis_flags'
*/
static int
count_axes(int ndim, npy_bool *axis_flags)
{
int idim;
int naxes = 0;
for (idim = 0; idim < ndim; ++idim) {
if (axis_flags[idim]) {
naxes++;
}
}
return naxes;
}
/*
* This function initializes a result array for a reduction operation
* which has no identity. This means it needs to copy the first element
* it sees along the reduction axes to result, then return a view of
* the operand which excludes that element.
*
* If a reduction has an identity, such as 0 or 1, the result should be
* initialized by calling PyArray_AssignZero(result, NULL, NULL) or
* PyArray_AssignOne(result, NULL, NULL), because this function raises an
* exception when there are no elements to reduce (which appropriate iff the
* reduction operation has no identity).
*
* This means it copies the subarray indexed at zero along each reduction axis
* into 'result', then returns a view into 'operand' excluding those copied
* elements.
*
* result : The array into which the result is computed. This must have
* the same number of dimensions as 'operand', but for each
* axis i where 'axis_flags[i]' is True, it has a single element.
* operand : The array being reduced.
* axis_flags : An array of boolean flags, one for each axis of 'operand'.
* When a flag is True, it indicates to reduce along that axis.
* out_skip_first_count : This gets populated with the number of first-visit
* elements that should be skipped during the
* iteration loop.
* funcname : The name of the reduction operation, for the purpose of
* better quality error messages. For example, "numpy.max"
* would be a good name for NumPy's max function.
*
* Returns a view which contains the remaining elements on which to do
* the reduction.
*/
NPY_NO_EXPORT PyArrayObject *
PyArray_InitializeReduceResult(
PyArrayObject *result, PyArrayObject *operand,
npy_bool *axis_flags,
npy_intp *out_skip_first_count, const char *funcname)
{
npy_intp *strides, *shape, shape_orig[NPY_MAXDIMS];
PyArrayObject *op_view = NULL;
int idim, ndim, nreduce_axes;
ndim = PyArray_NDIM(operand);
/* Default to no skipping first-visit elements in the iteration */
*out_skip_first_count = 0;
/* Take a view into 'operand' which we can modify. */
op_view = (PyArrayObject *)PyArray_View(operand, NULL, &PyArray_Type);
if (op_view == NULL) {
return NULL;
}
/*
* Now copy the subarray of the first element along each reduction axis,
* then return a view to the rest.
*
* Adjust the shape to only look at the first element along
* any of the reduction axes. We count the number of reduction axes
* at the same time.
*/
shape = PyArray_SHAPE(op_view);
nreduce_axes = 0;
if (ndim) {
memcpy(shape_orig, shape, ndim * sizeof(npy_intp));
}
for (idim = 0; idim < ndim; ++idim) {
if (axis_flags[idim]) {
if (shape[idim] == 0) {
PyErr_Format(PyExc_ValueError,
"zero-size array to reduction operation %s "
"which has no identity",
funcname);
Py_DECREF(op_view);
return NULL;
}
shape[idim] = 1;
++nreduce_axes;
}
}
/*
* Copy the elements into the result to start.
*/
if (PyArray_CopyInto(result, op_view) < 0) {
Py_DECREF(op_view);
return NULL;
}
/*
* If there is one reduction axis, adjust the view's
* shape to only look at the remaining elements
*/
if (nreduce_axes == 1) {
strides = PyArray_STRIDES(op_view);
for (idim = 0; idim < ndim; ++idim) {
if (axis_flags[idim]) {
shape[idim] = shape_orig[idim] - 1;
((PyArrayObject_fields *)op_view)->data += strides[idim];
}
}
}
/* If there are zero reduction axes, make the view empty */
else if (nreduce_axes == 0) {
for (idim = 0; idim < ndim; ++idim) {
shape[idim] = 0;
}
}
/*
* Otherwise iterate over the whole operand, but tell the inner loop
* to skip the elements we already copied by setting the skip_first_count.
*/
else {
*out_skip_first_count = PyArray_SIZE(result);
Py_DECREF(op_view);
Py_INCREF(operand);
op_view = operand;
}
return op_view;
}
/*
* This function executes all the standard NumPy reduction function
* boilerplate code, just calling the appropriate inner loop function where
* necessary.
*
* operand : The array to be reduced.
* out : NULL, or the array into which to place the result.
* wheremask : NOT YET SUPPORTED, but this parameter is placed here
* so that support can be added in the future without breaking
* API compatibility. Pass in NULL.
* operand_dtype : The dtype the inner loop expects for the operand.
* result_dtype : The dtype the inner loop expects for the result.
* casting : The casting rule to apply to the operands.
* axis_flags : Flags indicating the reduction axes of 'operand'.
* reorderable : If True, the reduction being done is reorderable, which
* means specifying multiple axes of reduction at once is ok,
* and the reduction code may calculate the reduction in an
* arbitrary order. The calculation may be reordered because
* of cache behavior or multithreading requirements.
* keepdims : If true, leaves the reduction dimensions in the result
* with size one.
* subok : If true, the result uses the subclass of operand, otherwise
* it is always a base class ndarray.
* identity : If Py_None, PyArray_InitializeReduceResult is used, otherwise
* this value is used to initialize the result to
* the reduction's unit.
* loop : The loop which does the reduction.
* data : Data which is passed to the inner loop.
* buffersize : Buffer size for the iterator. For the default, pass in 0.
* funcname : The name of the reduction function, for error messages.
* errormask : forwarded from _get_bufsize_errmask
*
* TODO FIXME: if you squint, this is essentially an second independent
* implementation of generalized ufuncs with signature (i)->(), plus a few
* extra bells and whistles. (Indeed, as far as I can tell, it was originally
* split out to support a fancy version of count_nonzero... which is not
* actually a reduction function at all, it's just a (i)->() function!) So
* probably these two implementation should be merged into one. (In fact it
* would be quite nice to support axis= and keepdims etc. for arbitrary
* generalized ufuncs!)
*/
NPY_NO_EXPORT PyArrayObject *
PyUFunc_ReduceWrapper(PyArrayObject *operand, PyArrayObject *out,
PyArrayObject *wheremask,
PyArray_Descr *operand_dtype,
PyArray_Descr *result_dtype,
NPY_CASTING casting,
npy_bool *axis_flags, int reorderable,
int keepdims,
int subok,
PyObject *identity,
PyArray_ReduceLoopFunc *loop,
void *data, npy_intp buffersize, const char *funcname,
int errormask)
{
PyArrayObject *result = NULL, *op_view = NULL;
npy_intp skip_first_count = 0;
/* Iterator parameters */
NpyIter *iter = NULL;
PyArrayObject *op[2];
PyArray_Descr *op_dtypes[2];
npy_uint32 flags, op_flags[2];
/* More than one axis means multiple orders are possible */
if (!reorderable && count_axes(PyArray_NDIM(operand), axis_flags) > 1) {
PyErr_Format(PyExc_ValueError,
"reduction operation '%s' is not reorderable, "
"so at most one axis may be specified",
funcname);
return NULL;
}
/* Validate that the parameters for future expansion are NULL */
if (wheremask != NULL) {
PyErr_SetString(PyExc_RuntimeError,
"Reduce operations in NumPy do not yet support "
"a where mask");
return NULL;
}
/*
* This either conforms 'out' to the ndim of 'operand', or allocates
* a new array appropriate for this reduction.
*
* A new array with WRITEBACKIFCOPY is allocated if operand and out have memory
* overlap.
*/
Py_INCREF(result_dtype);
result = PyArray_CreateReduceResult(operand, out,
result_dtype, axis_flags,
keepdims, subok, funcname);
if (result == NULL) {
goto fail;
}
/*
* Initialize the result to the reduction unit if possible,
* otherwise copy the initial values and get a view to the rest.
*/
if (identity != Py_None) {
if (PyArray_FillWithScalar(result, identity) < 0) {
goto fail;
}
op_view = operand;
Py_INCREF(op_view);
}
else {
op_view = PyArray_InitializeReduceResult(
result, operand, axis_flags, &skip_first_count, funcname);
if (op_view == NULL) {
goto fail;
}
/* empty op_view signals no reduction; but 0-d arrays cannot be empty */
if ((PyArray_SIZE(op_view) == 0) || (PyArray_NDIM(operand) == 0)) {
Py_DECREF(op_view);
op_view = NULL;
goto finish;
}
}
/* Set up the iterator */
op[0] = result;
op[1] = op_view;
op_dtypes[0] = result_dtype;
op_dtypes[1] = operand_dtype;
flags = NPY_ITER_BUFFERED |
NPY_ITER_EXTERNAL_LOOP |
NPY_ITER_GROWINNER |
NPY_ITER_DONT_NEGATE_STRIDES |
NPY_ITER_ZEROSIZE_OK |
NPY_ITER_REDUCE_OK |
NPY_ITER_REFS_OK;
op_flags[0] = NPY_ITER_READWRITE |
NPY_ITER_ALIGNED |
NPY_ITER_NO_SUBTYPE;
op_flags[1] = NPY_ITER_READONLY |
NPY_ITER_ALIGNED;
iter = NpyIter_AdvancedNew(2, op, flags,
NPY_KEEPORDER, casting,
op_flags,
op_dtypes,
-1, NULL, NULL, buffersize);
if (iter == NULL) {
goto fail;
}
/* Start with the floating-point exception flags cleared */
npy_clear_floatstatus_barrier((char*)&iter);
if (NpyIter_GetIterSize(iter) != 0) {
NpyIter_IterNextFunc *iternext;
char **dataptr;
npy_intp *strideptr;
npy_intp *countptr;
int needs_api;
iternext = NpyIter_GetIterNext(iter, NULL);
if (iternext == NULL) {
goto fail;
}
dataptr = NpyIter_GetDataPtrArray(iter);
strideptr = NpyIter_GetInnerStrideArray(iter);
countptr = NpyIter_GetInnerLoopSizePtr(iter);
needs_api = NpyIter_IterationNeedsAPI(iter);
/* Straightforward reduction */
if (loop == NULL) {
PyErr_Format(PyExc_RuntimeError,
"reduction operation %s did not supply an "
"inner loop function", funcname);
goto fail;
}
if (loop(iter, dataptr, strideptr, countptr,
iternext, needs_api, skip_first_count, data) < 0) {
goto fail;
}
}
/* Check whether any errors occurred during the loop */
if (PyErr_Occurred() ||
_check_ufunc_fperr(errormask, NULL, "reduce") < 0) {
goto fail;
}
NpyIter_Deallocate(iter);
Py_DECREF(op_view);
finish:
/* Strip out the extra 'one' dimensions in the result */
if (out == NULL) {
if (!keepdims) {
PyArray_RemoveAxesInPlace(result, axis_flags);
}
}
else {
PyArray_ResolveWritebackIfCopy(result); /* prevent spurious warnings */
Py_DECREF(result);
result = out;
Py_INCREF(result);
}
return result;
fail:
PyArray_ResolveWritebackIfCopy(result); /* prevent spurious warnings */
Py_XDECREF(result);
Py_XDECREF(op_view);
if (iter != NULL) {
NpyIter_Deallocate(iter);
}
return NULL;
}
|
faa9fbe9ac93efb13d58144cbbd626131c14fbbd
|
ed3b24ae57df21a5b089148235dd1b6d728e56f3
|
/ld/unit-tests/test-cases/kext-basic/mykext.c
|
6dfeb5c56a16e7a0beb56a8571c9fea2800d4035
|
[
"APSL-2.0",
"MIT"
] |
permissive
|
michaeleisel/zld
|
36ce14511ca9e0a971a0ed614bbee5dac9bb6fa1
|
519197a3bf4dbe47ea5a3bbce609df166f6f976d
|
refs/heads/master
| 2023-08-23T13:46:50.509156
| 2023-02-15T06:02:03
| 2023-02-15T06:02:03
| 237,002,244
| 1,217
| 55
|
MIT
| 2023-02-15T06:00:43
| 2020-01-29T14:32:45
|
C++
|
UTF-8
|
C
| false
| false
| 355
|
c
|
mykext.c
|
#include <mach/mach_types.h>
extern void extern_func();
int my_global = 3;
extern int extern_global;
kern_return_t mykext_start (kmod_info_t * ki, void * d) {
++my_global;
++extern_global;
extern_func();
return KERN_SUCCESS;
}
kern_return_t mykext_stop (kmod_info_t * ki, void * d) {
--my_global;
--extern_global;
return KERN_SUCCESS;
}
|
3c4612da7fc17f77ce2d75125a2f206ba84c0b85
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/boards/arm/stm32/stm32vldiscovery/include/board.h
|
3a1de139b827f17232e8df32149fa3f88156287b
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 4,979
|
h
|
board.h
|
/****************************************************************************
* boards/arm/stm32/stm32vldiscovery/include/board.h
*
* 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 __BOARDS_ARM_STM32_STM32VLDISCOVERY_INCLUDE_BOARD_H
#define __BOARDS_ARM_STM32_STM32VLDISCOVERY_INCLUDE_BOARD_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#ifndef __ASSEMBLY__
# include <stdint.h>
#endif
#include "stm32_rcc.h"
#include "stm32.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Clocking *****************************************************************/
/* On-board crystal frequency is 8MHz (HSE) */
#define STM32_BOARD_XTAL 8000000ul
/* PLL source is HSE / 1,
* PLL multiplier is 3: PLL output frequency is 8MHz (XTAL) x 3 = 24MHz
*/
#define STM32_CFGR2_PREDIV1 RCC_CFGR2_PREDIV1d1
#define STM32_CFGR_PLLSRC RCC_CFGR_PLLSRC
#define STM32_CFGR_PLLXTPRE 0
#define STM32_CFGR_PLLMUL RCC_CFGR_PLLMUL_CLKx3
#define STM32_PLL_FREQUENCY (3 * STM32_BOARD_XTAL)
/* Use the PLL and set the SYSCLK source to be the PLL */
#define STM32_SYSCLK_SW RCC_CFGR_SW_PLL
#define STM32_SYSCLK_SWS RCC_CFGR_SWS_PLL
#define STM32_SYSCLK_FREQUENCY STM32_PLL_FREQUENCY
/* AHB clock (HCLK) is SYSCLK (24MHz) */
#define STM32_RCC_CFGR_HPRE RCC_CFGR_HPRE_SYSCLK
#define STM32_HCLK_FREQUENCY STM32_PLL_FREQUENCY
/* APB2 clock (PCLK2) is HCLK (24MHz) */
#define STM32_RCC_CFGR_PPRE2 RCC_CFGR_PPRE2_HCLK
#define STM32_PCLK2_FREQUENCY STM32_HCLK_FREQUENCY
/* APB2 timers (1, 15-17) will receive PCLK2. */
#define STM32_APB2_TIM1_CLKIN STM32_PCLK2_FREQUENCY
#define STM32_APB2_TIM15_CLKIN STM32_PCLK2_FREQUENCY
#define STM32_APB2_TIM16_CLKIN STM32_PCLK2_FREQUENCY
#define STM32_APB2_TIM17_CLKIN STM32_PCLK2_FREQUENCY
/* APB1 clock (PCLK1) is HCLK (24MHz) */
#define STM32_RCC_CFGR_PPRE1 RCC_CFGR_PPRE1_HCLK
#define STM32_PCLK1_FREQUENCY STM32_HCLK_FREQUENCY
/* APB1 timers (2-7, 12-14) will receive PCLK1. */
#define STM32_APB1_TIM2_CLKIN STM32_PCLK1_FREQUENCY
#define STM32_APB1_TIM3_CLKIN STM32_PCLK1_FREQUENCY
#define STM32_APB1_TIM4_CLKIN STM32_PCLK1_FREQUENCY
#define STM32_APB1_TIM5_CLKIN STM32_PCLK1_FREQUENCY
#define STM32_APB1_TIM6_CLKIN STM32_PCLK1_FREQUENCY
#define STM32_APB1_TIM7_CLKIN STM32_PCLK1_FREQUENCY
#define STM32_APB1_TIM12_CLKIN STM32_PCLK1_FREQUENCY
#define STM32_APB1_TIM13_CLKIN STM32_PCLK1_FREQUENCY
#define STM32_APB1_TIM14_CLKIN STM32_PCLK1_FREQUENCY
/* Timer Frequencies, if APBx is set to 1, frequency is same to APBx
* otherwise frequency is 2xAPBx.
* Note: TIM1,15-17 are on APB2, others on APB1
*/
#define BOARD_TIM1_FREQUENCY STM32_HCLK_FREQUENCY
#define BOARD_TIM2_FREQUENCY STM32_HCLK_FREQUENCY
#define BOARD_TIM3_FREQUENCY STM32_HCLK_FREQUENCY
#define BOARD_TIM4_FREQUENCY STM32_HCLK_FREQUENCY
#define BOARD_TIM5_FREQUENCY STM32_HCLK_FREQUENCY
#define BOARD_TIM6_FREQUENCY STM32_HCLK_FREQUENCY
#define BOARD_TIM7_FREQUENCY STM32_HCLK_FREQUENCY
#define BOARD_TIM8_FREQUENCY STM32_HCLK_FREQUENCY
/* LED definitions **********************************************************/
/* It is assumed that a generic board has 1 LED. Thus only two different
* states can be shown. Statuses defined as "1" will light the LED, the
* ones defined as "0" will turn the LED off.
*/
#define LED_STARTED 1
#define LED_HEAPALLOCATE 1
#define LED_IRQSENABLED 1
#define LED_STACKCREATED 1
#define LED_INIRQ 1
#define LED_SIGNAL 1
#define LED_ASSERTION 0
#define LED_PANIC 0
/* Button definitions *******************************************************/
/* It is assumed that a generic board has 1 button. */
#define BUTTON_0 0
#define NUM_BUTTONS 1
#define BUTTON_0_BIT (1 << BUTTON_0)
#endif /* __BOARDS_ARM_STM32_STM32VLDISCOVERY_INCLUDE_BOARD_H */
|
3b45fca2cb615752072c3121e9f003a878021ac0
|
b445f7ba5ae4899c3782dc08627b778de6bbf12b
|
/include/yyjson/yyjson.c
|
17db9778f1ac14c669315c5be4394eb4f0d7a469
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
ijl/orjson
|
91e620f1e68e985064a68e77569b56ff378637ea
|
d1cd27e29c8df2768be016071d0800a92d120786
|
refs/heads/master
| 2023-08-31T05:10:58.385975
| 2023-08-29T12:29:42
| 2023-08-29T13:05:57
| 158,618,772
| 4,895
| 243
|
Apache-2.0
| 2023-09-08T00:40:34
| 2018-11-21T23:43:14
|
Python
|
UTF-8
|
C
| false
| false
| 346,765
|
c
|
yyjson.c
|
/*==============================================================================
Copyright (c) 2020 YaoYuan <ibireme@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*============================================================================*/
#include "yyjson.h"
#include <math.h>
/*==============================================================================
* Warning Suppress
*============================================================================*/
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wunused-function"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wunused-label"
# pragma clang diagnostic ignored "-Wunused-macros"
# pragma clang diagnostic ignored "-Wunused-variable"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wunused-label"
# pragma GCC diagnostic ignored "-Wunused-macros"
# pragma GCC diagnostic ignored "-Wunused-variable"
#elif defined(_MSC_VER)
# pragma warning(disable:4100) /* unreferenced formal parameter */
# pragma warning(disable:4101) /* unreferenced variable */
# pragma warning(disable:4102) /* unreferenced label */
# pragma warning(disable:4127) /* conditional expression is constant */
# pragma warning(disable:4706) /* assignment within conditional expression */
#endif
/*==============================================================================
* Version
*============================================================================*/
uint32_t yyjson_version(void) {
return YYJSON_VERSION_HEX;
}
/*==============================================================================
* Flags
*============================================================================*/
/* msvc intrinsic */
#if YYJSON_MSC_VER >= 1400
# include <intrin.h>
# if defined(_M_AMD64) || defined(_M_ARM64)
# define MSC_HAS_BIT_SCAN_64 1
# pragma intrinsic(_BitScanForward64)
# pragma intrinsic(_BitScanReverse64)
# else
# define MSC_HAS_BIT_SCAN_64 0
# endif
# if defined(_M_AMD64) || defined(_M_ARM64) || \
defined(_M_IX86) || defined(_M_ARM)
# define MSC_HAS_BIT_SCAN 1
# pragma intrinsic(_BitScanForward)
# pragma intrinsic(_BitScanReverse)
# else
# define MSC_HAS_BIT_SCAN 0
# endif
# if defined(_M_AMD64)
# define MSC_HAS_UMUL128 1
# pragma intrinsic(_umul128)
# else
# define MSC_HAS_UMUL128 0
# endif
#else
# define MSC_HAS_BIT_SCAN_64 0
# define MSC_HAS_BIT_SCAN 0
# define MSC_HAS_UMUL128 0
#endif
/* gcc builtin */
#if yyjson_has_builtin(__builtin_clzll) || yyjson_gcc_available(3, 4, 0)
# define GCC_HAS_CLZLL 1
#else
# define GCC_HAS_CLZLL 0
#endif
#if yyjson_has_builtin(__builtin_ctzll) || yyjson_gcc_available(3, 4, 0)
# define GCC_HAS_CTZLL 1
#else
# define GCC_HAS_CTZLL 0
#endif
/* int128 type */
#if defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16) && \
(defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER))
# define YYJSON_HAS_INT128 1
#else
# define YYJSON_HAS_INT128 0
#endif
/* IEEE 754 floating-point binary representation */
#if defined(__STDC_IEC_559__) || defined(__STDC_IEC_60559_BFP__)
# define YYJSON_HAS_IEEE_754 1
#elif (FLT_RADIX == 2) && (DBL_MANT_DIG == 53) && (DBL_DIG == 15) && \
(DBL_MIN_EXP == -1021) && (DBL_MAX_EXP == 1024) && \
(DBL_MIN_10_EXP == -307) && (DBL_MAX_10_EXP == 308)
# define YYJSON_HAS_IEEE_754 1
#else
# define YYJSON_HAS_IEEE_754 0
#endif
/*
Correct rounding in double number computations.
On the x86 architecture, some compilers may use x87 FPU instructions for
floating-point arithmetic. The x87 FPU loads all floating point number as
80-bit double-extended precision internally, then rounds the result to original
precision, which may produce inaccurate results. For a more detailed
explanation, see the paper: https://arxiv.org/abs/cs/0701192
Here are some examples of double precision calculation error:
2877.0 / 1e6 == 0.002877, but x87 returns 0.0028770000000000002
43683.0 * 1e21 == 4.3683e25, but x87 returns 4.3683000000000004e25
Here are some examples of compiler flags to generate x87 instructions on x86:
clang -m32 -mno-sse
gcc/icc -m32 -mfpmath=387
msvc /arch:SSE or /arch:IA32
If we are sure that there's no similar error described above, we can define the
YYJSON_DOUBLE_MATH_CORRECT as 1 to enable the fast path calculation. This is
not an accurate detection, it's just try to avoid the error at compile-time.
An accurate detection can be done at run-time:
bool is_double_math_correct(void) {
volatile double r = 43683.0;
r *= 1e21;
return r == 4.3683e25;
}
See also: utils.h in https://github.com/google/double-conversion/
*/
#if !defined(FLT_EVAL_METHOD) && defined(__FLT_EVAL_METHOD__)
# define FLT_EVAL_METHOD __FLT_EVAL_METHOD__
#endif
#if defined(FLT_EVAL_METHOD) && FLT_EVAL_METHOD != 0 && FLT_EVAL_METHOD != 1
# define YYJSON_DOUBLE_MATH_CORRECT 0
#elif defined(i386) || defined(__i386) || defined(__i386__) || \
defined(_X86_) || defined(__X86__) || defined(_M_IX86) || \
defined(__I86__) || defined(__IA32__) || defined(__THW_INTEL)
# if (defined(_MSC_VER) && defined(_M_IX86_FP) && _M_IX86_FP == 2) || \
(defined(__SSE2_MATH__) && __SSE2_MATH__)
# define YYJSON_DOUBLE_MATH_CORRECT 1
# else
# define YYJSON_DOUBLE_MATH_CORRECT 0
# endif
#elif defined(__mc68000__) || defined(__pnacl__) || defined(__native_client__)
# define YYJSON_DOUBLE_MATH_CORRECT 0
#else
# define YYJSON_DOUBLE_MATH_CORRECT 1
#endif
/* endian */
#if yyjson_has_include(<sys/types.h>)
# include <sys/types.h> /* POSIX */
#endif
#if yyjson_has_include(<endian.h>)
# include <endian.h> /* Linux */
#elif yyjson_has_include(<sys/endian.h>)
# include <sys/endian.h> /* BSD, Android */
#elif yyjson_has_include(<machine/endian.h>)
# include <machine/endian.h> /* BSD, Darwin */
#endif
#define YYJSON_BIG_ENDIAN 4321
#define YYJSON_LITTLE_ENDIAN 1234
#if defined(BYTE_ORDER) && BYTE_ORDER
# if defined(BIG_ENDIAN) && (BYTE_ORDER == BIG_ENDIAN)
# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN
# elif defined(LITTLE_ENDIAN) && (BYTE_ORDER == LITTLE_ENDIAN)
# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN
# endif
#elif defined(__BYTE_ORDER) && __BYTE_ORDER
# if defined(__BIG_ENDIAN) && (__BYTE_ORDER == __BIG_ENDIAN)
# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN
# elif defined(__LITTLE_ENDIAN) && (__BYTE_ORDER == __LITTLE_ENDIAN)
# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN
# endif
#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__
# if defined(__ORDER_BIG_ENDIAN__) && \
(__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN
# elif defined(__ORDER_LITTLE_ENDIAN__) && \
(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN
# endif
#elif (defined(__LITTLE_ENDIAN__) && __LITTLE_ENDIAN__ == 1) || \
defined(__i386) || defined(__i386__) || \
defined(_X86_) || defined(__X86__) || \
defined(_M_IX86) || defined(__THW_INTEL__) || \
defined(__x86_64) || defined(__x86_64__) || \
defined(__amd64) || defined(__amd64__) || \
defined(_M_AMD64) || defined(_M_X64) || \
defined(_M_ARM) || defined(_M_ARM64) || \
defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \
defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) || \
defined(__EMSCRIPTEN__) || defined(__wasm__) || \
defined(__loongarch__)
# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN
#elif (defined(__BIG_ENDIAN__) && __BIG_ENDIAN__ == 1) || \
defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \
defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__) || \
defined(__or1k__) || defined(__OR1K__)
# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN
#else
# define YYJSON_ENDIAN 0 /* unknown endian, detect at run-time */
#endif
/*
This macro controls how yyjson handles unaligned memory accesses.
By default, yyjson uses `memcpy()` for memory copying. This takes advantage of
the compiler's automatic optimizations to generate unaligned memory access
instructions when the target architecture supports it.
However, for some older compilers or architectures where `memcpy()` isn't
optimized well and may generate unnecessary function calls, consider defining
this macro as 1. In such cases, yyjson switches to manual byte-by-byte access,
potentially improving performance. An example of the generated assembly code on
the ARM platform can be found here: https://godbolt.org/z/334jjhxPT
As this flag has already been enabled for some common architectures in the
following code, users typically don't need to manually specify it. If users are
unsure about it, please review the generated assembly code or perform actual
benchmark to make an informed decision.
*/
#ifndef YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
# if defined(__ia64) || defined(_IA64) || defined(__IA64__) || \
defined(__ia64__) || defined(_M_IA64) || defined(__itanium__)
# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* Itanium */
# elif (defined(__arm__) || defined(__arm64__) || defined(__aarch64__)) && \
(defined(__GNUC__) || defined(__clang__)) && \
(!defined(__ARM_FEATURE_UNALIGNED) || !__ARM_FEATURE_UNALIGNED)
# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* ARM */
# elif defined(__sparc) || defined(__sparc__)
# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* SPARC */
# elif defined(__mips) || defined(__mips__) || defined(__MIPS__)
# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* MIPS */
# elif defined(__m68k__) || defined(M68000)
# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* M68K */
# else
# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 0
# endif
#endif
/*
Estimated initial ratio of the JSON data (data_size / value_count).
For example:
data: {"id":12345678,"name":"Harry"}
data_size: 30
value_count: 5
ratio: 6
yyjson uses dynamic memory with a growth factor of 1.5 when reading and writing
JSON, the ratios below are used to determine the initial memory size.
A too large ratio will waste memory, and a too small ratio will cause multiple
memory growths and degrade performance. Currently, these ratios are generated
with some commonly used JSON datasets.
*/
#define YYJSON_READER_ESTIMATED_PRETTY_RATIO 16
#define YYJSON_READER_ESTIMATED_MINIFY_RATIO 6
#define YYJSON_WRITER_ESTIMATED_PRETTY_RATIO 32
#define YYJSON_WRITER_ESTIMATED_MINIFY_RATIO 18
/* The initial and maximum size of the memory pool's chunk in yyjson_mut_doc. */
#define YYJSON_MUT_DOC_STR_POOL_INIT_SIZE 0x100
#define YYJSON_MUT_DOC_STR_POOL_MAX_SIZE 0x10000000
#define YYJSON_MUT_DOC_VAL_POOL_INIT_SIZE (0x10 * sizeof(yyjson_mut_val))
#define YYJSON_MUT_DOC_VAL_POOL_MAX_SIZE (0x1000000 * sizeof(yyjson_mut_val))
/* Default value for compile-time options. */
#ifndef YYJSON_DISABLE_READER
#define YYJSON_DISABLE_READER 0
#endif
#ifndef YYJSON_DISABLE_WRITER
#define YYJSON_DISABLE_WRITER 0
#endif
#ifndef YYJSON_DISABLE_UTILS
#define YYJSON_DISABLE_UTILS 0
#endif
#ifndef YYJSON_DISABLE_FAST_FP_CONV
#define YYJSON_DISABLE_FAST_FP_CONV 0
#endif
#ifndef YYJSON_DISABLE_NON_STANDARD
#define YYJSON_DISABLE_NON_STANDARD 0
#endif
#ifndef YYJSON_DISABLE_UTF8_VALIDATION
#define YYJSON_DISABLE_UTF8_VALIDATION 0
#endif
/*==============================================================================
* Macros
*============================================================================*/
/* Macros used for loop unrolling and other purpose. */
#define repeat2(x) { x x }
#define repeat3(x) { x x x }
#define repeat4(x) { x x x x }
#define repeat8(x) { x x x x x x x x }
#define repeat16(x) { x x x x x x x x x x x x x x x x }
#define repeat2_incr(x) { x(0) x(1) }
#define repeat4_incr(x) { x(0) x(1) x(2) x(3) }
#define repeat8_incr(x) { x(0) x(1) x(2) x(3) x(4) x(5) x(6) x(7) }
#define repeat16_incr(x) { x(0) x(1) x(2) x(3) x(4) x(5) x(6) x(7) \
x(8) x(9) x(10) x(11) x(12) x(13) x(14) x(15) }
#define repeat_in_1_18(x) { x(1) x(2) x(3) x(4) x(5) x(6) x(7) x(8) \
x(9) x(10) x(11) x(12) x(13) x(14) x(15) x(16) \
x(17) x(18) }
/* Macros used to provide branch prediction information for compiler. */
#undef likely
#define likely(x) yyjson_likely(x)
#undef unlikely
#define unlikely(x) yyjson_unlikely(x)
/* Macros used to provide inline information for compiler. */
#undef static_inline
#define static_inline static yyjson_inline
#undef static_noinline
#define static_noinline static yyjson_noinline
/* Macros for min and max. */
#undef yyjson_min
#define yyjson_min(x, y) ((x) < (y) ? (x) : (y))
#undef yyjson_max
#define yyjson_max(x, y) ((x) > (y) ? (x) : (y))
/* Used to write u64 literal for C89 which doesn't support "ULL" suffix. */
#undef U64
#define U64(hi, lo) ((((u64)hi##UL) << 32U) + lo##UL)
/* Used to cast away (remove) const qualifier. */
#define constcast(type) (type)(void *)(size_t)(const void *)
/* flag test */
#define has_read_flag(_flag) false
#define has_write_flag(_flag) unlikely(write_flag_eq(flg, YYJSON_WRITE_##_flag))
static_inline bool read_flag_eq(yyjson_read_flag flg, yyjson_read_flag chk) {
#if YYJSON_DISABLE_NON_STANDARD
if (chk == YYJSON_READ_ALLOW_INF_AND_NAN ||
chk == YYJSON_READ_ALLOW_COMMENTS ||
chk == YYJSON_READ_ALLOW_TRAILING_COMMAS ||
chk == YYJSON_READ_ALLOW_INVALID_UNICODE)
return false; /* this should be evaluated at compile-time */
#endif
return (flg & chk) != 0;
}
static_inline bool write_flag_eq(yyjson_write_flag flg, yyjson_write_flag chk) {
#if YYJSON_DISABLE_NON_STANDARD
if (chk == YYJSON_WRITE_ALLOW_INF_AND_NAN ||
chk == YYJSON_WRITE_ALLOW_INVALID_UNICODE)
return false; /* this should be evaluated at compile-time */
#endif
return (flg & chk) != 0;
}
/*==============================================================================
* Integer Constants
*============================================================================*/
/* U64 constant values */
#undef U64_MAX
#define U64_MAX U64(0xFFFFFFFF, 0xFFFFFFFF)
#undef I64_MAX
#define I64_MAX U64(0x7FFFFFFF, 0xFFFFFFFF)
#undef USIZE_MAX
#define USIZE_MAX ((usize)(~(usize)0))
/* Maximum number of digits for reading u32/u64/usize safety (not overflow). */
#undef U32_SAFE_DIG
#define U32_SAFE_DIG 9 /* u32 max is 4294967295, 10 digits */
#undef U64_SAFE_DIG
#define U64_SAFE_DIG 19 /* u64 max is 18446744073709551615, 20 digits */
#undef USIZE_SAFE_DIG
#define USIZE_SAFE_DIG (sizeof(usize) == 8 ? U64_SAFE_DIG : U32_SAFE_DIG)
/*==============================================================================
* IEEE-754 Double Number Constants
*============================================================================*/
/* Inf raw value (positive) */
#define F64_RAW_INF U64(0x7FF00000, 0x00000000)
/* NaN raw value (quiet NaN, no payload, no sign) */
#if defined(__hppa__) || (defined(__mips__) && !defined(__mips_nan2008))
#define F64_RAW_NAN U64(0x7FF7FFFF, 0xFFFFFFFF)
#else
#define F64_RAW_NAN U64(0x7FF80000, 0x00000000)
#endif
/* double number bits */
#define F64_BITS 64
/* double number exponent part bits */
#define F64_EXP_BITS 11
/* double number significand part bits */
#define F64_SIG_BITS 52
/* double number significand part bits (with 1 hidden bit) */
#define F64_SIG_FULL_BITS 53
/* double number significand bit mask */
#define F64_SIG_MASK U64(0x000FFFFF, 0xFFFFFFFF)
/* double number exponent bit mask */
#define F64_EXP_MASK U64(0x7FF00000, 0x00000000)
/* double number exponent bias */
#define F64_EXP_BIAS 1023
/* double number significant digits count in decimal */
#define F64_DEC_DIG 17
/* max significant digits count in decimal when reading double number */
#define F64_MAX_DEC_DIG 768
/* maximum decimal power of double number (1.7976931348623157e308) */
#define F64_MAX_DEC_EXP 308
/* minimum decimal power of double number (4.9406564584124654e-324) */
#define F64_MIN_DEC_EXP (-324)
/* maximum binary power of double number */
#define F64_MAX_BIN_EXP 1024
/* minimum binary power of double number */
#define F64_MIN_BIN_EXP (-1021)
/*==============================================================================
* Types
*============================================================================*/
/** Type define for primitive types. */
typedef float f32;
typedef double f64;
typedef int8_t i8;
typedef uint8_t u8;
typedef int16_t i16;
typedef uint16_t u16;
typedef int32_t i32;
typedef uint32_t u32;
typedef int64_t i64;
typedef uint64_t u64;
typedef size_t usize;
/** 128-bit integer, used by floating-point number reader and writer. */
#if YYJSON_HAS_INT128
__extension__ typedef __int128 i128;
__extension__ typedef unsigned __int128 u128;
#endif
/** 16/32/64-bit vector */
typedef struct v16 { char c[2]; } v16;
typedef struct v32 { char c[4]; } v32;
typedef struct v64 { char c[8]; } v64;
/** 16/32/64-bit vector union */
typedef union v16_uni { v16 v; u16 u; } v16_uni;
typedef union v32_uni { v32 v; u32 u; } v32_uni;
typedef union v64_uni { v64 v; u64 u; } v64_uni;
/*==============================================================================
* Load/Store Utils
*============================================================================*/
#if YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
#define byte_move_idx(x) ((char *)dst)[x] = ((const char *)src)[x];
static_inline void byte_copy_2(void *dst, const void *src) {
repeat2_incr(byte_move_idx)
}
static_inline void byte_copy_4(void *dst, const void *src) {
repeat4_incr(byte_move_idx)
}
static_inline void byte_copy_8(void *dst, const void *src) {
repeat8_incr(byte_move_idx)
}
static_inline void byte_copy_16(void *dst, const void *src) {
repeat16_incr(byte_move_idx)
}
static_inline void byte_move_2(void *dst, const void *src) {
repeat2_incr(byte_move_idx)
}
static_inline void byte_move_4(void *dst, const void *src) {
repeat4_incr(byte_move_idx)
}
static_inline void byte_move_8(void *dst, const void *src) {
repeat8_incr(byte_move_idx)
}
static_inline void byte_move_16(void *dst, const void *src) {
repeat16_incr(byte_move_idx)
}
static_inline bool byte_match_2(void *buf, const char *pat) {
return
((char *)buf)[0] == ((const char *)pat)[0] &&
((char *)buf)[1] == ((const char *)pat)[1];
}
static_inline bool byte_match_4(void *buf, const char *pat) {
return
((char *)buf)[0] == ((const char *)pat)[0] &&
((char *)buf)[1] == ((const char *)pat)[1] &&
((char *)buf)[2] == ((const char *)pat)[2] &&
((char *)buf)[3] == ((const char *)pat)[3];
}
static_inline u16 byte_load_2(const void *src) {
v16_uni uni;
uni.v.c[0] = ((const char *)src)[0];
uni.v.c[1] = ((const char *)src)[1];
return uni.u;
}
static_inline u32 byte_load_3(const void *src) {
v32_uni uni;
uni.v.c[0] = ((const char *)src)[0];
uni.v.c[1] = ((const char *)src)[1];
uni.v.c[2] = ((const char *)src)[2];
uni.v.c[3] = 0;
return uni.u;
}
static_inline u32 byte_load_4(const void *src) {
v32_uni uni;
uni.v.c[0] = ((const char *)src)[0];
uni.v.c[1] = ((const char *)src)[1];
uni.v.c[2] = ((const char *)src)[2];
uni.v.c[3] = ((const char *)src)[3];
return uni.u;
}
#undef byte_move_expr
#else
static_inline void byte_copy_2(void *dst, const void *src) {
memcpy(dst, src, 2);
}
static_inline void byte_copy_4(void *dst, const void *src) {
memcpy(dst, src, 4);
}
static_inline void byte_copy_8(void *dst, const void *src) {
memcpy(dst, src, 8);
}
static_inline void byte_copy_16(void *dst, const void *src) {
memcpy(dst, src, 16);
}
static_inline void byte_move_2(void *dst, const void *src) {
u16 tmp;
memcpy(&tmp, src, 2);
memcpy(dst, &tmp, 2);
}
static_inline void byte_move_4(void *dst, const void *src) {
u32 tmp;
memcpy(&tmp, src, 4);
memcpy(dst, &tmp, 4);
}
static_inline void byte_move_8(void *dst, const void *src) {
u64 tmp;
memcpy(&tmp, src, 8);
memcpy(dst, &tmp, 8);
}
static_inline void byte_move_16(void *dst, const void *src) {
char *pdst = (char *)dst;
const char *psrc = (const char *)src;
u64 tmp1, tmp2;
memcpy(&tmp1, psrc, 8);
memcpy(&tmp2, psrc + 8, 8);
memcpy(pdst, &tmp1, 8);
memcpy(pdst + 8, &tmp2, 8);
}
static_inline bool byte_match_2(void *buf, const char *pat) {
v16_uni u1, u2;
memcpy(&u1, buf, 2);
memcpy(&u2, pat, 2);
return u1.u == u2.u;
}
static_inline bool byte_match_4(void *buf, const char *pat) {
v32_uni u1, u2;
memcpy(&u1, buf, 4);
memcpy(&u2, pat, 4);
return u1.u == u2.u;
}
static_inline u16 byte_load_2(const void *src) {
v16_uni uni;
memcpy(&uni, src, 2);
return uni.u;
}
static_inline u32 byte_load_3(const void *src) {
v32_uni uni;
memcpy(&uni, src, 2);
uni.v.c[2] = ((const char *)src)[2];
uni.v.c[3] = 0;
return uni.u;
}
static_inline u32 byte_load_4(const void *src) {
v32_uni uni;
memcpy(&uni, src, 4);
return uni.u;
}
#endif
/*==============================================================================
* Number Utils
* These functions are used to detect and convert NaN and Inf numbers.
*============================================================================*/
/** Convert raw binary to double. */
static_inline f64 f64_from_raw(u64 u) {
/* use memcpy to avoid violating the strict aliasing rule */
f64 f;
memcpy(&f, &u, 8);
return f;
}
/** Convert double to raw binary. */
static_inline u64 f64_to_raw(f64 f) {
/* use memcpy to avoid violating the strict aliasing rule */
u64 u;
memcpy(&u, &f, 8);
return u;
}
/** Get raw 'infinity' with sign. */
static_inline u64 f64_raw_get_inf(bool sign) {
#if YYJSON_HAS_IEEE_754
return F64_RAW_INF | ((u64)sign << 63);
#elif defined(INFINITY)
return f64_to_raw(sign ? -INFINITY : INFINITY);
#else
return f64_to_raw(sign ? -HUGE_VAL : HUGE_VAL);
#endif
}
/** Get raw 'nan' with sign. */
static_inline u64 f64_raw_get_nan(bool sign) {
#if YYJSON_HAS_IEEE_754
return F64_RAW_NAN | ((u64)sign << 63);
#elif defined(NAN)
return f64_to_raw(sign ? (f64)-NAN : (f64)NAN);
#else
return f64_to_raw((sign ? -0.0 : 0.0) / 0.0);
#endif
}
/**
Convert normalized u64 (highest bit is 1) to f64.
Some compiler (such as Microsoft Visual C++ 6.0) do not support converting
number from u64 to f64. This function will first convert u64 to i64 and then
to f64, with `to nearest` rounding mode.
*/
static_inline f64 normalized_u64_to_f64(u64 val) {
#if YYJSON_U64_TO_F64_NO_IMPL
i64 sig = (i64)((val >> 1) | (val & 1));
return ((f64)sig) * (f64)2.0;
#else
return (f64)val;
#endif
}
/*==============================================================================
* Size Utils
* These functions are used for memory allocation.
*============================================================================*/
/** Returns whether the size is overflow after increment. */
static_inline bool size_add_is_overflow(usize size, usize add) {
return size > (size + add);
}
/** Returns whether the size is power of 2 (size should not be 0). */
static_inline bool size_is_pow2(usize size) {
return (size & (size - 1)) == 0;
}
/** Align size upwards (may overflow). */
static_inline usize size_align_up(usize size, usize align) {
if (size_is_pow2(align)) {
return (size + (align - 1)) & ~(align - 1);
} else {
return size + align - (size + align - 1) % align - 1;
}
}
/** Align size downwards. */
static_inline usize size_align_down(usize size, usize align) {
if (size_is_pow2(align)) {
return size & ~(align - 1);
} else {
return size - (size % align);
}
}
/** Align address upwards (may overflow). */
static_inline void *mem_align_up(void *mem, usize align) {
usize size;
memcpy(&size, &mem, sizeof(usize));
size = size_align_up(size, align);
memcpy(&mem, &size, sizeof(usize));
return mem;
}
/*==============================================================================
* Bits Utils
* These functions are used by the floating-point number reader and writer.
*============================================================================*/
/** Returns the number of leading 0-bits in value (input should not be 0). */
static_inline u32 u64_lz_bits(u64 v) {
#if GCC_HAS_CLZLL
return (u32)__builtin_clzll(v);
#elif MSC_HAS_BIT_SCAN_64
unsigned long r;
_BitScanReverse64(&r, v);
return (u32)63 - (u32)r;
#elif MSC_HAS_BIT_SCAN
unsigned long hi, lo;
bool hi_set = _BitScanReverse(&hi, (u32)(v >> 32)) != 0;
_BitScanReverse(&lo, (u32)v);
hi |= 32;
return (u32)63 - (u32)(hi_set ? hi : lo);
#else
/*
branchless, use de Bruijn sequences
see: https://www.chessprogramming.org/BitScan
*/
const u8 table[64] = {
63, 16, 62, 7, 15, 36, 61, 3, 6, 14, 22, 26, 35, 47, 60, 2,
9, 5, 28, 11, 13, 21, 42, 19, 25, 31, 34, 40, 46, 52, 59, 1,
17, 8, 37, 4, 23, 27, 48, 10, 29, 12, 43, 20, 32, 41, 53, 18,
38, 24, 49, 30, 44, 33, 54, 39, 50, 45, 55, 51, 56, 57, 58, 0
};
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
return table[(v * U64(0x03F79D71, 0xB4CB0A89)) >> 58];
#endif
}
/** Returns the number of trailing 0-bits in value (input should not be 0). */
static_inline u32 u64_tz_bits(u64 v) {
#if GCC_HAS_CTZLL
return (u32)__builtin_ctzll(v);
#elif MSC_HAS_BIT_SCAN_64
unsigned long r;
_BitScanForward64(&r, v);
return (u32)r;
#elif MSC_HAS_BIT_SCAN
unsigned long lo, hi;
bool lo_set = _BitScanForward(&lo, (u32)(v)) != 0;
_BitScanForward(&hi, (u32)(v >> 32));
hi += 32;
return lo_set ? lo : hi;
#else
/*
branchless, use de Bruijn sequences
see: https://www.chessprogramming.org/BitScan
*/
const u8 table[64] = {
0, 1, 2, 53, 3, 7, 54, 27, 4, 38, 41, 8, 34, 55, 48, 28,
62, 5, 39, 46, 44, 42, 22, 9, 24, 35, 59, 56, 49, 18, 29, 11,
63, 52, 6, 26, 37, 40, 33, 47, 61, 45, 43, 21, 23, 58, 17, 10,
51, 25, 36, 32, 60, 20, 57, 16, 50, 31, 19, 15, 30, 14, 13, 12
};
return table[((v & (~v + 1)) * U64(0x022FDD63, 0xCC95386D)) >> 58];
#endif
}
/*==============================================================================
* 128-bit Integer Utils
* These functions are used by the floating-point number reader and writer.
*============================================================================*/
/** Multiplies two 64-bit unsigned integers (a * b),
returns the 128-bit result as 'hi' and 'lo'. */
static_inline void u128_mul(u64 a, u64 b, u64 *hi, u64 *lo) {
#if YYJSON_HAS_INT128
u128 m = (u128)a * b;
*hi = (u64)(m >> 64);
*lo = (u64)(m);
#elif MSC_HAS_UMUL128
*lo = _umul128(a, b, hi);
#else
u32 a0 = (u32)(a), a1 = (u32)(a >> 32);
u32 b0 = (u32)(b), b1 = (u32)(b >> 32);
u64 p00 = (u64)a0 * b0, p01 = (u64)a0 * b1;
u64 p10 = (u64)a1 * b0, p11 = (u64)a1 * b1;
u64 m0 = p01 + (p00 >> 32);
u32 m00 = (u32)(m0), m01 = (u32)(m0 >> 32);
u64 m1 = p10 + m00;
u32 m10 = (u32)(m1), m11 = (u32)(m1 >> 32);
*hi = p11 + m01 + m11;
*lo = ((u64)m10 << 32) | (u32)p00;
#endif
}
/** Multiplies two 64-bit unsigned integers and add a value (a * b + c),
returns the 128-bit result as 'hi' and 'lo'. */
static_inline void u128_mul_add(u64 a, u64 b, u64 c, u64 *hi, u64 *lo) {
#if YYJSON_HAS_INT128
u128 m = (u128)a * b + c;
*hi = (u64)(m >> 64);
*lo = (u64)(m);
#else
u64 h, l, t;
u128_mul(a, b, &h, &l);
t = l + c;
h += (u64)(((t < l) | (t < c)));
*hi = h;
*lo = t;
#endif
}
/*==============================================================================
* File Utils
* These functions are used to read and write JSON files.
*============================================================================*/
#define YYJSON_FOPEN_EXT
#if !defined(_MSC_VER) && defined(__GLIBC__) && defined(__GLIBC_PREREQ)
# if __GLIBC_PREREQ(2, 7)
# undef YYJSON_FOPEN_EXT
# define YYJSON_FOPEN_EXT "e" /* glibc extension to enable O_CLOEXEC */
# endif
#endif
static_inline FILE *fopen_safe(const char *path, const char *mode) {
#if YYJSON_MSC_VER >= 1400
FILE *file = NULL;
if (fopen_s(&file, path, mode) != 0) return NULL;
return file;
#else
return fopen(path, mode);
#endif
}
static_inline FILE *fopen_readonly(const char *path) {
return fopen_safe(path, "rb" YYJSON_FOPEN_EXT);
}
static_inline FILE *fopen_writeonly(const char *path) {
return fopen_safe(path, "wb" YYJSON_FOPEN_EXT);
}
static_inline usize fread_safe(void *buf, usize size, FILE *file) {
#if YYJSON_MSC_VER >= 1400
return fread_s(buf, size, 1, size, file);
#else
return fread(buf, 1, size, file);
#endif
}
/*==============================================================================
* Default Memory Allocator
* This is a simple libc memory allocator wrapper.
*============================================================================*/
static void *default_malloc(void *ctx, usize size) {
return malloc(size);
}
static void *default_realloc(void *ctx, void *ptr, usize old_size, usize size) {
return realloc(ptr, size);
}
static void default_free(void *ctx, void *ptr) {
free(ptr);
}
static const yyjson_alc YYJSON_DEFAULT_ALC = {
default_malloc,
default_realloc,
default_free,
NULL
};
static void *null_malloc(void *ctx, usize size) {
return NULL;
}
static void *null_realloc(void *ctx, void *ptr, usize old_size, usize size) {
return NULL;
}
static void null_free(void *ctx, void *ptr) {
return;
}
static const yyjson_alc YYJSON_NULL_ALC = {
null_malloc,
null_realloc,
null_free,
NULL
};
/*==============================================================================
* Pool Memory Allocator
* This is a simple memory allocator that uses linked list memory chunk.
* The following code will be executed only when the library user creates
* this allocator manually.
*============================================================================*/
/** chunk header */
typedef struct pool_chunk {
usize size; /* chunk memory size (include chunk header) */
struct pool_chunk *next;
} pool_chunk;
/** ctx header */
typedef struct pool_ctx {
usize size; /* total memory size (include ctx header) */
pool_chunk *free_list;
} pool_ctx;
static void *pool_malloc(void *ctx_ptr, usize size) {
pool_ctx *ctx = (pool_ctx *)ctx_ptr;
pool_chunk *next, *prev = NULL, *cur = ctx->free_list;
if (unlikely(size == 0 || size >= ctx->size)) return NULL;
size = size_align_up(size, sizeof(pool_chunk)) + sizeof(pool_chunk);
while (cur) {
if (cur->size < size) {
/* not enough space, try next chunk */
prev = cur;
cur = cur->next;
continue;
}
if (cur->size >= size + sizeof(pool_chunk) * 2) {
/* too much space, split this chunk */
next = (pool_chunk *)(void *)((u8 *)cur + size);
next->size = cur->size - size;
next->next = cur->next;
cur->size = size;
} else {
/* just enough space, use whole chunk */
next = cur->next;
}
if (prev) prev->next = next;
else ctx->free_list = next;
return (void *)(cur + 1);
}
return NULL;
}
static void pool_free(void *ctx_ptr, void *ptr) {
pool_ctx *ctx = (pool_ctx *)ctx_ptr;
pool_chunk *cur = ((pool_chunk *)ptr) - 1;
pool_chunk *prev = NULL, *next = ctx->free_list;
while (next && next < cur) {
prev = next;
next = next->next;
}
if (prev) prev->next = cur;
else ctx->free_list = cur;
cur->next = next;
if (next && ((u8 *)cur + cur->size) == (u8 *)next) {
/* merge cur to higher chunk */
cur->size += next->size;
cur->next = next->next;
}
if (prev && ((u8 *)prev + prev->size) == (u8 *)cur) {
/* merge cur to lower chunk */
prev->size += cur->size;
prev->next = cur->next;
}
}
static void *pool_realloc(void *ctx_ptr, void *ptr,
usize old_size, usize size) {
pool_ctx *ctx = (pool_ctx *)ctx_ptr;
pool_chunk *cur = ((pool_chunk *)ptr) - 1, *prev, *next, *tmp;
usize free_size;
void *new_ptr;
if (unlikely(size == 0 || size >= ctx->size)) return NULL;
size = size_align_up(size, sizeof(pool_chunk)) + sizeof(pool_chunk);
/* reduce size */
if (unlikely(size <= cur->size)) {
free_size = cur->size - size;
if (free_size >= sizeof(pool_chunk) * 2) {
tmp = (pool_chunk *)(void *)((u8 *)cur + cur->size - free_size);
tmp->size = free_size;
pool_free(ctx_ptr, (void *)(tmp + 1));
cur->size -= free_size;
}
return ptr;
}
/* find next and prev chunk */
prev = NULL;
next = ctx->free_list;
while (next && next < cur) {
prev = next;
next = next->next;
}
/* merge to higher chunk if they are contiguous */
if ((u8 *)cur + cur->size == (u8 *)next &&
cur->size + next->size >= size) {
free_size = cur->size + next->size - size;
if (free_size > sizeof(pool_chunk) * 2) {
tmp = (pool_chunk *)(void *)((u8 *)cur + size);
if (prev) prev->next = tmp;
else ctx->free_list = tmp;
tmp->next = next->next;
tmp->size = free_size;
cur->size = size;
} else {
if (prev) prev->next = next->next;
else ctx->free_list = next->next;
cur->size += next->size;
}
return ptr;
}
/* fallback to malloc and memcpy */
new_ptr = pool_malloc(ctx_ptr, size - sizeof(pool_chunk));
if (new_ptr) {
memcpy(new_ptr, ptr, cur->size - sizeof(pool_chunk));
pool_free(ctx_ptr, ptr);
}
return new_ptr;
}
bool yyjson_alc_pool_init(yyjson_alc *alc, void *buf, usize size) {
pool_chunk *chunk;
pool_ctx *ctx;
if (unlikely(!alc)) return false;
*alc = YYJSON_NULL_ALC;
if (size < sizeof(pool_ctx) * 4) return false;
ctx = (pool_ctx *)mem_align_up(buf, sizeof(pool_ctx));
if (unlikely(!ctx)) return false;
size -= (usize)((u8 *)ctx - (u8 *)buf);
size = size_align_down(size, sizeof(pool_ctx));
chunk = (pool_chunk *)(ctx + 1);
chunk->size = size - sizeof(pool_ctx);
chunk->next = NULL;
ctx->size = size;
ctx->free_list = chunk;
alc->malloc = pool_malloc;
alc->realloc = pool_realloc;
alc->free = pool_free;
alc->ctx = (void *)ctx;
return true;
}
/*==============================================================================
* JSON document and value
*============================================================================*/
static_inline void unsafe_yyjson_str_pool_release(yyjson_str_pool *pool,
yyjson_alc *alc) {
yyjson_str_chunk *chunk = pool->chunks, *next;
while (chunk) {
next = chunk->next;
alc->free(alc->ctx, chunk);
chunk = next;
}
}
static_inline void unsafe_yyjson_val_pool_release(yyjson_val_pool *pool,
yyjson_alc *alc) {
yyjson_val_chunk *chunk = pool->chunks, *next;
while (chunk) {
next = chunk->next;
alc->free(alc->ctx, chunk);
chunk = next;
}
}
bool unsafe_yyjson_str_pool_grow(yyjson_str_pool *pool,
const yyjson_alc *alc, usize len) {
yyjson_str_chunk *chunk;
usize size, max_len;
/* create a new chunk */
max_len = USIZE_MAX - sizeof(yyjson_str_chunk);
if (unlikely(len > max_len)) return false;
size = len + sizeof(yyjson_str_chunk);
size = yyjson_max(pool->chunk_size, size);
chunk = (yyjson_str_chunk *)alc->malloc(alc->ctx, size);
if (unlikely(!chunk)) return false;
/* insert the new chunk as the head of the linked list */
chunk->next = pool->chunks;
chunk->chunk_size = size;
pool->chunks = chunk;
pool->cur = (char *)chunk + sizeof(yyjson_str_chunk);
pool->end = (char *)chunk + size;
/* the next chunk is twice the size of the current one */
size = yyjson_min(pool->chunk_size * 2, pool->chunk_size_max);
if (size < pool->chunk_size) size = pool->chunk_size_max; /* overflow */
pool->chunk_size = size;
return true;
}
bool unsafe_yyjson_val_pool_grow(yyjson_val_pool *pool,
const yyjson_alc *alc, usize count) {
yyjson_val_chunk *chunk;
usize size, max_count;
/* create a new chunk */
max_count = USIZE_MAX / sizeof(yyjson_mut_val) - 1;
if (unlikely(count > max_count)) return false;
size = (count + 1) * sizeof(yyjson_mut_val);
size = yyjson_max(pool->chunk_size, size);
chunk = (yyjson_val_chunk *)alc->malloc(alc->ctx, size);
if (unlikely(!chunk)) return false;
/* insert the new chunk as the head of the linked list */
chunk->next = pool->chunks;
chunk->chunk_size = size;
pool->chunks = chunk;
pool->cur = (yyjson_mut_val *)(void *)((u8 *)chunk) + 1;
pool->end = (yyjson_mut_val *)(void *)((u8 *)chunk + size);
/* the next chunk is twice the size of the current one */
size = yyjson_min(pool->chunk_size * 2, pool->chunk_size_max);
if (size < pool->chunk_size) size = pool->chunk_size_max; /* overflow */
pool->chunk_size = size;
return true;
}
bool yyjson_mut_doc_set_str_pool_size(yyjson_mut_doc *doc, size_t len) {
usize max_size = USIZE_MAX - sizeof(yyjson_str_chunk);
if (!doc || !len || len > max_size) return false;
doc->str_pool.chunk_size = len + sizeof(yyjson_str_chunk);
return true;
}
bool yyjson_mut_doc_set_val_pool_size(yyjson_mut_doc *doc, size_t count) {
usize max_count = USIZE_MAX / sizeof(yyjson_mut_val) - 1;
if (!doc || !count || count > max_count) return false;
doc->val_pool.chunk_size = (count + 1) * sizeof(yyjson_mut_val);
return true;
}
void yyjson_mut_doc_free(yyjson_mut_doc *doc) {
if (doc) {
yyjson_alc alc = doc->alc;
unsafe_yyjson_str_pool_release(&doc->str_pool, &alc);
unsafe_yyjson_val_pool_release(&doc->val_pool, &alc);
alc.free(alc.ctx, doc);
}
}
yyjson_mut_doc *yyjson_mut_doc_new(const yyjson_alc *alc) {
yyjson_mut_doc *doc;
if (!alc) alc = &YYJSON_DEFAULT_ALC;
doc = (yyjson_mut_doc *)alc->malloc(alc->ctx, sizeof(yyjson_mut_doc));
if (!doc) return NULL;
memset(doc, 0, sizeof(yyjson_mut_doc));
doc->alc = *alc;
doc->str_pool.chunk_size = YYJSON_MUT_DOC_STR_POOL_INIT_SIZE;
doc->str_pool.chunk_size_max = YYJSON_MUT_DOC_STR_POOL_MAX_SIZE;
doc->val_pool.chunk_size = YYJSON_MUT_DOC_VAL_POOL_INIT_SIZE;
doc->val_pool.chunk_size_max = YYJSON_MUT_DOC_VAL_POOL_MAX_SIZE;
return doc;
}
yyjson_mut_doc *yyjson_doc_mut_copy(yyjson_doc *doc, const yyjson_alc *alc) {
yyjson_mut_doc *m_doc;
yyjson_mut_val *m_val;
if (!doc || !doc->root) return NULL;
m_doc = yyjson_mut_doc_new(alc);
if (!m_doc) return NULL;
m_val = yyjson_val_mut_copy(m_doc, doc->root);
if (!m_val) {
yyjson_mut_doc_free(m_doc);
return NULL;
}
yyjson_mut_doc_set_root(m_doc, m_val);
return m_doc;
}
yyjson_mut_doc *yyjson_mut_doc_mut_copy(yyjson_mut_doc *doc,
const yyjson_alc *alc) {
yyjson_mut_doc *m_doc;
yyjson_mut_val *m_val;
if (!doc) return NULL;
if (!doc->root) return yyjson_mut_doc_new(alc);
m_doc = yyjson_mut_doc_new(alc);
if (!m_doc) return NULL;
m_val = yyjson_mut_val_mut_copy(m_doc, doc->root);
if (!m_val) {
yyjson_mut_doc_free(m_doc);
return NULL;
}
yyjson_mut_doc_set_root(m_doc, m_val);
return m_doc;
}
yyjson_mut_val *yyjson_val_mut_copy(yyjson_mut_doc *m_doc,
yyjson_val *i_vals) {
/*
The immutable object or array stores all sub-values in a contiguous memory,
We copy them to another contiguous memory as mutable values,
then reconnect the mutable values with the original relationship.
*/
usize i_vals_len;
yyjson_mut_val *m_vals, *m_val;
yyjson_val *i_val, *i_end;
if (!m_doc || !i_vals) return NULL;
i_end = unsafe_yyjson_get_next(i_vals);
i_vals_len = (usize)(unsafe_yyjson_get_next(i_vals) - i_vals);
m_vals = unsafe_yyjson_mut_val(m_doc, i_vals_len);
if (!m_vals) return NULL;
i_val = i_vals;
m_val = m_vals;
for (; i_val < i_end; i_val++, m_val++) {
yyjson_type type = unsafe_yyjson_get_type(i_val);
m_val->tag = i_val->tag;
m_val->uni.u64 = i_val->uni.u64;
if (type == YYJSON_TYPE_STR || type == YYJSON_TYPE_RAW) {
const char *str = i_val->uni.str;
usize str_len = unsafe_yyjson_get_len(i_val);
m_val->uni.str = unsafe_yyjson_mut_strncpy(m_doc, str, str_len);
if (!m_val->uni.str) return NULL;
} else if (type == YYJSON_TYPE_ARR) {
usize len = unsafe_yyjson_get_len(i_val);
if (len > 0) {
yyjson_val *ii_val = i_val + 1, *ii_next;
yyjson_mut_val *mm_val = m_val + 1, *mm_ctn = m_val, *mm_next;
while (len-- > 1) {
ii_next = unsafe_yyjson_get_next(ii_val);
mm_next = mm_val + (ii_next - ii_val);
mm_val->next = mm_next;
ii_val = ii_next;
mm_val = mm_next;
}
mm_val->next = mm_ctn + 1;
mm_ctn->uni.ptr = mm_val;
}
} else if (type == YYJSON_TYPE_OBJ) {
usize len = unsafe_yyjson_get_len(i_val);
if (len > 0) {
yyjson_val *ii_key = i_val + 1, *ii_nextkey;
yyjson_mut_val *mm_key = m_val + 1, *mm_ctn = m_val;
yyjson_mut_val *mm_nextkey;
while (len-- > 1) {
ii_nextkey = unsafe_yyjson_get_next(ii_key + 1);
mm_nextkey = mm_key + (ii_nextkey - ii_key);
mm_key->next = mm_key + 1;
mm_key->next->next = mm_nextkey;
ii_key = ii_nextkey;
mm_key = mm_nextkey;
}
mm_key->next = mm_key + 1;
mm_key->next->next = mm_ctn + 1;
mm_ctn->uni.ptr = mm_key;
}
}
}
return m_vals;
}
static yyjson_mut_val *unsafe_yyjson_mut_val_mut_copy(yyjson_mut_doc *m_doc,
yyjson_mut_val *m_vals) {
/*
The mutable object or array stores all sub-values in a circular linked
list, so we can traverse them in the same loop. The traversal starts from
the last item, continues with the first item in a list, and ends with the
second to last item, which needs to be linked to the last item to close the
circle.
*/
yyjson_mut_val *m_val = unsafe_yyjson_mut_val(m_doc, 1);
if (unlikely(!m_val)) return NULL;
m_val->tag = m_vals->tag;
switch (unsafe_yyjson_get_type(m_vals)) {
case YYJSON_TYPE_OBJ:
case YYJSON_TYPE_ARR:
if (unsafe_yyjson_get_len(m_vals) > 0) {
yyjson_mut_val *last = (yyjson_mut_val *)m_vals->uni.ptr;
yyjson_mut_val *next = last->next, *prev;
prev = unsafe_yyjson_mut_val_mut_copy(m_doc, last);
if (!prev) return NULL;
m_val->uni.ptr = (void *)prev;
while (next != last) {
prev->next = unsafe_yyjson_mut_val_mut_copy(m_doc, next);
if (!prev->next) return NULL;
prev = prev->next;
next = next->next;
}
prev->next = (yyjson_mut_val *)m_val->uni.ptr;
}
break;
case YYJSON_TYPE_RAW:
case YYJSON_TYPE_STR: {
const char *str = m_vals->uni.str;
usize str_len = unsafe_yyjson_get_len(m_vals);
m_val->uni.str = unsafe_yyjson_mut_strncpy(m_doc, str, str_len);
if (!m_val->uni.str) return NULL;
break;
}
default:
m_val->uni = m_vals->uni;
break;
}
return m_val;
}
yyjson_mut_val *yyjson_mut_val_mut_copy(yyjson_mut_doc *doc,
yyjson_mut_val *val) {
if (doc && val) return unsafe_yyjson_mut_val_mut_copy(doc, val);
return NULL;
}
/* Count the number of values and the total length of the strings. */
static void yyjson_mut_stat(yyjson_mut_val *val,
usize *val_sum, usize *str_sum) {
yyjson_type type = unsafe_yyjson_get_type(val);
*val_sum += 1;
if (type == YYJSON_TYPE_ARR || type == YYJSON_TYPE_OBJ) {
yyjson_mut_val *child = (yyjson_mut_val *)val->uni.ptr;
usize len = unsafe_yyjson_get_len(val), i;
len <<= (u8)(type == YYJSON_TYPE_OBJ);
*val_sum += len;
for (i = 0; i < len; i++) {
yyjson_type stype = unsafe_yyjson_get_type(child);
if (stype == YYJSON_TYPE_STR || stype == YYJSON_TYPE_RAW) {
*str_sum += unsafe_yyjson_get_len(child) + 1;
} else if (stype == YYJSON_TYPE_ARR || stype == YYJSON_TYPE_OBJ) {
yyjson_mut_stat(child, val_sum, str_sum);
*val_sum -= 1;
}
child = child->next;
}
} else if (type == YYJSON_TYPE_STR || type == YYJSON_TYPE_RAW) {
*str_sum += unsafe_yyjson_get_len(val) + 1;
}
}
/* Copy mutable values to immutable value pool. */
static usize yyjson_imut_copy(yyjson_val **val_ptr, char **buf_ptr,
yyjson_mut_val *mval) {
yyjson_val *val = *val_ptr;
yyjson_type type = unsafe_yyjson_get_type(mval);
if (type == YYJSON_TYPE_ARR || type == YYJSON_TYPE_OBJ) {
yyjson_mut_val *child = (yyjson_mut_val *)mval->uni.ptr;
usize len = unsafe_yyjson_get_len(mval), i;
usize val_sum = 1;
if (type == YYJSON_TYPE_OBJ) {
if (len) child = child->next->next;
len <<= 1;
} else {
if (len) child = child->next;
}
*val_ptr = val + 1;
for (i = 0; i < len; i++) {
val_sum += yyjson_imut_copy(val_ptr, buf_ptr, child);
child = child->next;
}
val->tag = mval->tag;
val->uni.ofs = val_sum * sizeof(yyjson_val);
return val_sum;
} else if (type == YYJSON_TYPE_STR || type == YYJSON_TYPE_RAW) {
char *buf = *buf_ptr;
usize len = unsafe_yyjson_get_len(mval);
memcpy((void *)buf, (const void *)mval->uni.str, len);
buf[len] = '\0';
val->tag = mval->tag;
val->uni.str = buf;
*val_ptr = val + 1;
*buf_ptr = buf + len + 1;
return 1;
} else {
val->tag = mval->tag;
val->uni = mval->uni;
*val_ptr = val + 1;
return 1;
}
}
yyjson_doc *yyjson_mut_doc_imut_copy(yyjson_mut_doc *mdoc,
const yyjson_alc *alc) {
if (!mdoc) return NULL;
return yyjson_mut_val_imut_copy(mdoc->root, alc);
}
yyjson_doc *yyjson_mut_val_imut_copy(yyjson_mut_val *mval,
const yyjson_alc *alc) {
usize val_num = 0, str_sum = 0, hdr_size, buf_size;
yyjson_doc *doc = NULL;
yyjson_val *val_hdr = NULL;
/* This value should be NULL here. Setting a non-null value suppresses
warning from the clang analyzer. */
char *str_hdr = (char *)(void *)&str_sum;
if (!mval) return NULL;
if (!alc) alc = &YYJSON_DEFAULT_ALC;
/* traverse the input value to get pool size */
yyjson_mut_stat(mval, &val_num, &str_sum);
/* create doc and val pool */
hdr_size = size_align_up(sizeof(yyjson_doc), sizeof(yyjson_val));
buf_size = hdr_size + val_num * sizeof(yyjson_val);
doc = (yyjson_doc *)alc->malloc(alc->ctx, buf_size);
if (!doc) return NULL;
memset(doc, 0, sizeof(yyjson_doc));
val_hdr = (yyjson_val *)(void *)((char *)(void *)doc + hdr_size);
doc->root = val_hdr;
doc->alc = *alc;
/* create str pool */
if (str_sum > 0) {
str_hdr = (char *)alc->malloc(alc->ctx, str_sum);
doc->str_pool = str_hdr;
if (!str_hdr) {
alc->free(alc->ctx, (void *)doc);
return NULL;
}
}
/* copy vals and strs */
doc->val_read = yyjson_imut_copy(&val_hdr, &str_hdr, mval);
doc->dat_read = str_sum + 1;
return doc;
}
static_inline bool unsafe_yyjson_num_equals(void *lhs, void *rhs) {
yyjson_val_uni *luni = &((yyjson_val *)lhs)->uni;
yyjson_val_uni *runi = &((yyjson_val *)rhs)->uni;
yyjson_subtype lt = unsafe_yyjson_get_subtype(lhs);
yyjson_subtype rt = unsafe_yyjson_get_subtype(rhs);
if (lt == rt)
return luni->u64 == runi->u64;
if (lt == YYJSON_SUBTYPE_SINT && rt == YYJSON_SUBTYPE_UINT)
return luni->i64 >= 0 && luni->u64 == runi->u64;
if (lt == YYJSON_SUBTYPE_UINT && rt == YYJSON_SUBTYPE_SINT)
return runi->i64 >= 0 && luni->u64 == runi->u64;
return false;
}
static_inline bool unsafe_yyjson_str_equals(void *lhs, void *rhs) {
usize len = unsafe_yyjson_get_len(lhs);
if (len != unsafe_yyjson_get_len(rhs)) return false;
return !memcmp(unsafe_yyjson_get_str(lhs),
unsafe_yyjson_get_str(rhs), len);
}
bool unsafe_yyjson_equals(yyjson_val *lhs, yyjson_val *rhs) {
yyjson_type type = unsafe_yyjson_get_type(lhs);
if (type != unsafe_yyjson_get_type(rhs)) return false;
switch (type) {
case YYJSON_TYPE_OBJ: {
usize len = unsafe_yyjson_get_len(lhs);
if (len != unsafe_yyjson_get_len(rhs)) return false;
if (len > 0) {
yyjson_obj_iter iter;
yyjson_obj_iter_init(rhs, &iter);
lhs = unsafe_yyjson_get_first(lhs);
while (len-- > 0) {
rhs = yyjson_obj_iter_getn(&iter, lhs->uni.str,
unsafe_yyjson_get_len(lhs));
if (!rhs || !unsafe_yyjson_equals(lhs + 1, rhs))
return false;
lhs = unsafe_yyjson_get_next(lhs + 1);
}
}
/* yyjson allows duplicate keys, so the check may be inaccurate */
return true;
}
case YYJSON_TYPE_ARR: {
usize len = unsafe_yyjson_get_len(lhs);
if (len != unsafe_yyjson_get_len(rhs)) return false;
if (len > 0) {
lhs = unsafe_yyjson_get_first(lhs);
rhs = unsafe_yyjson_get_first(rhs);
while (len-- > 0) {
if (!unsafe_yyjson_equals(lhs, rhs)) return false;
lhs = unsafe_yyjson_get_next(lhs);
rhs = unsafe_yyjson_get_next(rhs);
}
}
return true;
}
case YYJSON_TYPE_NUM:
return unsafe_yyjson_num_equals(lhs, rhs);
case YYJSON_TYPE_RAW:
case YYJSON_TYPE_STR:
return unsafe_yyjson_str_equals(lhs, rhs);
case YYJSON_TYPE_NULL:
case YYJSON_TYPE_BOOL:
return lhs->tag == rhs->tag;
default:
return false;
}
}
bool unsafe_yyjson_mut_equals(yyjson_mut_val *lhs, yyjson_mut_val *rhs) {
yyjson_type type = unsafe_yyjson_get_type(lhs);
if (type != unsafe_yyjson_get_type(rhs)) return false;
switch (type) {
case YYJSON_TYPE_OBJ: {
usize len = unsafe_yyjson_get_len(lhs);
if (len != unsafe_yyjson_get_len(rhs)) return false;
if (len > 0) {
yyjson_mut_obj_iter iter;
yyjson_mut_obj_iter_init(rhs, &iter);
lhs = (yyjson_mut_val *)lhs->uni.ptr;
while (len-- > 0) {
rhs = yyjson_mut_obj_iter_getn(&iter, lhs->uni.str,
unsafe_yyjson_get_len(lhs));
if (!rhs || !unsafe_yyjson_mut_equals(lhs->next, rhs))
return false;
lhs = lhs->next->next;
}
}
/* yyjson allows duplicate keys, so the check may be inaccurate */
return true;
}
case YYJSON_TYPE_ARR: {
usize len = unsafe_yyjson_get_len(lhs);
if (len != unsafe_yyjson_get_len(rhs)) return false;
if (len > 0) {
lhs = (yyjson_mut_val *)lhs->uni.ptr;
rhs = (yyjson_mut_val *)rhs->uni.ptr;
while (len-- > 0) {
if (!unsafe_yyjson_mut_equals(lhs, rhs)) return false;
lhs = lhs->next;
rhs = rhs->next;
}
}
return true;
}
case YYJSON_TYPE_NUM:
return unsafe_yyjson_num_equals(lhs, rhs);
case YYJSON_TYPE_RAW:
case YYJSON_TYPE_STR:
return unsafe_yyjson_str_equals(lhs, rhs);
case YYJSON_TYPE_NULL:
case YYJSON_TYPE_BOOL:
return lhs->tag == rhs->tag;
default:
return false;
}
}
#if !YYJSON_DISABLE_UTILS
/*==============================================================================
* JSON Pointer API (RFC 6901)
*============================================================================*/
/**
Get a token from JSON pointer string.
@param ptr [in,out]
in: string that points to current token prefix `/`
out: string that points to next token prefix `/`, or string end
@param end [in] end of the entire JSON Pointer string
@param len [out] unescaped token length
@param esc [out] number of escaped characters in this token
@return head of the token, or NULL if syntax error
*/
static_inline const char *ptr_next_token(const char **ptr, const char *end,
usize *len, usize *esc) {
const char *hdr = *ptr + 1;
const char *cur = hdr;
/* skip unescaped characters */
while (cur < end && *cur != '/' && *cur != '~') cur++;
if (likely(cur == end || *cur != '~')) {
/* no escaped characters, return */
*ptr = cur;
*len = (usize)(cur - hdr);
*esc = 0;
return hdr;
} else {
/* handle escaped characters */
usize esc_num = 0;
while (cur < end && *cur != '/') {
if (*cur++ == '~') {
if (cur == end || (*cur != '0' && *cur != '1')) {
*ptr = cur - 1;
return NULL;
}
esc_num++;
}
}
*ptr = cur;
*len = (usize)(cur - hdr) - esc_num;
*esc = esc_num;
return hdr;
}
}
/**
Convert token string to index.
@param cur [in] token head
@param len [in] token length
@param idx [out] the index number, or USIZE_MAX if token is '-'
@return true if token is a valid array index
*/
static_inline bool ptr_token_to_idx(const char *cur, usize len, usize *idx) {
const char *end = cur + len;
usize num = 0, add;
if (unlikely(len == 0 || len > USIZE_SAFE_DIG)) return false;
if (*cur == '0') {
if (unlikely(len > 1)) return false;
*idx = 0;
return true;
}
if (*cur == '-') {
if (unlikely(len > 1)) return false;
*idx = USIZE_MAX;
return true;
}
for (; cur < end && (add = (usize)((u8)*cur - (u8)'0')) <= 9; cur++) {
num = num * 10 + add;
}
if (unlikely(num == 0 || cur < end)) return false;
*idx = num;
return true;
}
/**
Compare JSON key with token.
@param key a string key (yyjson_val or yyjson_mut_val)
@param token a JSON pointer token
@param len unescaped token length
@param esc number of escaped characters in this token
@return true if `str` is equals to `token`
*/
static_inline bool ptr_token_eq(void *key,
const char *token, usize len, usize esc) {
yyjson_val *val = (yyjson_val *)key;
if (unsafe_yyjson_get_len(val) != len) return false;
if (likely(!esc)) {
return memcmp(val->uni.str, token, len) == 0;
} else {
const char *str = val->uni.str;
for (; len-- > 0; token++, str++) {
if (*token == '~') {
if (*str != (*++token == '0' ? '~' : '/')) return false;
} else {
if (*str != *token) return false;
}
}
return true;
}
}
/**
Get a value from array by token.
@param arr an array, should not be NULL or non-array type
@param token a JSON pointer token
@param len unescaped token length
@param esc number of escaped characters in this token
@return value at index, or NULL if token is not index or index is out of range
*/
static_inline yyjson_val *ptr_arr_get(yyjson_val *arr, const char *token,
usize len, usize esc) {
yyjson_val *val = unsafe_yyjson_get_first(arr);
usize num = unsafe_yyjson_get_len(arr), idx = 0;
if (unlikely(num == 0)) return NULL;
if (unlikely(!ptr_token_to_idx(token, len, &idx))) return NULL;
if (unlikely(idx >= num)) return NULL;
if (unsafe_yyjson_arr_is_flat(arr)) {
return val + idx;
} else {
while (idx-- > 0) val = unsafe_yyjson_get_next(val);
return val;
}
}
/**
Get a value from object by token.
@param obj [in] an object, should not be NULL or non-object type
@param token [in] a JSON pointer token
@param len [in] unescaped token length
@param esc [in] number of escaped characters in this token
@return value associated with the token, or NULL if no value
*/
static_inline yyjson_val *ptr_obj_get(yyjson_val *obj, const char *token,
usize len, usize esc) {
yyjson_val *key = unsafe_yyjson_get_first(obj);
usize num = unsafe_yyjson_get_len(obj);
if (unlikely(num == 0)) return NULL;
for (; num > 0; num--, key = unsafe_yyjson_get_next(key + 1)) {
if (ptr_token_eq(key, token, len, esc)) return key + 1;
}
return NULL;
}
/**
Get a value from array by token.
@param arr [in] an array, should not be NULL or non-array type
@param token [in] a JSON pointer token
@param len [in] unescaped token length
@param esc [in] number of escaped characters in this token
@param pre [out] previous (sibling) value of the returned value
@param last [out] whether index is last
@return value at index, or NULL if token is not index or index is out of range
*/
static_inline yyjson_mut_val *ptr_mut_arr_get(yyjson_mut_val *arr,
const char *token,
usize len, usize esc,
yyjson_mut_val **pre,
bool *last) {
yyjson_mut_val *val = (yyjson_mut_val *)arr->uni.ptr; /* last (tail) */
usize num = unsafe_yyjson_get_len(arr), idx;
if (last) *last = false;
if (false) *pre = NULL;
if (unlikely(num == 0)) {
if (last && len == 1 && (*token == '0' || *token == '-')) *last = true;
return NULL;
}
if (unlikely(!ptr_token_to_idx(token, len, &idx))) return NULL;
if (last) *last = (idx == num || idx == USIZE_MAX);
if (unlikely(idx >= num)) return NULL;
while (idx-- > 0) val = val->next;
*pre = val;
return val->next;
}
/**
Get a value from object by token.
@param obj [in] an object, should not be NULL or non-object type
@param token [in] a JSON pointer token
@param len [in] unescaped token length
@param esc [in] number of escaped characters in this token
@param pre [out] previous (sibling) key of the returned value's key
@return value associated with the token, or NULL if no value
*/
static_inline yyjson_mut_val *ptr_mut_obj_get(yyjson_mut_val *obj,
const char *token,
usize len, usize esc,
yyjson_mut_val **pre) {
yyjson_mut_val *pre_key = (yyjson_mut_val *)obj->uni.ptr, *key;
usize num = unsafe_yyjson_get_len(obj);
if (false) *pre = NULL;
if (unlikely(num == 0)) return NULL;
for (; num > 0; num--, pre_key = key) {
key = pre_key->next->next;
if (ptr_token_eq(key, token, len, esc)) {
*pre = pre_key;
return key->next;
}
}
return NULL;
}
/**
Create a string value with JSON pointer token.
@param token [in] a JSON pointer token
@param len [in] unescaped token length
@param esc [in] number of escaped characters in this token
@param doc [in] used for memory allocation when creating value
@return new string value, or NULL if memory allocation failed
*/
static_inline yyjson_mut_val *ptr_new_key(const char *token,
usize len, usize esc,
yyjson_mut_doc *doc) {
const char *src = token;
if (likely(!esc)) {
return yyjson_mut_strncpy(doc, src, len);
} else {
const char *end = src + len + esc;
char *dst = unsafe_yyjson_mut_str_alc(doc, len + esc);
char *str = dst;
if (unlikely(!dst)) return NULL;
for (; src < end; src++, dst++) {
if (*src != '~') *dst = *src;
else *dst = (*++src == '0' ? '~' : '/');
}
*dst = '\0';
return yyjson_mut_strn(doc, str, len);
}
}
/* macros for yyjson_ptr */
#define return_err(_ret, _code, _pos, _msg) do { \
if (err) { \
err->code = YYJSON_PTR_ERR_##_code; \
err->msg = _msg; \
err->pos = (usize)(_pos); \
} \
return _ret; \
} while (false)
#define return_err_resolve(_ret, _pos) \
return_err(_ret, RESOLVE, _pos, "JSON pointer cannot be resolved")
#define return_err_syntax(_ret, _pos) \
return_err(_ret, SYNTAX, _pos, "invalid escaped character")
#define return_err_alloc(_ret) \
return_err(_ret, MEMORY_ALLOCATION, 0, "failed to create value")
yyjson_val *unsafe_yyjson_ptr_getx(yyjson_val *val,
const char *ptr, size_t ptr_len,
yyjson_ptr_err *err) {
const char *hdr = ptr, *end = ptr + ptr_len, *token;
usize len, esc;
yyjson_type type;
while (true) {
token = ptr_next_token(&ptr, end, &len, &esc);
if (unlikely(!token)) return_err_syntax(NULL, ptr - hdr);
type = unsafe_yyjson_get_type(val);
if (type == YYJSON_TYPE_OBJ) {
val = ptr_obj_get(val, token, len, esc);
} else if (type == YYJSON_TYPE_ARR) {
val = ptr_arr_get(val, token, len, esc);
} else {
val = NULL;
}
if (!val) return_err_resolve(NULL, token - hdr);
if (ptr == end) return val;
}
}
yyjson_mut_val *unsafe_yyjson_mut_ptr_getx(yyjson_mut_val *val,
const char *ptr,
size_t ptr_len,
yyjson_ptr_ctx *ctx,
yyjson_ptr_err *err) {
const char *hdr = ptr, *end = ptr + ptr_len, *token;
usize len, esc;
yyjson_mut_val *ctn, *pre = NULL;
yyjson_type type;
bool idx_is_last = false;
while (true) {
token = ptr_next_token(&ptr, end, &len, &esc);
if (unlikely(!token)) return_err_syntax(NULL, ptr - hdr);
ctn = val;
type = unsafe_yyjson_get_type(val);
if (type == YYJSON_TYPE_OBJ) {
val = ptr_mut_obj_get(val, token, len, esc, &pre);
} else if (type == YYJSON_TYPE_ARR) {
val = ptr_mut_arr_get(val, token, len, esc, &pre, &idx_is_last);
} else {
val = NULL;
}
if (ctx && (ptr == end)) {
if (type == YYJSON_TYPE_OBJ ||
(type == YYJSON_TYPE_ARR && (val || idx_is_last))) {
ctx->ctn = ctn;
ctx->pre = pre;
}
}
if (!val) return_err_resolve(NULL, token - hdr);
if (ptr == end) return val;
}
}
bool unsafe_yyjson_mut_ptr_putx(yyjson_mut_val *val,
const char *ptr, size_t ptr_len,
yyjson_mut_val *new_val,
yyjson_mut_doc *doc,
bool create_parent, bool insert_new,
yyjson_ptr_ctx *ctx,
yyjson_ptr_err *err) {
const char *hdr = ptr, *end = ptr + ptr_len, *token;
usize token_len, esc, ctn_len;
yyjson_mut_val *ctn, *key, *pre = NULL;
yyjson_mut_val *sep_ctn = NULL, *sep_key = NULL, *sep_val = NULL;
yyjson_type ctn_type;
bool idx_is_last = false;
/* skip exist parent nodes */
while (true) {
token = ptr_next_token(&ptr, end, &token_len, &esc);
if (unlikely(!token)) return_err_syntax(false, ptr - hdr);
ctn = val;
ctn_type = unsafe_yyjson_get_type(ctn);
if (ctn_type == YYJSON_TYPE_OBJ) {
val = ptr_mut_obj_get(ctn, token, token_len, esc, &pre);
} else if (ctn_type == YYJSON_TYPE_ARR) {
val = ptr_mut_arr_get(ctn, token, token_len, esc, &pre,
&idx_is_last);
} else return_err_resolve(false, token - hdr);
if (!val) break;
if (ptr == end) break; /* is last token */
}
/* create parent nodes if not exist */
if (unlikely(ptr != end)) { /* not last token */
if (!create_parent) return_err_resolve(false, token - hdr);
/* add value at last index if container is array */
if (ctn_type == YYJSON_TYPE_ARR) {
if (!idx_is_last || !insert_new) {
return_err_resolve(false, token - hdr);
}
val = yyjson_mut_obj(doc);
if (!val) return_err_alloc(false);
/* delay attaching until all operations are completed */
sep_ctn = ctn;
sep_key = NULL;
sep_val = val;
/* move to next token */
ctn = val;
val = NULL;
ctn_type = YYJSON_TYPE_OBJ;
token = ptr_next_token(&ptr, end, &token_len, &esc);
if (unlikely(!token)) return_err_resolve(false, token - hdr);
}
/* container is object, create parent nodes */
while (ptr != end) { /* not last token */
key = ptr_new_key(token, token_len, esc, doc);
if (!key) return_err_alloc(false);
val = yyjson_mut_obj(doc);
if (!val) return_err_alloc(false);
/* delay attaching until all operations are completed */
if (!sep_ctn) {
sep_ctn = ctn;
sep_key = key;
sep_val = val;
} else {
yyjson_mut_obj_add(ctn, key, val);
}
/* move to next token */
ctn = val;
val = NULL;
token = ptr_next_token(&ptr, end, &token_len, &esc);
if (unlikely(!token)) return_err_syntax(false, ptr - hdr);
}
}
/* JSON pointer is resolved, insert or replace target value */
ctn_len = unsafe_yyjson_get_len(ctn);
if (ctn_type == YYJSON_TYPE_OBJ) {
if (ctx) ctx->ctn = ctn;
if (!val || insert_new) {
/* insert new key-value pair */
key = ptr_new_key(token, token_len, esc, doc);
if (unlikely(!key)) return_err_alloc(false);
if (ctx) ctx->pre = ctn_len ? (yyjson_mut_val *)ctn->uni.ptr : key;
unsafe_yyjson_mut_obj_add(ctn, key, new_val, ctn_len);
} else {
/* replace exist value */
key = pre->next->next;
if (ctx) ctx->pre = pre;
if (ctx) ctx->old = val;
yyjson_mut_obj_put(ctn, key, new_val);
}
} else {
/* array */
if (ctx && (val || idx_is_last)) ctx->ctn = ctn;
if (insert_new) {
/* append new value */
if (val) {
pre->next = new_val;
new_val->next = val;
if (ctx) ctx->pre = pre;
unsafe_yyjson_set_len(ctn, ctn_len + 1);
} else if (idx_is_last) {
if (ctx) ctx->pre = ctn_len ?
(yyjson_mut_val *)ctn->uni.ptr : new_val;
yyjson_mut_arr_append(ctn, new_val);
} else {
return_err_resolve(false, token - hdr);
}
} else {
/* replace exist value */
if (!val) return_err_resolve(false, token - hdr);
if (ctn_len > 1) {
new_val->next = val->next;
pre->next = new_val;
if (ctn->uni.ptr == val) ctn->uni.ptr = new_val;
} else {
new_val->next = new_val;
ctn->uni.ptr = new_val;
pre = new_val;
}
if (ctx) ctx->pre = pre;
if (ctx) ctx->old = val;
}
}
/* all operations are completed, attach the new components to the target */
if (unlikely(sep_ctn)) {
if (sep_key) yyjson_mut_obj_add(sep_ctn, sep_key, sep_val);
else yyjson_mut_arr_append(sep_ctn, sep_val);
}
return true;
}
yyjson_mut_val *unsafe_yyjson_mut_ptr_replacex(
yyjson_mut_val *val, const char *ptr, size_t len, yyjson_mut_val *new_val,
yyjson_ptr_ctx *ctx, yyjson_ptr_err *err) {
yyjson_mut_val *cur_val;
yyjson_ptr_ctx cur_ctx;
memset(&cur_ctx, 0, sizeof(cur_ctx));
if (!ctx) ctx = &cur_ctx;
cur_val = unsafe_yyjson_mut_ptr_getx(val, ptr, len, ctx, err);
if (!cur_val) return NULL;
if (yyjson_mut_is_obj(ctx->ctn)) {
yyjson_mut_val *key = ctx->pre->next->next;
yyjson_mut_obj_put(ctx->ctn, key, new_val);
} else {
yyjson_ptr_ctx_replace(ctx, new_val);
}
ctx->old = cur_val;
return cur_val;
}
yyjson_mut_val *unsafe_yyjson_mut_ptr_removex(yyjson_mut_val *val,
const char *ptr,
size_t len,
yyjson_ptr_ctx *ctx,
yyjson_ptr_err *err) {
yyjson_mut_val *cur_val;
yyjson_ptr_ctx cur_ctx;
memset(&cur_ctx, 0, sizeof(cur_ctx));
if (!ctx) ctx = &cur_ctx;
cur_val = unsafe_yyjson_mut_ptr_getx(val, ptr, len, ctx, err);
if (cur_val) {
if (yyjson_mut_is_obj(ctx->ctn)) {
yyjson_mut_val *key = ctx->pre->next->next;
yyjson_mut_obj_put(ctx->ctn, key, NULL);
} else {
yyjson_ptr_ctx_remove(ctx);
}
ctx->pre = NULL;
ctx->old = cur_val;
}
return cur_val;
}
/* macros for yyjson_ptr */
#undef return_err
#undef return_err_resolve
#undef return_err_syntax
#undef return_err_alloc
/*==============================================================================
* JSON Patch API (RFC 6902)
*============================================================================*/
/* JSON Patch operation */
typedef enum patch_op {
PATCH_OP_ADD, /* path, value */
PATCH_OP_REMOVE, /* path */
PATCH_OP_REPLACE, /* path, value */
PATCH_OP_MOVE, /* from, path */
PATCH_OP_COPY, /* from, path */
PATCH_OP_TEST, /* path, value */
PATCH_OP_NONE /* invalid */
} patch_op;
static patch_op patch_op_get(yyjson_val *op) {
const char *str = op->uni.str;
switch (unsafe_yyjson_get_len(op)) {
case 3:
if (!memcmp(str, "add", 3)) return PATCH_OP_ADD;
return PATCH_OP_NONE;
case 4:
if (!memcmp(str, "move", 4)) return PATCH_OP_MOVE;
if (!memcmp(str, "copy", 4)) return PATCH_OP_COPY;
if (!memcmp(str, "test", 4)) return PATCH_OP_TEST;
return PATCH_OP_NONE;
case 6:
if (!memcmp(str, "remove", 6)) return PATCH_OP_REMOVE;
return PATCH_OP_NONE;
case 7:
if (!memcmp(str, "replace", 7)) return PATCH_OP_REPLACE;
return PATCH_OP_NONE;
default:
return PATCH_OP_NONE;
}
}
/* macros for yyjson_patch */
#define return_err(_code, _msg) do { \
if (err->ptr.code == YYJSON_PTR_ERR_MEMORY_ALLOCATION) { \
err->code = YYJSON_PATCH_ERROR_MEMORY_ALLOCATION; \
err->msg = _msg; \
memset(&err->ptr, 0, sizeof(yyjson_ptr_err)); \
} else { \
err->code = YYJSON_PATCH_ERROR_##_code; \
err->msg = _msg; \
err->idx = iter.idx ? iter.idx - 1 : 0; \
} \
return NULL; \
} while (false)
#define return_err_copy() \
return_err(MEMORY_ALLOCATION, "failed to copy value")
#define return_err_key(_key) \
return_err(MISSING_KEY, "missing key " _key)
#define return_err_val(_key) \
return_err(INVALID_MEMBER, "invalid member " _key)
#define ptr_get(_ptr) yyjson_mut_ptr_getx( \
root, _ptr->uni.str, _ptr##_len, NULL, &err->ptr)
#define ptr_add(_ptr, _val) yyjson_mut_ptr_addx( \
root, _ptr->uni.str, _ptr##_len, _val, doc, false, NULL, &err->ptr)
#define ptr_remove(_ptr) yyjson_mut_ptr_removex( \
root, _ptr->uni.str, _ptr##_len, NULL, &err->ptr)
#define ptr_replace(_ptr, _val)yyjson_mut_ptr_replacex( \
root, _ptr->uni.str, _ptr##_len, _val, NULL, &err->ptr)
yyjson_mut_val *yyjson_patch(yyjson_mut_doc *doc,
yyjson_val *orig,
yyjson_val *patch,
yyjson_patch_err *err) {
yyjson_mut_val *root;
yyjson_val *obj;
yyjson_arr_iter iter;
yyjson_patch_err err_tmp;
if (!err) err = &err_tmp;
memset(err, 0, sizeof(*err));
memset(&iter, 0, sizeof(iter));
if (unlikely(!doc || !orig || !patch)) {
return_err(INVALID_PARAMETER, "input parameter is NULL");
}
if (unlikely(!yyjson_is_arr(patch))) {
return_err(INVALID_PARAMETER, "input patch is not array");
}
root = yyjson_val_mut_copy(doc, orig);
if (unlikely(!root)) return_err_copy();
/* iterate through the patch array */
yyjson_arr_iter_init(patch, &iter);
while ((obj = yyjson_arr_iter_next(&iter))) {
patch_op op_enum;
yyjson_val *op, *path, *from = NULL, *value;
yyjson_mut_val *val = NULL, *test;
usize path_len, from_len = 0;
if (unlikely(!unsafe_yyjson_is_obj(obj))) {
return_err(INVALID_OPERATION, "JSON patch operation is not object");
}
/* get required member: op */
op = yyjson_obj_get(obj, "op");
if (unlikely(!op)) return_err_key("`op`");
if (unlikely(!yyjson_is_str(op))) return_err_val("`op`");
op_enum = patch_op_get(op);
/* get required member: path */
path = yyjson_obj_get(obj, "path");
if (unlikely(!path)) return_err_key("`path`");
if (unlikely(!yyjson_is_str(path))) return_err_val("`path`");
path_len = unsafe_yyjson_get_len(path);
/* get required member: value, from */
switch ((int)op_enum) {
case PATCH_OP_ADD: case PATCH_OP_REPLACE: case PATCH_OP_TEST:
value = yyjson_obj_get(obj, "value");
if (unlikely(!value)) return_err_key("`value`");
val = yyjson_val_mut_copy(doc, value);
if (unlikely(!val)) return_err_copy();
break;
case PATCH_OP_MOVE: case PATCH_OP_COPY:
from = yyjson_obj_get(obj, "from");
if (unlikely(!from)) return_err_key("`from`");
if (unlikely(!yyjson_is_str(from))) return_err_val("`from`");
from_len = unsafe_yyjson_get_len(from);
break;
default:
break;
}
/* perform an operation */
switch ((int)op_enum) {
case PATCH_OP_ADD: /* add(path, val) */
if (unlikely(path_len == 0)) { root = val; break; }
if (unlikely(!ptr_add(path, val))) {
return_err(POINTER, "failed to add `path`");
}
break;
case PATCH_OP_REMOVE: /* remove(path) */
if (unlikely(!ptr_remove(path))) {
return_err(POINTER, "failed to remove `path`");
}
break;
case PATCH_OP_REPLACE: /* replace(path, val) */
if (unlikely(path_len == 0)) { root = val; break; }
if (unlikely(!ptr_replace(path, val))) {
return_err(POINTER, "failed to replace `path`");
}
break;
case PATCH_OP_MOVE: /* val = remove(from), add(path, val) */
if (unlikely(from_len == 0 && path_len == 0)) break;
val = ptr_remove(from);
if (unlikely(!val)) {
return_err(POINTER, "failed to remove `from`");
}
if (unlikely(path_len == 0)) { root = val; break; }
if (unlikely(!ptr_add(path, val))) {
return_err(POINTER, "failed to add `path`");
}
break;
case PATCH_OP_COPY: /* val = get(from).copy, add(path, val) */
val = ptr_get(from);
if (unlikely(!val)) {
return_err(POINTER, "failed to get `from`");
}
if (unlikely(path_len == 0)) { root = val; break; }
val = yyjson_mut_val_mut_copy(doc, val);
if (unlikely(!val)) return_err_copy();
if (unlikely(!ptr_add(path, val))) {
return_err(POINTER, "failed to add `path`");
}
break;
case PATCH_OP_TEST: /* test = get(path), test.eq(val) */
test = ptr_get(path);
if (unlikely(!test)) {
return_err(POINTER, "failed to get `path`");
}
if (unlikely(!yyjson_mut_equals(val, test))) {
return_err(EQUAL, "failed to test equal");
}
break;
default:
return_err(INVALID_MEMBER, "unsupported `op`");
}
}
return root;
}
yyjson_mut_val *yyjson_mut_patch(yyjson_mut_doc *doc,
yyjson_mut_val *orig,
yyjson_mut_val *patch,
yyjson_patch_err *err) {
yyjson_mut_val *root, *obj;
yyjson_mut_arr_iter iter;
yyjson_patch_err err_tmp;
if (!err) err = &err_tmp;
memset(err, 0, sizeof(*err));
memset(&iter, 0, sizeof(iter));
if (unlikely(!doc || !orig || !patch)) {
return_err(INVALID_PARAMETER, "input parameter is NULL");
}
if (unlikely(!yyjson_mut_is_arr(patch))) {
return_err(INVALID_PARAMETER, "input patch is not array");
}
root = yyjson_mut_val_mut_copy(doc, orig);
if (unlikely(!root)) return_err_copy();
/* iterate through the patch array */
yyjson_mut_arr_iter_init(patch, &iter);
while ((obj = yyjson_mut_arr_iter_next(&iter))) {
patch_op op_enum;
yyjson_mut_val *op, *path, *from = NULL, *value;
yyjson_mut_val *val = NULL, *test;
usize path_len, from_len = 0;
if (!unsafe_yyjson_is_obj(obj)) {
return_err(INVALID_OPERATION, "JSON patch operation is not object");
}
/* get required member: op */
op = yyjson_mut_obj_get(obj, "op");
if (unlikely(!op)) return_err_key("`op`");
if (unlikely(!yyjson_mut_is_str(op))) return_err_val("`op`");
op_enum = patch_op_get((yyjson_val *)(void *)op);
/* get required member: path */
path = yyjson_mut_obj_get(obj, "path");
if (unlikely(!path)) return_err_key("`path`");
if (unlikely(!yyjson_mut_is_str(path))) return_err_val("`path`");
path_len = unsafe_yyjson_get_len(path);
/* get required member: value, from */
switch ((int)op_enum) {
case PATCH_OP_ADD: case PATCH_OP_REPLACE: case PATCH_OP_TEST:
value = yyjson_mut_obj_get(obj, "value");
if (unlikely(!value)) return_err_key("`value`");
val = yyjson_mut_val_mut_copy(doc, value);
if (unlikely(!val)) return_err_copy();
break;
case PATCH_OP_MOVE: case PATCH_OP_COPY:
from = yyjson_mut_obj_get(obj, "from");
if (unlikely(!from)) return_err_key("`from`");
if (unlikely(!yyjson_mut_is_str(from))) {
return_err_val("`from`");
}
from_len = unsafe_yyjson_get_len(from);
break;
default:
break;
}
/* perform an operation */
switch ((int)op_enum) {
case PATCH_OP_ADD: /* add(path, val) */
if (unlikely(path_len == 0)) { root = val; break; }
if (unlikely(!ptr_add(path, val))) {
return_err(POINTER, "failed to add `path`");
}
break;
case PATCH_OP_REMOVE: /* remove(path) */
if (unlikely(!ptr_remove(path))) {
return_err(POINTER, "failed to remove `path`");
}
break;
case PATCH_OP_REPLACE: /* replace(path, val) */
if (unlikely(path_len == 0)) { root = val; break; }
if (unlikely(!ptr_replace(path, val))) {
return_err(POINTER, "failed to replace `path`");
}
break;
case PATCH_OP_MOVE: /* val = remove(from), add(path, val) */
if (unlikely(from_len == 0 && path_len == 0)) break;
val = ptr_remove(from);
if (unlikely(!val)) {
return_err(POINTER, "failed to remove `from`");
}
if (unlikely(path_len == 0)) { root = val; break; }
if (unlikely(!ptr_add(path, val))) {
return_err(POINTER, "failed to add `path`");
}
break;
case PATCH_OP_COPY: /* val = get(from).copy, add(path, val) */
val = ptr_get(from);
if (unlikely(!val)) {
return_err(POINTER, "failed to get `from`");
}
if (unlikely(path_len == 0)) { root = val; break; }
val = yyjson_mut_val_mut_copy(doc, val);
if (unlikely(!val)) return_err_copy();
if (unlikely(!ptr_add(path, val))) {
return_err(POINTER, "failed to add `path`");
}
break;
case PATCH_OP_TEST: /* test = get(path), test.eq(val) */
test = ptr_get(path);
if (unlikely(!test)) {
return_err(POINTER, "failed to get `path`");
}
if (unlikely(!yyjson_mut_equals(val, test))) {
return_err(EQUAL, "failed to test equal");
}
break;
default:
return_err(INVALID_MEMBER, "unsupported `op`");
}
}
return root;
}
/* macros for yyjson_patch */
#undef return_err
#undef return_err_copy
#undef return_err_key
#undef return_err_val
#undef ptr_get
#undef ptr_add
#undef ptr_remove
#undef ptr_replace
/*==============================================================================
* JSON Merge-Patch API (RFC 7386)
*============================================================================*/
yyjson_mut_val *yyjson_merge_patch(yyjson_mut_doc *doc,
yyjson_val *orig,
yyjson_val *patch) {
usize idx, max;
yyjson_val *key, *orig_val, *patch_val, local_orig;
yyjson_mut_val *builder, *mut_key, *mut_val, *merged_val;
if (unlikely(!yyjson_is_obj(patch))) {
return yyjson_val_mut_copy(doc, patch);
}
builder = yyjson_mut_obj(doc);
if (unlikely(!builder)) return NULL;
if (!yyjson_is_obj(orig)) {
orig = &local_orig;
orig->tag = builder->tag;
orig->uni = builder->uni;
}
/* If orig is contributing, copy any items not modified by the patch */
if (orig != &local_orig) {
yyjson_obj_foreach(orig, idx, max, key, orig_val) {
patch_val = yyjson_obj_getn(patch,
unsafe_yyjson_get_str(key),
unsafe_yyjson_get_len(key));
if (!patch_val) {
mut_key = yyjson_val_mut_copy(doc, key);
mut_val = yyjson_val_mut_copy(doc, orig_val);
if (!yyjson_mut_obj_add(builder, mut_key, mut_val)) return NULL;
}
}
}
/* Merge items modified by the patch. */
yyjson_obj_foreach(patch, idx, max, key, patch_val) {
/* null indicates the field is removed. */
if (unsafe_yyjson_is_null(patch_val)) {
continue;
}
mut_key = yyjson_val_mut_copy(doc, key);
orig_val = yyjson_obj_getn(orig,
unsafe_yyjson_get_str(key),
unsafe_yyjson_get_len(key));
merged_val = yyjson_merge_patch(doc, orig_val, patch_val);
if (!yyjson_mut_obj_add(builder, mut_key, merged_val)) return NULL;
}
return builder;
}
yyjson_mut_val *yyjson_mut_merge_patch(yyjson_mut_doc *doc,
yyjson_mut_val *orig,
yyjson_mut_val *patch) {
usize idx, max;
yyjson_mut_val *key, *orig_val, *patch_val, local_orig;
yyjson_mut_val *builder, *mut_key, *mut_val, *merged_val;
if (unlikely(!yyjson_mut_is_obj(patch))) {
return yyjson_mut_val_mut_copy(doc, patch);
}
builder = yyjson_mut_obj(doc);
if (unlikely(!builder)) return NULL;
if (!yyjson_mut_is_obj(orig)) {
orig = &local_orig;
orig->tag = builder->tag;
orig->uni = builder->uni;
}
/* If orig is contributing, copy any items not modified by the patch */
if (orig != &local_orig) {
yyjson_mut_obj_foreach(orig, idx, max, key, orig_val) {
patch_val = yyjson_mut_obj_getn(patch,
unsafe_yyjson_get_str(key),
unsafe_yyjson_get_len(key));
if (!patch_val) {
mut_key = yyjson_mut_val_mut_copy(doc, key);
mut_val = yyjson_mut_val_mut_copy(doc, orig_val);
if (!yyjson_mut_obj_add(builder, mut_key, mut_val)) return NULL;
}
}
}
/* Merge items modified by the patch. */
yyjson_mut_obj_foreach(patch, idx, max, key, patch_val) {
/* null indicates the field is removed. */
if (unsafe_yyjson_is_null(patch_val)) {
continue;
}
mut_key = yyjson_mut_val_mut_copy(doc, key);
orig_val = yyjson_mut_obj_getn(orig,
unsafe_yyjson_get_str(key),
unsafe_yyjson_get_len(key));
merged_val = yyjson_mut_merge_patch(doc, orig_val, patch_val);
if (!yyjson_mut_obj_add(builder, mut_key, merged_val)) return NULL;
}
return builder;
}
#endif /* YYJSON_DISABLE_UTILS */
/*==============================================================================
* Power10 Lookup Table
* These data are used by the floating-point number reader and writer.
*============================================================================*/
#if (!YYJSON_DISABLE_READER || !YYJSON_DISABLE_WRITER) && \
(!YYJSON_DISABLE_FAST_FP_CONV)
/** Minimum decimal exponent in pow10_sig_table. */
#define POW10_SIG_TABLE_MIN_EXP -343
/** Maximum decimal exponent in pow10_sig_table. */
#define POW10_SIG_TABLE_MAX_EXP 324
/** Minimum exact decimal exponent in pow10_sig_table */
#define POW10_SIG_TABLE_MIN_EXACT_EXP 0
/** Maximum exact decimal exponent in pow10_sig_table */
#define POW10_SIG_TABLE_MAX_EXACT_EXP 55
/** Normalized significant 128 bits of pow10, no rounded up (size: 10.4KB).
This lookup table is used by both the double number reader and writer.
(generate with misc/make_tables.c) */
static const u64 pow10_sig_table[] = {
U64(0xBF29DCAB, 0xA82FDEAE), U64(0x7432EE87, 0x3880FC33), /* ~= 10^-343 */
U64(0xEEF453D6, 0x923BD65A), U64(0x113FAA29, 0x06A13B3F), /* ~= 10^-342 */
U64(0x9558B466, 0x1B6565F8), U64(0x4AC7CA59, 0xA424C507), /* ~= 10^-341 */
U64(0xBAAEE17F, 0xA23EBF76), U64(0x5D79BCF0, 0x0D2DF649), /* ~= 10^-340 */
U64(0xE95A99DF, 0x8ACE6F53), U64(0xF4D82C2C, 0x107973DC), /* ~= 10^-339 */
U64(0x91D8A02B, 0xB6C10594), U64(0x79071B9B, 0x8A4BE869), /* ~= 10^-338 */
U64(0xB64EC836, 0xA47146F9), U64(0x9748E282, 0x6CDEE284), /* ~= 10^-337 */
U64(0xE3E27A44, 0x4D8D98B7), U64(0xFD1B1B23, 0x08169B25), /* ~= 10^-336 */
U64(0x8E6D8C6A, 0xB0787F72), U64(0xFE30F0F5, 0xE50E20F7), /* ~= 10^-335 */
U64(0xB208EF85, 0x5C969F4F), U64(0xBDBD2D33, 0x5E51A935), /* ~= 10^-334 */
U64(0xDE8B2B66, 0xB3BC4723), U64(0xAD2C7880, 0x35E61382), /* ~= 10^-333 */
U64(0x8B16FB20, 0x3055AC76), U64(0x4C3BCB50, 0x21AFCC31), /* ~= 10^-332 */
U64(0xADDCB9E8, 0x3C6B1793), U64(0xDF4ABE24, 0x2A1BBF3D), /* ~= 10^-331 */
U64(0xD953E862, 0x4B85DD78), U64(0xD71D6DAD, 0x34A2AF0D), /* ~= 10^-330 */
U64(0x87D4713D, 0x6F33AA6B), U64(0x8672648C, 0x40E5AD68), /* ~= 10^-329 */
U64(0xA9C98D8C, 0xCB009506), U64(0x680EFDAF, 0x511F18C2), /* ~= 10^-328 */
U64(0xD43BF0EF, 0xFDC0BA48), U64(0x0212BD1B, 0x2566DEF2), /* ~= 10^-327 */
U64(0x84A57695, 0xFE98746D), U64(0x014BB630, 0xF7604B57), /* ~= 10^-326 */
U64(0xA5CED43B, 0x7E3E9188), U64(0x419EA3BD, 0x35385E2D), /* ~= 10^-325 */
U64(0xCF42894A, 0x5DCE35EA), U64(0x52064CAC, 0x828675B9), /* ~= 10^-324 */
U64(0x818995CE, 0x7AA0E1B2), U64(0x7343EFEB, 0xD1940993), /* ~= 10^-323 */
U64(0xA1EBFB42, 0x19491A1F), U64(0x1014EBE6, 0xC5F90BF8), /* ~= 10^-322 */
U64(0xCA66FA12, 0x9F9B60A6), U64(0xD41A26E0, 0x77774EF6), /* ~= 10^-321 */
U64(0xFD00B897, 0x478238D0), U64(0x8920B098, 0x955522B4), /* ~= 10^-320 */
U64(0x9E20735E, 0x8CB16382), U64(0x55B46E5F, 0x5D5535B0), /* ~= 10^-319 */
U64(0xC5A89036, 0x2FDDBC62), U64(0xEB2189F7, 0x34AA831D), /* ~= 10^-318 */
U64(0xF712B443, 0xBBD52B7B), U64(0xA5E9EC75, 0x01D523E4), /* ~= 10^-317 */
U64(0x9A6BB0AA, 0x55653B2D), U64(0x47B233C9, 0x2125366E), /* ~= 10^-316 */
U64(0xC1069CD4, 0xEABE89F8), U64(0x999EC0BB, 0x696E840A), /* ~= 10^-315 */
U64(0xF148440A, 0x256E2C76), U64(0xC00670EA, 0x43CA250D), /* ~= 10^-314 */
U64(0x96CD2A86, 0x5764DBCA), U64(0x38040692, 0x6A5E5728), /* ~= 10^-313 */
U64(0xBC807527, 0xED3E12BC), U64(0xC6050837, 0x04F5ECF2), /* ~= 10^-312 */
U64(0xEBA09271, 0xE88D976B), U64(0xF7864A44, 0xC633682E), /* ~= 10^-311 */
U64(0x93445B87, 0x31587EA3), U64(0x7AB3EE6A, 0xFBE0211D), /* ~= 10^-310 */
U64(0xB8157268, 0xFDAE9E4C), U64(0x5960EA05, 0xBAD82964), /* ~= 10^-309 */
U64(0xE61ACF03, 0x3D1A45DF), U64(0x6FB92487, 0x298E33BD), /* ~= 10^-308 */
U64(0x8FD0C162, 0x06306BAB), U64(0xA5D3B6D4, 0x79F8E056), /* ~= 10^-307 */
U64(0xB3C4F1BA, 0x87BC8696), U64(0x8F48A489, 0x9877186C), /* ~= 10^-306 */
U64(0xE0B62E29, 0x29ABA83C), U64(0x331ACDAB, 0xFE94DE87), /* ~= 10^-305 */
U64(0x8C71DCD9, 0xBA0B4925), U64(0x9FF0C08B, 0x7F1D0B14), /* ~= 10^-304 */
U64(0xAF8E5410, 0x288E1B6F), U64(0x07ECF0AE, 0x5EE44DD9), /* ~= 10^-303 */
U64(0xDB71E914, 0x32B1A24A), U64(0xC9E82CD9, 0xF69D6150), /* ~= 10^-302 */
U64(0x892731AC, 0x9FAF056E), U64(0xBE311C08, 0x3A225CD2), /* ~= 10^-301 */
U64(0xAB70FE17, 0xC79AC6CA), U64(0x6DBD630A, 0x48AAF406), /* ~= 10^-300 */
U64(0xD64D3D9D, 0xB981787D), U64(0x092CBBCC, 0xDAD5B108), /* ~= 10^-299 */
U64(0x85F04682, 0x93F0EB4E), U64(0x25BBF560, 0x08C58EA5), /* ~= 10^-298 */
U64(0xA76C5823, 0x38ED2621), U64(0xAF2AF2B8, 0x0AF6F24E), /* ~= 10^-297 */
U64(0xD1476E2C, 0x07286FAA), U64(0x1AF5AF66, 0x0DB4AEE1), /* ~= 10^-296 */
U64(0x82CCA4DB, 0x847945CA), U64(0x50D98D9F, 0xC890ED4D), /* ~= 10^-295 */
U64(0xA37FCE12, 0x6597973C), U64(0xE50FF107, 0xBAB528A0), /* ~= 10^-294 */
U64(0xCC5FC196, 0xFEFD7D0C), U64(0x1E53ED49, 0xA96272C8), /* ~= 10^-293 */
U64(0xFF77B1FC, 0xBEBCDC4F), U64(0x25E8E89C, 0x13BB0F7A), /* ~= 10^-292 */
U64(0x9FAACF3D, 0xF73609B1), U64(0x77B19161, 0x8C54E9AC), /* ~= 10^-291 */
U64(0xC795830D, 0x75038C1D), U64(0xD59DF5B9, 0xEF6A2417), /* ~= 10^-290 */
U64(0xF97AE3D0, 0xD2446F25), U64(0x4B057328, 0x6B44AD1D), /* ~= 10^-289 */
U64(0x9BECCE62, 0x836AC577), U64(0x4EE367F9, 0x430AEC32), /* ~= 10^-288 */
U64(0xC2E801FB, 0x244576D5), U64(0x229C41F7, 0x93CDA73F), /* ~= 10^-287 */
U64(0xF3A20279, 0xED56D48A), U64(0x6B435275, 0x78C1110F), /* ~= 10^-286 */
U64(0x9845418C, 0x345644D6), U64(0x830A1389, 0x6B78AAA9), /* ~= 10^-285 */
U64(0xBE5691EF, 0x416BD60C), U64(0x23CC986B, 0xC656D553), /* ~= 10^-284 */
U64(0xEDEC366B, 0x11C6CB8F), U64(0x2CBFBE86, 0xB7EC8AA8), /* ~= 10^-283 */
U64(0x94B3A202, 0xEB1C3F39), U64(0x7BF7D714, 0x32F3D6A9), /* ~= 10^-282 */
U64(0xB9E08A83, 0xA5E34F07), U64(0xDAF5CCD9, 0x3FB0CC53), /* ~= 10^-281 */
U64(0xE858AD24, 0x8F5C22C9), U64(0xD1B3400F, 0x8F9CFF68), /* ~= 10^-280 */
U64(0x91376C36, 0xD99995BE), U64(0x23100809, 0xB9C21FA1), /* ~= 10^-279 */
U64(0xB5854744, 0x8FFFFB2D), U64(0xABD40A0C, 0x2832A78A), /* ~= 10^-278 */
U64(0xE2E69915, 0xB3FFF9F9), U64(0x16C90C8F, 0x323F516C), /* ~= 10^-277 */
U64(0x8DD01FAD, 0x907FFC3B), U64(0xAE3DA7D9, 0x7F6792E3), /* ~= 10^-276 */
U64(0xB1442798, 0xF49FFB4A), U64(0x99CD11CF, 0xDF41779C), /* ~= 10^-275 */
U64(0xDD95317F, 0x31C7FA1D), U64(0x40405643, 0xD711D583), /* ~= 10^-274 */
U64(0x8A7D3EEF, 0x7F1CFC52), U64(0x482835EA, 0x666B2572), /* ~= 10^-273 */
U64(0xAD1C8EAB, 0x5EE43B66), U64(0xDA324365, 0x0005EECF), /* ~= 10^-272 */
U64(0xD863B256, 0x369D4A40), U64(0x90BED43E, 0x40076A82), /* ~= 10^-271 */
U64(0x873E4F75, 0xE2224E68), U64(0x5A7744A6, 0xE804A291), /* ~= 10^-270 */
U64(0xA90DE353, 0x5AAAE202), U64(0x711515D0, 0xA205CB36), /* ~= 10^-269 */
U64(0xD3515C28, 0x31559A83), U64(0x0D5A5B44, 0xCA873E03), /* ~= 10^-268 */
U64(0x8412D999, 0x1ED58091), U64(0xE858790A, 0xFE9486C2), /* ~= 10^-267 */
U64(0xA5178FFF, 0x668AE0B6), U64(0x626E974D, 0xBE39A872), /* ~= 10^-266 */
U64(0xCE5D73FF, 0x402D98E3), U64(0xFB0A3D21, 0x2DC8128F), /* ~= 10^-265 */
U64(0x80FA687F, 0x881C7F8E), U64(0x7CE66634, 0xBC9D0B99), /* ~= 10^-264 */
U64(0xA139029F, 0x6A239F72), U64(0x1C1FFFC1, 0xEBC44E80), /* ~= 10^-263 */
U64(0xC9874347, 0x44AC874E), U64(0xA327FFB2, 0x66B56220), /* ~= 10^-262 */
U64(0xFBE91419, 0x15D7A922), U64(0x4BF1FF9F, 0x0062BAA8), /* ~= 10^-261 */
U64(0x9D71AC8F, 0xADA6C9B5), U64(0x6F773FC3, 0x603DB4A9), /* ~= 10^-260 */
U64(0xC4CE17B3, 0x99107C22), U64(0xCB550FB4, 0x384D21D3), /* ~= 10^-259 */
U64(0xF6019DA0, 0x7F549B2B), U64(0x7E2A53A1, 0x46606A48), /* ~= 10^-258 */
U64(0x99C10284, 0x4F94E0FB), U64(0x2EDA7444, 0xCBFC426D), /* ~= 10^-257 */
U64(0xC0314325, 0x637A1939), U64(0xFA911155, 0xFEFB5308), /* ~= 10^-256 */
U64(0xF03D93EE, 0xBC589F88), U64(0x793555AB, 0x7EBA27CA), /* ~= 10^-255 */
U64(0x96267C75, 0x35B763B5), U64(0x4BC1558B, 0x2F3458DE), /* ~= 10^-254 */
U64(0xBBB01B92, 0x83253CA2), U64(0x9EB1AAED, 0xFB016F16), /* ~= 10^-253 */
U64(0xEA9C2277, 0x23EE8BCB), U64(0x465E15A9, 0x79C1CADC), /* ~= 10^-252 */
U64(0x92A1958A, 0x7675175F), U64(0x0BFACD89, 0xEC191EC9), /* ~= 10^-251 */
U64(0xB749FAED, 0x14125D36), U64(0xCEF980EC, 0x671F667B), /* ~= 10^-250 */
U64(0xE51C79A8, 0x5916F484), U64(0x82B7E127, 0x80E7401A), /* ~= 10^-249 */
U64(0x8F31CC09, 0x37AE58D2), U64(0xD1B2ECB8, 0xB0908810), /* ~= 10^-248 */
U64(0xB2FE3F0B, 0x8599EF07), U64(0x861FA7E6, 0xDCB4AA15), /* ~= 10^-247 */
U64(0xDFBDCECE, 0x67006AC9), U64(0x67A791E0, 0x93E1D49A), /* ~= 10^-246 */
U64(0x8BD6A141, 0x006042BD), U64(0xE0C8BB2C, 0x5C6D24E0), /* ~= 10^-245 */
U64(0xAECC4991, 0x4078536D), U64(0x58FAE9F7, 0x73886E18), /* ~= 10^-244 */
U64(0xDA7F5BF5, 0x90966848), U64(0xAF39A475, 0x506A899E), /* ~= 10^-243 */
U64(0x888F9979, 0x7A5E012D), U64(0x6D8406C9, 0x52429603), /* ~= 10^-242 */
U64(0xAAB37FD7, 0xD8F58178), U64(0xC8E5087B, 0xA6D33B83), /* ~= 10^-241 */
U64(0xD5605FCD, 0xCF32E1D6), U64(0xFB1E4A9A, 0x90880A64), /* ~= 10^-240 */
U64(0x855C3BE0, 0xA17FCD26), U64(0x5CF2EEA0, 0x9A55067F), /* ~= 10^-239 */
U64(0xA6B34AD8, 0xC9DFC06F), U64(0xF42FAA48, 0xC0EA481E), /* ~= 10^-238 */
U64(0xD0601D8E, 0xFC57B08B), U64(0xF13B94DA, 0xF124DA26), /* ~= 10^-237 */
U64(0x823C1279, 0x5DB6CE57), U64(0x76C53D08, 0xD6B70858), /* ~= 10^-236 */
U64(0xA2CB1717, 0xB52481ED), U64(0x54768C4B, 0x0C64CA6E), /* ~= 10^-235 */
U64(0xCB7DDCDD, 0xA26DA268), U64(0xA9942F5D, 0xCF7DFD09), /* ~= 10^-234 */
U64(0xFE5D5415, 0x0B090B02), U64(0xD3F93B35, 0x435D7C4C), /* ~= 10^-233 */
U64(0x9EFA548D, 0x26E5A6E1), U64(0xC47BC501, 0x4A1A6DAF), /* ~= 10^-232 */
U64(0xC6B8E9B0, 0x709F109A), U64(0x359AB641, 0x9CA1091B), /* ~= 10^-231 */
U64(0xF867241C, 0x8CC6D4C0), U64(0xC30163D2, 0x03C94B62), /* ~= 10^-230 */
U64(0x9B407691, 0xD7FC44F8), U64(0x79E0DE63, 0x425DCF1D), /* ~= 10^-229 */
U64(0xC2109436, 0x4DFB5636), U64(0x985915FC, 0x12F542E4), /* ~= 10^-228 */
U64(0xF294B943, 0xE17A2BC4), U64(0x3E6F5B7B, 0x17B2939D), /* ~= 10^-227 */
U64(0x979CF3CA, 0x6CEC5B5A), U64(0xA705992C, 0xEECF9C42), /* ~= 10^-226 */
U64(0xBD8430BD, 0x08277231), U64(0x50C6FF78, 0x2A838353), /* ~= 10^-225 */
U64(0xECE53CEC, 0x4A314EBD), U64(0xA4F8BF56, 0x35246428), /* ~= 10^-224 */
U64(0x940F4613, 0xAE5ED136), U64(0x871B7795, 0xE136BE99), /* ~= 10^-223 */
U64(0xB9131798, 0x99F68584), U64(0x28E2557B, 0x59846E3F), /* ~= 10^-222 */
U64(0xE757DD7E, 0xC07426E5), U64(0x331AEADA, 0x2FE589CF), /* ~= 10^-221 */
U64(0x9096EA6F, 0x3848984F), U64(0x3FF0D2C8, 0x5DEF7621), /* ~= 10^-220 */
U64(0xB4BCA50B, 0x065ABE63), U64(0x0FED077A, 0x756B53A9), /* ~= 10^-219 */
U64(0xE1EBCE4D, 0xC7F16DFB), U64(0xD3E84959, 0x12C62894), /* ~= 10^-218 */
U64(0x8D3360F0, 0x9CF6E4BD), U64(0x64712DD7, 0xABBBD95C), /* ~= 10^-217 */
U64(0xB080392C, 0xC4349DEC), U64(0xBD8D794D, 0x96AACFB3), /* ~= 10^-216 */
U64(0xDCA04777, 0xF541C567), U64(0xECF0D7A0, 0xFC5583A0), /* ~= 10^-215 */
U64(0x89E42CAA, 0xF9491B60), U64(0xF41686C4, 0x9DB57244), /* ~= 10^-214 */
U64(0xAC5D37D5, 0xB79B6239), U64(0x311C2875, 0xC522CED5), /* ~= 10^-213 */
U64(0xD77485CB, 0x25823AC7), U64(0x7D633293, 0x366B828B), /* ~= 10^-212 */
U64(0x86A8D39E, 0xF77164BC), U64(0xAE5DFF9C, 0x02033197), /* ~= 10^-211 */
U64(0xA8530886, 0xB54DBDEB), U64(0xD9F57F83, 0x0283FDFC), /* ~= 10^-210 */
U64(0xD267CAA8, 0x62A12D66), U64(0xD072DF63, 0xC324FD7B), /* ~= 10^-209 */
U64(0x8380DEA9, 0x3DA4BC60), U64(0x4247CB9E, 0x59F71E6D), /* ~= 10^-208 */
U64(0xA4611653, 0x8D0DEB78), U64(0x52D9BE85, 0xF074E608), /* ~= 10^-207 */
U64(0xCD795BE8, 0x70516656), U64(0x67902E27, 0x6C921F8B), /* ~= 10^-206 */
U64(0x806BD971, 0x4632DFF6), U64(0x00BA1CD8, 0xA3DB53B6), /* ~= 10^-205 */
U64(0xA086CFCD, 0x97BF97F3), U64(0x80E8A40E, 0xCCD228A4), /* ~= 10^-204 */
U64(0xC8A883C0, 0xFDAF7DF0), U64(0x6122CD12, 0x8006B2CD), /* ~= 10^-203 */
U64(0xFAD2A4B1, 0x3D1B5D6C), U64(0x796B8057, 0x20085F81), /* ~= 10^-202 */
U64(0x9CC3A6EE, 0xC6311A63), U64(0xCBE33036, 0x74053BB0), /* ~= 10^-201 */
U64(0xC3F490AA, 0x77BD60FC), U64(0xBEDBFC44, 0x11068A9C), /* ~= 10^-200 */
U64(0xF4F1B4D5, 0x15ACB93B), U64(0xEE92FB55, 0x15482D44), /* ~= 10^-199 */
U64(0x99171105, 0x2D8BF3C5), U64(0x751BDD15, 0x2D4D1C4A), /* ~= 10^-198 */
U64(0xBF5CD546, 0x78EEF0B6), U64(0xD262D45A, 0x78A0635D), /* ~= 10^-197 */
U64(0xEF340A98, 0x172AACE4), U64(0x86FB8971, 0x16C87C34), /* ~= 10^-196 */
U64(0x9580869F, 0x0E7AAC0E), U64(0xD45D35E6, 0xAE3D4DA0), /* ~= 10^-195 */
U64(0xBAE0A846, 0xD2195712), U64(0x89748360, 0x59CCA109), /* ~= 10^-194 */
U64(0xE998D258, 0x869FACD7), U64(0x2BD1A438, 0x703FC94B), /* ~= 10^-193 */
U64(0x91FF8377, 0x5423CC06), U64(0x7B6306A3, 0x4627DDCF), /* ~= 10^-192 */
U64(0xB67F6455, 0x292CBF08), U64(0x1A3BC84C, 0x17B1D542), /* ~= 10^-191 */
U64(0xE41F3D6A, 0x7377EECA), U64(0x20CABA5F, 0x1D9E4A93), /* ~= 10^-190 */
U64(0x8E938662, 0x882AF53E), U64(0x547EB47B, 0x7282EE9C), /* ~= 10^-189 */
U64(0xB23867FB, 0x2A35B28D), U64(0xE99E619A, 0x4F23AA43), /* ~= 10^-188 */
U64(0xDEC681F9, 0xF4C31F31), U64(0x6405FA00, 0xE2EC94D4), /* ~= 10^-187 */
U64(0x8B3C113C, 0x38F9F37E), U64(0xDE83BC40, 0x8DD3DD04), /* ~= 10^-186 */
U64(0xAE0B158B, 0x4738705E), U64(0x9624AB50, 0xB148D445), /* ~= 10^-185 */
U64(0xD98DDAEE, 0x19068C76), U64(0x3BADD624, 0xDD9B0957), /* ~= 10^-184 */
U64(0x87F8A8D4, 0xCFA417C9), U64(0xE54CA5D7, 0x0A80E5D6), /* ~= 10^-183 */
U64(0xA9F6D30A, 0x038D1DBC), U64(0x5E9FCF4C, 0xCD211F4C), /* ~= 10^-182 */
U64(0xD47487CC, 0x8470652B), U64(0x7647C320, 0x0069671F), /* ~= 10^-181 */
U64(0x84C8D4DF, 0xD2C63F3B), U64(0x29ECD9F4, 0x0041E073), /* ~= 10^-180 */
U64(0xA5FB0A17, 0xC777CF09), U64(0xF4681071, 0x00525890), /* ~= 10^-179 */
U64(0xCF79CC9D, 0xB955C2CC), U64(0x7182148D, 0x4066EEB4), /* ~= 10^-178 */
U64(0x81AC1FE2, 0x93D599BF), U64(0xC6F14CD8, 0x48405530), /* ~= 10^-177 */
U64(0xA21727DB, 0x38CB002F), U64(0xB8ADA00E, 0x5A506A7C), /* ~= 10^-176 */
U64(0xCA9CF1D2, 0x06FDC03B), U64(0xA6D90811, 0xF0E4851C), /* ~= 10^-175 */
U64(0xFD442E46, 0x88BD304A), U64(0x908F4A16, 0x6D1DA663), /* ~= 10^-174 */
U64(0x9E4A9CEC, 0x15763E2E), U64(0x9A598E4E, 0x043287FE), /* ~= 10^-173 */
U64(0xC5DD4427, 0x1AD3CDBA), U64(0x40EFF1E1, 0x853F29FD), /* ~= 10^-172 */
U64(0xF7549530, 0xE188C128), U64(0xD12BEE59, 0xE68EF47C), /* ~= 10^-171 */
U64(0x9A94DD3E, 0x8CF578B9), U64(0x82BB74F8, 0x301958CE), /* ~= 10^-170 */
U64(0xC13A148E, 0x3032D6E7), U64(0xE36A5236, 0x3C1FAF01), /* ~= 10^-169 */
U64(0xF18899B1, 0xBC3F8CA1), U64(0xDC44E6C3, 0xCB279AC1), /* ~= 10^-168 */
U64(0x96F5600F, 0x15A7B7E5), U64(0x29AB103A, 0x5EF8C0B9), /* ~= 10^-167 */
U64(0xBCB2B812, 0xDB11A5DE), U64(0x7415D448, 0xF6B6F0E7), /* ~= 10^-166 */
U64(0xEBDF6617, 0x91D60F56), U64(0x111B495B, 0x3464AD21), /* ~= 10^-165 */
U64(0x936B9FCE, 0xBB25C995), U64(0xCAB10DD9, 0x00BEEC34), /* ~= 10^-164 */
U64(0xB84687C2, 0x69EF3BFB), U64(0x3D5D514F, 0x40EEA742), /* ~= 10^-163 */
U64(0xE65829B3, 0x046B0AFA), U64(0x0CB4A5A3, 0x112A5112), /* ~= 10^-162 */
U64(0x8FF71A0F, 0xE2C2E6DC), U64(0x47F0E785, 0xEABA72AB), /* ~= 10^-161 */
U64(0xB3F4E093, 0xDB73A093), U64(0x59ED2167, 0x65690F56), /* ~= 10^-160 */
U64(0xE0F218B8, 0xD25088B8), U64(0x306869C1, 0x3EC3532C), /* ~= 10^-159 */
U64(0x8C974F73, 0x83725573), U64(0x1E414218, 0xC73A13FB), /* ~= 10^-158 */
U64(0xAFBD2350, 0x644EEACF), U64(0xE5D1929E, 0xF90898FA), /* ~= 10^-157 */
U64(0xDBAC6C24, 0x7D62A583), U64(0xDF45F746, 0xB74ABF39), /* ~= 10^-156 */
U64(0x894BC396, 0xCE5DA772), U64(0x6B8BBA8C, 0x328EB783), /* ~= 10^-155 */
U64(0xAB9EB47C, 0x81F5114F), U64(0x066EA92F, 0x3F326564), /* ~= 10^-154 */
U64(0xD686619B, 0xA27255A2), U64(0xC80A537B, 0x0EFEFEBD), /* ~= 10^-153 */
U64(0x8613FD01, 0x45877585), U64(0xBD06742C, 0xE95F5F36), /* ~= 10^-152 */
U64(0xA798FC41, 0x96E952E7), U64(0x2C481138, 0x23B73704), /* ~= 10^-151 */
U64(0xD17F3B51, 0xFCA3A7A0), U64(0xF75A1586, 0x2CA504C5), /* ~= 10^-150 */
U64(0x82EF8513, 0x3DE648C4), U64(0x9A984D73, 0xDBE722FB), /* ~= 10^-149 */
U64(0xA3AB6658, 0x0D5FDAF5), U64(0xC13E60D0, 0xD2E0EBBA), /* ~= 10^-148 */
U64(0xCC963FEE, 0x10B7D1B3), U64(0x318DF905, 0x079926A8), /* ~= 10^-147 */
U64(0xFFBBCFE9, 0x94E5C61F), U64(0xFDF17746, 0x497F7052), /* ~= 10^-146 */
U64(0x9FD561F1, 0xFD0F9BD3), U64(0xFEB6EA8B, 0xEDEFA633), /* ~= 10^-145 */
U64(0xC7CABA6E, 0x7C5382C8), U64(0xFE64A52E, 0xE96B8FC0), /* ~= 10^-144 */
U64(0xF9BD690A, 0x1B68637B), U64(0x3DFDCE7A, 0xA3C673B0), /* ~= 10^-143 */
U64(0x9C1661A6, 0x51213E2D), U64(0x06BEA10C, 0xA65C084E), /* ~= 10^-142 */
U64(0xC31BFA0F, 0xE5698DB8), U64(0x486E494F, 0xCFF30A62), /* ~= 10^-141 */
U64(0xF3E2F893, 0xDEC3F126), U64(0x5A89DBA3, 0xC3EFCCFA), /* ~= 10^-140 */
U64(0x986DDB5C, 0x6B3A76B7), U64(0xF8962946, 0x5A75E01C), /* ~= 10^-139 */
U64(0xBE895233, 0x86091465), U64(0xF6BBB397, 0xF1135823), /* ~= 10^-138 */
U64(0xEE2BA6C0, 0x678B597F), U64(0x746AA07D, 0xED582E2C), /* ~= 10^-137 */
U64(0x94DB4838, 0x40B717EF), U64(0xA8C2A44E, 0xB4571CDC), /* ~= 10^-136 */
U64(0xBA121A46, 0x50E4DDEB), U64(0x92F34D62, 0x616CE413), /* ~= 10^-135 */
U64(0xE896A0D7, 0xE51E1566), U64(0x77B020BA, 0xF9C81D17), /* ~= 10^-134 */
U64(0x915E2486, 0xEF32CD60), U64(0x0ACE1474, 0xDC1D122E), /* ~= 10^-133 */
U64(0xB5B5ADA8, 0xAAFF80B8), U64(0x0D819992, 0x132456BA), /* ~= 10^-132 */
U64(0xE3231912, 0xD5BF60E6), U64(0x10E1FFF6, 0x97ED6C69), /* ~= 10^-131 */
U64(0x8DF5EFAB, 0xC5979C8F), U64(0xCA8D3FFA, 0x1EF463C1), /* ~= 10^-130 */
U64(0xB1736B96, 0xB6FD83B3), U64(0xBD308FF8, 0xA6B17CB2), /* ~= 10^-129 */
U64(0xDDD0467C, 0x64BCE4A0), U64(0xAC7CB3F6, 0xD05DDBDE), /* ~= 10^-128 */
U64(0x8AA22C0D, 0xBEF60EE4), U64(0x6BCDF07A, 0x423AA96B), /* ~= 10^-127 */
U64(0xAD4AB711, 0x2EB3929D), U64(0x86C16C98, 0xD2C953C6), /* ~= 10^-126 */
U64(0xD89D64D5, 0x7A607744), U64(0xE871C7BF, 0x077BA8B7), /* ~= 10^-125 */
U64(0x87625F05, 0x6C7C4A8B), U64(0x11471CD7, 0x64AD4972), /* ~= 10^-124 */
U64(0xA93AF6C6, 0xC79B5D2D), U64(0xD598E40D, 0x3DD89BCF), /* ~= 10^-123 */
U64(0xD389B478, 0x79823479), U64(0x4AFF1D10, 0x8D4EC2C3), /* ~= 10^-122 */
U64(0x843610CB, 0x4BF160CB), U64(0xCEDF722A, 0x585139BA), /* ~= 10^-121 */
U64(0xA54394FE, 0x1EEDB8FE), U64(0xC2974EB4, 0xEE658828), /* ~= 10^-120 */
U64(0xCE947A3D, 0xA6A9273E), U64(0x733D2262, 0x29FEEA32), /* ~= 10^-119 */
U64(0x811CCC66, 0x8829B887), U64(0x0806357D, 0x5A3F525F), /* ~= 10^-118 */
U64(0xA163FF80, 0x2A3426A8), U64(0xCA07C2DC, 0xB0CF26F7), /* ~= 10^-117 */
U64(0xC9BCFF60, 0x34C13052), U64(0xFC89B393, 0xDD02F0B5), /* ~= 10^-116 */
U64(0xFC2C3F38, 0x41F17C67), U64(0xBBAC2078, 0xD443ACE2), /* ~= 10^-115 */
U64(0x9D9BA783, 0x2936EDC0), U64(0xD54B944B, 0x84AA4C0D), /* ~= 10^-114 */
U64(0xC5029163, 0xF384A931), U64(0x0A9E795E, 0x65D4DF11), /* ~= 10^-113 */
U64(0xF64335BC, 0xF065D37D), U64(0x4D4617B5, 0xFF4A16D5), /* ~= 10^-112 */
U64(0x99EA0196, 0x163FA42E), U64(0x504BCED1, 0xBF8E4E45), /* ~= 10^-111 */
U64(0xC06481FB, 0x9BCF8D39), U64(0xE45EC286, 0x2F71E1D6), /* ~= 10^-110 */
U64(0xF07DA27A, 0x82C37088), U64(0x5D767327, 0xBB4E5A4C), /* ~= 10^-109 */
U64(0x964E858C, 0x91BA2655), U64(0x3A6A07F8, 0xD510F86F), /* ~= 10^-108 */
U64(0xBBE226EF, 0xB628AFEA), U64(0x890489F7, 0x0A55368B), /* ~= 10^-107 */
U64(0xEADAB0AB, 0xA3B2DBE5), U64(0x2B45AC74, 0xCCEA842E), /* ~= 10^-106 */
U64(0x92C8AE6B, 0x464FC96F), U64(0x3B0B8BC9, 0x0012929D), /* ~= 10^-105 */
U64(0xB77ADA06, 0x17E3BBCB), U64(0x09CE6EBB, 0x40173744), /* ~= 10^-104 */
U64(0xE5599087, 0x9DDCAABD), U64(0xCC420A6A, 0x101D0515), /* ~= 10^-103 */
U64(0x8F57FA54, 0xC2A9EAB6), U64(0x9FA94682, 0x4A12232D), /* ~= 10^-102 */
U64(0xB32DF8E9, 0xF3546564), U64(0x47939822, 0xDC96ABF9), /* ~= 10^-101 */
U64(0xDFF97724, 0x70297EBD), U64(0x59787E2B, 0x93BC56F7), /* ~= 10^-100 */
U64(0x8BFBEA76, 0xC619EF36), U64(0x57EB4EDB, 0x3C55B65A), /* ~= 10^-99 */
U64(0xAEFAE514, 0x77A06B03), U64(0xEDE62292, 0x0B6B23F1), /* ~= 10^-98 */
U64(0xDAB99E59, 0x958885C4), U64(0xE95FAB36, 0x8E45ECED), /* ~= 10^-97 */
U64(0x88B402F7, 0xFD75539B), U64(0x11DBCB02, 0x18EBB414), /* ~= 10^-96 */
U64(0xAAE103B5, 0xFCD2A881), U64(0xD652BDC2, 0x9F26A119), /* ~= 10^-95 */
U64(0xD59944A3, 0x7C0752A2), U64(0x4BE76D33, 0x46F0495F), /* ~= 10^-94 */
U64(0x857FCAE6, 0x2D8493A5), U64(0x6F70A440, 0x0C562DDB), /* ~= 10^-93 */
U64(0xA6DFBD9F, 0xB8E5B88E), U64(0xCB4CCD50, 0x0F6BB952), /* ~= 10^-92 */
U64(0xD097AD07, 0xA71F26B2), U64(0x7E2000A4, 0x1346A7A7), /* ~= 10^-91 */
U64(0x825ECC24, 0xC873782F), U64(0x8ED40066, 0x8C0C28C8), /* ~= 10^-90 */
U64(0xA2F67F2D, 0xFA90563B), U64(0x72890080, 0x2F0F32FA), /* ~= 10^-89 */
U64(0xCBB41EF9, 0x79346BCA), U64(0x4F2B40A0, 0x3AD2FFB9), /* ~= 10^-88 */
U64(0xFEA126B7, 0xD78186BC), U64(0xE2F610C8, 0x4987BFA8), /* ~= 10^-87 */
U64(0x9F24B832, 0xE6B0F436), U64(0x0DD9CA7D, 0x2DF4D7C9), /* ~= 10^-86 */
U64(0xC6EDE63F, 0xA05D3143), U64(0x91503D1C, 0x79720DBB), /* ~= 10^-85 */
U64(0xF8A95FCF, 0x88747D94), U64(0x75A44C63, 0x97CE912A), /* ~= 10^-84 */
U64(0x9B69DBE1, 0xB548CE7C), U64(0xC986AFBE, 0x3EE11ABA), /* ~= 10^-83 */
U64(0xC24452DA, 0x229B021B), U64(0xFBE85BAD, 0xCE996168), /* ~= 10^-82 */
U64(0xF2D56790, 0xAB41C2A2), U64(0xFAE27299, 0x423FB9C3), /* ~= 10^-81 */
U64(0x97C560BA, 0x6B0919A5), U64(0xDCCD879F, 0xC967D41A), /* ~= 10^-80 */
U64(0xBDB6B8E9, 0x05CB600F), U64(0x5400E987, 0xBBC1C920), /* ~= 10^-79 */
U64(0xED246723, 0x473E3813), U64(0x290123E9, 0xAAB23B68), /* ~= 10^-78 */
U64(0x9436C076, 0x0C86E30B), U64(0xF9A0B672, 0x0AAF6521), /* ~= 10^-77 */
U64(0xB9447093, 0x8FA89BCE), U64(0xF808E40E, 0x8D5B3E69), /* ~= 10^-76 */
U64(0xE7958CB8, 0x7392C2C2), U64(0xB60B1D12, 0x30B20E04), /* ~= 10^-75 */
U64(0x90BD77F3, 0x483BB9B9), U64(0xB1C6F22B, 0x5E6F48C2), /* ~= 10^-74 */
U64(0xB4ECD5F0, 0x1A4AA828), U64(0x1E38AEB6, 0x360B1AF3), /* ~= 10^-73 */
U64(0xE2280B6C, 0x20DD5232), U64(0x25C6DA63, 0xC38DE1B0), /* ~= 10^-72 */
U64(0x8D590723, 0x948A535F), U64(0x579C487E, 0x5A38AD0E), /* ~= 10^-71 */
U64(0xB0AF48EC, 0x79ACE837), U64(0x2D835A9D, 0xF0C6D851), /* ~= 10^-70 */
U64(0xDCDB1B27, 0x98182244), U64(0xF8E43145, 0x6CF88E65), /* ~= 10^-69 */
U64(0x8A08F0F8, 0xBF0F156B), U64(0x1B8E9ECB, 0x641B58FF), /* ~= 10^-68 */
U64(0xAC8B2D36, 0xEED2DAC5), U64(0xE272467E, 0x3D222F3F), /* ~= 10^-67 */
U64(0xD7ADF884, 0xAA879177), U64(0x5B0ED81D, 0xCC6ABB0F), /* ~= 10^-66 */
U64(0x86CCBB52, 0xEA94BAEA), U64(0x98E94712, 0x9FC2B4E9), /* ~= 10^-65 */
U64(0xA87FEA27, 0xA539E9A5), U64(0x3F2398D7, 0x47B36224), /* ~= 10^-64 */
U64(0xD29FE4B1, 0x8E88640E), U64(0x8EEC7F0D, 0x19A03AAD), /* ~= 10^-63 */
U64(0x83A3EEEE, 0xF9153E89), U64(0x1953CF68, 0x300424AC), /* ~= 10^-62 */
U64(0xA48CEAAA, 0xB75A8E2B), U64(0x5FA8C342, 0x3C052DD7), /* ~= 10^-61 */
U64(0xCDB02555, 0x653131B6), U64(0x3792F412, 0xCB06794D), /* ~= 10^-60 */
U64(0x808E1755, 0x5F3EBF11), U64(0xE2BBD88B, 0xBEE40BD0), /* ~= 10^-59 */
U64(0xA0B19D2A, 0xB70E6ED6), U64(0x5B6ACEAE, 0xAE9D0EC4), /* ~= 10^-58 */
U64(0xC8DE0475, 0x64D20A8B), U64(0xF245825A, 0x5A445275), /* ~= 10^-57 */
U64(0xFB158592, 0xBE068D2E), U64(0xEED6E2F0, 0xF0D56712), /* ~= 10^-56 */
U64(0x9CED737B, 0xB6C4183D), U64(0x55464DD6, 0x9685606B), /* ~= 10^-55 */
U64(0xC428D05A, 0xA4751E4C), U64(0xAA97E14C, 0x3C26B886), /* ~= 10^-54 */
U64(0xF5330471, 0x4D9265DF), U64(0xD53DD99F, 0x4B3066A8), /* ~= 10^-53 */
U64(0x993FE2C6, 0xD07B7FAB), U64(0xE546A803, 0x8EFE4029), /* ~= 10^-52 */
U64(0xBF8FDB78, 0x849A5F96), U64(0xDE985204, 0x72BDD033), /* ~= 10^-51 */
U64(0xEF73D256, 0xA5C0F77C), U64(0x963E6685, 0x8F6D4440), /* ~= 10^-50 */
U64(0x95A86376, 0x27989AAD), U64(0xDDE70013, 0x79A44AA8), /* ~= 10^-49 */
U64(0xBB127C53, 0xB17EC159), U64(0x5560C018, 0x580D5D52), /* ~= 10^-48 */
U64(0xE9D71B68, 0x9DDE71AF), U64(0xAAB8F01E, 0x6E10B4A6), /* ~= 10^-47 */
U64(0x92267121, 0x62AB070D), U64(0xCAB39613, 0x04CA70E8), /* ~= 10^-46 */
U64(0xB6B00D69, 0xBB55C8D1), U64(0x3D607B97, 0xC5FD0D22), /* ~= 10^-45 */
U64(0xE45C10C4, 0x2A2B3B05), U64(0x8CB89A7D, 0xB77C506A), /* ~= 10^-44 */
U64(0x8EB98A7A, 0x9A5B04E3), U64(0x77F3608E, 0x92ADB242), /* ~= 10^-43 */
U64(0xB267ED19, 0x40F1C61C), U64(0x55F038B2, 0x37591ED3), /* ~= 10^-42 */
U64(0xDF01E85F, 0x912E37A3), U64(0x6B6C46DE, 0xC52F6688), /* ~= 10^-41 */
U64(0x8B61313B, 0xBABCE2C6), U64(0x2323AC4B, 0x3B3DA015), /* ~= 10^-40 */
U64(0xAE397D8A, 0xA96C1B77), U64(0xABEC975E, 0x0A0D081A), /* ~= 10^-39 */
U64(0xD9C7DCED, 0x53C72255), U64(0x96E7BD35, 0x8C904A21), /* ~= 10^-38 */
U64(0x881CEA14, 0x545C7575), U64(0x7E50D641, 0x77DA2E54), /* ~= 10^-37 */
U64(0xAA242499, 0x697392D2), U64(0xDDE50BD1, 0xD5D0B9E9), /* ~= 10^-36 */
U64(0xD4AD2DBF, 0xC3D07787), U64(0x955E4EC6, 0x4B44E864), /* ~= 10^-35 */
U64(0x84EC3C97, 0xDA624AB4), U64(0xBD5AF13B, 0xEF0B113E), /* ~= 10^-34 */
U64(0xA6274BBD, 0xD0FADD61), U64(0xECB1AD8A, 0xEACDD58E), /* ~= 10^-33 */
U64(0xCFB11EAD, 0x453994BA), U64(0x67DE18ED, 0xA5814AF2), /* ~= 10^-32 */
U64(0x81CEB32C, 0x4B43FCF4), U64(0x80EACF94, 0x8770CED7), /* ~= 10^-31 */
U64(0xA2425FF7, 0x5E14FC31), U64(0xA1258379, 0xA94D028D), /* ~= 10^-30 */
U64(0xCAD2F7F5, 0x359A3B3E), U64(0x096EE458, 0x13A04330), /* ~= 10^-29 */
U64(0xFD87B5F2, 0x8300CA0D), U64(0x8BCA9D6E, 0x188853FC), /* ~= 10^-28 */
U64(0x9E74D1B7, 0x91E07E48), U64(0x775EA264, 0xCF55347D), /* ~= 10^-27 */
U64(0xC6120625, 0x76589DDA), U64(0x95364AFE, 0x032A819D), /* ~= 10^-26 */
U64(0xF79687AE, 0xD3EEC551), U64(0x3A83DDBD, 0x83F52204), /* ~= 10^-25 */
U64(0x9ABE14CD, 0x44753B52), U64(0xC4926A96, 0x72793542), /* ~= 10^-24 */
U64(0xC16D9A00, 0x95928A27), U64(0x75B7053C, 0x0F178293), /* ~= 10^-23 */
U64(0xF1C90080, 0xBAF72CB1), U64(0x5324C68B, 0x12DD6338), /* ~= 10^-22 */
U64(0x971DA050, 0x74DA7BEE), U64(0xD3F6FC16, 0xEBCA5E03), /* ~= 10^-21 */
U64(0xBCE50864, 0x92111AEA), U64(0x88F4BB1C, 0xA6BCF584), /* ~= 10^-20 */
U64(0xEC1E4A7D, 0xB69561A5), U64(0x2B31E9E3, 0xD06C32E5), /* ~= 10^-19 */
U64(0x9392EE8E, 0x921D5D07), U64(0x3AFF322E, 0x62439FCF), /* ~= 10^-18 */
U64(0xB877AA32, 0x36A4B449), U64(0x09BEFEB9, 0xFAD487C2), /* ~= 10^-17 */
U64(0xE69594BE, 0xC44DE15B), U64(0x4C2EBE68, 0x7989A9B3), /* ~= 10^-16 */
U64(0x901D7CF7, 0x3AB0ACD9), U64(0x0F9D3701, 0x4BF60A10), /* ~= 10^-15 */
U64(0xB424DC35, 0x095CD80F), U64(0x538484C1, 0x9EF38C94), /* ~= 10^-14 */
U64(0xE12E1342, 0x4BB40E13), U64(0x2865A5F2, 0x06B06FB9), /* ~= 10^-13 */
U64(0x8CBCCC09, 0x6F5088CB), U64(0xF93F87B7, 0x442E45D3), /* ~= 10^-12 */
U64(0xAFEBFF0B, 0xCB24AAFE), U64(0xF78F69A5, 0x1539D748), /* ~= 10^-11 */
U64(0xDBE6FECE, 0xBDEDD5BE), U64(0xB573440E, 0x5A884D1B), /* ~= 10^-10 */
U64(0x89705F41, 0x36B4A597), U64(0x31680A88, 0xF8953030), /* ~= 10^-9 */
U64(0xABCC7711, 0x8461CEFC), U64(0xFDC20D2B, 0x36BA7C3D), /* ~= 10^-8 */
U64(0xD6BF94D5, 0xE57A42BC), U64(0x3D329076, 0x04691B4C), /* ~= 10^-7 */
U64(0x8637BD05, 0xAF6C69B5), U64(0xA63F9A49, 0xC2C1B10F), /* ~= 10^-6 */
U64(0xA7C5AC47, 0x1B478423), U64(0x0FCF80DC, 0x33721D53), /* ~= 10^-5 */
U64(0xD1B71758, 0xE219652B), U64(0xD3C36113, 0x404EA4A8), /* ~= 10^-4 */
U64(0x83126E97, 0x8D4FDF3B), U64(0x645A1CAC, 0x083126E9), /* ~= 10^-3 */
U64(0xA3D70A3D, 0x70A3D70A), U64(0x3D70A3D7, 0x0A3D70A3), /* ~= 10^-2 */
U64(0xCCCCCCCC, 0xCCCCCCCC), U64(0xCCCCCCCC, 0xCCCCCCCC), /* ~= 10^-1 */
U64(0x80000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^0 */
U64(0xA0000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^1 */
U64(0xC8000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^2 */
U64(0xFA000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^3 */
U64(0x9C400000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^4 */
U64(0xC3500000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^5 */
U64(0xF4240000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^6 */
U64(0x98968000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^7 */
U64(0xBEBC2000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^8 */
U64(0xEE6B2800, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^9 */
U64(0x9502F900, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^10 */
U64(0xBA43B740, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^11 */
U64(0xE8D4A510, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^12 */
U64(0x9184E72A, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^13 */
U64(0xB5E620F4, 0x80000000), U64(0x00000000, 0x00000000), /* == 10^14 */
U64(0xE35FA931, 0xA0000000), U64(0x00000000, 0x00000000), /* == 10^15 */
U64(0x8E1BC9BF, 0x04000000), U64(0x00000000, 0x00000000), /* == 10^16 */
U64(0xB1A2BC2E, 0xC5000000), U64(0x00000000, 0x00000000), /* == 10^17 */
U64(0xDE0B6B3A, 0x76400000), U64(0x00000000, 0x00000000), /* == 10^18 */
U64(0x8AC72304, 0x89E80000), U64(0x00000000, 0x00000000), /* == 10^19 */
U64(0xAD78EBC5, 0xAC620000), U64(0x00000000, 0x00000000), /* == 10^20 */
U64(0xD8D726B7, 0x177A8000), U64(0x00000000, 0x00000000), /* == 10^21 */
U64(0x87867832, 0x6EAC9000), U64(0x00000000, 0x00000000), /* == 10^22 */
U64(0xA968163F, 0x0A57B400), U64(0x00000000, 0x00000000), /* == 10^23 */
U64(0xD3C21BCE, 0xCCEDA100), U64(0x00000000, 0x00000000), /* == 10^24 */
U64(0x84595161, 0x401484A0), U64(0x00000000, 0x00000000), /* == 10^25 */
U64(0xA56FA5B9, 0x9019A5C8), U64(0x00000000, 0x00000000), /* == 10^26 */
U64(0xCECB8F27, 0xF4200F3A), U64(0x00000000, 0x00000000), /* == 10^27 */
U64(0x813F3978, 0xF8940984), U64(0x40000000, 0x00000000), /* == 10^28 */
U64(0xA18F07D7, 0x36B90BE5), U64(0x50000000, 0x00000000), /* == 10^29 */
U64(0xC9F2C9CD, 0x04674EDE), U64(0xA4000000, 0x00000000), /* == 10^30 */
U64(0xFC6F7C40, 0x45812296), U64(0x4D000000, 0x00000000), /* == 10^31 */
U64(0x9DC5ADA8, 0x2B70B59D), U64(0xF0200000, 0x00000000), /* == 10^32 */
U64(0xC5371912, 0x364CE305), U64(0x6C280000, 0x00000000), /* == 10^33 */
U64(0xF684DF56, 0xC3E01BC6), U64(0xC7320000, 0x00000000), /* == 10^34 */
U64(0x9A130B96, 0x3A6C115C), U64(0x3C7F4000, 0x00000000), /* == 10^35 */
U64(0xC097CE7B, 0xC90715B3), U64(0x4B9F1000, 0x00000000), /* == 10^36 */
U64(0xF0BDC21A, 0xBB48DB20), U64(0x1E86D400, 0x00000000), /* == 10^37 */
U64(0x96769950, 0xB50D88F4), U64(0x13144480, 0x00000000), /* == 10^38 */
U64(0xBC143FA4, 0xE250EB31), U64(0x17D955A0, 0x00000000), /* == 10^39 */
U64(0xEB194F8E, 0x1AE525FD), U64(0x5DCFAB08, 0x00000000), /* == 10^40 */
U64(0x92EFD1B8, 0xD0CF37BE), U64(0x5AA1CAE5, 0x00000000), /* == 10^41 */
U64(0xB7ABC627, 0x050305AD), U64(0xF14A3D9E, 0x40000000), /* == 10^42 */
U64(0xE596B7B0, 0xC643C719), U64(0x6D9CCD05, 0xD0000000), /* == 10^43 */
U64(0x8F7E32CE, 0x7BEA5C6F), U64(0xE4820023, 0xA2000000), /* == 10^44 */
U64(0xB35DBF82, 0x1AE4F38B), U64(0xDDA2802C, 0x8A800000), /* == 10^45 */
U64(0xE0352F62, 0xA19E306E), U64(0xD50B2037, 0xAD200000), /* == 10^46 */
U64(0x8C213D9D, 0xA502DE45), U64(0x4526F422, 0xCC340000), /* == 10^47 */
U64(0xAF298D05, 0x0E4395D6), U64(0x9670B12B, 0x7F410000), /* == 10^48 */
U64(0xDAF3F046, 0x51D47B4C), U64(0x3C0CDD76, 0x5F114000), /* == 10^49 */
U64(0x88D8762B, 0xF324CD0F), U64(0xA5880A69, 0xFB6AC800), /* == 10^50 */
U64(0xAB0E93B6, 0xEFEE0053), U64(0x8EEA0D04, 0x7A457A00), /* == 10^51 */
U64(0xD5D238A4, 0xABE98068), U64(0x72A49045, 0x98D6D880), /* == 10^52 */
U64(0x85A36366, 0xEB71F041), U64(0x47A6DA2B, 0x7F864750), /* == 10^53 */
U64(0xA70C3C40, 0xA64E6C51), U64(0x999090B6, 0x5F67D924), /* == 10^54 */
U64(0xD0CF4B50, 0xCFE20765), U64(0xFFF4B4E3, 0xF741CF6D), /* == 10^55 */
U64(0x82818F12, 0x81ED449F), U64(0xBFF8F10E, 0x7A8921A4), /* ~= 10^56 */
U64(0xA321F2D7, 0x226895C7), U64(0xAFF72D52, 0x192B6A0D), /* ~= 10^57 */
U64(0xCBEA6F8C, 0xEB02BB39), U64(0x9BF4F8A6, 0x9F764490), /* ~= 10^58 */
U64(0xFEE50B70, 0x25C36A08), U64(0x02F236D0, 0x4753D5B4), /* ~= 10^59 */
U64(0x9F4F2726, 0x179A2245), U64(0x01D76242, 0x2C946590), /* ~= 10^60 */
U64(0xC722F0EF, 0x9D80AAD6), U64(0x424D3AD2, 0xB7B97EF5), /* ~= 10^61 */
U64(0xF8EBAD2B, 0x84E0D58B), U64(0xD2E08987, 0x65A7DEB2), /* ~= 10^62 */
U64(0x9B934C3B, 0x330C8577), U64(0x63CC55F4, 0x9F88EB2F), /* ~= 10^63 */
U64(0xC2781F49, 0xFFCFA6D5), U64(0x3CBF6B71, 0xC76B25FB), /* ~= 10^64 */
U64(0xF316271C, 0x7FC3908A), U64(0x8BEF464E, 0x3945EF7A), /* ~= 10^65 */
U64(0x97EDD871, 0xCFDA3A56), U64(0x97758BF0, 0xE3CBB5AC), /* ~= 10^66 */
U64(0xBDE94E8E, 0x43D0C8EC), U64(0x3D52EEED, 0x1CBEA317), /* ~= 10^67 */
U64(0xED63A231, 0xD4C4FB27), U64(0x4CA7AAA8, 0x63EE4BDD), /* ~= 10^68 */
U64(0x945E455F, 0x24FB1CF8), U64(0x8FE8CAA9, 0x3E74EF6A), /* ~= 10^69 */
U64(0xB975D6B6, 0xEE39E436), U64(0xB3E2FD53, 0x8E122B44), /* ~= 10^70 */
U64(0xE7D34C64, 0xA9C85D44), U64(0x60DBBCA8, 0x7196B616), /* ~= 10^71 */
U64(0x90E40FBE, 0xEA1D3A4A), U64(0xBC8955E9, 0x46FE31CD), /* ~= 10^72 */
U64(0xB51D13AE, 0xA4A488DD), U64(0x6BABAB63, 0x98BDBE41), /* ~= 10^73 */
U64(0xE264589A, 0x4DCDAB14), U64(0xC696963C, 0x7EED2DD1), /* ~= 10^74 */
U64(0x8D7EB760, 0x70A08AEC), U64(0xFC1E1DE5, 0xCF543CA2), /* ~= 10^75 */
U64(0xB0DE6538, 0x8CC8ADA8), U64(0x3B25A55F, 0x43294BCB), /* ~= 10^76 */
U64(0xDD15FE86, 0xAFFAD912), U64(0x49EF0EB7, 0x13F39EBE), /* ~= 10^77 */
U64(0x8A2DBF14, 0x2DFCC7AB), U64(0x6E356932, 0x6C784337), /* ~= 10^78 */
U64(0xACB92ED9, 0x397BF996), U64(0x49C2C37F, 0x07965404), /* ~= 10^79 */
U64(0xD7E77A8F, 0x87DAF7FB), U64(0xDC33745E, 0xC97BE906), /* ~= 10^80 */
U64(0x86F0AC99, 0xB4E8DAFD), U64(0x69A028BB, 0x3DED71A3), /* ~= 10^81 */
U64(0xA8ACD7C0, 0x222311BC), U64(0xC40832EA, 0x0D68CE0C), /* ~= 10^82 */
U64(0xD2D80DB0, 0x2AABD62B), U64(0xF50A3FA4, 0x90C30190), /* ~= 10^83 */
U64(0x83C7088E, 0x1AAB65DB), U64(0x792667C6, 0xDA79E0FA), /* ~= 10^84 */
U64(0xA4B8CAB1, 0xA1563F52), U64(0x577001B8, 0x91185938), /* ~= 10^85 */
U64(0xCDE6FD5E, 0x09ABCF26), U64(0xED4C0226, 0xB55E6F86), /* ~= 10^86 */
U64(0x80B05E5A, 0xC60B6178), U64(0x544F8158, 0x315B05B4), /* ~= 10^87 */
U64(0xA0DC75F1, 0x778E39D6), U64(0x696361AE, 0x3DB1C721), /* ~= 10^88 */
U64(0xC913936D, 0xD571C84C), U64(0x03BC3A19, 0xCD1E38E9), /* ~= 10^89 */
U64(0xFB587849, 0x4ACE3A5F), U64(0x04AB48A0, 0x4065C723), /* ~= 10^90 */
U64(0x9D174B2D, 0xCEC0E47B), U64(0x62EB0D64, 0x283F9C76), /* ~= 10^91 */
U64(0xC45D1DF9, 0x42711D9A), U64(0x3BA5D0BD, 0x324F8394), /* ~= 10^92 */
U64(0xF5746577, 0x930D6500), U64(0xCA8F44EC, 0x7EE36479), /* ~= 10^93 */
U64(0x9968BF6A, 0xBBE85F20), U64(0x7E998B13, 0xCF4E1ECB), /* ~= 10^94 */
U64(0xBFC2EF45, 0x6AE276E8), U64(0x9E3FEDD8, 0xC321A67E), /* ~= 10^95 */
U64(0xEFB3AB16, 0xC59B14A2), U64(0xC5CFE94E, 0xF3EA101E), /* ~= 10^96 */
U64(0x95D04AEE, 0x3B80ECE5), U64(0xBBA1F1D1, 0x58724A12), /* ~= 10^97 */
U64(0xBB445DA9, 0xCA61281F), U64(0x2A8A6E45, 0xAE8EDC97), /* ~= 10^98 */
U64(0xEA157514, 0x3CF97226), U64(0xF52D09D7, 0x1A3293BD), /* ~= 10^99 */
U64(0x924D692C, 0xA61BE758), U64(0x593C2626, 0x705F9C56), /* ~= 10^100 */
U64(0xB6E0C377, 0xCFA2E12E), U64(0x6F8B2FB0, 0x0C77836C), /* ~= 10^101 */
U64(0xE498F455, 0xC38B997A), U64(0x0B6DFB9C, 0x0F956447), /* ~= 10^102 */
U64(0x8EDF98B5, 0x9A373FEC), U64(0x4724BD41, 0x89BD5EAC), /* ~= 10^103 */
U64(0xB2977EE3, 0x00C50FE7), U64(0x58EDEC91, 0xEC2CB657), /* ~= 10^104 */
U64(0xDF3D5E9B, 0xC0F653E1), U64(0x2F2967B6, 0x6737E3ED), /* ~= 10^105 */
U64(0x8B865B21, 0x5899F46C), U64(0xBD79E0D2, 0x0082EE74), /* ~= 10^106 */
U64(0xAE67F1E9, 0xAEC07187), U64(0xECD85906, 0x80A3AA11), /* ~= 10^107 */
U64(0xDA01EE64, 0x1A708DE9), U64(0xE80E6F48, 0x20CC9495), /* ~= 10^108 */
U64(0x884134FE, 0x908658B2), U64(0x3109058D, 0x147FDCDD), /* ~= 10^109 */
U64(0xAA51823E, 0x34A7EEDE), U64(0xBD4B46F0, 0x599FD415), /* ~= 10^110 */
U64(0xD4E5E2CD, 0xC1D1EA96), U64(0x6C9E18AC, 0x7007C91A), /* ~= 10^111 */
U64(0x850FADC0, 0x9923329E), U64(0x03E2CF6B, 0xC604DDB0), /* ~= 10^112 */
U64(0xA6539930, 0xBF6BFF45), U64(0x84DB8346, 0xB786151C), /* ~= 10^113 */
U64(0xCFE87F7C, 0xEF46FF16), U64(0xE6126418, 0x65679A63), /* ~= 10^114 */
U64(0x81F14FAE, 0x158C5F6E), U64(0x4FCB7E8F, 0x3F60C07E), /* ~= 10^115 */
U64(0xA26DA399, 0x9AEF7749), U64(0xE3BE5E33, 0x0F38F09D), /* ~= 10^116 */
U64(0xCB090C80, 0x01AB551C), U64(0x5CADF5BF, 0xD3072CC5), /* ~= 10^117 */
U64(0xFDCB4FA0, 0x02162A63), U64(0x73D9732F, 0xC7C8F7F6), /* ~= 10^118 */
U64(0x9E9F11C4, 0x014DDA7E), U64(0x2867E7FD, 0xDCDD9AFA), /* ~= 10^119 */
U64(0xC646D635, 0x01A1511D), U64(0xB281E1FD, 0x541501B8), /* ~= 10^120 */
U64(0xF7D88BC2, 0x4209A565), U64(0x1F225A7C, 0xA91A4226), /* ~= 10^121 */
U64(0x9AE75759, 0x6946075F), U64(0x3375788D, 0xE9B06958), /* ~= 10^122 */
U64(0xC1A12D2F, 0xC3978937), U64(0x0052D6B1, 0x641C83AE), /* ~= 10^123 */
U64(0xF209787B, 0xB47D6B84), U64(0xC0678C5D, 0xBD23A49A), /* ~= 10^124 */
U64(0x9745EB4D, 0x50CE6332), U64(0xF840B7BA, 0x963646E0), /* ~= 10^125 */
U64(0xBD176620, 0xA501FBFF), U64(0xB650E5A9, 0x3BC3D898), /* ~= 10^126 */
U64(0xEC5D3FA8, 0xCE427AFF), U64(0xA3E51F13, 0x8AB4CEBE), /* ~= 10^127 */
U64(0x93BA47C9, 0x80E98CDF), U64(0xC66F336C, 0x36B10137), /* ~= 10^128 */
U64(0xB8A8D9BB, 0xE123F017), U64(0xB80B0047, 0x445D4184), /* ~= 10^129 */
U64(0xE6D3102A, 0xD96CEC1D), U64(0xA60DC059, 0x157491E5), /* ~= 10^130 */
U64(0x9043EA1A, 0xC7E41392), U64(0x87C89837, 0xAD68DB2F), /* ~= 10^131 */
U64(0xB454E4A1, 0x79DD1877), U64(0x29BABE45, 0x98C311FB), /* ~= 10^132 */
U64(0xE16A1DC9, 0xD8545E94), U64(0xF4296DD6, 0xFEF3D67A), /* ~= 10^133 */
U64(0x8CE2529E, 0x2734BB1D), U64(0x1899E4A6, 0x5F58660C), /* ~= 10^134 */
U64(0xB01AE745, 0xB101E9E4), U64(0x5EC05DCF, 0xF72E7F8F), /* ~= 10^135 */
U64(0xDC21A117, 0x1D42645D), U64(0x76707543, 0xF4FA1F73), /* ~= 10^136 */
U64(0x899504AE, 0x72497EBA), U64(0x6A06494A, 0x791C53A8), /* ~= 10^137 */
U64(0xABFA45DA, 0x0EDBDE69), U64(0x0487DB9D, 0x17636892), /* ~= 10^138 */
U64(0xD6F8D750, 0x9292D603), U64(0x45A9D284, 0x5D3C42B6), /* ~= 10^139 */
U64(0x865B8692, 0x5B9BC5C2), U64(0x0B8A2392, 0xBA45A9B2), /* ~= 10^140 */
U64(0xA7F26836, 0xF282B732), U64(0x8E6CAC77, 0x68D7141E), /* ~= 10^141 */
U64(0xD1EF0244, 0xAF2364FF), U64(0x3207D795, 0x430CD926), /* ~= 10^142 */
U64(0x8335616A, 0xED761F1F), U64(0x7F44E6BD, 0x49E807B8), /* ~= 10^143 */
U64(0xA402B9C5, 0xA8D3A6E7), U64(0x5F16206C, 0x9C6209A6), /* ~= 10^144 */
U64(0xCD036837, 0x130890A1), U64(0x36DBA887, 0xC37A8C0F), /* ~= 10^145 */
U64(0x80222122, 0x6BE55A64), U64(0xC2494954, 0xDA2C9789), /* ~= 10^146 */
U64(0xA02AA96B, 0x06DEB0FD), U64(0xF2DB9BAA, 0x10B7BD6C), /* ~= 10^147 */
U64(0xC83553C5, 0xC8965D3D), U64(0x6F928294, 0x94E5ACC7), /* ~= 10^148 */
U64(0xFA42A8B7, 0x3ABBF48C), U64(0xCB772339, 0xBA1F17F9), /* ~= 10^149 */
U64(0x9C69A972, 0x84B578D7), U64(0xFF2A7604, 0x14536EFB), /* ~= 10^150 */
U64(0xC38413CF, 0x25E2D70D), U64(0xFEF51385, 0x19684ABA), /* ~= 10^151 */
U64(0xF46518C2, 0xEF5B8CD1), U64(0x7EB25866, 0x5FC25D69), /* ~= 10^152 */
U64(0x98BF2F79, 0xD5993802), U64(0xEF2F773F, 0xFBD97A61), /* ~= 10^153 */
U64(0xBEEEFB58, 0x4AFF8603), U64(0xAAFB550F, 0xFACFD8FA), /* ~= 10^154 */
U64(0xEEAABA2E, 0x5DBF6784), U64(0x95BA2A53, 0xF983CF38), /* ~= 10^155 */
U64(0x952AB45C, 0xFA97A0B2), U64(0xDD945A74, 0x7BF26183), /* ~= 10^156 */
U64(0xBA756174, 0x393D88DF), U64(0x94F97111, 0x9AEEF9E4), /* ~= 10^157 */
U64(0xE912B9D1, 0x478CEB17), U64(0x7A37CD56, 0x01AAB85D), /* ~= 10^158 */
U64(0x91ABB422, 0xCCB812EE), U64(0xAC62E055, 0xC10AB33A), /* ~= 10^159 */
U64(0xB616A12B, 0x7FE617AA), U64(0x577B986B, 0x314D6009), /* ~= 10^160 */
U64(0xE39C4976, 0x5FDF9D94), U64(0xED5A7E85, 0xFDA0B80B), /* ~= 10^161 */
U64(0x8E41ADE9, 0xFBEBC27D), U64(0x14588F13, 0xBE847307), /* ~= 10^162 */
U64(0xB1D21964, 0x7AE6B31C), U64(0x596EB2D8, 0xAE258FC8), /* ~= 10^163 */
U64(0xDE469FBD, 0x99A05FE3), U64(0x6FCA5F8E, 0xD9AEF3BB), /* ~= 10^164 */
U64(0x8AEC23D6, 0x80043BEE), U64(0x25DE7BB9, 0x480D5854), /* ~= 10^165 */
U64(0xADA72CCC, 0x20054AE9), U64(0xAF561AA7, 0x9A10AE6A), /* ~= 10^166 */
U64(0xD910F7FF, 0x28069DA4), U64(0x1B2BA151, 0x8094DA04), /* ~= 10^167 */
U64(0x87AA9AFF, 0x79042286), U64(0x90FB44D2, 0xF05D0842), /* ~= 10^168 */
U64(0xA99541BF, 0x57452B28), U64(0x353A1607, 0xAC744A53), /* ~= 10^169 */
U64(0xD3FA922F, 0x2D1675F2), U64(0x42889B89, 0x97915CE8), /* ~= 10^170 */
U64(0x847C9B5D, 0x7C2E09B7), U64(0x69956135, 0xFEBADA11), /* ~= 10^171 */
U64(0xA59BC234, 0xDB398C25), U64(0x43FAB983, 0x7E699095), /* ~= 10^172 */
U64(0xCF02B2C2, 0x1207EF2E), U64(0x94F967E4, 0x5E03F4BB), /* ~= 10^173 */
U64(0x8161AFB9, 0x4B44F57D), U64(0x1D1BE0EE, 0xBAC278F5), /* ~= 10^174 */
U64(0xA1BA1BA7, 0x9E1632DC), U64(0x6462D92A, 0x69731732), /* ~= 10^175 */
U64(0xCA28A291, 0x859BBF93), U64(0x7D7B8F75, 0x03CFDCFE), /* ~= 10^176 */
U64(0xFCB2CB35, 0xE702AF78), U64(0x5CDA7352, 0x44C3D43E), /* ~= 10^177 */
U64(0x9DEFBF01, 0xB061ADAB), U64(0x3A088813, 0x6AFA64A7), /* ~= 10^178 */
U64(0xC56BAEC2, 0x1C7A1916), U64(0x088AAA18, 0x45B8FDD0), /* ~= 10^179 */
U64(0xF6C69A72, 0xA3989F5B), U64(0x8AAD549E, 0x57273D45), /* ~= 10^180 */
U64(0x9A3C2087, 0xA63F6399), U64(0x36AC54E2, 0xF678864B), /* ~= 10^181 */
U64(0xC0CB28A9, 0x8FCF3C7F), U64(0x84576A1B, 0xB416A7DD), /* ~= 10^182 */
U64(0xF0FDF2D3, 0xF3C30B9F), U64(0x656D44A2, 0xA11C51D5), /* ~= 10^183 */
U64(0x969EB7C4, 0x7859E743), U64(0x9F644AE5, 0xA4B1B325), /* ~= 10^184 */
U64(0xBC4665B5, 0x96706114), U64(0x873D5D9F, 0x0DDE1FEE), /* ~= 10^185 */
U64(0xEB57FF22, 0xFC0C7959), U64(0xA90CB506, 0xD155A7EA), /* ~= 10^186 */
U64(0x9316FF75, 0xDD87CBD8), U64(0x09A7F124, 0x42D588F2), /* ~= 10^187 */
U64(0xB7DCBF53, 0x54E9BECE), U64(0x0C11ED6D, 0x538AEB2F), /* ~= 10^188 */
U64(0xE5D3EF28, 0x2A242E81), U64(0x8F1668C8, 0xA86DA5FA), /* ~= 10^189 */
U64(0x8FA47579, 0x1A569D10), U64(0xF96E017D, 0x694487BC), /* ~= 10^190 */
U64(0xB38D92D7, 0x60EC4455), U64(0x37C981DC, 0xC395A9AC), /* ~= 10^191 */
U64(0xE070F78D, 0x3927556A), U64(0x85BBE253, 0xF47B1417), /* ~= 10^192 */
U64(0x8C469AB8, 0x43B89562), U64(0x93956D74, 0x78CCEC8E), /* ~= 10^193 */
U64(0xAF584166, 0x54A6BABB), U64(0x387AC8D1, 0x970027B2), /* ~= 10^194 */
U64(0xDB2E51BF, 0xE9D0696A), U64(0x06997B05, 0xFCC0319E), /* ~= 10^195 */
U64(0x88FCF317, 0xF22241E2), U64(0x441FECE3, 0xBDF81F03), /* ~= 10^196 */
U64(0xAB3C2FDD, 0xEEAAD25A), U64(0xD527E81C, 0xAD7626C3), /* ~= 10^197 */
U64(0xD60B3BD5, 0x6A5586F1), U64(0x8A71E223, 0xD8D3B074), /* ~= 10^198 */
U64(0x85C70565, 0x62757456), U64(0xF6872D56, 0x67844E49), /* ~= 10^199 */
U64(0xA738C6BE, 0xBB12D16C), U64(0xB428F8AC, 0x016561DB), /* ~= 10^200 */
U64(0xD106F86E, 0x69D785C7), U64(0xE13336D7, 0x01BEBA52), /* ~= 10^201 */
U64(0x82A45B45, 0x0226B39C), U64(0xECC00246, 0x61173473), /* ~= 10^202 */
U64(0xA34D7216, 0x42B06084), U64(0x27F002D7, 0xF95D0190), /* ~= 10^203 */
U64(0xCC20CE9B, 0xD35C78A5), U64(0x31EC038D, 0xF7B441F4), /* ~= 10^204 */
U64(0xFF290242, 0xC83396CE), U64(0x7E670471, 0x75A15271), /* ~= 10^205 */
U64(0x9F79A169, 0xBD203E41), U64(0x0F0062C6, 0xE984D386), /* ~= 10^206 */
U64(0xC75809C4, 0x2C684DD1), U64(0x52C07B78, 0xA3E60868), /* ~= 10^207 */
U64(0xF92E0C35, 0x37826145), U64(0xA7709A56, 0xCCDF8A82), /* ~= 10^208 */
U64(0x9BBCC7A1, 0x42B17CCB), U64(0x88A66076, 0x400BB691), /* ~= 10^209 */
U64(0xC2ABF989, 0x935DDBFE), U64(0x6ACFF893, 0xD00EA435), /* ~= 10^210 */
U64(0xF356F7EB, 0xF83552FE), U64(0x0583F6B8, 0xC4124D43), /* ~= 10^211 */
U64(0x98165AF3, 0x7B2153DE), U64(0xC3727A33, 0x7A8B704A), /* ~= 10^212 */
U64(0xBE1BF1B0, 0x59E9A8D6), U64(0x744F18C0, 0x592E4C5C), /* ~= 10^213 */
U64(0xEDA2EE1C, 0x7064130C), U64(0x1162DEF0, 0x6F79DF73), /* ~= 10^214 */
U64(0x9485D4D1, 0xC63E8BE7), U64(0x8ADDCB56, 0x45AC2BA8), /* ~= 10^215 */
U64(0xB9A74A06, 0x37CE2EE1), U64(0x6D953E2B, 0xD7173692), /* ~= 10^216 */
U64(0xE8111C87, 0xC5C1BA99), U64(0xC8FA8DB6, 0xCCDD0437), /* ~= 10^217 */
U64(0x910AB1D4, 0xDB9914A0), U64(0x1D9C9892, 0x400A22A2), /* ~= 10^218 */
U64(0xB54D5E4A, 0x127F59C8), U64(0x2503BEB6, 0xD00CAB4B), /* ~= 10^219 */
U64(0xE2A0B5DC, 0x971F303A), U64(0x2E44AE64, 0x840FD61D), /* ~= 10^220 */
U64(0x8DA471A9, 0xDE737E24), U64(0x5CEAECFE, 0xD289E5D2), /* ~= 10^221 */
U64(0xB10D8E14, 0x56105DAD), U64(0x7425A83E, 0x872C5F47), /* ~= 10^222 */
U64(0xDD50F199, 0x6B947518), U64(0xD12F124E, 0x28F77719), /* ~= 10^223 */
U64(0x8A5296FF, 0xE33CC92F), U64(0x82BD6B70, 0xD99AAA6F), /* ~= 10^224 */
U64(0xACE73CBF, 0xDC0BFB7B), U64(0x636CC64D, 0x1001550B), /* ~= 10^225 */
U64(0xD8210BEF, 0xD30EFA5A), U64(0x3C47F7E0, 0x5401AA4E), /* ~= 10^226 */
U64(0x8714A775, 0xE3E95C78), U64(0x65ACFAEC, 0x34810A71), /* ~= 10^227 */
U64(0xA8D9D153, 0x5CE3B396), U64(0x7F1839A7, 0x41A14D0D), /* ~= 10^228 */
U64(0xD31045A8, 0x341CA07C), U64(0x1EDE4811, 0x1209A050), /* ~= 10^229 */
U64(0x83EA2B89, 0x2091E44D), U64(0x934AED0A, 0xAB460432), /* ~= 10^230 */
U64(0xA4E4B66B, 0x68B65D60), U64(0xF81DA84D, 0x5617853F), /* ~= 10^231 */
U64(0xCE1DE406, 0x42E3F4B9), U64(0x36251260, 0xAB9D668E), /* ~= 10^232 */
U64(0x80D2AE83, 0xE9CE78F3), U64(0xC1D72B7C, 0x6B426019), /* ~= 10^233 */
U64(0xA1075A24, 0xE4421730), U64(0xB24CF65B, 0x8612F81F), /* ~= 10^234 */
U64(0xC94930AE, 0x1D529CFC), U64(0xDEE033F2, 0x6797B627), /* ~= 10^235 */
U64(0xFB9B7CD9, 0xA4A7443C), U64(0x169840EF, 0x017DA3B1), /* ~= 10^236 */
U64(0x9D412E08, 0x06E88AA5), U64(0x8E1F2895, 0x60EE864E), /* ~= 10^237 */
U64(0xC491798A, 0x08A2AD4E), U64(0xF1A6F2BA, 0xB92A27E2), /* ~= 10^238 */
U64(0xF5B5D7EC, 0x8ACB58A2), U64(0xAE10AF69, 0x6774B1DB), /* ~= 10^239 */
U64(0x9991A6F3, 0xD6BF1765), U64(0xACCA6DA1, 0xE0A8EF29), /* ~= 10^240 */
U64(0xBFF610B0, 0xCC6EDD3F), U64(0x17FD090A, 0x58D32AF3), /* ~= 10^241 */
U64(0xEFF394DC, 0xFF8A948E), U64(0xDDFC4B4C, 0xEF07F5B0), /* ~= 10^242 */
U64(0x95F83D0A, 0x1FB69CD9), U64(0x4ABDAF10, 0x1564F98E), /* ~= 10^243 */
U64(0xBB764C4C, 0xA7A4440F), U64(0x9D6D1AD4, 0x1ABE37F1), /* ~= 10^244 */
U64(0xEA53DF5F, 0xD18D5513), U64(0x84C86189, 0x216DC5ED), /* ~= 10^245 */
U64(0x92746B9B, 0xE2F8552C), U64(0x32FD3CF5, 0xB4E49BB4), /* ~= 10^246 */
U64(0xB7118682, 0xDBB66A77), U64(0x3FBC8C33, 0x221DC2A1), /* ~= 10^247 */
U64(0xE4D5E823, 0x92A40515), U64(0x0FABAF3F, 0xEAA5334A), /* ~= 10^248 */
U64(0x8F05B116, 0x3BA6832D), U64(0x29CB4D87, 0xF2A7400E), /* ~= 10^249 */
U64(0xB2C71D5B, 0xCA9023F8), U64(0x743E20E9, 0xEF511012), /* ~= 10^250 */
U64(0xDF78E4B2, 0xBD342CF6), U64(0x914DA924, 0x6B255416), /* ~= 10^251 */
U64(0x8BAB8EEF, 0xB6409C1A), U64(0x1AD089B6, 0xC2F7548E), /* ~= 10^252 */
U64(0xAE9672AB, 0xA3D0C320), U64(0xA184AC24, 0x73B529B1), /* ~= 10^253 */
U64(0xDA3C0F56, 0x8CC4F3E8), U64(0xC9E5D72D, 0x90A2741E), /* ~= 10^254 */
U64(0x88658996, 0x17FB1871), U64(0x7E2FA67C, 0x7A658892), /* ~= 10^255 */
U64(0xAA7EEBFB, 0x9DF9DE8D), U64(0xDDBB901B, 0x98FEEAB7), /* ~= 10^256 */
U64(0xD51EA6FA, 0x85785631), U64(0x552A7422, 0x7F3EA565), /* ~= 10^257 */
U64(0x8533285C, 0x936B35DE), U64(0xD53A8895, 0x8F87275F), /* ~= 10^258 */
U64(0xA67FF273, 0xB8460356), U64(0x8A892ABA, 0xF368F137), /* ~= 10^259 */
U64(0xD01FEF10, 0xA657842C), U64(0x2D2B7569, 0xB0432D85), /* ~= 10^260 */
U64(0x8213F56A, 0x67F6B29B), U64(0x9C3B2962, 0x0E29FC73), /* ~= 10^261 */
U64(0xA298F2C5, 0x01F45F42), U64(0x8349F3BA, 0x91B47B8F), /* ~= 10^262 */
U64(0xCB3F2F76, 0x42717713), U64(0x241C70A9, 0x36219A73), /* ~= 10^263 */
U64(0xFE0EFB53, 0xD30DD4D7), U64(0xED238CD3, 0x83AA0110), /* ~= 10^264 */
U64(0x9EC95D14, 0x63E8A506), U64(0xF4363804, 0x324A40AA), /* ~= 10^265 */
U64(0xC67BB459, 0x7CE2CE48), U64(0xB143C605, 0x3EDCD0D5), /* ~= 10^266 */
U64(0xF81AA16F, 0xDC1B81DA), U64(0xDD94B786, 0x8E94050A), /* ~= 10^267 */
U64(0x9B10A4E5, 0xE9913128), U64(0xCA7CF2B4, 0x191C8326), /* ~= 10^268 */
U64(0xC1D4CE1F, 0x63F57D72), U64(0xFD1C2F61, 0x1F63A3F0), /* ~= 10^269 */
U64(0xF24A01A7, 0x3CF2DCCF), U64(0xBC633B39, 0x673C8CEC), /* ~= 10^270 */
U64(0x976E4108, 0x8617CA01), U64(0xD5BE0503, 0xE085D813), /* ~= 10^271 */
U64(0xBD49D14A, 0xA79DBC82), U64(0x4B2D8644, 0xD8A74E18), /* ~= 10^272 */
U64(0xEC9C459D, 0x51852BA2), U64(0xDDF8E7D6, 0x0ED1219E), /* ~= 10^273 */
U64(0x93E1AB82, 0x52F33B45), U64(0xCABB90E5, 0xC942B503), /* ~= 10^274 */
U64(0xB8DA1662, 0xE7B00A17), U64(0x3D6A751F, 0x3B936243), /* ~= 10^275 */
U64(0xE7109BFB, 0xA19C0C9D), U64(0x0CC51267, 0x0A783AD4), /* ~= 10^276 */
U64(0x906A617D, 0x450187E2), U64(0x27FB2B80, 0x668B24C5), /* ~= 10^277 */
U64(0xB484F9DC, 0x9641E9DA), U64(0xB1F9F660, 0x802DEDF6), /* ~= 10^278 */
U64(0xE1A63853, 0xBBD26451), U64(0x5E7873F8, 0xA0396973), /* ~= 10^279 */
U64(0x8D07E334, 0x55637EB2), U64(0xDB0B487B, 0x6423E1E8), /* ~= 10^280 */
U64(0xB049DC01, 0x6ABC5E5F), U64(0x91CE1A9A, 0x3D2CDA62), /* ~= 10^281 */
U64(0xDC5C5301, 0xC56B75F7), U64(0x7641A140, 0xCC7810FB), /* ~= 10^282 */
U64(0x89B9B3E1, 0x1B6329BA), U64(0xA9E904C8, 0x7FCB0A9D), /* ~= 10^283 */
U64(0xAC2820D9, 0x623BF429), U64(0x546345FA, 0x9FBDCD44), /* ~= 10^284 */
U64(0xD732290F, 0xBACAF133), U64(0xA97C1779, 0x47AD4095), /* ~= 10^285 */
U64(0x867F59A9, 0xD4BED6C0), U64(0x49ED8EAB, 0xCCCC485D), /* ~= 10^286 */
U64(0xA81F3014, 0x49EE8C70), U64(0x5C68F256, 0xBFFF5A74), /* ~= 10^287 */
U64(0xD226FC19, 0x5C6A2F8C), U64(0x73832EEC, 0x6FFF3111), /* ~= 10^288 */
U64(0x83585D8F, 0xD9C25DB7), U64(0xC831FD53, 0xC5FF7EAB), /* ~= 10^289 */
U64(0xA42E74F3, 0xD032F525), U64(0xBA3E7CA8, 0xB77F5E55), /* ~= 10^290 */
U64(0xCD3A1230, 0xC43FB26F), U64(0x28CE1BD2, 0xE55F35EB), /* ~= 10^291 */
U64(0x80444B5E, 0x7AA7CF85), U64(0x7980D163, 0xCF5B81B3), /* ~= 10^292 */
U64(0xA0555E36, 0x1951C366), U64(0xD7E105BC, 0xC332621F), /* ~= 10^293 */
U64(0xC86AB5C3, 0x9FA63440), U64(0x8DD9472B, 0xF3FEFAA7), /* ~= 10^294 */
U64(0xFA856334, 0x878FC150), U64(0xB14F98F6, 0xF0FEB951), /* ~= 10^295 */
U64(0x9C935E00, 0xD4B9D8D2), U64(0x6ED1BF9A, 0x569F33D3), /* ~= 10^296 */
U64(0xC3B83581, 0x09E84F07), U64(0x0A862F80, 0xEC4700C8), /* ~= 10^297 */
U64(0xF4A642E1, 0x4C6262C8), U64(0xCD27BB61, 0x2758C0FA), /* ~= 10^298 */
U64(0x98E7E9CC, 0xCFBD7DBD), U64(0x8038D51C, 0xB897789C), /* ~= 10^299 */
U64(0xBF21E440, 0x03ACDD2C), U64(0xE0470A63, 0xE6BD56C3), /* ~= 10^300 */
U64(0xEEEA5D50, 0x04981478), U64(0x1858CCFC, 0xE06CAC74), /* ~= 10^301 */
U64(0x95527A52, 0x02DF0CCB), U64(0x0F37801E, 0x0C43EBC8), /* ~= 10^302 */
U64(0xBAA718E6, 0x8396CFFD), U64(0xD3056025, 0x8F54E6BA), /* ~= 10^303 */
U64(0xE950DF20, 0x247C83FD), U64(0x47C6B82E, 0xF32A2069), /* ~= 10^304 */
U64(0x91D28B74, 0x16CDD27E), U64(0x4CDC331D, 0x57FA5441), /* ~= 10^305 */
U64(0xB6472E51, 0x1C81471D), U64(0xE0133FE4, 0xADF8E952), /* ~= 10^306 */
U64(0xE3D8F9E5, 0x63A198E5), U64(0x58180FDD, 0xD97723A6), /* ~= 10^307 */
U64(0x8E679C2F, 0x5E44FF8F), U64(0x570F09EA, 0xA7EA7648), /* ~= 10^308 */
U64(0xB201833B, 0x35D63F73), U64(0x2CD2CC65, 0x51E513DA), /* ~= 10^309 */
U64(0xDE81E40A, 0x034BCF4F), U64(0xF8077F7E, 0xA65E58D1), /* ~= 10^310 */
U64(0x8B112E86, 0x420F6191), U64(0xFB04AFAF, 0x27FAF782), /* ~= 10^311 */
U64(0xADD57A27, 0xD29339F6), U64(0x79C5DB9A, 0xF1F9B563), /* ~= 10^312 */
U64(0xD94AD8B1, 0xC7380874), U64(0x18375281, 0xAE7822BC), /* ~= 10^313 */
U64(0x87CEC76F, 0x1C830548), U64(0x8F229391, 0x0D0B15B5), /* ~= 10^314 */
U64(0xA9C2794A, 0xE3A3C69A), U64(0xB2EB3875, 0x504DDB22), /* ~= 10^315 */
U64(0xD433179D, 0x9C8CB841), U64(0x5FA60692, 0xA46151EB), /* ~= 10^316 */
U64(0x849FEEC2, 0x81D7F328), U64(0xDBC7C41B, 0xA6BCD333), /* ~= 10^317 */
U64(0xA5C7EA73, 0x224DEFF3), U64(0x12B9B522, 0x906C0800), /* ~= 10^318 */
U64(0xCF39E50F, 0xEAE16BEF), U64(0xD768226B, 0x34870A00), /* ~= 10^319 */
U64(0x81842F29, 0xF2CCE375), U64(0xE6A11583, 0x00D46640), /* ~= 10^320 */
U64(0xA1E53AF4, 0x6F801C53), U64(0x60495AE3, 0xC1097FD0), /* ~= 10^321 */
U64(0xCA5E89B1, 0x8B602368), U64(0x385BB19C, 0xB14BDFC4), /* ~= 10^322 */
U64(0xFCF62C1D, 0xEE382C42), U64(0x46729E03, 0xDD9ED7B5), /* ~= 10^323 */
U64(0x9E19DB92, 0xB4E31BA9), U64(0x6C07A2C2, 0x6A8346D1) /* ~= 10^324 */
};
/**
Get the cached pow10 value from pow10_sig_table.
@param exp10 The exponent of pow(10, e). This value must in range
POW10_SIG_TABLE_MIN_EXP to POW10_SIG_TABLE_MAX_EXP.
@param hi The highest 64 bits of pow(10, e).
@param lo The lower 64 bits after `hi`.
*/
static_inline void pow10_table_get_sig(i32 exp10, u64 *hi, u64 *lo) {
i32 idx = exp10 - (POW10_SIG_TABLE_MIN_EXP);
*hi = pow10_sig_table[idx * 2];
*lo = pow10_sig_table[idx * 2 + 1];
}
/**
Get the exponent (base 2) for highest 64 bits significand in pow10_sig_table.
*/
static_inline void pow10_table_get_exp(i32 exp10, i32 *exp2) {
/* e2 = floor(log2(pow(10, e))) - 64 + 1 */
/* = floor(e * log2(10) - 63) */
*exp2 = (exp10 * 217706 - 4128768) >> 16;
}
#endif
#if !YYJSON_DISABLE_READER
/*==============================================================================
* JSON Character Matcher
*============================================================================*/
/** Character type */
typedef u8 char_type;
/** Whitespace character: ' ', '\\t', '\\n', '\\r'. */
static const char_type CHAR_TYPE_SPACE = 1 << 0;
/** Number character: '-', [0-9]. */
static const char_type CHAR_TYPE_NUMBER = 1 << 1;
/** JSON Escaped character: '"', '\', [0x00-0x1F]. */
static const char_type CHAR_TYPE_ESC_ASCII = 1 << 2;
/** Non-ASCII character: [0x80-0xFF]. */
static const char_type CHAR_TYPE_NON_ASCII = 1 << 3;
/** JSON container character: '{', '['. */
static const char_type CHAR_TYPE_CONTAINER = 1 << 4;
/** Comment character: '/'. */
static const char_type CHAR_TYPE_COMMENT = 1 << 5;
/** Line end character: '\\n', '\\r', '\0'. */
static const char_type CHAR_TYPE_LINE_END = 1 << 6;
/** Hexadecimal numeric character: [0-9a-fA-F]. */
static const char_type CHAR_TYPE_HEX = 1 << 7;
/** Character type table (generate with misc/make_tables.c) */
static const char_type char_table[256] = {
0x44, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x05, 0x45, 0x04, 0x04, 0x45, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x20,
0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82,
0x82, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x10, 0x04, 0x00, 0x00, 0x00,
0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08,
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08
};
/** Match a character with specified type. */
static_inline bool char_is_type(u8 c, char_type type) {
return (char_table[c] & type) != 0;
}
/** Match a whitespace: ' ', '\\t', '\\n', '\\r'. */
static_inline bool char_is_space(u8 c) {
return char_is_type(c, (char_type)CHAR_TYPE_SPACE);
}
/** Match a whitespace or comment: ' ', '\\t', '\\n', '\\r', '/'. */
static_inline bool char_is_space_or_comment(u8 c) {
return char_is_type(c, (char_type)(CHAR_TYPE_SPACE | CHAR_TYPE_COMMENT));
}
/** Match a JSON number: '-', [0-9]. */
static_inline bool char_is_number(u8 c) {
return char_is_type(c, (char_type)CHAR_TYPE_NUMBER);
}
/** Match a JSON container: '{', '['. */
static_inline bool char_is_container(u8 c) {
return char_is_type(c, (char_type)CHAR_TYPE_CONTAINER);
}
/** Match a stop character in ASCII string: '"', '\', [0x00-0x1F,0x80-0xFF]. */
static_inline bool char_is_ascii_stop(u8 c) {
return char_is_type(c, (char_type)(CHAR_TYPE_ESC_ASCII |
CHAR_TYPE_NON_ASCII));
}
/** Match a line end character: '\\n', '\\r', '\0'. */
static_inline bool char_is_line_end(u8 c) {
return char_is_type(c, (char_type)CHAR_TYPE_LINE_END);
}
/** Match a hexadecimal numeric character: [0-9a-fA-F]. */
static_inline bool char_is_hex(u8 c) {
return char_is_type(c, (char_type)CHAR_TYPE_HEX);
}
/*==============================================================================
* Digit Character Matcher
*============================================================================*/
/** Digit type */
typedef u8 digi_type;
/** Digit: '0'. */
static const digi_type DIGI_TYPE_ZERO = 1 << 0;
/** Digit: [1-9]. */
static const digi_type DIGI_TYPE_NONZERO = 1 << 1;
/** Plus sign (positive): '+'. */
static const digi_type DIGI_TYPE_POS = 1 << 2;
/** Minus sign (negative): '-'. */
static const digi_type DIGI_TYPE_NEG = 1 << 3;
/** Decimal point: '.' */
static const digi_type DIGI_TYPE_DOT = 1 << 4;
/** Exponent sign: 'e, 'E'. */
static const digi_type DIGI_TYPE_EXP = 1 << 5;
/** Digit type table (generate with misc/make_tables.c) */
static const digi_type digi_table[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x04, 0x00, 0x08, 0x10, 0x00,
0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,
0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/** Match a character with specified type. */
static_inline bool digi_is_type(u8 d, digi_type type) {
return (digi_table[d] & type) != 0;
}
/** Match a sign: '+', '-' */
static_inline bool digi_is_sign(u8 d) {
return digi_is_type(d, (digi_type)(DIGI_TYPE_POS | DIGI_TYPE_NEG));
}
/** Match a none zero digit: [1-9] */
static_inline bool digi_is_nonzero(u8 d) {
return digi_is_type(d, (digi_type)DIGI_TYPE_NONZERO);
}
/** Match a digit: [0-9] */
static_inline bool digi_is_digit(u8 d) {
return digi_is_type(d, (digi_type)(DIGI_TYPE_ZERO | DIGI_TYPE_NONZERO));
}
/** Match an exponent sign: 'e', 'E'. */
static_inline bool digi_is_exp(u8 d) {
return digi_is_type(d, (digi_type)DIGI_TYPE_EXP);
}
/** Match a floating point indicator: '.', 'e', 'E'. */
static_inline bool digi_is_fp(u8 d) {
return digi_is_type(d, (digi_type)(DIGI_TYPE_DOT | DIGI_TYPE_EXP));
}
/** Match a digit or floating point indicator: [0-9], '.', 'e', 'E'. */
static_inline bool digi_is_digit_or_fp(u8 d) {
return digi_is_type(d, (digi_type)(DIGI_TYPE_ZERO | DIGI_TYPE_NONZERO |
DIGI_TYPE_DOT | DIGI_TYPE_EXP));
}
/*==============================================================================
* Hex Character Reader
* This function is used by JSON reader to read escaped characters.
*============================================================================*/
/**
This table is used to convert 4 hex character sequence to a number.
A valid hex character [0-9A-Fa-f] will mapped to it's raw number [0x00, 0x0F],
an invalid hex character will mapped to [0xF0].
(generate with misc/make_tables.c)
*/
static const u8 hex_conv_table[256] = {
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0
};
/**
Scans an escaped character sequence as a UTF-16 code unit (branchless).
e.g. "\\u005C" should pass "005C" as `cur`.
This requires the string has 4-byte zero padding.
*/
static_inline bool read_hex_u16(const u8 *cur, u16 *val) {
u16 c0, c1, c2, c3, t0, t1;
c0 = hex_conv_table[cur[0]];
c1 = hex_conv_table[cur[1]];
c2 = hex_conv_table[cur[2]];
c3 = hex_conv_table[cur[3]];
t0 = (u16)((c0 << 8) | c2);
t1 = (u16)((c1 << 8) | c3);
*val = (u16)((t0 << 4) | t1);
return ((t0 | t1) & (u16)0xF0F0) == 0;
}
/*==============================================================================
* JSON Reader Utils
* These functions are used by JSON reader to read literals and comments.
*============================================================================*/
/** Read 'true' literal, '*cur' should be 't'. */
static_inline bool read_true(u8 **ptr, yyjson_val *val) {
u8 *cur = *ptr;
u8 **end = ptr;
if (likely(byte_match_4(cur, "true"))) {
val->tag = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_TRUE;
*end = cur + 4;
return true;
}
return false;
}
/** Read 'false' literal, '*cur' should be 'f'. */
static_inline bool read_false(u8 **ptr, yyjson_val *val) {
u8 *cur = *ptr;
u8 **end = ptr;
if (likely(byte_match_4(cur + 1, "alse"))) {
val->tag = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_FALSE;
*end = cur + 5;
return true;
}
return false;
}
/** Read 'null' literal, '*cur' should be 'n'. */
static_inline bool read_null(u8 **ptr, yyjson_val *val) {
u8 *cur = *ptr;
u8 **end = ptr;
if (likely(byte_match_4(cur, "null"))) {
val->tag = YYJSON_TYPE_NULL;
*end = cur + 4;
return true;
}
return false;
}
/** Read 'Inf' or 'Infinity' literal (ignoring case). */
static_inline bool read_inf(bool sign, u8 **ptr, u8 **pre, yyjson_val *val) {
u8 *hdr = *ptr - sign;
u8 *cur = *ptr;
u8 **end = ptr;
if ((cur[0] == 'I' || cur[0] == 'i') &&
(cur[1] == 'N' || cur[1] == 'n') &&
(cur[2] == 'F' || cur[2] == 'f')) {
if ((cur[3] == 'I' || cur[3] == 'i') &&
(cur[4] == 'N' || cur[4] == 'n') &&
(cur[5] == 'I' || cur[5] == 'i') &&
(cur[6] == 'T' || cur[6] == 't') &&
(cur[7] == 'Y' || cur[7] == 'y')) {
cur += 8;
} else {
cur += 3;
}
*end = cur;
if (false) {
/* add null-terminator for previous raw string */
if (*pre) **pre = '\0';
*pre = cur;
val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW;
val->uni.str = (const char *)hdr;
} else {
val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;
val->uni.u64 = f64_raw_get_inf(sign);
}
return true;
}
return false;
}
/** Read 'NaN' literal (ignoring case). */
static_inline bool read_nan(bool sign, u8 **ptr, u8 **pre, yyjson_val *val) {
u8 *hdr = *ptr - sign;
u8 *cur = *ptr;
u8 **end = ptr;
if ((cur[0] == 'N' || cur[0] == 'n') &&
(cur[1] == 'A' || cur[1] == 'a') &&
(cur[2] == 'N' || cur[2] == 'n')) {
cur += 3;
*end = cur;
if (false) {
/* add null-terminator for previous raw string */
if (*pre) **pre = '\0';
*pre = cur;
val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW;
val->uni.str = (const char *)hdr;
} else {
val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;
val->uni.u64 = f64_raw_get_nan(sign);
}
return true;
}
return false;
}
/** Read 'Inf', 'Infinity' or 'NaN' literal (ignoring case). */
static_inline bool read_inf_or_nan(bool sign, u8 **ptr, u8 **pre,
yyjson_val *val) {
if (read_inf(sign, ptr, pre, val)) return true;
if (read_nan(sign, ptr, pre, val)) return true;
return false;
}
/** Read a JSON number as raw string. */
static_noinline bool read_number_raw(u8 **ptr,
u8 **pre,
yyjson_read_flag flg,
yyjson_val *val,
const char **msg) {
#define return_err(_pos, _msg) do { \
*msg = _msg; \
*end = _pos; \
return false; \
} while (false)
#define return_raw() do { \
val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW; \
val->uni.str = (const char *)hdr; \
*pre = cur; *end = cur; return true; \
} while (false)
u8 *hdr = *ptr;
u8 *cur = *ptr;
u8 **end = ptr;
/* add null-terminator for previous raw string */
if (*pre) **pre = '\0';
/* skip sign */
cur += (*cur == '-');
/* read first digit, check leading zero */
if (unlikely(!digi_is_digit(*cur))) {
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (read_inf_or_nan(*hdr == '-', &cur, pre, val)) return_raw();
}
return_err(cur, "no digit after minus sign");
}
/* read integral part */
if (*cur == '0') {
cur++;
if (unlikely(digi_is_digit(*cur))) {
return_err(cur - 1, "number with leading zero is not allowed");
}
if (!digi_is_fp(*cur)) return_raw();
} else {
while (digi_is_digit(*cur)) cur++;
if (!digi_is_fp(*cur)) return_raw();
}
/* read fraction part */
if (*cur == '.') {
cur++;
if (!digi_is_digit(*cur++)) {
return_err(cur, "no digit after decimal point");
}
while (digi_is_digit(*cur)) cur++;
}
/* read exponent part */
if (digi_is_exp(*cur)) {
cur += 1 + digi_is_sign(cur[1]);
if (!digi_is_digit(*cur++)) {
return_err(cur, "no digit after exponent sign");
}
while (digi_is_digit(*cur)) cur++;
}
return_raw();
#undef return_err
#undef return_raw
}
/**
Skips spaces and comments as many as possible.
It will return false in these cases:
1. No character is skipped. The 'end' pointer is set as input cursor.
2. A multiline comment is not closed. The 'end' pointer is set as the head
of this comment block.
*/
static_noinline bool skip_spaces_and_comments(u8 **ptr) {
u8 *hdr = *ptr;
u8 *cur = *ptr;
u8 **end = ptr;
while (true) {
if (byte_match_2(cur, "/*")) {
hdr = cur;
cur += 2;
while (true) {
if (byte_match_2(cur, "*/")) {
cur += 2;
break;
}
if (*cur == 0) {
*end = hdr;
return false;
}
cur++;
}
continue;
}
if (byte_match_2(cur, "//")) {
cur += 2;
while (!char_is_line_end(*cur)) cur++;
continue;
}
if (char_is_space(*cur)) {
cur += 1;
while (char_is_space(*cur)) cur++;
continue;
}
break;
}
*end = cur;
return hdr != cur;
}
/**
Check truncated string.
Returns true if `cur` match `str` but is truncated.
*/
static_inline bool is_truncated_str(u8 *cur, u8 *end,
const char *str,
bool case_sensitive) {
usize len = strlen(str);
if (cur + len <= end || end <= cur) return false;
if (case_sensitive) {
return memcmp(cur, str, (usize)(end - cur)) == 0;
}
for (; cur < end; cur++, str++) {
if ((*cur != (u8)*str) && (*cur != (u8)*str - 'a' + 'A')) {
return false;
}
}
return true;
}
/**
Check truncated JSON on parsing errors.
Returns true if the input is valid but truncated.
*/
static_noinline bool is_truncated_end(u8 *hdr, u8 *cur, u8 *end,
yyjson_read_code code,
yyjson_read_flag flg) {
if (cur >= end) return true;
if (code == YYJSON_READ_ERROR_LITERAL) {
if (is_truncated_str(cur, end, "true", true) ||
is_truncated_str(cur, end, "false", true) ||
is_truncated_str(cur, end, "null", true)) {
return true;
}
}
if (code == YYJSON_READ_ERROR_UNEXPECTED_CHARACTER ||
code == YYJSON_READ_ERROR_INVALID_NUMBER ||
code == YYJSON_READ_ERROR_LITERAL) {
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (*cur == '-') cur++;
if (is_truncated_str(cur, end, "infinity", false) ||
is_truncated_str(cur, end, "nan", false)) {
return true;
}
}
}
if (code == YYJSON_READ_ERROR_UNEXPECTED_CONTENT) {
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (hdr + 3 <= cur &&
is_truncated_str(cur - 3, end, "infinity", false)) {
return true; /* e.g. infin would be read as inf + in */
}
}
}
if (code == YYJSON_READ_ERROR_INVALID_STRING) {
usize len = (usize)(end - cur);
/* unicode escape sequence */
if (*cur == '\\') {
if (len == 1) return true;
if (len <= 5) {
if (*++cur != 'u') return false;
for (++cur; cur < end; cur++) {
if (!char_is_hex(*cur)) return false;
}
return true;
}
return false;
}
/* 2 to 4 bytes UTF-8, see `read_string()` for details. */
if (*cur & 0x80) {
u8 c0 = cur[0], c1 = cur[1], c2 = cur[2];
if (len == 1) {
/* 2 bytes UTF-8, truncated */
if ((c0 & 0xE0) == 0xC0 && (c0 & 0x1E) != 0x00) return true;
/* 3 bytes UTF-8, truncated */
if ((c0 & 0xF0) == 0xE0) return true;
/* 4 bytes UTF-8, truncated */
if ((c0 & 0xF8) == 0xF0 && (c0 & 0x07) <= 0x04) return true;
}
if (len == 2) {
/* 3 bytes UTF-8, truncated */
if ((c0 & 0xF0) == 0xE0 &&
(c1 & 0xC0) == 0x80) {
u8 pat = (u8)(((c0 & 0x0F) << 1) | ((c1 & 0x20) >> 5));
return 0x01 <= pat && pat != 0x1B;
}
/* 4 bytes UTF-8, truncated */
if ((c0 & 0xF8) == 0xF0 &&
(c1 & 0xC0) == 0x80) {
u8 pat = (u8)(((c0 & 0x07) << 2) | ((c1 & 0x30) >> 4));
return 0x01 <= pat && pat <= 0x10;
}
}
if (len == 3) {
/* 4 bytes UTF-8, truncated */
if ((c0 & 0xF8) == 0xF0 &&
(c1 & 0xC0) == 0x80 &&
(c2 & 0xC0) == 0x80) {
u8 pat = (u8)(((c0 & 0x07) << 2) | ((c1 & 0x30) >> 4));
return 0x01 <= pat && pat <= 0x10;
}
}
}
}
return false;
}
#if YYJSON_HAS_IEEE_754 && !YYJSON_DISABLE_FAST_FP_CONV /* FP_READER */
/*==============================================================================
* BigInt For Floating Point Number Reader
*
* The bigint algorithm is used by floating-point number reader to get correctly
* rounded result for numbers with lots of digits. This part of code is rarely
* used for common numbers.
*============================================================================*/
/** Maximum exponent of exact pow10 */
#define U64_POW10_MAX_EXP 19
/** Table: [ 10^0, ..., 10^19 ] (generate with misc/make_tables.c) */
static const u64 u64_pow10_table[U64_POW10_MAX_EXP + 1] = {
U64(0x00000000, 0x00000001), U64(0x00000000, 0x0000000A),
U64(0x00000000, 0x00000064), U64(0x00000000, 0x000003E8),
U64(0x00000000, 0x00002710), U64(0x00000000, 0x000186A0),
U64(0x00000000, 0x000F4240), U64(0x00000000, 0x00989680),
U64(0x00000000, 0x05F5E100), U64(0x00000000, 0x3B9ACA00),
U64(0x00000002, 0x540BE400), U64(0x00000017, 0x4876E800),
U64(0x000000E8, 0xD4A51000), U64(0x00000918, 0x4E72A000),
U64(0x00005AF3, 0x107A4000), U64(0x00038D7E, 0xA4C68000),
U64(0x002386F2, 0x6FC10000), U64(0x01634578, 0x5D8A0000),
U64(0x0DE0B6B3, 0xA7640000), U64(0x8AC72304, 0x89E80000)
};
/** Maximum numbers of chunks used by a bigint (58 is enough here). */
#define BIGINT_MAX_CHUNKS 64
/** Unsigned arbitrarily large integer */
typedef struct bigint {
u32 used; /* used chunks count, should not be 0 */
u64 bits[BIGINT_MAX_CHUNKS]; /* chunks */
} bigint;
/**
Evaluate 'big += val'.
@param big A big number (can be 0).
@param val An unsigned integer (can be 0).
*/
static_inline void bigint_add_u64(bigint *big, u64 val) {
u32 idx, max;
u64 num = big->bits[0];
u64 add = num + val;
big->bits[0] = add;
if (likely((add >= num) || (add >= val))) return;
for ((void)(idx = 1), max = big->used; idx < max; idx++) {
if (likely(big->bits[idx] != U64_MAX)) {
big->bits[idx] += 1;
return;
}
big->bits[idx] = 0;
}
big->bits[big->used++] = 1;
}
/**
Evaluate 'big *= val'.
@param big A big number (can be 0).
@param val An unsigned integer (cannot be 0).
*/
static_inline void bigint_mul_u64(bigint *big, u64 val) {
u32 idx = 0, max = big->used;
u64 hi, lo, carry = 0;
for (; idx < max; idx++) {
if (big->bits[idx]) break;
}
for (; idx < max; idx++) {
u128_mul_add(big->bits[idx], val, carry, &hi, &lo);
big->bits[idx] = lo;
carry = hi;
}
if (carry) big->bits[big->used++] = carry;
}
/**
Evaluate 'big *= 2^exp'.
@param big A big number (can be 0).
@param exp An exponent integer (can be 0).
*/
static_inline void bigint_mul_pow2(bigint *big, u32 exp) {
u32 shft = exp % 64;
u32 move = exp / 64;
u32 idx = big->used;
if (unlikely(shft == 0)) {
for (; idx > 0; idx--) {
big->bits[idx + move - 1] = big->bits[idx - 1];
}
big->used += move;
while (move) big->bits[--move] = 0;
} else {
big->bits[idx] = 0;
for (; idx > 0; idx--) {
u64 num = big->bits[idx] << shft;
num |= big->bits[idx - 1] >> (64 - shft);
big->bits[idx + move] = num;
}
big->bits[move] = big->bits[0] << shft;
big->used += move + (big->bits[big->used + move] > 0);
while (move) big->bits[--move] = 0;
}
}
/**
Evaluate 'big *= 10^exp'.
@param big A big number (can be 0).
@param exp An exponent integer (cannot be 0).
*/
static_inline void bigint_mul_pow10(bigint *big, i32 exp) {
for (; exp >= U64_POW10_MAX_EXP; exp -= U64_POW10_MAX_EXP) {
bigint_mul_u64(big, u64_pow10_table[U64_POW10_MAX_EXP]);
}
if (exp) {
bigint_mul_u64(big, u64_pow10_table[exp]);
}
}
/**
Compare two bigint.
@return -1 if 'a < b', +1 if 'a > b', 0 if 'a == b'.
*/
static_inline i32 bigint_cmp(bigint *a, bigint *b) {
u32 idx = a->used;
if (a->used < b->used) return -1;
if (a->used > b->used) return +1;
while (idx-- > 0) {
u64 av = a->bits[idx];
u64 bv = b->bits[idx];
if (av < bv) return -1;
if (av > bv) return +1;
}
return 0;
}
/**
Evaluate 'big = val'.
@param big A big number (can be 0).
@param val An unsigned integer (can be 0).
*/
static_inline void bigint_set_u64(bigint *big, u64 val) {
big->used = 1;
big->bits[0] = val;
}
/** Set a bigint with floating point number string. */
static_noinline void bigint_set_buf(bigint *big, u64 sig, i32 *exp,
u8 *sig_cut, u8 *sig_end, u8 *dot_pos) {
if (unlikely(!sig_cut)) {
/* no digit cut, set significant part only */
bigint_set_u64(big, sig);
return;
} else {
/* some digits were cut, read them from 'sig_cut' to 'sig_end' */
u8 *hdr = sig_cut;
u8 *cur = hdr;
u32 len = 0;
u64 val = 0;
bool dig_big_cut = false;
bool has_dot = (hdr < dot_pos) & (dot_pos < sig_end);
u32 dig_len_total = U64_SAFE_DIG + (u32)(sig_end - hdr) - has_dot;
sig -= (*sig_cut >= '5'); /* sig was rounded before */
if (dig_len_total > F64_MAX_DEC_DIG) {
dig_big_cut = true;
sig_end -= dig_len_total - (F64_MAX_DEC_DIG + 1);
sig_end -= (dot_pos + 1 == sig_end);
dig_len_total = (F64_MAX_DEC_DIG + 1);
}
*exp -= (i32)dig_len_total - U64_SAFE_DIG;
big->used = 1;
big->bits[0] = sig;
while (cur < sig_end) {
if (likely(cur != dot_pos)) {
val = val * 10 + (u8)(*cur++ - '0');
len++;
if (unlikely(cur == sig_end && dig_big_cut)) {
/* The last digit must be non-zero, */
/* set it to '1' for correct rounding. */
val = val - (val % 10) + 1;
}
if (len == U64_SAFE_DIG || cur == sig_end) {
bigint_mul_pow10(big, (i32)len);
bigint_add_u64(big, val);
val = 0;
len = 0;
}
} else {
cur++;
}
}
}
}
/*==============================================================================
* Diy Floating Point
*============================================================================*/
/** "Do It Yourself Floating Point" struct. */
typedef struct diy_fp {
u64 sig; /* significand */
i32 exp; /* exponent, base 2 */
i32 pad; /* padding, useless */
} diy_fp;
/** Get cached rounded diy_fp with pow(10, e) The input value must in range
[POW10_SIG_TABLE_MIN_EXP, POW10_SIG_TABLE_MAX_EXP]. */
static_inline diy_fp diy_fp_get_cached_pow10(i32 exp10) {
diy_fp fp;
u64 sig_ext;
pow10_table_get_sig(exp10, &fp.sig, &sig_ext);
pow10_table_get_exp(exp10, &fp.exp);
fp.sig += (sig_ext >> 63);
return fp;
}
/** Returns fp * fp2. */
static_inline diy_fp diy_fp_mul(diy_fp fp, diy_fp fp2) {
u64 hi, lo;
u128_mul(fp.sig, fp2.sig, &hi, &lo);
fp.sig = hi + (lo >> 63);
fp.exp += fp2.exp + 64;
return fp;
}
/** Convert diy_fp to IEEE-754 raw value. */
static_inline u64 diy_fp_to_ieee_raw(diy_fp fp) {
u64 sig = fp.sig;
i32 exp = fp.exp;
u32 lz_bits;
if (unlikely(fp.sig == 0)) return 0;
lz_bits = u64_lz_bits(sig);
sig <<= lz_bits;
sig >>= F64_BITS - F64_SIG_FULL_BITS;
exp -= (i32)lz_bits;
exp += F64_BITS - F64_SIG_FULL_BITS;
exp += F64_SIG_BITS;
if (unlikely(exp >= F64_MAX_BIN_EXP)) {
/* overflow */
return F64_RAW_INF;
} else if (likely(exp >= F64_MIN_BIN_EXP - 1)) {
/* normal */
exp += F64_EXP_BIAS;
return ((u64)exp << F64_SIG_BITS) | (sig & F64_SIG_MASK);
} else if (likely(exp >= F64_MIN_BIN_EXP - F64_SIG_FULL_BITS)) {
/* subnormal */
return sig >> (F64_MIN_BIN_EXP - exp - 1);
} else {
/* underflow */
return 0;
}
}
/*==============================================================================
* JSON Number Reader (IEEE-754)
*============================================================================*/
/** Maximum exact pow10 exponent for double value. */
#define F64_POW10_EXP_MAX_EXACT 22
/** Cached pow10 table. */
static const f64 f64_pow10_table[] = {
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12,
1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22
};
/**
Read a JSON number.
1. This function assume that the floating-point number is in IEEE-754 format.
2. This function support uint64/int64/double number. If an integer number
cannot fit in uint64/int64, it will returns as a double number. If a double
number is infinite, the return value is based on flag.
3. This function (with inline attribute) may generate a lot of instructions.
*/
static_inline bool read_number(u8 **ptr,
u8 **pre,
yyjson_read_flag flg,
yyjson_val *val,
const char **msg) {
#define return_err(_pos, _msg) do { \
*msg = _msg; \
*end = _pos; \
return false; \
} while (false)
#define return_0() do { \
val->tag = YYJSON_TYPE_NUM | (u8)((u8)sign << 3); \
val->uni.u64 = 0; \
*end = cur; return true; \
} while (false)
#define return_i64(_v) do { \
val->tag = YYJSON_TYPE_NUM | (u8)((u8)sign << 3); \
val->uni.u64 = (u64)(sign ? (u64)(~(_v) + 1) : (u64)(_v)); \
*end = cur; return true; \
} while (false)
#define return_f64(_v) do { \
val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \
val->uni.f64 = sign ? -(f64)(_v) : (f64)(_v); \
*end = cur; return true; \
} while (false)
#define return_f64_bin(_v) do { \
val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \
val->uni.u64 = ((u64)sign << 63) | (u64)(_v); \
*end = cur; return true; \
} while (false)
#define return_inf() do { \
if (has_read_flag(BIGNUM_AS_RAW)) return_raw(); \
if (has_read_flag(ALLOW_INF_AND_NAN)) return_f64_bin(F64_RAW_INF); \
else return_err(hdr, "number is infinity when parsed as double"); \
} while (false)
#define return_raw() do { \
if (*pre) **pre = '\0'; /* add null-terminator for previous raw string */ \
val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW; \
val->uni.str = (const char *)hdr; \
*pre = cur; *end = cur; return true; \
} while (false)
u8 *sig_cut = NULL; /* significant part cutting position for long number */
u8 *sig_end = NULL; /* significant part ending position */
u8 *dot_pos = NULL; /* decimal point position */
u64 sig = 0; /* significant part of the number */
i32 exp = 0; /* exponent part of the number */
bool exp_sign; /* temporary exponent sign from literal part */
i64 exp_sig = 0; /* temporary exponent number from significant part */
i64 exp_lit = 0; /* temporary exponent number from exponent literal part */
u64 num; /* temporary number for reading */
u8 *tmp; /* temporary cursor for reading */
u8 *hdr = *ptr;
u8 *cur = *ptr;
u8 **end = ptr;
bool sign;
/* read number as raw string if has `YYJSON_READ_NUMBER_AS_RAW` flag */
if (unlikely(pre && !has_read_flag(BIGNUM_AS_RAW))) {
return read_number_raw(ptr, pre, flg, val, msg);
}
sign = (*hdr == '-');
cur += sign;
/* begin with a leading zero or non-digit */
if (unlikely(!digi_is_nonzero(*cur))) { /* 0 or non-digit char */
if (unlikely(*cur != '0')) { /* non-digit char */
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (read_inf_or_nan(sign, &cur, pre, val)) {
*end = cur;
return true;
}
}
return_err(cur, "no digit after minus sign");
}
/* begin with 0 */
if (likely(!digi_is_digit_or_fp(*++cur))) return_0();
if (likely(*cur == '.')) {
dot_pos = cur++;
if (unlikely(!digi_is_digit(*cur))) {
return_err(cur, "no digit after decimal point");
}
while (unlikely(*cur == '0')) cur++;
if (likely(digi_is_digit(*cur))) {
/* first non-zero digit after decimal point */
sig = (u64)(*cur - '0'); /* read first digit */
cur--;
goto digi_frac_1; /* continue read fraction part */
}
}
if (unlikely(digi_is_digit(*cur))) {
return_err(cur - 1, "number with leading zero is not allowed");
}
if (unlikely(digi_is_exp(*cur))) { /* 0 with any exponent is still 0 */
cur += (usize)1 + digi_is_sign(cur[1]);
if (unlikely(!digi_is_digit(*cur))) {
return_err(cur, "no digit after exponent sign");
}
while (digi_is_digit(*++cur));
}
return_f64_bin(0);
}
/* begin with non-zero digit */
sig = (u64)(*cur - '0');
/*
Read integral part, same as the following code.
for (int i = 1; i <= 18; i++) {
num = cur[i] - '0';
if (num <= 9) sig = num + sig * 10;
else goto digi_sepr_i;
}
*/
#define expr_intg(i) \
if (likely((num = (u64)(cur[i] - (u8)'0')) <= 9)) sig = num + sig * 10; \
else { goto digi_sepr_##i; }
repeat_in_1_18(expr_intg)
#undef expr_intg
cur += 19; /* skip continuous 19 digits */
if (!digi_is_digit_or_fp(*cur)) {
/* this number is an integer consisting of 19 digits */
if (sign && (sig > ((u64)1 << 63))) { /* overflow */
if (has_read_flag(BIGNUM_AS_RAW)) return_raw();
return_f64(normalized_u64_to_f64(sig));
}
return_i64(sig);
}
goto digi_intg_more; /* read more digits in integral part */
/* process first non-digit character */
#define expr_sepr(i) \
digi_sepr_##i: \
if (likely(!digi_is_fp(cur[i]))) { cur += i; return_i64(sig); } \
dot_pos = cur + i; \
if (likely(cur[i] == '.')) goto digi_frac_##i; \
cur += i; sig_end = cur; goto digi_exp_more;
repeat_in_1_18(expr_sepr)
#undef expr_sepr
/* read fraction part */
#define expr_frac(i) \
digi_frac_##i: \
if (likely((num = (u64)(cur[i + 1] - (u8)'0')) <= 9)) \
sig = num + sig * 10; \
else { goto digi_stop_##i; }
repeat_in_1_18(expr_frac)
#undef expr_frac
cur += 20; /* skip 19 digits and 1 decimal point */
if (!digi_is_digit(*cur)) goto digi_frac_end; /* fraction part end */
goto digi_frac_more; /* read more digits in fraction part */
/* significant part end */
#define expr_stop(i) \
digi_stop_##i: \
cur += i + 1; \
goto digi_frac_end;
repeat_in_1_18(expr_stop)
#undef expr_stop
/* read more digits in integral part */
digi_intg_more:
if (digi_is_digit(*cur)) {
if (!digi_is_digit_or_fp(cur[1])) {
/* this number is an integer consisting of 20 digits */
num = (u64)(*cur - '0');
if ((sig < (U64_MAX / 10)) ||
(sig == (U64_MAX / 10) && num <= (U64_MAX % 10))) {
sig = num + sig * 10;
cur++;
/* convert to double if overflow */
if (sign) {
if (has_read_flag(BIGNUM_AS_RAW)) return_raw();
return_f64(normalized_u64_to_f64(sig));
}
return_i64(sig);
}
}
}
if (digi_is_exp(*cur)) {
dot_pos = cur;
goto digi_exp_more;
}
if (*cur == '.') {
dot_pos = cur++;
if (!digi_is_digit(*cur)) {
return_err(cur, "no digit after decimal point");
}
}
/* read more digits in fraction part */
digi_frac_more:
sig_cut = cur; /* too large to fit in u64, excess digits need to be cut */
sig += (*cur >= '5'); /* round */
while (digi_is_digit(*++cur));
if (!dot_pos) {
if (!digi_is_fp(*cur) && has_read_flag(BIGNUM_AS_RAW)) {
return_raw(); /* it's a large integer */
}
dot_pos = cur;
if (*cur == '.') {
if (!digi_is_digit(*++cur)) {
return_err(cur, "no digit after decimal point");
}
while (digi_is_digit(*cur)) cur++;
}
}
exp_sig = (i64)(dot_pos - sig_cut);
exp_sig += (dot_pos < sig_cut);
/* ignore trailing zeros */
tmp = cur - 1;
while (*tmp == '0' || *tmp == '.') tmp--;
if (tmp < sig_cut) {
sig_cut = NULL;
} else {
sig_end = cur;
}
if (digi_is_exp(*cur)) goto digi_exp_more;
goto digi_exp_finish;
/* fraction part end */
digi_frac_end:
if (unlikely(dot_pos + 1 == cur)) {
return_err(cur, "no digit after decimal point");
}
sig_end = cur;
exp_sig = -(i64)((u64)(cur - dot_pos) - 1);
if (likely(!digi_is_exp(*cur))) {
if (unlikely(exp_sig < F64_MIN_DEC_EXP - 19)) {
return_f64_bin(0); /* underflow */
}
exp = (i32)exp_sig;
goto digi_finish;
} else {
goto digi_exp_more;
}
/* read exponent part */
digi_exp_more:
exp_sign = (*++cur == '-');
cur += digi_is_sign(*cur);
if (unlikely(!digi_is_digit(*cur))) {
return_err(cur, "no digit after exponent sign");
}
while (*cur == '0') cur++;
/* read exponent literal */
tmp = cur;
while (digi_is_digit(*cur)) {
exp_lit = (i64)((u8)(*cur++ - '0') + (u64)exp_lit * 10);
}
if (unlikely(cur - tmp >= U64_SAFE_DIG)) {
if (exp_sign) {
return_f64_bin(0); /* underflow */
} else {
return_inf(); /* overflow */
}
}
exp_sig += exp_sign ? -exp_lit : exp_lit;
/* validate exponent value */
digi_exp_finish:
if (unlikely(exp_sig < F64_MIN_DEC_EXP - 19)) {
return_f64_bin(0); /* underflow */
}
if (unlikely(exp_sig > F64_MAX_DEC_EXP)) {
return_inf(); /* overflow */
}
exp = (i32)exp_sig;
/* all digit read finished */
digi_finish:
/*
Fast path 1:
1. The floating-point number calculation should be accurate, see the
comments of macro `YYJSON_DOUBLE_MATH_CORRECT`.
2. Correct rounding should be performed (fegetround() == FE_TONEAREST).
3. The input of floating point number calculation does not lose precision,
which means: 64 - leading_zero(input) - trailing_zero(input) < 53.
We don't check all available inputs here, because that would make the code
more complicated, and not friendly to branch predictor.
*/
#if YYJSON_DOUBLE_MATH_CORRECT
if (sig < ((u64)1 << 53) &&
exp >= -F64_POW10_EXP_MAX_EXACT &&
exp <= +F64_POW10_EXP_MAX_EXACT) {
f64 dbl = (f64)sig;
if (exp < 0) {
dbl /= f64_pow10_table[-exp];
} else {
dbl *= f64_pow10_table[+exp];
}
return_f64(dbl);
}
#endif
/*
Fast path 2:
To keep it simple, we only accept normal number here,
let the slow path to handle subnormal and infinity number.
*/
if (likely(!sig_cut &&
exp > -F64_MAX_DEC_EXP + 1 &&
exp < +F64_MAX_DEC_EXP - 20)) {
/*
The result value is exactly equal to (sig * 10^exp),
the exponent part (10^exp) can be converted to (sig2 * 2^exp2).
The sig2 can be an infinite length number, only the highest 128 bits
is cached in the pow10_sig_table.
Now we have these bits:
sig1 (normalized 64bit) : aaaaaaaa
sig2 (higher 64bit) : bbbbbbbb
sig2_ext (lower 64bit) : cccccccc
sig2_cut (extra unknown bits) : dddddddddddd....
And the calculation process is:
----------------------------------------
aaaaaaaa *
bbbbbbbbccccccccdddddddddddd....
----------------------------------------
abababababababab +
acacacacacacacac +
adadadadadadadadadad....
----------------------------------------
[hi____][lo____] +
[hi2___][lo2___] +
[unknown___________....]
----------------------------------------
The addition with carry may affect higher bits, but if there is a 0
in higher bits, the bits higher than 0 will not be affected.
`lo2` + `unknown` may get a carry bit and may affect `hi2`, the max
value of `hi2` is 0xFFFFFFFFFFFFFFFE, so `hi2` will not overflow.
`lo` + `hi2` may also get a carry bit and may affect `hi`, but only
the highest significant 53 bits of `hi` is needed. If there is a 0
in the lower bits of `hi`, then all the following bits can be dropped.
To convert the result to IEEE-754 double number, we need to perform
correct rounding:
1. if bit 54 is 0, round down,
2. if bit 54 is 1 and any bit beyond bit 54 is 1, round up,
3. if bit 54 is 1 and all bits beyond bit 54 are 0, round to even,
as the extra bits is unknown, this case will not be handled here.
*/
u64 raw;
u64 sig1, sig2, sig2_ext, hi, lo, hi2, lo2, add, bits;
i32 exp2;
u32 lz;
bool exact = false, carry, round_up;
/* convert (10^exp) to (sig2 * 2^exp2) */
pow10_table_get_sig(exp, &sig2, &sig2_ext);
pow10_table_get_exp(exp, &exp2);
/* normalize and multiply */
lz = u64_lz_bits(sig);
sig1 = sig << lz;
exp2 -= (i32)lz;
u128_mul(sig1, sig2, &hi, &lo);
/*
The `hi` is in range [0x4000000000000000, 0xFFFFFFFFFFFFFFFE],
To get normalized value, `hi` should be shifted to the left by 0 or 1.
The highest significant 53 bits is used by IEEE-754 double number,
and the bit 54 is used to detect rounding direction.
The lowest (64 - 54 - 1) bits is used to check whether it contains 0.
*/
bits = hi & (((u64)1 << (64 - 54 - 1)) - 1);
if (bits - 1 < (((u64)1 << (64 - 54 - 1)) - 2)) {
/*
(bits != 0 && bits != 0x1FF) => (bits - 1 < 0x1FF - 1)
The `bits` is not zero, so we don't need to check `round to even`
case. The `bits` contains bit `0`, so we can drop the extra bits
after `0`.
*/
exact = true;
} else {
/*
(bits == 0 || bits == 0x1FF)
The `bits` is filled with all `0` or all `1`, so we need to check
lower bits with another 64-bit multiplication.
*/
u128_mul(sig1, sig2_ext, &hi2, &lo2);
add = lo + hi2;
if (add + 1 > (u64)1) {
/*
(add != 0 && add != U64_MAX) => (add + 1 > 1)
The `add` is not zero, so we don't need to check `round to
even` case. The `add` contains bit `0`, so we can drop the
extra bits after `0`. The `hi` cannot be U64_MAX, so it will
not overflow.
*/
carry = add < lo || add < hi2;
hi += carry;
exact = true;
}
}
if (exact) {
/* normalize */
lz = hi < ((u64)1 << 63);
hi <<= lz;
exp2 -= (i32)lz;
exp2 += 64;
/* test the bit 54 and get rounding direction */
round_up = (hi & ((u64)1 << (64 - 54))) > (u64)0;
hi += (round_up ? ((u64)1 << (64 - 54)) : (u64)0);
/* test overflow */
if (hi < ((u64)1 << (64 - 54))) {
hi = ((u64)1 << 63);
exp2 += 1;
}
/* This is a normal number, convert it to IEEE-754 format. */
hi >>= F64_BITS - F64_SIG_FULL_BITS;
exp2 += F64_BITS - F64_SIG_FULL_BITS + F64_SIG_BITS;
exp2 += F64_EXP_BIAS;
raw = ((u64)exp2 << F64_SIG_BITS) | (hi & F64_SIG_MASK);
return_f64_bin(raw);
}
}
/*
Slow path: read double number exactly with diyfp.
1. Use cached diyfp to get an approximation value.
2. Use bigcomp to check the approximation value if needed.
This algorithm refers to google's double-conversion project:
https://github.com/google/double-conversion
*/
{
const i32 ERR_ULP_LOG = 3;
const i32 ERR_ULP = 1 << ERR_ULP_LOG;
const i32 ERR_CACHED_POW = ERR_ULP / 2;
const i32 ERR_MUL_FIXED = ERR_ULP / 2;
const i32 DIY_SIG_BITS = 64;
const i32 EXP_BIAS = F64_EXP_BIAS + F64_SIG_BITS;
const i32 EXP_SUBNORMAL = -EXP_BIAS + 1;
u64 fp_err;
u32 bits;
i32 order_of_magnitude;
i32 effective_significand_size;
i32 precision_digits_count;
u64 precision_bits;
u64 half_way;
u64 raw;
diy_fp fp, fp_upper;
bigint big_full, big_comp;
i32 cmp;
fp.sig = sig;
fp.exp = 0;
fp_err = sig_cut ? (u64)(ERR_ULP / 2) : (u64)0;
/* normalize */
bits = u64_lz_bits(fp.sig);
fp.sig <<= bits;
fp.exp -= (i32)bits;
fp_err <<= bits;
/* multiply and add error */
fp = diy_fp_mul(fp, diy_fp_get_cached_pow10(exp));
fp_err += (u64)ERR_CACHED_POW + (fp_err != 0) + (u64)ERR_MUL_FIXED;
/* normalize */
bits = u64_lz_bits(fp.sig);
fp.sig <<= bits;
fp.exp -= (i32)bits;
fp_err <<= bits;
/* effective significand */
order_of_magnitude = DIY_SIG_BITS + fp.exp;
if (likely(order_of_magnitude >= EXP_SUBNORMAL + F64_SIG_FULL_BITS)) {
effective_significand_size = F64_SIG_FULL_BITS;
} else if (order_of_magnitude <= EXP_SUBNORMAL) {
effective_significand_size = 0;
} else {
effective_significand_size = order_of_magnitude - EXP_SUBNORMAL;
}
/* precision digits count */
precision_digits_count = DIY_SIG_BITS - effective_significand_size;
if (unlikely(precision_digits_count + ERR_ULP_LOG >= DIY_SIG_BITS)) {
i32 shr = (precision_digits_count + ERR_ULP_LOG) - DIY_SIG_BITS + 1;
fp.sig >>= shr;
fp.exp += shr;
fp_err = (fp_err >> shr) + 1 + (u32)ERR_ULP;
precision_digits_count -= shr;
}
/* half way */
precision_bits = fp.sig & (((u64)1 << precision_digits_count) - 1);
precision_bits *= (u32)ERR_ULP;
half_way = (u64)1 << (precision_digits_count - 1);
half_way *= (u32)ERR_ULP;
/* rounding */
fp.sig >>= precision_digits_count;
fp.sig += (precision_bits >= half_way + fp_err);
fp.exp += precision_digits_count;
/* get IEEE double raw value */
raw = diy_fp_to_ieee_raw(fp);
if (unlikely(raw == F64_RAW_INF)) return_inf();
if (likely(precision_bits <= half_way - fp_err ||
precision_bits >= half_way + fp_err)) {
return_f64_bin(raw); /* number is accurate */
}
/* now the number is the correct value, or the next lower value */
/* upper boundary */
if (raw & F64_EXP_MASK) {
fp_upper.sig = (raw & F64_SIG_MASK) + ((u64)1 << F64_SIG_BITS);
fp_upper.exp = (i32)((raw & F64_EXP_MASK) >> F64_SIG_BITS);
} else {
fp_upper.sig = (raw & F64_SIG_MASK);
fp_upper.exp = 1;
}
fp_upper.exp -= F64_EXP_BIAS + F64_SIG_BITS;
fp_upper.sig <<= 1;
fp_upper.exp -= 1;
fp_upper.sig += 1; /* add half ulp */
/* compare with bigint */
bigint_set_buf(&big_full, sig, &exp, sig_cut, sig_end, dot_pos);
bigint_set_u64(&big_comp, fp_upper.sig);
if (exp >= 0) {
bigint_mul_pow10(&big_full, +exp);
} else {
bigint_mul_pow10(&big_comp, -exp);
}
if (fp_upper.exp > 0) {
bigint_mul_pow2(&big_comp, (u32)+fp_upper.exp);
} else {
bigint_mul_pow2(&big_full, (u32)-fp_upper.exp);
}
cmp = bigint_cmp(&big_full, &big_comp);
if (likely(cmp != 0)) {
/* round down or round up */
raw += (cmp > 0);
} else {
/* falls midway, round to even */
raw += (raw & 1);
}
if (unlikely(raw == F64_RAW_INF)) return_inf();
return_f64_bin(raw);
}
#undef return_err
#undef return_inf
#undef return_0
#undef return_i64
#undef return_f64
#undef return_f64_bin
#undef return_raw
}
#else /* FP_READER */
/**
Read a JSON number.
This is a fallback function if the custom number reader is disabled.
This function use libc's strtod() to read floating-point number.
*/
static_inline bool read_number(u8 **ptr,
u8 **pre,
yyjson_read_flag flg,
yyjson_val *val,
const char **msg) {
#define return_err(_pos, _msg) do { \
*msg = _msg; \
*end = _pos; \
return false; \
} while (false)
#define return_0() do { \
val->tag = YYJSON_TYPE_NUM | (u64)((u8)sign << 3); \
val->uni.u64 = 0; \
*end = cur; return true; \
} while (false)
#define return_i64(_v) do { \
val->tag = YYJSON_TYPE_NUM | (u64)((u8)sign << 3); \
val->uni.u64 = (u64)(sign ? (u64)(~(_v) + 1) : (u64)(_v)); \
*end = cur; return true; \
} while (false)
#define return_f64(_v) do { \
val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \
val->uni.f64 = sign ? -(f64)(_v) : (f64)(_v); \
*end = cur; return true; \
} while (false)
#define return_f64_bin(_v) do { \
val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \
val->uni.u64 = ((u64)sign << 63) | (u64)(_v); \
*end = cur; return true; \
} while (false)
#define return_inf() do { \
if (has_read_flag(BIGNUM_AS_RAW)) return_raw(); \
if (has_read_flag(ALLOW_INF_AND_NAN)) return_f64_bin(F64_RAW_INF); \
else return_err(hdr, "number is infinity when parsed as double"); \
} while (false)
#define return_raw() do { \
if (*pre) **pre = '\0'; /* add null-terminator for previous raw string */ \
val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW; \
val->uni.str = (const char *)hdr; \
*pre = cur; *end = cur; return true; \
} while (false)
u64 sig, num;
u8 *hdr = *ptr;
u8 *cur = *ptr;
u8 **end = ptr;
u8 *dot = NULL;
u8 *f64_end = NULL;
bool sign;
/* read number as raw string if has `YYJSON_READ_NUMBER_AS_RAW` flag */
if (unlikely(pre && !has_read_flag(BIGNUM_AS_RAW))) {
return read_number_raw(ptr, pre, flg, val, msg);
}
sign = (*hdr == '-');
cur += sign;
sig = (u8)(*cur - '0');
/* read first digit, check leading zero */
if (unlikely(!digi_is_digit(*cur))) {
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (read_inf_or_nan(sign, &cur, pre, val)) {
*end = cur;
return true;
}
}
return_err(cur, "no digit after minus sign");
}
if (*cur == '0') {
cur++;
if (unlikely(digi_is_digit(*cur))) {
return_err(cur - 1, "number with leading zero is not allowed");
}
if (!digi_is_fp(*cur)) return_0();
goto read_double;
}
/* read continuous digits, up to 19 characters */
#define expr_intg(i) \
if (likely((num = (u64)(cur[i] - (u8)'0')) <= 9)) sig = num + sig * 10; \
else { cur += i; goto intg_end; }
repeat_in_1_18(expr_intg)
#undef expr_intg
/* here are 19 continuous digits, skip them */
cur += 19;
if (digi_is_digit(cur[0]) && !digi_is_digit_or_fp(cur[1])) {
/* this number is an integer consisting of 20 digits */
num = (u8)(*cur - '0');
if ((sig < (U64_MAX / 10)) ||
(sig == (U64_MAX / 10) && num <= (U64_MAX % 10))) {
sig = num + sig * 10;
cur++;
if (sign) {
if (has_read_flag(BIGNUM_AS_RAW)) return_raw();
return_f64(normalized_u64_to_f64(sig));
}
return_i64(sig);
}
}
intg_end:
/* continuous digits ended */
if (!digi_is_digit_or_fp(*cur)) {
/* this number is an integer consisting of 1 to 19 digits */
if (sign && (sig > ((u64)1 << 63))) {
if (has_read_flag(BIGNUM_AS_RAW)) return_raw();
return_f64(normalized_u64_to_f64(sig));
}
return_i64(sig);
}
read_double:
/* this number should be read as double */
while (digi_is_digit(*cur)) cur++;
if (!digi_is_fp(*cur) && has_read_flag(BIGNUM_AS_RAW)) {
return_raw(); /* it's a large integer */
}
if (*cur == '.') {
/* skip fraction part */
dot = cur;
cur++;
if (!digi_is_digit(*cur)) {
return_err(cur, "no digit after decimal point");
}
cur++;
while (digi_is_digit(*cur)) cur++;
}
if (digi_is_exp(*cur)) {
/* skip exponent part */
cur += 1 + digi_is_sign(cur[1]);
if (!digi_is_digit(*cur)) {
return_err(cur, "no digit after exponent sign");
}
cur++;
while (digi_is_digit(*cur)) cur++;
}
/*
libc's strtod() is used to parse the floating-point number.
Note that the decimal point character used by strtod() is locale-dependent,
and the rounding direction may affected by fesetround().
For currently known locales, (en, zh, ja, ko, am, he, hi) use '.' as the
decimal point, while other locales use ',' as the decimal point.
Here strtod() is called twice for different locales, but if another thread
happens calls setlocale() between two strtod(), parsing may still fail.
*/
val->uni.f64 = strtod((const char *)hdr, (char **)&f64_end);
if (unlikely(f64_end != cur)) {
/* replace '.' with ',' for locale */
bool cut = (*cur == ',');
if (cut) *cur = ' ';
if (dot) *dot = ',';
val->uni.f64 = strtod((const char *)hdr, (char **)&f64_end);
/* restore ',' to '.' */
if (cut) *cur = ',';
if (dot) *dot = '.';
if (unlikely(f64_end != cur)) {
return_err(hdr, "strtod() failed to parse the number");
}
}
if (unlikely(val->uni.f64 >= HUGE_VAL || val->uni.f64 <= -HUGE_VAL)) {
return_inf();
}
val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;
*end = cur;
return true;
#undef return_err
#undef return_0
#undef return_i64
#undef return_f64
#undef return_f64_bin
#undef return_inf
#undef return_raw
}
#endif /* FP_READER */
/*==============================================================================
* JSON String Reader
*============================================================================*/
/**
Read a JSON string.
@param ptr The head pointer of string before '"' prefix (inout).
@param lst JSON last position.
@param inv Allow invalid unicode.
@param val The string value to be written.
@param msg The error message pointer.
@return Whether success.
*/
static_inline bool read_string(u8 **ptr,
u8 *lst,
bool inv,
yyjson_val *val,
const char **msg) {
/*
Each unicode code point is encoded as 1 to 4 bytes in UTF-8 encoding,
we use 4-byte mask and pattern value to validate UTF-8 byte sequence,
this requires the input data to have 4-byte zero padding.
---------------------------------------------------
1 byte
unicode range [U+0000, U+007F]
unicode min [.......0]
unicode max [.1111111]
bit pattern [0.......]
---------------------------------------------------
2 byte
unicode range [U+0080, U+07FF]
unicode min [......10 ..000000]
unicode max [...11111 ..111111]
bit require [...xxxx. ........] (1E 00)
bit mask [xxx..... xx......] (E0 C0)
bit pattern [110..... 10......] (C0 80)
---------------------------------------------------
3 byte
unicode range [U+0800, U+FFFF]
unicode min [........ ..100000 ..000000]
unicode max [....1111 ..111111 ..111111]
bit require [....xxxx ..x..... ........] (0F 20 00)
bit mask [xxxx.... xx...... xx......] (F0 C0 C0)
bit pattern [1110.... 10...... 10......] (E0 80 80)
---------------------------------------------------
3 byte invalid (reserved for surrogate halves)
unicode range [U+D800, U+DFFF]
unicode min [....1101 ..100000 ..000000]
unicode max [....1101 ..111111 ..111111]
bit mask [....xxxx ..x..... ........] (0F 20 00)
bit pattern [....1101 ..1..... ........] (0D 20 00)
---------------------------------------------------
4 byte
unicode range [U+10000, U+10FFFF]
unicode min [........ ...10000 ..000000 ..000000]
unicode max [.....100 ..001111 ..111111 ..111111]
bit require [.....xxx ..xx.... ........ ........] (07 30 00 00)
bit mask [xxxxx... xx...... xx...... xx......] (F8 C0 C0 C0)
bit pattern [11110... 10...... 10...... 10......] (F0 80 80 80)
---------------------------------------------------
*/
#if YYJSON_ENDIAN == YYJSON_BIG_ENDIAN
const u32 b1_mask = 0x80000000UL;
const u32 b1_patt = 0x00000000UL;
const u32 b2_mask = 0xE0C00000UL;
const u32 b2_patt = 0xC0800000UL;
const u32 b2_requ = 0x1E000000UL;
const u32 b3_mask = 0xF0C0C000UL;
const u32 b3_patt = 0xE0808000UL;
const u32 b3_requ = 0x0F200000UL;
const u32 b3_erro = 0x0D200000UL;
const u32 b4_mask = 0xF8C0C0C0UL;
const u32 b4_patt = 0xF0808080UL;
const u32 b4_requ = 0x07300000UL;
const u32 b4_err0 = 0x04000000UL;
const u32 b4_err1 = 0x03300000UL;
#elif YYJSON_ENDIAN == YYJSON_LITTLE_ENDIAN
const u32 b1_mask = 0x00000080UL;
const u32 b1_patt = 0x00000000UL;
const u32 b2_mask = 0x0000C0E0UL;
const u32 b2_patt = 0x000080C0UL;
const u32 b2_requ = 0x0000001EUL;
const u32 b3_mask = 0x00C0C0F0UL;
const u32 b3_patt = 0x008080E0UL;
const u32 b3_requ = 0x0000200FUL;
const u32 b3_erro = 0x0000200DUL;
const u32 b4_mask = 0xC0C0C0F8UL;
const u32 b4_patt = 0x808080F0UL;
const u32 b4_requ = 0x00003007UL;
const u32 b4_err0 = 0x00000004UL;
const u32 b4_err1 = 0x00003003UL;
#else
/* this should be evaluated at compile-time */
v32_uni b1_mask_uni = {{ 0x80, 0x00, 0x00, 0x00 }};
v32_uni b1_patt_uni = {{ 0x00, 0x00, 0x00, 0x00 }};
v32_uni b2_mask_uni = {{ 0xE0, 0xC0, 0x00, 0x00 }};
v32_uni b2_patt_uni = {{ 0xC0, 0x80, 0x00, 0x00 }};
v32_uni b2_requ_uni = {{ 0x1E, 0x00, 0x00, 0x00 }};
v32_uni b3_mask_uni = {{ 0xF0, 0xC0, 0xC0, 0x00 }};
v32_uni b3_patt_uni = {{ 0xE0, 0x80, 0x80, 0x00 }};
v32_uni b3_requ_uni = {{ 0x0F, 0x20, 0x00, 0x00 }};
v32_uni b3_erro_uni = {{ 0x0D, 0x20, 0x00, 0x00 }};
v32_uni b4_mask_uni = {{ 0xF8, 0xC0, 0xC0, 0xC0 }};
v32_uni b4_patt_uni = {{ 0xF0, 0x80, 0x80, 0x80 }};
v32_uni b4_requ_uni = {{ 0x07, 0x30, 0x00, 0x00 }};
v32_uni b4_err0_uni = {{ 0x04, 0x00, 0x00, 0x00 }};
v32_uni b4_err1_uni = {{ 0x03, 0x30, 0x00, 0x00 }};
u32 b1_mask = b1_mask_uni.u;
u32 b1_patt = b1_patt_uni.u;
u32 b2_mask = b2_mask_uni.u;
u32 b2_patt = b2_patt_uni.u;
u32 b2_requ = b2_requ_uni.u;
u32 b3_mask = b3_mask_uni.u;
u32 b3_patt = b3_patt_uni.u;
u32 b3_requ = b3_requ_uni.u;
u32 b3_erro = b3_erro_uni.u;
u32 b4_mask = b4_mask_uni.u;
u32 b4_patt = b4_patt_uni.u;
u32 b4_requ = b4_requ_uni.u;
u32 b4_err0 = b4_err0_uni.u;
u32 b4_err1 = b4_err1_uni.u;
#endif
#define is_valid_seq_1(uni) ( \
((uni & b1_mask) == b1_patt) \
)
#define is_valid_seq_2(uni) ( \
((uni & b2_mask) == b2_patt) && \
((uni & b2_requ)) \
)
#define is_valid_seq_3(uni) ( \
((uni & b3_mask) == b3_patt) && \
((tmp = (uni & b3_requ))) && \
((tmp != b3_erro)) \
)
#define is_valid_seq_4(uni) ( \
((uni & b4_mask) == b4_patt) && \
((tmp = (uni & b4_requ))) && \
((tmp & b4_err0) == 0 || (tmp & b4_err1) == 0) \
)
#define return_err(_end, _msg) do { \
*msg = _msg; \
*end = _end; \
return false; \
} while (false)
u8 *cur = *ptr;
u8 **end = ptr;
u8 *src = ++cur, *dst, *pos;
u16 hi, lo;
u32 uni, tmp;
skip_ascii:
/* Most strings have no escaped characters, so we can jump them quickly. */
skip_ascii_begin:
/*
We want to make loop unrolling, as shown in the following code. Some
compiler may not generate instructions as expected, so we rewrite it with
explicit goto statements. We hope the compiler can generate instructions
like this: https://godbolt.org/z/8vjsYq
while (true) repeat16({
if (likely(!(char_is_ascii_stop(*src)))) src++;
else break;
})
*/
#define expr_jump(i) \
if (likely(!char_is_ascii_stop(src[i]))) {} \
else goto skip_ascii_stop##i;
#define expr_stop(i) \
skip_ascii_stop##i: \
src += i; \
goto skip_ascii_end;
repeat16_incr(expr_jump)
src += 16;
goto skip_ascii_begin;
repeat16_incr(expr_stop)
#undef expr_jump
#undef expr_stop
skip_ascii_end:
/*
GCC may store src[i] in a register at each line of expr_jump(i) above.
These instructions are useless and will degrade performance.
This inline asm is a hint for gcc: "the memory has been modified,
do not cache it".
MSVC, Clang, ICC can generate expected instructions without this hint.
*/
#if YYJSON_IS_REAL_GCC
__asm__ volatile("":"=m"(*src));
#endif
if (likely(*src == '"')) {
val->tag = ((u64)(src - cur) << YYJSON_TAG_BIT) |
(u64)(YYJSON_TYPE_STR);
val->uni.str = (const char *)cur;
*src = '\0';
*end = src + 1;
return true;
}
skip_utf8:
if (*src & 0x80) { /* non-ASCII character */
/*
Non-ASCII character appears here, which means that the text is likely
to be written in non-English or emoticons. According to some common
data set statistics, byte sequences of the same length may appear
consecutively. We process the byte sequences of the same length in each
loop, which is more friendly to branch prediction.
*/
pos = src;
#if YYJSON_DISABLE_UTF8_VALIDATION
while (true) repeat8({
if (likely((*src & 0xF0) == 0xE0)) src += 3;
else break;
})
if (*src < 0x80) goto skip_ascii;
while (true) repeat8({
if (likely((*src & 0xE0) == 0xC0)) src += 2;
else break;
})
while (true) repeat8({
if (likely((*src & 0xF8) == 0xF0)) src += 4;
else break;
})
#else
uni = byte_load_4(src);
while (is_valid_seq_3(uni)) {
src += 3;
uni = byte_load_4(src);
}
if (is_valid_seq_1(uni)) goto skip_ascii;
while (is_valid_seq_2(uni)) {
src += 2;
uni = byte_load_4(src);
}
while (is_valid_seq_4(uni)) {
src += 4;
uni = byte_load_4(src);
}
#endif
if (false) {
if (!inv) return_err(src, "invalid UTF-8 encoding in string");
++src;
}
goto skip_ascii;
}
/* The escape character appears, we need to copy it. */
dst = src;
copy_escape:
if (likely(*src == '\\')) {
switch (*++src) {
case '"': *dst++ = '"'; src++; break;
case '\\': *dst++ = '\\'; src++; break;
case '/': *dst++ = '/'; src++; break;
case 'b': *dst++ = '\b'; src++; break;
case 'f': *dst++ = '\f'; src++; break;
case 'n': *dst++ = '\n'; src++; break;
case 'r': *dst++ = '\r'; src++; break;
case 't': *dst++ = '\t'; src++; break;
case 'u':
if (unlikely(!read_hex_u16(++src, &hi))) {
return_err(src - 2, "invalid escaped sequence in string");
}
src += 4;
if (likely((hi & 0xF800) != 0xD800)) {
/* a BMP character */
if (hi >= 0x800) {
*dst++ = (u8)(0xE0 | (hi >> 12));
*dst++ = (u8)(0x80 | ((hi >> 6) & 0x3F));
*dst++ = (u8)(0x80 | (hi & 0x3F));
} else if (hi >= 0x80) {
*dst++ = (u8)(0xC0 | (hi >> 6));
*dst++ = (u8)(0x80 | (hi & 0x3F));
} else {
*dst++ = (u8)hi;
}
} else {
/* a non-BMP character, represented as a surrogate pair */
if (unlikely((hi & 0xFC00) != 0xD800)) {
return_err(src - 6, "invalid high surrogate in string");
}
if (unlikely(!byte_match_2(src, "\\u"))) {
return_err(src, "no low surrogate in string");
}
if (unlikely(!read_hex_u16(src + 2, &lo))) {
return_err(src, "invalid escaped sequence in string");
}
if (unlikely((lo & 0xFC00) != 0xDC00)) {
return_err(src, "invalid low surrogate in string");
}
uni = ((((u32)hi - 0xD800) << 10) |
((u32)lo - 0xDC00)) + 0x10000;
*dst++ = (u8)(0xF0 | (uni >> 18));
*dst++ = (u8)(0x80 | ((uni >> 12) & 0x3F));
*dst++ = (u8)(0x80 | ((uni >> 6) & 0x3F));
*dst++ = (u8)(0x80 | (uni & 0x3F));
src += 6;
}
break;
default: return_err(src, "invalid escaped character in string");
}
} else if (likely(*src == '"')) {
val->tag = ((u64)(dst - cur) << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;
val->uni.str = (const char *)cur;
*dst = '\0';
*end = src + 1;
return true;
} else {
if (!inv) return_err(src, "unexpected control character in string");
if (src >= lst) return_err(src, "unclosed string");
*dst++ = *src++;
}
copy_ascii:
/*
Copy continuous ASCII, loop unrolling, same as the following code:
while (true) repeat16({
if (unlikely(char_is_ascii_stop(*src))) break;
*dst++ = *src++;
})
*/
#if YYJSON_IS_REAL_GCC
# define expr_jump(i) \
if (likely(!(char_is_ascii_stop(src[i])))) {} \
else { __asm__ volatile("":"=m"(src[i])); goto copy_ascii_stop_##i; }
#else
# define expr_jump(i) \
if (likely(!(char_is_ascii_stop(src[i])))) {} \
else { goto copy_ascii_stop_##i; }
#endif
repeat16_incr(expr_jump)
#undef expr_jump
byte_move_16(dst, src);
src += 16;
dst += 16;
goto copy_ascii;
/*
The memory will be moved forward by at least 1 byte. So the `byte_move`
can be one byte more than needed to reduce the number of instructions.
*/
copy_ascii_stop_0:
goto copy_utf8;
copy_ascii_stop_1:
byte_move_2(dst, src);
src += 1;
dst += 1;
goto copy_utf8;
copy_ascii_stop_2:
byte_move_2(dst, src);
src += 2;
dst += 2;
goto copy_utf8;
copy_ascii_stop_3:
byte_move_4(dst, src);
src += 3;
dst += 3;
goto copy_utf8;
copy_ascii_stop_4:
byte_move_4(dst, src);
src += 4;
dst += 4;
goto copy_utf8;
copy_ascii_stop_5:
byte_move_4(dst, src);
byte_move_2(dst + 4, src + 4);
src += 5;
dst += 5;
goto copy_utf8;
copy_ascii_stop_6:
byte_move_4(dst, src);
byte_move_2(dst + 4, src + 4);
src += 6;
dst += 6;
goto copy_utf8;
copy_ascii_stop_7:
byte_move_8(dst, src);
src += 7;
dst += 7;
goto copy_utf8;
copy_ascii_stop_8:
byte_move_8(dst, src);
src += 8;
dst += 8;
goto copy_utf8;
copy_ascii_stop_9:
byte_move_8(dst, src);
byte_move_2(dst + 8, src + 8);
src += 9;
dst += 9;
goto copy_utf8;
copy_ascii_stop_10:
byte_move_8(dst, src);
byte_move_2(dst + 8, src + 8);
src += 10;
dst += 10;
goto copy_utf8;
copy_ascii_stop_11:
byte_move_8(dst, src);
byte_move_4(dst + 8, src + 8);
src += 11;
dst += 11;
goto copy_utf8;
copy_ascii_stop_12:
byte_move_8(dst, src);
byte_move_4(dst + 8, src + 8);
src += 12;
dst += 12;
goto copy_utf8;
copy_ascii_stop_13:
byte_move_8(dst, src);
byte_move_4(dst + 8, src + 8);
byte_move_2(dst + 12, src + 12);
src += 13;
dst += 13;
goto copy_utf8;
copy_ascii_stop_14:
byte_move_8(dst, src);
byte_move_4(dst + 8, src + 8);
byte_move_2(dst + 12, src + 12);
src += 14;
dst += 14;
goto copy_utf8;
copy_ascii_stop_15:
byte_move_16(dst, src);
src += 15;
dst += 15;
goto copy_utf8;
copy_utf8:
if (*src & 0x80) { /* non-ASCII character */
pos = src;
uni = byte_load_4(src);
#if YYJSON_DISABLE_UTF8_VALIDATION
while (true) repeat4({
if ((uni & b3_mask) == b3_patt) {
byte_copy_4(dst, &uni);
dst += 3;
src += 3;
uni = byte_load_4(src);
} else break;
})
if ((uni & b1_mask) == b1_patt) goto copy_ascii;
while (true) repeat4({
if ((uni & b2_mask) == b2_patt) {
byte_copy_2(dst, &uni);
dst += 2;
src += 2;
uni = byte_load_4(src);
} else break;
})
while (true) repeat4({
if ((uni & b4_mask) == b4_patt) {
byte_copy_4(dst, &uni);
dst += 4;
src += 4;
uni = byte_load_4(src);
} else break;
})
#else
while (is_valid_seq_3(uni)) {
byte_copy_4(dst, &uni);
dst += 3;
src += 3;
uni = byte_load_4(src);
}
if (is_valid_seq_1(uni)) goto copy_ascii;
while (is_valid_seq_2(uni)) {
byte_copy_2(dst, &uni);
dst += 2;
src += 2;
uni = byte_load_4(src);
}
while (is_valid_seq_4(uni)) {
byte_copy_4(dst, &uni);
dst += 4;
src += 4;
uni = byte_load_4(src);
}
#endif
if (false) {
if (!inv) return_err(src, "invalid UTF-8 encoding in string");
goto copy_ascii_stop_1;
}
goto copy_ascii;
}
goto copy_escape;
#undef return_err
#undef is_valid_seq_1
#undef is_valid_seq_2
#undef is_valid_seq_3
#undef is_valid_seq_4
}
/*==============================================================================
* JSON Reader Implementation
*
* We use goto statements to build the finite state machine (FSM).
* The FSM's state was held by program counter (PC) and the 'goto' make the
* state transitions.
*============================================================================*/
/** Read single value JSON document. */
static_noinline yyjson_doc *read_root_single(u8 *hdr,
u8 *cur,
u8 *end,
yyjson_alc alc,
yyjson_read_flag flg,
yyjson_read_err *err) {
#define return_err(_pos, _code, _msg) do { \
if (is_truncated_end(hdr, _pos, end, YYJSON_READ_ERROR_##_code, flg)) { \
err->pos = (usize)(end - hdr); \
err->code = YYJSON_READ_ERROR_UNEXPECTED_END; \
err->msg = "unexpected end of data"; \
} else { \
err->pos = (usize)(_pos - hdr); \
err->code = YYJSON_READ_ERROR_##_code; \
err->msg = _msg; \
} \
if (val_hdr) alc.free(alc.ctx, (void *)val_hdr); \
return NULL; \
} while (false)
usize hdr_len; /* value count used by doc */
usize alc_num; /* value count capacity */
yyjson_val *val_hdr; /* the head of allocated values */
yyjson_val *val; /* current value */
yyjson_doc *doc; /* the JSON document, equals to val_hdr */
const char *msg; /* error message */
bool raw; /* read number as raw */
bool inv; /* allow invalid unicode */
u8 *raw_end; /* raw end for null-terminator */
u8 **pre; /* previous raw end pointer */
hdr_len = sizeof(yyjson_doc) / sizeof(yyjson_val);
hdr_len += (sizeof(yyjson_doc) % sizeof(yyjson_val)) > 0;
alc_num = hdr_len + 1; /* single value */
val_hdr = (yyjson_val *)alc.malloc(alc.ctx, alc_num * sizeof(yyjson_val));
if (unlikely(!val_hdr)) goto fail_alloc;
val = val_hdr + hdr_len;
raw = has_read_flag(NUMBER_AS_RAW) || has_read_flag(BIGNUM_AS_RAW);
inv = has_read_flag(ALLOW_INVALID_UNICODE) != 0;
raw_end = NULL;
pre = raw ? &raw_end : NULL;
if (char_is_number(*cur)) {
if (likely(read_number(&cur, pre, flg, val, &msg))) goto doc_end;
goto fail_number;
}
if (*cur == '"') {
if (likely(read_string(&cur, end, inv, val, &msg))) goto doc_end;
goto fail_string;
}
if (*cur == 't') {
if (likely(read_true(&cur, val))) goto doc_end;
goto fail_literal;
}
if (*cur == 'f') {
if (likely(read_false(&cur, val))) goto doc_end;
goto fail_literal;
}
if (*cur == 'n') {
if (likely(read_null(&cur, val))) goto doc_end;
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (read_nan(false, &cur, pre, val)) goto doc_end;
}
goto fail_literal;
}
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (read_inf_or_nan(false, &cur, pre, val)) goto doc_end;
}
goto fail_character;
doc_end:
/* check invalid contents after json document */
if (unlikely(cur < end) && !has_read_flag(STOP_WHEN_DONE)) {
if (has_read_flag(ALLOW_COMMENTS)) {
if (!skip_spaces_and_comments(&cur)) {
if (byte_match_2(cur, "/*")) goto fail_comment;
}
} else {
while (char_is_space(*cur)) cur++;
}
if (unlikely(cur < end)) goto fail_garbage;
}
if (pre && *pre) **pre = '\0';
doc = (yyjson_doc *)val_hdr;
doc->root = val_hdr + hdr_len;
doc->alc = alc;
doc->dat_read = (usize)(cur - hdr);
doc->val_read = 1;
doc->str_pool = has_read_flag(INSITU) ? NULL : (char *)hdr;
return doc;
fail_string:
return_err(cur, INVALID_STRING, msg);
fail_number:
return_err(cur, INVALID_NUMBER, msg);
fail_alloc:
return_err(cur, MEMORY_ALLOCATION, "memory allocation failed");
fail_literal:
return_err(cur, LITERAL, "invalid literal");
fail_comment:
return_err(cur, INVALID_COMMENT, "unclosed multiline comment");
fail_character:
return_err(cur, UNEXPECTED_CHARACTER, "unexpected character");
fail_garbage:
return_err(cur, UNEXPECTED_CONTENT, "unexpected content after document");
#undef return_err
}
/** Read JSON document (accept all style, but optimized for minify). */
static_inline yyjson_doc *read_root_minify(u8 *hdr,
u8 *cur,
u8 *end,
yyjson_alc alc,
yyjson_read_flag flg,
yyjson_read_err *err) {
#define return_err(_pos, _code, _msg) do { \
if (is_truncated_end(hdr, _pos, end, YYJSON_READ_ERROR_##_code, flg)) { \
err->pos = (usize)(end - hdr); \
err->code = YYJSON_READ_ERROR_UNEXPECTED_END; \
err->msg = "unexpected end of data"; \
} else { \
err->pos = (usize)(_pos - hdr); \
err->code = YYJSON_READ_ERROR_##_code; \
err->msg = _msg; \
} \
if (val_hdr) alc.free(alc.ctx, (void *)val_hdr); \
return NULL; \
} while (false)
#define val_incr() do { \
val++; \
if (unlikely(val >= val_end)) { \
usize alc_old = alc_len; \
alc_len += alc_len / 2; \
if ((sizeof(usize) < 8) && (alc_len >= alc_max)) goto fail_alloc; \
val_tmp = (yyjson_val *)alc.realloc(alc.ctx, (void *)val_hdr, \
alc_old * sizeof(yyjson_val), \
alc_len * sizeof(yyjson_val)); \
if ((!val_tmp)) goto fail_alloc; \
val = val_tmp + (usize)(val - val_hdr); \
ctn = val_tmp + (usize)(ctn - val_hdr); \
val_hdr = val_tmp; \
val_end = val_tmp + (alc_len - 2); \
} \
} while (false)
usize dat_len; /* data length in bytes, hint for allocator */
usize hdr_len; /* value count used by yyjson_doc */
usize alc_len; /* value count allocated */
usize alc_max; /* maximum value count for allocator */
usize ctn_len; /* the number of elements in current container */
yyjson_val *val_hdr; /* the head of allocated values */
yyjson_val *val_end; /* the end of allocated values */
yyjson_val *val_tmp; /* temporary pointer for realloc */
yyjson_val *val; /* current JSON value */
yyjson_val *ctn; /* current container */
yyjson_val *ctn_parent; /* parent of current container */
yyjson_doc *doc; /* the JSON document, equals to val_hdr */
const char *msg; /* error message */
bool raw; /* read number as raw */
bool inv; /* allow invalid unicode */
u8 *raw_end; /* raw end for null-terminator */
u8 **pre; /* previous raw end pointer */
dat_len = has_read_flag(STOP_WHEN_DONE) ? 256 : (usize)(end - cur);
hdr_len = sizeof(yyjson_doc) / sizeof(yyjson_val);
hdr_len += (sizeof(yyjson_doc) % sizeof(yyjson_val)) > 0;
alc_max = USIZE_MAX / sizeof(yyjson_val);
alc_len = hdr_len + (dat_len / YYJSON_READER_ESTIMATED_MINIFY_RATIO) + 4;
alc_len = yyjson_min(alc_len, alc_max);
val_hdr = (yyjson_val *)alc.malloc(alc.ctx, alc_len * sizeof(yyjson_val));
if (unlikely(!val_hdr)) goto fail_alloc;
val_end = val_hdr + (alc_len - 2); /* padding for key-value pair reading */
val = val_hdr + hdr_len;
ctn = val;
ctn_len = 0;
raw = has_read_flag(NUMBER_AS_RAW) || has_read_flag(BIGNUM_AS_RAW);
inv = has_read_flag(ALLOW_INVALID_UNICODE) != 0;
raw_end = NULL;
pre = raw ? &raw_end : NULL;
if (*cur++ == '{') {
ctn->tag = YYJSON_TYPE_OBJ;
ctn->uni.ofs = 0;
goto obj_key_begin;
} else {
ctn->tag = YYJSON_TYPE_ARR;
ctn->uni.ofs = 0;
goto arr_val_begin;
}
arr_begin:
/* save current container */
ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |
(ctn->tag & YYJSON_TAG_MASK);
/* create a new array value, save parent container offset */
val_incr();
val->tag = YYJSON_TYPE_ARR;
val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);
/* push the new array value as current container */
ctn = val;
ctn_len = 0;
arr_val_begin:
if (*cur == '{') {
cur++;
goto obj_begin;
}
if (*cur == '[') {
cur++;
goto arr_begin;
}
if (char_is_number(*cur)) {
val_incr();
ctn_len++;
if (likely(read_number(&cur, pre, flg, val, &msg))) goto arr_val_end;
goto fail_number;
}
if (*cur == '"') {
val_incr();
ctn_len++;
if (likely(read_string(&cur, end, inv, val, &msg))) goto arr_val_end;
goto fail_string;
}
if (*cur == 't') {
val_incr();
ctn_len++;
if (likely(read_true(&cur, val))) goto arr_val_end;
goto fail_literal;
}
if (*cur == 'f') {
val_incr();
ctn_len++;
if (likely(read_false(&cur, val))) goto arr_val_end;
goto fail_literal;
}
if (*cur == 'n') {
val_incr();
ctn_len++;
if (likely(read_null(&cur, val))) goto arr_val_end;
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (read_nan(false, &cur, pre, val)) goto arr_val_end;
}
goto fail_literal;
}
if (*cur == ']') {
cur++;
if (likely(ctn_len == 0)) goto arr_end;
if (has_read_flag(ALLOW_TRAILING_COMMAS)) goto arr_end;
while (*cur != ',') cur--;
goto fail_trailing_comma;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto arr_val_begin;
}
if (has_read_flag(ALLOW_INF_AND_NAN) &&
(*cur == 'i' || *cur == 'I' || *cur == 'N')) {
val_incr();
ctn_len++;
if (read_inf_or_nan(false, &cur, pre, val)) goto arr_val_end;
goto fail_character;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto arr_val_begin;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
arr_val_end:
if (*cur == ',') {
cur++;
goto arr_val_begin;
}
if (*cur == ']') {
cur++;
goto arr_end;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto arr_val_end;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto arr_val_end;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
arr_end:
/* get parent container */
ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);
/* save the next sibling value offset */
ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);
ctn->tag = ((ctn_len) << YYJSON_TAG_BIT) | YYJSON_TYPE_ARR;
if (unlikely(ctn == ctn_parent)) goto doc_end;
/* pop parent as current container */
ctn = ctn_parent;
ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);
if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {
goto obj_val_end;
} else {
goto arr_val_end;
}
obj_begin:
/* push container */
ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |
(ctn->tag & YYJSON_TAG_MASK);
val_incr();
val->tag = YYJSON_TYPE_OBJ;
/* offset to the parent */
val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);
ctn = val;
ctn_len = 0;
obj_key_begin:
if (likely(*cur == '"')) {
val_incr();
ctn_len++;
if (likely(read_string(&cur, end, inv, val, &msg))) goto obj_key_end;
goto fail_string;
}
if (likely(*cur == '}')) {
cur++;
if (likely(ctn_len == 0)) goto obj_end;
if (has_read_flag(ALLOW_TRAILING_COMMAS)) goto obj_end;
while (*cur != ',') cur--;
goto fail_trailing_comma;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto obj_key_begin;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto obj_key_begin;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
obj_key_end:
if (*cur == ':') {
cur++;
goto obj_val_begin;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto obj_key_end;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto obj_key_end;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
obj_val_begin:
if (*cur == '"') {
val++;
ctn_len++;
if (likely(read_string(&cur, end, inv, val, &msg))) goto obj_val_end;
goto fail_string;
}
if (char_is_number(*cur)) {
val++;
ctn_len++;
if (likely(read_number(&cur, pre, flg, val, &msg))) goto obj_val_end;
goto fail_number;
}
if (*cur == '{') {
cur++;
goto obj_begin;
}
if (*cur == '[') {
cur++;
goto arr_begin;
}
if (*cur == 't') {
val++;
ctn_len++;
if (likely(read_true(&cur, val))) goto obj_val_end;
goto fail_literal;
}
if (*cur == 'f') {
val++;
ctn_len++;
if (likely(read_false(&cur, val))) goto obj_val_end;
goto fail_literal;
}
if (*cur == 'n') {
val++;
ctn_len++;
if (likely(read_null(&cur, val))) goto obj_val_end;
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (read_nan(false, &cur, pre, val)) goto obj_val_end;
}
goto fail_literal;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto obj_val_begin;
}
if (has_read_flag(ALLOW_INF_AND_NAN) &&
(*cur == 'i' || *cur == 'I' || *cur == 'N')) {
val++;
ctn_len++;
if (read_inf_or_nan(false, &cur, pre, val)) goto obj_val_end;
goto fail_character;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto obj_val_begin;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
obj_val_end:
if (likely(*cur == ',')) {
cur++;
goto obj_key_begin;
}
if (likely(*cur == '}')) {
cur++;
goto obj_end;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto obj_val_end;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto obj_val_end;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
obj_end:
/* pop container */
ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);
/* point to the next value */
ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);
ctn->tag = (ctn_len << (YYJSON_TAG_BIT - 1)) | YYJSON_TYPE_OBJ;
if (unlikely(ctn == ctn_parent)) goto doc_end;
ctn = ctn_parent;
ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);
if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {
goto obj_val_end;
} else {
goto arr_val_end;
}
doc_end:
/* check invalid contents after json document */
if (unlikely(cur < end) && !has_read_flag(STOP_WHEN_DONE)) {
if (has_read_flag(ALLOW_COMMENTS)) {
skip_spaces_and_comments(&cur);
if (byte_match_2(cur, "/*")) goto fail_comment;
} else {
while (char_is_space(*cur)) cur++;
}
if (unlikely(cur < end)) goto fail_garbage;
}
if (pre && *pre) **pre = '\0';
doc = (yyjson_doc *)val_hdr;
doc->root = val_hdr + hdr_len;
doc->alc = alc;
doc->dat_read = (usize)(cur - hdr);
doc->val_read = (usize)((val - doc->root) + 1);
doc->str_pool = has_read_flag(INSITU) ? NULL : (char *)hdr;
return doc;
fail_string:
return_err(cur, INVALID_STRING, msg);
fail_number:
return_err(cur, INVALID_NUMBER, msg);
fail_alloc:
return_err(cur, MEMORY_ALLOCATION, "memory allocation failed");
fail_trailing_comma:
return_err(cur, JSON_STRUCTURE, "trailing comma is not allowed");
fail_literal:
return_err(cur, LITERAL, "invalid literal");
fail_comment:
return_err(cur, INVALID_COMMENT, "unclosed multiline comment");
fail_character:
return_err(cur, UNEXPECTED_CHARACTER, "unexpected character");
fail_garbage:
return_err(cur, UNEXPECTED_CONTENT, "unexpected content after document");
#undef val_incr
#undef return_err
}
/** Read JSON document (accept all style, but optimized for pretty). */
static_inline yyjson_doc *read_root_pretty(u8 *hdr,
u8 *cur,
u8 *end,
yyjson_alc alc,
yyjson_read_flag flg,
yyjson_read_err *err) {
#define return_err(_pos, _code, _msg) do { \
if (is_truncated_end(hdr, _pos, end, YYJSON_READ_ERROR_##_code, flg)) { \
err->pos = (usize)(end - hdr); \
err->code = YYJSON_READ_ERROR_UNEXPECTED_END; \
err->msg = "unexpected end of data"; \
} else { \
err->pos = (usize)(_pos - hdr); \
err->code = YYJSON_READ_ERROR_##_code; \
err->msg = _msg; \
} \
if (val_hdr) alc.free(alc.ctx, (void *)val_hdr); \
return NULL; \
} while (false)
#define val_incr() do { \
val++; \
if (unlikely(val >= val_end)) { \
usize alc_old = alc_len; \
alc_len += alc_len / 2; \
if ((sizeof(usize) < 8) && (alc_len >= alc_max)) goto fail_alloc; \
val_tmp = (yyjson_val *)alc.realloc(alc.ctx, (void *)val_hdr, \
alc_old * sizeof(yyjson_val), \
alc_len * sizeof(yyjson_val)); \
if ((!val_tmp)) goto fail_alloc; \
val = val_tmp + (usize)(val - val_hdr); \
ctn = val_tmp + (usize)(ctn - val_hdr); \
val_hdr = val_tmp; \
val_end = val_tmp + (alc_len - 2); \
} \
} while (false)
usize dat_len; /* data length in bytes, hint for allocator */
usize hdr_len; /* value count used by yyjson_doc */
usize alc_len; /* value count allocated */
usize alc_max; /* maximum value count for allocator */
usize ctn_len; /* the number of elements in current container */
yyjson_val *val_hdr; /* the head of allocated values */
yyjson_val *val_end; /* the end of allocated values */
yyjson_val *val_tmp; /* temporary pointer for realloc */
yyjson_val *val; /* current JSON value */
yyjson_val *ctn; /* current container */
yyjson_val *ctn_parent; /* parent of current container */
yyjson_doc *doc; /* the JSON document, equals to val_hdr */
const char *msg; /* error message */
bool raw; /* read number as raw */
bool inv; /* allow invalid unicode */
u8 *raw_end; /* raw end for null-terminator */
u8 **pre; /* previous raw end pointer */
dat_len = has_read_flag(STOP_WHEN_DONE) ? 256 : (usize)(end - cur);
hdr_len = sizeof(yyjson_doc) / sizeof(yyjson_val);
hdr_len += (sizeof(yyjson_doc) % sizeof(yyjson_val)) > 0;
alc_max = USIZE_MAX / sizeof(yyjson_val);
alc_len = hdr_len + (dat_len / YYJSON_READER_ESTIMATED_PRETTY_RATIO) + 4;
alc_len = yyjson_min(alc_len, alc_max);
val_hdr = (yyjson_val *)alc.malloc(alc.ctx, alc_len * sizeof(yyjson_val));
if (unlikely(!val_hdr)) goto fail_alloc;
val_end = val_hdr + (alc_len - 2); /* padding for key-value pair reading */
val = val_hdr + hdr_len;
ctn = val;
ctn_len = 0;
raw = has_read_flag(NUMBER_AS_RAW) || has_read_flag(BIGNUM_AS_RAW);
inv = has_read_flag(ALLOW_INVALID_UNICODE) != 0;
raw_end = NULL;
pre = raw ? &raw_end : NULL;
if (*cur++ == '{') {
ctn->tag = YYJSON_TYPE_OBJ;
ctn->uni.ofs = 0;
if (*cur == '\n') cur++;
goto obj_key_begin;
} else {
ctn->tag = YYJSON_TYPE_ARR;
ctn->uni.ofs = 0;
if (*cur == '\n') cur++;
goto arr_val_begin;
}
arr_begin:
/* save current container */
ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |
(ctn->tag & YYJSON_TAG_MASK);
/* create a new array value, save parent container offset */
val_incr();
val->tag = YYJSON_TYPE_ARR;
val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);
/* push the new array value as current container */
ctn = val;
ctn_len = 0;
if (*cur == '\n') cur++;
arr_val_begin:
#if YYJSON_IS_REAL_GCC
while (true) repeat16({
if (byte_match_2(cur, " ")) cur += 2;
else break;
})
#else
while (true) repeat16({
if (likely(byte_match_2(cur, " "))) cur += 2;
else break;
})
#endif
if (*cur == '{') {
cur++;
goto obj_begin;
}
if (*cur == '[') {
cur++;
goto arr_begin;
}
if (char_is_number(*cur)) {
val_incr();
ctn_len++;
if (likely(read_number(&cur, pre, flg, val, &msg))) goto arr_val_end;
goto fail_number;
}
if (*cur == '"') {
val_incr();
ctn_len++;
if (likely(read_string(&cur, end, inv, val, &msg))) goto arr_val_end;
goto fail_string;
}
if (*cur == 't') {
val_incr();
ctn_len++;
if (likely(read_true(&cur, val))) goto arr_val_end;
goto fail_literal;
}
if (*cur == 'f') {
val_incr();
ctn_len++;
if (likely(read_false(&cur, val))) goto arr_val_end;
goto fail_literal;
}
if (*cur == 'n') {
val_incr();
ctn_len++;
if (likely(read_null(&cur, val))) goto arr_val_end;
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (read_nan(false, &cur, pre, val)) goto arr_val_end;
}
goto fail_literal;
}
if (*cur == ']') {
cur++;
if (likely(ctn_len == 0)) goto arr_end;
if (has_read_flag(ALLOW_TRAILING_COMMAS)) goto arr_end;
while (*cur != ',') cur--;
goto fail_trailing_comma;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto arr_val_begin;
}
if (has_read_flag(ALLOW_INF_AND_NAN) &&
(*cur == 'i' || *cur == 'I' || *cur == 'N')) {
val_incr();
ctn_len++;
if (read_inf_or_nan(false, &cur, pre, val)) goto arr_val_end;
goto fail_character;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto arr_val_begin;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
arr_val_end:
if (byte_match_2(cur, ",\n")) {
cur += 2;
goto arr_val_begin;
}
if (*cur == ',') {
cur++;
goto arr_val_begin;
}
if (*cur == ']') {
cur++;
goto arr_end;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto arr_val_end;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto arr_val_end;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
arr_end:
/* get parent container */
ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);
/* save the next sibling value offset */
ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);
ctn->tag = ((ctn_len) << YYJSON_TAG_BIT) | YYJSON_TYPE_ARR;
if (unlikely(ctn == ctn_parent)) goto doc_end;
/* pop parent as current container */
ctn = ctn_parent;
ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);
if (*cur == '\n') cur++;
if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {
goto obj_val_end;
} else {
goto arr_val_end;
}
obj_begin:
/* push container */
ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |
(ctn->tag & YYJSON_TAG_MASK);
val_incr();
val->tag = YYJSON_TYPE_OBJ;
/* offset to the parent */
val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);
ctn = val;
ctn_len = 0;
if (*cur == '\n') cur++;
obj_key_begin:
#if YYJSON_IS_REAL_GCC
while (true) repeat16({
if (byte_match_2(cur, " ")) cur += 2;
else break;
})
#else
while (true) repeat16({
if (likely(byte_match_2(cur, " "))) cur += 2;
else break;
})
#endif
if (likely(*cur == '"')) {
val_incr();
ctn_len++;
if (likely(read_string(&cur, end, inv, val, &msg))) goto obj_key_end;
goto fail_string;
}
if (likely(*cur == '}')) {
cur++;
if (likely(ctn_len == 0)) goto obj_end;
if (has_read_flag(ALLOW_TRAILING_COMMAS)) goto obj_end;
while (*cur != ',') cur--;
goto fail_trailing_comma;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto obj_key_begin;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto obj_key_begin;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
obj_key_end:
if (byte_match_2(cur, ": ")) {
cur += 2;
goto obj_val_begin;
}
if (*cur == ':') {
cur++;
goto obj_val_begin;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto obj_key_end;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto obj_key_end;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
obj_val_begin:
if (*cur == '"') {
val++;
ctn_len++;
if (likely(read_string(&cur, end, inv, val, &msg))) goto obj_val_end;
goto fail_string;
}
if (char_is_number(*cur)) {
val++;
ctn_len++;
if (likely(read_number(&cur, pre, flg, val, &msg))) goto obj_val_end;
goto fail_number;
}
if (*cur == '{') {
cur++;
goto obj_begin;
}
if (*cur == '[') {
cur++;
goto arr_begin;
}
if (*cur == 't') {
val++;
ctn_len++;
if (likely(read_true(&cur, val))) goto obj_val_end;
goto fail_literal;
}
if (*cur == 'f') {
val++;
ctn_len++;
if (likely(read_false(&cur, val))) goto obj_val_end;
goto fail_literal;
}
if (*cur == 'n') {
val++;
ctn_len++;
if (likely(read_null(&cur, val))) goto obj_val_end;
if (has_read_flag(ALLOW_INF_AND_NAN)) {
if (read_nan(false, &cur, pre, val)) goto obj_val_end;
}
goto fail_literal;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto obj_val_begin;
}
if (has_read_flag(ALLOW_INF_AND_NAN) &&
(*cur == 'i' || *cur == 'I' || *cur == 'N')) {
val++;
ctn_len++;
if (read_inf_or_nan(false, &cur, pre, val)) goto obj_val_end;
goto fail_character;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto obj_val_begin;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
obj_val_end:
if (byte_match_2(cur, ",\n")) {
cur += 2;
goto obj_key_begin;
}
if (likely(*cur == ',')) {
cur++;
goto obj_key_begin;
}
if (likely(*cur == '}')) {
cur++;
goto obj_end;
}
if (char_is_space(*cur)) {
while (char_is_space(*++cur));
goto obj_val_end;
}
if (has_read_flag(ALLOW_COMMENTS)) {
if (skip_spaces_and_comments(&cur)) goto obj_val_end;
if (byte_match_2(cur, "/*")) goto fail_comment;
}
goto fail_character;
obj_end:
/* pop container */
ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);
/* point to the next value */
ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);
ctn->tag = (ctn_len << (YYJSON_TAG_BIT - 1)) | YYJSON_TYPE_OBJ;
if (unlikely(ctn == ctn_parent)) goto doc_end;
ctn = ctn_parent;
ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);
if (*cur == '\n') cur++;
if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {
goto obj_val_end;
} else {
goto arr_val_end;
}
doc_end:
/* check invalid contents after json document */
if (unlikely(cur < end) && !has_read_flag(STOP_WHEN_DONE)) {
if (has_read_flag(ALLOW_COMMENTS)) {
skip_spaces_and_comments(&cur);
if (byte_match_2(cur, "/*")) goto fail_comment;
} else {
while (char_is_space(*cur)) cur++;
}
if (unlikely(cur < end)) goto fail_garbage;
}
if (pre && *pre) **pre = '\0';
doc = (yyjson_doc *)val_hdr;
doc->root = val_hdr + hdr_len;
doc->alc = alc;
doc->dat_read = (usize)(cur - hdr);
doc->val_read = (usize)((val - val_hdr)) - hdr_len + 1;
doc->str_pool = has_read_flag(INSITU) ? NULL : (char *)hdr;
return doc;
fail_string:
return_err(cur, INVALID_STRING, msg);
fail_number:
return_err(cur, INVALID_NUMBER, msg);
fail_alloc:
return_err(cur, MEMORY_ALLOCATION, "memory allocation failed");
fail_trailing_comma:
return_err(cur, JSON_STRUCTURE, "trailing comma is not allowed");
fail_literal:
return_err(cur, LITERAL, "invalid literal");
fail_comment:
return_err(cur, INVALID_COMMENT, "unclosed multiline comment");
fail_character:
return_err(cur, UNEXPECTED_CHARACTER, "unexpected character");
fail_garbage:
return_err(cur, UNEXPECTED_CONTENT, "unexpected content after document");
#undef val_incr
#undef return_err
}
/*==============================================================================
* JSON Reader Entrance
*============================================================================*/
yyjson_doc *yyjson_read_opts(char *dat,
usize len,
yyjson_read_flag flg,
const yyjson_alc *alc_ptr,
yyjson_read_err *err) {
#define return_err(_pos, _code, _msg) do { \
err->pos = (usize)(_pos); \
err->msg = _msg; \
err->code = YYJSON_READ_ERROR_##_code; \
if (!has_read_flag(INSITU) && hdr) alc.free(alc.ctx, (void *)hdr); \
return NULL; \
} while (false)
yyjson_alc alc;
yyjson_doc *doc;
u8 *hdr = NULL, *end, *cur;
/* validate input parameters */
if (!alc_ptr) {
alc = YYJSON_DEFAULT_ALC;
} else {
alc = *alc_ptr;
}
if (unlikely(!dat)) {
return_err(0, INVALID_PARAMETER, "input data is NULL");
}
if (unlikely(!len)) {
return_err(0, INVALID_PARAMETER, "input length is 0");
}
/* add 4-byte zero padding for input data if necessary */
if (has_read_flag(INSITU)) {
hdr = (u8 *)dat;
end = (u8 *)dat + len;
cur = (u8 *)dat;
} else {
if (unlikely(len >= USIZE_MAX - YYJSON_PADDING_SIZE)) {
return_err(0, MEMORY_ALLOCATION, "memory allocation failed");
}
hdr = (u8 *)alc.malloc(alc.ctx, len + YYJSON_PADDING_SIZE);
if (unlikely(!hdr)) {
return_err(0, MEMORY_ALLOCATION, "memory allocation failed");
}
end = hdr + len;
cur = hdr;
memcpy(hdr, dat, len);
memset(end, 0, YYJSON_PADDING_SIZE);
}
/* skip empty contents before json document */
if (unlikely(char_is_space_or_comment(*cur))) {
if (has_read_flag(ALLOW_COMMENTS)) {
if (!skip_spaces_and_comments(&cur)) {
return_err(cur - hdr, INVALID_COMMENT,
"unclosed multiline comment");
}
} else {
if (likely(char_is_space(*cur))) {
while (char_is_space(*++cur));
}
}
if (unlikely(cur >= end)) {
return_err(0, EMPTY_CONTENT, "input data is empty");
}
}
/* read json document */
if (likely(char_is_container(*cur))) {
if (char_is_space(cur[1]) && char_is_space(cur[2])) {
doc = read_root_pretty(hdr, cur, end, alc, flg, err);
} else {
doc = read_root_minify(hdr, cur, end, alc, flg, err);
}
} else {
doc = read_root_single(hdr, cur, end, alc, flg, err);
}
/* check result */
if (likely(doc)) {
memset(err, 0, sizeof(yyjson_read_err));
} else {
/* RFC 8259: JSON text MUST be encoded using UTF-8 */
if (err->pos == 0 && err->code != YYJSON_READ_ERROR_MEMORY_ALLOCATION) {
if ((hdr[0] == 0xEF && hdr[1] == 0xBB && hdr[2] == 0xBF)) {
err->msg = "byte order mark (BOM) is not supported";
} else if (len >= 4 &&
((hdr[0] == 0x00 && hdr[1] == 0x00 &&
hdr[2] == 0xFE && hdr[3] == 0xFF) ||
(hdr[0] == 0xFF && hdr[1] == 0xFE &&
hdr[2] == 0x00 && hdr[3] == 0x00))) {
err->msg = "UTF-32 encoding is not supported";
} else if (len >= 2 &&
((hdr[0] == 0xFE && hdr[1] == 0xFF) ||
(hdr[0] == 0xFF && hdr[1] == 0xFE))) {
err->msg = "UTF-16 encoding is not supported";
}
}
if (!has_read_flag(INSITU)) alc.free(alc.ctx, (void *)hdr);
}
return doc;
#undef return_err
}
yyjson_doc *yyjson_read_file(const char *path,
yyjson_read_flag flg,
const yyjson_alc *alc_ptr,
yyjson_read_err *err) {
#define return_err(_code, _msg) do { \
err->pos = 0; \
err->msg = _msg; \
err->code = YYJSON_READ_ERROR_##_code; \
return NULL; \
} while (false)
yyjson_doc *doc;
FILE *file;
if (unlikely(!path)) return_err(INVALID_PARAMETER, "input path is NULL");
file = fopen_readonly(path);
if (unlikely(!file)) return_err(FILE_OPEN, "file opening failed");
doc = yyjson_read_fp(file, flg, alc_ptr, err);
fclose(file);
return doc;
#undef return_err
}
yyjson_doc *yyjson_read_fp(FILE *file,
yyjson_read_flag flg,
const yyjson_alc *alc_ptr,
yyjson_read_err *err) {
#define return_err(_code, _msg) do { \
err->pos = 0; \
err->msg = _msg; \
err->code = YYJSON_READ_ERROR_##_code; \
if (buf) alc.free(alc.ctx, buf); \
return NULL; \
} while (false)
yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
yyjson_doc *doc;
long file_size = 0, file_pos;
void *buf = NULL;
usize buf_size = 0;
/* validate input parameters */
if (unlikely(!file)) return_err(INVALID_PARAMETER, "input file is NULL");
/* get current position */
file_pos = ftell(file);
if (file_pos != -1) {
/* get total file size, may fail */
if (fseek(file, 0, SEEK_END) == 0) file_size = ftell(file);
/* reset to original position, may fail */
if (fseek(file, file_pos, SEEK_SET) != 0) file_size = 0;
/* get file size from current postion to end */
if (file_size > 0) file_size -= file_pos;
}
/* read file */
if (file_size > 0) {
/* read the entire file in one call */
buf_size = (usize)file_size + YYJSON_PADDING_SIZE;
buf = alc.malloc(alc.ctx, buf_size);
if (buf == NULL) {
return_err(MEMORY_ALLOCATION, "fail to alloc memory");
}
if (fread_safe(buf, (usize)file_size, file) != (usize)file_size) {
return_err(FILE_READ, "file reading failed");
}
} else {
/* failed to get file size, read it as a stream */
usize chunk_min = (usize)64;
usize chunk_max = (usize)512 * 1024 * 1024;
usize chunk_now = chunk_min;
usize read_size;
void *tmp;
buf_size = YYJSON_PADDING_SIZE;
while (true) {
if (buf_size + chunk_now < buf_size) { /* overflow */
return_err(MEMORY_ALLOCATION, "fail to alloc memory");
}
buf_size += chunk_now;
if (!buf) {
buf = alc.malloc(alc.ctx, buf_size);
if (!buf) return_err(MEMORY_ALLOCATION, "fail to alloc memory");
} else {
tmp = alc.realloc(alc.ctx, buf, buf_size - chunk_now, buf_size);
if (!tmp) return_err(MEMORY_ALLOCATION, "fail to alloc memory");
buf = tmp;
}
tmp = ((u8 *)buf) + buf_size - YYJSON_PADDING_SIZE - chunk_now;
read_size = fread_safe(tmp, chunk_now, file);
file_size += (long)read_size;
if (read_size != chunk_now) break;
chunk_now *= 2;
if (chunk_now > chunk_max) chunk_now = chunk_max;
}
}
/* read JSON */
memset((u8 *)buf + file_size, 0, YYJSON_PADDING_SIZE);
flg |= YYJSON_READ_INSITU;
doc = yyjson_read_opts((char *)buf, (usize)file_size, flg, &alc, err);
if (doc) {
doc->str_pool = (char *)buf;
return doc;
} else {
alc.free(alc.ctx, buf);
return NULL;
}
#undef return_err
}
const char *yyjson_read_number(const char *dat,
yyjson_val *val,
yyjson_read_flag flg,
const yyjson_alc *alc,
yyjson_read_err *err) {
#define return_err(_pos, _code, _msg) do { \
err->pos = _pos > hdr ? (usize)(_pos - hdr) : 0; \
err->msg = _msg; \
err->code = YYJSON_READ_ERROR_##_code; \
return NULL; \
} while (false)
u8 *hdr = constcast(u8 *)dat, *cur = hdr;
bool raw; /* read number as raw */
u8 *raw_end; /* raw end for null-terminator */
u8 **pre; /* previous raw end pointer */
const char *msg;
#if !YYJSON_HAS_IEEE_754 || YYJSON_DISABLE_FAST_FP_CONV
u8 buf[128];
usize dat_len;
#endif
if (unlikely(!dat)) {
return_err(cur, INVALID_PARAMETER, "input data is NULL");
}
if (unlikely(!val)) {
return_err(cur, INVALID_PARAMETER, "output value is NULL");
}
#if !YYJSON_HAS_IEEE_754 || YYJSON_DISABLE_FAST_FP_CONV
if (!alc) alc = &YYJSON_DEFAULT_ALC;
dat_len = strlen(dat);
if (dat_len < sizeof(buf)) {
memcpy(buf, dat, dat_len + 1);
hdr = buf;
cur = hdr;
} else {
hdr = (u8 *)alc->malloc(alc->ctx, dat_len + 1);
cur = hdr;
if (unlikely(!hdr)) {
return_err(cur, MEMORY_ALLOCATION, "memory allocation failed");
}
memcpy(hdr, dat, dat_len + 1);
}
hdr[dat_len] = 0;
#endif
raw = false;
raw_end = NULL;
pre = raw ? &raw_end : NULL;
#if !YYJSON_HAS_IEEE_754 || YYJSON_DISABLE_FAST_FP_CONV
if (!read_number(&cur, pre, flg, val, &msg)) {
if (dat_len >= sizeof(buf)) alc->free(alc->ctx, hdr);
return_err(cur, INVALID_NUMBER, msg);
}
if (dat_len >= sizeof(buf)) alc->free(alc->ctx, hdr);
if (yyjson_is_raw(val)) val->uni.str = dat;
return dat + (cur - hdr);
#else
if (!read_number(&cur, pre, flg, val, &msg)) {
return_err(cur, INVALID_NUMBER, msg);
}
return (const char *)cur;
#endif
#undef return_err
}
#endif /* YYJSON_DISABLE_READER */
#if !YYJSON_DISABLE_WRITER
/*==============================================================================
* Integer Writer
*
* The maximum value of uint32_t is 4294967295 (10 digits),
* these digits are named as 'aabbccddee' here.
*
* Although most compilers may convert the "division by constant value" into
* "multiply and shift", manual conversion can still help some compilers
* generate fewer and better instructions.
*
* Reference:
* Division by Invariant Integers using Multiplication, 1994.
* https://gmplib.org/~tege/divcnst-pldi94.pdf
* Improved division by invariant integers, 2011.
* https://gmplib.org/~tege/division-paper.pdf
*============================================================================*/
/** Digit table from 00 to 99. */
yyjson_align(2)
static const char digit_table[200] = {
'0', '0', '0', '1', '0', '2', '0', '3', '0', '4',
'0', '5', '0', '6', '0', '7', '0', '8', '0', '9',
'1', '0', '1', '1', '1', '2', '1', '3', '1', '4',
'1', '5', '1', '6', '1', '7', '1', '8', '1', '9',
'2', '0', '2', '1', '2', '2', '2', '3', '2', '4',
'2', '5', '2', '6', '2', '7', '2', '8', '2', '9',
'3', '0', '3', '1', '3', '2', '3', '3', '3', '4',
'3', '5', '3', '6', '3', '7', '3', '8', '3', '9',
'4', '0', '4', '1', '4', '2', '4', '3', '4', '4',
'4', '5', '4', '6', '4', '7', '4', '8', '4', '9',
'5', '0', '5', '1', '5', '2', '5', '3', '5', '4',
'5', '5', '5', '6', '5', '7', '5', '8', '5', '9',
'6', '0', '6', '1', '6', '2', '6', '3', '6', '4',
'6', '5', '6', '6', '6', '7', '6', '8', '6', '9',
'7', '0', '7', '1', '7', '2', '7', '3', '7', '4',
'7', '5', '7', '6', '7', '7', '7', '8', '7', '9',
'8', '0', '8', '1', '8', '2', '8', '3', '8', '4',
'8', '5', '8', '6', '8', '7', '8', '8', '8', '9',
'9', '0', '9', '1', '9', '2', '9', '3', '9', '4',
'9', '5', '9', '6', '9', '7', '9', '8', '9', '9'
};
static_inline u8 *write_u32_len_8(u32 val, u8 *buf) {
u32 aa, bb, cc, dd, aabb, ccdd; /* 8 digits: aabbccdd */
aabb = (u32)(((u64)val * 109951163) >> 40); /* (val / 10000) */
ccdd = val - aabb * 10000; /* (val % 10000) */
aa = (aabb * 5243) >> 19; /* (aabb / 100) */
cc = (ccdd * 5243) >> 19; /* (ccdd / 100) */
bb = aabb - aa * 100; /* (aabb % 100) */
dd = ccdd - cc * 100; /* (ccdd % 100) */
byte_copy_2(buf + 0, digit_table + aa * 2);
byte_copy_2(buf + 2, digit_table + bb * 2);
byte_copy_2(buf + 4, digit_table + cc * 2);
byte_copy_2(buf + 6, digit_table + dd * 2);
return buf + 8;
}
static_inline u8 *write_u32_len_4(u32 val, u8 *buf) {
u32 aa, bb; /* 4 digits: aabb */
aa = (val * 5243) >> 19; /* (val / 100) */
bb = val - aa * 100; /* (val % 100) */
byte_copy_2(buf + 0, digit_table + aa * 2);
byte_copy_2(buf + 2, digit_table + bb * 2);
return buf + 4;
}
static_inline u8 *write_u32_len_1_8(u32 val, u8 *buf) {
u32 aa, bb, cc, dd, aabb, bbcc, ccdd, lz;
if (val < 100) { /* 1-2 digits: aa */
lz = val < 10; /* leading zero: 0 or 1 */
byte_copy_2(buf + 0, digit_table + val * 2 + lz);
buf -= lz;
return buf + 2;
} else if (val < 10000) { /* 3-4 digits: aabb */
aa = (val * 5243) >> 19; /* (val / 100) */
bb = val - aa * 100; /* (val % 100) */
lz = aa < 10; /* leading zero: 0 or 1 */
byte_copy_2(buf + 0, digit_table + aa * 2 + lz);
buf -= lz;
byte_copy_2(buf + 2, digit_table + bb * 2);
return buf + 4;
} else if (val < 1000000) { /* 5-6 digits: aabbcc */
aa = (u32)(((u64)val * 429497) >> 32); /* (val / 10000) */
bbcc = val - aa * 10000; /* (val % 10000) */
bb = (bbcc * 5243) >> 19; /* (bbcc / 100) */
cc = bbcc - bb * 100; /* (bbcc % 100) */
lz = aa < 10; /* leading zero: 0 or 1 */
byte_copy_2(buf + 0, digit_table + aa * 2 + lz);
buf -= lz;
byte_copy_2(buf + 2, digit_table + bb * 2);
byte_copy_2(buf + 4, digit_table + cc * 2);
return buf + 6;
} else { /* 7-8 digits: aabbccdd */
aabb = (u32)(((u64)val * 109951163) >> 40); /* (val / 10000) */
ccdd = val - aabb * 10000; /* (val % 10000) */
aa = (aabb * 5243) >> 19; /* (aabb / 100) */
cc = (ccdd * 5243) >> 19; /* (ccdd / 100) */
bb = aabb - aa * 100; /* (aabb % 100) */
dd = ccdd - cc * 100; /* (ccdd % 100) */
lz = aa < 10; /* leading zero: 0 or 1 */
byte_copy_2(buf + 0, digit_table + aa * 2 + lz);
buf -= lz;
byte_copy_2(buf + 2, digit_table + bb * 2);
byte_copy_2(buf + 4, digit_table + cc * 2);
byte_copy_2(buf + 6, digit_table + dd * 2);
return buf + 8;
}
}
static_inline u8 *write_u64_len_5_8(u32 val, u8 *buf) {
u32 aa, bb, cc, dd, aabb, bbcc, ccdd, lz;
if (val < 1000000) { /* 5-6 digits: aabbcc */
aa = (u32)(((u64)val * 429497) >> 32); /* (val / 10000) */
bbcc = val - aa * 10000; /* (val % 10000) */
bb = (bbcc * 5243) >> 19; /* (bbcc / 100) */
cc = bbcc - bb * 100; /* (bbcc % 100) */
lz = aa < 10; /* leading zero: 0 or 1 */
byte_copy_2(buf + 0, digit_table + aa * 2 + lz);
buf -= lz;
byte_copy_2(buf + 2, digit_table + bb * 2);
byte_copy_2(buf + 4, digit_table + cc * 2);
return buf + 6;
} else { /* 7-8 digits: aabbccdd */
aabb = (u32)(((u64)val * 109951163) >> 40); /* (val / 10000) */
ccdd = val - aabb * 10000; /* (val % 10000) */
aa = (aabb * 5243) >> 19; /* (aabb / 100) */
cc = (ccdd * 5243) >> 19; /* (ccdd / 100) */
bb = aabb - aa * 100; /* (aabb % 100) */
dd = ccdd - cc * 100; /* (ccdd % 100) */
lz = aa < 10; /* leading zero: 0 or 1 */
byte_copy_2(buf + 0, digit_table + aa * 2 + lz);
buf -= lz;
byte_copy_2(buf + 2, digit_table + bb * 2);
byte_copy_2(buf + 4, digit_table + cc * 2);
byte_copy_2(buf + 6, digit_table + dd * 2);
return buf + 8;
}
}
static_inline u8 *write_u64(u64 val, u8 *buf) {
u64 tmp, hgh;
u32 mid, low;
if (val < 100000000) { /* 1-8 digits */
buf = write_u32_len_1_8((u32)val, buf);
return buf;
} else if (val < (u64)100000000 * 100000000) { /* 9-16 digits */
hgh = val / 100000000; /* (val / 100000000) */
low = (u32)(val - hgh * 100000000); /* (val % 100000000) */
buf = write_u32_len_1_8((u32)hgh, buf);
buf = write_u32_len_8(low, buf);
return buf;
} else { /* 17-20 digits */
tmp = val / 100000000; /* (val / 100000000) */
low = (u32)(val - tmp * 100000000); /* (val % 100000000) */
hgh = (u32)(tmp / 10000); /* (tmp / 10000) */
mid = (u32)(tmp - hgh * 10000); /* (tmp % 10000) */
buf = write_u64_len_5_8((u32)hgh, buf);
buf = write_u32_len_4(mid, buf);
buf = write_u32_len_8(low, buf);
return buf;
}
}
/*==============================================================================
* Number Writer
*============================================================================*/
#if YYJSON_HAS_IEEE_754 && !YYJSON_DISABLE_FAST_FP_CONV /* FP_WRITER */
/** Trailing zero count table for number 0 to 99.
(generate with misc/make_tables.c) */
static const u8 dec_trailing_zero_table[] = {
2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/** Write an unsigned integer with a length of 1 to 16. */
static_inline u8 *write_u64_len_1_to_16(u64 val, u8 *buf) {
u64 hgh;
u32 low;
if (val < 100000000) { /* 1-8 digits */
buf = write_u32_len_1_8((u32)val, buf);
return buf;
} else { /* 9-16 digits */
hgh = val / 100000000; /* (val / 100000000) */
low = (u32)(val - hgh * 100000000); /* (val % 100000000) */
buf = write_u32_len_1_8((u32)hgh, buf);
buf = write_u32_len_8(low, buf);
return buf;
}
}
/** Write an unsigned integer with a length of 1 to 17. */
static_inline u8 *write_u64_len_1_to_17(u64 val, u8 *buf) {
u64 hgh;
u32 mid, low, one;
if (val >= (u64)100000000 * 10000000) { /* len: 16 to 17 */
hgh = val / 100000000; /* (val / 100000000) */
low = (u32)(val - hgh * 100000000); /* (val % 100000000) */
one = (u32)(hgh / 100000000); /* (hgh / 100000000) */
mid = (u32)(hgh - (u64)one * 100000000); /* (hgh % 100000000) */
*buf = (u8)((u8)one + (u8)'0');
buf += one > 0;
buf = write_u32_len_8(mid, buf);
buf = write_u32_len_8(low, buf);
return buf;
} else if (val >= (u64)100000000){ /* len: 9 to 15 */
hgh = val / 100000000; /* (val / 100000000) */
low = (u32)(val - hgh * 100000000); /* (val % 100000000) */
buf = write_u32_len_1_8((u32)hgh, buf);
buf = write_u32_len_8(low, buf);
return buf;
} else { /* len: 1 to 8 */
buf = write_u32_len_1_8((u32)val, buf);
return buf;
}
}
/**
Write an unsigned integer with a length of 15 to 17 with trailing zero trimmed.
These digits are named as "aabbccddeeffgghhii" here.
For example, input 1234567890123000, output "1234567890123".
*/
static_inline u8 *write_u64_len_15_to_17_trim(u8 *buf, u64 sig) {
bool lz; /* leading zero */
u32 tz1, tz2, tz; /* trailing zero */
u32 abbccddee = (u32)(sig / 100000000);
u32 ffgghhii = (u32)(sig - (u64)abbccddee * 100000000);
u32 abbcc = abbccddee / 10000; /* (abbccddee / 10000) */
u32 ddee = abbccddee - abbcc * 10000; /* (abbccddee % 10000) */
u32 abb = (u32)(((u64)abbcc * 167773) >> 24); /* (abbcc / 100) */
u32 a = (abb * 41) >> 12; /* (abb / 100) */
u32 bb = abb - a * 100; /* (abb % 100) */
u32 cc = abbcc - abb * 100; /* (abbcc % 100) */
/* write abbcc */
buf[0] = (u8)(a + '0');
buf += a > 0;
lz = bb < 10 && a == 0;
byte_copy_2(buf + 0, digit_table + bb * 2 + lz);
buf -= lz;
byte_copy_2(buf + 2, digit_table + cc * 2);
if (ffgghhii) {
u32 dd = (ddee * 5243) >> 19; /* (ddee / 100) */
u32 ee = ddee - dd * 100; /* (ddee % 100) */
u32 ffgg = (u32)(((u64)ffgghhii * 109951163) >> 40); /* (val / 10000) */
u32 hhii = ffgghhii - ffgg * 10000; /* (val % 10000) */
u32 ff = (ffgg * 5243) >> 19; /* (aabb / 100) */
u32 gg = ffgg - ff * 100; /* (aabb % 100) */
byte_copy_2(buf + 4, digit_table + dd * 2);
byte_copy_2(buf + 6, digit_table + ee * 2);
byte_copy_2(buf + 8, digit_table + ff * 2);
byte_copy_2(buf + 10, digit_table + gg * 2);
if (hhii) {
u32 hh = (hhii * 5243) >> 19; /* (ccdd / 100) */
u32 ii = hhii - hh * 100; /* (ccdd % 100) */
byte_copy_2(buf + 12, digit_table + hh * 2);
byte_copy_2(buf + 14, digit_table + ii * 2);
tz1 = dec_trailing_zero_table[hh];
tz2 = dec_trailing_zero_table[ii];
tz = ii ? tz2 : (tz1 + 2);
buf += 16 - tz;
return buf;
} else {
tz1 = dec_trailing_zero_table[ff];
tz2 = dec_trailing_zero_table[gg];
tz = gg ? tz2 : (tz1 + 2);
buf += 12 - tz;
return buf;
}
} else {
if (ddee) {
u32 dd = (ddee * 5243) >> 19; /* (ddee / 100) */
u32 ee = ddee - dd * 100; /* (ddee % 100) */
byte_copy_2(buf + 4, digit_table + dd * 2);
byte_copy_2(buf + 6, digit_table + ee * 2);
tz1 = dec_trailing_zero_table[dd];
tz2 = dec_trailing_zero_table[ee];
tz = ee ? tz2 : (tz1 + 2);
buf += 8 - tz;
return buf;
} else {
tz1 = dec_trailing_zero_table[bb];
tz2 = dec_trailing_zero_table[cc];
tz = cc ? tz2 : (tz1 + tz2);
buf += 4 - tz;
return buf;
}
}
}
/** Write a signed integer in the range -324 to 308. */
static_inline u8 *write_f64_exp(i32 exp, u8 *buf) {
buf[0] = '-';
buf += exp < 0;
exp = exp < 0 ? -exp : exp;
if (exp < 100) {
u32 lz = exp < 10;
byte_copy_2(buf + 0, digit_table + (u32)exp * 2 + lz);
return buf + 2 - lz;
} else {
u32 hi = ((u32)exp * 656) >> 16; /* exp / 100 */
u32 lo = (u32)exp - hi * 100; /* exp % 100 */
buf[0] = (u8)((u8)hi + (u8)'0');
byte_copy_2(buf + 1, digit_table + lo * 2);
return buf + 3;
}
}
/** Multiplies 128-bit integer and returns highest 64-bit rounded value. */
static_inline u64 round_to_odd(u64 hi, u64 lo, u64 cp) {
u64 x_hi, x_lo, y_hi, y_lo;
u128_mul(cp, lo, &x_hi, &x_lo);
u128_mul_add(cp, hi, x_hi, &y_hi, &y_lo);
return y_hi | (y_lo > 1);
}
/**
Convert double number from binary to decimal.
The output significand is shortest decimal but may have trailing zeros.
This function use the Schubfach algorithm:
Raffaello Giulietti, The Schubfach way to render doubles (5th version), 2022.
https://drive.google.com/file/d/1gp5xv4CAa78SVgCeWfGqqI4FfYYYuNFb
https://mail.openjdk.java.net/pipermail/core-libs-dev/2021-November/083536.html
https://github.com/openjdk/jdk/pull/3402 (Java implementation)
https://github.com/abolz/Drachennest (C++ implementation)
See also:
Dragonbox: A New Floating-Point Binary-to-Decimal Conversion Algorithm, 2022.
https://github.com/jk-jeon/dragonbox/blob/master/other_files/Dragonbox.pdf
https://github.com/jk-jeon/dragonbox
@param sig_raw The raw value of significand in IEEE 754 format.
@param exp_raw The raw value of exponent in IEEE 754 format.
@param sig_bin The decoded value of significand in binary.
@param exp_bin The decoded value of exponent in binary.
@param sig_dec The output value of significand in decimal.
@param exp_dec The output value of exponent in decimal.
@warning The input double number should not be 0, inf, nan.
*/
static_inline void f64_bin_to_dec(u64 sig_raw, u32 exp_raw,
u64 sig_bin, i32 exp_bin,
u64 *sig_dec, i32 *exp_dec) {
bool is_even, regular_spacing, u_inside, w_inside, round_up;
u64 s, sp, cb, cbl, cbr, vb, vbl, vbr, pow10hi, pow10lo, upper, lower, mid;
i32 k, h, exp10;
is_even = !(sig_bin & 1);
regular_spacing = (sig_raw == 0 && exp_raw > 1);
cbl = 4 * sig_bin - 2 + regular_spacing;
cb = 4 * sig_bin;
cbr = 4 * sig_bin + 2;
/* exp_bin: [-1074, 971] */
/* k = regular_spacing ? floor(log10(pow(2, exp_bin))) */
/* : floor(log10(pow(2, exp_bin) * 3.0 / 4.0)) */
/* = regular_spacing ? floor(exp_bin * log10(2)) */
/* : floor(exp_bin * log10(2) + log10(3.0 / 4.0)) */
k = (i32)(exp_bin * 315653 - (regular_spacing ? 131237 : 0)) >> 20;
/* k: [-324, 292] */
/* h = exp_bin + floor(log2(pow(10, e))) */
/* = exp_bin + floor(log2(10) * e) */
exp10 = -k;
h = exp_bin + ((exp10 * 217707) >> 16) + 1;
pow10_table_get_sig(exp10, &pow10hi, &pow10lo);
pow10lo += (exp10 < POW10_SIG_TABLE_MIN_EXACT_EXP ||
exp10 > POW10_SIG_TABLE_MAX_EXACT_EXP);
vbl = round_to_odd(pow10hi, pow10lo, cbl << h);
vb = round_to_odd(pow10hi, pow10lo, cb << h);
vbr = round_to_odd(pow10hi, pow10lo, cbr << h);
lower = vbl + !is_even;
upper = vbr - !is_even;
s = vb / 4;
if (s >= 10) {
sp = s / 10;
u_inside = (lower <= 40 * sp);
w_inside = (upper >= 40 * sp + 40);
if (u_inside != w_inside) {
*sig_dec = sp + w_inside;
*exp_dec = k + 1;
return;
}
}
u_inside = (lower <= 4 * s);
w_inside = (upper >= 4 * s + 4);
mid = 4 * s + 2;
round_up = (vb > mid) || (vb == mid && (s & 1) != 0);
*sig_dec = s + ((u_inside != w_inside) ? w_inside : round_up);
*exp_dec = k;
}
/**
Write a double number (requires 32 bytes buffer).
We follows the ECMAScript specification to print floating point numbers,
but with the following changes:
1. Keep the negative sign of 0.0 to preserve input information.
2. Keep decimal point to indicate the number is floating point.
3. Remove positive sign of exponent part.
*/
static_inline u8 *write_f64_raw(u8 *buf, u64 raw, yyjson_write_flag flg) {
u64 sig_bin, sig_dec, sig_raw;
i32 exp_bin, exp_dec, sig_len, dot_pos, i, max;
u32 exp_raw, hi, lo;
u8 *hdr, *num_hdr, *num_end, *dot_end;
bool sign;
/* decode raw bytes from IEEE-754 double format. */
sign = (bool)(raw >> (F64_BITS - 1));
sig_raw = raw & F64_SIG_MASK;
exp_raw = (u32)((raw & F64_EXP_MASK) >> F64_SIG_BITS);
/* return inf and nan */
if (unlikely(exp_raw == ((u32)1 << F64_EXP_BITS) - 1)) {
if (has_write_flag(INF_AND_NAN_AS_NULL)) {
byte_copy_4(buf, "null");
return buf + 4;
}
else if (has_write_flag(ALLOW_INF_AND_NAN)) {
if (sig_raw == 0) {
buf[0] = '-';
buf += sign;
byte_copy_8(buf, "Infinity");
buf += 8;
return buf;
} else {
byte_copy_4(buf, "NaN");
return buf + 3;
}
}
return NULL;
}
/* add sign for all finite double value, including 0.0 and inf */
buf[0] = '-';
buf += sign;
hdr = buf;
/* return zero */
if ((raw << 1) == 0) {
byte_copy_4(buf, "0.0");
buf += 3;
return buf;
}
if (likely(exp_raw != 0)) {
/* normal number */
sig_bin = sig_raw | ((u64)1 << F64_SIG_BITS);
exp_bin = (i32)exp_raw - F64_EXP_BIAS - F64_SIG_BITS;
/* fast path for small integer number without fraction */
if (-F64_SIG_BITS <= exp_bin && exp_bin <= 0) {
if (u64_tz_bits(sig_bin) >= (u32)-exp_bin) {
/* number is integer in range 1 to 0x1FFFFFFFFFFFFF */
sig_dec = sig_bin >> -exp_bin;
buf = write_u64_len_1_to_16(sig_dec, buf);
byte_copy_2(buf, ".0");
buf += 2;
return buf;
}
}
/* binary to decimal */
f64_bin_to_dec(sig_raw, exp_raw, sig_bin, exp_bin, &sig_dec, &exp_dec);
/* the sig length is 15 to 17 */
sig_len = 17;
sig_len -= (sig_dec < (u64)100000000 * 100000000);
sig_len -= (sig_dec < (u64)100000000 * 10000000);
/* the decimal point position relative to the first digit */
dot_pos = sig_len + exp_dec;
if (-6 < dot_pos && dot_pos <= 21) {
/* no need to write exponent part */
if (dot_pos <= 0) {
/* dot before first digit */
/* such as 0.1234, 0.000001234 */
num_hdr = hdr + (2 - dot_pos);
num_end = write_u64_len_15_to_17_trim(num_hdr, sig_dec);
hdr[0] = '0';
hdr[1] = '.';
hdr += 2;
max = -dot_pos;
for (i = 0; i < max; i++) hdr[i] = '0';
return num_end;
} else {
/* dot after first digit */
/* such as 1.234, 1234.0, 123400000000000000000.0 */
memset(hdr + 0, '0', 8);
memset(hdr + 8, '0', 8);
memset(hdr + 16, '0', 8);
num_hdr = hdr + 1;
num_end = write_u64_len_15_to_17_trim(num_hdr, sig_dec);
for (i = 0; i < dot_pos; i++) hdr[i] = hdr[i + 1];
hdr[dot_pos] = '.';
dot_end = hdr + dot_pos + 2;
return dot_end < num_end ? num_end : dot_end;
}
} else {
/* write with scientific notation */
/* such as 1.234e56 */
u8 *end = write_u64_len_15_to_17_trim(buf + 1, sig_dec);
end -= (end == buf + 2); /* remove '.0', e.g. 2.0e34 -> 2e34 */
exp_dec += sig_len - 1;
hdr[0] = hdr[1];
hdr[1] = '.';
end[0] = 'e';
buf = write_f64_exp(exp_dec, end + 1);
return buf;
}
} else {
/* subnormal number */
sig_bin = sig_raw;
exp_bin = 1 - F64_EXP_BIAS - F64_SIG_BITS;
/* binary to decimal */
f64_bin_to_dec(sig_raw, exp_raw, sig_bin, exp_bin, &sig_dec, &exp_dec);
/* write significand part */
buf = write_u64_len_1_to_17(sig_dec, buf + 1);
hdr[0] = hdr[1];
hdr[1] = '.';
do {
buf--;
exp_dec++;
} while (*buf == '0');
exp_dec += (i32)(buf - hdr - 2);
buf += (*buf != '.');
buf[0] = 'e';
buf++;
/* write exponent part */
buf[0] = '-';
buf++;
exp_dec = -exp_dec;
hi = ((u32)exp_dec * 656) >> 16; /* exp / 100 */
lo = (u32)exp_dec - hi * 100; /* exp % 100 */
buf[0] = (u8)((u8)hi + (u8)'0');
byte_copy_2(buf + 1, digit_table + lo * 2);
buf += 3;
return buf;
}
}
#else /* FP_WRITER */
/** Write a double number (requires 32 bytes buffer). */
static_inline u8 *write_f64_raw(u8 *buf, u64 raw, yyjson_write_flag flg) {
/*
For IEEE 754, `DBL_DECIMAL_DIG` is 17 for round-trip.
For non-IEEE formats, 17 is used to avoid buffer overflow,
round-trip is not guaranteed.
*/
#if defined(DBL_DECIMAL_DIG) && DBL_DECIMAL_DIG != 17
int dig = DBL_DECIMAL_DIG > 17 ? 17 : DBL_DECIMAL_DIG;
#else
int dig = 17;
#endif
/*
The snprintf() function is locale-dependent. For currently known locales,
(en, zh, ja, ko, am, he, hi) use '.' as the decimal point, while other
locales use ',' as the decimal point. we need to replace ',' with '.'
to avoid the locale setting.
*/
f64 val = f64_from_raw(raw);
#if YYJSON_MSC_VER >= 1400
int len = sprintf_s((char *)buf, 32, "%.*g", dig, val);
#elif defined(snprintf) || (YYJSON_STDC_VER >= 199901L)
int len = snprintf((char *)buf, 32, "%.*g", dig, val);
#else
int len = sprintf((char *)buf, "%.*g", dig, val);
#endif
u8 *cur = buf;
if (unlikely(len < 1)) return NULL;
cur += (*cur == '-');
if (unlikely(!digi_is_digit(*cur))) {
/* nan, inf, or bad output */
if (has_write_flag(INF_AND_NAN_AS_NULL)) {
byte_copy_4(buf, "null");
return buf + 4;
}
else if (has_write_flag(ALLOW_INF_AND_NAN)) {
if (*cur == 'i') {
byte_copy_8(cur, "Infinity");
cur += 8;
return cur;
} else if (*cur == 'n') {
byte_copy_4(buf, "NaN");
return buf + 3;
}
}
return NULL;
} else {
/* finite number */
int i = 0;
bool fp = false;
for (; i < len; i++) {
if (buf[i] == ',') buf[i] = '.';
if (digi_is_fp((u8)buf[i])) fp = true;
}
if (!fp) {
buf[len++] = '.';
buf[len++] = '0';
}
}
return buf + len;
}
#endif /* FP_WRITER */
/** Write a JSON number (requires 32 bytes buffer). */
static_inline u8 *write_number(u8 *cur, yyjson_val *val,
yyjson_write_flag flg) {
if (val->tag & YYJSON_SUBTYPE_REAL) {
u64 raw = val->uni.u64;
return write_f64_raw(cur, raw, flg);
} else {
u64 pos = val->uni.u64;
u64 neg = ~pos + 1;
usize sgn = ((val->tag & YYJSON_SUBTYPE_SINT) > 0) & ((i64)pos < 0);
*cur = '-';
return write_u64(sgn ? neg : pos, cur + sgn);
}
}
/*==============================================================================
* String Writer
*============================================================================*/
/** Character encode type, if (type > CHAR_ENC_ERR_1) bytes = type / 2; */
typedef u8 char_enc_type;
#define CHAR_ENC_CPY_1 0 /* 1-byte UTF-8, copy. */
#define CHAR_ENC_ERR_1 1 /* 1-byte UTF-8, error. */
#define CHAR_ENC_ESC_A 2 /* 1-byte ASCII, escaped as '\x'. */
#define CHAR_ENC_ESC_1 3 /* 1-byte UTF-8, escaped as '\uXXXX'. */
#define CHAR_ENC_CPY_2 4 /* 2-byte UTF-8, copy. */
#define CHAR_ENC_ESC_2 5 /* 2-byte UTF-8, escaped as '\uXXXX'. */
#define CHAR_ENC_CPY_3 6 /* 3-byte UTF-8, copy. */
#define CHAR_ENC_ESC_3 7 /* 3-byte UTF-8, escaped as '\uXXXX'. */
#define CHAR_ENC_CPY_4 8 /* 4-byte UTF-8, copy. */
#define CHAR_ENC_ESC_4 9 /* 4-byte UTF-8, escaped as '\uXXXX\uXXXX'. */
/** Character encode type table: don't escape unicode, don't escape '/'.
(generate with misc/make_tables.c) */
static const char_enc_type enc_table_cpy[256] = {
3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
0, 0, 2, 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, 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, 2, 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, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
8, 8, 8, 8, 8, 8, 8, 8, 1, 1, 1, 1, 1, 1, 1, 1
};
/** Character encode type table: don't escape unicode, escape '/'.
(generate with misc/make_tables.c) */
static const char_enc_type enc_table_cpy_slash[256] = {
3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
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,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 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, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
8, 8, 8, 8, 8, 8, 8, 8, 1, 1, 1, 1, 1, 1, 1, 1
};
/** Character encode type table: escape unicode, don't escape '/'.
(generate with misc/make_tables.c) */
static const char_enc_type enc_table_esc[256] = {
3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
0, 0, 2, 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, 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, 2, 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, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1
};
/** Character encode type table: escape unicode, escape '/'.
(generate with misc/make_tables.c) */
static const char_enc_type enc_table_esc_slash[256] = {
3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
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,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 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, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1
};
/** Escaped hex character table: ["00" "01" "02" ... "FD" "FE" "FF"].
(generate with misc/make_tables.c) */
yyjson_align(2)
static const u8 esc_hex_char_table[512] = {
'0', '0', '0', '1', '0', '2', '0', '3',
'0', '4', '0', '5', '0', '6', '0', '7',
'0', '8', '0', '9', '0', 'A', '0', 'B',
'0', 'C', '0', 'D', '0', 'E', '0', 'F',
'1', '0', '1', '1', '1', '2', '1', '3',
'1', '4', '1', '5', '1', '6', '1', '7',
'1', '8', '1', '9', '1', 'A', '1', 'B',
'1', 'C', '1', 'D', '1', 'E', '1', 'F',
'2', '0', '2', '1', '2', '2', '2', '3',
'2', '4', '2', '5', '2', '6', '2', '7',
'2', '8', '2', '9', '2', 'A', '2', 'B',
'2', 'C', '2', 'D', '2', 'E', '2', 'F',
'3', '0', '3', '1', '3', '2', '3', '3',
'3', '4', '3', '5', '3', '6', '3', '7',
'3', '8', '3', '9', '3', 'A', '3', 'B',
'3', 'C', '3', 'D', '3', 'E', '3', 'F',
'4', '0', '4', '1', '4', '2', '4', '3',
'4', '4', '4', '5', '4', '6', '4', '7',
'4', '8', '4', '9', '4', 'A', '4', 'B',
'4', 'C', '4', 'D', '4', 'E', '4', 'F',
'5', '0', '5', '1', '5', '2', '5', '3',
'5', '4', '5', '5', '5', '6', '5', '7',
'5', '8', '5', '9', '5', 'A', '5', 'B',
'5', 'C', '5', 'D', '5', 'E', '5', 'F',
'6', '0', '6', '1', '6', '2', '6', '3',
'6', '4', '6', '5', '6', '6', '6', '7',
'6', '8', '6', '9', '6', 'A', '6', 'B',
'6', 'C', '6', 'D', '6', 'E', '6', 'F',
'7', '0', '7', '1', '7', '2', '7', '3',
'7', '4', '7', '5', '7', '6', '7', '7',
'7', '8', '7', '9', '7', 'A', '7', 'B',
'7', 'C', '7', 'D', '7', 'E', '7', 'F',
'8', '0', '8', '1', '8', '2', '8', '3',
'8', '4', '8', '5', '8', '6', '8', '7',
'8', '8', '8', '9', '8', 'A', '8', 'B',
'8', 'C', '8', 'D', '8', 'E', '8', 'F',
'9', '0', '9', '1', '9', '2', '9', '3',
'9', '4', '9', '5', '9', '6', '9', '7',
'9', '8', '9', '9', '9', 'A', '9', 'B',
'9', 'C', '9', 'D', '9', 'E', '9', 'F',
'A', '0', 'A', '1', 'A', '2', 'A', '3',
'A', '4', 'A', '5', 'A', '6', 'A', '7',
'A', '8', 'A', '9', 'A', 'A', 'A', 'B',
'A', 'C', 'A', 'D', 'A', 'E', 'A', 'F',
'B', '0', 'B', '1', 'B', '2', 'B', '3',
'B', '4', 'B', '5', 'B', '6', 'B', '7',
'B', '8', 'B', '9', 'B', 'A', 'B', 'B',
'B', 'C', 'B', 'D', 'B', 'E', 'B', 'F',
'C', '0', 'C', '1', 'C', '2', 'C', '3',
'C', '4', 'C', '5', 'C', '6', 'C', '7',
'C', '8', 'C', '9', 'C', 'A', 'C', 'B',
'C', 'C', 'C', 'D', 'C', 'E', 'C', 'F',
'D', '0', 'D', '1', 'D', '2', 'D', '3',
'D', '4', 'D', '5', 'D', '6', 'D', '7',
'D', '8', 'D', '9', 'D', 'A', 'D', 'B',
'D', 'C', 'D', 'D', 'D', 'E', 'D', 'F',
'E', '0', 'E', '1', 'E', '2', 'E', '3',
'E', '4', 'E', '5', 'E', '6', 'E', '7',
'E', '8', 'E', '9', 'E', 'A', 'E', 'B',
'E', 'C', 'E', 'D', 'E', 'E', 'E', 'F',
'F', '0', 'F', '1', 'F', '2', 'F', '3',
'F', '4', 'F', '5', 'F', '6', 'F', '7',
'F', '8', 'F', '9', 'F', 'A', 'F', 'B',
'F', 'C', 'F', 'D', 'F', 'E', 'F', 'F'
};
/** Escaped single character table. (generate with misc/make_tables.c) */
yyjson_align(2)
static const u8 esc_single_char_table[512] = {
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
'\\', 'b', '\\', 't', '\\', 'n', ' ', ' ',
'\\', 'f', '\\', 'r', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', '\\', '"', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', '\\', '/',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
'\\', '\\', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
};
/** Returns the encode table with options. */
static_inline const char_enc_type *get_enc_table_with_flag(
yyjson_read_flag flg) {
if (has_write_flag(ESCAPE_UNICODE)) {
if (has_write_flag(ESCAPE_SLASHES)) {
return enc_table_esc_slash;
} else {
return enc_table_esc;
}
} else {
if (has_write_flag(ESCAPE_SLASHES)) {
return enc_table_cpy_slash;
} else {
return enc_table_cpy;
}
}
}
/** Write raw string. */
static_inline u8 *write_raw(u8 *cur, const u8 *raw, usize raw_len) {
memcpy(cur, raw, raw_len);
return cur + raw_len;
}
/**
Write string no-escape.
@param cur Buffer cursor.
@param str A UTF-8 string, null-terminator is not required.
@param str_len Length of string in bytes.
@return The buffer cursor after string.
*/
static_inline u8 *write_string_noesc(u8 *cur, const u8 *str, usize str_len) {
*cur++ = '"';
while (str_len >= 16) {
byte_copy_16(cur, str);
cur += 16;
str += 16;
str_len -= 16;
}
while (str_len >= 4) {
byte_copy_4(cur, str);
cur += 4;
str += 4;
str_len -= 4;
}
while (str_len) {
*cur++ = *str++;
str_len -= 1;
}
*cur++ = '"';
return cur;
}
/**
Write UTF-8 string (requires len * 6 + 2 bytes buffer).
@param cur Buffer cursor.
@param esc Escape unicode.
@param inv Allow invalid unicode.
@param str A UTF-8 string, null-terminator is not required.
@param str_len Length of string in bytes.
@param enc_table Encode type table for character.
@return The buffer cursor after string, or NULL on invalid unicode.
*/
static_inline u8 *write_string(u8 *cur, bool esc, bool inv,
const u8 *str, usize str_len,
const char_enc_type *enc_table) {
/* UTF-8 character mask and pattern, see `read_string()` for details. */
#if YYJSON_ENDIAN == YYJSON_BIG_ENDIAN
const u16 b2_mask = 0xE0C0UL;
const u16 b2_patt = 0xC080UL;
const u16 b2_requ = 0x1E00UL;
const u32 b3_mask = 0xF0C0C000UL;
const u32 b3_patt = 0xE0808000UL;
const u32 b3_requ = 0x0F200000UL;
const u32 b3_erro = 0x0D200000UL;
const u32 b4_mask = 0xF8C0C0C0UL;
const u32 b4_patt = 0xF0808080UL;
const u32 b4_requ = 0x07300000UL;
const u32 b4_err0 = 0x04000000UL;
const u32 b4_err1 = 0x03300000UL;
#elif YYJSON_ENDIAN == YYJSON_LITTLE_ENDIAN
const u16 b2_mask = 0xC0E0UL;
const u16 b2_patt = 0x80C0UL;
const u16 b2_requ = 0x001EUL;
const u32 b3_mask = 0x00C0C0F0UL;
const u32 b3_patt = 0x008080E0UL;
const u32 b3_requ = 0x0000200FUL;
const u32 b3_erro = 0x0000200DUL;
const u32 b4_mask = 0xC0C0C0F8UL;
const u32 b4_patt = 0x808080F0UL;
const u32 b4_requ = 0x00003007UL;
const u32 b4_err0 = 0x00000004UL;
const u32 b4_err1 = 0x00003003UL;
#else
/* this should be evaluated at compile-time */
v16_uni b2_mask_uni = {{ 0xE0, 0xC0 }};
v16_uni b2_patt_uni = {{ 0xC0, 0x80 }};
v16_uni b2_requ_uni = {{ 0x1E, 0x00 }};
v32_uni b3_mask_uni = {{ 0xF0, 0xC0, 0xC0, 0x00 }};
v32_uni b3_patt_uni = {{ 0xE0, 0x80, 0x80, 0x00 }};
v32_uni b3_requ_uni = {{ 0x0F, 0x20, 0x00, 0x00 }};
v32_uni b3_erro_uni = {{ 0x0D, 0x20, 0x00, 0x00 }};
v32_uni b4_mask_uni = {{ 0xF8, 0xC0, 0xC0, 0xC0 }};
v32_uni b4_patt_uni = {{ 0xF0, 0x80, 0x80, 0x80 }};
v32_uni b4_requ_uni = {{ 0x07, 0x30, 0x00, 0x00 }};
v32_uni b4_err0_uni = {{ 0x04, 0x00, 0x00, 0x00 }};
v32_uni b4_err1_uni = {{ 0x03, 0x30, 0x00, 0x00 }};
u16 b2_mask = b2_mask_uni.u;
u16 b2_patt = b2_patt_uni.u;
u16 b2_requ = b2_requ_uni.u;
u32 b3_mask = b3_mask_uni.u;
u32 b3_patt = b3_patt_uni.u;
u32 b3_requ = b3_requ_uni.u;
u32 b3_erro = b3_erro_uni.u;
u32 b4_mask = b4_mask_uni.u;
u32 b4_patt = b4_patt_uni.u;
u32 b4_requ = b4_requ_uni.u;
u32 b4_err0 = b4_err0_uni.u;
u32 b4_err1 = b4_err1_uni.u;
#endif
#define is_valid_seq_2(uni) ( \
((uni & b2_mask) == b2_patt) && \
((uni & b2_requ)) \
)
#define is_valid_seq_3(uni) ( \
((uni & b3_mask) == b3_patt) && \
((tmp = (uni & b3_requ))) && \
((tmp != b3_erro)) \
)
#define is_valid_seq_4(uni) ( \
((uni & b4_mask) == b4_patt) && \
((tmp = (uni & b4_requ))) && \
((tmp & b4_err0) == 0 || (tmp & b4_err1) == 0) \
)
/* The replacement character U+FFFD, used to indicate invalid character. */
const v32 rep = {{ 'F', 'F', 'F', 'D' }};
const v32 pre = {{ '\\', 'u', '0', '0' }};
const u8 *src = str;
const u8 *end = str + str_len;
*cur++ = '"';
copy_ascii:
/*
Copy continuous ASCII, loop unrolling, same as the following code:
while (end > src) (
if (unlikely(enc_table[*src])) break;
*cur++ = *src++;
);
*/
#define expr_jump(i) \
if (unlikely(enc_table[src[i]])) goto stop_char_##i;
#define expr_stop(i) \
stop_char_##i: \
memcpy(cur, src, i); \
cur += i; src += i; goto copy_utf8;
while (end - src >= 16) {
repeat16_incr(expr_jump)
byte_copy_16(cur, src);
cur += 16; src += 16;
}
while (end - src >= 4) {
repeat4_incr(expr_jump)
byte_copy_4(cur, src);
cur += 4; src += 4;
}
while (end > src) {
expr_jump(0)
*cur++ = *src++;
}
*cur++ = '"';
return cur;
repeat16_incr(expr_stop)
#undef expr_jump
#undef expr_stop
copy_utf8:
if (unlikely(src + 4 > end)) {
if (end == src) goto copy_end;
if (end - src < enc_table[*src] / 2) goto err_one;
}
switch (enc_table[*src]) {
case CHAR_ENC_CPY_1: {
*cur++ = *src++;
goto copy_ascii;
}
case CHAR_ENC_CPY_2: {
u16 v;
#if YYJSON_DISABLE_UTF8_VALIDATION
byte_copy_2(cur, src);
#else
v = byte_load_2(src);
if (unlikely(!is_valid_seq_2(v))) goto err_cpy;
byte_copy_2(cur, src);
#endif
cur += 2;
src += 2;
goto copy_utf8;
}
case CHAR_ENC_CPY_3: {
u32 v, tmp;
#if YYJSON_DISABLE_UTF8_VALIDATION
if (likely(src + 4 <= end)) {
byte_copy_4(cur, src);
} else {
byte_copy_2(cur, src);
cur[2] = src[2];
}
#else
if (likely(src + 4 <= end)) {
v = byte_load_4(src);
if (unlikely(!is_valid_seq_3(v))) goto err_cpy;
byte_copy_4(cur, src);
} else {
v = byte_load_3(src);
if (unlikely(!is_valid_seq_3(v))) goto err_cpy;
byte_copy_4(cur, &v);
}
#endif
cur += 3;
src += 3;
goto copy_utf8;
}
case CHAR_ENC_CPY_4: {
u32 v, tmp;
#if YYJSON_DISABLE_UTF8_VALIDATION
byte_copy_4(cur, src);
#else
v = byte_load_4(src);
if (unlikely(!is_valid_seq_4(v))) goto err_cpy;
byte_copy_4(cur, src);
#endif
cur += 4;
src += 4;
goto copy_utf8;
}
case CHAR_ENC_ESC_A: {
byte_copy_2(cur, &esc_single_char_table[*src * 2]);
cur += 2;
src += 1;
goto copy_utf8;
}
case CHAR_ENC_ESC_1: {
byte_copy_4(cur + 0, &pre);
byte_copy_2(cur + 4, &esc_hex_char_table[*src * 2]);
cur += 6;
src += 1;
goto copy_utf8;
}
case CHAR_ENC_ESC_2: {
u16 u, v;
#if !YYJSON_DISABLE_UTF8_VALIDATION
v = byte_load_2(src);
if (unlikely(!is_valid_seq_2(v))) goto err_esc;
#endif
u = (u16)(((u16)(src[0] & 0x1F) << 6) |
((u16)(src[1] & 0x3F) << 0));
byte_copy_2(cur + 0, &pre);
byte_copy_2(cur + 2, &esc_hex_char_table[(u >> 8) * 2]);
byte_copy_2(cur + 4, &esc_hex_char_table[(u & 0xFF) * 2]);
cur += 6;
src += 2;
goto copy_utf8;
}
case CHAR_ENC_ESC_3: {
u16 u;
u32 v, tmp;
#if !YYJSON_DISABLE_UTF8_VALIDATION
v = byte_load_3(src);
if (unlikely(!is_valid_seq_3(v))) goto err_esc;
#endif
u = (u16)(((u16)(src[0] & 0x0F) << 12) |
((u16)(src[1] & 0x3F) << 6) |
((u16)(src[2] & 0x3F) << 0));
byte_copy_2(cur + 0, &pre);
byte_copy_2(cur + 2, &esc_hex_char_table[(u >> 8) * 2]);
byte_copy_2(cur + 4, &esc_hex_char_table[(u & 0xFF) * 2]);
cur += 6;
src += 3;
goto copy_utf8;
}
case CHAR_ENC_ESC_4: {
u32 hi, lo, u, v, tmp;
#if !YYJSON_DISABLE_UTF8_VALIDATION
v = byte_load_4(src);
if (unlikely(!is_valid_seq_4(v))) goto err_esc;
#endif
u = ((u32)(src[0] & 0x07) << 18) |
((u32)(src[1] & 0x3F) << 12) |
((u32)(src[2] & 0x3F) << 6) |
((u32)(src[3] & 0x3F) << 0);
u -= 0x10000;
hi = (u >> 10) + 0xD800;
lo = (u & 0x3FF) + 0xDC00;
byte_copy_2(cur + 0, &pre);
byte_copy_2(cur + 2, &esc_hex_char_table[(hi >> 8) * 2]);
byte_copy_2(cur + 4, &esc_hex_char_table[(hi & 0xFF) * 2]);
byte_copy_2(cur + 6, &pre);
byte_copy_2(cur + 8, &esc_hex_char_table[(lo >> 8) * 2]);
byte_copy_2(cur + 10, &esc_hex_char_table[(lo & 0xFF) * 2]);
cur += 12;
src += 4;
goto copy_utf8;
}
case CHAR_ENC_ERR_1: {
goto err_one;
}
default: break;
}
copy_end:
*cur++ = '"';
return cur;
err_one:
if (esc) goto err_esc;
else goto err_cpy;
err_cpy:
if (!inv) return NULL;
*cur++ = *src++;
goto copy_utf8;
err_esc:
if (!inv) return NULL;
byte_copy_2(cur + 0, &pre);
byte_copy_4(cur + 2, &rep);
cur += 6;
src += 1;
goto copy_utf8;
#undef is_valid_seq_2
#undef is_valid_seq_3
#undef is_valid_seq_4
}
/*==============================================================================
* Writer Utilities
*============================================================================*/
/** Write null (requires 8 bytes buffer). */
static_inline u8 *write_null(u8 *cur) {
v64 v = {{ 'n', 'u', 'l', 'l', ',', '\n', 0, 0 }};
byte_copy_8(cur, &v);
return cur + 4;
}
/** Write bool (requires 8 bytes buffer). */
static_inline u8 *write_bool(u8 *cur, bool val) {
v64 v0 = {{ 'f', 'a', 'l', 's', 'e', ',', '\n', 0 }};
v64 v1 = {{ 't', 'r', 'u', 'e', ',', '\n', 0, 0 }};
if (val) {
byte_copy_8(cur, &v1);
} else {
byte_copy_8(cur, &v0);
}
return cur + 5 - val;
}
/** Write indent (requires level x 4 bytes buffer).
Param spaces should not larger than 4. */
static_inline u8 *write_indent(u8 *cur, usize level, usize spaces) {
while (level-- > 0) {
byte_copy_4(cur, " ");
cur += spaces;
}
return cur;
}
/** Write data to file pointer. */
static bool write_dat_to_fp(FILE *fp, u8 *dat, usize len,
yyjson_write_err *err) {
if (fwrite(dat, len, 1, fp) != 1) {
err->msg = "file writing failed";
err->code = YYJSON_WRITE_ERROR_FILE_WRITE;
return false;
}
return true;
}
/** Write data to file. */
static bool write_dat_to_file(const char *path, u8 *dat, usize len,
yyjson_write_err *err) {
#define return_err(_code, _msg) do { \
err->msg = _msg; \
err->code = YYJSON_WRITE_ERROR_##_code; \
if (file) fclose(file); \
return false; \
} while (false)
FILE *file = fopen_writeonly(path);
if (file == NULL) {
return_err(FILE_OPEN, "file opening failed");
}
if (fwrite(dat, len, 1, file) != 1) {
return_err(FILE_WRITE, "file writing failed");
}
if (fclose(file) != 0) {
file = NULL;
return_err(FILE_WRITE, "file closing failed");
}
return true;
#undef return_err
}
/*==============================================================================
* JSON Writer Implementation
*============================================================================*/
typedef struct yyjson_write_ctx {
usize tag;
} yyjson_write_ctx;
static_inline void yyjson_write_ctx_set(yyjson_write_ctx *ctx,
usize size, bool is_obj) {
ctx->tag = (size << 1) | (usize)is_obj;
}
static_inline void yyjson_write_ctx_get(yyjson_write_ctx *ctx,
usize *size, bool *is_obj) {
usize tag = ctx->tag;
*size = tag >> 1;
*is_obj = (bool)(tag & 1);
}
/** Write single JSON value. */
static_inline u8 *yyjson_write_single(yyjson_val *val,
yyjson_write_flag flg,
yyjson_alc alc,
usize *dat_len,
yyjson_write_err *err) {
#define return_err(_code, _msg) do { \
if (hdr) alc.free(alc.ctx, (void *)hdr); \
*dat_len = 0; \
err->code = YYJSON_WRITE_ERROR_##_code; \
err->msg = _msg; \
return NULL; \
} while (false)
#define incr_len(_len) do { \
hdr = (u8 *)alc.malloc(alc.ctx, _len); \
if (!hdr) goto fail_alloc; \
cur = hdr; \
} while (false)
#define check_str_len(_len) do { \
if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \
goto fail_alloc; \
} while (false)
u8 *hdr = NULL, *cur;
usize str_len;
const u8 *str_ptr;
const char_enc_type *enc_table = get_enc_table_with_flag(flg);
bool cpy = (enc_table == enc_table_cpy);
bool esc = has_write_flag(ESCAPE_UNICODE) != 0;
bool inv = has_write_flag(ALLOW_INVALID_UNICODE) != 0;
switch (unsafe_yyjson_get_type(val)) {
case YYJSON_TYPE_RAW:
str_len = unsafe_yyjson_get_len(val);
str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
check_str_len(str_len);
incr_len(str_len + 1);
cur = write_raw(cur, str_ptr, str_len);
break;
case YYJSON_TYPE_STR:
str_len = unsafe_yyjson_get_len(val);
str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
check_str_len(str_len);
incr_len(str_len * 6 + 4);
if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {
cur = write_string_noesc(cur, str_ptr, str_len);
} else {
cur = write_string(cur, esc, inv, str_ptr, str_len, enc_table);
if (unlikely(!cur)) goto fail_str;
}
break;
case YYJSON_TYPE_NUM:
incr_len(32);
cur = write_number(cur, val, flg);
if (unlikely(!cur)) goto fail_num;
break;
case YYJSON_TYPE_BOOL:
incr_len(8);
cur = write_bool(cur, unsafe_yyjson_get_bool(val));
break;
case YYJSON_TYPE_NULL:
incr_len(8);
cur = write_null(cur);
break;
case YYJSON_TYPE_ARR:
incr_len(4);
byte_copy_2(cur, "[]");
cur += 2;
break;
case YYJSON_TYPE_OBJ:
incr_len(4);
byte_copy_2(cur, "{}");
cur += 2;
break;
default:
goto fail_type;
}
*cur = '\0';
*dat_len = (usize)(cur - hdr);
memset(err, 0, sizeof(yyjson_write_err));
return hdr;
fail_alloc:
return_err(MEMORY_ALLOCATION, "memory allocation failed");
fail_type:
return_err(INVALID_VALUE_TYPE, "invalid JSON value type");
fail_num:
return_err(NAN_OR_INF, "nan or inf number is not allowed");
fail_str:
return_err(INVALID_STRING, "invalid utf-8 encoding in string");
#undef return_err
#undef check_str_len
#undef incr_len
}
/** Write JSON document minify.
The root of this document should be a non-empty container. */
static_inline u8 *yyjson_write_minify(const yyjson_val *root,
const yyjson_write_flag flg,
const yyjson_alc alc,
usize *dat_len,
yyjson_write_err *err) {
#define return_err(_code, _msg) do { \
*dat_len = 0; \
err->code = YYJSON_WRITE_ERROR_##_code; \
err->msg = _msg; \
if (hdr) alc.free(alc.ctx, hdr); \
return NULL; \
} while (false)
#define incr_len(_len) do { \
ext_len = (usize)(_len); \
if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \
alc_inc = yyjson_max(alc_len / 2, ext_len); \
alc_inc = size_align_up(alc_inc, sizeof(yyjson_write_ctx)); \
if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \
goto fail_alloc; \
alc_len += alc_inc; \
tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \
if (unlikely(!tmp)) goto fail_alloc; \
ctx_len = (usize)(end - (u8 *)ctx); \
ctx_tmp = (yyjson_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \
memmove((void *)ctx_tmp, (void *)(tmp + ((u8 *)ctx - hdr)), ctx_len); \
ctx = ctx_tmp; \
cur = tmp + (cur - hdr); \
end = tmp + alc_len; \
hdr = tmp; \
} \
} while (false)
#define check_str_len(_len) do { \
if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \
goto fail_alloc; \
} while (false)
yyjson_val *val;
yyjson_type val_type;
usize ctn_len, ctn_len_tmp;
bool ctn_obj, ctn_obj_tmp, is_key;
u8 *hdr, *cur, *end, *tmp;
yyjson_write_ctx *ctx, *ctx_tmp;
usize alc_len, alc_inc, ctx_len, ext_len, str_len;
const u8 *str_ptr;
const char_enc_type *enc_table = get_enc_table_with_flag(flg);
bool cpy = (enc_table == enc_table_cpy);
bool esc = has_write_flag(ESCAPE_UNICODE) != 0;
bool inv = has_write_flag(ALLOW_INVALID_UNICODE) != 0;
alc_len = root->uni.ofs / sizeof(yyjson_val);
alc_len = alc_len * YYJSON_WRITER_ESTIMATED_MINIFY_RATIO + 64;
alc_len = size_align_up(alc_len, sizeof(yyjson_write_ctx));
hdr = (u8 *)alc.malloc(alc.ctx, alc_len);
if (!hdr) goto fail_alloc;
cur = hdr;
end = hdr + alc_len;
ctx = (yyjson_write_ctx *)(void *)end;
doc_begin:
val = constcast(yyjson_val *)root;
val_type = unsafe_yyjson_get_type(val);
ctn_obj = (val_type == YYJSON_TYPE_OBJ);
ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;
*cur++ = (u8)('[' | ((u8)ctn_obj << 5));
val++;
val_begin:
val_type = unsafe_yyjson_get_type(val);
if (val_type == YYJSON_TYPE_STR) {
is_key = ((u8)ctn_obj & (u8)~ctn_len);
str_len = unsafe_yyjson_get_len(val);
str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
check_str_len(str_len);
incr_len(str_len * 6 + 16);
if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {
cur = write_string_noesc(cur, str_ptr, str_len);
} else {
cur = write_string(cur, esc, inv, str_ptr, str_len, enc_table);
if (unlikely(!cur)) goto fail_str;
}
*cur++ = is_key ? ':' : ',';
goto val_end;
}
if (val_type == YYJSON_TYPE_NUM) {
incr_len(32);
cur = write_number(cur, val, flg);
if (unlikely(!cur)) goto fail_num;
*cur++ = ',';
goto val_end;
}
if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==
(YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {
ctn_len_tmp = unsafe_yyjson_get_len(val);
ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);
incr_len(16);
if (unlikely(ctn_len_tmp == 0)) {
/* write empty container */
*cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));
*cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));
*cur++ = ',';
goto val_end;
} else {
/* push context, setup new container */
yyjson_write_ctx_set(--ctx, ctn_len, ctn_obj);
ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;
ctn_obj = ctn_obj_tmp;
*cur++ = (u8)('[' | ((u8)ctn_obj << 5));
val++;
goto val_begin;
}
}
if (val_type == YYJSON_TYPE_BOOL) {
incr_len(16);
cur = write_bool(cur, unsafe_yyjson_get_bool(val));
cur++;
goto val_end;
}
if (val_type == YYJSON_TYPE_NULL) {
incr_len(16);
cur = write_null(cur);
cur++;
goto val_end;
}
if (val_type == YYJSON_TYPE_RAW) {
str_len = unsafe_yyjson_get_len(val);
str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
check_str_len(str_len);
incr_len(str_len + 2);
cur = write_raw(cur, str_ptr, str_len);
*cur++ = ',';
goto val_end;
}
goto fail_type;
val_end:
val++;
ctn_len--;
if (unlikely(ctn_len == 0)) goto ctn_end;
goto val_begin;
ctn_end:
cur--;
*cur++ = (u8)(']' | ((u8)ctn_obj << 5));
*cur++ = ',';
if (unlikely((u8 *)ctx >= end)) goto doc_end;
yyjson_write_ctx_get(ctx++, &ctn_len, &ctn_obj);
ctn_len--;
if (likely(ctn_len > 0)) {
goto val_begin;
} else {
goto ctn_end;
}
doc_end:
*--cur = '\0';
*dat_len = (usize)(cur - hdr);
memset(err, 0, sizeof(yyjson_write_err));
return hdr;
fail_alloc:
return_err(MEMORY_ALLOCATION, "memory allocation failed");
fail_type:
return_err(INVALID_VALUE_TYPE, "invalid JSON value type");
fail_num:
return_err(NAN_OR_INF, "nan or inf number is not allowed");
fail_str:
return_err(INVALID_STRING, "invalid utf-8 encoding in string");
#undef return_err
#undef incr_len
#undef check_str_len
}
/** Write JSON document pretty.
The root of this document should be a non-empty container. */
static_inline u8 *yyjson_write_pretty(const yyjson_val *root,
const yyjson_write_flag flg,
const yyjson_alc alc,
usize *dat_len,
yyjson_write_err *err) {
#define return_err(_code, _msg) do { \
*dat_len = 0; \
err->code = YYJSON_WRITE_ERROR_##_code; \
err->msg = _msg; \
if (hdr) alc.free(alc.ctx, hdr); \
return NULL; \
} while (false)
#define incr_len(_len) do { \
ext_len = (usize)(_len); \
if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \
alc_inc = yyjson_max(alc_len / 2, ext_len); \
alc_inc = size_align_up(alc_inc, sizeof(yyjson_write_ctx)); \
if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \
goto fail_alloc; \
alc_len += alc_inc; \
tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \
if (unlikely(!tmp)) goto fail_alloc; \
ctx_len = (usize)(end - (u8 *)ctx); \
ctx_tmp = (yyjson_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \
memmove((void *)ctx_tmp, (void *)(tmp + ((u8 *)ctx - hdr)), ctx_len); \
ctx = ctx_tmp; \
cur = tmp + (cur - hdr); \
end = tmp + alc_len; \
hdr = tmp; \
} \
} while (false)
#define check_str_len(_len) do { \
if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \
goto fail_alloc; \
} while (false)
yyjson_val *val;
yyjson_type val_type;
usize ctn_len, ctn_len_tmp;
bool ctn_obj, ctn_obj_tmp, is_key, no_indent;
u8 *hdr, *cur, *end, *tmp;
yyjson_write_ctx *ctx, *ctx_tmp;
usize alc_len, alc_inc, ctx_len, ext_len, str_len, level;
const u8 *str_ptr;
const char_enc_type *enc_table = get_enc_table_with_flag(flg);
bool cpy = (enc_table == enc_table_cpy);
bool esc = has_write_flag(ESCAPE_UNICODE) != 0;
bool inv = has_write_flag(ALLOW_INVALID_UNICODE) != 0;
usize spaces = has_write_flag(PRETTY_TWO_SPACES) ? 2 : 4;
alc_len = root->uni.ofs / sizeof(yyjson_val);
alc_len = alc_len * YYJSON_WRITER_ESTIMATED_PRETTY_RATIO + 64;
alc_len = size_align_up(alc_len, sizeof(yyjson_write_ctx));
hdr = (u8 *)alc.malloc(alc.ctx, alc_len);
if (!hdr) goto fail_alloc;
cur = hdr;
end = hdr + alc_len;
ctx = (yyjson_write_ctx *)(void *)end;
doc_begin:
val = constcast(yyjson_val *)root;
val_type = unsafe_yyjson_get_type(val);
ctn_obj = (val_type == YYJSON_TYPE_OBJ);
ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;
*cur++ = (u8)('[' | ((u8)ctn_obj << 5));
*cur++ = '\n';
val++;
level = 1;
val_begin:
val_type = unsafe_yyjson_get_type(val);
if (val_type == YYJSON_TYPE_STR) {
is_key = (bool)((u8)ctn_obj & (u8)~ctn_len);
no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
str_len = unsafe_yyjson_get_len(val);
str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
check_str_len(str_len);
incr_len(str_len * 6 + 16 + (no_indent ? 0 : level * 4));
cur = write_indent(cur, no_indent ? 0 : level, spaces);
if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {
cur = write_string_noesc(cur, str_ptr, str_len);
} else {
cur = write_string(cur, esc, inv, str_ptr, str_len, enc_table);
if (unlikely(!cur)) goto fail_str;
}
*cur++ = is_key ? ':' : ',';
*cur++ = is_key ? ' ' : '\n';
goto val_end;
}
if (val_type == YYJSON_TYPE_NUM) {
no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
incr_len(32 + (no_indent ? 0 : level * 4));
cur = write_indent(cur, no_indent ? 0 : level, spaces);
cur = write_number(cur, val, flg);
if (unlikely(!cur)) goto fail_num;
*cur++ = ',';
*cur++ = '\n';
goto val_end;
}
if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==
(YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {
no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
ctn_len_tmp = unsafe_yyjson_get_len(val);
ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);
if (unlikely(ctn_len_tmp == 0)) {
/* write empty container */
incr_len(16 + (no_indent ? 0 : level * 4));
cur = write_indent(cur, no_indent ? 0 : level, spaces);
*cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));
*cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));
*cur++ = ',';
*cur++ = '\n';
goto val_end;
} else {
/* push context, setup new container */
incr_len(32 + (no_indent ? 0 : level * 4));
yyjson_write_ctx_set(--ctx, ctn_len, ctn_obj);
ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;
ctn_obj = ctn_obj_tmp;
cur = write_indent(cur, no_indent ? 0 : level, spaces);
level++;
*cur++ = (u8)('[' | ((u8)ctn_obj << 5));
*cur++ = '\n';
val++;
goto val_begin;
}
}
if (val_type == YYJSON_TYPE_BOOL) {
no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
incr_len(16 + (no_indent ? 0 : level * 4));
cur = write_indent(cur, no_indent ? 0 : level, spaces);
cur = write_bool(cur, unsafe_yyjson_get_bool(val));
cur += 2;
goto val_end;
}
if (val_type == YYJSON_TYPE_NULL) {
no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
incr_len(16 + (no_indent ? 0 : level * 4));
cur = write_indent(cur, no_indent ? 0 : level, spaces);
cur = write_null(cur);
cur += 2;
goto val_end;
}
if (val_type == YYJSON_TYPE_RAW) {
str_len = unsafe_yyjson_get_len(val);
str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
check_str_len(str_len);
incr_len(str_len + 3);
cur = write_raw(cur, str_ptr, str_len);
*cur++ = ',';
*cur++ = '\n';
goto val_end;
}
goto fail_type;
val_end:
val++;
ctn_len--;
if (unlikely(ctn_len == 0)) goto ctn_end;
goto val_begin;
ctn_end:
cur -= 2;
*cur++ = '\n';
incr_len(level * 4);
cur = write_indent(cur, --level, spaces);
*cur++ = (u8)(']' | ((u8)ctn_obj << 5));
if (unlikely((u8 *)ctx >= end)) goto doc_end;
yyjson_write_ctx_get(ctx++, &ctn_len, &ctn_obj);
ctn_len--;
*cur++ = ',';
*cur++ = '\n';
if (likely(ctn_len > 0)) {
goto val_begin;
} else {
goto ctn_end;
}
doc_end:
*cur = '\0';
*dat_len = (usize)(cur - hdr);
memset(err, 0, sizeof(yyjson_write_err));
return hdr;
fail_alloc:
return_err(MEMORY_ALLOCATION, "memory allocation failed");
fail_type:
return_err(INVALID_VALUE_TYPE, "invalid JSON value type");
fail_num:
return_err(NAN_OR_INF, "nan or inf number is not allowed");
fail_str:
return_err(INVALID_STRING, "invalid utf-8 encoding in string");
#undef return_err
#undef incr_len
#undef check_str_len
}
char *yyjson_val_write_opts(const yyjson_val *val,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
usize *dat_len,
yyjson_write_err *err) {
yyjson_write_err dummy_err;
usize dummy_dat_len;
yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
yyjson_val *root = constcast(yyjson_val *)val;
err = err ? err : &dummy_err;
dat_len = dat_len ? dat_len : &dummy_dat_len;
if (unlikely(!root)) {
*dat_len = 0;
err->msg = "input JSON is NULL";
err->code = YYJSON_READ_ERROR_INVALID_PARAMETER;
return NULL;
}
if (!unsafe_yyjson_is_ctn(root) || unsafe_yyjson_get_len(root) == 0) {
return (char *)yyjson_write_single(root, flg, alc, dat_len, err);
} else if (flg & (YYJSON_WRITE_PRETTY | YYJSON_WRITE_PRETTY_TWO_SPACES)) {
return (char *)yyjson_write_pretty(root, flg, alc, dat_len, err);
} else {
return (char *)yyjson_write_minify(root, flg, alc, dat_len, err);
}
}
char *yyjson_write_opts(const yyjson_doc *doc,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
usize *dat_len,
yyjson_write_err *err) {
yyjson_val *root = doc ? doc->root : NULL;
return yyjson_val_write_opts(root, flg, alc_ptr, dat_len, err);
}
bool yyjson_val_write_file(const char *path,
const yyjson_val *val,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
yyjson_write_err *err) {
yyjson_write_err dummy_err;
u8 *dat;
usize dat_len = 0;
yyjson_val *root = constcast(yyjson_val *)val;
bool suc;
alc_ptr = alc_ptr ? alc_ptr : &YYJSON_DEFAULT_ALC;
err = err ? err : &dummy_err;
if (unlikely(!path || !*path)) {
err->msg = "input path is invalid";
err->code = YYJSON_READ_ERROR_INVALID_PARAMETER;
return false;
}
dat = (u8 *)yyjson_val_write_opts(root, flg, alc_ptr, &dat_len, err);
if (unlikely(!dat)) return false;
suc = write_dat_to_file(path, dat, dat_len, err);
alc_ptr->free(alc_ptr->ctx, dat);
return suc;
}
bool yyjson_val_write_fp(FILE *fp,
const yyjson_val *val,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
yyjson_write_err *err) {
yyjson_write_err dummy_err;
u8 *dat;
usize dat_len = 0;
yyjson_val *root = constcast(yyjson_val *)val;
bool suc;
alc_ptr = alc_ptr ? alc_ptr : &YYJSON_DEFAULT_ALC;
err = err ? err : &dummy_err;
if (unlikely(!fp)) {
err->msg = "input fp is invalid";
err->code = YYJSON_READ_ERROR_INVALID_PARAMETER;
return false;
}
dat = (u8 *)yyjson_val_write_opts(root, flg, alc_ptr, &dat_len, err);
if (unlikely(!dat)) return false;
suc = write_dat_to_fp(fp, dat, dat_len, err);
alc_ptr->free(alc_ptr->ctx, dat);
return suc;
}
bool yyjson_write_file(const char *path,
const yyjson_doc *doc,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
yyjson_write_err *err) {
yyjson_val *root = doc ? doc->root : NULL;
return yyjson_val_write_file(path, root, flg, alc_ptr, err);
}
bool yyjson_write_fp(FILE *fp,
const yyjson_doc *doc,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
yyjson_write_err *err) {
yyjson_val *root = doc ? doc->root : NULL;
return yyjson_val_write_fp(fp, root, flg, alc_ptr, err);
}
/*==============================================================================
* Mutable JSON Writer Implementation
*============================================================================*/
typedef struct yyjson_mut_write_ctx {
usize tag;
yyjson_mut_val *ctn;
} yyjson_mut_write_ctx;
static_inline void yyjson_mut_write_ctx_set(yyjson_mut_write_ctx *ctx,
yyjson_mut_val *ctn,
usize size, bool is_obj) {
ctx->tag = (size << 1) | (usize)is_obj;
ctx->ctn = ctn;
}
static_inline void yyjson_mut_write_ctx_get(yyjson_mut_write_ctx *ctx,
yyjson_mut_val **ctn,
usize *size, bool *is_obj) {
usize tag = ctx->tag;
*size = tag >> 1;
*is_obj = (bool)(tag & 1);
*ctn = ctx->ctn;
}
/** Get the estimated number of values for the mutable JSON document. */
static_inline usize yyjson_mut_doc_estimated_val_num(
const yyjson_mut_doc *doc) {
usize sum = 0;
yyjson_val_chunk *chunk = doc->val_pool.chunks;
while (chunk) {
sum += chunk->chunk_size / sizeof(yyjson_mut_val) - 1;
if (chunk == doc->val_pool.chunks) {
sum -= (usize)(doc->val_pool.end - doc->val_pool.cur);
}
chunk = chunk->next;
}
return sum;
}
/** Write single JSON value. */
static_inline u8 *yyjson_mut_write_single(yyjson_mut_val *val,
yyjson_write_flag flg,
yyjson_alc alc,
usize *dat_len,
yyjson_write_err *err) {
return yyjson_write_single((yyjson_val *)val, flg, alc, dat_len, err);
}
/** Write JSON document minify.
The root of this document should be a non-empty container. */
static_inline u8 *yyjson_mut_write_minify(const yyjson_mut_val *root,
usize estimated_val_num,
yyjson_write_flag flg,
yyjson_alc alc,
usize *dat_len,
yyjson_write_err *err) {
#define return_err(_code, _msg) do { \
*dat_len = 0; \
err->code = YYJSON_WRITE_ERROR_##_code; \
err->msg = _msg; \
if (hdr) alc.free(alc.ctx, hdr); \
return NULL; \
} while (false)
#define incr_len(_len) do { \
ext_len = (usize)(_len); \
if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \
alc_inc = yyjson_max(alc_len / 2, ext_len); \
alc_inc = size_align_up(alc_inc, sizeof(yyjson_mut_write_ctx)); \
if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \
goto fail_alloc; \
alc_len += alc_inc; \
tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \
if (unlikely(!tmp)) goto fail_alloc; \
ctx_len = (usize)(end - (u8 *)ctx); \
ctx_tmp = (yyjson_mut_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \
memmove((void *)ctx_tmp, (void *)(tmp + ((u8 *)ctx - hdr)), ctx_len); \
ctx = ctx_tmp; \
cur = tmp + (cur - hdr); \
end = tmp + alc_len; \
hdr = tmp; \
} \
} while (false)
#define check_str_len(_len) do { \
if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \
goto fail_alloc; \
} while (false)
yyjson_mut_val *val, *ctn;
yyjson_type val_type;
usize ctn_len, ctn_len_tmp;
bool ctn_obj, ctn_obj_tmp, is_key;
u8 *hdr, *cur, *end, *tmp;
yyjson_mut_write_ctx *ctx, *ctx_tmp;
usize alc_len, alc_inc, ctx_len, ext_len, str_len;
const u8 *str_ptr;
const char_enc_type *enc_table = get_enc_table_with_flag(flg);
bool cpy = (enc_table == enc_table_cpy);
bool esc = has_write_flag(ESCAPE_UNICODE) != 0;
bool inv = has_write_flag(ALLOW_INVALID_UNICODE) != 0;
alc_len = estimated_val_num * YYJSON_WRITER_ESTIMATED_MINIFY_RATIO + 64;
alc_len = size_align_up(alc_len, sizeof(yyjson_mut_write_ctx));
hdr = (u8 *)alc.malloc(alc.ctx, alc_len);
if (!hdr) goto fail_alloc;
cur = hdr;
end = hdr + alc_len;
ctx = (yyjson_mut_write_ctx *)(void *)end;
doc_begin:
val = constcast(yyjson_mut_val *)root;
val_type = unsafe_yyjson_get_type(val);
ctn_obj = (val_type == YYJSON_TYPE_OBJ);
ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;
*cur++ = (u8)('[' | ((u8)ctn_obj << 5));
ctn = val;
val = (yyjson_mut_val *)val->uni.ptr; /* tail */
val = ctn_obj ? val->next->next : val->next;
val_begin:
val_type = unsafe_yyjson_get_type(val);
if (val_type == YYJSON_TYPE_STR) {
is_key = ((u8)ctn_obj & (u8)~ctn_len);
str_len = unsafe_yyjson_get_len(val);
str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
check_str_len(str_len);
incr_len(str_len * 6 + 16);
if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {
cur = write_string_noesc(cur, str_ptr, str_len);
} else {
cur = write_string(cur, esc, inv, str_ptr, str_len, enc_table);
if (unlikely(!cur)) goto fail_str;
}
*cur++ = is_key ? ':' : ',';
goto val_end;
}
if (val_type == YYJSON_TYPE_NUM) {
incr_len(32);
cur = write_number(cur, (yyjson_val *)val, flg);
if (unlikely(!cur)) goto fail_num;
*cur++ = ',';
goto val_end;
}
if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==
(YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {
ctn_len_tmp = unsafe_yyjson_get_len(val);
ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);
incr_len(16);
if (unlikely(ctn_len_tmp == 0)) {
/* write empty container */
*cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));
*cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));
*cur++ = ',';
goto val_end;
} else {
/* push context, setup new container */
yyjson_mut_write_ctx_set(--ctx, ctn, ctn_len, ctn_obj);
ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;
ctn_obj = ctn_obj_tmp;
*cur++ = (u8)('[' | ((u8)ctn_obj << 5));
ctn = val;
val = (yyjson_mut_val *)ctn->uni.ptr; /* tail */
val = ctn_obj ? val->next->next : val->next;
goto val_begin;
}
}
if (val_type == YYJSON_TYPE_BOOL) {
incr_len(16);
cur = write_bool(cur, unsafe_yyjson_get_bool(val));
cur++;
goto val_end;
}
if (val_type == YYJSON_TYPE_NULL) {
incr_len(16);
cur = write_null(cur);
cur++;
goto val_end;
}
if (val_type == YYJSON_TYPE_RAW) {
str_len = unsafe_yyjson_get_len(val);
str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
check_str_len(str_len);
incr_len(str_len + 2);
cur = write_raw(cur, str_ptr, str_len);
*cur++ = ',';
goto val_end;
}
goto fail_type;
val_end:
ctn_len--;
if (unlikely(ctn_len == 0)) goto ctn_end;
val = val->next;
goto val_begin;
ctn_end:
cur--;
*cur++ = (u8)(']' | ((u8)ctn_obj << 5));
*cur++ = ',';
if (unlikely((u8 *)ctx >= end)) goto doc_end;
val = ctn->next;
yyjson_mut_write_ctx_get(ctx++, &ctn, &ctn_len, &ctn_obj);
ctn_len--;
if (likely(ctn_len > 0)) {
goto val_begin;
} else {
goto ctn_end;
}
doc_end:
*--cur = '\0';
*dat_len = (usize)(cur - hdr);
err->code = YYJSON_WRITE_SUCCESS;
err->msg = "success";
return hdr;
fail_alloc:
return_err(MEMORY_ALLOCATION, "memory allocation failed");
fail_type:
return_err(INVALID_VALUE_TYPE, "invalid JSON value type");
fail_num:
return_err(NAN_OR_INF, "nan or inf number is not allowed");
fail_str:
return_err(INVALID_STRING, "invalid utf-8 encoding in string");
#undef return_err
#undef incr_len
#undef check_str_len
}
/** Write JSON document pretty.
The root of this document should be a non-empty container. */
static_inline u8 *yyjson_mut_write_pretty(const yyjson_mut_val *root,
usize estimated_val_num,
yyjson_write_flag flg,
yyjson_alc alc,
usize *dat_len,
yyjson_write_err *err) {
#define return_err(_code, _msg) do { \
*dat_len = 0; \
err->code = YYJSON_WRITE_ERROR_##_code; \
err->msg = _msg; \
if (hdr) alc.free(alc.ctx, hdr); \
return NULL; \
} while (false)
#define incr_len(_len) do { \
ext_len = (usize)(_len); \
if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \
alc_inc = yyjson_max(alc_len / 2, ext_len); \
alc_inc = size_align_up(alc_inc, sizeof(yyjson_mut_write_ctx)); \
if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \
goto fail_alloc; \
alc_len += alc_inc; \
tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \
if (unlikely(!tmp)) goto fail_alloc; \
ctx_len = (usize)(end - (u8 *)ctx); \
ctx_tmp = (yyjson_mut_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \
memmove((void *)ctx_tmp, (void *)(tmp + ((u8 *)ctx - hdr)), ctx_len); \
ctx = ctx_tmp; \
cur = tmp + (cur - hdr); \
end = tmp + alc_len; \
hdr = tmp; \
} \
} while (false)
#define check_str_len(_len) do { \
if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \
goto fail_alloc; \
} while (false)
yyjson_mut_val *val, *ctn;
yyjson_type val_type;
usize ctn_len, ctn_len_tmp;
bool ctn_obj, ctn_obj_tmp, is_key, no_indent;
u8 *hdr, *cur, *end, *tmp;
yyjson_mut_write_ctx *ctx, *ctx_tmp;
usize alc_len, alc_inc, ctx_len, ext_len, str_len, level;
const u8 *str_ptr;
const char_enc_type *enc_table = get_enc_table_with_flag(flg);
bool cpy = (enc_table == enc_table_cpy);
bool esc = has_write_flag(ESCAPE_UNICODE) != 0;
bool inv = has_write_flag(ALLOW_INVALID_UNICODE) != 0;
usize spaces = has_write_flag(PRETTY_TWO_SPACES) ? 2 : 4;
alc_len = estimated_val_num * YYJSON_WRITER_ESTIMATED_PRETTY_RATIO + 64;
alc_len = size_align_up(alc_len, sizeof(yyjson_mut_write_ctx));
hdr = (u8 *)alc.malloc(alc.ctx, alc_len);
if (!hdr) goto fail_alloc;
cur = hdr;
end = hdr + alc_len;
ctx = (yyjson_mut_write_ctx *)(void *)end;
doc_begin:
val = constcast(yyjson_mut_val *)root;
val_type = unsafe_yyjson_get_type(val);
ctn_obj = (val_type == YYJSON_TYPE_OBJ);
ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;
*cur++ = (u8)('[' | ((u8)ctn_obj << 5));
*cur++ = '\n';
ctn = val;
val = (yyjson_mut_val *)val->uni.ptr; /* tail */
val = ctn_obj ? val->next->next : val->next;
level = 1;
val_begin:
val_type = unsafe_yyjson_get_type(val);
if (val_type == YYJSON_TYPE_STR) {
is_key = (bool)((u8)ctn_obj & (u8)~ctn_len);
no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
str_len = unsafe_yyjson_get_len(val);
str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
check_str_len(str_len);
incr_len(str_len * 6 + 16 + (no_indent ? 0 : level * 4));
cur = write_indent(cur, no_indent ? 0 : level, spaces);
if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {
cur = write_string_noesc(cur, str_ptr, str_len);
} else {
cur = write_string(cur, esc, inv, str_ptr, str_len, enc_table);
if (unlikely(!cur)) goto fail_str;
}
*cur++ = is_key ? ':' : ',';
*cur++ = is_key ? ' ' : '\n';
goto val_end;
}
if (val_type == YYJSON_TYPE_NUM) {
no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
incr_len(32 + (no_indent ? 0 : level * 4));
cur = write_indent(cur, no_indent ? 0 : level, spaces);
cur = write_number(cur, (yyjson_val *)val, flg);
if (unlikely(!cur)) goto fail_num;
*cur++ = ',';
*cur++ = '\n';
goto val_end;
}
if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==
(YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {
no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
ctn_len_tmp = unsafe_yyjson_get_len(val);
ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);
if (unlikely(ctn_len_tmp == 0)) {
/* write empty container */
incr_len(16 + (no_indent ? 0 : level * 4));
cur = write_indent(cur, no_indent ? 0 : level, spaces);
*cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));
*cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));
*cur++ = ',';
*cur++ = '\n';
goto val_end;
} else {
/* push context, setup new container */
incr_len(32 + (no_indent ? 0 : level * 4));
yyjson_mut_write_ctx_set(--ctx, ctn, ctn_len, ctn_obj);
ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;
ctn_obj = ctn_obj_tmp;
cur = write_indent(cur, no_indent ? 0 : level, spaces);
level++;
*cur++ = (u8)('[' | ((u8)ctn_obj << 5));
*cur++ = '\n';
ctn = val;
val = (yyjson_mut_val *)ctn->uni.ptr; /* tail */
val = ctn_obj ? val->next->next : val->next;
goto val_begin;
}
}
if (val_type == YYJSON_TYPE_BOOL) {
no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
incr_len(16 + (no_indent ? 0 : level * 4));
cur = write_indent(cur, no_indent ? 0 : level, spaces);
cur = write_bool(cur, unsafe_yyjson_get_bool(val));
cur += 2;
goto val_end;
}
if (val_type == YYJSON_TYPE_NULL) {
no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
incr_len(16 + (no_indent ? 0 : level * 4));
cur = write_indent(cur, no_indent ? 0 : level, spaces);
cur = write_null(cur);
cur += 2;
goto val_end;
}
if (val_type == YYJSON_TYPE_RAW) {
str_len = unsafe_yyjson_get_len(val);
str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
check_str_len(str_len);
incr_len(str_len + 3);
cur = write_raw(cur, str_ptr, str_len);
*cur++ = ',';
*cur++ = '\n';
goto val_end;
}
goto fail_type;
val_end:
ctn_len--;
if (unlikely(ctn_len == 0)) goto ctn_end;
val = val->next;
goto val_begin;
ctn_end:
cur -= 2;
*cur++ = '\n';
incr_len(level * 4);
cur = write_indent(cur, --level, spaces);
*cur++ = (u8)(']' | ((u8)ctn_obj << 5));
if (unlikely((u8 *)ctx >= end)) goto doc_end;
val = ctn->next;
yyjson_mut_write_ctx_get(ctx++, &ctn, &ctn_len, &ctn_obj);
ctn_len--;
*cur++ = ',';
*cur++ = '\n';
if (likely(ctn_len > 0)) {
goto val_begin;
} else {
goto ctn_end;
}
doc_end:
*cur = '\0';
*dat_len = (usize)(cur - hdr);
err->code = YYJSON_WRITE_SUCCESS;
err->msg = "success";
return hdr;
fail_alloc:
return_err(MEMORY_ALLOCATION, "memory allocation failed");
fail_type:
return_err(INVALID_VALUE_TYPE, "invalid JSON value type");
fail_num:
return_err(NAN_OR_INF, "nan or inf number is not allowed");
fail_str:
return_err(INVALID_STRING, "invalid utf-8 encoding in string");
#undef return_err
#undef incr_len
#undef check_str_len
}
static char *yyjson_mut_write_opts_impl(const yyjson_mut_val *val,
usize estimated_val_num,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
usize *dat_len,
yyjson_write_err *err) {
yyjson_write_err dummy_err;
usize dummy_dat_len;
yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
yyjson_mut_val *root = constcast(yyjson_mut_val *)val;
err = err ? err : &dummy_err;
dat_len = dat_len ? dat_len : &dummy_dat_len;
if (unlikely(!root)) {
*dat_len = 0;
err->msg = "input JSON is NULL";
err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;
return NULL;
}
if (!unsafe_yyjson_is_ctn(root) || unsafe_yyjson_get_len(root) == 0) {
return (char *)yyjson_mut_write_single(root, flg, alc, dat_len, err);
} else if (flg & (YYJSON_WRITE_PRETTY | YYJSON_WRITE_PRETTY_TWO_SPACES)) {
return (char *)yyjson_mut_write_pretty(root, estimated_val_num,
flg, alc, dat_len, err);
} else {
return (char *)yyjson_mut_write_minify(root, estimated_val_num,
flg, alc, dat_len, err);
}
}
char *yyjson_mut_val_write_opts(const yyjson_mut_val *val,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
usize *dat_len,
yyjson_write_err *err) {
return yyjson_mut_write_opts_impl(val, 0, flg, alc_ptr, dat_len, err);
}
char *yyjson_mut_write_opts(const yyjson_mut_doc *doc,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
usize *dat_len,
yyjson_write_err *err) {
yyjson_mut_val *root;
usize estimated_val_num;
if (likely(doc)) {
root = doc->root;
estimated_val_num = yyjson_mut_doc_estimated_val_num(doc);
} else {
root = NULL;
estimated_val_num = 0;
}
return yyjson_mut_write_opts_impl(root, estimated_val_num,
flg, alc_ptr, dat_len, err);
}
bool yyjson_mut_val_write_file(const char *path,
const yyjson_mut_val *val,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
yyjson_write_err *err) {
yyjson_write_err dummy_err;
u8 *dat;
usize dat_len = 0;
yyjson_mut_val *root = constcast(yyjson_mut_val *)val;
bool suc;
alc_ptr = alc_ptr ? alc_ptr : &YYJSON_DEFAULT_ALC;
err = err ? err : &dummy_err;
if (unlikely(!path || !*path)) {
err->msg = "input path is invalid";
err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;
return false;
}
dat = (u8 *)yyjson_mut_val_write_opts(root, flg, alc_ptr, &dat_len, err);
if (unlikely(!dat)) return false;
suc = write_dat_to_file(path, dat, dat_len, err);
alc_ptr->free(alc_ptr->ctx, dat);
return suc;
}
bool yyjson_mut_val_write_fp(FILE *fp,
const yyjson_mut_val *val,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
yyjson_write_err *err) {
yyjson_write_err dummy_err;
u8 *dat;
usize dat_len = 0;
yyjson_mut_val *root = constcast(yyjson_mut_val *)val;
bool suc;
alc_ptr = alc_ptr ? alc_ptr : &YYJSON_DEFAULT_ALC;
err = err ? err : &dummy_err;
if (unlikely(!fp)) {
err->msg = "input fp is invalid";
err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;
return false;
}
dat = (u8 *)yyjson_mut_val_write_opts(root, flg, alc_ptr, &dat_len, err);
if (unlikely(!dat)) return false;
suc = write_dat_to_fp(fp, dat, dat_len, err);
alc_ptr->free(alc_ptr->ctx, dat);
return suc;
}
bool yyjson_mut_write_file(const char *path,
const yyjson_mut_doc *doc,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
yyjson_write_err *err) {
yyjson_mut_val *root = doc ? doc->root : NULL;
return yyjson_mut_val_write_file(path, root, flg, alc_ptr, err);
}
bool yyjson_mut_write_fp(FILE *fp,
const yyjson_mut_doc *doc,
yyjson_write_flag flg,
const yyjson_alc *alc_ptr,
yyjson_write_err *err) {
yyjson_mut_val *root = doc ? doc->root : NULL;
return yyjson_mut_val_write_fp(fp, root, flg, alc_ptr, err);
}
#endif /* YYJSON_DISABLE_WRITER */
|
d1e9283384ff998c33ceabac9855575705ca612c
|
75196819c910f3fd523f1a4d28e5d0fe12570ab1
|
/src/bdb53/src/os/os_rw.c
|
5604f3f2ecca4bf547fa4a69a908d74653a63b7d
|
[
"MIT",
"BSD-3-Clause",
"Sleepycat"
] |
permissive
|
gridcoin-community/Gridcoin-Research
|
889967579b5b05bcc3ae836697a0f173b5ae91ea
|
21414dd0f63c9a34060f7f762f08d1a52aeb9e87
|
refs/heads/development
| 2023-09-04T09:21:55.006935
| 2023-09-03T17:45:20
| 2023-09-03T17:45:20
| 23,332,350
| 292
| 117
|
MIT
| 2023-09-11T10:22:10
| 2014-08-25T23:41:04
|
HTML
|
UTF-8
|
C
| false
| false
| 6,774
|
c
|
os_rw.c
|
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 1997, 2013 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
#include "db_config.h"
#include "db_int.h"
/*
* __os_io --
* Do an I/O.
*
* PUBLIC: int __os_io __P((ENV *, int, DB_FH *, db_pgno_t,
* PUBLIC: u_int32_t, u_int32_t, u_int32_t, u_int8_t *, size_t *));
*/
int
__os_io(env, op, fhp, pgno, pgsize, relative, io_len, buf, niop)
ENV *env;
int op;
DB_FH *fhp;
db_pgno_t pgno;
u_int32_t pgsize, relative, io_len;
u_int8_t *buf;
size_t *niop;
{
#if defined(HAVE_PREAD) && defined(HAVE_PWRITE)
DB_ENV *dbenv;
off_t offset;
ssize_t nio;
#endif
int ret;
/*
* Check for illegal usage.
*
* This routine is used in one of two ways: reading bytes from an
* absolute offset and reading a specific database page. All of
* our absolute offsets are known to fit into a u_int32_t, while
* our database pages might be at offsets larger than a u_int32_t.
*/
DB_ASSERT(env, F_ISSET(fhp, DB_FH_OPENED) && fhp->fd != -1);
DB_ASSERT(env, (pgno == 0 && pgsize == 0) || relative == 0);
#if defined(HAVE_PREAD) && defined(HAVE_PWRITE)
dbenv = env == NULL ? NULL : env->dbenv;
if ((offset = relative) == 0)
offset = (off_t)pgno * pgsize;
switch (op) {
case DB_IO_READ:
if (DB_GLOBAL(j_read) != NULL)
goto slow;
#if defined(HAVE_STATISTICS)
++fhp->read_count;
#endif
if (dbenv != NULL &&
FLD_ISSET(dbenv->verbose, DB_VERB_FILEOPS_ALL))
__db_msg(env, DB_STR_A("0130",
"fileops: read %s: %lu bytes at offset %lu",
"%s %lu %lu"), fhp->name, (u_long)io_len,
(u_long)offset);
LAST_PANIC_CHECK_BEFORE_IO(env);
nio = DB_GLOBAL(j_pread) != NULL ?
DB_GLOBAL(j_pread)(fhp->fd, buf, io_len, offset) :
pread(fhp->fd, buf, io_len, offset);
break;
case DB_IO_WRITE:
if (DB_GLOBAL(j_write) != NULL)
goto slow;
#ifdef HAVE_FILESYSTEM_NOTZERO
if (__os_fs_notzero())
goto slow;
#endif
#if defined(HAVE_STATISTICS)
++fhp->write_count;
#endif
if (dbenv != NULL &&
FLD_ISSET(dbenv->verbose, DB_VERB_FILEOPS_ALL))
__db_msg(env, DB_STR_A("0131",
"fileops: write %s: %lu bytes at offset %lu",
"%s %lu %lu"), fhp->name, (u_long)io_len,
(u_long)offset);
LAST_PANIC_CHECK_BEFORE_IO(env);
nio = DB_GLOBAL(j_pwrite) != NULL ?
DB_GLOBAL(j_pwrite)(fhp->fd, buf, io_len, offset) :
pwrite(fhp->fd, buf, io_len, offset);
break;
default:
return (EINVAL);
}
if (nio == (ssize_t)io_len) {
*niop = io_len;
return (0);
}
slow:
#endif
MUTEX_LOCK(env, fhp->mtx_fh);
if ((ret = __os_seek(env, fhp, pgno, pgsize, relative)) != 0)
goto err;
switch (op) {
case DB_IO_READ:
ret = __os_read(env, fhp, buf, io_len, niop);
break;
case DB_IO_WRITE:
ret = __os_write(env, fhp, buf, io_len, niop);
break;
default:
ret = EINVAL;
break;
}
err: MUTEX_UNLOCK(env, fhp->mtx_fh);
return (ret);
}
/*
* __os_read --
* Read from a file handle.
*
* PUBLIC: int __os_read __P((ENV *, DB_FH *, void *, size_t, size_t *));
*/
int
__os_read(env, fhp, addr, len, nrp)
ENV *env;
DB_FH *fhp;
void *addr;
size_t len;
size_t *nrp;
{
DB_ENV *dbenv;
size_t offset;
ssize_t nr;
int ret;
u_int8_t *taddr;
dbenv = env == NULL ? NULL : env->dbenv;
ret = 0;
DB_ASSERT(env, F_ISSET(fhp, DB_FH_OPENED) && fhp->fd != -1);
#if defined(HAVE_STATISTICS)
++fhp->read_count;
#endif
if (dbenv != NULL && FLD_ISSET(dbenv->verbose, DB_VERB_FILEOPS_ALL))
__db_msg(env, DB_STR_A("0132",
"fileops: read %s: %lu bytes", "%s %lu"),
fhp->name, (u_long)len);
if (DB_GLOBAL(j_read) != NULL) {
*nrp = len;
LAST_PANIC_CHECK_BEFORE_IO(env);
if (DB_GLOBAL(j_read)(fhp->fd, addr, len) != (ssize_t)len) {
ret = __os_get_syserr();
__db_syserr(env, ret, DB_STR_A("0133",
"read: %#lx, %lu", "%#lx %lu"),
P_TO_ULONG(addr), (u_long)len);
ret = __os_posix_err(ret);
}
return (ret);
}
for (taddr = addr, offset = 0;
offset < len; taddr += nr, offset += (u_int32_t)nr) {
LAST_PANIC_CHECK_BEFORE_IO(env);
RETRY_CHK(((nr = read(fhp->fd,
CHAR_STAR_CAST taddr, len - offset)) < 0 ? 1 : 0), ret);
if (nr == 0 || ret != 0)
break;
}
*nrp = (size_t)(taddr - (u_int8_t *)addr);
if (ret != 0) {
__db_syserr(env, ret, DB_STR_A("0134",
"read: %#lx, %lu", "%#lx %lu"),
P_TO_ULONG(taddr), (u_long)len - offset);
ret = __os_posix_err(ret);
}
return (ret);
}
/*
* __os_write --
* Write to a file handle.
*
* PUBLIC: int __os_write __P((ENV *, DB_FH *, void *, size_t, size_t *));
*/
int
__os_write(env, fhp, addr, len, nwp)
ENV *env;
DB_FH *fhp;
void *addr;
size_t len;
size_t *nwp;
{
DB_ASSERT(env, F_ISSET(fhp, DB_FH_OPENED) && fhp->fd != -1);
#ifdef HAVE_FILESYSTEM_NOTZERO
/* Zero-fill as necessary. */
if (__os_fs_notzero()) {
int ret;
if ((ret = __db_zero_fill(env, fhp)) != 0)
return (ret);
}
#endif
return (__os_physwrite(env, fhp, addr, len, nwp));
}
/*
* __os_physwrite --
* Physical write to a file handle.
*
* PUBLIC: int __os_physwrite
* PUBLIC: __P((ENV *, DB_FH *, void *, size_t, size_t *));
*/
int
__os_physwrite(env, fhp, addr, len, nwp)
ENV *env;
DB_FH *fhp;
void *addr;
size_t len;
size_t *nwp;
{
DB_ENV *dbenv;
size_t offset;
ssize_t nw;
int ret;
u_int8_t *taddr;
dbenv = env == NULL ? NULL : env->dbenv;
ret = 0;
#if defined(HAVE_STATISTICS)
++fhp->write_count;
#endif
if (dbenv != NULL && FLD_ISSET(dbenv->verbose, DB_VERB_FILEOPS_ALL))
__db_msg(env, DB_STR_A("0135",
"fileops: write %s: %lu bytes", "%s %lu"),
fhp->name, (u_long)len);
#if defined(HAVE_FILESYSTEM_NOTZERO) && defined(DIAGNOSTIC)
if (__os_fs_notzero()) {
struct stat sb;
off_t cur_off;
DB_ASSERT(env, fstat(fhp->fd, &sb) != -1 &&
(cur_off = lseek(fhp->fd, (off_t)0, SEEK_CUR)) != -1 &&
cur_off <= sb.st_size);
}
#endif
if (DB_GLOBAL(j_write) != NULL) {
*nwp = len;
LAST_PANIC_CHECK_BEFORE_IO(env);
if (DB_GLOBAL(j_write)(fhp->fd, addr, len) != (ssize_t)len) {
ret = __os_get_syserr();
__db_syserr(env, ret, DB_STR_A("0136",
"write: %#lx, %lu", "%#lx %lu"),
P_TO_ULONG(addr), (u_long)len);
ret = __os_posix_err(ret);
DB_EVENT(env, DB_EVENT_WRITE_FAILED, NULL);
}
return (ret);
}
for (taddr = addr, offset = 0;
offset < len; taddr += nw, offset += (u_int32_t)nw) {
LAST_PANIC_CHECK_BEFORE_IO(env);
RETRY_CHK(((nw = write(fhp->fd,
CHAR_STAR_CAST taddr, len - offset)) < 0 ? 1 : 0), ret);
if (ret != 0)
break;
}
*nwp = len;
if (ret != 0) {
__db_syserr(env, ret, DB_STR_A("0137",
"write: %#lx, %lu", "%#lx %lu"),
P_TO_ULONG(taddr), (u_long)len - offset);
ret = __os_posix_err(ret);
DB_EVENT(env, DB_EVENT_WRITE_FAILED, NULL);
}
return (ret);
}
|
0e986fd6f9e2b7082427e9f096d746dd5f5640a6
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/usr.bin/mandoc/chars.c
|
524a16ee79cf9948a4647cdcc0a8e5df452a651a
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 13,550
|
c
|
chars.c
|
/* $OpenBSD: chars.c,v 1.51 2022/06/26 20:30:00 schwarze Exp $ */
/*
* Copyright (c) 2009, 2010, 2011 Kristaps Dzonsons <kristaps@bsd.lv>
* Copyright (c) 2011, 2014, 2015, 2017, 2018, 2020
* Ingo Schwarze <schwarze@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <assert.h>
#include <ctype.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mandoc.h"
#include "mandoc_aux.h"
#include "mandoc_ohash.h"
#include "libmandoc.h"
struct ln {
const char roffcode[16];
const char *ascii;
int unicode;
};
/* Special break control characters. */
static const char ascii_nbrsp[2] = { ASCII_NBRSP, '\0' };
static const char ascii_break[2] = { ASCII_BREAK, '\0' };
static struct ln lines[] = {
/* Spacing. */
{ " ", ascii_nbrsp, 0x00a0 },
{ "~", ascii_nbrsp, 0x00a0 },
{ "0", ascii_nbrsp, 0x00a0 },
{ ":", ascii_break, 0 },
/* Lines. */
{ "ba", "|", 0x007c },
{ "br", "|", 0x2502 },
{ "ul", "_", 0x005f },
{ "_", "_", 0x005f },
{ "ru", "_", 0x005f },
{ "rn", "-", 0x203e },
{ "bb", "|", 0x00a6 },
{ "sl", "/", 0x002f },
{ "rs", "\\", 0x005c },
/* Text markers. */
{ "ci", "O", 0x25cb },
{ "bu", "+\bo", 0x2022 },
{ "dd", "<**>", 0x2021 },
{ "dg", "<*>", 0x2020 },
{ "lz", "<>", 0x25ca },
{ "sq", "[]", 0x25a1 },
{ "ps", "<paragraph>", 0x00b6 },
{ "sc", "<section>", 0x00a7 },
{ "lh", "<=", 0x261c },
{ "rh", "=>", 0x261e },
{ "at", "@", 0x0040 },
{ "sh", "#", 0x0023 },
{ "CR", "<cr>", 0x21b5 },
{ "OK", "\\/", 0x2713 },
{ "CL", "C", 0x2663 },
{ "SP", "S", 0x2660 },
{ "HE", "H", 0x2665 },
{ "DI", "D", 0x2666 },
/* Legal symbols. */
{ "co", "(C)", 0x00a9 },
{ "rg", "(R)", 0x00ae },
{ "tm", "tm", 0x2122 },
/* Punctuation. */
{ "em", "--", 0x2014 },
{ "en", "-", 0x2013 },
{ "hy", "-", 0x2010 },
{ "e", "\\", 0x005c },
{ "r!", "!", 0x00a1 },
{ "r?", "?", 0x00bf },
/* Quotes. */
{ "Bq", ",,", 0x201e },
{ "bq", ",", 0x201a },
{ "lq", "\"", 0x201c },
{ "rq", "\"", 0x201d },
{ "Lq", "\"", 0x201c },
{ "Rq", "\"", 0x201d },
{ "oq", "`", 0x2018 },
{ "cq", "\'", 0x2019 },
{ "aq", "\'", 0x0027 },
{ "dq", "\"", 0x0022 },
{ "Fo", "<<", 0x00ab },
{ "Fc", ">>", 0x00bb },
{ "fo", "<", 0x2039 },
{ "fc", ">", 0x203a },
/* Brackets. */
{ "lB", "[", 0x005b },
{ "rB", "]", 0x005d },
{ "lC", "{", 0x007b },
{ "rC", "}", 0x007d },
{ "la", "<", 0x27e8 },
{ "ra", ">", 0x27e9 },
{ "bv", "|", 0x23aa },
{ "braceex", "|", 0x23aa },
{ "bracketlefttp", "|", 0x23a1 },
{ "bracketleftbt", "|", 0x23a3 },
{ "bracketleftex", "|", 0x23a2 },
{ "bracketrighttp", "|", 0x23a4 },
{ "bracketrightbt", "|", 0x23a6 },
{ "bracketrightex", "|", 0x23a5 },
{ "lt", ",-", 0x23a7 },
{ "bracelefttp", ",-", 0x23a7 },
{ "lk", "{", 0x23a8 },
{ "braceleftmid", "{", 0x23a8 },
{ "lb", "`-", 0x23a9 },
{ "braceleftbt", "`-", 0x23a9 },
{ "braceleftex", "|", 0x23aa },
{ "rt", "-.", 0x23ab },
{ "bracerighttp", "-.", 0x23ab },
{ "rk", "}", 0x23ac },
{ "bracerightmid", "}", 0x23ac },
{ "rb", "-\'", 0x23ad },
{ "bracerightbt", "-\'", 0x23ad },
{ "bracerightex", "|", 0x23aa },
{ "parenlefttp", "/", 0x239b },
{ "parenleftbt", "\\", 0x239d },
{ "parenleftex", "|", 0x239c },
{ "parenrighttp", "\\", 0x239e },
{ "parenrightbt", "/", 0x23a0 },
{ "parenrightex", "|", 0x239f },
/* Arrows and lines. */
{ "<-", "<-", 0x2190 },
{ "->", "->", 0x2192 },
{ "<>", "<->", 0x2194 },
{ "da", "|\bv", 0x2193 },
{ "ua", "|\b^", 0x2191 },
{ "va", "^v", 0x2195 },
{ "lA", "<=", 0x21d0 },
{ "rA", "=>", 0x21d2 },
{ "hA", "<=>", 0x21d4 },
{ "uA", "=\b^", 0x21d1 },
{ "dA", "=\bv", 0x21d3 },
{ "vA", "^=v", 0x21d5 },
{ "an", "-", 0x23af },
/* Logic. */
{ "AN", "^", 0x2227 },
{ "OR", "v", 0x2228 },
{ "no", "~", 0x00ac },
{ "tno", "~", 0x00ac },
{ "te", "<there\037exists>", 0x2203 },
{ "fa", "<for\037all>", 0x2200 },
{ "st", "<such\037that>", 0x220b },
{ "tf", "<therefore>", 0x2234 },
{ "3d", "<therefore>", 0x2234 },
{ "or", "|", 0x007c },
/* Mathematicals. */
{ "pl", "+", 0x002b },
{ "mi", "-", 0x2212 },
{ "-", "-", 0x002d },
{ "-+", "-+", 0x2213 },
{ "+-", "+-", 0x00b1 },
{ "t+-", "+-", 0x00b1 },
{ "pc", ".", 0x00b7 },
{ "md", ".", 0x22c5 },
{ "mu", "x", 0x00d7 },
{ "tmu", "x", 0x00d7 },
{ "c*", "O\bx", 0x2297 },
{ "c+", "O\b+", 0x2295 },
{ "di", "/", 0x00f7 },
{ "tdi", "/", 0x00f7 },
{ "f/", "/", 0x2044 },
{ "**", "*", 0x2217 },
{ "<=", "<=", 0x2264 },
{ ">=", ">=", 0x2265 },
{ "<<", "<<", 0x226a },
{ ">>", ">>", 0x226b },
{ "eq", "=", 0x003d },
{ "!=", "!=", 0x2260 },
{ "==", "==", 0x2261 },
{ "ne", "!==", 0x2262 },
{ "ap", "~", 0x223c },
{ "|=", "-~", 0x2243 },
{ "=~", "=~", 0x2245 },
{ "~~", "~~", 0x2248 },
{ "~=", "~=", 0x2248 },
{ "pt", "<proportional\037to>", 0x221d },
{ "es", "{}", 0x2205 },
{ "mo", "<element\037of>", 0x2208 },
{ "nm", "<not\037element\037of>", 0x2209 },
{ "sb", "<proper\037subset>", 0x2282 },
{ "nb", "<not\037subset>", 0x2284 },
{ "sp", "<proper\037superset>", 0x2283 },
{ "nc", "<not\037superset>", 0x2285 },
{ "ib", "<subset\037or\037equal>", 0x2286 },
{ "ip", "<superset\037or\037equal>", 0x2287 },
{ "ca", "<intersection>", 0x2229 },
{ "cu", "<union>", 0x222a },
{ "/_", "<angle>", 0x2220 },
{ "pp", "<perpendicular>", 0x22a5 },
{ "is", "<integral>", 0x222b },
{ "integral", "<integral>", 0x222b },
{ "sum", "<sum>", 0x2211 },
{ "product", "<product>", 0x220f },
{ "coproduct", "<coproduct>", 0x2210 },
{ "gr", "<nabla>", 0x2207 },
{ "sr", "<sqrt>", 0x221a },
{ "sqrt", "<sqrt>", 0x221a },
{ "lc", "|~", 0x2308 },
{ "rc", "~|", 0x2309 },
{ "lf", "|_", 0x230a },
{ "rf", "_|", 0x230b },
{ "if", "<infinity>", 0x221e },
{ "Ah", "<Aleph>", 0x2135 },
{ "Im", "<Im>", 0x2111 },
{ "Re", "<Re>", 0x211c },
{ "wp", "p", 0x2118 },
{ "pd", "<del>", 0x2202 },
{ "-h", "/h", 0x210f },
{ "hbar", "/h", 0x210f },
{ "12", "1/2", 0x00bd },
{ "14", "1/4", 0x00bc },
{ "34", "3/4", 0x00be },
{ "18", "1/8", 0x215B },
{ "38", "3/8", 0x215C },
{ "58", "5/8", 0x215D },
{ "78", "7/8", 0x215E },
{ "S1", "^1", 0x00B9 },
{ "S2", "^2", 0x00B2 },
{ "S3", "^3", 0x00B3 },
/* Ligatures. */
{ "ff", "ff", 0xfb00 },
{ "fi", "fi", 0xfb01 },
{ "fl", "fl", 0xfb02 },
{ "Fi", "ffi", 0xfb03 },
{ "Fl", "ffl", 0xfb04 },
{ "AE", "AE", 0x00c6 },
{ "ae", "ae", 0x00e6 },
{ "OE", "OE", 0x0152 },
{ "oe", "oe", 0x0153 },
{ "ss", "ss", 0x00df },
{ "IJ", "IJ", 0x0132 },
{ "ij", "ij", 0x0133 },
/* Accents. */
{ "a\"", "\"", 0x02dd },
{ "a-", "-", 0x00af },
{ "a.", ".", 0x02d9 },
{ "a^", "^", 0x005e },
{ "aa", "\'", 0x00b4 },
{ "\'", "\'", 0x00b4 },
{ "ga", "`", 0x0060 },
{ "`", "`", 0x0060 },
{ "ab", "'\b`", 0x02d8 },
{ "ac", ",", 0x00b8 },
{ "ad", "\"", 0x00a8 },
{ "ah", "v", 0x02c7 },
{ "ao", "o", 0x02da },
{ "a~", "~", 0x007e },
{ "ho", ",", 0x02db },
{ "ha", "^", 0x005e },
{ "ti", "~", 0x007e },
{ "u02DC", "~", 0x02dc },
/* Accented letters. */
{ "'A", "'\bA", 0x00c1 },
{ "'E", "'\bE", 0x00c9 },
{ "'I", "'\bI", 0x00cd },
{ "'O", "'\bO", 0x00d3 },
{ "'U", "'\bU", 0x00da },
{ "'Y", "'\bY", 0x00dd },
{ "'a", "'\ba", 0x00e1 },
{ "'e", "'\be", 0x00e9 },
{ "'i", "'\bi", 0x00ed },
{ "'o", "'\bo", 0x00f3 },
{ "'u", "'\bu", 0x00fa },
{ "'y", "'\by", 0x00fd },
{ "`A", "`\bA", 0x00c0 },
{ "`E", "`\bE", 0x00c8 },
{ "`I", "`\bI", 0x00cc },
{ "`O", "`\bO", 0x00d2 },
{ "`U", "`\bU", 0x00d9 },
{ "`a", "`\ba", 0x00e0 },
{ "`e", "`\be", 0x00e8 },
{ "`i", "`\bi", 0x00ec },
{ "`o", "`\bo", 0x00f2 },
{ "`u", "`\bu", 0x00f9 },
{ "~A", "~\bA", 0x00c3 },
{ "~N", "~\bN", 0x00d1 },
{ "~O", "~\bO", 0x00d5 },
{ "~a", "~\ba", 0x00e3 },
{ "~n", "~\bn", 0x00f1 },
{ "~o", "~\bo", 0x00f5 },
{ ":A", "\"\bA", 0x00c4 },
{ ":E", "\"\bE", 0x00cb },
{ ":I", "\"\bI", 0x00cf },
{ ":O", "\"\bO", 0x00d6 },
{ ":U", "\"\bU", 0x00dc },
{ ":a", "\"\ba", 0x00e4 },
{ ":e", "\"\be", 0x00eb },
{ ":i", "\"\bi", 0x00ef },
{ ":o", "\"\bo", 0x00f6 },
{ ":u", "\"\bu", 0x00fc },
{ ":y", "\"\by", 0x00ff },
{ "^A", "^\bA", 0x00c2 },
{ "^E", "^\bE", 0x00ca },
{ "^I", "^\bI", 0x00ce },
{ "^O", "^\bO", 0x00d4 },
{ "^U", "^\bU", 0x00db },
{ "^a", "^\ba", 0x00e2 },
{ "^e", "^\be", 0x00ea },
{ "^i", "^\bi", 0x00ee },
{ "^o", "^\bo", 0x00f4 },
{ "^u", "^\bu", 0x00fb },
{ ",C", ",\bC", 0x00c7 },
{ ",c", ",\bc", 0x00e7 },
{ "/L", "/\bL", 0x0141 },
{ "/l", "/\bl", 0x0142 },
{ "/O", "/\bO", 0x00d8 },
{ "/o", "/\bo", 0x00f8 },
{ "oA", "o\bA", 0x00c5 },
{ "oa", "o\ba", 0x00e5 },
/* Special letters. */
{ "-D", "Dh", 0x00d0 },
{ "Sd", "dh", 0x00f0 },
{ "TP", "Th", 0x00de },
{ "Tp", "th", 0x00fe },
{ ".i", "i", 0x0131 },
{ ".j", "j", 0x0237 },
/* Currency. */
{ "Do", "$", 0x0024 },
{ "ct", "/\bc", 0x00a2 },
{ "Eu", "EUR", 0x20ac },
{ "eu", "EUR", 0x20ac },
{ "Ye", "=\bY", 0x00a5 },
{ "Po", "-\bL", 0x00a3 },
{ "Cs", "o\bx", 0x00a4 },
{ "Fn", ",\bf", 0x0192 },
/* Units. */
{ "de", "<degree>", 0x00b0 },
{ "%0", "<permille>", 0x2030 },
{ "fm", "\'", 0x2032 },
{ "sd", "\"", 0x2033 },
{ "mc", "<micro>", 0x00b5 },
{ "Of", "_\ba", 0x00aa },
{ "Om", "_\bo", 0x00ba },
/* Greek characters. */
{ "*A", "A", 0x0391 },
{ "*B", "B", 0x0392 },
{ "*G", "<Gamma>", 0x0393 },
{ "*D", "<Delta>", 0x0394 },
{ "*E", "E", 0x0395 },
{ "*Z", "Z", 0x0396 },
{ "*Y", "H", 0x0397 },
{ "*H", "<Theta>", 0x0398 },
{ "*I", "I", 0x0399 },
{ "*K", "K", 0x039a },
{ "*L", "<Lambda>", 0x039b },
{ "*M", "M", 0x039c },
{ "*N", "N", 0x039d },
{ "*C", "<Xi>", 0x039e },
{ "*O", "O", 0x039f },
{ "*P", "<Pi>", 0x03a0 },
{ "*R", "P", 0x03a1 },
{ "*S", "<Sigma>", 0x03a3 },
{ "*T", "T", 0x03a4 },
{ "*U", "Y", 0x03a5 },
{ "*F", "<Phi>", 0x03a6 },
{ "*X", "X", 0x03a7 },
{ "*Q", "<Psi>", 0x03a8 },
{ "*W", "<Omega>", 0x03a9 },
{ "*a", "<alpha>", 0x03b1 },
{ "*b", "<beta>", 0x03b2 },
{ "*g", "<gamma>", 0x03b3 },
{ "*d", "<delta>", 0x03b4 },
{ "*e", "<epsilon>", 0x03b5 },
{ "*z", "<zeta>", 0x03b6 },
{ "*y", "<eta>", 0x03b7 },
{ "*h", "<theta>", 0x03b8 },
{ "*i", "<iota>", 0x03b9 },
{ "*k", "<kappa>", 0x03ba },
{ "*l", "<lambda>", 0x03bb },
{ "*m", "<mu>", 0x03bc },
{ "*n", "<nu>", 0x03bd },
{ "*c", "<xi>", 0x03be },
{ "*o", "o", 0x03bf },
{ "*p", "<pi>", 0x03c0 },
{ "*r", "<rho>", 0x03c1 },
{ "*s", "<sigma>", 0x03c3 },
{ "*t", "<tau>", 0x03c4 },
{ "*u", "<upsilon>", 0x03c5 },
{ "*f", "<phi>", 0x03d5 },
{ "*x", "<chi>", 0x03c7 },
{ "*q", "<psi>", 0x03c8 },
{ "*w", "<omega>", 0x03c9 },
{ "+h", "<theta>", 0x03d1 },
{ "+f", "<phi>", 0x03c6 },
{ "+p", "<pi>", 0x03d6 },
{ "+e", "<epsilon>", 0x03f5 },
{ "ts", "<sigma>", 0x03c2 },
};
static struct ohash mchars;
void
mchars_free(void)
{
ohash_delete(&mchars);
}
void
mchars_alloc(void)
{
size_t i;
unsigned int slot;
mandoc_ohash_init(&mchars, 9, offsetof(struct ln, roffcode));
for (i = 0; i < sizeof(lines)/sizeof(lines[0]); i++) {
slot = ohash_qlookup(&mchars, lines[i].roffcode);
assert(ohash_find(&mchars, slot) == NULL);
ohash_insert(&mchars, slot, lines + i);
}
}
int
mchars_spec2cp(const char *p, size_t sz)
{
const struct ln *ln;
const char *end;
end = p + sz;
ln = ohash_find(&mchars, ohash_qlookupi(&mchars, p, &end));
return ln != NULL ? ln->unicode : -1;
}
int
mchars_num2char(const char *p, size_t sz)
{
int i;
i = mandoc_strntoi(p, sz, 10);
return i >= 0 && i < 256 ? i : -1;
}
int
mchars_num2uc(const char *p, size_t sz)
{
int i;
i = mandoc_strntoi(p, sz, 16);
assert(i >= 0 && i <= 0x10FFFF);
return i;
}
const char *
mchars_spec2str(const char *p, size_t sz, size_t *rsz)
{
const struct ln *ln;
const char *end;
end = p + sz;
ln = ohash_find(&mchars, ohash_qlookupi(&mchars, p, &end));
if (ln == NULL)
return NULL;
*rsz = strlen(ln->ascii);
return ln->ascii;
}
const char *
mchars_uc2str(int uc)
{
size_t i;
for (i = 0; i < sizeof(lines)/sizeof(lines[0]); i++)
if (uc == lines[i].unicode)
return lines[i].ascii;
return "<?>";
}
|
60ac27ecfeef95e608a2856e6e0982f016a10c84
|
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
|
/ni/src/lib/nfp/svdW.c
|
033eb3e6e121c288293d2790f14639799461a7d5
|
[
"Apache-2.0"
] |
permissive
|
NCAR/ncl
|
243c30eaefce642d53373aa583b73df72eb59f22
|
8a96101fe14d0cf0f5ed66a5e6b1733084bc69df
|
refs/heads/develop
| 2023-03-17T07:53:18.883458
| 2022-05-11T16:01:03
| 2022-05-11T16:01:03
| 67,087,395
| 254
| 68
|
NOASSERTION
| 2022-10-08T07:20:06
| 2016-09-01T01:34:28
|
C
|
UTF-8
|
C
| false
| false
| 61,317
|
c
|
svdW.c
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "wrapper.h"
extern void NGCALLF(dsvdlap,DSVDLAP)(double *,double *,int *,int *,int *,
int *,int *,int *,double *,int *,
double *,int *,double *, double *,
double *, double *, double *,double *,
double *, int *, int *);
extern void NGCALLF(dsvdsv,DSVDSV)(double *,double *, int *,int *,int *,
int *,int *,int *,double *, int *,
double *, double *,double *, double *,
double *,double *, double *,int *,
double *,int *,int *);
extern void NGCALLF(dsvdpar,DSVDPAR)(double *,int *,int*,int*,char*,int);
extern void NGCALLF(dgesvd,DGESVD)(char *, char *, int *, int *, double *,
int *, double *, double *, int *,
double *, int*, double *, int *, int *);
NhlErrorTypes svdcov_W( void )
{
/*
* Input array variables
*/
void *x, *y, *homlft, *hetlft, *homrgt, *hetrgt;
double *dx, *dy, *homlft_tmp, *hetlft_tmp, *homrgt_tmp, *hetrgt_tmp;
ng_size_t dsizes_x[2];
int has_missing_x;
ng_size_t dsizes_y[2];
int has_missing_y;
ng_size_t dsizes_homlft[2];
ng_size_t dsizes_hetlft[2];
ng_size_t dsizes_homrgt[2];
ng_size_t dsizes_hetrgt[2];
NclScalar missing_x, missing_y, missing_dx, missing_dy;
NclBasicDataTypes type_x, type_y;
NclBasicDataTypes type_homlft, type_hetlft, type_homrgt, type_hetrgt;
ng_size_t ntimes, ncolx, ncoly, lab;
int *nsvd;
int ier = 0, iflag=0, iprint=0;
/*
* Work array variables
*/
double *w;
ng_size_t lwk, nsvmx;
/*
* Output array variables
*/
double *svdpcv_tmp, *ak_tmp, *bk_tmp;
void *svdpcv, *fnorm, *condn, *ak, *bk;
int *lapack_err;
ng_size_t dsizes_svdpcv[1];
NclBasicDataTypes type_svdpcv;
NclTypeClass type_svdpcv_class;
/*
* Attribute variables
*/
int att_id;
ng_size_t dsizes[1];
NclMultiDValData att_md, return_md;
NclVar tmp_var;
NclStackEntry return_data;
/*
* various
*/
ng_size_t ipt7;
ng_size_t total_size_x, total_size_y, total_size_lft, total_size_rgt;
/*
* Retrieve input parameters.
*/
x = (void*)NclGetArgValue(
0,
7,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
&type_x,
DONT_CARE);
y = (void*)NclGetArgValue(
1,
7,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
&type_y,
DONT_CARE);
nsvd = (int *)NclGetArgValue(
2,
7,
NULL,
NULL,
NULL,
NULL,
NULL,
DONT_CARE);
homlft = (void*)NclGetArgValue(
3,
7,
NULL,
dsizes_homlft,
NULL,
NULL,
&type_homlft,
DONT_CARE);
hetlft = (void*)NclGetArgValue(
4,
7,
NULL,
dsizes_hetlft,
NULL,
NULL,
&type_hetlft,
DONT_CARE);
homrgt = (void*)NclGetArgValue(
5,
7,
NULL,
dsizes_homrgt,
NULL,
NULL,
&type_homrgt,
DONT_CARE);
hetrgt = (void*)NclGetArgValue(
6,
7,
NULL,
dsizes_hetrgt,
NULL,
NULL,
&type_hetrgt,
DONT_CARE);
/*
* The last dimension of x and y must be the same.
*/
if( dsizes_x[1] != dsizes_y[1] ) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: The rightmost dimension of both input arrays must be the same size");
return(NhlFATAL);
}
ncolx = dsizes_x[0];
ncoly = dsizes_y[0];
ntimes = dsizes_x[1];
lab = ntimes * *nsvd;
nsvmx = min(ncolx,ncoly);
/*
* Check nsvd, the number of SVD patterns to be calculated.
*/
if (*nsvd > nsvmx) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: nsvx exceeds maximum possible patterns");
return(NhlFATAL);
}
/*
* Check dimension sizes. The leftmost dimension must be nsvd. The second
* dimension must be the same as the leftmost dimension of x (or y if
* it's the rgt arrays).
*/
if( dsizes_homlft[0] != *nsvd || dsizes_hetlft[0] != *nsvd ||
dsizes_homlft[1] != ncolx || dsizes_hetlft[1] != ncolx ) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: The rightmost dimension of the homlft/hetlft arrays must be the same as the leftmost dimension of x, and the leftmost dimension must be nsvx");
return(NhlFATAL);
}
if( dsizes_homrgt[0] != *nsvd || dsizes_hetrgt[0] != *nsvd ||
dsizes_homrgt[1] != ncoly || dsizes_hetrgt[1] != ncoly ) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: The rightmost dimension of the homrgt/hetrgt arrays must be the same as the leftmost dimension of y, and the leftmost dimension must be nsvx");
return(NhlFATAL);
}
/*
* The hom/het arrays must be float or double. It doesn't matter what
* the input types are.
*/
if((type_hetlft != NCL_float && type_hetlft != NCL_double) ||
(type_homlft != NCL_float && type_homlft != NCL_double) ||
(type_homrgt != NCL_float && type_homrgt != NCL_double) ||
(type_hetrgt != NCL_float && type_hetrgt != NCL_double)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: The hetlft/homlft/hetrgt/homrgt arrays must be of type float or double");
return(NhlFATAL);
}
/*
* Calculate total sizes of input arrays.
*/
total_size_x = ncolx * ntimes;
total_size_y = ncoly * ntimes;
total_size_lft = *nsvd * ncolx;
total_size_rgt = *nsvd * ncoly;
/*
* Coerce missing values, if any.
*/
coerce_missing(type_x,has_missing_x,&missing_x,&missing_dx,NULL);
coerce_missing(type_y,has_missing_y,&missing_y,&missing_dy,NULL);
/*
* Coerce x and y to double if necessary.
*/
dx = coerce_input_double(x,type_x,total_size_x,has_missing_x,&missing_x,
&missing_dx);
dy = coerce_input_double(y,type_y,total_size_y,has_missing_y,&missing_y,
&missing_dy);
if(dx == NULL || dy == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: Unable to allocate memory for coercing input arrays to double precision");
return(NhlFATAL);
}
/*
* Allocate space for double precision hom/het. There's no need to do a
* coercion because hom/het is an output-only variable (i.e, there are no
* values coming in). hom/het can only be float or double, so only
* allocate space for a d.p. array if hom/het is float.
*/
homlft_tmp = coerce_output_double(homlft,type_homlft,total_size_lft);
hetlft_tmp = coerce_output_double(hetlft,type_hetlft,total_size_lft);
homrgt_tmp = coerce_output_double(homrgt,type_homrgt,total_size_rgt);
hetrgt_tmp = coerce_output_double(hetrgt,type_hetrgt,total_size_rgt);
if(homlft_tmp == NULL || hetlft_tmp == NULL ||
homrgt_tmp == NULL || hetrgt_tmp == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: Unable to allocate memory for coercing output arrays to double precision");
return(NhlFATAL);
}
/*
* Determine type of output values and allocate space for them.
*/
dsizes_svdpcv[0] = *nsvd;
if(type_x != NCL_double && type_y != NCL_double) {
type_svdpcv = NCL_float;
svdpcv = (void *)calloc(*nsvd,sizeof(float));
ak = (void *)calloc(lab,sizeof(float));
bk = (void *)calloc(lab,sizeof(float));
svdpcv_tmp = (double *)calloc(*nsvd,sizeof(double));
ak_tmp = (double *)calloc(lab,sizeof(double));
bk_tmp = (double *)calloc(lab,sizeof(double));
if( svdpcv == NULL || svdpcv_tmp == NULL || ak == NULL || bk == NULL ||
ak_tmp == NULL || bk_tmp == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: Unable to allocate memory for output values");
return(NhlFATAL);
}
}
else {
type_svdpcv = NCL_double;
svdpcv = (void *)calloc(*nsvd,sizeof(double));
ak = (void *)calloc(lab,sizeof(double));
bk = (void *)calloc(lab,sizeof(double));
if( svdpcv == NULL || ak == NULL || bk == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: Unable to allocate memory for output values");
return(NhlFATAL);
}
svdpcv_tmp = (double *)svdpcv;
ak_tmp = (double *)ak;
bk_tmp = (double *)bk;
}
/*
* Allocate memory for work array. Note that this work array is actually
* serving as a work array, plus memory for 6 other arrays in the
* Fortran routine (CRV, U, VT, SV, AK, BK).
*
* Originally we had "5*min(ncolx,ncoly)-4", but the SGI version of
* the DGESVD routine recommends "5*min(ncolx,ncoly)", so we decided
* to take the bigger of the two, and go with "5*min(ncolx,ncoly)".
*/
lwk = ncolx*ncoly + nsvmx*ncolx + nsvmx*ncoly +
ntimes*ncolx + ntimes*ncoly + nsvmx +
max(3*nsvmx + max(ncolx,ncoly), 5*nsvmx);
w = (double *)calloc(lwk,sizeof(double));
if( w == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: Unable to allocate memory for work array");
return(NhlFATAL);
}
/*
* Call the Fortran version of 'svdlap' with the full argument list.
*/
if((ntimes <= INT_MAX) &&
(ncolx <= INT_MAX) &&
(ncoly <= INT_MAX) &&
(lab <= INT_MAX) &&
(lwk <= INT_MAX))
{
int intimes = (int) ntimes;
int incolx = (int) ncolx;
int incoly = (int) ncoly;
int ilab = (int) lab;
int ilwk = (int) lwk;
NGCALLF(dsvdlap,DSVDLAP)(dx,dy,&intimes,&intimes,&incolx,&incoly,nsvd,&iflag,
&missing_dx.doubleval,&iprint,w,&ilwk,svdpcv_tmp,
homlft_tmp,homrgt_tmp,hetlft_tmp,hetrgt_tmp,
ak_tmp,bk_tmp,&ilab,&ier);
}
else
{
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov: one or more dimension sizes is greater than INT_MAX");
return(NhlFATAL);
}
if (ier) {
NhlPError(NhlWARNING,NhlEUNKNOWN,"svdcov: ier = %d\n", ier );
}
/*
* Free unneeded memory.
*/
if((void*)dx != x) NclFree(dx);
if((void*)dy != y) NclFree(dy);
/*
* If hom/het were originally float, then we need to coerce them from
* double to float.
*/
if(type_homlft == NCL_float) {
coerce_output_float_only(homlft,homlft_tmp,total_size_lft,0);
NclFree(homlft_tmp);
}
if(type_hetlft == NCL_float) {
coerce_output_float_only(hetlft,hetlft_tmp,total_size_lft,0);
NclFree(hetlft_tmp);
}
if(type_homrgt == NCL_float) {
coerce_output_float_only(homrgt,homrgt_tmp,total_size_rgt,0);
NclFree(homrgt_tmp);
}
if(type_hetrgt == NCL_float) {
coerce_output_float_only(hetrgt,hetrgt_tmp,total_size_rgt,0);
NclFree(hetrgt_tmp);
}
/*
* Assign values for various attributes.
*/
ipt7 = ncolx*ncoly + *nsvd*(ncolx+ncoly) + ntimes*(ncolx+ncoly) + *nsvd;
if(type_svdpcv == NCL_float) {
fnorm = (void *)calloc(1,sizeof(float));
condn = (void *)calloc(1,sizeof(float));
coerce_output_float_only(svdpcv,svdpcv_tmp,*nsvd,0);
coerce_output_float_only(ak,ak_tmp,lab,0);
coerce_output_float_only(bk,bk_tmp,lab,0);
NclFree(svdpcv_tmp);
NclFree(ak_tmp);
NclFree(bk_tmp);
}
else {
fnorm = (void *)calloc(1,sizeof(double));
condn = (void *)calloc(1,sizeof(double));
}
coerce_output_float_or_double(fnorm,&w[ipt7],type_svdpcv,1,0);
coerce_output_float_or_double(condn,&w[ipt7+1],type_svdpcv,1,0);
lapack_err = (int *)calloc(1,sizeof(int));
*lapack_err = (int)w[ipt7+3];
/*
* Set up variable to return.
*/
type_svdpcv_class = (NclTypeClass)_NclNameToTypeClass(NrmStringToQuark(_NclBasicDataTypeToName(type_svdpcv)));
return_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
svdpcv,
NULL,
1,
dsizes_svdpcv,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
/*
* Set up attributes to return.
*/
att_id = _NclAttCreate(NULL,NULL,Ncl_Att,0,NULL);
/*
* Create individual attributes.
*/
dsizes[0] = 1;
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
fnorm,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
_NclAddAtt(
att_id,
"fnorm",
att_md,
NULL
);
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
condn,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
_NclAddAtt(
att_id,
"condn",
att_md,
NULL
);
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
(void*)lapack_err,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)nclTypeintClass
);
_NclAddAtt(
att_id,
"lapack_err",
att_md,
NULL
);
dsizes[0] = lab;
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
ak,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
_NclAddAtt(
att_id,
"ak",
att_md,
NULL
);
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
bk,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
_NclAddAtt(
att_id,
"bk",
att_md,
NULL
);
NclFree(w);
tmp_var = _NclVarCreate(
NULL,
NULL,
Ncl_Var,
0,
NULL,
return_md,
NULL,
att_id,
NULL,
RETURNVAR,
NULL,
TEMPORARY
);
/*
* Return output grid and attributes to NCL.
*/
return_data.kind = NclStk_VAR;
return_data.u.data_var = tmp_var;
_NclPlaceReturn(return_data);
return(NhlNOERROR);
}
NhlErrorTypes svdstd_W( void )
{
/*
* Input array variables
*/
void *x, *y, *homlft, *hetlft, *homrgt, *hetrgt;
double *dx, *dy, *homlft_tmp, *hetlft_tmp, *homrgt_tmp, *hetrgt_tmp;
ng_size_t dsizes_x[2];
int has_missing_x;
ng_size_t dsizes_y[2];
int has_missing_y;
ng_size_t dsizes_homlft[2];
ng_size_t dsizes_hetlft[2];
ng_size_t dsizes_homrgt[2];
ng_size_t dsizes_hetrgt[2];
NclScalar missing_x, missing_y, missing_dx, missing_dy;
NclBasicDataTypes type_x, type_y;
NclBasicDataTypes type_homlft, type_hetlft, type_homrgt, type_hetrgt;
ng_size_t ntimes, ncolx, ncoly, lab;
int *nsvd;
int ier = 0, iflag=1, iprint=0;
/*
* Work array variables
*/
double *w;
ng_size_t lwk, nsvmx;
/*
* Output array variables
*/
double *svdpcv_tmp, *ak_tmp, *bk_tmp;
void *svdpcv, *fnorm, *condn, *ak, *bk;
int *lapack_err;
ng_size_t dsizes_svdpcv[1];
NclBasicDataTypes type_svdpcv;
NclTypeClass type_svdpcv_class;
/*
* Attribute variables
*/
int att_id;
ng_size_t dsizes[1];
NclMultiDValData att_md, return_md;
NclVar tmp_var;
NclStackEntry return_data;
/*
* various
*/
ng_size_t ipt7;
ng_size_t total_size_x, total_size_y, total_size_lft, total_size_rgt;
/*
* Retrieve input parameters.
*/
x = (void*)NclGetArgValue(
0,
7,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
&type_x,
DONT_CARE);
y = (void*)NclGetArgValue(
1,
7,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
&type_y,
DONT_CARE);
nsvd = (int *)NclGetArgValue(
2,
7,
NULL,
NULL,
NULL,
NULL,
NULL,
DONT_CARE);
homlft = (void*)NclGetArgValue(
3,
7,
NULL,
dsizes_homlft,
NULL,
NULL,
&type_homlft,
DONT_CARE);
hetlft = (void*)NclGetArgValue(
4,
7,
NULL,
dsizes_hetlft,
NULL,
NULL,
&type_hetlft,
DONT_CARE);
homrgt = (void*)NclGetArgValue(
5,
7,
NULL,
dsizes_homrgt,
NULL,
NULL,
&type_homrgt,
DONT_CARE);
hetrgt = (void*)NclGetArgValue(
6,
7,
NULL,
dsizes_hetrgt,
NULL,
NULL,
&type_hetrgt,
DONT_CARE);
/*
* The last dimension of x and y must be the same.
*/
if( dsizes_x[1] != dsizes_y[1] ) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: The rightmost dimension of both input arrays must be the same size");
return(NhlFATAL);
}
ncolx = dsizes_x[0];
ncoly = dsizes_y[0];
ntimes = dsizes_x[1];
lab = ntimes * *nsvd;
nsvmx = min(ncolx,ncoly);
/*
* Check nsvd, the number of SVD patterns to be calculated.
*/
if (*nsvd > nsvmx) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: nsvx exceeds maximum possible patterns");
return(NhlFATAL);
}
/*
* Check dimension sizes. The leftmost dimension must be nsvd. The second
* dimension must be the same as the leftmost dimension of x (or y if
* it's the rgt arrays).
*/
if( dsizes_homlft[0] != *nsvd || dsizes_hetlft[0] != *nsvd ||
dsizes_homlft[1] != ncolx || dsizes_hetlft[1] != ncolx ) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: The rightmost dimension of the homlft/hetlft arrays must be the same as the leftmost dimension of x, and the leftmost dimension must be nsvx");
return(NhlFATAL);
}
if( dsizes_homrgt[0] != *nsvd || dsizes_hetrgt[0] != *nsvd ||
dsizes_homrgt[1] != ncoly || dsizes_hetrgt[1] != ncoly ) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: The rightmost dimension of the homrgt/hetrgt arrays must be the same as the leftmost dimension of y, and the leftmost dimension must be nsvx");
return(NhlFATAL);
}
/*
* The hom/het arrays must be float or double. It doesn't matter what
* the input types are.
*/
if((type_hetlft != NCL_float && type_hetlft != NCL_double) ||
(type_homlft != NCL_float && type_homlft != NCL_double) ||
(type_homrgt != NCL_float && type_homrgt != NCL_double) ||
(type_hetrgt != NCL_float && type_hetrgt != NCL_double)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: The hetlft/homlft/hetrgt/homrgt arrays must be of type float or double");
return(NhlFATAL);
}
/*
* Calculate total sizes of input arrays.
*/
total_size_x = ncolx * ntimes;
total_size_y = ncoly * ntimes;
total_size_lft = *nsvd * ncolx;
total_size_rgt = *nsvd * ncoly;
/*
* Coerce missing values, if any.
*/
coerce_missing(type_x,has_missing_x,&missing_x,&missing_dx,NULL);
coerce_missing(type_y,has_missing_y,&missing_y,&missing_dy,NULL);
/*
* Coerce x and y to double if necessary.
*/
dx = coerce_input_double(x,type_x,total_size_x,has_missing_x,&missing_x,
&missing_dx);
dy = coerce_input_double(y,type_y,total_size_y,has_missing_y,&missing_y,
&missing_dy);
if(dx == NULL || dy == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: Unable to allocate memory for coercing input arrays to double precision");
return(NhlFATAL);
}
/*
* Allocate space for double precision hom/het. There's no need to do a
* coercion because hom/het is an output-only variable (i.e, there are no
* values coming in). hom/het can only be float or double, so only
* allocate space for a d.p. array if hom/het is float.
*/
homlft_tmp = coerce_output_double(homlft,type_homlft,total_size_lft);
hetlft_tmp = coerce_output_double(hetlft,type_hetlft,total_size_lft);
homrgt_tmp = coerce_output_double(homrgt,type_homrgt,total_size_rgt);
hetrgt_tmp = coerce_output_double(hetrgt,type_hetrgt,total_size_rgt);
if(homlft_tmp == NULL || hetlft_tmp == NULL ||
homrgt_tmp == NULL || hetrgt_tmp == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: Unable to allocate memory for coercing output arrays to double precision");
return(NhlFATAL);
}
/*
* Determine type of output values and allocate space for them.
*/
dsizes_svdpcv[0] = *nsvd;
if(type_x != NCL_double && type_y != NCL_double) {
type_svdpcv = NCL_float;
svdpcv = (void *)calloc(*nsvd,sizeof(float));
svdpcv_tmp = (double *)calloc(*nsvd,sizeof(double));
ak_tmp = (double *)calloc(lab,sizeof(double));
bk_tmp = (double *)calloc(lab,sizeof(double));
ak = (void *)calloc(lab,sizeof(float));
bk = (void *)calloc(lab,sizeof(float));
if( svdpcv == NULL || svdpcv_tmp == NULL || ak == NULL || bk == NULL ||
ak_tmp == NULL || bk_tmp == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: Unable to allocate memory for output values");
return(NhlFATAL);
}
}
else {
type_svdpcv = NCL_double;
svdpcv = (void *)calloc(*nsvd,sizeof(double));
ak = (void *)calloc(lab,sizeof(double));
bk = (void *)calloc(lab,sizeof(double));
svdpcv_tmp = (double*)svdpcv;
ak_tmp = (double *)ak;
bk_tmp = (double *)bk;
if( svdpcv == NULL || ak == NULL || bk == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: Unable to allocate memory for output values");
return(NhlFATAL);
}
}
/*
* Allocate memory for work array. Note that this work array is actually
* serving as a work array, plus memory for 6 other arrays in the
* Fortran routine (CRV, U, VT, SV, AK, BK).
*
* Originally we had "5*min(ncolx,ncoly)-4", but the SGI version of
* the DGESVD routine recommends "5*min(ncolx,ncoly)", so we decided
* to take the bigger of the two, and go with "5*min(ncolx,ncoly)".
*/
lwk = ncolx*ncoly + nsvmx*ncolx + nsvmx*ncoly +
ntimes*ncolx + ntimes*ncoly + nsvmx +
max(3*nsvmx + max(ncolx,ncoly), 5*nsvmx);
w = (double *)calloc(lwk,sizeof(double));
if( w == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: Unable to allocate memory for work array");
return(NhlFATAL);
}
/*
* Call the Fortran version of 'svdlap' with the full argument list.
*/
if((ntimes <= INT_MAX) &&
(ncolx <= INT_MAX) &&
(ncoly <= INT_MAX) &&
(lab <= INT_MAX) &&
(lwk <= INT_MAX))
{
int intimes = (int) ntimes;
int incolx = (int) ncolx;
int incoly = (int) ncoly;
int ilab = (int) lab;
int ilwk = (int) lwk;
NGCALLF(dsvdlap,DSVDLAP)(dx,dy,&intimes,&intimes,&incolx,&incoly,nsvd,&iflag,
&missing_dx.doubleval,&iprint,w,&ilwk,svdpcv_tmp,
homlft_tmp,homrgt_tmp,hetlft_tmp,hetrgt_tmp,
ak_tmp,bk_tmp,&ilab,&ier);
}
else
{
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd: one or more input dimension sizes is greater than INT_MAX");
return(NhlFATAL);
}
if (ier) {
NhlPError(NhlWARNING,NhlEUNKNOWN,"svdstd: ier = %d\n", ier );
}
/*
* Free unneeded memory.
*/
if((void*)dx != x) NclFree(dx);
if((void*)dy != y) NclFree(dy);
/*
* If hom/het were originally float, then we need to coerce them from
* double to float.
*/
if(type_homlft == NCL_float) {
coerce_output_float_only(homlft,homlft_tmp,total_size_lft,0);
NclFree(homlft_tmp);
}
if(type_hetlft == NCL_float) {
coerce_output_float_only(hetlft,hetlft_tmp,total_size_lft,0);
NclFree(hetlft_tmp);
}
if(type_homrgt == NCL_float) {
coerce_output_float_only(homrgt,homrgt_tmp,total_size_rgt,0);
NclFree(homrgt_tmp);
}
if(type_hetrgt == NCL_float) {
coerce_output_float_only(hetrgt,hetrgt_tmp,total_size_rgt,0);
NclFree(hetrgt_tmp);
}
/*
* Assign values for various attributes.
*/
ipt7 = ncolx*ncoly + *nsvd*(ncolx+ncoly) + ntimes*(ncolx+ncoly) + *nsvd;
if(type_svdpcv == NCL_float) {
fnorm = (void *)calloc(1,sizeof(float));
condn = (void *)calloc(1,sizeof(float));
coerce_output_float_only(svdpcv,svdpcv_tmp,*nsvd,0);
coerce_output_float_only(ak,ak_tmp,lab,0);
coerce_output_float_only(bk,bk_tmp,lab,0);
NclFree(svdpcv_tmp);
NclFree(ak_tmp);
NclFree(bk_tmp);
}
else {
fnorm = (void *)calloc(1,sizeof(double));
condn = (void *)calloc(1,sizeof(double));
}
coerce_output_float_or_double(fnorm,&w[ipt7],type_svdpcv,1,0);
coerce_output_float_or_double(condn,&w[ipt7+1],type_svdpcv,1,0);
lapack_err = (int *)calloc(1,sizeof(int));
*lapack_err = (int)w[ipt7+3];
/*
* Set up variable to return.
*/
type_svdpcv_class = (NclTypeClass)_NclNameToTypeClass(NrmStringToQuark(_NclBasicDataTypeToName(type_svdpcv)));
return_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
svdpcv,
NULL,
1,
dsizes_svdpcv,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
/*
* Set up attributes to return.
*/
att_id = _NclAttCreate(NULL,NULL,Ncl_Att,0,NULL);
/*
* Create individual attributes.
*/
dsizes[0] = 1;
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
fnorm,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
_NclAddAtt(
att_id,
"fnorm",
att_md,
NULL
);
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
condn,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
_NclAddAtt(
att_id,
"condn",
att_md,
NULL
);
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
(void*)lapack_err,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)nclTypeintClass
);
_NclAddAtt(
att_id,
"lapack_err",
att_md,
NULL
);
dsizes[0] = lab;
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
ak,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
_NclAddAtt(
att_id,
"ak",
att_md,
NULL
);
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
bk,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
_NclAddAtt(
att_id,
"bk",
att_md,
NULL
);
NclFree(w);
tmp_var = _NclVarCreate(
NULL,
NULL,
Ncl_Var,
0,
NULL,
return_md,
NULL,
att_id,
NULL,
RETURNVAR,
NULL,
TEMPORARY
);
/*
* Return output grid and attributes to NCL.
*/
return_data.kind = NclStk_VAR;
return_data.u.data_var = tmp_var;
_NclPlaceReturn(return_data);
return(NhlNOERROR);
}
NhlErrorTypes svdcov_sv_W( void )
{
/*
* Input array variables
*/
void *x, *y, *svlft, *svrgt;
double *dx, *dy, *svlft_tmp, *svrgt_tmp;
ng_size_t dsizes_x[2];
int has_missing_x;
ng_size_t dsizes_y[2];
int has_missing_y;
ng_size_t dsizes_svlft[2];
ng_size_t dsizes_svrgt[2];
NclScalar missing_x, missing_y, missing_dx, missing_dy;
NclBasicDataTypes type_x, type_y, type_svlft, type_svrgt;
ng_size_t ntimes, ncolx, ncoly;
int *nsvd;
int ier = 0, iflag=0, iprint=0;
/*
* Work array variables
*/
double *w, *crv, *u, *vt;
ng_size_t lwork, nsvmx;
/*
* Output array variables
*/
double *svdpcv_tmp, *sv_tmp;
void *svdpcv, *sv;
ng_size_t dsizes_svdpcv[1];
NclBasicDataTypes type_svdpcv;
NclTypeClass type_svdpcv_class;
/*
* Attribute variables
*/
int att_id;
ng_size_t dsizes[1];
NclMultiDValData att_md, return_md;
NclVar tmp_var;
NclStackEntry return_data;
/*
* Various
*/
ng_size_t total_size_x, total_size_y, total_size_svrgt, total_size_svlft;
/*
* Retrieve input parameters.
*/
x = (void*)NclGetArgValue(
0,
5,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
&type_x,
DONT_CARE);
y = (void*)NclGetArgValue(
1,
5,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
&type_y,
DONT_CARE);
nsvd = (int *)NclGetArgValue(
2,
5,
NULL,
NULL,
NULL,
NULL,
NULL,
DONT_CARE);
svlft = (void*)NclGetArgValue(
3,
5,
NULL,
dsizes_svlft,
NULL,
NULL,
&type_svlft,
DONT_CARE);
svrgt = (void*)NclGetArgValue(
4,
5,
NULL,
dsizes_svrgt,
NULL,
NULL,
&type_svrgt,
DONT_CARE);
/*
* The rightmost dimensions must be the same.
*/
if( dsizes_x[1] != dsizes_y[1] ) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: The rightmost dimension of both input arrays must be the same size");
return(NhlFATAL);
}
ncolx = dsizes_x[0];
ncoly = dsizes_y[0];
ntimes = dsizes_x[1];
/*
* Check dimension sizes. The leftmost dimension must be nsvd. The
* second dimension must be the same as the leftmost dimension of
* x (or y if it's the rgt arrays).
*/
if( dsizes_svlft[0] != *nsvd || dsizes_svlft[1] != dsizes_x[0]) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: The rightmost dimension of the left array must be the same as the leftmost dimension of x, and the leftmost dimension must be nsvx");
return(NhlFATAL);
}
if( dsizes_svrgt[0] != *nsvd ||
dsizes_svrgt[1] != dsizes_y[0]) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: The rightmost dimension of the right array must be the same as the leftmost dimension of y, and the leftmost dimension must be nsvx");
return(NhlFATAL);
}
/*
* Check nsvd, the number of SVD patterns to be calculated.
*/
if (*nsvd > min(ncolx,ncoly)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: nsvx exceeds maximum possible patterns");
return(NhlFATAL);
}
/*
* Calculate total sizes of input arrays.
*/
total_size_x = ntimes * ncolx;
total_size_y = ntimes * ncoly;
total_size_svlft = *nsvd * ncolx;
total_size_svrgt = *nsvd * ncoly;
/*
* Coerce missing values, if any.
*/
coerce_missing(type_x,has_missing_x,&missing_x,&missing_dx,NULL);
coerce_missing(type_y,has_missing_y,&missing_y,&missing_dy,NULL);
/*
* Coerce x and y to double if necessary.
*/
dx = coerce_input_double(x,type_x,total_size_x,has_missing_x,&missing_x,
&missing_dx);
dy = coerce_input_double(y,type_y,total_size_y,has_missing_y,&missing_y,
&missing_dy);
if(dx == NULL || dy == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: Unable to allocate memory for coercing input arrays to double precision");
return(NhlFATAL);
}
/*
* svlft and svrgt must be float or double. It doesn't matter what the input
* types are.
*/
if((type_svlft != NCL_float && type_svlft != NCL_double) ||
(type_svrgt != NCL_float && type_svrgt != NCL_double)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: svLeft/svRight must be of type float or double");
return(NhlFATAL);
}
/*
* Allocate space for double precision svrgt/lft. There's no need to do a
* coercion because svrgt/lft is an output-only variable (i.e, there are no
* values coming in). svrgt/lft can only be float or double, so only
* allocate space for a d.p. array if svrgt/lft is float.
*/
svlft_tmp = coerce_output_double(svlft,type_svlft,total_size_svlft);
svrgt_tmp = coerce_output_double(svrgt,type_svrgt,total_size_svrgt);
if(svlft_tmp == NULL || svrgt_tmp == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: Unable to allocate memory for coercing output arrays to double precision");
return(NhlFATAL);
}
/*
* Determine type of output values and allocate space for them.
*/
dsizes_svdpcv[0] = *nsvd;
nsvmx = min(ncolx,ncoly);
if(type_x != NCL_double && type_y != NCL_double) {
type_svdpcv = NCL_float;
svdpcv = (void *)calloc(*nsvd,sizeof(float));
svdpcv_tmp = (double *)calloc(*nsvd,sizeof(double));
sv = (void *)calloc(nsvmx,sizeof(float));
sv_tmp = (double *)calloc(nsvmx,sizeof(double));
if(svdpcv == NULL || svdpcv_tmp == NULL || sv == NULL || sv_tmp == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: Unable to allocate memory for output arrays");
return(NhlFATAL);
}
}
else {
type_svdpcv = NCL_double;
svdpcv = (void *)calloc(*nsvd,sizeof(double));
sv = (void *)calloc(nsvmx,sizeof(double));
svdpcv_tmp = (double*)svdpcv;
sv_tmp = (double*)sv;
if(svdpcv == NULL || sv == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: Unable to allocate memory for output arrays");
return(NhlFATAL);
}
}
/*
* Allocate memory for work and output arrays.
*/
lwork = max(3*nsvmx+max(ncolx,ncoly),5*nsvmx);
w = (double *)calloc(lwork,sizeof(double));
u = (double *)calloc(nsvmx*ncolx,sizeof(double));
vt = (double *)calloc(nsvmx*ncoly,sizeof(double));
crv = (double *)calloc(ncolx*ncoly,sizeof(double));
if( w == NULL || crv == NULL || u == NULL || vt == NULL || sv == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: Unable to allocate memory for work arrays");
return(NhlFATAL);
}
/*
* Call the Fortran version of 'svdlap' with the full argument list.
*/
if((ntimes <= INT_MAX) &&
(ncolx <= INT_MAX) &&
(ncoly <= INT_MAX) &&
(nsvmx <= INT_MAX) &&
(lwork <= INT_MAX))
{
int intimes = (int) ntimes;
int incolx = (int) ncolx;
int incoly = (int) ncoly;
int insvmx = (int) nsvmx;
int ilwork = (int) lwork;
NGCALLF(dsvdsv,DSVDSV)(dx,dy,&intimes,&intimes,&incolx,&incoly,nsvd,&iflag,
&missing_dx.doubleval,&iprint,svlft_tmp,svrgt_tmp,
svdpcv_tmp,crv,u,vt,sv_tmp,&insvmx,w,&ilwork,&ier);
}
else
{
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdcov_sv: one or more input dimension sizes is greater than INT_MAX");
return(NhlFATAL);
}
/*
* Free memory.
*/
NclFree(w);
NclFree(crv);
NclFree(u);
NclFree(vt);
if((void*)dx != x) NclFree(dx);
if((void*)dy != y) NclFree(dy);
/*
* If svlft/rgt were originally float, then we need to coerce them from
* double to float.
*/
if(type_svrgt == NCL_float) {
coerce_output_float_only(svrgt,svrgt_tmp,total_size_svrgt,0);
NclFree(svrgt_tmp);
}
if(type_svlft == NCL_float) {
coerce_output_float_only(svlft,svlft_tmp,total_size_svlft,0);
NclFree(svlft_tmp);
}
if(type_svdpcv != NCL_double) {
coerce_output_float_only(svdpcv,svdpcv_tmp,*nsvd,0);
coerce_output_float_only(sv,sv_tmp,nsvmx,0);
NclFree(sv_tmp);
NclFree(svdpcv_tmp);
}
/*
* Set up return values.
*/
type_svdpcv_class = (NclTypeClass)_NclNameToTypeClass(NrmStringToQuark(_NclBasicDataTypeToName(type_svdpcv)));
return_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
svdpcv,
NULL,
1,
dsizes_svdpcv,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
/*
* Set up attributes to return.
*/
att_id = _NclAttCreate(NULL,NULL,Ncl_Att,0,NULL);
dsizes[0] = nsvmx;
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
sv,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
_NclAddAtt(
att_id,
"sv",
att_md,
NULL
);
tmp_var = _NclVarCreate(
NULL,
NULL,
Ncl_Var,
0,
NULL,
return_md,
NULL,
att_id,
NULL,
RETURNVAR,
NULL,
TEMPORARY
);
/*
* Return output grid and attributes to NCL.
*/
return_data.kind = NclStk_VAR;
return_data.u.data_var = tmp_var;
_NclPlaceReturn(return_data);
return(NhlNOERROR);
}
NhlErrorTypes svdstd_sv_W( void )
{
/*
* Input array variables
*/
void *x, *y, *svlft, *svrgt;
double *dx, *dy, *svlft_tmp, *svrgt_tmp;
ng_size_t dsizes_x[2];
int has_missing_x;
ng_size_t dsizes_y[2];
int has_missing_y;
ng_size_t dsizes_svlft[2];
ng_size_t dsizes_svrgt[2];
NclScalar missing_x, missing_y, missing_dx, missing_dy;
NclBasicDataTypes type_x, type_y, type_svlft, type_svrgt;
ng_size_t ntimes, ncolx, ncoly;
int *nsvd;
int ier = 0, iflag=1, iprint=0;
/*
* Work array variables
*/
double *w, *crv, *u, *vt;
ng_size_t lwork, nsvmx;
/*
* Output array variables
*/
double *svdpcv_tmp, *sv_tmp;
void *svdpcv, *sv;
ng_size_t dsizes_svdpcv[1];
NclBasicDataTypes type_svdpcv;
NclTypeClass type_svdpcv_class;
/*
* Attribute variables
*/
int att_id;
ng_size_t dsizes[1];
NclMultiDValData att_md, return_md;
NclVar tmp_var;
NclStackEntry return_data;
/*
* Various
*/
ng_size_t total_size_x, total_size_y, total_size_svrgt, total_size_svlft;
/*
* Retrieve input parameters.
*/
x = (void*)NclGetArgValue(
0,
5,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
&type_x,
DONT_CARE);
y = (void*)NclGetArgValue(
1,
5,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
&type_y,
DONT_CARE);
nsvd = (int *)NclGetArgValue(
2,
5,
NULL,
NULL,
NULL,
NULL,
NULL,
DONT_CARE);
svlft = (void*)NclGetArgValue(
3,
5,
NULL,
dsizes_svlft,
NULL,
NULL,
&type_svlft,
DONT_CARE);
svrgt = (void*)NclGetArgValue(
4,
5,
NULL,
dsizes_svrgt,
NULL,
NULL,
&type_svrgt,
DONT_CARE);
/*
* The rightmost dimensions must be the same.
*/
if( dsizes_x[1] != dsizes_y[1] ) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: The rightmost dimension of both input arrays must be the same size");
return(NhlFATAL);
}
ncolx = dsizes_x[0];
ncoly = dsizes_y[0];
ntimes = dsizes_x[1];
/*
* Check dimension sizes. The leftmost dimension must be nsvd. The
* second dimension must be the same as the leftmost dimension of
* x (or y if it's the rgt arrays).
*/
if( dsizes_svlft[0] != *nsvd || dsizes_svlft[1] != dsizes_x[0]) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: The rightmost dimension of the left array must be the same as the leftmost dimension of x, and the leftmost dimension must be nsvx");
return(NhlFATAL);
}
if( dsizes_svrgt[0] != *nsvd ||
dsizes_svrgt[1] != dsizes_y[0]) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: The rightmost dimension of the right array must be the same as the leftmost dimension of y, and the leftmost dimension must be nsvx");
return(NhlFATAL);
}
/*
* Check nsvd, the number of SVD patterns to be calculated.
*/
if (*nsvd > min(ncolx,ncoly)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: nsvx exceeds maximum possible patterns");
return(NhlFATAL);
}
/*
* Calculate total sizes of input arrays.
*/
total_size_x = ntimes * ncolx;
total_size_y = ntimes * ncoly;
total_size_svlft = *nsvd * ncolx;
total_size_svrgt = *nsvd * ncoly;
/*
* Coerce missing values, if any.
*/
coerce_missing(type_x,has_missing_x,&missing_x,&missing_dx,NULL);
coerce_missing(type_y,has_missing_y,&missing_y,&missing_dy,NULL);
/*
* Coerce x and y to double if necessary.
*/
dx = coerce_input_double(x,type_x,total_size_x,has_missing_x,&missing_x,
&missing_dx);
dy = coerce_input_double(y,type_y,total_size_y,has_missing_y,&missing_y,
&missing_dy);
if(dx == NULL || dy == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: Unable to allocate memory for coercing input arrays to double precision");
return(NhlFATAL);
}
/*
* svlft and svrgt must be float or double. It doesn't matter what the input
* types are.
*/
if(((type_svlft != NCL_float) && (type_svlft != NCL_double)) ||
((type_svrgt != NCL_float) && (type_svrgt != NCL_double))) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: svLeft/svRight must be of type float or double");
return(NhlFATAL);
}
/*
* Allocate space for double precision svrgt/lft. There's no need to do a
* coercion because svrgt/lft is an output-only variable (i.e, there are no
* values coming in). svrgt/lft can only be float or double, so only
* allocate space for a d.p. array if svrgt/lft is float.
*/
svlft_tmp = coerce_output_double(svlft,type_svlft,total_size_svlft);
svrgt_tmp = coerce_output_double(svrgt,type_svrgt,total_size_svrgt);
if(svlft_tmp == NULL || svrgt_tmp == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: Unable to allocate memory for coercing output arrays to double precision");
return(NhlFATAL);
}
/*
* Determine type of output values and allocate space for them.
*/
dsizes_svdpcv[0] = *nsvd;
nsvmx = min(ncolx,ncoly);
if(type_x != NCL_double && type_y != NCL_double) {
type_svdpcv = NCL_float;
svdpcv = (void *)calloc(*nsvd,sizeof(float));
svdpcv_tmp = (double *)calloc(*nsvd,sizeof(double));
sv = (void *)calloc(nsvmx,sizeof(float));
sv_tmp = (double *)calloc(nsvmx,sizeof(double));
if(svdpcv == NULL || svdpcv_tmp == NULL || sv == NULL || sv_tmp == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: Unable to allocate memory for output arrays");
return(NhlFATAL);
}
}
else {
type_svdpcv = NCL_double;
svdpcv = (void *)calloc(*nsvd,sizeof(double));
sv = (void *)calloc(nsvmx,sizeof(double));
svdpcv_tmp = (double*)svdpcv;
sv_tmp = (double*)sv;
if(svdpcv == NULL || sv == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: Unable to allocate memory for output arrays");
return(NhlFATAL);
}
}
/*
* Allocate memory for work and output arrays.
*/
lwork = max(3*nsvmx+max(ncolx,ncoly),5*nsvmx);
w = (double *)calloc(lwork,sizeof(double));
u = (double *)calloc(nsvmx*ncolx,sizeof(double));
vt = (double *)calloc(nsvmx*ncoly,sizeof(double));
crv = (double *)calloc(ncolx*ncoly,sizeof(double));
if( w == NULL || crv == NULL || u == NULL || vt == NULL || sv == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: Unable to allocate memory for work arrays");
return(NhlFATAL);
}
/*
* Call the Fortran version of 'svdlap' with the full argument list.
*/
if((ntimes <= INT_MAX) &&
(ncolx <= INT_MAX) &&
(ncoly <= INT_MAX) &&
(nsvmx <= INT_MAX) &&
(lwork <= INT_MAX))
{
int intimes = (int) ntimes;
int incolx = (int) ncolx;
int incoly = (int) ncoly;
int insvmx = (int) nsvmx;
int ilwork = (int) lwork;
NGCALLF(dsvdsv,DSVDSV)(dx,dy,&intimes,&intimes,&incolx,&incoly,nsvd,&iflag,
&missing_dx.doubleval,&iprint,svlft_tmp,svrgt_tmp,
svdpcv_tmp,crv,u,vt,sv_tmp,&insvmx,w,&ilwork,&ier);
}
else
{
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdstd_sv: one or more input dimension sizes is greater than INT_MAX");
return(NhlFATAL);
}
/*
* Free memory.
*/
NclFree(w);
NclFree(crv);
NclFree(u);
NclFree(vt);
if((void*)dx != x) NclFree(dx);
if((void*)dy != y) NclFree(dy);
/*
* If svlft/rgt were originally float, then we need to coerce them from
* double to float.
*/
if(type_svrgt == NCL_float) {
coerce_output_float_only(svrgt,svrgt_tmp,total_size_svrgt,0);
NclFree(svrgt_tmp);
}
if(type_svlft == NCL_float) {
coerce_output_float_only(svlft,svlft_tmp,total_size_svlft,0);
NclFree(svlft_tmp);
}
if(type_svdpcv != NCL_double) {
coerce_output_float_only(svdpcv,svdpcv_tmp,*nsvd,0);
coerce_output_float_only(sv,sv_tmp,nsvmx,0);
NclFree(sv_tmp);
NclFree(svdpcv_tmp);
}
/*
* Set up return values.
*/
type_svdpcv_class = (NclTypeClass)_NclNameToTypeClass(NrmStringToQuark(_NclBasicDataTypeToName(type_svdpcv)));
return_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
svdpcv,
NULL,
1,
dsizes_svdpcv,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
/*
* Set up attributes to return.
*/
att_id = _NclAttCreate(NULL,NULL,Ncl_Att,0,NULL);
dsizes[0] = nsvmx;
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
sv,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)type_svdpcv_class
);
_NclAddAtt(
att_id,
"sv",
att_md,
NULL
);
tmp_var = _NclVarCreate(
NULL,
NULL,
Ncl_Var,
0,
NULL,
return_md,
NULL,
att_id,
NULL,
RETURNVAR,
NULL,
TEMPORARY
);
/*
* Return output grid and attributes to NCL.
*/
return_data.kind = NclStk_VAR;
return_data.u.data_var = tmp_var;
_NclPlaceReturn(return_data);
return(NhlNOERROR);
}
NhlErrorTypes svd_lapack_W( void )
{
/*
* Input array variables
*/
void *a, *u, *v;
NrmQuark *jobu, *jobv;
int *optv;
double *tmp_a, *tmp_u, *tmp_vt;
int ndims_a;
ng_size_t dsizes_a[NCL_MAX_DIMENSIONS];
ng_size_t dsizes_u[2];
ng_size_t dsizes_v[2];
int has_missing_a;
NclScalar missing_a, missing_da;
NclBasicDataTypes type_a, type_u, type_v;
/*
* Work array variables
*/
double *work;
ng_size_t lwk;
/*
* Output array variables
*/
double *tmp_sgesvd;
void *sgesvd;
int *info;
ng_size_t dsizes_sgesvd[1];
NclBasicDataTypes type_sgesvd;
NclTypeClass type_sgesvd_class;
/*
* Attribute variables
*/
int att_id;
ng_size_t dsizes[1];
NclMultiDValData att_md, return_md;
NclVar tmp_var;
NclStackEntry return_data;
/*
* various
*/
ng_size_t i, j, k1, k2, nrow, ncol, minrc, size_a, size_u, size_v;
ng_size_t ldu, ucol, ldvt;
int found_missing_a;
/*
* Retrieve input parameters.
*/
a = (void*)NclGetArgValue(
0,
6,
&ndims_a,
dsizes_a,
&missing_a,
&has_missing_a,
&type_a,
DONT_CARE);
/*
* The grid coming in must be at least two-dimensional.
*/
if( ndims_a < 2 ) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svd_lapack: The input array must be at least two-dimensional");
return(NhlFATAL);
}
jobu = (NrmQuark *)NclGetArgValue(
1,
6,
NULL,
NULL,
NULL,
NULL,
NULL,
DONT_CARE);
jobv = (NrmQuark *)NclGetArgValue(
2,
6,
NULL,
NULL,
NULL,
NULL,
NULL,
DONT_CARE);
/*
* This part not needed yet, because "S" and "S" are being hard-coded
* for jobu and jobv.
*
* c_jobu = NrmQuarkToString(*jobu);
* c_jobv = NrmQuarkToString(*jobv);
*/
optv = (int *)NclGetArgValue(
3,
6,
NULL,
NULL,
NULL,
NULL,
NULL,
DONT_CARE);
u = (void*)NclGetArgValue(
4,
6,
NULL,
dsizes_u,
NULL,
NULL,
&type_u,
DONT_CARE);
v = (void*)NclGetArgValue(
5,
6,
NULL,
dsizes_v,
NULL,
NULL,
&type_v,
DONT_CARE);
/*
* Check the dimensions of u and v against the dimensions of a.
* The leftmost dimensions of "a" will be collapsed into one
* dimension (ncol).
*/
ncol = 1;
for( i = 0; i <= ndims_a-2; i++ ) ncol *= dsizes_a[i];
nrow = dsizes_a[ndims_a-1];
minrc = min(nrow,ncol);
ucol = dsizes_u[0];
ldu = dsizes_u[1];
ldvt = dsizes_v[1];
if(ldu < nrow || ucol < minrc) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svd_lapack: The dimensions of 'u' must be min(N,M) x M, where (N,M) are the dimensions of 'a'");
return(NhlFATAL);
}
if( dsizes_v[0] != ncol || ldvt < minrc) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svd_lapack: The dimensions of 'v' must be min(N,M) x N where (N,M) are the dimensions of 'a'");
return(NhlFATAL);
}
/*
* The hom/het arrays must be float or double. It doesn't matter what
* the input types are.
*/
if(((type_u != NCL_float) && (type_u != NCL_double)) ||
((type_v != NCL_float) && (type_v != NCL_double))) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svd_lapack: The u, v arrays must be of type float or double");
return(NhlFATAL);
}
/*
* Calculate total sizes of input arrays and output arrays.
*/
size_a = ncol * nrow;
size_u = ucol * ldu;
size_v = ncol * ldvt;
/*
* Coerce input to double if necessary
*/
tmp_a = coerce_input_double(a,type_a,size_a,has_missing_a,&missing_a,
&missing_da);
/*
* Check for missing values, which are not allowed.
*/
found_missing_a = contains_missing(tmp_a,size_a,has_missing_a,
missing_da.doubleval);
if(found_missing_a) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svd_lapack: The input array cannot contain any missing values");
set_subset_output_missing(a,0,type_a,size_a,missing_da.doubleval);
return(NhlFATAL);
}
/*
* Allocate space for double precision u/v. There's no need to do a
* coercion because u/v are output-only variables (i.e, there are no
* values coming in). u/v can only be float or double, so only
* allocate space for a dp array if u/v is float.
*
* If v needs to be transposed, (optv=1), then create space for tmp_vt
* no matter what.
*/
info = (int*)calloc(1,sizeof(int));
tmp_u = coerce_output_double(u,type_u,size_u);
if(*optv == 1) {
tmp_vt = (double*)calloc(size_v,sizeof(double));
}
else {
tmp_vt = coerce_output_double(v,type_v,size_v);
}
if(tmp_u == NULL || tmp_vt == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svd_lapack: Unable to allocate memory for coercing output arrays to double precision");
return(NhlFATAL);
}
/*
* Determine type of output values and allocate space for them.
*/
dsizes_sgesvd[0] = minrc;
if(type_a != NCL_double) {
type_sgesvd = NCL_float;
sgesvd = (void *)calloc(minrc,sizeof(float));
tmp_sgesvd = (double *)calloc(minrc,sizeof(double));
if( sgesvd == NULL || tmp_sgesvd == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svd_lapack: Unable to allocate memory for output array");
return(NhlFATAL);
}
}
else {
type_sgesvd = NCL_double;
sgesvd = (void *)calloc(minrc,sizeof(double));
if( sgesvd == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svd_lapack: Unable to allocate memory for output array");
return(NhlFATAL);
}
tmp_sgesvd = (double *)sgesvd;
}
/*
* Allocate memory for work array.
*/
lwk = max( 3*minrc + max(nrow,ncol), 5 * minrc);
work = (double *)calloc(lwk,sizeof(double));
if( work == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"svd_lapack: Unable to allocate memory for work array");
return(NhlFATAL);
}
/*
* Call the Fortran version of 'svdlap' with the full argument list.
*/
if((nrow <= INT_MAX) &&
(ncol <= INT_MAX) &&
(ldu <= INT_MAX) &&
(ldvt <= INT_MAX) &&
(lwk <= INT_MAX))
{
int inrow = (int) nrow;
int incol = (int) ncol;
int ildu = (int) ldu;
int ildvt = (int) ldvt;
int ilwk = (int) lwk;
NGCALLF(dgesvd,DGESVD)("S", "S", &inrow, &incol, tmp_a, &inrow,
tmp_sgesvd, tmp_u, &ildu, tmp_vt, &ildvt,
work, &ilwk, info);
}
else
{
NhlPError(NhlFATAL,NhlEUNKNOWN,"svd_lapack: one or more input dimension sizes is greater than INT_MAX");
return(NhlFATAL);
}
/*
* Coerce output back to float if necessary.
*/
if(type_sgesvd == NCL_float) {
coerce_output_float_only(sgesvd,tmp_sgesvd,minrc,0);
NclFree(tmp_sgesvd);
}
/*
* Coerce u and v back to float if necessary and transpose v if desired.
*/
if(type_u == NCL_float) {
coerce_output_float_only(u,tmp_u,size_u,0);
NclFree(tmp_u);
}
if(*optv == 1) {
if(type_v == NCL_float) {
for( i = 0; i < ncol; i++ ) {
for( j = 0; j < ldvt; j++ ) {
k1 = i * ncol + j;
k2 = j * ldvt + i;
((float*)v)[k2] = (float)tmp_vt[k1];
}
}
}
else {
for( i = 0; i < ncol; i++ ) {
for( j = 0; j < ldvt; j++ ) {
k1 = i * ncol + j;
k2 = j * ldvt + i;
((double*)v)[k2] = (double)tmp_vt[k1];
}
}
}
NclFree(tmp_vt);
}
else {
if(type_v == NCL_float ) {
coerce_output_float_only(v,tmp_vt,size_v,0);
NclFree(tmp_vt);
}
}
/*
* Free memory.
*/
NclFree(work);
if(type_a != NCL_double)
NclFree(tmp_a);
/*
* Set up variable to return and assign values for "info" attribute.
*/
type_sgesvd_class = (NclTypeClass)_NclNameToTypeClass(NrmStringToQuark(_NclBasicDataTypeToName(type_sgesvd)));
return_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
sgesvd,
NULL,
1,
dsizes_sgesvd,
TEMPORARY,
NULL,
(NclObjClass)type_sgesvd_class
);
/*
* Set up attributes to return.
*/
att_id = _NclAttCreate(NULL,NULL,Ncl_Att,0,NULL);
/*
* Create individual attributes.
*/
dsizes[0] = 1;
att_md = _NclCreateVal(
NULL,
NULL,
Ncl_MultiDValData,
0,
(void*)info,
NULL,
1,
dsizes,
TEMPORARY,
NULL,
(NclObjClass)nclTypeintClass
);
_NclAddAtt(
att_id,
"info",
att_md,
NULL
);
tmp_var = _NclVarCreate(
NULL,
NULL,
Ncl_Var,
0,
NULL,
return_md,
NULL,
att_id,
NULL,
RETURNVAR,
NULL,
TEMPORARY
);
/*
* Return output grid and attributes to NCL.
*/
return_data.kind = NclStk_VAR;
return_data.u.data_var = tmp_var;
_NclPlaceReturn(return_data);
return(NhlNOERROR);
}
NhlErrorTypes svdpar_W( void )
{
/*
* Input variables.
*/
void *x;
double *dx;
ng_size_t dsizes_x[2];
NclBasicDataTypes type_x;
NrmQuark *label;
char *label2;
/*
* Get data to print.
*/
x = (void*)NclGetArgValue(
0,
2,
NULL,
dsizes_x,
NULL,
NULL,
&type_x,
DONT_CARE);
/*
* Coerce to double if necessary.
*/
dx = coerce_input_double(x,type_x,dsizes_x[0]*dsizes_x[1],0,NULL,NULL);
/*
* Get label.
*/
label = (NrmQuark *)NclGetArgValue(
1,
2,
NULL,
NULL,
NULL,
NULL,
NULL,
DONT_CARE);
label2 = NrmQuarkToString(*label);
/*
* Call the Fortran version of 'dsvdpar' with the full argument list.
*/
if((dsizes_x[0] <= INT_MAX) && (dsizes_x[1] <= INT_MAX))
{
int x0 = (int) dsizes_x[0];
int x1 = (int) dsizes_x[1];
NGCALLF(dsvdpar,DSVDPAR)(dx,&x1,&x1,&x0,
label2,strlen(label2));
}
else
{
NhlPError(NhlFATAL,NhlEUNKNOWN,"svdpar: one or more input dimension sizes is greater than INT_MAX");
return(NhlFATAL);
}
/*
* Free up memory and return.
*/
if((void*)dx != x) NclFree(dx);
return(NhlNOERROR);
}
|
603589c1da2138cecaa425b53e22abe4eee1c15b
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/sys/device.h
|
2c67b99b0284c4240dda2dbd93bfe6026e0efb8c
|
[
"BSD-2-Clause"
] |
permissive
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 25,121
|
h
|
device.h
|
/* $NetBSD: device.h,v 1.186 2023/05/22 14:58:22 riastradh Exp $ */
/*
* Copyright (c) 2021 The NetBSD Foundation, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION 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) 1996, 2000 Christopher G. Demetriou
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed for the
* NetBSD Project. See http://www.NetBSD.org/ for
* information about NetBSD.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* --(license Id: LICENSE.proto,v 1.1 2000/06/13 21:40:26 cgd Exp )--
*/
/*
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This software was developed by the Computer Systems Engineering group
* at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
* contributed to Berkeley.
*
* All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Lawrence Berkeley Laboratories.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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.
*
* @(#)device.h 8.2 (Berkeley) 2/17/94
*/
#ifndef _SYS_DEVICE_H_
#define _SYS_DEVICE_H_
#include <sys/device_if.h>
#include <sys/evcnt.h>
#include <sys/queue.h>
#if defined(_KERNEL) || defined(_KMEMUSER)
#include <sys/mutex.h>
#include <sys/condvar.h>
#include <sys/pmf.h>
#endif
#include <prop/proplib.h>
/*
* Minimal device structures.
* Note that all ``system'' device types are listed here.
*/
typedef enum devclass {
DV_DULL, /* generic, no special info */
DV_CPU, /* CPU (carries resource utilization) */
DV_DISK, /* disk drive (label, etc) */
DV_IFNET, /* network interface */
DV_TAPE, /* tape device */
DV_TTY, /* serial line interface (?) */
DV_AUDIODEV, /* audio device */
DV_DISPLAYDEV, /* display device */
DV_BUS, /* bus device */
DV_VIRTUAL, /* unbacked virtual device */
} devclass_t;
/*
* Actions for ca_activate.
*/
typedef enum devact {
DVACT_DEACTIVATE /* deactivate the device */
} devact_t;
typedef enum {
DVA_SYSTEM,
DVA_HARDWARE
} devactive_t;
typedef struct cfdata *cfdata_t;
typedef struct cfdriver *cfdriver_t;
typedef struct cfattach *cfattach_t;
#if defined(_KERNEL) || defined(_KMEMUSER) || defined(_STANDALONE)
/*
* devhandle_t --
*
* This is an abstraction of the device handles used by ACPI,
* OpenFirmware, and others, to support device enumeration and
* device tree linkage. A devhandle_t can be safely passed
* by value.
*/
struct devhandle {
const struct devhandle_impl * impl;
union {
/*
* Storage for the device handle. Which storage field
* is used is at the sole discretion of the type
* implementation.
*/
void * pointer;
const void * const_pointer;
uintptr_t uintptr;
intptr_t integer;
};
};
typedef struct devhandle devhandle_t;
#endif
#if defined(_KERNEL) || defined(_KMEMUSER)
struct device_compatible_entry {
union {
const char *compat;
uintptr_t id;
};
union {
const void *data;
uintptr_t value;
};
};
#define DEVICE_COMPAT_EOL { .compat = NULL }
struct device_suspensor {
const device_suspensor_t *ds_delegator;
char ds_name[32];
};
struct device_garbage {
device_t *dg_devs;
int dg_ndevs;
};
typedef enum {
/* Used to represent invalid states. */
DEVHANDLE_TYPE_INVALID = 0,
/* ACPI */
DEVHANDLE_TYPE_ACPI = 0x41435049, /* 'ACPI' */
/* OpenFirmware, FDT */
DEVHANDLE_TYPE_OF = 0x4f504657, /* 'OPFW' */
/* Sun OpenBoot */
DEVHANDLE_TYPE_OPENBOOT = 0x4f504254, /* 'OPBT' */
/* Private (opaque data) */
DEVHANDLE_TYPE_PRIVATE = 0x50525654, /* 'PRVT' */
/* Max value. */
DEVHANDLE_TYPE_MAX = 0xffffffff
} devhandle_type_t;
/* Device method call function signature. */
typedef int (*device_call_t)(device_t, devhandle_t, void *);
struct device_call_descriptor {
const char *name;
device_call_t call;
};
#define _DEVICE_CALL_REGISTER(_g_, _c_) \
__link_set_add_rodata(_g_, __CONCAT(_c_,_descriptor));
#define DEVICE_CALL_REGISTER(_g_, _n_, _c_) \
static const struct device_call_descriptor __CONCAT(_c_,_descriptor) = {\
.name = (_n_), .call = (_c_) \
}; \
_DEVICE_CALL_REGISTER(_g_, _c_)
struct devhandle_impl {
devhandle_type_t type;
const struct devhandle_impl * super;
device_call_t (*lookup_device_call)(devhandle_t,
const char *, devhandle_t *);
};
/* Max size of a device external name (including terminating NUL) */
#define DEVICE_XNAME_SIZE 16
struct device;
/*
* struct cfattach::ca_flags (must not overlap with device_impl.h
* struct device::dv_flags for now)
*/
#define DVF_PRIV_ALLOC 0x0002 /* device private storage != device */
#define DVF_DETACH_SHUTDOWN 0x0080 /* device detaches safely at shutdown */
#ifdef _KERNEL
TAILQ_HEAD(devicelist, device);
#endif
enum deviter_flags {
DEVITER_F_RW = 0x1
, DEVITER_F_SHUTDOWN = 0x2
, DEVITER_F_LEAVES_FIRST = 0x4
, DEVITER_F_ROOT_FIRST = 0x8
};
typedef enum deviter_flags deviter_flags_t;
struct deviter {
device_t di_prev;
deviter_flags_t di_flags;
int di_curdepth;
int di_maxdepth;
devgen_t di_gen;
};
typedef struct deviter deviter_t;
struct shutdown_state {
bool initialized;
deviter_t di;
};
#endif
/*
* Description of a locator, as part of interface attribute definitions.
*/
struct cflocdesc {
const char *cld_name;
const char *cld_defaultstr; /* NULL if no default */
int cld_default;
};
/*
* Description of an interface attribute, provided by potential
* parent device drivers, referred to by child device configuration data.
*/
struct cfiattrdata {
const char *ci_name;
int ci_loclen;
const struct cflocdesc ci_locdesc[
#if defined(__GNUC__) && __GNUC__ <= 2
0
#endif
];
};
/*
* Description of a configuration parent. Each device attachment attaches
* to an "interface attribute", which is given in this structure. The parent
* *must* carry this attribute. Optionally, an individual device instance
* may also specify a specific parent device instance.
*/
struct cfparent {
const char *cfp_iattr; /* interface attribute */
const char *cfp_parent; /* optional specific parent */
int cfp_unit; /* optional specific unit
(DVUNIT_ANY to wildcard) */
};
/*
* Configuration data (i.e., data placed in ioconf.c).
*/
struct cfdata {
const char *cf_name; /* driver name */
const char *cf_atname; /* attachment name */
unsigned int cf_unit:24; /* unit number */
unsigned char cf_fstate; /* finding state (below) */
int *cf_loc; /* locators (machine dependent) */
int cf_flags; /* flags from config */
const struct cfparent *cf_pspec;/* parent specification */
};
#define FSTATE_NOTFOUND 0 /* has not been found */
#define FSTATE_FOUND 1 /* has been found */
#define FSTATE_STAR 2 /* duplicable */
#define FSTATE_DSTAR 3 /* has not been found, and disabled */
#define FSTATE_DNOTFOUND 4 /* duplicate, and disabled */
/*
* Multiple configuration data tables may be maintained. This structure
* provides the linkage.
*/
struct cftable {
cfdata_t ct_cfdata; /* pointer to cfdata table */
TAILQ_ENTRY(cftable) ct_list; /* list linkage */
};
#ifdef _KERNEL
TAILQ_HEAD(cftablelist, cftable);
#endif
typedef int (*cfsubmatch_t)(device_t, cfdata_t, const int *, void *);
typedef int (*cfsearch_t)(device_t, cfdata_t, const int *, void *);
/*
* `configuration' attachment and driver (what the machine-independent
* autoconf uses). As devices are found, they are applied against all
* the potential matches. The one with the best match is taken, and a
* device structure (plus any other data desired) is allocated. Pointers
* to these are placed into an array of pointers. The array itself must
* be dynamic since devices can be found long after the machine is up
* and running.
*
* Devices can have multiple configuration attachments if they attach
* to different attributes (busses, or whatever), to allow specification
* of multiple match and attach functions. There is only one configuration
* driver per driver, so that things like unit numbers and the device
* structure array will be shared.
*/
struct cfattach {
const char *ca_name; /* name of attachment */
LIST_ENTRY(cfattach) ca_list; /* link on cfdriver's list */
size_t ca_devsize; /* size of dev data (for alloc) */
int ca_flags; /* flags for driver allocation etc */
int (*ca_match)(device_t, cfdata_t, void *);
void (*ca_attach)(device_t, device_t, void *);
int (*ca_detach)(device_t, int);
int (*ca_activate)(device_t, devact_t);
/* technically, the next 2 belong into "struct cfdriver" */
int (*ca_rescan)(device_t, const char *,
const int *); /* scan for new children */
void (*ca_childdetached)(device_t, device_t);
};
LIST_HEAD(cfattachlist, cfattach);
#define CFATTACH_DECL3_NEW(name, ddsize, matfn, attfn, detfn, actfn, \
rescanfn, chdetfn, __flags) \
struct cfattach __CONCAT(name,_ca) = { \
.ca_name = ___STRING(name), \
.ca_devsize = ddsize, \
.ca_flags = (__flags) | DVF_PRIV_ALLOC, \
.ca_match = matfn, \
.ca_attach = attfn, \
.ca_detach = detfn, \
.ca_activate = actfn, \
.ca_rescan = rescanfn, \
.ca_childdetached = chdetfn, \
}
#define CFATTACH_DECL2_NEW(name, ddsize, matfn, attfn, detfn, actfn, \
rescanfn, chdetfn) \
CFATTACH_DECL3_NEW(name, ddsize, matfn, attfn, detfn, actfn, \
rescanfn, chdetfn, 0)
#define CFATTACH_DECL_NEW(name, ddsize, matfn, attfn, detfn, actfn) \
CFATTACH_DECL2_NEW(name, ddsize, matfn, attfn, detfn, actfn, NULL, NULL)
/* Flags given to config_detach(), and the ca_detach function. */
#define DETACH_FORCE 0x01 /* force detachment; hardware gone */
#define DETACH_QUIET 0x02 /* don't print a notice */
#define DETACH_SHUTDOWN 0x04 /* detach because of system shutdown */
#define DETACH_POWEROFF 0x08 /* going to power off; power down devices */
struct cfdriver {
LIST_ENTRY(cfdriver) cd_list; /* link on allcfdrivers */
struct cfattachlist cd_attach; /* list of all attachments */
device_t *cd_devs; /* devices found */
const char *cd_name; /* device name */
enum devclass cd_class; /* device classification */
int cd_ndevs; /* size of cd_devs array */
const struct cfiattrdata * const *cd_attrs; /* attributes provided */
};
LIST_HEAD(cfdriverlist, cfdriver);
#define CFDRIVER_DECL(name, class, attrs) \
struct cfdriver __CONCAT(name,_cd) = { \
.cd_name = ___STRING(name), \
.cd_class = class, \
.cd_attrs = attrs, \
}
/*
* The cfattachinit is a data structure used to associate a list of
* cfattach's with cfdrivers as found in the static kernel configuration.
*/
struct cfattachinit {
const char *cfai_name; /* driver name */
struct cfattach * const *cfai_list;/* list of attachments */
};
/*
* the same, but with a non-constant list so it can be modified
* for module bookkeeping
*/
struct cfattachlkminit {
const char *cfai_name; /* driver name */
struct cfattach **cfai_list; /* list of attachments */
};
/*
* Configuration printing functions, and their return codes. The second
* argument is NULL if the device was configured; otherwise it is the name
* of the parent device. The return value is ignored if the device was
* configured, so most functions can return UNCONF unconditionally.
*/
typedef int (*cfprint_t)(void *, const char *); /* XXX const char * */
#define QUIET 0 /* print nothing */
#define UNCONF 1 /* print " not configured\n" */
#define UNSUPP 2 /* print " not supported\n" */
/*
* Pseudo-device attach information (function + number of pseudo-devs).
*/
struct pdevinit {
void (*pdev_attach)(int);
int pdev_count;
};
/* This allows us to wildcard a device unit. */
#define DVUNIT_ANY -1
#if defined(_KERNEL) || defined(_KMEMUSER) || defined(_STANDALONE)
/*
* Arguments passed to config_search() and config_found().
*/
struct cfargs {
uintptr_t cfargs_version; /* version field */
/* version 1 fields */
cfsubmatch_t submatch; /* submatch function (direct config) */
cfsearch_t search; /* search function (indirect config) */
const char * iattr; /* interface attribute */
const int * locators; /* locators array */
devhandle_t devhandle; /* devhandle_t (by value) */
/* version 2 fields below here */
};
#define CFARGS_VERSION 1 /* current cfargs version */
#define CFARGS_NONE NULL /* no cfargs to pass */
/*
* Construct a cfargs with this macro, like so:
*
* CFARGS(.submatch = config_stdsubmatch,
* .devhandle = my_devhandle)
*
* You must supply at least one field. If you don't need any, use the
* CFARGS_NONE macro.
*/
#define CFARGS(...) \
&((const struct cfargs){ \
.cfargs_version = CFARGS_VERSION, \
__VA_ARGS__ \
})
#endif /* _KERNEL || _KMEMUSER || _STANDALONE */
#ifdef _KERNEL
extern struct cfdriverlist allcfdrivers;/* list of all cfdrivers */
extern struct cftablelist allcftables; /* list of all cfdata tables */
extern device_t booted_device; /* the device we booted from */
extern const char *booted_method; /* the method the device was found */
extern int booted_partition; /* the partition on that device */
extern daddr_t booted_startblk; /* or the start of a wedge */
extern uint64_t booted_nblks; /* and the size of that wedge */
extern char *bootspec; /* and the device/wedge name */
extern bool root_is_mounted; /* true if root is mounted */
struct vnode *opendisk(device_t);
int getdisksize(struct vnode *, uint64_t *, unsigned int *);
struct dkwedge_info;
int getdiskinfo(struct vnode *, struct dkwedge_info *);
void config_init(void);
int config_init_component(struct cfdriver *const*,
const struct cfattachinit *, struct cfdata *);
int config_fini_component(struct cfdriver *const*,
const struct cfattachinit *, struct cfdata *);
void config_init_mi(void);
void drvctl_init(void);
void drvctl_fini(void);
extern int (*devmon_insert_vec)(const char *, prop_dictionary_t);
int config_cfdriver_attach(struct cfdriver *);
int config_cfdriver_detach(struct cfdriver *);
int config_cfattach_attach(const char *, struct cfattach *);
int config_cfattach_detach(const char *, struct cfattach *);
int config_cfdata_attach(cfdata_t, int);
int config_cfdata_detach(cfdata_t);
struct cfdriver *config_cfdriver_lookup(const char *);
struct cfattach *config_cfattach_lookup(const char *, const char *);
const struct cfiattrdata *cfiattr_lookup(const char *, const struct cfdriver *);
const char *cfdata_ifattr(const struct cfdata *);
int config_stdsubmatch(device_t, cfdata_t, const int *, void *);
cfdata_t config_search(device_t, void *, const struct cfargs *);
cfdata_t config_rootsearch(cfsubmatch_t, const char *, void *);
device_t config_found(device_t, void *, cfprint_t, const struct cfargs *);
device_t config_rootfound(const char *, void *);
device_t config_attach(device_t, cfdata_t, void *, cfprint_t,
const struct cfargs *);
device_t config_found_acquire(device_t, void *, cfprint_t,
const struct cfargs *);
device_t config_attach_acquire(device_t, cfdata_t, void *, cfprint_t,
const struct cfargs *);
int config_match(device_t, cfdata_t, void *);
int config_probe(device_t, cfdata_t, void *);
bool ifattr_match(const char *, const char *);
device_t config_attach_pseudo(cfdata_t);
device_t config_attach_pseudo_acquire(cfdata_t, void *);
int config_detach(device_t, int);
int config_detach_release(device_t, int);
int config_detach_children(device_t, int flags);
void config_detach_commit(device_t);
bool config_detach_all(int);
int config_deactivate(device_t);
void config_defer(device_t, void (*)(device_t));
void config_deferred(device_t);
void config_interrupts(device_t, void (*)(device_t));
void config_mountroot(device_t, void (*)(device_t));
void config_pending_incr(device_t);
void config_pending_decr(device_t);
void config_create_interruptthreads(void);
void config_create_mountrootthreads(void);
int config_finalize_register(device_t, int (*)(device_t));
void config_finalize(void);
void config_finalize_mountroot(void);
void config_twiddle_init(void);
void config_twiddle_fn(void *);
void null_childdetached(device_t, device_t);
device_t device_lookup(cfdriver_t, int);
void *device_lookup_private(cfdriver_t, int);
device_t device_lookup_acquire(cfdriver_t, int);
void device_acquire(device_t);
void device_release(device_t);
void device_register(device_t, void *);
void device_register_post_config(device_t, void *);
devclass_t device_class(device_t);
cfdata_t device_cfdata(device_t);
cfdriver_t device_cfdriver(device_t);
cfattach_t device_cfattach(device_t);
int device_unit(device_t);
const char *device_xname(device_t);
device_t device_parent(device_t);
bool device_is_active(device_t);
bool device_activation(device_t, devact_level_t);
bool device_is_enabled(device_t);
bool device_has_power(device_t);
int device_locator(device_t, u_int);
void *device_private(device_t);
void device_set_private(device_t, void *);
prop_dictionary_t device_properties(device_t);
void device_set_handle(device_t, devhandle_t);
devhandle_t device_handle(device_t);
bool devhandle_is_valid(devhandle_t);
devhandle_t devhandle_invalid(void);
devhandle_type_t devhandle_type(devhandle_t);
int devhandle_compare(devhandle_t, devhandle_t);
device_call_t devhandle_lookup_device_call(devhandle_t, const char *,
devhandle_t *);
void devhandle_impl_inherit(struct devhandle_impl *,
const struct devhandle_impl *);
device_t deviter_first(deviter_t *, deviter_flags_t);
void deviter_init(deviter_t *, deviter_flags_t);
device_t deviter_next(deviter_t *);
void deviter_release(deviter_t *);
bool device_active(device_t, devactive_t);
bool device_active_register(device_t,
void (*)(device_t, devactive_t));
void device_active_deregister(device_t,
void (*)(device_t, devactive_t));
bool device_is_a(device_t, const char *);
bool device_attached_to_iattr(device_t, const char *);
device_t device_find_by_xname(const char *);
device_t device_find_by_driver_unit(const char *, int);
int device_enumerate_children(device_t,
bool (*)(device_t, devhandle_t, void *), void *);
int device_compatible_match(const char **, int,
const struct device_compatible_entry *);
int device_compatible_pmatch(const char **, int,
const struct device_compatible_entry *);
const struct device_compatible_entry *
device_compatible_lookup(const char **, int,
const struct device_compatible_entry *);
const struct device_compatible_entry *
device_compatible_plookup(const char **, int,
const struct device_compatible_entry *);
int device_compatible_match_strlist(const char *, size_t,
const struct device_compatible_entry *);
int device_compatible_pmatch_strlist(const char *, size_t,
const struct device_compatible_entry *);
const struct device_compatible_entry *
device_compatible_lookup_strlist(const char *, size_t,
const struct device_compatible_entry *);
const struct device_compatible_entry *
device_compatible_plookup_strlist(const char *, size_t,
const struct device_compatible_entry *);
int device_compatible_match_id(uintptr_t const, uintptr_t const,
const struct device_compatible_entry *);
const struct device_compatible_entry *
device_compatible_lookup_id(uintptr_t const, uintptr_t const,
const struct device_compatible_entry *);
void device_pmf_driver_child_register(device_t);
void device_pmf_driver_set_child_register(device_t,
void (*)(device_t));
void *device_pmf_bus_private(device_t);
bool device_pmf_bus_suspend(device_t, const pmf_qual_t *);
bool device_pmf_bus_resume(device_t, const pmf_qual_t *);
bool device_pmf_bus_shutdown(device_t, int);
void device_pmf_bus_register(device_t, void *,
bool (*)(device_t, const pmf_qual_t *),
bool (*)(device_t, const pmf_qual_t *),
bool (*)(device_t, int),
void (*)(device_t));
void device_pmf_bus_deregister(device_t);
device_t shutdown_first(struct shutdown_state *);
device_t shutdown_next(struct shutdown_state *);
/*
* device calls --
*
* This provides a generic mechanism for invoking special methods on
* devices, often dependent on the device tree implementation used
* by the platform.
*
* While individual subsystems may define their own device calls,
* the ones prefixed with "device-" are reserved, and defined by
* the device autoconfiguration subsystem. It is the responsibility
* of each device tree back end to implement these calls.
*
* We define a generic interface; individual device calls feature
* type checking of the argument structure. The argument structures
* and the call binding data are automatically generated from device
* call interface descriptions by gendevcalls.awk.
*/
struct device_call_generic {
const char *name;
void *args;
};
int device_call_generic(device_t, const struct device_call_generic *);
#define device_call(dev, call) \
device_call_generic((dev), &(call)->generic)
#endif /* _KERNEL */
#endif /* !_SYS_DEVICE_H_ */
|
d8e97349bfc8bcbdb116b52ba3774fe5ec828840
|
baa9fffc817a2a993d4ecc774d3f277783308c20
|
/src/ucs/memory/memtype_cache.h
|
d9c69acdadc9c68aea9c0c975145a364b166e060
|
[
"BSD-3-Clause"
] |
permissive
|
openucx/ucx
|
9a0f2205295afbdf3cff14b5d24af781b123f5ea
|
73a48700badb7cbace64d94b82f408e2a26fca32
|
refs/heads/master
| 2023-09-01T16:51:26.913950
| 2023-09-01T13:02:25
| 2023-09-01T13:02:25
| 25,379,390
| 966
| 420
|
NOASSERTION
| 2023-09-14T12:29:35
| 2014-10-17T22:17:24
|
C
|
UTF-8
|
C
| false
| false
| 3,858
|
h
|
memtype_cache.h
|
/**
* Copyright (c) NVIDIA CORPORATION & AFFILIATES, 2018. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#ifndef UCS_MEMTYPE_CACHE_H_
#define UCS_MEMTYPE_CACHE_H_
#include "memory_type.h"
#include <ucs/datastruct/pgtable.h>
#include <ucs/datastruct/list.h>
#include <ucs/stats/stats_fwd.h>
#include <ucs/sys/compiler_def.h>
#include <ucs/sys/topo/base/topo.h>
#include <ucs/type/spinlock.h>
#include <pthread.h>
BEGIN_C_DECLS
typedef struct ucs_memtype_cache ucs_memtype_cache_t;
typedef struct ucs_memtype_cache_region ucs_memtype_cache_region_t;
/* The single global instance of memory type cache */
extern ucs_memtype_cache_t *ucs_memtype_cache_global_instance;
/* Memory information record */
typedef struct ucs_memory_info {
ucs_memory_type_t type; /**< Memory type */
ucs_sys_device_t sys_dev; /**< System device index */
void *base_address; /**< Base address of the underlying allocation */
size_t alloc_length; /**< Whole length of the underlying allocation */
} ucs_memory_info_t;
struct ucs_memtype_cache {
ucs_spinlock_t lock; /**< protests the page table */
ucs_pgtable_t pgtable; /**< Page table to hold the regions */
};
void ucs_memtype_cache_global_init();
void ucs_memtype_cache_cleanup();
/**
* Find if address range is in memtype cache.
*
* @param [in] address Address to lookup.
* @param [in] size Length of the memory.
* @param [out] mem_info Set to the memory info of the address range.
* UCS_MEMORY_TYPE_UNKNOWN is a special value which
* means the memory type is an unknown non-host
* memory, and should be detected in another way.
*
* @return UCS_OK - an element was found and the memory info is valid.
* @return UCS_ERR_NO_ELEM - an element was not found.
* @return UCS_ERR_UNSUPPORTED - the memory type cache is disabled.
*/
ucs_status_t ucs_memtype_cache_lookup(const void *address, size_t size,
ucs_memory_info_t *mem_info);
/**
* Update the memory type of an address range.
* Can be used after @ucs_memtype_cache_lookup returns UCM_MEM_TYPE_LAST, to
* set the memory type after it was detected.
*
* @param [in] address Start address to update.
* @param [in] size Size of the memory to update.
* @param [in] mem_type Set the memory type of the address range to this
* value.
* @param [in] sys_dev Set the system device of the address range to
* this value.
*/
void ucs_memtype_cache_update(const void *address, size_t size,
ucs_memory_type_t mem_type,
ucs_sys_device_t sys_dev);
/**
* Remove the address range from a memtype cache.
*
* @param [in] address Start address to remove.
* @param [in] size Size of the memory to remove.
*/
void ucs_memtype_cache_remove(const void *address, size_t size);
/**
* Find if global memtype_cache is empty.
*
* @return 1 if empty 0 if otherwise.
*/
static UCS_F_ALWAYS_INLINE int ucs_memtype_cache_is_empty()
{
return (ucs_memtype_cache_global_instance != NULL) &&
(ucs_memtype_cache_global_instance->pgtable.num_regions == 0);
}
/**
* Helper function to set memory info structure to host memory type.
*
* @param [out] mem_info Pointer to memory info structure.
*/
static UCS_F_ALWAYS_INLINE void
ucs_memory_info_set_host(ucs_memory_info_t *mem_info)
{
mem_info->type = UCS_MEMORY_TYPE_HOST;
mem_info->sys_dev = UCS_SYS_DEVICE_ID_UNKNOWN;
mem_info->base_address = NULL;
mem_info->alloc_length = -1;
}
END_C_DECLS
#endif
|
ac6895a638f6cee73fd731934568cd508908a523
|
55540f3e86f1d5d86ef6b5d295a63518e274efe3
|
/customer_app/enjoy/bledemo/bledemo/ble_apps.c
|
b19fe070088511fc2764c63dd5d3539fc346c27c
|
[
"Apache-2.0"
] |
permissive
|
bouffalolab/bl_iot_sdk
|
bc5eaf036b70f8c65dd389439062b169f8d09daa
|
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
|
refs/heads/master
| 2023-08-31T03:38:03.369853
| 2023-08-16T08:50:33
| 2023-08-18T09:13:27
| 307,347,250
| 244
| 101
|
Apache-2.0
| 2023-08-28T06:29:02
| 2020-10-26T11:16:30
|
C
|
UTF-8
|
C
| false
| false
| 9,334
|
c
|
ble_apps.c
|
/*
* Copyright (c) 2020 Bouffblfolab.
*
* This file is part of
* *** Bouffblfolab Software Dev Kit ***
* (see www.bouffblfolab.com).
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materiblfs provided with the distribution.
* 3. Neither the name of Bouffblfo Lab nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHblfL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTblf, SPECIblf, EXEMPLARY, OR CONSEQUENTIblf
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ble_app.h"
#include <FreeRTOS.h>
#include <task.h>
#include "bluetooth.h"
#include "ble_cli_cmds.h"
#include "hci_driver.h"
#include "ble_lib_api.h"
#include <aos/kernel.h>
#include <aos/yloop.h>
#include "conn.h"
#include "gatt.h"
#include "hci_core.h"
#include "uuid.h"
//#include "oad_api.h"
#include "bl_gpio.h"
#include <vfs.h>
static void ble_bl_ccc_cfg_changed(const struct bt_gatt_attr *attr, u16_t vblfue);
static int ble_blf_recv(struct bt_conn *conn,
const struct bt_gatt_attr *attr, const void *buf,
u16_t len, u16_t offset, u8_t flags);
static const struct bt_data ad[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA(BT_DATA_NAME_COMPLETE, "BL_602", 6),
BT_DATA(BT_DATA_MANUFACTURER_DATA, "BL_602", 6),
};
static struct bt_gatt_attr blattrs[]= {
BT_GATT_PRIMARY_SERVICE(BT_UUID_TEST),
BT_GATT_CHARACTERISTIC(BT_UUID_TEST_RX,
BT_GATT_CHRC_NOTIFY,
BT_GATT_PERM_READ,
NULL,
NULL,
NULL),
BT_GATT_CCC(ble_bl_ccc_cfg_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
BT_GATT_CHARACTERISTIC(BT_UUID_TEST_TX,
BT_GATT_CHRC_WRITE_WITHOUT_RESP,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
NULL,
ble_blf_recv,
NULL)
};
static struct bt_conn *ble_bl_conn=NULL;
static bool notify_flag=false;
static void ble_bl_ccc_cfg_changed(const struct bt_gatt_attr *attr, u16_t vblfue)
{
if(vblfue == BT_GATT_CCC_NOTIFY) {
printf("enable notify.\n");
notify_flag=true;
} else {
printf("disable notify.\n");
notify_flag=false;
}
}
void ble_bl_notify_task(void)
{
char data[10] = {0x00,0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09};
if(ble_bl_conn!=NULL&¬ify_flag==true){
printf("ble_bl_notify_task.\n");
bt_gatt_notify(ble_bl_conn, &blattrs[1],data,10);
}
}
void ble_bl_disconnect(void)
{
if(ble_bl_conn!=NULL)
{
printf("user disconnect\n");
bt_conn_disconnect(ble_bl_conn,BT_HCI_ERR_REMOTE_USER_TERM_CONN);
aos_post_event(EV_BLE_TEST,BLE_DEV_DISCONN,NULL);
}
}
static int ble_blf_recv(struct bt_conn *conn,
const struct bt_gatt_attr *attr, const void *buf,
u16_t len, u16_t offset, u8_t flags)
{
uint8_t *recv_buffer;
recv_buffer=pvPortMalloc(sizeof(uint8_t)*len);
memcpy(recv_buffer, buf, len);
printf("ble rx=%d\n",len);
for (size_t i = 0; i < len; i++)
{
printf("0x%x ",recv_buffer[i]);
}
vPortFree(recv_buffer);
printf("\n");
return 0;
}
struct bt_gatt_service ble_bl_server = BT_GATT_SERVICE(blattrs);
static void bt_ready(void)
{
bt_set_name("blf_602");
printf("Bluetooth initiblfized\n");
bleapps_adv_starting();
}
void bleapps_adv_starting(void)
{
int err;
printf("Bluetooth Advertising start\n");
err = bt_le_adv_start(BT_LE_ADV_CONN_NAME, ad, ARRAY_SIZE(ad), NULL, 0);
if (err) {
printf("Advertising failed to start (err %d)\n", err);
}else{
aos_post_event(EV_BLE_TEST,BLE_ADV_START,NULL);
}
}
void bleapps_adv_stop(void)
{
int err;
printf("Bluetooth Advertising stop\n");
err =bt_le_adv_stop();
if (err) {
printf("Advertising failed to stop (err %d)\n", err);
}else{
aos_post_event(EV_BLE_TEST,BLE_ADV_STOP,NULL);
}
}
static void ble_app_init(int err)
{
if (err != 0) {
printf("BT FAILED started\n");
}else{
printf("BT SUCCESS started\n");
bt_ready();
}
}
static void bl_connected(struct bt_conn *conn, uint8_t err)
{
struct bt_le_conn_param param;
param.interval_max=24;
param.interval_min=24;
param.latency=0;
param.timeout=600;
int update_err;
if (err) {
printf("Connection failed (err 0x%02x)\n", err);
} else {
printf("Connected\n");
ble_bl_conn=conn;
update_err = bt_conn_le_param_update(conn, ¶m);
if (err) {
printf("conn update failed (err %d)\r\n", err);
} else {
printf("conn update initiated\r\n");
}
#if 0
#if defined(CONFIG_BT_SMP)
bt_conn_set_security(conn, BT_SECURITY_L4);
#endif
#endif
aos_post_event(EV_BLE_TEST,BLE_DEV_CONN,NULL);
}
}
static void bl_disconnected(struct bt_conn *conn, uint8_t reason)
{
printf("Disconnected (reason 0x%02x)\n", reason);
aos_post_event(EV_BLE_TEST,BLE_DEV_DISCONN,NULL);
}
static struct bt_conn_cb conn_callbacks = {
.connected = bl_connected,
.disconnected = bl_disconnected,
};
static void ble_stack_start(void)
{
// Initiblfize BLE controller
ble_controller_init(configMAX_PRIORITIES - 1);
// Initiblfize BLE Host stack
hci_driver_init();
bt_enable(ble_app_init);
}
#if defined(CONFIG_BT_SMP)
static void auth_passkey_display(struct bt_conn *conn, unsigned int passkey)
{
char addr[BT_ADDR_LE_STR_LEN];
bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
printf("passkey_str is: %06u\r\n", passkey);
}
static void auth_passkey_confirm(struct bt_conn *conn, unsigned int passkey)
{
char addr[BT_ADDR_LE_STR_LEN];
bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
printf("Confirm passkey for %s: %06u\r\n", addr, passkey);
bt_conn_auth_passkey_confirm(conn);
}
static void auth_passkey_entry(struct bt_conn *conn)
{
char addr[BT_ADDR_LE_STR_LEN];
bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
printf("Enter passkey for %s\r\n", addr);
}
static void auth_cancel(struct bt_conn *conn)
{
char addr[BT_ADDR_LE_STR_LEN];
bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
printf("Pairing cancelled: %s\r\n", addr);
}
static void auth_pairing_confirm(struct bt_conn *conn)
{
char addr[BT_ADDR_LE_STR_LEN];
bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
printf("Confirm pairing for %s\r\n", addr);
}
static void auth_pairing_complete(struct bt_conn *conn, bool bonded)
{
char addr[BT_ADDR_LE_STR_LEN];
bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
printf("%s with %s\r\n", bonded ? "Bonded" : "Paired", addr);
}
static void auth_pairing_failed(struct bt_conn *conn, enum bt_security_err reason)
{
char addr[BT_ADDR_LE_STR_LEN];
bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
printf("Pairing failed with %s\r\n", addr);
}
static struct bt_conn_auth_cb auth_cb_display = {
.passkey_display = auth_passkey_display,
.passkey_entry = auth_passkey_entry,
.passkey_confirm = auth_passkey_confirm,
.cancel = auth_cancel,
.pairing_confirm = auth_pairing_confirm,
.pairing_failed = auth_pairing_failed,
.pairing_complete = auth_pairing_complete,
};
#endif
void apps_ble_start(void)
{
int err;
ble_stack_start();
bt_conn_cb_register(&conn_callbacks);
err=bt_gatt_service_register(&ble_bl_server);
if (err==0) {
printf("bt_gatt_service_register ok\n");
} else {
printf("bt_gatt_service_register err\n");
}
#if defined(CONFIG_BT_SMP)
err = bt_conn_auth_cb_register(&auth_cb_display);
if(err){
printf("Auth callback has blfready been registered\r\n");
}else{
printf("Register auth callback successfully\r\n");
}
#endif
}
|
e6374a12e6f7f651a5674101f44a9ce185738404
|
4f4296fc13f014753dcd847d06cdff71ce679663
|
/src/plugin/regress/vce/vce.h
|
4ae55ee999766786737b6578bd5982979082fd09
|
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
mcaceresb/stata-gtools
|
943f890aefa5fa9c648fed3722186b4dc0046312
|
10d53be2d89b0af05152c269b340e4ec7f859a10
|
refs/heads/master
| 2023-06-07T16:28:21.559318
| 2022-12-09T01:55:07
| 2022-12-09T01:55:07
| 91,460,490
| 169
| 38
|
MIT
| 2019-01-06T05:51:59
| 2017-05-16T13:17:17
|
Stata
|
UTF-8
|
C
| false
| false
| 3,508
|
h
|
vce.h
|
#ifndef GREGRESS_VCE
#define GREGRESS_VCE
// Finite sample adjustment
// ------------------------
typedef ST_double (*gf_regress_vceadj)(
GT_size,
GT_size,
GT_size,
ST_double *
);
ST_double gf_regress_vceadj_ols_robust (GT_size N, GT_size kmodel, GT_size J, ST_double *w);
ST_double gf_regress_vceadj_ols_cluster (GT_size N, GT_size kmodel, GT_size J, ST_double *w);
ST_double gf_regress_vceadj_mle_robust (GT_size N, GT_size kmodel, GT_size J, ST_double *w);
ST_double gf_regress_vceadj_mle_cluster (GT_size N, GT_size kmodel, GT_size J, ST_double *w);
ST_double gf_regress_vceadj_ols_robust_fw (GT_size N, GT_size kmodel, GT_size J, ST_double *w);
ST_double gf_regress_vceadj_ols_cluster_fw (GT_size N, GT_size kmodel, GT_size J, ST_double *w);
ST_double gf_regress_vceadj_mle_robust_fw (GT_size N, GT_size kmodel, GT_size J, ST_double *w);
ST_double gf_regress_vceadj_mle_cluster_fw (GT_size N, GT_size kmodel, GT_size J, ST_double *w);
// Homoskedastic
// -------------
void (*gf_regress_ols_se) (ST_double *, ST_double *, ST_double *, ST_double *, GT_size *, GT_size, GT_size, GT_size);
void gf_regress_ols_seunw (ST_double *e, ST_double *w, ST_double *V, ST_double *se, GT_size *colix, GT_size N, GT_size kx, GT_size kmodel);
void gf_regress_ols_sew (ST_double *e, ST_double *w, ST_double *V, ST_double *se, GT_size *colix, GT_size N, GT_size kx, GT_size kmodel);
void gf_regress_ols_sefw (ST_double *e, ST_double *w, ST_double *V, ST_double *se, GT_size *colix, GT_size N, GT_size kx, GT_size kmodel);
void gf_regress_ols_copyvcov (ST_double *V, ST_double *XX, GT_size kx, GT_size *colix);
// Robust SE
// ---------
void (*gf_regress_ols_robust) (
ST_double *,
ST_double *,
ST_double *,
ST_double *,
ST_double *,
ST_double *,
ST_double *,
GT_size *,
GT_size,
GT_size,
GT_size,
gf_regress_vceadj
);
void gf_regress_ols_robust_colmajor (ST_double *e, ST_double *w, ST_double *V, ST_double *VV, ST_double *X, ST_double *XX, ST_double *se, GT_size *colix, GT_size N, GT_size kx, GT_size kmodel, gf_regress_vceadj vceadj);
void gf_regress_ols_robust_wcolmajor (ST_double *e, ST_double *w, ST_double *V, ST_double *VV, ST_double *X, ST_double *XX, ST_double *se, GT_size *colix, GT_size N, GT_size kx, GT_size kmodel, gf_regress_vceadj vceadj);
void gf_regress_ols_robust_fwcolmajor (ST_double *e, ST_double *w, ST_double *V, ST_double *VV, ST_double *X, ST_double *XX, ST_double *se, GT_size *colix, GT_size N, GT_size kx, GT_size kmodel, gf_regress_vceadj vceadj);
// Cluster SE
// ----------
void (*gf_regress_ols_cluster) (
ST_double *,
ST_double *,
GT_size *,
GT_size *,
GT_size,
ST_double *,
GT_size *,
ST_double *,
ST_double *,
ST_double *,
ST_double *,
ST_double *,
GT_size *,
GT_size,
GT_size,
GT_size,
gf_regress_vceadj
);
void gf_regress_ols_cluster_colmajor (ST_double *e, ST_double *w, GT_size *info, GT_size *index, GT_size J, ST_double *U, GT_size *ux, ST_double *V, ST_double *VV, ST_double *X, ST_double *XX, ST_double *se, GT_size *colix, GT_size N, GT_size kx, GT_size kmodel, gf_regress_vceadj vceadj);
void gf_regress_ols_cluster_wcolmajor (ST_double *e, ST_double *w, GT_size *info, GT_size *index, GT_size J, ST_double *U, GT_size *ux, ST_double *V, ST_double *VV, ST_double *X, ST_double *XX, ST_double *se, GT_size *colix, GT_size N, GT_size kx, GT_size kmodel, gf_regress_vceadj vceadj);
#endif
|
fc5ea1bc3594688660ec51a526f95256f2018ffd
|
6832a9c81b16ead373325f70fb97753d6a211539
|
/src/libtools/myfts.c
|
fc23d38f0b44c466aa4f4cd2ddf96bb09486d5e1
|
[
"MIT"
] |
permissive
|
ptitSeb/box86
|
2d3a0c4574905ff8d9dc7b5afb5444a273832bd6
|
ad934455c1b40feeebe5e6bd09b9063519102859
|
refs/heads/master
| 2023-08-22T05:30:54.331500
| 2023-08-20T13:01:58
| 2023-08-20T13:01:58
| 164,844,546
| 2,877
| 294
|
MIT
| 2023-07-27T11:19:10
| 2019-01-09T10:49:32
|
C
|
UTF-8
|
C
| false
| false
| 5,542
|
c
|
myfts.c
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <syscall.h>
#include <stddef.h>
#include <stdarg.h>
#include <fts.h>
#include "box86context.h"
#include "debug.h"
#include "x86emu.h"
#include "emu/x86emu_private.h"
#include "signals.h"
#include "box86stack.h"
#include "dynarec.h"
#include "callback.h"
#include "myalign.h"
#include "bridge.h"
#include "custommem.h"
#include "khash.h"
// kh_ftsent_t store each ftsent conversion from native -> x86
KHASH_MAP_INIT_INT(ftsent, x86_ftsent_t*)
// kh_fts_t store a kh_ftsent_t for each fts...
KHASH_MAP_INIT_INT(fts, kh_ftsent_t*)
#define SUPER() \
GO(0) \
GO(1) \
GO(2) \
GO(3)
// compare
#ifdef NOALIGN
#define GO(A) \
static uintptr_t my_compare_fct_##A = 0; \
static int my_compare_##A(FTSENT* a, FTSENT* b) \
{ \
return (int)RunFunctionFmt(my_compare_fct_##A, "pp", a, b); \
}
#else
#define GO(A) \
static uintptr_t my_compare_fct_##A = 0; \
static int my_compare_##A(FTSENT* a, FTSENT* b) \
{ \
x86_ftsent_t x86_a, x86_b; \
UnalignFTSENT(&x86_a, a); \
UnalignFTSENT(&x86_b, b); \
return (int)RunFunctionFmt(my_compare_fct_##A, "pp", x86_a, x86_b); \
}
#endif
SUPER()
#undef GO
static void* findcompareFct(void* fct)
{
if(!fct) return fct;
if(GetNativeFnc((uintptr_t)fct)) return GetNativeFnc((uintptr_t)fct);
#define GO(A) if(my_compare_fct_##A == (uintptr_t)fct) return my_compare_##A;
SUPER()
#undef GO
#define GO(A) if(my_compare_fct_##A == 0) {my_compare_fct_##A = (uintptr_t)fct; return my_compare_##A; }
SUPER()
#undef GO
printf_log(LOG_NONE, "Warning, no more slot for libpng12 compare callback\n");
return NULL;
}
#undef SUPER
#ifndef NOALIGN
kh_ftsent_t* getFtsentMap(box86context_t* context, void* ftsp)
{
khint_t k;
int ret;
kh_fts_t *ftsmap = context->ftsmap;
k = kh_get(fts, ftsmap, (uintptr_t)ftsp);
if(k==kh_end(ftsmap)) {
k = kh_put(fts, ftsmap, (uintptr_t)ftsp, &ret);
kh_value(ftsmap, k) = kh_init(ftsent);
}
return kh_value(ftsmap, k);
}
int existFtsent(box86context_t* context, void* ftsp, FTSENT* ftsent)
{
khint_t k;
kh_ftsent_t *ftsentMap = getFtsentMap(context, ftsp);
k = kh_get(ftsent, ftsentMap, (uintptr_t)ftsent);
return (k==kh_end(ftsentMap))?0:1;
}
x86_ftsent_t* getFtsent(kh_ftsent_t* ftsentMap, FTSENT* ftsent, int dolink)
{
if(!ftsent)
return NULL;
khint_t k;
int ret;
k = kh_get(ftsent, ftsentMap, (uintptr_t)ftsent);
if(k!=kh_end(ftsentMap))
return kh_value(ftsentMap, k);
// new value... so need convertion & alignment
k = kh_put(ftsent, ftsentMap, (uintptr_t)ftsent, &ret);
x86_ftsent_t *x86ftsent = kh_value(ftsentMap, k) = (x86_ftsent_t*)box_malloc(sizeof(x86_ftsent_t));
UnalignFTSENT(x86ftsent, ftsent); // unalign
// handle the 3 embedded ftsent...
if(ftsent->fts_info<=14 && ftsent->fts_info!=7) { //14 is max value, 7 is err
if(ftsent->fts_info == FTS_DC)
x86ftsent->fts_cycle = getFtsent(ftsentMap, ftsent->fts_cycle, dolink);
if(ftsent->fts_level>=0) {
x86ftsent->fts_parent = getFtsent(ftsentMap, ftsent->fts_parent, dolink);
if(dolink)
x86ftsent->fts_link = getFtsent(ftsentMap, ftsent->fts_link, dolink);
}
}
return x86ftsent;
}
void freeFts(box86context_t* context, void* ftsp)
{
khint_t k;
kh_fts_t *ftsmap = context->ftsmap;
k = kh_get(fts, ftsmap, (uintptr_t)ftsp);
if(k==kh_end(ftsmap))
return; // nothing to do...
kh_ftsent_t *ftsentMap = kh_value(ftsmap, k);
x86_ftsent_t* x86ftsent;
kh_foreach_value(ftsentMap, x86ftsent, box_free(x86ftsent));
kh_destroy(ftsent, ftsentMap);
kh_del(fts, ftsmap, k);
}
#endif
EXPORT void* my_fts_open(x86emu_t* emu, void* path, int options, void* compare_fn)
{
(void)emu;
return fts_open(path, options, findcompareFct(compare_fn));
}
EXPORT int my_fts_close(x86emu_t* emu, void* ftsp)
{
#ifndef NOALIGN
freeFts(emu->context, ftsp);
#else
(void)emu;
#endif
return fts_close(ftsp);
}
EXPORT void* my_fts_read(x86emu_t* emu, void* ftsp)
{
#ifdef NOALIGN
(void)emu;
return fts_read(ftsp);
#else
return getFtsent(getFtsentMap(emu->context, ftsp), fts_read(ftsp), 0);
#endif
}
EXPORT void* my_fts_children(x86emu_t* emu, void* ftsp, int options)
{
#ifdef NOALIGN
(void)emu;
return fts_children(ftsp, options);
#else
return getFtsent(getFtsentMap(emu->context, ftsp), fts_children(ftsp, options), 1);
#endif
}
void InitFTSMap(box86context_t* context)
{
#ifndef NOALIGN
context->ftsmap = kh_init(fts);
#else
(void)context;
#endif
}
void FreeFTSMap(box86context_t* context)
{
#ifndef NOALIGN
uintptr_t ptr;
kh_ftsent_t *ftsentMap;
(void)ftsentMap;
kh_foreach(context->ftsmap, ptr, ftsentMap, freeFts(context, (FTSENT*)ptr));
kh_destroy(fts, context->ftsmap);
#else
(void)context;
#endif
}
|
68bed3b60d4fd5571ac1b2de21ea0271667a89e2
|
321d11eaee885ceb3a74db0a062f9bbdf282148c
|
/ssl/d1_srtp.c
|
6228fe1871e71add5eccc414677e9bc50778b573
|
[
"Apache-2.0",
"OpenSSL",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
openssl/openssl
|
75691ebaae957793f2ff0673f77545277dfb3988
|
5318c012885a5382eadbf95aa9c1d35664bca819
|
refs/heads/master
| 2023-09-03T15:22:52.727123
| 2023-09-01T07:10:49
| 2023-09-02T14:30:01
| 7,634,677
| 24,148
| 11,569
|
Apache-2.0
| 2023-09-14T19:48:11
| 2013-01-15T22:34:48
|
C
|
UTF-8
|
C
| false
| false
| 4,443
|
c
|
d1_srtp.c
|
/*
* Copyright 2011-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* DTLS code by Eric Rescorla <ekr@rtfm.com>
*
* Copyright (C) 2006, Network Resonance, Inc. Copyright (C) 2011, RTFM, Inc.
*/
#include <stdio.h>
#include <openssl/objects.h>
#include "ssl_local.h"
#include "quic/quic_local.h"
#ifndef OPENSSL_NO_SRTP
static SRTP_PROTECTION_PROFILE srtp_known_profiles[] = {
{
"SRTP_AES128_CM_SHA1_80",
SRTP_AES128_CM_SHA1_80,
},
{
"SRTP_AES128_CM_SHA1_32",
SRTP_AES128_CM_SHA1_32,
},
{
"SRTP_AEAD_AES_128_GCM",
SRTP_AEAD_AES_128_GCM,
},
{
"SRTP_AEAD_AES_256_GCM",
SRTP_AEAD_AES_256_GCM,
},
{
"SRTP_DOUBLE_AEAD_AES_128_GCM_AEAD_AES_128_GCM",
SRTP_DOUBLE_AEAD_AES_128_GCM_AEAD_AES_128_GCM,
},
{
"SRTP_DOUBLE_AEAD_AES_256_GCM_AEAD_AES_256_GCM",
SRTP_DOUBLE_AEAD_AES_256_GCM_AEAD_AES_256_GCM,
},
{
"SRTP_ARIA_128_CTR_HMAC_SHA1_80",
SRTP_ARIA_128_CTR_HMAC_SHA1_80,
},
{
"SRTP_ARIA_128_CTR_HMAC_SHA1_32",
SRTP_ARIA_128_CTR_HMAC_SHA1_32,
},
{
"SRTP_ARIA_256_CTR_HMAC_SHA1_80",
SRTP_ARIA_256_CTR_HMAC_SHA1_80,
},
{
"SRTP_ARIA_256_CTR_HMAC_SHA1_32",
SRTP_ARIA_256_CTR_HMAC_SHA1_32,
},
{
"SRTP_AEAD_ARIA_128_GCM",
SRTP_AEAD_ARIA_128_GCM,
},
{
"SRTP_AEAD_ARIA_256_GCM",
SRTP_AEAD_ARIA_256_GCM,
},
{0}
};
static int find_profile_by_name(char *profile_name,
SRTP_PROTECTION_PROFILE **pptr, size_t len)
{
SRTP_PROTECTION_PROFILE *p;
p = srtp_known_profiles;
while (p->name) {
if ((len == strlen(p->name))
&& strncmp(p->name, profile_name, len) == 0) {
*pptr = p;
return 0;
}
p++;
}
return 1;
}
static int ssl_ctx_make_profiles(const char *profiles_string,
STACK_OF(SRTP_PROTECTION_PROFILE) **out)
{
STACK_OF(SRTP_PROTECTION_PROFILE) *profiles;
char *col;
char *ptr = (char *)profiles_string;
SRTP_PROTECTION_PROFILE *p;
if ((profiles = sk_SRTP_PROTECTION_PROFILE_new_null()) == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES);
return 1;
}
do {
col = strchr(ptr, ':');
if (!find_profile_by_name(ptr, &p, col ? (size_t)(col - ptr)
: strlen(ptr))) {
if (sk_SRTP_PROTECTION_PROFILE_find(profiles, p) >= 0) {
ERR_raise(ERR_LIB_SSL, SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
goto err;
}
if (!sk_SRTP_PROTECTION_PROFILE_push(profiles, p)) {
ERR_raise(ERR_LIB_SSL, SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES);
goto err;
}
} else {
ERR_raise(ERR_LIB_SSL, SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE);
goto err;
}
if (col)
ptr = col + 1;
} while (col);
sk_SRTP_PROTECTION_PROFILE_free(*out);
*out = profiles;
return 0;
err:
sk_SRTP_PROTECTION_PROFILE_free(profiles);
return 1;
}
int SSL_CTX_set_tlsext_use_srtp(SSL_CTX *ctx, const char *profiles)
{
if (IS_QUIC_METHOD(ctx->method))
return 1;
return ssl_ctx_make_profiles(profiles, &ctx->srtp_profiles);
}
int SSL_set_tlsext_use_srtp(SSL *s, const char *profiles)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
if (sc == NULL)
return 1;
return ssl_ctx_make_profiles(profiles, &sc->srtp_profiles);
}
STACK_OF(SRTP_PROTECTION_PROFILE) *SSL_get_srtp_profiles(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
if (sc != NULL) {
if (sc->srtp_profiles != NULL) {
return sc->srtp_profiles;
} else if ((s->ctx != NULL) && (s->ctx->srtp_profiles != NULL)) {
return s->ctx->srtp_profiles;
}
}
return NULL;
}
SRTP_PROTECTION_PROFILE *SSL_get_selected_srtp_profile(SSL *s)
{
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
if (sc == NULL)
return 0;
return sc->srtp_profile;
}
#endif
|
97f4ed1685322a8d82401ccc8ef532c72633d772
|
b452bbb87214f174122f425f6f98f4c3890c3cca
|
/internal/ccall/neatogen/matinv.c
|
35b56df2a6ce73649f121d4e3c6fda4fdce10316
|
[
"EPL-1.0",
"MIT"
] |
permissive
|
goccy/go-graphviz
|
bea9bc86b42734aff7ffae283aeae71702ca588a
|
865af036ddbb745c4424bbd2fdaa9a75668cf0d4
|
refs/heads/master
| 2023-07-20T08:05:39.868377
| 2023-03-21T23:49:44
| 2023-03-21T23:49:44
| 236,740,615
| 511
| 66
|
MIT
| 2023-07-07T13:53:28
| 2020-01-28T13:24:09
|
Go
|
UTF-8
|
C
| false
| false
| 2,115
|
c
|
matinv.c
|
/* $Id$ $Revision$ */
/* vim:set shiftwidth=4 ts=8: */
/*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************/
/*
* This code was (mostly) written by Ken Turkowski, who said:
*
* Oh, that. I wrote it in college the first time. It's open source - I think I
* posted it after seeing so many people solve equations by inverting matrices
* by computing minors naïvely.
* -Ken
*
* The views represented here are mine and are not necessarily shared by
* my employer.
Ken Turkowski turk@apple.com
Immersive Media Technologist http://www.worldserver.com/turk/
Apple Computer, Inc.
1 Infinite Loop, MS 302-3VR
Cupertino, CA 95014
*/
/* Matinv() inverts the matrix A using LU decomposition. Arguments:
* A - the (n x n) matrix to be inverted
* Ainv - the (n x n) inverted matrix
* n - the order of the matrices A and Ainv
*/
#include <stdlib.h>
#include "render.h"
extern int lu_decompose(double **a, int n);
extern void lu_solve(double *x, double *b, int n);
int matinv(double **A, double **Ainv, int n)
{
register int i, j;
double *b, temp;
/* Decompose matrix into L and U triangular matrices */
if (lu_decompose(A, n) == 0)
return (0); /* Singular */
/* Invert matrix by solving n simultaneous equations n times */
b = N_NEW(n, double);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
b[j] = 0.0;
b[i] = 1.0;
lu_solve(Ainv[i], b, n); /* Into a row of Ainv: fix later */
}
free(b);
/* Transpose matrix */
for (i = 0; i < n; i++) {
for (j = 0; j < i; j++) {
temp = Ainv[i][j];
Ainv[i][j] = Ainv[j][i];
Ainv[j][i] = temp;
}
}
return (1);
}
|
4bc6f0674fa7749ef2a7de6add42b0c464586bdc
|
71e688f2915b29137bada1383976c072e154e276
|
/include/swizzle/hlsl++_matrix_row0_1.h
|
a606fc4632001144e254ef84436cf158ba510d16
|
[
"MIT"
] |
permissive
|
redorav/hlslpp
|
fa12a46b408fdc150d84589ce1e86a2f868b521a
|
0c9822d2aa896f4450961ecd70fba87f9f8b20e0
|
refs/heads/master
| 2023-08-21T14:30:46.505535
| 2023-08-16T19:40:02
| 2023-08-16T19:40:02
| 80,052,246
| 433
| 40
|
MIT
| 2023-09-03T09:24:56
| 2017-01-25T19:59:55
|
C++
|
UTF-8
|
C
| false
| false
| 695
|
h
|
hlsl++_matrix_row0_1.h
|
// -------------------------------
// _mNM
// -------------------------------
hlslpp_swizzle_start swizzle1<0> _m00; hlslpp_swizzle_end
hlslpp_swizzle_start swizzle2<0, 0> _m00_m00; hlslpp_swizzle_end
hlslpp_swizzle_start swizzle3<0, 0, 0> _m00_m00_m00; hlslpp_swizzle_end
hlslpp_swizzle_start swizzle4<0, 0, 0, 0> _m00_m00_m00_m00; hlslpp_swizzle_end
// -------------------------------
// _NM
// -------------------------------
hlslpp_swizzle_start swizzle1<0> _11; hlslpp_swizzle_end
hlslpp_swizzle_start swizzle2<0, 0> _11_11; hlslpp_swizzle_end
hlslpp_swizzle_start swizzle3<0, 0, 0> _11_11_11; hlslpp_swizzle_end
hlslpp_swizzle_start swizzle4<0, 0, 0, 0> _11_11_11_11; hlslpp_swizzle_end
|
455fb1500ab037939f8ee5f1163783f3b2d3d49d
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/usr.sbin/dhcrelay6/packet.c
|
6f634282d37d8baedd2dc754251b1115d4de1d00
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 6,669
|
c
|
packet.c
|
/* $OpenBSD: packet.c,v 1.1 2017/03/17 14:45:16 rzalamena Exp $ */
/* Packet assembly code, originally contributed by Archie Cobbs. */
/*
* Copyright (c) 1995, 1996, 1999 The Internet Software Consortium.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of The Internet Software Consortium 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 INTERNET SOFTWARE CONSORTIUM AND
* CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM 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.
*
* This software has been written for the Internet Software Consortium
* by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
* Enterprises. To learn more about the Internet Software Consortium,
* see ``http://www.vix.com/isc''. To learn more about Vixie
* Enterprises, see ``http://www.vix.com''.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/udp.h>
#include <netinet/if_ether.h>
#include <string.h>
#include "dhcp.h"
#include "dhcpd.h"
#include "log.h"
u_int32_t checksum(unsigned char *, unsigned, u_int32_t);
u_int32_t wrapsum(u_int32_t);
u_int32_t
checksum(unsigned char *buf, unsigned nbytes, u_int32_t sum)
{
unsigned int i;
/* Checksum all the pairs of bytes first... */
for (i = 0; i < (nbytes & ~1U); i += 2) {
sum += (u_int16_t)ntohs(*((u_int16_t *)(buf + i)));
if (sum > 0xFFFF)
sum -= 0xFFFF;
}
/*
* If there's a single byte left over, checksum it, too.
* Network byte order is big-endian, so the remaining byte is
* the high byte.
*/
if (i < nbytes) {
sum += buf[i] << 8;
if (sum > 0xFFFF)
sum -= 0xFFFF;
}
return (sum);
}
u_int32_t
wrapsum(u_int32_t sum)
{
sum = ~sum & 0xFFFF;
return (htons(sum));
}
void
assemble_hw_header(unsigned char *buf, int *bufix, struct packet_ctx *pc)
{
struct ether_header eh;
memcpy(eh.ether_shost, pc->pc_smac, ETHER_ADDR_LEN);
memcpy(eh.ether_dhost, pc->pc_dmac, ETHER_ADDR_LEN);
eh.ether_type = htons(pc->pc_ethertype);
memcpy(&buf[*bufix], &eh, ETHER_HDR_LEN);
*bufix += ETHER_HDR_LEN;
}
void
assemble_udp_ip6_header(unsigned char *p, int *off, struct packet_ctx *pc,
unsigned char *payload, int plen)
{
struct ip6_hdr ip6;
struct udphdr uh;
memset(&ip6, 0, sizeof(ip6));
ip6.ip6_vfc = IPV6_VERSION;
ip6.ip6_nxt = IPPROTO_UDP;
ip6.ip6_src = ss2sin6(&pc->pc_src)->sin6_addr;
ip6.ip6_dst = ss2sin6(&pc->pc_dst)->sin6_addr;
ip6.ip6_plen = htons(sizeof(uh) + plen);
ip6.ip6_hlim = 64;
memcpy(&p[*off], &ip6, sizeof(ip6));
*off += sizeof(ip6);
memset(&uh, 0, sizeof(uh));
uh.uh_ulen = ip6.ip6_plen;
uh.uh_sport = ss2sin6(&pc->pc_src)->sin6_port;
uh.uh_dport = ss2sin6(&pc->pc_dst)->sin6_port;
uh.uh_sum = wrapsum(
checksum((unsigned char *)&uh, sizeof(uh),
checksum(payload, plen,
checksum((unsigned char *)&ip6.ip6_src, sizeof(ip6.ip6_src),
checksum((unsigned char *)&ip6.ip6_dst, sizeof(ip6.ip6_dst),
IPPROTO_UDP + ntohs(ip6.ip6_plen)
))))
);
memcpy(&p[*off], &uh, sizeof(uh));
*off += sizeof(uh);
}
ssize_t
decode_hw_header(unsigned char *buf, int bufix, struct packet_ctx *pc)
{
struct ether_header *ether;
ether = (struct ether_header *)(buf + bufix);
memcpy(pc->pc_dmac, ether->ether_dhost, ETHER_ADDR_LEN);
memcpy(pc->pc_smac, ether->ether_shost, ETHER_ADDR_LEN);
pc->pc_ethertype = ntohs(ether->ether_type);
pc->pc_htype = ARPHRD_ETHER;
pc->pc_hlen = ETHER_ADDR_LEN;
return sizeof(struct ether_header);
}
ssize_t
decode_udp_ip6_header(unsigned char *p, int off, struct packet_ctx *pc,
size_t plen)
{
struct ip6_hdr *ip6;
struct udphdr *uh;
struct in6_addr *asrc, *adst;
size_t ptotal, poff = 0;
uint16_t ocksum, cksum;
/* Check the IPv6 header. */
if (plen < sizeof(*ip6)) {
log_debug("package too small (%ld)", plen);
return -1;
}
ip6 = (struct ip6_hdr *)(p + off);
if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
log_debug("invalid IPv6 version");
return -1;
}
poff += sizeof(*ip6);
ptotal = ntohs(ip6->ip6_plen);
if (ptotal > plen) {
log_debug("expected %ld bytes, but got %ld", ptotal, plen);
return (-1);
}
pc->pc_src.ss_len = sizeof(struct sockaddr_in6);
pc->pc_src.ss_family = AF_INET6;
asrc = &ss2sin6(&pc->pc_src)->sin6_addr;
memcpy(asrc, &ip6->ip6_src, sizeof(*asrc));
pc->pc_dst.ss_len = sizeof(struct sockaddr_in6);
pc->pc_dst.ss_family = AF_INET6;
adst = &ss2sin6(&pc->pc_dst)->sin6_addr;
memcpy(adst, &ip6->ip6_dst, sizeof(*adst));
/* Deal with the UDP header. */
if (ip6->ip6_nxt != IPPROTO_UDP) {
/* We don't support skipping extensions yet. */
log_debug("expected UDP header, got %#02X", ip6->ip6_nxt);
return -1;
}
uh = (struct udphdr *)((uint8_t *)ip6 + sizeof(*ip6));
ss2sin6(&pc->pc_src)->sin6_port = uh->uh_sport;
ss2sin6(&pc->pc_dst)->sin6_port = uh->uh_dport;
ocksum = uh->uh_sum;
uh->uh_sum = 0;
poff += sizeof(*uh);
/* Validate the packet. */
cksum = wrapsum(
checksum((unsigned char *)asrc, sizeof(*asrc),
checksum((unsigned char *)adst, sizeof(*adst),
checksum((unsigned char *)uh, sizeof(*uh),
checksum(p + off + poff, ptotal - sizeof(*uh),
IPPROTO_UDP + ntohs(uh->uh_ulen)))))
);
if (ocksum != cksum) {
log_debug("checksum invalid (%#04x != %#04x)",
ocksum, cksum);
return -1;
}
return poff;
}
|
5c92197e9ac447a21906d9f6f9cd19928a4a8cc9
|
2c73a693c2b3c162eae2ab94f649d8c4494878ba
|
/components/lvgl/lv_demos/src/lv_ex_widgets/lv_ex_linemeter/lv_ex_linemeter_1.c
|
6cfc0221176d157e8fa68ffa9d0a5d5bde4a4709
|
[
"MIT"
] |
permissive
|
openLuat/LuatOS
|
185e1e140aed908434168133571ddcafe98f4e12
|
4b29d5121ab4f7133630331e8502c526c7856897
|
refs/heads/master
| 2023-08-23T04:57:23.263539
| 2023-08-23T04:46:46
| 2023-08-23T04:46:46
| 230,403,844
| 378
| 93
|
MIT
| 2021-12-17T02:19:30
| 2019-12-27T08:29:19
|
C
|
UTF-8
|
C
| false
| false
| 565
|
c
|
lv_ex_linemeter_1.c
|
#include "../../../lv_examples.h"
#if LV_USE_LINEMETER
void lv_ex_linemeter_1(void)
{
/*Create a line meter */
lv_obj_t * lmeter;
lmeter = lv_linemeter_create(lv_scr_act(), NULL);
lv_linemeter_set_range(lmeter, 0, 100); /*Set the range*/
lv_linemeter_set_value(lmeter, 80); /*Set the current value*/
lv_linemeter_set_scale(lmeter, 240, 21); /*Set the angle and number of lines*/
lv_obj_set_size(lmeter, 150, 150);
lv_obj_align(lmeter, NULL, LV_ALIGN_CENTER, 0, 0);
}
#endif
|
39faab2b99f1e77022daf794cca61eac99c8bafd
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/wayland-protocols/gtk/gtk/gtkbuilder.c
|
e06fda638a7a429c695d2029982c20bcea6e0bfe
|
[
"LGPL-2.0-only",
"Apache-2.0",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 96,272
|
c
|
gtkbuilder.c
|
/* GTK - The GIMP Toolkit
* Copyright (C) 1998-2002 James Henstridge <james@daa.com.au>
* Copyright (C) 2006-2007 Async Open Source,
* Johan Dahlin <jdahlin@async.com.br>,
* Henrique Romano <henrique@async.com.br>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* GtkBuilder:
*
* A `GtkBuilder` reads XML descriptions of a user interface and
* instantiates the described objects.
*
* To create a `GtkBuilder` from a user interface description, call
* [ctor@Gtk.Builder.new_from_file], [ctor@Gtk.Builder.new_from_resource]
* or [ctor@Gtk.Builder.new_from_string].
*
* In the (unusual) case that you want to add user interface
* descriptions from multiple sources to the same `GtkBuilder` you can
* call [ctor@Gtk.Builder.new] to get an empty builder and populate it by
* (multiple) calls to [method@Gtk.Builder.add_from_file],
* [method@Gtk.Builder.add_from_resource] or
* [method@Gtk.Builder.add_from_string].
*
* A `GtkBuilder` holds a reference to all objects that it has constructed
* and drops these references when it is finalized. This finalization can
* cause the destruction of non-widget objects or widgets which are not
* contained in a toplevel window. For toplevel windows constructed by a
* builder, it is the responsibility of the user to call
* [method@Gtk.Window.destroy] to get rid of them and all the widgets
* they contain.
*
* The functions [method@Gtk.Builder.get_object] and
* [method@Gtk.Builder.get_objects] can be used to access the widgets in
* the interface by the names assigned to them inside the UI description.
* Toplevel windows returned by these functions will stay around until the
* user explicitly destroys them with [method@Gtk.Window.destroy]. Other
* widgets will either be part of a larger hierarchy constructed by the
* builder (in which case you should not have to worry about their lifecycle),
* or without a parent, in which case they have to be added to some container
* to make use of them. Non-widget objects need to be reffed with
* g_object_ref() to keep them beyond the lifespan of the builder.
*
* # GtkBuilder UI Definitions
*
* `GtkBuilder` parses textual descriptions of user interfaces which are
* specified in XML format. We refer to these descriptions as “GtkBuilder
* UI definitions” or just “UI definitions” if the context is clear.
*
* The toplevel element is `<interface>`. It optionally takes a “domain”
* attribute, which will make the builder look for translated strings
* using `dgettext()` in the domain specified. This can also be done by
* calling [method@Gtk.Builder.set_translation_domain] on the builder.
*
* Objects are described by `<object>` elements, which can contain
* `<property>` elements to set properties, `<signal>` elements which
* connect signals to handlers, and `<child>` elements, which describe
* child objects (most often widgets inside a container, but also e.g.
* actions in an action group, or columns in a tree model). A `<child>`
* element contains an `<object>` element which describes the child object.
*
* The target toolkit version(s) are described by `<requires>` elements,
* the “lib” attribute specifies the widget library in question (currently
* the only supported value is “gtk”) and the “version” attribute specifies
* the target version in the form “`<major>`.`<minor>`”. `GtkBuilder` will
* error out if the version requirements are not met.
*
* Typically, the specific kind of object represented by an `<object>`
* element is specified by the “class” attribute. If the type has not
* been loaded yet, GTK tries to find the `get_type()` function from the
* class name by applying heuristics. This works in most cases, but if
* necessary, it is possible to specify the name of the `get_type()`
* function explicitly with the "type-func" attribute.
*
* Objects may be given a name with the “id” attribute, which allows the
* application to retrieve them from the builder with
* [method@Gtk.Builder.get_object]. An id is also necessary to use the
* object as property value in other parts of the UI definition. GTK
* reserves ids starting and ending with `___` (three consecutive
* underscores) for its own purposes.
*
* Setting properties of objects is pretty straightforward with the
* `<property>` element: the “name” attribute specifies the name of the
* property, and the content of the element specifies the value.
* If the “translatable” attribute is set to a true value, GTK uses
* `gettext()` (or `dgettext()` if the builder has a translation domain set)
* to find a translation for the value. This happens before the value
* is parsed, so it can be used for properties of any type, but it is
* probably most useful for string properties. It is also possible to
* specify a context to disambiguate short strings, and comments which
* may help the translators.
*
* `GtkBuilder` can parse textual representations for the most common
* property types: characters, strings, integers, floating-point numbers,
* booleans (strings like “TRUE”, “t”, “yes”, “y”, “1” are interpreted
* as %TRUE, strings like “FALSE”, “f”, “no”, “n”, “0” are interpreted
* as %FALSE), enumerations (can be specified by their name, nick or
* integer value), flags (can be specified by their name, nick, integer
* value, optionally combined with “|”, e.g.
* “GTK_INPUT_HINT_EMOJI|GTK_INPUT_HINT_LOWERCASE”)
* and colors (in a format understood by [method@Gdk.RGBA.parse]).
*
* `GVariant`s can be specified in the format understood by
* g_variant_parse(), and pixbufs can be specified as a filename of an
* image file to load.
*
* Objects can be referred to by their name and by default refer to
* objects declared in the local XML fragment and objects exposed via
* [method@Gtk.Builder.expose_object]. In general, `GtkBuilder` allows
* forward references to objects — declared in the local XML; an object
* doesn’t have to be constructed before it can be referred to. The
* exception to this rule is that an object has to be constructed before
* it can be used as the value of a construct-only property.
*
* It is also possible to bind a property value to another object's
* property value using the attributes "bind-source" to specify the
* source object of the binding, and optionally, "bind-property" and
* "bind-flags" to specify the source property and source binding flags
* respectively. Internally, `GtkBuilder` implements this using `GBinding`
* objects. For more information see g_object_bind_property().
*
* Sometimes it is necessary to refer to widgets which have implicitly
* been constructed by GTK as part of a composite widget, to set
* properties on them or to add further children (e.g. the content area
* of a `GtkDialog`). This can be achieved by setting the “internal-child”
* property of the `<child>` element to a true value. Note that #GtkBuilder
* still requires an `<object>` element for the internal child, even if it
* has already been constructed.
*
* A number of widgets have different places where a child can be added
* (e.g. tabs vs. page content in notebooks). This can be reflected in
* a UI definition by specifying the “type” attribute on a `<child>`
* The possible values for the “type” attribute are described in the
* sections describing the widget-specific portions of UI definitions.
*
* # Signal handlers and function pointers
*
* Signal handlers are set up with the `<signal>` element. The “name”
* attribute specifies the name of the signal, and the “handler” attribute
* specifies the function to connect to the signal.
* The remaining attributes, “after”, “swapped” and “object”, have the
* same meaning as the corresponding parameters of the
* g_signal_connect_object() or g_signal_connect_data() functions. A
* “last_modification_time” attribute is also allowed, but it does not
* have a meaning to the builder.
*
* If you rely on `GModule` support to lookup callbacks in the symbol table,
* the following details should be noted:
*
* When compiling applications for Windows, you must declare signal callbacks
* with %G_MODULE_EXPORT, or they will not be put in the symbol table.
* On Linux and Unix, this is not necessary; applications should instead
* be compiled with the -Wl,--export-dynamic `CFLAGS`, and linked against
* `gmodule-export-2.0`.
*
* # A GtkBuilder UI Definition
*
* ```xml
* <interface>
* <object class="GtkDialog" id="dialog1">
* <child internal-child="vbox">
* <object class="GtkBox" id="vbox1">
* <child internal-child="action_area">
* <object class="GtkBox" id="hbuttonbox1">
* <child>
* <object class="GtkButton" id="ok_button">
* <property name="label">gtk-ok</property>
* <signal name="clicked" handler="ok_button_clicked"/>
* </object>
* </child>
* </object>
* </child>
* </object>
* </child>
* </object>
* </interface>
* ```
*
* Beyond this general structure, several object classes define their
* own XML DTD fragments for filling in the ANY placeholders in the DTD
* above. Note that a custom element in a <child> element gets parsed by
* the custom tag handler of the parent object, while a custom element in
* an <object> element gets parsed by the custom tag handler of the object.
*
* These XML fragments are explained in the documentation of the
* respective objects.
*
* A `<template>` tag can be used to define a widget class’s components.
* See the [GtkWidget documentation](class.Widget.html#building-composite-widgets-from-template-xml) for details.
*/
#include "config.h"
#include <errno.h> /* errno */
#include <stdlib.h>
#include <string.h> /* strlen */
#include "gtkbuilderprivate.h"
#include "gdkpixbufutilsprivate.h"
#include "gtkbuildableprivate.h"
#include "gtkbuilderlistitemfactory.h"
#include "gtkbuilderscopeprivate.h"
#include "gtkdebug.h"
#include "gtkexpression.h"
#include "gtkmain.h"
#include "gtkicontheme.h"
#include "gtkintl.h"
#include "gtkprivate.h"
#include "gtkshortcutactionprivate.h"
#include "gtkshortcuttrigger.h"
#include "gtktestutils.h"
#include "gtktypebuiltins.h"
#include "gtkicontheme.h"
#include "gtkiconthemeprivate.h"
#include "gdkpixbufutilsprivate.h"
#include "gtkdebug.h"
static void gtk_builder_finalize (GObject *object);
static void gtk_builder_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec);
static void gtk_builder_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec);
enum {
PROP_0,
PROP_CURRENT_OBJECT,
PROP_SCOPE,
PROP_TRANSLATION_DOMAIN,
LAST_PROP
};
static GParamSpec *builder_props[LAST_PROP];
struct _GtkBuilder
{
GObject parent_instance;
};
struct _GtkBuilderClass
{
GObjectClass parent_class;
};
typedef struct
{
char *domain;
GHashTable *objects;
GSList *delayed_properties;
GPtrArray *signals;
GSList *bindings;
char *filename;
char *resource_prefix;
GType template_type;
GObject *current_object;
GtkBuilderScope *scope;
} GtkBuilderPrivate;
G_DEFINE_TYPE_WITH_PRIVATE (GtkBuilder, gtk_builder, G_TYPE_OBJECT)
static void
gtk_builder_dispose (GObject *object)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (GTK_BUILDER (object));
g_clear_object (&priv->current_object);
g_clear_object (&priv->scope);
G_OBJECT_CLASS (gtk_builder_parent_class)->dispose (object);
}
static void
gtk_builder_class_init (GtkBuilderClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->dispose = gtk_builder_dispose;
gobject_class->finalize = gtk_builder_finalize;
gobject_class->set_property = gtk_builder_set_property;
gobject_class->get_property = gtk_builder_get_property;
/**
* GtkBuilder:translation-domain: (attributes org.gtk.Property.get=gtk_builder_get_translation_domain org.gtk.Property.set=gtk_builder_set_translation_domain)
*
* The translation domain used when translating property values that
* have been marked as translatable.
*
* If the translation domain is %NULL, #GtkBuilder uses gettext(),
* otherwise g_dgettext().
*/
builder_props[PROP_TRANSLATION_DOMAIN] =
g_param_spec_string ("translation-domain",
P_("Translation Domain"),
P_("The translation domain used by gettext"),
NULL,
GTK_PARAM_READWRITE);
/**
* GtkBuilder:current-object: (attributes org.gtk.Property.get=gtk_builder_get_current_object org.gtk.Property.set=gtk_builder_set_current_object)
*
* The object the builder is evaluating for.
*/
builder_props[PROP_CURRENT_OBJECT] =
g_param_spec_object ("current-object",
P_("Current object"),
P_("The object the builder is evaluating for"),
G_TYPE_OBJECT,
GTK_PARAM_READWRITE);
/**
* GtkBuilder:scope: (attributes org.gtk.Property.get=gtk_builder_get_scope org.gtk.Property.set=gtk_builder_set_scope)
*
* The scope the builder is operating in
*/
builder_props[PROP_SCOPE] =
g_param_spec_object ("scope",
P_("Scope"),
P_("The scope the builder is operating in"),
GTK_TYPE_BUILDER_SCOPE,
GTK_PARAM_READWRITE | G_PARAM_CONSTRUCT);
g_object_class_install_properties (gobject_class, LAST_PROP, builder_props);
}
static void
gtk_builder_init (GtkBuilder *builder)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
priv->domain = NULL;
priv->objects = g_hash_table_new_full (g_str_hash, g_str_equal,
g_free, g_object_unref);
}
/*
* GObject virtual methods
*/
static void
gtk_builder_finalize (GObject *object)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (GTK_BUILDER (object));
g_free (priv->domain);
g_free (priv->filename);
g_free (priv->resource_prefix);
#ifdef G_ENABLE_DEBUG
if (GTK_DEBUG_CHECK (BUILDER_OBJECTS))
{
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init (&iter, priv->objects);
while (g_hash_table_iter_next (&iter, &key, &value))
{
if (G_OBJECT (value)->ref_count == 1)
g_message ("builder: %s with id %s unused",
G_OBJECT_TYPE_NAME (value), (const char *)key);
}
}
#endif
g_hash_table_destroy (priv->objects);
if (priv->signals)
g_ptr_array_free (priv->signals, TRUE);
G_OBJECT_CLASS (gtk_builder_parent_class)->finalize (object);
}
static void
gtk_builder_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GtkBuilder *builder = GTK_BUILDER (object);
switch (prop_id)
{
case PROP_CURRENT_OBJECT:
gtk_builder_set_current_object (builder, g_value_get_object (value));
break;
case PROP_SCOPE:
gtk_builder_set_scope (builder, g_value_get_object (value));
break;
case PROP_TRANSLATION_DOMAIN:
gtk_builder_set_translation_domain (builder, g_value_get_string (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gtk_builder_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GtkBuilder *builder = GTK_BUILDER (object);
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
switch (prop_id)
{
case PROP_CURRENT_OBJECT:
g_value_set_object (value, priv->current_object);
break;
case PROP_SCOPE:
g_value_set_object (value, priv->scope);
break;
case PROP_TRANSLATION_DOMAIN:
g_value_set_string (value, priv->domain);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/*
* GtkBuilder virtual methods
*/
typedef struct
{
char *object;
GParamSpec *pspec;
char *value;
int line;
int col;
} DelayedProperty;
typedef struct
{
GPtrArray *names;
GArray *values;
guint len;
} ObjectProperties;
static void
object_properties_init (ObjectProperties *self)
{
self->names = NULL;
self->values = NULL;
self->len = 0;
}
static void
object_properties_destroy (ObjectProperties *self)
{
if (self == NULL)
return;
if (self->names)
g_ptr_array_unref (self->names);
if (self->values)
g_array_unref (self->values);
self->len = 0;
}
static void
object_properties_add (ObjectProperties *self,
const char *name,
const GValue *value)
{
if (!self->names)
self->names = g_ptr_array_sized_new (8);
if (!self->values)
{
self->values = g_array_sized_new (FALSE, FALSE, sizeof (GValue), 8);
g_array_set_clear_func (self->values, (GDestroyNotify) g_value_unset);
}
g_ptr_array_add (self->names, (char *) name);
g_array_append_vals (self->values, value, 1);
g_assert (self->names->len == self->values->len);
self->len += 1;
}
static const char *
object_properties_get_name (const ObjectProperties *self,
guint idx)
{
g_assert (self->names);
return g_ptr_array_index (self->names, idx);
}
static GValue *
object_properties_get_value (const ObjectProperties *self,
guint idx)
{
g_assert (self->values);
return &g_array_index (self->values, GValue, idx);
}
static void
gtk_builder_get_parameters (GtkBuilder *builder,
GType object_type,
const char *object_name,
GPtrArray *properties,
GParamFlags filter_flags,
ObjectProperties *parameters,
ObjectProperties *filtered_parameters)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
DelayedProperty *property;
GError *error = NULL;
if (!properties)
return;
for (guint i = 0; i < properties->len; i++)
{
PropertyInfo *prop = g_ptr_array_index (properties, i);
const char *property_name = g_intern_string (prop->pspec->name);
GValue property_value = G_VALUE_INIT;
if (prop->value)
{
g_value_init (&property_value, G_PARAM_SPEC_VALUE_TYPE (prop->pspec));
if (G_PARAM_SPEC_VALUE_TYPE (prop->pspec) == GTK_TYPE_EXPRESSION)
gtk_value_set_expression (&property_value, prop->value);
else
g_assert_not_reached ();
}
else if (prop->bound && (!prop->text || prop->text->len == 0))
{
/* Ignore properties with a binding and no value since they are
* only there for to express the binding.
*/
continue;
}
else if (G_IS_PARAM_SPEC_OBJECT (prop->pspec) &&
(G_PARAM_SPEC_VALUE_TYPE (prop->pspec) != GDK_TYPE_PIXBUF) &&
(G_PARAM_SPEC_VALUE_TYPE (prop->pspec) != GDK_TYPE_TEXTURE) &&
(G_PARAM_SPEC_VALUE_TYPE (prop->pspec) != GDK_TYPE_PAINTABLE) &&
(G_PARAM_SPEC_VALUE_TYPE (prop->pspec) != GTK_TYPE_SHORTCUT_TRIGGER) &&
(G_PARAM_SPEC_VALUE_TYPE (prop->pspec) != GTK_TYPE_SHORTCUT_ACTION) &&
(G_PARAM_SPEC_VALUE_TYPE (prop->pspec) != G_TYPE_FILE))
{
GObject *object = g_hash_table_lookup (priv->objects,
g_strstrip (prop->text->str));
if (object)
{
g_value_init (&property_value, G_OBJECT_TYPE (object));
g_value_set_object (&property_value, object);
}
else
{
if (prop->pspec->flags & G_PARAM_CONSTRUCT_ONLY)
{
g_warning ("Failed to get construct only property "
"%s of %s with value '%s'",
prop->pspec->name, object_name, prop->text->str);
continue;
}
/* Delay setting property */
property = g_slice_new (DelayedProperty);
property->pspec = prop->pspec;
property->object = g_strdup (object_name);
property->value = g_strdup (prop->text->str);
property->line = prop->line;
property->col = prop->col;
priv->delayed_properties = g_slist_prepend (priv->delayed_properties,
property);
continue;
}
}
else if (!gtk_builder_value_from_string (builder, prop->pspec,
prop->text->str,
&property_value,
&error))
{
g_warning ("Failed to set property %s.%s to %s: %s",
g_type_name (object_type), prop->pspec->name, prop->text->str,
error->message);
g_error_free (error);
error = NULL;
continue;
}
if (prop->pspec->flags & filter_flags)
{
if (filtered_parameters)
object_properties_add (filtered_parameters, property_name, &property_value);
}
else
{
if (parameters)
object_properties_add (parameters, property_name, &property_value);
}
}
}
static const char *
object_get_id (GObject *object)
{
if (GTK_IS_BUILDABLE (object))
return gtk_buildable_get_buildable_id (GTK_BUILDABLE (object));
else
return g_object_get_data (object, "gtk-builder-id");
}
static GObject *
gtk_builder_get_internal_child (GtkBuilder *builder,
ObjectInfo *info,
const char *childname,
GError **error)
{
GObject *obj = NULL;
while (!obj)
{
if (!info->parent)
break;
info = (ObjectInfo*)((ChildInfo*)info->parent)->parent;
if (!info)
break;
GTK_NOTE (BUILDER,
g_message ("Trying to get internal child %s from %s",
childname, object_get_id (info->object)));
if (GTK_IS_BUILDABLE (info->object))
obj = gtk_buildable_get_internal_child (GTK_BUILDABLE (info->object),
builder,
childname);
};
if (!obj)
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Unknown internal child: %s", childname);
}
return obj;
}
static inline void
object_set_id (GObject *object,
const char *id)
{
if (GTK_IS_BUILDABLE (object))
gtk_buildable_set_buildable_id (GTK_BUILDABLE (object), id);
else
g_object_set_data_full (object, "gtk-builder-id", g_strdup (id), g_free);
}
void
_gtk_builder_add_object (GtkBuilder *builder,
const char *id,
GObject *object)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
object_set_id (object, id);
g_hash_table_insert (priv->objects, g_strdup (id), g_object_ref (object));
}
static void
gtk_builder_take_bindings (GtkBuilder *builder,
GObject *target,
GSList *bindings)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GSList *l;
for (l = bindings; l; l = l->next)
{
CommonInfo *common_info = l->data;
if (common_info->tag_type == TAG_BINDING)
{
BindingInfo *info = l->data;
info->target = target;
}
else if (common_info->tag_type == TAG_BINDING_EXPRESSION)
{
BindingExpressionInfo *info = l->data;
info->target = target;
}
else
{
g_assert_not_reached ();
}
}
priv->bindings = g_slist_concat (priv->bindings, bindings);
}
static void
ensure_special_construct_parameters (GtkBuilder *builder,
GType object_type,
ObjectProperties *construct_parameters)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GValue value = G_VALUE_INIT;
if (g_type_is_a (object_type, GTK_TYPE_BUILDER_LIST_ITEM_FACTORY))
{
g_value_init (&value, GTK_TYPE_BUILDER_SCOPE);
g_value_set_object (&value, priv->scope);
object_properties_add (construct_parameters, "scope", &value);
}
}
GObject *
_gtk_builder_construct (GtkBuilder *builder,
ObjectInfo *info,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
ObjectProperties parameters, construct_parameters;
GObject *obj;
int i;
GtkBuildableIface *iface;
gboolean custom_set_property;
GtkBuildable *buildable;
GParamFlags param_filter_flags;
g_assert (info->type != G_TYPE_INVALID);
if (priv->template_type != 0 &&
g_type_is_a (info->type, priv->template_type))
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_OBJECT_TYPE_REFUSED,
"Refused to build object of type '%s' because it "
"conforms to the template type '%s', avoiding infinite recursion.",
g_type_name (info->type), g_type_name (priv->template_type));
return NULL;
}
/* If there is a manual constructor (like UIManager), or if this is a
* reference to an internal child, then we filter out construct-only
* and warn that they cannot be set.
*
* Otherwise if we are calling g_object_new_with_properties(), we want
* to pass both G_PARAM_CONSTRUCT and G_PARAM_CONSTRUCT_ONLY to the
* object's constructor.
*
* Passing all construct properties to g_object_new_with_properties()
* slightly improves performance as the construct properties will only
* be set once.
*/
if (info->constructor ||
(info->parent &&
info->parent->tag_type == TAG_CHILD &&
((ChildInfo*)info->parent)->internal_child != NULL))
param_filter_flags = G_PARAM_CONSTRUCT_ONLY;
else
param_filter_flags = G_PARAM_CONSTRUCT | G_PARAM_CONSTRUCT_ONLY;
object_properties_init (¶meters);
object_properties_init (&construct_parameters);
gtk_builder_get_parameters (builder, info->type,
info->id,
info->properties,
param_filter_flags,
¶meters,
&construct_parameters);
if (info->constructor)
{
GObject *constructor;
constructor = g_hash_table_lookup (priv->objects, info->constructor);
if (constructor == NULL)
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Unknown object constructor for %s: %s",
info->id,
info->constructor);
object_properties_destroy (¶meters);
object_properties_destroy (&construct_parameters);
return NULL;
}
obj = gtk_buildable_construct_child (GTK_BUILDABLE (constructor),
builder,
info->id);
g_assert (obj != NULL);
if (construct_parameters.len > 0)
g_warning ("Can't pass in construct-only parameters to %s", info->id);
}
else if (info->parent &&
info->parent->tag_type == TAG_CHILD &&
((ChildInfo*)info->parent)->internal_child != NULL)
{
char *childname = ((ChildInfo*)info->parent)->internal_child;
obj = gtk_builder_get_internal_child (builder, info, childname, error);
if (!obj)
{
object_properties_destroy (¶meters);
object_properties_destroy (&construct_parameters);
return NULL;
}
if (construct_parameters.len > 0)
g_warning ("Can't pass in construct-only parameters to %s", childname);
g_object_ref (obj);
}
else
{
ensure_special_construct_parameters (builder, info->type, &construct_parameters);
if (construct_parameters.len > 0)
obj = g_object_new_with_properties (info->type,
construct_parameters.len,
(const char **) construct_parameters.names->pdata,
(GValue *) construct_parameters.values->data);
else
obj = g_object_new (info->type, NULL);
/* No matter what, make sure we have a reference.
*
* If it's an initially unowned object, sink it.
* If it's not initially unowned then we have the reference already.
*
* In the case that this is a window it will be sunk already and
* this is effectively a call to g_object_ref(). That's what
* we want.
*/
if (G_IS_INITIALLY_UNOWNED (obj))
g_object_ref_sink (obj);
GTK_NOTE (BUILDER,
g_message ("created %s of type %s", info->id, g_type_name (info->type)));
}
object_properties_destroy (&construct_parameters);
custom_set_property = FALSE;
buildable = NULL;
iface = NULL;
if (GTK_IS_BUILDABLE (obj))
{
buildable = GTK_BUILDABLE (obj);
iface = GTK_BUILDABLE_GET_IFACE (obj);
if (iface->set_buildable_property)
custom_set_property = TRUE;
}
for (i = 0; i < parameters.len; i++)
{
const char *name = object_properties_get_name (¶meters, i);
const GValue *value = object_properties_get_value (¶meters, i);
if (custom_set_property)
iface->set_buildable_property (buildable, builder, name, value);
else
g_object_set_property (obj, name, value);
#ifdef G_ENABLE_DEBUG
if (GTK_DEBUG_CHECK (BUILDER))
{
char *str = g_strdup_value_contents (value);
g_message ("set %s: %s = %s", info->id, name, str);
g_free (str);
}
#endif
}
object_properties_destroy (¶meters);
if (info->bindings)
gtk_builder_take_bindings (builder, obj, info->bindings);
/* put it in the hash table. */
_gtk_builder_add_object (builder, info->id, obj);
/* we already own a reference to obj. */
g_object_unref (obj);
return obj;
}
void
_gtk_builder_apply_properties (GtkBuilder *builder,
ObjectInfo *info,
GError **error)
{
ObjectProperties parameters;
GtkBuildableIface *iface;
GtkBuildable *buildable;
gboolean custom_set_property;
int i;
g_assert (info->object != NULL);
g_assert (info->type != G_TYPE_INVALID);
object_properties_init (¶meters);
/* Fetch all properties that are not construct-only */
gtk_builder_get_parameters (builder, info->type,
info->id,
info->properties,
G_PARAM_CONSTRUCT_ONLY,
¶meters, NULL);
custom_set_property = FALSE;
buildable = NULL;
iface = NULL;
if (GTK_IS_BUILDABLE (info->object))
{
buildable = GTK_BUILDABLE (info->object);
iface = GTK_BUILDABLE_GET_IFACE (info->object);
if (iface->set_buildable_property)
custom_set_property = TRUE;
}
for (i = 0; i < parameters.len; i++)
{
const char *name = object_properties_get_name (¶meters, i);
const GValue *value = object_properties_get_value (¶meters, i);
if (custom_set_property)
iface->set_buildable_property (buildable, builder, name, value);
else
g_object_set_property (info->object, name, value);
#ifdef G_ENABLE_DEBUG
if (GTK_DEBUG_CHECK (BUILDER))
{
char *str = g_strdup_value_contents (value);
g_message ("set %s: %s = %s", info->id, name, str);
g_free (str);
}
#endif
}
object_properties_destroy (¶meters);
}
void
_gtk_builder_add (GtkBuilder *builder,
ChildInfo *child_info)
{
GObject *object;
GObject *parent;
/* Internal children are already added
* Also prevent us from being called twice.
*/
if (!child_info ||
child_info->internal_child ||
child_info->added)
return;
object = child_info->object;
if (!object)
return;
if (!child_info->parent)
{
g_warning ("%s: Not adding, No parent", object_get_id (object));
return;
}
g_assert (object != NULL);
parent = ((ObjectInfo*)child_info->parent)->object;
GTK_NOTE (BUILDER,
g_message ("adding %s to %s", object_get_id (object), object_get_id (parent)));
if (G_IS_LIST_STORE (parent))
{
if (child_info->type != NULL)
{
GTK_BUILDER_WARN_INVALID_CHILD_TYPE (parent, child_info->type);
}
else
{
g_list_store_append (G_LIST_STORE (parent), object);
}
}
else
{
g_assert (GTK_IS_BUILDABLE (parent));
gtk_buildable_add_child (GTK_BUILDABLE (parent), builder, object,
child_info->type);
}
child_info->added = TRUE;
}
void
_gtk_builder_add_signals (GtkBuilder *builder,
GPtrArray *signals)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
if (G_UNLIKELY (!priv->signals))
priv->signals = g_ptr_array_new_with_free_func ((GDestroyNotify)_free_signal_info);
g_ptr_array_extend_and_steal (priv->signals, signals);
}
static gboolean
gtk_builder_apply_delayed_properties (GtkBuilder *builder,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GSList *l, *props;
gboolean result = TRUE;
/* take the list over from the builder->priv.
*
* g_slist_reverse does not copy the list, so the list now
* belongs to us (and we free it at the end of this function).
*/
props = g_slist_reverse (priv->delayed_properties);
priv->delayed_properties = NULL;
for (l = props; l; l = l->next)
{
DelayedProperty *property = l->data;
GObject *object, *obj;
if (result)
{
object = g_hash_table_lookup (priv->objects, property->object);
g_assert (object != NULL);
obj = gtk_builder_lookup_object (builder, property->value, property->line, property->col, error);
if (obj)
g_object_set (object, property->pspec->name, obj, NULL);
else
result = FALSE;
}
g_free (property->value);
g_free (property->object);
g_slice_free (DelayedProperty, property);
}
g_slist_free (props);
return result;
}
static inline gboolean
gtk_builder_create_bindings (GtkBuilder *builder,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GSList *l;
gboolean result = TRUE;
for (l = priv->bindings; l; l = l->next)
{
CommonInfo *common_info = l->data;
if (common_info->tag_type == TAG_BINDING)
{
BindingInfo *info = l->data;
GObject *source;
source = gtk_builder_lookup_object (builder, info->source, info->line, info->col, error);
if (source)
g_object_bind_property (source, info->source_property,
info->target, info->target_pspec->name,
info->flags);
else
error = NULL;
_free_binding_info (info, NULL);
}
else if (common_info->tag_type == TAG_BINDING_EXPRESSION)
{
BindingExpressionInfo *info = l->data;
GtkExpression *expression;
GObject *object;
if (info->object_name)
{
object = gtk_builder_lookup_object (builder, info->object_name, info->line, info->col, error);
if (object == NULL)
{
error = NULL;
result = FALSE;
}
}
else if (priv->current_object)
{
object = priv->current_object;
}
else
{
object = info->target;
}
if (object)
{
expression = expression_info_construct (builder, info->expr, error);
if (expression == NULL)
{
g_prefix_error (error, "%s:%d:%d: ", priv->filename, info->line, info->col);
error = NULL;
result = FALSE;
}
else
{
gtk_expression_bind (expression, info->target, info->target_pspec->name, object);
}
}
free_binding_expression_info (info);
}
else
g_assert_not_reached ();
}
g_slist_free (priv->bindings);
priv->bindings = NULL;
return result;
}
/**
* gtk_builder_new:
*
* Creates a new empty builder object.
*
* This function is only useful if you intend to make multiple calls
* to [method@Gtk.Builder.add_from_file], [method@Gtk.Builder.add_from_resource]
* or [method@Gtk.Builder.add_from_string] in order to merge multiple UI
* descriptions into a single builder.
*
* Returns: a new (empty) `GtkBuilder` object
*/
GtkBuilder *
gtk_builder_new (void)
{
return g_object_new (GTK_TYPE_BUILDER, NULL);
}
/**
* gtk_builder_add_from_file:
* @builder: a `GtkBuilder`
* @filename: the name of the file to parse
* @error: (allow-none): return location for an error, or %NULL
*
* Parses a file containing a UI definition and merges it with
* the current contents of @builder.
*
* This function is useful if you need to call
* [method@Gtk.Builder.set_current_object]) to add user data to
* callbacks before loading GtkBuilder UI. Otherwise, you probably
* want [ctor@Gtk.Builder.new_from_file] instead.
*
* If an error occurs, 0 will be returned and @error will be assigned a
* `GError` from the `GTK_BUILDER_ERROR`, `G_MARKUP_ERROR` or `G_FILE_ERROR`
* domains.
*
* It’s not really reasonable to attempt to handle failures of this
* call. You should not use this function with untrusted files (ie:
* files that are not part of your application). Broken `GtkBuilder`
* files can easily crash your program, and it’s possible that memory
* was leaked leading up to the reported failure. The only reasonable
* thing to do when an error is detected is to call `g_error()`.
*
* Returns: %TRUE on success, %FALSE if an error occurred
*/
gboolean
gtk_builder_add_from_file (GtkBuilder *builder,
const char *filename,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
char *buffer;
gsize length;
GError *tmp_error;
g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
g_return_val_if_fail (filename != NULL, 0);
g_return_val_if_fail (error == NULL || *error == NULL, 0);
tmp_error = NULL;
if (!g_file_get_contents (filename, &buffer, &length, &tmp_error))
{
g_propagate_error (error, tmp_error);
return FALSE;
}
g_free (priv->filename);
g_free (priv->resource_prefix);
priv->filename = g_strdup (filename);
priv->resource_prefix = NULL;
_gtk_builder_parser_parse_buffer (builder, filename,
buffer, (gssize)length,
NULL,
&tmp_error);
g_free (buffer);
if (tmp_error != NULL)
{
g_propagate_error (error, tmp_error);
return FALSE;
}
return TRUE;
}
/**
* gtk_builder_add_objects_from_file:
* @builder: a `GtkBuilder`
* @filename: the name of the file to parse
* @object_ids: (array zero-terminated=1) (element-type utf8): nul-terminated array of objects to build
* @error: (allow-none): return location for an error, or %NULL
*
* Parses a file containing a UI definition building only the
* requested objects and merges them with the current contents
* of @builder.
*
* Upon errors, 0 will be returned and @error will be assigned a
* `GError` from the %GTK_BUILDER_ERROR, %G_MARKUP_ERROR or %G_FILE_ERROR
* domain.
*
* If you are adding an object that depends on an object that is not
* its child (for instance a `GtkTreeView` that depends on its
* `GtkTreeModel`), you have to explicitly list all of them in @object_ids.
*
* Returns: %TRUE on success, %FALSE if an error occurred
*/
gboolean
gtk_builder_add_objects_from_file (GtkBuilder *builder,
const char *filename,
const char **object_ids,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
char *buffer;
gsize length;
GError *tmp_error;
g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
g_return_val_if_fail (filename != NULL, 0);
g_return_val_if_fail (object_ids != NULL && object_ids[0] != NULL, 0);
g_return_val_if_fail (error == NULL || *error == NULL, 0);
tmp_error = NULL;
if (!g_file_get_contents (filename, &buffer, &length, &tmp_error))
{
g_propagate_error (error, tmp_error);
return 0;
}
g_free (priv->filename);
g_free (priv->resource_prefix);
priv->filename = g_strdup (filename);
priv->resource_prefix = NULL;
_gtk_builder_parser_parse_buffer (builder, filename,
buffer, (gssize)length,
object_ids,
&tmp_error);
g_free (buffer);
if (tmp_error != NULL)
{
g_propagate_error (error, tmp_error);
return FALSE;
}
return TRUE;
}
/**
* gtk_builder_extend_with_template:
* @builder: a `GtkBuilder`
* @object: the object that is being extended
* @template_type: the type that the template is for
* @buffer: the string to parse
* @length: the length of @buffer (may be -1 if @buffer is nul-terminated)
* @error: (allow-none): return location for an error, or %NULL
*
* Main private entry point for building composite components
* from template XML.
*
* This is exported purely to let `gtk-builder-tool` validate
* templates, applications have no need to call this function.
*
* Returns: A positive value on success, 0 if an error occurred
*/
gboolean
gtk_builder_extend_with_template (GtkBuilder *builder,
GObject *object,
GType template_type,
const char *buffer,
gssize length,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GError *tmp_error;
char *filename;
g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
g_return_val_if_fail (G_IS_OBJECT (object), 0);
g_return_val_if_fail (g_type_name (template_type) != NULL, 0);
g_return_val_if_fail (g_type_is_a (G_OBJECT_TYPE (object), template_type), 0);
g_return_val_if_fail (buffer && buffer[0], 0);
tmp_error = NULL;
g_free (priv->filename);
g_free (priv->resource_prefix);
priv->filename = g_strdup (".");
priv->resource_prefix = NULL;
priv->template_type = template_type;
filename = g_strconcat ("<", g_type_name (template_type), " template>", NULL);
gtk_builder_expose_object (builder, g_type_name (template_type), object);
_gtk_builder_parser_parse_buffer (builder, filename,
buffer, length,
NULL,
&tmp_error);
g_free (filename);
if (tmp_error != NULL)
{
g_propagate_error (error, tmp_error);
return FALSE;
}
return TRUE;
}
/**
* gtk_builder_add_from_resource:
* @builder: a `GtkBuilder`
* @resource_path: the path of the resource file to parse
* @error: (allow-none): return location for an error, or %NULL
*
* Parses a resource file containing a UI definition
* and merges it with the current contents of @builder.
*
* This function is useful if you need to call
* [method@Gtk.Builder.set_current_object] to add user data to
* callbacks before loading GtkBuilder UI. Otherwise, you probably
* want [ctor@Gtk.Builder.new_from_resource] instead.
*
* If an error occurs, 0 will be returned and @error will be assigned a
* `GError` from the %GTK_BUILDER_ERROR, %G_MARKUP_ERROR or %G_RESOURCE_ERROR
* domain.
*
* It’s not really reasonable to attempt to handle failures of this
* call. The only reasonable thing to do when an error is detected is
* to call g_error().
*
* Returns: %TRUE on success, %FALSE if an error occurred
*/
gboolean
gtk_builder_add_from_resource (GtkBuilder *builder,
const char *resource_path,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GError *tmp_error;
GBytes *data;
char *filename_for_errors;
char *slash;
g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
g_return_val_if_fail (resource_path != NULL, 0);
g_return_val_if_fail (error == NULL || *error == NULL, 0);
tmp_error = NULL;
data = g_resources_lookup_data (resource_path, 0, &tmp_error);
if (data == NULL)
{
g_propagate_error (error, tmp_error);
return 0;
}
g_free (priv->filename);
g_free (priv->resource_prefix);
priv->filename = g_strdup (".");
slash = strrchr (resource_path, '/');
if (slash != NULL)
priv->resource_prefix = g_strndup (resource_path, slash - resource_path + 1);
else
priv->resource_prefix = g_strdup ("/");
filename_for_errors = g_strconcat ("<resource>", resource_path, NULL);
_gtk_builder_parser_parse_buffer (builder, filename_for_errors,
g_bytes_get_data (data, NULL), g_bytes_get_size (data),
NULL,
&tmp_error);
g_free (filename_for_errors);
g_bytes_unref (data);
if (tmp_error != NULL)
{
g_propagate_error (error, tmp_error);
return FALSE;
}
return TRUE;
}
/**
* gtk_builder_add_objects_from_resource:
* @builder: a `GtkBuilder`
* @resource_path: the path of the resource file to parse
* @object_ids: (array zero-terminated=1) (element-type utf8): nul-terminated array of objects to build
* @error: (allow-none): return location for an error, or %NULL
*
* Parses a resource file containing a UI definition, building
* only the requested objects and merges them with the current
* contents of @builder.
*
* Upon errors, 0 will be returned and @error will be assigned a
* `GError` from the %GTK_BUILDER_ERROR, %G_MARKUP_ERROR or %G_RESOURCE_ERROR
* domain.
*
* If you are adding an object that depends on an object that is not
* its child (for instance a `GtkTreeView` that depends on its
* `GtkTreeModel`), you have to explicitly list all of them in @object_ids.
*
* Returns: %TRUE on success, %FALSE if an error occurred
*/
gboolean
gtk_builder_add_objects_from_resource (GtkBuilder *builder,
const char *resource_path,
const char **object_ids,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GError *tmp_error;
GBytes *data;
char *filename_for_errors;
char *slash;
g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
g_return_val_if_fail (resource_path != NULL, 0);
g_return_val_if_fail (object_ids != NULL && object_ids[0] != NULL, 0);
g_return_val_if_fail (error == NULL || *error == NULL, 0);
tmp_error = NULL;
data = g_resources_lookup_data (resource_path, 0, &tmp_error);
if (data == NULL)
{
g_propagate_error (error, tmp_error);
return FALSE;
}
g_free (priv->filename);
g_free (priv->resource_prefix);
priv->filename = g_strdup (".");
slash = strrchr (resource_path, '/');
if (slash != NULL)
priv->resource_prefix = g_strndup (resource_path, slash - resource_path + 1);
else
priv->resource_prefix = g_strdup ("/");
filename_for_errors = g_strconcat ("<resource>", resource_path, NULL);
_gtk_builder_parser_parse_buffer (builder, filename_for_errors,
g_bytes_get_data (data, NULL), g_bytes_get_size (data),
object_ids,
&tmp_error);
g_free (filename_for_errors);
g_bytes_unref (data);
if (tmp_error != NULL)
{
g_propagate_error (error, tmp_error);
return FALSE;
}
return TRUE;
}
/**
* gtk_builder_add_from_string:
* @builder: a `GtkBuilder`
* @buffer: the string to parse
* @length: the length of @buffer (may be -1 if @buffer is nul-terminated)
* @error: (allow-none): return location for an error, or %NULL
*
* Parses a string containing a UI definition and merges it
* with the current contents of @builder.
*
* This function is useful if you need to call
* [method@Gtk.Builder.set_current_object] to add user data to
* callbacks before loading `GtkBuilder` UI. Otherwise, you probably
* want [ctor@Gtk.Builder.new_from_string] instead.
*
* Upon errors %FALSE will be returned and @error will be assigned a
* `GError` from the %GTK_BUILDER_ERROR, %G_MARKUP_ERROR or
* %G_VARIANT_PARSE_ERROR domain.
*
* It’s not really reasonable to attempt to handle failures of this
* call. The only reasonable thing to do when an error is detected is
* to call g_error().
*
* Returns: %TRUE on success, %FALSE if an error occurred
*/
gboolean
gtk_builder_add_from_string (GtkBuilder *builder,
const char *buffer,
gssize length,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GError *tmp_error;
g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
g_return_val_if_fail (buffer != NULL, 0);
g_return_val_if_fail (error == NULL || *error == NULL, 0);
tmp_error = NULL;
g_free (priv->filename);
g_free (priv->resource_prefix);
priv->filename = g_strdup (".");
priv->resource_prefix = NULL;
_gtk_builder_parser_parse_buffer (builder, "<input>",
buffer, length,
NULL,
&tmp_error);
if (tmp_error != NULL)
{
g_propagate_error (error, tmp_error);
return FALSE;
}
return TRUE;
}
/**
* gtk_builder_add_objects_from_string:
* @builder: a `GtkBuilder`
* @buffer: the string to parse
* @length: the length of @buffer (may be -1 if @buffer is nul-terminated)
* @object_ids: (array zero-terminated=1) (element-type utf8): nul-terminated array of objects to build
* @error: (allow-none): return location for an error, or %NULL
*
* Parses a string containing a UI definition, building only the
* requested objects and merges them with the current contents of
* @builder.
*
* Upon errors %FALSE will be returned and @error will be assigned a
* `GError` from the %GTK_BUILDER_ERROR or %G_MARKUP_ERROR domain.
*
* If you are adding an object that depends on an object that is not
* its child (for instance a `GtkTreeView` that depends on its
* `GtkTreeModel`), you have to explicitly list all of them in @object_ids.
*
* Returns: %TRUE on success, %FALSE if an error occurred
*/
gboolean
gtk_builder_add_objects_from_string (GtkBuilder *builder,
const char *buffer,
gssize length,
const char **object_ids,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GError *tmp_error;
g_return_val_if_fail (GTK_IS_BUILDER (builder), 0);
g_return_val_if_fail (buffer != NULL, 0);
g_return_val_if_fail (object_ids != NULL && object_ids[0] != NULL, 0);
g_return_val_if_fail (error == NULL || *error == NULL, 0);
tmp_error = NULL;
g_free (priv->filename);
g_free (priv->resource_prefix);
priv->filename = g_strdup (".");
priv->resource_prefix = NULL;
_gtk_builder_parser_parse_buffer (builder, "<input>",
buffer, length,
object_ids,
&tmp_error);
if (tmp_error != NULL)
{
g_propagate_error (error, tmp_error);
return FALSE;
}
return TRUE;
}
/**
* gtk_builder_get_object:
* @builder: a `GtkBuilder`
* @name: name of object to get
*
* Gets the object named @name.
*
* Note that this function does not increment the reference count
* of the returned object.
*
* Returns: (nullable) (transfer none): the object named @name
* or %NULL if it could not be found in the object tree.
*/
GObject *
gtk_builder_get_object (GtkBuilder *builder,
const char *name)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
g_return_val_if_fail (name != NULL, NULL);
return g_hash_table_lookup (priv->objects, name);
}
/**
* gtk_builder_get_objects:
* @builder: a `GtkBuilder`
*
* Gets all objects that have been constructed by @builder.
*
* Note that this function does not increment the reference
* counts of the returned objects.
*
* Returns: (element-type GObject) (transfer container): a
* newly-allocated `GSList` containing all the objects
* constructed by the `GtkBuilder instance`. It should be
* freed by g_slist_free()
*/
GSList *
gtk_builder_get_objects (GtkBuilder *builder)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GSList *objects = NULL;
GObject *object;
GHashTableIter iter;
g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
g_hash_table_iter_init (&iter, priv->objects);
while (g_hash_table_iter_next (&iter, NULL, (gpointer *)&object))
objects = g_slist_prepend (objects, object);
return g_slist_reverse (objects);
}
/**
* gtk_builder_set_translation_domain: (attributes org.gtk.Method.set_property=translation-domain)
* @builder: a `GtkBuilder`
* @domain: (nullable): the translation domain or %NULL
*
* Sets the translation domain of @builder.
*/
void
gtk_builder_set_translation_domain (GtkBuilder *builder,
const char *domain)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
char *new_domain;
g_return_if_fail (GTK_IS_BUILDER (builder));
new_domain = g_strdup (domain);
g_free (priv->domain);
priv->domain = new_domain;
g_object_notify_by_pspec (G_OBJECT (builder), builder_props[PROP_TRANSLATION_DOMAIN]);
}
/**
* gtk_builder_get_translation_domain: (attributes org.gtk.Method.get_property=translation-domain)
* @builder: a `GtkBuilder`
*
* Gets the translation domain of @builder.
*
* Returns: (transfer none) (nullable): the translation domain
* or %NULL. This string is owned by the builder object and
* must not be modified or freed.
*/
const char *
gtk_builder_get_translation_domain (GtkBuilder *builder)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
return priv->domain;
}
/**
* gtk_builder_expose_object:
* @builder: a `GtkBuilder`
* @name: the name of the object exposed to the builder
* @object: the object to expose
*
* Add @object to the @builder object pool so it can be
* referenced just like any other object built by builder.
*/
void
gtk_builder_expose_object (GtkBuilder *builder,
const char *name,
GObject *object)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
g_return_if_fail (GTK_IS_BUILDER (builder));
g_return_if_fail (name && name[0]);
g_return_if_fail (!g_hash_table_contains (priv->objects, name));
object_set_id (object, name);
g_hash_table_insert (priv->objects,
g_strdup (name),
g_object_ref (object));
}
/**
* gtk_builder_get_current_object: (attributes org.gtk.Method.get_property=current-object)
* @builder: a `GtkBuilder`
*
* Gets the current object set via gtk_builder_set_current_object().
*
* Returns: (nullable) (transfer none): the current object
*/
GObject *
gtk_builder_get_current_object (GtkBuilder *builder)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
return priv->current_object;
}
/**
* gtk_builder_set_current_object: (attributes org.gtk.Method.set_property=current-object)
* @builder: a `GtkBuilder`
* @current_object: (nullable) (transfer none): the new current object or
* %NULL for none
*
* Sets the current object for the @builder.
*
* The current object can be thought of as the `this` object that the
* builder is working for and will often be used as the default object
* when an object is optional.
*
* [method@Gtk.Widget.init_template] for example will set the current
* object to the widget the template is inited for. For functions like
* [ctor@Gtk.Builder.new_from_resource], the current object will be %NULL.
*/
void
gtk_builder_set_current_object (GtkBuilder *builder,
GObject *current_object)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
g_return_if_fail (GTK_IS_BUILDER (builder));
g_return_if_fail (current_object || G_IS_OBJECT (current_object));
if (!g_set_object (&priv->current_object, current_object))
return;
g_object_notify_by_pspec (G_OBJECT (builder), builder_props[PROP_CURRENT_OBJECT]);
}
/**
* gtk_builder_get_scope: (attributes org.gtk.Method.get_property=scope)
* @builder: a `GtkBuilder`
*
* Gets the scope in use that was set via gtk_builder_set_scope().
*
* Returns: (transfer none): the current scope
*/
GtkBuilderScope *
gtk_builder_get_scope (GtkBuilder *builder)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
return priv->scope;
}
/**
* gtk_builder_set_scope: (attributes org.gtk.Method.set_property=scope)
* @builder: a `GtkBuilder`
* @scope: (nullable) (transfer none): the scope to use or
* %NULL for the default
*
* Sets the scope the builder should operate in.
*
* If @scope is %NULL a new [class@Gtk.BuilderCScope] will be created.
*/
void
gtk_builder_set_scope (GtkBuilder *builder,
GtkBuilderScope *scope)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
g_return_if_fail (GTK_IS_BUILDER (builder));
g_return_if_fail (scope == NULL || GTK_IS_BUILDER_SCOPE (scope));
if (scope && priv->scope == scope)
return;
g_clear_object (&priv->scope);
if (scope)
priv->scope = g_object_ref (scope);
else
priv->scope = gtk_builder_cscope_new ();
g_object_notify_by_pspec (G_OBJECT (builder), builder_props[PROP_SCOPE]);
}
static gboolean
gtk_builder_connect_signals (GtkBuilder *builder,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GObject *object;
GObject *connect_object;
gboolean result = TRUE;
if (!priv->signals ||
priv->signals->len == 0)
return TRUE;
for (guint i = 0; i < priv->signals->len; i++)
{
SignalInfo *signal = g_ptr_array_index (priv->signals, i);
GClosure *closure;
g_assert (signal != NULL);
g_assert (signal->id != 0);
object = g_hash_table_lookup (priv->objects, signal->object_name);
g_assert (object != NULL);
connect_object = NULL;
if (signal->connect_object_name)
{
connect_object = g_hash_table_lookup (priv->objects,
signal->connect_object_name);
if (!connect_object)
{
g_set_error (error,
GTK_BUILDER_ERROR, GTK_BUILDER_ERROR_INVALID_ID,
"Could not lookup object %s on signal %s of object %s",
signal->connect_object_name, g_signal_name (signal->id),
signal->object_name);
break;
}
}
closure = gtk_builder_create_closure (builder,
signal->handler,
signal->flags & G_CONNECT_SWAPPED ? TRUE : FALSE,
connect_object,
error);
if (closure == NULL)
{
result = false;
break;
}
g_signal_connect_closure_by_id (object,
signal->id,
signal->detail,
closure,
signal->flags & G_CONNECT_AFTER ? TRUE : FALSE);
}
g_ptr_array_free (priv->signals, TRUE);
priv->signals = NULL;
return result;
}
gboolean
_gtk_builder_finish (GtkBuilder *builder,
GError **error)
{
return gtk_builder_apply_delayed_properties (builder, error)
&& gtk_builder_create_bindings (builder, error)
&& gtk_builder_connect_signals (builder, error);
}
/**
* gtk_builder_value_from_string:
* @builder: a `GtkBuilder`
* @pspec: the `GParamSpec` for the property
* @string: the string representation of the value
* @value: (out): the `GValue` to store the result in
* @error: (allow-none): return location for an error, or %NULL
*
* Demarshals a value from a string.
*
* This function calls g_value_init() on the @value argument,
* so it need not be initialised beforehand.
*
* Can handle char, uchar, boolean, int, uint, long,
* ulong, enum, flags, float, double, string, `GdkRGBA` and
* `GtkAdjustment` type values.
*
* Upon errors %FALSE will be returned and @error will be
* assigned a `GError` from the %GTK_BUILDER_ERROR domain.
*
* Returns: %TRUE on success
*/
gboolean
gtk_builder_value_from_string (GtkBuilder *builder,
GParamSpec *pspec,
const char *string,
GValue *value,
GError **error)
{
g_return_val_if_fail (GTK_IS_BUILDER (builder), FALSE);
g_return_val_if_fail (G_IS_PARAM_SPEC (pspec), FALSE);
g_return_val_if_fail (string != NULL, FALSE);
g_return_val_if_fail (value != NULL, FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
/*
* GParamSpecUnichar has the internal type G_TYPE_UINT,
* so we cannot handle this in the switch, do it separately
*/
if (G_IS_PARAM_SPEC_UNICHAR (pspec))
{
gunichar c;
g_value_init (value, G_TYPE_UINT);
c = g_utf8_get_char_validated (string, strlen (string));
if (c != 0 && c != (gunichar)-1 && c != (gunichar)-2)
g_value_set_uint (value, c);
return TRUE;
}
/*
* GParamSpecVariant can specify a GVariantType which can help with
* parsing, so we need to take care of that here.
*/
if (G_IS_PARAM_SPEC_VARIANT (pspec))
{
GParamSpecVariant *variant_pspec = G_PARAM_SPEC_VARIANT (pspec);
const GVariantType *type;
GVariant *variant;
g_value_init (value, G_TYPE_VARIANT);
/* The GVariant parser doesn't deal with indefinite types */
if (g_variant_type_is_definite (variant_pspec->type))
type = variant_pspec->type;
else
type = NULL;
variant = g_variant_parse (type, string, NULL, NULL, error);
if (variant == NULL)
return FALSE;
g_value_take_variant (value, variant);
return TRUE;
}
return gtk_builder_value_from_string_type (builder,
G_PARAM_SPEC_VALUE_TYPE (pspec),
string, value, error);
}
gboolean
_gtk_builder_boolean_from_string (const char *string,
gboolean *value,
GError **error)
{
if (string[0] == '\0')
goto error;
else if (string[1] == '\0')
{
char c;
c = string[0];
if (c == '1' ||
c == 'y' || c == 't' ||
c == 'Y' || c == 'T')
*value = TRUE;
else if (c == '0' ||
c == 'n' || c == 'f' ||
c == 'N' || c == 'F')
*value = FALSE;
else
goto error;
}
else
{
if (g_ascii_strcasecmp (string, "true") == 0 ||
g_ascii_strcasecmp (string, "yes") == 0)
*value = TRUE;
else if (g_ascii_strcasecmp (string, "false") == 0 ||
g_ascii_strcasecmp (string, "no") == 0)
*value = FALSE;
else
goto error;
}
return TRUE;
error:
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not parse boolean '%s'",
string);
return FALSE;
}
/**
* gtk_builder_value_from_string_type:
* @builder: a `GtkBuilder`
* @type: the `GType` of the value
* @string: the string representation of the value
* @value: (out): the #GValue to store the result in
* @error: (allow-none): return location for an error, or %NULL
*
* Demarshals a value from a string.
*
* Unlike [method@Gtk.Builder.value_from_string], this function
* takes a `GType` instead of `GParamSpec`.
*
* Calls g_value_init() on the @value argument, so it
* need not be initialised beforehand.
*
* Upon errors %FALSE will be returned and @error will be
* assigned a `GError` from the %GTK_BUILDER_ERROR domain.
*
* Returns: %TRUE on success
*/
gboolean
gtk_builder_value_from_string_type (GtkBuilder *builder,
GType type,
const char *string,
GValue *value,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
gboolean ret = TRUE;
g_return_val_if_fail (string != NULL, FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
g_value_init (value, type);
switch (G_TYPE_FUNDAMENTAL (type))
{
case G_TYPE_CHAR:
g_value_set_schar (value, string[0]);
break;
case G_TYPE_UCHAR:
g_value_set_uchar (value, (guchar)string[0]);
break;
case G_TYPE_BOOLEAN:
{
gboolean b;
if (!_gtk_builder_boolean_from_string (string, &b, error))
{
ret = FALSE;
break;
}
g_value_set_boolean (value, b);
break;
}
case G_TYPE_INT:
case G_TYPE_LONG:
case G_TYPE_INT64:
{
gint64 l;
char *endptr = NULL;
errno = 0;
l = g_ascii_strtoll (string, &endptr, 0);
if (errno || endptr == string)
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not parse integer '%s'",
string);
ret = FALSE;
break;
}
if (G_VALUE_HOLDS_INT (value))
g_value_set_int (value, l);
else if (G_VALUE_HOLDS_LONG (value))
g_value_set_long (value, l);
else
g_value_set_int64 (value, l);
break;
}
case G_TYPE_UINT:
case G_TYPE_ULONG:
case G_TYPE_UINT64:
{
guint64 ul;
char *endptr = NULL;
errno = 0;
ul = g_ascii_strtoull (string, &endptr, 0);
if (errno || endptr == string)
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not parse unsigned integer '%s'",
string);
ret = FALSE;
break;
}
if (G_VALUE_HOLDS_UINT (value))
g_value_set_uint (value, ul);
else if (G_VALUE_HOLDS_ULONG (value))
g_value_set_ulong (value, ul);
else
g_value_set_uint64 (value, ul);
break;
}
case G_TYPE_ENUM:
{
int enum_value;
if (!_gtk_builder_enum_from_string (type, string, &enum_value, error))
{
ret = FALSE;
break;
}
g_value_set_enum (value, enum_value);
break;
}
case G_TYPE_FLAGS:
{
guint flags_value;
if (!_gtk_builder_flags_from_string (type, NULL, string, &flags_value, error))
{
ret = FALSE;
break;
}
g_value_set_flags (value, flags_value);
break;
}
case G_TYPE_FLOAT:
case G_TYPE_DOUBLE:
{
double d;
char *endptr = NULL;
errno = 0;
d = g_ascii_strtod (string, &endptr);
if (errno || endptr == string)
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not parse double '%s'",
string);
ret = FALSE;
break;
}
if (G_VALUE_HOLDS_FLOAT (value))
g_value_set_float (value, d);
else
g_value_set_double (value, d);
break;
}
case G_TYPE_STRING:
g_value_set_string (value, string);
break;
case G_TYPE_VARIANT:
{
GVariant *variant;
variant = g_variant_parse (NULL, string, NULL, NULL, error);
if (value != NULL)
g_value_take_variant (value, variant);
else
ret = FALSE;
}
break;
case G_TYPE_BOXED:
if (G_VALUE_HOLDS (value, GDK_TYPE_RGBA))
{
GdkRGBA rgba = { 0 };
if (gdk_rgba_parse (&rgba, string))
g_value_set_boxed (value, &rgba);
else
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not parse RGBA color '%s'",
string);
ret = FALSE;
}
}
else if (G_VALUE_HOLDS (value, GSK_TYPE_TRANSFORM))
{
GskTransform *transform;
if (gsk_transform_parse (string, &transform))
g_value_take_boxed (value, transform);
else
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not parse transform '%s'",
string);
ret = FALSE;
}
}
else if (G_VALUE_HOLDS (value, G_TYPE_STRV))
{
char **vector = g_strsplit (string, "\n", 0);
g_value_take_boxed (value, vector);
}
else if (G_VALUE_HOLDS (value, G_TYPE_BYTES))
{
g_value_take_boxed (value, g_bytes_new (string, strlen (string)));
}
else
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not parse '%s' as a %s",
string, G_VALUE_TYPE_NAME (value));
ret = FALSE;
}
break;
case G_TYPE_OBJECT:
case G_TYPE_INTERFACE:
if (G_VALUE_HOLDS (value, GDK_TYPE_PIXBUF) ||
G_VALUE_HOLDS (value, GDK_TYPE_PAINTABLE) ||
G_VALUE_HOLDS (value, GDK_TYPE_TEXTURE))
{
char *filename;
GError *tmp_error = NULL;
GdkPixbuf *pixbuf = NULL;
GObject *object;
object = g_hash_table_lookup (priv->objects, string);
if (object)
{
if (g_type_is_a (G_OBJECT_TYPE (object), G_VALUE_TYPE (value)))
{
g_value_set_object (value, object);
return TRUE;
}
else
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not load image '%s': "
" '%s' is already used as object id for a %s",
string, string, G_OBJECT_TYPE_NAME (object));
return FALSE;
}
}
filename = _gtk_builder_get_resource_path (builder, string);
if (filename != NULL)
{
GInputStream *stream = g_resources_open_stream (filename, 0, &tmp_error);
if (stream != NULL)
{
pixbuf = gdk_pixbuf_new_from_stream (stream, NULL, &tmp_error);
g_object_unref (stream);
}
}
else
{
filename = _gtk_builder_get_absolute_filename (builder, string);
pixbuf = gdk_pixbuf_new_from_file (filename, &tmp_error);
}
if (pixbuf == NULL)
{
g_warning ("Could not load image '%s': %s",
string, tmp_error->message);
g_error_free (tmp_error);
pixbuf = _gdk_pixbuf_new_from_resource (IMAGE_MISSING_RESOURCE_PATH, "png", NULL);
}
if (pixbuf)
{
if (G_VALUE_HOLDS (value, GDK_TYPE_TEXTURE) ||
G_VALUE_HOLDS (value, GDK_TYPE_PAINTABLE))
{
GdkTexture *texture = gdk_texture_new_for_pixbuf (pixbuf);
g_value_set_object (value, texture);
g_object_unref (texture);
}
else
{
g_value_set_object (value, pixbuf);
}
g_object_unref (G_OBJECT (pixbuf));
}
g_free (filename);
ret = TRUE;
}
else if (G_VALUE_HOLDS (value, G_TYPE_FILE))
{
GFile *file;
if (g_hash_table_contains (priv->objects, string))
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not create file '%s': "
" '%s' is already used as object id",
string, string);
return FALSE;
}
file = g_file_new_for_uri (string);
g_value_set_object (value, file);
g_object_unref (G_OBJECT (file));
ret = TRUE;
}
else if (G_VALUE_HOLDS (value, GTK_TYPE_SHORTCUT_TRIGGER))
{
GtkShortcutTrigger *trigger = gtk_shortcut_trigger_parse_string (string);
if (trigger)
g_value_take_object (value, trigger);
else
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not parse shortcut trigger '%s'",
string);
ret = FALSE;
}
}
else if (G_VALUE_HOLDS (value, GTK_TYPE_SHORTCUT_ACTION))
{
GtkShortcutAction *action = gtk_shortcut_action_parse_builder (builder, string, error);
/* Works for success and failure (NULL) case */
g_value_take_object (value, action);
}
else
{
GObject *object = g_hash_table_lookup (priv->objects, string);
if (object && g_value_type_compatible (G_OBJECT_TYPE (object), type))
{
g_value_set_object (value, object);
}
else if (object)
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Object named \"%s\" is of type \"%s\" which is not compatible with expected type \%s\"",
string, G_OBJECT_TYPE_NAME (object), g_type_name (type));
ret = FALSE;
}
else
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"No object named \"%s\"", string);
ret = FALSE;
}
}
break;
case G_TYPE_POINTER:
if (G_VALUE_HOLDS (value, G_TYPE_GTYPE))
{
GType resolved_type;
resolved_type = gtk_builder_get_type_from_name (builder, string);
if (resolved_type == G_TYPE_INVALID)
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Unsupported GType '%s' for value of type 'GType'", string);
return FALSE;
}
g_value_set_gtype (value, resolved_type);
ret = TRUE;
}
else
ret = FALSE;
break;
default:
ret = FALSE;
break;
}
/* Catch unassigned error for object types as well as any unsupported types.
* While parsing GtkBuilder; object types are deserialized
* without calling gtk_builder_value_from_string_type().
*/
if (!ret && error && *error == NULL)
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Unsupported GType '%s'", g_type_name (type));
return ret;
}
gboolean
_gtk_builder_enum_from_string (GType type,
const char *string,
int *enum_value,
GError **error)
{
GEnumClass *eclass;
GEnumValue *ev;
char *endptr;
int value;
gboolean ret;
g_return_val_if_fail (G_TYPE_IS_ENUM (type), FALSE);
g_return_val_if_fail (string != NULL, FALSE);
ret = TRUE;
endptr = NULL;
errno = 0;
value = g_ascii_strtoull (string, &endptr, 0);
if (errno == 0 && endptr != string) /* parsed a number */
*enum_value = value;
else
{
eclass = g_type_class_ref (type);
ev = g_enum_get_value_by_name (eclass, string);
if (!ev)
ev = g_enum_get_value_by_nick (eclass, string);
if (ev)
*enum_value = ev->value;
else
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Could not parse enum: '%s'",
string);
ret = FALSE;
}
g_type_class_unref (eclass);
}
return ret;
}
gboolean
_gtk_builder_flags_from_string (GType type,
GFlagsValue *aliases,
const char *string,
guint *flags_value,
GError **error)
{
GFlagsClass *fclass;
char *endptr, *prevptr;
guint i, j, k, value;
char *flagstr;
GFlagsValue *fv;
const char *flag;
gunichar ch;
gboolean eos, ret;
g_return_val_if_fail (G_TYPE_IS_FLAGS (type), FALSE);
g_return_val_if_fail (string != 0, FALSE);
ret = TRUE;
endptr = NULL;
errno = 0;
value = g_ascii_strtoull (string, &endptr, 0);
if (errno == 0 && endptr != string) /* parsed a number */
*flags_value = value;
else
{
fclass = g_type_class_ref (type);
flagstr = g_strdup (string);
for (value = i = j = 0; ; i++)
{
eos = flagstr[i] == '\0';
if (!eos && flagstr[i] != '|')
continue;
flag = &flagstr[j];
endptr = &flagstr[i];
if (!eos)
{
flagstr[i++] = '\0';
j = i;
}
/* trim spaces */
for (;;)
{
ch = g_utf8_get_char (flag);
if (!g_unichar_isspace (ch))
break;
flag = g_utf8_next_char (flag);
}
while (endptr > flag)
{
prevptr = g_utf8_prev_char (endptr);
ch = g_utf8_get_char (prevptr);
if (!g_unichar_isspace (ch))
break;
endptr = prevptr;
}
if (endptr > flag)
{
*endptr = '\0';
fv = NULL;
if (aliases)
{
for (k = 0; aliases[k].value_nick; k++)
{
if (g_ascii_strcasecmp (aliases[k].value_nick, flag) == 0)
{
fv = &aliases[k];
break;
}
}
}
if (!fv)
fv = g_flags_get_value_by_name (fclass, flag);
if (!fv)
fv = g_flags_get_value_by_nick (fclass, flag);
if (fv)
value |= fv->value;
else
{
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_VALUE,
"Unknown flag: '%s'",
flag);
ret = FALSE;
break;
}
}
if (eos)
{
*flags_value = value;
break;
}
}
g_free (flagstr);
g_type_class_unref (fclass);
}
return ret;
}
/**
* gtk_builder_get_type_from_name:
* @builder: a `GtkBuilder`
* @type_name: type name to lookup
*
* Looks up a type by name.
*
* This is using the virtual function that `GtkBuilder` has
* for that purpose. This is mainly used when implementing
* the `GtkBuildable` interface on a type.
*
* Returns: the `GType` found for @type_name or %G_TYPE_INVALID
* if no type was found
*/
GType
gtk_builder_get_type_from_name (GtkBuilder *builder,
const char *type_name)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GType type;
g_return_val_if_fail (GTK_IS_BUILDER (builder), G_TYPE_INVALID);
g_return_val_if_fail (type_name != NULL, G_TYPE_INVALID);
type = gtk_builder_scope_get_type_from_name (priv->scope, builder, type_name);
if (type == G_TYPE_INVALID)
return G_TYPE_INVALID;
if (G_TYPE_IS_CLASSED (type))
g_type_class_unref (g_type_class_ref (type));
return type;
}
GQuark
gtk_builder_error_quark (void)
{
return g_quark_from_static_string ("gtk-builder-error-quark");
}
char *
_gtk_builder_get_resource_path (GtkBuilder *builder, const char *string)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
if (g_str_has_prefix (string, "resource:///"))
return g_uri_unescape_string (string + 11, "/");
if (g_path_is_absolute (string) ||
priv->resource_prefix == NULL)
return NULL;
return g_build_path ("/", priv->resource_prefix, string, NULL);
}
char *
_gtk_builder_get_absolute_filename (GtkBuilder *builder,
const char *string)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
char *filename;
char *dirname = NULL;
if (g_path_is_absolute (string))
return g_strdup (string);
if (priv->filename &&
strcmp (priv->filename, ".") != 0)
{
dirname = g_path_get_dirname (priv->filename);
if (strcmp (dirname, ".") == 0)
{
g_free (dirname);
dirname = g_get_current_dir ();
}
}
else
dirname = g_get_current_dir ();
filename = g_build_filename (dirname, string, NULL);
g_free (dirname);
return filename;
}
GType
_gtk_builder_get_template_type (GtkBuilder *builder)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
return priv->template_type;
}
/**
* gtk_builder_create_closure:
* @builder: a `GtkBuilder`
* @function_name: name of the function to look up
* @flags: closure creation flags
* @object: (nullable): Object to create the closure with
* @error: (allow-none): return location for an error, or %NULL
*
* Creates a closure to invoke the function called @function_name.
*
* This is using the create_closure() implementation of @builder's
* [class@Gtk.BuilderScope].
*
* If no closure could be created, %NULL will be returned and @error
* will be set.
*
* Returns: (nullable): A new closure for invoking @function_name
*/
GClosure *
gtk_builder_create_closure (GtkBuilder *builder,
const char *function_name,
GtkBuilderClosureFlags flags,
GObject *object,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
g_return_val_if_fail (GTK_IS_BUILDER (builder), NULL);
g_return_val_if_fail (function_name, NULL);
g_return_val_if_fail (object == NULL || G_IS_OBJECT (object), NULL);
g_return_val_if_fail (error == NULL || *error == NULL, NULL);
return gtk_builder_scope_create_closure (priv->scope, builder, function_name, flags, object, error);
}
/**
* gtk_builder_new_from_file: (constructor)
* @filename: filename of user interface description file
*
* Parses the UI definition in the file @filename.
*
* If there is an error opening the file or parsing the description then
* the program will be aborted. You should only ever attempt to parse
* user interface descriptions that are shipped as part of your program.
*
* Returns: (transfer full): a `GtkBuilder` containing the described interface
*/
GtkBuilder *
gtk_builder_new_from_file (const char *filename)
{
GError *error = NULL;
GtkBuilder *builder;
builder = gtk_builder_new ();
if (!gtk_builder_add_from_file (builder, filename, &error))
g_error ("failed to add UI from file %s: %s", filename, error->message);
return builder;
}
/**
* gtk_builder_new_from_resource: (constructor)
* @resource_path: a `GResource` resource path
*
* Parses the UI definition at @resource_path.
*
* If there is an error locating the resource or parsing the
* description, then the program will be aborted.
*
* Returns: (transfer full): a `GtkBuilder` containing the described interface
*/
GtkBuilder *
gtk_builder_new_from_resource (const char *resource_path)
{
GError *error = NULL;
GtkBuilder *builder;
builder = gtk_builder_new ();
if (!gtk_builder_add_from_resource (builder, resource_path, &error))
g_error ("failed to add UI from resource %s: %s", resource_path, error->message);
return builder;
}
/**
* gtk_builder_new_from_string: (constructor)
* @string: a user interface (XML) description
* @length: the length of @string, or -1
*
* Parses the UI definition in @string.
*
* If @string is %NULL-terminated, then @length should be -1.
* If @length is not -1, then it is the length of @string.
*
* If there is an error parsing @string then the program will be
* aborted. You should not attempt to parse user interface description
* from untrusted sources.
*
* Returns: (transfer full): a `GtkBuilder` containing the interface described by @string
*/
GtkBuilder *
gtk_builder_new_from_string (const char *string,
gssize length)
{
GError *error = NULL;
GtkBuilder *builder;
builder = gtk_builder_new ();
if (!gtk_builder_add_from_string (builder, string, length, &error))
g_error ("failed to add UI: %s", error->message);
return builder;
}
/*< private >
* _gtk_builder_prefix_error:
* @builder: a #GtkBuilder
* @context: the #GtkBuildableParseContext
* @error: an error
*
* Calls g_prefix_error() to prepend a filename:line:column marker
* to the given error. The filename is taken from @builder, and
* the line and column are obtained by calling
* g_markup_parse_context_get_position().
*
* This is intended to be called on errors returned by
* g_markup_collect_attributes() in a start_element vfunc.
*/
void
_gtk_builder_prefix_error (GtkBuilder *builder,
GtkBuildableParseContext *context,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
int line, col;
gtk_buildable_parse_context_get_position (context, &line, &col);
g_prefix_error (error, "%s:%d:%d ", priv->filename, line, col);
}
/*< private >
* _gtk_builder_error_unhandled_tag:
* @builder: a #GtkBuilder
* @context: the #GtkBuildableParseContext
* @object: name of the object that is being handled
* @element_name: name of the element whose start tag is being handled
* @error: return location for the error
*
* Sets @error to a suitable error indicating that an @element_name
* tag is not expected in the custom markup for @object.
*
* This is intended to be called in a start_element vfunc.
*/
void
_gtk_builder_error_unhandled_tag (GtkBuilder *builder,
GtkBuildableParseContext *context,
const char *object,
const char *element_name,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
int line, col;
gtk_buildable_parse_context_get_position (context, &line, &col);
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_UNHANDLED_TAG,
"%s:%d:%d Unsupported tag for %s: <%s>",
priv->filename, line, col,
object, element_name);
}
/*< private >
* @builder: a #GtkBuilder
* @context: the #GtkBuildableParseContext
* @parent_name: the name of the expected parent element
* @error: return location for an error
*
* Checks that the parent element of the currently handled
* start tag is @parent_name and set @error if it isn't.
*
* This is intended to be called in start_element vfuncs to
* ensure that element nesting is as intended.
*
* Returns: %TRUE if @parent_name is the parent element
*/
gboolean
_gtk_builder_check_parent (GtkBuilder *builder,
GtkBuildableParseContext *context,
const char *parent_name,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GPtrArray *stack;
int line, col;
const char *parent;
const char *element;
stack = gtk_buildable_parse_context_get_element_stack (context);
element = g_ptr_array_index (stack, stack->len - 1);
parent = stack->len > 1 ? g_ptr_array_index (stack, stack->len - 2) : "";
if (g_str_equal (parent_name, parent) ||
(g_str_equal (parent_name, "object") && g_str_equal (parent, "template")))
return TRUE;
gtk_buildable_parse_context_get_position (context, &line, &col);
g_set_error (error,
GTK_BUILDER_ERROR,
GTK_BUILDER_ERROR_INVALID_TAG,
"%s:%d:%d Can't use <%s> here",
priv->filename, line, col, element);
return FALSE;
}
GObject *
gtk_builder_lookup_object (GtkBuilder *builder,
const char *name,
int line,
int col,
GError **error)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GObject *obj;
obj = g_hash_table_lookup (priv->objects, name);
if (obj == NULL)
{
g_set_error (error,
GTK_BUILDER_ERROR, GTK_BUILDER_ERROR_INVALID_ID,
"%s:%d:%d Object with ID %s not found",
priv->filename, line, col, name);
}
return obj;
}
/*< private >
* @builder: a #GtkBuilder
* @name: object name to look up
* @line: line number where @name was encountered
* @col: column number where @name was encountered
*
* Looks up an object by name. Similar to gtk_builder_get_object(),
* but sets an error if lookup fails during custom_tag_end,
* custom_finished or parser_finished vfuncs.
*
* The reason for doing things this way is that these vfuncs don't
* take a GError** parameter to return an error.
*
* Returns: the found object
*/
GObject *
_gtk_builder_lookup_object (GtkBuilder *builder,
const char *name,
int line,
int col)
{
GtkBuilderPrivate *priv = gtk_builder_get_instance_private (builder);
GObject *obj;
GError *error = NULL;
obj = g_hash_table_lookup (priv->objects, name);
error = (GError *) g_object_get_data (G_OBJECT (builder), "lookup-error");
if (!obj && !error)
{
g_set_error (&error,
GTK_BUILDER_ERROR, GTK_BUILDER_ERROR_INVALID_ID,
"%s:%d:%d Object with ID %s not found",
priv->filename, line, col, name);
g_object_set_data_full (G_OBJECT (builder), "lookup-error",
error, (GDestroyNotify)g_error_free);
}
return obj;
}
/*< private >
* _gtk_builder_lookup_failed:
* @GtkBuilder: a #GtkBuilder
* @error: return location for error
*
* Finds whether any object lookups have failed.
*
* Returns: %TRUE if @error has been set
*/
gboolean
_gtk_builder_lookup_failed (GtkBuilder *builder,
GError **error)
{
GError *lookup_error;
lookup_error = (GError*) g_object_steal_data (G_OBJECT (builder), "lookup-error");
if (lookup_error)
{
g_propagate_error (error, lookup_error);
return TRUE;
}
return FALSE;
}
|
f3892ea38945a1ddf2431da52ec7d510ed94fb4e
|
e1d9c54e9925e30e388a255b53a93cccad0b94cb
|
/examples/list_secret/main.c
|
c5c42fe128d4a98d7b04644f8e8cbed98e9e1197
|
[
"Apache-2.0"
] |
permissive
|
kubernetes-client/c
|
dd4fd8095485c083e0f40f2b48159b1609a6141b
|
5ac5ff25e9809a92a48111b1f77574b6d040b711
|
refs/heads/master
| 2023-08-13T10:51:03.702497
| 2023-08-07T19:18:32
| 2023-08-07T19:18:32
| 247,958,425
| 127
| 47
|
Apache-2.0
| 2023-09-07T20:07:00
| 2020-03-17T11:59:05
|
C
|
UTF-8
|
C
| false
| false
| 3,254
|
c
|
main.c
|
#include <kube_config.h>
#include <apiClient.h>
#include <CoreV1API.h>
#include <malloc.h>
#include <stdio.h>
#include <errno.h>
void list_secret(apiClient_t * apiClient)
{
v1_secret_list_t *secret_list = CoreV1API_listNamespacedSecret(apiClient,
"default", // char *namespace
"true", // char *pretty
0, // int allowWatchBookmarks
NULL, // char * _continue
NULL, // char * fieldSelector
NULL, // char * labelSelector
0, // int limit
NULL, // char * resourceVersion
NULL, // char * resourceVersionMatch
0, // sendInitialEvents
0, // int timeoutSeconds
0 // int watch
);
printf("The return code of HTTP request=%ld\n", apiClient->response_code);
if (200 == apiClient->response_code) {
printf("List the secrets successfully.\n");
} else {
fprintf(stderr, "Failed to list the secrets.\n");
return;
}
if (secret_list && secret_list->items) {
listEntry_t *secret_list_entry = NULL;
v1_secret_t *secret = NULL;
list_ForEach(secret_list_entry, secret_list->items) {
secret = secret_list_entry->data;
printf("\tThe secret name: %s\n", secret->metadata->name);
listEntry_t *data_entry = NULL;
keyValuePair_t *pair = NULL;
list_ForEach(data_entry, secret->data) {
pair = data_entry->data;
printf("\tkey=%s, value=%s\n", pair->key, (char *) pair->value);
}
}
v1_secret_list_free(secret_list);
secret_list = NULL;
} else {
fprintf(stderr, "The secret list is invalid.\n");
}
}
int main(int argc, char *argv[])
{
char *basePath = NULL;
sslConfig_t *sslConfig = NULL;
list_t *apiKeys = NULL;
int rc = load_kube_config(&basePath, &sslConfig, &apiKeys, NULL); /* NULL means loading configuration from $HOME/.kube/config */
if (rc != 0) {
fprintf(stderr, "Cannot load kubernetes configuration.\n");
return -1;
}
apiClient_t *apiClient = apiClient_create_with_base_path(basePath, sslConfig, apiKeys);
if (!apiClient) {
fprintf(stderr, "Cannot create a kubernetes client.\n");
return -1;
}
list_secret(apiClient);
apiClient_free(apiClient);
apiClient = NULL;
free_client_config(basePath, sslConfig, apiKeys);
basePath = NULL;
sslConfig = NULL;
apiKeys = NULL;
apiClient_unsetupGlobalEnv();
return 0;
}
|
ad5fbf6100bea1cbd5eb19f5db4c2ee9011e4325
|
e1d9c54e9925e30e388a255b53a93cccad0b94cb
|
/kubernetes/websocket/wsclient.h
|
b2d322c49bdf0a81f35f68806fb35a1c6b7c887b
|
[
"Apache-2.0",
"curl"
] |
permissive
|
kubernetes-client/c
|
dd4fd8095485c083e0f40f2b48159b1609a6141b
|
5ac5ff25e9809a92a48111b1f77574b6d040b711
|
refs/heads/master
| 2023-08-13T10:51:03.702497
| 2023-08-07T19:18:32
| 2023-08-07T19:18:32
| 247,958,425
| 127
| 47
|
Apache-2.0
| 2023-09-07T20:07:00
| 2020-03-17T11:59:05
|
C
|
UTF-8
|
C
| false
| false
| 1,017
|
h
|
wsclient.h
|
#ifndef _WSCLIENT_H
#define _WSCLIENT_H
#include <libwebsockets.h>
#include "../include/apiClient.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*data_callback_func) (void **, long *);
typedef enum wsc_mode_t {
WSC_MODE_NORMAL = 0,
WSC_MODE_IT
} wsc_mode_t;
typedef struct wsclient_t {
char *server_address;
int server_port;
char *path;
char *data_to_send;
long data_to_send_len;
void *data_received;
long data_received_len;
data_callback_func data_callback_func;
int log_mask;
lws_sorted_usec_list_t sul; /* schedule connection retry */
struct lws *wsi; /* related wsi if any */
uint16_t retry_count; /* count of consequetive retries */
sslConfig_t *ssl_config;
list_t *api_tokens;
} wsclient_t;
wsclient_t *wsclient_create(const char *, sslConfig_t *, list_t *, int);
void wsclient_free(wsclient_t *);
int wsclient_run(wsclient_t *, wsc_mode_t);
#ifdef __cplusplus
}
#endif
#endif /* _WSCLIENT_H */
|
1e6dae37e3c02ece39a09f7102182e996207d186
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/video/sunxi/disp2/disp/de/lowlevel_sun50iw1/de_vsu.c
|
081656a4cac51dc94f3cd72cad4e546c85815b7b
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 28,646
|
c
|
de_vsu.c
|
//*********************************************************************************************************************
// All Winner Tech, All Right Reserved. 2014-2015 Copyright (c)
//
// File name : de_vsu.c
//
// Description : display engine 2.0 vsu basic function definition
//
// History : 2014/03/20 vito cheng v0.1 Initial version
//
//*********************************************************************************************************************
#include "de_vsu_type.h"
#include "de_scaler.h"
#include "de_scaler_table.h"
static volatile __vsu_reg_t *vsu_dev[DEVICE_NUM][VI_CHN_NUM];
static de_reg_blocks vsu_glb_block[DEVICE_NUM][VI_CHN_NUM];
static de_reg_blocks vsu_out_block[DEVICE_NUM][VI_CHN_NUM];
static de_reg_blocks vsu_yscale_block[DEVICE_NUM][VI_CHN_NUM];
static de_reg_blocks vsu_cscale_block[DEVICE_NUM][VI_CHN_NUM];
static de_reg_blocks vsu_yhcoeff0_block[DEVICE_NUM][VI_CHN_NUM];
static de_reg_blocks vsu_yhcoeff1_block[DEVICE_NUM][VI_CHN_NUM];
static de_reg_blocks vsu_yvcoeff_block[DEVICE_NUM][VI_CHN_NUM];
static de_reg_blocks vsu_chcoeff0_block[DEVICE_NUM][VI_CHN_NUM];
static de_reg_blocks vsu_chcoeff1_block[DEVICE_NUM][VI_CHN_NUM];
static de_reg_blocks vsu_cvcoeff_block[DEVICE_NUM][VI_CHN_NUM];
int de_vsu_update_regs(unsigned int sel)
{
int i,chno;
chno=de_feat_get_num_vi_chns(sel);
for (i=0;i<chno;i++)
{
if (vsu_glb_block[sel][i].dirty == 0x1){
memcpy((void *)vsu_glb_block[sel][i].off,vsu_glb_block[sel][i].val,vsu_glb_block[sel][i].size);
vsu_glb_block[sel][i].dirty = 0x0;}
if (vsu_out_block[sel][i].dirty == 0x1){
memcpy((void *)vsu_out_block[sel][i].off,vsu_out_block[sel][i].val,vsu_out_block[sel][i].size);
vsu_out_block[sel][i].dirty = 0x0;}
if (vsu_yscale_block[sel][i].dirty == 0x1){
memcpy((void *)vsu_yscale_block[sel][i].off,vsu_yscale_block[sel][i].val,vsu_yscale_block[sel][i].size);
vsu_yscale_block[sel][i].dirty = 0x0;}
if (vsu_cscale_block[sel][i].dirty == 0x1){
memcpy((void *)vsu_cscale_block[sel][i].off,vsu_cscale_block[sel][i].val,vsu_cscale_block[sel][i].size);
vsu_cscale_block[sel][i].dirty = 0x0;}
if (vsu_yhcoeff0_block[sel][i].dirty == 0x1){
memcpy((void *)vsu_yhcoeff0_block[sel][i].off,vsu_yhcoeff0_block[sel][i].val,vsu_yhcoeff0_block[sel][i].size);
memcpy((void *)vsu_yhcoeff1_block[sel][i].off,vsu_yhcoeff1_block[sel][i].val,vsu_yhcoeff1_block[sel][i].size);
memcpy((void *)vsu_yvcoeff_block[sel][i].off,vsu_yvcoeff_block[sel][i].val,vsu_yvcoeff_block[sel][i].size);
memcpy((void *)vsu_chcoeff0_block[sel][i].off,vsu_chcoeff0_block[sel][i].val,vsu_chcoeff0_block[sel][i].size);
memcpy((void *)vsu_chcoeff1_block[sel][i].off,vsu_chcoeff1_block[sel][i].val,vsu_chcoeff1_block[sel][i].size);
memcpy((void *)vsu_cvcoeff_block[sel][i].off,vsu_cvcoeff_block[sel][i].val,vsu_cvcoeff_block[sel][i].size);
vsu_yhcoeff0_block[sel][i].dirty = 0x0;}
}
return 0;
}
int de_vsu_init(unsigned int sel, uintptr_t reg_base)
{
int j, chno;
uintptr_t vsu_base;
void *memory;
chno = de_feat_get_num_vi_chns(sel);
for (j=0;j<chno;j++)
{
vsu_base = reg_base + (sel+1)*0x00100000 + VSU_OFST + j*0x20000; //display path offset should be defined
memory = (void *)kmalloc(sizeof(__vsu_reg_t), GFP_KERNEL | __GFP_ZERO);
if (NULL == memory) {
__wrn("malloc video scaler[%d][%d] memory fail! size=0x%x\n", sel, j, (unsigned int)sizeof(__vsu_reg_t));
return -1;
}
vsu_glb_block[sel][j].off = vsu_base;
vsu_glb_block[sel][j].val = memory;
vsu_glb_block[sel][j].size = 0x10;
vsu_glb_block[sel][j].dirty = 0;
vsu_out_block[sel][j].off = vsu_base + 0x40;
vsu_out_block[sel][j].val = memory + 0x40;
vsu_out_block[sel][j].size = 0x4;
vsu_out_block[sel][j].dirty = 0;
vsu_yscale_block[sel][j].off = vsu_base + 0x80;
vsu_yscale_block[sel][j].val = memory + 0x80;
vsu_yscale_block[sel][j].size = 0x20;
vsu_yscale_block[sel][j].dirty = 0;
vsu_cscale_block[sel][j].off = vsu_base + 0xc0;
vsu_cscale_block[sel][j].val = memory + 0xc0;
vsu_cscale_block[sel][j].size = 0x20;
vsu_cscale_block[sel][j].dirty = 0;
vsu_yhcoeff0_block[sel][j].off = vsu_base + 0x200;
vsu_yhcoeff0_block[sel][j].val = memory + 0x200;
vsu_yhcoeff0_block[sel][j].size = 0x80;
vsu_yhcoeff1_block[sel][j].off = vsu_base + 0x300;
vsu_yhcoeff1_block[sel][j].val = memory + 0x300;
vsu_yhcoeff1_block[sel][j].size = 0x80;
vsu_yvcoeff_block[sel][j].off = vsu_base + 0x400;
vsu_yvcoeff_block[sel][j].val = memory + 0x400;
vsu_yvcoeff_block[sel][j].size = 0x80;
vsu_chcoeff0_block[sel][j].off = vsu_base + 0x600;
vsu_chcoeff0_block[sel][j].val = memory + 0x600;
vsu_chcoeff0_block[sel][j].size = 0x80;
vsu_chcoeff1_block[sel][j].off = vsu_base + 0x700;
vsu_chcoeff1_block[sel][j].val = memory + 0x700;
vsu_chcoeff1_block[sel][j].size = 0x80;
vsu_cvcoeff_block[sel][j].off = vsu_base + 0x800;
vsu_cvcoeff_block[sel][j].val = memory + 0x800;
vsu_cvcoeff_block[sel][j].size = 0x80;
vsu_yhcoeff0_block[sel][j].dirty = 0; //only use one para to represent all coeff block
de_vsu_set_reg_base(sel, j, memory);
}
return 0;
}
//*********************************************************************************************************************
// function : de_vsu_set_reg_base(unsigned int sel, unsigned int chno, void *base)
// description : set vsu reg base
// parameters :
// sel <rtmx select>
// chno <overlay select>
// base <reg base>
// return :
// success
//*********************************************************************************************************************
int de_vsu_set_reg_base(unsigned int sel, unsigned int chno, void *base)
{
__inf("sel=%d, chno=%d, base=0x%p\n", sel, chno, base);
vsu_dev[sel][chno] = (__vsu_reg_t *)base;
return 0;
}
//*********************************************************************************************************************
// function : de_vsu_enable(unsigned int sel, unsigned int chno, unsigned int en)
// description : enable/disable vsu
// parameters :
// sel <rtmx select>
// chno <overlay select>
// en <enable: 0-diable; 1-enable>
// return :
// success
//*********************************************************************************************************************
int de_vsu_enable(unsigned int sel, unsigned int chno, unsigned int en)
{
vsu_dev[sel][chno]->ctrl.bits.en = en;
vsu_glb_block[sel][chno].dirty = 1;
return 0;
}
//*********************************************************************************************************************
// function : de_vsu_calc_fir_coef(unsigned int step)
// description : set fir coefficients
// parameters :
// step <horizontal scale ratio of vsu>
// return :
// offset (in word) of coefficient table
//*********************************************************************************************************************
static unsigned int de_vsu_calc_fir_coef(unsigned int step)
{
unsigned int pt_coef;
unsigned int scale_ratio, int_part, float_part, fir_coef_ofst;
scale_ratio = step>>(VSU_PHASE_FRAC_BITWIDTH-3);
int_part = scale_ratio>>3;
float_part = scale_ratio & 0x7;
fir_coef_ofst = (int_part==0) ? VSU_ZOOM0_SIZE :
(int_part==1) ? VSU_ZOOM0_SIZE + float_part :
(int_part==2) ? VSU_ZOOM0_SIZE + VSU_ZOOM1_SIZE + (float_part>>1) :
(int_part==3) ? VSU_ZOOM0_SIZE + VSU_ZOOM1_SIZE + VSU_ZOOM2_SIZE :
(int_part==4) ? VSU_ZOOM0_SIZE + VSU_ZOOM1_SIZE + VSU_ZOOM2_SIZE + VSU_ZOOM3_SIZE :
VSU_ZOOM0_SIZE + VSU_ZOOM1_SIZE + VSU_ZOOM2_SIZE + VSU_ZOOM3_SIZE + VSU_ZOOM4_SIZE;
pt_coef = fir_coef_ofst * VSU_PHASE_NUM ;
return pt_coef;
}
//*********************************************************************************************************************
// function : de_vsu_set_para(unsigned int sel, unsigned int chno, unsigned int *coef)
// description : set fir coefficients
// parameters :
// sel <rtmx select>
// chno <overlay select>
// *coef <coefficients pointer>
// return :
// success
//*********************************************************************************************************************
int de_vsu_set_para(unsigned int sel, unsigned int chno, unsigned int enable, unsigned char fmt,
unsigned int in_w, unsigned int in_h,unsigned int out_w, unsigned int out_h,
scaler_para *ypara,scaler_para *cpara)
{
unsigned int pt_coef,in_cw,in_ch,format;
__inf("sel%d, ch %d, en=%d, in<%dx%d>,out<%dx%d>\n", sel, chno, enable, in_w, in_h, out_w, out_h);
vsu_dev[sel][chno]->ctrl.bits.en = enable;
if (0==enable)
{
vsu_glb_block[sel][chno].dirty = 1;
return 0;
}
switch(fmt)
{
case DE_FORMAT_YUV422_I_YVYU:
case DE_FORMAT_YUV422_I_YUYV:
case DE_FORMAT_YUV422_I_UYVY:
case DE_FORMAT_YUV422_I_VYUY:
case DE_FORMAT_YUV422_P:
case DE_FORMAT_YUV422_SP_UVUV:
case DE_FORMAT_YUV422_SP_VUVU:
{
in_cw =(in_w+1)>>1;
in_ch =in_h;
format = VSU_FORMAT_YUV422;
break;
}
case DE_FORMAT_YUV420_P:
case DE_FORMAT_YUV420_SP_UVUV:
case DE_FORMAT_YUV420_SP_VUVU:
{
in_cw =(in_w+1)>>1;
in_ch =(in_h+1)>>1;
format = VSU_FORMAT_YUV420;
break;
}
case DE_FORMAT_YUV411_P:
case DE_FORMAT_YUV411_SP_UVUV:
case DE_FORMAT_YUV411_SP_VUVU:
{
in_cw =(in_w+3)>>2;
in_ch =in_h;
format = VSU_FORMAT_YUV411;
break;
}
default:
in_cw =in_w;
in_ch =in_h;
format = VSU_FORMAT_RGB;
break;
}
//basic parameter
vsu_dev[sel][chno]->outsize.dwval = ((out_h - 1)<<16) | (out_w - 1);
vsu_dev[sel][chno]->ysize.dwval = ((in_h - 1)<<16) | (in_w - 1);
vsu_dev[sel][chno]->csize.dwval = ((in_ch - 1)<<16) | (in_cw - 1);
vsu_dev[sel][chno]->yhstep.dwval = ypara->hstep<<VSU_PHASE_FRAC_REG_SHIFT;
vsu_dev[sel][chno]->yvstep.dwval = ypara->vstep<<VSU_PHASE_FRAC_REG_SHIFT;
vsu_dev[sel][chno]->chstep.dwval = cpara->hstep<<VSU_PHASE_FRAC_REG_SHIFT;
vsu_dev[sel][chno]->cvstep.dwval = cpara->vstep<<VSU_PHASE_FRAC_REG_SHIFT;
vsu_dev[sel][chno]->yhphase.dwval = ypara->hphase<<VSU_PHASE_FRAC_REG_SHIFT;
vsu_dev[sel][chno]->yvphase0.dwval = ypara->vphase<<VSU_PHASE_FRAC_REG_SHIFT;
//modify 14-11-8
vsu_dev[sel][chno]->chphase.dwval = cpara->hphase<<VSU_PHASE_FRAC_REG_SHIFT;
vsu_dev[sel][chno]->cvphase0.dwval = cpara->vphase<<VSU_PHASE_FRAC_REG_SHIFT;
//fir coefficient
//ch0
pt_coef = de_vsu_calc_fir_coef(ypara->hstep);
memcpy(&vsu_dev[sel][chno]->yhcoeff0, lan3coefftab32_left+pt_coef, sizeof(unsigned int)*VSU_PHASE_NUM);
memcpy(&vsu_dev[sel][chno]->yhcoeff1, lan3coefftab32_right+pt_coef, sizeof(unsigned int)*VSU_PHASE_NUM);
pt_coef = de_vsu_calc_fir_coef(ypara->vstep);
memcpy(&vsu_dev[sel][chno]->yvcoeff, lan2coefftab32+pt_coef, sizeof(unsigned int)*VSU_PHASE_NUM);
//ch1/2
if (VSU_FORMAT_RGB == format)
{
pt_coef = de_vsu_calc_fir_coef(cpara->hstep);
memcpy(&vsu_dev[sel][chno]->chcoeff0, lan3coefftab32_left+pt_coef, sizeof(unsigned int)*VSU_PHASE_NUM);
memcpy(&vsu_dev[sel][chno]->chcoeff1, lan3coefftab32_right+pt_coef, sizeof(unsigned int)*VSU_PHASE_NUM);
pt_coef = de_vsu_calc_fir_coef(cpara->vstep);
memcpy(&vsu_dev[sel][chno]->cvcoeff, lan2coefftab32+pt_coef, sizeof(unsigned int)*VSU_PHASE_NUM);
}
else
{
pt_coef = de_vsu_calc_fir_coef(cpara->hstep);
memcpy(&vsu_dev[sel][chno]->chcoeff0, bicubic8coefftab32_left+pt_coef, sizeof(unsigned int)*VSU_PHASE_NUM);
memcpy(&vsu_dev[sel][chno]->chcoeff1, bicubic8coefftab32_right+pt_coef, sizeof(unsigned int)*VSU_PHASE_NUM);
pt_coef = de_vsu_calc_fir_coef(cpara->vstep);
memcpy(&vsu_dev[sel][chno]->cvcoeff, bicubic4coefftab32+pt_coef, sizeof(unsigned int)*VSU_PHASE_NUM);
}
vsu_dev[sel][chno]->ctrl.bits.coef_switch_rdy = 1;
vsu_glb_block[sel][chno].dirty = 1;
vsu_out_block[sel][chno].dirty = 1;
vsu_yscale_block[sel][chno].dirty = 1;
vsu_cscale_block[sel][chno].dirty = 1;
vsu_yhcoeff0_block[sel][chno].dirty = 1;
return 0;
}
//*********************************************************************************************************************
// function : de_vsu_calc_scaler_para(unsigned char fmt, de_rect64 crop, de_rect frame, de_rect *crop_fix,
// scaler_para *ypara,scaler_para *cpara)
// description : calculate scaler parameters
// parameters :
// fmt <format>
// crop.w <framebuffer crop width with 32bit fraction part>
// crop.h <framebuffer crop height with 32bit fraction part>
// crop.x <framebuffer coordinate x with 32bit fraction part>
// crop.y <framebuffer coordinate y with 32bit fraction part>
// frame.w <frame width in integer>
// frame.h <frame height in integer>
// crop_fix->w<framebuffer crop_fix width after fixed>
// crop_fix->h<framebuffer crop_fix height after fixed>
// crop_fix->x<framebuffer crop_fix coordinate x after fixed>
// crop_fix->y<framebuffer crop_fix coordinate y after fixed>
// yhstep <y/r channel horizon scale ratio>
// yvstep <y/r channel vertical scale ratio>
// yhphase <y/r channel horizon initial phase>
// yvphase <y/r channel vertical initial phase>
// chstep <uv/gb channel horizon scale ratio>
// cvstep <uv/gb channel vertical scale ratio>
// chphase <uv/gb channel horizon initial phase>
// cvphase <uv/gb channel vertical initial phase>
// return :
// success
//*********************************************************************************************************************
int de_vsu_calc_scaler_para(unsigned char fmt, de_rect64 crop, de_rect frame, de_rect *crop_fix,
scaler_para *ypara,scaler_para *cpara)
{
int format;
unsigned long long tmp = 0;
switch(fmt)
{
case DE_FORMAT_YUV422_I_YVYU:
case DE_FORMAT_YUV422_I_YUYV:
case DE_FORMAT_YUV422_I_UYVY:
case DE_FORMAT_YUV422_I_VYUY:
case DE_FORMAT_YUV422_P:
case DE_FORMAT_YUV422_SP_UVUV:
case DE_FORMAT_YUV422_SP_VUVU:
{
format = VSU_FORMAT_YUV422;break;
}
case DE_FORMAT_YUV420_P:
case DE_FORMAT_YUV420_SP_UVUV:
case DE_FORMAT_YUV420_SP_VUVU:
{
format = VSU_FORMAT_YUV420;break;
}
case DE_FORMAT_YUV411_P:
case DE_FORMAT_YUV411_SP_UVUV:
case DE_FORMAT_YUV411_SP_VUVU:
{
format = VSU_FORMAT_YUV411;break;
}
default:
format = VSU_FORMAT_RGB;break;
}
tmp = (N2_POWER(crop.w,VSU_PHASE_FRAC_BITWIDTH));
if (frame.w)
do_div(tmp, frame.w);
else
tmp = 0;
ypara->hstep= (unsigned int)(tmp>>VSU_FB_FRAC_BITWIDTH);
tmp = (N2_POWER(crop.h,VSU_PHASE_FRAC_BITWIDTH));
if (frame.h)
do_div(tmp, frame.h);
else
tmp = 0;
ypara->vstep= (unsigned int)(tmp>>VSU_FB_FRAC_BITWIDTH);
ypara->hphase = ((crop.x & 0xffffffff)>>(32-VSU_PHASE_FRAC_BITWIDTH));
ypara->vphase = ((crop.y & 0xffffffff)>>(32-VSU_PHASE_FRAC_BITWIDTH));
crop_fix->w = (unsigned int)(((crop.w & 0xffffffff) + (crop.x & 0xffffffff))>= N2_POWER(1,VSU_FB_FRAC_BITWIDTH)?
((crop.w>>VSU_FB_FRAC_BITWIDTH) + 1) : (crop.w>>VSU_FB_FRAC_BITWIDTH));
crop_fix->h = (unsigned int)(((crop.h & 0xffffffff) + (crop.y & 0xffffffff))>= N2_POWER(1,VSU_FB_FRAC_BITWIDTH)?
((crop.h>>VSU_FB_FRAC_BITWIDTH) + 1) : (crop.h>>VSU_FB_FRAC_BITWIDTH));
crop_fix->x = (int)(crop.x>>VSU_FB_FRAC_BITWIDTH);
crop_fix->y = (int)(crop.y>>VSU_FB_FRAC_BITWIDTH);
if (VSU_FORMAT_RGB == format)
{
cpara->hstep = ypara->hstep;
cpara->vstep = ypara->vstep;
cpara->hphase = ypara->hphase;
cpara->vphase = ypara->vphase;
}
else if (VSU_FORMAT_YUV422 == format)
{
//horizon crop info fix
if ((crop_fix->x & 0x1) == 0x0 && (crop_fix->w & 0x1) == 0x1) //odd crop_w, crop down width, last line may disappear
{
crop_fix->w = (crop_fix->w>>1)<<1;
}
else if ((crop_fix->x & 0x1) == 0x1 && (crop_fix->w & 0x1) == 0x0) //odd crop_x, crop down x, and phase + 1
{
crop_fix->x = (crop_fix->x>>1)<<1;
ypara->hphase = ypara->hphase + (unsigned int)(N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH));
}
else if ((crop_fix->x & 0x1) == 0x1 && (crop_fix->w & 0x1) == 0x1) //odd crop_x and crop_w, crop_x - 1, and phase + 1, crop_w + 1
{
crop_fix->x = (crop_fix->x>>1)<<1;
ypara->hphase = ypara->hphase + (unsigned int)(N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH));
crop_fix->w = ((crop_fix->w + 1)>>1)<<1;
}
cpara->hstep = ypara->hstep>>1;
cpara->vstep = ypara->vstep;
cpara->hphase = ypara->hphase;
cpara->vphase = ypara->vphase;
}
else if (VSU_FORMAT_YUV420 == format)
{
//horizon crop info fix
if ((crop_fix->x & 0x1) == 0x0 && (crop_fix->w & 0x1) == 0x1) //odd crop_w, crop down width, last line may disappear
{
crop_fix->w = (crop_fix->w>>1)<<1;
}
else if ((crop_fix->x & 0x1) == 0x1 && (crop_fix->w & 0x1) == 0x0) //odd crop_x, crop down x, and phase + 1
{
crop_fix->x = (crop_fix->x>>1)<<1;
ypara->hphase = ypara->hphase + (unsigned int)(N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH));
}
else if ((crop_fix->x & 0x1) == 0x1 && (crop_fix->w & 0x1) == 0x1) //odd crop_x and crop_w, crop_x - 1, and phase + 1, crop_w + 1
{
crop_fix->x = (crop_fix->x>>1)<<1;
ypara->hphase = ypara->hphase + (unsigned int)(N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH));
crop_fix->w = ((crop_fix->w + 1)>>1)<<1;
}
//vertical crop info fix
if ((crop_fix->y & 0x1) == 0x0 && (crop_fix->h & 0x1) == 0x1) //odd crop_h, crop down height, last line may disappear
{
crop_fix->h = (crop_fix->h>>1)<<1;
}
else if ((crop_fix->y & 0x1) == 0x1 && (crop_fix->h & 0x1) == 0x0) //odd crop_y, crop down y, and phase + 1
{
crop_fix->y = (crop_fix->y>>1)<<1;
ypara->vphase = ypara->vphase + (unsigned int)(N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH));
}
else if ((crop_fix->y & 0x1) == 0x1 && (crop_fix->h & 0x1) == 0x1) //odd crop_y and crop_h, crop_y - 1, and phase + 1, crop_h + 1
{
crop_fix->y = (crop_fix->y>>1)<<1;
ypara->vphase = ypara->vphase + (unsigned int)(N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH));
crop_fix->h = ((crop_fix->h + 1)>>1)<<1;
}
cpara->hstep = ypara->hstep>>1;
cpara->vstep = ypara->vstep>>1;
//cpara->hphase = (ypara->hphase>>1) - ((N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH))>>2); //H.261, H.263, MPEG-1 sample method
cpara->hphase = ypara->hphase>>1; //MPEG-2, MPEG-4.2, H264, VC-1 sample method (default choise)
cpara->vphase = (ypara->vphase>>1) - ((N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH))>>2); //chorma vertical phase should -0.25 when input format is yuv420
}
else if (VSU_FORMAT_YUV411 == format)
{
//horizon crop info
if ((crop_fix->x & 0x3) == 0x0 && (crop_fix->w & 0x3) != 0x0) //odd crop_w, crop down width, last 1-3 lines may disappear
{
crop_fix->w = (crop_fix->w>>2)<<2;
}
else if ((crop_fix->x & 0x3) != 0x0 && (crop_fix->w & 0x3) == 0x0) //odd crop_x, crop down x, and phase + 1
{
crop_fix->x = (crop_fix->x>>2)<<2;
ypara->hphase = ypara->hphase + (unsigned int)(N2_POWER(crop_fix->x & 0x3,VSU_PHASE_FRAC_BITWIDTH));
}
else if ((crop_fix->x & 0x3) != 0x0 && (crop_fix->w & 0x3) != 0x0) //odd crop_x and crop_w, crop_x aligned to 4 pixel
{
crop_fix->x = (crop_fix->x>>2)<<2;
ypara->hphase = ypara->hphase + (unsigned int)(N2_POWER(crop_fix->x & 0x3,VSU_PHASE_FRAC_BITWIDTH));
crop_fix->w = ((crop_fix->w + (crop_fix->x & 0x3))>>2)<<2;
}
cpara->hstep = ypara->hstep>>2;
cpara->vstep = ypara->vstep;
cpara->hphase = ypara->hphase;
cpara->vphase = ypara->vphase;
}
return 0;
}
//*********************************************************************************************************************
// function : de_vsu_sel_ovl_scaler_para(unsigned char *en, scaler_para *layer_luma_scale_para[], scaler_para *layer_chroma_scale_para[],
// scaler_para *ovl_luma_scale_para, scaler_para *ovl_chroma_scale_para)
// description : calculate video overlay scaler parameters
// parameters :
// en <pointer of layer enable>
// layer_luma_scale_para <pointer array of video layer luma channel scaler parameter>
// layer_chroma_scale_para <pointer array of video layer chroma channel scaler parameter>
// ovl_luma_scale_para <pointer of video overlay luma channel scaler parameter>
// ovl_chroma_scale_para <pointer of video overlay chroma channel scaler parameter>
// return :
// success
//*********************************************************************************************************************
int de_vsu_sel_ovl_scaler_para(unsigned char *en, scaler_para *layer_luma_scale_para, scaler_para *layer_chroma_scale_para,
scaler_para *ovl_luma_scale_para, scaler_para *ovl_chroma_scale_para)
{
int i, j, layer_en_num;
int used_layer_idx[LAYER_MAX_NUM_PER_CHN];
//get valid layer number and record layer index
layer_en_num = 0;
j = 0;
for (i=0; i<LAYER_MAX_NUM_PER_CHN; i++)
{
if (*(en + i) == 1)
{
layer_en_num++;
used_layer_idx[j++] = i;
}
}
if (layer_en_num==1) //only one layer enabled in one overlay
{
//set overlay scale para through this layer
ovl_luma_scale_para->hphase = layer_luma_scale_para[used_layer_idx[0]].hphase;
ovl_luma_scale_para->vphase = layer_luma_scale_para[used_layer_idx[0]].vphase;
ovl_luma_scale_para->hstep = layer_luma_scale_para[used_layer_idx[0]].hstep;
ovl_luma_scale_para->vstep = layer_luma_scale_para[used_layer_idx[0]].vstep;
// FIXME
ovl_chroma_scale_para->hphase = layer_chroma_scale_para[used_layer_idx[0]].hphase;
ovl_chroma_scale_para->vphase = layer_chroma_scale_para[used_layer_idx[0]].vphase;
ovl_chroma_scale_para->hstep = layer_chroma_scale_para[used_layer_idx[0]].hstep;
ovl_chroma_scale_para->vstep = layer_chroma_scale_para[used_layer_idx[0]].vstep;
//
}
else if (layer_en_num>1) //two or more layers enabled in one overlay
{
//set overlay scale step through first enabled layer
ovl_luma_scale_para->hstep = layer_luma_scale_para[used_layer_idx[0]].hstep;
ovl_luma_scale_para->vstep = layer_luma_scale_para[used_layer_idx[0]].vstep;
ovl_chroma_scale_para->hstep = layer_chroma_scale_para[used_layer_idx[0]].hstep;
ovl_chroma_scale_para->vstep = layer_chroma_scale_para[used_layer_idx[0]].vstep;
//set overlay phase through first enabled non-zero-phase layer
for (i=0; i<layer_en_num; i++)
{
if (layer_luma_scale_para[used_layer_idx[i]].hphase != 0)
{
ovl_luma_scale_para->hphase = layer_luma_scale_para[used_layer_idx[i]].hphase;
ovl_chroma_scale_para->hphase = layer_chroma_scale_para[used_layer_idx[i]].hphase;
break;
}
}
//all layer phase equal to zero
if (i == layer_en_num)
{
ovl_luma_scale_para->hphase = layer_luma_scale_para[used_layer_idx[0]].hphase;
ovl_chroma_scale_para->hphase = layer_chroma_scale_para[used_layer_idx[0]].hphase;
}
//set overlay phase through first non-zero layer
for (i=0; i<layer_en_num; i++)
{
if (layer_luma_scale_para[used_layer_idx[i]].vphase != 0)
{
ovl_luma_scale_para->vphase = layer_luma_scale_para[used_layer_idx[i]].vphase;
ovl_chroma_scale_para->vphase = layer_chroma_scale_para[used_layer_idx[i]].vphase;
break;
}
}
//all layer phase equal to zero
if (i == layer_en_num)
{
ovl_luma_scale_para->vphase = layer_luma_scale_para[used_layer_idx[0]].vphase;
ovl_chroma_scale_para->vphase = layer_chroma_scale_para[used_layer_idx[0]].vphase;
}
}
else
{
ovl_luma_scale_para->hphase = 0;
ovl_luma_scale_para->vphase = 0;
ovl_luma_scale_para->hstep = (unsigned int)N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH);
ovl_luma_scale_para->vstep = (unsigned int)N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH);
ovl_chroma_scale_para->hphase = 0;
ovl_chroma_scale_para->vphase = 0;
ovl_chroma_scale_para->hstep = (unsigned int)N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH);
ovl_chroma_scale_para->vstep = (unsigned int)N2_POWER(1,VSU_PHASE_FRAC_BITWIDTH);
}
return 0;
}
//*********************************************************************************************************************
// function : de_vsu_recalc_scale_para(int coarse_status, unsigned int vsu_outw, unsigned int vsu_outh,
// unsigned int vsu_inw, unsigned int vsu_inh, unsigned int vsu_inw_c, unsigned int vsu_inh_c
// scale_para *fix_y_para, scale_para *fix_c_para)
// description : recalculate scale para through coarse status
// parameters :
// coarse_status <0-no coarse scale in both direction,
// 1-coarse scale only in horizon,
// 2-coarse scale only in vertical,
// 3-coarse scale in both direction>
// vsu_outw,vsu_outh <vsu output size>
// vsu_inw,vsu_inh <vsu input y size>
// vsu_inw_c,vsu_inh_c <vsu input cbcr size>
// fix_y_para <vsu y channel fixed scale para>
// fix_c_para <vsu cbcr channel fixed scale para>
// return :
// success
//*********************************************************************************************************************
int de_vsu_recalc_scale_para(int coarse_status, unsigned int vsu_outw, unsigned int vsu_outh,
unsigned int vsu_inw, unsigned int vsu_inh, unsigned int vsu_inw_c, unsigned int vsu_inh_c,
scaler_para *fix_y_para, scaler_para *fix_c_para)
{
unsigned int tmp = 0;
if (coarse_status & DE_CS_HORZ)
{
tmp = N2_POWER(vsu_inw, VSU_PHASE_FRAC_BITWIDTH);
tmp = tmp / vsu_outw;
fix_y_para->hstep = tmp;
tmp = N2_POWER(vsu_inw_c, VSU_PHASE_FRAC_BITWIDTH);
tmp = tmp / vsu_outw;
fix_c_para->hstep = tmp;
fix_y_para->hphase = 0; //no meaning when coarse scale using
fix_c_para->hphase = 0; //no meaning when coarse scale using
}
if (coarse_status & DE_CS_VERT)
{
tmp = N2_POWER(vsu_inh, VSU_PHASE_FRAC_BITWIDTH);
tmp = tmp / vsu_outh;
fix_y_para->vstep = tmp;
tmp = N2_POWER(vsu_inh_c, VSU_PHASE_FRAC_BITWIDTH);
tmp = tmp / vsu_outh;
fix_c_para->vstep = tmp;
fix_y_para->vphase = 0; //no meaning when coarse scale using
fix_c_para->vphase = 0; //no meaning when coarse scale using
}
return 0;
}
//*********************************************************************************************************************
// function : de_recalc_ovl_bld_for_scale((unsigned int scaler_en, unsigned char *lay_en, int laynum, scaler_para *step,
// de_rect *layer, de_rect *bld_rect, unsigned int *ovlw, unsigned int *ovlh,
// unsigned int gsu_sel, unsigned int scn_w, unsigned scn_h)
// description : recalculate overlay and blending parameters for scaler size limitation
//
//*********************************************************************************************************************
int de_recalc_ovl_bld_for_scale(unsigned int scaler_en, unsigned char *lay_en, int laynum, scaler_para *step,
de_rect *layer, de_rect *bld_rect, unsigned int *ovlw, unsigned int *ovlh,
unsigned int gsu_sel, unsigned int scn_w, unsigned scn_h)
{
unsigned int shift, i;
unsigned int org_bld_w, org_bld_h;
if (scaler_en==0)
return 0;
if (*ovlw != 0 && *ovlh != 0 && bld_rect->w != 0 && bld_rect->h != 0 && step->hstep != 0 && step->vstep != 0)
{
//horizon
if (*ovlw < SC_MIN_WIDTH || bld_rect->w < SC_MIN_WIDTH)
{
shift = (gsu_sel==0)?VSU_PHASE_FRAC_BITWIDTH : GSU_PHASE_FRAC_BITWIDTH;
org_bld_w = bld_rect->w;
if (step->hstep > (1<<shift)) //scale down
{
bld_rect->w = SC_MIN_WIDTH;
*ovlw = (step->hstep*SC_MIN_WIDTH)>>shift;
}
else //scale up
{
*ovlw = SC_MIN_WIDTH;
bld_rect->w = SC_MIN_WIDTH*(1<<shift)/step->hstep;
}
if (bld_rect->w + bld_rect->x > scn_w)
{
bld_rect->x -= (bld_rect->w - org_bld_w);
for (i=0;i<laynum;i++)
{
if (lay_en[i])
{
layer[i].x += ((step->hstep*(bld_rect->w - org_bld_w))>>shift);
}
}
}
}
//vertical
if (*ovlh < SC_MIN_HEIGHT || bld_rect->h< SC_MIN_HEIGHT)
{
shift = (gsu_sel==0)?VSU_PHASE_FRAC_BITWIDTH : GSU_PHASE_FRAC_BITWIDTH;
org_bld_h = bld_rect->h;
if (step->vstep > (1<<shift)) //scale down
{
bld_rect->h = SC_MIN_HEIGHT;
*ovlh = (step->vstep*SC_MIN_HEIGHT)>>shift;
}
else //scale up
{
*ovlh = SC_MIN_HEIGHT;
bld_rect->h = SC_MIN_HEIGHT*(1<<shift)/step->vstep;
}
if (bld_rect->h + bld_rect->y > scn_h)
{
bld_rect->y -= (bld_rect->h - org_bld_h);
for (i=0;i<laynum;i++)
{
if (lay_en[i])
{
layer[i].y += ((step->vstep*(bld_rect->h - org_bld_h))>>shift);
}
}
}
}
}
return 0 ;
}
|
3975f3b8bbc93400d6f5d6405e384f0a3975fafe
|
6f7788d4d4291021c4d01d845984db689c572632
|
/IDA_files/D750/D750_Services_1.10.idc
|
f8f732b5e027434291afe1b186ab178e75460155
|
[] |
no_license
|
simeonpilgrim/nikon-firmware-tools
|
f56de1d4f15b617a818c8c9eda1877d44b816354
|
2d63d451efb1457baeaa5be2368ff3123a652dd1
|
refs/heads/master
| 2023-04-04T12:06:46.828391
| 2023-03-28T02:26:43
| 2023-03-28T02:26:43
| 32,547,047
| 153
| 34
| null | 2022-12-18T03:47:31
| 2015-03-19T21:25:26
|
Java
|
UTF-8
|
C
| false
| false
| 5,459
|
idc
|
D750_Services_1.10.idc
|
#include <idc.idc>
static try_make_func(start, name, type)
{
auto addr;
if(start == 0)
return;
addr = start & 0xFFffFFfe;
if( addr != start )
{
SetReg(addr, "T", 1);
}
if(strlen(name) > 0 ){
MakeNameEx(addr, name, 0 );
}
MakeFunction(addr, BADADDR);
if(strlen(type) > 0 ){
SetType(addr, type);
}
}
static make_vtab(loc, name, type)
{
Message("loc: %x name: %s\n", loc, name);
MakeUnknown(loc, 0x10, 0 );
MakeStructEx(loc, 0x10, "vtab_ent");
MakeNameEx(loc, sprintf("%s_%s_vtab", type, name), 0);
try_make_func(Dword(loc), sprintf("%s_%s_create", type, name), "");
try_make_func(Dword(loc+4), sprintf("%s_%s_init", type, name), "");
try_make_func(Dword(loc+8), sprintf("%s_%s_start", type, name), "");
try_make_func(Dword(loc+0xc), sprintf("%s_%s_4", type, name), "");
}
static print_op(op)
{
//n, type, offb, offo, flags, dtyp, reg, value, addr, specval,specflag1, specflag2, specflag3, specflag4
Message(" n: %d type: %d offb: %x offo: %o flags: %x, dtyp: %d reg: %d value: %x addr: %x\n",op.n, op.type, op.offb, op.offo, op.flags, op.dtyp, op.reg, op.value, op.addr);
}
static srv_block(loc, type_name)
{
auto vtab_func, name_ea, name, obj;
vtab_func = Dword(loc);
name_ea = Dword(loc + 0xC );
name = GetString( name_ea, -1, ASCSTR_C );
// Fixup entry
MakeUnknown(loc, 0x10, 0 );
MakeStructEx(loc, 0x10, "srv_ent");
try_make_func(vtab_func, sprintf("get_%s_srv_vtab", name), "");
vtab_func = vtab_func & 0xFFffFFfe;
obj = DecodeInstruction(vtab_func);
//Message("ea %x name %s\n", vtab_func, name);
if( obj > 0 && obj.itype == 30 && obj.n == 2 )
{
//Message(" n %d itype %d\n", obj.n, obj.itype );
//print_op(obj.Op0);
//print_op(obj.Op1);
make_vtab(Dword(obj.Op1.addr), name, type_name);
}
}
static srv_blocks(start, end, type_name)
{
auto ea;
ea = start;
while( ea < end)
{
srv_block(ea, type_name);
ea = ea + 0x010;
}
}
static driver_block(loc)
{
auto vtab_func, name_ea, name, obj;
name_ea = Dword(loc + 0x1C );
name = GetString( name_ea, -1, ASCSTR_C );
// Fixup entry
MakeUnknown(loc, 0x20, 0 );
MakeStructEx(loc, 0x20, "driver_ent");
vtab_func = Dword(loc+4);
//Message("ea %x name %s 0x%x\n", loc, name, vtab_func);
if(vtab_func != 0)
{
try_make_func(vtab_func, sprintf("get_%s_drv_vtab", name), "");
vtab_func = vtab_func & 0xFFffFFfe;
obj = DecodeInstruction(vtab_func);
//Message("ea %x name %s\n", vtab_func, name);
if( obj > 0 && obj.itype == 30 && obj.n == 2 )
{
//Message(" n %d itype %d\n", obj.n, obj.itype );
//print_op(obj.Op0);
//print_op(obj.Op1);
make_vtab(Dword(obj.Op1.addr), name, "drv");
}
}
try_make_func(Dword(loc+0x8), sprintf("%s_%s_2", "drv", name), "");
try_make_func(Dword(loc+0xC), sprintf("%s_%s_3", "drv", name), "");
if(Dword(loc+0x10)>0)
{
MakeNameEx(Dword(loc+0x10), sprintf("%s_%s_data", "drv", name), 0);
}
}
static driver_blocks(start, end )
{
auto ea;
ea = start;
while( ea < end)
{
driver_block(ea);
ea = ea + 0x020;
}
}
static make_strucs()
{
auto id, mid;
if( GetStrucIdByName("srv_ent") == -1 )
{
id = AddStrucEx(-1,"srv_ent",0);
id = GetStrucIdByName("srv_ent");
mid = AddStrucMember(id,"get_vtab_func", 0x0, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
mid = AddStrucMember(id,"field_4", 0X4, 0x20000400, -1, 4);
mid = AddStrucMember(id,"field_8", 0X8, 0x20000400, -1, 4);
mid = AddStrucMember(id,"name", 0XC, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
}
if( GetStrucIdByName("vtab_ent") == -1 )
{
id = AddStrucEx(-1,"vtab_ent",0);
id = GetStrucIdByName("vtab_ent");
mid = AddStrucMember(id,"create_func", 0x0, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
mid = AddStrucMember(id,"init_func", 0X4, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
mid = AddStrucMember(id,"start_func", 0X8, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
mid = AddStrucMember(id,"ns_4_func", 0XC, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
}
if( GetStrucIdByName("driver_ent") == -1 )
{
id = AddStrucEx(-1,"driver_ent",0);
id = GetStrucIdByName("driver_ent");
mid = AddStrucMember(id,"field_0", 0X0, 0x20000400, -1, 4);
mid = AddStrucMember(id,"get_vtab_func", 0x4, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
mid = AddStrucMember(id,"func_2", 0x8, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
mid = AddStrucMember(id,"func_3", 0xC, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
mid = AddStrucMember(id,"data", 0x10, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
mid = AddStrucMember(id,"field_14", 0X14, 0x20000400, -1, 4);
mid = AddStrucMember(id,"field_18", 0X18, 0x20000400, -1, 4);
mid = AddStrucMember(id,"name", 0X1C, 0x20500400, 0, 4, 0XFFFFFFFF, 0, 0x000002);
}
}
static main()
{
make_strucs();
make_vtab(0x1003dd14, "Application", "");
srv_blocks(0x1003DD24, 0x1003DEF4, "app");
make_vtab(0x1003DEF4, "Service", "");
srv_blocks(0x1003DF04, 0x1003E094, "srv");
make_vtab(0x1003D6F0, "Driver", "");
driver_blocks(0x1003d700, 0x1003D9E0);
}
|
a7eb972a98cf569c4b35495ff01cad8052d4dd49
|
5de3ec4e6c65e60da1ed32b03748f96de7ef0b95
|
/Pods/Headers/Private/Realm/RLMObjectStore.h
|
e94e3dd2195451c709701920a2c49682165db309
|
[
"MIT"
] |
permissive
|
aaronpearce/DevSwitch
|
5154730f4f9eabcc14a6ad1222c6823b250b991e
|
98a1e6ded11907a02d21380ca93999d34b85b0b2
|
refs/heads/master
| 2021-06-10T22:56:56.239592
| 2021-06-04T21:25:40
| 2021-06-04T21:25:40
| 177,062,016
| 457
| 25
|
MIT
| 2019-03-24T22:37:41
| 2019-03-22T03:00:31
|
Swift
|
UTF-8
|
C
| false
| false
| 39
|
h
|
RLMObjectStore.h
|
../../../Realm/include/RLMObjectStore.h
|
50408b6834c3b6f052c78e01cfc9dc26b273e561
|
b452bbb87214f174122f425f6f98f4c3890c3cca
|
/internal/ccall/common/htmllex.c
|
ed98ca2ff3114cc0036d57fcd3d1756264298609
|
[
"MIT"
] |
permissive
|
goccy/go-graphviz
|
bea9bc86b42734aff7ffae283aeae71702ca588a
|
865af036ddbb745c4424bbd2fdaa9a75668cf0d4
|
refs/heads/master
| 2023-07-20T08:05:39.868377
| 2023-03-21T23:49:44
| 2023-03-21T23:49:44
| 236,740,615
| 511
| 66
|
MIT
| 2023-07-07T13:53:28
| 2020-01-28T13:24:09
|
Go
|
UTF-8
|
C
| false
| false
| 23,762
|
c
|
htmllex.c
|
/* $Id$ $Revision$ */
/* vim:set shiftwidth=4 ts=8: */
/*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************/
#include "render.h"
#include "htmltable.h"
#include "htmlparse.h"
#include "htmllex.h"
#include "cdt.h"
#include <ctype.h>
#ifdef HAVE_EXPAT
#include <expat.h>
#endif
#ifndef XML_STATUS_ERROR
#define XML_STATUS_ERROR 0
#endif
typedef struct {
#ifdef HAVE_EXPAT
XML_Parser parser;
#endif
char* ptr; /* input source */
int tok; /* token type */
agxbuf* xb; /* buffer to gather T_string data */
agxbuf lb; /* buffer for translating lexical data */
char warn; /* set if warning given */
char error; /* set if error given */
char inCell; /* set if in TD to allow T_string */
char mode; /* for handling artificial <HTML>..</HTML> */
char *currtok; /* for error reporting */
char *prevtok; /* for error reporting */
int currtoklen;
int prevtoklen;
} lexstate_t;
static lexstate_t state;
/* error_context:
* Print the last 2 "token"s seen.
*/
static void error_context(void)
{
agxbclear(state.xb);
if (state.prevtoklen > 0)
agxbput_n(state.xb, state.prevtok, state.prevtoklen);
agxbput_n(state.xb, state.currtok, state.currtoklen);
agerr(AGPREV, "... %s ...\n", agxbuse(state.xb));
}
/* htmlerror:
* yyerror - called by yacc output
*/
void htmlerror(const char *msg)
{
if (state.error)
return;
state.error = 1;
agerr(AGERR, "%s in line %d \n", msg, htmllineno());
error_context();
}
#ifdef HAVE_EXPAT
/* lexerror:
* called by lexer when unknown <..> is found.
*/
static void lexerror(const char *name)
{
state.tok = T_error;
state.error = 1;
agerr(AGERR, "Unknown HTML element <%s> on line %d \n",
name, htmllineno());
}
typedef int (*attrFn) (void *, char *);
typedef int (*bcmpfn) (const void *, const void *);
#define MAX_CHAR (((unsigned char)(~0)) >> 1)
#define MIN_CHAR ((signed char)(~MAX_CHAR))
#define MAX_UCHAR ((unsigned char)(~0))
#define MAX_USHORT ((unsigned short)(~0))
/* Mechanism for automatically processing attributes */
typedef struct {
char *name; /* attribute name */
attrFn action; /* action to perform if name matches */
} attr_item;
#define ISIZE (sizeof(attr_item))
/* icmp:
* Compare two attr_item. Used in bsearch
*/
static int icmp(attr_item * i, attr_item * j)
{
return strcasecmp(i->name, j->name);
}
static int bgcolorfn(htmldata_t * p, char *v)
{
p->bgcolor = strdup(v);
return 0;
}
static int pencolorfn(htmldata_t * p, char *v)
{
p->pencolor = strdup(v);
return 0;
}
static int hreffn(htmldata_t * p, char *v)
{
p->href = strdup(v);
return 0;
}
static int sidesfn(htmldata_t * p, char *v)
{
unsigned short flags = 0;
char c;
while ((c = *v++)) {
switch (tolower(c)) {
case 'l' :
flags |= BORDER_LEFT;
break;
case 't' :
flags |= BORDER_TOP;
break;
case 'r' :
flags |= BORDER_RIGHT;
break;
case 'b' :
flags |= BORDER_BOTTOM;
break;
default :
agerr(AGWARN, "Unrecognized character '%c' (%d) in sides attribute\n", c, c);
break;
}
}
if (flags != BORDER_MASK)
p->flags |= flags;
return 0;
}
static int titlefn(htmldata_t * p, char *v)
{
p->title = strdup(v);
return 0;
}
static int portfn(htmldata_t * p, char *v)
{
p->port = strdup(v);
return 0;
}
#define DELIM " ,"
static int stylefn(htmldata_t * p, char *v)
{
int rv = 0;
char c;
char* tk;
char* buf = strdup (v);
for (tk = strtok (buf, DELIM); tk; tk = strtok (NULL, DELIM)) {
c = (char) toupper(*tk);
if (c == 'R') {
if (!strcasecmp(tk + 1, "OUNDED")) p->style |= ROUNDED;
else if (!strcasecmp(tk + 1, "ADIAL")) p->style |= RADIAL;
else {
agerr(AGWARN, "Illegal value %s for STYLE - ignored\n", tk);
rv = 1;
}
}
else if(!strcasecmp(tk,"SOLID")) p->style &= ~(DOTTED|DASHED);
else if(!strcasecmp(tk,"INVISIBLE") || !strcasecmp(tk,"INVIS")) p->style |= INVISIBLE;
else if(!strcasecmp(tk,"DOTTED")) p->style |= DOTTED;
else if(!strcasecmp(tk,"DASHED")) p->style |= DASHED;
else {
agerr(AGWARN, "Illegal value %s for STYLE - ignored\n", tk);
rv = 1;
}
}
free (buf);
return rv;
}
static int targetfn(htmldata_t * p, char *v)
{
p->target = strdup(v);
return 0;
}
static int idfn(htmldata_t * p, char *v)
{
p->id = strdup(v);
return 0;
}
/* doInt:
* Scan v for integral value. Check that
* the value is >= min and <= max. Return value in ul.
* String s is name of value.
* Return 0 if okay; 1 otherwise.
*/
static int doInt(char *v, char *s, int min, int max, long *ul)
{
int rv = 0;
char *ep;
long b = strtol(v, &ep, 10);
if (ep == v) {
agerr(AGWARN, "Improper %s value %s - ignored", s, v);
rv = 1;
} else if (b > max) {
agerr(AGWARN, "%s value %s > %d - too large - ignored", s, v, max);
rv = 1;
} else if (b < min) {
agerr(AGWARN, "%s value %s < %d - too small - ignored", s, v, min);
rv = 1;
} else
*ul = b;
return rv;
}
static int gradientanglefn(htmldata_t * p, char *v)
{
long u;
if (doInt(v, "GRADIENTANGLE", 0, 360, &u))
return 1;
p->gradientangle = (unsigned short) u;
return 0;
}
static int borderfn(htmldata_t * p, char *v)
{
long u;
if (doInt(v, "BORDER", 0, MAX_UCHAR, &u))
return 1;
p->border = (unsigned char) u;
p->flags |= BORDER_SET;
return 0;
}
static int cellpaddingfn(htmldata_t * p, char *v)
{
long u;
if (doInt(v, "CELLPADDING", 0, MAX_UCHAR, &u))
return 1;
p->pad = (unsigned char) u;
p->flags |= PAD_SET;
return 0;
}
static int cellspacingfn(htmldata_t * p, char *v)
{
long u;
if (doInt(v, "CELLSPACING", MIN_CHAR, MAX_CHAR, &u))
return 1;
p->space = (signed char) u;
p->flags |= SPACE_SET;
return 0;
}
static int cellborderfn(htmltbl_t * p, char *v)
{
long u;
if (doInt(v, "CELLSBORDER", 0, MAX_CHAR, &u))
return 1;
p->cb = (unsigned char) u;
return 0;
}
static int columnsfn(htmltbl_t * p, char *v)
{
if (*v != '*') {
agerr(AGWARN, "Unknown value %s for COLUMNS - ignored\n", v);
return 1;
}
p->flags |= HTML_VRULE;
return 0;
}
static int rowsfn(htmltbl_t * p, char *v)
{
if (*v != '*') {
agerr(AGWARN, "Unknown value %s for ROWS - ignored\n", v);
return 1;
}
p->flags |= HTML_HRULE;
return 0;
}
static int fixedsizefn(htmldata_t * p, char *v)
{
int rv = 0;
char c = (char) toupper(*(unsigned char *) v);
if ((c == 'T') && !strcasecmp(v + 1, "RUE"))
p->flags |= FIXED_FLAG;
else if ((c != 'F') || strcasecmp(v + 1, "ALSE")) {
agerr(AGWARN, "Illegal value %s for FIXEDSIZE - ignored\n", v);
rv = 1;
}
return rv;
}
static int valignfn(htmldata_t * p, char *v)
{
int rv = 0;
char c = (char) toupper(*v);
if ((c == 'B') && !strcasecmp(v + 1, "OTTOM"))
p->flags |= VALIGN_BOTTOM;
else if ((c == 'T') && !strcasecmp(v + 1, "OP"))
p->flags |= VALIGN_TOP;
else if ((c != 'M') || strcasecmp(v + 1, "IDDLE")) {
agerr(AGWARN, "Illegal value %s for VALIGN - ignored\n", v);
rv = 1;
}
return rv;
}
static int halignfn(htmldata_t * p, char *v)
{
int rv = 0;
char c = (char) toupper(*v);
if ((c == 'L') && !strcasecmp(v + 1, "EFT"))
p->flags |= HALIGN_LEFT;
else if ((c == 'R') && !strcasecmp(v + 1, "IGHT"))
p->flags |= HALIGN_RIGHT;
else if ((c != 'C') || strcasecmp(v + 1, "ENTER")) {
agerr(AGWARN, "Illegal value %s for ALIGN - ignored\n", v);
rv = 1;
}
return rv;
}
static int cell_halignfn(htmldata_t * p, char *v)
{
int rv = 0;
char c = (char) toupper(*v);
if ((c == 'L') && !strcasecmp(v + 1, "EFT"))
p->flags |= HALIGN_LEFT;
else if ((c == 'R') && !strcasecmp(v + 1, "IGHT"))
p->flags |= HALIGN_RIGHT;
else if ((c == 'T') && !strcasecmp(v + 1, "EXT"))
p->flags |= HALIGN_TEXT;
else if ((c != 'C') || strcasecmp(v + 1, "ENTER"))
rv = 1;
if (rv)
agerr(AGWARN, "Illegal value %s for ALIGN in TD - ignored\n", v);
return rv;
}
static int balignfn(htmldata_t * p, char *v)
{
int rv = 0;
char c = (char) toupper(*v);
if ((c == 'L') && !strcasecmp(v + 1, "EFT"))
p->flags |= BALIGN_LEFT;
else if ((c == 'R') && !strcasecmp(v + 1, "IGHT"))
p->flags |= BALIGN_RIGHT;
else if ((c != 'C') || strcasecmp(v + 1, "ENTER"))
rv = 1;
if (rv)
agerr(AGWARN, "Illegal value %s for BALIGN in TD - ignored\n", v);
return rv;
}
static int heightfn(htmldata_t * p, char *v)
{
long u;
if (doInt(v, "HEIGHT", 0, MAX_USHORT, &u))
return 1;
p->height = (unsigned short) u;
return 0;
}
static int widthfn(htmldata_t * p, char *v)
{
long u;
if (doInt(v, "WIDTH", 0, MAX_USHORT, &u))
return 1;
p->width = (unsigned short) u;
return 0;
}
static int rowspanfn(htmlcell_t * p, char *v)
{
long u;
if (doInt(v, "ROWSPAN", 0, MAX_USHORT, &u))
return 1;
if (u == 0) {
agerr(AGWARN, "ROWSPAN value cannot be 0 - ignored\n");
return 1;
}
p->rspan = (unsigned short) u;
return 0;
}
static int colspanfn(htmlcell_t * p, char *v)
{
long u;
if (doInt(v, "COLSPAN", 0, MAX_USHORT, &u))
return 1;
if (u == 0) {
agerr(AGWARN, "COLSPAN value cannot be 0 - ignored\n");
return 1;
}
p->cspan = (unsigned short) u;
return 0;
}
static int fontcolorfn(textfont_t * p, char *v)
{
p->color = v;
return 0;
}
static int facefn(textfont_t * p, char *v)
{
p->name = v;
return 0;
}
static int ptsizefn(textfont_t * p, char *v)
{
long u;
if (doInt(v, "POINT-SIZE", 0, MAX_UCHAR, &u))
return 1;
p->size = (double) u;
return 0;
}
static int srcfn(htmlimg_t * p, char *v)
{
p->src = strdup(v);
return 0;
}
static int scalefn(htmlimg_t * p, char *v)
{
p->scale = strdup(v);
return 0;
}
static int alignfn(int *p, char *v)
{
int rv = 0;
char c = (char) toupper(*v);
if ((c == 'R') && !strcasecmp(v + 1, "IGHT"))
*p = 'r';
else if ((c == 'L') || !strcasecmp(v + 1, "EFT"))
*p = 'l';
else if ((c == 'C') || strcasecmp(v + 1, "ENTER"))
*p = 'n';
else {
agerr(AGWARN, "Illegal value %s for ALIGN - ignored\n", v);
rv = 1;
}
return rv;
}
/* Tables used in binary search; MUST be alphabetized */
static attr_item tbl_items[] = {
{"align", (attrFn) halignfn},
{"bgcolor", (attrFn) bgcolorfn},
{"border", (attrFn) borderfn},
{"cellborder", (attrFn) cellborderfn},
{"cellpadding", (attrFn) cellpaddingfn},
{"cellspacing", (attrFn) cellspacingfn},
{"color", (attrFn) pencolorfn},
{"columns", (attrFn) columnsfn},
{"fixedsize", (attrFn) fixedsizefn},
{"gradientangle", (attrFn) gradientanglefn},
{"height", (attrFn) heightfn},
{"href", (attrFn) hreffn},
{"id", (attrFn) idfn},
{"port", (attrFn) portfn},
{"rows", (attrFn) rowsfn},
{"sides", (attrFn) sidesfn},
{"style", (attrFn) stylefn},
{"target", (attrFn) targetfn},
{"title", (attrFn) titlefn},
{"tooltip", (attrFn) titlefn},
{"valign", (attrFn) valignfn},
{"width", (attrFn) widthfn},
};
static attr_item cell_items[] = {
{"align", (attrFn) cell_halignfn},
{"balign", (attrFn) balignfn},
{"bgcolor", (attrFn) bgcolorfn},
{"border", (attrFn) borderfn},
{"cellpadding", (attrFn) cellpaddingfn},
{"cellspacing", (attrFn) cellspacingfn},
{"color", (attrFn) pencolorfn},
{"colspan", (attrFn) colspanfn},
{"fixedsize", (attrFn) fixedsizefn},
{"gradientangle", (attrFn) gradientanglefn},
{"height", (attrFn) heightfn},
{"href", (attrFn) hreffn},
{"id", (attrFn) idfn},
{"port", (attrFn) portfn},
{"rowspan", (attrFn) rowspanfn},
{"sides", (attrFn) sidesfn},
{"style", (attrFn) stylefn},
{"target", (attrFn) targetfn},
{"title", (attrFn) titlefn},
{"tooltip", (attrFn) titlefn},
{"valign", (attrFn) valignfn},
{"width", (attrFn) widthfn},
};
static attr_item font_items[] = {
{"color", (attrFn) fontcolorfn},
{"face", (attrFn) facefn},
{"point-size", (attrFn) ptsizefn},
};
static attr_item img_items[] = {
{"scale", (attrFn) scalefn},
{"src", (attrFn) srcfn},
};
static attr_item br_items[] = {
{"align", (attrFn) alignfn},
};
/* doAttrs:
* General function for processing list of name/value attributes.
* Do binary search on items table. If match found, invoke action
* passing it tp and attribute value.
* Table size is given by nel
* Name/value pairs are in array atts, which is null terminated.
* s is the name of the HTML element being processed.
*/
static void
doAttrs(void *tp, attr_item * items, int nel, char **atts, char *s)
{
char *name;
char *val;
attr_item *ip;
attr_item key;
while ((name = *atts++) != NULL) {
val = *atts++;
key.name = name;
ip = (attr_item *) bsearch(&key, items, nel, ISIZE, (bcmpfn) icmp);
if (ip)
state.warn |= ip->action(tp, val);
else {
agerr(AGWARN, "Illegal attribute %s in %s - ignored\n", name,
s);
state.warn = 1;
}
}
}
static void mkBR(char **atts)
{
htmllval.i = UNSET_ALIGN;
doAttrs(&htmllval.i, br_items, sizeof(br_items) / ISIZE, atts, "<BR>");
}
static htmlimg_t *mkImg(char **atts)
{
htmlimg_t *img = NEW(htmlimg_t);
doAttrs(img, img_items, sizeof(img_items) / ISIZE, atts, "<IMG>");
return img;
}
static textfont_t *mkFont(GVC_t *gvc, char **atts, int flags, int ul)
{
textfont_t tf = {NULL,NULL,NULL,0.0,0,0};
tf.size = -1.0; /* unassigned */
tf.flags = flags;
if (atts)
doAttrs(&tf, font_items, sizeof(font_items) / ISIZE, atts, "<FONT>");
return dtinsert(gvc->textfont_dt, &tf);
}
static htmlcell_t *mkCell(char **atts)
{
htmlcell_t *cell = NEW(htmlcell_t);
cell->cspan = 1;
cell->rspan = 1;
doAttrs(cell, cell_items, sizeof(cell_items) / ISIZE, atts, "<TD>");
return cell;
}
static htmltbl_t *mkTbl(char **atts)
{
htmltbl_t *tbl = NEW(htmltbl_t);
tbl->rc = -1; /* flag that table is a raw, parsed table */
tbl->cb = -1; /* unset cell border attribute */
doAttrs(tbl, tbl_items, sizeof(tbl_items) / ISIZE, atts, "<TABLE>");
return tbl;
}
static void startElement(void *user, const char *name, char **atts)
{
GVC_t *gvc = (GVC_t*)user;
if (strcasecmp(name, "TABLE") == 0) {
htmllval.tbl = mkTbl(atts);
state.inCell = 0;
state.tok = T_table;
} else if ((strcasecmp(name, "TR") == 0)
|| (strcasecmp(name, "TH") == 0)) {
state.inCell = 0;
state.tok = T_row;
} else if (strcasecmp(name, "TD") == 0) {
state.inCell = 1;
htmllval.cell = mkCell(atts);
state.tok = T_cell;
} else if (strcasecmp(name, "FONT") == 0) {
htmllval.font = mkFont(gvc, atts, 0, 0);
state.tok = T_font;
} else if (strcasecmp(name, "B") == 0) {
htmllval.font = mkFont(gvc, 0, HTML_BF, 0);
state.tok = T_bold;
} else if (strcasecmp(name, "S") == 0) {
htmllval.font = mkFont(gvc, 0, HTML_S, 0);
state.tok = T_s;
} else if (strcasecmp(name, "U") == 0) {
htmllval.font = mkFont(gvc, 0, HTML_UL, 1);
state.tok = T_underline;
} else if (strcasecmp(name, "O") == 0) {
htmllval.font = mkFont(gvc, 0, HTML_OL, 1);
state.tok = T_overline;
} else if (strcasecmp(name, "I") == 0) {
htmllval.font = mkFont(gvc, 0, HTML_IF, 0);
state.tok = T_italic;
} else if (strcasecmp(name, "SUP") == 0) {
htmllval.font = mkFont(gvc, 0, HTML_SUP, 0);
state.tok = T_sup;
} else if (strcasecmp(name, "SUB") == 0) {
htmllval.font = mkFont(gvc, 0, HTML_SUB, 0);
state.tok = T_sub;
} else if (strcasecmp(name, "BR") == 0) {
mkBR(atts);
state.tok = T_br;
} else if (strcasecmp(name, "HR") == 0) {
state.tok = T_hr;
} else if (strcasecmp(name, "VR") == 0) {
state.tok = T_vr;
} else if (strcasecmp(name, "IMG") == 0) {
htmllval.img = mkImg(atts);
state.tok = T_img;
} else if (strcasecmp(name, "HTML") == 0) {
state.tok = T_html;
} else {
lexerror(name);
}
}
static void endElement(void *user, const char *name)
{
if (strcasecmp(name, "TABLE") == 0) {
state.tok = T_end_table;
state.inCell = 1;
} else if ((strcasecmp(name, "TR") == 0)
|| (strcasecmp(name, "TH") == 0)) {
state.tok = T_end_row;
} else if (strcasecmp(name, "TD") == 0) {
state.tok = T_end_cell;
state.inCell = 0;
} else if (strcasecmp(name, "HTML") == 0) {
state.tok = T_end_html;
} else if (strcasecmp(name, "FONT") == 0) {
state.tok = T_end_font;
} else if (strcasecmp(name, "B") == 0) {
state.tok = T_n_bold;
} else if (strcasecmp(name, "U") == 0) {
state.tok = T_n_underline;
} else if (strcasecmp(name, "O") == 0) {
state.tok = T_n_overline;
} else if (strcasecmp(name, "I") == 0) {
state.tok = T_n_italic;
} else if (strcasecmp(name, "SUP") == 0) {
state.tok = T_n_sup;
} else if (strcasecmp(name, "SUB") == 0) {
state.tok = T_n_sub;
} else if (strcasecmp(name, "S") == 0) {
state.tok = T_n_s;
} else if (strcasecmp(name, "BR") == 0) {
if (state.tok == T_br)
state.tok = T_BR;
else
state.tok = T_end_br;
} else if (strcasecmp(name, "HR") == 0) {
if (state.tok == T_hr)
state.tok = T_HR;
else
state.tok = T_end_hr;
} else if (strcasecmp(name, "VR") == 0) {
if (state.tok == T_vr)
state.tok = T_VR;
else
state.tok = T_end_vr;
} else if (strcasecmp(name, "IMG") == 0) {
if (state.tok == T_img)
state.tok = T_IMG;
else
state.tok = T_end_img;
} else {
lexerror(name);
}
}
/* characterData:
* Generate T_string token. Do this only when immediately in
* <TD>..</TD> or <HTML>..</HTML>, i.e., when inCell is true.
* Strip out formatting characters but keep spaces.
* Distinguish between all whitespace vs. strings with non-whitespace
* characters.
*/
static void characterData(void *user, const char *s, int length)
{
int i, cnt = 0;
unsigned char c;
if (state.inCell) {
for (i = length; i; i--) {
c = *s++;
if (c >= ' ') {
cnt++;
agxbputc(state.xb, c);
}
}
if (cnt) state.tok = T_string;
}
}
#endif
int initHTMLlexer(char *src, agxbuf * xb, htmlenv_t *env)
{
#ifdef HAVE_EXPAT
state.xb = xb;
agxbinit (&state.lb, SMALLBUF, NULL);
state.ptr = src;
state.mode = 0;
state.warn = 0;
state.error = 0;
state.currtoklen = 0;
state.prevtoklen = 0;
state.inCell = 1;
state.parser = XML_ParserCreate(charsetToStr(GD_charset(env->g)));
XML_SetUserData(state.parser, GD_gvc(env->g));
XML_SetElementHandler(state.parser,
(XML_StartElementHandler) startElement,
endElement);
XML_SetCharacterDataHandler(state.parser, characterData);
return 0;
#else
static int first;
if (!first) {
agerr(AGWARN,
"Not built with libexpat. Table formatting is not available.\n");
first++;
}
return 1;
#endif
}
int clearHTMLlexer()
{
#ifdef HAVE_EXPAT
int rv = state.warn | state.error;
XML_ParserFree(state.parser);
agxbfree (&state.lb);
return rv;
#else
return 1;
#endif
}
#ifdef HAVE_EXPAT
/* eatComment:
* Given first character after open comment, eat characters
* upto comment close, returning pointer to closing > if it exists,
* or null character otherwise.
* We rely on HTML strings having matched nested <>.
*/
static char *eatComment(char *p)
{
int depth = 1;
char *s = p;
char c;
while (depth && (c = *s++)) {
if (c == '<')
depth++;
else if (c == '>')
depth--;
}
s--; /* move back to '\0' or '>' */
if (*s) {
char *t = s - 2;
if ((t < p) || strncmp(t, "--", 2)) {
agerr(AGWARN, "Unclosed comment\n");
state.warn = 1;
}
}
return s;
}
/* findNext:
* Return next XML unit. This is either <..>, an HTML
* comment <!-- ... -->, or characters up to next <.
*/
static char *findNext(char *s, agxbuf* xb)
{
char* t = s + 1;
char c;
if (*s == '<') {
if ((*t == '!') && !strncmp(t + 1, "--", 2))
t = eatComment(t + 3);
else
while (*t && (*t != '>'))
t++;
if (*t != '>') {
agerr(AGWARN, "Label closed before end of HTML element\n");
state.warn = 1;
} else
t++;
} else {
t = s;
while ((c = *t) && (c != '<')) {
if ((c == '&') && (*(t+1) != '#')) {
t = scanEntity(t + 1, xb);
}
else {
agxbputc(xb, c);
t++;
}
}
}
return t;
}
#endif
int htmllineno()
{
#ifdef HAVE_EXPAT
return XML_GetCurrentLineNumber(state.parser);
#else
return 0;
#endif
}
#ifdef DEBUG
static void printTok(int tok)
{
char *s;
switch (tok) {
case T_VR:
s = "T_VR";
break;
case T_vr:
s = "T_vr";
break;
case T_end_vr:
s = "T_end_vr";
break;
case T_HR:
s = "T_HR";
break;
case T_hr:
s = "T_hr";
break;
case T_end_hr:
s = "T_end_hr";
break;
case T_BR:
s = "T_BR";
break;
case T_br:
s = "T_br";
break;
case T_end_br:
s = "T_end_br";
break;
case T_end_table:
s = "T_end_table";
break;
case T_row:
s = "T_row";
break;
case T_end_row:
s = "T_end_row";
break;
case T_end_cell:
s = "T_end_cell";
break;
case T_html:
s = "T_html";
break;
case T_end_html:
s = "T_end_html";
break;
case T_string:
s = "T_string";
break;
case T_error:
s = "T_error";
break;
case T_table:
s = "T_table";
break;
case T_cell:
s = "T_cell";
break;
case T_img:
s = "T_img";
break;
case T_end_img:
s = "T_end_img";
break;
case T_IMG:
s = "T_IMG";
break;
case T_underline:
s = "T_underline";
break;
case T_n_underline:
s = "T_n_underline";
break;
case T_overline:
s = "T_overline";
break;
case T_n_overline:
s = "T_n_overline";
break;
case T_italic:
s = "T_italic";
break;
case T_n_italic:
s = "T_n_italic";
break;
case T_bold:
s = "T_bold";
break;
case T_n_bold:
s = "T_n_bold";
break;
case T_s:
s = "T_s";
break;
case T_n_s:
s = "T_n_s";
break;
default:
s = "<unknown>";
}
if (tok == T_string) {
fprintf(stderr, "%s \"", s);
fwrite(agxbstart(state.xb), 1, agxblen(state.xb), stderr);
fprintf(stderr, "\"\n");
} else
fprintf(stderr, "%s\n", s);
}
#endif
int htmllex()
{
#ifdef HAVE_EXPAT
static char *begin_html = "<HTML>";
static char *end_html = "</HTML>";
char *s;
char *endp = 0;
int len, llen;
int rv;
state.tok = 0;
do {
if (state.mode == 2)
return EOF;
if (state.mode == 0) {
state.mode = 1;
s = begin_html;
len = strlen(s);
endp = 0;
} else {
s = state.ptr;
if (*s == '\0') {
state.mode = 2;
s = end_html;
len = strlen(s);
} else {
endp = findNext(s,&state.lb);
len = endp - s;
}
}
state.prevtok = state.currtok;
state.prevtoklen = state.currtoklen;
state.currtok = s;
state.currtoklen = len;
if ((llen = agxblen(&state.lb)))
rv = XML_Parse(state.parser, agxbuse(&state.lb),llen, 0);
else
rv = XML_Parse(state.parser, s, len, (len ? 0 : 1));
if (rv == XML_STATUS_ERROR) {
if (!state.error) {
agerr(AGERR, "%s in line %d \n",
XML_ErrorString(XML_GetErrorCode(state.parser)),
htmllineno());
error_context();
state.error = 1;
state.tok = T_error;
}
}
if (endp)
state.ptr = endp;
} while (state.tok == 0);
#if DEBUG
printTok (state.tok);
#endif
return state.tok;
#else
return EOF;
#endif
}
|
609923bf5576f3634526c43507163a31e827f6ed
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/input/touchscreen/max11801_ts.c
|
00bc6caa27f5c296c073d46802197ded10e1e1a5
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 7,473
|
c
|
max11801_ts.c
|
/*
* Driver for MAXI MAX11801 - A Resistive touch screen controller with
* i2c interface
*
* Copyright (C) 2011 Freescale Semiconductor, Inc.
* Author: Zhang Jiejing <jiejing.zhang@freescale.com>
*
* Based on mcs5000_ts.c
*
* 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 driver aims to support the series of MAXI touch chips max11801
* through max11803. The main difference between these 4 chips can be
* found in the table below:
* -----------------------------------------------------
* | CHIP | AUTO MODE SUPPORT(FIFO) | INTERFACE |
* |----------------------------------------------------|
* | max11800 | YES | SPI |
* | max11801 | YES | I2C |
* | max11802 | NO | SPI |
* | max11803 | NO | I2C |
* ------------------------------------------------------
*
* Currently, this driver only supports max11801.
*
* Data Sheet:
* http://www.maxim-ic.com/datasheet/index.mvp/id/5943
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/bitops.h>
/* Register Address define */
#define GENERNAL_STATUS_REG 0x00
#define GENERNAL_CONF_REG 0x01
#define MESURE_RES_CONF_REG 0x02
#define MESURE_AVER_CONF_REG 0x03
#define ADC_SAMPLE_TIME_CONF_REG 0x04
#define PANEL_SETUPTIME_CONF_REG 0x05
#define DELAY_CONVERSION_CONF_REG 0x06
#define TOUCH_DETECT_PULLUP_CONF_REG 0x07
#define AUTO_MODE_TIME_CONF_REG 0x08 /* only for max11800/max11801 */
#define APERTURE_CONF_REG 0x09 /* only for max11800/max11801 */
#define AUX_MESURE_CONF_REG 0x0a
#define OP_MODE_CONF_REG 0x0b
/* FIFO is found only in max11800 and max11801 */
#define FIFO_RD_CMD (0x50 << 1)
#define MAX11801_FIFO_INT (1 << 2)
#define MAX11801_FIFO_OVERFLOW (1 << 3)
#define XY_BUFSIZE 4
#define XY_BUF_OFFSET 4
#define MAX11801_MAX_X 0xfff
#define MAX11801_MAX_Y 0xfff
#define MEASURE_TAG_OFFSET 2
#define MEASURE_TAG_MASK (3 << MEASURE_TAG_OFFSET)
#define EVENT_TAG_OFFSET 0
#define EVENT_TAG_MASK (3 << EVENT_TAG_OFFSET)
#define MEASURE_X_TAG (0 << MEASURE_TAG_OFFSET)
#define MEASURE_Y_TAG (1 << MEASURE_TAG_OFFSET)
/* These are the state of touch event state machine */
enum {
EVENT_INIT,
EVENT_MIDDLE,
EVENT_RELEASE,
EVENT_FIFO_END
};
struct max11801_data {
struct i2c_client *client;
struct input_dev *input_dev;
};
static u8 read_register(struct i2c_client *client, int addr)
{
/* XXX: The chip ignores LSB of register address */
return i2c_smbus_read_byte_data(client, addr << 1);
}
static int max11801_write_reg(struct i2c_client *client, int addr, int data)
{
/* XXX: The chip ignores LSB of register address */
return i2c_smbus_write_byte_data(client, addr << 1, data);
}
static irqreturn_t max11801_ts_interrupt(int irq, void *dev_id)
{
struct max11801_data *data = dev_id;
struct i2c_client *client = data->client;
int status, i, ret;
u8 buf[XY_BUFSIZE];
int x = -1;
int y = -1;
status = read_register(data->client, GENERNAL_STATUS_REG);
if (status & (MAX11801_FIFO_INT | MAX11801_FIFO_OVERFLOW)) {
status = read_register(data->client, GENERNAL_STATUS_REG);
ret = i2c_smbus_read_i2c_block_data(client, FIFO_RD_CMD,
XY_BUFSIZE, buf);
/*
* We should get 4 bytes buffer that contains X,Y
* and event tag
*/
if (ret < XY_BUFSIZE)
goto out;
for (i = 0; i < XY_BUFSIZE; i += XY_BUFSIZE / 2) {
if ((buf[i + 1] & MEASURE_TAG_MASK) == MEASURE_X_TAG)
x = (buf[i] << XY_BUF_OFFSET) +
(buf[i + 1] >> XY_BUF_OFFSET);
else if ((buf[i + 1] & MEASURE_TAG_MASK) == MEASURE_Y_TAG)
y = (buf[i] << XY_BUF_OFFSET) +
(buf[i + 1] >> XY_BUF_OFFSET);
}
if ((buf[1] & EVENT_TAG_MASK) != (buf[3] & EVENT_TAG_MASK))
goto out;
switch (buf[1] & EVENT_TAG_MASK) {
case EVENT_INIT:
/* fall through */
case EVENT_MIDDLE:
input_report_abs(data->input_dev, ABS_X, x);
input_report_abs(data->input_dev, ABS_Y, y);
input_event(data->input_dev, EV_KEY, BTN_TOUCH, 1);
input_sync(data->input_dev);
break;
case EVENT_RELEASE:
input_event(data->input_dev, EV_KEY, BTN_TOUCH, 0);
input_sync(data->input_dev);
break;
case EVENT_FIFO_END:
break;
}
}
out:
return IRQ_HANDLED;
}
static void max11801_ts_phy_init(struct max11801_data *data)
{
struct i2c_client *client = data->client;
/* Average X,Y, take 16 samples, average eight media sample */
max11801_write_reg(client, MESURE_AVER_CONF_REG, 0xff);
/* X,Y panel setup time set to 20us */
max11801_write_reg(client, PANEL_SETUPTIME_CONF_REG, 0x11);
/* Rough pullup time (2uS), Fine pullup time (10us) */
max11801_write_reg(client, TOUCH_DETECT_PULLUP_CONF_REG, 0x10);
/* Auto mode init period = 5ms , scan period = 5ms*/
max11801_write_reg(client, AUTO_MODE_TIME_CONF_REG, 0xaa);
/* Aperture X,Y set to +- 4LSB */
max11801_write_reg(client, APERTURE_CONF_REG, 0x33);
/* Enable Power, enable Automode, enable Aperture, enable Average X,Y */
max11801_write_reg(client, OP_MODE_CONF_REG, 0x36);
}
static int max11801_ts_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct max11801_data *data;
struct input_dev *input_dev;
int error;
data = kzalloc(sizeof(struct max11801_data), GFP_KERNEL);
input_dev = input_allocate_device();
if (!data || !input_dev) {
dev_err(&client->dev, "Failed to allocate memory\n");
error = -ENOMEM;
goto err_free_mem;
}
data->client = client;
data->input_dev = input_dev;
input_dev->name = "max11801_ts";
input_dev->id.bustype = BUS_I2C;
input_dev->dev.parent = &client->dev;
__set_bit(EV_ABS, input_dev->evbit);
__set_bit(EV_KEY, input_dev->evbit);
__set_bit(BTN_TOUCH, input_dev->keybit);
input_set_abs_params(input_dev, ABS_X, 0, MAX11801_MAX_X, 0, 0);
input_set_abs_params(input_dev, ABS_Y, 0, MAX11801_MAX_Y, 0, 0);
input_set_drvdata(input_dev, data);
max11801_ts_phy_init(data);
error = request_threaded_irq(client->irq, NULL, max11801_ts_interrupt,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
"max11801_ts", data);
if (error) {
dev_err(&client->dev, "Failed to register interrupt\n");
goto err_free_mem;
}
error = input_register_device(data->input_dev);
if (error)
goto err_free_irq;
i2c_set_clientdata(client, data);
return 0;
err_free_irq:
free_irq(client->irq, data);
err_free_mem:
input_free_device(input_dev);
kfree(data);
return error;
}
static int max11801_ts_remove(struct i2c_client *client)
{
struct max11801_data *data = i2c_get_clientdata(client);
free_irq(client->irq, data);
input_unregister_device(data->input_dev);
kfree(data);
return 0;
}
static const struct i2c_device_id max11801_ts_id[] = {
{"max11801", 0},
{ }
};
MODULE_DEVICE_TABLE(i2c, max11801_ts_id);
static struct i2c_driver max11801_ts_driver = {
.driver = {
.name = "max11801_ts",
.owner = THIS_MODULE,
},
.id_table = max11801_ts_id,
.probe = max11801_ts_probe,
.remove = max11801_ts_remove,
};
module_i2c_driver(max11801_ts_driver);
MODULE_AUTHOR("Zhang Jiejing <jiejing.zhang@freescale.com>");
MODULE_DESCRIPTION("Touchscreen driver for MAXI MAX11801 controller");
MODULE_LICENSE("GPL");
|
e44090efab9762ecf492e0c8cdbdde13334c4f9e
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/gpu/drm/savage/savage_bci.c
|
b55c1d66114745e1db6c56f027be1b953269d2e1
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 31,338
|
c
|
savage_bci.c
|
/* savage_bci.c -- BCI support for Savage
*
* Copyright 2004 Felix Kuehling
* All Rights Reserved.
*
* 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, sub license,
* 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 (including the
* next paragraph) 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
* NON-INFRINGEMENT. IN NO EVENT SHALL FELIX KUEHLING 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.
*/
#include <drm/drmP.h>
#include <drm/savage_drm.h>
#include "savage_drv.h"
/* Need a long timeout for shadow status updates can take a while
* and so can waiting for events when the queue is full. */
#define SAVAGE_DEFAULT_USEC_TIMEOUT 1000000 /* 1s */
#define SAVAGE_EVENT_USEC_TIMEOUT 5000000 /* 5s */
#define SAVAGE_FREELIST_DEBUG 0
static int savage_do_cleanup_bci(struct drm_device *dev);
static int
savage_bci_wait_fifo_shadow(drm_savage_private_t * dev_priv, unsigned int n)
{
uint32_t mask = dev_priv->status_used_mask;
uint32_t threshold = dev_priv->bci_threshold_hi;
uint32_t status;
int i;
#if SAVAGE_BCI_DEBUG
if (n > dev_priv->cob_size + SAVAGE_BCI_FIFO_SIZE - threshold)
DRM_ERROR("Trying to emit %d words "
"(more than guaranteed space in COB)\n", n);
#endif
for (i = 0; i < SAVAGE_DEFAULT_USEC_TIMEOUT; i++) {
DRM_MEMORYBARRIER();
status = dev_priv->status_ptr[0];
if ((status & mask) < threshold)
return 0;
DRM_UDELAY(1);
}
#if SAVAGE_BCI_DEBUG
DRM_ERROR("failed!\n");
DRM_INFO(" status=0x%08x, threshold=0x%08x\n", status, threshold);
#endif
return -EBUSY;
}
static int
savage_bci_wait_fifo_s3d(drm_savage_private_t * dev_priv, unsigned int n)
{
uint32_t maxUsed = dev_priv->cob_size + SAVAGE_BCI_FIFO_SIZE - n;
uint32_t status;
int i;
for (i = 0; i < SAVAGE_DEFAULT_USEC_TIMEOUT; i++) {
status = SAVAGE_READ(SAVAGE_STATUS_WORD0);
if ((status & SAVAGE_FIFO_USED_MASK_S3D) <= maxUsed)
return 0;
DRM_UDELAY(1);
}
#if SAVAGE_BCI_DEBUG
DRM_ERROR("failed!\n");
DRM_INFO(" status=0x%08x\n", status);
#endif
return -EBUSY;
}
static int
savage_bci_wait_fifo_s4(drm_savage_private_t * dev_priv, unsigned int n)
{
uint32_t maxUsed = dev_priv->cob_size + SAVAGE_BCI_FIFO_SIZE - n;
uint32_t status;
int i;
for (i = 0; i < SAVAGE_DEFAULT_USEC_TIMEOUT; i++) {
status = SAVAGE_READ(SAVAGE_ALT_STATUS_WORD0);
if ((status & SAVAGE_FIFO_USED_MASK_S4) <= maxUsed)
return 0;
DRM_UDELAY(1);
}
#if SAVAGE_BCI_DEBUG
DRM_ERROR("failed!\n");
DRM_INFO(" status=0x%08x\n", status);
#endif
return -EBUSY;
}
/*
* Waiting for events.
*
* The BIOSresets the event tag to 0 on mode changes. Therefore we
* never emit 0 to the event tag. If we find a 0 event tag we know the
* BIOS stomped on it and return success assuming that the BIOS waited
* for engine idle.
*
* Note: if the Xserver uses the event tag it has to follow the same
* rule. Otherwise there may be glitches every 2^16 events.
*/
static int
savage_bci_wait_event_shadow(drm_savage_private_t * dev_priv, uint16_t e)
{
uint32_t status;
int i;
for (i = 0; i < SAVAGE_EVENT_USEC_TIMEOUT; i++) {
DRM_MEMORYBARRIER();
status = dev_priv->status_ptr[1];
if ((((status & 0xffff) - e) & 0xffff) <= 0x7fff ||
(status & 0xffff) == 0)
return 0;
DRM_UDELAY(1);
}
#if SAVAGE_BCI_DEBUG
DRM_ERROR("failed!\n");
DRM_INFO(" status=0x%08x, e=0x%04x\n", status, e);
#endif
return -EBUSY;
}
static int
savage_bci_wait_event_reg(drm_savage_private_t * dev_priv, uint16_t e)
{
uint32_t status;
int i;
for (i = 0; i < SAVAGE_EVENT_USEC_TIMEOUT; i++) {
status = SAVAGE_READ(SAVAGE_STATUS_WORD1);
if ((((status & 0xffff) - e) & 0xffff) <= 0x7fff ||
(status & 0xffff) == 0)
return 0;
DRM_UDELAY(1);
}
#if SAVAGE_BCI_DEBUG
DRM_ERROR("failed!\n");
DRM_INFO(" status=0x%08x, e=0x%04x\n", status, e);
#endif
return -EBUSY;
}
uint16_t savage_bci_emit_event(drm_savage_private_t * dev_priv,
unsigned int flags)
{
uint16_t count;
BCI_LOCALS;
if (dev_priv->status_ptr) {
/* coordinate with Xserver */
count = dev_priv->status_ptr[1023];
if (count < dev_priv->event_counter)
dev_priv->event_wrap++;
} else {
count = dev_priv->event_counter;
}
count = (count + 1) & 0xffff;
if (count == 0) {
count++; /* See the comment above savage_wait_event_*. */
dev_priv->event_wrap++;
}
dev_priv->event_counter = count;
if (dev_priv->status_ptr)
dev_priv->status_ptr[1023] = (uint32_t) count;
if ((flags & (SAVAGE_WAIT_2D | SAVAGE_WAIT_3D))) {
unsigned int wait_cmd = BCI_CMD_WAIT;
if ((flags & SAVAGE_WAIT_2D))
wait_cmd |= BCI_CMD_WAIT_2D;
if ((flags & SAVAGE_WAIT_3D))
wait_cmd |= BCI_CMD_WAIT_3D;
BEGIN_BCI(2);
BCI_WRITE(wait_cmd);
} else {
BEGIN_BCI(1);
}
BCI_WRITE(BCI_CMD_UPDATE_EVENT_TAG | (uint32_t) count);
return count;
}
/*
* Freelist management
*/
static int savage_freelist_init(struct drm_device * dev)
{
drm_savage_private_t *dev_priv = dev->dev_private;
struct drm_device_dma *dma = dev->dma;
struct drm_buf *buf;
drm_savage_buf_priv_t *entry;
int i;
DRM_DEBUG("count=%d\n", dma->buf_count);
dev_priv->head.next = &dev_priv->tail;
dev_priv->head.prev = NULL;
dev_priv->head.buf = NULL;
dev_priv->tail.next = NULL;
dev_priv->tail.prev = &dev_priv->head;
dev_priv->tail.buf = NULL;
for (i = 0; i < dma->buf_count; i++) {
buf = dma->buflist[i];
entry = buf->dev_private;
SET_AGE(&entry->age, 0, 0);
entry->buf = buf;
entry->next = dev_priv->head.next;
entry->prev = &dev_priv->head;
dev_priv->head.next->prev = entry;
dev_priv->head.next = entry;
}
return 0;
}
static struct drm_buf *savage_freelist_get(struct drm_device * dev)
{
drm_savage_private_t *dev_priv = dev->dev_private;
drm_savage_buf_priv_t *tail = dev_priv->tail.prev;
uint16_t event;
unsigned int wrap;
DRM_DEBUG("\n");
UPDATE_EVENT_COUNTER();
if (dev_priv->status_ptr)
event = dev_priv->status_ptr[1] & 0xffff;
else
event = SAVAGE_READ(SAVAGE_STATUS_WORD1) & 0xffff;
wrap = dev_priv->event_wrap;
if (event > dev_priv->event_counter)
wrap--; /* hardware hasn't passed the last wrap yet */
DRM_DEBUG(" tail=0x%04x %d\n", tail->age.event, tail->age.wrap);
DRM_DEBUG(" head=0x%04x %d\n", event, wrap);
if (tail->buf && (TEST_AGE(&tail->age, event, wrap) || event == 0)) {
drm_savage_buf_priv_t *next = tail->next;
drm_savage_buf_priv_t *prev = tail->prev;
prev->next = next;
next->prev = prev;
tail->next = tail->prev = NULL;
return tail->buf;
}
DRM_DEBUG("returning NULL, tail->buf=%p!\n", tail->buf);
return NULL;
}
void savage_freelist_put(struct drm_device * dev, struct drm_buf * buf)
{
drm_savage_private_t *dev_priv = dev->dev_private;
drm_savage_buf_priv_t *entry = buf->dev_private, *prev, *next;
DRM_DEBUG("age=0x%04x wrap=%d\n", entry->age.event, entry->age.wrap);
if (entry->next != NULL || entry->prev != NULL) {
DRM_ERROR("entry already on freelist.\n");
return;
}
prev = &dev_priv->head;
next = prev->next;
prev->next = entry;
next->prev = entry;
entry->prev = prev;
entry->next = next;
}
/*
* Command DMA
*/
static int savage_dma_init(drm_savage_private_t * dev_priv)
{
unsigned int i;
dev_priv->nr_dma_pages = dev_priv->cmd_dma->size /
(SAVAGE_DMA_PAGE_SIZE * 4);
dev_priv->dma_pages = kmalloc(sizeof(drm_savage_dma_page_t) *
dev_priv->nr_dma_pages, GFP_KERNEL);
if (dev_priv->dma_pages == NULL)
return -ENOMEM;
for (i = 0; i < dev_priv->nr_dma_pages; ++i) {
SET_AGE(&dev_priv->dma_pages[i].age, 0, 0);
dev_priv->dma_pages[i].used = 0;
dev_priv->dma_pages[i].flushed = 0;
}
SET_AGE(&dev_priv->last_dma_age, 0, 0);
dev_priv->first_dma_page = 0;
dev_priv->current_dma_page = 0;
return 0;
}
void savage_dma_reset(drm_savage_private_t * dev_priv)
{
uint16_t event;
unsigned int wrap, i;
event = savage_bci_emit_event(dev_priv, 0);
wrap = dev_priv->event_wrap;
for (i = 0; i < dev_priv->nr_dma_pages; ++i) {
SET_AGE(&dev_priv->dma_pages[i].age, event, wrap);
dev_priv->dma_pages[i].used = 0;
dev_priv->dma_pages[i].flushed = 0;
}
SET_AGE(&dev_priv->last_dma_age, event, wrap);
dev_priv->first_dma_page = dev_priv->current_dma_page = 0;
}
void savage_dma_wait(drm_savage_private_t * dev_priv, unsigned int page)
{
uint16_t event;
unsigned int wrap;
/* Faked DMA buffer pages don't age. */
if (dev_priv->cmd_dma == &dev_priv->fake_dma)
return;
UPDATE_EVENT_COUNTER();
if (dev_priv->status_ptr)
event = dev_priv->status_ptr[1] & 0xffff;
else
event = SAVAGE_READ(SAVAGE_STATUS_WORD1) & 0xffff;
wrap = dev_priv->event_wrap;
if (event > dev_priv->event_counter)
wrap--; /* hardware hasn't passed the last wrap yet */
if (dev_priv->dma_pages[page].age.wrap > wrap ||
(dev_priv->dma_pages[page].age.wrap == wrap &&
dev_priv->dma_pages[page].age.event > event)) {
if (dev_priv->wait_evnt(dev_priv,
dev_priv->dma_pages[page].age.event)
< 0)
DRM_ERROR("wait_evnt failed!\n");
}
}
uint32_t *savage_dma_alloc(drm_savage_private_t * dev_priv, unsigned int n)
{
unsigned int cur = dev_priv->current_dma_page;
unsigned int rest = SAVAGE_DMA_PAGE_SIZE -
dev_priv->dma_pages[cur].used;
unsigned int nr_pages = (n - rest + SAVAGE_DMA_PAGE_SIZE - 1) /
SAVAGE_DMA_PAGE_SIZE;
uint32_t *dma_ptr;
unsigned int i;
DRM_DEBUG("cur=%u, cur->used=%u, n=%u, rest=%u, nr_pages=%u\n",
cur, dev_priv->dma_pages[cur].used, n, rest, nr_pages);
if (cur + nr_pages < dev_priv->nr_dma_pages) {
dma_ptr = (uint32_t *) dev_priv->cmd_dma->handle +
cur * SAVAGE_DMA_PAGE_SIZE + dev_priv->dma_pages[cur].used;
if (n < rest)
rest = n;
dev_priv->dma_pages[cur].used += rest;
n -= rest;
cur++;
} else {
dev_priv->dma_flush(dev_priv);
nr_pages =
(n + SAVAGE_DMA_PAGE_SIZE - 1) / SAVAGE_DMA_PAGE_SIZE;
for (i = cur; i < dev_priv->nr_dma_pages; ++i) {
dev_priv->dma_pages[i].age = dev_priv->last_dma_age;
dev_priv->dma_pages[i].used = 0;
dev_priv->dma_pages[i].flushed = 0;
}
dma_ptr = (uint32_t *) dev_priv->cmd_dma->handle;
dev_priv->first_dma_page = cur = 0;
}
for (i = cur; nr_pages > 0; ++i, --nr_pages) {
#if SAVAGE_DMA_DEBUG
if (dev_priv->dma_pages[i].used) {
DRM_ERROR("unflushed page %u: used=%u\n",
i, dev_priv->dma_pages[i].used);
}
#endif
if (n > SAVAGE_DMA_PAGE_SIZE)
dev_priv->dma_pages[i].used = SAVAGE_DMA_PAGE_SIZE;
else
dev_priv->dma_pages[i].used = n;
n -= SAVAGE_DMA_PAGE_SIZE;
}
dev_priv->current_dma_page = --i;
DRM_DEBUG("cur=%u, cur->used=%u, n=%u\n",
i, dev_priv->dma_pages[i].used, n);
savage_dma_wait(dev_priv, dev_priv->current_dma_page);
return dma_ptr;
}
static void savage_dma_flush(drm_savage_private_t * dev_priv)
{
unsigned int first = dev_priv->first_dma_page;
unsigned int cur = dev_priv->current_dma_page;
uint16_t event;
unsigned int wrap, pad, align, len, i;
unsigned long phys_addr;
BCI_LOCALS;
if (first == cur &&
dev_priv->dma_pages[cur].used == dev_priv->dma_pages[cur].flushed)
return;
/* pad length to multiples of 2 entries
* align start of next DMA block to multiles of 8 entries */
pad = -dev_priv->dma_pages[cur].used & 1;
align = -(dev_priv->dma_pages[cur].used + pad) & 7;
DRM_DEBUG("first=%u, cur=%u, first->flushed=%u, cur->used=%u, "
"pad=%u, align=%u\n",
first, cur, dev_priv->dma_pages[first].flushed,
dev_priv->dma_pages[cur].used, pad, align);
/* pad with noops */
if (pad) {
uint32_t *dma_ptr = (uint32_t *) dev_priv->cmd_dma->handle +
cur * SAVAGE_DMA_PAGE_SIZE + dev_priv->dma_pages[cur].used;
dev_priv->dma_pages[cur].used += pad;
while (pad != 0) {
*dma_ptr++ = BCI_CMD_WAIT;
pad--;
}
}
DRM_MEMORYBARRIER();
/* do flush ... */
phys_addr = dev_priv->cmd_dma->offset +
(first * SAVAGE_DMA_PAGE_SIZE +
dev_priv->dma_pages[first].flushed) * 4;
len = (cur - first) * SAVAGE_DMA_PAGE_SIZE +
dev_priv->dma_pages[cur].used - dev_priv->dma_pages[first].flushed;
DRM_DEBUG("phys_addr=%lx, len=%u\n",
phys_addr | dev_priv->dma_type, len);
BEGIN_BCI(3);
BCI_SET_REGISTERS(SAVAGE_DMABUFADDR, 1);
BCI_WRITE(phys_addr | dev_priv->dma_type);
BCI_DMA(len);
/* fix alignment of the start of the next block */
dev_priv->dma_pages[cur].used += align;
/* age DMA pages */
event = savage_bci_emit_event(dev_priv, 0);
wrap = dev_priv->event_wrap;
for (i = first; i < cur; ++i) {
SET_AGE(&dev_priv->dma_pages[i].age, event, wrap);
dev_priv->dma_pages[i].used = 0;
dev_priv->dma_pages[i].flushed = 0;
}
/* age the current page only when it's full */
if (dev_priv->dma_pages[cur].used == SAVAGE_DMA_PAGE_SIZE) {
SET_AGE(&dev_priv->dma_pages[cur].age, event, wrap);
dev_priv->dma_pages[cur].used = 0;
dev_priv->dma_pages[cur].flushed = 0;
/* advance to next page */
cur++;
if (cur == dev_priv->nr_dma_pages)
cur = 0;
dev_priv->first_dma_page = dev_priv->current_dma_page = cur;
} else {
dev_priv->first_dma_page = cur;
dev_priv->dma_pages[cur].flushed = dev_priv->dma_pages[i].used;
}
SET_AGE(&dev_priv->last_dma_age, event, wrap);
DRM_DEBUG("first=cur=%u, cur->used=%u, cur->flushed=%u\n", cur,
dev_priv->dma_pages[cur].used,
dev_priv->dma_pages[cur].flushed);
}
static void savage_fake_dma_flush(drm_savage_private_t * dev_priv)
{
unsigned int i, j;
BCI_LOCALS;
if (dev_priv->first_dma_page == dev_priv->current_dma_page &&
dev_priv->dma_pages[dev_priv->current_dma_page].used == 0)
return;
DRM_DEBUG("first=%u, cur=%u, cur->used=%u\n",
dev_priv->first_dma_page, dev_priv->current_dma_page,
dev_priv->dma_pages[dev_priv->current_dma_page].used);
for (i = dev_priv->first_dma_page;
i <= dev_priv->current_dma_page && dev_priv->dma_pages[i].used;
++i) {
uint32_t *dma_ptr = (uint32_t *) dev_priv->cmd_dma->handle +
i * SAVAGE_DMA_PAGE_SIZE;
#if SAVAGE_DMA_DEBUG
/* Sanity check: all pages except the last one must be full. */
if (i < dev_priv->current_dma_page &&
dev_priv->dma_pages[i].used != SAVAGE_DMA_PAGE_SIZE) {
DRM_ERROR("partial DMA page %u: used=%u",
i, dev_priv->dma_pages[i].used);
}
#endif
BEGIN_BCI(dev_priv->dma_pages[i].used);
for (j = 0; j < dev_priv->dma_pages[i].used; ++j) {
BCI_WRITE(dma_ptr[j]);
}
dev_priv->dma_pages[i].used = 0;
}
/* reset to first page */
dev_priv->first_dma_page = dev_priv->current_dma_page = 0;
}
int savage_driver_load(struct drm_device *dev, unsigned long chipset)
{
drm_savage_private_t *dev_priv;
dev_priv = kzalloc(sizeof(drm_savage_private_t), GFP_KERNEL);
if (dev_priv == NULL)
return -ENOMEM;
dev->dev_private = (void *)dev_priv;
dev_priv->chipset = (enum savage_family)chipset;
pci_set_master(dev->pdev);
return 0;
}
/*
* Initialize mappings. On Savage4 and SavageIX the alignment
* and size of the aperture is not suitable for automatic MTRR setup
* in drm_addmap. Therefore we add them manually before the maps are
* initialized, and tear them down on last close.
*/
int savage_driver_firstopen(struct drm_device *dev)
{
drm_savage_private_t *dev_priv = dev->dev_private;
unsigned long mmio_base, fb_base, fb_size, aperture_base;
/* fb_rsrc and aper_rsrc aren't really used currently, but still exist
* in case we decide we need information on the BAR for BSD in the
* future.
*/
unsigned int fb_rsrc, aper_rsrc;
int ret = 0;
dev_priv->mtrr[0].handle = -1;
dev_priv->mtrr[1].handle = -1;
dev_priv->mtrr[2].handle = -1;
if (S3_SAVAGE3D_SERIES(dev_priv->chipset)) {
fb_rsrc = 0;
fb_base = pci_resource_start(dev->pdev, 0);
fb_size = SAVAGE_FB_SIZE_S3;
mmio_base = fb_base + SAVAGE_FB_SIZE_S3;
aper_rsrc = 0;
aperture_base = fb_base + SAVAGE_APERTURE_OFFSET;
/* this should always be true */
if (pci_resource_len(dev->pdev, 0) == 0x08000000) {
/* Don't make MMIO write-cobining! We need 3
* MTRRs. */
dev_priv->mtrr[0].base = fb_base;
dev_priv->mtrr[0].size = 0x01000000;
dev_priv->mtrr[0].handle =
drm_mtrr_add(dev_priv->mtrr[0].base,
dev_priv->mtrr[0].size, DRM_MTRR_WC);
dev_priv->mtrr[1].base = fb_base + 0x02000000;
dev_priv->mtrr[1].size = 0x02000000;
dev_priv->mtrr[1].handle =
drm_mtrr_add(dev_priv->mtrr[1].base,
dev_priv->mtrr[1].size, DRM_MTRR_WC);
dev_priv->mtrr[2].base = fb_base + 0x04000000;
dev_priv->mtrr[2].size = 0x04000000;
dev_priv->mtrr[2].handle =
drm_mtrr_add(dev_priv->mtrr[2].base,
dev_priv->mtrr[2].size, DRM_MTRR_WC);
} else {
DRM_ERROR("strange pci_resource_len %08llx\n",
(unsigned long long)
pci_resource_len(dev->pdev, 0));
}
} else if (dev_priv->chipset != S3_SUPERSAVAGE &&
dev_priv->chipset != S3_SAVAGE2000) {
mmio_base = pci_resource_start(dev->pdev, 0);
fb_rsrc = 1;
fb_base = pci_resource_start(dev->pdev, 1);
fb_size = SAVAGE_FB_SIZE_S4;
aper_rsrc = 1;
aperture_base = fb_base + SAVAGE_APERTURE_OFFSET;
/* this should always be true */
if (pci_resource_len(dev->pdev, 1) == 0x08000000) {
/* Can use one MTRR to cover both fb and
* aperture. */
dev_priv->mtrr[0].base = fb_base;
dev_priv->mtrr[0].size = 0x08000000;
dev_priv->mtrr[0].handle =
drm_mtrr_add(dev_priv->mtrr[0].base,
dev_priv->mtrr[0].size, DRM_MTRR_WC);
} else {
DRM_ERROR("strange pci_resource_len %08llx\n",
(unsigned long long)
pci_resource_len(dev->pdev, 1));
}
} else {
mmio_base = pci_resource_start(dev->pdev, 0);
fb_rsrc = 1;
fb_base = pci_resource_start(dev->pdev, 1);
fb_size = pci_resource_len(dev->pdev, 1);
aper_rsrc = 2;
aperture_base = pci_resource_start(dev->pdev, 2);
/* Automatic MTRR setup will do the right thing. */
}
ret = drm_addmap(dev, mmio_base, SAVAGE_MMIO_SIZE, _DRM_REGISTERS,
_DRM_READ_ONLY, &dev_priv->mmio);
if (ret)
return ret;
ret = drm_addmap(dev, fb_base, fb_size, _DRM_FRAME_BUFFER,
_DRM_WRITE_COMBINING, &dev_priv->fb);
if (ret)
return ret;
ret = drm_addmap(dev, aperture_base, SAVAGE_APERTURE_SIZE,
_DRM_FRAME_BUFFER, _DRM_WRITE_COMBINING,
&dev_priv->aperture);
return ret;
}
/*
* Delete MTRRs and free device-private data.
*/
void savage_driver_lastclose(struct drm_device *dev)
{
drm_savage_private_t *dev_priv = dev->dev_private;
int i;
for (i = 0; i < 3; ++i)
if (dev_priv->mtrr[i].handle >= 0)
drm_mtrr_del(dev_priv->mtrr[i].handle,
dev_priv->mtrr[i].base,
dev_priv->mtrr[i].size, DRM_MTRR_WC);
}
int savage_driver_unload(struct drm_device *dev)
{
drm_savage_private_t *dev_priv = dev->dev_private;
kfree(dev_priv);
return 0;
}
static int savage_do_init_bci(struct drm_device * dev, drm_savage_init_t * init)
{
drm_savage_private_t *dev_priv = dev->dev_private;
if (init->fb_bpp != 16 && init->fb_bpp != 32) {
DRM_ERROR("invalid frame buffer bpp %d!\n", init->fb_bpp);
return -EINVAL;
}
if (init->depth_bpp != 16 && init->depth_bpp != 32) {
DRM_ERROR("invalid depth buffer bpp %d!\n", init->fb_bpp);
return -EINVAL;
}
if (init->dma_type != SAVAGE_DMA_AGP &&
init->dma_type != SAVAGE_DMA_PCI) {
DRM_ERROR("invalid dma memory type %d!\n", init->dma_type);
return -EINVAL;
}
dev_priv->cob_size = init->cob_size;
dev_priv->bci_threshold_lo = init->bci_threshold_lo;
dev_priv->bci_threshold_hi = init->bci_threshold_hi;
dev_priv->dma_type = init->dma_type;
dev_priv->fb_bpp = init->fb_bpp;
dev_priv->front_offset = init->front_offset;
dev_priv->front_pitch = init->front_pitch;
dev_priv->back_offset = init->back_offset;
dev_priv->back_pitch = init->back_pitch;
dev_priv->depth_bpp = init->depth_bpp;
dev_priv->depth_offset = init->depth_offset;
dev_priv->depth_pitch = init->depth_pitch;
dev_priv->texture_offset = init->texture_offset;
dev_priv->texture_size = init->texture_size;
dev_priv->sarea = drm_getsarea(dev);
if (!dev_priv->sarea) {
DRM_ERROR("could not find sarea!\n");
savage_do_cleanup_bci(dev);
return -EINVAL;
}
if (init->status_offset != 0) {
dev_priv->status = drm_core_findmap(dev, init->status_offset);
if (!dev_priv->status) {
DRM_ERROR("could not find shadow status region!\n");
savage_do_cleanup_bci(dev);
return -EINVAL;
}
} else {
dev_priv->status = NULL;
}
if (dev_priv->dma_type == SAVAGE_DMA_AGP && init->buffers_offset) {
dev->agp_buffer_token = init->buffers_offset;
dev->agp_buffer_map = drm_core_findmap(dev,
init->buffers_offset);
if (!dev->agp_buffer_map) {
DRM_ERROR("could not find DMA buffer region!\n");
savage_do_cleanup_bci(dev);
return -EINVAL;
}
drm_core_ioremap(dev->agp_buffer_map, dev);
if (!dev->agp_buffer_map->handle) {
DRM_ERROR("failed to ioremap DMA buffer region!\n");
savage_do_cleanup_bci(dev);
return -ENOMEM;
}
}
if (init->agp_textures_offset) {
dev_priv->agp_textures =
drm_core_findmap(dev, init->agp_textures_offset);
if (!dev_priv->agp_textures) {
DRM_ERROR("could not find agp texture region!\n");
savage_do_cleanup_bci(dev);
return -EINVAL;
}
} else {
dev_priv->agp_textures = NULL;
}
if (init->cmd_dma_offset) {
if (S3_SAVAGE3D_SERIES(dev_priv->chipset)) {
DRM_ERROR("command DMA not supported on "
"Savage3D/MX/IX.\n");
savage_do_cleanup_bci(dev);
return -EINVAL;
}
if (dev->dma && dev->dma->buflist) {
DRM_ERROR("command and vertex DMA not supported "
"at the same time.\n");
savage_do_cleanup_bci(dev);
return -EINVAL;
}
dev_priv->cmd_dma = drm_core_findmap(dev, init->cmd_dma_offset);
if (!dev_priv->cmd_dma) {
DRM_ERROR("could not find command DMA region!\n");
savage_do_cleanup_bci(dev);
return -EINVAL;
}
if (dev_priv->dma_type == SAVAGE_DMA_AGP) {
if (dev_priv->cmd_dma->type != _DRM_AGP) {
DRM_ERROR("AGP command DMA region is not a "
"_DRM_AGP map!\n");
savage_do_cleanup_bci(dev);
return -EINVAL;
}
drm_core_ioremap(dev_priv->cmd_dma, dev);
if (!dev_priv->cmd_dma->handle) {
DRM_ERROR("failed to ioremap command "
"DMA region!\n");
savage_do_cleanup_bci(dev);
return -ENOMEM;
}
} else if (dev_priv->cmd_dma->type != _DRM_CONSISTENT) {
DRM_ERROR("PCI command DMA region is not a "
"_DRM_CONSISTENT map!\n");
savage_do_cleanup_bci(dev);
return -EINVAL;
}
} else {
dev_priv->cmd_dma = NULL;
}
dev_priv->dma_flush = savage_dma_flush;
if (!dev_priv->cmd_dma) {
DRM_DEBUG("falling back to faked command DMA.\n");
dev_priv->fake_dma.offset = 0;
dev_priv->fake_dma.size = SAVAGE_FAKE_DMA_SIZE;
dev_priv->fake_dma.type = _DRM_SHM;
dev_priv->fake_dma.handle = kmalloc(SAVAGE_FAKE_DMA_SIZE,
GFP_KERNEL);
if (!dev_priv->fake_dma.handle) {
DRM_ERROR("could not allocate faked DMA buffer!\n");
savage_do_cleanup_bci(dev);
return -ENOMEM;
}
dev_priv->cmd_dma = &dev_priv->fake_dma;
dev_priv->dma_flush = savage_fake_dma_flush;
}
dev_priv->sarea_priv =
(drm_savage_sarea_t *) ((uint8_t *) dev_priv->sarea->handle +
init->sarea_priv_offset);
/* setup bitmap descriptors */
{
unsigned int color_tile_format;
unsigned int depth_tile_format;
unsigned int front_stride, back_stride, depth_stride;
if (dev_priv->chipset <= S3_SAVAGE4) {
color_tile_format = dev_priv->fb_bpp == 16 ?
SAVAGE_BD_TILE_16BPP : SAVAGE_BD_TILE_32BPP;
depth_tile_format = dev_priv->depth_bpp == 16 ?
SAVAGE_BD_TILE_16BPP : SAVAGE_BD_TILE_32BPP;
} else {
color_tile_format = SAVAGE_BD_TILE_DEST;
depth_tile_format = SAVAGE_BD_TILE_DEST;
}
front_stride = dev_priv->front_pitch / (dev_priv->fb_bpp / 8);
back_stride = dev_priv->back_pitch / (dev_priv->fb_bpp / 8);
depth_stride =
dev_priv->depth_pitch / (dev_priv->depth_bpp / 8);
dev_priv->front_bd = front_stride | SAVAGE_BD_BW_DISABLE |
(dev_priv->fb_bpp << SAVAGE_BD_BPP_SHIFT) |
(color_tile_format << SAVAGE_BD_TILE_SHIFT);
dev_priv->back_bd = back_stride | SAVAGE_BD_BW_DISABLE |
(dev_priv->fb_bpp << SAVAGE_BD_BPP_SHIFT) |
(color_tile_format << SAVAGE_BD_TILE_SHIFT);
dev_priv->depth_bd = depth_stride | SAVAGE_BD_BW_DISABLE |
(dev_priv->depth_bpp << SAVAGE_BD_BPP_SHIFT) |
(depth_tile_format << SAVAGE_BD_TILE_SHIFT);
}
/* setup status and bci ptr */
dev_priv->event_counter = 0;
dev_priv->event_wrap = 0;
dev_priv->bci_ptr = (volatile uint32_t *)
((uint8_t *) dev_priv->mmio->handle + SAVAGE_BCI_OFFSET);
if (S3_SAVAGE3D_SERIES(dev_priv->chipset)) {
dev_priv->status_used_mask = SAVAGE_FIFO_USED_MASK_S3D;
} else {
dev_priv->status_used_mask = SAVAGE_FIFO_USED_MASK_S4;
}
if (dev_priv->status != NULL) {
dev_priv->status_ptr =
(volatile uint32_t *)dev_priv->status->handle;
dev_priv->wait_fifo = savage_bci_wait_fifo_shadow;
dev_priv->wait_evnt = savage_bci_wait_event_shadow;
dev_priv->status_ptr[1023] = dev_priv->event_counter;
} else {
dev_priv->status_ptr = NULL;
if (S3_SAVAGE3D_SERIES(dev_priv->chipset)) {
dev_priv->wait_fifo = savage_bci_wait_fifo_s3d;
} else {
dev_priv->wait_fifo = savage_bci_wait_fifo_s4;
}
dev_priv->wait_evnt = savage_bci_wait_event_reg;
}
/* cliprect functions */
if (S3_SAVAGE3D_SERIES(dev_priv->chipset))
dev_priv->emit_clip_rect = savage_emit_clip_rect_s3d;
else
dev_priv->emit_clip_rect = savage_emit_clip_rect_s4;
if (savage_freelist_init(dev) < 0) {
DRM_ERROR("could not initialize freelist\n");
savage_do_cleanup_bci(dev);
return -ENOMEM;
}
if (savage_dma_init(dev_priv) < 0) {
DRM_ERROR("could not initialize command DMA\n");
savage_do_cleanup_bci(dev);
return -ENOMEM;
}
return 0;
}
static int savage_do_cleanup_bci(struct drm_device * dev)
{
drm_savage_private_t *dev_priv = dev->dev_private;
if (dev_priv->cmd_dma == &dev_priv->fake_dma) {
kfree(dev_priv->fake_dma.handle);
} else if (dev_priv->cmd_dma && dev_priv->cmd_dma->handle &&
dev_priv->cmd_dma->type == _DRM_AGP &&
dev_priv->dma_type == SAVAGE_DMA_AGP)
drm_core_ioremapfree(dev_priv->cmd_dma, dev);
if (dev_priv->dma_type == SAVAGE_DMA_AGP &&
dev->agp_buffer_map && dev->agp_buffer_map->handle) {
drm_core_ioremapfree(dev->agp_buffer_map, dev);
/* make sure the next instance (which may be running
* in PCI mode) doesn't try to use an old
* agp_buffer_map. */
dev->agp_buffer_map = NULL;
}
kfree(dev_priv->dma_pages);
return 0;
}
static int savage_bci_init(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_savage_init_t *init = data;
LOCK_TEST_WITH_RETURN(dev, file_priv);
switch (init->func) {
case SAVAGE_INIT_BCI:
return savage_do_init_bci(dev, init);
case SAVAGE_CLEANUP_BCI:
return savage_do_cleanup_bci(dev);
}
return -EINVAL;
}
static int savage_bci_event_emit(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_savage_private_t *dev_priv = dev->dev_private;
drm_savage_event_emit_t *event = data;
DRM_DEBUG("\n");
LOCK_TEST_WITH_RETURN(dev, file_priv);
event->count = savage_bci_emit_event(dev_priv, event->flags);
event->count |= dev_priv->event_wrap << 16;
return 0;
}
static int savage_bci_event_wait(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_savage_private_t *dev_priv = dev->dev_private;
drm_savage_event_wait_t *event = data;
unsigned int event_e, hw_e;
unsigned int event_w, hw_w;
DRM_DEBUG("\n");
UPDATE_EVENT_COUNTER();
if (dev_priv->status_ptr)
hw_e = dev_priv->status_ptr[1] & 0xffff;
else
hw_e = SAVAGE_READ(SAVAGE_STATUS_WORD1) & 0xffff;
hw_w = dev_priv->event_wrap;
if (hw_e > dev_priv->event_counter)
hw_w--; /* hardware hasn't passed the last wrap yet */
event_e = event->count & 0xffff;
event_w = event->count >> 16;
/* Don't need to wait if
* - event counter wrapped since the event was emitted or
* - the hardware has advanced up to or over the event to wait for.
*/
if (event_w < hw_w || (event_w == hw_w && event_e <= hw_e))
return 0;
else
return dev_priv->wait_evnt(dev_priv, event_e);
}
/*
* DMA buffer management
*/
static int savage_bci_get_buffers(struct drm_device *dev,
struct drm_file *file_priv,
struct drm_dma *d)
{
struct drm_buf *buf;
int i;
for (i = d->granted_count; i < d->request_count; i++) {
buf = savage_freelist_get(dev);
if (!buf)
return -EAGAIN;
buf->file_priv = file_priv;
if (DRM_COPY_TO_USER(&d->request_indices[i],
&buf->idx, sizeof(buf->idx)))
return -EFAULT;
if (DRM_COPY_TO_USER(&d->request_sizes[i],
&buf->total, sizeof(buf->total)))
return -EFAULT;
d->granted_count++;
}
return 0;
}
int savage_bci_buffers(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
struct drm_device_dma *dma = dev->dma;
struct drm_dma *d = data;
int ret = 0;
LOCK_TEST_WITH_RETURN(dev, file_priv);
/* Please don't send us buffers.
*/
if (d->send_count != 0) {
DRM_ERROR("Process %d trying to send %d buffers via drmDMA\n",
DRM_CURRENTPID, d->send_count);
return -EINVAL;
}
/* We'll send you buffers.
*/
if (d->request_count < 0 || d->request_count > dma->buf_count) {
DRM_ERROR("Process %d trying to get %d buffers (of %d max)\n",
DRM_CURRENTPID, d->request_count, dma->buf_count);
return -EINVAL;
}
d->granted_count = 0;
if (d->request_count) {
ret = savage_bci_get_buffers(dev, file_priv, d);
}
return ret;
}
void savage_reclaim_buffers(struct drm_device *dev, struct drm_file *file_priv)
{
struct drm_device_dma *dma = dev->dma;
drm_savage_private_t *dev_priv = dev->dev_private;
int release_idlelock = 0;
int i;
if (!dma)
return;
if (!dev_priv)
return;
if (!dma->buflist)
return;
if (file_priv->master && file_priv->master->lock.hw_lock) {
drm_idlelock_take(&file_priv->master->lock);
release_idlelock = 1;
}
for (i = 0; i < dma->buf_count; i++) {
struct drm_buf *buf = dma->buflist[i];
drm_savage_buf_priv_t *buf_priv = buf->dev_private;
if (buf->file_priv == file_priv && buf_priv &&
buf_priv->next == NULL && buf_priv->prev == NULL) {
uint16_t event;
DRM_DEBUG("reclaimed from client\n");
event = savage_bci_emit_event(dev_priv, SAVAGE_WAIT_3D);
SET_AGE(&buf_priv->age, event, dev_priv->event_wrap);
savage_freelist_put(dev, buf);
}
}
if (release_idlelock)
drm_idlelock_release(&file_priv->master->lock);
}
struct drm_ioctl_desc savage_ioctls[] = {
DRM_IOCTL_DEF_DRV(SAVAGE_BCI_INIT, savage_bci_init, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(SAVAGE_BCI_CMDBUF, savage_bci_cmdbuf, DRM_AUTH),
DRM_IOCTL_DEF_DRV(SAVAGE_BCI_EVENT_EMIT, savage_bci_event_emit, DRM_AUTH),
DRM_IOCTL_DEF_DRV(SAVAGE_BCI_EVENT_WAIT, savage_bci_event_wait, DRM_AUTH),
};
int savage_max_ioctl = DRM_ARRAY_SIZE(savage_ioctls);
|
5a431bb640c7ca45e8ba1fb595375031f6f625bb
|
de21f9075f55640514c29ef0f1fe3f0690845764
|
/regression/cbmc/condition-propagation-2/test.c
|
c47532f7b43a44a1fbb65d394813c10d53d88797
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause"
] |
permissive
|
diffblue/cbmc
|
975a074ac445febb3b5715f8792beb545522dc18
|
decd2839c2f51a54b2ad0f3e89fdc1b4bf78cd16
|
refs/heads/develop
| 2023-08-31T05:52:05.342195
| 2023-08-30T13:31:51
| 2023-08-30T13:31:51
| 51,877,056
| 589
| 309
|
NOASSERTION
| 2023-09-14T18:49:17
| 2016-02-16T23:03:52
|
C++
|
UTF-8
|
C
| false
| false
| 88
|
c
|
test.c
|
int main(int argc, char **argv)
{
__CPROVER_assume(argc == 1);
assert(argc == 1);
}
|
ff81ee7448901d3c4c6e6eb0dc8e62883a7ac508
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/src/325AD0.c
|
5192eece9a203093b30d5c2546ca1750180acbde
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 5,874
|
c
|
325AD0.c
|
#include "common.h"
#include "effects.h"
#include "nu/nusys.h"
u32 effect_prng_seed = 0x1E6D3457;
void* effectFuncs[] = {
guRotateF, guTranslateF, guTranslate, guScaleF, guMtxCatF, guMtxF2L, guMtxL2F, queue_render_task,
create_effect_instance, remove_effect, general_heap_malloc, mem_clear, NULL, rand_int, clamp_angle, sin_deg,
cos_deg, atan2, npc_raycast_down_sides, load_effect, sqrtf, mdl_draw_hidden_panel_surface, is_point_visible,
guPerspectiveF, guMtxIdentF, transform_point, guLookAtHiliteF, set_screen_overlay_params_back,
set_screen_overlay_center, set_screen_overlay_center_worldpos, mdl_get_next_texture_address, guPositionF, guOrthoF,
guFrustumF, draw_prev_frame_buffer_at_screen_pos, draw_box, draw_msg, get_msg_width, get_background_color_blend, sfx_play_sound_at_position
};
s32 D_E0200734[128] = {
0x100B2AF5, 0x45B59924, 0x35094B45, 0x4ABFA67A, 0x164F5371, 0x7B195845, 0x58562A56, 0x25733D41,
0x48008107, 0x0E004F28, 0x6963B8AD, 0x5B82AB71, 0x6BC1F51B, 0x3D947816, 0x39705175, 0x44409A59,
0x0ED99067, 0x5F70B6F8, 0x3225AEEE, 0x08B5E97C, 0x2CDE7594, 0x5E9E5B7D, 0x5B2A2888, 0x107F0F50,
0x58FBC53B, 0x65F69F19, 0x3AF6CEF3, 0x15C3894F, 0x4C931A2C, 0x39A897E9, 0x5945BB8C, 0x5C9E4521,
0x7F5E310D, 0x0E4F06D2, 0x275DEB9C, 0x15AD847F, 0x09685F17, 0x7FB415F2, 0x3B20C1C0, 0x5168E01E,
0x0DB4651A, 0x24847A6D, 0x2CEB8B8F, 0x79765A35, 0x6218F283, 0x665BDD04, 0x3DB6F48F, 0x70F282EB,
0x45CC93FC, 0x6FDCA37D, 0x79A86C67, 0x72AB0990, 0x4E7AFEFA, 0x54D294F0, 0x032A18E0, 0x2776C435,
0x3AC93409, 0x3E20E7D4, 0x3D3A4D85, 0x075C4E35, 0x77C97FBD, 0x16800911, 0x63FA9357, 0x7727B0CB,
0x24CF0FE3, 0x0B587EF3, 0x0CD5354A, 0x2E376EFA, 0x0B0C94E5, 0x47F5F70A, 0x7FA04F19, 0x18C0FA00,
0x6C7A7178, 0x2C8BDAA8, 0x12375435, 0x4E9363FB, 0x12E7B7AD, 0x4FEE48C4, 0x3F85E6E6, 0x58B44BA9,
0x3FCAEC41, 0x392E534E, 0x4B5F553A, 0x0E45EB3C, 0x0E00E83E, 0x4E896E1A, 0x35BCAF71, 0x48CA1C47,
0x0CAA55EE, 0x72F6FCF6, 0x50266A7D, 0x0473D5AC, 0x09770608, 0x3420FDD4, 0x7B9B8677, 0x2E4615EB,
0x3F797CC7, 0x0870BBC1, 0x5C7D84E6, 0x4A8611AC, 0x5066B2CB, 0x5C1DD3FF, 0x63470BAC, 0x3CE12443,
0x08A9AEA7, 0x757E5FE2, 0x0B74883F, 0x1B916654, 0x456CA8A6, 0x4AFA6F25, 0x7445B1FE, 0x053794E8,
0x0428C273, 0x3FA50738, 0x137D8024, 0x1229AAB1, 0x0E2E7552, 0x493A2F95, 0x5AF3C6F9, 0x1AD8CB41,
0x3C312C8C, 0x2B1A3176, 0x1F4CA0ED, 0x45A83294, 0x5F3B2F4A, 0x1AE82764, 0x73EE487F, 0x1EB4AC11,
};
// very simple 'random' number generator that mutates a single value in memory
// prng implementation is identical to that of guRandom
u32 effect_rand_int(s32 max) {
u32 seed = (effect_prng_seed << 2) + 2;
seed *= (seed + 1);
seed = seed >> 2;
effect_prng_seed = seed;
return effect_prng_seed % (max + 1);
}
// very simple 'random' number generator using a LUT
s32 func_E0200044(s32 max, s32 idx) {
s32 lookupVal = D_E0200734[idx % ARRAY_COUNT(D_E0200734)];
if (lookupVal < 0) {
lookupVal = -lookupVal;
}
return lookupVal % (max + 1);
}
// Unused, UB, abandon all hope, ye who enter here
void func_E02000AC(s32 arg0, s32 arg1) {
s32 i;
s32 j;
s32 width;
s32 x;
s32 new_var;
s32 var_t3;
s32 s2 = 20;
s32 s1 = 0;
gDPSetPrimColor(gMainGfxPos++, 0, 0, 128, 128, 128, 255);
width = 80;
for (i = 0; i < 10; i++, s1 = i * 24, s2 = i * 24 + 20) {
x = arg0;
new_var = x + width;
var_t3 = i * 6;
gDPSetTextureImage(gMainGfxPos++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 80, nuGfxCfb_ptr);
gDPSetTile(gMainGfxPos++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 20, 0x0000, G_TX_LOADTILE, 0, G_TX_NOMIRROR | G_TX_WRAP,
6, G_TX_NOLOD, G_TX_NOMIRROR | G_TX_WRAP, 7, G_TX_NOLOD);
gDPLoadSync(gMainGfxPos++);
gDPLoadTile(gMainGfxPos++, G_TX_LOADTILE, 0, s1, 0x013C, s2);
gDPPipeSync(gMainGfxPos++);
gDPSetTile(gMainGfxPos++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 20, 0x0000, G_TX_RENDERTILE, 0,
G_TX_NOMIRROR | G_TX_WRAP, 6, G_TX_NOLOD, G_TX_NOMIRROR | G_TX_WRAP, 7, G_TX_NOLOD);
gDPSetTileSize(gMainGfxPos++, G_TX_RENDERTILE, arg0 << G_TEXTURE_IMAGE_FRAC,
(arg1 + var_t3) << G_TEXTURE_IMAGE_FRAC, (arg0 + 79) << G_TEXTURE_IMAGE_FRAC,
((arg1 + var_t3) + 5) << G_TEXTURE_IMAGE_FRAC);
gDPSetTileSize(gMainGfxPos++, G_TX_RENDERTILE + 1, arg0 << G_TEXTURE_IMAGE_FRAC,
(arg1 + var_t3) << G_TEXTURE_IMAGE_FRAC, (arg0 + 79) << G_TEXTURE_IMAGE_FRAC,
((arg1 + var_t3) + 5) << G_TEXTURE_IMAGE_FRAC);
for (j = 0; j < 1; j++) {
gDPSetTextureImage(gMainGfxPos++, G_IM_FMT_RGBA, G_IM_SIZ_16b, 320, nuGfxCfb_ptr);
gDPSetTile(gMainGfxPos++, G_IM_FMT_RGBA, G_IM_SIZ_16b,
((((((x + width) - 1) - x) + 1) * G_IM_SIZ_16b_TILE_BYTES) + 7) >> 3, 0x100, G_TX_LOADTILE, 0,
G_TX_WRAP, 6, G_TX_NOLOD, G_TX_WRAP, 7, G_TX_NOLOD);
gDPLoadSync(gMainGfxPos++);
gDPLoadTile(gMainGfxPos++, G_TX_LOADTILE, x << G_TEXTURE_IMAGE_FRAC,
(arg1 + var_t3) << G_TEXTURE_IMAGE_FRAC,
((new_var) - 1) << G_TEXTURE_IMAGE_FRAC,
((arg1 + var_t3) + 5) << G_TEXTURE_IMAGE_FRAC);
gDPPipeSync(gMainGfxPos++);
gDPSetTile(gMainGfxPos++, G_IM_FMT_RGBA, G_IM_SIZ_16b,
((((((x + width) - 1) - x) + 1) * G_IM_SIZ_16b_TILE_BYTES) + 7) >> 3, 0x100, G_TX_RENDERTILE + 1,
0, G_TX_WRAP, 6, G_TX_NOLOD, G_TX_WRAP, 7, G_TX_NOLOD);
gSPTextureRectangle(gMainGfxPos++, x * 4, (arg1 + var_t3) * 4, (x + width) * 4, ((arg1 + var_t3) + 6) * 4,
0, x * 32, (arg1 + (i * 6)) * 32, 0x400, 0x400);
}
gDPPipeSync(gMainGfxPos++);
}
}
|
80ce864013146176989ab8070d6c4b3451ee95d2
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/ffmpeg/libavformat/network.h
|
71c49a73fbb549c95a3ae147d08b5ee19563c77a
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"BSD-2-Clause",
"BSD-3-Clause",
"LGPL-2.1-only",
"LGPL-3.0-only",
"GPL-2.0-only",
"GPL-3.0-or-later",
"LGPL-3.0-or-later",
"IJG",
"LicenseRef-scancode-other-permissive",
"GPL-2.0-or-later",
"GPL-3.0-only"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 10,113
|
h
|
network.h
|
/*
* Copyright (c) 2007 The FFmpeg Project
*
* This file is part of FFmpeg.
*
* FFmpeg 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 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVFORMAT_NETWORK_H
#define AVFORMAT_NETWORK_H
#include <errno.h>
#include <stdint.h>
#include "config.h"
#include "libavutil/error.h"
#include "os_support.h"
#include "avio.h"
#include "url.h"
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_WINSOCK2_H
#include <winsock2.h>
#include <ws2tcpip.h>
#ifndef EPROTONOSUPPORT
#define EPROTONOSUPPORT WSAEPROTONOSUPPORT
#endif
#ifndef ETIMEDOUT
#define ETIMEDOUT WSAETIMEDOUT
#endif
#ifndef ECONNREFUSED
#define ECONNREFUSED WSAECONNREFUSED
#endif
#ifndef EINPROGRESS
#define EINPROGRESS WSAEINPROGRESS
#endif
#ifndef ENOTCONN
#define ENOTCONN WSAENOTCONN
#endif
#define getsockopt(a, b, c, d, e) getsockopt(a, b, c, (char*) d, e)
#define setsockopt(a, b, c, d, e) setsockopt(a, b, c, (const char*) d, e)
int ff_neterrno(void);
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#define ff_neterrno() AVERROR(errno)
#endif /* HAVE_WINSOCK2_H */
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#if HAVE_POLL_H
#include <poll.h>
#endif
int ff_socket_nonblock(int socket, int enable);
int ff_network_init(void);
void ff_network_close(void);
int ff_tls_init(void);
void ff_tls_deinit(void);
int ff_network_wait_fd(int fd, int write);
/**
* This works similarly to ff_network_wait_fd, but waits up to 'timeout' microseconds
* Uses ff_network_wait_fd in a loop
*
* @param fd Socket descriptor
* @param write Set 1 to wait for socket able to be read, 0 to be written
* @param timeout Timeout interval, in microseconds. Actual precision is 100000 mcs, due to ff_network_wait_fd usage
* @param int_cb Interrupt callback, is checked before each ff_network_wait_fd call
* @return 0 if data can be read/written, AVERROR(ETIMEDOUT) if timeout expired, or negative error code
*/
int ff_network_wait_fd_timeout(int fd, int write, int64_t timeout, AVIOInterruptCB *int_cb);
/**
* Waits for up to 'timeout' microseconds. If the usert's int_cb is set and
* triggered, return before that.
* @param timeout Timeout in microseconds. Maybe have lower actual precision.
* @param int_cb Interrupt callback, is checked regularly.
* @return AVERROR(ETIMEDOUT) if timeout expirted, AVERROR_EXIT if interrupted by int_cb
*/
int ff_network_sleep_interruptible(int64_t timeout, AVIOInterruptCB *int_cb);
#if !HAVE_STRUCT_SOCKADDR_STORAGE
struct sockaddr_storage {
#if HAVE_STRUCT_SOCKADDR_SA_LEN
uint8_t ss_len;
uint8_t ss_family;
#else
uint16_t ss_family;
#endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
char ss_pad1[6];
int64_t ss_align;
char ss_pad2[112];
};
#endif /* !HAVE_STRUCT_SOCKADDR_STORAGE */
typedef union sockaddr_union {
struct sockaddr_storage storage;
struct sockaddr_in in;
#if HAVE_STRUCT_SOCKADDR_IN6
struct sockaddr_in6 in6;
#endif
} sockaddr_union;
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
#if !HAVE_STRUCT_ADDRINFO
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
int ai_addrlen;
struct sockaddr *ai_addr;
char *ai_canonname;
struct addrinfo *ai_next;
};
#endif /* !HAVE_STRUCT_ADDRINFO */
/* getaddrinfo constants */
#ifndef EAI_AGAIN
#define EAI_AGAIN 2
#endif
#ifndef EAI_BADFLAGS
#define EAI_BADFLAGS 3
#endif
#ifndef EAI_FAIL
#define EAI_FAIL 4
#endif
#ifndef EAI_FAMILY
#define EAI_FAMILY 5
#endif
#ifndef EAI_MEMORY
#define EAI_MEMORY 6
#endif
#ifndef EAI_NODATA
#define EAI_NODATA 7
#endif
#ifndef EAI_NONAME
#define EAI_NONAME 8
#endif
#ifndef EAI_SERVICE
#define EAI_SERVICE 9
#endif
#ifndef EAI_SOCKTYPE
#define EAI_SOCKTYPE 10
#endif
#ifndef AI_PASSIVE
#define AI_PASSIVE 1
#endif
#ifndef AI_CANONNAME
#define AI_CANONNAME 2
#endif
#ifndef AI_NUMERICHOST
#define AI_NUMERICHOST 4
#endif
#ifndef NI_NOFQDN
#define NI_NOFQDN 1
#endif
#ifndef NI_NUMERICHOST
#define NI_NUMERICHOST 2
#endif
#ifndef NI_NAMERQD
#define NI_NAMERQD 4
#endif
#ifndef NI_NUMERICSERV
#define NI_NUMERICSERV 8
#endif
#ifndef NI_DGRAM
#define NI_DGRAM 16
#endif
#if !HAVE_GETADDRINFO
int ff_getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **res);
void ff_freeaddrinfo(struct addrinfo *res);
int ff_getnameinfo(const struct sockaddr *sa, int salen,
char *host, int hostlen,
char *serv, int servlen, int flags);
#define getaddrinfo ff_getaddrinfo
#define freeaddrinfo ff_freeaddrinfo
#define getnameinfo ff_getnameinfo
#endif /* !HAVE_GETADDRINFO */
#if !HAVE_GETADDRINFO || HAVE_WINSOCK2_H
const char *ff_gai_strerror(int ecode);
#undef gai_strerror
#define gai_strerror ff_gai_strerror
#endif /* !HAVE_GETADDRINFO || HAVE_WINSOCK2_H */
#ifndef INADDR_LOOPBACK
#define INADDR_LOOPBACK 0x7f000001
#endif
#ifndef INET_ADDRSTRLEN
#define INET_ADDRSTRLEN 16
#endif
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN INET_ADDRSTRLEN
#endif
#ifndef IN_MULTICAST
#define IN_MULTICAST(a) ((((uint32_t)(a)) & 0xf0000000) == 0xe0000000)
#endif
#ifndef IN6_IS_ADDR_MULTICAST
#define IN6_IS_ADDR_MULTICAST(a) (((uint8_t *) (a))[0] == 0xff)
#endif
int ff_is_multicast_address(struct sockaddr *addr);
#define POLLING_TIME 100 /// Time in milliseconds between interrupt check
/**
* Bind to a file descriptor and poll for a connection.
*
* @param fd First argument of bind().
* @param addr Second argument of bind().
* @param addrlen Third argument of bind().
* @param timeout Polling timeout in milliseconds.
* @param h URLContext providing interrupt check
* callback and logging context.
* @return A non-blocking file descriptor on success
* or an AVERROR on failure.
*/
int ff_listen_bind(int fd, const struct sockaddr *addr,
socklen_t addrlen, int timeout,
URLContext *h);
/**
* Bind to a file descriptor to an address without accepting connections.
* @param fd First argument of bind().
* @param addr Second argument of bind().
* @param addrlen Third argument of bind().
* @return 0 on success or an AVERROR on failure.
*/
int ff_listen(int fd, const struct sockaddr *addr, socklen_t addrlen,
void *logctx);
/**
* Poll for a single connection on the passed file descriptor.
* @param fd The listening socket file descriptor.
* @param timeout Polling timeout in milliseconds.
* @param h URLContext providing interrupt check
* callback and logging context.
* @return A non-blocking file descriptor on success
* or an AVERROR on failure.
*/
int ff_accept(int fd, int timeout, URLContext *h);
/**
* Connect to a file descriptor and poll for result.
*
* @param fd First argument of connect(),
* will be set as non-blocking.
* @param addr Second argument of connect().
* @param addrlen Third argument of connect().
* @param timeout Polling timeout in milliseconds.
* @param h URLContext providing interrupt check
* callback and logging context.
* @param will_try_next Whether the caller will try to connect to another
* address for the same host name, affecting the form of
* logged errors.
* @return 0 on success, AVERROR on failure.
*/
int ff_listen_connect(int fd, const struct sockaddr *addr,
socklen_t addrlen, int timeout,
URLContext *h, int will_try_next);
int ff_http_match_no_proxy(const char *no_proxy, const char *hostname);
int ff_socket(int domain, int type, int protocol, void *logctx);
void ff_log_net_error(void *ctx, int level, const char* prefix);
/**
* Connect to any of the given addrinfo addresses, with multiple attempts
* running in parallel.
*
* @param addrs The list of addresses to try to connect to.
* This list will be mutated internally, but the list head
* will remain as such, so this doesn't affect the caller
* freeing the list afterwards.
* @param timeout_ms_per_address The number of milliseconds to wait for each
* connection attempt. Since multiple addresses are tried,
* some of them in parallel, the total run time will at most
* be timeout_ms_per_address*ceil(nb_addrs/parallel) +
* (parallel - 1) * NEXT_ATTEMPT_DELAY_MS.
* @param parallel The maximum number of connections to attempt in parallel.
* This is limited to an internal maximum capacity.
* @param h URLContext providing interrupt check
* callback and logging context.
* @param fd If successful, the connected socket is returned here.
* @param customize_fd Function that will be called for each socket created,
* to allow the caller to set socket options before calling
* connect() on it, may be NULL.
* @param customize_ctx Context parameter passed to customize_fd.
* @return 0 on success, AVERROR on failure.
*/
int ff_connect_parallel(struct addrinfo *addrs, int timeout_ms_per_address,
int parallel, URLContext *h, int *fd,
void (*customize_fd)(void *, int), void *customize_ctx);
#endif /* AVFORMAT_NETWORK_H */
|
e3eefa93df2d759c7f37ed599743ee24d1dedacb
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/arch/arm/mach-rpc/include/mach/uncompress.h
|
0fd4b0b8ef22ea91b2990588a5158bc226e0f170
|
[
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 4,373
|
h
|
uncompress.h
|
/*
* arch/arm/mach-rpc/include/mach/uncompress.h
*
* Copyright (C) 1996 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define VIDMEM ((char *)SCREEN_START)
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/setup.h>
#include <asm/page.h>
int video_size_row;
unsigned char bytes_per_char_h;
extern unsigned long con_charconvtable[256];
struct param_struct {
unsigned long page_size;
unsigned long nr_pages;
unsigned long ramdisk_size;
unsigned long mountrootrdonly;
unsigned long rootdev;
unsigned long video_num_cols;
unsigned long video_num_rows;
unsigned long video_x;
unsigned long video_y;
unsigned long memc_control_reg;
unsigned char sounddefault;
unsigned char adfsdrives;
unsigned char bytes_per_char_h;
unsigned char bytes_per_char_v;
unsigned long unused[256/4-11];
};
static const unsigned long palette_4[16] = {
0x00000000,
0x000000cc,
0x0000cc00, /* Green */
0x0000cccc, /* Yellow */
0x00cc0000, /* Blue */
0x00cc00cc, /* Magenta */
0x00cccc00, /* Cyan */
0x00cccccc, /* White */
0x00000000,
0x000000ff,
0x0000ff00,
0x0000ffff,
0x00ff0000,
0x00ff00ff,
0x00ffff00,
0x00ffffff
};
#define palette_setpixel(p) *(unsigned long *)(IO_START+0x00400000) = 0x10000000|((p) & 255)
#define palette_write(v) *(unsigned long *)(IO_START+0x00400000) = 0x00000000|((v) & 0x00ffffff)
/*
* params_phys is a linker defined symbol - see
* arch/arm/boot/compressed/Makefile
*/
extern __attribute__((pure)) struct param_struct *params(void);
#define params (params())
#ifndef STANDALONE_DEBUG
unsigned long video_num_cols;
unsigned long video_num_rows;
unsigned long video_x;
unsigned long video_y;
unsigned char bytes_per_char_v;
int white;
/*
* This does not append a newline
*/
static void putc(int c)
{
extern void ll_write_char(char *, char c, char white);
int x,y;
char *ptr;
x = video_x;
y = video_y;
if (c == '\n') {
if (++y >= video_num_rows)
y--;
} else if (c == '\r') {
x = 0;
} else {
ptr = VIDMEM + ((y*video_num_cols*bytes_per_char_v+x)*bytes_per_char_h);
ll_write_char(ptr, c, white);
if (++x >= video_num_cols) {
x = 0;
if ( ++y >= video_num_rows ) {
y--;
}
}
}
video_x = x;
video_y = y;
}
static inline void flush(void)
{
}
/*
* Setup for decompression
*/
static void arch_decomp_setup(void)
{
int i;
struct tag *t = (struct tag *)params;
unsigned int nr_pages = 0, page_size = PAGE_SIZE;
if (t->hdr.tag == ATAG_CORE)
{
for (; t->hdr.size; t = tag_next(t))
{
if (t->hdr.tag == ATAG_VIDEOTEXT)
{
video_num_rows = t->u.videotext.video_lines;
video_num_cols = t->u.videotext.video_cols;
bytes_per_char_h = t->u.videotext.video_points;
bytes_per_char_v = t->u.videotext.video_points;
video_x = t->u.videotext.x;
video_y = t->u.videotext.y;
}
if (t->hdr.tag == ATAG_MEM)
{
page_size = PAGE_SIZE;
nr_pages += (t->u.mem.size / PAGE_SIZE);
}
}
}
else
{
nr_pages = params->nr_pages;
page_size = params->page_size;
video_num_rows = params->video_num_rows;
video_num_cols = params->video_num_cols;
video_x = params->video_x;
video_y = params->video_y;
bytes_per_char_h = params->bytes_per_char_h;
bytes_per_char_v = params->bytes_per_char_v;
}
video_size_row = video_num_cols * bytes_per_char_h;
if (bytes_per_char_h == 4)
for (i = 0; i < 256; i++)
con_charconvtable[i] =
(i & 128 ? 1 << 0 : 0) |
(i & 64 ? 1 << 4 : 0) |
(i & 32 ? 1 << 8 : 0) |
(i & 16 ? 1 << 12 : 0) |
(i & 8 ? 1 << 16 : 0) |
(i & 4 ? 1 << 20 : 0) |
(i & 2 ? 1 << 24 : 0) |
(i & 1 ? 1 << 28 : 0);
else
for (i = 0; i < 16; i++)
con_charconvtable[i] =
(i & 8 ? 1 << 0 : 0) |
(i & 4 ? 1 << 8 : 0) |
(i & 2 ? 1 << 16 : 0) |
(i & 1 ? 1 << 24 : 0);
palette_setpixel(0);
if (bytes_per_char_h == 1) {
palette_write (0);
palette_write (0x00ffffff);
for (i = 2; i < 256; i++)
palette_write (0);
white = 1;
} else {
for (i = 0; i < 256; i++)
palette_write (i < 16 ? palette_4[i] : 0);
white = 7;
}
if (nr_pages * page_size < 4096*1024) error("<4M of mem\n");
}
#endif
|
6b1aa0eb5036e2f8d082551eb62afa0cc40beafc
|
52c16ddfdfc0ad35874fae64cafc03192ccbc224
|
/test/string.c
|
e466bb84f53aad11a6520294c210f42a4fd97b79
|
[
"MIT"
] |
permissive
|
fredrikwidlund/libreactor
|
949c5a7fe5404ae599521d3ec24500dfb0730cf9
|
64afa5364c445736317e44e820a85f09aa88dfc0
|
refs/heads/master
| 2022-01-30T21:48:08.920110
| 2022-01-11T11:37:45
| 2022-01-11T11:37:45
| 35,740,163
| 378
| 42
|
MIT
| 2023-09-09T21:34:19
| 2015-05-16T21:02:03
|
C
|
UTF-8
|
C
| false
| false
| 2,847
|
c
|
string.c
|
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <setjmp.h>
#include <cmocka.h>
#include "reactor.h"
static void test_env(void **arg)
{
(void) arg;
assert_int_equal(chdir(DATADIR), 0);
}
static void string_tests(void **arg)
{
string s, t;
data d;
(void) arg;
/* new string */
s = string_null();
assert_true(string_equal(string_null(), s));
s = string_append_data(s, data_string("test"));
string_free(s);
/* load string from file and save */
s = string_load("/dev/null");
assert_true(string_equal(s, string_null()));
assert_int_equal(string_save(s, "/dev/null"), 0);
/* copy string */
s = string_append_data(string_null(), data_string("test"));
s = string_append_data(s, data_string("test"));
string_free(string_copy(s));
string_free(s);
/* copy null string */
string_free(string_copy(string_null()));
/* read from file */
string_free(string_load("LICENSE"));
/* read from non-existing file */
assert_true(string_equal(string_null(), string_load("/doesnotexist")));
/* find sub-string */
s = string_append_data(string_null(), data_string("xxxxxtestxxxxx"));
d = string_find_data(s, data_string("xtestx"));
assert_false(data_empty(d));
/* fail find */
d = string_find_data(s, data_string("ytesty"));
assert_true(data_empty(d));
/* fail null */
d = string_find_data(s, data_null());
assert_true(data_empty(d));
string_free(s);
/* compare */
s = string_append_data(string_null(), data_string(""));
assert_true(string_equal(string_null(), string_null()));
assert_true(string_equal(s, string_null()));
string_free(s);
s = string_append_data(string_null(), data_string("a"));
t = string_append_data(string_null(), data_string("b"));
assert_false(string_equal(s, t));
string_free(s);
string_free(t);
/* erase and replace null */
s = string_append_data(string_null(), data_string("xxxxxtestxxxxx"));
s = string_erase_data(s, data_null());
s = string_replace_data(s, data_null(), data_null());
assert_int_equal(string_size(s), 14);
assert_int_equal(string_capacity(s), 14);
string_free(s);
/* prepend */
s = string_prepend_data(string_null(), data_string("xxxxxtestxxxxx"));
/* replace */
s = string_replace_data(s, data_string("test"), data_null());
s = string_replace_all_data(s, data_string("x"), data_string("y"));
s = string_replace_all_data(s, data_string("x"), data_string("y"));
assert_true(string_equal(s, s));
assert_false(string_equal(s, string_null()));
/* save */
assert_int_equal(string_save(s, "doesnotexist"), -1);
assert_int_equal(string_save(s, "/dev/null"), 0);
string_free(s);
}
int main()
{
const struct CMUnitTest tests[] =
{
cmocka_unit_test(test_env),
cmocka_unit_test(string_tests)
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
|
41d907610e85ff72392876a5a3ac4a5521e008a1
|
c72be999abf8848a7d09264ba9ee7bae30f4524a
|
/xme/xme/ports/hardware/cpu/gen_c/xme/hal/math_arch.c
|
175a8f312f84a1ba8dd640cf11ecd84256288329
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
ipa-rmb/autopnp
|
8399be67c1a3de61e01619dc8677c52728ffd836
|
f25517a093c772a1481bcff3e9da055d4c627954
|
refs/heads/indigo_dev
| 2022-05-05T01:57:05.858437
| 2022-04-29T07:31:42
| 2022-04-29T07:31:42
| 3,398,225
| 144
| 101
| null | 2019-07-08T06:11:13
| 2012-02-09T15:30:28
|
C
|
UTF-8
|
C
| false
| false
| 1,509
|
c
|
math_arch.c
|
/*
* Copyright (c) 2011-2012, fortiss GmbH.
* Licensed under the Apache License, Version 2.0.
*
* Use, modification and distribution are subject to the terms specified
* in the accompanying license file LICENSE.txt located at the root directory
* of this software distribution. A copy is available at
* http://chromosome.fortiss.org/.
*
* This file is part of CHROMOSOME.
*
* $Id: math_arch.c 3345 2013-05-17 12:07:58Z geisinger $
*/
/**
* \file
* Math functions (architecture specific part: generic C stub).
*/
/******************************************************************************/
/*** Includes ***/
/******************************************************************************/
#include "xme/hal/math_arch.h"
/******************************************************************************/
/*** Implementation ***/
/******************************************************************************/
uint32_t
xme_hal_math_ceilPowerOfTwo(uint32_t x)
{
if ((0 < x) && (x <= 0x80000000))
{
uint32_t mask = 0x80000000;
do
{
if (0 != (x & mask)) {
return (x == mask) ? mask : mask << 1;
}
mask >>= 1;
} while (1);
}
return 0;
}
uint32_t
xme_hal_math_floorPowerOfTwo(uint32_t x)
{
if (0 < x)
{
uint32_t mask = 0x80000000;
do
{
if (0 != (x & mask)) {
return mask;
}
mask >>= 1;
} while (1);
}
return 0;
}
|
ff75f64be3665ba8319f9fbd70676552416dfb60
|
a6f47c6b702055aa2cc1a9ee051017320a8c602b
|
/modules/gdnative/include/gdnative/basis.h
|
f3ef388dd9d69090da31622240dee24acf8665a3
|
[
"FTL",
"Zlib",
"MIT",
"BSD-3-Clause",
"Bitstream-Vera",
"CC0-1.0",
"MPL-2.0",
"OFL-1.1",
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
Stary2001/godot
|
849ca3045a687d9b34de7cc24a8b6d26f89f95bc
|
00c6ce9716ed542997bc2b59136bceb3729db970
|
refs/heads/3.5.2-stable_switch
| 2023-05-25T08:38:55.387308
| 2023-04-14T23:07:10
| 2023-04-23T20:32:29
| 148,190,960
| 306
| 38
|
MIT
| 2023-05-19T20:10:22
| 2018-09-10T17:11:15
|
C++
|
UTF-8
|
C
| false
| false
| 6,275
|
h
|
basis.h
|
/**************************************************************************/
/* basis.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/**************************************************************************/
#ifndef GDNATIVE_BASIS_H
#define GDNATIVE_BASIS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#define GODOT_BASIS_SIZE 36
#ifndef GODOT_CORE_API_GODOT_BASIS_TYPE_DEFINED
#define GODOT_CORE_API_GODOT_BASIS_TYPE_DEFINED
typedef struct {
uint8_t _dont_touch_that[GODOT_BASIS_SIZE];
} godot_basis;
#endif
// reduce extern "C" nesting for VS2013
#ifdef __cplusplus
}
#endif
#include <gdnative/gdnative.h>
#include <gdnative/quat.h>
#include <gdnative/vector3.h>
#ifdef __cplusplus
extern "C" {
#endif
void GDAPI godot_basis_new_with_rows(godot_basis *r_dest, const godot_vector3 *p_x_axis, const godot_vector3 *p_y_axis, const godot_vector3 *p_z_axis);
void GDAPI godot_basis_new_with_axis_and_angle(godot_basis *r_dest, const godot_vector3 *p_axis, const godot_real p_phi);
void GDAPI godot_basis_new_with_euler(godot_basis *r_dest, const godot_vector3 *p_euler);
void GDAPI godot_basis_new_with_euler_quat(godot_basis *r_dest, const godot_quat *p_euler);
godot_string GDAPI godot_basis_as_string(const godot_basis *p_self);
godot_basis GDAPI godot_basis_inverse(const godot_basis *p_self);
godot_basis GDAPI godot_basis_transposed(const godot_basis *p_self);
godot_basis GDAPI godot_basis_orthonormalized(const godot_basis *p_self);
godot_real GDAPI godot_basis_determinant(const godot_basis *p_self);
godot_basis GDAPI godot_basis_rotated(const godot_basis *p_self, const godot_vector3 *p_axis, const godot_real p_phi);
godot_basis GDAPI godot_basis_scaled(const godot_basis *p_self, const godot_vector3 *p_scale);
godot_vector3 GDAPI godot_basis_get_scale(const godot_basis *p_self);
godot_vector3 GDAPI godot_basis_get_euler(const godot_basis *p_self);
godot_quat GDAPI godot_basis_get_quat(const godot_basis *p_self);
void GDAPI godot_basis_set_quat(godot_basis *p_self, const godot_quat *p_quat);
void GDAPI godot_basis_set_axis_angle_scale(godot_basis *p_self, const godot_vector3 *p_axis, godot_real p_phi, const godot_vector3 *p_scale);
void GDAPI godot_basis_set_euler_scale(godot_basis *p_self, const godot_vector3 *p_euler, const godot_vector3 *p_scale);
void GDAPI godot_basis_set_quat_scale(godot_basis *p_self, const godot_quat *p_quat, const godot_vector3 *p_scale);
godot_real GDAPI godot_basis_tdotx(const godot_basis *p_self, const godot_vector3 *p_with);
godot_real GDAPI godot_basis_tdoty(const godot_basis *p_self, const godot_vector3 *p_with);
godot_real GDAPI godot_basis_tdotz(const godot_basis *p_self, const godot_vector3 *p_with);
godot_vector3 GDAPI godot_basis_xform(const godot_basis *p_self, const godot_vector3 *p_v);
godot_vector3 GDAPI godot_basis_xform_inv(const godot_basis *p_self, const godot_vector3 *p_v);
godot_int GDAPI godot_basis_get_orthogonal_index(const godot_basis *p_self);
void GDAPI godot_basis_new(godot_basis *r_dest);
// p_elements is a pointer to an array of 3 (!!) vector3
void GDAPI godot_basis_get_elements(const godot_basis *p_self, godot_vector3 *p_elements);
godot_vector3 GDAPI godot_basis_get_axis(const godot_basis *p_self, const godot_int p_axis);
void GDAPI godot_basis_set_axis(godot_basis *p_self, const godot_int p_axis, const godot_vector3 *p_value);
godot_vector3 GDAPI godot_basis_get_row(const godot_basis *p_self, const godot_int p_row);
void GDAPI godot_basis_set_row(godot_basis *p_self, const godot_int p_row, const godot_vector3 *p_value);
godot_bool GDAPI godot_basis_operator_equal(const godot_basis *p_self, const godot_basis *p_b);
godot_basis GDAPI godot_basis_operator_add(const godot_basis *p_self, const godot_basis *p_b);
godot_basis GDAPI godot_basis_operator_subtract(const godot_basis *p_self, const godot_basis *p_b);
godot_basis GDAPI godot_basis_operator_multiply_vector(const godot_basis *p_self, const godot_basis *p_b);
godot_basis GDAPI godot_basis_operator_multiply_scalar(const godot_basis *p_self, const godot_real p_b);
godot_basis GDAPI godot_basis_slerp(const godot_basis *p_self, const godot_basis *p_b, const godot_real p_t);
#ifdef __cplusplus
}
#endif
#endif // GDNATIVE_BASIS_H
|
fb3910f6f0df519c8501c6b77ab98e425971e7b6
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/security/mhash/patches/patch-include_mutils_mutils.h
|
e9524696269041fccc9344de85007daf124c63d0
|
[] |
no_license
|
NetBSD/pkgsrc
|
a0732c023519650ef821ab89c23ab6ab59e25bdb
|
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
|
refs/heads/trunk
| 2023-09-01T07:40:12.138283
| 2023-09-01T05:25:19
| 2023-09-01T05:25:19
| 88,439,572
| 321
| 138
| null | 2023-07-12T22:34:14
| 2017-04-16T20:04:15
| null |
UTF-8
|
C
| false
| false
| 383
|
h
|
patch-include_mutils_mutils.h
|
$NetBSD: patch-include_mutils_mutils.h,v 1.1 2015/06/18 06:17:33 dholland Exp $
Sun Studio doesn't understand __const.
--- include/mutils/mutils.h~ 2015-06-18 06:08:36.000000000 +0000
+++ include/mutils/mutils.h
@@ -23,7 +23,7 @@
#include <mutils/mincludes.h>
-#if defined(const)
+#if defined(const) || (defined(__sun) && !defined(__GNUC__))
#define __const const
#endif
|
96a170c1b8e8de33dc70d7552d3bfce2117c06ea
|
e910318d01528d82040507a49eeeb8dade45b31f
|
/ports/esp32/machine_i2c.c
|
8d8c2e9e637a2a95b255983838cd77555c28d87d
|
[
"MIT"
] |
permissive
|
pfalcon/pycopy
|
e844480a5e5cd463530328889daed2ba87552b8a
|
3ac90ae9c3c6bbebfba9cada2d37025e35c62796
|
refs/heads/pfalcon
| 2023-08-30T09:39:52.290147
| 2022-09-08T16:42:38
| 2022-09-08T16:42:38
| 15,507,576
| 753
| 71
|
MIT
| 2021-05-08T04:59:21
| 2013-12-29T11:38:47
|
C
|
UTF-8
|
C
| false
| false
| 6,715
|
c
|
machine_i2c.c
|
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Damien P. George
*
* 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.
*/
#include "py/runtime.h"
#include "py/mphal.h"
#include "py/mperrno.h"
#include "extmod/machine_i2c.h"
#include "modmachine.h"
#include "driver/i2c.h"
#ifndef MICROPY_HW_I2C0_SCL
#define MICROPY_HW_I2C0_SCL (GPIO_NUM_18)
#define MICROPY_HW_I2C0_SDA (GPIO_NUM_19)
#endif
#ifndef MICROPY_HW_I2C1_SCL
#if CONFIG_IDF_TARGET_ESP32
#define MICROPY_HW_I2C1_SCL (GPIO_NUM_25)
#define MICROPY_HW_I2C1_SDA (GPIO_NUM_26)
#else
#define MICROPY_HW_I2C1_SCL (GPIO_NUM_9)
#define MICROPY_HW_I2C1_SDA (GPIO_NUM_8)
#endif
#endif
#define I2C_DEFAULT_TIMEOUT_US (10000) // 10ms
typedef struct _machine_hw_i2c_obj_t {
mp_obj_base_t base;
i2c_port_t port : 8;
gpio_num_t scl : 8;
gpio_num_t sda : 8;
} machine_hw_i2c_obj_t;
STATIC machine_hw_i2c_obj_t machine_hw_i2c_obj[I2C_NUM_MAX];
STATIC void machine_hw_i2c_init(machine_hw_i2c_obj_t *self, uint32_t freq, uint32_t timeout_us, bool first_init) {
if (!first_init) {
i2c_driver_delete(self->port);
}
i2c_config_t conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = self->sda,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_io_num = self->scl,
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = freq,
};
i2c_param_config(self->port, &conf);
i2c_set_timeout(self->port, I2C_APB_CLK_FREQ / 1000000 * timeout_us);
i2c_driver_install(self->port, I2C_MODE_MASTER, 0, 0, 0);
}
int machine_hw_i2c_transfer(mp_obj_base_t *self_in, uint16_t addr, size_t n, mp_machine_i2c_buf_t *bufs, unsigned int flags) {
machine_hw_i2c_obj_t *self = MP_OBJ_TO_PTR(self_in);
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, addr << 1 | (flags & MP_MACHINE_I2C_FLAG_READ), true);
int data_len = 0;
for (; n--; ++bufs) {
if (flags & MP_MACHINE_I2C_FLAG_READ) {
i2c_master_read(cmd, bufs->buf, bufs->len, n == 0 ? I2C_MASTER_LAST_NACK : I2C_MASTER_ACK);
} else {
if (bufs->len != 0) {
i2c_master_write(cmd, bufs->buf, bufs->len, true);
}
}
data_len += bufs->len;
}
if (flags & MP_MACHINE_I2C_FLAG_STOP) {
i2c_master_stop(cmd);
}
// TODO proper timeout
esp_err_t err = i2c_master_cmd_begin(self->port, cmd, 100 * (1 + data_len) / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
if (err == ESP_FAIL) {
return -MP_ENODEV;
} else if (err == ESP_ERR_TIMEOUT) {
return -MP_ETIMEDOUT;
} else if (err != ESP_OK) {
return -abs(err);
}
return data_len;
}
/******************************************************************************/
// MicroPython bindings for machine API
STATIC void machine_hw_i2c_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
machine_hw_i2c_obj_t *self = MP_OBJ_TO_PTR(self_in);
int h, l;
i2c_get_period(self->port, &h, &l);
mp_printf(print, "I2C(%u, scl=%u, sda=%u, freq=%u)",
self->port, self->scl, self->sda, I2C_APB_CLK_FREQ / (h + l));
}
mp_obj_t machine_hw_i2c_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
// Parse args
enum { ARG_id, ARG_scl, ARG_sda, ARG_freq, ARG_timeout };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_id, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
{ MP_QSTR_scl, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
{ MP_QSTR_sda, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
{ MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 400000} },
{ MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = I2C_DEFAULT_TIMEOUT_US} },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
// Get I2C bus
mp_int_t i2c_id = mp_obj_get_int(args[ARG_id].u_obj);
if (!(I2C_NUM_0 <= i2c_id && i2c_id < I2C_NUM_MAX)) {
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("I2C(%d) doesn't exist"), i2c_id);
}
// Get static peripheral object
machine_hw_i2c_obj_t *self = (machine_hw_i2c_obj_t *)&machine_hw_i2c_obj[i2c_id];
bool first_init = false;
if (self->base.type == NULL) {
// Created for the first time, set default pins
self->base.type = &machine_hw_i2c_type;
self->port = i2c_id;
if (self->port == I2C_NUM_0) {
self->scl = MICROPY_HW_I2C0_SCL;
self->sda = MICROPY_HW_I2C0_SDA;
} else {
self->scl = MICROPY_HW_I2C1_SCL;
self->sda = MICROPY_HW_I2C1_SDA;
}
first_init = true;
}
// Set SCL/SDA pins if given
if (args[ARG_scl].u_obj != MP_OBJ_NULL) {
self->scl = mp_hal_get_pin_obj(args[ARG_scl].u_obj);
}
if (args[ARG_sda].u_obj != MP_OBJ_NULL) {
self->sda = mp_hal_get_pin_obj(args[ARG_sda].u_obj);
}
// Initialise the I2C peripheral
machine_hw_i2c_init(self, args[ARG_freq].u_int, args[ARG_timeout].u_int, first_init);
return MP_OBJ_FROM_PTR(self);
}
STATIC const mp_machine_i2c_p_t machine_hw_i2c_p = {
.transfer = machine_hw_i2c_transfer,
};
const mp_obj_type_t machine_hw_i2c_type = {
{ &mp_type_type },
.name = MP_QSTR_I2C,
.print = machine_hw_i2c_print,
.make_new = machine_hw_i2c_make_new,
.protocol = &machine_hw_i2c_p,
.locals_dict = (mp_obj_dict_t *)&mp_machine_i2c_locals_dict,
};
|
f306ac5ee986e7e956e50b5731e0ae128e08ab18
|
5ab69c8644a936a3d9dec1669a86c7369c911bf8
|
/arch/cpu/cc26x0-cc13x0/rf-core/rf-core.c
|
cce716cea2ad35b819ee7b52baa81a24851de267
|
[
"BSD-3-Clause"
] |
permissive
|
contiki-ng/contiki-ng
|
393d36f68b98f5ee3544ea32502cf662ffb2fe9f
|
31fcaadf7a0dc8ceea07f438cd69db73174879e6
|
refs/heads/develop
| 2023-09-01T20:10:30.000765
| 2023-09-01T14:37:12
| 2023-09-01T14:37:12
| 91,191,972
| 1,242
| 788
|
BSD-3-Clause
| 2023-09-14T19:08:35
| 2017-05-13T17:37:59
|
C
|
UTF-8
|
C
| false
| false
| 25,025
|
c
|
rf-core.c
|
/*
* Copyright (c) 2015, Texas Instruments Incorporated - http://www.ti.com/
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER 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.
*/
/*---------------------------------------------------------------------------*/
/**
* \addtogroup rf-core
* @{
*
* \file
* Implementation of the CC13xx/CC26xx RF core driver
*/
/*---------------------------------------------------------------------------*/
#include "contiki.h"
#include "dev/watchdog.h"
#include "sys/process.h"
#include "sys/energest.h"
#include "sys/cc.h"
#include "net/netstack.h"
#include "net/packetbuf.h"
#include "rf-core/rf-core.h"
#include "rf-core/rf-switch.h"
#include "ti-lib.h"
/*---------------------------------------------------------------------------*/
/* RF core and RF HAL API */
#include "hw_rfc_dbell.h"
#include "hw_rfc_pwr.h"
/*---------------------------------------------------------------------------*/
/* RF Core Mailbox API */
#include "driverlib/rf_mailbox.h"
#include "driverlib/rf_common_cmd.h"
#include "driverlib/rf_data_entry.h"
/*---------------------------------------------------------------------------*/
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
/*---------------------------------------------------------------------------*/
#define DEBUG 0
#if DEBUG
#define PRINTF(...) printf(__VA_ARGS__)
#else
#define PRINTF(...)
#endif
/*---------------------------------------------------------------------------*/
#ifdef RF_CORE_CONF_DEBUG_CRC
#define RF_CORE_DEBUG_CRC RF_CORE_CONF_DEBUG_CRC
#else
#define RF_CORE_DEBUG_CRC DEBUG
#endif
/*---------------------------------------------------------------------------*/
/* RF interrupts */
#define RX_FRAME_IRQ IRQ_RX_ENTRY_DONE
#define ERROR_IRQ (IRQ_INTERNAL_ERROR | IRQ_RX_BUF_FULL)
#define RX_NOK_IRQ IRQ_RX_NOK
/* Those IRQs are enabled all the time */
#if RF_CORE_DEBUG_CRC
#define ENABLED_IRQS (RX_FRAME_IRQ | ERROR_IRQ | RX_NOK_IRQ)
#else
#define ENABLED_IRQS (RX_FRAME_IRQ | ERROR_IRQ)
#endif
#define ENABLED_IRQS_POLL_MODE (ENABLED_IRQS & ~(RX_FRAME_IRQ | ERROR_IRQ))
#define cc26xx_rf_cpe0_isr RFCCPE0IntHandler
#define cc26xx_rf_cpe1_isr RFCCPE1IntHandler
/*---------------------------------------------------------------------------*/
typedef ChipType_t chip_type_t;
/*---------------------------------------------------------------------------*/
/* Remember the last Radio Op issued to the radio */
static rfc_radioOp_t *last_radio_op = NULL;
/*---------------------------------------------------------------------------*/
/* A struct holding pointers to the primary mode's abort() and restore() */
static const rf_core_primary_mode_t *primary_mode = NULL;
/*---------------------------------------------------------------------------*/
/* RAT has 32-bit register, overflows once 18 minutes */
#define RAT_RANGE 4294967296ull
/* approximate value */
#define RAT_OVERFLOW_PERIOD_SECONDS (60 * 18)
/* how often to check for the overflow, as a minimum */
#define RAT_OVERFLOW_TIMER_INTERVAL (CLOCK_SECOND * RAT_OVERFLOW_PERIOD_SECONDS / 3)
/* Radio timer (RAT) offset as compared to the rtimer counter (RTC) */
static int32_t rat_offset;
static bool rat_offset_known;
/* Value during the last read of the RAT register */
static uint32_t rat_last_value;
/* For RAT overflow handling */
static struct ctimer rat_overflow_timer;
static volatile uint32_t rat_overflow_counter;
static rtimer_clock_t rat_last_overflow;
static void rat_overflow_check_timer_cb(void *);
/*---------------------------------------------------------------------------*/
volatile int8_t rf_core_last_rssi = RF_CORE_CMD_CCA_REQ_RSSI_UNKNOWN;
volatile uint8_t rf_core_last_corr_lqi = 0;
volatile uint32_t rf_core_last_packet_timestamp = 0;
/*---------------------------------------------------------------------------*/
/* Are we currently in poll mode? */
uint8_t rf_core_poll_mode = 0;
/*---------------------------------------------------------------------------*/
/* Status of the last command sent */
volatile uint32_t last_cmd_status;
/*---------------------------------------------------------------------------*/
PROCESS(rf_core_process, "CC13xx / CC26xx RF driver");
/*---------------------------------------------------------------------------*/
#define RF_CORE_CLOCKS_MASK (RFC_PWR_PWMCLKEN_RFC_M | RFC_PWR_PWMCLKEN_CPE_M \
| RFC_PWR_PWMCLKEN_CPERAM_M | RFC_PWR_PWMCLKEN_FSCA_M \
| RFC_PWR_PWMCLKEN_PHA_M | RFC_PWR_PWMCLKEN_RAT_M \
| RFC_PWR_PWMCLKEN_RFERAM_M | RFC_PWR_PWMCLKEN_RFE_M \
| RFC_PWR_PWMCLKEN_MDMRAM_M | RFC_PWR_PWMCLKEN_MDM_M)
/*---------------------------------------------------------------------------*/
#define RF_CMD0 0x0607
/*---------------------------------------------------------------------------*/
uint8_t
rf_core_is_accessible()
{
if(ti_lib_prcm_rf_ready()) {
return RF_CORE_ACCESSIBLE;
}
return RF_CORE_NOT_ACCESSIBLE;
}
/*---------------------------------------------------------------------------*/
uint_fast8_t
rf_core_send_cmd(uint32_t cmd, uint32_t *status)
{
uint32_t timeout_count = 0;
bool interrupts_disabled;
bool is_radio_op = false;
/* reset the status variables to invalid values */
last_cmd_status = (uint32_t)-1;
*status = last_cmd_status;
/*
* If cmd is 4-byte aligned, then it's either a radio OP or an immediate
* command. Clear the status field if it's a radio OP
*/
if((cmd & 0x03) == 0) {
uint32_t cmd_type;
cmd_type = ((rfc_command_t *)cmd)->commandNo & RF_CORE_COMMAND_TYPE_MASK;
if(cmd_type == RF_CORE_COMMAND_TYPE_IEEE_FG_RADIO_OP ||
cmd_type == RF_CORE_COMMAND_TYPE_RADIO_OP) {
is_radio_op = true;
((rfc_radioOp_t *)cmd)->status = RF_CORE_RADIO_OP_STATUS_IDLE;
}
}
/*
* Make sure ContikiMAC doesn't turn us off from within an interrupt while
* we are accessing RF Core registers
*/
interrupts_disabled = ti_lib_int_master_disable();
if(!rf_core_is_accessible()) {
PRINTF("rf_core_send_cmd: RF was off\n");
if(!interrupts_disabled) {
ti_lib_int_master_enable();
}
return RF_CORE_CMD_ERROR;
}
if(is_radio_op) {
uint16_t command_no = ((rfc_radioOp_t *)cmd)->commandNo;
if((command_no & RF_CORE_COMMAND_PROTOCOL_MASK) != RF_CORE_COMMAND_PROTOCOL_COMMON &&
(command_no & RF_CORE_COMMAND_TYPE_MASK) == RF_CORE_COMMAND_TYPE_RADIO_OP) {
last_radio_op = (rfc_radioOp_t *)cmd;
}
}
HWREG(RFC_DBELL_BASE + RFC_DBELL_O_CMDR) = cmd;
do {
last_cmd_status = HWREG(RFC_DBELL_BASE + RFC_DBELL_O_CMDSTA);
if(++timeout_count > 50000) {
PRINTF("rf_core_send_cmd: 0x%08lx Timeout\n", cmd);
if(!interrupts_disabled) {
ti_lib_int_master_enable();
}
*status = last_cmd_status;
return RF_CORE_CMD_ERROR;
}
} while((last_cmd_status & RF_CORE_CMDSTA_RESULT_MASK) == RF_CORE_CMDSTA_PENDING);
if(!interrupts_disabled) {
ti_lib_int_master_enable();
}
/*
* If we reach here the command is no longer pending. It is either completed
* successfully or with error
*/
*status = last_cmd_status;
return (last_cmd_status & RF_CORE_CMDSTA_RESULT_MASK) == RF_CORE_CMDSTA_DONE;
}
/*---------------------------------------------------------------------------*/
uint_fast8_t
rf_core_wait_cmd_done(void *cmd)
{
volatile rfc_radioOp_t *command = (rfc_radioOp_t *)cmd;
uint32_t timeout_cnt = 0;
/*
* 0xn4nn=DONE, 0x0400=DONE_OK while all other "DONE" values means done
* but with some kind of error (ref. "Common radio operation status codes")
*/
do {
if(++timeout_cnt > 500000) {
return RF_CORE_CMD_ERROR;
}
} while((command->status & RF_CORE_RADIO_OP_MASKED_STATUS)
!= RF_CORE_RADIO_OP_MASKED_STATUS_DONE);
last_cmd_status = command->status;
return (command->status & RF_CORE_RADIO_OP_MASKED_STATUS)
== RF_CORE_RADIO_OP_STATUS_DONE_OK;
}
/*---------------------------------------------------------------------------*/
uint32_t
rf_core_cmd_status(void)
{
return last_cmd_status;
}
/*---------------------------------------------------------------------------*/
static int
fs_powerdown(void)
{
rfc_CMD_FS_POWERDOWN_t cmd;
uint32_t cmd_status;
rf_core_init_radio_op((rfc_radioOp_t *)&cmd, sizeof(cmd), CMD_FS_POWERDOWN);
if(rf_core_send_cmd((uint32_t)&cmd, &cmd_status) != RF_CORE_CMD_OK) {
PRINTF("fs_powerdown: CMDSTA=0x%08lx\n", cmd_status);
return RF_CORE_CMD_ERROR;
}
if(rf_core_wait_cmd_done(&cmd) != RF_CORE_CMD_OK) {
PRINTF("fs_powerdown: CMDSTA=0x%08lx, status=0x%04x\n",
cmd_status, cmd.status);
return RF_CORE_CMD_ERROR;
}
return RF_CORE_CMD_OK;
}
/*---------------------------------------------------------------------------*/
int
rf_core_power_up()
{
uint32_t cmd_status;
bool interrupts_disabled = ti_lib_int_master_disable();
ti_lib_int_pend_clear(INT_RFC_CPE_0);
ti_lib_int_pend_clear(INT_RFC_CPE_1);
ti_lib_int_disable(INT_RFC_CPE_0);
ti_lib_int_disable(INT_RFC_CPE_1);
/* Enable RF Core power domain */
ti_lib_prcm_power_domain_on(PRCM_DOMAIN_RFCORE);
while(ti_lib_prcm_power_domain_status(PRCM_DOMAIN_RFCORE)
!= PRCM_DOMAIN_POWER_ON);
ti_lib_prcm_domain_enable(PRCM_DOMAIN_RFCORE);
ti_lib_prcm_load_set();
while(!ti_lib_prcm_load_get());
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = 0x0;
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIEN) = 0x0;
ti_lib_int_enable(INT_RFC_CPE_0);
ti_lib_int_enable(INT_RFC_CPE_1);
if(!interrupts_disabled) {
ti_lib_int_master_enable();
}
rf_switch_power_up();
/* Let CPE boot */
HWREG(RFC_PWR_NONBUF_BASE + RFC_PWR_O_PWMCLKEN) = RF_CORE_CLOCKS_MASK;
/* Turn on additional clocks on boot */
HWREG(RFC_DBELL_BASE + RFC_DBELL_O_RFACKIFG) = 0;
HWREG(RFC_DBELL_BASE+RFC_DBELL_O_CMDR) =
CMDR_DIR_CMD_2BYTE(RF_CMD0,
RFC_PWR_PWMCLKEN_MDMRAM | RFC_PWR_PWMCLKEN_RFERAM);
/* Send ping (to verify RFCore is ready and alive) */
if(rf_core_send_cmd(CMDR_DIR_CMD(CMD_PING), &cmd_status) != RF_CORE_CMD_OK) {
PRINTF("rf_core_power_up: CMD_PING fail, CMDSTA=0x%08lx\n", cmd_status);
return RF_CORE_CMD_ERROR;
}
return RF_CORE_CMD_OK;
}
/*---------------------------------------------------------------------------*/
uint8_t
rf_core_start_rat(void)
{
uint32_t cmd_status;
rfc_CMD_SYNC_START_RAT_t cmd_start;
/* Start radio timer (RAT) */
rf_core_init_radio_op((rfc_radioOp_t *)&cmd_start, sizeof(cmd_start), CMD_SYNC_START_RAT);
/* copy the value and send back */
cmd_start.rat0 = rat_offset;
if(rf_core_send_cmd((uint32_t)&cmd_start, &cmd_status) != RF_CORE_CMD_OK) {
PRINTF("rf_core_get_rat_rtc_offset: SYNC_START_RAT fail, CMDSTA=0x%08lx\n",
cmd_status);
return RF_CORE_CMD_ERROR;
}
/* Wait until done (?) */
if(rf_core_wait_cmd_done(&cmd_start) != RF_CORE_CMD_OK) {
PRINTF("rf_core_cmd_ok: SYNC_START_RAT wait, CMDSTA=0x%08lx, status=0x%04x\n",
cmd_status, cmd_start.status);
return RF_CORE_CMD_ERROR;
}
return RF_CORE_CMD_OK;
}
/*---------------------------------------------------------------------------*/
uint8_t
rf_core_stop_rat(void)
{
rfc_CMD_SYNC_STOP_RAT_t cmd_stop;
uint32_t cmd_status;
rf_core_init_radio_op((rfc_radioOp_t *)&cmd_stop, sizeof(cmd_stop), CMD_SYNC_STOP_RAT);
int ret = rf_core_send_cmd((uint32_t)&cmd_stop, &cmd_status);
if(ret != RF_CORE_CMD_OK) {
PRINTF("rf_core_get_rat_rtc_offset: SYNC_STOP_RAT fail, ret %d CMDSTA=0x%08lx\n",
ret, cmd_status);
return ret;
}
/* Wait until done */
ret = rf_core_wait_cmd_done(&cmd_stop);
if(ret != RF_CORE_CMD_OK) {
PRINTF("rf_core_cmd_ok: SYNC_STOP_RAT wait, CMDSTA=0x%08lx, status=0x%04x\n",
cmd_status, cmd_stop.status);
return ret;
}
if(!rat_offset_known) {
/* save the offset, but only if this is the first time */
rat_offset_known = true;
rat_offset = cmd_stop.rat0;
}
return RF_CORE_CMD_OK;
}
/*---------------------------------------------------------------------------*/
void
rf_core_power_down()
{
bool interrupts_disabled = ti_lib_int_master_disable();
ti_lib_int_disable(INT_RFC_CPE_0);
ti_lib_int_disable(INT_RFC_CPE_1);
if(rf_core_is_accessible()) {
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = 0x0;
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIEN) = 0x0;
/* need to send FS_POWERDOWN or analog components will use power */
fs_powerdown();
}
rf_core_stop_rat();
/* Shut down the RFCORE clock domain in the MCU VD */
ti_lib_prcm_domain_disable(PRCM_DOMAIN_RFCORE);
ti_lib_prcm_load_set();
while(!ti_lib_prcm_load_get());
/* Turn off RFCORE PD */
ti_lib_prcm_power_domain_off(PRCM_DOMAIN_RFCORE);
while(ti_lib_prcm_power_domain_status(PRCM_DOMAIN_RFCORE)
!= PRCM_DOMAIN_POWER_OFF);
rf_switch_power_down();
ti_lib_int_pend_clear(INT_RFC_CPE_0);
ti_lib_int_pend_clear(INT_RFC_CPE_1);
ti_lib_int_enable(INT_RFC_CPE_0);
ti_lib_int_enable(INT_RFC_CPE_1);
if(!interrupts_disabled) {
ti_lib_int_master_enable();
}
}
/*---------------------------------------------------------------------------*/
uint8_t
rf_core_set_modesel()
{
uint8_t rv = RF_CORE_CMD_ERROR;
chip_type_t chip_type = ti_lib_chipinfo_get_chip_type();
if(chip_type == CHIP_TYPE_CC2650) {
HWREG(PRCM_BASE + PRCM_O_RFCMODESEL) = PRCM_RFCMODESEL_CURR_MODE5;
rv = RF_CORE_CMD_OK;
} else if(chip_type == CHIP_TYPE_CC2630) {
HWREG(PRCM_BASE + PRCM_O_RFCMODESEL) = PRCM_RFCMODESEL_CURR_MODE2;
rv = RF_CORE_CMD_OK;
} else if(chip_type == CHIP_TYPE_CC1310) {
HWREG(PRCM_BASE + PRCM_O_RFCMODESEL) = PRCM_RFCMODESEL_CURR_MODE3;
rv = RF_CORE_CMD_OK;
} else if(chip_type == CHIP_TYPE_CC1350) {
HWREG(PRCM_BASE + PRCM_O_RFCMODESEL) = PRCM_RFCMODESEL_CURR_MODE5;
rv = RF_CORE_CMD_OK;
#if CPU_FAMILY_CC26X0R2
} else if(chip_type == CHIP_TYPE_CC2640R2) {
HWREG(PRCM_BASE + PRCM_O_RFCMODESEL) = PRCM_RFCMODESEL_CURR_MODE1;
rv = RF_CORE_CMD_OK;
#endif
}
return rv;
}
/*---------------------------------------------------------------------------*/
uint8_t
rf_core_boot()
{
if(rf_core_power_up() != RF_CORE_CMD_OK) {
PRINTF("rf_core_boot: rf_core_power_up() failed\n");
rf_core_power_down();
return RF_CORE_CMD_ERROR;
}
if(rf_core_start_rat() != RF_CORE_CMD_OK) {
PRINTF("rf_core_boot: rf_core_start_rat() failed\n");
rf_core_power_down();
return RF_CORE_CMD_ERROR;
}
return RF_CORE_CMD_OK;
}
/*---------------------------------------------------------------------------*/
uint8_t
rf_core_restart_rat(void)
{
if(rf_core_stop_rat() != RF_CORE_CMD_OK) {
PRINTF("rf_core_restart_rat: rf_core_stop_rat() failed\n");
/* Don't bail out here, still try to start it */
}
if(rf_core_start_rat() != RF_CORE_CMD_OK) {
PRINTF("rf_core_restart_rat: rf_core_start_rat() failed\n");
rf_core_power_down();
return RF_CORE_CMD_ERROR;
}
return RF_CORE_CMD_OK;
}
/*---------------------------------------------------------------------------*/
void
rf_core_setup_interrupts(void)
{
bool interrupts_disabled;
const uint32_t enabled_irqs = rf_core_poll_mode ? ENABLED_IRQS_POLL_MODE : ENABLED_IRQS;
/* We are already turned on by the caller, so this should not happen */
if(!rf_core_is_accessible()) {
PRINTF("setup_interrupts: No access\n");
return;
}
/* Disable interrupts */
interrupts_disabled = ti_lib_int_master_disable();
/* Set all interrupt channels to CPE0 channel, error to CPE1 */
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEISL) = ERROR_IRQ;
/* Acknowledge configured interrupts */
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIEN) = enabled_irqs;
/* Clear interrupt flags, active low clear(?) */
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = 0x0;
ti_lib_int_pend_clear(INT_RFC_CPE_0);
ti_lib_int_pend_clear(INT_RFC_CPE_1);
ti_lib_int_enable(INT_RFC_CPE_0);
ti_lib_int_enable(INT_RFC_CPE_1);
if(!interrupts_disabled) {
ti_lib_int_master_enable();
}
}
/*---------------------------------------------------------------------------*/
void
rf_core_cmd_done_en(bool fg)
{
uint32_t irq = 0;
const uint32_t enabled_irqs = rf_core_poll_mode ? ENABLED_IRQS_POLL_MODE : ENABLED_IRQS;
if(!rf_core_poll_mode) {
irq = fg ? IRQ_LAST_FG_COMMAND_DONE : IRQ_LAST_COMMAND_DONE;
}
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = enabled_irqs;
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIEN) = enabled_irqs | irq;
}
/*---------------------------------------------------------------------------*/
void
rf_core_cmd_done_dis(void)
{
const uint32_t enabled_irqs = rf_core_poll_mode ? ENABLED_IRQS_POLL_MODE : ENABLED_IRQS;
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIEN) = enabled_irqs;
}
/*---------------------------------------------------------------------------*/
rfc_radioOp_t *
rf_core_get_last_radio_op()
{
return last_radio_op;
}
/*---------------------------------------------------------------------------*/
void
rf_core_init_radio_op(rfc_radioOp_t *op, uint16_t len, uint16_t command)
{
memset(op, 0, len);
op->commandNo = command;
op->condition.rule = COND_NEVER;
}
/*---------------------------------------------------------------------------*/
void
rf_core_primary_mode_register(const rf_core_primary_mode_t *mode)
{
primary_mode = mode;
}
/*---------------------------------------------------------------------------*/
void
rf_core_primary_mode_abort()
{
if(primary_mode) {
if(primary_mode->abort) {
primary_mode->abort();
}
}
}
/*---------------------------------------------------------------------------*/
uint8_t
rf_core_primary_mode_restore()
{
if(primary_mode) {
if(primary_mode->restore) {
return primary_mode->restore();
}
}
return RF_CORE_CMD_ERROR;
}
/*---------------------------------------------------------------------------*/
uint8_t
rf_core_rat_init(void)
{
rat_last_value = HWREG(RFC_RAT_BASE + RATCNT);
ctimer_set(&rat_overflow_timer, RAT_OVERFLOW_TIMER_INTERVAL,
rat_overflow_check_timer_cb, NULL);
return 1;
}
/*---------------------------------------------------------------------------*/
uint8_t
rf_core_check_rat_overflow(void)
{
uint32_t rat_current_value;
uint8_t interrupts_disabled;
/* Bail out if the RF is not on */
if(primary_mode == NULL || !primary_mode->is_on()) {
return 0;
}
interrupts_disabled = ti_lib_int_master_disable();
rat_current_value = HWREG(RFC_RAT_BASE + RATCNT);
if(rat_current_value + RAT_RANGE / 4 < rat_last_value) {
/* Overflow detected */
rat_last_overflow = RTIMER_NOW();
rat_overflow_counter++;
}
rat_last_value = rat_current_value;
if(!interrupts_disabled) {
ti_lib_int_master_enable();
}
return 1;
}
/*---------------------------------------------------------------------------*/
static void
rat_overflow_check_timer_cb(void *unused)
{
uint8_t success = 0;
uint8_t was_off = 0;
if(primary_mode != NULL) {
if(!primary_mode->is_on()) {
was_off = 1;
if(NETSTACK_RADIO.on() != RF_CORE_CMD_OK) {
PRINTF("overflow: on() failed\n");
ctimer_set(&rat_overflow_timer, CLOCK_SECOND,
rat_overflow_check_timer_cb, NULL);
return;
}
}
success = rf_core_check_rat_overflow();
if(was_off) {
NETSTACK_RADIO.off();
}
}
if(success) {
/* Retry after half of the interval */
ctimer_set(&rat_overflow_timer, RAT_OVERFLOW_TIMER_INTERVAL,
rat_overflow_check_timer_cb, NULL);
} else {
/* Retry sooner */
ctimer_set(&rat_overflow_timer, CLOCK_SECOND,
rat_overflow_check_timer_cb, NULL);
}
}
/*---------------------------------------------------------------------------*/
uint32_t
rf_core_convert_rat_to_rtimer(uint32_t rat_timestamp)
{
uint64_t rat_timestamp64;
uint32_t adjusted_overflow_counter;
uint8_t was_off = 0;
if(primary_mode == NULL) {
PRINTF("rf_core_convert_rat_to_rtimer: not initialized\n");
return 0;
}
if(!primary_mode->is_on()) {
was_off = 1;
NETSTACK_RADIO.on();
}
rf_core_check_rat_overflow();
if(was_off) {
NETSTACK_RADIO.off();
}
adjusted_overflow_counter = rat_overflow_counter;
/* if the timestamp is large and the last oveflow was recently,
assume that the timestamp refers to the time before the overflow */
if(rat_timestamp > (uint32_t)(RAT_RANGE * 3 / 4)) {
if(RTIMER_CLOCK_LT(RTIMER_NOW(),
rat_last_overflow + RAT_OVERFLOW_PERIOD_SECONDS * RTIMER_SECOND / 4)) {
adjusted_overflow_counter--;
}
}
/* add the overflowed time to the timestamp */
rat_timestamp64 = rat_timestamp + RAT_RANGE * adjusted_overflow_counter;
/* correct timestamp so that it refers to the end of the SFD */
rat_timestamp64 += primary_mode->sfd_timestamp_offset;
return RADIO_TO_RTIMER(rat_timestamp64 - rat_offset);
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(rf_core_process, ev, data)
{
int len;
PROCESS_BEGIN();
while(1) {
PROCESS_YIELD_UNTIL(ev == PROCESS_EVENT_POLL);
do {
watchdog_periodic();
packetbuf_clear();
len = NETSTACK_RADIO.read(packetbuf_dataptr(), PACKETBUF_SIZE);
if(len > 0) {
packetbuf_set_datalen(len);
NETSTACK_MAC.input();
}
} while(len > 0);
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
static void
rx_nok_isr(void)
{
}
/*---------------------------------------------------------------------------*/
void
cc26xx_rf_cpe1_isr(void)
{
PRINTF("RF Error\n");
if(!rf_core_is_accessible()) {
if(rf_core_power_up() != RF_CORE_CMD_OK) {
return;
}
}
if(HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & IRQ_RX_BUF_FULL) {
PRINTF("\nRF: BUF_FULL\n\n");
/* make sure read_frame() will be called to make space in RX buffer */
process_poll(&rf_core_process);
/* Clear the IRQ_RX_BUF_FULL interrupt flag by writing zero to bit */
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = ~(IRQ_RX_BUF_FULL);
}
/* Clear INTERNAL_ERROR interrupt flag */
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = 0x7FFFFFFF;
}
/*---------------------------------------------------------------------------*/
void
cc26xx_rf_cpe0_isr(void)
{
if(!rf_core_is_accessible()) {
PRINTF("RF ISR called but RF not ready... PANIC!!\n");
if(rf_core_power_up() != RF_CORE_CMD_OK) {
PRINTF("rf_core_power_up() failed\n");
return;
}
}
ti_lib_int_master_disable();
if(HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & RX_FRAME_IRQ) {
/* Clear the RX_ENTRY_DONE interrupt flag */
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = 0xFF7FFFFF;
process_poll(&rf_core_process);
}
if(RF_CORE_DEBUG_CRC) {
if(HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) & RX_NOK_IRQ) {
/* Clear the RX_NOK interrupt flag */
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = 0xFFFDFFFF;
rx_nok_isr();
}
}
if(HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) &
(IRQ_LAST_FG_COMMAND_DONE | IRQ_LAST_COMMAND_DONE)) {
/* Clear the two TX-related interrupt flags */
HWREG(RFC_DBELL_NONBUF_BASE + RFC_DBELL_O_RFCPEIFG) = 0xFFFFFFF5;
}
ti_lib_int_master_enable();
}
/*---------------------------------------------------------------------------*/
/** @} */
|
7afb350b01146581f77f7a7f441f09bc37ac8ae5
|
3c76f1d8d548863f4a92209da9758c3f86ac5b72
|
/m-deque.h
|
f8742e712c041b947e2b40a5c852ec10b2b46fe2
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
P-p-H-d/mlib
|
57ba169f11dbaf425b6b87c24b654df1e67a5af0
|
469239adcd1c37f09e208b7c09fe7f749de84892
|
refs/heads/master
| 2023-09-04T11:07:23.155619
| 2023-08-24T21:32:47
| 2023-08-24T21:32:47
| 82,404,078
| 749
| 67
|
BSD-2-Clause
| 2023-06-13T21:46:59
| 2017-02-18T17:35:25
|
C
|
UTF-8
|
C
| false
| false
| 86,669
|
h
|
m-deque.h
|
/*
* M*LIB - DEQUE module
*
* Copyright (c) 2017-2023, Patrick Pelissier
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MSTARLIB_DEQUE_H
#define MSTARLIB_DEQUE_H
#include "m-i-list.h"
/* Define a deque of a given type and its associated functions.
USAGE: DEQUE_DEF(name, type [, oplist_of_the_type]) */
#define M_DEQUE_DEF(name, ...) \
M_DEQUE_DEF_AS(name, M_F(name,_t), M_F(name,_it_t), __VA_ARGS__)
/* Define a deque of a given type and its associated functions.
as the provided type name_t with the iterator named it_t.
USAGE: DEQUE_DEF(name, name_t, it_t, type [, oplist_of_the_type]) */
#define M_DEQUE_DEF_AS(name, name_t, it_t, ...) \
M_BEGIN_PROTECTED_CODE \
M_D3QU3_DEF_P1(M_IF_NARGS_EQ1(__VA_ARGS__) \
((name, __VA_ARGS__, M_GLOBAL_OPLIST_OR_DEF(__VA_ARGS__)(), name_t, it_t, M_F(name, _node_ct) ), \
(name, __VA_ARGS__, name_t, it_t, M_F(name, _node_ct)))) \
M_END_PROTECTED_CODE
/* Define the oplist of a deque of a type.
USAGE: DEQUE_OPLIST(name[, oplist of the type]) */
#define M_DEQUE_OPLIST(...) \
M_D3QU3_OPLIST_P1 (M_IF_NARGS_EQ1(__VA_ARGS__) \
((__VA_ARGS__, M_BASIC_OPLIST), \
(__VA_ARGS__ )))
/* Default initial size of a bucket of items */
#ifndef M_USE_DEQUE_DEFAULT_SIZE
#define M_USE_DEQUE_DEFAULT_SIZE 8
#endif
/*****************************************************************************/
/********************************* INTERNAL **********************************/
/*****************************************************************************/
/* Define the internal contract of a deque */
#define M_D3QU3_CONTRACT(d) do { \
M_ASSERT ((d) != NULL); \
M_ASSERT ((d)->default_size >= M_USE_DEQUE_DEFAULT_SIZE); \
M_ASSERT ((d)->front->node != NULL); \
M_ASSERT ((d)->front->index <= (d)->front->node->size); \
M_ASSERT ((d)->back->node != NULL); \
M_ASSERT ((d)->back->index <= (d)->back->node->size); \
M_ASSERT ((d)->front->node != (d)->back->node || \
(d)->front->index <= (d)->back->index); \
M_ASSERT ((d)->front->node != (d)->back->node || \
(d)->back->index - (d)->front->index == (d)->count); \
} while (0)
/* Deferred evaluation for the deque definition,
so that all arguments are evaluated before further expansion */
#define M_D3QU3_DEF_P1(arg) M_ID( M_D3QU3_DEF_P2 arg )
/* Validate the oplist before going further */
#define M_D3QU3_DEF_P2(name, type, oplist, deque_t, it_t, node_t) \
M_IF_OPLIST(oplist)(M_D3QU3_DEF_P3, M_D3QU3_DEF_FAILURE)(name, type, oplist, deque_t, it_t, node_t)
/* Stop processing with a compilation failure */
#define M_D3QU3_DEF_FAILURE(name, type, oplist, deque_t, it_t, node_t) \
M_STATIC_FAILURE(M_LIB_NOT_AN_OPLIST, "(DEQUE_DEF): the given argument is not a valid oplist: " #oplist)
/* Internal deque definition
- name: prefix to be used
- type: type of the elements of the deque
- oplist: oplist of the type of the elements of the container
- deque_t: alias for M_F(name, _t) [ type of the container ]
- it_t: alias for M_F(name, _it_t) [ iterator of the container ]
- node_t: alias for node_t [ node ]
*/
#define M_D3QU3_DEF_P3(name, type, oplist, deque_t, it_t, node_t) \
M_D3QU3_DEF_TYPE(name, type, oplist, deque_t, it_t, node_t) \
M_CHECK_COMPATIBLE_OPLIST(name, 1, type, oplist) \
M_D3QU3_DEF_CORE(name, type, oplist, deque_t, it_t, node_t) \
M_EMPLACE_QUEUE_DEF(name, deque_t, M_F(name, _emplace_back), oplist, M_D3QUE_EMPLACE_BACK_DEF) \
M_EMPLACE_QUEUE_DEF(name, deque_t, M_F(name, _emplace_front), oplist, M_D3QUE_EMPLACE_FRONT_DEF)
/* Define the types.
It is a linked list of buckets of the types,
each new created bucket size grows compared to the previous one
resulting in:
strict O(1) for push/pop
O(ln(n)) for random access.
No insert / delete operations are planned.
[Could be done in O(n) complexity if needed]
Define the bucket (aka node) structure.
*/
#define M_D3QU3_DEF_TYPE(name, type, oplist, deque_t, it_t, node_t) \
\
typedef struct M_F(name, _node_s) { \
ILIST_INTERFACE(M_F(name, _node_list), struct M_F(name, _node_s)); \
size_t size; \
type data[M_MIN_FLEX_ARRAY_SIZE]; \
} node_t; \
\
/* Each node is allocated with a variable size bucket (so we use \
M_GET_REALLOC for the allocation). But we want to delete the nodes \
automatically with the intrusive list used for storing the nodes: \
so we register as a DEL operator the FREE operator of the oplist. \
The interfaces are compatible. \
*/ \
/* FIXME: How can I separate public types and private implementation? */ \
ILIST_DEF(M_F(name, _node_list), node_t, (DEL(M_GET_FREE oplist)) ) \
\
/* Define an internal iterator */ \
typedef struct M_F(name, _it2_s) { \
node_t *node; \
size_t index; \
} M_F(name, _it2_ct)[1]; \
\
/* Define the deque type: \
- 'list' if the list of buckets containing the objects. \
- 'front' is a pseudo-iterator to the first \
- 'back' is a pseudo-iterator to the one after last element \
- 'default_size' is the size used for the creation of a new bucket \
- 'count' is the number of elements in the container. \
*/ \
typedef struct M_F(name, _s) { \
M_F(name, _node_list_t) list; \
M_F(name, _it2_ct) front; \
M_F(name, _it2_ct) back; \
size_t default_size; \
size_t count; \
} deque_t[1]; \
\
/* Define pointer alias */ \
typedef struct M_F(name, _s) *M_F(name, _ptr); \
typedef const struct M_F(name, _s) *M_F(name, _srcptr); \
\
/* Define the iterator object */ \
typedef struct M_F(name, _it_s) { \
node_t *node; \
size_t index; \
const struct M_F(name, _s) *deque; \
} it_t[1]; \
\
/* Define internal types for oplist */ \
typedef deque_t M_F(name, _ct); \
typedef type M_F(name, _subtype_ct); \
typedef it_t M_F(name, _it_ct); \
/* Define the core functions */
#define M_D3QU3_DEF_CORE(name, type, oplist, deque_t, it_t, node_t) \
\
/* Allocate a new node for a deque */ \
M_INLINE node_t* \
M_C3(m_d3qu3_,name,_new_node)(deque_t d) \
{ \
size_t def = d->default_size; \
/* Test for overflow of the size computation */ \
if (M_UNLIKELY_NOMEM (def > SIZE_MAX / sizeof (type) - sizeof(node_t))) { \
M_MEMORY_FULL(sizeof(node_t)+def * sizeof(type)); \
return NULL; \
} \
/* Alloc a new node with dynamic size */ \
node_t*n = (node_t*) (void*) \
M_CALL_REALLOC(oplist, char, NULL, \
sizeof(node_t) + def * sizeof(type) ); \
if (M_UNLIKELY_NOMEM (n==NULL)) { \
M_MEMORY_FULL(sizeof(node_t)+def * sizeof(type)); \
return NULL; \
} \
/* Initialize the node */ \
n->size = def; \
M_F(name, _node_list_init_field)(n); \
/* Increase the next bucket allocation */ \
/* Do not increase it too much if there are few items */ \
def = M_MIN(def, d->count); \
d->default_size = M_CALL_INC_ALLOC(oplist, def); \
/* FIXME: Check for overflow? */ \
return n; \
} \
\
M_INLINE void \
M_F(name, _init)(deque_t d) \
{ \
M_F(name, _node_list_init)(d->list); \
d->default_size = M_USE_DEQUE_DEFAULT_SIZE; \
d->count = 0; \
node_t *n = M_C3(m_d3qu3_,name,_new_node)(d); \
if (n == NULL) return; \
M_F(name, _node_list_push_back)(d->list, n); \
d->front->node = n; \
d->front->index = M_USE_DEQUE_DEFAULT_SIZE/2; \
d->back->node = n; \
d->back->index = M_USE_DEQUE_DEFAULT_SIZE/2; \
M_D3QU3_CONTRACT(d); \
} \
\
M_INLINE void \
M_F(name, _reset)(deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
node_t *min_node = NULL; \
for(node_t *n = d->front->node; \
n != NULL ; \
n = (n == d->back->node) ? NULL : \
M_F(name, _node_list_next_obj)(d->list, n) ){ \
size_t min = n == d->front->node ? d->front->index : 0; \
size_t max = n == d->back->node ? d->back->index : n->size; \
for(size_t i = min; i < max; i++) { \
M_CALL_CLEAR(oplist, n->data[i]); \
} \
min_node = (min_node == NULL || min_node->size > n->size) ? n : min_node; \
} \
M_ASSERT (min_node != NULL); \
d->front->node = min_node; \
d->front->index = min_node->size / 2; \
d->back->node = min_node; \
d->back->index = min_node->size / 2; \
d->count = 0; \
M_D3QU3_CONTRACT(d); \
} \
\
M_INLINE void \
M_F(name, _clear)(deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
M_F(name, _reset)(d); \
/* We have registered the delete operator to clear all objects */ \
M_F(name, _node_list_clear)(d->list); \
/* It is safer to clean some variables */ \
d->front->node = NULL; \
d->back->node = NULL; \
d->count = 0; \
} \
\
M_INLINE type * \
M_F(name, _push_back_raw)(deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
node_t *n = d->back->node; \
size_t index = d->back->index; \
if (M_UNLIKELY (n->size <= index)) { \
/* try to get an already allocated node */ \
n = M_F(name, _node_list_next_obj)(d->list, n); \
if (n == NULL) { \
/* No node exists, allocate a new one */ \
n = M_C3(m_d3qu3_,name,_new_node)(d); \
if (M_UNLIKELY (n == NULL)) return NULL; \
M_F(name, _node_list_push_back)(d->list, n); \
} \
d->back->node = n; \
index = 0; \
} \
type *ret = &n->data[index]; \
index++; \
d->count ++; \
d->back->index = index; \
M_D3QU3_CONTRACT(d); \
return ret; \
} \
\
/* Internal, for INIT_WITH */ \
M_INLINE type * \
M_F(name, _push_raw)(deque_t d) \
{ \
return M_F(name, _push_back_raw)(d); \
} \
\
M_INLINE void \
M_F(name, _push_back)(deque_t d, type const x) \
{ \
type *p = M_F(name, _push_back_raw)(d); \
if (M_LIKELY(p != NULL)) { \
M_CALL_INIT_SET(oplist, *p, x); \
} \
} \
\
M_IF_METHOD(INIT, oplist)( \
M_INLINE type * \
M_F(name, _push_back_new)(deque_t d) \
{ \
type *p = M_F(name, _push_back_raw)(d); \
if (M_LIKELY(p != NULL)) { \
M_CALL_INIT(oplist, *p); \
} \
return p; \
} \
, ) \
\
M_INLINE void \
M_F(name, _push_back_move)(deque_t d, type *x) \
{ \
M_ASSERT (x != NULL); \
type *p = M_F(name, _push_back_raw)(d); \
if (M_UNLIKELY(p == NULL)) \
return; \
M_DO_INIT_MOVE (oplist, *p, *x); \
} \
\
M_INLINE type* \
M_F(name, _push_front_raw)(deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
node_t *n = d->front->node; \
size_t index = d->front->index; \
index --; \
/* If overflow */ \
if (M_UNLIKELY (n->size <= index)) { \
n = M_F(name, _node_list_previous_obj)(d->list, n); \
if (n == NULL) { \
n = M_C3(m_d3qu3_,name,_new_node)(d); \
if (M_UNLIKELY (n == NULL)) return NULL; \
M_F(name, _node_list_push_front)(d->list, n); \
} \
d->front->node = n; \
index = n->size -1; \
} \
type *ret = &n->data[index]; \
d->count ++; \
d->front->index = index; \
M_D3QU3_CONTRACT(d); \
return ret; \
} \
\
M_INLINE void \
M_F(name, _push_front)(deque_t d, type const x) \
{ \
type *p = M_F(name, _push_front_raw)(d); \
if (M_LIKELY(p != NULL)) { \
M_CALL_INIT_SET(oplist, *p, x); \
} \
} \
\
M_IF_METHOD(INIT, oplist)( \
M_INLINE type * \
M_F(name, _push_front_new)(deque_t d) \
{ \
type *p = M_F(name, _push_front_raw)(d); \
if (M_LIKELY(p != NULL)) { \
M_CALL_INIT(oplist, *p); \
} \
return p; \
} \
,) \
\
M_INLINE void \
M_F(name, _push_front_move)(deque_t d, type *x) \
{ \
M_ASSERT (x != NULL); \
type *p = M_F(name, _push_front_raw)(d); \
if (M_UNLIKELY(p == NULL)) \
return; \
M_DO_INIT_MOVE (oplist, *p, *x); \
} \
\
M_INLINE void \
M_F(name, _pop_back)(type *ptr, deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT(d->count > 0); \
node_t *n = d->back->node; \
size_t index = d->back->index; \
index --; \
if (M_UNLIKELY (n->size <= index)) { \
/* If there is a next node, \
pop the back node and push it back to the front. This \
reduce the used memory if the deque is used as a FIFO queue.*/ \
node_t *next = M_F(name, _node_list_next_obj)(d->list, n); \
if (next != NULL) { \
next = M_F(name, _node_list_pop_back)(d->list); \
M_ASSERT (next != n); \
M_F(name, _node_list_push_front)(d->list, next); \
} \
n = M_F(name, _node_list_previous_obj)(d->list, n); \
M_ASSERT (n != NULL && n->size > 1); \
d->back->node = n; \
index = n->size-1; \
} \
if (ptr != NULL) \
M_IF_METHOD(MOVE, oplist) ( \
M_CALL_MOVE(oplist, *ptr, n->data[index]); else \
, \
M_CALL_SET(oplist, *ptr, n->data[index]); \
) \
M_CALL_CLEAR(oplist, n->data[index]); \
d->count --; \
d->back->index = index; \
M_D3QU3_CONTRACT(d); \
} \
\
M_IF_METHOD(INIT, oplist)( \
M_INLINE void \
M_F(name, _pop_back_move)(type *ptr, deque_t d) \
{ \
M_ASSERT(ptr != NULL); \
/* Note: Lazy implementation. Can be improved if needed */ \
M_CALL_INIT(oplist, *ptr); \
M_F(name, _pop_back)(ptr, d); \
} \
, ) \
\
M_INLINE void \
M_F(name, _pop_front)(type *ptr, deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT(d->count > 0); \
node_t *n = d->front->node; \
size_t index = d->front->index; \
if (ptr != NULL) \
M_IF_METHOD(MOVE, oplist) ( \
M_CALL_MOVE(oplist, *ptr, n->data[index]); else \
, \
M_CALL_SET(oplist, *ptr, n->data[index]); \
) \
M_CALL_CLEAR(oplist, n->data[index]); \
index++; \
if (M_UNLIKELY (n->size <= index)) { \
/* If there is a previous node, \
pop the front node and push it back to the back. This \
recycles the used memory if the deque is used as a FIFO queue.*/ \
node_t *prev = M_F(name, _node_list_previous_obj)(d->list, n); \
if (prev != NULL) { \
prev = M_F(name, _node_list_pop_front)(d->list); \
M_ASSERT (prev != n); \
M_F(name, _node_list_push_back)(d->list, prev); \
} \
/* Update front iterator to point to the next object */ \
n = M_F(name, _node_list_next_obj)(d->list, n); \
if (M_UNLIKELY(n == NULL)) { \
/* No next obj. \
It is only possible if there was only 1 element */ \
M_ASSERT(d->count == 1); \
/* Reset the deque to the midle of the current node */ \
d->back->node = d->front->node; \
index = d->front->node->size/2; \
d->back->index = d->front->node->size/2; \
} else { \
d->front->node = n; \
index = 0; \
} \
} \
d->count --; \
d->front->index = index; \
M_D3QU3_CONTRACT(d); \
} \
\
M_IF_METHOD(INIT, oplist)( \
M_INLINE void \
M_F(name, _pop_front_move)(type *ptr, deque_t d) \
{ \
M_ASSERT(ptr != NULL); \
/* Note: Lazy implementation */ \
M_CALL_INIT(oplist, *ptr); \
M_F(name, _pop_front)(ptr, d); \
} \
,) \
\
M_INLINE type * \
M_F(name, _back)(const deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT (d->count > 0); \
size_t i = d->back->index; \
node_t *n = d->back->node; \
if (M_UNLIKELY (i == 0)) { \
n = M_F(name, _node_list_previous_obj)(d->list, n); \
M_ASSERT (n != NULL); \
i = n->size; \
} \
return &n->data[i-1]; \
} \
\
M_INLINE type * \
M_F(name, _front)(const deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT (d->count > 0); \
size_t i = d->front->index; \
node_t *n = d->front->node; \
return &n->data[i]; \
} \
\
M_INLINE size_t \
M_F(name, _size)(const deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
return d->count; \
} \
\
M_INLINE size_t \
M_F(name, _capacity_back)(const deque_t v) \
{ \
M_D3QU3_CONTRACT(v); \
size_t s = 0; \
for(node_t *n = M_F(name, _node_list_back)(v->list); \
n != NULL ; \
n = (n == v->back->node) ? NULL : \
M_F(name, _node_list_previous_obj)(v->list, n) ){ \
s += (n == v->back->node ? v->back->index : n->size); \
} \
return s; \
} \
\
M_INLINE size_t \
M_F(name, _capacity_front)(const deque_t v) \
{ \
M_D3QU3_CONTRACT(v); \
size_t s = 0; \
for(node_t *n = M_F(name, _node_list_front)(v->list); \
n != NULL ; \
n = (n == v->front->node) ? NULL : \
M_F(name, _node_list_next_obj)(v->list, n) ){ \
s += n->size - (n == v->front->node ? v->front->index : 0); \
} \
return s; \
} \
\
M_INLINE size_t \
M_F(name, _capacity)(const deque_t v) \
{ \
return M_F(name, _capacity_back)(v)+M_F(name, _capacity_front)(v); \
} \
\
M_INLINE bool \
M_F(name, _empty_p)(const deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
return d->count == 0; \
} \
\
M_INLINE void \
M_F(name, _it)(it_t it, const deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT (it != NULL); \
it->node = d->front->node; \
it->index = d->front->index; \
it->deque = d; \
} \
\
M_INLINE void \
M_F(name, _it_last)(it_t it, const deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT (it != NULL); \
it->node = d->back->node; \
it->index = d->back->index - 1; \
it->deque = d; \
if (M_UNLIKELY (it->index >= it->node->size)) { \
it->node = M_F(name, _node_list_previous_obj)(d->list, it->node); \
M_ASSERT (it->node != NULL && it->node->size > 1); \
it->index = it->node->size-1; \
} \
} \
\
M_INLINE void \
M_F(name, _it_end)(it_t it, const deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT (it != NULL); \
it->node = d->back->node; \
it->index = d->back->index; \
it->deque = d; \
} \
\
M_INLINE void \
M_F(name, _it_set)(it_t it1, const it_t it2) \
{ \
M_ASSERT (it1 != NULL); \
M_ASSERT (it2 != NULL); \
it1->node = it2->node; \
it1->index = it2->index; \
it1->deque = it2->deque; \
} \
\
M_INLINE bool \
M_F(name, _end_p)(it_t it) \
{ \
M_ASSERT (it != NULL); \
return (it->node == it->deque->back->node \
&& it->index >= it->deque->back->index) \
|| (it->node == it->deque->front->node \
&& it->index < it->deque->front->index); \
} \
\
M_INLINE void \
M_F(name, _next)(it_t it) \
{ \
M_ASSERT (it != NULL); \
node_t *n = it->node; \
it->index ++; \
if (M_UNLIKELY (it->index >= n->size)) { \
n = M_F(name, _node_list_next_obj)(it->deque->list, n); \
if (M_UNLIKELY (n == NULL || it->node == it->deque->back->node)) { \
/* Point to 'end' (can't undo it) */ \
it->node = it->deque->back->node; \
it->index = it->deque->back->node->size; \
return; \
} \
it->node = n; \
it->index = 0; \
} \
} \
\
M_INLINE void \
M_F(name, _previous)(it_t it) \
{ \
M_ASSERT (it != NULL); \
node_t *n = it->node; \
it->index --; \
if (M_UNLIKELY (it->index >= n->size)) { \
n = M_F(name, _node_list_previous_obj)(it->deque->list, n); \
if (M_UNLIKELY (n == NULL || it->node == it->deque->front->node)) { \
/* Point to 'end' (can't undo it) */ \
it->node = it->deque->back->node; \
it->index = it->deque->back->node->size; \
return; \
} \
it->node = n; \
it->index = n->size - 1; \
} \
} \
\
M_INLINE bool \
M_F(name, _last_p)(it_t it) \
{ \
M_ASSERT (it != NULL); \
it_t it2; \
M_F(name, _it_set)(it2, it); \
M_F(name, _next)(it2); \
return M_F(name, _end_p)(it2); \
} \
\
M_INLINE bool \
M_F(name, _it_equal_p)(it_t it1, const it_t it2) \
{ \
M_ASSERT (it1 != NULL); \
M_ASSERT (it2 != NULL); \
return it1->deque == it2->deque \
&& it1->node == it2->node \
&& it1->index == it2->index; \
} \
\
M_INLINE type * \
M_F(name, _ref)(it_t it) \
{ \
M_ASSERT (it != NULL); \
M_ASSERT (it->index < it->node->size); \
return &it->node->data[it->index]; \
} \
\
M_INLINE type const * \
M_F(name, _cref)(it_t it) \
{ \
M_ASSERT (it != NULL); \
M_ASSERT (it->index < it->node->size); \
return M_CONST_CAST(type, &it->node->data[it->index]); \
} \
\
M_INLINE void \
M_F(name, _remove)(deque_t d, it_t it) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT (it != NULL && it->node != NULL); \
M_ASSERT (d->count >= 1); \
M_ASSERT_INDEX(it->index, it->node->size); \
\
node_t *n = it->node; \
M_CALL_CLEAR(oplist, n->data[it->index]); \
if (n == d->back->node) { \
/* back index points to the element after the end */ \
M_ASSERT (d->back->index != 0); \
M_ASSERT (it->index < d->back->index); \
/* We cannot have a node deletion in this case */ \
memmove(&n->data[it->index], &n->data[it->index+1], \
sizeof(type) * (d->back->index - it->index - 1)); \
d->back->index --; \
/* The iterator points to the next element */ \
} else if (n == d->front->node) { \
/* front index points to the first element */ \
if (M_UNLIKELY (d->front->index == n->size -1)) { \
/* Node 'smart' deletion (single element) */ \
/* Update front iterator to point to the next object */ \
n = M_F(name, _node_list_next_obj)(d->list, n); \
/* We must have a next element, as we have a different back node \
than the front node. */ \
M_ASSERT (n != NULL); \
d->front->node = n; \
d->front->index = 0; \
/* The iterator references this element */ \
it->node = n; \
it->index = 0; \
} else { \
memmove(&n->data[d->front->index+1], &n->data[d->front->index], \
sizeof(type) * (it->index - d->front->index)); \
d->front->index ++; \
/* The iterator shall reference the next element */ \
M_F(name, _next)(it); \
} \
} else { \
/* Nether front or end node */ \
if (M_UNLIKELY(n->size == 1)) { \
/* The iterator shall reference the next element */ \
M_F(name, _next)(it); \
/* Node deletion */ \
M_ASSERT(d->count > 1); \
M_F(name, _node_list_unlink)(n); \
M_CALL_FREE(oplist, n); \
} else { \
memmove(&n->data[it->index], &n->data[it->index+1], \
sizeof(type) * (it->node->size - it->index - 1)); \
/* We lose capacity of the node... */ \
n->size --; \
/* The iterator points to the next element \
except if it was the last one*/ \
if (M_UNLIKELY(it->index >= n->size)) M_F(name, _next)(it); \
} \
} \
d->count--; \
M_D3QU3_CONTRACT(d); \
} \
\
M_INLINE void \
M_F(name, _init_set)(deque_t d, const deque_t src) \
{ \
M_D3QU3_CONTRACT(src); \
M_ASSERT (d != NULL); \
M_F(name, _node_list_init)(d->list); \
d->default_size = M_USE_DEQUE_DEFAULT_SIZE + src->count; \
d->count = src->count; \
node_t *n = M_C3(m_d3qu3_,name,_new_node)(d); \
if (n == NULL) return; \
d->default_size /= 2; \
M_F(name, _node_list_push_back)(d->list, n); \
d->front->node = n; \
d->front->index = M_USE_DEQUE_DEFAULT_SIZE/2; \
d->back->node = n; \
d->back->index = M_USE_DEQUE_DEFAULT_SIZE/2 + src->count; \
it_t it; \
size_t i = M_USE_DEQUE_DEFAULT_SIZE/2; \
for(M_F(name, _it)(it, src); !M_F(name, _end_p)(it) ; M_F(name, _next)(it)) { \
type const *obj = M_F(name, _cref)(it); \
M_CALL_INIT_SET(oplist, n->data[i], *obj); \
i++; \
M_ASSERT (i <= d->back->index); \
} \
M_D3QU3_CONTRACT(d); \
} \
\
M_INLINE void \
M_F(name, _set)(deque_t d, deque_t const src) \
{ \
if (M_UNLIKELY (src == d)) \
return; \
/* TODO: Reuse memory of d! */ \
M_F(name, _clear)(d); \
M_F(name, _init_set)(d, src); \
} \
\
M_INLINE void \
M_F(name, _init_move)(deque_t d, deque_t src) \
{ \
M_D3QU3_CONTRACT(src); \
M_ASSERT (d!= NULL); \
M_F(name,_node_list_init_move)(d->list, src->list); \
d->front->node = src->front->node; \
d->front->index = src->front->index; \
d->back->node = src->back->node; \
d->back->index = src->back->index; \
d->default_size = src->default_size; \
d->count = src->count; \
memset(src, 0, sizeof(deque_t)); \
M_D3QU3_CONTRACT(d); \
} \
\
M_INLINE void \
M_F(name, _move)(deque_t d, deque_t src) \
{ \
M_D3QU3_CONTRACT(d); \
M_D3QU3_CONTRACT(src); \
M_F(name, _clear)(d); \
M_F(name, _init_move)(d, src); \
M_D3QU3_CONTRACT(d); \
} \
\
M_INLINE void \
M_F(name, _swap)(deque_t d, deque_t e) \
{ \
M_D3QU3_CONTRACT(d); \
M_D3QU3_CONTRACT(e); \
M_F(name, _node_list_swap) (d->list, e->list); \
M_SWAP(node_t *, d->front->node, e->front->node); \
M_SWAP(node_t *, d->back->node, e->back->node); \
M_SWAP(size_t, d->front->index, e->front->index); \
M_SWAP(size_t, d->back->index, e->back->index); \
M_SWAP(size_t, d->default_size, e->default_size); \
M_SWAP(size_t, d->count, e->count); \
M_D3QU3_CONTRACT(d); \
M_D3QU3_CONTRACT(e); \
} \
\
M_INLINE type* \
M_F(name, _get)(deque_t d, size_t key) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT_INDEX (key, d->count); \
const size_t index0 = d->front->index; \
size_t count = 0; \
/* This loop is in log(N) since the size increase exponentially.*/ \
for(node_t *n = d->front->node; true ; \
n = (n == d->back->node) ? NULL : \
M_F(name, _node_list_next_obj)(d->list, n) ){ \
M_ASSERT(n != NULL); \
if (index0 + key < count + n->size) { \
return &n->data[index0 + key - count]; \
} \
count += n->size; \
} \
} \
\
M_INLINE type const * \
M_F(name, _cget)(deque_t d, size_t key) \
{ \
return M_CONST_CAST(type, M_F(name, _get)(d, key)); \
} \
\
M_INLINE void \
M_F(name, _set_at)(deque_t d, size_t key, type const x) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT_INDEX (key, d->count); \
type *p = M_F(name, _get)(d, key); \
M_CALL_SET(oplist, *p, x); \
M_D3QU3_CONTRACT(d); \
} \
\
M_IF_METHOD(EQUAL, oplist)( \
M_INLINE bool \
M_F(name, _equal_p)(const deque_t d1, const deque_t d2) \
{ \
M_D3QU3_CONTRACT(d1); \
M_D3QU3_CONTRACT(d2); \
if (d1->count != d2->count) \
return false; \
it_t it1; \
it_t it2; \
for(M_F(name, _it)(it1, d1), M_F(name,_it)(it2, d2); \
!M_F(name, _end_p)(it1) ; \
M_F(name, _next)(it1), M_F(name, _next)(it2)) { \
type const *obj1 = M_F(name, _cref)(it1); \
type const *obj2 = M_F(name, _cref)(it2); \
if (M_CALL_EQUAL(oplist, *obj1, *obj2) == false) \
return false; \
} \
M_ASSERT (M_F(name, _end_p)(it2)); \
return true; \
} \
, /* NO EQUAL */) \
\
M_IF_METHOD(HASH, oplist)( \
M_INLINE size_t \
M_F(name, _hash)(const deque_t d) \
{ \
M_D3QU3_CONTRACT(d); \
M_HASH_DECL(hash); \
it_t it; \
for(M_F(name, _it)(it, d); !M_F(name, _end_p)(it); M_F(name, _next)(it)) { \
type const *obj = M_F(name, _cref)(it); \
M_HASH_UP (hash, M_CALL_HASH(oplist, *obj)); \
} \
return M_HASH_FINAL(hash); \
} \
, /* NO HASH */) \
\
M_IF_METHOD(SWAP, oplist)( \
M_INLINE void \
M_F(name, _swap_at)(deque_t d, size_t i, size_t j) \
{ \
M_D3QU3_CONTRACT(d); \
M_ASSERT_INDEX (i, d->count); \
M_ASSERT_INDEX (j, d->count); \
type *obj1 = M_F(name, _get)(d, i); \
type *obj2 = M_F(name, _get)(d, j); \
M_CALL_SWAP(oplist, *obj1, *obj2); \
M_D3QU3_CONTRACT(d); \
} \
, /* NO SWAP */) \
\
M_IF_METHOD(GET_STR, oplist)( \
M_INLINE void \
M_F(name, _get_str)(m_string_t str, deque_t const deque, bool append) \
{ \
M_D3QU3_CONTRACT(deque); \
(append ? m_string_cat_cstr : m_string_set_cstr) (str, "["); \
it_t it; \
for (M_F(name, _it)(it, deque) ; \
!M_F(name, _end_p)(it); \
M_F(name, _next)(it)){ \
type const *item = M_F(name, _cref)(it); \
M_CALL_GET_STR(oplist, str, *item, true); \
if (!M_F(name, _last_p)(it)) \
m_string_push_back (str, M_GET_SEPARATOR oplist); \
} \
m_string_push_back (str, ']'); \
} \
, /* no GET_STR */ ) \
\
M_IF_METHOD(OUT_STR, oplist)( \
M_INLINE void \
M_F(name, _out_str)(FILE *file, const deque_t deque) \
{ \
M_D3QU3_CONTRACT(deque); \
M_ASSERT (file != NULL); \
fputc ('[', file); \
it_t it; \
for (M_F(name, _it)(it, deque) ; \
!M_F(name, _end_p)(it); \
M_F(name, _next)(it)) { \
type const *item = M_F(name, _cref)(it); \
M_CALL_OUT_STR(oplist, file, *item); \
if (!M_F(name, _last_p)(it)) \
fputc (M_GET_SEPARATOR oplist, file); \
} \
fputc (']', file); \
} \
, /* no OUT_STR */ ) \
\
M_IF_METHOD2(PARSE_STR, INIT, oplist)( \
M_INLINE bool \
M_F(name, _parse_str)(deque_t deque, const char str[], const char **endp) \
{ \
M_D3QU3_CONTRACT(deque); \
M_ASSERT (str != NULL); \
M_F(name,_reset)(deque); \
bool success = false; \
int c = *str++; \
if (M_UNLIKELY (c != '[')) goto exit; \
c = *str++; \
if (M_UNLIKELY (c == ']')) {success = true; goto exit;} \
if (M_UNLIKELY (c == 0)) goto exit; \
str--; \
type item; \
M_CALL_INIT(oplist, item); \
do { \
bool b = M_CALL_PARSE_STR(oplist, item, str, &str); \
do { c = *str++; } while (isspace(c)); \
if (b == false || c == 0) { goto exit_clear; } \
M_F(name, _push_back)(deque, item); \
} while (c == M_GET_SEPARATOR oplist); \
M_D3QU3_CONTRACT(deque); \
success = (c == ']'); \
exit_clear: \
M_CALL_CLEAR(oplist, item); \
exit: \
if (endp) *endp = str; \
return success; \
} \
, /* no PARSE_STR */ ) \
\
M_IF_METHOD2(IN_STR, INIT, oplist)( \
M_INLINE bool \
M_F(name, _in_str)(deque_t deque, FILE *file) \
{ \
M_D3QU3_CONTRACT(deque); \
M_ASSERT (file != NULL); \
M_F(name,_reset)(deque); \
int c = fgetc(file); \
if (M_UNLIKELY (c != '[')) return false; \
c = fgetc(file); \
if (M_UNLIKELY (c == ']')) return true; \
if (M_UNLIKELY (c == EOF)) return false; \
ungetc(c, file); \
type item; \
M_CALL_INIT(oplist, item); \
do { \
bool b = M_CALL_IN_STR(oplist, item, file); \
do { c = fgetc(file); } while (isspace(c)); \
if (b == false || c == EOF) { break; } \
M_F(name, _push_back)(deque, item); \
} while (c == M_GET_SEPARATOR oplist); \
M_CALL_CLEAR(oplist, item); \
M_D3QU3_CONTRACT(deque); \
return c == ']'; \
} \
, /* no IN_STR */ ) \
\
M_IF_METHOD(OUT_SERIAL, oplist)( \
M_INLINE m_serial_return_code_t \
M_F(name, _out_serial)(m_serial_write_t f, const deque_t deque) \
{ \
M_D3QU3_CONTRACT(deque); \
M_ASSERT (f != NULL && f->m_interface != NULL); \
m_serial_local_t local; \
m_serial_return_code_t ret; \
bool first_done = false; \
ret = f->m_interface->write_array_start(local, f, deque->count); \
M_F(name, _it_ct) it; \
for (M_F(name, _it)(it, deque) ; \
!M_F(name, _end_p)(it); \
M_F(name, _next)(it)){ \
type const *item = M_F(name, _cref)(it); \
if (first_done) \
ret |= f->m_interface->write_array_next(local, f); \
ret |= M_CALL_OUT_SERIAL(oplist, f, *item); \
first_done = true; \
} \
ret |= f->m_interface->write_array_end(local, f); \
return ret & M_SERIAL_FAIL; \
} \
, /* no OUT_SERIAL */ ) \
\
M_IF_METHOD2(IN_SERIAL, INIT, oplist)( \
M_INLINE m_serial_return_code_t \
M_F(name, _in_serial)(deque_t deque, m_serial_read_t f) \
{ \
M_D3QU3_CONTRACT(deque); \
M_ASSERT (f != NULL && f->m_interface != NULL); \
m_serial_local_t local; \
m_serial_return_code_t ret; \
size_t estimated_size = 0; \
M_F(name,_reset)(deque); \
ret = f->m_interface->read_array_start(local, f, &estimated_size); \
if (M_UNLIKELY (ret != M_SERIAL_OK_CONTINUE)) return ret; \
type item; \
M_CALL_INIT(oplist, item); \
do { \
ret = M_CALL_IN_SERIAL(oplist, item, f); \
if (ret != M_SERIAL_OK_DONE) { break; } \
M_F(name, _push_back)(deque, item); \
ret = f->m_interface->read_array_next(local, f); \
} while (ret == M_SERIAL_OK_CONTINUE); \
M_CALL_CLEAR(oplist, item); \
return ret; \
} \
, /* no IN_SERIAL & INIT */ ) \
/* Definition of the emplace_back function for deque */
#define M_D3QUE_EMPLACE_BACK_DEF(name, name_t, function_name, oplist, init_func, exp_emplace_type) \
M_INLINE void \
function_name(name_t v \
M_EMPLACE_LIST_TYPE_VAR(a, exp_emplace_type) ) \
{ \
M_F(name, _subtype_ct) *data = M_F(name, _push_back_raw)(v); \
if (M_UNLIKELY (data == NULL) ) \
return; \
M_EMPLACE_CALL_FUNC(a, init_func, oplist, *data, exp_emplace_type); \
}
/* Definition of the emplace_front function for deque */
#define M_D3QUE_EMPLACE_FRONT_DEF(name, name_t, function_name, oplist, init_func, exp_emplace_type) \
M_INLINE void \
function_name(name_t v \
M_EMPLACE_LIST_TYPE_VAR(a, exp_emplace_type) ) \
{ \
M_F(name, _subtype_ct) *data = M_F(name, _push_front_raw)(v); \
if (M_UNLIKELY (data == NULL) ) \
return; \
M_EMPLACE_CALL_FUNC(a, init_func, oplist, *data, exp_emplace_type); \
}
/********************************* INTERNAL **********************************/
/* Deferred evaluation for the oplist definition,
so that all arguments are evaluated before further expansion */
#define M_D3QU3_OPLIST_P1(arg) M_D3QU3_OPLIST_P2 arg
/* Validation of the given oplist */
#define M_D3QU3_OPLIST_P2(name, oplist) \
M_IF_OPLIST(oplist)(M_D3QU3_OPLIST_P3, M_D3QU3_OPLIST_FAILURE)(name, oplist)
/* Prepare a clean compilation failure */
#define M_D3QU3_OPLIST_FAILURE(name, oplist) \
((M_LIB_ERROR(ARGUMENT_OF_DEQUE_OPLIST_IS_NOT_AN_OPLIST, name, oplist)))
/* OPLIST definition of a deque */
#define M_D3QU3_OPLIST_P3(name, oplist) \
(INIT(M_F(name, _init)) \
,INIT_SET(M_F(name, _init_set)) \
,INIT_WITH(API_1(M_INIT_WITH_VAI)) \
,SET(M_F(name, _set)) \
,CLEAR(M_F(name, _clear)) \
,INIT_MOVE(M_F(name, _init_move)) \
,MOVE(M_F(name, _move)) \
,SWAP(M_F(name, _swap)) \
,NAME(name) \
,TYPE(M_F(name,_ct)) \
,SUBTYPE(M_F(name, _subtype_ct)) \
,EMPTY_P(M_F(name,_empty_p)) \
,IT_TYPE(M_F(name,_it_ct)) \
,IT_FIRST(M_F(name,_it)) \
,IT_LAST(M_F(name,_it_last)) \
,IT_END(M_F(name,_it_end)) \
,IT_SET(M_F(name,_it_set)) \
,IT_END_P(M_F(name,_end_p)) \
,IT_LAST_P(M_F(name,_last_p)) \
,IT_EQUAL_P(M_F(name,_it_equal_p)) \
,IT_NEXT(M_F(name,_next)) \
,IT_PREVIOUS(M_F(name,_previous)) \
,IT_REF(M_F(name,_ref)) \
,IT_CREF(M_F(name,_cref)) \
,IT_REMOVE(M_F(name,_remove)) \
,RESET(M_F(name,_reset)) \
,GET_SIZE(M_F(name, _size)) \
,PUSH(M_F(name,_push_back)) \
,POP(M_F(name,_pop_back)) \
,OPLIST(oplist) \
,M_IF_METHOD(GET_STR, oplist)(GET_STR(M_F(name, _get_str)),) \
,M_IF_METHOD(PARSE_STR, oplist)(PARSE_STR(M_F(name, _parse_str)),) \
,M_IF_METHOD(OUT_STR, oplist)(OUT_STR(M_F(name, _out_str)),) \
,M_IF_METHOD(IN_STR, oplist)(IN_STR(M_F(name, _in_str)),) \
,M_IF_METHOD(OUT_SERIAL, oplist)(OUT_SERIAL(M_F(name, _out_serial)),) \
,M_IF_METHOD(IN_SERIAL, oplist)(IN_SERIAL(M_F(name, _in_serial)),) \
,M_IF_METHOD(EQUAL, oplist)(EQUAL(M_F(name, _equal_p)),) \
,M_IF_METHOD(HASH, oplist)(HASH(M_F(name, _hash)),) \
)
/********************************* INTERNAL **********************************/
#if M_USE_SMALL_NAME
#define DEQUE_DEF M_DEQUE_DEF
#define DEQUE_DEF_AS M_DEQUE_DEF_AS
#define DEQUE_OPLIST M_DEQUE_OPLIST
#endif
#endif
|
7a4f5dd4e56a91f6e6e210cb5df84a4651be3655
|
1f399edf85d995443d01f66d77eca0723886d0ff
|
/hypervisor/include/arch/x86/asm/guest/vcat.h
|
22c53c1cbf031350b4a651196825825a952463cf
|
[
"BSD-3-Clause"
] |
permissive
|
projectacrn/acrn-hypervisor
|
f9c5864d54929a5d2fa36b5e78c08f19b46b8f98
|
390740aa1b1e9d62c51f8e3afa0c29e07e43fa23
|
refs/heads/master
| 2023-08-18T05:07:01.310327
| 2023-08-11T07:49:36
| 2023-08-16T13:20:27
| 123,983,554
| 1,059
| 686
|
BSD-3-Clause
| 2023-09-14T09:51:10
| 2018-03-05T21:52:25
|
C
|
UTF-8
|
C
| false
| false
| 815
|
h
|
vcat.h
|
/*
* Copyright (C) 2021-2022 Intel Corporation.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef VCAT_H_
#define VCAT_H_
#include <asm/guest/vm.h>
bool is_l2_vcat_configured(const struct acrn_vm *vm);
bool is_l3_vcat_configured(const struct acrn_vm *vm);
uint16_t vcat_get_vcbm_len(const struct acrn_vm *vm, int res);
void init_vcat_msrs(struct acrn_vcpu *vcpu);
uint16_t vcat_get_num_vclosids(const struct acrn_vm *vm);
uint64_t vcat_pcbm_to_vcbm(const struct acrn_vm *vm, uint64_t pcbm, int res);
int32_t read_vcbm(const struct acrn_vcpu *vcpu, uint32_t vmsr, uint64_t *rval);
int32_t write_vcbm(struct acrn_vcpu *vcpu, uint32_t vmsr, uint64_t val);
int32_t read_vclosid(const struct acrn_vcpu *vcpu, uint64_t *rval);
int32_t write_vclosid(struct acrn_vcpu *vcpu, uint64_t val);
#endif /* VCAT_H_ */
|
4555a2c323bc7590ea9cabbb59c596e5bd5a9eec
|
93be5d831adfdc50cb4275e54e1741d0d1a2ea06
|
/lib/ld/elf.c
|
1d13afccf5f29d1413c89238c489ea435bb1de85
|
[
"ISC"
] |
permissive
|
reswitched/libtransistor
|
9b22a06b9244aac469e0c08f540196587e88ce2d
|
e356d4b57259e24fed725af08d1bd21902475e14
|
refs/heads/development
| 2021-05-16T03:26:54.866613
| 2019-08-25T02:51:30
| 2019-09-28T22:27:54
| 105,481,619
| 225
| 65
|
ISC
| 2019-06-22T01:01:21
| 2017-10-01T23:18:26
|
C
|
UTF-8
|
C
| false
| false
| 986
|
c
|
elf.c
|
#include<libtransistor/ld/elf.h>
#include<libtransistor/err.h>
#include<stdint.h>
result_t elf_dynamic_find_value(Elf64_Dyn *dynamic, int64_t tag, uint64_t *value) {
uint64_t *found = NULL;
*value = 0;
for(; dynamic->d_tag != DT_NULL; dynamic++) {
if(dynamic->d_tag == tag) {
if(found != NULL) {
return LIBTRANSISTOR_ERR_TRNLD_DUPLICATE_DT_ENTRY;
} else {
found = &dynamic->d_val;
}
}
}
if(found == NULL) {
return LIBTRANSISTOR_ERR_TRNLD_MISSING_DT_ENTRY;
}
*value = *found;
return RESULT_OK;
}
result_t elf_dynamic_find_offset(Elf64_Dyn *dynamic, int64_t tag, void **value, void *aslr_base) {
uint64_t intermediate;
result_t r = elf_dynamic_find_value(dynamic, tag, &intermediate);
*value = aslr_base + intermediate;
return r;
}
uint64_t elf_hash_string(const char *name) {
uint64_t h = 0;
uint64_t g;
while(*name) {
h = (h << 4) + *(const uint8_t*) name++;
if((g = (h & 0xf0000000)) != 0) {
h ^= g >> 24;
}
h&= ~g;
}
return h;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.