added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T20:50:32.345670+00:00 | 2016-12-08T10:59:35 | 5fafae4266043dccaa26caa42d67da05bb45c385 | {
"blob_id": "5fafae4266043dccaa26caa42d67da05bb45c385",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-08T10:59:35",
"content_id": "87eb93bb257b91d8cea84d04bedb7941ee069b95",
"detected_licenses": [
"MIT"
],
"directory_id": "df94ad4ecbf3f7fd9f4459ae94e7034081ea77eb",
"extension": "c",
"filename": "hnjalloc.c",
"fork_events_count": 0,
"gha_created_at": "2017-11-08T18:43:58",
"gha_event_created_at": "2017-11-08T18:43:58",
"gha_language": null,
"gha_license_id": null,
"github_id": 110016147,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2007,
"license": "MIT",
"license_type": "permissive",
"path": "/PxCore/PxCore/hnjalloc.c",
"provenance": "stackv2-0110.json.gz:216683",
"repo_name": "SeppPenner/PixLib-OpenSource",
"revision_date": "2016-12-08T10:59:35",
"revision_id": "77335117a48a2ca746dde1d8d3e2dc1599beb785",
"snapshot_id": "20a6b046359ceee20d94ddf70426896f772b4e8e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/SeppPenner/PixLib-OpenSource/77335117a48a2ca746dde1d8d3e2dc1599beb785/PxCore/PxCore/hnjalloc.c",
"visit_date": "2021-06-09T15:50:20.506545"
} | stackv2 | /* LibHnj is dual licensed under LGPL and MPL. Boilerplate for both
* licenses follows.
*/
/* LibHnj - a library for high quality hyphenation and justification
* Copyright (C) 1998 Raph Levien, (C) 2001 ALTLinux, Moscow
*
* 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, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307 USA.
*/
/*
* The contents of this file are subject to the Mozilla Public License
* Version 1.0 (the "MPL"); you may not use this file except in
* compliance with the MPL. You may obtain a copy of the MPL at
* http://www.mozilla.org/MPL/
*
* Software distributed under the MPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the MPL
* for the specific language governing rights and limitations under the
* MPL.
*
*/
/* wrappers for malloc */
#include <stdlib.h>
#include <stdio.h>
void * hnj_malloc(int size);
void * hnj_realloc(void *p, int size);
void hnj_free(void *p);
void * hnj_malloc(int size) {
void *p;
p = malloc(size);
if (p == NULL)
{
fprintf(stderr, "can't allocate %d bytes\n", size);
exit(1);
}
return p;
}
void *hnj_realloc(void *p, int size) {
p = realloc (p, size);
if (p == NULL)
{
fprintf (stderr, "can't allocate %d bytes\n", size);
exit (1);
}
return p;
}
void hnj_free(void *p) {
free (p);
}
| 2.03125 | 2 |
2024-11-18T20:50:32.398474+00:00 | 2019-08-24T19:59:27 | 86afb7017a7411100bce9c36d5c15ef7b6f3992c | {
"blob_id": "86afb7017a7411100bce9c36d5c15ef7b6f3992c",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-24T19:59:27",
"content_id": "479b0880f831b41e7c19585e48ce6b6e5624dc94",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "4846596e5502fc134f743b88ade98b2937318627",
"extension": "h",
"filename": "dsec_ta_manage_object.h",
"fork_events_count": 0,
"gha_created_at": "2019-08-24T19:52:33",
"gha_event_created_at": "2019-08-24T19:52:34",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 204205518,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3129,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/trusted_application/src/dsec_ta_manage_object.h",
"provenance": "stackv2-0110.json.gz:216813",
"repo_name": "aim2nasa/libddssec",
"revision_date": "2019-08-24T19:59:27",
"revision_id": "971a3bb0cdc59093400a3ecb155412bfc524d361",
"snapshot_id": "92281e31a3fbda5a2faf9ad8d3e3e8ad3c88ba66",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aim2nasa/libddssec/971a3bb0cdc59093400a3ecb155412bfc524d361/trusted_application/src/dsec_ta_manage_object.h",
"visit_date": "2020-07-10T07:31:59.469282"
} | stackv2 |
/*
* DDS Security library
* Copyright (c) 2019, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef DSEC_TA_MANAGE_OBJECT_H
#define DSEC_TA_MANAGE_OBJECT_H
#include <tee_internal_api.h>
#include <stdint.h>
/*!
* \addtogroup GroupTA Trusted Application
*
* \brief Object management internal API.
* \{
*/
/*! Maximum number of bytes for temporary internal storage */
#define DSEC_OBJECT_DATA_MAX_SIZE ((size_t)(2<<16))
/*! Maximum length of a builtin object's name, including \0 */
#define DSEC_MAX_NAME_LENGTH (256U)
/*!
* \brief Unload the object memory.
*
* \details Uses memset to set all of the object memory to zero and resets the
* metadata.
*/
void dsec_ta_unload_object_memory(void);
/*!
* \brief Load a builtin object to the object memory.
*
* \details Find a builtin object by name and copy it to a temporary buffer.
* If an object has been loaded already, it must be unloaded by clearing
* the object memory.
*
* \param[out] buffer Pointer which is set to point to a pointer to a buffer of
* the loaded data.
*
* \param[in] size Pointer which is set to point to the size of the loaded
* data.
*
* \retval ::TEE_SUCCESS Success.
* \retval ::TEE_ERROR_ITEM_NOT_FOUND Failed to find a matching object by name.
* \retval ::TEE_ERROR_OUT_OF_MEMORY There is already an object loaded.
* \retval ::TEE_ERROR_BAD_PARAMETERS The pointer to object to be loaded is
* NULL.
*/
TEE_Result dsec_ta_load_builtin(void** buffer,
size_t* size,
const char name[DSEC_MAX_NAME_LENGTH]);
#if DSEC_TEST
/*!
* \brief Invoke dsec_ta_load_builtin from the tests.
*
* \details Used for testing loading from the normal world.
*
* \param parameters_type The types of each of the parameters in parameters[1]
* as specified by the Global Platform TEE internal core API specification.
*
* \param[in] parameters[0].memref.buffer Pointer to a buffer containing the
* object ID name of the object.
*
* \param[in] parameters[0].memref.size The length of the object ID name of the
* object.
*
* \retval ::TEE_SUCCESS Success.
* \retval ::TEE_ERROR_ITEM_NOT_FOUND Failed to find a matching object by name.
* \retval ::TEE_ERROR_OUT_OF_MEMORY There is already an object loaded.
* \retval ::TEE_ERROR_BAD_PARAMETERS The pointer to object to be loaded is
* NULL.
* \retval ::TEE_ERROR_BAD_PARAMETERS Wrong TEE_PARAM_TYPES (Testing error).
* \retval ::TEE_ERROR_OUT_OF_MEMORY Couldn't copy name (Testing error).
*/
TEE_Result dsec_ta_test_load_object_builtin(uint32_t parameters_type,
const TEE_Param parameters[1]);
/*!
* \brief Invoke dsec_ta_unload_object_memory from the tests.
*
* \details Used for testing unloading from the normal world.
*
* \retval ::TEE_SUCCESS Success.
* \retval ::TEE_ERROR_BAD_STATE The object_memory data or metadata was not
* reset.
*/
TEE_Result dsec_ta_test_unload_object(void);
#endif /* DSEC_TEST */
/*!
* \}
*/
#endif /* DSEC_TA_MANAGE_OBJECT_H */
| 2.265625 | 2 |
2024-11-18T20:50:32.698737+00:00 | 2020-08-05T13:41:46 | 1618e5d59c78524ef31683d93ef4c5f2f19701b5 | {
"blob_id": "1618e5d59c78524ef31683d93ef4c5f2f19701b5",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-05T13:41:46",
"content_id": "3aabe440e0e048f46ad9d34d246a04c5a513f5fe",
"detected_licenses": [
"Unlicense"
],
"directory_id": "7cf0b8bf34567f798bcf087acfd00155120ac3e1",
"extension": "c",
"filename": "ph_link.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 285299169,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9374,
"license": "Unlicense",
"license_type": "permissive",
"path": "/ph_link.c",
"provenance": "stackv2-0110.json.gz:216943",
"repo_name": "elektronika-ba/protohole_link",
"revision_date": "2020-08-05T13:41:46",
"revision_id": "60f5861b61e2a9b5d3ad984d5add50950b86261e",
"snapshot_id": "196a744b61ab3db932835c9eb90e09d406b37156",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/elektronika-ba/protohole_link/60f5861b61e2a9b5d3ad984d5add50950b86261e/ph_link.c",
"visit_date": "2022-11-27T03:56:48.385511"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include "ph_link.h"
void PH_LINK_init_sequences_ctx(struct PH_LINK_ctx* ctx, uint32_t tx_sequence, uint32_t rx_sequence) {
ctx->tx_sequence = tx_sequence;
ctx->rx_sequence = rx_sequence;
ctx->rx_sequence_big_window_active = 0;
ctx->rx_sequence_big_window_value = 0;
ctx->rx_sequence_big_window_counter = 0;
}
void PH_LINK_init_buffer_ctx(struct PH_LINK_ctx* ctx, uint8_t* buffer, uint32_t buffer_size) {
ctx->buffer = buffer;
ctx->buffer_size = buffer_size;
}
void PH_LINK_init_callbacks_ctx(struct PH_LINK_ctx* ctx, void(*aes_cipher_callback)(uint8_t*, uint32_t), void(*aes_decipher_callback)(uint8_t*, uint32_t), void(*cmac_generate_callback)(uint8_t*, uint32_t, uint8_t*), void (*on_receive_callback)(uint8_t, struct PH_LINK_message*), void (*on_send_callback)(uint8_t*, uint32_t)) {
ctx->aes_cipher_callback = aes_cipher_callback;
ctx->aes_decipher_callback = aes_decipher_callback;
ctx->cmac_generate_callback = cmac_generate_callback;
ctx->on_receive_callback = on_receive_callback;
ctx->on_send_callback = on_send_callback;
}
void PH_LINK_init_ctx(struct PH_LINK_ctx* ctx, uint32_t tx_sequence, uint32_t rx_sequence, void(*aes_cipher_callback)(uint8_t*, uint32_t), void(*aes_decipher_callback)(uint8_t*, uint32_t), void(*cmac_generate_callback)(uint8_t*, uint32_t, uint8_t*), void (*on_receive_callback)(uint8_t, struct PH_LINK_message*), void (*on_send_callback)(uint8_t*, uint32_t)) {
PH_LINK_init_callbacks_ctx(ctx, aes_cipher_callback, aes_decipher_callback, cmac_generate_callback, on_receive_callback, on_send_callback);
PH_LINK_init_sequences_ctx(ctx, tx_sequence, rx_sequence);
}
/* Decodes the payload from ctx.buffer into PH_LINK_message and calls the on_receive_callback if defined */
uint8_t PH_LINK_decode(struct PH_LINK_ctx* ctx, uint32_t length, struct PH_LINK_message* msg) {
return PH_LINK_receive(ctx, ctx->buffer, length, msg);
}
/* Decodes the payload from provided buffer into PH_LINK_message and calls the on_receive_callback if defined */
uint8_t PH_LINK_receive(struct PH_LINK_ctx* ctx, uint8_t* buffer, uint32_t length, struct PH_LINK_message* msg) {
if (length > ctx->buffer_size) return PH_LINK_RX_NO_MEMORY;
// structure: encrypted{ [RANDOM] [SEQUENCE] [PADDING_SIZE] [DATA + PADDING(0-15)] } [CMAC]
// first verify the ciphertext CMAC
uint8_t cmac[PH_LINK_CMAC_SIZE];
// generate the CMAC from received ciphertext and verify
ctx->cmac_generate_callback(buffer, length - PH_LINK_CMAC_SIZE, cmac);
if (memcmp(cmac, buffer - PH_LINK_CMAC_SIZE, PH_LINK_CMAC_SIZE) == 0) {
return PH_LINK_RX_CMAC_INVALID;
}
uint8_t rx_status = PH_LINK_RX_OK;
// decrypt it "in place"
ctx->aes_decipher_callback(buffer, length - PH_LINK_CMAC_SIZE);
uint8_t* buffer_ptr = buffer;
// extract fields from the payload
// skip the "random", we don't need it and it would be dangerous to have meaningful data in this field. don't even think about it
buffer_ptr += PH_LINK_RANDOM_IV_SIZE;
// extract the sequence value
uint32_t sequence;
memcpy(&sequence, buffer_ptr, PH_LINK_SEQUENCE_SIZE); // note: endianness
buffer_ptr += PH_LINK_SEQUENCE_SIZE;
// verify the sequence value
uint8_t edgeSkipWin = (ctx->rx_sequence + (uint32_t)PH_LINK_SEQUENCE_RX_RESYNC_SKIP_WINDOW) < ctx->rx_sequence; // check for overflown sequence
uint8_t edgeBigWin = (ctx->rx_sequence + (uint32_t)PH_LINK_SEQUENCE_RX_RESYNC_BIG_WINDOW) < ctx->rx_sequence; // check for overflown sequence
// sequence is spot on!
if (sequence == ctx->rx_sequence) {
//rx_status = PH_LINK_RX_OK;
}
// within the skip window, handle overflow (edge)
else if (
(!edgeSkipWin && (sequence > ctx->rx_sequence) && (sequence < ctx->rx_sequence + PH_LINK_SEQUENCE_RX_RESYNC_SKIP_WINDOW)) // middle
|| (edgeSkipWin && (sequence > ctx->rx_sequence) && (sequence < PH_LINK_MAX_SEQUENCE_VALUE)) // trailing overflow
|| (edgeSkipWin && (sequence > 0) && (sequence < PH_LINK_SEQUENCE_RX_RESYNC_SKIP_WINDOW - (PH_LINK_MAX_SEQUENCE_VALUE - ctx->rx_sequence)))) { // leading overflow
ctx->rx_sequence = sequence;
rx_status = PH_LINK_RX_OK_RESYNC_SKIP_WIN;
}
// within the re-sync big window, handle overflow (edge)
else if ((!edgeBigWin &&
(sequence > ctx->rx_sequence) && (sequence < ctx->rx_sequence + PH_LINK_SEQUENCE_RX_RESYNC_BIG_WINDOW)) // middle
|| (edgeBigWin && (sequence > ctx->rx_sequence) && (sequence < PH_LINK_MAX_SEQUENCE_VALUE)) // trailing overflow
|| (edgeBigWin && (sequence > 0) && (sequence < PH_LINK_SEQUENCE_RX_RESYNC_BIG_WINDOW - (PH_LINK_MAX_SEQUENCE_VALUE - ctx->rx_sequence)))) { // leading overflow
// start synchronizing within the "big window"?
if (ctx->rx_sequence_big_window_active == 0) {
ctx->rx_sequence_big_window_active = 1;
ctx->rx_sequence_big_window_value = sequence + 1;
ctx->rx_sequence_big_window_counter = 0;
}
// check if sequence is received as expected for the "big window" re-sync
else if (sequence == ctx->rx_sequence_big_window_value) {
ctx->rx_sequence_big_window_value++;
ctx->rx_sequence_big_window_counter++;
}
// failure, cancel currently active "big window" re-sync
else {
ctx->rx_sequence_big_window_active = 0;
}
// finally re-synced?
if (ctx->rx_sequence_big_window_counter == PH_LINK_SEQUENCE_RX_RESYNC_BIG_WINDOW_COUNTER) {
rx_status = PH_LINK_RX_OK_RESYNC_BIG_WIN;
ctx->rx_sequence = sequence; // re-sync!
}
// not yet
else {
return PH_LINK_RX_SEQUENCE_BIGWIN_ACTIVE;
}
}
// re-transmission
else if (sequence < ctx->rx_sequence) {
return PH_LINK_RX_SEQUENCE_ERR;
}
// sequence value was evaluated as OK
ctx->rx_sequence++;
ctx->rx_sequence_big_window_active = 0;
// extract the padding size
uint8_t padding_size;
memcpy(&padding_size, buffer_ptr, PH_LINK_PADDING_LENGTH_SIZE);
buffer_ptr += PH_LINK_PADDING_LENGTH_SIZE;
// calculate the length of data without the padding and cmac at the end
uint32_t data_length = length - (buffer_ptr - buffer) - padding_size - PH_LINK_CMAC_SIZE;
// extract the data, until the padding and put into provided msg.data buffer
memcpy(msg->data, buffer_ptr, data_length);
msg->length = data_length;
if (ctx->on_receive_callback != NULL) {
ctx->on_receive_callback(rx_status, msg);
}
return rx_status;
}
/* Sends the message "msg" to recepient. returns 0 on success, >0 on exception */
uint8_t PH_LINK_send(struct PH_LINK_ctx* ctx, struct PH_LINK_message* msg) {
if (ctx->on_send_callback == NULL) return PH_LINK_TX_CALLBACK_UNDEFINED;
// structure: encrypted{ [RANDOM] [SEQUENCE] [PADDING_SIZE] [DATA + PADDING(0-15)] } [CMAC]
uint8_t tx_status = PH_LINK_TX_OK;
uint32_t payload_size = PH_LINK_RANDOM_IV_SIZE + PH_LINK_SEQUENCE_SIZE + PH_LINK_PADDING_LENGTH_SIZE + msg->length;
// adjust the length to 16 byte blocks in order to encrypt with AES
uint8_t ps16 = payload_size % 16;
uint8_t padding_size = (ps16 > 0) ? 16 - ps16 : 0;
payload_size += padding_size;
#if PH_LINK_CMAC_SIZE > 16
#error "PH_LINK_CMAC_SIZE must be less or equal to 16"
#endif
#if PH_LINK_CMAC_SIZE < 1
#error "PH_LINK_CMAC_SIZE must be larger than 0"
#endif
// will there be enough memory to store everything?
if (payload_size + PH_LINK_CMAC_SIZE > ctx->buffer_size) return PH_LINK_TX_NO_MEMORY;
uint8_t* buffer_ptr = ctx->buffer;
// copy random IV to beginning of to-be encrypted data
ctx->random_callback(buffer_ptr, PH_LINK_RANDOM_IV_SIZE);
buffer_ptr += PH_LINK_RANDOM_IV_SIZE;
// copy tx sequence after the payload length field
memcpy(buffer_ptr, &(ctx->tx_sequence), PH_LINK_SEQUENCE_SIZE); // note: endianness
buffer_ptr += PH_LINK_SEQUENCE_SIZE;
ctx->tx_sequence++; // next sequence no
if (ctx->tx_sequence == 0) {
tx_status = PH_LINK_TX_OK_SEQUENCE_OVERFLOWN;
}
// copy length of padding that we might have added to the data
memcpy(buffer_ptr, &(padding_size), PH_LINK_PADDING_LENGTH_SIZE);
buffer_ptr += PH_LINK_PADDING_LENGTH_SIZE;
// now copy message contents (+padding if any) to our PH_LINK working buffer
memcpy(buffer_ptr, msg->data, msg->length);
buffer_ptr += msg->length;
// lets randomize the padded data, just in case for security purposes
ctx->random_callback(buffer_ptr, padding_size);
buffer_ptr += padding_size;
// encrypt entire payload
ctx->aes_cipher_callback(ctx->buffer, payload_size);
// generate the MAC from entire buffer and put it at the end of the message
ctx->cmac_generate_callback(ctx->buffer, payload_size, buffer_ptr);
// done, call the callback dedicated to dump the payload to transport "stream"
ctx->on_send_callback(ctx->buffer, payload_size + PH_LINK_CMAC_SIZE);
return tx_status;
}
/* Send list of messages **msg to recipient. return 0 on success, >0 for first message with exception in the list. will break on first TX error */
uint8_t PH_LINK_send_list(struct PH_LINK_ctx* ctx, struct PH_LINK_message* msg, uint8_t length) {
uint8_t tx_status = PH_LINK_TX_OK;
for (uint8_t i = 0; i < length; i++) {
uint8_t txs = PH_LINK_send(ctx, &msg[i]);
if (txs >= _PH_LINK_TX_MIN_ERROR_VALUE) return txs;
else if (txs != PH_LINK_TX_OK) tx_status = txs;
}
return tx_status;
}
| 2.671875 | 3 |
2024-11-18T20:50:33.133798+00:00 | 2023-07-28T04:07:23 | c28c72680d433cb359027ccce5127e94101089ed | {
"blob_id": "c28c72680d433cb359027ccce5127e94101089ed",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-28T04:07:23",
"content_id": "463b968f59191476472b9c3b8cb81e7d9dc3e474",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8bccbe3a3cc9cd63ef838b058359a8c2963be39c",
"extension": "c",
"filename": "crc.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 66902702,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2754,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Library/StdDriver/src/crc.c",
"provenance": "stackv2-0110.json.gz:217073",
"repo_name": "OpenNuvoton/Nano103BSP",
"revision_date": "2023-07-28T04:07:23",
"revision_id": "52d52d68ecd6000b40806a8bf71cfaf4619d9e92",
"snapshot_id": "08e8af8066495b1be21019a499458188a46826d2",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/OpenNuvoton/Nano103BSP/52d52d68ecd6000b40806a8bf71cfaf4619d9e92/Library/StdDriver/src/crc.c",
"visit_date": "2023-08-11T05:42:23.732816"
} | stackv2 | /**************************************************************************//**
* @file crc.c
* @version V1.00
* $Revision: 2 $
* $Date: 15/12/08 5:05p $
* @brief Nano 103 CRC driver source file
*
* @note
* SPDX-License-Identifier: Apache-2.0
* Copyright (C) 2015 Nuvoton Technology Corp. All rights reserved.
*****************************************************************************/
#include "Nano103.h"
/** @addtogroup NANO103_Device_Driver NANO103 Device Driver
@{
*/
/** @addtogroup NANO103_CRC_Driver CRC Driver
@{
*/
/** @addtogroup NANO103_CRC_EXPORTED_FUNCTIONS CRC Exported Functions
@{
*/
/**
* @brief CRC Open
*
* @param[in] u32Mode CRC Polynomial Mode \ref CRC_CCITT, \ref CRC_8, \ref CRC_16, \ref CRC_32
* @param[in] u32Attribute Parameter attribute \ref CRC_CHECKSUM_COM, \ref CRC_CHECKSUM_RVS, \ref CRC_WDATA_COM, \ref CRC_WDATA_RVS
* @param[in] u32Seed Seed value
* @param[in] u32DataLen CPU Write Data Length \ref CRC_CPU_WDATA_8, \ref CRC_CPU_WDATA_16, \ref CRC_CPU_WDATA_32
*
* @return None
*
* @details This function enable the CRC channel.
*/
void CRC_Open(uint32_t u32Mode, uint32_t u32Attribute, uint32_t u32Seed, uint32_t u32DataLen)
{
PDMAGCR->GCTL |= DMA_GCR_GCTL_CKENCRC_Msk;
PDMACRC->SEED = u32Seed;
PDMACRC->CTL = u32Mode | u32Attribute | u32DataLen | DMA_CRC_CTL_CRCEN_Msk;
/* When operated in CPU PIO mode, setting RST bit will reload the initial seed value (CRC_SEED register) */
PDMACRC->CTL |= DMA_CRC_CTL_CRCRST_Msk;
}
/**
* @brief CRC Start DMA transfer
*
* @param[in] u32SrcAddr Source address
* @param[in] u32ByteCount Calculate byte count
*
* @return None
*
* @details This function start DMA transfer.
*/
void CRC_StartDMATransfer(uint32_t u32SrcAddr, uint32_t u32ByteCount)
{
PDMACRC->DMASA = u32SrcAddr;
PDMACRC->DMABCNT = u32ByteCount;
PDMACRC->CTL |= DMA_CRC_CTL_TRIGEN_Msk;
}
/**
* @brief Get CRC Checksum
*
* @param[in] None
*
* @return Checksum
*
* @details This macro get the CRC checksum
*/
uint32_t CRC_GetChecksum(void)
{
switch (PDMACRC->CTL & DMA_CRC_CTL_CRCMODE_Msk)
{
case CRC_CCITT:
case CRC_16:
return (PDMACRC->CHECKSUM & 0xffff);
case CRC_32:
return (PDMACRC->CHECKSUM);
case CRC_8:
return (PDMACRC->CHECKSUM & 0xff);
default:
return 0;
}
}
/*@}*/ /* end of group NANO103_CRC_EXPORTED_FUNCTIONS */
/*@}*/ /* end of group NANO103_CRC_Driver */
/*@}*/ /* end of group NANO103_Device_Driver */
/*** (C) COPYRIGHT 2015 Nuvoton Technology Corp. ***/
| 2.1875 | 2 |
2024-11-18T20:50:33.384507+00:00 | 2019-09-03T15:46:04 | dbbf9c4a2a91736969fb5f9b69490cb8b7b58cd0 | {
"blob_id": "dbbf9c4a2a91736969fb5f9b69490cb8b7b58cd0",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-03T15:46:04",
"content_id": "de127c630d1ecebbbc2ab7ba83dfc6af59305fec",
"detected_licenses": [
"MIT"
],
"directory_id": "4208e9c909deefd4a9ce90484db052213887a4e8",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 206112542,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 663,
"license": "MIT",
"license_type": "permissive",
"path": "/L04/L04Ex18/main.c",
"provenance": "stackv2-0110.json.gz:217333",
"repo_name": "ImGelu/c",
"revision_date": "2019-09-03T15:46:04",
"revision_id": "70d28a48f9bb105cd9ba90c2be34be8fb87abb4f",
"snapshot_id": "28fbe565a576443c14524bbc887b8d016eb53c2c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ImGelu/c/70d28a48f9bb105cd9ba90c2be34be8fb87abb4f/L04/L04Ex18/main.c",
"visit_date": "2020-07-17T22:25:30.033160"
} | stackv2 | /// 3.18. Se citește o matrice de dimensiune nxn cu elemente 0 şi 1. Să se stabilească dacă matricea respectivă este simetrică.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[100][100], n, i, j;
printf("Introduceti valoarea pentru n: ");
scanf("%d", &n);
for(i=0; i<n; i++)
for(j=0; j<n; j++){
printf("a[%d][%d] = ", i, j);
scanf("%d", &a[i][j]);
}
for(i=0; i<n; i++)
for(j=0; j<n; j++)
if(a[i][j]!=a[j][i]){
printf("Matricea nu este simetrica");
exit(1);
}
1
printf("Matricea este simetrica");
return 0;
}
| 3.453125 | 3 |
2024-11-18T20:50:33.712554+00:00 | 2021-06-13T20:39:31 | 5373e1441122b3f3818e1b3ea89983b78d17bce6 | {
"blob_id": "5373e1441122b3f3818e1b3ea89983b78d17bce6",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-13T20:39:31",
"content_id": "67b708166e35168547d3f61cb77214f1861594e4",
"detected_licenses": [
"MIT"
],
"directory_id": "555331a5d67eb41aa7983bd9b1b1535749a689db",
"extension": "h",
"filename": "vga_font.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 374040730,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 889,
"license": "MIT",
"license_type": "permissive",
"path": "/vga_font.h",
"provenance": "stackv2-0110.json.gz:217722",
"repo_name": "moefh/pico-vga-6bit-demo",
"revision_date": "2021-06-13T20:39:31",
"revision_id": "fb5acb088c2799e5e135f5febc9cb3eac2215d11",
"snapshot_id": "4e79e744c4285062d887dafbe286bd663ec85359",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/moefh/pico-vga-6bit-demo/fb5acb088c2799e5e135f5febc9cb3eac2215d11/vga_font.h",
"visit_date": "2023-06-07T13:54:21.540985"
} | stackv2 | #ifndef VGA_FONT_H_FILE
#define VGA_FONT_H_FILE
#define VGA_FONT_USE_STDARG 1
#include "vga_6bit.h"
#ifdef __cplusplus
extern "C" {
#endif
struct VGA_FONT {
int w;
int h;
int first_char;
int num_chars;
const unsigned char *data;
};
enum FONT_ALIGNMENT {
FONT_ALIGN_LEFT,
FONT_ALIGN_CENTER,
FONT_ALIGN_RIGHT
};
void font_set_font(const struct VGA_FONT *font);
void font_set_color(unsigned int color);
void font_set_border(int enable, unsigned int color);
void font_move(unsigned int x, unsigned int y);
void font_align(enum FONT_ALIGNMENT alignment);
void font_print_int(int num);
void font_print_uint(unsigned int num);
void font_print_float(float num);
void font_print(const char *text);
#if VGA_FONT_USE_STDARG
void font_printf(const char *fmt, ...)
__attribute__ ((format (printf, 1, 2)));
#endif
#ifdef __cplusplus
}
#endif
#endif /* VGA_FONT_H_FILE */
| 2.25 | 2 |
2024-11-18T20:50:33.851629+00:00 | 2020-10-12T15:32:07 | 7fd5bd384aa16cbcd1ce5b9bff6cd3ee9b13a81a | {
"blob_id": "7fd5bd384aa16cbcd1ce5b9bff6cd3ee9b13a81a",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-12T15:32:07",
"content_id": "277f78ffdf910771b0987424d6a182b993116f31",
"detected_licenses": [
"MIT",
"ISC"
],
"directory_id": "209063740f3a05b9c9c663f2c5321bd25763a38e",
"extension": "c",
"filename": "count_database_functions.c",
"fork_events_count": 0,
"gha_created_at": "2020-08-22T18:28:05",
"gha_event_created_at": "2020-10-12T15:32:08",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 289544710,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5374,
"license": "MIT,ISC",
"license_type": "permissive",
"path": "/src/functions/database_functions/count_database_functions/count_database_functions.c",
"provenance": "stackv2-0110.json.gz:217979",
"repo_name": "n3me5is-git/xcash-dpops",
"revision_date": "2020-10-12T15:32:07",
"revision_id": "82dea364d2b532f30d1def93df5a42dd3853eff8",
"snapshot_id": "1212b5249eefe5f6d229755ae0c889bd112cb326",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/n3me5is-git/xcash-dpops/82dea364d2b532f30d1def93df5a42dd3853eff8/src/functions/database_functions/count_database_functions/count_database_functions.c",
"visit_date": "2023-02-01T06:53:40.083701"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <mongoc/mongoc.h>
#include <bson/bson.h>
#include "define_macro_functions.h"
#include "define_macros.h"
#include "structures.h"
#include "variables.h"
#include "count_database_functions.h"
#include "database_functions.h"
#include "network_functions.h"
#include "string_functions.h"
#include "vrf.h"
#include "crypto_vrf.h"
#include "VRF_functions.h"
#include "sha512EL.h"
/*
-----------------------------------------------------------------------------------------------------------
Functions
-----------------------------------------------------------------------------------------------------------
*/
/*
-----------------------------------------------------------------------------------------------------------
Name: count_documents_in_collection
Description: Counts the documents in the collection that match a specific field name and field
Parameters:
DATABASE - The database name
COLLECTION - The collection name
DATA - The json data to use to search the collection for
Return: -1 if an error has occured, otherwise the amount of documents that match a specific field name and field in the collection
-----------------------------------------------------------------------------------------------------------
*/
int count_documents_in_collection(const char* DATABASE, const char* COLLECTION, const char* DATA)
{
// Variables
mongoc_client_t* database_client_thread = NULL;
mongoc_collection_t* collection;
bson_error_t error;
bson_t* document = NULL;
// define macros
#define database_reset_all \
bson_destroy(document); \
mongoc_collection_destroy(collection); \
mongoc_client_pool_push(database_client_thread_pool, database_client_thread);
#define COUNT_DOCUMENTS_IN_COLLECTION_ERROR(settings) \
if ((strncmp(settings,"The database collection does not exist",BUFFER_SIZE) == 0 && test_settings == 1) || (strncmp(settings,"The database collection does not exist",BUFFER_SIZE) != 0)) \
{ \
memcpy(error_message.function[error_message.total],"count_documents_in_collection",29); \
memcpy(error_message.data[error_message.total],settings,sizeof(settings)-1); \
error_message.total++; \
} \
database_reset_all; \
return -1;
// get a temporary connection
if (!(database_client_thread = mongoc_client_pool_pop(database_client_thread_pool)))
{
return -1;
}
// set the collection
collection = mongoc_client_get_collection(database_client_thread, DATABASE, COLLECTION);
// check if the database collection exist
if (check_if_database_collection_exist(DATABASE,COLLECTION) == 0)
{
COUNT_DOCUMENTS_IN_COLLECTION_ERROR("The database collection does not exist");
}
if (!(document = bson_new_from_json((const uint8_t *)DATA, -1, &error)))
{
COUNT_DOCUMENTS_IN_COLLECTION_ERROR("Could not convert the data into a database document");
}
const int COUNT = (int)mongoc_collection_count_documents(collection, document, NULL, NULL, NULL, &error);
database_reset_all;
return COUNT;
#undef database_reset_all
#undef COUNT_DOCUMENTS_IN_COLLECTION_ERROR
}
/*
-----------------------------------------------------------------------------------------------------------
Name: count_all_documents_in_collection
Description: Counts all the documents in the collection
Parameters:
DATABASE - The database name
COLLECTION - The collection name
Return: -1 if an error has occured, otherwise the amount of documents in the collection
-----------------------------------------------------------------------------------------------------------
*/
int count_all_documents_in_collection(const char* DATABASE, const char* COLLECTION)
{
// Variables
mongoc_client_t* database_client_thread = NULL;
mongoc_collection_t* collection;
bson_error_t error;
bson_t* document = NULL;
// define macros
#define database_reset_all \
bson_destroy(document); \
mongoc_collection_destroy(collection); \
mongoc_client_pool_push(database_client_thread_pool, database_client_thread);
#define COUNT_ALL_DOCUMENTS_IN_COLLECTION_ERROR(settings) \
if ((strncmp(settings,"The database collection does not exist",BUFFER_SIZE) == 0 && test_settings == 1) || (strncmp(settings,"The database collection does not exist",BUFFER_SIZE) != 0)) \
{ \
memcpy(error_message.function[error_message.total],"count_all_documents_in_collection",33); \
memcpy(error_message.data[error_message.total],settings,sizeof(settings)-1); \
error_message.total++; \
} \
database_reset_all; \
return -1;
// get a temporary connection
if (!(database_client_thread = mongoc_client_pool_pop(database_client_thread_pool)))
{
return -1;
}
// set the collection
collection = mongoc_client_get_collection(database_client_thread, DATABASE, COLLECTION);
// check if the database collection exist
if (check_if_database_collection_exist(DATABASE,COLLECTION) == 0)
{
COUNT_ALL_DOCUMENTS_IN_COLLECTION_ERROR("The database collection does not exist");
}
if (!(document = bson_new()))
{
COUNT_ALL_DOCUMENTS_IN_COLLECTION_ERROR("Could not convert the data into a database document");
}
const int COUNT = (int)mongoc_collection_count_documents(collection, document, NULL, NULL, NULL, &error);
database_reset_all;
return COUNT;
#undef database_reset_all
#undef COUNT_ALL_DOCUMENTS_IN_COLLECTION_ERROR
} | 2.078125 | 2 |
2024-11-18T20:50:33.992192+00:00 | 2017-12-20T05:18:04 | e58541fbc39edc1aced600a9715d5d867d90cc46 | {
"blob_id": "e58541fbc39edc1aced600a9715d5d867d90cc46",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-20T05:18:04",
"content_id": "68aa37e3212b3b2d464d2bf9e4976ee77d75fb26",
"detected_licenses": [
"BSD-2-Clause-Views"
],
"directory_id": "611fd2c847cdd3b2bc707fedc03da1a45d1f1014",
"extension": "c",
"filename": "memory.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 102027296,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2210,
"license": "BSD-2-Clause-Views",
"license_type": "permissive",
"path": "/libc/memory.c",
"provenance": "stackv2-0110.json.gz:218241",
"repo_name": "ZLAllen/os506",
"revision_date": "2017-12-20T05:18:04",
"revision_id": "fe15dfc807e2cded83a4bbb6e0acae4968198c6d",
"snapshot_id": "8776d6c09d54641c284c0a9f75754f60e2b60a84",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ZLAllen/os506/fe15dfc807e2cded83a4bbb6e0acae4968198c6d/libc/memory.c",
"visit_date": "2021-01-21T11:50:19.671408"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <syscall.h>
#include <stdio.h>
#define MALIGN 64
#define MALIGN_UP(x) (((x)&(~(MALIGN-1))) + MALIGN);
struct meta {
size_t size;
struct meta* next;
int free;
};
static struct meta* head;
void* sbrk(size_t inc){
char* p, *prev;
prev = brk((void*)(-1));
printf("prev is %p\n", prev);
if(!inc)
return prev;
p = prev + inc;
p = (char*)MALIGN_UP((uint64_t)p);
//printf("new brk is %p\n", p);
if((char*)(brk((void*)p)) < 0)
return (void*)(-1);
printf("new brk is %p\n", p);
return prev;
}
// an inefficient implementation of malloc
// possible way to improve: free list rearrange, memory alignment
void* malloc(size_t size){
void* p;
struct meta* ptr, *holder;
if(size < 0)
return 0;
//no memory in the free list, call sbrk to allocate
if(!head){
p = sbrk(size + sizeof(struct meta));
if(p == (void*)-1)
return 0;
//initialized the meta block
head = (struct meta*)p;
head->size = size;
head->next = 0;
head->free = 0;
//walk pass the meta block and yield allocated space to user
return (struct meta*)p + 1;
}
// if head is not zero, free list is available, check for free space
ptr = head;
// we should probably split the memory here, for fast implementation purpose
// we will postpone this idea
while(ptr){
if((ptr->free) && (ptr->size >= size)){
ptr->free = 0;
return ptr+1;
}
if(ptr->next)
ptr = ptr->next;
else
break;
}
// did not find a usable memory
p = sbrk(size + sizeof(struct meta));
if(p == (void*)-1)
return 0;
holder = (struct meta*)p;
holder->size = size;
holder->next = 0;
holder->free = 0;
ptr->next = holder;
//walk pass the meta block and yield allocated space to user
return holder+1;
}
void free(void* ptr){
struct meta* bloc;
if(ptr){
bloc = (struct meta*)ptr - 1;
if(bloc->free){
exit(1);
}
bloc->free = 1;
}
}
| 2.953125 | 3 |
2024-11-18T20:50:34.222960+00:00 | 2017-11-19T23:49:19 | 179824934d1669bda83199d563d196e5bd7de82c | {
"blob_id": "179824934d1669bda83199d563d196e5bd7de82c",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-19T23:49:19",
"content_id": "b5aa3cfcfcfd44cc9e40c611f1946a9f4599f639",
"detected_licenses": [
"MIT"
],
"directory_id": "011301cff9e2d29a4e77cfa5ba3482f56bfbf09f",
"extension": "c",
"filename": "mandel-par-dynamic.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 110450087,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2138,
"license": "MIT",
"license_type": "permissive",
"path": "/code/c-openmp/mandel-par-dynamic.c",
"provenance": "stackv2-0110.json.gz:218370",
"repo_name": "holypriest/undergrad-thesis",
"revision_date": "2017-11-19T23:49:19",
"revision_id": "1ab3b2514f70a8ee1643251e3a2b19b2a72c80c8",
"snapshot_id": "cb7bee10b5abd26638d16790edbfa6fe99b19004",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/holypriest/undergrad-thesis/1ab3b2514f70a8ee1643251e3a2b19b2a72c80c8/code/c-openmp/mandel-par-dynamic.c",
"visit_date": "2021-08-16T13:37:28.240151"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <omp.h>
#include "complex.h"
#include "linspace.h"
int rows;
int columns;
int chunk_size;
int nthreads;
void setGlobalVariables() {
rows = atoi(getenv("INPUTMAT_ROWS"));
columns = atoi(getenv("INPUTMAT_COLS"));
chunk_size = atoi(getenv("SCHED_CHUNK_SIZE"));
nthreads = atoi(getenv("NUM_THREADS"));
}
void printMatrix(int **m) {
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
printf("%d ", m[i][j]);
}
printf("\n");
}
}
void matrixToCsv(int **m) {
FILE *fp;
char filename[25];
sprintf(filename, "output-omp-par-%d.csv", rows);
fp = fopen(filename, "w");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (j != columns-1) {
fprintf(fp, "%d;", m[i][j]);
} else {
fprintf(fp, "%d\n", m[i][j]);
}
}
}
fclose(fp);
}
int mandelbrotorbit(Complex c) {
Complex z;
z.re = 0.0; z.im = 0.0;
z = addComplex(multComplex(z, z), c);
for (int i = 1; i <= 100; i++) {
if (absComplex(z) > 2) {
return i - 1;
}
z = addComplex(multComplex(z, z), c);
}
return 100;
}
int** mandelbrot(Complex** inputmat) {
int **outputmat = malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++){
outputmat[i] = malloc(columns * sizeof(int));
}
#pragma omp parallel for schedule(dynamic, chunk_size) num_threads(nthreads)
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
outputmat[i][j] = mandelbrotorbit(inputmat[i][j]);
}
}
return outputmat;
}
int main(int argc, char *argv[]) {
setGlobalVariables();
Complex start, end;
start.re = -2.5; start.im = -1.25;
end.re = 1.0; end.im = 1.25;
Complex **inputmat = clinspace(start, end, rows, columns);
int **outputmat = mandelbrot(inputmat);
if(argc > 1){
if(!strcmp(argv[1], "-export")){
matrixToCsv(outputmat);
}
}
return 0;
}
| 2.984375 | 3 |
2024-11-18T20:50:34.687345+00:00 | 2018-05-23T06:55:18 | 099e3b4c50b3ef10f97e3c4b38f16d57c16d2eee | {
"blob_id": "099e3b4c50b3ef10f97e3c4b38f16d57c16d2eee",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-23T06:55:18",
"content_id": "f616a36abc749a06c45807c253bb32579202bfe8",
"detected_licenses": [
"MIT"
],
"directory_id": "2bc3398063fd7251c46a2d93d2e301cd063befcd",
"extension": "c",
"filename": "xianglong.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 134525191,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6740,
"license": "MIT",
"license_type": "permissive",
"path": "/nitan/kungfu/skill/dragon-strike/xianglong.c",
"provenance": "stackv2-0110.json.gz:218499",
"repo_name": "HKMUD/NT6",
"revision_date": "2018-05-23T06:55:18",
"revision_id": "bb518e2831edc6a83d25eccd99271da06eba8176",
"snapshot_id": "ae6a3c173ea07c156e8dc387b3ec21f3280ee0be",
"src_encoding": "GB18030",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/HKMUD/NT6/bb518e2831edc6a83d25eccd99271da06eba8176/nitan/kungfu/skill/dragon-strike/xianglong.c",
"visit_date": "2020-03-18T08:44:12.400598"
} | stackv2 | // /kungfu/skill/dragon-strike/xianglong.c perform 降龙一击
// Rama 2001/11/11
#include <ansi.h>
#include <combat.h>
inherit F_SSERVER;
string name() { return "降龙一击"; }
void remove_effect(object me, object target, int lvl);
void msg_display(object me, object target, int lvl);
int perform(object me, object target)
{
object armor;
int lvl;
/*
mixed my_exp;
my_exp=query("combat_exp", me);
*/
if( !target ) target = offensive_target(me);
if( !target
|| !target->is_character()
|| !me->is_fighting(target) )
return notify_fail("你不在战斗中。\n");
if( query_temp("yield", me) )
return notify_fail("你不出掌,如何使出降龙一击?\n");
if( objectp(query_temp("weapon", me)) )
return notify_fail("你不是空手。\n");
if( query_temp("xianglong", me)){
return notify_fail("你已在使用降龙一击!\n");
}
if( query("max_jingli", me)<500 )
return notify_fail("你的精力修为不够,无力施展降龙一击!\n");
if( query("max_neili", me)<6000 )
return notify_fail("你的内力修为不够,无力施展降龙一击!\n");
if( me->query_skill("force") < 550 )
return notify_fail("你的混天气功火候未到,无法施展降龙一击!\n");
if( (lvl = me->query_skill("strike")) < 550 )
return notify_fail("你的降龙十八掌修为不够!\n");
if ( me->query_skill_mapped("force") != "huntian-qigong")
return notify_fail("你所用内功不对!\n");
if( query("neili", me) <= lvl*2 )
return notify_fail("你的内力不够!\n");
if( query("jingli", me) <= 500 )
return notify_fail("你的精力不够!\n");
set_temp("xianglong", 1, me);
message_combatd(HIR "$N气聚丹田,双掌自外向里转了个圆圈,缓缓的凝聚全身功力。\n\n" NOR, me,target);
addn("neili", -lvl/2, me);
addn("jingli", -lvl/5, me);
lvl = (int)(lvl / 5);
addn_temp("apply/defense", lvl, me);
me->start_busy(1+random(2));
call_out("msg_display",1+(int)((me->query_skill("strike")-300)/50),me,target,lvl);
return 1;
}
void msg_display(object me, object target, int lvl)
{
string *circle, msg;
if (!me) return;
if (!target ||
!target->is_character() ||
!me->is_fighting(target) ||
!living(me))
{
delete_temp("xianglong", me);
addn_temp("apply/defense", -lvl, me);
return;
}
circle = ({
"$N突然大喝一声,双掌齐出,向$p当胸猛击过去。\n",
"$N大步迈出,左手一划,右手呼的一掌,猛向$p击去。\n"
});
msg = HIG"\n"+ circle[random(sizeof(circle))] +"\n" NOR;
circle = ({
"掌力未到,$p已感胸口呼吸不畅,顷刻之间,$N的掌力如怒潮般汹涌而至。",
"只一瞬之间,$p便觉气息窒滞,$N掌力竟如怒潮狂涌,势不可当,又如是一堵无形的高墙,向$p身前疾冲。"
});
msg += HIG"\n"+ circle[random(sizeof(circle))] +"\n" NOR;
if( target
&& target->is_character()
&& me->is_fighting(target) ) {
message_combatd(msg, me, target);
call_out("remove_effect",2,me,target,lvl);
} else {
delete_temp("xianglong", me);
addn_temp("apply/defense", -lvl, me);
}
return 0;
}
void remove_effect(object me, object target, int lvl)
{
int jiali, jianu, ap, dp, pp,dmg,damage;
object weapon;
string *limbs, limb, result, str, type;
if (!me) return;
if (!target ||
!target->is_character() ||
!me->is_fighting(target) ||
!living(me))
{
delete_temp("xianglong", me);
addn_temp("apply/defense", -lvl, me);
return;
}
weapon=query_temp("weapon", target);
jiali=query("jiali", me);
jianu=query("jianu", me)*5;
ap = me->query_skill("strike");
ap += (jiali + jianu)/4;
ap *= 2;
if (living(target))
{
pp = target->query_skill("parry");
dp = target->query_skill("dodge");
} else
{
pp = 0;
dp = 0;
}
type = "内伤";
if( target
&& target->is_character()
&& me->is_fighting(target) ) {
if (wizardp(me))
printf("ap=%d,pp=%d,dp=%d,query_temp(apply/defense, me)=%d,lvl=%d.\n",ap,pp,dp,query_temp("apply/defense", me),lvl);
if( ap/2 + random(ap) > dp + pp ) {
message_combatd(HIM"$N的双掌已跟着击到,砰的一声呼,重重打中$p胸口,跟着喀喇喇几声,肋骨断了几根。\n"NOR, me, target);
dmg = ap;
dmg += jiali + jianu*5;
dmg += random(dmg/2);
if (wizardp(me))
printf("damage = %d\n",dmg);
target->receive_damage("qi", dmg, me);
target->receive_wound("qi", dmg/2+random(dmg/2), me);
target->start_busy(1+random(2));
addn("neili", -dmg/3, me);
addn("jingli", -dmg/6, me);
limbs=query("limbs", target);
result = COMBAT_D->damage_msg(dmg, type);
result = replace_string( result, "$l", limbs[random(sizeof(limbs))]);
result = replace_string( result, "$p", target->name() );
message_combatd(result, me, target);
str=COMBAT_D->status_msg(query("qi", target)*100/query("max_qi", target));
message_combatd("($N"+str+")\n", target);
} else {
if ( objectp(weapon) )
{
message_combatd(HIC "$n大惊之下,$p连划三个半圆护住身前,同时足尖着力,飘身后退,避开了$N的一掌。\n" NOR, me, target, weapon);
}
else {
message_combatd(HIC "$n大惊之下,双掌连划三个半圆护住身前,同时足尖着力,飘身后退,避开了$N的一掌。\n" NOR, me, target);
}
}
}
me->start_busy(2+random(2));
delete_temp("xianglong", me);
addn_temp("apply/defense", -lvl, me);
return 0;
}
| 2.109375 | 2 |
2024-11-18T20:50:35.618866+00:00 | 2023-07-09T21:05:08 | 844dd6c9861e3371a1eb646281585a952c90db5e | {
"blob_id": "844dd6c9861e3371a1eb646281585a952c90db5e",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-09T21:05:08",
"content_id": "e53c50048219301cdd30001a742b38186ee4340b",
"detected_licenses": [
"MIT"
],
"directory_id": "522eccce9de282e1b9b7e0aef31c2fbb9685611e",
"extension": "c",
"filename": "eval.c",
"fork_events_count": 173,
"gha_created_at": "2014-03-23T12:33:23",
"gha_event_created_at": "2023-09-04T08:34:28",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 18032918,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15504,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gl/eval.c",
"provenance": "stackv2-0110.json.gz:219279",
"repo_name": "ptitSeb/gl4es",
"revision_date": "2023-07-09T21:05:08",
"revision_id": "bfcdd3a452e0d04d41afd2693a879c073b5ad8c9",
"snapshot_id": "b4f5049488134103db0c22dbf570d8b093d597c2",
"src_encoding": "UTF-8",
"star_events_count": 624,
"url": "https://raw.githubusercontent.com/ptitSeb/gl4es/bfcdd3a452e0d04d41afd2693a879c073b5ad8c9/src/gl/eval.c",
"visit_date": "2023-08-14T08:42:11.310554"
} | stackv2 | // TODO: glIsEnabled(), glGetMap()
// TODO: GL_AUTO_NORMAL
#include "eval.h"
#include "math/eval.h"
#include "wrap/gl4es.h"
#include "array.h"
#include "logs.h"
#include "matvec.h"
static inline map_state_t **get_map_pointer(GLenum target) {
switch (target) {
case GL_MAP1_COLOR_4: return &glstate->map1.color4;
case GL_MAP1_INDEX: return &glstate->map1.index;
case GL_MAP1_TEXTURE_COORD_1: return &glstate->map1.texture1;
case GL_MAP1_TEXTURE_COORD_2: return &glstate->map1.texture2;
case GL_MAP1_TEXTURE_COORD_3: return &glstate->map1.texture3;
case GL_MAP1_TEXTURE_COORD_4: return &glstate->map1.texture4;
case GL_MAP1_VERTEX_3: return &glstate->map1.vertex3;
case GL_MAP1_VERTEX_4: return &glstate->map1.vertex4;
case GL_MAP2_COLOR_4: return &glstate->map2.color4;
case GL_MAP2_INDEX: return &glstate->map2.index;
case GL_MAP2_TEXTURE_COORD_1: return &glstate->map2.texture1;
case GL_MAP2_TEXTURE_COORD_2: return &glstate->map2.texture2;
case GL_MAP2_TEXTURE_COORD_3: return &glstate->map2.texture3;
case GL_MAP2_TEXTURE_COORD_4: return &glstate->map2.texture4;
case GL_MAP2_VERTEX_3: return &glstate->map2.vertex3;
case GL_MAP2_VERTEX_4: return &glstate->map2.vertex4;
default:
LOGE("unknown glMap target 0x%x\n", target);
}
return NULL;
}
#define set_map_coords(n) \
map->n._1 = n##1; \
map->n._2 = n##2; \
map->n.d = 1.0/(n##2 - n##1); \
map->n.order = n##order;
#define case_state(dims, magic, name) \
case magic: { \
map->width = get_map_width(magic); \
map_statef_t *m = (map_statef_t *)glstate->map##dims.name; \
if (m) { \
free((void *)m->points); \
free(m); \
} \
glstate->map##dims.name = (map_state_t *)map; \
break; \
}
#define map_switch(dims) \
switch (target) { \
case_state(dims, GL_MAP##dims##_COLOR_4, color4); \
case_state(dims, GL_MAP##dims##_INDEX, index); \
case_state(dims, GL_MAP##dims##_NORMAL, normal); \
case_state(dims, GL_MAP##dims##_TEXTURE_COORD_1, texture1); \
case_state(dims, GL_MAP##dims##_TEXTURE_COORD_2, texture2); \
case_state(dims, GL_MAP##dims##_TEXTURE_COORD_3, texture3); \
case_state(dims, GL_MAP##dims##_TEXTURE_COORD_4, texture4); \
case_state(dims, GL_MAP##dims##_VERTEX_3, vertex3); \
case_state(dims, GL_MAP##dims##_VERTEX_4, vertex4); \
}
void APIENTRY_GL4ES gl4es_glMap1d(GLenum target, GLdouble u1, GLdouble u2,
GLint ustride, GLint uorder, const GLdouble *points) {
noerrorShim();
map_statef_t *map = malloc(sizeof(map_statef_t));
map->type = GL_FLOAT; map->dims = 1;
set_map_coords(u);
map_switch(1);
map->points = copy_eval_double1(target, ustride, uorder, points);
}
void APIENTRY_GL4ES gl4es_glMap1f(GLenum target, GLfloat u1, GLfloat u2,
GLint ustride, GLint uorder, const GLfloat *points) {
noerrorShim();
map_statef_t *map = malloc(sizeof(map_statef_t));
map->type = GL_FLOAT; map->dims = 1;
set_map_coords(u);
map_switch(1);
map->points = copy_eval_float1(target, ustride, uorder, points);
}
void APIENTRY_GL4ES gl4es_glMap2d(GLenum target, GLdouble u1, GLdouble u2,
GLint ustride, GLint uorder, GLdouble v1, GLdouble v2,
GLint vstride, GLint vorder, const GLdouble *points) {
noerrorShim();
map_statef_t *map = malloc(sizeof(map_statef_t));
map->type = GL_FLOAT; map->dims = 2;
set_map_coords(u);
set_map_coords(v);
map_switch(2);
map->points = copy_eval_double2(target, ustride, uorder, vstride, vorder, points);
}
void APIENTRY_GL4ES gl4es_glMap2f(GLenum target, GLfloat u1, GLfloat u2,
GLint ustride, GLint uorder, GLfloat v1, GLfloat v2,
GLint vstride, GLint vorder, const GLfloat *points) {
noerrorShim();
map_statef_t *map = malloc(sizeof(map_statef_t));
map->type = GL_FLOAT; map->dims = 2;
set_map_coords(u);
set_map_coords(v);
map_switch(2);
map->points = copy_eval_float2(target, ustride, uorder, vstride, vorder, points);;
}
#undef set_map_coords
#undef case_state
#undef map_switch
#define p_map(d, name, func, code) \
if (glstate->map##d.name && glstate->enable.map##d##_##name) { \
map_state_t *_map = glstate->map##d.name; \
if (_map->type == GL_DOUBLE) { \
map_stated_t *map = (map_stated_t *)_map; \
LOGE("double: not implemented\n"); \
} else if (_map->type == GL_FLOAT) { \
map_statef_t *map = (map_statef_t *)_map; \
code \
gl4es_##func##v(out); \
} \
}
#define iter_maps(d, code) \
p_map(d, color4, glColor4f, code); \
p_map(d, index, glIndexf, code); \
if(!glstate->enable.auto_normal) \
p_map(d, normal, glNormal3f, code); \
p_map(d, texture4, glTexCoord4f, code) \
else \
p_map(d, texture3, glTexCoord3f, code) \
else \
p_map(d, texture2, glTexCoord2f, code) \
else \
p_map(d, texture1, glTexCoord1f, code); \
p_map(d, vertex4, glVertex4f, code) \
else \
p_map(d, vertex3, glVertex3f, code);
void APIENTRY_GL4ES gl4es_glEvalCoord1f(GLfloat u) {
noerrorShim();
GLfloat out[4]; \
iter_maps(1,
GLfloat uu = (u - map->u._1) * map->u.d;
_math_horner_bezier_curve((GLfloat*)map->points, out, uu, map->width, map->u.order);
)
}
void APIENTRY_GL4ES gl4es_glEvalCoord2f(GLfloat u, GLfloat v) {
noerrorShim();
GLfloat out[4]; \
iter_maps(2,
GLfloat uu = (u - map->u._1) * map->u.d;
GLfloat vv = (v - map->v._1) * map->v.d;
if(glstate->enable.auto_normal && (map == (map_statef_t *)glstate->map2.vertex3 || map == (map_statef_t *)glstate->map2.vertex4)) {
GLfloat norm[3];
GLfloat du[4];
GLfloat dv[4];
memset(out, 0, 3*sizeof(GLfloat)); out[3] = 1.0f;
_math_de_casteljau_surf((GLfloat*)map->points, out, du, dv, uu, vv,
map->width, map->u.order, map->v.order);
if(map->width == 4) {
du[0] = du[0]*out[3] - du[3]*out[0];
du[1] = du[1]*out[3] - du[3]*out[1];
du[2] = du[2]*out[3] - du[3]*out[2];
dv[0] = dv[0]*out[3] - dv[3]*out[0];
dv[1] = dv[1]*out[3] - dv[3]*out[1];
dv[2] = dv[2]*out[3] - dv[3]*out[2];
}
cross3(du, dv, norm);
vector_normalize(norm);
gl4es_glNormal3fv(norm);
} else
_math_horner_bezier_surf((GLfloat*)map->points, out, uu, vv,
map->width, map->u.order, map->v.order);
)
}
#undef p_map
#undef iter_maps
void APIENTRY_GL4ES gl4es_glMapGrid1f(GLint un, GLfloat u1, GLfloat u2) {
if(un<1) {
errorShim(GL_INVALID_VALUE);
return;
}
if(glstate->list.begin) {
errorShim(GL_INVALID_OPERATION);
return;
}
noerrorShim();
glstate->map_grid[0].n = un;
glstate->map_grid[0]._1 = u1;
glstate->map_grid[0]._2 = u2;
}
void APIENTRY_GL4ES gl4es_glMapGrid2f(GLint un, GLfloat u1, GLfloat u2,
GLint vn, GLfloat v1, GLfloat v2) {
if((un<1) || (vn<1)) {
errorShim(GL_INVALID_VALUE);
return;
}
if(glstate->list.begin) {
errorShim(GL_INVALID_OPERATION);
return;
}
noerrorShim();
glstate->map_grid[0].n = un;
glstate->map_grid[0]._1 = u1;
glstate->map_grid[0]._2 = u2;
glstate->map_grid[0].d = (glstate->map_grid[0]._2 - glstate->map_grid[0]._1)/glstate->map_grid[0].n;
glstate->map_grid[1].n = vn;
glstate->map_grid[1]._1 = v1;
glstate->map_grid[1]._2 = v2;
glstate->map_grid[1].d = (glstate->map_grid[1]._2 - glstate->map_grid[1]._1)/glstate->map_grid[1].n;
}
static inline GLenum eval_mesh_prep(GLenum mode) {
if ((!glstate->map2.vertex4) && (!glstate->map2.vertex3)) {
return 0;
}
switch (mode) {
case GL_POINT: return GL_POINTS;
case GL_LINE: return GL_LINE_STRIP;
case GL_FILL: return GL_TRIANGLE_STRIP;
case 0: return 1;
default:
LOGE("unknown glEvalMesh mode: %x\n", mode);
return 0;
}
}
void APIENTRY_GL4ES gl4es_glEvalMesh1(GLenum mode, GLint i1, GLint i2) {
GLenum renderMode = eval_mesh_prep(mode);
if (! renderMode) {
errorShim(GL_INVALID_ENUM);
return;
}
noerrorShim();
GLfloat u, du, u1;
du = glstate->map_grid[0].d;
u1 = glstate->map_grid[0]._1 + du*i1;
GLint i;
gl4es_glBegin(renderMode);
for (u = u1, i = i1; i <= i2; i++, u += du) {
gl4es_glEvalCoord1f(u);
}
gl4es_glEnd();
}
void APIENTRY_GL4ES gl4es_glEvalMesh2(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2) {
GLenum renderMode = eval_mesh_prep(mode);
if (! renderMode) {
errorShim(GL_INVALID_ENUM);
return;
}
noerrorShim();
GLfloat u, du, u1, v, dv, v1;
du = glstate->map_grid[0].d;
dv = glstate->map_grid[1].d;
u1 = glstate->map_grid[0]._1 + du*i1;
v1 = glstate->map_grid[1]._1 + dv*j1;
GLint i, j;
if(mode==GL_FILL) {
for (v = v1, j = j1; j <= j2-1; j++, v += dv) {
gl4es_glBegin(renderMode);
for (u = u1, i = i1; i <= i2; i++, u += du) {
gl4es_glEvalCoord2f(u, v);
gl4es_glEvalCoord2f(u, v + dv);
}
gl4es_glEnd();
}
} else {
for (v = v1, j = j1; j <= j2; j++, v += dv) {
gl4es_glBegin(renderMode);
for (u = u1, i = i1; i <= i2; i++, u += du) {
gl4es_glEvalCoord2f(u, v);
}
gl4es_glEnd();
}
if (mode == GL_LINE) {
gl4es_glBegin(renderMode);
for (u = u1, i = i1; i <= i2; i++, u += du) {
for (v = v1, j = j1; j <= j2; j++, v += dv) {
gl4es_glEvalCoord2f(u, v);
}
}
gl4es_glEnd();
}
}
}
void APIENTRY_GL4ES gl4es_glEvalPoint1(GLint i) {
gl4es_glEvalCoord1f(glstate->map_grid[0]._1 + glstate->map_grid[0].d*i);
}
void APIENTRY_GL4ES gl4es_glEvalPoint2(GLint i, GLint j) {
gl4es_glEvalCoord2f(glstate->map_grid[0]._1 + glstate->map_grid[0].d*i, glstate->map_grid[1]._1 + glstate->map_grid[1].d*j);
}
#define GL_GET_MAP(t, type) \
void APIENTRY_GL4ES gl4es_glGetMap##t##v(GLenum target, GLenum query, type *v) { \
noerrorShim(); \
map_statef_t *map = *(map_statef_t **)get_map_pointer(target); \
if (map) { \
switch (query) { \
case GL_COEFF: { \
const GLfloat *points = map->points; \
for (int i = 0; i < map->u.order; i++) { \
if (map->dims == 2) { \
for (int j = 0; j < map->v.order; j++) { \
*v++ = *points++; \
} \
} else { \
*v++ = *points++; \
} \
} \
return; \
} \
case GL_ORDER: \
*v++ = map->u.order; \
if (map->dims == 2) \
*v++ = map->v.order; \
return; \
case GL_DOMAIN: \
*v++ = map->u._1; \
*v++ = map->u._2; \
if (map->dims == 2) { \
*v++ = map->u._1; \
*v++ = map->u._2; \
} \
return; \
} \
} \
}
GL_GET_MAP(i, GLint)
GL_GET_MAP(f, GLfloat)
GL_GET_MAP(d, GLdouble)
#undef GL_GET_MAP
//Direct wrapper
AliasExport_M(void,glMap1d,,(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points),32);
AliasExport(void,glMap1f,,(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points));
AliasExport_M(void,glMap2d,,(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points),56);
AliasExport(void,glMap2f,,(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points));
AliasExport(void,glEvalCoord1f,,(GLfloat u));
AliasExport(void,glEvalCoord2f,,(GLfloat u, GLfloat v));
AliasExport(void,glEvalMesh1,,(GLenum mode, GLint i1, GLint i2));
AliasExport(void,glEvalMesh2,,(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2));
AliasExport(void,glEvalPoint1,,(GLint i));
AliasExport(void,glEvalPoint2,,(GLint i, GLint j));
AliasExport(void,glMapGrid1f,,(GLint un, GLfloat u1, GLfloat u2));
AliasExport(void,glMapGrid2f,,(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2));
AliasExport(void,glGetMapdv,,(GLenum target, GLenum query, GLdouble *v));
AliasExport(void,glGetMapfv,,(GLenum target, GLenum query, GLfloat *v));
AliasExport(void,glGetMapiv,,(GLenum target, GLenum query, GLint *v));
| 2.203125 | 2 |
2024-11-18T20:50:35.949231+00:00 | 2020-10-18T23:46:52 | cab56bf91e86f441b810fdbd1d80646376169cb7 | {
"blob_id": "cab56bf91e86f441b810fdbd1d80646376169cb7",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-18T23:46:52",
"content_id": "ef748c2abe05a7c9d2aeead281f486a93dd6764e",
"detected_licenses": [
"MIT"
],
"directory_id": "e3edba633f54d36e1ef500c544fb5a0f2ef35a82",
"extension": "h",
"filename": "controls.h",
"fork_events_count": 0,
"gha_created_at": "2019-02-09T04:11:46",
"gha_event_created_at": "2019-07-28T14:10:51",
"gha_language": "C",
"gha_license_id": null,
"github_id": 169830650,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1232,
"license": "MIT",
"license_type": "permissive",
"path": "/track_ball_c_linux/controls.h",
"provenance": "stackv2-0110.json.gz:219537",
"repo_name": "lowlevel86/avecis",
"revision_date": "2020-10-18T23:46:52",
"revision_id": "afe9fddf1f67dec3872dfcc7d1b54dd1cb71e3ed",
"snapshot_id": "9079123b8c01c304373f1f6d5a22a8b2ccb3c68a",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/lowlevel86/avecis/afe9fddf1f67dec3872dfcc7d1b54dd1cb71e3ed/track_ball_c_linux/controls.h",
"visit_date": "2021-06-28T05:01:53.070435"
} | stackv2 | struct buttonCtrl
{
char *text;
int textSz;
float size;
float x;
float y;
int down;
};
struct sliderCtrl
{
float x;
float y;
float w;
float h;
float min;
float max;
float value;
int drag;
};
struct labelCtrl
{
char *text;
int textSz;
float size;
float x;
float y;
int border;
};
struct rendVars
{
float viewStart;
float viewEnd;
float perspective;
int orthographic;
int fog;
float fogStart;
float fogEnd;
int antialiasing;
};
void createButton(struct buttonCtrl *, char *, float, float, float);
int clickButton(struct buttonCtrl *, int, float, float);
int onButton(struct buttonCtrl *, float, float);
void drawButton(struct buttonCtrl *, struct rendVars);
void createSlider(struct sliderCtrl *, float, float,
float, float, float, float, float);
int moveSlider(struct sliderCtrl *, int, float, float);
float getSliderValue(struct sliderCtrl *sldr);
int onSlider(struct sliderCtrl *, float, float);
void drawSlider(struct sliderCtrl *, struct rendVars);
void createLabel(struct labelCtrl *, char *, float, float, float, int);
int onLabel(struct labelCtrl *, float, float);
void drawLabel(struct labelCtrl *, struct rendVars);
| 2.03125 | 2 |
2024-11-18T20:50:36.072125+00:00 | 2021-06-18T20:39:30 | c7927a2fb3ebe817c0bd4719988995f8bd74dd4a | {
"blob_id": "c7927a2fb3ebe817c0bd4719988995f8bd74dd4a",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-18T20:39:30",
"content_id": "06b4521f0b04bdfc627e1cf29facd0eb255afbec",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "952a1a80a48b03bb1a20df1ea34d513848f0c853",
"extension": "c",
"filename": "wrapper.c",
"fork_events_count": 1,
"gha_created_at": "2021-06-12T19:01:29",
"gha_event_created_at": "2021-06-18T20:39:31",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 376364891,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4791,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/openal/wrapper.c",
"provenance": "stackv2-0110.json.gz:219665",
"repo_name": "ted537/go-openal",
"revision_date": "2021-06-18T20:39:30",
"revision_id": "fa36a2aaf89ef19c7732a6eaff8ed5e99dca0fb7",
"snapshot_id": "9b2bb0c3061221b2a2dc374913eab81b3a1d0f44",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/ted537/go-openal/fa36a2aaf89ef19c7732a6eaff8ed5e99dca0fb7/openal/wrapper.c",
"visit_date": "2023-06-01T07:09:39.499863"
} | stackv2 | // Copyright 2009 Peter H. Froehlich. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "local.h"
#include "wrapper.h"
const char *walGetString(ALenum param) {
return alGetString(param);
}
void walGetBooleanv(ALenum param, void* data) {
alGetBooleanv(param, data);
}
void walGetIntegerv(ALenum param, void* data) {
alGetIntegerv(param, data);
}
void walGetFloatv(ALenum param, void* data) {
alGetFloatv(param, data);
}
void walGetDoublev(ALenum param, void* data) {
alGetDoublev(param, data);
}
// Listeners
void walListenerfv(ALenum param, const void* values) {
alListenerfv(param, values);
}
void walListeneriv(ALenum param, const void* values) {
alListeneriv(param, values);
}
ALfloat walGetListenerf(ALenum param) {
ALfloat result;
alGetListenerf(param, &result);
return result;
}
void walGetListener3f(ALenum param, void *value1, void *value2, void *value3) {
alGetListener3f(param, value1, value2, value3);
}
void walGetListenerfv(ALenum param, void* values) {
alGetListenerfv(param, values);
}
ALint walGetListeneri(ALenum param) {
ALint result;
alGetListeneri(param, &result);
return result;
}
void walGetListener3i(ALenum param, void *value1, void *value2, void *value3) {
alGetListener3i(param, value1, value2, value3);
}
void walGetListeneriv(ALenum param, void* values) {
alGetListeneriv(param, values);
}
// Sources
void walGenSources(ALsizei n, void *sources) {
alGenSources(n, sources);
}
void walDeleteSources(ALsizei n, const void *sources) {
alDeleteSources(n, sources);
}
void walSourcefv(ALuint sid, ALenum param, const void* values) {
alSourcefv(sid, param, values);
}
void walSourceiv(ALuint sid, ALenum param, const void* values) {
alSourceiv(sid, param, values);
}
ALfloat walGetSourcef(ALuint sid, ALenum param) {
ALfloat result;
alGetSourcef(sid, param, &result);
return result;
}
void walGetSource3f(ALuint sid, ALenum param, void *value1, void *value2, void *value3) {
alGetSource3f(sid, param, value1, value2, value3);
}
void walGetSourcefv(ALuint sid, ALenum param, void* values) {
alGetSourcefv(sid, param, values);
}
ALint walGetSourcei(ALuint sid, ALenum param) {
ALint result;
alGetSourcei(sid, param, &result);
return result;
}
void walGetSource3i(ALuint sid, ALenum param, void *value1, void *value2, void *value3) {
alGetSource3i(sid, param, value1, value2, value3);
}
void walGetSourceiv(ALuint sid, ALenum param, void* values) {
alGetSourceiv(sid, param, values);
}
void walSourcePlayv(ALsizei ns, const void *sids) {
alSourcePlayv(ns, sids);
}
void walSourceStopv(ALsizei ns, const void *sids) {
alSourceStopv(ns, sids);
}
void walSourceRewindv(ALsizei ns, const void *sids) {
alSourceRewindv(ns, sids);
}
void walSourcePausev(ALsizei ns, const void *sids) {
alSourcePausev(ns, sids);
}
void walSourceQueueBuffers(ALuint sid, ALsizei numEntries, const void *bids) {
alSourceQueueBuffers(sid, numEntries, bids);
}
void walSourceUnqueueBuffers(ALuint sid, ALsizei numEntries, void *bids) {
alSourceUnqueueBuffers(sid, numEntries, bids);
}
// Buffers
void walGenBuffers(ALsizei n, void *buffers) {
alGenBuffers(n, buffers);
}
void walDeleteBuffers(ALsizei n, const void *buffers) {
alDeleteBuffers(n, buffers);
}
void walBufferfv(ALuint bid, ALenum param, const void* values) {
alBufferfv(bid, param, values);
}
void walBufferiv(ALuint bid, ALenum param, const void* values) {
alBufferiv(bid, param, values);
}
ALfloat walGetBufferf(ALuint bid, ALenum param) {
ALfloat result;
alGetBufferf(bid, param, &result);
return result;
}
void walGetBuffer3f(ALuint bid, ALenum param, void *value1, void *value2, void *value3) {
alGetBuffer3f(bid, param, value1, value2, value3);
}
void walGetBufferfv(ALuint bid, ALenum param, void* values) {
alGetBufferfv(bid, param, values);
}
ALint walGetBufferi(ALuint bid, ALenum param) {
ALint result;
alGetBufferi(bid, param, &result);
return result;
}
void walGetBuffer3i(ALuint bid, ALenum param, void *value1, void *value2, void *value3) {
alGetBuffer3i(bid, param, value1, value2, value3);
}
void walGetBufferiv(ALuint bid, ALenum param, void* values) {
alGetBufferiv(bid, param, values);
}
// Singulars
ALuint walGenSource(void) {
ALuint source;
alGenSources(1, &source);
return source;
}
void walDeleteSource(ALuint source) {
alDeleteSources(1, &source);
}
ALuint walGenBuffer(void) {
ALuint buffer;
alGenBuffers(1, &buffer);
return buffer;
}
void walDeleteBuffer(ALuint buffer) {
alDeleteBuffers(1, &buffer);
}
void walSourceQueueBuffer(ALuint sid, ALuint bid) {
alSourceQueueBuffers(sid, 1, &bid);
}
ALuint walSourceUnqueueBuffer(ALuint sid) {
ALuint result;
alSourceUnqueueBuffers(sid, 1, &result);
return result;
}
| 2.03125 | 2 |
2024-11-18T20:50:36.185320+00:00 | 2017-04-27T01:09:17 | 9772e97abe7a804ca5a5328b4da644c3b3629cbd | {
"blob_id": "9772e97abe7a804ca5a5328b4da644c3b3629cbd",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-27T01:09:17",
"content_id": "b8c688f467f03173839288209c11be310c996894",
"detected_licenses": [
"MIT"
],
"directory_id": "c971407d6d5b2071f6ba156445fb271951d39648",
"extension": "c",
"filename": "utxo.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 89539589,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 572,
"license": "MIT",
"license_type": "permissive",
"path": "/lightningd/utxo.c",
"provenance": "stackv2-0110.json.gz:219794",
"repo_name": "monacoinproject/lightning",
"revision_date": "2017-04-27T01:09:17",
"revision_id": "8be8745c1f8d3222a9ad86103c2f3afb79f71420",
"snapshot_id": "fc18576916da25e25b0bcc157cd576cebf202348",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/monacoinproject/lightning/8be8745c1f8d3222a9ad86103c2f3afb79f71420/lightningd/utxo.c",
"visit_date": "2021-01-20T03:25:25.648203"
} | stackv2 | #include <lightningd/utxo.h>
#include <wire/wire.h>
void towire_utxo(u8 **pptr, const struct utxo *utxo)
{
towire_sha256_double(pptr, &utxo->txid);
towire_u32(pptr, utxo->outnum);
towire_u64(pptr, utxo->amount);
towire_u32(pptr, utxo->keyindex);
towire_bool(pptr, utxo->is_p2sh);
}
void fromwire_utxo(const u8 **ptr, size_t *max, struct utxo *utxo)
{
fromwire_sha256_double(ptr, max, &utxo->txid);
utxo->outnum = fromwire_u32(ptr, max);
utxo->amount = fromwire_u64(ptr, max);
utxo->keyindex = fromwire_u32(ptr, max);
utxo->is_p2sh = fromwire_bool(ptr, max);
}
| 2.015625 | 2 |
2024-11-18T20:50:36.236835+00:00 | 2020-12-16T17:46:51 | 3c98e4f8869114d388ab284b61fb000c4736ceef | {
"blob_id": "3c98e4f8869114d388ab284b61fb000c4736ceef",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-16T17:46:51",
"content_id": "c3fa9f3cc907cfee8bc7d665bd1e0fe8f99f321b",
"detected_licenses": [
"MIT"
],
"directory_id": "b090d02f34997fb29855b8ccf106dc4b5a611b40",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4035,
"license": "MIT",
"license_type": "permissive",
"path": "/Languages/C/main.c",
"provenance": "stackv2-0110.json.gz:219925",
"repo_name": "msujon-AMD/rocBLAS-Examples",
"revision_date": "2020-12-16T17:46:51",
"revision_id": "ae507d023042e30dbab84332761778525f16d453",
"snapshot_id": "fa272fdbc2824705c08082b49cd99edebf4e8571",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/msujon-AMD/rocBLAS-Examples/ae507d023042e30dbab84332761778525f16d453/Languages/C/main.c",
"visit_date": "2023-04-12T02:37:32.041771"
} | stackv2 | /*
Copyright (c) 2019-2020 Advanced Micro Devices, Inc. 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.
*/
#include <hip/hip_runtime.h>
#include <rocblas.h>
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "error_macros.h"
int main(int argc, char** argv)
{
size_t lda, ldb, lddev;
size_t rows, cols;
int n = 267;
if (argc > 1) n = atoi(argv[1]);
rows = n;
cols = 2*n;
lda = ldb = lddev = n;
typedef double data_type;
rocblas_handle handle;
rocblas_status rstatus = rocblas_create_handle(&handle);
CHECK_ROCBLAS_STATUS(rstatus);
hipStream_t test_stream;
rstatus = rocblas_get_stream( handle, &test_stream );
CHECK_ROCBLAS_STATUS(rstatus);
data_type* ha;
data_type* hb;
// allocate pinned memory to allow async memory transfer
CHECK_HIP_ERROR(hipHostMalloc((void**)&ha, lda * cols * sizeof(data_type), hipHostMallocMapped));
CHECK_HIP_ERROR(hipHostMalloc((void**)&hb, ldb * cols * sizeof(data_type), hipHostMallocMapped));
for(int i1 = 0; i1 < rows; i1++)
for(int i2 = 0; i2 < cols; i2++)
ha[i1 + i2 * lda] = 1.0;
data_type* da = 0;
data_type* db = 0;
data_type* dc = 0;
CHECK_HIP_ERROR(hipMalloc((void**)&da, lddev * cols * sizeof(data_type)));
CHECK_HIP_ERROR(hipMalloc((void**)&db, lddev * cols * sizeof(data_type)));
CHECK_HIP_ERROR(hipMalloc((void**)&dc, lddev * cols * sizeof(data_type)));
// upload asynchronously from pinned memory
rstatus = rocblas_set_matrix_async(rows, cols, sizeof(data_type), ha, lda, da, lddev, test_stream);
rstatus = rocblas_set_matrix_async(rows, cols, sizeof(data_type), ha, lda, db, lddev, test_stream);
// scalar arguments will be from host memory
rstatus = rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host);
CHECK_ROCBLAS_STATUS(rstatus);
data_type alpha = 1.0;
data_type beta = 2.0;
// invoke asynchronous computation
rstatus = rocblas_dgeam(handle, rocblas_operation_none, rocblas_operation_none, rows, cols, &alpha, da, lddev, &beta, db, lddev, dc, lddev);
CHECK_ROCBLAS_STATUS(rstatus);
// fetch results asynchronously to pinned memory
rstatus = rocblas_get_matrix_async(rows, cols, sizeof(data_type), dc, lddev, hb, ldb, test_stream);
CHECK_ROCBLAS_STATUS(rstatus);
// wait on transfer to be finished
CHECK_HIP_ERROR(hipStreamSynchronize(test_stream));
// check against expected results
bool fail = false;
for(int i1 = 0; i1 < rows; i1++)
for(int i2 = 0; i2 < cols; i2++)
if (hb[i1 + i2 * ldb] != 3.0*ha[i1 + i2 * lda])
fail = true;
CHECK_HIP_ERROR(hipFree(da));
CHECK_HIP_ERROR(hipFree(db));
CHECK_HIP_ERROR(hipFree(dc));
// free pinned memory
CHECK_HIP_ERROR(hipHostFree(ha));
CHECK_HIP_ERROR(hipHostFree(hb));
rstatus = rocblas_destroy_handle(handle);
CHECK_ROCBLAS_STATUS(rstatus);
fprintf(stdout, "%s\n", fail ? "FAIL" : "PASS");
return 0;
}
| 2.140625 | 2 |
2024-11-18T20:50:36.287224+00:00 | 2018-08-22T20:34:53 | 91fb9500b34852a6fca1e508290948d4f7dcaa54 | {
"blob_id": "91fb9500b34852a6fca1e508290948d4f7dcaa54",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-22T20:34:53",
"content_id": "683ff59d50761519b71239504a3abd18bfd30c40",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "8ee782ea7cc7a5c28ce3eaf494315b25628e81b9",
"extension": "c",
"filename": "ex22.c",
"fork_events_count": 0,
"gha_created_at": "2018-08-23T03:37:59",
"gha_event_created_at": "2018-08-23T03:38:00",
"gha_language": null,
"gha_license_id": null,
"github_id": 145795896,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11354,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/dm/impls/plex/examples/tests/ex22.c",
"provenance": "stackv2-0110.json.gz:220056",
"repo_name": "yangyang14641/petsc",
"revision_date": "2018-08-22T20:34:53",
"revision_id": "3b586aafbd9adb74d8cf97d861fd767185bb2947",
"snapshot_id": "28765910d63fa43868cf9605e08b66bc7f96a6d6",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/yangyang14641/petsc/3b586aafbd9adb74d8cf97d861fd767185bb2947/src/dm/impls/plex/examples/tests/ex22.c",
"visit_date": "2020-03-27T02:31:00.208658"
} | stackv2 |
const char help[] = "Test DMPlexCoordinatesToReference().\n\n";
#include <petscdm.h>
#include <petscdmplex.h>
static PetscErrorCode testIdentity(DM dm, PetscBool dmIsSimplicial, PetscInt cell, PetscRandom randCtx, PetscInt numPoints, PetscReal tol)
{
PetscInt i, j, dimC, dimR;
PetscReal *preimage, *mapped, *inverted;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = DMGetDimension(dm,&dimR);CHKERRQ(ierr);
ierr = DMGetCoordinateDim(dm,&dimC);CHKERRQ(ierr);
ierr = DMGetWorkArray(dm,dimR * numPoints,MPIU_REAL,&preimage);CHKERRQ(ierr);
ierr = DMGetWorkArray(dm,dimC * numPoints,MPIU_REAL,&mapped);CHKERRQ(ierr);
ierr = DMGetWorkArray(dm,dimR * numPoints,MPIU_REAL,&inverted);CHKERRQ(ierr);
for (i = 0; i < dimR * numPoints; i++) {
ierr = PetscRandomGetValueReal(randCtx, &preimage[i]);CHKERRQ(ierr);
}
if (dmIsSimplicial && dimR > 1) {
for (i = 0; i < numPoints; i++) {
for (j = 0; j < dimR; j++) {
PetscReal x = preimage[i * dimR + j];
PetscReal y = preimage[i * dimR + ((j + 1) % dimR)];
preimage[i * dimR + ((j + 1) % dimR)] = -1. + (y + 1.) * 0.5 * (1. - x);
}
}
}
ierr = DMPlexReferenceToCoordinates(dm,cell,numPoints,preimage,mapped);CHKERRQ(ierr);
ierr = DMPlexCoordinatesToReference(dm,cell,numPoints,mapped,inverted);CHKERRQ(ierr);
for (i = 0; i < numPoints; i++) {
PetscReal max = 0.;
for (j = 0; j < dimR; j++) {
max = PetscMax(max,PetscAbsReal(preimage[i * dimR + j] - inverted[i * dimR + j]));
}
if (max > tol) {
ierr = PetscPrintf(PETSC_COMM_SELF,"Bad inversion for cell %D with error %g (tol %g): (",cell,(double)max,(double)tol);CHKERRQ(ierr);
for (j = 0; j < dimR; j++) {
ierr = PetscPrintf(PETSC_COMM_SELF,"%+f",(double) preimage[i * dimR + j]);CHKERRQ(ierr);
if (j < dimR - 1) {
ierr = PetscPrintf(PETSC_COMM_SELF,",");CHKERRQ(ierr);
}
}
ierr = PetscPrintf(PETSC_COMM_SELF,") --> (");CHKERRQ(ierr);
for (j = 0; j < dimC; j++) {
ierr = PetscPrintf(PETSC_COMM_SELF,"%+f",(double) mapped[i * dimC + j]);CHKERRQ(ierr);
if (j < dimC - 1) {
ierr = PetscPrintf(PETSC_COMM_SELF,",");CHKERRQ(ierr);
}
}
ierr = PetscPrintf(PETSC_COMM_SELF,") --> (");CHKERRQ(ierr);
for (j = 0; j < dimR; j++) {
ierr = PetscPrintf(PETSC_COMM_SELF,"%+f",(double) inverted[i * dimR + j]);CHKERRQ(ierr);
if (j < dimR - 1) {
ierr = PetscPrintf(PETSC_COMM_SELF,",");CHKERRQ(ierr);
}
}
ierr = PetscPrintf(PETSC_COMM_SELF,")\n");CHKERRQ(ierr);
} else {
char strBuf[BUFSIZ] = {'\0'};
size_t offset = 0, count;
ierr = PetscSNPrintfCount(strBuf + offset,BUFSIZ-offset,"Good inversion for cell %D: (",&count,cell);CHKERRQ(ierr);
offset += count;
for (j = 0; j < dimR; j++) {
ierr = PetscSNPrintfCount(strBuf + offset,BUFSIZ-offset,"%+f",&count,(double) preimage[i * dimR + j]);CHKERRQ(ierr);
offset += count;
if (j < dimR - 1) {
ierr = PetscSNPrintfCount(strBuf + offset,BUFSIZ-offset,",",&count);CHKERRQ(ierr);
offset += count;
}
}
ierr = PetscSNPrintfCount(strBuf + offset,BUFSIZ-offset,") --> (",&count);CHKERRQ(ierr);
offset += count;
for (j = 0; j < dimC; j++) {
ierr = PetscSNPrintfCount(strBuf + offset,BUFSIZ-offset,"%+f",&count,(double) mapped[i * dimC + j]);CHKERRQ(ierr);
offset += count;
if (j < dimC - 1) {
ierr = PetscSNPrintfCount(strBuf + offset,BUFSIZ-offset,",",&count);CHKERRQ(ierr);
offset += count;
}
}
ierr = PetscSNPrintfCount(strBuf + offset,BUFSIZ-offset,") --> (",&count);CHKERRQ(ierr);
offset += count;
for (j = 0; j < dimR; j++) {
ierr = PetscSNPrintfCount(strBuf + offset,BUFSIZ-offset,"%+f",&count,(double) inverted[i * dimR + j]);CHKERRQ(ierr);
offset += count;
if (j < dimR - 1) {
ierr = PetscSNPrintfCount(strBuf + offset,BUFSIZ-offset,",",&count);CHKERRQ(ierr);
offset += count;
}
}
ierr = PetscSNPrintfCount(strBuf + offset,BUFSIZ-offset,")\n",&count);CHKERRQ(ierr);
ierr = PetscInfo1(dm,"%s",strBuf);CHKERRQ(ierr);
}
}
ierr = DMRestoreWorkArray(dm,dimR * numPoints,MPIU_REAL,&inverted);CHKERRQ(ierr);
ierr = DMRestoreWorkArray(dm,dimC * numPoints,MPIU_REAL,&mapped);CHKERRQ(ierr);
ierr = DMRestoreWorkArray(dm,dimR * numPoints,MPIU_REAL,&preimage);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscErrorCode identityEmbedding(PetscInt dim, PetscReal time, const PetscReal *x, PetscInt Nf, PetscScalar *u, void *ctx)
{
PetscInt i;
for (i = 0; i < dim; i++) {u[i] = x[i];};
return 0;
}
int main(int argc, char **argv)
{
PetscRandom randCtx;
PetscInt dim, dimC, isSimplex, isFE, numTests = 10;
PetscReal perturb = 0.1, tol = 10. * PETSC_SMALL;
PetscErrorCode ierr;
ierr = PetscInitialize(&argc,&argv,NULL,help);if (ierr) return ierr;
ierr = PetscRandomCreate(PETSC_COMM_SELF,&randCtx);CHKERRQ(ierr);
ierr = PetscRandomSetInterval(randCtx,-1.,1.);CHKERRQ(ierr);
ierr = PetscRandomSetFromOptions(randCtx);CHKERRQ(ierr);
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,NULL,"ex21",NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-vertex_perturbation","scale of random vertex distortion",NULL,perturb,&perturb,NULL);CHKERRQ(ierr);
ierr = PetscOptionsInt("-num_test_points","number of points to test",NULL,numTests,&numTests,NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnd();CHKERRQ(ierr);
for (dim = 1; dim <= 3; dim++) {
for (dimC = dim; dimC <= PetscMin(3,dim + 1); dimC++) {
for (isSimplex = 0; isSimplex < 2; isSimplex++) {
for (isFE = 0; isFE < 2; isFE++) {
DM dm;
Vec coords;
PetscScalar *coordArray;
PetscReal noise;
PetscInt i, n, order = 1;
ierr = DMPlexCreateReferenceCell(PETSC_COMM_SELF,dim,isSimplex ? PETSC_TRUE : PETSC_FALSE, &dm);CHKERRQ(ierr);
if (isFE) {
DM dmCoord;
PetscSpace sp;
PetscFE fe;
Vec localCoords;
PetscErrorCode (*funcs[1])(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *) = {identityEmbedding};
void *ctxs[1] = {NULL};
ierr = PetscFECreateDefault(PetscObjectComm((PetscObject) dm),dim,dim,isSimplex ? PETSC_TRUE : PETSC_FALSE,isSimplex ? NULL : "tensor_" ,PETSC_DEFAULT,&fe);CHKERRQ(ierr);
ierr = PetscFEGetBasisSpace(fe,&sp);CHKERRQ(ierr);
ierr = PetscSpaceGetOrder(sp,&order);CHKERRQ(ierr);
ierr = DMSetField(dm,0,(PetscObject)fe);CHKERRQ(ierr);
ierr = DMCreateLocalVector(dm,&localCoords);CHKERRQ(ierr);
ierr = VecSetDM(localCoords,NULL);CHKERRQ(ierr);
ierr = DMProjectFunctionLocal(dm,0,funcs,ctxs,INSERT_VALUES,localCoords);CHKERRQ(ierr);
ierr = DMClone(dm,&dmCoord);CHKERRQ(ierr);
ierr = DMSetField(dmCoord,0,(PetscObject)fe);CHKERRQ(ierr);
ierr = PetscFEDestroy(&fe);CHKERRQ(ierr);
ierr = DMSetCoordinateDM(dm,dmCoord);CHKERRQ(ierr);
ierr = DMDestroy(&dmCoord);CHKERRQ(ierr);
ierr = DMSetCoordinatesLocal(dm,localCoords);CHKERRQ(ierr);
ierr = VecDestroy(&localCoords);CHKERRQ(ierr);
}
ierr = PetscInfo4(dm,"Testing %s%D %DD mesh embedded in %DD\n",isSimplex ? "P" : "Q" , order, dim, dimC);CHKERRQ(ierr);
ierr = DMGetCoordinatesLocal(dm,&coords);CHKERRQ(ierr);
ierr = VecGetLocalSize(coords,&n);CHKERRQ(ierr);
if (dimC > dim) { /* reembed in higher dimension */
PetscSection sec, newSec;
PetscInt pStart, pEnd, p, i, newN;
Vec newVec;
DM coordDM;
PetscScalar *newCoordArray;
ierr = DMGetCoordinateSection(dm,&sec);CHKERRQ(ierr);
ierr = PetscSectionCreate(PetscObjectComm((PetscObject)sec),&newSec);CHKERRQ(ierr);
ierr = PetscSectionSetNumFields(newSec,1);CHKERRQ(ierr);
ierr = PetscSectionGetChart(sec,&pStart,&pEnd);CHKERRQ(ierr);
ierr = PetscSectionSetChart(newSec,pStart,pEnd);CHKERRQ(ierr);
for (p = pStart; p < pEnd; p++) {
PetscInt nDof;
ierr = PetscSectionGetDof(sec,p,&nDof);CHKERRQ(ierr);
if (nDof % dim) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Coordinate section point %D has %D dofs != 0 mod %D",p,nDof,dim);
ierr = PetscSectionSetDof(newSec,p,(nDof/dim)*dimC);CHKERRQ(ierr);
ierr = PetscSectionSetFieldDof(newSec,p,0,(nDof/dim)*dimC);CHKERRQ(ierr);
}
ierr = PetscSectionSetUp(newSec);CHKERRQ(ierr);
ierr = PetscSectionGetStorageSize(newSec,&newN);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF,newN,&newVec);CHKERRQ(ierr);
ierr = VecGetArray(newVec,&newCoordArray);CHKERRQ(ierr);
ierr = VecGetArray(coords,&coordArray);CHKERRQ(ierr);
for (i = 0; i < n / dim; i++) {
PetscInt j;
for (j = 0; j < dim; j++) {
newCoordArray[i * dimC + j] = coordArray[i * dim + j];
}
for (; j < dimC; j++) {
newCoordArray[i * dimC + j] = 0.;
}
}
ierr = VecRestoreArray(coords,&coordArray);CHKERRQ(ierr);
ierr = VecRestoreArray(newVec,&newCoordArray);CHKERRQ(ierr);
ierr = DMSetCoordinateDim(dm,dimC);CHKERRQ(ierr);
ierr = DMSetCoordinateSection(dm,dimC,newSec);CHKERRQ(ierr);
ierr = DMSetCoordinatesLocal(dm,newVec);CHKERRQ(ierr);
ierr = VecDestroy(&newVec);CHKERRQ(ierr);
ierr = PetscSectionDestroy(&newSec);CHKERRQ(ierr);
ierr = DMGetCoordinatesLocal(dm,&coords);CHKERRQ(ierr);
ierr = DMGetCoordinateDM(dm,&coordDM);CHKERRQ(ierr);
if (isFE) {
PetscFE fe;
ierr = PetscFECreateDefault(PetscObjectComm((PetscObject) dm),dim,dimC,isSimplex ? PETSC_TRUE : PETSC_FALSE,isSimplex ? NULL : "tensor_",PETSC_DEFAULT,&fe);CHKERRQ(ierr);
ierr = DMSetField(coordDM,0,(PetscObject)fe);CHKERRQ(ierr);
ierr = PetscFEDestroy(&fe);CHKERRQ(ierr);
}
ierr = DMSetCoordinateDim(coordDM,dimC);CHKERRQ(ierr);
ierr = VecGetLocalSize(coords,&n);CHKERRQ(ierr);
}
ierr = VecGetArray(coords,&coordArray);CHKERRQ(ierr);
for (i = 0; i < n; i++) {
ierr = PetscRandomGetValueReal(randCtx,&noise);CHKERRQ(ierr);
coordArray[i] += noise * perturb;
}
ierr = VecRestoreArray(coords,&coordArray);CHKERRQ(ierr);
ierr = DMSetCoordinatesLocal(dm, coords);CHKERRQ(ierr);
ierr = testIdentity(dm, isSimplex ? PETSC_TRUE : PETSC_FALSE, 0, randCtx, numTests, tol);CHKERRQ(ierr);
ierr = DMDestroy(&dm);CHKERRQ(ierr);
}
}
}
}
ierr = PetscRandomDestroy(&randCtx);CHKERRQ(ierr);
ierr = PetscFinalize();
return ierr;
}
/*TEST
test:
suffix: 0
args: -petscspace_order 2 -tensor_petscspace_order 2
TEST*/
| 2.25 | 2 |
2024-11-18T20:50:37.226611+00:00 | 2013-11-12T13:21:31 | 261da00ad421c4ddc09b1d60c476c0a7dc27a789 | {
"blob_id": "261da00ad421c4ddc09b1d60c476c0a7dc27a789",
"branch_name": "refs/heads/master",
"committer_date": "2013-11-12T13:21:31",
"content_id": "b69478b516e895464fd7b58e936ddf1b5c81e0d6",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "bdb92131f1549b87a1dd0917d8400f438825cdd0",
"extension": "c",
"filename": "tfec3.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7162,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/uart_nrf_demo/aeickho-tiny-fecc/tfec3.c",
"provenance": "stackv2-0110.json.gz:220315",
"repo_name": "aeickho/pix32_uart_demo",
"revision_date": "2013-11-12T13:21:31",
"revision_id": "353bb56c1384dc83f8aa3fb87d6f0b5454813aa5",
"snapshot_id": "1ee57732f31649e733cc83b399d89186d2304681",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aeickho/pix32_uart_demo/353bb56c1384dc83f8aa3fb87d6f0b5454813aa5/uart_nrf_demo/aeickho-tiny-fecc/tfec3.c",
"visit_date": "2020-04-06T03:32:27.656826"
} | stackv2 | /*
* Copyright 2012 Sebastian Gesemann. 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 SEBASTIAN GESEMANN ''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 SEBASTIAN GESEMANN 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 <assert.h>
#include "tfec3.h"
/*
* Generator polynomial: x^5 + x^1 + 1 (0x13)
* x^1 (2) generates all invertible elements.
*/
static const unsigned char inv_table[] = {
0x01, 0x9E, 0xDB, 0x76, 0xF2, 0xC5, 0xA4, 0x38
};
static unsigned char inv(unsigned char x)
{
unsigned char t;
x &= 0xF;
t = inv_table[x >> 1];
return (x&1) ? t & 0xF : t >> 4;
}
static tfec3_u32 twice(tfec3_u32 vec)
{
return ((vec & 0x77777777u) << 1) ^
((0x88888888u - ((vec & 0x88888888u) >> 3)) & 0x33333333u);
}
static tfec3_u32 scale(unsigned char a, tfec3_u32 vec)
{
int i;
tfec3_u32 acc = 0;
for (i=0; i<3; ++i) {
acc ^= (-(tfec3_u32)(a & 1)) & vec; vec = twice(vec); a >>= 1;
}
acc ^= (-(tfec3_u32)(a & 1)) & vec;
return acc;
}
static void block_blank(int words, tfec3_u32 x[])
{
int i;
for (i=0; i<words; ++i)
x[i] = 0;
}
static void block_scale_by_2(int words, tfec3_u32 x[])
{
int i;
for (i=0; i<words; ++i)
x[i] = twice(x[i]);
}
static void block_scale_by_a(int words, unsigned char a, tfec3_u32 x[])
{
int i;
if (a==1) return; /* nothing to do */
for (i=0; i<words; ++i)
x[i] = scale(a,x[i]);
}
static void block_xpy(int words, const tfec3_u32 x[], tfec3_u32 y[])
{
int i;
for (i=0; i<words; ++i)
y[i] ^= x[i];
}
static void block_axpy(int words, unsigned char a, const tfec3_u32 x[], tfec3_u32 y[])
{
int i;
if (a==0) return; /* nothing to do */
if (a==1) { block_xpy(words,x,y); return; }
for (i=0; i<words; ++i)
y[i] ^= scale(a,x[i]);
}
#if 0
static void block_xp2y(int words, const tfec3_u32 x[], tfec3_u32 y[])
{
int i;
for (i=0; i<words; ++i)
y[i] = twice(y[i]) ^ x[i];
}
#else
#define block_xp2y(w,x,y) do { \
block_scale_by_2((w),(y)); \
block_xpy((w),(x),(y)); \
} while(0)
#endif
static int find_index(int of, const int inlist[])
{
int i;
for (i=0; ; ++i)
if (inlist[i]==of) return i;
}
static void invert_inplace(int order, unsigned char *mat[], int words, tfec3_u32 *blocks[])
{
int o, c, r, rr;
unsigned char tmp;
for (o=0; o<order; ++o) {
if (mat[o][o]!=0) {
tmp = inv(mat[o][o]);
block_scale_by_a(words,tmp,blocks[o]);
for (c=o; c<order; ++c)
mat[o][c] = scale(tmp,mat[o][c]);
} else {
rr=0;
for (r=o+1; r<order; ++r)
if (mat[r][o]) {rr=r; break;}
assert(rr!=0);
tmp = inv(mat[rr][o]);
block_axpy(words,tmp,blocks[rr],blocks[o]);
for (c=o; c<order; ++c)
mat[o][c] ^= scale(tmp,mat[rr][c]);
}
assert(mat[o][o]==1);
for (r=0; r<order; ++r)
if (r!=o && mat[r][o]) {
tmp = mat[r][o];
block_axpy(words,tmp,blocks[o],blocks[r]);
for (c=o; c<order; ++c)
mat[r][c] ^= scale(tmp,mat[o][c]);
}
}
}
void tfec3_encode(int words, int blocks, int redundancy, tfec3_u32 *io[])
{
int b;
tfec3_u32 *p, *q, *r;
assert(blocks<=15);
assert(redundancy<=3);
p = redundancy>=1 ? io[blocks ] : 0;
q = redundancy>=2 ? io[blocks+1] : 0;
r = redundancy>=3 ? io[blocks+2] : 0;
if (p) block_blank(words,p);
if (r) block_blank(words,r);
for (b=0; b<blocks; ++b) {
if (p) block_xpy (words,io[b],p);
if (r) block_xp2y(words,io[b],r);
}
if (q) {
block_blank(words,q);
for (b=blocks; b-->0; ) {
block_xp2y(words,io[b],q);
}
}
}
int tfec3_decode(int words, int blocks, int redundancy,
const unsigned char valid[], tfec3_u32 *io[])
{
int b, c;
int misslist[3] = {0}; /* list of missing data blocks */
int missctr = 0; /* number of missing data blocks */
int order = 0; /* order of equation system that needs to be solved */
tfec3_u32 *partial_pqr[3] = {0};
unsigned char matrix[3][3] = {{0}};
unsigned char *mat[3] = {0};
assert(blocks<=15);
assert(redundancy<=3);
/* check which data blocks are missing... */
for (b=0; b<blocks; ++b) {
if (!valid[b]) {
if (missctr==redundancy) return 0; /* already too many missing */
misslist[missctr++] = b;
}
}
if (missctr==0) return 1; /* nothing to do */
/* check which redundancy blocks we can use for recovery... */
for (b=0; b<redundancy && order<missctr; ++b) {
if (valid[blocks+b]) {
partial_pqr[b] = io[misslist[order]];
mat[order] = matrix[b];
++order;
}
}
if (order<missctr) return 0; /* too many missing */
/* compute partial P, Q, R (excluding missing data blocks)
* in place of missing blocks and keep track of how the
* missing blocks would have contributed to P, Q, R in matrix...
*/
for (b=0; b<3; ++b)
if (partial_pqr[b]) block_blank(words,partial_pqr[b]);
if (partial_pqr[0] || partial_pqr[2])
for (b=0; b<blocks; ++b) {
for (c=0; c<missctr; ++c) matrix[2][c] = twice(matrix[2][c]);
if (valid[b]) {
if (partial_pqr[0]) block_xpy (words,io[b],partial_pqr[0]);
if (partial_pqr[2]) block_xp2y(words,io[b],partial_pqr[2]);
} else {
c = find_index(b,misslist);
matrix[0][c] ^= 1;
matrix[2][c] ^= 1;
if (partial_pqr[2]) block_scale_by_2(words,partial_pqr[2]);
}
}
if (partial_pqr[1])
for (b=blocks; b-->0; ) {
for (c=0; c<missctr; ++c) matrix[1][c] = twice(matrix[1][c]);
if (valid[b]) {
block_xp2y(words,io[b],partial_pqr[1]);
} else {
c = find_index(b,misslist);
matrix[1][c] = 1;
block_scale_by_2(words,partial_pqr[1]);
}
}
/* compute difference between partial P/Q/R and received P/Q/R */
for (b=0; b<3; ++b)
if (partial_pqr[b])
block_xpy(words,io[blocks+b],partial_pqr[b]);
/* strip null pointers from partial_pqr array */
for (b=0, c=0; b<order; ++b) {
while (!partial_pqr[c]) ++c;
partial_pqr[b] = partial_pqr[c++];
}
invert_inplace(order,mat,words,partial_pqr);
return 1;
}
| 2.359375 | 2 |
2024-11-18T20:50:37.316322+00:00 | 2019-08-02T14:36:57 | 950386c49560186e53f51bba6083241c737c3b4a | {
"blob_id": "950386c49560186e53f51bba6083241c737c3b4a",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-02T14:36:57",
"content_id": "de87c9193d93f2738e2ce7690bf58ce4c4f1d9cf",
"detected_licenses": [
"MIT"
],
"directory_id": "88b4bb7bb047da24982c7d985d78d8143e626cc0",
"extension": "c",
"filename": "friend.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 193114791,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 456,
"license": "MIT",
"license_type": "permissive",
"path": "/14.Structures&OtherDataForms/friend.c",
"provenance": "stackv2-0110.json.gz:220444",
"repo_name": "HuangStomach/C-primer-plus",
"revision_date": "2019-08-02T14:36:57",
"revision_id": "ecb24ab1ba3ec58e68cff2fce5049b328e84c24b",
"snapshot_id": "f26e1fad85a651bcc5c4b36bfe60b1e1cea7e991",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/HuangStomach/C-primer-plus/ecb24ab1ba3ec58e68cff2fce5049b328e84c24b/14.Structures&OtherDataForms/friend.c",
"visit_date": "2020-06-07T23:29:20.126880"
} | stackv2 | #include <stdio.h>
#define LEN 20
const char * msgs[5] = {
"A", "B", "C", "D", "E"
};
struct names {
char first[LEN];
char last[LEN];
};
struct guy {
struct names handle;
char favfood[LEN];
char job[LEN];
float income;
};
int main(void) {
struct guy fellow = {
{ "Ewen", "Villard" },
"grilled salmon",
"personality coach",
68112.00
};
/* skip some output */
return 0;
}
| 2.4375 | 2 |
2024-11-18T20:50:40.588424+00:00 | 2021-08-27T07:33:04 | d39402193dacfd58710b71496382bbbeab675980 | {
"blob_id": "d39402193dacfd58710b71496382bbbeab675980",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-27T07:33:04",
"content_id": "feedc2ada7976a3c98998c08d42d921e78a8fee2",
"detected_licenses": [
"MIT"
],
"directory_id": "fb93245ca6d4a795c9f91ea816169f7dbb187fb7",
"extension": "c",
"filename": "install.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 365431207,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2139,
"license": "MIT",
"license_type": "permissive",
"path": "/install.c",
"provenance": "stackv2-0110.json.gz:220963",
"repo_name": "TSP66/COINETTE",
"revision_date": "2021-08-27T07:33:04",
"revision_id": "e9e82a0fc4bbe682b96aca64ff9fc9b359d6f47f",
"snapshot_id": "9cad7ca0920130176865d820cfcca454035cc817",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TSP66/COINETTE/e9e82a0fc4bbe682b96aca64ff9fc9b359d6f47f/install.c",
"visit_date": "2023-07-15T04:24:16.921174"
} | stackv2 | //
// install.cpp
//
//
// Created by Tom Petty on 8/5/21.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "terminal_color.h"
void install_depedencies(void){
//Set color to black with white background
printf(BBLK);
printf(WHTB);
printf("Installing Depedencies: Python3, GMP, Fastecdsa");
printf(reset);
printf("\n \n");
//Set
printf(BWHT);
printf(BLUB);
system("");
printf("Installing Python3:");
system("");
int python3 = system("brew install python3");
if(python3 != -1){
printf(reset);
printf("\n");
printf(REDB);
printf(BWHT);
printf("Error installing Python3: Exiting");
//return -1;
}
else{
printf(reset);
printf("\n");
printf(GRNB);
printf(BWHT);
printf("Successfully installed Python3");
}
printf(reset);
printf("\n \n");
//Set
printf(BWHT);
printf(BLUB);
system("");
printf("Installing GMP:");
system("");
int gmp = system("brew install gmp");
if(gmp != -1){
printf(reset);
printf("\n");
printf(REDB);
printf(BWHT);
printf("Error installing GMP: Exiting");
//return -1;
}
else{
printf(reset);
printf("\n");
printf(GRNB);
printf(BWHT);
printf("Successfully installed GMP");
}
printf(reset);
printf("\n \n");
//Set
printf(BWHT);
printf(BLUB);
system("");
printf("Installing Fastecdsa:");
system("");
int fastecdsa = system("pip3 install fastecdsa");
if(fastecdsa != -1){
printf(reset);
printf("\n");
printf(REDB);
printf(BWHT);
printf("Error installing Fastecdsa: Exiting");
//return -1;
}
else{
printf(reset);
printf("\n");
printf(GRNB);
printf(BWHT);
printf("Successfully installed Fastecdsa");
}
}
int main(void){
install_depedencies();
return(0);
}
| 2.828125 | 3 |
2024-11-18T20:50:41.104577+00:00 | 2018-07-11T11:40:14 | bfac2b403abb34993d5a55c749cf6edef00ff24c | {
"blob_id": "bfac2b403abb34993d5a55c749cf6edef00ff24c",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-11T11:40:14",
"content_id": "2cd12fb4736b34fd62be01f0052d2c2740d7fdb6",
"detected_licenses": [
"MIT"
],
"directory_id": "dd8da3aa401818453ee919c3236616911cc46b60",
"extension": "c",
"filename": "Pid.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 23598,
"license": "MIT",
"license_type": "permissive",
"path": "/Software/RoboLib/Pid.c",
"provenance": "stackv2-0110.json.gz:221223",
"repo_name": "jasonhaominglo/McuMiniSumoRobot",
"revision_date": "2018-07-11T11:40:14",
"revision_id": "32cdc587b705597104c1f4ff73aef7d1aabef10f",
"snapshot_id": "cf871c5d0b13a25316a381b0b4b4cf21b2e731a1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jasonhaominglo/McuMiniSumoRobot/32cdc587b705597104c1f4ff73aef7d1aabef10f/Software/RoboLib/Pid.c",
"visit_date": "2022-02-03T15:42:45.695242"
} | stackv2 | /**
* \file
* \brief This is the implementation of the PID Module
* \author Erich Styger, erich.styger@hslu.ch
*/
#include "Platform.h"
#if PL_CONFIG_HAS_PID
#include "Pid.h"
#include "Motor.h"
#include "McuUtility.h"
#include "Reflectance.h"
#define PID_DEBUG 0 /* careful: this will slow down the PID loop frequency! */
#if PL_CONFIG_HAS_LINE_PID
static PID_Config lineFwConfig;
#endif
#if PL_CONFIG_GO_DEADEND_BW
static PID_Config lineBwConfig;
#endif
#if PL_CONFIG_HAS_POS_PID
static PID_Config posLeftConfig, posRightConfig;
#endif
#if PL_CONFIG_HAS_SPEED_PID
static PID_Config speedLeftConfig, speedRightConfig;
#endif
uint8_t PID_GetPIDConfig(PID_ConfigType config, PID_Config **confP) {
switch(config) {
#if PL_CONFIG_HAS_LINE_PID
case PID_CONFIG_LINE_FW:
*confP = &lineFwConfig; break;
#endif
#if PL_CONFIG_GO_DEADEND_BW
case PID_CONFIG_LINE_BW:
*confP = &lineBwConfig; break;
#endif
case PID_CONFIG_POS_LEFT:
*confP = &posLeftConfig; break;
case PID_CONFIG_POS_RIGHT:
*confP = &posRightConfig; break;
case PID_CONFIG_SPEED_LEFT:
*confP = &speedLeftConfig; break;
case PID_CONFIG_SPEED_RIGHT:
*confP = &speedRightConfig; break;
default:
*confP = NULL;
return ERR_FAILED;
}
return ERR_OK;
}
#if PL_CONFIG_HAS_SPEED_PID || PL_CONFIG_HAS_POS_PID || PL_CONFIG_HAS_LINE_PID
static int32_t PID(int32_t currVal, int32_t setVal, PID_Config *config) {
int32_t error;
int32_t pid;
/* perform PID closed control loop calculation */
error = setVal-currVal; /* calculate error */
pid = (error*config->pFactor100)/100; /* P part */
config->integral += error; /* integrate error */
if (config->integral>config->iAntiWindup) {
config->integral = config->iAntiWindup;
} else if (config->integral<-config->iAntiWindup) {
config->integral = -config->iAntiWindup;
}
#if 1 /* see http://brettbeauregard.com/blog/2011/04/improving-the-beginner%E2%80%99s-pid-reset-windup/ */
{
int32_t max;
max = 0xffff; /* max value of PWM */
if (config->integral > max) {
config->integral = max;
} else if (config->integral < -max) {
config->integral = -max;
}
}
#endif
pid += (config->integral*config->iFactor100)/100; /* add I part */
pid += ((error-config->lastError)*config->dFactor100)/100; /* add D part */
config->lastError = error; /* remember for next iteration of D part */
return pid;
}
#endif
#if PL_CONFIG_HAS_LINE_PID
static int32_t Limit(int32_t val, int32_t minVal, int32_t maxVal) {
if (val<minVal) {
return minVal;
} else if (val>maxVal) {
return maxVal;
}
return val;
}
#if 0
static MOT_Direction AbsSpeed(int32_t *speedP) {
if (*speedP<0) {
*speedP = -(*speedP);
return MOT_DIR_BACKWARD;
}
return MOT_DIR_FORWARD;
}
#endif
#if 0
/*! \brief returns error (always positive) percent */
static uint8_t errorWithinPercent(int32_t error) {
if (error<0) {
error = -error;
}
error = error/(REF_MAX_LINE_VALUE/2/100);
if (error>100) {
error = 100;
}
return error;
}
#endif
#if PL_APP_LINE_FOLLOWING || PL_APP_LINE_MAZE
static void PID_LineCfg(uint16_t currLine, uint16_t setLine, uint16_t currLineWidth, bool forward, PID_Config *config) {
int32_t pid, speed, speedL, speedR;
#if PID_DEBUG
unsigned char buf[16];
static uint8_t cnt = 0;
#endif
// uint8_t errorPercent;
MOT_Direction directionL=MOT_DIR_FORWARD, directionR=MOT_DIR_FORWARD;
(void)currLineWidth;
pid = PID(currLine, setLine, config);
//errorPercent = errorWithinPercent(currLine-setLine);
/* transform into different speed for motors. The PID is used as difference value to the motor PWM */
if (!forward) { /* going backward */
/* need to do it slow as sensor is on the 'back', and we cannot usual turns to get the sensor back 'on line' */
speed = ((int32_t)config->maxSpeedPercent)*(0xffff/100)*6/10; /* %60 */
pid = Limit(pid, -speed, speed);
if (pid<0) { /* turn right */
speedR = speed;
speedL = speed-pid;
} else { /* turn left */
speedR = speed+pid;
speedL = speed;
}
#if 0 /* simple differential steering */
} else {
speed = ((int32_t)config->maxSpeedPercent)*(0xffff/100); /* 100% */
pid = Limit(pid, -speed, speed);
if (pid<0) { /* turn right */
speedR = speed;
speedL = speed-pid;
} else { /* turn left */
speedR = speed+pid;
speedL = speed;
}
}
#elif 1 || PL_DO_MINT /* aggressive line following! */
} else {
speed = ((int32_t)config->maxSpeedPercent)*(0xffff/100); /* scale to base speed */
if (pid<0) { /* turn right */
speedR = speed+pid; /* decrease speed */
speedL = speed-pid; /* increase speed */
} else { /* turn left */
speedR = speed+pid; /* increase speed */
speedL = speed-pid; /* decrease speed */
}
}
#else
} else if (errorPercent <= 20) { /* pretty on center: move forward both motors with base speed */
speed = ((int32_t)config->maxSpeedPercent)*(0xffff/100); /* 100% */
pid = Limit(pid, -speed, speed);
if (pid<0) { /* turn right */
speedR = speed;
speedL = speed-pid;
} else { /* turn left */
speedR = speed+pid;
speedL = speed;
}
} else if (errorPercent <= 30) {
/* outside left/right halve position from center, slow down one motor and speed up the other */
// speed = ((int32_t)config->maxSpeedPercent)*(0xffff/100)*10/10; /* 80% */
speed = 50*(0xffff/100);
pid = Limit(pid, -speed, speed);
if (pid<0) { /* turn right */
speedR = speed+pid; /* decrease speed */
speedL = speed-pid; /* increase speed */
} else { /* turn left */
speedR = speed+pid; /* increase speed */
speedL = speed-pid; /* decrease speed */
}
} else if (errorPercent <= 60) {
// speed = ((int32_t)config->maxSpeedPercent)*(0xffff/100)*10/10; /* %70 */
speed = 80*(0xffff/100);
pid = Limit(pid, -speed, speed);
if (pid<0) { /* turn right */
speedR = 0 /*maxSpeed+pid*/; /* decrease speed */
speedL = speed-pid; /* increase speed */
} else { /* turn left */
speedR = speed+pid; /* increase speed */
speedL = 0 /*maxSpeed-pid*/; /* decrease speed */
}
} else {
/* line is far to the left or right: use backward motor motion */
// speed = ((int32_t)config->maxSpeedPercent)*(0xffff/100)*10/10; /* %100 */
speed = 100*(0xffff/100);
if (pid<0) { /* turn right */
speedR = -speed+pid; /* decrease speed */
speedL = speed-pid; /* increase speed */
} else { /* turn left */
speedR = speed+pid; /* increase speed */
speedL = -speed-pid; /* decrease speed */
}
speedL = Limit(speedL, -speed, speed);
speedR = Limit(speedR, -speed, speed);
directionL = AbsSpeed(&speedL);
directionR = AbsSpeed(&speedR);
}
#endif
/* speed is now always positive, make sure it is within 16bit PWM boundary */
if (speedL>0xFFFF) {
speedL = 0xFFFF;
} else if (speedL<0) {
speedL = 0;
}
if (speedR>0xFFFF) {
speedR = 0xFFFF;
} else if (speedR<0) {
speedR = 0;
}
if (!forward) { /* swap direction/speed */
if (directionL==MOT_DIR_FORWARD) {
directionL=MOT_DIR_BACKWARD;
} else {
directionL=MOT_DIR_FORWARD;
}
if (directionR==MOT_DIR_FORWARD) {
directionR=MOT_DIR_BACKWARD;
} else {
directionR=MOT_DIR_FORWARD;
}
}
/* send new speed values to motor */
MOT_SetVal(MOT_GetMotorHandle(MOT_MOTOR_LEFT), 0xFFFF-speedL); /* PWM is low active */
MOT_SetDirection(MOT_GetMotorHandle(MOT_MOTOR_LEFT), directionL);
MOT_SetVal(MOT_GetMotorHandle(MOT_MOTOR_RIGHT), 0xFFFF-speedR); /* PWM is low active */
MOT_SetDirection(MOT_GetMotorHandle(MOT_MOTOR_RIGHT), directionR);
#if PID_DEBUG /* debug diagnostic */
{
cnt++;
if (cnt>10) { /* limit number of messages to the console */
McuShell_StdIO_OutErr_FctType ioOut = SHELL_GetStdio()->stdOut;
cnt = 0;
McuShell_SendStr((unsigned char*)"line:", ioOut);
buf[0] = '\0';
McuUtility_strcatNum16u(buf, sizeof(buf), currLine);
McuShell_SendStr(buf, ioOut);
McuShell_SendStr((unsigned char*)" sum:", ioOut);
buf[0] = '\0';
McuUtility_strcatNum32Hex(buf, sizeof(buf), integral);
McuShell_SendStr(buf, ioOut);
McuShell_SendStr((unsigned char*)" left:", ioOut);
McuShell_SendStr(directionL==MOT_DIR_FORWARD?(unsigned char*)"fw ":(unsigned char*)"bw ", ioOut);
buf[0] = '\0';
McuUtility_strcatNum16Hex(buf, sizeof(buf), speedL);
McuShell_SendStr(buf, ioOut);
McuShell_SendStr((unsigned char*)" right:", ioOut);
McuShell_SendStr(directionR==MOT_DIR_FORWARD?(unsigned char*)"fw ":(unsigned char*)"bw ", ioOut);
buf[0] = '\0';
McuUtility_strcatNum16Hex(buf, sizeof(buf), speedR);
McuShell_SendStr(buf, ioOut);
McuShell_SendStr((unsigned char*)"\r\n", ioOut);
}
}
#endif
}
#endif //PL_APP_LINE_FOLLOWING || PL_APP_LINE_MAZE
#endif /* PL_HAS_LINE_SENSOR */
#if PL_APP_LINE_FOLLOWING || PL_APP_LINE_MAZE
void PID_Line(uint16_t currLinePos, uint16_t setLinePos, uint16_t currLineWidth, bool forward) {
#if PL_CONFIG_HAS_LINE_PID
#if PL_CONFIG_GO_DEADEND_BW
if (forward) {
PID_LineCfg(currLinePos, setLinePos, forward, &lineFwConfig);
} else {
PID_LineCfg(currLinePos, setLinePos, forward, &lineBwConfig);
}
#else
(void)forward; /* not used */
PID_LineCfg(currLinePos, setLinePos, currLineWidth, forward, &lineFwConfig);
#endif
#endif
}
#endif
#if PL_CONFIG_HAS_POS_PID
static void PID_PosCfg(int32_t currPos, int32_t setPos, bool isLeft, PID_Config *config) {
int32_t speed;
MOT_Direction direction=MOT_DIR_FORWARD;
MOT_MotorDevice *motHandle;
#if PL_CONFIG_HIGH_RES_ENCODER
int error;
error = setPos-currPos;
if (error>-10 && error<10) { /* avoid jitter around zero */
setPos = currPos;
}
#endif
speed = PID(currPos, setPos, config);
/* transform into motor speed */
speed *= 1000; /* scale PID, otherwise we need high PID constants */
if (speed>=0) {
direction = MOT_DIR_FORWARD;
} else { /* negative, make it positive */
speed = -speed; /* make positive */
direction = MOT_DIR_BACKWARD;
}
/* speed is now always positive, make sure it is within 16bit PWM boundary */
if (speed>0xFFFF) {
speed = 0xFFFF;
}
/* limit speed to maximum value */
speed = (speed*config->maxSpeedPercent)/100;
/* send new speed values to motor */
if (isLeft) {
motHandle = MOT_GetMotorHandle(MOT_MOTOR_LEFT);
} else {
motHandle = MOT_GetMotorHandle(MOT_MOTOR_RIGHT);
}
#if 0
MOT_SetVal(motHandle, 0xFFFF-speed); /* PWM is low active */
#else
MOT_SetVal(motHandle, speed); /* PWM is high active */
#endif
MOT_SetDirection(motHandle, direction);
MOT_UpdatePercent(motHandle, direction);
}
void PID_Pos(int32_t currPos, int32_t setPos, bool isLeft) {
if (isLeft) {
PID_PosCfg(currPos, setPos, isLeft, &posLeftConfig);
} else {
PID_PosCfg(currPos, setPos, isLeft, &posRightConfig);
}
}
#endif /* PL_CONFIG_HAS_POS_PID */
#if PL_CONFIG_HAS_SPEED_PID
static void PID_SpeedCfg(int32_t currSpeed, int32_t setSpeed, bool isLeft, PID_Config *config) {
int32_t speed;
MOT_Direction direction=MOT_DIR_FORWARD;
MOT_MotorDevice *motHandle;
if (setSpeed==0) { /* \todo Actually this test is more of a hack, should not be needed! */
speed = 0;
/* reset PID I and D values */
config->integral = 0;
config->lastError = 0;
} else {
speed = PID(currSpeed, setSpeed, config);
}
if (speed>=0) {
direction = MOT_DIR_FORWARD;
} else { /* negative, make it positive */
speed = -speed; /* make positive */
direction = MOT_DIR_BACKWARD;
}
/* speed shall be positive here, make sure it is within 16bit PWM boundary */
if (speed>0xFFFF) {
speed = 0xFFFF;
}
/* send new speed values to motor */
if (isLeft) {
motHandle = MOT_GetMotorHandle(MOT_MOTOR_LEFT);
} else {
motHandle = MOT_GetMotorHandle(MOT_MOTOR_RIGHT);
}
#if 0
MOT_SetVal(motHandle, 0xFFFF-speed); /* PWM is low active */
#else
MOT_SetVal(motHandle, speed); /* PWM is high active */
#endif
MOT_SetDirection(motHandle, direction);
MOT_UpdatePercent(motHandle, direction);
}
void PID_Speed(int32_t currSpeed, int32_t setSpeed, bool isLeft) {
if (isLeft) {
PID_SpeedCfg(currSpeed, setSpeed, isLeft, &speedLeftConfig);
} else {
PID_SpeedCfg(currSpeed, setSpeed, isLeft, &speedRightConfig);
}
}
#endif /* PL_CONFIG_HAS_SPEED_PID */
#if PL_CONFIG_HAS_SHELL
static void PID_PrintHelp(const McuShell_StdIOType *io) {
McuShell_SendHelpStr((unsigned char*)"pid", (unsigned char*)"Group of PID commands\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Shows PID help or status\r\n", io->stdOut);
#if PL_CONFIG_HAS_POS_PID
McuShell_SendHelpStr((unsigned char*)" pos (p|i|d|w) <value>", (unsigned char*)"Sets P, I, D or anti-Windup position value\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" pos speed <value>", (unsigned char*)"Maximum speed % value\r\n", io->stdOut);
#endif
#if PL_CONFIG_HAS_SPEED_PID
McuShell_SendHelpStr((unsigned char*)" speed (L|R) (p|i|d|w) <value>", (unsigned char*)"Sets P, I, D or anti-Windup position value\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" speed (L|R) speed <value>", (unsigned char*)"Maximum speed % value\r\n", io->stdOut);
#endif
#if PL_CONFIG_HAS_LINE_PID
McuShell_SendHelpStr((unsigned char*)" fw (p|i|d|w) <value>", (unsigned char*)"Sets P, I, D or anti-Windup line value\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" fw speed <value>", (unsigned char*)"Maximum speed % value\r\n", io->stdOut);
#endif
#if PL_CONFIG_GO_DEADEND_BW
McuShell_SendHelpStr((unsigned char*)" bw (p|i|d|w) <value>", (unsigned char*)"Sets P, I, D or anti-Windup backward value\r\n", io->stdOut);
McuShell_SendHelpStr((unsigned char*)" bw speed <value>", (unsigned char*)"Maximum backward speed % value\r\n", io->stdOut);
#endif
}
#if PL_CONFIG_HAS_SPEED_PID || PL_CONFIG_HAS_POS_PID || PL_CONFIG_HAS_LINE_PID
static void PrintPIDstatus(PID_Config *config, const unsigned char *kindStr, const McuShell_StdIOType *io) {
unsigned char buf[48];
unsigned char kindBuf[16];
McuUtility_strcpy(kindBuf, sizeof(buf), (unsigned char*)" ");
McuUtility_strcat(kindBuf, sizeof(buf), kindStr);
McuUtility_strcat(kindBuf, sizeof(buf), (unsigned char*)" PID");
McuUtility_strcpy(buf, sizeof(buf), (unsigned char*)"p: ");
McuUtility_strcatNum32s(buf, sizeof(buf), config->pFactor100);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" i: ");
McuUtility_strcatNum32s(buf, sizeof(buf), config->iFactor100);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)" d: ");
McuUtility_strcatNum32s(buf, sizeof(buf), config->dFactor100);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr(kindBuf, buf, io->stdOut);
McuUtility_strcpy(kindBuf, sizeof(buf), (unsigned char*)" ");
McuUtility_strcat(kindBuf, sizeof(buf), kindStr);
McuUtility_strcat(kindBuf, sizeof(buf), (unsigned char*)" windup");
McuUtility_Num32sToStr(buf, sizeof(buf), config->iAntiWindup);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr(kindBuf, buf, io->stdOut);
McuUtility_strcpy(kindBuf, sizeof(buf), (unsigned char*)" ");
McuUtility_strcat(kindBuf, sizeof(buf), kindStr);
McuUtility_strcat(kindBuf, sizeof(buf), (unsigned char*)" error");
McuUtility_Num32sToStr(buf, sizeof(buf), config->lastError);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr(kindBuf, buf, io->stdOut);
McuUtility_strcpy(kindBuf, sizeof(buf), (unsigned char*)" ");
McuUtility_strcat(kindBuf, sizeof(buf), kindStr);
McuUtility_strcat(kindBuf, sizeof(buf), (unsigned char*)" integral");
McuUtility_Num32sToStr(buf, sizeof(buf), config->integral);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"\r\n");
McuShell_SendStatusStr(kindBuf, buf, io->stdOut);
McuUtility_strcpy(kindBuf, sizeof(buf), (unsigned char*)" ");
McuUtility_strcat(kindBuf, sizeof(buf), kindStr);
McuUtility_strcat(kindBuf, sizeof(buf), (unsigned char*)" speed");
McuUtility_Num8uToStr(buf, sizeof(buf), config->maxSpeedPercent);
McuUtility_strcat(buf, sizeof(buf), (unsigned char*)"%\r\n");
McuShell_SendStatusStr(kindBuf, buf, io->stdOut);
}
#endif
static void PID_PrintStatus(const McuShell_StdIOType *io) {
#if PL_CONFIG_HAS_LINE_PID || PL_CONFIG_GO_DEADEND_BW || PL_CONFIG_HAS_POS_PID || PL_CONFIG_HAS_SPEED_PID
McuShell_SendStatusStr((unsigned char*)"pid", (unsigned char*)"\r\n", io->stdOut);
#endif
#if PL_CONFIG_HAS_LINE_PID
PrintPIDstatus(&lineFwConfig, (unsigned char*)"fw", io);
#endif
#if PL_CONFIG_GO_DEADEND_BW
PrintPIDstatus(&lineBwConfig, (unsigned char*)"bw", io);
#endif
#if PL_CONFIG_HAS_POS_PID
PrintPIDstatus(&posLeftConfig, (unsigned char*)"pos L", io);
PrintPIDstatus(&posRightConfig, (unsigned char*)"pos R", io);
#endif
#if PL_CONFIG_HAS_SPEED_PID
PrintPIDstatus(&speedLeftConfig, (unsigned char*)"speed L", io);
PrintPIDstatus(&speedRightConfig, (unsigned char*)"speed R", io);
#endif
}
#if PL_CONFIG_HAS_SPEED_PID || PL_CONFIG_HAS_POS_PID || PL_CONFIG_HAS_LINE_PID
static uint8_t ParsePidParameter(PID_Config *config, const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io) {
const unsigned char *p;
uint32_t val32u;
uint8_t val8u;
uint8_t res = ERR_OK;
if (McuUtility_strncmp((char*)cmd, (char*)"p ", sizeof("p ")-1)==0) {
p = cmd+sizeof("p");
if (McuUtility_ScanDecimal32uNumber(&p, &val32u)==ERR_OK) {
config->pFactor100 = val32u;
*handled = TRUE;
} else {
McuShell_SendStr((unsigned char*)"Wrong argument\r\n", io->stdErr);
res = ERR_FAILED;
}
} else if (McuUtility_strncmp((char*)cmd, (char*)"i ", sizeof("i ")-1)==0) {
p = cmd+sizeof("i");
if (McuUtility_ScanDecimal32uNumber(&p, &val32u)==ERR_OK) {
config->iFactor100 = val32u;
*handled = TRUE;
} else {
McuShell_SendStr((unsigned char*)"Wrong argument\r\n", io->stdErr);
res = ERR_FAILED;
}
} else if (McuUtility_strncmp((char*)cmd, (char*)"d ", sizeof("d ")-1)==0) {
p = cmd+sizeof("d");
if (McuUtility_ScanDecimal32uNumber(&p, &val32u)==ERR_OK) {
config->dFactor100 = val32u;
*handled = TRUE;
} else {
McuShell_SendStr((unsigned char*)"Wrong argument\r\n", io->stdErr);
res = ERR_FAILED;
}
} else if (McuUtility_strncmp((char*)cmd, (char*)"w ", sizeof("w ")-1)==0) {
p = cmd+sizeof("w");
if (McuUtility_ScanDecimal32uNumber(&p, &val32u)==ERR_OK) {
config->iAntiWindup = val32u;
*handled = TRUE;
} else {
McuShell_SendStr((unsigned char*)"Wrong argument\r\n", io->stdErr);
res = ERR_FAILED;
}
} else if (McuUtility_strncmp((char*)cmd, (char*)"speed ", sizeof("speed ")-1)==0) {
p = cmd+sizeof("speed");
if (McuUtility_ScanDecimal8uNumber(&p, &val8u)==ERR_OK && val8u<=100) {
config->maxSpeedPercent = val8u;
*handled = TRUE;
} else {
McuShell_SendStr((unsigned char*)"Wrong argument\r\n", io->stdErr);
res = ERR_FAILED;
}
}
return res;
}
#endif
uint8_t PID_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io) {
uint8_t res = ERR_OK;
if (McuUtility_strcmp((char*)cmd, (char*)McuShell_CMD_HELP)==0 || McuUtility_strcmp((char*)cmd, (char*)"pid help")==0) {
PID_PrintHelp(io);
*handled = TRUE;
} else if (McuUtility_strcmp((char*)cmd, (char*)McuShell_CMD_STATUS)==0 || McuUtility_strcmp((char*)cmd, (char*)"pid status")==0) {
PID_PrintStatus(io);
*handled = TRUE;
#if PL_CONFIG_HAS_LINE_PID
} else if (McuUtility_strncmp((char*)cmd, (char*)"pid fw ", sizeof("pid fw ")-1)==0) {
res = ParsePidParameter(&lineFwConfig, cmd+sizeof("pid fw ")-1, handled, io);
#endif
#if PL_CONFIG_GO_DEADEND_BW
} else if (McuUtility_strncmp((char*)cmd, (char*)"pid bw ", sizeof("pid bw ")-1)==0) {
res = ParsePidParameter(&lineBwConfig, cmd+sizeof("pid bw ")-1, handled, io);
#endif
#if PL_CONFIG_HAS_POS_PID
} else if (McuUtility_strncmp((char*)cmd, (char*)"pid pos ", sizeof("pid pos ")-1)==0) {
res = ParsePidParameter(&posLeftConfig, cmd+sizeof("pid pos ")-1, handled, io);
if (res==ERR_OK) {
res = ParsePidParameter(&posRightConfig, cmd+sizeof("pid pos ")-1, handled, io);
}
#endif
#if PL_CONFIG_HAS_SPEED_PID
} else if (McuUtility_strncmp((char*)cmd, (char*)"pid speed L ", sizeof("pid speed L ")-1)==0) {
res = ParsePidParameter(&speedLeftConfig, cmd+sizeof("pid speed L ")-1, handled, io);
} else if (McuUtility_strncmp((char*)cmd, (char*)"pid speed R ", sizeof("pid speed R ")-1)==0) {
res = ParsePidParameter(&speedRightConfig, cmd+sizeof("pid speed R ")-1, handled, io);
#endif
}
return res;
}
#endif /* PL_CONFIG_HAS_SHELL */
void PID_Start(void) {
#if PL_CONFIG_HAS_LINE_PID
lineFwConfig.lastError = 0;
lineFwConfig.integral = 0;
#endif
#if PL_CONFIG_GO_DEADEND_BW
lineBwConfig.lastError = 0;
lineBwConfig.integral = 0;
#endif
#if PL_CONFIG_HAS_POS_PID
posLeftConfig.lastError = 0;
posLeftConfig.integral = 0;
posRightConfig.lastError = 0;
posRightConfig.integral = 0;
#endif
#if PL_CONFIG_HAS_SPEED_PID
speedLeftConfig.lastError = 0;
speedLeftConfig.integral = 0;
speedRightConfig.lastError = 0;
speedRightConfig.integral = 0;
#endif
}
void PID_Deinit(void) {
}
void PID_Init(void) {
#if PL_CONFIG_HAS_LINE_PID
lineFwConfig.pFactor100 = 0;
lineFwConfig.iFactor100 = 0;
lineFwConfig.dFactor100 = 0;
lineFwConfig.iAntiWindup = 0;
lineFwConfig.maxSpeedPercent = 0;
lineFwConfig.lastError = 0;
lineFwConfig.integral = 0;
lineFwConfig.lastError = 0;
lineFwConfig.integral = 0;
#if PL_CONFIG_GO_DEADEND_BW
lineBwConfig.param = 0;
lineBwConfig.pFactor100 = 0;
lineBwConfig.iFactor100 = 0;
lineBwConfig.dFactor100 = 0;
lineBwConfig.iAntiWindup = 0;
lineBwConfig.maxSpeedPercent = 0;
lineBwConfig.lastError = 0;
lineBwConfig.integral = 0;
#endif
#endif /* PL_CONFIG_HAS_LINE_PID */
#if PL_CONFIG_HAS_POS_PID
posLeftConfig.pFactor100 = 0;
posLeftConfig.iFactor100 = 0;
posLeftConfig.dFactor100 = 0;
posLeftConfig.iAntiWindup = 0;
posLeftConfig.maxSpeedPercent = 0;
posLeftConfig.lastError = 0;
posLeftConfig.integral = 0;
posRightConfig.pFactor100 = posLeftConfig.pFactor100;
posRightConfig.iFactor100 = posLeftConfig.iFactor100;
posRightConfig.dFactor100 = posLeftConfig.dFactor100;
posRightConfig.iAntiWindup = posLeftConfig.iAntiWindup;
posRightConfig.maxSpeedPercent = posLeftConfig.maxSpeedPercent;
posRightConfig.lastError = posLeftConfig.lastError;
posRightConfig.integral = posLeftConfig.integral;
#endif
#if PL_CONFIG_HAS_SPEED_PID
speedLeftConfig.pFactor100 = 0;
speedLeftConfig.iFactor100 = 0;
speedLeftConfig.dFactor100 = 0;
speedLeftConfig.iAntiWindup = 0;
speedLeftConfig.maxSpeedPercent = 0;
speedLeftConfig.lastError = 0;
speedLeftConfig.integral = 0;
speedRightConfig.pFactor100 = speedLeftConfig.pFactor100;
speedRightConfig.iFactor100 = speedLeftConfig.iFactor100;
speedRightConfig.dFactor100 = speedLeftConfig.dFactor100;
speedRightConfig.iAntiWindup = speedLeftConfig.iAntiWindup;
speedRightConfig.maxSpeedPercent = speedLeftConfig.maxSpeedPercent;
speedRightConfig.lastError = speedLeftConfig.lastError;
speedRightConfig.integral = speedLeftConfig.integral;
#endif
}
#endif /* PL_HAS_PID */
| 2.421875 | 2 |
2024-11-18T20:50:41.872038+00:00 | 2021-01-11T12:11:41 | 3356d0be064ffb6b00d1bfe0b19d7ec3b3872afa | {
"blob_id": "3356d0be064ffb6b00d1bfe0b19d7ec3b3872afa",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-11T12:11:41",
"content_id": "0aa79dcc8e40f31a58b09a70f223dd9272b41416",
"detected_licenses": [
"MIT"
],
"directory_id": "39a10ceeb69ea9d650090305607b2a171b73041f",
"extension": "c",
"filename": "ins_del_dis_linkedlist.c",
"fork_events_count": 143,
"gha_created_at": "2019-06-03T22:36:31",
"gha_event_created_at": "2023-01-04T21:47:48",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 190091719,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2949,
"license": "MIT",
"license_type": "permissive",
"path": "/source/snippets/c/ins_del_dis_linkedlist.c",
"provenance": "stackv2-0110.json.gz:221482",
"repo_name": "rickwest/devsnippets",
"revision_date": "2021-01-11T12:11:41",
"revision_id": "6e2a48494b385e807eda9d7a64512255eb8fe7ff",
"snapshot_id": "e73681f1c6e61c7f5fd639f05aac24f43b9e847c",
"src_encoding": "UTF-8",
"star_events_count": 70,
"url": "https://raw.githubusercontent.com/rickwest/devsnippets/6e2a48494b385e807eda9d7a64512255eb8fe7ff/source/snippets/c/ins_del_dis_linkedlist.c",
"visit_date": "2023-01-14T21:22:42.223013"
} | stackv2 | #include<stdio.h>
#include <malloc.h>
struct data * insert(struct data *,int); /* cannot be used to insert element at beginning or end */
struct data * delete(struct data *,int); /* cannot be used to delete element from beginning or end */
struct data * display(struct data *);
struct data{
int roll_no;
char fname[10];
char lname[10];
int dob;
unsigned long int ph_no;
struct data * next;
};
int main(){
struct data * start=NULL;
struct data * node = (struct data *)malloc(sizeof(struct data));
int n;
printf("How many students are there? : ");
scanf("%d",&n);
start= node;
struct data * ptr=start;
for(int i=0;i<n;i++){
printf("Enter roll no, first name, last name, dob(ddmmyyyy) and phone number : \n");
scanf("%d %s %s %d %lu",&ptr->roll_no, ptr->fname, ptr->lname, &ptr->dob, &ptr->ph_no);
if(i<n-1){
struct data * node=(struct data *)malloc(sizeof(struct data));
ptr->next=node;
ptr=ptr->next;
}
else{
ptr->next=NULL;
}
}
while(1){
int ch;
printf("Choose an operation:\n1.Add student\n2.Delete student\n");
printf("3.Display\n0.Exit\nEnter your choice : ");
scanf("%d",&ch);
if(ch==0){
break;
}
int roll;
switch(ch){
case 1:
printf("Enter roll no after which you want to insert : ");
scanf("%d",&roll);
insert(start, roll);
break;
case 2:
printf("Enter roll no to delete : ");
scanf("%d",&roll);
delete(start, roll);
break;
case 3:
display(start);
}
}
return 0;
}
struct data * insert(struct data * start, int roll_no){
struct data * ptr=start;
while (ptr->roll_no!=roll_no){
ptr=ptr->next;
}
struct data * node=(struct data *)malloc(sizeof(struct data));
printf("Enter roll no, first name, last name, dob(ddmmyyyy) and phone number : \n");
scanf("%d %s %s %d %lu",&node->roll_no, node->fname, node->lname, &node->dob, &node->ph_no);
node->next=ptr->next;
ptr->next=node;
}
struct data * delete(struct data * start, int roll_no){
struct data * ptr=start;
struct data * preptr=ptr;
while (ptr->roll_no!=roll_no){
preptr=ptr;
ptr=ptr->next;
}
struct data * temp=ptr;
preptr->next=temp->next;
free(temp);
}
struct data * display(struct data * start){
struct data * ptr=start;
printf("roll no first name last name dob phone no\n");
while(ptr!=NULL){
printf(" %d ",ptr->roll_no);
printf("%s ",ptr->fname);
printf("%s ",ptr->lname);
printf("%d ",ptr->dob);
printf("%lu ",ptr->ph_no);
printf("\n");
ptr=ptr->next;
}
}
| 3.828125 | 4 |
2024-11-18T20:50:41.967844+00:00 | 2017-08-31T16:35:22 | f6f6b5d1e549ebac5c9abfe7591c82babe92e909 | {
"blob_id": "f6f6b5d1e549ebac5c9abfe7591c82babe92e909",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-31T16:35:22",
"content_id": "5d232ef2a5ff3ce2fbf9043df80ffd8de2f1a1ee",
"detected_licenses": [
"MIT"
],
"directory_id": "a8d88111648f815423e00cdcdfb5932e99a759e8",
"extension": "c",
"filename": "jpeg2ppm.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 98234945,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2361,
"license": "MIT",
"license_type": "permissive",
"path": "/src/jpeg2ppm.c",
"provenance": "stackv2-0110.json.gz:221611",
"repo_name": "Smoltbob/JPEG-decoder.c",
"revision_date": "2017-08-31T16:35:22",
"revision_id": "4a8c03f26481e29741c4fcad0a8235534d893023",
"snapshot_id": "bb300a83463d9b6c0c43efd56c5e8a25b97e1e42",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Smoltbob/JPEG-decoder.c/4a8c03f26481e29741c4fcad0a8235534d893023/src/jpeg2ppm.c",
"visit_date": "2021-01-01T18:04:22.724060"
} | stackv2 | #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "jpeg_reader.h"
#include "bitstream.h"
#include "extracteur.h"
#include "traitement.h"
#include "conversion_rgb.h"
#include "ppm.h"
#include "parametre_image.h"
#include "upsampling.h"
#include "structure.h"
#include "securite.h"
int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: %s fichier.jpeg\n", argv[0]);
return EXIT_FAILURE;
}
/* On recupere le nom du fichier JPEG sur la ligne de commande. */
const char *filename = argv[1];
if( access( filename, F_OK ) == -1 ) {
fprintf(stderr, "Error : file %s does not exist\n", argv[1]);
return EXIT_FAILURE;
}
if (check_extension(filename, "jpg") == false && check_extension(filename, "jpeg") == false){
fprintf(stderr, "Error : invalid extension. Expected : jpg ou jpeg.\n");
return EXIT_FAILURE;
}
/* On cree un jpeg_desc qui permettra de lire ce fichier. */
struct jpeg_desc *jdesc = read_jpeg(filename);
/* On recupere le flux des donnees brutes a partir du descripteur. */
struct bitstream *stream = get_bitstream(jdesc);
/* taille image en pixels */
uint32_t nb_mcu = nombre_mcu(jdesc);
/* image finale */
uint32_t *image = allouer_image(jdesc);
for (uint32_t i = 0; i < nb_mcu; i++) {
/* Décodage d'une mcu a partir du flux */
struct mcu mcu = decoder(jdesc, stream);
/* iQuant, Zigzag et iDCT */
traiter_mcu(&mcu, jdesc);
/* Conversion de la mcu en structure mcu suréchantilonnée */
struct fmcu fmcu_up = upsampling(&mcu, jdesc);
free_mcu(mcu);
/* YCbCr -> RGB */
uint32_t* pixels_mcu = conversion_rgb(fmcu_up, jdesc);
free_fmcu(fmcu_up);
uint32_t *pixels_ord = reordonne_pixel_fmcu(pixels_mcu, jdesc);
free(pixels_mcu);
for (uint32_t k=0; k<fmcu_up.nb_blocs*64; k++) {
image[i*fmcu_up.nb_blocs*64+k] = pixels_ord[k];
}
free(pixels_ord);
}
/* Ordonancement des pixels et troncature */
uint32_t *real = generer_pixels(image, jdesc);
free(image);
/* Génération du ppm */
generer_ppm(real, jdesc);
free(real);
/* Nettoyage de printemps : close_jpeg ferme aussi le bitstream */
close_jpeg(jdesc);
return EXIT_SUCCESS;
}
| 2.59375 | 3 |
2024-11-18T20:50:42.068211+00:00 | 2023-07-30T07:00:50 | eb0c065cdb68a472a98eb0e112f8a9199b2c0e23 | {
"blob_id": "eb0c065cdb68a472a98eb0e112f8a9199b2c0e23",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-30T07:00:50",
"content_id": "79b2f0f085ecb9d78e26dd4735c7652cb7098637",
"detected_licenses": [
"MIT"
],
"directory_id": "db04ecf258aef8a187823b8e47f4a1ae908e5897",
"extension": "c",
"filename": "MedianofTwoSortedArrays.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 74735489,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 562,
"license": "MIT",
"license_type": "permissive",
"path": "/C/MedianofTwoSortedArrays.c",
"provenance": "stackv2-0110.json.gz:221739",
"repo_name": "JumHorn/leetcode",
"revision_date": "2023-07-30T07:00:50",
"revision_id": "abf145686dcfac860b0f6b26a04e3edd133b238c",
"snapshot_id": "9612a26e531ceae7f25e2a749600632da6882075",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JumHorn/leetcode/abf145686dcfac860b0f6b26a04e3edd133b238c/C/MedianofTwoSortedArrays.c",
"visit_date": "2023-08-03T21:12:13.945602"
} | stackv2 |
//merge
//count the number of smaller half part
double findMedianSortedArrays(int *nums1, int nums1Size, int *nums2, int nums2Size)
{
int sum = nums1Size + nums2Size, count = sum / 2, midleft, midright;
for (int i = 0, j = 0; count >= 0 && (i < nums1Size || j < nums2Size);)
{
if (i == nums1Size)
midright = nums2[j++];
else if (j == nums2Size)
midright = nums1[i++];
else
midright = (nums1[i] < nums2[j] ? nums1[i++] : nums2[j++]);
if (--count == 0)
midleft = midright;
}
return sum % 2 == 0 ? (midleft + midright) / 2.0 : midright;
} | 2.859375 | 3 |
2024-11-18T20:50:42.931774+00:00 | 2018-05-22T12:10:27 | 4010be529e559dff3ca5342cef8ce9742bac294d | {
"blob_id": "4010be529e559dff3ca5342cef8ce9742bac294d",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-22T12:10:27",
"content_id": "54564ab1f3f7f7e41a10e23bc3cd3084975c8354",
"detected_licenses": [
"MIT"
],
"directory_id": "d61c9fd8250f160f517c12a22d1338ca5ef88040",
"extension": "c",
"filename": "queue.c",
"fork_events_count": 2,
"gha_created_at": "2016-01-04T07:48:51",
"gha_event_created_at": "2017-06-28T07:03:58",
"gha_language": "C",
"gha_license_id": null,
"github_id": 48982268,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8172,
"license": "MIT",
"license_type": "permissive",
"path": "/queue.c",
"provenance": "stackv2-0110.json.gz:222782",
"repo_name": "Enerccio/libds",
"revision_date": "2018-05-22T12:10:27",
"revision_id": "091a986445d384553e782c426b7fad38705e6dac",
"snapshot_id": "6fdce58be6dd2cc86cfe835e61296ec28bd75e09",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Enerccio/libds/091a986445d384553e782c426b7fad38705e6dac/queue.c",
"visit_date": "2021-05-04T09:59:26.274047"
} | stackv2 | /*
* The MIT License (MIT)
* Copyright (c) 2015 Peter Vanusanik <admin@en-circle.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.
*
* queue.c
* Created on: Jan 3, 2016
* Author: Peter Vanusanik
* Contents:
*/
#include "queue.h"
/******************************************************************************//**
* \brief Creates empty queue
*
* This queue can taky any amount of elements and will resize itself when necessary.
********************************************************************************/
queue_t* create_queue() {
queue_t* queue = (queue_t*) malloc(sizeof(queue_t));
if (queue) {
queue->first = 0;
queue->last = 0;
queue->size = 0;
queue->is_static = false;
}
return queue;
}
/******************************************************************************//**
* \brief Creates static empty queue with max_queue elements
*
* This queue can hold at most max_queue elements.
********************************************************************************/
queue_t* create_queue_static(uint32_t max_queue) {
queue_t* queue = (queue_t*) malloc(sizeof(queue_t));
if (queue) {
queue->first = 0;
queue->last = 0;
queue->size = 0;
queue->is_static = true;
queue->queue_pool.max_size = max_queue;
queue->queue_pool.pool_data = (void*) malloc(sizeof(queue_element_t) * max_queue);
if (!queue->queue_pool.pool_data) {
free(queue);
return NULL;
}
memset(queue->queue_pool.pool_data, 0, sizeof(queue_element_t) * max_queue);
}
return queue;
}
/******************************************************************************//**
* \brief Removes head of the queue and returns it.
*
* Returns NULL if queue is empty.
********************************************************************************/
void* queue_pop(queue_t* queue) {
queue_element_t* queue_head = queue->first;
if (queue_head == 0)
return 0;
if (queue->size == 1) {
queue->first = 0;
queue->last = 0;
queue->size = 0;
void* data = queue_head->data;
if (queue->is_static == true)
queue_head->__pool_c = 0; // ready for scrapping into the pool
else
free(queue_head);
return data;
}
void* data = queue_head->data;
queue->first = queue_head->next;
if (queue->is_static == true)
queue_head->__pool_c = 0;
else
free(queue_head);
queue->size--;
return data;
}
/******************************************************************************//**
* \brief Returns head of the queue without removing it.
*
* Returns NULL if queue is empty.
********************************************************************************/
void* queue_peek(queue_t* queue) {
queue_element_t* queue_head = queue->first;
if (queue_head == 0)
return 0;
return queue_head->data;
}
/******************************************************************************//**
* Returns true if queue is not empty.
********************************************************************************/
bool queue_has_elements(queue_t* queue) {
return queue_size(queue) > 0;
}
/******************************************************************************//**
* Returns empty segment for queue element allocation.
********************************************************************************/
static queue_element_t* get_free_segment(queue_t* queue) {
uintptr_t block = (uintptr_t) queue->queue_pool.pool_data;
while (block < ((uintptr_t) queue->queue_pool.pool_data) +
(queue->queue_pool.max_size * sizeof(queue_element_t))) {
queue_element_t* el = (queue_element_t*) block;
if (el->__pool_c == 0) {// it is a free block, yay
memset(el, 0, sizeof(queue_element_t)); // purge old data
el->__pool_c = true; // now it is used
return el;
}
block += sizeof(queue_element_t);
}
// we have exhausted all the memory, return instantly
return 0;
}
/******************************************************************************//**
* \brief Adds element to the queue.
*
* Element is put at the end of the queue.
* Returns true if failure happened.
********************************************************************************/
bool queue_push(queue_t* queue, void* data) {
queue_element_t* element;
if (queue->is_static == true)
element = get_free_segment(queue);
else
element = (queue_element_t*) malloc(sizeof(queue_element_t));
if (element == 0)
return true;
element->data = data;
element->next = 0;
element->previous = 0;
if (queue->first == 0) {
queue->first = queue->last = element;
queue->size = 1;
} else {
queue->last->next = element;
element->previous = queue->last;
queue->last = element;
queue->size++;
}
return false;
}
/******************************************************************************//**
* Returns number of elements in the queue.
********************************************************************************/
uint32_t queue_size(queue_t* queue) {
return queue->size;
}
/******************************************************************************//**
* \brief Deallocates queue.
*
* Removes all memory used by this queue. Elements in the queue are NOT
* deallocated.
********************************************************************************/
void free_queue(queue_t* queue) {
if (queue->is_static == true) {
free(queue);
free(queue->queue_pool.pool_data);
} else {
queue_element_t* el = queue->first;
while (el != 0) {
queue_element_t* tmp = el->next;
free(el);
el = tmp;
}
free(queue);
}
}
/******************************************************************************//**
* \brief Removes element from queue at any position.
*
* Element is compared via ==.
********************************************************************************/
void queue_remove(void* element, queue_t* queue) {
if (queue->size == 0)
return;
queue_element_t* e = queue->first;
while (e != 0 && e->data != element)
e = e->next;
if (e) {
if (e->previous)
e->previous->next = e->next;
if (e->next)
e->next->previous = e->previous;
if (queue->is_static == true)
e->__pool_c = 0;
else
free(e);
}
}
/******************************************************************************//**
* \brief Returns element from queue found by search predicate.
*
* For more info, see array.
********************************************************************************/
void* queue_find_by_predicate(void* data, search_predicate_t func, queue_t* queue) {
if (queue->size == 0)
return 0;
queue_element_t* e = queue->first;
while (e != 0 && func(e->data, data) == false)
e = e->next;
if (e)
return e->data;
else
return 0;
}
| 2.8125 | 3 |
2024-11-18T20:50:43.025939+00:00 | 2015-04-20T05:09:08 | 9f28f92ba86b62811ad3294df0d9874e450ea662 | {
"blob_id": "9f28f92ba86b62811ad3294df0d9874e450ea662",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-20T05:09:08",
"content_id": "4d7910e60be254609f535214145f4f0805db2377",
"detected_licenses": [
"MIT"
],
"directory_id": "603f55151334a2a20fadc75fdf6f60fbac5b6dd6",
"extension": "h",
"filename": "mameBitmap.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 34121193,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 31408,
"license": "MIT",
"license_type": "permissive",
"path": "/mameBitmap.h",
"provenance": "stackv2-0110.json.gz:222913",
"repo_name": "ar90n/mameBitmap",
"revision_date": "2015-04-20T05:09:08",
"revision_id": "4a05236058bcd219b1000750cba295e41a700b8c",
"snapshot_id": "e4e1a5c672dc4f4403681a8bcd74a10c8185bff4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ar90n/mameBitmap/4a05236058bcd219b1000750cba295e41a700b8c/mameBitmap.h",
"visit_date": "2020-06-06T06:52:14.517717"
} | stackv2 | #ifndef __MAME_BITMAP_HEADER__
# define __MAME_BITMAP_HEADER__
# ifdef __cplusplus
extern "C" {
# endif
# include <stdint.h>
# include <stdbool.h>
# include <stdio.h>
/* data type definitions */
typedef bool (*mameBitmap_read_byte_callback_ptr)( void* param, uint8_t* byte );
typedef bool (*mameBitmap_write_byte_callback_ptr)( void* param, uint8_t byte );
typedef enum
{
MAMEBITMAP_FORMAT_PBM_ASCII = 1,
MAMEBITMAP_FORMAT_PGM_ASCII,
MAMEBITMAP_FORMAT_PPM_ASCII,
MAMEBITMAP_FORMAT_PBM_RAW,
MAMEBITMAP_FORMAT_PGM_RAW,
MAMEBITMAP_FORMAT_PPM_RAW,
MAMEBITMAP_FORMAT_UNKNOWN,
} mameBitmap_format;
typedef struct {
mameBitmap_read_byte_callback_ptr read_callback;
void* read_callback_param;
mameBitmap_write_byte_callback_ptr write_callback;
void* write_callback_param;
int input_cache;
size_t used_buffer_size;
struct {
mameBitmap_format format;
uint16_t width;
uint16_t height;
int max_value;
}info;
} mameBitmap_context;
/* prototype definitions of mameBitmap API. */
bool mameBitmap_initialize( mameBitmap_context* context,
mameBitmap_read_byte_callback_ptr read_callback,
void* read_callback_param,
mameBitmap_write_byte_callback_ptr write_callback,
void* write_callback_param );
bool mameBitmap_encode( mameBitmap_context* context,
uint16_t width,
uint16_t height,
mameBitmap_format format,
uint16_t max_value );
bool mameBitmap_decode( mameBitmap_context* context );
bool mameBitmap_dispose( mameBitmap_context* context );
bool mameBitmap_getInfo( mameBitmap_read_byte_callback_ptr read_callback,
void* read_callback_param,
uint16_t* width,
uint16_t* height,
mameBitmap_format* format,
uint16_t* max_value );
bool mameBitmap_getImageSize( uint16_t width,
uint16_t height,
mameBitmap_format format,
size_t* image_size );
/* prototype definitions of refarence callbacks */
typedef struct {
void* buffer_ptr;
size_t buffer_pos;
size_t buffer_length;
} mameBitmap_memory_callback_param;
bool mameBitmap_input_from_memory_callback( void* param, uint8_t* byte );
bool mameBitmap_output_to_memory_callback( void* param, uint8_t byte );
bool mameBitmap_input_from_file_callback( void* param, uint8_t* byte );
bool mameBitmap_output_to_file_callback( void* param, uint8_t byte );
/* prototype definitions of simple API wrapper */
bool mameBitmap_getInfoFromMemory( void* input_buffer,
size_t input_buffer_size,
uint16_t* width,
uint16_t* height,
mameBitmap_format* format,
uint16_t* max_value );
bool mameBitmap_getInfoFromFile( const char* file_name,
uint16_t* width,
uint16_t* height,
mameBitmap_format* format,
uint16_t* max_value );
bool mameBitmap_encodeToMemory( void* input_buffer,
size_t input_size,
void* output_buffer,
size_t output_buffer_size,
uint16_t width,
uint16_t height,
mameBitmap_format format,
uint16_t max_value,
size_t* used_buffer_size );
bool mameBitmap_encodeToFile( void* output_buffer,
size_t output_buffer_size,
const char* file_name,
uint16_t width,
uint16_t height,
mameBitmap_format format,
uint16_t max_value,
size_t* used_buffer_size );
bool mameBitmap_decodeFromMemory( void* input_buffer,
size_t input_size,
void* output_buffer,
size_t output_buffer_size,
uint16_t* width,
uint16_t* height,
mameBitmap_format* format,
uint16_t* max_value,
size_t* used_buffer_size );
bool mameBitmap_decodeFromFile( const char* file_name,
void* output_buffer,
size_t output_buffer_size,
uint16_t* width,
uint16_t* height,
mameBitmap_format* format,
uint16_t* max_value,
size_t* used_buffer_size );
/* prototype definitions of internal functions */
bool mameBitmap_readByte( mameBitmap_context* context, uint8_t* byte );
bool mameBitmap_unreadByte( mameBitmap_context* context, uint8_t byte );
bool mameBitmap_writeByte( mameBitmap_context* context, uint8_t byte );
bool mameBitmap_is_space( char byte );
bool mameBitmap_readASCIIElem( mameBitmap_context* context, uint16_t* elem_value, uint16_t elem_length );
bool mameBitmap_writeASCIIElem( mameBitmap_context* context, uint16_t elem_value );
bool mameBitmap_getFormat( uint8_t magic_number, mameBitmap_format* format );
bool mameBitmap_getComponents( mameBitmap_format format, uint8_t* components );
bool mameBitmap_getMagicNumber( mameBitmap_format format, uint8_t* magic_number );
bool mameBitmap_skipComment( mameBitmap_context* context );
bool mameBitmap_getElemLength( mameBitmap_context* context, int* elem_length );
bool mameBitmap_getBitsPerComponent( mameBitmap_context* context, uint8_t* bits_per_component );
bool mameBitmap_decodeHeader( mameBitmap_context* context );
bool mameBitmap_decodeASCII( mameBitmap_context* context );
bool mameBitmap_decodeBINARY( mameBitmap_context* context );
bool mameBitmap_encodeHeader( mameBitmap_context* context );
bool mameBitmap_encodeASCII( mameBitmap_context* context );
bool mameBitmap_encodeBINARY( mameBitmap_context* context );
# define MAMEBITMAP_CHECK( X ) do{if( (X) == false ) return false; } while(0);
# define MAMEBITMAP_NULL_CHECK( X ) MAMEBITMAP_CHECK( (X) != NULL )
bool mameBitmap_initialize( mameBitmap_context* context,
mameBitmap_read_byte_callback_ptr read_callback,
void* read_callback_param,
mameBitmap_write_byte_callback_ptr write_callback,
void* write_callback_param )
{
MAMEBITMAP_NULL_CHECK( context )
MAMEBITMAP_NULL_CHECK( read_callback )
MAMEBITMAP_NULL_CHECK( write_callback )
context->read_callback = read_callback;
context->read_callback_param = read_callback_param;
context->write_callback = write_callback;
context->write_callback_param = write_callback_param;
context->used_buffer_size = 0;
context->input_cache = -1;
return true;
}
bool mameBitmap_readByte( mameBitmap_context* context, uint8_t* byte )
{
MAMEBITMAP_NULL_CHECK( context );
MAMEBITMAP_NULL_CHECK( byte );
if( 0 <= context->input_cache )
{
*byte = (uint8_t)context->input_cache;
context->input_cache = -1;
return true;
}
return context->read_callback( context->read_callback_param, byte );
}
bool mameBitmap_unreadByte( mameBitmap_context* context, uint8_t byte )
{
MAMEBITMAP_NULL_CHECK( context )
if( 0 <= context->input_cache )
{
return false;
}
context->input_cache = byte;
return true;
}
bool mameBitmap_writeByte( mameBitmap_context* context, uint8_t byte )
{
MAMEBITMAP_NULL_CHECK( context );
context->used_buffer_size++;
return context->write_callback( context->write_callback_param, byte );
}
bool mameBitmap_is_space( char byte )
{
return byte == ' ' || byte == '\t' || byte == '\n';
}
bool mameBitmap_readASCIIElem( mameBitmap_context* context, uint16_t* elem_value, uint16_t elem_length )
{
MAMEBITMAP_NULL_CHECK( context );
MAMEBITMAP_NULL_CHECK( elem_value );
uint8_t val = 0;
do
{
MAMEBITMAP_CHECK( mameBitmap_readByte( context, &val ) );
} while( mameBitmap_is_space( val ) );
*elem_value = 0;
uint16_t work_elem_length = elem_length;
while( !mameBitmap_is_space( val ) && ( 0 < work_elem_length ) )
{
*elem_value *= 10;
*elem_value += ( val - '0' );
work_elem_length--;
if( 0 < work_elem_length )
{
bool ret = mameBitmap_readByte( context, &val );
if( !ret )
{
break;
}
}
}
return true;
}
bool mameBitmap_writeASCIIElem( mameBitmap_context* context, uint16_t elem_value )
{
MAMEBITMAP_NULL_CHECK( context )
uint8_t elem_str[5]; /* 5 = (int)log10( 65535 ) */
int digits = 0;
do
{
elem_str[digits] = ( elem_value % 10 ) + '0';
elem_value /= 10;
digits++;
} while( 0 < elem_value );
for( int i = 0; i < digits; i++ )
{
uint8_t write_byte = elem_str[digits - i - 1];
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, write_byte ) );
}
return true;
}
bool mameBitmap_getFormat( uint8_t magic_number, mameBitmap_format* format )
{
MAMEBITMAP_NULL_CHECK( format );
bool ret = false;
if( magic_number == 0 || MAMEBITMAP_FORMAT_UNKNOWN <= magic_number )
{
*format = MAMEBITMAP_FORMAT_UNKNOWN;
ret = false;
}
else
{
*format = (mameBitmap_format)magic_number;
ret = true;
}
return ret;
}
bool mameBitmap_getMagicNumber( mameBitmap_format format, uint8_t* magic_number )
{
MAMEBITMAP_NULL_CHECK( magic_number );
bool ret = false;
if( format != MAMEBITMAP_FORMAT_UNKNOWN )
{
*magic_number = (uint8_t)format;
ret = true;
}
return ret;
}
bool mameBitmap_skipComment( mameBitmap_context* context )
{
MAMEBITMAP_NULL_CHECK( context );
uint8_t val;
MAMEBITMAP_CHECK( mameBitmap_readByte( context, &val ) );
while( val == '#' )
{
do
{
MAMEBITMAP_CHECK( mameBitmap_readByte( context, &val ) );
} while( val != '\n' );
MAMEBITMAP_CHECK( mameBitmap_readByte( context, &val ) );
}
mameBitmap_unreadByte( context, val );
return true;
}
bool mameBitmap_getComponents( mameBitmap_format format, uint8_t* components )
{
MAMEBITMAP_NULL_CHECK( components );
*components = 1;
if( format == MAMEBITMAP_FORMAT_PPM_ASCII || format == MAMEBITMAP_FORMAT_PPM_RAW )
{
*components = 3;
}
return true;
}
bool mameBitmap_getBitsPerComponent( mameBitmap_context* context, uint8_t* bits_per_component )
{
MAMEBITMAP_NULL_CHECK( context );
MAMEBITMAP_NULL_CHECK( bits_per_component );
*bits_per_component = 8;
if( context->info.format == MAMEBITMAP_FORMAT_PBM_ASCII || context->info.format == MAMEBITMAP_FORMAT_PBM_RAW )
{
*bits_per_component = 1;
}
return true;
}
bool mameBitmap_getElemLength( mameBitmap_context* context, int* elem_length )
{
MAMEBITMAP_NULL_CHECK( context );
MAMEBITMAP_NULL_CHECK( elem_length );
*elem_length = -1;
if( context->info.format == MAMEBITMAP_FORMAT_PBM_ASCII || context->info.format == MAMEBITMAP_FORMAT_PBM_RAW )
{
*elem_length = 1;
}
return true;
}
bool mameBitmap_decodeHeader( mameBitmap_context* context )
{
uint8_t val;
MAMEBITMAP_CHECK( mameBitmap_readByte( context, &val ) );
MAMEBITMAP_CHECK( val == 'P' );
MAMEBITMAP_CHECK( mameBitmap_readByte( context, &val ) );
uint8_t magic_number = val - '0';
MAMEBITMAP_CHECK( mameBitmap_getFormat( magic_number, &context->info.format ) );
MAMEBITMAP_CHECK( context->info.format != MAMEBITMAP_FORMAT_UNKNOWN );
MAMEBITMAP_CHECK( mameBitmap_readByte( context, &val ) );
MAMEBITMAP_CHECK( mameBitmap_is_space( val ) );
MAMEBITMAP_CHECK( mameBitmap_skipComment( context ) );
MAMEBITMAP_CHECK( mameBitmap_readASCIIElem( context, &(context->info.width), -1 ) );
MAMEBITMAP_CHECK( mameBitmap_readASCIIElem( context, &(context->info.height), -1 ) );
context->info.max_value = 1;
if( context->info.format != MAMEBITMAP_FORMAT_PBM_ASCII && context->info.format != MAMEBITMAP_FORMAT_PBM_RAW )
{
uint16_t elem;
MAMEBITMAP_CHECK( mameBitmap_readASCIIElem( context, &elem, -1 ) );
context->info.max_value = elem;
}
return true;
}
bool mameBitmap_decodeASCII( mameBitmap_context* context )
{
MAMEBITMAP_NULL_CHECK( context );
uint8_t components;
MAMEBITMAP_CHECK( mameBitmap_getComponents( context->info.format, &components ));
int elem_length;
MAMEBITMAP_CHECK( mameBitmap_getElemLength( context, &elem_length ) );
int hor_bytes = components * context->info.width;
for( int y = 0; y < context->info.height; y++ )
{
for( int x = 0; x < hor_bytes; x++ )
{
uint16_t val;
MAMEBITMAP_CHECK( mameBitmap_readASCIIElem( context, &val, elem_length ) );
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, (uint8_t)val ) );
}
}
return true;
}
bool mameBitmap_decodeBINARY( mameBitmap_context* context )
{
MAMEBITMAP_NULL_CHECK( context );
uint8_t bits_per_component;
MAMEBITMAP_CHECK( mameBitmap_getBitsPerComponent( context, &bits_per_component ) );
uint8_t components;
MAMEBITMAP_CHECK( mameBitmap_getComponents( context->info.format, &components ) );
uint16_t hor_width = components * context->info.width;
for( int y = 0; y < context->info.height; y++ )
{
uint16_t remain_width = hor_width;
while( 0 < remain_width )
{
uint8_t ival;
MAMEBITMAP_CHECK( mameBitmap_readByte( context, &ival ) );
uint8_t valid_bit_mask = ( 1 << bits_per_component ) - 1;
uint8_t current_width = ( ( 8 / bits_per_component ) < remain_width ) ? (8 / bits_per_component ) : remain_width;
for( int i = 0; i < current_width; i++ )
{
uint8_t bit_shift = 8 - bits_per_component * ( i + 1 );
uint8_t oval = ( ival >> bit_shift ) & valid_bit_mask;
oval = ( context->info.max_value < oval ) ? context->info.max_value : oval;
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, oval ) );
}
remain_width -= current_width;
}
}
return true;
}
bool mameBitmap_encodeHeader( mameBitmap_context* context )
{
MAMEBITMAP_NULL_CHECK( context );
uint8_t magic_number[4] = { 'P', 0, '\n', '\0' };
MAMEBITMAP_CHECK( mameBitmap_getMagicNumber( context->info.format, &( magic_number[1] ) ) );
magic_number[1] += '0';
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, magic_number[0] ) );
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, magic_number[1] ) );
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, magic_number[2] ) );
MAMEBITMAP_CHECK( mameBitmap_writeASCIIElem( context, context->info.width ) );
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, ' ' ) );
MAMEBITMAP_CHECK( mameBitmap_writeASCIIElem( context, context->info.height ) );
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, '\n' ) );
if( context->info.format != MAMEBITMAP_FORMAT_PBM_ASCII && context->info.format != MAMEBITMAP_FORMAT_PBM_RAW )
{
MAMEBITMAP_CHECK( mameBitmap_writeASCIIElem( context, context->info.max_value ) );
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, '\n' ) );
}
return true;
}
bool mameBitmap_encodeASCII( mameBitmap_context* context )
{
MAMEBITMAP_NULL_CHECK( context );
uint8_t components;
MAMEBITMAP_CHECK( mameBitmap_getComponents( context->info.format, &components ));
int elem_length;
MAMEBITMAP_CHECK( mameBitmap_getElemLength( context, &elem_length ) );
int hor_bytes = components * context->info.width;
for( int y = 0; y < context->info.height; y++ )
{
for( int x = 0; x < hor_bytes; x++ )
{
uint8_t val;
MAMEBITMAP_CHECK( mameBitmap_readByte( context, &val ) );
val = ( context->info.max_value < val ) ? context->info.max_value : val;
MAMEBITMAP_CHECK( mameBitmap_writeASCIIElem( context, val ) );
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, ' ' ) );
}
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, '\n' ) );
}
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, '\0' ) );
return true;
}
bool mameBitmap_encodeBINARY( mameBitmap_context* context )
{
MAMEBITMAP_NULL_CHECK( context );
uint8_t bits_per_component;
MAMEBITMAP_CHECK( mameBitmap_getBitsPerComponent( context, &bits_per_component ) );
uint8_t components;
MAMEBITMAP_CHECK( mameBitmap_getComponents( context->info.format, &components ) );
uint16_t hor_width = components * context->info.width;
for( int y = 0; y < context->info.height; y++ )
{
uint16_t remain_width = hor_width;
while( 0 < remain_width )
{
uint8_t valid_bit_mask = ( 1 << bits_per_component ) - 1;
uint8_t current_width = ( ( 8 / bits_per_component ) < remain_width ) ? (8 / bits_per_component ) : remain_width;
uint8_t oval = 0;
for( int i = 0; i < current_width; i++ )
{
uint8_t ival;
MAMEBITMAP_CHECK( mameBitmap_readByte( context, &ival ) );
uint8_t bit_shift = 8 - bits_per_component * ( i + 1 );
oval |= ( ival & valid_bit_mask ) << bit_shift;
}
MAMEBITMAP_CHECK( mameBitmap_writeByte( context, oval ) );
remain_width -= current_width;
}
}
return true;
}
bool mameBitmap_encode( mameBitmap_context* context, uint16_t width, uint16_t height, mameBitmap_format format, uint16_t max_value )
{
MAMEBITMAP_NULL_CHECK( context );
MAMEBITMAP_CHECK( 0 < width );
MAMEBITMAP_CHECK( 0 < height );
MAMEBITMAP_CHECK( MAMEBITMAP_FORMAT_PBM_ASCII <= format && format <= MAMEBITMAP_FORMAT_PPM_RAW );
MAMEBITMAP_CHECK( 0 < max_value );
context->info.width = width;
context->info.height = height;
context->info.format = format;
context->info.max_value = max_value;
MAMEBITMAP_CHECK( mameBitmap_encodeHeader( context ) );
switch( context->info.format )
{
case MAMEBITMAP_FORMAT_PBM_ASCII: /* fall through */
case MAMEBITMAP_FORMAT_PGM_ASCII: /* fall through */
case MAMEBITMAP_FORMAT_PPM_ASCII:
{
MAMEBITMAP_CHECK( mameBitmap_encodeASCII( context ) );
}break;
case MAMEBITMAP_FORMAT_PBM_RAW: /* fall through */
case MAMEBITMAP_FORMAT_PGM_RAW: /* fall through */
case MAMEBITMAP_FORMAT_PPM_RAW:
{
MAMEBITMAP_CHECK( mameBitmap_encodeBINARY( context ) );
}break;
default:
{
return false;
}
}
return true;
}
bool mameBitmap_decode( mameBitmap_context* context )
{
MAMEBITMAP_NULL_CHECK( context );
MAMEBITMAP_CHECK( mameBitmap_decodeHeader( context ) );
switch( context->info.format )
{
case MAMEBITMAP_FORMAT_PBM_ASCII: /* fall through */
case MAMEBITMAP_FORMAT_PGM_ASCII: /* fall through */
case MAMEBITMAP_FORMAT_PPM_ASCII:
{
MAMEBITMAP_CHECK( mameBitmap_decodeASCII( context ) );
}break;
case MAMEBITMAP_FORMAT_PBM_RAW: /* fall through */
case MAMEBITMAP_FORMAT_PGM_RAW: /* fall through */
case MAMEBITMAP_FORMAT_PPM_RAW:
{
MAMEBITMAP_CHECK( mameBitmap_decodeBINARY( context ) );
}break;
default:
{
return false;
}
}
return true;
}
bool mameBitmap_dispose( mameBitmap_context* context )
{
return true;
}
bool mameBitmap_getInfo( mameBitmap_read_byte_callback_ptr read_callback,
void* read_callback_param,
uint16_t* width,
uint16_t* height,
mameBitmap_format* format,
uint16_t* max_value )
{
MAMEBITMAP_NULL_CHECK( read_callback );
MAMEBITMAP_NULL_CHECK( read_callback_param );
MAMEBITMAP_NULL_CHECK( width );
MAMEBITMAP_NULL_CHECK( height );
MAMEBITMAP_NULL_CHECK( format );
MAMEBITMAP_NULL_CHECK( max_value );
mameBitmap_context work_context[1];
work_context->read_callback = read_callback;
work_context->read_callback_param = read_callback_param;
work_context->input_cache = -1;
mameBitmap_decodeHeader( work_context );
*format = work_context->info.format;
*width = work_context->info.width;
*height = work_context->info.height;
*max_value = work_context->info.max_value;
return true;
}
bool mameBitmap_getImageSize( uint16_t width,
uint16_t height,
mameBitmap_format format,
size_t* image_size )
{
uint8_t components;
MAMEBITMAP_CHECK( mameBitmap_getComponents( format, &components ) );
*image_size = components * width * height;
return true;
}
bool mameBitmap_input_from_memory_callback( void* param, uint8_t* byte )
{
MAMEBITMAP_NULL_CHECK( param )
MAMEBITMAP_NULL_CHECK( byte )
mameBitmap_memory_callback_param *callback_param = (mameBitmap_memory_callback_param*)param;
MAMEBITMAP_CHECK( callback_param->buffer_pos < callback_param->buffer_length )
*byte = ((uint8_t*)callback_param->buffer_ptr)[ callback_param->buffer_pos ];
callback_param->buffer_pos++;
return true;
}
bool mameBitmap_output_to_memory_callback( void* param, uint8_t byte )
{
MAMEBITMAP_NULL_CHECK( param )
mameBitmap_memory_callback_param *callback_param = (mameBitmap_memory_callback_param*)param;
MAMEBITMAP_CHECK( callback_param->buffer_pos < callback_param->buffer_length )
((uint8_t*)callback_param->buffer_ptr)[ callback_param->buffer_pos ] = byte;
(( mameBitmap_memory_callback_param* )param)->buffer_pos++;
return true;
}
bool mameBitmap_input_from_file_callback( void* param, uint8_t* byte )
{
MAMEBITMAP_NULL_CHECK( param )
MAMEBITMAP_NULL_CHECK( byte )
FILE* fp = (FILE*)param;
size_t n = fread( byte, 1, 1, fp );
return ( n == 1 );
}
bool mameBitmap_output_to_file_callback( void* param, uint8_t byte )
{
MAMEBITMAP_NULL_CHECK( param )
FILE* fp = (FILE*)param;
size_t n = fwrite( &byte, 1, 1, fp );
return ( n == 1 );
}
bool mameBitmap_getInfoFromMemory( void* input_buffer,
size_t input_buffer_size,
uint16_t* width,
uint16_t* height,
mameBitmap_format* format,
uint16_t* max_value )
{
MAMEBITMAP_NULL_CHECK( input_buffer );
MAMEBITMAP_CHECK( 0 < input_buffer_size );
MAMEBITMAP_NULL_CHECK( width );
MAMEBITMAP_NULL_CHECK( height );
MAMEBITMAP_NULL_CHECK( format );
MAMEBITMAP_NULL_CHECK( max_value );
mameBitmap_memory_callback_param input_param = {
.buffer_ptr = input_buffer,
.buffer_pos = 0,
.buffer_length = input_buffer_size
};
MAMEBITMAP_CHECK( mameBitmap_getInfo( mameBitmap_input_from_memory_callback, &input_param, width, height, format, max_value ) );
return true;
}
bool mameBitmap_decodeFromMemory( void* input_buffer,
size_t input_buffer_size,
void* output_buffer,
size_t output_buffer_size,
uint16_t* width,
uint16_t* height,
mameBitmap_format* format,
uint16_t* max_value,
size_t* used_buffer_size )
{
MAMEBITMAP_NULL_CHECK( input_buffer );
MAMEBITMAP_CHECK( 0 < input_buffer_size );
MAMEBITMAP_NULL_CHECK( output_buffer );
MAMEBITMAP_CHECK( 0 < output_buffer_size );
MAMEBITMAP_NULL_CHECK( width );
MAMEBITMAP_NULL_CHECK( height );
MAMEBITMAP_NULL_CHECK( format );
MAMEBITMAP_NULL_CHECK( max_value );
mameBitmap_context context[1];
mameBitmap_memory_callback_param input_param = {
.buffer_ptr = input_buffer,
.buffer_pos = 0,
.buffer_length = input_buffer_size
};
mameBitmap_memory_callback_param output_param = {
.buffer_ptr = output_buffer,
.buffer_pos = 0,
.buffer_length = output_buffer_size
};
MAMEBITMAP_CHECK( mameBitmap_initialize( context,
mameBitmap_input_from_memory_callback,
&input_param,
mameBitmap_output_to_memory_callback,
&output_param ) );
MAMEBITMAP_CHECK( mameBitmap_decode( context ) );
*width = context->info.width;
*height = context->info.height;
*format = context->info.format;
*max_value = context->info.max_value;
*used_buffer_size = context->used_buffer_size;
return true;
}
bool mameBitmap_encodeToMemory( void* input_buffer,
size_t input_buffer_size,
void* output_buffer,
size_t output_buffer_size,
uint16_t width,
uint16_t height,
mameBitmap_format format,
uint16_t max_value,
size_t* used_buffer_size )
{
MAMEBITMAP_NULL_CHECK( input_buffer );
MAMEBITMAP_CHECK( 0 < input_buffer_size );
MAMEBITMAP_NULL_CHECK( output_buffer );
MAMEBITMAP_CHECK( 0 < output_buffer_size );
MAMEBITMAP_CHECK( 0 < width );
MAMEBITMAP_CHECK( 0 < height );
MAMEBITMAP_CHECK( MAMEBITMAP_FORMAT_PBM_ASCII <= format && format <= MAMEBITMAP_FORMAT_PPM_RAW );
MAMEBITMAP_CHECK( 0 < max_value );
mameBitmap_context context[1];
mameBitmap_memory_callback_param input_param = {
.buffer_ptr = input_buffer,
.buffer_pos = 0,
.buffer_length = input_buffer_size
};
mameBitmap_memory_callback_param output_param = {
.buffer_ptr = output_buffer,
.buffer_pos = 0,
.buffer_length = output_buffer_size
};
MAMEBITMAP_CHECK( mameBitmap_initialize( context,
mameBitmap_input_from_memory_callback,
&input_param,
mameBitmap_output_to_memory_callback,
&output_param ) );
MAMEBITMAP_CHECK( mameBitmap_encode( context, width, height, format, max_value ) );
*used_buffer_size = context->used_buffer_size;
return true;
}
bool mameBitmap_getInfoFromFile( const char* file_name,
uint16_t* width,
uint16_t* height,
mameBitmap_format* format,
uint16_t* max_value )
{
MAMEBITMAP_NULL_CHECK( file_name );
MAMEBITMAP_NULL_CHECK( format );
MAMEBITMAP_NULL_CHECK( width );
MAMEBITMAP_NULL_CHECK( height );
MAMEBITMAP_NULL_CHECK( max_value );
FILE* fp = fopen(file_name, "r");
MAMEBITMAP_NULL_CHECK( fp );
bool ret = mameBitmap_getInfo( mameBitmap_input_from_file_callback, (void*)fp, width, height, format, max_value );
fclose( fp );
return ret;
}
bool mameBitmap_decodeFromFile( const char* file_name,
void* output_buffer,
size_t output_buffer_size,
uint16_t* width,
uint16_t* height,
mameBitmap_format* format,
uint16_t* max_value,
size_t* used_buffer_size )
{
MAMEBITMAP_NULL_CHECK( file_name );
MAMEBITMAP_NULL_CHECK( output_buffer );
MAMEBITMAP_CHECK( 0 < output_buffer_size );
mameBitmap_context context[1];
FILE* fp = fopen(file_name, "r");
MAMEBITMAP_NULL_CHECK( fp );
mameBitmap_memory_callback_param output_param = {
.buffer_ptr = output_buffer,
.buffer_pos = 0,
.buffer_length = output_buffer_size
};
bool ret = mameBitmap_initialize( context,
mameBitmap_input_from_file_callback,
(void*)fp,
mameBitmap_output_to_memory_callback,
&output_param );
if( !ret )
{
fclose(fp);
return false;
}
ret = mameBitmap_decode( context );
fclose(fp);
*width = context->info.width;
*height = context->info.height;
*format = context->info.format;
*max_value = context->info.max_value;
*used_buffer_size = context->used_buffer_size;
return ret;
}
bool mameBitmap_encodeToFile( void* input_buffer,
size_t input_buffer_size,
const char* file_name,
uint16_t width,
uint16_t height,
mameBitmap_format format,
uint16_t max_value,
size_t* used_buffer_size )
{
MAMEBITMAP_NULL_CHECK( file_name );
MAMEBITMAP_NULL_CHECK( input_buffer );
MAMEBITMAP_CHECK( 0 < input_buffer_size );
MAMEBITMAP_CHECK( 0 < width );
MAMEBITMAP_CHECK( 0 < height );
MAMEBITMAP_CHECK( MAMEBITMAP_FORMAT_PBM_ASCII <= format && format <= MAMEBITMAP_FORMAT_PPM_RAW );
MAMEBITMAP_CHECK( 0 < max_value );
mameBitmap_context context[1];
FILE* fp = fopen(file_name, "w");
MAMEBITMAP_NULL_CHECK( fp );
mameBitmap_memory_callback_param input_param = {
.buffer_ptr = input_buffer,
.buffer_pos = 0,
.buffer_length = input_buffer_size
};
bool ret = mameBitmap_initialize( context,
mameBitmap_input_from_memory_callback,
&input_param,
mameBitmap_output_to_file_callback,
(void*)fp );
if( !ret )
{
fclose(fp);
return false;
}
ret = mameBitmap_encode( context, width, height, format, max_value );
fclose(fp);
return ret;
}
# ifdef __cplusplus
}
# endif
#endif /* __MAME_BITMAP_HEADER__ */
| 2.125 | 2 |
2024-11-18T20:50:43.735842+00:00 | 2019-09-26T04:58:35 | 7fd14eb0f39a98dff711a0fe5e7d16cc23a19c50 | {
"blob_id": "7fd14eb0f39a98dff711a0fe5e7d16cc23a19c50",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-26T04:58:35",
"content_id": "0a6b18127e9bba451f28c08b48094abd9d4d866b",
"detected_licenses": [
"MIT"
],
"directory_id": "529f8446a21968b64552515606687def820cae0a",
"extension": "c",
"filename": "nvme_test.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44579057,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5196,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/c/nvme_test/nvme_test.c",
"provenance": "stackv2-0110.json.gz:223830",
"repo_name": "qzan9/jni-nvm",
"revision_date": "2019-09-26T04:58:35",
"revision_id": "3e47c72063d3ec0bb09e0125c23f80d7e4be82c3",
"snapshot_id": "d4ba6b97b9607bed1d344268137966598094c961",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/qzan9/jni-nvm/3e47c72063d3ec0bb09e0125c23f80d7e4be82c3/src/main/c/nvme_test/nvme_test.c",
"visit_date": "2021-01-21T13:29:58.646409"
} | stackv2 | /*
* nvme_test: testing and verifying ...
*
* Author(s)
* azq @qzan9 anzhongqi@ncic.ac.cn
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <stddef.h>
#include <fcntl.h>
#include <unistd.h>
#include <rte_config.h>
#include <rte_malloc.h>
#include <rte_mempool.h>
#include <rte_cycles.h>
#include <spdk/nvme.h>
#define REQUEST_POOL_SIZE (1024)
#define REQUEST_CACHE_SIZE (0)
#define REQUEST_PRIVATE_SIZE (0)
#define NAMESPACE_ID (1)
#define IO_SIZE (4096)
#define BUFFER_ALIGN (0x200)
static struct spdk_nvme_ctrlr *ctrlr;
static uint32_t ns_id;
static struct spdk_nvme_ns *ns;
static uint32_t ns_sector;
static uint64_t ns_size;
static struct spdk_nvme_qpair *qpair;
static uint32_t io_size;
static uint32_t io_depth;
struct rte_mempool *request_mempool;
static char *ealargs[] = { "nvme_test", "-c 0x100", "-n 1", };
static unsigned int seed = 0;
static bool
probe_cb(void *cb_ctx, struct spdk_pci_device *dev, struct spdk_nvme_ctrlr_opts *opts)
{
if (ctrlr) {
return false;
}
if (spdk_pci_device_has_non_uio_driver(dev)) {
fprintf(stderr, "%04x:%02x:%02x.%02x: non-UIO/kernel driver detected!\n",
spdk_pci_device_get_domain(dev),
spdk_pci_device_get_bus(dev),
spdk_pci_device_get_dev(dev),
spdk_pci_device_get_func(dev));
return false;
}
return true;
}
static void
attach_cb(void *cb_ctx, struct spdk_pci_device *dev, struct spdk_nvme_ctrlr *_ctrlr, const struct spdk_nvme_ctrlr_opts *opts)
{
ctrlr = _ctrlr;
ns = spdk_nvme_ctrlr_get_ns(ctrlr, ns_id);
ns_sector = spdk_nvme_ns_get_sector_size(ns);
ns_size = spdk_nvme_ns_get_size(ns);
qpair = spdk_nvme_ctrlr_alloc_io_qpair(ctrlr, 0);
printf("attached to %04x:%02x:%02x.%02x!\n",
spdk_pci_device_get_domain(dev),
spdk_pci_device_get_bus(dev),
spdk_pci_device_get_dev(dev),
spdk_pci_device_get_func(dev));
}
static void
io_complete(void *cb_args, const struct spdk_nvme_cpl *completion)
{
io_depth--;
}
int main(int argc, char *argv[])
{
uint8_t *wbuf, *rbuf;
uint64_t offset_in_blocks;
uint32_t size_in_blocks;
int rnd;
// initialize EAL
if (rte_eal_init(sizeof(ealargs) / sizeof(ealargs[0]), ealargs) < 0) {
fprintf(stderr, "failed to initialize EAL!\n");
goto FAIL;
}
printf("\n==================================\n");
printf( " nvme_test - ict.ncic.syssw.ufo" );
printf("\n==================================\n");
ctrlr = NULL;
ns_id = NAMESPACE_ID;
ns = NULL;
io_size = IO_SIZE;
io_depth = 0;
request_mempool = rte_mempool_create("nvme_request",
REQUEST_POOL_SIZE, spdk_nvme_request_size(),
REQUEST_CACHE_SIZE, REQUEST_PRIVATE_SIZE,
NULL, NULL, NULL, NULL,
SOCKET_ID_ANY, 0);
if (request_mempool == NULL) {
fprintf(stderr, "failed to create request pool!\n");
goto FAIL;
}
if (spdk_nvme_probe(NULL, probe_cb, attach_cb)) {
fprintf(stderr, "failed to probe and attach to NVMe device!\n");
goto FAIL;
}
if (!ctrlr) {
fprintf(stderr, "failed to probe a suitable controller!\n");
goto FAIL;
}
if (!spdk_nvme_ns_is_active(ns)) {
fprintf(stderr, "namespace %d is in-active!\n", ns_id);
goto FAIL;
}
if (ns_size < io_size) {
fprintf(stderr, "invalid I/O size %"PRIu32"!\n", io_size);
goto FAIL;
}
if (!qpair) {
fprintf(stderr, "failed to allocate queue pair!\n");
goto FAIL;
}
// prepare hugepage memory buffer
wbuf = rte_malloc(NULL, io_size, BUFFER_ALIGN);
if (wbuf == NULL) {
fprintf(stderr, "failed to rte_malloc write buffer!\n");
goto FAIL;
}
memset(wbuf, 0xff, io_size); // set value to 11111111...
rbuf = rte_malloc(NULL, io_size, BUFFER_ALIGN);
if (rbuf == NULL) {
fprintf(stderr, "failed to rte_malloc read buffer!\n");
goto FAIL;
}
memset(rbuf, 0x00, io_size); // set value to 00000000...
// write down, then read back
rnd = open("/dev/urandom", O_RDONLY);
read(rnd, wbuf, io_size); // randomly set the write buffer
close(rnd);
offset_in_blocks = io_size / ns_sector; // any location could be OK ...
size_in_blocks = io_size / ns_sector;
if (spdk_nvme_ns_cmd_write(ns, qpair, wbuf, offset_in_blocks, size_in_blocks, io_complete, NULL, 0)) {
fprintf(stderr, "failed to submit write request!\n");
goto FAIL;
}
io_depth++;
while (io_depth > 0) {
spdk_nvme_qpair_process_completions(qpair, 0);
}
if (spdk_nvme_ns_cmd_read(ns, qpair, rbuf, offset_in_blocks, size_in_blocks, io_complete, NULL, 0)) {
fprintf(stderr, "failed to submit read request!\n");
goto FAIL;
}
io_depth++;
while (io_depth > 0) {
spdk_nvme_qpair_process_completions(qpair, 0);
}
// compare two buffers
if (memcmp((void *)wbuf, (void *)rbuf, io_size) == 0) {
printf("YES!\n");
}
// release resources
if (qpair) {
spdk_nvme_ctrlr_free_io_qpair(qpair);
}
if (ctrlr) {
spdk_nvme_detach(ctrlr);
}
return 0;
FAIL:
if (qpair) {
spdk_nvme_ctrlr_free_io_qpair(qpair);
}
if (ctrlr) {
spdk_nvme_detach(ctrlr);
}
return 1;
}
| 2.0625 | 2 |
2024-11-18T20:50:43.828574+00:00 | 2023-03-27T07:01:24 | 9f7300165209fc3c1b1044b407f93d823e665aab | {
"blob_id": "9f7300165209fc3c1b1044b407f93d823e665aab",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-27T07:06:35",
"content_id": "7d4d285186a25f336ea690c21cdbbf3eb557eef7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4c5ccc64afbb67de745bd005555611a4bed1d3ad",
"extension": "c",
"filename": "main.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 108112890,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6806,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/SampleCode/StdDriver/WWDT_CompareINT/main.c",
"provenance": "stackv2-0110.json.gz:223958",
"repo_name": "OpenNuvoton/M051BSP",
"revision_date": "2023-03-27T07:01:24",
"revision_id": "440d2d1884e96118668bf627845e00337cfeaaf5",
"snapshot_id": "63c77ad366678af49d91758cb141f9b130caf134",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/OpenNuvoton/M051BSP/440d2d1884e96118668bf627845e00337cfeaaf5/SampleCode/StdDriver/WWDT_CompareINT/main.c",
"visit_date": "2023-04-06T21:08:14.055942"
} | stackv2 | /**************************************************************************//**
* @file main.c
* @version V3.00
* $Revision: 8 $
* $Date: 15/05/22 2:39p $
* @brief Show how to reload the WWDT counter value.
* @note
* Copyright (C) 2013 Nuvoton Technology Corp. All rights reserved.
******************************************************************************/
#include <stdio.h>
#include "M051Series.h"
#define PLLCON_SETTING CLK_PLLCON_50MHz_HXT
#define PLL_CLOCK 50000000
/*---------------------------------------------------------------------------------------------------------*/
/* Global Interface Variables Declarations */
/*---------------------------------------------------------------------------------------------------------*/
extern int IsDebugFifoEmpty(void);
volatile uint32_t g_u32WWDTINTCount = 0;
/**
* @brief IRQ Handler for WDT and WWDT Interrupt
*
* @param None
*
* @return None
*
* @details The WDT_IRQHandler is default IRQ of WDT and WWDT, declared in startup_M051Series.s.
*/
void WDT_IRQHandler(void)
{
if(WWDT_GET_INT_FLAG() == 1)
{
/* Clear WWDT compare match interrupt flag */
WWDT_CLEAR_INT_FLAG();
g_u32WWDTINTCount++;
if(g_u32WWDTINTCount < 10)
{
/* To reload the WWDT counter value to 0x3F */
WWDT_RELOAD_COUNTER();
}
printf("WWDT compare match interrupt occurred. (%d)\n", g_u32WWDTINTCount);
}
}
void SYS_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init System Clock */
/*---------------------------------------------------------------------------------------------------------*/
/* Enable IRC22M clock */
CLK->PWRCON |= CLK_PWRCON_IRC22M_EN_Msk;
/* Waiting for IRC22M clock ready */
CLK_WaitClockReady(CLK_CLKSTATUS_IRC22M_STB_Msk);
/* Switch HCLK clock source to HIRC */
CLK->CLKSEL0 = CLK_CLKSEL0_HCLK_S_HIRC;
/* Set PLL to Power-down mode and PLL_STB bit in CLKSTATUS register will be cleared by hardware.*/
CLK->PLLCON |= CLK_PLLCON_PD_Msk;
/* Enable external 12 MHz XTAL, IRC10K */
CLK->PWRCON |= CLK_PWRCON_XTL12M_EN_Msk | CLK_PWRCON_OSC10K_EN_Msk;
/* Enable PLL and Set PLL frequency */
CLK->PLLCON = PLLCON_SETTING;
/* Waiting for clock ready */
CLK_WaitClockReady(CLK_CLKSTATUS_PLL_STB_Msk | CLK_CLKSTATUS_XTL12M_STB_Msk | CLK_CLKSTATUS_IRC10K_STB_Msk);
/* Switch HCLK clock source to PLL, STCLK to HCLK/2 */
CLK->CLKSEL0 = CLK_CLKSEL0_STCLK_S_HCLK_DIV2 | CLK_CLKSEL0_HCLK_S_PLL;
/* Enable peripheral clock */
CLK->APBCLK = CLK_APBCLK_UART0_EN_Msk | CLK_APBCLK_WDT_EN_Msk;
/* Peripheral clock source */
CLK->CLKSEL1 = CLK_CLKSEL1_UART_S_PLL;
CLK->CLKSEL2 = CLK_CLKSEL2_WWDT_S_HCLK_DIV2048;
/* Update System Core Clock */
/* User can use SystemCoreClockUpdate() to calculate PllClock, SystemCoreClock and CycylesPerUs automatically. */
SystemCoreClockUpdate();
/*---------------------------------------------------------------------------------------------------------*/
/* Init I/O Multi-function */
/*---------------------------------------------------------------------------------------------------------*/
/* Set P3 multi-function pins for UART0 RXD, TXD */
SYS->P3_MFP &= ~(SYS_MFP_P30_Msk | SYS_MFP_P31_Msk);
SYS->P3_MFP |= (SYS_MFP_P30_RXD0 | SYS_MFP_P31_TXD0);
}
void UART0_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init UART */
/*---------------------------------------------------------------------------------------------------------*/
/* Reset IP */
SYS_ResetModule(UART0_RST);
/* Configure UART0 and set UART0 Baudrate */
UART_Open(UART0, 115200);
}
/*---------------------------------------------------------------------------------------------------------*/
/* MAIN function */
/*---------------------------------------------------------------------------------------------------------*/
int main(void)
{
volatile uint32_t u32InitCount;
double dPeriodTime;
/* Unlock protected registers */
SYS_UnlockReg();
/* Init System, peripheral clock and multi-function I/O */
SYS_Init();
/* Lock protected registers */
SYS_LockReg();
/* Init UART0 for printf */
UART0_Init();
#if !( __GNUC__ )
printf("\n\nCPU @ %d Hz\n", SystemCoreClock);
#endif
if(WWDT_GET_RESET_FLAG() == 1)
{
WWDT_CLEAR_RESET_FLAG();
printf("\n*** WWDT time-out reset occurred ***\n");
}
#if !( __GNUC__ )
printf("\n\nCPU @ %d Hz\n", SystemCoreClock);
#endif
printf("+-------------------------------------------------+\n");
printf("| WWDT Compare March Interrupt Sample Code |\n");
printf("+-------------------------------------------------+\n\n");
printf("# WWDT Settings: \n");
#if !( __GNUC__ )
dPeriodTime = (((double)(1000000 * 2048) / (double)SystemCoreClock) * 1024) * 32;
printf(" Clock source is HCLK/2048(%d Hz); Enable interrupt; Window Compare value is 32;\n", SystemCoreClock / 2048);
#endif
printf(" Select max WWDT time-out period is 1024 * (64 * WWDT_clock);\n");
#if !( __GNUC__ )
printf("# When WWDT start counting, system will generate first WWDT compare match interrupt after %.2f us.\n", dPeriodTime);
#endif
printf(" 1.) reload WWDT counter value to 0x3F when WWDT interrupt count less than 10 to avoid WWDT reset occurred.\n");
printf(" 2.) system will be reset by WWDT counting time-out while WWDT interrupt count reaches to 10.\n\n");
u32InitCount = g_u32WWDTINTCount = 0;
/* Enable WDT/WWDT NVIC */
NVIC_EnableIRQ(WDT_IRQn);
/* Configure WWDT compare value is 32; max time-out period is 1024*(64*WWDT_clk) and enable WWDT interrupt then start WWDT counting */
/* Note: WWDTCR register can be written only once after chip is powered on or reset */
WWDT_Open(WWDT_PRESCALER_1024, 32, TRUE);
printf("[WWDTCR: 0x%08X]\n\n", WWDT->WWDTCR);
while(1);
}
/*** (C) COPYRIGHT 2013 Nuvoton Technology Corp. ***/
| 2.203125 | 2 |
2024-11-18T20:50:43.965128+00:00 | 2021-09-27T10:28:41 | 9414b4a882013b2143bc80e82ba2aa69f25d477b | {
"blob_id": "9414b4a882013b2143bc80e82ba2aa69f25d477b",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-27T10:28:41",
"content_id": "fcea72b385b0b8e96cf0b7a5b4172a345259a3f9",
"detected_licenses": [
"curl"
],
"directory_id": "a5162318b4ad32904ae1ce066817c43dc1c67340",
"extension": "c",
"filename": "paging.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 410830494,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1948,
"license": "curl",
"license_type": "permissive",
"path": "/model/paging.c",
"provenance": "stackv2-0110.json.gz:224216",
"repo_name": "lagrello/lagrello-c",
"revision_date": "2021-09-27T10:28:41",
"revision_id": "0e28d53814edad59bdc845affce48265f2941a2f",
"snapshot_id": "6ffdee45268be06e28837a4c57e370c127d89320",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lagrello/lagrello-c/0e28d53814edad59bdc845affce48265f2941a2f/model/paging.c",
"visit_date": "2023-08-13T04:16:14.356233"
} | stackv2 | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "paging.h"
paging_t *paging_create(
char *previous,
char *next
) {
paging_t *paging_local_var = malloc(sizeof(paging_t));
if (!paging_local_var) {
return NULL;
}
paging_local_var->previous = previous;
paging_local_var->next = next;
return paging_local_var;
}
void paging_free(paging_t *paging) {
if(NULL == paging){
return ;
}
listEntry_t *listEntry;
if (paging->previous) {
free(paging->previous);
paging->previous = NULL;
}
if (paging->next) {
free(paging->next);
paging->next = NULL;
}
free(paging);
}
cJSON *paging_convertToJSON(paging_t *paging) {
cJSON *item = cJSON_CreateObject();
// paging->previous
if (!paging->previous) {
goto fail;
}
if(cJSON_AddStringToObject(item, "previous", paging->previous) == NULL) {
goto fail; //String
}
// paging->next
if (!paging->next) {
goto fail;
}
if(cJSON_AddStringToObject(item, "next", paging->next) == NULL) {
goto fail; //String
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
paging_t *paging_parseFromJSON(cJSON *pagingJSON){
paging_t *paging_local_var = NULL;
// paging->previous
cJSON *previous = cJSON_GetObjectItemCaseSensitive(pagingJSON, "previous");
if (!previous) {
goto end;
}
if(!cJSON_IsString(previous))
{
goto end; //String
}
// paging->next
cJSON *next = cJSON_GetObjectItemCaseSensitive(pagingJSON, "next");
if (!next) {
goto end;
}
if(!cJSON_IsString(next))
{
goto end; //String
}
paging_local_var = paging_create (
strdup(previous->valuestring),
strdup(next->valuestring)
);
return paging_local_var;
end:
return NULL;
}
| 2.796875 | 3 |
2024-11-18T20:50:44.334408+00:00 | 2014-12-23T17:10:20 | 0aa6e26a0417e4cbe4a55190dc839b3900dd95a7 | {
"blob_id": "0aa6e26a0417e4cbe4a55190dc839b3900dd95a7",
"branch_name": "refs/heads/master",
"committer_date": "2014-12-23T17:10:20",
"content_id": "bd2497fc60a1ad06cd7cd7aca14fb4e9860e4741",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "daf73ba238395b01d668bd30efde6a1571e62fff",
"extension": "c",
"filename": "microblazeNewlib.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8152,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/semihosting/microblazeNewlib/1.0/model/microblazeNewlib.c",
"provenance": "stackv2-0110.json.gz:224734",
"repo_name": "mcmenaminadrian/ovpmicroblaze",
"revision_date": "2014-12-23T17:10:20",
"revision_id": "878ab437cfcdfa9b0eb997fc44c9982c4c975f94",
"snapshot_id": "ebd5c5180020488c4adbee800d17a3e04e9deeec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mcmenaminadrian/ovpmicroblaze/878ab437cfcdfa9b0eb997fc44c9982c4c975f94/semihosting/microblazeNewlib/1.0/model/microblazeNewlib.c",
"visit_date": "2021-01-23T15:14:58.866183"
} | stackv2 | /*
* Copyright (c) 2005-2014 Imperas Software Ltd., www.imperas.com
*
* 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.
*
*/
// VMI area includes
#include "vmi/vmiMessage.h"
#include "vmi/vmiOSAttrs.h"
#include "vmi/vmiOSLib.h"
#include "vmi/vmiRt.h"
#include "vmi/vmiVersion.h"
// Message prefix
#define CPU_PREFIX "MICROBLAZE_NEWLIB"
// Number of arguments passed in regs as defined by ABI
#define REG_ARG_NUM 6
// Number of file descriptors supported
#define FILE_DES_NUM 128
// This is the offset from _impure_ptr to the errno field
// In microblaze toolchain, when compiled with _REENT_SMALL defined this is 12
// rather than the standard value of 0
#define ERRNO_OFFSET 12
////////////////////////////////////////////////////////////////////////////////
// TYPES
////////////////////////////////////////////////////////////////////////////////
typedef struct vmiosObjectS {
// first three argument registers (standard ABI)
vmiRegInfoCP args[REG_ARG_NUM];
// return register (standard ABI)
vmiRegInfoCP resultReg;
// stack pointer register (standard ABI)
vmiRegInfoCP argSP;
char **argv, **envp;
// Info for errno handling (set and used in newlibSemiHost.c.h)
Addr impurePtrAddr;
memDomainP impurePtrDomain;
Addr errnoAddr;
memDomainP errnoDomain;
// file descriptor table (set and used in newlibSemiHost.c.h)
Int32 fileDescriptors[FILE_DES_NUM];
} vmiosObject;
//
// microblaze/newlib stat structure
//
typedef struct {
Uns32 _u1; // 0:
Uns32 mode; // 4: mode
Uns32 _u2; // 8:
Uns32 _u3; // 12:
Uns32 size; // 16: size
Uns32 atime; // 20: atime
Uns32 _u4; // 24:
Uns32 mtime; // 28: mtime
Uns32 _u5; // 32:
Uns32 ctime; // 36: ctime
Uns32 _u6; // 40:
Uns32 blksize; // 44: blksize
Uns32 blocks; // 48: blocks
} newlibStat;
////////////////////////////////////////////////////////////////////////////////
// UTILITIES REQUIRED BY newlibSemiHost.c.h
////////////////////////////////////////////////////////////////////////////////
//
// Get the Constant pointer for the Stack Pointer
//
static vmiRegInfoCP getSPCP(
vmiProcessorP processor,
vmiosObjectP object
) {
return object->argSP;
}
//
// Get the Constant pointer for the register
//
static vmiRegInfoCP getArgCP(
vmiProcessorP processor,
vmiosObjectP object,
Uns32 index
) {
vmiRegInfoCP regCP = 0;
if(index>=REG_ARG_NUM) {
vmiMessage("P", CPU_PREFIX"_ANS",
"No more than %u function arguments supported",
REG_ARG_NUM
);
vmirtFinish(-1);
} else {
regCP = object->args[index];
}
return regCP;
}
//
// Read a function argument using the standard ABI
//
static void getArg(
vmiProcessorP processor,
vmiosObjectP object,
Uns32 index,
void *result
) {
if(index>=REG_ARG_NUM) {
vmiMessage("P", CPU_PREFIX"_ANS",
"No more than %u function arguments supported",
REG_ARG_NUM
);
vmirtFinish(-1);
} else {
vmiRegInfoCP regCP = getArgCP(processor, object, index);
vmiosRegRead(processor, regCP, result);
}
}
////////////////////////////////////////////////////////////////////////////////
// Include code common to all newlib implementations
////////////////////////////////////////////////////////////////////////////////
#include "ovpworld.org/modelSupport/semihosting/1.0/model/newlib.c.h"
////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR & DESTRUCTOR
////////////////////////////////////////////////////////////////////////////////
//
// Constructor
//
static VMIOS_CONSTRUCTOR_FN(constructor) {
// first three argument registers (standard ABI)
object->args[0] = vmiosGetRegDesc(processor, "R5");
object->args[1] = vmiosGetRegDesc(processor, "R6");
object->args[2] = vmiosGetRegDesc(processor, "R7");
object->args[3] = vmiosGetRegDesc(processor, "R8");
object->args[4] = vmiosGetRegDesc(processor, "R9");
object->args[5] = vmiosGetRegDesc(processor, "R10");
// return register (standard ABI)
object->resultReg = vmiosGetRegDesc(processor, "R3");
// Stack Pointer
object->argSP = vmiosGetRegDesc(processor, "R1");
Bool found;
object->argv = (char **)(UnsPS)vmirtPlatformUns64Attribute(processor, "userargv", &found);
object->envp = (char **)(UnsPS)vmirtPlatformUns64Attribute(processor, "userenvp", &found);
// Sets up data common to all newlib implementations
// Defined in newlibSemiHost.c.h
setupNewlib(object, processor);
}
//
// Destructor
//
static VMIOS_DESTRUCTOR_FN(destructor) {
}
////////////////////////////////////////////////////////////////////////////////
// INTERCEPT ATTRIBUTES
////////////////////////////////////////////////////////////////////////////////
vmiosAttr modelAttrs = {
////////////////////////////////////////////////////////////////////////
// VERSION
////////////////////////////////////////////////////////////////////////
.versionString = VMI_VERSION, // version string (THIS MUST BE FIRST)
.modelType = VMI_INTERCEPT_LIBRARY, // type
.packageName = "Newlib", // description
.objectSize = sizeof(vmiosObject), // size in bytes of OSS object
////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR/DESTRUCTOR ROUTINES
////////////////////////////////////////////////////////////////////////
.constructorCB = constructor, // object constructor
.destructorCB = destructor, // object destructor
////////////////////////////////////////////////////////////////////////
// INSTRUCTION INTERCEPT ROUTINES
////////////////////////////////////////////////////////////////////////
.morphCB = 0, // morph callback
.nextPCCB = 0, // get next instruction address
.disCB = 0, // disassemble instruction
////////////////////////////////////////////////////////////////////////
// ADDRESS INTERCEPT DEFINITIONS
////////////////////////////////////////////////////////////////////////
.intercepts = {
// ----------------- ------- ------ -----------------
// Name Address Opaque Callback
// ----------------- ------- ------ -----------------
//
// newlib entries
//
{ "exit", 0, True, exitCB },
{ "open", 0, True, openCB },
{ "close", 0, True, closeCB },
{ "read", 0, True, readCB },
{ "write", 0, True, writeCB },
{ "lseek", 0, True, lseekCB },
{ "fstat", 0, True, fstatCB },
{ "lstat", 0, True, lstatCB },
{ "stat", 0, True, statCB },
{ "kill", 0, True, killCB },
{ "gettimeofday", 0, True, gettimeofdayCB },
{ "times", 0, True, timesCB },
{ "unlink", 0, True, unlinkCB },
{ "time", 0, True, timeCB },
//
// Intercept main for argc, argv, env
//
{ "main", 0, False, mainStackInitCB},
{ 0 },
}
};
| 2.046875 | 2 |
2024-11-18T20:50:44.476356+00:00 | 2021-10-17T01:31:27 | 4568bb6ea1f4d838694601cdbf1c846c9db4873e | {
"blob_id": "4568bb6ea1f4d838694601cdbf1c846c9db4873e",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-17T01:31:27",
"content_id": "e5e9a6be4a933255f11f2470c2dfa0849d930be4",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "32e48bb5c7b9714e25bc9312f185a85e02338cc5",
"extension": "c",
"filename": "strftime.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 397209343,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1392,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/usr/libs/libc/time/strftime.c",
"provenance": "stackv2-0110.json.gz:224864",
"repo_name": "thebigcx/micro",
"revision_date": "2021-10-17T01:31:27",
"revision_id": "6400dfe82b1dcf42d2ef976ac5f7eb1f9a4a5c7c",
"snapshot_id": "3e31cc30822c89bed342797ca407079bdf52a3c4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/thebigcx/micro/6400dfe82b1dcf42d2ef976ac5f7eb1f9a4a5c7c/usr/libs/libc/time/strftime.c",
"visit_date": "2023-08-25T18:25:17.336079"
} | stackv2 | #include <time.h>
#include <string.h>
#include <langinfo.h>
#include <stdlib.h>
size_t strftime(char* s, size_t max,
const char* format,
const struct tm* tm)
{
size_t i = 0;
char buf[128];
while (*format != 0)
{
if (i + 1 >= max) return 0;
if (*format != '%')
{
s[i++] = *format++;
}
else
{
switch (*++format)
{
case '%':
s[i++] = '%';
break;
case 'a':
{
const char* day = nl_langinfo(ABDAY_1 + tm->tm_wday);
strncpy(s + i, day, strlen(day));
i += strlen(day);
break;
}
case 'b':
{
const char* mon = nl_langinfo(ABMON_1 + tm->tm_mon);
strncpy(s + i, mon, strlen(mon));
i += strlen(mon);
break;
}
case 'd':
{
itoa(tm->tm_mday, buf, 10);
strcpy(s + i, buf);
i += strlen(buf);
break;
}
case 'H':
{
itoa(tm->tm_hour, buf, 10);
strcpy(s + i, buf);
i += strlen(buf);
break;
}
case 'M':
{
itoa(tm->tm_min, buf, 10);
strcpy(s + i, buf);
i += strlen(buf);
break;
}
case 'S':
{
itoa(tm->tm_sec, buf, 10);
strcpy(s + i, buf);
i += strlen(buf);
break;
}
case 'Y':
{
itoa(tm->tm_year, buf, 10);
strcpy(s + i, buf);
i += strlen(buf);
break;
}
default:
break;
}
format++;
}
}
return i;
} | 2.546875 | 3 |
2024-11-18T20:50:44.611431+00:00 | 2018-08-03T12:03:58 | f110458c8d3c3cd224de264a30cab49ecf89efba | {
"blob_id": "f110458c8d3c3cd224de264a30cab49ecf89efba",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-03T12:03:58",
"content_id": "e9aec6b34842c468c7cfe11237a0bf212d893735",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "99f2db7c025fb44137b23e5d1d2b8a50a4f5e4f4",
"extension": "c",
"filename": "sysinit.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7559,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/Performance/Src/sysinit.c",
"provenance": "stackv2-0110.json.gz:224994",
"repo_name": "EmbeddedSystemClass/STM32-Advanced",
"revision_date": "2018-08-03T12:03:58",
"revision_id": "e6e2ca0a75322a70df85de6e374e9e960b4624b4",
"snapshot_id": "bba4a6cb98bb1a20df422e76db01c5b677547c25",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/EmbeddedSystemClass/STM32-Advanced/e6e2ca0a75322a70df85de6e374e9e960b4624b4/Performance/Src/sysinit.c",
"visit_date": "2021-05-16T21:02:37.190252"
} | stackv2 | /**
******************************************************************************
@file stm32f7_performances/Src/sysinit.c
@author MCD Application Team
@version V2.0.0
@date 24-February-2017
@brief This file contains the routine that initialize the system.
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f7xx_hal.h"
#include "sysinit.h"
#include "stm32746g_discovery_lcd.h" /* LCD_FB_START_ADDRESS */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void SystemClock_Config(void);
static void Cache_Init(void);
static void Error_Handler(void);
static void MPU_Config(void);
#if defined (DCACHE_ENABLE)
static void EnableDCache(void);
#endif
/* Private functions ---------------------------------------------------------*/
void system_init(void) {
/* Initialize hardware layer */
HAL_Init();
/* Disable ART beacause it was already enabled in HAL_Init(). Enable it if
the flag ART_ENABLE has been activated */
__HAL_FLASH_ART_DISABLE();
#if defined (ART_ENABLE)
__HAL_FLASH_ART_ENABLE();
__DSB();
#endif
#if defined (PF_ART_ENABLE)
__HAL_FLASH_PREFETCH_BUFFER_ENABLE();
#endif
/* Configure the MPU for SRAM1, SRAM2 and LCD FrameBuffer in SDRAM */
MPU_Config();
/* Enable instruction or/and data caches */
Cache_Init();
/* Configure the System clock to have a frequency of 200 MHz */
SystemClock_Config();
}
/**
@brief System Clock Configuration
The system Clock is configured as follow :
System Clock source = PLL (HSE)
SYSCLK(Hz) = 216000000
HCLK(Hz) = 216000000
AHB Prescaler = 1
APB1 Prescaler = 4
APB2 Prescaler = 2
HSE Frequency(Hz) = 25000000
PLL_M = 25
PLL_N = 432
PLL_P = 2
PLL_Q = 9
VDD(V) = 3.3
Main regulator output voltage = Scale1 mode
Flash Latency(WS) = FLASH_WS: defined in the project configuration.
@param None
@retval None
*/
static void SystemClock_Config(void) {
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_OscInitTypeDef RCC_OscInitStruct;
/* Enable HSE Oscillator and activate PLL with HSE as source */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSIState = RCC_HSI_OFF;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 25;
#ifdef DATA_IN_ExtSDRAM /* FMC max frequency is 100MHz */
RCC_OscInitStruct.PLL.PLLN = 400;
RCC_OscInitStruct.PLL.PLLQ = 8;
#else
RCC_OscInitStruct.PLL.PLLN = 432;
RCC_OscInitStruct.PLL.PLLQ = 9;
#endif
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/* activate the OverDrive to reach the 216 Mhz Frequency */
if (HAL_PWREx_EnableOverDrive() != HAL_OK) {
Error_Handler();
}
/* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2
clocks dividers */
RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_WS) != HAL_OK) {
Error_Handler();
}
}
/**
@brief Enable instruction cache or/and data cache
@param None
@retval None
*/
static void Cache_Init(void) {
#if defined (ICACHE_ENABLE)
/* Enable instruction cache */
SCB_EnableICache();
#endif /* ICACHE_ENABLE */
#if defined (DCACHE_ENABLE)
/* Invalidate and enable data cache */
EnableDCache();
#endif /* DCACHE_ENABLE */
}
/**
@brief Configure the MPU for SDRAM (LCD Frame buffer region only).
@param None
@retval None
*/
static void MPU_Config(void) {
MPU_Region_InitTypeDef MPU_InitStruct;
/* Disable the MPU */
HAL_MPU_Disable();
/* Configure the MPU attributes as WT for LCD Frame buffer region */
MPU_InitStruct.Enable = MPU_REGION_ENABLE;
MPU_InitStruct.BaseAddress = LCD_FB_START_ADDRESS;
/* Frame buffer size:
- Pixel format used is: ARGB8888 -> the pixel is represented in 32-bit (8+8+8+8) -> 4 bytes
Please refer to: BSP_LCD_LayerDefaultInit():
layer_cfg.PixelFormat = LTDC_PIXEL_FORMAT_ARGB8888;
- The LCD size is 640x480.
-> The frame buffer size = 640 x 480 x 4 = 1228800 bytes -> 1,2MByte.
The nearest MPU size value is 2MB.
*/
MPU_InitStruct.Size = MPU_REGION_SIZE_2MB;
MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS;
MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE;
MPU_InitStruct.IsCacheable = MPU_ACCESS_CACHEABLE;
MPU_InitStruct.IsShareable = MPU_ACCESS_NOT_SHAREABLE;
MPU_InitStruct.Number = MPU_REGION_NUMBER1;
MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;
MPU_InitStruct.SubRegionDisable = 0x00;
MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_ENABLE;
HAL_MPU_ConfigRegion(&MPU_InitStruct);
/* Enable the MPU */
HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);
}
/**
@brief Reconfigure the systick timer for HAL
@param None
@retval None
*/
void Systick_reconfig(void) {
/*Configure the SysTick to have interrupt in 1ms time basis*/
HAL_SYSTICK_Config(SystemCoreClock / 1000);
/*Configure the SysTick IRQ priority */
HAL_NVIC_SetPriority(SysTick_IRQn, 0xF , 0);
}
#if defined (DCACHE_ENABLE)
/**
@brief Enable Data cache
@param None
@retval None
*/
static void EnableDCache(void) {
#if (__DCACHE_PRESENT == 1U)
uint32_t ccsidr;
uint32_t sets;
uint32_t ways;
/* Level 1 data cache */
SCB->CSSELR = (0U << 1U) | 0U;
__DSB();
ccsidr = SCB->CCSIDR;
/* invalidate D-Cache */
sets = (uint32_t)(CCSIDR_SETS(ccsidr));
do {
ways = (uint32_t)(CCSIDR_WAYS(ccsidr));
do {
SCB->DCISW = (((sets << SCB_DCISW_SET_Pos) & SCB_DCISW_SET_Msk) |
((ways << SCB_DCISW_WAY_Pos) & SCB_DCISW_WAY_Msk));
__DSB();
} while (ways--);
} while (sets--);
__DSB();
/* enable D-Cache */
SCB->CCR |= (uint32_t)SCB_CCR_DC_Msk;
__DSB();
__ISB();
#endif
}
#endif
/**
@brief This function is executed in case of error occurrence.
@param None
@retval None
*/
static void Error_Handler(void) {
/* User may add here some code to deal with this error */
while (1) {
}
}
| 2.328125 | 2 |
2024-11-18T20:50:44.672806+00:00 | 2018-05-07T21:13:14 | 76561305c7ecf13871bab6c293642623701a5faf | {
"blob_id": "76561305c7ecf13871bab6c293642623701a5faf",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-07T21:13:14",
"content_id": "315b92a5a0f3a314dfc2e4116abfa7a1f17983da",
"detected_licenses": [
"MIT"
],
"directory_id": "c8265e233ee5854cd5ad6670ff08fd8096c5dfd7",
"extension": "c",
"filename": "LED.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 128528625,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 589,
"license": "MIT",
"license_type": "permissive",
"path": "/LED.c",
"provenance": "stackv2-0110.json.gz:225122",
"repo_name": "jesse7chen/PotholeDetection",
"revision_date": "2018-05-07T21:13:14",
"revision_id": "decccf4ef878d237ea21639033dce81735fa9e8f",
"snapshot_id": "03a9295ddeece77782aae326362f74073198da19",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jesse7chen/PotholeDetection/decccf4ef878d237ea21639033dce81735fa9e8f/LED.c",
"visit_date": "2020-03-09T01:57:51.981826"
} | stackv2 | #include "LED.h"
#include "LPC11xx.h"
static unsigned int ledStatus = 0;
void ledInit(void)
{
//set port 0_7 to output (high current drain in LPC1114)
LPC_GPIO0->DIR |= (1<<7);
//LPC_GPIO0->DIR |= (1UL << 6);
//LPC_GPIO0->DIR |= (1UL << 9);
}
void ledOn(void)
{
LPC_GPIO0->DATA &= ~(1<<7);
ledStatus = 1;
}
void ledOff(void)
{
LPC_GPIO0->DATA |= (1<<7);
ledStatus = 0;
}
void toggleLED(void){
if(ledStatus){
ledOff();
ledStatus = 0;
}
else{
ledOn();
ledStatus = 1;
}
}
| 2.46875 | 2 |
2024-11-18T20:50:44.801991+00:00 | 2019-04-18T13:23:03 | 1b7c9f7cc8b80430dc425c5e6cc3f000b0afad1f | {
"blob_id": "1b7c9f7cc8b80430dc425c5e6cc3f000b0afad1f",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-18T13:23:03",
"content_id": "884ba5d1e552577528fc9b5f904248c95503d6d7",
"detected_licenses": [
"Zlib"
],
"directory_id": "36948d3871b791d0a8e5eb01ca0267069bb68303",
"extension": "h",
"filename": "errors.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 179077739,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1204,
"license": "Zlib",
"license_type": "permissive",
"path": "/common/errors.h",
"provenance": "stackv2-0110.json.gz:225382",
"repo_name": "pea-pousset/gbcc",
"revision_date": "2019-04-18T13:23:03",
"revision_id": "e9bb9a1cf932c4fafee086e300d9306916ea7f65",
"snapshot_id": "29b4bd85fcc56243a1557212d84cad4e605c2335",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/pea-pousset/gbcc/e9bb9a1cf932c4fafee086e300d9306916ea7f65/common/errors.h",
"visit_date": "2020-05-04T09:53:21.673445"
} | stackv2 | /**
* \addtogroup Commons
* \{
* \addtogroup Errors
* \{
*/
#ifndef ERRORS_H
#define ERRORS_H
#include <assert.h>
#include <string.h>
#define __FILENAME__ (strrchr(__FILE__, '\\') ? \
strrchr(__FILE__, '\\') + 1 : __FILE__)
#ifndef NDEBUG
#define TODO(x) printf("[TODO: %s %s:%d]\n", x, __FILENAME__, __LINE__)
#else
#define TODO(x)
#endif
typedef enum
{
N, /**< note */
W, /**< warning */
E, /**< error */
F /**< fatal, force the program to exit */
} errtype_t;
extern int eline; /**< Line to display in an error message */
extern int ecolumn; /**< Column to display in an error message */
extern const char* const notestr;
extern const char* const warnstr;
extern const char* const errstr;
extern const char* const ferrstr;
void esetprogram(const char* const name);
void esetonfatal(void (*func)(int));
void esetfile(const char* name);
int errors();
int warnings();
int fatal();
void add_error();
void clear_errors();
void clear_fatal();
void err(errtype_t type, const char* message, ...);
void ccerr(errtype_t type, const char* message, ...);
#endif
/**
* \} Errors
* \} Commons
*/
| 2.28125 | 2 |
2024-11-18T20:50:45.020394+00:00 | 2023-08-09T21:04:51 | e504216250f09a4fbc31f32819aef3207a686857 | {
"blob_id": "e504216250f09a4fbc31f32819aef3207a686857",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-09T21:04:51",
"content_id": "785941d2958fea91fe123391b2d3e654c7be0ef4",
"detected_licenses": [
"MIT"
],
"directory_id": "060c02561085a494df306deb2f3a8fddb984c73a",
"extension": "c",
"filename": "common.c",
"fork_events_count": 33,
"gha_created_at": "2020-07-13T02:00:09",
"gha_event_created_at": "2023-09-13T14:49:28",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 279184900,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4105,
"license": "MIT",
"license_type": "permissive",
"path": "/src/common.c",
"provenance": "stackv2-0110.json.gz:225649",
"repo_name": "Interlisp/maiko",
"revision_date": "2023-08-09T21:04:51",
"revision_id": "7fce08f92c221bcb98e5f6d560aa50cb942e95b3",
"snapshot_id": "48631ae6abc9d98d5c3eeb5f5eb736adf400ea8f",
"src_encoding": "UTF-8",
"star_events_count": 110,
"url": "https://raw.githubusercontent.com/Interlisp/maiko/7fce08f92c221bcb98e5f6d560aa50cb942e95b3/src/common.c",
"visit_date": "2023-09-03T12:23:43.081470"
} | stackv2 | /* $Id: common.c,v 1.2 1999/01/03 02:06:52 sybalsky Exp $ (C) Copyright Venue, All Rights Reserved
*/
/************************************************************************/
/* */
/* (C) Copyright 1989, 1990, 1990, 1991, 1992, 1993, 1994, 1995 Venue. */
/* All Rights Reserved. */
/* Manufactured in the United States of America. */
/* */
/************************************************************************/
#include "version.h"
#include <fcntl.h> // for fcntl, F_GETFL, O_RDONLY, O_RDWR
#include <setjmp.h> // for setjmp, jmp_buf
#include <stdio.h> // for fflush, fprintf, printf, getchar, stderr
#include <stdlib.h> // for exit
#include <string.h> // for memset
#include <sys/select.h> // for fd_set
#include "commondefs.h" // for error, stab, warn
#include "dbprint.h" // for DBPRINT
#include "emlglob.h"
#include "kprintdefs.h" // for print
#include "lispemul.h" // for NIL, DLword, LispPTR
#include "lspglob.h"
#include "uraiddefs.h" // for device_after_raid, device_before_raid, ura...
#include "uraidextdefs.h" // for URMAXFXNUM, URaid_inputstring, URaid_FXarray
void stab(void) { DBPRINT(("Now in stab\n")); }
/***************************************************************
error
common sub-routine.
Printout error message.
Enter URAID.
And exit.(takeshi)
******************************************************************/
extern fd_set LispReadFds;
extern int LispKbdFd;
extern struct screen LispScreen;
extern int displaywidth, displayheight;
extern DLword *DisplayRegion68k;
extern int FrameBufferFd;
extern jmp_buf BT_jumpbuf;
extern jmp_buf SD_jumpbuf;
extern int BT_temp; /* holds the continue-character the user typed */
/* Currentry Don't care Ether re-initial */
/* Medley only */
/************************************************************************/
/* */
/* e r r o r */
/* */
/* Last-ditch error handling; enters URAID, low-level debug. */
/* */
/************************************************************************/
LispPTR Uraid_mess = NIL;
int error(const char *cp) {
char *ptr;
if (device_before_raid() < 0) {
fprintf(stderr, "Can't Enter URAID.\n");
exit(-1);
}
/* comm read */
URaid_errmess = cp;
fprintf(stderr, "\n*Error* %s\n", cp);
fflush(stdin);
fprintf(stderr, "Enter the URaid\n");
print(Uraid_mess);
putchar('\n');
/* XXX: make sure output is flushed so we can see where we are */
fflush(stdout); fflush(stderr);
URaid_currentFX = URMAXFXNUM + 1;
memset(URaid_FXarray, 0, URMAXFXNUM * 4);
#ifndef DOS
{
int stat = fcntl(fileno(stdin), F_GETFL, 0);
if (stat != O_RDONLY && stat != O_RDWR)
if (freopen("/dev/tty", "r", stdin) == NULL) {
perror("Reopen of stdin failed.");
exit(0);
}
}
#endif /* DOS */
uraidloop:
if (setjmp(BT_jumpbuf) == 1) goto uraidloop;
if (setjmp(SD_jumpbuf) == 1) goto uraidloop;
for (;;) { /* URAID LOOP */
uraid_commclear();
BT_temp = 0; /* So we get the "more" option on screen-full */
printf("\n< ");
for (ptr = URaid_inputstring; (*ptr = getchar()) != '\n'; ptr++) {}
URaid_argnum = sscanf(URaid_inputstring, "%1s%s%s", URaid_comm, URaid_arg1, URaid_arg2);
if (uraid_commands() == NIL) break;
/* XXX: make sure output is flushed so we can see where we are */
fflush(stdout); fflush(stderr);
} /* for end */
/**TopOfStack = NIL;if error is called from subr TOS will be set NIL**/
if (device_after_raid() < 0) {
printf("Can't return to Lisp. Return to UNIX?");
{
int c;
c = getchar();
if ((c == 'Y') || (c == 'y')) exit(-1);
}
fflush(stdin);
goto uraidloop;
}
return (0);
}
/************************************************************************/
/* */
/* w a r n */
/* */
/* Print a warning message, but don't stop running. */
/* */
/************************************************************************/
void warn(const char *s)
{ printf("\nWARN: %s \n", s); }
| 2.078125 | 2 |
2024-11-18T20:50:45.362497+00:00 | 2020-02-18T22:40:29 | cc6eae453d84542934c78116efa4a8a3126490bd | {
"blob_id": "cc6eae453d84542934c78116efa4a8a3126490bd",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-18T22:40:29",
"content_id": "99013e78ddc2b54729a39896437c69b47574066d",
"detected_licenses": [
"MIT"
],
"directory_id": "0d3314e57bb2e2bf04a0a0bffc841c2018efee79",
"extension": "c",
"filename": "io.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 180029400,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1338,
"license": "MIT",
"license_type": "permissive",
"path": "/src/c/io.c",
"provenance": "stackv2-0110.json.gz:225779",
"repo_name": "JakubGrobelny/aurox-lang",
"revision_date": "2020-02-18T22:40:29",
"revision_id": "ab547d75b4b2f88829961256506707bd22a8312d",
"snapshot_id": "b2115d1214788fa839caf19f260102cbedf762f5",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/JakubGrobelny/aurox-lang/ab547d75b4b2f88829961256506707bd22a8312d/src/c/io.c",
"visit_date": "2020-05-05T12:27:06.647948"
} | stackv2 | #include <stdio.h>
#include <SWI-Prolog.h>
static foreign_t pl_read_int(term_t to)
{
if (PL_is_variable(to))
{
long n;
if (!scanf("%ld", &n))
PL_fail;
return PL_unify_int64(to, n);
}
PL_fail;
}
static foreign_t pl_read_float(term_t to)
{
if (PL_is_variable(to))
{
double x;
if (!scanf("%lf", &x))
PL_fail;
return PL_unify_float(to, x);
}
PL_fail;
}
static foreign_t pl_printf(term_t in)
{
char* str;
if (PL_get_atom_chars(in, &str))
{
printf("%s", str);
PL_succeed;
}
PL_exception;
}
static foreign_t pl_read_string(term_t to)
{
if (PL_is_variable(to))
{
char buf[1024];
if (!fgets(buf, sizeof(buf), stdin))
PL_fail;
return PL_unify_string_chars(to, buf);
}
PL_fail;
}
static foreign_t pl_read_char(term_t to)
{
char buf[2] = {'\0', '\0'};
buf[0] = getchar();
return PL_unify_string_chars(to, buf);
}
install_t install_io()
{
PL_register_foreign("read_int", 1, pl_read_int, 0);
PL_register_foreign("read_float", 1, pl_read_float, 0);
PL_register_foreign("printf", 1, pl_printf, 0);
PL_register_foreign("read_char", 1, pl_read_char, 0);
PL_register_foreign("read_string", 1, pl_read_string, 0);
} | 2.578125 | 3 |
2024-11-18T20:50:45.489696+00:00 | 2023-08-27T19:14:02 | c2c48744ab9afacffbd99689692bebd0b42794fc | {
"blob_id": "c2c48744ab9afacffbd99689692bebd0b42794fc",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-27T19:14:02",
"content_id": "769e8835e8b66322bdcd8db0dbf2222de5f1b306",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "7c857119fe1505b1d80d6e62969661c06dc1a2f4",
"extension": "c",
"filename": "EmmcBlockIo.c",
"fork_events_count": 770,
"gha_created_at": "2019-09-02T08:22:14",
"gha_event_created_at": "2023-09-03T12:41:33",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 205810121,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 82122,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.c",
"provenance": "stackv2-0110.json.gz:225908",
"repo_name": "CloverHackyColor/CloverBootloader",
"revision_date": "2023-08-27T19:14:02",
"revision_id": "2711170df4f60b2ae5aa20add3e00f35cf57b7e5",
"snapshot_id": "7042ca7dd6b513d22be591a295e49071ae1482ee",
"src_encoding": "UTF-8",
"star_events_count": 4734,
"url": "https://raw.githubusercontent.com/CloverHackyColor/CloverBootloader/2711170df4f60b2ae5aa20add3e00f35cf57b7e5/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.c",
"visit_date": "2023-08-30T22:14:34.590134"
} | stackv2 | /** @file
The helper functions for BlockIo and BlockIo2 protocol.
Copyright (c) 2015 - 2017, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "EmmcDxe.h"
/**
Nonblocking I/O callback funtion when the event is signaled.
@param[in] Event The Event this notify function registered to.
@param[in] Context Pointer to the context data registered to the
Event.
**/
VOID
EFIAPI
AsyncIoCallback (
IN EFI_EVENT Event,
IN VOID *Context
)
{
EMMC_REQUEST *Request;
EFI_STATUS Status;
Status = gBS->CloseEvent (Event);
if (EFI_ERROR(Status)) {
return;
}
Request = (EMMC_REQUEST *) Context;
DEBUG_CODE_BEGIN ();
DEBUG ((EFI_D_INFO, "Emmc Async Request: CmdIndex[%d] Arg[%08x] %r\n",
Request->SdMmcCmdBlk.CommandIndex, Request->SdMmcCmdBlk.CommandArgument,
Request->Packet.TransactionStatus));
DEBUG_CODE_END ();
if (EFI_ERROR(Request->Packet.TransactionStatus)) {
Request->Token->TransactionStatus = Request->Packet.TransactionStatus;
}
RemoveEntryList (&Request->Link);
if (Request->IsEnd) {
gBS->SignalEvent (Request->Token->Event);
}
FreePool(Request);
}
/**
Send command SELECT to the device to select/deselect the device.
@param[in] Device A pointer to the EMMC_DEVICE instance.
@param[in] Rca The relative device address to use.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcSelect (
IN EMMC_DEVICE *Device,
IN UINT16 Rca
)
{
EFI_STATUS Status;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
PassThru = Device->Private->PassThru;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = EMMC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SELECT_DESELECT_CARD;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16;
Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL);
return Status;
}
/**
Send command SEND_STATUS to the device to get device status.
@param[in] Device A pointer to the EMMC_DEVICE instance.
@param[in] Rca The relative device address to use.
@param[out] DevStatus The buffer to store the device status.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcSendStatus (
IN EMMC_DEVICE *Device,
IN UINT16 Rca,
OUT UINT32 *DevStatus
)
{
EFI_STATUS Status;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
PassThru = Device->Private->PassThru;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = EMMC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SEND_STATUS;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16;
Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL);
if (!EFI_ERROR(Status)) {
CopyMem(DevStatus, &SdMmcStatusBlk.Resp0, sizeof (UINT32));
}
return Status;
}
/**
Send command SEND_CSD to the device to get the CSD register data.
@param[in] Device A pointer to the EMMC_DEVICE instance.
@param[in] Rca The relative device address to use.
@param[out] Csd The buffer to store the EMMC_CSD register data.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcGetCsd (
IN EMMC_DEVICE *Device,
IN UINT16 Rca,
OUT EMMC_CSD *Csd
)
{
EFI_STATUS Status;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
PassThru = Device->Private->PassThru;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
ZeroMem (Csd, sizeof (EMMC_CSD));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = EMMC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SEND_CSD;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2;
SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16;
Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL);
if (!EFI_ERROR(Status)) {
//
// For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12.
//
CopyMem(((UINT8*)Csd) + 1, &SdMmcStatusBlk.Resp0, sizeof (EMMC_CSD) - 1);
}
return Status;
}
/**
Send command SEND_CID to the device to get the CID register data.
@param[in] Device A pointer to the EMMC_DEVICE instance.
@param[in] Rca The relative device address to use.
@param[out] Cid The buffer to store the EMMC_CID register data.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcGetCid (
IN EMMC_DEVICE *Device,
IN UINT16 Rca,
OUT EMMC_CID *Cid
)
{
EFI_STATUS Status;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
PassThru = Device->Private->PassThru;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
ZeroMem (Cid, sizeof (EMMC_CID));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = EMMC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SEND_CID;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2;
SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16;
Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL);
if (!EFI_ERROR(Status)) {
//
// For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12.
//
CopyMem(((UINT8*)Cid) + 1, &SdMmcStatusBlk.Resp0, sizeof (EMMC_CID) - 1);
}
return Status;
}
/**
Send command SEND_EXT_CSD to the device to get the EXT_CSD register data.
@param[in] Device A pointer to the EMMC_DEVICE instance.
@param[out] ExtCsd The buffer to store the EXT_CSD register data.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcGetExtCsd (
IN EMMC_DEVICE *Device,
OUT EMMC_EXT_CSD *ExtCsd
)
{
EFI_STATUS Status;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk;
EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk;
EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet;
PassThru = Device->Private->PassThru;
ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk));
ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk));
ZeroMem (&Packet, sizeof (Packet));
ZeroMem (ExtCsd, sizeof (EMMC_EXT_CSD));
Packet.SdMmcCmdBlk = &SdMmcCmdBlk;
Packet.SdMmcStatusBlk = &SdMmcStatusBlk;
Packet.Timeout = EMMC_GENERIC_TIMEOUT;
SdMmcCmdBlk.CommandIndex = EMMC_SEND_EXT_CSD;
SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc;
SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
SdMmcCmdBlk.CommandArgument = 0x00000000;
Packet.InDataBuffer = ExtCsd;
Packet.InTransferLength = sizeof (EMMC_EXT_CSD);
Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL);
return Status;
}
/**
Set the specified EXT_CSD register field through sync or async I/O request.
@param[in] Partition A pointer to the EMMC_PARTITION instance.
@param[in] Offset The offset of the specified field in EXT_CSD register.
@param[in] Value The byte value written to the field specified by Offset.
@param[in] Token A pointer to the token associated with the transaction.
@param[in] IsEnd A boolean to show whether it's the last cmd in a series of cmds.
This parameter is only meaningful in async I/O request.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcSetExtCsd (
IN EMMC_PARTITION *Partition,
IN UINT8 Offset,
IN UINT8 Value,
IN EFI_BLOCK_IO2_TOKEN *Token,
IN BOOLEAN IsEnd
)
{
EFI_STATUS Status;
EMMC_DEVICE *Device;
EMMC_REQUEST *SetExtCsdReq;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
UINT32 CommandArgument;
EFI_TPL OldTpl;
SetExtCsdReq = NULL;
Device = Partition->Device;
PassThru = Device->Private->PassThru;
SetExtCsdReq = AllocateZeroPool(sizeof (EMMC_REQUEST));
if (SetExtCsdReq == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
SetExtCsdReq->Signature = EMMC_REQUEST_SIGNATURE;
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
InsertTailList (&Partition->Queue, &SetExtCsdReq->Link);
gBS->RestoreTPL (OldTpl);
SetExtCsdReq->Packet.SdMmcCmdBlk = &SetExtCsdReq->SdMmcCmdBlk;
SetExtCsdReq->Packet.SdMmcStatusBlk = &SetExtCsdReq->SdMmcStatusBlk;
SetExtCsdReq->Packet.Timeout = EMMC_GENERIC_TIMEOUT;
SetExtCsdReq->SdMmcCmdBlk.CommandIndex = EMMC_SWITCH;
SetExtCsdReq->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SetExtCsdReq->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1b;
//
// Write the Value to the field specified by Offset.
//
CommandArgument = (Value << 8) | (Offset << 16) | BIT24 | BIT25;
SetExtCsdReq->SdMmcCmdBlk.CommandArgument = CommandArgument;
SetExtCsdReq->IsEnd = IsEnd;
SetExtCsdReq->Token = Token;
if ((Token != NULL) && (Token->Event != NULL)) {
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
AsyncIoCallback,
SetExtCsdReq,
&SetExtCsdReq->Event
);
if (EFI_ERROR(Status)) {
goto Error;
}
} else {
SetExtCsdReq->Event = NULL;
}
Status = PassThru->PassThru (PassThru, Device->Slot, &SetExtCsdReq->Packet, SetExtCsdReq->Event);
Error:
if ((Token != NULL) && (Token->Event != NULL)) {
//
// For asynchronous operation, only free request and event in error case.
// The request and event will be freed in asynchronous callback for success case.
//
if (EFI_ERROR(Status) && (SetExtCsdReq != NULL)) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&SetExtCsdReq->Link);
gBS->RestoreTPL (OldTpl);
if (SetExtCsdReq->Event != NULL) {
gBS->CloseEvent (SetExtCsdReq->Event);
}
FreePool(SetExtCsdReq);
}
} else {
//
// For synchronous operation, free request whatever the execution result is.
//
if (SetExtCsdReq != NULL) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&SetExtCsdReq->Link);
gBS->RestoreTPL (OldTpl);
FreePool(SetExtCsdReq);
}
}
return Status;
}
/**
Set the number of blocks for a block read/write cmd through sync or async I/O request.
@param[in] Partition A pointer to the EMMC_PARTITION instance.
@param[in] BlockNum The number of blocks for transfer.
@param[in] Token A pointer to the token associated with the transaction.
@param[in] IsEnd A boolean to show whether it's the last cmd in a series of cmds.
This parameter is only meaningful in async I/O request.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcSetBlkCount (
IN EMMC_PARTITION *Partition,
IN UINT16 BlockNum,
IN EFI_BLOCK_IO2_TOKEN *Token,
IN BOOLEAN IsEnd
)
{
EFI_STATUS Status;
EMMC_DEVICE *Device;
EMMC_REQUEST *SetBlkCntReq;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EFI_TPL OldTpl;
SetBlkCntReq = NULL;
Device = Partition->Device;
PassThru = Device->Private->PassThru;
SetBlkCntReq = AllocateZeroPool(sizeof (EMMC_REQUEST));
if (SetBlkCntReq == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
SetBlkCntReq->Signature = EMMC_REQUEST_SIGNATURE;
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
InsertTailList (&Partition->Queue, &SetBlkCntReq->Link);
gBS->RestoreTPL (OldTpl);
SetBlkCntReq->Packet.SdMmcCmdBlk = &SetBlkCntReq->SdMmcCmdBlk;
SetBlkCntReq->Packet.SdMmcStatusBlk = &SetBlkCntReq->SdMmcStatusBlk;
SetBlkCntReq->Packet.Timeout = EMMC_GENERIC_TIMEOUT;
SetBlkCntReq->SdMmcCmdBlk.CommandIndex = EMMC_SET_BLOCK_COUNT;
SetBlkCntReq->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
SetBlkCntReq->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
SetBlkCntReq->SdMmcCmdBlk.CommandArgument = BlockNum;
SetBlkCntReq->IsEnd = IsEnd;
SetBlkCntReq->Token = Token;
if ((Token != NULL) && (Token->Event != NULL)) {
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
AsyncIoCallback,
SetBlkCntReq,
&SetBlkCntReq->Event
);
if (EFI_ERROR(Status)) {
goto Error;
}
} else {
SetBlkCntReq->Event = NULL;
}
Status = PassThru->PassThru (PassThru, Device->Slot, &SetBlkCntReq->Packet, SetBlkCntReq->Event);
Error:
if ((Token != NULL) && (Token->Event != NULL)) {
//
// For asynchronous operation, only free request and event in error case.
// The request and event will be freed in asynchronous callback for success case.
//
if (EFI_ERROR(Status) && (SetBlkCntReq != NULL)) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&SetBlkCntReq->Link);
gBS->RestoreTPL (OldTpl);
if (SetBlkCntReq->Event != NULL) {
gBS->CloseEvent (SetBlkCntReq->Event);
}
FreePool(SetBlkCntReq);
}
} else {
//
// For synchronous operation, free request whatever the execution result is.
//
if (SetBlkCntReq != NULL) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&SetBlkCntReq->Link);
gBS->RestoreTPL (OldTpl);
FreePool(SetBlkCntReq);
}
}
return Status;
}
/**
Read blocks through security protocol cmds with the way of sync or async I/O request.
@param[in] Partition A pointer to the EMMC_PARTITION instance.
@param[in] SecurityProtocolId The value of the "Security Protocol" parameter of
the security protocol command to be sent.
@param[in] SecurityProtocolSpecificData The value of the "Security Protocol Specific" parameter
of the security protocol command to be sent.
@param[in] PayloadBufferSize Size in bytes of the payload data buffer.
@param[out] PayloadBuffer A pointer to a destination buffer to store the security
protocol command specific payload data for the security
protocol command. The caller is responsible for having
either implicit or explicit ownership of the buffer.
@param[in] IsRead Indicates it is a read or write operation.
@param[in] Timeout The timeout value, in 100ns units.
@param[in] Token A pointer to the token associated with the transaction.
@param[in] IsEnd A boolean to show whether it's the last cmd in a series of cmds.
This parameter is only meaningful in async I/O request.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcProtocolInOut (
IN EMMC_PARTITION *Partition,
IN UINT8 SecurityProtocol,
IN UINT16 SecurityProtocolSpecificData,
IN UINTN PayloadBufferSize,
OUT VOID *PayloadBuffer,
IN BOOLEAN IsRead,
IN UINT64 Timeout,
IN EFI_BLOCK_IO2_TOKEN *Token,
IN BOOLEAN IsEnd
)
{
EFI_STATUS Status;
EMMC_DEVICE *Device;
EMMC_REQUEST *ProtocolReq;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EFI_TPL OldTpl;
ProtocolReq = NULL;
Device = Partition->Device;
PassThru = Device->Private->PassThru;
ProtocolReq = AllocateZeroPool(sizeof (EMMC_REQUEST));
if (ProtocolReq == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
ProtocolReq->Signature = EMMC_REQUEST_SIGNATURE;
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
InsertTailList (&Partition->Queue, &ProtocolReq->Link);
gBS->RestoreTPL (OldTpl);
ProtocolReq->Packet.SdMmcCmdBlk = &ProtocolReq->SdMmcCmdBlk;
ProtocolReq->Packet.SdMmcStatusBlk = &ProtocolReq->SdMmcStatusBlk;
if (IsRead) {
ProtocolReq->Packet.InDataBuffer = PayloadBuffer;
ProtocolReq->Packet.InTransferLength = (UINT32)PayloadBufferSize;
ProtocolReq->SdMmcCmdBlk.CommandIndex = EMMC_PROTOCOL_RD;
ProtocolReq->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc;
ProtocolReq->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
} else {
ProtocolReq->Packet.OutDataBuffer = PayloadBuffer;
ProtocolReq->Packet.OutTransferLength = (UINT32)PayloadBufferSize;
ProtocolReq->SdMmcCmdBlk.CommandIndex = EMMC_PROTOCOL_WR;
ProtocolReq->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc;
ProtocolReq->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
}
ProtocolReq->SdMmcCmdBlk.CommandArgument = (SecurityProtocol << 8) | (SecurityProtocolSpecificData << 16);
//
// Convert to 1 microsecond unit.
//
ProtocolReq->Packet.Timeout = DivU64x32 (Timeout, 10) + 1;
ProtocolReq->IsEnd = IsEnd;
ProtocolReq->Token = Token;
if ((Token != NULL) && (Token->Event != NULL)) {
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
AsyncIoCallback,
ProtocolReq,
&ProtocolReq->Event
);
if (EFI_ERROR(Status)) {
goto Error;
}
} else {
ProtocolReq->Event = NULL;
}
Status = PassThru->PassThru (PassThru, Device->Slot, &ProtocolReq->Packet, ProtocolReq->Event);
Error:
if ((Token != NULL) && (Token->Event != NULL)) {
//
// For asynchronous operation, only free request and event in error case.
// The request and event will be freed in asynchronous callback for success case.
//
if (EFI_ERROR(Status) && (ProtocolReq != NULL)) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&ProtocolReq->Link);
gBS->RestoreTPL (OldTpl);
if (ProtocolReq->Event != NULL) {
gBS->CloseEvent (ProtocolReq->Event);
}
FreePool(ProtocolReq);
}
} else {
//
// For synchronous operation, free request whatever the execution result is.
//
if (ProtocolReq != NULL) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&ProtocolReq->Link);
gBS->RestoreTPL (OldTpl);
FreePool(ProtocolReq);
}
}
return Status;
}
/**
Read/write multiple blocks through sync or async I/O request.
@param[in] Partition A pointer to the EMMC_PARTITION instance.
@param[in] Lba The starting logical block address to be read/written.
The caller is responsible for reading/writing to only
legitimate locations.
@param[in] Buffer A pointer to the destination/source buffer for the data.
@param[in] BufferSize Size of Buffer, must be a multiple of device block size.
@param[in] IsRead Indicates it is a read or write operation.
@param[in] Token A pointer to the token associated with the transaction.
@param[in] IsEnd A boolean to show whether it's the last cmd in a series of cmds.
This parameter is only meaningful in async I/O request.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcRwMultiBlocks (
IN EMMC_PARTITION *Partition,
IN EFI_LBA Lba,
IN VOID *Buffer,
IN UINTN BufferSize,
IN BOOLEAN IsRead,
IN EFI_BLOCK_IO2_TOKEN *Token,
IN BOOLEAN IsEnd
)
{
EFI_STATUS Status;
EMMC_DEVICE *Device;
EMMC_REQUEST *RwMultiBlkReq;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EFI_TPL OldTpl;
RwMultiBlkReq = NULL;
Device = Partition->Device;
PassThru = Device->Private->PassThru;
RwMultiBlkReq = AllocateZeroPool(sizeof (EMMC_REQUEST));
if (RwMultiBlkReq == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
RwMultiBlkReq->Signature = EMMC_REQUEST_SIGNATURE;
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
InsertTailList (&Partition->Queue, &RwMultiBlkReq->Link);
gBS->RestoreTPL (OldTpl);
RwMultiBlkReq->Packet.SdMmcCmdBlk = &RwMultiBlkReq->SdMmcCmdBlk;
RwMultiBlkReq->Packet.SdMmcStatusBlk = &RwMultiBlkReq->SdMmcStatusBlk;
//
// Calculate timeout value through the below formula.
// Timeout = (transfer size) / (2MB/s).
// Taking 2MB/s as divisor is because it's nearest to the eMMC lowest
// transfer speed (2.4MB/s).
// Refer to eMMC 5.0 spec section 6.9.1 for details.
//
RwMultiBlkReq->Packet.Timeout = (BufferSize / (2 * 1024 * 1024) + 1) * 1000 * 1000;
if (IsRead) {
RwMultiBlkReq->Packet.InDataBuffer = Buffer;
RwMultiBlkReq->Packet.InTransferLength = (UINT32)BufferSize;
RwMultiBlkReq->SdMmcCmdBlk.CommandIndex = EMMC_READ_MULTIPLE_BLOCK;
RwMultiBlkReq->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc;
RwMultiBlkReq->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
} else {
RwMultiBlkReq->Packet.OutDataBuffer = Buffer;
RwMultiBlkReq->Packet.OutTransferLength = (UINT32)BufferSize;
RwMultiBlkReq->SdMmcCmdBlk.CommandIndex = EMMC_WRITE_MULTIPLE_BLOCK;
RwMultiBlkReq->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc;
RwMultiBlkReq->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
}
if (Partition->Device->SectorAddressing) {
RwMultiBlkReq->SdMmcCmdBlk.CommandArgument = (UINT32)Lba;
} else {
RwMultiBlkReq->SdMmcCmdBlk.CommandArgument = (UINT32)MultU64x32 (Lba, Partition->BlockMedia.BlockSize);
}
RwMultiBlkReq->IsEnd = IsEnd;
RwMultiBlkReq->Token = Token;
if ((Token != NULL) && (Token->Event != NULL)) {
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
AsyncIoCallback,
RwMultiBlkReq,
&RwMultiBlkReq->Event
);
if (EFI_ERROR(Status)) {
goto Error;
}
} else {
RwMultiBlkReq->Event = NULL;
}
Status = PassThru->PassThru (PassThru, Device->Slot, &RwMultiBlkReq->Packet, RwMultiBlkReq->Event);
Error:
if ((Token != NULL) && (Token->Event != NULL)) {
//
// For asynchronous operation, only free request and event in error case.
// The request and event will be freed in asynchronous callback for success case.
//
if (EFI_ERROR(Status) && (RwMultiBlkReq != NULL)) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&RwMultiBlkReq->Link);
gBS->RestoreTPL (OldTpl);
if (RwMultiBlkReq->Event != NULL) {
gBS->CloseEvent (RwMultiBlkReq->Event);
}
FreePool(RwMultiBlkReq);
}
} else {
//
// For synchronous operation, free request whatever the execution result is.
//
if (RwMultiBlkReq != NULL) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&RwMultiBlkReq->Link);
gBS->RestoreTPL (OldTpl);
FreePool(RwMultiBlkReq);
}
}
return Status;
}
/**
This function transfers data from/to EMMC device.
@param[in] Partition A pointer to the EMMC_PARTITION instance.
@param[in] MediaId The media ID that the read/write request is for.
@param[in] Lba The starting logical block address to be read/written.
The caller is responsible for reading/writing to only
legitimate locations.
@param[in, out] Buffer A pointer to the destination/source buffer for the data.
@param[in] BufferSize Size of Buffer, must be a multiple of device block size.
@param[in] IsRead Indicates it is a read or write operation.
@param[in, out] Token A pointer to the token associated with the transaction.
@retval EFI_SUCCESS The data was read/written correctly to the device.
@retval EFI_WRITE_PROTECTED The device can not be read/written to.
@retval EFI_DEVICE_ERROR The device reported an error while performing the read/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 read/write request contains LBAs that are not valid,
or the buffer is not on proper alignment.
**/
EFI_STATUS
EmmcReadWrite (
IN EMMC_PARTITION *Partition,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN OUT VOID *Buffer,
IN UINTN BufferSize,
IN BOOLEAN IsRead,
IN OUT EFI_BLOCK_IO2_TOKEN *Token
)
{
EFI_STATUS Status;
EMMC_DEVICE *Device;
EFI_BLOCK_IO_MEDIA *Media;
UINTN BlockSize;
UINTN BlockNum;
UINTN IoAlign;
UINT8 PartitionConfig;
UINTN Remaining;
UINT32 MaxBlock;
BOOLEAN LastRw;
Status = EFI_SUCCESS;
Device = Partition->Device;
Media = &Partition->BlockMedia;
LastRw = FALSE;
if (MediaId != Media->MediaId) {
return EFI_MEDIA_CHANGED;
}
if (!IsRead && Media->ReadOnly) {
return EFI_WRITE_PROTECTED;
}
//
// Check parameters.
//
if (Buffer == NULL) {
return EFI_INVALID_PARAMETER;
}
if (BufferSize == 0) {
if ((Token != NULL) && (Token->Event != NULL)) {
Token->TransactionStatus = EFI_SUCCESS;
gBS->SignalEvent (Token->Event);
}
return EFI_SUCCESS;
}
BlockSize = Media->BlockSize;
if ((BufferSize % BlockSize) != 0) {
return EFI_BAD_BUFFER_SIZE;
}
BlockNum = BufferSize / BlockSize;
if ((Lba + BlockNum - 1) > Media->LastBlock) {
return EFI_INVALID_PARAMETER;
}
IoAlign = Media->IoAlign;
if (IoAlign > 0 && (((UINTN) Buffer & (IoAlign - 1)) != 0)) {
return EFI_INVALID_PARAMETER;
}
if ((Token != NULL) && (Token->Event != NULL)) {
Token->TransactionStatus = EFI_SUCCESS;
}
//
// Check if needs to switch partition access.
//
PartitionConfig = Device->ExtCsd.PartitionConfig;
if ((PartitionConfig & 0x7) != Partition->PartitionType) {
PartitionConfig &= (UINT8)~0x7;
PartitionConfig |= Partition->PartitionType;
Status = EmmcSetExtCsd (Partition, OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), PartitionConfig, Token, FALSE);
if (EFI_ERROR(Status)) {
return Status;
}
Device->ExtCsd.PartitionConfig = PartitionConfig;
}
//
// Start to execute data transfer. The max block number in single cmd is 65535 blocks.
//
Remaining = BlockNum;
MaxBlock = 0xFFFF;
while (Remaining > 0) {
if (Remaining <= MaxBlock) {
BlockNum = Remaining;
LastRw = TRUE;
} else {
BlockNum = MaxBlock;
}
Status = EmmcSetBlkCount (Partition, (UINT16)BlockNum, Token, FALSE);
if (EFI_ERROR(Status)) {
return Status;
}
BufferSize = BlockNum * BlockSize;
Status = EmmcRwMultiBlocks (Partition, Lba, Buffer, BufferSize, IsRead, Token, LastRw);
if (EFI_ERROR(Status)) {
return Status;
}
DEBUG ((DEBUG_BLKIO,
"Emmc%a(): Part %d Lba 0x%x BlkNo 0x%x Event %p with %r\n",
IsRead ? "Read " : "Write", Partition->PartitionType, Lba, BlockNum,
(Token != NULL) ? Token->Event : NULL, Status));
Lba += BlockNum;
Buffer = (UINT8*)Buffer + BufferSize;
Remaining -= BlockNum;
}
return Status;
}
/**
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
EmmcReset (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN BOOLEAN ExtendedVerification
)
{
EFI_STATUS Status;
EMMC_PARTITION *Partition;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
Partition = EMMC_PARTITION_DATA_FROM_BLKIO (This);
PassThru = Partition->Device->Private->PassThru;
Status = PassThru->ResetDevice (PassThru, Partition->Device->Slot);
if (EFI_ERROR(Status)) {
Status = EFI_DEVICE_ERROR;
}
return Status;
}
/**
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
EmmcReadBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
)
{
EFI_STATUS Status;
EMMC_PARTITION *Partition;
Partition = EMMC_PARTITION_DATA_FROM_BLKIO (This);
Status = EmmcReadWrite (Partition, MediaId, Lba, Buffer, BufferSize, TRUE, NULL);
return Status;
}
/**
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
EmmcWriteBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
IN VOID *Buffer
)
{
EFI_STATUS Status;
EMMC_PARTITION *Partition;
Partition = EMMC_PARTITION_DATA_FROM_BLKIO (This);
Status = EmmcReadWrite (Partition, MediaId, Lba, Buffer, BufferSize, FALSE, NULL);
return Status;
}
/**
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 writing back the data
@retval EFI_NO_MEDIA There is no media in the device.
**/
EFI_STATUS
EFIAPI
EmmcFlushBlocks (
IN EFI_BLOCK_IO_PROTOCOL *This
)
{
//
// return directly
//
return EFI_SUCCESS;
}
/**
Reset the Block Device.
@param[in] This Indicates a pointer to the calling context.
@param[in] 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
EmmcResetEx (
IN EFI_BLOCK_IO2_PROTOCOL *This,
IN BOOLEAN ExtendedVerification
)
{
EMMC_PARTITION *Partition;
LIST_ENTRY *Link;
LIST_ENTRY *NextLink;
EMMC_REQUEST *Request;
EFI_TPL OldTpl;
Partition = EMMC_PARTITION_DATA_FROM_BLKIO2 (This);
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
for (Link = GetFirstNode (&Partition->Queue);
!IsNull (&Partition->Queue, Link);
Link = NextLink) {
NextLink = GetNextNode (&Partition->Queue, Link);
RemoveEntryList (Link);
Request = EMMC_REQUEST_FROM_LINK (Link);
gBS->CloseEvent (Request->Event);
Request->Token->TransactionStatus = EFI_ABORTED;
if (Request->IsEnd) {
gBS->SignalEvent (Request->Token->Event);
}
FreePool(Request);
}
gBS->RestoreTPL (OldTpl);
return EFI_SUCCESS;
}
/**
Read BufferSize bytes from Lba into Buffer.
@param[in] This Indicates a pointer to the calling context.
@param[in] MediaId Id of the media, changes every time the media is replaced.
@param[in] Lba The starting Logical Block Address to read from.
@param[in, out] Token A pointer to the token associated with the transaction.
@param[in] BufferSize Size of Buffer, must be a multiple of device block size.
@param[out] 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 read request was queued if Event is not NULL.
The data was read correctly from the device if
the Event is NULL.
@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 is not for the current media.
@retval EFI_BAD_BUFFER_SIZE The BufferSize parameter is not a multiple of the
intrinsic 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.
@retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack
of resources.
**/
EFI_STATUS
EFIAPI
EmmcReadBlocksEx (
IN EFI_BLOCK_IO2_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN OUT EFI_BLOCK_IO2_TOKEN *Token,
IN UINTN BufferSize,
OUT VOID *Buffer
)
{
EFI_STATUS Status;
EMMC_PARTITION *Partition;
Partition = EMMC_PARTITION_DATA_FROM_BLKIO2 (This);
Status = EmmcReadWrite (Partition, MediaId, Lba, Buffer, BufferSize, TRUE, Token);
return Status;
}
/**
Write BufferSize bytes from Lba into Buffer.
@param[in] This Indicates a pointer to the calling context.
@param[in] MediaId The media ID that the write request is for.
@param[in] Lba The starting logical block address to be written. The
caller is responsible for writing to only legitimate
locations.
@param[in, out] Token A pointer to the token associated with the transaction.
@param[in] BufferSize Size of Buffer, must be a multiple of device block size.
@param[in] 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
EmmcWriteBlocksEx (
IN EFI_BLOCK_IO2_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN OUT EFI_BLOCK_IO2_TOKEN *Token,
IN UINTN BufferSize,
IN VOID *Buffer
)
{
EFI_STATUS Status;
EMMC_PARTITION *Partition;
Partition = EMMC_PARTITION_DATA_FROM_BLKIO2 (This);
Status = EmmcReadWrite (Partition, MediaId, Lba, Buffer, BufferSize, FALSE, Token);
return Status;
}
/**
Flush the Block Device.
@param[in] This Indicates a pointer to the calling context.
@param[in, out] Token A pointer to the token associated with the transaction.
@retval EFI_SUCCESS All outstanding data was written to the device
@retval EFI_DEVICE_ERROR The device reported an error while writing back the data
@retval EFI_NO_MEDIA There is no media in the device.
**/
EFI_STATUS
EFIAPI
EmmcFlushBlocksEx (
IN EFI_BLOCK_IO2_PROTOCOL *This,
IN OUT EFI_BLOCK_IO2_TOKEN *Token
)
{
//
// Signal event and return directly.
//
if (Token != NULL && Token->Event != NULL) {
Token->TransactionStatus = EFI_SUCCESS;
gBS->SignalEvent (Token->Event);
}
return EFI_SUCCESS;
}
/**
Send a security protocol command to a device that receives data and/or the result
of one or more commands sent by SendData.
The ReceiveData function sends a security protocol command to the given MediaId.
The security protocol command sent is defined by SecurityProtocolId and contains
the security protocol specific data SecurityProtocolSpecificData. The function
returns the data from the security protocol command in PayloadBuffer.
For devices supporting the SCSI command set, the security protocol command is sent
using the SECURITY PROTOCOL IN command defined in SPC-4.
For devices supporting the ATA command set, the security protocol command is sent
using one of the TRUSTED RECEIVE commands defined in ATA8-ACS if PayloadBufferSize
is non-zero.
If the PayloadBufferSize is zero, the security protocol command is sent using the
Trusted Non-Data command defined in ATA8-ACS.
If PayloadBufferSize is too small to store the available data from the security
protocol command, the function shall copy PayloadBufferSize bytes into the
PayloadBuffer and return EFI_WARN_BUFFER_TOO_SMALL.
If PayloadBuffer or PayloadTransferSize is NULL and PayloadBufferSize is non-zero,
the function shall return EFI_INVALID_PARAMETER.
If the given MediaId does not support security protocol commands, the function shall
return EFI_UNSUPPORTED. If there is no media in the device, the function returns
EFI_NO_MEDIA. If the MediaId is not the ID for the current media in the device,
the function returns EFI_MEDIA_CHANGED.
If the security protocol fails to complete within the Timeout period, the function
shall return EFI_TIMEOUT.
If the security protocol command completes without an error, the function shall
return EFI_SUCCESS. If the security protocol command completes with an error, the
function shall return EFI_DEVICE_ERROR.
@param[in] This Indicates a pointer to the calling context.
@param[in] MediaId ID of the medium to receive data from.
@param[in] Timeout The timeout, in 100ns units, to use for the execution
of the security protocol command. A Timeout value of 0
means that this function will wait indefinitely for the
security protocol command to execute. If Timeout is greater
than zero, then this function will return EFI_TIMEOUT
if the time required to execute the receive data command
is greater than Timeout.
@param[in] SecurityProtocolId The value of the "Security Protocol" parameter of
the security protocol command to be sent.
@param[in] SecurityProtocolSpecificData The value of the "Security Protocol Specific" parameter
of the security protocol command to be sent.
@param[in] PayloadBufferSize Size in bytes of the payload data buffer.
@param[out] PayloadBuffer A pointer to a destination buffer to store the security
protocol command specific payload data for the security
protocol command. The caller is responsible for having
either implicit or explicit ownership of the buffer.
@param[out] PayloadTransferSize A pointer to a buffer to store the size in bytes of the
data written to the payload data buffer.
@param[in] IsRead Indicates it is a read or write operation.
@retval EFI_SUCCESS The security protocol command completed successfully.
@retval EFI_WARN_BUFFER_TOO_SMALL The PayloadBufferSize was too small to store the available
data from the device. The PayloadBuffer contains the truncated data.
@retval EFI_UNSUPPORTED The given MediaId does not support security protocol commands.
@retval EFI_DEVICE_ERROR The security protocol command completed with an error.
@retval EFI_NO_MEDIA There is no media in the device.
@retval EFI_MEDIA_CHANGED The MediaId is not for the current media.
@retval EFI_INVALID_PARAMETER The PayloadBuffer or PayloadTransferSize is NULL and
PayloadBufferSize is non-zero.
@retval EFI_TIMEOUT A timeout occurred while waiting for the security
protocol command to execute.
**/
EFI_STATUS
EFIAPI
EmmcSecurityProtocolInOut (
IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This,
IN UINT32 MediaId,
IN UINT64 Timeout,
IN UINT8 SecurityProtocolId,
IN UINT16 SecurityProtocolSpecificData,
IN UINTN PayloadBufferSize,
OUT VOID *PayloadBuffer,
OUT UINTN *PayloadTransferSize,
IN BOOLEAN IsRead
)
{
EFI_STATUS Status;
EMMC_PARTITION *Partition;
EMMC_DEVICE *Device;
EFI_BLOCK_IO_MEDIA *Media;
UINTN BlockSize;
UINTN BlockNum;
UINTN IoAlign;
UINTN Remaining;
UINT32 MaxBlock;
UINT8 PartitionConfig;
Status = EFI_SUCCESS;
Partition = EMMC_PARTITION_DATA_FROM_SSP (This);
Device = Partition->Device;
Media = &Partition->BlockMedia;
if (PayloadTransferSize != NULL) {
*PayloadTransferSize = 0;
}
if ((PayloadBuffer == NULL) && (PayloadBufferSize != 0)) {
return EFI_INVALID_PARAMETER;
}
if (MediaId != Media->MediaId) {
return EFI_MEDIA_CHANGED;
}
if (PayloadBufferSize == 0) {
return EFI_SUCCESS;
}
BlockSize = Media->BlockSize;
if ((PayloadBufferSize % BlockSize) != 0) {
return EFI_BAD_BUFFER_SIZE;
}
BlockNum = PayloadBufferSize / BlockSize;
IoAlign = Media->IoAlign;
if (IoAlign > 0 && (((UINTN) PayloadBuffer & (IoAlign - 1)) != 0)) {
return EFI_INVALID_PARAMETER;
}
//
// Security protocol interface is synchronous transfer.
// Waiting for async I/O list to be empty before any operation.
//
while (!IsListEmpty (&Partition->Queue));
//
// Check if needs to switch partition access.
//
PartitionConfig = Device->ExtCsd.PartitionConfig;
if ((PartitionConfig & 0x7) != Partition->PartitionType) {
PartitionConfig &= (UINT8)~0x7;
PartitionConfig |= Partition->PartitionType;
Status = EmmcSetExtCsd (Partition, OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), PartitionConfig, NULL, FALSE);
if (EFI_ERROR(Status)) {
return Status;
}
Device->ExtCsd.PartitionConfig = PartitionConfig;
}
//
// Start to execute data transfer. The max block number in single cmd is 65535 blocks.
//
Remaining = BlockNum;
MaxBlock = 0xFFFF;
while (Remaining > 0) {
if (Remaining <= MaxBlock) {
BlockNum = Remaining;
} else {
BlockNum = MaxBlock;
}
Status = EmmcSetBlkCount (Partition, (UINT16)BlockNum, NULL, FALSE);
if (EFI_ERROR(Status)) {
return Status;
}
PayloadBufferSize = BlockNum * BlockSize;
Status = EmmcProtocolInOut (Partition, SecurityProtocolId, SecurityProtocolSpecificData, PayloadBufferSize, PayloadBuffer, IsRead, Timeout, NULL, FALSE);
if (EFI_ERROR(Status)) {
return Status;
}
PayloadBuffer = (UINT8*)PayloadBuffer + PayloadBufferSize;
Remaining -= BlockNum;
if (PayloadTransferSize != NULL) {
*PayloadTransferSize += PayloadBufferSize;
}
}
return Status;
}
/**
Send a security protocol command to a device that receives data and/or the result
of one or more commands sent by SendData.
The ReceiveData function sends a security protocol command to the given MediaId.
The security protocol command sent is defined by SecurityProtocolId and contains
the security protocol specific data SecurityProtocolSpecificData. The function
returns the data from the security protocol command in PayloadBuffer.
For devices supporting the SCSI command set, the security protocol command is sent
using the SECURITY PROTOCOL IN command defined in SPC-4.
For devices supporting the ATA command set, the security protocol command is sent
using one of the TRUSTED RECEIVE commands defined in ATA8-ACS if PayloadBufferSize
is non-zero.
If the PayloadBufferSize is zero, the security protocol command is sent using the
Trusted Non-Data command defined in ATA8-ACS.
If PayloadBufferSize is too small to store the available data from the security
protocol command, the function shall copy PayloadBufferSize bytes into the
PayloadBuffer and return EFI_WARN_BUFFER_TOO_SMALL.
If PayloadBuffer or PayloadTransferSize is NULL and PayloadBufferSize is non-zero,
the function shall return EFI_INVALID_PARAMETER.
If the given MediaId does not support security protocol commands, the function shall
return EFI_UNSUPPORTED. If there is no media in the device, the function returns
EFI_NO_MEDIA. If the MediaId is not the ID for the current media in the device,
the function returns EFI_MEDIA_CHANGED.
If the security protocol fails to complete within the Timeout period, the function
shall return EFI_TIMEOUT.
If the security protocol command completes without an error, the function shall
return EFI_SUCCESS. If the security protocol command completes with an error, the
function shall return EFI_DEVICE_ERROR.
@param This Indicates a pointer to the calling context.
@param MediaId ID of the medium to receive data from.
@param Timeout The timeout, in 100ns units, to use for the execution
of the security protocol command. A Timeout value of 0
means that this function will wait indefinitely for the
security protocol command to execute. If Timeout is greater
than zero, then this function will return EFI_TIMEOUT
if the time required to execute the receive data command
is greater than Timeout.
@param SecurityProtocolId The value of the "Security Protocol" parameter of
the security protocol command to be sent.
@param SecurityProtocolSpecificData The value of the "Security Protocol Specific" parameter
of the security protocol command to be sent.
@param PayloadBufferSize Size in bytes of the payload data buffer.
@param PayloadBuffer A pointer to a destination buffer to store the security
protocol command specific payload data for the security
protocol command. The caller is responsible for having
either implicit or explicit ownership of the buffer.
@param PayloadTransferSize A pointer to a buffer to store the size in bytes of the
data written to the payload data buffer.
@retval EFI_SUCCESS The security protocol command completed successfully.
@retval EFI_WARN_BUFFER_TOO_SMALL The PayloadBufferSize was too small to store the available
data from the device. The PayloadBuffer contains the truncated data.
@retval EFI_UNSUPPORTED The given MediaId does not support security protocol commands.
@retval EFI_DEVICE_ERROR The security protocol command completed with an error.
@retval EFI_NO_MEDIA There is no media in the device.
@retval EFI_MEDIA_CHANGED The MediaId is not for the current media.
@retval EFI_INVALID_PARAMETER The PayloadBuffer or PayloadTransferSize is NULL and
PayloadBufferSize is non-zero.
@retval EFI_TIMEOUT A timeout occurred while waiting for the security
protocol command to execute.
**/
EFI_STATUS
EFIAPI
EmmcSecurityProtocolIn (
IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This,
IN UINT32 MediaId,
IN UINT64 Timeout,
IN UINT8 SecurityProtocolId,
IN UINT16 SecurityProtocolSpecificData,
IN UINTN PayloadBufferSize,
OUT VOID *PayloadBuffer,
OUT UINTN *PayloadTransferSize
)
{
EFI_STATUS Status;
if ((PayloadTransferSize == NULL) && PayloadBufferSize != 0) {
return EFI_INVALID_PARAMETER;
}
Status = EmmcSecurityProtocolInOut (
This,
MediaId,
Timeout,
SecurityProtocolId,
SecurityProtocolSpecificData,
PayloadBufferSize,
PayloadBuffer,
PayloadTransferSize,
TRUE
);
return Status;
}
/**
Send a security protocol command to a device.
The SendData function sends a security protocol command containing the payload
PayloadBuffer to the given MediaId. The security protocol command sent is
defined by SecurityProtocolId and contains the security protocol specific data
SecurityProtocolSpecificData. If the underlying protocol command requires a
specific padding for the command payload, the SendData function shall add padding
bytes to the command payload to satisfy the padding requirements.
For devices supporting the SCSI command set, the security protocol command is sent
using the SECURITY PROTOCOL OUT command defined in SPC-4.
For devices supporting the ATA command set, the security protocol command is sent
using one of the TRUSTED SEND commands defined in ATA8-ACS if PayloadBufferSize
is non-zero. If the PayloadBufferSize is zero, the security protocol command is
sent using the Trusted Non-Data command defined in ATA8-ACS.
If PayloadBuffer is NULL and PayloadBufferSize is non-zero, the function shall
return EFI_INVALID_PARAMETER.
If the given MediaId does not support security protocol commands, the function
shall return EFI_UNSUPPORTED. If there is no media in the device, the function
returns EFI_NO_MEDIA. If the MediaId is not the ID for the current media in the
device, the function returns EFI_MEDIA_CHANGED.
If the security protocol fails to complete within the Timeout period, the function
shall return EFI_TIMEOUT.
If the security protocol command completes without an error, the function shall return
EFI_SUCCESS. If the security protocol command completes with an error, the function
shall return EFI_DEVICE_ERROR.
@param This Indicates a pointer to the calling context.
@param MediaId ID of the medium to receive data from.
@param Timeout The timeout, in 100ns units, to use for the execution
of the security protocol command. A Timeout value of 0
means that this function will wait indefinitely for the
security protocol command to execute. If Timeout is greater
than zero, then this function will return EFI_TIMEOUT
if the time required to execute the receive data command
is greater than Timeout.
@param SecurityProtocolId The value of the "Security Protocol" parameter of
the security protocol command to be sent.
@param SecurityProtocolSpecificData The value of the "Security Protocol Specific" parameter
of the security protocol command to be sent.
@param PayloadBufferSize Size in bytes of the payload data buffer.
@param PayloadBuffer A pointer to a destination buffer to store the security
protocol command specific payload data for the security
protocol command.
@retval EFI_SUCCESS The security protocol command completed successfully.
@retval EFI_UNSUPPORTED The given MediaId does not support security protocol commands.
@retval EFI_DEVICE_ERROR The security protocol command completed with an error.
@retval EFI_NO_MEDIA There is no media in the device.
@retval EFI_MEDIA_CHANGED The MediaId is not for the current media.
@retval EFI_INVALID_PARAMETER The PayloadBuffer is NULL and PayloadBufferSize is non-zero.
@retval EFI_TIMEOUT A timeout occurred while waiting for the security
protocol command to execute.
**/
EFI_STATUS
EFIAPI
EmmcSecurityProtocolOut (
IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This,
IN UINT32 MediaId,
IN UINT64 Timeout,
IN UINT8 SecurityProtocolId,
IN UINT16 SecurityProtocolSpecificData,
IN UINTN PayloadBufferSize,
IN VOID *PayloadBuffer
)
{
EFI_STATUS Status;
Status = EmmcSecurityProtocolInOut (
This,
MediaId,
Timeout,
SecurityProtocolId,
SecurityProtocolSpecificData,
PayloadBufferSize,
PayloadBuffer,
NULL,
FALSE
);
return Status;
}
/**
Set the erase start address through sync or async I/O request.
@param[in] Partition A pointer to the EMMC_PARTITION instance.
@param[in] StartLba The starting logical block address to be erased.
@param[in] Token A pointer to the token associated with the transaction.
@param[in] IsEnd A boolean to show whether it's the last cmd in a series of cmds.
This parameter is only meaningful in async I/O request.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcEraseBlockStart (
IN EMMC_PARTITION *Partition,
IN EFI_LBA StartLba,
IN EFI_BLOCK_IO2_TOKEN *Token,
IN BOOLEAN IsEnd
)
{
EFI_STATUS Status;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EMMC_DEVICE *Device;
EMMC_REQUEST *EraseBlockStart;
EFI_TPL OldTpl;
EraseBlockStart = NULL;
Device = Partition->Device;
PassThru = Device->Private->PassThru;
EraseBlockStart = AllocateZeroPool(sizeof (EMMC_REQUEST));
if (EraseBlockStart == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
EraseBlockStart->Signature = EMMC_REQUEST_SIGNATURE;
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
InsertTailList (&Partition->Queue, &EraseBlockStart->Link);
gBS->RestoreTPL (OldTpl);
EraseBlockStart->Packet.SdMmcCmdBlk = &EraseBlockStart->SdMmcCmdBlk;
EraseBlockStart->Packet.SdMmcStatusBlk = &EraseBlockStart->SdMmcStatusBlk;
EraseBlockStart->Packet.Timeout = EMMC_GENERIC_TIMEOUT;
EraseBlockStart->SdMmcCmdBlk.CommandIndex = EMMC_ERASE_GROUP_START;
EraseBlockStart->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
EraseBlockStart->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
if (Device->SectorAddressing) {
EraseBlockStart->SdMmcCmdBlk.CommandArgument = (UINT32)StartLba;
} else {
EraseBlockStart->SdMmcCmdBlk.CommandArgument = (UINT32)MultU64x32 (StartLba, Partition->BlockMedia.BlockSize);
}
EraseBlockStart->IsEnd = IsEnd;
EraseBlockStart->Token = Token;
if ((Token != NULL) && (Token->Event != NULL)) {
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
AsyncIoCallback,
EraseBlockStart,
&EraseBlockStart->Event
);
if (EFI_ERROR(Status)) {
goto Error;
}
} else {
EraseBlockStart->Event = NULL;
}
Status = PassThru->PassThru (PassThru, Device->Slot, &EraseBlockStart->Packet, EraseBlockStart->Event);
Error:
if ((Token != NULL) && (Token->Event != NULL)) {
//
// For asynchronous operation, only free request and event in error case.
// The request and event will be freed in asynchronous callback for success case.
//
if (EFI_ERROR(Status) && (EraseBlockStart != NULL)) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&EraseBlockStart->Link);
gBS->RestoreTPL (OldTpl);
if (EraseBlockStart->Event != NULL) {
gBS->CloseEvent (EraseBlockStart->Event);
}
FreePool(EraseBlockStart);
}
} else {
//
// For synchronous operation, free request whatever the execution result is.
//
if (EraseBlockStart != NULL) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&EraseBlockStart->Link);
gBS->RestoreTPL (OldTpl);
FreePool(EraseBlockStart);
}
}
return Status;
}
/**
Set the erase end address through sync or async I/O request.
@param[in] Partition A pointer to the EMMC_PARTITION instance.
@param[in] EndLba The ending logical block address to be erased.
@param[in] Token A pointer to the token associated with the transaction.
@param[in] IsEnd A boolean to show whether it's the last cmd in a series of cmds.
This parameter is only meaningful in async I/O request.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcEraseBlockEnd (
IN EMMC_PARTITION *Partition,
IN EFI_LBA EndLba,
IN EFI_BLOCK_IO2_TOKEN *Token,
IN BOOLEAN IsEnd
)
{
EFI_STATUS Status;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EMMC_DEVICE *Device;
EMMC_REQUEST *EraseBlockEnd;
EFI_TPL OldTpl;
EraseBlockEnd = NULL;
Device = Partition->Device;
PassThru = Device->Private->PassThru;
EraseBlockEnd = AllocateZeroPool(sizeof (EMMC_REQUEST));
if (EraseBlockEnd == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
EraseBlockEnd->Signature = EMMC_REQUEST_SIGNATURE;
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
InsertTailList (&Partition->Queue, &EraseBlockEnd->Link);
gBS->RestoreTPL (OldTpl);
EraseBlockEnd->Packet.SdMmcCmdBlk = &EraseBlockEnd->SdMmcCmdBlk;
EraseBlockEnd->Packet.SdMmcStatusBlk = &EraseBlockEnd->SdMmcStatusBlk;
EraseBlockEnd->Packet.Timeout = EMMC_GENERIC_TIMEOUT;
EraseBlockEnd->SdMmcCmdBlk.CommandIndex = EMMC_ERASE_GROUP_END;
EraseBlockEnd->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
EraseBlockEnd->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1;
if (Device->SectorAddressing) {
EraseBlockEnd->SdMmcCmdBlk.CommandArgument = (UINT32)EndLba;
} else {
EraseBlockEnd->SdMmcCmdBlk.CommandArgument = (UINT32)MultU64x32 (EndLba, Partition->BlockMedia.BlockSize);
}
EraseBlockEnd->IsEnd = IsEnd;
EraseBlockEnd->Token = Token;
if ((Token != NULL) && (Token->Event != NULL)) {
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
AsyncIoCallback,
EraseBlockEnd,
&EraseBlockEnd->Event
);
if (EFI_ERROR(Status)) {
goto Error;
}
} else {
EraseBlockEnd->Event = NULL;
}
Status = PassThru->PassThru (PassThru, Device->Slot, &EraseBlockEnd->Packet, EraseBlockEnd->Event);
Error:
if ((Token != NULL) && (Token->Event != NULL)) {
//
// For asynchronous operation, only free request and event in error case.
// The request and event will be freed in asynchronous callback for success case.
//
if (EFI_ERROR(Status) && (EraseBlockEnd != NULL)) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&EraseBlockEnd->Link);
gBS->RestoreTPL (OldTpl);
if (EraseBlockEnd->Event != NULL) {
gBS->CloseEvent (EraseBlockEnd->Event);
}
FreePool(EraseBlockEnd);
}
} else {
//
// For synchronous operation, free request whatever the execution result is.
//
if (EraseBlockEnd != NULL) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&EraseBlockEnd->Link);
gBS->RestoreTPL (OldTpl);
FreePool(EraseBlockEnd);
}
}
return Status;
}
/**
Erase specified blocks through sync or async I/O request.
@param[in] Partition A pointer to the EMMC_PARTITION instance.
@param[in] Token A pointer to the token associated with the transaction.
@param[in] IsEnd A boolean to show whether it's the last cmd in a series of cmds.
This parameter is only meaningful in async I/O request.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcEraseBlock (
IN EMMC_PARTITION *Partition,
IN EFI_BLOCK_IO2_TOKEN *Token,
IN BOOLEAN IsEnd
)
{
EFI_STATUS Status;
EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru;
EMMC_DEVICE *Device;
EMMC_REQUEST *EraseBlock;
EFI_TPL OldTpl;
EraseBlock = NULL;
Device = Partition->Device;
PassThru = Device->Private->PassThru;
EraseBlock = AllocateZeroPool(sizeof (EMMC_REQUEST));
if (EraseBlock == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
EraseBlock->Signature = EMMC_REQUEST_SIGNATURE;
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
InsertTailList (&Partition->Queue, &EraseBlock->Link);
gBS->RestoreTPL (OldTpl);
EraseBlock->Packet.SdMmcCmdBlk = &EraseBlock->SdMmcCmdBlk;
EraseBlock->Packet.SdMmcStatusBlk = &EraseBlock->SdMmcStatusBlk;
EraseBlock->Packet.Timeout = EMMC_GENERIC_TIMEOUT;
EraseBlock->SdMmcCmdBlk.CommandIndex = EMMC_ERASE;
EraseBlock->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc;
EraseBlock->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1b;
if ((Device->ExtCsd.SecFeatureSupport & BIT4) != 0) {
//
// Perform a Trim operation which applies the erase operation to write blocks
// instead of erase groups. (Spec JESD84-B51, eMMC Electrical Standard 5.1,
// Section 6.6.10 and 6.10.4)
//
EraseBlock->SdMmcCmdBlk.CommandArgument = 1;
}
EraseBlock->IsEnd = IsEnd;
EraseBlock->Token = Token;
if ((Token != NULL) && (Token->Event != NULL)) {
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
AsyncIoCallback,
EraseBlock,
&EraseBlock->Event
);
if (EFI_ERROR(Status)) {
goto Error;
}
} else {
EraseBlock->Event = NULL;
}
Status = PassThru->PassThru (PassThru, Device->Slot, &EraseBlock->Packet, EraseBlock->Event);
Error:
if ((Token != NULL) && (Token->Event != NULL)) {
//
// For asynchronous operation, only free request and event in error case.
// The request and event will be freed in asynchronous callback for success case.
//
if (EFI_ERROR(Status) && (EraseBlock != NULL)) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&EraseBlock->Link);
gBS->RestoreTPL (OldTpl);
if (EraseBlock->Event != NULL) {
gBS->CloseEvent (EraseBlock->Event);
}
FreePool(EraseBlock);
}
} else {
//
// For synchronous operation, free request whatever the execution result is.
//
if (EraseBlock != NULL) {
OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
RemoveEntryList (&EraseBlock->Link);
gBS->RestoreTPL (OldTpl);
FreePool(EraseBlock);
}
}
return Status;
}
/**
Write zeros to specified blocks.
@param[in] Partition A pointer to the EMMC_PARTITION instance.
@param[in] StartLba The starting logical block address to write zeros.
@param[in] Size The size in bytes to fill with zeros. This must be a multiple of
the physical block size of the device.
@retval EFI_SUCCESS The request is executed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be executed due to a lack of resources.
@retval Others The request could not be executed successfully.
**/
EFI_STATUS
EmmcWriteZeros (
IN EMMC_PARTITION *Partition,
IN EFI_LBA StartLba,
IN UINTN Size
)
{
EFI_STATUS Status;
UINT8 *Buffer;
UINT32 MediaId;
Buffer = AllocateZeroPool(Size);
if (Buffer == NULL) {
return EFI_OUT_OF_RESOURCES;
}
MediaId = Partition->BlockMedia.MediaId;
Status = EmmcReadWrite (Partition, MediaId, StartLba, Buffer, Size, FALSE, NULL);
FreePool(Buffer);
return Status;
}
/**
Erase a specified number of device blocks.
@param[in] This Indicates a pointer to the calling context.
@param[in] MediaId The media ID that the erase request is for.
@param[in] Lba The starting logical block address to be
erased. The caller is responsible for erasing
only legitimate locations.
@param[in, out] Token A pointer to the token associated with the
transaction.
@param[in] Size The size in bytes to be erased. This must be
a multiple of the physical block size of the
device.
@retval EFI_SUCCESS The erase request was queued if Event is not
NULL. The data was erased correctly to the
device if the Event is NULL.to the device.
@retval EFI_WRITE_PROTECTED The device cannot be erased due to write
protection.
@retval EFI_DEVICE_ERROR The device reported an error while attempting
to perform the erase operation.
@retval EFI_INVALID_PARAMETER The erase request contains LBAs that are not
valid.
@retval EFI_NO_MEDIA There is no media in the device.
@retval EFI_MEDIA_CHANGED The MediaId is not for the current media.
**/
EFI_STATUS
EFIAPI
EmmcEraseBlocks (
IN EFI_ERASE_BLOCK_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN OUT EFI_ERASE_BLOCK_TOKEN *Token,
IN UINTN Size
)
{
EFI_STATUS Status;
EFI_BLOCK_IO_MEDIA *Media;
UINTN BlockSize;
UINTN BlockNum;
EFI_LBA FirstLba;
EFI_LBA LastLba;
EFI_LBA StartGroupLba;
EFI_LBA EndGroupLba;
UINT32 EraseGroupSize;
UINT32 Remainder;
UINTN WriteZeroSize;
UINT8 PartitionConfig;
EMMC_PARTITION *Partition;
EMMC_DEVICE *Device;
Status = EFI_SUCCESS;
Partition = EMMC_PARTITION_DATA_FROM_ERASEBLK (This);
Device = Partition->Device;
Media = &Partition->BlockMedia;
if (MediaId != Media->MediaId) {
return EFI_MEDIA_CHANGED;
}
if (Media->ReadOnly) {
return EFI_WRITE_PROTECTED;
}
//
// Check parameters.
//
BlockSize = Media->BlockSize;
if ((Size % BlockSize) != 0) {
return EFI_INVALID_PARAMETER;
}
BlockNum = Size / BlockSize;
if ((Lba + BlockNum - 1) > Media->LastBlock) {
return EFI_INVALID_PARAMETER;
}
if ((Token != NULL) && (Token->Event != NULL)) {
Token->TransactionStatus = EFI_SUCCESS;
}
FirstLba = Lba;
LastLba = Lba + BlockNum - 1;
//
// Check if needs to switch partition access.
//
PartitionConfig = Device->ExtCsd.PartitionConfig;
if ((PartitionConfig & 0x7) != Partition->PartitionType) {
PartitionConfig &= (UINT8)~0x7;
PartitionConfig |= Partition->PartitionType;
Status = EmmcSetExtCsd (Partition, OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), PartitionConfig, (EFI_BLOCK_IO2_TOKEN*)Token, FALSE);
if (EFI_ERROR(Status)) {
return Status;
}
Device->ExtCsd.PartitionConfig = PartitionConfig;
}
if ((Device->ExtCsd.SecFeatureSupport & BIT4) == 0) {
//
// If the Trim operation is not supported by the device, handle the erase
// of blocks that do not form a complete erase group separately.
//
EraseGroupSize = This->EraseLengthGranularity;
DivU64x32Remainder (FirstLba, EraseGroupSize, &Remainder);
StartGroupLba = (Remainder == 0) ? FirstLba : (FirstLba + EraseGroupSize - Remainder);
DivU64x32Remainder (LastLba + 1, EraseGroupSize, &Remainder);
EndGroupLba = LastLba + 1 - Remainder;
//
// If the size to erase is smaller than the erase group size, the whole
// erase operation is performed by writting zeros.
//
if (BlockNum < EraseGroupSize) {
Status = EmmcWriteZeros (Partition, FirstLba, Size);
if (EFI_ERROR(Status)) {
return Status;
}
DEBUG ((
DEBUG_INFO,
"EmmcEraseBlocks(): Lba 0x%x BlkNo 0x%x Event %p with %r\n",
Lba,
BlockNum,
(Token != NULL) ? Token->Event : NULL,
Status
));
if ((Token != NULL) && (Token->Event != NULL)) {
Token->TransactionStatus = EFI_SUCCESS;
gBS->SignalEvent (Token->Event);
}
return EFI_SUCCESS;
}
//
// If the starting LBA to erase is not aligned with the start of an erase
// group, write zeros to erase the data from starting LBA to the end of the
// current erase group.
//
if (StartGroupLba > FirstLba) {
WriteZeroSize = (UINTN)(StartGroupLba - FirstLba) * BlockSize;
Status = EmmcWriteZeros (Partition, FirstLba, WriteZeroSize);
if (EFI_ERROR(Status)) {
return Status;
}
}
//
// If the ending LBA to erase is not aligned with the end of an erase
// group, write zeros to erase the data from the start of the erase group
// to the ending LBA.
//
if (EndGroupLba <= LastLba) {
WriteZeroSize = (UINTN)(LastLba + 1 - EndGroupLba) * BlockSize;
Status = EmmcWriteZeros (Partition, EndGroupLba, WriteZeroSize);
if (EFI_ERROR(Status)) {
return Status;
}
}
//
// Check whether there is erase group to erase.
//
if (EndGroupLba <= StartGroupLba) {
DEBUG ((
DEBUG_INFO,
"EmmcEraseBlocks(): Lba 0x%x BlkNo 0x%x Event %p with %r\n",
Lba,
BlockNum,
(Token != NULL) ? Token->Event : NULL,
Status
));
if ((Token != NULL) && (Token->Event != NULL)) {
Token->TransactionStatus = EFI_SUCCESS;
gBS->SignalEvent (Token->Event);
}
return EFI_SUCCESS;
}
FirstLba = StartGroupLba;
LastLba = EndGroupLba - 1;
}
Status = EmmcEraseBlockStart (Partition, FirstLba, (EFI_BLOCK_IO2_TOKEN*)Token, FALSE);
if (EFI_ERROR(Status)) {
return Status;
}
Status = EmmcEraseBlockEnd (Partition, LastLba, (EFI_BLOCK_IO2_TOKEN*)Token, FALSE);
if (EFI_ERROR(Status)) {
return Status;
}
Status = EmmcEraseBlock (Partition, (EFI_BLOCK_IO2_TOKEN*)Token, TRUE);
if (EFI_ERROR(Status)) {
return Status;
}
DEBUG ((
DEBUG_INFO,
"EmmcEraseBlocks(): Lba 0x%x BlkNo 0x%x Event %p with %r\n",
Lba,
BlockNum,
(Token != NULL) ? Token->Event : NULL,
Status
));
return Status;
}
| 2.328125 | 2 |
2024-11-18T20:50:45.576580+00:00 | 2023-08-17T16:08:06 | 919b4172109f2e4e142f3aecc4e244eb2bfc2fdf | {
"blob_id": "919b4172109f2e4e142f3aecc4e244eb2bfc2fdf",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-17T16:08:06",
"content_id": "55537cf4a7c8329bec70a3a9968437c56dea0354",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "eecd5e4c50d8b78a769bcc2675250576bed34066",
"extension": "c",
"filename": "qmdqt.c",
"fork_events_count": 169,
"gha_created_at": "2013-03-10T20:55:21",
"gha_event_created_at": "2023-03-29T11:02:58",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 8691401,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2712,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/mat/order/qmdqt.c",
"provenance": "stackv2-0110.json.gz:226041",
"repo_name": "petsc/petsc",
"revision_date": "2023-08-17T16:08:06",
"revision_id": "9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9",
"snapshot_id": "3b1a04fea71858e0292f9fd4d04ea11618c50969",
"src_encoding": "UTF-8",
"star_events_count": 341,
"url": "https://raw.githubusercontent.com/petsc/petsc/9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9/src/mat/order/qmdqt.c",
"visit_date": "2023-08-17T20:51:16.507070"
} | stackv2 |
/* qmdqt.f -- translated by f2c (version 19931217).*/
#include <petscsys.h>
#include <petsc/private/matorderimpl.h>
/***************************************************************/
/******** QMDQT ..... QUOT MIN DEG QUOT TRANSFORM ********/
/***************************************************************/
/* PURPOSE - THIS SUBROUTINE PERFORMS THE QUOTIENT GRAPH */
/* TRANSFORMATION AFTER A NODE HAS BEEN ELIMINATED.*/
/* INPUT PARAMETERS -*/
/* ROOT - THE NODE JUST ELIMINATED. IT BECOMES THE*/
/* REPRESENTATIVE OF THE NEW SUPERNODE.*/
/* (XADJ, ADJNCY) - THE ADJACENCY STRUCTURE.*/
/* (RCHSZE, RCHSET) - THE REACHABLE SET OF ROOT IN THE*/
/* OLD QUOTIENT GRAPH.*/
/* NBRHD - THE NEIGHBORHOOD SET WHICH WILL BE MERGED*/
/* WITH ROOT TO FORM THE NEW SUPERNODE.*/
/* MARKER - THE MARKER VECTOR.*/
/* UPDATED PARAMETER -*/
/* ADJNCY - BECOMES THE ADJNCY OF THE QUOTIENT GRAPH.*/
/***************************************************************/
PetscErrorCode SPARSEPACKqmdqt(const PetscInt *root, const PetscInt *xadj, const PetscInt *inadjncy, PetscInt *marker, PetscInt *rchsze, PetscInt *rchset, PetscInt *nbrhd)
{
PetscInt *adjncy = (PetscInt *)inadjncy; /* Used as temporary and reset within this function */
/* System generated locals */
PetscInt i__1, i__2;
/* Local variables */
PetscInt inhd, irch, node, ilink, j, nabor, jstop, jstrt;
PetscFunctionBegin;
/* Parameter adjustments */
--nbrhd;
--rchset;
--marker;
--adjncy;
--xadj;
irch = 0;
inhd = 0;
node = *root;
L100:
jstrt = xadj[node];
jstop = xadj[node + 1] - 2;
if (jstop < jstrt) goto L300;
/* PLACE REACH NODES INTO THE ADJACENT LIST OF NODE*/
i__1 = jstop;
for (j = jstrt; j <= i__1; ++j) {
++irch;
adjncy[j] = rchset[irch];
if (irch >= *rchsze) goto L400;
}
/* LINK TO OTHER SPACE PROVIDED BY THE NBRHD SET.*/
L300:
ilink = adjncy[jstop + 1];
node = -ilink;
if (ilink < 0) goto L100;
++inhd;
node = nbrhd[inhd];
adjncy[jstop + 1] = -node;
goto L100;
/* ALL REACHABLE NODES HAVE BEEN SAVED. END THE ADJ LIST.*/
/* ADD ROOT TO THE NBR LIST OF EACH NODE IN THE REACH SET.*/
L400:
adjncy[j + 1] = 0;
i__1 = *rchsze;
for (irch = 1; irch <= i__1; ++irch) {
node = rchset[irch];
if (marker[node] < 0) goto L600;
jstrt = xadj[node];
jstop = xadj[node + 1] - 1;
i__2 = jstop;
for (j = jstrt; j <= i__2; ++j) {
nabor = adjncy[j];
if (marker[nabor] >= 0) goto L500;
adjncy[j] = *root;
goto L600;
L500:;
}
L600:;
}
PetscFunctionReturn(PETSC_SUCCESS);
}
| 2.015625 | 2 |
2024-11-18T20:50:46.041391+00:00 | 2020-11-30T00:54:09 | 90dc176d9e532b01ddd2f3b65c803aacf5098370 | {
"blob_id": "90dc176d9e532b01ddd2f3b65c803aacf5098370",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-30T00:54:09",
"content_id": "37f94710d4c68e1603c06f723ca714014c12b6bb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e0da29ba68e01da56df63a166e0429b262045669",
"extension": "c",
"filename": "MB_DATA.C",
"fork_events_count": 5,
"gha_created_at": "2016-08-28T07:44:15",
"gha_event_created_at": "2020-11-30T00:54:10",
"gha_language": "C",
"gha_license_id": null,
"github_id": 66756136,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6096,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Modbus-rtu/STM32G070KB_uC-Modbus_RTU/Modbus/Cfg/MB_DATA.C",
"provenance": "stackv2-0110.json.gz:226302",
"repo_name": "Soway-code/modbus",
"revision_date": "2020-11-30T00:54:09",
"revision_id": "15932ecf88f7a33630ded477bbbc5294e13d6cdf",
"snapshot_id": "46df7456fd73514713afa304a8985097a9ec06e3",
"src_encoding": "GB18030",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Soway-code/modbus/15932ecf88f7a33630ded477bbbc5294e13d6cdf/Modbus-rtu/STM32G070KB_uC-Modbus_RTU/Modbus/Cfg/MB_DATA.C",
"visit_date": "2023-01-21T06:39:16.950717"
} | stackv2 |
/*
*********************************************************************************************************
*
* uC/MODBUS TARGET SPECIFIC DATA ACCESS FUNCTIONS
*
* Filename : mb_data.c
* Version : V2.12
* Programmer(s) : JJL
*********************************************************************************************************
* Note(s) :
*********************************************************************************************************
*/
/*
*********************************************************************************************************
* INCLUDE FILES
*********************************************************************************************************
*/
#include <mb.h>
#include "main.h"
/*
*********************************************************************************************************
* LOCAL GLOBAL VARIABLES
*********************************************************************************************************
*/
#define REG_HOLDING_START 0x0000 //保持寄存器起始地址
#define REG_HOLDING_NREGS 125 //保持寄存器数量
volatile uint16_t MB_DATA[125] = {0};
volatile uint16_t* Ptr = &MB_DATA[0];
volatile uint16_t MB_DATA_04[125] = {0x0,0xBE2,0x0,0x12C,0x4,0x5,0x6,0x7,0x8,0x9,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x20,0x21,0x23};
volatile uint16_t* Ptr_04 = &MB_DATA_04[0];
/*
*********************************************************************************************************
* PROTOTYPES
*********************************************************************************************************
*/
#if (MODBUS_CFG_FC01_EN == DEF_ENABLED)
CPU_BOOLEAN
MB_CoilRd (CPU_INT16U coil, CPU_INT16U *perr)
{
*perr = MODBUS_ERR_RANGE;
return (DEF_FALSE);
}
#endif
#if (MODBUS_CFG_FC05_EN == DEF_ENABLED) || \
(MODBUS_CFG_FC15_EN == DEF_ENABLED)
void
MB_CoilWr (CPU_INT16U coil, CPU_BOOLEAN coil_val, CPU_INT16U *perr)
{
*perr = MODBUS_ERR_RANGE;
}
#endif
#if (MODBUS_CFG_FC02_EN == DEF_ENABLED)
CPU_BOOLEAN
MB_DIRd (CPU_INT16U di, CPU_INT16U *perr)
{
*perr = MODBUS_ERR_RANGE;
return DEF_FALSE;
}
#endif
#if (MODBUS_CFG_FC04_EN == DEF_ENABLED)
CPU_INT16U
MB_InRegRd (CPU_INT16U reg, CPU_INT16U *perr)
{
CPU_INT16U val;
reg &= 0x00FF;
if ( reg <= REG_HOLDING_START+REG_HOLDING_NREGS-1 ) //有效地址
{
*perr = MODBUS_ERR_NONE;
val = *(Ptr_04+reg);
}
else
{
*perr = MODBUS_ERR_RANGE;
val = 0;
}
return (val);
}
#endif
#if (MODBUS_CFG_FP_EN == DEF_ENABLED)
#if (MODBUS_CFG_FC04_EN == DEF_ENABLED)
CPU_FP32
MB_InRegRdFP (CPU_INT16U reg, CPU_INT16U *perr)
{
*perr = MODBUS_ERR_RANGE;
return ((CPU_FP32)0);
}
#endif
#endif
#if (MODBUS_CFG_FC03_EN == DEF_ENABLED)
CPU_INT16U
MB_HoldingRegRd (CPU_INT16U reg, CPU_INT16U *perr)
{
CPU_INT16U val;
reg = reg & 0x00FF;
if ( reg <= REG_HOLDING_START+REG_HOLDING_NREGS-1 ) //有效地址
{
*perr = MODBUS_ERR_NONE;
val = *(Ptr+reg);
}
else
{
*perr = MODBUS_ERR_RANGE;
val = 0;
}
return (val);
}
#endif
#if (MODBUS_CFG_FP_EN == DEF_ENABLED)
#if (MODBUS_CFG_FC03_EN == DEF_ENABLED)
CPU_FP32
MB_HoldingRegRdFP (CPU_INT16U reg, CPU_INT16U *perr)
{
*perr = MODBUS_ERR_RANGE;
return ((CPU_FP32)0);
}
#endif
#endif
#if (MODBUS_CFG_FC06_EN == DEF_ENABLED) || \
(MODBUS_CFG_FC16_EN == DEF_ENABLED)
void
MB_HoldingRegWr (CPU_INT16U reg, CPU_INT16U reg_val_16, CPU_INT16U *perr)
{
uint8_t buf;
reg = reg & 0x00FF;
if ( reg < REG_HOLDING_START+REG_HOLDING_NREGS ) //有效地址
{
*perr = MODBUS_ERR_NONE;
*(Ptr+reg) = reg_val_16;
buf = (uint8_t)reg_val_16;
switch (reg)
{
case 0x30:{
InFlash_Write_OneByte(DEVICE_ADDR,buf); //设备地址
//HAL_NVIC_SystemReset();
break;
}
case 0x31:{
InFlash_Write_OneByte(BAUDRATE,buf); //串口波特率
// HAL_NVIC_SystemReset();
break;
}
case 0x32:{
InFlash_Write_OneByte(PARITY,buf); //串口奇偶校验
// HAL_NVIC_SystemReset();
break;
}
case 0x34:{
InFlash_Write_OneByte(COMPENSATE,buf); // 补偿使能
break;
}
case 0x35:{
InFlash_Write_OneByte(FILTER,buf); // 滤波系数
break;
}
case 0x36:{
InFlash_Write_OneByte(AUTO_UPLOAD,buf); //自动上传周期
break;
}
case 0x37:{
InFlash_Write_OneByte(CORRECT_K,buf); //修正系数K
break;
}
case 0x38:{
InFlash_Write_OneByte(CORRECT_B,buf); //修正系数B
break;
}
case 0x40:{
InFlash_Write_OneByte(UPPERTEMP,buf); //温度上阀值
break;
}
case 0x41:{
InFlash_Write_OneByte(LOWERTEMP,buf); //温度下阀值
break;
}
default:*perr = MODBUS_ERR_RANGE;
break;
}
// MB_ASCII_Tx(pch); /* Send back reply. */
//
// HAL_NVIC_SystemReset();
}
else
{
*perr = MODBUS_ERR_RANGE;
}
}
#endif
#if (MODBUS_CFG_FP_EN == DEF_ENABLED)
#if (MODBUS_CFG_FC06_EN == DEF_ENABLED) || \
(MODBUS_CFG_FC16_EN == DEF_ENABLED)
void
MB_HoldingRegWrFP (CPU_INT16U reg, CPU_FP32 reg_val_fp, CPU_INT16U *perr)
{
*perr = MODBUS_ERR_RANGE;
}
#endif
#endif
#if (MODBUS_CFG_FC20_EN == DEF_ENABLED)
CPU_INT16U
MB_FileRd (CPU_INT16U file_nbr,
CPU_INT16U record_nbr,
CPU_INT16U ix,
CPU_INT08U record_len,
CPU_INT16U *perr)
{
(void)file_nbr;
(void)record_nbr;
(void)ix;
(void)record_len;
*perr = MODBUS_ERR_NONE;
return (0);
}
#endif
#if (MODBUS_CFG_FC21_EN == DEF_ENABLED)
void
MB_FileWr (CPU_INT16U file_nbr,
CPU_INT16U record_nbr,
CPU_INT16U ix,
CPU_INT08U record_len,
CPU_INT16U val,
CPU_INT16U *perr)
{
(void)file_nbr;
(void)record_nbr;
(void)ix;
(void)record_len;
(void)val;
*perr = MODBUS_ERR_NONE;
}
#endif
| 2.40625 | 2 |
2024-11-18T20:50:46.294110+00:00 | 2016-03-04T15:33:16 | 6c79b613bdb8185ad51611d42a568ac9b1f83a1a | {
"blob_id": "6c79b613bdb8185ad51611d42a568ac9b1f83a1a",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-04T15:33:16",
"content_id": "b1096c12f1c9103dd04dc64145a8ea206a31e666",
"detected_licenses": [
"MIT"
],
"directory_id": "728595b94b1f834e5b007664b6f3ed2343038e5b",
"extension": "h",
"filename": "unittest.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16846,
"license": "MIT",
"license_type": "permissive",
"path": "/src/unittest.h",
"provenance": "stackv2-0110.json.gz:226565",
"repo_name": "marcogiusti/libunittest",
"revision_date": "2016-03-04T15:33:16",
"revision_id": "e5dce40e79a5aaf3364fc5715c54732660986a17",
"snapshot_id": "484a727908b72338d108d5f5339489b34b30659b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marcogiusti/libunittest/e5dce40e79a5aaf3364fc5715c54732660986a17/src/unittest.h",
"visit_date": "2021-01-15T10:25:12.554119"
} | stackv2 | /*
* Copyright (C) 2015 Marco Giusti.
*/
/** @file
* The header file to include.
*/
#include <stdbool.h>
#include <stdio.h>
#ifndef UNITTEST_H
#define UNITTEST_H
struct test_case;
struct test_suite;
/**
* Define the common fields for the test_result types.
*/
#define RESULT_HEAD \
/** Set to stop the runner to run more tests. */ \
bool shouldstop; \
/** Set to interrupt the tests at the first failure. */ \
bool failfast; \
/** The stream to use to print the results of the run. */ \
FILE *stream; \
/** Free the resources acquired by the result. */ \
void (*free)(struct test_result *result); \
/** Executed before a run. */ \
void (*start_run)(struct test_result *result); \
/** Executed after a run. */ \
void (*stop_run)(struct test_result *result); \
/** Executed before each test. */ \
void (*start_test)(struct test_result *result, struct test_case *test); \
/** Executed after each test. */ \
void (*stop_test)(struct test_result *result, struct test_case *test); \
/** Add a test to the list of the skipped ones.
* @note The result does *not* own the test and should not try to free it.
*/ \
void (*add_skip)(struct test_result *result, struct test_case *test); \
/** Add a test to the list of the success.
* @note The result does *not* own the test and should not try to free it.
*/ \
void (*add_success)(struct test_result *result, struct test_case *test); \
/** Add a test to the list of the unexpected success.
* @note The result does *not* own the test and should not try to free it.
*/ \
void (*add_xsuccess)(struct test_result *result, struct test_case *test); \
/** Add a test to the list of the failures.
* @note The result does *not* own the test and should not try to free it.
*/ \
void (*add_failure)(struct test_result *result, struct test_case *test); \
/** Add a test to the list of the expected failures.
* @note The result does *not* own the test and should not try to free it.
*/ \
void (*add_xfailure)(struct test_result *result, struct test_case *test); \
/** Add a test to the list of errors.
* @note The result does *not* own the test and should not try to free it.
*/ \
void (*add_error)(struct test_result *result, struct test_case *test); \
/** Return a `int` suitable as parameter to exit(). */ \
int (*was_successful)(struct test_result* result);
/**
* Represent the result of the tests.
* TODO: implement an error list.
*/
struct test_result {
RESULT_HEAD
};
/**
* Create a new tap_result, an implementation of test_result.
* @note If the memory allocation fails, the program aborts.
* @param stream A stream the use to print the output.
* @param failfast If the tests should stop at the first failure.
*/
struct test_result *tap_result_new(bool failfast, FILE *stream);
/**
* Groups the required test arguments in a macro to hide the implementation
* requirements.
*/
#define _TESTARG __test__
#define _RESULTARG __result__
#define TESTARGS struct test_case *_TESTARG, struct test_result *_RESULTARG
/**
* Define the common fields for the test_case types.
*/
#define CASE_HEAD \
/** The name of the test. Useful if the test fail to track the failure */ \
const char *name; \
/** The message to use in case the test fails. */ \
const char *msg; \
/** If not NULL the test is skipped. */ \
const char *skip; \
/** If not NULL the reason why test (should) fail. */ \
const char *todo; \
/** The condition actually tested. */ \
const char *condition; \
/** The name of the file where the test is located. */ \
const char *filename; \
/** The line number in the file. */ \
unsigned int lineno; \
void (*func)(struct test_case *test, struct test_result *result, \
void *usrptr); \
/** Run the test. All the arguments must be not NULL. */ \
void (*run)(struct test_case *test, struct test_suite *suite, \
struct test_result *result); \
/**
* Check that `condition` is true and update the result.
* Don't use it directly but one of the ASSERT_ macros instead.
* @param result The result to update.
* @param pass If the test passed.
* @param condition The condition tested.
* @param msg The message associated with this assertion.
* @param filename The file where the test is located.
* @param lineno the line number in the file.
*/ \
void (*assert_impl)(struct test_case *test, struct test_result *result, \
bool pass, const char *condition, const char *msg, \
const char *filename, unsigned int lineno); \
/**
* Add an irrecoverable error.
* Don't use this function directly but ERROR macro instead.
* @param result The result to update.
* @param msg The error message.
* @param filename The file where the test is located.
* @param lineno the line number in the file.
*/ \
void (*error)(struct test_case *test, struct test_result *result, \
const char *msg, const char *filename, unsigned int lineno);
/**
* Represent the smallest unit of testing.
*/
struct test_case {
CASE_HEAD
};
/**
* Create a new test case for the function `func`.
* @note If the memory allocation fails, the program aborts.
* @param func The function to run as part of the test.
*/
#define test_case_new(func) \
test_case_new_impl(#func, NULL, NULL, func)
/**
* Create a new test case for the function `func` but skip it.
* @note If the memory allocation fails, the program aborts.
* @param func The function to run as part of the test.
* @param reason The reason why the test must be skipped.
*/
#define test_case_skip_new(func, reason) \
test_case_new_impl(#func, reason, NULL, func)
/**
* Create a new test case for the function `func` and mark it as failing.
* @note If the memory allocation fails, the program aborts.
* @param func The function to run as part of the test.
* @param reason The reason why the test fails.
*/
#define test_case_todo_new(func, reason) \
test_case_new_impl(#func, NULL, reason, func)
/**
* Create a new test case.
* @note Don't use this function but one of the test_case_*_new macros.
*/
struct test_case *test_case_new_impl(const char *name, const char *skip,
const char *todo,
void (*func)(struct test_case *, struct test_result *, void *));
/**
* Define the common fields for the test_suite types.
*/
#define SUITE_HEAD \
/** The name of the suite. */ \
char *name; \
/** A documentation string. */ \
char *doc; \
/** If not NULL the suite is skipped. */ \
char *skip; \
/** A generic pointer that the user could use in a test case. */ \
void *usrptr; \
/** Free the resources acquired by this suite. */ \
void (*free)(struct test_suite *suite); \
/** Called to set up the preconditions that the test needs.
* @note It must not fail. */ \
void (*setup)(struct test_suite *suite); \
/** Tear down the test fixture. @note It must not fail. */ \
void (*teardown)(struct test_suite *suite); \
/** Add a test to the current suite. */ \
void (*add_test)(struct test_suite *suite, struct test_case *test); \
/** Add a child suite to the current suite. */ \
void (*add_suite)(struct test_suite *suite, struct test_suite *suitec); \
/** Run all the tests of the suite. */ \
void (*run)(struct test_suite *suite, struct test_result *result); \
/** Return the number of the tests in the suite. */ \
unsigned int (*len)(struct test_suite *suite);
/**
* A collection of test cases.
* TODO: make it also a collection of suites.
*/
struct test_suite {
SUITE_HEAD
};
/**
* Create a new test suite.
* @note If the memory allocation fails, the program aborts.
*/
struct test_suite *test_suite_new(void);
/**
* Define the common fields for the test_runner types.
*/
#define RUNNER_HEAD \
/** A result of the tests run. */ \
struct test_result *result; \
/** Free the resources acquired by the runner. */ \
void (*free)(struct test_runner *runner); \
/** Run the test suite. */ \
struct test_result *(*run)(struct test_runner *runner, \
struct test_suite *suite);
/**
* The test runner run the suite and return a result.
*/
struct test_runner {
RUNNER_HEAD
};
/**
* Create a new runner that is compatible with the
* [TAP specification](http://testanything.org/tap-specification.html).
* @note If the memory allocation fails, the program aborts.
* @param verbosity Indicate the verbosity level of the runner.
* @param failfast If true the runner stop at the first test failed.
* @param buffered If true the output is buffered.
* @param stream The stream where to print the output.
*/
struct test_runner *tap_runner_new(int verbosity, bool failfast, bool buffered,
FILE *stream);
/**
* Define the common fields for the test_loader types.
*/
#define LOADER_HEAD \
/** Free the resources acquired by the loader. */ \
void (*free)(struct test_loader *loader); \
/** Load the tests based on the parameters passed. */ \
struct test_suite *(*load_tests)(struct test_loader *loader, int argc, \
char *argv[]);
/**
* The loader loads the tests to run.
* The default implementation search in the main program for the function
* `load_test_suite()` and, if found, run it.
*/
struct test_loader {
LOADER_HEAD
};
/**
* Create a new test_loader.
* @note If the memory allocation fails, the program aborts.
*/
struct test_loader *test_loader_new(void);
/**
* A loader implementation that load a single function as test case.
*/
struct test_loader_func {
LOADER_HEAD
/** The name of the function. */
const char *name;
/** If not `NULL` the test should be skipped, otherwise the reason of the
* skip. */
const char *skip;
/** If not `NULL` the reason why the test should fail. */
const char *todo;
/** The pointer to the test case. */
void (*func)(struct test_case *test, struct test_result *result,
void *usrptr);
};
/**
* Create a new test_loader_func.
* @note If the memory allocation fails, the program aborts.
*/
struct test_loader *func_loader_new(void);
/**
* Main entry point.
* Parse the options, if needed create the runner and the loader, load the
* tests and run them.
* @param argc Lenght of argv with the ending `NULL`.
* @param argv Array of parameters passed to the loader. argv[0] is the name of
* the program.
* @param runner The runner that will run the tests.
* @param loader The loader that will load the tests.
* @return 0 if all the tests pass, a suitable exit status otherwise.
*/
int test_main(int argc, char *argv[], struct test_runner *runner,
struct test_loader *loader);
/**
* Create a default loader, load the tests and run them.
* Look test_main for a description of the parameters with the exception of
* `loader` which is `NULL`.
*/
#define test_main2(argc, argv, runner) test_main(argc, argv, runner, NULL)
/**
* Create a default loader and runner, load the tests and run them.
* Look test_main for a description of the parameters with the exception of
* `loader` and `runner` which are `NULL`.
*/
#define test_main3(argc, argv) test_main(argc, argv, NULL, NULL)
/**
* Load the tests and run them.
* @param runner The test_runner to use. Must not be NULL.
* @param loader The test_loader to use. Must not be NULL.
* @param argc Lenght of argv with the ending `NULL`.
* @param argv Array of parameters passed to the loader. argv[0] is **not** the
* name of the program.
* @return 0 if all the tests pass, a suitable exit status otherwise.
*/
int run_tests(struct test_runner *runner, struct test_loader *loader, int argc,
char *argv[]);
/**
* A test that always pass.
* @param msg A message to print.
*/
#define SUCCESS(msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
true, \
"SUCCESS", \
msg, \
__FILE__, \
__LINE__); \
} while(0)
/**
* A test that always fails.
* @note It does not return.
* @param msg A message to print.
*/
#define FAIL(msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
false, \
"FAIL", \
msg, \
__FILE__, \
__LINE__); \
} while(0)
#define ERROR(msg) do { \
_TESTARG->error(_TESTARG, \
_RESULTARG, \
msg, \
__FILE__, \
__LINE__); \
} while(0)
/**
* Test that the `first` and `second` parameters are equal.
* @note If it fails, it does not return.
* @param first The first member of the comparition.
* @param second The second member of the comparition.
* @param msg A message to print.
*/
#define ASSERT_EQUAL(first, second, msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
(first) == (second), \
"(" #first ") == (" #second ")", \
msg, \
__FILE__, \
__LINE__); \
} while(0)
/**
* Test that the `first` and `second` parameters are not equal.
* @note If it fails, it does not return.
* @param first The first member of the comparition.
* @param second The second member of the comparition.
* @param msg A message to print.
*/
#define ASSERT_NOT_EQUAL(first, second, msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
(first) != (second), \
"(" #first ") != (" #second ")", \
msg, \
__FILE__, \
__LINE__); \
} while(0)
/**
* Test that the two pointers are equal.
* @note If it fails, it does not return.
* @param first The first pointer.
* @param second The second pointer.
* @param msg A message to print.
*/
#define ASSERT_PTR_EQUAL(first, second, msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
(const void *)(first) == (const void *)(second), \
"(const void *)(" #first ") == (const void *)(" #second ")", \
msg, \
__FILE__, \
__LINE__); \
} while(0)
/**
* Test that the two pointers are not equal.
* @note If it fails, it does not return.
* @param first The first pointer.
* @param second The second pointer.
* @param msg A message to print.
*/
#define ASSERT_PTR_NOT_EQUAL(first, second, msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
(const void *)(first) != (const void *)(second), \
"(const void *)(" #first ") != (const void *)(" #second ")", \
msg, \
__FILE__, \
__LINE__); \
} while(0)
/**
* Test that the pointers is `NULL`.
* @note If it fails, it does not return.
* @param ptr The pointer to test.
* @param msg A message to print.
*/
#define ASSERT_PTR_NULL(ptr, msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
(const void *)(ptr) == NULL, \
"(const void *)(" #ptr ") == NULL", \
msg, \
__FILE__, \
__LINE__); \
} while(0)
/**
* Test that the pointers is not `NULL`.
* @note If it fails, it does not return.
* @param ptr The pointer to test.
* @param msg A message to print.
*/
#define ASSERT_PTR_NOT_NULL(ptr, msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
(const void *)(ptr) != NULL, \
"(const void *)(" #ptr ") != NULL", \
msg, \
__FILE__, \
__LINE__); \
} while(0)
/**
* Test that the two strings are equal.
* @note If it fails, it does not return.
* @param first The first string.
* @param second The second string.
* @param msg A message to print.
*/
#define ASSERT_STRING_EQUAL(first, second, msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
strcmp((const char *)(first) == (const char *)(second)), \
"strcmp(" #first " == " #second ")", \
msg, \
__FILE__, \
__LINE__); \
} while(0)
/**
* Test that the two strings are not equal.
* @note If it fails, it does not return.
* @param first The first string.
* @param second The second string.
* @param msg A message to print.
*/
#define ASSERT_STRING_NOT_EQUAL(first, second, msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
strcmp((const char *)(first) != (const char *)(second)), \
"strcmp(" #first " != " #second ")", \
msg, \
__FILE__, \
__LINE__); \
} while(0)
/**
* Test that first and second are approximately equal.
* Do the test by computing the difference and comparing to zero.
* @note If it fails, it does not return.
* @param first The first number.
* @param second The second number.
* @param msg A message to print.
*/
#define ASSERT_ALMOST_EQUAL(first, second, delta, msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
fabs((double) (first) - (double) (second)) <= \
fabs((double) delta), \
"fabs((double) (" #first ") - (double) (" #second ")) <= " \
"fabs((double) " #delta ")", \
__FILE__, \
__LINE__); \
} while(0)
/**
* Test that first and second are not approximately equal.
* Do the test by computing the difference and comparing to zero.
* @note If it fails, it does not return.
* @param first The first number.
* @param second The second number.
* @param msg A message to print.
*/
#define ASSERT_NOT_ALMOST_EQUAL(first, second, delta, msg) do { \
_TESTARG->assert_impl(_TESTARG, \
_RESULTARG, \
fabs((double) (first) - (double) (second)) > \
fabs((double) delta), \
"fabs((double) (" #first ") - (double) (" #second ")) > " \
"fabs((double) " #delta ")", \
__FILE__, \
__LINE__); \
} while(0)
#endif /* UNITTEST_H */
| 2.390625 | 2 |
2024-11-18T20:50:47.026151+00:00 | 2020-10-17T10:20:08 | 5e8e6bb3d4749cde76f0f7bf4dde02303cf51e7a | {
"blob_id": "5e8e6bb3d4749cde76f0f7bf4dde02303cf51e7a",
"branch_name": "refs/heads/main",
"committer_date": "2020-10-17T10:20:08",
"content_id": "761c1e186008c4bc9f495bf99edac4232649dd17",
"detected_licenses": [
"MIT"
],
"directory_id": "055352b9314f9513ebcecea8486428a2952f3240",
"extension": "h",
"filename": "type.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 304539295,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1502,
"license": "MIT",
"license_type": "permissive",
"path": "/type.h",
"provenance": "stackv2-0110.json.gz:226821",
"repo_name": "Forgeof-Creation/c-db_exp",
"revision_date": "2020-10-17T10:20:08",
"revision_id": "0efe4ca33462368d5a22ac100399a322dd78f1d2",
"snapshot_id": "8f656fcb0930ace4a2c4bae0705c89b97fe7ade2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Forgeof-Creation/c-db_exp/0efe4ca33462368d5a22ac100399a322dd78f1d2/type.h",
"visit_date": "2022-12-28T21:26:34.992571"
} | stackv2 | #include <ctype.h>
int verify(FILE *db)
{
Type type = get_type(db);
char buffer[128];
get_value(buffer, db);
if (type == STRING)
{
int buff_ptr = 0;
while (buffer[buff_ptr] != '\0')
{
if (isalpha(buffer[buff_ptr]) != 0)
{
return 0;
}
buff_ptr++;
}
}
if (type == INT)
{
int buff_ptr = 0;
while (buffer[buff_ptr] != '\0')
{
if (isdigit(buffer[buff_ptr]) == 0)
{
return 1;
}
buff_ptr++;
}
}
if (type == FLOAT)
{
int buff_ptr = 0;
while (buffer[buff_ptr] != '\0')
{
if ((isdigit(buffer[buff_ptr]) == 0) || (buffer[buff_ptr] != '.'))
{
return 1;
}
buff_ptr++;
}
}
if (type == NONE)
{
if (buffer[0] != '\0')
{
return 1;
}
}
return 0;
}
int verify_from_key(FILE *db, char key[])
{
Type type = get_type_with_key(key, db);
char buffer[128];
value_from_key(buffer, key, db);
if (type == STRING)
{
int buff_ptr = 0;
while (buffer[buff_ptr] != '\0')
{
if (isalpha(buffer[buff_ptr]) != 0)
{
return 0;
}
buff_ptr++;
}
}
if (type == INT)
{
int buff_ptr = 0;
while (buffer[buff_ptr] != '\0')
{
if (isdigit(buffer[buff_ptr]) == 0)
{
return 1;
}
buff_ptr++;
}
}
if (type == FLOAT)
{
int buff_ptr = 0;
while (buffer[buff_ptr] != '\0')
{
if ((isdigit(buffer[buff_ptr]) == 0) || (buffer[buff_ptr] != '.'))
{
return 1;
}
buff_ptr++;
}
}
if (type == NONE)
{
if (buffer[0] != '\0')
{
return 1;
}
}
return 0;
}
| 2.765625 | 3 |
2024-11-18T20:50:47.246158+00:00 | 2020-02-03T15:22:21 | ac5f6ca8eebbf77c8d7f7013bef6b6b927a10ecc | {
"blob_id": "ac5f6ca8eebbf77c8d7f7013bef6b6b927a10ecc",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-03T15:22:21",
"content_id": "8efcbd621e1aacc7cfa85105508bfab3679922a9",
"detected_licenses": [
"MIT"
],
"directory_id": "6681e14a202c9635795b81d7a0f7f159516f5caa",
"extension": "c",
"filename": "AVComm.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13582,
"license": "MIT",
"license_type": "permissive",
"path": "/AVCommDriver/AVComm.c",
"provenance": "stackv2-0110.json.gz:227078",
"repo_name": "wumn290/AVCore",
"revision_date": "2020-02-03T15:22:21",
"revision_id": "3782b13d6b74221e18dac450006bbd933a322c8c",
"snapshot_id": "875482893e53a051f4aee96bb66b91c26a91f0d2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wumn290/AVCore/3782b13d6b74221e18dac450006bbd933a322c8c/AVCommDriver/AVComm.c",
"visit_date": "2022-04-18T00:16:21.771811"
} | stackv2 | /**
\file
\brief Implements KMEventsAPI
Exports Driver that implements KM-UM communication interface
in KM. Communication interfaces are provided via exports.
*/
#include "AVComm.h"
#include "Globals.h"
#include "KMUMcomm.h"
#include "EventsKMStructures.h"
NTSTATUS AVCommConnectNotifyCallback(
_In_ PFLT_PORT ClientPort,
_In_ PVOID ServerPortCookie,
_In_reads_bytes_(SizeOfContext) PVOID ConnectionContext,
_In_ ULONG SizeOfContext,
_Outptr_result_maybenull_ PVOID* ConnectionCookie
);
VOID AVCommDisconnectNotifyCallback(
_In_opt_ PVOID ConnectionCookie
);
NTSTATUS AVCommPrepareServerPort(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ AV_CONNECTION_TYPE ConnectionType
);
NTSTATUS AVCommInit(PFLT_FILTER Filter);
void AVCommStop(VOID);
NTSTATUS AVCommCreateBuffer(PVOID srcBuffer, SIZE_T srcSize, void** outUmBuffer, PSIZE_T outUmSize);
NTSTATUS AVCommFreeBuffer(PVOID UmBuffer, PSIZE_T UmBufferSize);
NTSTATUS AVCommSendEvent(AV_EVENT_TYPE, void*, int, PAV_EVENT_RESPONSE, PULONG);
HANDLE AVCommGetUmPID(VOID);
UCHAR AVCommIsExcludedPID(HANDLE PID);
UCHAR AVCommIsInitialized(VOID);
VOID AVCommGetUmBuffer(PVOID umAddr, PVOID outKmBuffer, SIZE_T size);
#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT, DriverEntry)
#pragma alloc_text(PAGE, DllInitialize)
#pragma alloc_text(PAGE, DllUnload)
#pragma alloc_text(PAGE, AVCommConnectNotifyCallback)
#pragma alloc_text(PAGE, AVCommDisconnectNotifyCallback)
#pragma alloc_text(PAGE, AVCommPrepareServerPort)
#pragma alloc_text(PAGE, AVCommInit)
#pragma alloc_text(PAGE, AVCommStop)
#pragma alloc_text(PAGE, AVCommCreateBuffer)
#pragma alloc_text(PAGE, AVCommGetUmBuffer)
#pragma alloc_text(PAGE, AVCommFreeBuffer)
#pragma alloc_text(PAGE, AVCommSendEvent)
#pragma alloc_text(PAGE, AVCommIsExcludedPID)
#pragma alloc_text(PAGE, AVCommIsInitialized)
#endif
/**
Global parameters. Holds KM-UM communication context.
*/
AV_COMM_GLOBAL_DATA Globals;
/**
This function is called when DLL is loaded.
\param[in] RegistryPath Path to the service regisy key.
\return Initialization status.
*/
NTSTATUS DllInitialize(
_In_ PUNICODE_STRING RegistryPath
)
{
UNREFERENCED_PARAMETER(RegistryPath);
DbgPrint("AVCommDriver.sys is now loading\n");
return STATUS_SUCCESS;
}
/**
\brief Unload routine.
This function is called when DLL is being unloaded.
\return STATUS_SUCCESS.
*/
NTSTATUS DllUnload(VOID)
{
DbgPrint("AVCommDriver.sys is now unloading\n");
return STATUS_SUCCESS;
}
/**
Temporary entry point needed to initialize the class system dll.
It only zeros out the globals.
\param[in] DriverObject Pointer to the driver object created by the system.
\return STATUS_SUCCESS
*/
NTSTATUS
DriverEntry(
IN PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING RegistryPath
)
{
UNREFERENCED_PARAMETER(DriverObject);
UNREFERENCED_PARAMETER(RegistryPath);
RtlZeroMemory(&Globals, sizeof(Globals));
return STATUS_SUCCESS;
}
/**
Communication connection callback routine.
This is called when user-mode connects to the server port.
This function sets up KM-UM global communication context.
\param[in] ClientPort This is the client connection port that will be used to send messages from the filter
\param[in] ServerPortCookie Unused
\param[in] ConnectionContext The connection context passed from the user. This is to recognize which type
connection the user is trying to connect.
\param[in] SizeofContext The size of the connection context.
\param[out] ConnectionCookie Propagation of the connection context to disconnection callback.
\return STATUS_SUCCESS - to accept the connection
STATUS_INSUFFICIENT_RESOURCES - if memory is not enough
STATUS_INVALID_PARAMETER_3 - Connection context is not valid.
*/
NTSTATUS AVCommConnectNotifyCallback(
_In_ PFLT_PORT ClientPort,
_In_ PVOID ServerPortCookie,
_In_reads_bytes_(SizeOfContext) PVOID ConnectionContext,
_In_ ULONG SizeOfContext,
_Outptr_result_maybenull_ PVOID* ConnectionCookie
)
{
PAV_CONNECTION_CONTEXT connectionCtx = (PAV_CONNECTION_CONTEXT)ConnectionContext;
PAV_CONNECTION_TYPE connectionCookie = NULL;
PAGED_CODE();
UNREFERENCED_PARAMETER(ServerPortCookie);
UNREFERENCED_PARAMETER(SizeOfContext);
if (NULL == connectionCtx) {
return STATUS_INVALID_PARAMETER_3;
}
// ConnectionContext passed in may be deleted. We need to make a copy of it.
connectionCookie = (PAV_CONNECTION_TYPE)ExAllocatePoolWithTag(PagedPool,
sizeof(AV_CONNECTION_TYPE),
AV_CONNECTION_CTX_TAG);
if (NULL == connectionCookie) {
return STATUS_INSUFFICIENT_RESOURCES;
}
NTSTATUS status = STATUS_SUCCESS;
*connectionCookie = connectionCtx->Type;
switch (connectionCtx->Type)
{
case AvConnectForEvents:
Globals.EventsClientPort = ClientPort;
OBJECT_ATTRIBUTES objectAttributes;
InitializeObjectAttributes(&objectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
CLIENT_ID client_id;
Globals.AVCoreServicePID = connectionCtx->ProcessID;
client_id.UniqueProcess = connectionCtx->ProcessID;
client_id.UniqueThread = 0;
status = ZwOpenProcess(&Globals.AVCoreServiceHandle, PROCESS_ALL_ACCESS, &objectAttributes, &client_id);
if (status != STATUS_SUCCESS)
{
// couldn't get AVCore service process handle
*ConnectionCookie = NULL;
return STATUS_INVALID_PARAMETER_3;
}
status = PsLookupProcessByProcessId(connectionCtx->ProcessID, &Globals.AVCoreServiceEprocess);
if (status != STATUS_SUCCESS)
{
// couldn't get AVCore service process handle
*ConnectionCookie = NULL;
return STATUS_INVALID_PARAMETER_3;
}
*ConnectionCookie = connectionCookie;
break;
default:
ExFreePoolWithTag(connectionCookie,
AV_CONNECTION_CTX_TAG);
*ConnectionCookie = NULL;
return STATUS_INVALID_PARAMETER_3;
}
return STATUS_SUCCESS;
}
/**
Communication disconnection callback routine.
This is called when user-mode disconnects the server port.
\param[in,out] ConnectionCookie The cookie set in AvConnectNotifyCallback(...). It is connection context.
*/
VOID AVCommDisconnectNotifyCallback(
_In_opt_ PVOID ConnectionCookie
)
{
PAV_CONNECTION_TYPE connectionType = (PAV_CONNECTION_TYPE)ConnectionCookie;
PAGED_CODE();
if (NULL == connectionType)
{
return;
}
// Close communication handle
switch (*connectionType)
{
case AvConnectForEvents:
FltCloseClientPort(Globals.Filter, &Globals.EventsClientPort);
Globals.EventsClientPort = NULL;
break;
default:
return;
}
ExFreePoolWithTag(connectionType,
AV_CONNECTION_CTX_TAG);
}
/**
A wrapper function that prepare the communicate port.
\param[in] SecurityDescriptor Specifies a security descriptor to InitializeObjectAttributes(...).
\param[in] ConnectionType The type of connection: AvConnectForEvents
\return Status of the prepartion.
*/
NTSTATUS AVCommPrepareServerPort(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ AV_CONNECTION_TYPE ConnectionType
)
{
NTSTATUS status;
OBJECT_ATTRIBUTES oa;
UNICODE_STRING uniString;
LONG maxConnections = 1;
PCWSTR portName = NULL;
PFLT_PORT* pServerPort = NULL;
PAGED_CODE();
switch (ConnectionType)
{
case AvConnectForEvents:
portName = AV_SCAN_PORT_NAME;
pServerPort = &Globals.EventsServerPort;
break;
default:
FLT_ASSERTMSG("No such connection type.\n", FALSE);
return STATUS_INVALID_PARAMETER;
}
RtlInitUnicodeString(&uniString, portName);
InitializeObjectAttributes(&oa,
&uniString,
OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE,
NULL,
SecurityDescriptor);
status = FltCreateCommunicationPort(Globals.Filter,
pServerPort, // this is the output to server port.
&oa,
NULL,
AVCommConnectNotifyCallback,
AVCommDisconnectNotifyCallback,
NULL,
maxConnections);
return status;
}
/**
Initialises minifilter-driver that is used for KM-UM communications.
\param[in] Filter Pointer to minifilter driver instance that will be used to register communication port.
\return Status of initialization.
*/
NTSTATUS AVCommInit(PFLT_FILTER Filter)
{
NTSTATUS status = STATUS_SUCCESS;
PSECURITY_DESCRIPTOR sd = NULL;
Globals.Filter = Filter;
try
{
if (!NT_SUCCESS(status))
{
leave;
}
// Builds a default security descriptor for use with FltCreateCommunicationPort.
status = FltBuildDefaultSecurityDescriptor(&sd, FLT_PORT_ALL_ACCESS);
if (!NT_SUCCESS(status))
{
leave;
}
// Prepare ports between kernel and user.
status = AVCommPrepareServerPort(sd, AvConnectForEvents);
if (!NT_SUCCESS(status))
{
leave;
}
}
finally
{
if (sd != NULL)
{
FltFreeSecurityDescriptor(sd);
}
if (!NT_SUCCESS(status))
{
AVCommStop();
}
}
return status;
}
/**
\brief Closes KM-UM communication.
Stops communication port. Zeros out Filter pointer.
*/
void AVCommStop(VOID)
{
if (NULL != Globals.EventsServerPort)
{
FltCloseCommunicationPort(Globals.EventsServerPort);
}
if (NULL != Globals.Filter)
{
Globals.Filter = NULL;
}
}
/**
\brief Transfers KM buffer to UM.
Allocates a block of memory in UM AVCore service and transferes
given KM memory block there.
\param[in] srcBuffer Pointer to the source buffer located in KM address space.
\param[in] srcSize Number of bytes to move from srcBuffer to UM.
\param[out] outUmBuffer Pointer to the pointer that will recieve the address of created buffer.
\param[out\ outUmSize Pointer to the variable where the size of allocated UM buffer will be stored.
of the buffer allocated in the UM address space. Should be zero.
\return Status of operation.
*/
NTSTATUS AVCommCreateBuffer(PVOID srcBuffer, SIZE_T srcSize, void **outUmBuffer, PSIZE_T outUmSize)
{
*outUmSize = srcSize;
// allocat memory in UM address space of AVCore service.
NTSTATUS status = ZwAllocateVirtualMemory(Globals.AVCoreServiceHandle, outUmBuffer, 0, outUmSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (status != STATUS_SUCCESS)
{
// couldn't allocate memory in UM
return status;
}
// Chnage stack to that of the target UM process (AVCore service)
KAPC_STATE pkapcState;
KeStackAttachProcess(Globals.AVCoreServiceEprocess, &pkapcState);
// copy buffer from KM to allocated buffer in UM.
memcpy(*outUmBuffer, srcBuffer, srcSize);
// Restore stack
KeUnstackDetachProcess(&pkapcState);
return status;
}
/**
\brief Retrieves buffer from UM.
Copies buffer from UM. This API is used to copy UM responses buffer
to KM memory. KM buffer should be large enough to receive size bytes.
\param[in] umAddr Address of the buffer provided from UM.
\param[out] outKmBuffer Pointer to the KM bufferthat will recieve contents of specified UM buffer.
\param[in] size Size of the UM buffer.
*/
VOID AVCommGetUmBuffer(PVOID umAddr, PVOID outKmBuffer, SIZE_T size)
{
// Chnage stack to that of the target UM process (AVCore service)
KAPC_STATE pkapcState;
KeStackAttachProcess(Globals.AVCoreServiceEprocess, &pkapcState);
// copy buffer from KM to allocated buffer in UM.
memcpy(outKmBuffer, umAddr, size);
// Restore stack
KeUnstackDetachProcess(&pkapcState);
}
/**
\brief Frees UM memory
Frees the block of memory in UM address space
that was allocated via AVCommCreateBuffer.
\param[in] UmBuffer Pointer to the UM buffer (outUmBuffer)
\param[in] UmBufferSize Size of UM buffer received from AVCommCreateBuffer (outUmSize)
\return Status of operation.
*/
NTSTATUS AVCommFreeBuffer(PVOID UmBuffer, PSIZE_T UmBufferSize)
{
return ZwFreeVirtualMemory(Globals.AVCoreServiceHandle, UmBuffer, UmBufferSize, MEM_RELEASE);
}
/**
\brief Sends given event to UM service via communication port.
This API is blocking. Function will return after event processing in UM.
\param[in] eventBuffer Pointer to the event structure formed in KM memory space.
\param[in] eventBufferSize Size of eventBuffer.
\param[out] UMResponse Pointer to buffer that will receive AV_EVENT_RESPONSE structure.
\param[out] UMResponseLength Size of UMResponse buffer.
\return Status of event submition.
*/
NTSTATUS AVCommSendEvent(AV_EVENT_TYPE eventType, void* eventBuffer, int eventBufferSize, PAV_EVENT_RESPONSE UMResponse, PULONG UMResponseLength)
{
// Prepare AV_MESSAGE structure that will be sent to UM via comm port.
AV_MESSAGE avMessage = { 0 };
avMessage.MessageType = AvMsgEvent;
avMessage.EventType = eventType;
avMessage.EventBuffer = NULL;
avMessage.EventBufferLength = eventBufferSize;
// Put Event structure to UM memory and save address in AV_MESSAGE structure.
SIZE_T umBuffEventSize = avMessage.EventBufferLength;
NTSTATUS status = AVCommCreateBuffer(eventBuffer, umBuffEventSize, &avMessage.EventBuffer, &umBuffEventSize);
if (status != STATUS_SUCCESS)
{
// couldn't allocate memory in UM
return STATUS_MEMORY_NOT_ALLOCATED;
}
// Send event to the AVCore UM service and wait for the response
status = FltSendMessage(Globals.Filter,
&Globals.EventsClientPort,
&avMessage,
sizeof(AV_MESSAGE),
UMResponse,
UMResponseLength,
NULL);
NTSTATUS freeStatus = AVCommFreeBuffer(&avMessage.EventBuffer, &umBuffEventSize);
if (freeStatus != STATUS_SUCCESS) { return freeStatus; }
return status;
}
/**
\brief Implements KM event scanning exclusion based on PID.
This API should be called before submitting events via AVCommSendEvent
to check whether the process is exluded (truested).
By default AVCore service process is trusted.
\param[in] PID Current PID.
\return Excluded (TRUE).
*/
UCHAR AVCommIsExcludedPID(HANDLE PID)
{
return Globals.AVCoreServicePID == PID;
}
/**
\brief Checks KM-UM communication state.
Checks weather client comm port was set up (KM-UM communication
was established).
\return BOOLEAN
*/
UCHAR AVCommIsInitialized()
{
return Globals.EventsClientPort != NULL;
} | 2.171875 | 2 |
2024-11-18T20:50:53.373129+00:00 | 2023-08-30T23:07:48 | dc5f302027dc9d70c03b62202ad978443b9e07e7 | {
"blob_id": "dc5f302027dc9d70c03b62202ad978443b9e07e7",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T23:07:48",
"content_id": "9cc95b773dbf070123a657194c95d321ea05272d",
"detected_licenses": [
"PostgreSQL"
],
"directory_id": "8a51a96f61699f0318315ccc89cef39f6866f2b5",
"extension": "c",
"filename": "jsonb_util.c",
"fork_events_count": 4807,
"gha_created_at": "2010-09-21T11:35:45",
"gha_event_created_at": "2023-09-09T13:59:15",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 927442,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 55587,
"license": "PostgreSQL",
"license_type": "permissive",
"path": "/src/backend/utils/adt/jsonb_util.c",
"provenance": "stackv2-0110.json.gz:227468",
"repo_name": "postgres/postgres",
"revision_date": "2023-08-30T23:07:48",
"revision_id": "b5934bfd6071fed3a38cea0cfaa93afda63d9c0c",
"snapshot_id": "979febf2b41c00090d1256228f768f33e7ef3b6f",
"src_encoding": "UTF-8",
"star_events_count": 13691,
"url": "https://raw.githubusercontent.com/postgres/postgres/b5934bfd6071fed3a38cea0cfaa93afda63d9c0c/src/backend/utils/adt/jsonb_util.c",
"visit_date": "2023-08-31T00:10:01.373472"
} | stackv2 | /*-------------------------------------------------------------------------
*
* jsonb_util.c
* converting between Jsonb and JsonbValues, and iterating.
*
* Copyright (c) 2014-2023, PostgreSQL Global Development Group
*
*
* IDENTIFICATION
* src/backend/utils/adt/jsonb_util.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_type.h"
#include "common/hashfn.h"
#include "common/jsonapi.h"
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/json.h"
#include "utils/jsonb.h"
#include "utils/memutils.h"
#include "utils/varlena.h"
/*
* Maximum number of elements in an array (or key/value pairs in an object).
* This is limited by two things: the size of the JEntry array must fit
* in MaxAllocSize, and the number of elements (or pairs) must fit in the bits
* reserved for that in the JsonbContainer.header field.
*
* (The total size of an array's or object's elements is also limited by
* JENTRY_OFFLENMASK, but we're not concerned about that here.)
*/
#define JSONB_MAX_ELEMS (Min(MaxAllocSize / sizeof(JsonbValue), JB_CMASK))
#define JSONB_MAX_PAIRS (Min(MaxAllocSize / sizeof(JsonbPair), JB_CMASK))
static void fillJsonbValue(JsonbContainer *container, int index,
char *base_addr, uint32 offset,
JsonbValue *result);
static bool equalsJsonbScalarValue(JsonbValue *a, JsonbValue *b);
static int compareJsonbScalarValue(JsonbValue *a, JsonbValue *b);
static Jsonb *convertToJsonb(JsonbValue *val);
static void convertJsonbValue(StringInfo buffer, JEntry *header, JsonbValue *val, int level);
static void convertJsonbArray(StringInfo buffer, JEntry *header, JsonbValue *val, int level);
static void convertJsonbObject(StringInfo buffer, JEntry *header, JsonbValue *val, int level);
static void convertJsonbScalar(StringInfo buffer, JEntry *header, JsonbValue *scalarVal);
static int reserveFromBuffer(StringInfo buffer, int len);
static void appendToBuffer(StringInfo buffer, const char *data, int len);
static void copyToBuffer(StringInfo buffer, int offset, const char *data, int len);
static short padBufferToInt(StringInfo buffer);
static JsonbIterator *iteratorFromContainer(JsonbContainer *container, JsonbIterator *parent);
static JsonbIterator *freeAndGetParent(JsonbIterator *it);
static JsonbParseState *pushState(JsonbParseState **pstate);
static void appendKey(JsonbParseState *pstate, JsonbValue *string);
static void appendValue(JsonbParseState *pstate, JsonbValue *scalarVal);
static void appendElement(JsonbParseState *pstate, JsonbValue *scalarVal);
static int lengthCompareJsonbStringValue(const void *a, const void *b);
static int lengthCompareJsonbString(const char *val1, int len1,
const char *val2, int len2);
static int lengthCompareJsonbPair(const void *a, const void *b, void *binequal);
static void uniqueifyJsonbObject(JsonbValue *object, bool unique_keys,
bool skip_nulls);
static JsonbValue *pushJsonbValueScalar(JsonbParseState **pstate,
JsonbIteratorToken seq,
JsonbValue *scalarVal);
void
JsonbToJsonbValue(Jsonb *jsonb, JsonbValue *val)
{
val->type = jbvBinary;
val->val.binary.data = &jsonb->root;
val->val.binary.len = VARSIZE(jsonb) - VARHDRSZ;
}
/*
* Turn an in-memory JsonbValue into a Jsonb for on-disk storage.
*
* Generally we find it more convenient to directly iterate through the Jsonb
* representation and only really convert nested scalar values.
* JsonbIteratorNext() does this, so that clients of the iteration code don't
* have to directly deal with the binary representation (JsonbDeepContains() is
* a notable exception, although all exceptions are internal to this module).
* In general, functions that accept a JsonbValue argument are concerned with
* the manipulation of scalar values, or simple containers of scalar values,
* where it would be inconvenient to deal with a great amount of other state.
*/
Jsonb *
JsonbValueToJsonb(JsonbValue *val)
{
Jsonb *out;
if (IsAJsonbScalar(val))
{
/* Scalar value */
JsonbParseState *pstate = NULL;
JsonbValue *res;
JsonbValue scalarArray;
scalarArray.type = jbvArray;
scalarArray.val.array.rawScalar = true;
scalarArray.val.array.nElems = 1;
pushJsonbValue(&pstate, WJB_BEGIN_ARRAY, &scalarArray);
pushJsonbValue(&pstate, WJB_ELEM, val);
res = pushJsonbValue(&pstate, WJB_END_ARRAY, NULL);
out = convertToJsonb(res);
}
else if (val->type == jbvObject || val->type == jbvArray)
{
out = convertToJsonb(val);
}
else
{
Assert(val->type == jbvBinary);
out = palloc(VARHDRSZ + val->val.binary.len);
SET_VARSIZE(out, VARHDRSZ + val->val.binary.len);
memcpy(VARDATA(out), val->val.binary.data, val->val.binary.len);
}
return out;
}
/*
* Get the offset of the variable-length portion of a Jsonb node within
* the variable-length-data part of its container. The node is identified
* by index within the container's JEntry array.
*/
uint32
getJsonbOffset(const JsonbContainer *jc, int index)
{
uint32 offset = 0;
int i;
/*
* Start offset of this entry is equal to the end offset of the previous
* entry. Walk backwards to the most recent entry stored as an end
* offset, returning that offset plus any lengths in between.
*/
for (i = index - 1; i >= 0; i--)
{
offset += JBE_OFFLENFLD(jc->children[i]);
if (JBE_HAS_OFF(jc->children[i]))
break;
}
return offset;
}
/*
* Get the length of the variable-length portion of a Jsonb node.
* The node is identified by index within the container's JEntry array.
*/
uint32
getJsonbLength(const JsonbContainer *jc, int index)
{
uint32 off;
uint32 len;
/*
* If the length is stored directly in the JEntry, just return it.
* Otherwise, get the begin offset of the entry, and subtract that from
* the stored end+1 offset.
*/
if (JBE_HAS_OFF(jc->children[index]))
{
off = getJsonbOffset(jc, index);
len = JBE_OFFLENFLD(jc->children[index]) - off;
}
else
len = JBE_OFFLENFLD(jc->children[index]);
return len;
}
/*
* BT comparator worker function. Returns an integer less than, equal to, or
* greater than zero, indicating whether a is less than, equal to, or greater
* than b. Consistent with the requirements for a B-Tree operator class
*
* Strings are compared lexically, in contrast with other places where we use a
* much simpler comparator logic for searching through Strings. Since this is
* called from B-Tree support function 1, we're careful about not leaking
* memory here.
*/
int
compareJsonbContainers(JsonbContainer *a, JsonbContainer *b)
{
JsonbIterator *ita,
*itb;
int res = 0;
ita = JsonbIteratorInit(a);
itb = JsonbIteratorInit(b);
do
{
JsonbValue va,
vb;
JsonbIteratorToken ra,
rb;
ra = JsonbIteratorNext(&ita, &va, false);
rb = JsonbIteratorNext(&itb, &vb, false);
if (ra == rb)
{
if (ra == WJB_DONE)
{
/* Decisively equal */
break;
}
if (ra == WJB_END_ARRAY || ra == WJB_END_OBJECT)
{
/*
* There is no array or object to compare at this stage of
* processing. jbvArray/jbvObject values are compared
* initially, at the WJB_BEGIN_ARRAY and WJB_BEGIN_OBJECT
* tokens.
*/
continue;
}
if (va.type == vb.type)
{
switch (va.type)
{
case jbvString:
case jbvNull:
case jbvNumeric:
case jbvBool:
res = compareJsonbScalarValue(&va, &vb);
break;
case jbvArray:
/*
* This could be a "raw scalar" pseudo array. That's
* a special case here though, since we still want the
* general type-based comparisons to apply, and as far
* as we're concerned a pseudo array is just a scalar.
*/
if (va.val.array.rawScalar != vb.val.array.rawScalar)
res = (va.val.array.rawScalar) ? -1 : 1;
if (va.val.array.nElems != vb.val.array.nElems)
res = (va.val.array.nElems > vb.val.array.nElems) ? 1 : -1;
break;
case jbvObject:
if (va.val.object.nPairs != vb.val.object.nPairs)
res = (va.val.object.nPairs > vb.val.object.nPairs) ? 1 : -1;
break;
case jbvBinary:
elog(ERROR, "unexpected jbvBinary value");
break;
case jbvDatetime:
elog(ERROR, "unexpected jbvDatetime value");
break;
}
}
else
{
/* Type-defined order */
res = (va.type > vb.type) ? 1 : -1;
}
}
else
{
/*
* It's safe to assume that the types differed, and that the va
* and vb values passed were set.
*
* If the two values were of the same container type, then there'd
* have been a chance to observe the variation in the number of
* elements/pairs (when processing WJB_BEGIN_OBJECT, say). They're
* either two heterogeneously-typed containers, or a container and
* some scalar type.
*
* We don't have to consider the WJB_END_ARRAY and WJB_END_OBJECT
* cases here, because we would have seen the corresponding
* WJB_BEGIN_ARRAY and WJB_BEGIN_OBJECT tokens first, and
* concluded that they don't match.
*/
Assert(ra != WJB_END_ARRAY && ra != WJB_END_OBJECT);
Assert(rb != WJB_END_ARRAY && rb != WJB_END_OBJECT);
Assert(va.type != vb.type);
Assert(va.type != jbvBinary);
Assert(vb.type != jbvBinary);
/* Type-defined order */
res = (va.type > vb.type) ? 1 : -1;
}
}
while (res == 0);
while (ita != NULL)
{
JsonbIterator *i = ita->parent;
pfree(ita);
ita = i;
}
while (itb != NULL)
{
JsonbIterator *i = itb->parent;
pfree(itb);
itb = i;
}
return res;
}
/*
* Find value in object (i.e. the "value" part of some key/value pair in an
* object), or find a matching element if we're looking through an array. Do
* so on the basis of equality of the object keys only, or alternatively
* element values only, with a caller-supplied value "key". The "flags"
* argument allows the caller to specify which container types are of interest.
*
* This exported utility function exists to facilitate various cases concerned
* with "containment". If asked to look through an object, the caller had
* better pass a Jsonb String, because their keys can only be strings.
* Otherwise, for an array, any type of JsonbValue will do.
*
* In order to proceed with the search, it is necessary for callers to have
* both specified an interest in exactly one particular container type with an
* appropriate flag, as well as having the pointed-to Jsonb container be of
* one of those same container types at the top level. (Actually, we just do
* whichever makes sense to save callers the trouble of figuring it out - at
* most one can make sense, because the container either points to an array
* (possibly a "raw scalar" pseudo array) or an object.)
*
* Note that we can return a jbvBinary JsonbValue if this is called on an
* object, but we never do so on an array. If the caller asks to look through
* a container type that is not of the type pointed to by the container,
* immediately fall through and return NULL. If we cannot find the value,
* return NULL. Otherwise, return palloc()'d copy of value.
*/
JsonbValue *
findJsonbValueFromContainer(JsonbContainer *container, uint32 flags,
JsonbValue *key)
{
JEntry *children = container->children;
int count = JsonContainerSize(container);
Assert((flags & ~(JB_FARRAY | JB_FOBJECT)) == 0);
/* Quick out without a palloc cycle if object/array is empty */
if (count <= 0)
return NULL;
if ((flags & JB_FARRAY) && JsonContainerIsArray(container))
{
JsonbValue *result = palloc(sizeof(JsonbValue));
char *base_addr = (char *) (children + count);
uint32 offset = 0;
int i;
for (i = 0; i < count; i++)
{
fillJsonbValue(container, i, base_addr, offset, result);
if (key->type == result->type)
{
if (equalsJsonbScalarValue(key, result))
return result;
}
JBE_ADVANCE_OFFSET(offset, children[i]);
}
pfree(result);
}
else if ((flags & JB_FOBJECT) && JsonContainerIsObject(container))
{
/* Object key passed by caller must be a string */
Assert(key->type == jbvString);
return getKeyJsonValueFromContainer(container, key->val.string.val,
key->val.string.len, NULL);
}
/* Not found */
return NULL;
}
/*
* Find value by key in Jsonb object and fetch it into 'res', which is also
* returned.
*
* 'res' can be passed in as NULL, in which case it's newly palloc'ed here.
*/
JsonbValue *
getKeyJsonValueFromContainer(JsonbContainer *container,
const char *keyVal, int keyLen, JsonbValue *res)
{
JEntry *children = container->children;
int count = JsonContainerSize(container);
char *baseAddr;
uint32 stopLow,
stopHigh;
Assert(JsonContainerIsObject(container));
/* Quick out without a palloc cycle if object is empty */
if (count <= 0)
return NULL;
/*
* Binary search the container. Since we know this is an object, account
* for *Pairs* of Jentrys
*/
baseAddr = (char *) (children + count * 2);
stopLow = 0;
stopHigh = count;
while (stopLow < stopHigh)
{
uint32 stopMiddle;
int difference;
const char *candidateVal;
int candidateLen;
stopMiddle = stopLow + (stopHigh - stopLow) / 2;
candidateVal = baseAddr + getJsonbOffset(container, stopMiddle);
candidateLen = getJsonbLength(container, stopMiddle);
difference = lengthCompareJsonbString(candidateVal, candidateLen,
keyVal, keyLen);
if (difference == 0)
{
/* Found our key, return corresponding value */
int index = stopMiddle + count;
if (!res)
res = palloc(sizeof(JsonbValue));
fillJsonbValue(container, index, baseAddr,
getJsonbOffset(container, index),
res);
return res;
}
else
{
if (difference < 0)
stopLow = stopMiddle + 1;
else
stopHigh = stopMiddle;
}
}
/* Not found */
return NULL;
}
/*
* Get i-th value of a Jsonb array.
*
* Returns palloc()'d copy of the value, or NULL if it does not exist.
*/
JsonbValue *
getIthJsonbValueFromContainer(JsonbContainer *container, uint32 i)
{
JsonbValue *result;
char *base_addr;
uint32 nelements;
if (!JsonContainerIsArray(container))
elog(ERROR, "not a jsonb array");
nelements = JsonContainerSize(container);
base_addr = (char *) &container->children[nelements];
if (i >= nelements)
return NULL;
result = palloc(sizeof(JsonbValue));
fillJsonbValue(container, i, base_addr,
getJsonbOffset(container, i),
result);
return result;
}
/*
* A helper function to fill in a JsonbValue to represent an element of an
* array, or a key or value of an object.
*
* The node's JEntry is at container->children[index], and its variable-length
* data is at base_addr + offset. We make the caller determine the offset
* since in many cases the caller can amortize that work across multiple
* children. When it can't, it can just call getJsonbOffset().
*
* A nested array or object will be returned as jbvBinary, ie. it won't be
* expanded.
*/
static void
fillJsonbValue(JsonbContainer *container, int index,
char *base_addr, uint32 offset,
JsonbValue *result)
{
JEntry entry = container->children[index];
if (JBE_ISNULL(entry))
{
result->type = jbvNull;
}
else if (JBE_ISSTRING(entry))
{
result->type = jbvString;
result->val.string.val = base_addr + offset;
result->val.string.len = getJsonbLength(container, index);
Assert(result->val.string.len >= 0);
}
else if (JBE_ISNUMERIC(entry))
{
result->type = jbvNumeric;
result->val.numeric = (Numeric) (base_addr + INTALIGN(offset));
}
else if (JBE_ISBOOL_TRUE(entry))
{
result->type = jbvBool;
result->val.boolean = true;
}
else if (JBE_ISBOOL_FALSE(entry))
{
result->type = jbvBool;
result->val.boolean = false;
}
else
{
Assert(JBE_ISCONTAINER(entry));
result->type = jbvBinary;
/* Remove alignment padding from data pointer and length */
result->val.binary.data = (JsonbContainer *) (base_addr + INTALIGN(offset));
result->val.binary.len = getJsonbLength(container, index) -
(INTALIGN(offset) - offset);
}
}
/*
* Push JsonbValue into JsonbParseState.
*
* Used when parsing JSON tokens to form Jsonb, or when converting an in-memory
* JsonbValue to a Jsonb.
*
* Initial state of *JsonbParseState is NULL, since it'll be allocated here
* originally (caller will get JsonbParseState back by reference).
*
* Only sequential tokens pertaining to non-container types should pass a
* JsonbValue. There is one exception -- WJB_BEGIN_ARRAY callers may pass a
* "raw scalar" pseudo array to append it - the actual scalar should be passed
* next and it will be added as the only member of the array.
*
* Values of type jbvBinary, which are rolled up arrays and objects,
* are unpacked before being added to the result.
*/
JsonbValue *
pushJsonbValue(JsonbParseState **pstate, JsonbIteratorToken seq,
JsonbValue *jbval)
{
JsonbIterator *it;
JsonbValue *res = NULL;
JsonbValue v;
JsonbIteratorToken tok;
int i;
if (jbval && (seq == WJB_ELEM || seq == WJB_VALUE) && jbval->type == jbvObject)
{
pushJsonbValue(pstate, WJB_BEGIN_OBJECT, NULL);
for (i = 0; i < jbval->val.object.nPairs; i++)
{
pushJsonbValue(pstate, WJB_KEY, &jbval->val.object.pairs[i].key);
pushJsonbValue(pstate, WJB_VALUE, &jbval->val.object.pairs[i].value);
}
return pushJsonbValue(pstate, WJB_END_OBJECT, NULL);
}
if (jbval && (seq == WJB_ELEM || seq == WJB_VALUE) && jbval->type == jbvArray)
{
pushJsonbValue(pstate, WJB_BEGIN_ARRAY, NULL);
for (i = 0; i < jbval->val.array.nElems; i++)
{
pushJsonbValue(pstate, WJB_ELEM, &jbval->val.array.elems[i]);
}
return pushJsonbValue(pstate, WJB_END_ARRAY, NULL);
}
if (!jbval || (seq != WJB_ELEM && seq != WJB_VALUE) ||
jbval->type != jbvBinary)
{
/* drop through */
return pushJsonbValueScalar(pstate, seq, jbval);
}
/* unpack the binary and add each piece to the pstate */
it = JsonbIteratorInit(jbval->val.binary.data);
if ((jbval->val.binary.data->header & JB_FSCALAR) && *pstate)
{
tok = JsonbIteratorNext(&it, &v, true);
Assert(tok == WJB_BEGIN_ARRAY);
Assert(v.type == jbvArray && v.val.array.rawScalar);
tok = JsonbIteratorNext(&it, &v, true);
Assert(tok == WJB_ELEM);
res = pushJsonbValueScalar(pstate, seq, &v);
tok = JsonbIteratorNext(&it, &v, true);
Assert(tok == WJB_END_ARRAY);
Assert(it == NULL);
return res;
}
while ((tok = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
res = pushJsonbValueScalar(pstate, tok,
tok < WJB_BEGIN_ARRAY ||
(tok == WJB_BEGIN_ARRAY &&
v.val.array.rawScalar) ? &v : NULL);
return res;
}
/*
* Do the actual pushing, with only scalar or pseudo-scalar-array values
* accepted.
*/
static JsonbValue *
pushJsonbValueScalar(JsonbParseState **pstate, JsonbIteratorToken seq,
JsonbValue *scalarVal)
{
JsonbValue *result = NULL;
switch (seq)
{
case WJB_BEGIN_ARRAY:
Assert(!scalarVal || scalarVal->val.array.rawScalar);
*pstate = pushState(pstate);
result = &(*pstate)->contVal;
(*pstate)->contVal.type = jbvArray;
(*pstate)->contVal.val.array.nElems = 0;
(*pstate)->contVal.val.array.rawScalar = (scalarVal &&
scalarVal->val.array.rawScalar);
if (scalarVal && scalarVal->val.array.nElems > 0)
{
/* Assume that this array is still really a scalar */
Assert(scalarVal->type == jbvArray);
(*pstate)->size = scalarVal->val.array.nElems;
}
else
{
(*pstate)->size = 4;
}
(*pstate)->contVal.val.array.elems = palloc(sizeof(JsonbValue) *
(*pstate)->size);
break;
case WJB_BEGIN_OBJECT:
Assert(!scalarVal);
*pstate = pushState(pstate);
result = &(*pstate)->contVal;
(*pstate)->contVal.type = jbvObject;
(*pstate)->contVal.val.object.nPairs = 0;
(*pstate)->size = 4;
(*pstate)->contVal.val.object.pairs = palloc(sizeof(JsonbPair) *
(*pstate)->size);
break;
case WJB_KEY:
Assert(scalarVal->type == jbvString);
appendKey(*pstate, scalarVal);
break;
case WJB_VALUE:
Assert(IsAJsonbScalar(scalarVal));
appendValue(*pstate, scalarVal);
break;
case WJB_ELEM:
Assert(IsAJsonbScalar(scalarVal));
appendElement(*pstate, scalarVal);
break;
case WJB_END_OBJECT:
uniqueifyJsonbObject(&(*pstate)->contVal,
(*pstate)->unique_keys,
(*pstate)->skip_nulls);
/* fall through! */
case WJB_END_ARRAY:
/* Steps here common to WJB_END_OBJECT case */
Assert(!scalarVal);
result = &(*pstate)->contVal;
/*
* Pop stack and push current array/object as value in parent
* array/object
*/
*pstate = (*pstate)->next;
if (*pstate)
{
switch ((*pstate)->contVal.type)
{
case jbvArray:
appendElement(*pstate, result);
break;
case jbvObject:
appendValue(*pstate, result);
break;
default:
elog(ERROR, "invalid jsonb container type");
}
}
break;
default:
elog(ERROR, "unrecognized jsonb sequential processing token");
}
return result;
}
/*
* pushJsonbValue() worker: Iteration-like forming of Jsonb
*/
static JsonbParseState *
pushState(JsonbParseState **pstate)
{
JsonbParseState *ns = palloc(sizeof(JsonbParseState));
ns->next = *pstate;
ns->unique_keys = false;
ns->skip_nulls = false;
return ns;
}
/*
* pushJsonbValue() worker: Append a pair key to state when generating a Jsonb
*/
static void
appendKey(JsonbParseState *pstate, JsonbValue *string)
{
JsonbValue *object = &pstate->contVal;
Assert(object->type == jbvObject);
Assert(string->type == jbvString);
if (object->val.object.nPairs >= JSONB_MAX_PAIRS)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of jsonb object pairs exceeds the maximum allowed (%zu)",
JSONB_MAX_PAIRS)));
if (object->val.object.nPairs >= pstate->size)
{
pstate->size *= 2;
object->val.object.pairs = repalloc(object->val.object.pairs,
sizeof(JsonbPair) * pstate->size);
}
object->val.object.pairs[object->val.object.nPairs].key = *string;
object->val.object.pairs[object->val.object.nPairs].order = object->val.object.nPairs;
}
/*
* pushJsonbValue() worker: Append a pair value to state when generating a
* Jsonb
*/
static void
appendValue(JsonbParseState *pstate, JsonbValue *scalarVal)
{
JsonbValue *object = &pstate->contVal;
Assert(object->type == jbvObject);
object->val.object.pairs[object->val.object.nPairs++].value = *scalarVal;
}
/*
* pushJsonbValue() worker: Append an element to state when generating a Jsonb
*/
static void
appendElement(JsonbParseState *pstate, JsonbValue *scalarVal)
{
JsonbValue *array = &pstate->contVal;
Assert(array->type == jbvArray);
if (array->val.array.nElems >= JSONB_MAX_ELEMS)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of jsonb array elements exceeds the maximum allowed (%zu)",
JSONB_MAX_ELEMS)));
if (array->val.array.nElems >= pstate->size)
{
pstate->size *= 2;
array->val.array.elems = repalloc(array->val.array.elems,
sizeof(JsonbValue) * pstate->size);
}
array->val.array.elems[array->val.array.nElems++] = *scalarVal;
}
/*
* Given a JsonbContainer, expand to JsonbIterator to iterate over items
* fully expanded to in-memory representation for manipulation.
*
* See JsonbIteratorNext() for notes on memory management.
*/
JsonbIterator *
JsonbIteratorInit(JsonbContainer *container)
{
return iteratorFromContainer(container, NULL);
}
/*
* Get next JsonbValue while iterating
*
* Caller should initially pass their own, original iterator. They may get
* back a child iterator palloc()'d here instead. The function can be relied
* on to free those child iterators, lest the memory allocated for highly
* nested objects become unreasonable, but only if callers don't end iteration
* early (by breaking upon having found something in a search, for example).
*
* Callers in such a scenario, that are particularly sensitive to leaking
* memory in a long-lived context may walk the ancestral tree from the final
* iterator we left them with to its oldest ancestor, pfree()ing as they go.
* They do not have to free any other memory previously allocated for iterators
* but not accessible as direct ancestors of the iterator they're last passed
* back.
*
* Returns "Jsonb sequential processing" token value. Iterator "state"
* reflects the current stage of the process in a less granular fashion, and is
* mostly used here to track things internally with respect to particular
* iterators.
*
* Clients of this function should not have to handle any jbvBinary values
* (since recursive calls will deal with this), provided skipNested is false.
* It is our job to expand the jbvBinary representation without bothering them
* with it. However, clients should not take it upon themselves to touch array
* or Object element/pair buffers, since their element/pair pointers are
* garbage. Also, *val will not be set when returning WJB_END_ARRAY or
* WJB_END_OBJECT, on the assumption that it's only useful to access values
* when recursing in.
*/
JsonbIteratorToken
JsonbIteratorNext(JsonbIterator **it, JsonbValue *val, bool skipNested)
{
if (*it == NULL)
return WJB_DONE;
/*
* When stepping into a nested container, we jump back here to start
* processing the child. We will not recurse further in one call, because
* processing the child will always begin in JBI_ARRAY_START or
* JBI_OBJECT_START state.
*/
recurse:
switch ((*it)->state)
{
case JBI_ARRAY_START:
/* Set v to array on first array call */
val->type = jbvArray;
val->val.array.nElems = (*it)->nElems;
/*
* v->val.array.elems is not actually set, because we aren't doing
* a full conversion
*/
val->val.array.rawScalar = (*it)->isScalar;
(*it)->curIndex = 0;
(*it)->curDataOffset = 0;
(*it)->curValueOffset = 0; /* not actually used */
/* Set state for next call */
(*it)->state = JBI_ARRAY_ELEM;
return WJB_BEGIN_ARRAY;
case JBI_ARRAY_ELEM:
if ((*it)->curIndex >= (*it)->nElems)
{
/*
* All elements within array already processed. Report this
* to caller, and give it back original parent iterator (which
* independently tracks iteration progress at its level of
* nesting).
*/
*it = freeAndGetParent(*it);
return WJB_END_ARRAY;
}
fillJsonbValue((*it)->container, (*it)->curIndex,
(*it)->dataProper, (*it)->curDataOffset,
val);
JBE_ADVANCE_OFFSET((*it)->curDataOffset,
(*it)->children[(*it)->curIndex]);
(*it)->curIndex++;
if (!IsAJsonbScalar(val) && !skipNested)
{
/* Recurse into container. */
*it = iteratorFromContainer(val->val.binary.data, *it);
goto recurse;
}
else
{
/*
* Scalar item in array, or a container and caller didn't want
* us to recurse into it.
*/
return WJB_ELEM;
}
case JBI_OBJECT_START:
/* Set v to object on first object call */
val->type = jbvObject;
val->val.object.nPairs = (*it)->nElems;
/*
* v->val.object.pairs is not actually set, because we aren't
* doing a full conversion
*/
(*it)->curIndex = 0;
(*it)->curDataOffset = 0;
(*it)->curValueOffset = getJsonbOffset((*it)->container,
(*it)->nElems);
/* Set state for next call */
(*it)->state = JBI_OBJECT_KEY;
return WJB_BEGIN_OBJECT;
case JBI_OBJECT_KEY:
if ((*it)->curIndex >= (*it)->nElems)
{
/*
* All pairs within object already processed. Report this to
* caller, and give it back original containing iterator
* (which independently tracks iteration progress at its level
* of nesting).
*/
*it = freeAndGetParent(*it);
return WJB_END_OBJECT;
}
else
{
/* Return key of a key/value pair. */
fillJsonbValue((*it)->container, (*it)->curIndex,
(*it)->dataProper, (*it)->curDataOffset,
val);
if (val->type != jbvString)
elog(ERROR, "unexpected jsonb type as object key");
/* Set state for next call */
(*it)->state = JBI_OBJECT_VALUE;
return WJB_KEY;
}
case JBI_OBJECT_VALUE:
/* Set state for next call */
(*it)->state = JBI_OBJECT_KEY;
fillJsonbValue((*it)->container, (*it)->curIndex + (*it)->nElems,
(*it)->dataProper, (*it)->curValueOffset,
val);
JBE_ADVANCE_OFFSET((*it)->curDataOffset,
(*it)->children[(*it)->curIndex]);
JBE_ADVANCE_OFFSET((*it)->curValueOffset,
(*it)->children[(*it)->curIndex + (*it)->nElems]);
(*it)->curIndex++;
/*
* Value may be a container, in which case we recurse with new,
* child iterator (unless the caller asked not to, by passing
* skipNested).
*/
if (!IsAJsonbScalar(val) && !skipNested)
{
*it = iteratorFromContainer(val->val.binary.data, *it);
goto recurse;
}
else
return WJB_VALUE;
}
elog(ERROR, "invalid iterator state");
return -1;
}
/*
* Initialize an iterator for iterating all elements in a container.
*/
static JsonbIterator *
iteratorFromContainer(JsonbContainer *container, JsonbIterator *parent)
{
JsonbIterator *it;
it = palloc0(sizeof(JsonbIterator));
it->container = container;
it->parent = parent;
it->nElems = JsonContainerSize(container);
/* Array starts just after header */
it->children = container->children;
switch (container->header & (JB_FARRAY | JB_FOBJECT))
{
case JB_FARRAY:
it->dataProper =
(char *) it->children + it->nElems * sizeof(JEntry);
it->isScalar = JsonContainerIsScalar(container);
/* This is either a "raw scalar", or an array */
Assert(!it->isScalar || it->nElems == 1);
it->state = JBI_ARRAY_START;
break;
case JB_FOBJECT:
it->dataProper =
(char *) it->children + it->nElems * sizeof(JEntry) * 2;
it->state = JBI_OBJECT_START;
break;
default:
elog(ERROR, "unknown type of jsonb container");
}
return it;
}
/*
* JsonbIteratorNext() worker: Return parent, while freeing memory for current
* iterator
*/
static JsonbIterator *
freeAndGetParent(JsonbIterator *it)
{
JsonbIterator *v = it->parent;
pfree(it);
return v;
}
/*
* Worker for "contains" operator's function
*
* Formally speaking, containment is top-down, unordered subtree isomorphism.
*
* Takes iterators that belong to some container type. These iterators
* "belong" to those values in the sense that they've just been initialized in
* respect of them by the caller (perhaps in a nested fashion).
*
* "val" is lhs Jsonb, and mContained is rhs Jsonb when called from top level.
* We determine if mContained is contained within val.
*/
bool
JsonbDeepContains(JsonbIterator **val, JsonbIterator **mContained)
{
JsonbValue vval,
vcontained;
JsonbIteratorToken rval,
rcont;
/*
* Guard against stack overflow due to overly complex Jsonb.
*
* Functions called here independently take this precaution, but that
* might not be sufficient since this is also a recursive function.
*/
check_stack_depth();
rval = JsonbIteratorNext(val, &vval, false);
rcont = JsonbIteratorNext(mContained, &vcontained, false);
if (rval != rcont)
{
/*
* The differing return values can immediately be taken as indicating
* two differing container types at this nesting level, which is
* sufficient reason to give up entirely (but it should be the case
* that they're both some container type).
*/
Assert(rval == WJB_BEGIN_OBJECT || rval == WJB_BEGIN_ARRAY);
Assert(rcont == WJB_BEGIN_OBJECT || rcont == WJB_BEGIN_ARRAY);
return false;
}
else if (rcont == WJB_BEGIN_OBJECT)
{
Assert(vval.type == jbvObject);
Assert(vcontained.type == jbvObject);
/*
* If the lhs has fewer pairs than the rhs, it can't possibly contain
* the rhs. (This conclusion is safe only because we de-duplicate
* keys in all Jsonb objects; thus there can be no corresponding
* optimization in the array case.) The case probably won't arise
* often, but since it's such a cheap check we may as well make it.
*/
if (vval.val.object.nPairs < vcontained.val.object.nPairs)
return false;
/* Work through rhs "is it contained within?" object */
for (;;)
{
JsonbValue *lhsVal; /* lhsVal is from pair in lhs object */
JsonbValue lhsValBuf;
rcont = JsonbIteratorNext(mContained, &vcontained, false);
/*
* When we get through caller's rhs "is it contained within?"
* object without failing to find one of its values, it's
* contained.
*/
if (rcont == WJB_END_OBJECT)
return true;
Assert(rcont == WJB_KEY);
Assert(vcontained.type == jbvString);
/* First, find value by key... */
lhsVal =
getKeyJsonValueFromContainer((*val)->container,
vcontained.val.string.val,
vcontained.val.string.len,
&lhsValBuf);
if (!lhsVal)
return false;
/*
* ...at this stage it is apparent that there is at least a key
* match for this rhs pair.
*/
rcont = JsonbIteratorNext(mContained, &vcontained, true);
Assert(rcont == WJB_VALUE);
/*
* Compare rhs pair's value with lhs pair's value just found using
* key
*/
if (lhsVal->type != vcontained.type)
{
return false;
}
else if (IsAJsonbScalar(lhsVal))
{
if (!equalsJsonbScalarValue(lhsVal, &vcontained))
return false;
}
else
{
/* Nested container value (object or array) */
JsonbIterator *nestval,
*nestContained;
Assert(lhsVal->type == jbvBinary);
Assert(vcontained.type == jbvBinary);
nestval = JsonbIteratorInit(lhsVal->val.binary.data);
nestContained = JsonbIteratorInit(vcontained.val.binary.data);
/*
* Match "value" side of rhs datum object's pair recursively.
* It's a nested structure.
*
* Note that nesting still has to "match up" at the right
* nesting sub-levels. However, there need only be zero or
* more matching pairs (or elements) at each nesting level
* (provided the *rhs* pairs/elements *all* match on each
* level), which enables searching nested structures for a
* single String or other primitive type sub-datum quite
* effectively (provided the user constructed the rhs nested
* structure such that we "know where to look").
*
* In other words, the mapping of container nodes in the rhs
* "vcontained" Jsonb to internal nodes on the lhs is
* injective, and parent-child edges on the rhs must be mapped
* to parent-child edges on the lhs to satisfy the condition
* of containment (plus of course the mapped nodes must be
* equal).
*/
if (!JsonbDeepContains(&nestval, &nestContained))
return false;
}
}
}
else if (rcont == WJB_BEGIN_ARRAY)
{
JsonbValue *lhsConts = NULL;
uint32 nLhsElems = vval.val.array.nElems;
Assert(vval.type == jbvArray);
Assert(vcontained.type == jbvArray);
/*
* Handle distinction between "raw scalar" pseudo arrays, and real
* arrays.
*
* A raw scalar may contain another raw scalar, and an array may
* contain a raw scalar, but a raw scalar may not contain an array. We
* don't do something like this for the object case, since objects can
* only contain pairs, never raw scalars (a pair is represented by an
* rhs object argument with a single contained pair).
*/
if (vval.val.array.rawScalar && !vcontained.val.array.rawScalar)
return false;
/* Work through rhs "is it contained within?" array */
for (;;)
{
rcont = JsonbIteratorNext(mContained, &vcontained, true);
/*
* When we get through caller's rhs "is it contained within?"
* array without failing to find one of its values, it's
* contained.
*/
if (rcont == WJB_END_ARRAY)
return true;
Assert(rcont == WJB_ELEM);
if (IsAJsonbScalar(&vcontained))
{
if (!findJsonbValueFromContainer((*val)->container,
JB_FARRAY,
&vcontained))
return false;
}
else
{
uint32 i;
/*
* If this is first container found in rhs array (at this
* depth), initialize temp lhs array of containers
*/
if (lhsConts == NULL)
{
uint32 j = 0;
/* Make room for all possible values */
lhsConts = palloc(sizeof(JsonbValue) * nLhsElems);
for (i = 0; i < nLhsElems; i++)
{
/* Store all lhs elements in temp array */
rcont = JsonbIteratorNext(val, &vval, true);
Assert(rcont == WJB_ELEM);
if (vval.type == jbvBinary)
lhsConts[j++] = vval;
}
/* No container elements in temp array, so give up now */
if (j == 0)
return false;
/* We may have only partially filled array */
nLhsElems = j;
}
/* XXX: Nested array containment is O(N^2) */
for (i = 0; i < nLhsElems; i++)
{
/* Nested container value (object or array) */
JsonbIterator *nestval,
*nestContained;
bool contains;
nestval = JsonbIteratorInit(lhsConts[i].val.binary.data);
nestContained = JsonbIteratorInit(vcontained.val.binary.data);
contains = JsonbDeepContains(&nestval, &nestContained);
if (nestval)
pfree(nestval);
if (nestContained)
pfree(nestContained);
if (contains)
break;
}
/*
* Report rhs container value is not contained if couldn't
* match rhs container to *some* lhs cont
*/
if (i == nLhsElems)
return false;
}
}
}
else
{
elog(ERROR, "invalid jsonb container type");
}
elog(ERROR, "unexpectedly fell off end of jsonb container");
return false;
}
/*
* Hash a JsonbValue scalar value, mixing the hash value into an existing
* hash provided by the caller.
*
* Some callers may wish to independently XOR in JB_FOBJECT and JB_FARRAY
* flags.
*/
void
JsonbHashScalarValue(const JsonbValue *scalarVal, uint32 *hash)
{
uint32 tmp;
/* Compute hash value for scalarVal */
switch (scalarVal->type)
{
case jbvNull:
tmp = 0x01;
break;
case jbvString:
tmp = DatumGetUInt32(hash_any((const unsigned char *) scalarVal->val.string.val,
scalarVal->val.string.len));
break;
case jbvNumeric:
/* Must hash equal numerics to equal hash codes */
tmp = DatumGetUInt32(DirectFunctionCall1(hash_numeric,
NumericGetDatum(scalarVal->val.numeric)));
break;
case jbvBool:
tmp = scalarVal->val.boolean ? 0x02 : 0x04;
break;
default:
elog(ERROR, "invalid jsonb scalar type");
tmp = 0; /* keep compiler quiet */
break;
}
/*
* Combine hash values of successive keys, values and elements by rotating
* the previous value left 1 bit, then XOR'ing in the new
* key/value/element's hash value.
*/
*hash = pg_rotate_left32(*hash, 1);
*hash ^= tmp;
}
/*
* Hash a value to a 64-bit value, with a seed. Otherwise, similar to
* JsonbHashScalarValue.
*/
void
JsonbHashScalarValueExtended(const JsonbValue *scalarVal, uint64 *hash,
uint64 seed)
{
uint64 tmp;
switch (scalarVal->type)
{
case jbvNull:
tmp = seed + 0x01;
break;
case jbvString:
tmp = DatumGetUInt64(hash_any_extended((const unsigned char *) scalarVal->val.string.val,
scalarVal->val.string.len,
seed));
break;
case jbvNumeric:
tmp = DatumGetUInt64(DirectFunctionCall2(hash_numeric_extended,
NumericGetDatum(scalarVal->val.numeric),
UInt64GetDatum(seed)));
break;
case jbvBool:
if (seed)
tmp = DatumGetUInt64(DirectFunctionCall2(hashcharextended,
BoolGetDatum(scalarVal->val.boolean),
UInt64GetDatum(seed)));
else
tmp = scalarVal->val.boolean ? 0x02 : 0x04;
break;
default:
elog(ERROR, "invalid jsonb scalar type");
break;
}
*hash = ROTATE_HIGH_AND_LOW_32BITS(*hash);
*hash ^= tmp;
}
/*
* Are two scalar JsonbValues of the same type a and b equal?
*/
static bool
equalsJsonbScalarValue(JsonbValue *a, JsonbValue *b)
{
if (a->type == b->type)
{
switch (a->type)
{
case jbvNull:
return true;
case jbvString:
return lengthCompareJsonbStringValue(a, b) == 0;
case jbvNumeric:
return DatumGetBool(DirectFunctionCall2(numeric_eq,
PointerGetDatum(a->val.numeric),
PointerGetDatum(b->val.numeric)));
case jbvBool:
return a->val.boolean == b->val.boolean;
default:
elog(ERROR, "invalid jsonb scalar type");
}
}
elog(ERROR, "jsonb scalar type mismatch");
return false;
}
/*
* Compare two scalar JsonbValues, returning -1, 0, or 1.
*
* Strings are compared using the default collation. Used by B-tree
* operators, where a lexical sort order is generally expected.
*/
static int
compareJsonbScalarValue(JsonbValue *a, JsonbValue *b)
{
if (a->type == b->type)
{
switch (a->type)
{
case jbvNull:
return 0;
case jbvString:
return varstr_cmp(a->val.string.val,
a->val.string.len,
b->val.string.val,
b->val.string.len,
DEFAULT_COLLATION_OID);
case jbvNumeric:
return DatumGetInt32(DirectFunctionCall2(numeric_cmp,
PointerGetDatum(a->val.numeric),
PointerGetDatum(b->val.numeric)));
case jbvBool:
if (a->val.boolean == b->val.boolean)
return 0;
else if (a->val.boolean > b->val.boolean)
return 1;
else
return -1;
default:
elog(ERROR, "invalid jsonb scalar type");
}
}
elog(ERROR, "jsonb scalar type mismatch");
return -1;
}
/*
* Functions for manipulating the resizable buffer used by convertJsonb and
* its subroutines.
*/
/*
* Reserve 'len' bytes, at the end of the buffer, enlarging it if necessary.
* Returns the offset to the reserved area. The caller is expected to fill
* the reserved area later with copyToBuffer().
*/
static int
reserveFromBuffer(StringInfo buffer, int len)
{
int offset;
/* Make more room if needed */
enlargeStringInfo(buffer, len);
/* remember current offset */
offset = buffer->len;
/* reserve the space */
buffer->len += len;
/*
* Keep a trailing null in place, even though it's not useful for us; it
* seems best to preserve the invariants of StringInfos.
*/
buffer->data[buffer->len] = '\0';
return offset;
}
/*
* Copy 'len' bytes to a previously reserved area in buffer.
*/
static void
copyToBuffer(StringInfo buffer, int offset, const char *data, int len)
{
memcpy(buffer->data + offset, data, len);
}
/*
* A shorthand for reserveFromBuffer + copyToBuffer.
*/
static void
appendToBuffer(StringInfo buffer, const char *data, int len)
{
int offset;
offset = reserveFromBuffer(buffer, len);
copyToBuffer(buffer, offset, data, len);
}
/*
* Append padding, so that the length of the StringInfo is int-aligned.
* Returns the number of padding bytes appended.
*/
static short
padBufferToInt(StringInfo buffer)
{
int padlen,
p,
offset;
padlen = INTALIGN(buffer->len) - buffer->len;
offset = reserveFromBuffer(buffer, padlen);
/* padlen must be small, so this is probably faster than a memset */
for (p = 0; p < padlen; p++)
buffer->data[offset + p] = '\0';
return padlen;
}
/*
* Given a JsonbValue, convert to Jsonb. The result is palloc'd.
*/
static Jsonb *
convertToJsonb(JsonbValue *val)
{
StringInfoData buffer;
JEntry jentry;
Jsonb *res;
/* Should not already have binary representation */
Assert(val->type != jbvBinary);
/* Allocate an output buffer. It will be enlarged as needed */
initStringInfo(&buffer);
/* Make room for the varlena header */
reserveFromBuffer(&buffer, VARHDRSZ);
convertJsonbValue(&buffer, &jentry, val, 0);
/*
* Note: the JEntry of the root is discarded. Therefore the root
* JsonbContainer struct must contain enough information to tell what kind
* of value it is.
*/
res = (Jsonb *) buffer.data;
SET_VARSIZE(res, buffer.len);
return res;
}
/*
* Subroutine of convertJsonb: serialize a single JsonbValue into buffer.
*
* The JEntry header for this node is returned in *header. It is filled in
* with the length of this value and appropriate type bits. If we wish to
* store an end offset rather than a length, it is the caller's responsibility
* to adjust for that.
*
* If the value is an array or an object, this recurses. 'level' is only used
* for debugging purposes.
*/
static void
convertJsonbValue(StringInfo buffer, JEntry *header, JsonbValue *val, int level)
{
check_stack_depth();
if (!val)
return;
/*
* A JsonbValue passed as val should never have a type of jbvBinary, and
* neither should any of its sub-components. Those values will be produced
* by convertJsonbArray and convertJsonbObject, the results of which will
* not be passed back to this function as an argument.
*/
if (IsAJsonbScalar(val))
convertJsonbScalar(buffer, header, val);
else if (val->type == jbvArray)
convertJsonbArray(buffer, header, val, level);
else if (val->type == jbvObject)
convertJsonbObject(buffer, header, val, level);
else
elog(ERROR, "unknown type of jsonb container to convert");
}
static void
convertJsonbArray(StringInfo buffer, JEntry *header, JsonbValue *val, int level)
{
int base_offset;
int jentry_offset;
int i;
int totallen;
uint32 containerhead;
int nElems = val->val.array.nElems;
/* Remember where in the buffer this array starts. */
base_offset = buffer->len;
/* Align to 4-byte boundary (any padding counts as part of my data) */
padBufferToInt(buffer);
/*
* Construct the header Jentry and store it in the beginning of the
* variable-length payload.
*/
containerhead = nElems | JB_FARRAY;
if (val->val.array.rawScalar)
{
Assert(nElems == 1);
Assert(level == 0);
containerhead |= JB_FSCALAR;
}
appendToBuffer(buffer, (char *) &containerhead, sizeof(uint32));
/* Reserve space for the JEntries of the elements. */
jentry_offset = reserveFromBuffer(buffer, sizeof(JEntry) * nElems);
totallen = 0;
for (i = 0; i < nElems; i++)
{
JsonbValue *elem = &val->val.array.elems[i];
int len;
JEntry meta;
/*
* Convert element, producing a JEntry and appending its
* variable-length data to buffer
*/
convertJsonbValue(buffer, &meta, elem, level + 1);
len = JBE_OFFLENFLD(meta);
totallen += len;
/*
* Bail out if total variable-length data exceeds what will fit in a
* JEntry length field. We check this in each iteration, not just
* once at the end, to forestall possible integer overflow.
*/
if (totallen > JENTRY_OFFLENMASK)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("total size of jsonb array elements exceeds the maximum of %d bytes",
JENTRY_OFFLENMASK)));
/*
* Convert each JB_OFFSET_STRIDE'th length to an offset.
*/
if ((i % JB_OFFSET_STRIDE) == 0)
meta = (meta & JENTRY_TYPEMASK) | totallen | JENTRY_HAS_OFF;
copyToBuffer(buffer, jentry_offset, (char *) &meta, sizeof(JEntry));
jentry_offset += sizeof(JEntry);
}
/* Total data size is everything we've appended to buffer */
totallen = buffer->len - base_offset;
/* Check length again, since we didn't include the metadata above */
if (totallen > JENTRY_OFFLENMASK)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("total size of jsonb array elements exceeds the maximum of %d bytes",
JENTRY_OFFLENMASK)));
/* Initialize the header of this node in the container's JEntry array */
*header = JENTRY_ISCONTAINER | totallen;
}
static void
convertJsonbObject(StringInfo buffer, JEntry *header, JsonbValue *val, int level)
{
int base_offset;
int jentry_offset;
int i;
int totallen;
uint32 containerheader;
int nPairs = val->val.object.nPairs;
/* Remember where in the buffer this object starts. */
base_offset = buffer->len;
/* Align to 4-byte boundary (any padding counts as part of my data) */
padBufferToInt(buffer);
/*
* Construct the header Jentry and store it in the beginning of the
* variable-length payload.
*/
containerheader = nPairs | JB_FOBJECT;
appendToBuffer(buffer, (char *) &containerheader, sizeof(uint32));
/* Reserve space for the JEntries of the keys and values. */
jentry_offset = reserveFromBuffer(buffer, sizeof(JEntry) * nPairs * 2);
/*
* Iterate over the keys, then over the values, since that is the ordering
* we want in the on-disk representation.
*/
totallen = 0;
for (i = 0; i < nPairs; i++)
{
JsonbPair *pair = &val->val.object.pairs[i];
int len;
JEntry meta;
/*
* Convert key, producing a JEntry and appending its variable-length
* data to buffer
*/
convertJsonbScalar(buffer, &meta, &pair->key);
len = JBE_OFFLENFLD(meta);
totallen += len;
/*
* Bail out if total variable-length data exceeds what will fit in a
* JEntry length field. We check this in each iteration, not just
* once at the end, to forestall possible integer overflow.
*/
if (totallen > JENTRY_OFFLENMASK)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("total size of jsonb object elements exceeds the maximum of %d bytes",
JENTRY_OFFLENMASK)));
/*
* Convert each JB_OFFSET_STRIDE'th length to an offset.
*/
if ((i % JB_OFFSET_STRIDE) == 0)
meta = (meta & JENTRY_TYPEMASK) | totallen | JENTRY_HAS_OFF;
copyToBuffer(buffer, jentry_offset, (char *) &meta, sizeof(JEntry));
jentry_offset += sizeof(JEntry);
}
for (i = 0; i < nPairs; i++)
{
JsonbPair *pair = &val->val.object.pairs[i];
int len;
JEntry meta;
/*
* Convert value, producing a JEntry and appending its variable-length
* data to buffer
*/
convertJsonbValue(buffer, &meta, &pair->value, level + 1);
len = JBE_OFFLENFLD(meta);
totallen += len;
/*
* Bail out if total variable-length data exceeds what will fit in a
* JEntry length field. We check this in each iteration, not just
* once at the end, to forestall possible integer overflow.
*/
if (totallen > JENTRY_OFFLENMASK)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("total size of jsonb object elements exceeds the maximum of %d bytes",
JENTRY_OFFLENMASK)));
/*
* Convert each JB_OFFSET_STRIDE'th length to an offset.
*/
if (((i + nPairs) % JB_OFFSET_STRIDE) == 0)
meta = (meta & JENTRY_TYPEMASK) | totallen | JENTRY_HAS_OFF;
copyToBuffer(buffer, jentry_offset, (char *) &meta, sizeof(JEntry));
jentry_offset += sizeof(JEntry);
}
/* Total data size is everything we've appended to buffer */
totallen = buffer->len - base_offset;
/* Check length again, since we didn't include the metadata above */
if (totallen > JENTRY_OFFLENMASK)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("total size of jsonb object elements exceeds the maximum of %d bytes",
JENTRY_OFFLENMASK)));
/* Initialize the header of this node in the container's JEntry array */
*header = JENTRY_ISCONTAINER | totallen;
}
static void
convertJsonbScalar(StringInfo buffer, JEntry *header, JsonbValue *scalarVal)
{
int numlen;
short padlen;
switch (scalarVal->type)
{
case jbvNull:
*header = JENTRY_ISNULL;
break;
case jbvString:
appendToBuffer(buffer, scalarVal->val.string.val, scalarVal->val.string.len);
*header = scalarVal->val.string.len;
break;
case jbvNumeric:
numlen = VARSIZE_ANY(scalarVal->val.numeric);
padlen = padBufferToInt(buffer);
appendToBuffer(buffer, (char *) scalarVal->val.numeric, numlen);
*header = JENTRY_ISNUMERIC | (padlen + numlen);
break;
case jbvBool:
*header = (scalarVal->val.boolean) ?
JENTRY_ISBOOL_TRUE : JENTRY_ISBOOL_FALSE;
break;
case jbvDatetime:
{
char buf[MAXDATELEN + 1];
size_t len;
JsonEncodeDateTime(buf,
scalarVal->val.datetime.value,
scalarVal->val.datetime.typid,
&scalarVal->val.datetime.tz);
len = strlen(buf);
appendToBuffer(buffer, buf, len);
*header = len;
}
break;
default:
elog(ERROR, "invalid jsonb scalar type");
}
}
/*
* Compare two jbvString JsonbValue values, a and b.
*
* This is a special qsort() comparator used to sort strings in certain
* internal contexts where it is sufficient to have a well-defined sort order.
* In particular, object pair keys are sorted according to this criteria to
* facilitate cheap binary searches where we don't care about lexical sort
* order.
*
* a and b are first sorted based on their length. If a tie-breaker is
* required, only then do we consider string binary equality.
*/
static int
lengthCompareJsonbStringValue(const void *a, const void *b)
{
const JsonbValue *va = (const JsonbValue *) a;
const JsonbValue *vb = (const JsonbValue *) b;
Assert(va->type == jbvString);
Assert(vb->type == jbvString);
return lengthCompareJsonbString(va->val.string.val, va->val.string.len,
vb->val.string.val, vb->val.string.len);
}
/*
* Subroutine for lengthCompareJsonbStringValue
*
* This is also useful separately to implement binary search on
* JsonbContainers.
*/
static int
lengthCompareJsonbString(const char *val1, int len1, const char *val2, int len2)
{
if (len1 == len2)
return memcmp(val1, val2, len1);
else
return len1 > len2 ? 1 : -1;
}
/*
* qsort_arg() comparator to compare JsonbPair values.
*
* Third argument 'binequal' may point to a bool. If it's set, *binequal is set
* to true iff a and b have full binary equality, since some callers have an
* interest in whether the two values are equal or merely equivalent.
*
* N.B: String comparisons here are "length-wise"
*
* Pairs with equals keys are ordered such that the order field is respected.
*/
static int
lengthCompareJsonbPair(const void *a, const void *b, void *binequal)
{
const JsonbPair *pa = (const JsonbPair *) a;
const JsonbPair *pb = (const JsonbPair *) b;
int res;
res = lengthCompareJsonbStringValue(&pa->key, &pb->key);
if (res == 0 && binequal)
*((bool *) binequal) = true;
/*
* Guarantee keeping order of equal pair. Unique algorithm will prefer
* first element as value.
*/
if (res == 0)
res = (pa->order > pb->order) ? -1 : 1;
return res;
}
/*
* Sort and unique-ify pairs in JsonbValue object
*/
static void
uniqueifyJsonbObject(JsonbValue *object, bool unique_keys, bool skip_nulls)
{
bool hasNonUniq = false;
Assert(object->type == jbvObject);
if (object->val.object.nPairs > 1)
qsort_arg(object->val.object.pairs, object->val.object.nPairs, sizeof(JsonbPair),
lengthCompareJsonbPair, &hasNonUniq);
if (hasNonUniq && unique_keys)
ereport(ERROR,
errcode(ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE),
errmsg("duplicate JSON object key value"));
if (hasNonUniq || skip_nulls)
{
JsonbPair *ptr,
*res;
while (skip_nulls && object->val.object.nPairs > 0 &&
object->val.object.pairs->value.type == jbvNull)
{
/* If skip_nulls is true, remove leading items with null */
object->val.object.pairs++;
object->val.object.nPairs--;
}
if (object->val.object.nPairs > 0)
{
ptr = object->val.object.pairs + 1;
res = object->val.object.pairs;
while (ptr - object->val.object.pairs < object->val.object.nPairs)
{
/* Avoid copying over duplicate or null */
if (lengthCompareJsonbStringValue(ptr, res) != 0 &&
(!skip_nulls || ptr->value.type != jbvNull))
{
res++;
if (ptr != res)
memcpy(res, ptr, sizeof(JsonbPair));
}
ptr++;
}
object->val.object.nPairs = res + 1 - object->val.object.pairs;
}
}
}
| 2.265625 | 2 |
2024-11-18T20:50:53.439882+00:00 | 2023-08-08T09:39:15 | a32fec1cf078aff53870778071435fc38228486c | {
"blob_id": "a32fec1cf078aff53870778071435fc38228486c",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-08T09:39:15",
"content_id": "b6fcdf4cb805a74c1bd315fafccd10864dadd5d1",
"detected_licenses": [
"ISC"
],
"directory_id": "f8cc1dd4b1378490386def2e0571561fab10b275",
"extension": "c",
"filename": "byte_in.c",
"fork_events_count": 32,
"gha_created_at": "2015-02-28T12:01:41",
"gha_event_created_at": "2021-04-11T10:10:54",
"gha_language": "C",
"gha_license_id": "ISC",
"github_id": 31461366,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 253,
"license": "ISC",
"license_type": "permissive",
"path": "/src/libstddjb/byte_in.c",
"provenance": "stackv2-0110.json.gz:227600",
"repo_name": "skarnet/skalibs",
"revision_date": "2023-08-08T09:39:15",
"revision_id": "1f2d5f95684e93f8523e369ef1fed7a75c444082",
"snapshot_id": "b1eb2a0e38663cbfa918ee0a7916f56227bd7c2d",
"src_encoding": "UTF-8",
"star_events_count": 104,
"url": "https://raw.githubusercontent.com/skarnet/skalibs/1f2d5f95684e93f8523e369ef1fed7a75c444082/src/libstddjb/byte_in.c",
"visit_date": "2023-08-23T07:33:20.996016"
} | stackv2 | /* ISC license. */
#include <string.h>
#include <skalibs/bytestr.h>
size_t byte_in (char const *s, size_t n, char const *sep, size_t len)
{
char const *t = s ;
while (n--)
{
if (memchr(sep, *t, len)) break ;
++t ;
}
return t - s ;
}
| 2.484375 | 2 |
2024-11-18T20:50:53.581346+00:00 | 2021-10-08T08:55:59 | a70cc7121032cec93f35cfc18d5bb74f2a5f6816 | {
"blob_id": "a70cc7121032cec93f35cfc18d5bb74f2a5f6816",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-08T08:55:59",
"content_id": "302caea3b94fd8d02b1313e33ea35f0ea3f4925c",
"detected_licenses": [
"MIT"
],
"directory_id": "1042727d90b03c9a1040264f28d75b4b8102969d",
"extension": "c",
"filename": "ft_recursive_power.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 414789071,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 245,
"license": "MIT",
"license_type": "permissive",
"path": "/c05/ex03/ft_recursive_power.c",
"provenance": "stackv2-0110.json.gz:227856",
"repo_name": "mmasstou/1337piscine",
"revision_date": "2021-10-08T08:55:59",
"revision_id": "264f165648d97a5adf8a27ede8a8fdcd3cc4cbbe",
"snapshot_id": "64ecfdb89036f306e4d018f29b0149c8c60c8070",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/mmasstou/1337piscine/264f165648d97a5adf8a27ede8a8fdcd3cc4cbbe/c05/ex03/ft_recursive_power.c",
"visit_date": "2023-08-22T08:04:21.236342"
} | stackv2 | int ft_recursive_power(int nb, int power)
{
if (power < 0)
return(0);
else if (power == 0)
return (1);
else
return (nb *= ft_recursive_power(nb,power - 1));
}
#include <stdio.h>
int main(void)
{
printf("%d",ft_recursive_power(5,10));
} | 2.71875 | 3 |
2024-11-18T20:50:53.869708+00:00 | 2023-02-08T15:47:58 | cdb5aedaeb74be4a7593cd0904e2c806d58e134a | {
"blob_id": "cdb5aedaeb74be4a7593cd0904e2c806d58e134a",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-08T15:47:58",
"content_id": "db1f3a272d51af284ef592c480fac984dfa5235f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4ac22a0c3d2bd467947d53efc31bf165f5b7f292",
"extension": "c",
"filename": "gen_emoji_property.c",
"fork_events_count": 0,
"gha_created_at": "2020-02-13T12:58:45",
"gha_event_created_at": "2020-02-13T12:58:46",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 240260955,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5269,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/gen_emoji_property.c",
"provenance": "stackv2-0110.json.gz:228115",
"repo_name": "rauhma/fsdyn",
"revision_date": "2023-02-08T15:47:58",
"revision_id": "008fcf8ef9eeed30da1f28fb9353b202c6bf4a29",
"snapshot_id": "9c1b6cbe24e2c5800a13e25d50ac3c7de1aa6144",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rauhma/fsdyn/008fcf8ef9eeed30da1f28fb9353b202c6bf4a29/src/gen_emoji_property.c",
"visit_date": "2023-02-22T00:21:07.406442"
} | stackv2 | #if _POSIX_C_SOURCE < 200809L
#define _GNU_SOURCE
#endif
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "charstr.h"
#include "intset.h"
enum {
N_CP = 0x110000,
};
static intset_t *cat_emoji;
static intset_t *cat_emoji_presentation;
static intset_t *cat_emoji_modifier;
static intset_t *cat_emoji_modifier_base;
static intset_t *cat_emoji_component;
static intset_t *cat_extended_pictographic;
static void make_categories()
{
cat_emoji = make_intset(N_CP);
cat_emoji_presentation = make_intset(N_CP);
cat_emoji_modifier = make_intset(N_CP);
cat_emoji_modifier_base = make_intset(N_CP);
cat_emoji_component = make_intset(N_CP);
cat_extended_pictographic = make_intset(N_CP);
}
static void destroy_categories()
{
destroy_intset(cat_emoji);
destroy_intset(cat_emoji_presentation);
destroy_intset(cat_emoji_modifier);
destroy_intset(cat_emoji_modifier_base);
destroy_intset(cat_emoji_component);
destroy_intset(cat_extended_pictographic);
}
static void add_to_category(int start, int finish, const char *category)
{
intset_t *set;
if (!strcmp(category, "Emoji"))
set = cat_emoji;
else if (!strcmp(category, "Emoji_Presentation"))
set = cat_emoji_presentation;
else if (!strcmp(category, "Emoji_Modifier"))
set = cat_emoji_modifier;
else if (!strcmp(category, "Emoji_Modifier_Base"))
set = cat_emoji_modifier_base;
else if (!strcmp(category, "Emoji_Component"))
set = cat_emoji_component;
else if (!strcmp(category, "Extended_Pictographic"))
set = cat_extended_pictographic;
else
assert(false);
for (int cp = start; cp <= finish; cp++)
intset_add(set, cp);
}
static void generate_category(intset_t *set, const char *cat)
{
printf("\n"
"bool charset_unicode_emoji_prop_is_%s(int cp)\n"
"{\n"
" switch (cp) {\n",
cat);
/* Condense long, sequential ranges */
enum { CUT = 20 };
int largest = -1;
bool case_found = false;
for (int cp = 0; cp < N_CP; cp++)
if (intset_has(set, cp)) {
int begin = cp;
for (cp++; cp < N_CP && intset_has(set, cp); cp++)
;
int end = cp--;
largest = cp;
if (end - begin < CUT)
for (int n = begin; n < end; n++) {
case_found = true;
printf(" case %d:\n", n);
}
}
if (case_found)
printf(" return true;\n");
printf(" default:\n"
" if (cp > %d)\n"
" return false;\n",
largest);
for (int cp = 0; cp < N_CP; cp++)
if (intset_has(set, cp)) {
int begin = cp;
for (cp++; cp < N_CP && intset_has(set, cp); cp++)
;
int end = cp--;
if (end - begin >= CUT)
printf(" if (cp < %d)\n"
" return false;\n"
" if (cp < %d)\n"
" return true;\n",
begin, end);
}
printf(" return false;\n"
" }\n"
"}\n");
}
static void generate_categories()
{
printf("#include <stdbool.h>\n");
generate_category(cat_emoji, "emoji");
generate_category(cat_emoji_presentation, "emoji_presentation");
generate_category(cat_emoji_modifier, "emoji_modifier");
generate_category(cat_emoji_modifier_base, "emoji_modifier_base");
generate_category(cat_emoji_component, "emoji_component");
generate_category(cat_extended_pictographic, "extended_pictographic");
}
int main(int argc, const char *const *argv)
{
make_categories();
FILE *f = fopen(argv[1], "r");
char *line = NULL;
size_t length = 0;
while (getline(&line, &length, f) > 0) {
list_t *parts = charstr_split(line, '#', 1);
const char *body = list_elem_get_value(list_get_first(parts));
list_t *fields = charstr_split(body, ';', -1);
char *cp_range = (char *) list_pop_first(fields);
assert(cp_range);
char *value = (char *) list_pop_first(fields);
if (value) {
list_t *range = charstr_split_str(cp_range, "..", -1);
char *first = (char *) list_pop_first(range);
char *last = (char *) list_pop_first(range);
if (!last)
last = charstr_dupstr(first);
int start = strtol(first, NULL, 16);
int finish = strtol(last, NULL, 16);
char *category = charstr_strip(value);
add_to_category(start, finish, category);
fsfree(category);
fsfree(first);
fsfree(last);
list_foreach(range, (void *) fsfree, NULL);
destroy_list(range);
fsfree(value);
}
fsfree(cp_range);
list_foreach(fields, (void *) fsfree, NULL);
destroy_list(fields);
list_foreach(parts, (void *) fsfree, NULL);
destroy_list(parts);
}
free(line);
generate_categories();
destroy_categories();
return EXIT_SUCCESS;
}
| 2.890625 | 3 |
2024-11-18T20:50:54.174174+00:00 | 2020-02-15T13:34:10 | ecdf6ff6fafbe1a41acea362eefe71b40c70afae | {
"blob_id": "ecdf6ff6fafbe1a41acea362eefe71b40c70afae",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-15T13:34:10",
"content_id": "fbbec504dc1502216237aa8acc2eeab7d34f48a4",
"detected_licenses": [
"MIT"
],
"directory_id": "4755e089c3e5a7ddf1ea9058adf0e07db56371d1",
"extension": "c",
"filename": "parse_main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 193251893,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1885,
"license": "MIT",
"license_type": "permissive",
"path": "/src/obj_parser/parse_main.c",
"provenance": "stackv2-0110.json.gz:228243",
"repo_name": "mdovhopo/Scop_42",
"revision_date": "2020-02-15T13:34:10",
"revision_id": "8d0c82d2ca4249b28f8bfe900d142c8b7c8ff353",
"snapshot_id": "cdc532860339baf7d6289c25084b628ffdcaedf2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mdovhopo/Scop_42/8d0c82d2ca4249b28f8bfe900d142c8b7c8ff353/src/obj_parser/parse_main.c",
"visit_date": "2020-06-08T15:29:57.801048"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parse_main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mdovhopo <mdovhopo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/03 12:07:04 by tryckylake #+# #+# */
/* Updated: 2019/09/08 16:55:35 by mdovhopo ### ########.fr */
/* */
/* ************************************************************************** */
#include "scop.h"
const char *g_first_tokens[] = {
"v",
"vn",
"f",
"mtllib",
"usemtl",
"o",
"s",
NULL
};
void (*g_line_parsers[])(char **tokens, t_obj *obj, uint32_t line_count) = {
&parse_vertex,
&parse_vertex_normal,
&parse_index,
&parse_mtllib,
&parse_usemtl,
&parse_object,
&parse_smooth
};
void parse_obj_file(const char *path, t_obj *obj)
{
char *line;
static uint32_t line_count = 1;
t_first_token token_id;
char **tokens;
char *trimmed_line;
line = NULL;
while (ft_read_next_line(path, &line) > 0)
{
trimmed_line = ft_strtrim(line);
free(line);
if (*trimmed_line == '#' || *trimmed_line == 0 || *trimmed_line == '\n')
{
free(trimmed_line);
line_count++;
continue;
}
tokens = ft_strsplit(trimmed_line, ' ');
token_id = find_str_in_array((char**)g_first_tokens, tokens[0]);
if (token_id != UNKNOWN_TOKEN)
g_line_parsers[token_id](tokens + 1, obj, line_count);
line_count++;
free_2d_arr(tokens);
free(trimmed_line);
}
}
| 2.234375 | 2 |
2024-11-18T20:50:57.232486+00:00 | 2015-10-19T04:24:32 | 1f97373c9cf00fa5b11747bddd5a0e392ec7d2be | {
"blob_id": "1f97373c9cf00fa5b11747bddd5a0e392ec7d2be",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-19T04:24:32",
"content_id": "a56178d0751539b6fdf4e2a5d3177b216a5bf17c",
"detected_licenses": [
"MIT"
],
"directory_id": "d23a7aec9ee7dfe9ac507c09de88f150f7a7ad59",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44510594,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3038,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0110.json.gz:228503",
"repo_name": "Achoulos/Tower-Of-Hanoi",
"revision_date": "2015-10-19T04:24:32",
"revision_id": "80cdaa1ad3c20534308aa3ca4ac7424616dbea5a",
"snapshot_id": "c8559b3ca1b371dfb6ce0528fd6b34b19d7d31e8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Achoulos/Tower-Of-Hanoi/80cdaa1ad3c20534308aa3ca4ac7424616dbea5a/main.c",
"visit_date": "2021-01-13T00:43:15.205298"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define TOTAL_RINGS 3
typedef struct
{
int* stack;
int* top;
} STACK;
int pop(int stack, STACK* stacks[])
{
int data = *(stacks[stack]->top);
*(stacks[stack]->top) = 0;
if (&(stacks[stack]->stack[0]) == stacks[stack]->top) {
return data;
}
stacks[stack]->top--;
return data;
}
void push(int data, int stack, STACK* stacks[])
{
if (&(stacks[stack]->stack[0]) == stacks[stack]->top && stacks[stack]->stack[0] == 0) {
*(stacks[stack]->top) = data;
return;
}
else
{
stacks[stack]->top++;
*(stacks[stack]->top) = data;
}
}
void printBoard(STACK* stacks[])
{
int d;
int a;
for(d = TOTAL_RINGS-1; d >= 0; d--)
{
for(a = 0; a < 3; a++)
{
printf("%d\t", stacks[a]->stack[d]);
}
printf("\n");
}
}
void initialize(STACK* stacks[])
{
int i;
int j;
for(j = 0; j < 3; j++)
{
stacks[j] = malloc(sizeof(STACK));
stacks[j]->stack = malloc(sizeof(int)*TOTAL_RINGS);
stacks[j]->top = malloc(sizeof(int));
for(i = 0; i < TOTAL_RINGS; i++)
stacks[j]->stack[i] = 0;
}
for(i = 1; i <= TOTAL_RINGS; i++)
stacks[0]->stack[TOTAL_RINGS-i] = i;
}
bool won(int stick[])
{
int i;
for(i = 0; i < TOTAL_RINGS; i++)
{
if(stick[i] != TOTAL_RINGS-i)
return false;
}
return true;
}
bool valid(int input, int source)
{
return ( (1 <= input) && (input <= 3) && input != source);
}
int main(void) {
int userInput;
int source;
STACK* stacks[3];
initialize(stacks);
stacks[0]->top = &stacks[0]->stack[TOTAL_RINGS-1];
stacks[1]->top = &stacks[1]->stack[0];
stacks[2]->top = &stacks[2]->stack[0];
printf("Welcome to Towers of Hanoi!\n");
while(1)
{
printf("Please select a starting stick.\n");
scanf("%d", &userInput );
source = userInput;
if(!valid(userInput, -1))
{
printf("Invalid stick, try again please!\n");
continue;
}
printf("Now please select a destination stick.\n");
scanf("%d", &userInput);
if(!valid(userInput, source))
{
printf("Invalid stick, try again please!\n");
continue;
}
if (*(stacks[source-1]->top) > *(stacks[userInput-1]->top) && *(stacks[userInput-1]->top) != 0) {
printf("You can't move a big ring over a small ring!\n");
}
else if (*(stacks[source-1]->top) != 0)
push(pop(source-1, stacks), userInput-1, stacks);
if(won(stacks[2]->stack))
{
printf("Woo, you won!\n");
printBoard(stacks);
return 1;
}
printBoard(stacks);
}
return 0;
}
| 3.140625 | 3 |
2024-11-18T20:50:57.394853+00:00 | 2017-11-30T08:25:50 | b6ce35632e758e8e3a220287c118a161a5fe6d12 | {
"blob_id": "b6ce35632e758e8e3a220287c118a161a5fe6d12",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-30T08:25:50",
"content_id": "67c9990d4a6445ed38ca4da06728fc225c3bcd34",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9842e47efd954b220346933a9c8d510d77952349",
"extension": "c",
"filename": "pthread_example.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 111594705,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1479,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/pthread_example.c",
"provenance": "stackv2-0110.json.gz:228633",
"repo_name": "ggupta2005/Operating-Systems-Examples",
"revision_date": "2017-11-30T08:25:50",
"revision_id": "c246c874737256ef3bc7af7436d52b956e354fd8",
"snapshot_id": "5d5b301f5c8aa7b5d0e9e3eeaf23680ab479ea69",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ggupta2005/Operating-Systems-Examples/c246c874737256ef3bc7af7436d52b956e354fd8/pthread_example.c",
"visit_date": "2021-08-22T13:17:15.994595"
} | stackv2 | /*
* This is a sample C-program using linux POSIX threads and usage of
* mutexes over global variables.
*/
#include<pthread.h>
#include<stdio.h>
/*
* Maximum number of threads
*/
#define MAX_THREADS 5
int count = 0; // Global variable across threads
pthread_mutex_t count_mutex; // Mutex to guard the global variable
pthread_rwlock_t count_lock; // Read-write lock to guard the global
// variable
/*
* Thread function
*/
void *inc_count(void *t)
{
/* Lock the mutex */
pthread_mutex_lock(&count_mutex);
/* Take the read-write lock */
//pthread_rwlock_wrlock(&count_lock);
/* Increment the global count */
++count;
printf("The value of count is %d\n", count);
/* Release the read-write lock */
//pthread_rwlock_unlock(&count_lock);
/* Un-lock the mutex */
pthread_mutex_unlock(&count_mutex);
}
int main ()
{
int index;
pthread_t threads[MAX_THREADS];
/* Initialize the mutex */
pthread_mutex_init(&count_mutex, NULL);
/* Initialize the read-write lock */
//pthread_rwlock_init(&count_lock, NULL);
/* Create POSIX threads with a thread function */
for (index = 0; index < MAX_THREADS; ++index) {
pthread_create(&threads[index], NULL, inc_count, NULL);
}
/* Wait for the POSIX threads to finish thread function */
for (index = 0; index < MAX_THREADS; ++index) {
pthread_join(threads[index], NULL);
}
return(0);
}
| 3.90625 | 4 |
2024-11-18T20:50:57.542572+00:00 | 2023-01-07T00:09:11 | 064ce6a4d3d2b76d261c1625bb364be6ec7c1284 | {
"blob_id": "064ce6a4d3d2b76d261c1625bb364be6ec7c1284",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-07T00:09:11",
"content_id": "927d97bf735a9ebd947259f5ed9098cb52fc6caa",
"detected_licenses": [
"MIT"
],
"directory_id": "1a16506ec1f8c0756ac727a7fe02b78031974188",
"extension": "c",
"filename": "test2.c",
"fork_events_count": 2,
"gha_created_at": "2020-04-08T23:57:39",
"gha_event_created_at": "2020-04-14T21:37:38",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 254227537,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 379,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/doctest/test2.c",
"provenance": "stackv2-0110.json.gz:228763",
"repo_name": "intel/fffc",
"revision_date": "2023-01-07T00:09:11",
"revision_id": "eb6cb9554c4aad7a90b456314eb99353b7315e38",
"snapshot_id": "7d954aa3b0996254bb7bea1663111f4d44cdb6d7",
"src_encoding": "UTF-8",
"star_events_count": 22,
"url": "https://raw.githubusercontent.com/intel/fffc/eb6cb9554c4aad7a90b456314eb99353b7315e38/tests/doctest/test2.c",
"visit_date": "2023-05-27T15:28:02.157061"
} | stackv2 | // test2.c
// Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: MIT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int f(char *x, char *unused) {
if (*x != 'X') {
exit(-1);
}
printf("%s\n", x);
return 0;
}
int main(void) {
char *arg = strdup("hello!");
char *arg2 = strdup("supercalifragilisticexpialidocious(sp)");
return f(arg, arg2);
}
| 2.65625 | 3 |
2024-11-18T20:50:58.077748+00:00 | 2018-04-05T22:01:51 | a5b13ef2392d482694a9fe0d54f25616c8e80584 | {
"blob_id": "a5b13ef2392d482694a9fe0d54f25616c8e80584",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-05T22:01:51",
"content_id": "9b3a1664c44983da0d2d44de0a2215a1f202a239",
"detected_licenses": [
"MIT"
],
"directory_id": "82cc9b432925f64d4df63b71aba42d76ba8deac5",
"extension": "c",
"filename": "str_mem.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4451,
"license": "MIT",
"license_type": "permissive",
"path": "/meeting1/str_mem/str_mem.c",
"provenance": "stackv2-0110.json.gz:229412",
"repo_name": "CheeseL0ver/intro2c",
"revision_date": "2018-04-05T22:01:51",
"revision_id": "debd36a17aa483803d41081912d75cfe32234740",
"snapshot_id": "5f689ecb8d472fe0815035e97dc4b4435529c117",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CheeseL0ver/intro2c/debd36a17aa483803d41081912d75cfe32234740/meeting1/str_mem/str_mem.c",
"visit_date": "2021-09-11T01:42:34.026664"
} | stackv2 | #include <stdio.h>
#include <string.h>
// So... we've talked about all of the types, but we haven't see Strings yet. What's up with that?
// In C, there is no string type. None whatsoever. A string is a null-terminated character array.
// This means that a string is a bunch of chars that ends with a char containing the value `0`.
// The compiler does allow us to declare strings in a human-readable way though:
void str_demo() {
char *s = "this is a string in C";
char s2[] = "note that we can also declare it like an array";
// C automatically inserts a null character at the end of these strings.
// to iterate over all characters in the string:
for (char *c = s; *c != 0; c++) {
printf("%c\n", *c);
}
// note that we don't have to count iterations, since we can just go until we hit a character
// with the integer value 0 (the null character).
// since strings are just character arrays (pointers), concatenation with the + operator makes
// no sense whatsoever (s + s2) is the sum of the addresses of those strings.
// instead, we manipulate strings through helper functions defined in string.h and strings.h
// to see a list of these helpers, type `man 3 string`
// to properly concatenate C strings, we can do this:
char big[128];
strcpy(big, s); // copy s into big
strcat(big, s2); // concatenate s2 to the end of our new copy of s
// big now contains s concatenated with s2.
// NOTE: we CANNOT return big to another function. The storage space for the big array is
// part of the current function's stack, and it will be overwritten by subsequent function
// calls once it returns.
// In this case, how can we possibly return strings (and other arrays) from a function?
// We need to learn a bit about how C memory is managed.
}
// we need stdlib.h for the malloc and free functions
#include <stdlib.h>
char * mem_demo() {
// In C, we can allocate memory in two places:
// the stack - the default
// the heap - using special functions
// memory allocated on the stack is safe **until** we return, but not after.
// memory allocated on the heap is safe to use **until** we manually say otherwise.
// So how do we allocate magic heap memory?
char * new_space = (char *) malloc(128 * sizeof(char));
// Okay, what the heck did we just do? Let's break it down:
// - malloc is a function that allocated a quantity of *bytes* on the heap and
// returns a pointer to the start of those bytes.
// - We asked for 128 * sizeof(char) bytes, which is enough space for 128 chars.
// - malloc will ask the operating system for 128 bytes of memory and then return
// the address of the start of that memory to us.
// - So why do we have to cast it? The return type of malloc is **weird**. It is
// (void *), a pointer without a type. This is because malloc doesn't know or
// care what you want to use the memory for. You ask for X number of bytes, and
// it gives them to you. So it is good practice to cast the return value of
// malloc to the pointer type that you actually want.
// Well cool, we have some space on the heap! We can return that and then never worry about it
// again, right?
// ...
// C doesn't have a garbage collector. That means that memory, once allocated to something,
// stays allocated until the programmer says otherwise.
// Our newly allocated 128 bytes will belong to our program forever if we don't get rid
// of them when we're finished with them.
return new_space;
}
void destroy_str(char *victim) {
// So how do we give the memory back to the operating system? There's another function
// that does that. It's called "free".
free(victim);
// Bam, all of the memory in victim has been returned to the OS and to other programs
// running on the system.
// Unless, of course, the char* that was passed in wasn't allocated with malloc. If it was
// a pointer to a char on the stack, undefined behavior occurs. If free was already called
// on that pointer, undefined behavior occurs.
// The moral of the story? Be careful to free memory that you allocate, but be EXTRA careful
// not to free memory twice or to free memory that you didn't allocate on the heap.
}
// Okay, time for a string manipulation challenge! See chal6.c
| 3.390625 | 3 |
2024-11-18T20:50:58.671913+00:00 | 2015-03-02T19:15:15 | bd3fd8b0bd7776d17cea7ff873ab78bfd5325a42 | {
"blob_id": "bd3fd8b0bd7776d17cea7ff873ab78bfd5325a42",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-02T19:15:15",
"content_id": "ea9c2eb40838cd3fc172b28b91e15ce7e9dd1e61",
"detected_licenses": [
"MIT"
],
"directory_id": "3d2ad1c40c7c2c0adfa9dd3b6cccf117fe44ab50",
"extension": "c",
"filename": "driver.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 31557813,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 975,
"license": "MIT",
"license_type": "permissive",
"path": "/AdjoinableMPIexamples/SendRecvPatterns/IsendIrecvWaitallNeighborsInRing/driver.c",
"provenance": "stackv2-0110.json.gz:229802",
"repo_name": "zsdfewm/RevMPI",
"revision_date": "2015-03-02T19:15:15",
"revision_id": "8bc7b4bb24b6743fc23619e9ce525fbc37d110bd",
"snapshot_id": "45d2ee4e63c04b6e7f430f114a9770db5f0fb3f9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zsdfewm/RevMPI/8bc7b4bb24b6743fc23619e9ce525fbc37d110bd/AdjoinableMPIexamples/SendRecvPatterns/IsendIrecvWaitallNeighborsInRing/driver.c",
"visit_date": "2018-12-28T01:37:54.829999"
} | stackv2 | #include <stdio.h>
#include <mpi.h>
int main(int argc, char** argv) {
MPI_Init(0,0);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int world_rank,left_rank,right_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
left_rank=(world_rank-1+world_size)%world_size;
right_rank=(world_rank+1)%world_size;
double sBuf,rBuf[2];
MPI_Request r[4];
sBuf = 3.0*world_rank;
MPI_Isend(&sBuf , 1, MPI_DOUBLE, left_rank, 0, MPI_COMM_WORLD, &r[0]);
MPI_Isend(&sBuf , 1, MPI_DOUBLE, right_rank, 0, MPI_COMM_WORLD, &r[1]);
MPI_Irecv(&rBuf[0], 1, MPI_DOUBLE, left_rank, 0, MPI_COMM_WORLD, &r[2]);
MPI_Irecv(&rBuf[1], 1, MPI_DOUBLE, right_rank, 0, MPI_COMM_WORLD, &r[3]);
MPI_Waitall(4,r,MPI_STATUS_IGNORE);
printf(__FILE__ ": process %d received number %f from process %d\n", world_rank,rBuf[0],left_rank);
printf(__FILE__ ": process %d received number %f from process %d\n", world_rank,rBuf[1],right_rank);
MPI_Finalize();
return 0;
}
| 2.421875 | 2 |
2024-11-18T20:50:58.896085+00:00 | 2021-07-01T18:27:03 | 6e6d2a4d18b2c38930ce0865af3a799b5050eb0b | {
"blob_id": "6e6d2a4d18b2c38930ce0865af3a799b5050eb0b",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-01T18:27:03",
"content_id": "6e4cc837019ab033c909497cfffbd91d13592678",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "5b09f0ef666d00f4dac8c057bba3492a42622f6e",
"extension": "c",
"filename": "as-sorion.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 380531484,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2120,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/as-sorion.c",
"provenance": "stackv2-0110.json.gz:229931",
"repo_name": "Adsorion-Collection/As-Sorion",
"revision_date": "2021-07-01T18:27:03",
"revision_id": "9f9f3ff2794ad7beb84d1d75edab92ebaa4423fc",
"snapshot_id": "aa6735e3d40ab3f42f296ca92ca86e66fe40433f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Adsorion-Collection/As-Sorion/9f9f3ff2794ad7beb84d1d75edab92ebaa4423fc/src/as-sorion.c",
"visit_date": "2023-06-08T02:39:08.165623"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <parser.h>
#include <as-arch/instruction.h>
#include <as-sorion.h>
#include <string.h>
uint32_t line_count_without_defs = 0;
assembler_info_t assemble(char* file_name){
FILE* file = fopen(file_name, "r");
uint64_t line_count = 0;
uint64_t file_length = 0;
char c = fgetc(file);
while(c != EOF){
file_length++;
if(c == '\n'){
line_count++;
}
c = fgetc(file);
}
fclose(file);
line_count++;
char* file_buffer = (char*)malloc(file_length * sizeof(char) + 1);
char** file_line_buffer = (char**)malloc(line_count * sizeof(char*));
file = fopen(file_name, "r");
c = fgetc(file);
for(uint64_t i = 0; i < file_length; c = fgetc(file), i++){
file_buffer[i] = c;
}
file_buffer[file_length] = '\0';
uint64_t line_number = 0;
uint64_t line_index = 0;
for(uint64_t i = 0; i <= file_length; i++){
if(file_buffer[i] == '\0' || file_buffer[i] == '\n'){
char* line = (char*)malloc(line_index * sizeof(char) + 1);
memcpy(line, file_buffer + i - line_index, line_index);
line[line_index] = '\0';
file_line_buffer[line_number] = line;
line_index = 0;
line_number++;
}else{
line_index++;
}
}
fclose(file);
for(uint64_t i = 0; i < line_count; i++){
preprocess_line(file_line_buffer[i], i);
}
uint16_t* bytecode_buffer = (uint16_t*)calloc(line_count_without_defs, sizeof(uint16_t));
uint64_t bytecode_buffer_index = 0;
for(uint64_t i = 0; i < line_count; i++){
uint16_t* line_bytecode = parse_line(file_line_buffer[i], i);
if(line_bytecode){
memcpy((void*)bytecode_buffer + bytecode_buffer_index * 6, line_bytecode, 6);
bytecode_buffer_index++;
free(line_bytecode);
}
}
free(file_buffer);
free(file_line_buffer);
assembler_info_t info = {.bytecode_buffer = bytecode_buffer, .bytecode_buffer_length = line_count_without_defs * 6};
return info;
}
int main(void){
register_instructions();
assemble("test.asm");
} | 2.5625 | 3 |
2024-11-18T20:51:00.721969+00:00 | 2021-07-03T09:36:51 | 034b5ed97d7208fedc2c0486ad24064351f75e82 | {
"blob_id": "034b5ed97d7208fedc2c0486ad24064351f75e82",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-03T09:36:51",
"content_id": "ba0a90d5a5f9dac353302c50483267cf21ba26fa",
"detected_licenses": [
"MIT"
],
"directory_id": "da1782191988c105bba5781aa0cf1bb6f40a32a2",
"extension": "c",
"filename": "net.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 382401285,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9172,
"license": "MIT",
"license_type": "permissive",
"path": "/net.c",
"provenance": "stackv2-0110.json.gz:230060",
"repo_name": "nort-cnc-control/libip",
"revision_date": "2021-07-03T09:36:51",
"revision_id": "c835ac56a662c09918baad05f5e160693d1eaf2c",
"snapshot_id": "9a70e1f8364432d33a04b4f157e3190f4eb99e3e",
"src_encoding": "UTF-8",
"star_events_count": 23,
"url": "https://raw.githubusercontent.com/nort-cnc-control/libip/c835ac56a662c09918baad05f5e160693d1eaf2c/net.c",
"visit_date": "2023-06-26T01:38:40.880443"
} | stackv2 | /*
MIT License
Copyright (c) 2021 Vladislav Tsendrovskii
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 <stdint.h>
#include <unistd.h>
#include <string.h>
#include <net.h>
#include <ethernet.h>
#include <icmp.h>
#include <udp.h>
#include <ip.h>
#include <arp.h>
static uint8_t local_mac[6];
static uint32_t local_ip;
static struct packet_state_s
{
uint8_t remote_mac[6];
uint32_t remote_ip;
} packet_state;
static uint8_t send_buffer[ETHERNET_MTU];
#define ARP_RECORDS 10
static struct apr_record
{
int8_t ttl;
uint8_t mac[6];
uint32_t ip;
} arp_table[ARP_RECORDS];
static const uint8_t mac_bcast[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
typedef const uint8_t *mac_ptr;
static void find_mac(const uint32_t ip, mac_ptr *mac)
{
int i;
*mac = mac_bcast;
for (i = 0; i < ARP_RECORDS; i++)
{
if (ip == arp_table[i].ip)
{
*mac = arp_table[i].mac;
arp_table[i].ttl = 0;
break;
}
}
}
static void remember_mac(const uint32_t ip, const uint8_t mac[6])
{
int i;
int maxttl;
int maxi;
for (i = 0; i < ARP_RECORDS; i++)
arp_table[i].ttl++;
for (i = 0; i < ARP_RECORDS; i++)
{
if (arp_table[i].ip == 0)
{
arp_table[i].ip = ip;
arp_table[i].mac[0] = mac[0];
arp_table[i].mac[1] = mac[1];
arp_table[i].mac[2] = mac[2];
arp_table[i].mac[3] = mac[3];
arp_table[i].mac[4] = mac[4];
arp_table[i].mac[5] = mac[5];
arp_table[i].ttl = 0;
return;
}
}
maxttl = 0;
maxi = 0;
for (i = 0; i < ARP_RECORDS; i++)
{
if (arp_table[i].ttl > maxttl)
{
maxi = i;
maxttl = arp_table[i].ttl;
}
}
arp_table[maxi].ip = ip;
arp_table[maxi].mac[0] = mac[0];
arp_table[maxi].mac[1] = mac[1];
arp_table[maxi].mac[2] = mac[2];
arp_table[maxi].mac[3] = mac[3];
arp_table[maxi].mac[4] = mac[4];
arp_table[maxi].mac[5] = mac[5];
arp_table[maxi].ttl = 0;
}
/* Sending outcoming packets */
void libip_send_udp_packet(const uint8_t *payload, size_t payload_len, uint32_t remote_ip, uint16_t local_port, uint16_t remote_port)
{
memset(send_buffer, 0, sizeof(send_buffer));
uint8_t *buffer = send_buffer;
mac_ptr remote_mac;
find_mac(remote_ip, &remote_mac);
size_t udp_payload_len = udp_fill_payload(buffer + ETHERNET_HEADER_LEN + IP_HEADER_LEN, payload, payload_len);
size_t udp_len = udp_fill_header(buffer + ETHERNET_HEADER_LEN + IP_HEADER_LEN, local_port, remote_port, udp_payload_len);
size_t ip_len = ip_fill_header(buffer + ETHERNET_HEADER_LEN, local_ip, remote_ip, IP_PROTOCOL_UDP, 30, udp_len);
size_t eth_len = ethernet_fill_header(buffer, local_mac, remote_mac, ETHERTYPE_IP, ip_len);
send_ethernet_frame(buffer, eth_len);
}
void libip_send_icmp_echo_reply(const uint8_t *payload, size_t len, const uint32_t remote_ip, uint16_t id, uint16_t seq)
{
memset(send_buffer, 0, sizeof(send_buffer));
uint8_t *buffer = send_buffer;
mac_ptr remote_mac;
find_mac(remote_ip, &remote_mac);
size_t payload_len = icmp_fill_echo_payload(buffer + ETHERNET_HEADER_LEN + IP_HEADER_LEN + ICMP_HEADER_LEN, payload, len);
size_t echo_len = icmp_fill_echo_header(buffer + ETHERNET_HEADER_LEN + IP_HEADER_LEN + ICMP_HEADER_LEN, id, seq, payload_len);
size_t icmp_len = icmp_fill_header(buffer + ETHERNET_HEADER_LEN + IP_HEADER_LEN, ICMP_TYPE_ECHO_REPLY, 0, echo_len);
size_t ip_len = ip_fill_header(buffer + ETHERNET_HEADER_LEN, local_ip, remote_ip, IP_PROTOCOL_ICMP, 30, icmp_len);
size_t eth_len = ethernet_fill_header(buffer, local_mac, remote_mac, ETHERTYPE_IP, ip_len);
send_ethernet_frame(send_buffer, eth_len);
}
void libip_send_arp_response(const uint32_t remote_ip, const uint8_t remote_mac[6])
{
memset(send_buffer, 0, sizeof(send_buffer));
uint8_t remote_ip_buf[4] = {(uint8_t)(remote_ip >> 24), (uint8_t)(remote_ip >> 16), (uint8_t)(remote_ip >> 8), (uint8_t)(remote_ip)};
uint8_t local_ip_buf[4] = {(uint8_t)(local_ip >> 24), (uint8_t)(local_ip >> 16), (uint8_t)(local_ip >> 8), (uint8_t)(local_ip)};
uint8_t *buffer = send_buffer;
arp_set_sender_hardware(buffer + ETHERNET_HEADER_LEN, local_mac, 6, 4);
arp_set_sender_protocol(buffer + ETHERNET_HEADER_LEN, local_ip_buf, 6, 4);
arp_set_target_hardware(buffer + ETHERNET_HEADER_LEN, remote_mac, 6, 4);
arp_set_target_protocol(buffer + ETHERNET_HEADER_LEN, remote_ip_buf, 6, 4);
size_t arp_len = arp_fill_header(buffer + ETHERNET_HEADER_LEN, ARP_HTYPE_ETHERNET, 6, ETHERTYPE_IP, 4, ARP_OPERATION_RESPONSE);
size_t eth_len = ethernet_fill_header(buffer, local_mac, remote_mac, ETHERTYPE_ARP, arp_len);
send_ethernet_frame(send_buffer, eth_len);
}
/* Handle incoming packets */
static void handle_udp(const uint8_t *payload, size_t len)
{
if (!udp_validate(payload, len))
return;
uint16_t sport = udp_get_source(payload, len);
uint16_t dport = udp_get_destination(payload, len);
size_t udp_payload_len;
const uint8_t *udp_payload = udp_get_payload(payload, len, &udp_payload_len);
udp_packet_handler(packet_state.remote_ip, dport, sport, udp_payload, udp_payload_len);
}
static void handle_icmp(const uint8_t *payload, size_t len)
{
if (!icmp_validate(payload, len))
return;
uint8_t type = icmp_get_type(payload, len);
uint8_t code = icmp_get_code(payload, len);
switch (type)
{
case ICMP_TYPE_ECHO:
{
if (!icmp_echo_validate(payload, len))
break;
uint16_t id = icmp_echo_get_identifier(payload, len);
uint16_t sn = icmp_echo_get_sequence_number(payload, len);
size_t icmp_payload_len;
const uint8_t *icmp_payload = icmp_echo_get_payload(payload, len, &icmp_payload_len);
/* Send ICMP ECHO REPLY response */
libip_send_icmp_echo_reply(icmp_payload, icmp_payload_len, packet_state.remote_ip, id, sn);
break;
}
default:
break;
}
}
static void handle_ip(const uint8_t *payload, size_t len)
{
if (!ip_validate(payload, len))
return;
uint8_t protocol = ip_get_protocol(payload, len);
packet_state.remote_ip = ip_get_source(payload, len);
remember_mac(packet_state.remote_ip, packet_state.remote_mac);
size_t ip_payload_len;
const uint8_t *ip_payload = ip_get_payload(payload, len, &ip_payload_len);
switch (protocol)
{
case IP_PROTOCOL_UDP:
{
handle_udp(ip_payload, ip_payload_len);
break;
}
case IP_PROTOCOL_ICMP:
{
handle_icmp(ip_payload, ip_payload_len);
return;
}
default:
break;
}
}
static void handle_arp(const uint8_t *payload, size_t len)
{
if (!arp_validate(payload, len))
return;
uint16_t hw = arp_get_hardware(payload, len);
uint16_t proto = arp_get_protocol(payload, len);
if (hw != ARP_HTYPE_ETHERNET || proto != ETHERTYPE_IP)
return;
size_t hwlen;
size_t plen;
uint8_t sender_hw[6];
memcpy(sender_hw, arp_get_sender_hardware(payload, len, &hwlen), sizeof(sender_hw));
uint8_t sender_p[4];
memcpy(sender_p, arp_get_sender_protocol(payload, len, &plen), sizeof(sender_p));
const uint8_t *target_hw = arp_get_target_hardware(payload, len, &hwlen);
const uint8_t *target_p = arp_get_target_protocol(payload, len, &plen);
uint32_t sender_ip = (uint32_t)sender_p[0] << 24 | (uint32_t)sender_p[1] << 16 | (uint32_t)sender_p[2] << 8 | (uint32_t)sender_p[3];
uint32_t target_ip = (uint32_t)target_p[0] << 24 | (uint32_t)target_p[1] << 16 | (uint32_t)target_p[2] << 8 | (uint32_t)target_p[3];
uint16_t op = arp_get_operation(payload, len);
switch (op)
{
case ARP_OPERATION_REQUEST:
{
if (target_ip == local_ip)
{
uint8_t *buffer = send_buffer;
uint8_t rshw[6], rsp[4];
/* Send ARP response */
libip_send_arp_response(sender_ip, sender_hw);
}
break;
}
case ARP_OPERATION_RESPONSE:
{
break;
}
default:
break;
}
}
void libip_handle_ethernet(const uint8_t *payload, size_t len)
{
if (!ethernet_validate(payload, len))
return;
uint16_t ethertype = ethernet_get_ethertype(payload, len);
memcpy(packet_state.remote_mac, ethernet_get_source(payload, len), 6);
size_t ethernet_payload_len;
const uint8_t *ethernet_payload = ethernet_get_payload(payload, len, ðernet_payload_len);
switch (ethertype)
{
case ETHERTYPE_IP:
handle_ip(ethernet_payload, ethernet_payload_len);
break;
case ETHERTYPE_ARP:
handle_arp(ethernet_payload, ethernet_payload_len);
break;
default:
break;
}
}
void libip_init(uint32_t ip, const uint8_t mac[6])
{
local_ip = ip;
memcpy(local_mac, mac, 6);
}
| 2.453125 | 2 |
2024-11-18T20:51:00.825675+00:00 | 2015-03-13T05:57:18 | 8ea066369120bd67d08563a11146ed8387c96897 | {
"blob_id": "8ea066369120bd67d08563a11146ed8387c96897",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-13T05:57:18",
"content_id": "0e83ae2048130a75f5e77ecf867eb88e275e3a3b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "22058fd2b605221bc52c9aac4572f09e54f44879",
"extension": "h",
"filename": "heap_heapify.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 523,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Algorithms/heap_heapify.h",
"provenance": "stackv2-0110.json.gz:230188",
"repo_name": "XClouded/Algorithms",
"revision_date": "2015-03-13T05:57:18",
"revision_id": "3d153d99eae8becc645903aa37fd224f0efefb81",
"snapshot_id": "8bd454bbd04d36d0f1f0dd7c7830f4091de67375",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/XClouded/Algorithms/3d153d99eae8becc645903aa37fd224f0efefb81/Algorithms/heap_heapify.h",
"visit_date": "2021-01-17T15:54:16.943157"
} | stackv2 | //
// heap_heapify.h
// Algorithms
//
// Created by BunnyBlue on 3/6/15.
// Copyright (c) 2015 BunnyBlue. All rights reserved.
//
#ifndef __Algorithms__heap_heapify__
#define __Algorithms__heap_heapify__
#include <stdio.h>
void max_heapify(int*A, int heapsize,int i);
void build_heap(int*A,int len);
void heapSort(int *A,int len);
int inline PARENT(int i){
return i/2;
};
int inline LEFT(int i){
return 2*i;}
int inline RIGHT(int i){
return i*2+1;}
#endif /* defined(__Algorithms__heap_heapify__) */
| 2.125 | 2 |
2024-11-18T20:51:01.081954+00:00 | 2023-01-09T11:14:13 | a3995c73fc5e019e387c5f561ed5550d2e83f2e1 | {
"blob_id": "a3995c73fc5e019e387c5f561ed5550d2e83f2e1",
"branch_name": "refs/heads/main",
"committer_date": "2023-01-09T11:14:13",
"content_id": "8704780bbb6a4130d6297bcbb60e7f2131ba530b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "39ec21a0054abb77d8faa868e7a95022426d1717",
"extension": "c",
"filename": "main.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 539887056,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2227,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/comparison/umwait/main.c",
"provenance": "stackv2-0110.json.gz:230445",
"repo_name": "cispa/mwait",
"revision_date": "2023-01-09T11:14:13",
"revision_id": "6fde378f65b0118cae701c5f59a35b0f6d09b2a4",
"snapshot_id": "b76c508269a5df4d8ec48123562ed38fbca609e4",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/cispa/mwait/6fde378f65b0118cae701c5f59a35b0f6d09b2a4/comparison/umwait/main.c",
"visit_date": "2023-02-28T14:20:59.569902"
} | stackv2 | #define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <fcntl.h>
#include <time.h>
#include <sched.h>
#include "../cacheutils.h"
#define CORE1 1
#define CORE2 0
#define EVENT_INTERVAL 1000
#define OFFSET (64 * 21)
volatile char __attribute__((aligned(4096))) data[4096];
size_t event_internal = 500000;
#define INSTR_MONITOR asm volatile("umonitor %%rax" : : "a"(data), "c"(0), "d"(0));
#define INSTR_WAIT asm volatile("xor %%rbx, %%rbx; umwait %%rcx; jnc 1f; inc %%rbx; 1: nop" : "=b"(carry) : "a"(-1), "d"(-1), "c"(0));
#define INSTR_NAME "UMONITOR"
void pin_to_core(int core) {
cpu_set_t cpuset;
pthread_t thread;
thread = pthread_self();
CPU_ZERO(&cpuset);
CPU_SET(core, &cpuset);
pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
}
void write_speculative2(void* ptr) {
speculation_start(s);
*(char*)ptr ^= 1;
speculation_end(s);
}
int cnt = 0;
size_t volatile t_sync = 0;
void* accessor(void* dummy) {
pin_to_core(CORE2);
int seed = time(NULL); srand(seed);
printf("Go!\n");
while(1) {
sched_yield();
size_t r = rand() % event_internal + 1;
// wait(r);
wait(EVENT_INTERVAL);
//write_speculative2(data);
write_speculative2(data+OFFSET); // CONTROL
cnt++;
}
}
int main() {
memset(data, 1, sizeof(data));
pin_to_core(CORE1);
int pos = 0, t = 0;
int start = time(NULL);
int current = time(NULL);
pthread_t pt;
pthread_create(&pt, NULL, accessor, NULL);
while(1) {
/* UMONITOR */
INSTR_MONITOR
size_t carry = 0;
INSTR_WAIT
if(!carry)
pos++;
current = time(NULL);
if(start != current) {
start = current;
printf("%5d / %5d (%.2f)\n", pos, cnt, pos * 100.0 / cnt);
pos = 0;
cnt = 0;
t++;
if (t==1000) {
t = 0;
event_internal = event_internal * 4 / 5;
printf("event_internal alters!!!\n\n");
if (event_internal < 500)
break;
}
}
}
}
| 2.6875 | 3 |
2024-11-18T21:15:30.921695+00:00 | 2020-06-03T06:46:40 | 90ec819a6f0f7f4ab79e8816ed2b7eea0d9c9831 | {
"blob_id": "90ec819a6f0f7f4ab79e8816ed2b7eea0d9c9831",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-03T06:46:40",
"content_id": "ae262ca83fb2194775a731f8f98bfae19825dea6",
"detected_licenses": [
"MIT"
],
"directory_id": "3e9072ed49bcf2e628417a63d729ea8d7033a051",
"extension": "c",
"filename": "ViscPerzina.C",
"fork_events_count": 3,
"gha_created_at": "2020-03-02T07:43:54",
"gha_event_created_at": "2020-03-23T16:28:47",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 244309925,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5148,
"license": "MIT",
"license_type": "permissive",
"path": "/Sources/Libraries/finiteElement/ViscPerzina.C",
"provenance": "stackv2-0112.json.gz:31",
"repo_name": "pantale/ReDynELA",
"revision_date": "2020-06-03T06:46:40",
"revision_id": "273db43f7a32f956847ce88c2d0e0b7f432a2bb5",
"snapshot_id": "4e9f3ab0d0b2a1e806c310a0aba1ff292dd11338",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/pantale/ReDynELA/273db43f7a32f956847ce88c2d0e0b7f432a2bb5/Sources/Libraries/finiteElement/ViscPerzina.C",
"visit_date": "2021-07-20T11:03:27.103726"
} | stackv2 | /***************************************************************************
* *
* DynELA Project *
* *
* (c) Copyright 1997-2006 *
* *
* Equipe C.M.A.O *
* Laboratoire Genie de production *
* Ecole Nationale d'Ingenieurs de Tarbes *
* BP 1629 - 65016 TARBES cedex *
* *
* *
* Main Author: Olivier PANTALE *
* *
**************************************************************************/
// begin date :
/*
Class ViscPerzina definition
*/
/*!
\file ViscPerzina.C
\brief fichier .C de d�finition d'un mat�riau �lasto-plastique de type Metafor.
\ingroup femLibrary
Ce fichier sert � la d�finition d'un mat�riau de type �lasto-plastique de type Metafor sur DynELA.
\author © Olivier PANTALE
\since DynELA 0.9.5
\date 1997-2004
*/
#include <ViscPerzina.h>
#include <IntegrationPoint.h>
#include <Element.h>
//-----------------------------------------------------------------------------
Indice ViscPerzina::getType()
//-----------------------------------------------------------------------------
{
return Perzina;
}
//-----------------------------------------------------------------------------
ViscPerzina::ViscPerzina() : Viscosity()
//-----------------------------------------------------------------------------
{
K = 0;
m = 0;
n = 0;
}
//-----------------------------------------------------------------------------
ViscPerzina::ViscPerzina(const ViscPerzina &mat) : Viscosity(mat)
//-----------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
ViscPerzina::~ViscPerzina()
//-----------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
Indice ViscPerzina::getNumberOfConstitutiveParameters()
//-----------------------------------------------------------------------------
{
return 3;
}
//-----------------------------------------------------------------------------
const char *ViscPerzina::getConstitutiveParameterName(Indice ind)
//-----------------------------------------------------------------------------
{
switch (ind)
{
case 1:
return "K";
break;
case 2:
return "m";
break;
case 3:
return "n";
break;
}
return "";
}
//-----------------------------------------------------------------------------
Real &ViscPerzina::getConstitutiveParameter(Indice ind)
//-----------------------------------------------------------------------------
{
switch (ind)
{
case 1:
return K;
break;
case 2:
return m;
break;
case 3:
return n;
break;
}
return K;
}
//-----------------------------------------------------------------------------
Real ViscPerzina::getViscousStress(Element *element, Real shift)
//-----------------------------------------------------------------------------
{
Real evp = element->ref->evp + Sqrt23 * shift;
return K * pow(element->ref->evp, m) * pow(evp, n);
}
//-----------------------------------------------------------------------------
void ViscPerzina::print(ostream &os) const
//-----------------------------------------------------------------------------
{
os << "Perzina viscosity law\n";
}
//-----------------------------------------------------------------------------
ostream &operator<<(ostream &os, ViscPerzina &mat)
//-----------------------------------------------------------------------------
{
mat.print(os);
return os;
}
//-----------------------------------------------------------------------------
void ViscPerzina::toFile(FILE *pfile)
//-----------------------------------------------------------------------------
{
for (Indice i = 1; i <= 8; i++)
{
// fprintf (pfile, "P%ld = %lf\n",i,P[i]);
}
}
//-----------------------------------------------------------------------------
String ViscPerzina::convertToDynELASourceFile(String name)
//-----------------------------------------------------------------------------
{
String str;
char sstr[1000];
str = "";
if (K != 0)
{
sprintf(sstr, "%s.setK(%12.7E);\n", name.chars(), K);
str += sstr;
}
if (m != 0)
{
sprintf(sstr, "%s.setm(%12.7E);\n", name.chars(), m);
str += sstr;
}
if (n != 0)
{
sprintf(sstr, "%s.setn(%12.7E);\n", name.chars(), n);
str += sstr;
}
return str;
}
| 2.09375 | 2 |
2024-11-18T21:15:31.009096+00:00 | 2013-09-10T20:00:31 | 021d5bae286d711ef52e95bdffec48d0026fef37 | {
"blob_id": "021d5bae286d711ef52e95bdffec48d0026fef37",
"branch_name": "HEAD",
"committer_date": "2013-09-10T20:00:31",
"content_id": "17dbfd7ae0d5243f100c401a9d626d99b21ff661",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "84abfe4ffdbc39e156a0bc2d8daf14a88813e907",
"extension": "c",
"filename": "wnm_sta.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7266,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/hardware/wifi/rtl8723as_vt/wlan/wpa_supplicant_8/wpa_supplicant/wnm_sta.c",
"provenance": "stackv2-0112.json.gz:161",
"repo_name": "jhgkfusdhuk48l48dso84u0fofh840dfo/android_device_actions_gs702a",
"revision_date": "2013-09-10T20:00:31",
"revision_id": "a2ff49817a0102f6c5e0a5d3de49421285ffbaeb",
"snapshot_id": "52c138bfafeb5127ca49bb3aff2aebcfbbe2e47b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jhgkfusdhuk48l48dso84u0fofh840dfo/android_device_actions_gs702a/a2ff49817a0102f6c5e0a5d3de49421285ffbaeb/hardware/wifi/rtl8723as_vt/wlan/wpa_supplicant_8/wpa_supplicant/wnm_sta.c",
"visit_date": "2017-11-30T10:57:32.449428"
} | stackv2 | /*
* wpa_supplicant - WNM
* Copyright (c) 2011-2012, Qualcomm Atheros, Inc.
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#include "utils/includes.h"
#include "utils/common.h"
#include "common/ieee802_11_defs.h"
#include "rsn_supp/wpa.h"
#include "../wpa_supplicant/wpa_supplicant_i.h"
#include "../wpa_supplicant/driver_i.h"
#define MAX_TFS_IE_LEN 1024
#ifdef CONFIG_IEEE80211V
/* get the TFS IE from driver */
static int ieee80211_11_get_tfs_ie(struct wpa_supplicant *wpa_s, u8 *buf,
u16 *buf_len, enum wnm_oper oper)
{
wpa_printf(MSG_DEBUG, "%s: TFS get operation %d", __func__, oper);
return wpa_drv_wnm_oper(wpa_s, oper, wpa_s->bssid, buf, buf_len);
}
/* set the TFS IE to driver */
static int ieee80211_11_set_tfs_ie(struct wpa_supplicant *wpa_s,
const u8 *addr, u8 *buf, u16 *buf_len,
enum wnm_oper oper)
{
wpa_printf(MSG_DEBUG, "%s: TFS set operation %d", __func__, oper);
return wpa_drv_wnm_oper(wpa_s, oper, addr, buf, buf_len);
}
/* MLME-SLEEPMODE.request */
int ieee802_11_send_wnmsleep_req(struct wpa_supplicant *wpa_s,
u8 action, u8 intval)
{
struct ieee80211_mgmt *mgmt;
int res;
size_t len;
struct wnm_sleep_element *wnmsleep_ie;
u8 *wnmtfs_ie;
u8 wnmsleep_ie_len;
u16 wnmtfs_ie_len; /* possibly multiple IE(s) */
enum wnm_oper tfs_oper = action == 0 ? WNM_SLEEP_TFS_REQ_IE_ADD :
WNM_SLEEP_TFS_REQ_IE_NONE;
/* WNM-Sleep Mode IE */
wnmsleep_ie_len = sizeof(struct wnm_sleep_element);
wnmsleep_ie = os_zalloc(sizeof(struct wnm_sleep_element));
if (wnmsleep_ie == NULL)
return -1;
wnmsleep_ie->eid = WLAN_EID_WNMSLEEP;
wnmsleep_ie->len = wnmsleep_ie_len - 2;
wnmsleep_ie->action_type = action;
wnmsleep_ie->status = WNM_STATUS_SLEEP_ACCEPT;
wnmsleep_ie->intval = intval;
/* TFS IE(s) */
wnmtfs_ie = os_zalloc(MAX_TFS_IE_LEN);
if (wnmtfs_ie == NULL) {
os_free(wnmsleep_ie);
return -1;
}
if (ieee80211_11_get_tfs_ie(wpa_s, wnmtfs_ie, &wnmtfs_ie_len,
tfs_oper)) {
wnmtfs_ie_len = 0;
os_free(wnmtfs_ie);
wnmtfs_ie = NULL;
}
mgmt = os_zalloc(sizeof(*mgmt) + wnmsleep_ie_len + wnmtfs_ie_len);
if (mgmt == NULL) {
wpa_printf(MSG_DEBUG, "MLME: Failed to allocate buffer for "
"WNM-Sleep Request action frame");
return -1;
}
os_memcpy(mgmt->da, wpa_s->bssid, ETH_ALEN);
os_memcpy(mgmt->sa, wpa_s->own_addr, ETH_ALEN);
os_memcpy(mgmt->bssid, wpa_s->bssid, ETH_ALEN);
mgmt->frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
WLAN_FC_STYPE_ACTION);
mgmt->u.action.category = WLAN_ACTION_WNM;
mgmt->u.action.u.wnm_sleep_req.action = WNM_SLEEP_MODE_REQ;
os_memcpy(mgmt->u.action.u.wnm_sleep_req.variable, wnmsleep_ie,
wnmsleep_ie_len);
/* copy TFS IE here */
if (wnmtfs_ie_len > 0) {
os_memcpy(mgmt->u.action.u.wnm_sleep_req.variable +
wnmsleep_ie_len, wnmtfs_ie, wnmtfs_ie_len);
}
len = 1 + sizeof(mgmt->u.action.u.wnm_sleep_req) + wnmsleep_ie_len +
wnmtfs_ie_len;
res = wpa_drv_send_action(wpa_s, wpa_s->assoc_freq, 0, wpa_s->bssid,
wpa_s->own_addr, wpa_s->bssid,
&mgmt->u.action.category, len, 0);
if (res < 0)
wpa_printf(MSG_DEBUG, "Failed to send WNM-Sleep Request "
"(action=%d, intval=%d)", action, intval);
os_free(wnmsleep_ie);
os_free(wnmtfs_ie);
os_free(mgmt);
return res;
}
static void ieee802_11_rx_wnmsleep_resp(struct wpa_supplicant *wpa_s,
const u8 *frm, int len)
{
/*
* Action [1] | Diaglog Token [1] | Key Data Len [2] | Key Data |
* WNM-Sleep Mode IE | TFS Response IE
*/
u8 *pos = (u8 *) frm; /* point to action field */
u16 key_len_total = le_to_host16(*((u16 *)(frm+2)));
u8 gtk_len;
#ifdef CONFIG_IEEE80211W
u8 igtk_len;
#endif /* CONFIG_IEEE80211W */
struct wnm_sleep_element *wnmsleep_ie = NULL;
/* multiple TFS Resp IE (assuming consecutive) */
u8 *tfsresp_ie_start = NULL;
u8 *tfsresp_ie_end = NULL;
u16 tfsresp_ie_len = 0;
wpa_printf(MSG_DEBUG, "action=%d token = %d key_len_total = %d",
frm[0], frm[1], key_len_total);
pos += 4 + key_len_total;
while (pos - frm < len) {
u8 ie_len = *(pos + 1);
if (*pos == WLAN_EID_WNMSLEEP)
wnmsleep_ie = (struct wnm_sleep_element *) pos;
else if (*pos == WLAN_EID_TFS_RESP) {
if (!tfsresp_ie_start)
tfsresp_ie_start = pos;
tfsresp_ie_end = pos;
} else
wpa_printf(MSG_DEBUG, "EID %d not recognized", *pos);
pos += ie_len + 2;
}
if (!wnmsleep_ie) {
wpa_printf(MSG_DEBUG, "No WNM-Sleep IE found");
return;
}
if (wnmsleep_ie->status == WNM_STATUS_SLEEP_ACCEPT) {
wpa_printf(MSG_DEBUG, "Successfully recv WNM-Sleep Response "
"frame (action=%d, intval=%d)",
wnmsleep_ie->action_type, wnmsleep_ie->intval);
if (wnmsleep_ie->action_type == 0) {
wpa_drv_wnm_oper(wpa_s, WNM_SLEEP_ENTER_CONFIRM,
wpa_s->bssid, NULL, NULL);
/* remove GTK/IGTK ?? */
/* set the TFS Resp IE(s) */
if (tfsresp_ie_start && tfsresp_ie_end &&
tfsresp_ie_end - tfsresp_ie_start >= 0) {
tfsresp_ie_len = (tfsresp_ie_end +
tfsresp_ie_end[1] + 2) -
tfsresp_ie_start;
wpa_printf(MSG_DEBUG, "TFS Resp IE(s) found");
/*
* pass the TFS Resp IE(s) to driver for
* processing
*/
if (ieee80211_11_set_tfs_ie(
wpa_s, wpa_s->bssid,
tfsresp_ie_start,
&tfsresp_ie_len,
WNM_SLEEP_TFS_RESP_IE_SET))
wpa_printf(MSG_DEBUG, "Fail to set "
"TFS Resp IE");
}
} else if (wnmsleep_ie->action_type == 1) {
wpa_drv_wnm_oper(wpa_s, WNM_SLEEP_EXIT_CONFIRM,
wpa_s->bssid, NULL, NULL);
/* Install GTK/IGTK */
do {
/* point to key data field */
u8 *ptr = (u8 *) frm + 1 + 1 + 2;
while (ptr < (u8 *) frm + 4 + key_len_total) {
if (*ptr == WNM_SLEEP_SUBELEM_GTK) {
gtk_len = *(ptr + 4);
wpa_wnmsleep_install_key(
wpa_s->wpa,
WNM_SLEEP_SUBELEM_GTK,
ptr);
ptr += 13 + gtk_len;
#ifdef CONFIG_IEEE80211W
} else if (*ptr ==
WNM_SLEEP_SUBELEM_IGTK) {
igtk_len = WPA_IGTK_LEN;
wpa_wnmsleep_install_key(
wpa_s->wpa,
WNM_SLEEP_SUBELEM_IGTK,
ptr);
ptr += 10 + WPA_IGTK_LEN;
#endif /* CONFIG_IEEE80211W */
} else
break; /* skip the loop */
}
} while(0);
}
} else {
wpa_printf(MSG_DEBUG, "Reject recv WNM-Sleep Response frame "
"(action=%d, intval=%d)",
wnmsleep_ie->action_type, wnmsleep_ie->intval);
if (wnmsleep_ie->action_type == 0)
wpa_drv_wnm_oper(wpa_s, WNM_SLEEP_ENTER_FAIL,
wpa_s->bssid, NULL, NULL);
else if (wnmsleep_ie->action_type == 1)
wpa_drv_wnm_oper(wpa_s, WNM_SLEEP_EXIT_FAIL,
wpa_s->bssid, NULL, NULL);
}
}
void ieee802_11_rx_wnm_action(struct wpa_supplicant *wpa_s,
struct rx_action *action)
{
u8 *pos = (u8 *) action->data; /* point to action field */
u8 act = *pos++;
/* u8 dialog_token = *pos++; */
switch (act) {
case WNM_SLEEP_MODE_RESP:
ieee802_11_rx_wnmsleep_resp(wpa_s, action->data, action->len);
break;
default:
break;
}
}
#endif /* CONFIG_IEEE80211V */
| 2.046875 | 2 |
2024-11-18T21:15:31.695097+00:00 | 2018-01-04T10:47:56 | 26d2b807d2aae051b5dd58a841bcfc46cfbe8858 | {
"blob_id": "26d2b807d2aae051b5dd58a841bcfc46cfbe8858",
"branch_name": "refs/heads/live",
"committer_date": "2018-01-04T10:47:56",
"content_id": "2d1c0083d7a8440941dbac466a30a945adcfe17b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9a229778b8f73dcaad28c74cc16a3ba8ee4a3cb7",
"extension": "c",
"filename": "env.c",
"fork_events_count": 2,
"gha_created_at": "2014-05-27T10:40:28",
"gha_event_created_at": "2016-11-14T13:47:46",
"gha_language": "C",
"gha_license_id": null,
"github_id": 20216405,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5046,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/libliquify/env.c",
"provenance": "stackv2-0112.json.gz:804",
"repo_name": "bbcarchdev/quilt",
"revision_date": "2018-01-04T10:47:56",
"revision_id": "30c76a236662056df03266069457687681185dd5",
"snapshot_id": "b25b8e91dddf4a3c2ade30128786fb0868b0913a",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/bbcarchdev/quilt/30c76a236662056df03266069457687681185dd5/libliquify/env.c",
"visit_date": "2021-04-09T16:37:28.801669"
} | stackv2 | /* Author: Mo McRoberts <mo.mcroberts@bbc.co.uk>
*
* Copyright (c) 2014 BBC.
*
* 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.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "p_libliquify.h"
static void liquify_logger_(int level, const char *fmt, va_list ap);
/* Create a liquify environment */
LIQUIFY *
liquify_create(void)
{
LIQUIFY *p;
p = (LIQUIFY *) calloc(1, sizeof(LIQUIFY));
if(!p)
{
fprintf(stderr, "libliquify: failed to allocate %lu bytes: %s\n", (unsigned long) sizeof(LIQUIFY), strerror(errno));
return NULL;
}
p->vlogf = liquify_logger_;
return p;
}
/* Set the logging callback for use in a liquify environment.
* Pass NULL as the callback to reset to the default logger.
*/
int
liquify_set_logger(LIQUIFY *liquify, void (*logger)(int level, const char *fmt, va_list ap))
{
if(!logger)
{
logger = liquify_logger_;
}
liquify->vlogf = logger;
return 0;
}
/* Set the loader callback (and user data pointer) to be used in a liquify
* environment. The callback will be invoked when liquify_load() needs to
* load a template which hasn't yet been loaded into the environment
* (including through parsing of the {% include ... %} tag).
*
* The loader is responsible for locating and reading the file (or
* equivalent), passing it to liquify_parse(), and returning the parsed
* LIQUIFYTPL which will be used as the result of the call to liquify_load().
*/
int
liquify_set_loader(LIQUIFY *liquify, LIQUIFYTPL *(*loader)(LIQUIFY *env, const char *name, void *dta), void *data)
{
if(loader)
{
liquify->loader = loader;
liquify->loaddata = data;
}
else
{
liquify->loader = NULL;
liquify->loaddata = NULL;
}
return 0;
}
/* Load a template, if it hasn't already been loaded into the environment,
* using the callback set via liquify_set_loader().
*/
LIQUIFYTPL *
liquify_load(LIQUIFY *liquify, const char *name)
{
LIQUIFYTPL *tpl;
tpl = liquify_locate(liquify, name);
if(tpl)
{
liquify_logf(liquify, LOG_DEBUG, "template '%s' has already been loaded\n", name);
/* Template has already been loaded */
return tpl;
}
if(liquify->loader)
{
/* Invoke the loader callback */
return liquify->loader(liquify, name, liquify->loaddata);
}
liquify_logf(liquify, LOG_ERR, "cannot load template '%s': no loader has been provided\n", name);
return NULL;
}
/* Destroy a liquify environment, freeing resources used by any loaded
* templates.
*/
int
liquify_destroy(LIQUIFY *liquify)
{
LIQUIFYTPL *tpl;
while(liquify->first)
{
tpl = liquify->first->next;
liquify_tpl_free_(liquify->first);
liquify->first = tpl;
}
free(liquify);
return 0;
}
/* Log a message in an environment. If a callback has been defined by
* liquify_set_logger(), it will be used.
*/
void
liquify_logf(LIQUIFY *liquify, int level, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
liquify_vlogf(liquify, level, fmt, ap);
}
void
liquify_vlogf(LIQUIFY *liquify, int level, const char *fmt, va_list ap)
{
liquify->vlogf(level, fmt, ap);
}
/* Allocate a zero-filled buffer of len bytes, logging a critical error and
* aborting the process if it fails.
*/
void *
liquify_alloc(LIQUIFY *liquify, size_t len)
{
void *ptr;
ptr = calloc(1, len);
if(!ptr)
{
liquify_logf(liquify, LOG_CRIT, "failed to allocate %lu bytes: %s\n", (unsigned long) len, strerror(errno));
abort();
}
return ptr;
}
/* Resize a buffer to len bytes, logging a critical error and aborting the
* process if it fails. Note that if the new buffer is larger than the old
* one, the extension bytes won't be zero-filled.
*/
void *
liquify_realloc(LIQUIFY *restrict liquify, void *restrict ptr, size_t newlen)
{
ptr = realloc(ptr, newlen);
if(!ptr)
{
liquify_logf(liquify, LOG_CRIT, "failed to re-allocate %lu bytes: %s\n", (unsigned long) newlen, strerror(errno));
abort();
}
return ptr;
}
/* Allocate a buffer and copy the contents of a string, logging a critical
* error and aborting the process if allocation fails.
*/
char *
liquify_strdup(LIQUIFY *restrict liquify, const char *src)
{
char *ptr;
size_t l;
l = strlen(src);
ptr = (char *) liquify_alloc(liquify, l + 1);
memcpy(ptr, src, l);
ptr[l] = 0;
return ptr;
}
/* Free a buffer previously allocated by liquify_alloc() or liquify_strdup() */
void
liquify_free(LIQUIFY *restrict liquify, void *restrict ptr)
{
(void) liquify;
free(ptr);
}
/* A simple default logger */
static void
liquify_logger_(int level, const char *fmt, va_list ap)
{
(void) level;
vfprintf(stderr, fmt, ap);
}
| 2.21875 | 2 |
2024-11-18T21:15:31.853121+00:00 | 2019-07-25T08:27:49 | 5e772eaaafdc3dc6545833642b546807c5c1bcb4 | {
"blob_id": "5e772eaaafdc3dc6545833642b546807c5c1bcb4",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-25T08:27:49",
"content_id": "4a70ae9439d35f7fe05e286eba50b342c6e38461",
"detected_licenses": [
"MIT"
],
"directory_id": "e619ebeb546fd3a724f436a57ff3749bb10f9c30",
"extension": "c",
"filename": "libraid_user.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 198788464,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3779,
"license": "MIT",
"license_type": "permissive",
"path": "/libraid_user.c",
"provenance": "stackv2-0112.json.gz:1061",
"repo_name": "Ankit-rana/graid",
"revision_date": "2019-07-25T08:27:49",
"revision_id": "236aa55929bef03e781281e61614b7542c9eabd1",
"snapshot_id": "70c13e879666726044e3e60e02d7101111aa1118",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ankit-rana/graid/236aa55929bef03e781281e61614b7542c9eabd1/libraid_user.c",
"visit_date": "2020-06-23T23:55:13.691039"
} | stackv2 | #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DEVICES 100
#define MAXSTR 200
struct system
{
int num_raids;
struct raid *raids;
};
struct raid
{
int raid_id;
char raid_name[MAXSTR];
int stripe_size;
int bps; // blocks per sector
int num_devices;
struct device *devices[MAX_DEVICES];
int raidsize;
struct raid * next;
};
struct device
{
char *name;
int size;
};
int create_new_raid(struct system * s, char *raid_name, int num_devices, ...)
{
va_list list;
int i = 0;
struct raid *r;
struct device *disk;
// initialize one raid node
r = malloc(sizeof(struct raid));
if (r != NULL)
{
memset(r, 0, sizeof(struct raid));
}
r->next = NULL;
// set raid id
r->raid_id=s->num_raids;
// set raid name
strcpy(r->raid_name,raid_name);
// set number of devices
r->num_devices = num_devices;
// iterate over each device and set name
va_start(list, num_devices);
for(i=0; i<num_devices; i++)
{
// initialize disk
disk = malloc(sizeof(struct device));
memset(disk, 0, sizeof(struct device));
// set each name using va_arg(list, char *)
disk->name = va_arg(list, char *);
r->devices[i] = disk;
}
va_end(list);
// TODO : add raid node to linked list
if (s->raids == NULL){
// just add
s->raids = r;
} else {
// iterate to end and then add
while(s->raids->next != NULL)
s->raids = s->raids->next;
s->raids->next = r;
}
// s->raids[s->num_raids] = r;
// increment system.num_raids
s->num_raids += 1;
return EXIT_SUCCESS;
}
int delete_raid(struct system *s, int id)
{
struct raid *r = s->raids;
int i = 0;
// free all disks
while (s->raids->raid_id == id || s->raids != NULL)
{
r = s->raids;
s->raids = s->raids->next;
}
if (s->raids == NULL){
printf("Raid with ID %d does not exists.", id);
return 0;
}
// free all disks
for (i=0; i<s->raids->num_devices; i++)
{
free(s->raids->devices[i]);
}
// free raid
r->next = s->raids->next;
free(s->raids);
s->num_raids--;
return 0;
}
int initialize_system(struct system **sp)
{
// Do not let more than one system exists together
if (*sp != NULL)
{
return 0;
}
*sp = malloc(sizeof(struct system));
if(*sp != NULL)
{
memset(*sp, 0, sizeof(struct system));
}
return 0;
}
void print_raid_config(struct system *s)
{
int j=0;
printf("\n");
printf("Total Raids: %d\n", s->num_raids);
if (s->raids == NULL)
{
return;
}
while(s->raids != NULL)
{
printf("Raid ID: %d\n", s->raids->raid_id);
printf("Raid Name: %s\n", s->raids->raid_name);
for (j=0; j<s->raids->num_devices; j++)
{
printf("device: %s\n", s->raids->devices[j]->name);
}
s->raids = s->raids->next;
}
}
int main()
{
struct system * s;
char * rname,* lname;
char * d0;
char * d1;
int id = 1;
rname = malloc(sizeof(43));
lname = malloc(sizeof(43));
rname = "ankit_raid";
lname = "rana_raid";
d0 = malloc(sizeof(43));
d0 = "/dev/sdb";
d1 = malloc(sizeof(43));
d1 = "/dev/sdc";
// initialize system structure
initialize_system(&s);
// set raid config
create_new_raid(s, rname, 2, d0, d1);
create_new_raid(s, lname, 2, d0, d1);
//create_new_raid(s, rname, 0);
// view raid config
print_raid_config(s);
delete_raid(s,id);
//print_raid_config(s);
return 0;
}
| 3.125 | 3 |
2024-11-18T21:15:32.163390+00:00 | 2023-02-16T11:27:40 | 96f9943998be2af653b26c9078baa92a3fc18761 | {
"blob_id": "96f9943998be2af653b26c9078baa92a3fc18761",
"branch_name": "refs/heads/main",
"committer_date": "2023-02-16T14:59:16",
"content_id": "315b2ae7adb864aa6e390048e1b660b985e6d10f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493",
"extension": "c",
"filename": "timeout_order.c",
"fork_events_count": 32,
"gha_created_at": "2016-08-05T22:14:50",
"gha_event_created_at": "2022-04-05T17:14:07",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 65052293,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1924,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tests/kernel/common/src/timeout_order.c",
"provenance": "stackv2-0112.json.gz:1574",
"repo_name": "intel/zephyr",
"revision_date": "2023-02-16T11:27:40",
"revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee",
"snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/tests/kernel/common/src/timeout_order.c",
"visit_date": "2023-09-04T00:20:35.217393"
} | stackv2 | /*
* Copyright (c) 2017 Wind River Systems, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
#include <zephyr/ztest.h>
#define NUM_TIMEOUTS 3
static struct k_timer timer[NUM_TIMEOUTS];
static struct k_sem sem[NUM_TIMEOUTS];
static int results[NUM_TIMEOUTS], cur;
static void thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p2);
ARG_UNUSED(p3);
uintptr_t id = (uintptr_t)p1;
k_timer_status_sync(&timer[id]);
/* no need to protect cur, all threads have the same prio */
results[cur++] = id;
k_sem_give(&sem[id]);
}
#define STACKSIZE (512 + CONFIG_TEST_EXTRA_STACK_SIZE)
static K_THREAD_STACK_ARRAY_DEFINE(stacks, NUM_TIMEOUTS, STACKSIZE);
static struct k_thread threads[NUM_TIMEOUTS];
/**
* @addtogroup kernel_common_tests
* @{
*/
/**
* @brief Test timeout ordering
*
* @details Timeouts, when expiring on the same tick, should be handled
* in the same order they were queued.
*
* @see k_timer_start()
*/
ZTEST(common_1cpu, test_timeout_order)
{
int ii, prio = k_thread_priority_get(k_current_get()) + 1;
for (ii = 0; ii < NUM_TIMEOUTS; ii++) {
(void)k_thread_create(&threads[ii], stacks[ii], STACKSIZE,
thread, INT_TO_POINTER(ii), 0, 0,
prio, 0, K_NO_WAIT);
k_timer_init(&timer[ii], 0, 0);
k_sem_init(&sem[ii], 0, 1);
results[ii] = -1;
}
uint32_t uptime = k_uptime_get_32();
/* sync on tick */
while (uptime == k_uptime_get_32()) {
#if defined(CONFIG_ARCH_POSIX)
k_busy_wait(50);
#endif
}
for (ii = 0; ii < NUM_TIMEOUTS; ii++) {
k_timer_start(&timer[ii], K_MSEC(100), K_NO_WAIT);
}
/* Wait for all timers to fire */
k_msleep(125);
/* Check results */
for (ii = 0; ii < NUM_TIMEOUTS; ii++) {
zassert_equal(results[ii], ii, "");
}
/* Clean up */
for (ii = 0; ii < NUM_TIMEOUTS; ii++) {
k_timer_stop(&timer[ii]);
k_thread_join(&threads[ii], K_FOREVER);
}
}
/**
* @}
*/
| 2.53125 | 3 |
2024-11-18T21:15:32.227815+00:00 | 2022-09-03T14:11:00 | dd98f80104c6deb1022d497c3461e45a195b0c0e | {
"blob_id": "dd98f80104c6deb1022d497c3461e45a195b0c0e",
"branch_name": "refs/heads/master",
"committer_date": "2022-09-03T14:11:00",
"content_id": "3a22a15ff2cc566de5dcb9d397a79b21b81f3d32",
"detected_licenses": [
"MIT"
],
"directory_id": "c1337b11e0dafe374183cbccd5d9ff6e3cd167de",
"extension": "c",
"filename": "median.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 251291963,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9968,
"license": "MIT",
"license_type": "permissive",
"path": "/median.c",
"provenance": "stackv2-0112.json.gz:1704",
"repo_name": "jlprieur/sourcc",
"revision_date": "2022-09-03T14:11:00",
"revision_id": "a8106aadf4fbed04fc14b552c3504d6686fa7032",
"snapshot_id": "09c933fb8a093db2e98266f674c36317502d3991",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jlprieur/sourcc/a8106aadf4fbed04fc14b552c3504d6686fa7032/median.c",
"visit_date": "2022-09-20T09:46:21.370744"
} | stackv2 | /*************************************************************************
* Program to compute the median of a list of files
* (used to generate the "unresolved" mean autocorrelation of power spectrum
* for speckle processing)
*
* JLP
* Version 22/02/2007
**************************************************************************/
#include <jlp_ftoc.h>
#define DEBUG
/* Contained in jlp_sort.c :
int JLP_MEDIAN(float *data, int npts, float *value);
*/
/* Prototypes of files contained here: */
static int median_read_data(char *list_file, float ***img, int *nfiles,
INT4 *nx, INT4 *ny);
static int median_compute_mean(float *mean_img, float **img, int nfiles,
INT4 nx, INT4 ny, float *a0, float *a1);
static int median_compute_coeff(float *model, float *imgg, INT4 nx, INT4 ny,
float *a0, float *a1);
static int median_compute_median(float *median_img, float **img,
INT4 nx, INT4 ny, int nfiles);
/***************************************************************************/
int main(int argc, char *argv[]) {
float **img, *mean_img, *median_img, *a0, *a1;
int nfiles, status, isize;
INT4 nx, ny;
register int iter, i, k;
char list_file[60], out_fname[60], comments[80];
/* To handle "runs median" */
for(k = 7; k > 0; k--) if(argc == k && argv[k-1][0] == '\0') argc = k-1;
if(argc != 3) {
printf("Error, argc=%d \n Syntax is:\n", argc);
printf("median.exe list.dat output_file\n");
printf("or: runs median list.dat output_file\n");
return(-1);
}
sscanf(argv[1], "%s", list_file);
sscanf(argv[2], "%s", out_fname);
JLP_INQUIFMT();
/* Read the files, allocate memory for img
* and load the pointers into img array */
status = median_read_data(list_file, &img, &nfiles, &nx, &ny);
#ifdef DEBUG
printf("median_read_data has read %d files, nx=%d ny=%d status=%d\n",
nfiles, nx, ny, status);
#endif
/* Allocate memory for mean_img (mean of all the images): */
mean_img = (float *)malloc(nx * ny * sizeof(float));
median_img = (float *)malloc(nx * ny * sizeof(float));
a0 = (float *)malloc(nfiles * sizeof(float));
a1 = (float *)malloc(nfiles * sizeof(float));
/* Initialize a0 and a1 arrays to compute the first mean: */
for(k = 0; k < nfiles; k++) {
a0[k] = 0.; a1[k] = 1.;
}
/* First computation of the mean with dummy a0 and a1:
* and then iterate to obtain a stable solution:
* (tested in 2007: 8 iterations are enough)
*/
for(iter = 0; iter < 8; iter++) {
median_compute_mean(mean_img, img, nfiles, nx, ny, a0, a1);
for(k = 0; k < nfiles; k++)
median_compute_coeff(mean_img, img[k], nx, ny, &a0[k], &a1[k]);
#ifdef DEBUG
printf("iter=%d a0[0]=%f a1[0]=%f\n", iter, a0[0], a1[0]);
#endif
}
/* Compute mean another time (since the center has been zeroed
* by median_compute_coeff):
*/
median_compute_mean(mean_img, img, nfiles, nx, ny, a0, a1);
/* Normalization of the images with those coefficients: */
isize = nx * ny;
for(k = 0; k < nfiles; k++)
for(i = 0; i < isize; i++) img[k][i] = (img[k][i] - a0[k]) / a1[k];
/* Compute the median of all frames: */
median_compute_median(median_img, img, nx, ny, nfiles);
sprintf(comments,"Median computed from %s",list_file);
JLP_WRITEIMAG(median_img, &nx, &ny, &nx, out_fname, comments);
/* Save mean array (to see if there are some remnants of the
* autocorrelation peaks) : */
#ifdef DEBUG
strcpy(out_fname,"test_mean");
sprintf(comments,"Mean computed from %s",list_file);
JLP_WRITEIMAG(mean_img, &nx, &ny, &nx, out_fname, comments);
#endif
/* Free memory: */
for(k = 0; k < nfiles; k++) free(img[k]);
free(mean_img);
free(median_img);
free(a0);
free(a1);
return(0);
}
/**************************************************************************
* median_read_data
* to read all the images corresponding to the list contained in list_file
*
* INPUT:
* list_file: name of the file containing the list of images
*
* OUTPUT:
* img: array of pointers with the addresses of the arrays
* nfiles: number of image files
* nx, ny: size of the images
**************************************************************************/
static int median_read_data(char *list_file, float ***img, int *nfiles,
INT4 *nx, INT4 *ny)
{
INT_PNTR pntr_ima;
INT4 nx1, ny1;
int status, k;
char fname[60], comments[80];
FILE *fp;
*nfiles = 0;
if((fp = fopen(list_file,"r")) == NULL) {
printf("median_read_data/Error reading list of files contained in %s\n",
list_file);
return(-1);
}
/* First go to count the files: */
k = 0;
while(!feof(fp)) {
if(fscanf(fp, "%s\n", fname)) k++;
}
fclose(fp);
/* Allocate memory space for pointers: */
*img = (float **)malloc(k * sizeof(float **));
/* Second go to open the files: */
if((fp = fopen(list_file,"r")) == NULL) {
printf("median_read_data/Error reading list of files contained in %s\n",
list_file);
return(-1);
}
k = 0;
while(!feof(fp)) {
if(fscanf(fp, "%s\n", fname)) {
status = JLP_VM_READIMAG1(&pntr_ima, &nx1, &ny1, fname, comments);
#ifdef DEBUG
printf("OK: reading file %s, status = %d\n", fname, status);
#endif
if(status != 0) {
fprintf(stderr, "median_read_data/Error reading file %s status=%d\n",
fname, status);
fclose(fp);
return(-2);
}
if(k == 0) {
*nx = nx1; *ny = ny1;
} else {
if(*nx != nx1 || *ny != ny1) {
fprintf(stderr, "median_read_data/Error, incompatible sizes: nx=%d nx1=%d ny=%d ny1=%d\n",
*nx, nx1, *ny, ny1);
fclose(fp);
return(-3);
}
}
(*img)[k++] = (float *)pntr_ima;
}
}
*nfiles = k;
fclose(fp);
return(0);
}
/**************************************************************************
* median_compute_mean
* to compute the mean of all the images contained in img array
*
* INPUT:
* img: array of pointers with the addresses of the arrays
* nfiles: number of image files
* nx, ny: size of the images
* a0, a1: coefficients to be applied to the input images
* (img - a0) / a1), since model * a1 + a0 is close to img)
*
* OUTPUT:
* mean_img: mean array
**************************************************************************/
static int median_compute_mean(float *mean_img, float **img, int nfiles,
INT4 nx, INT4 ny, float *a0, float *a1)
{
float ww;
int isize;
register int i, k;
isize = nx * ny;
for(i = 0; i < isize; i++) mean_img[i] = 0.;
ww = 0.;
for(k = 0; k < nfiles; k++) {
if(a1[k] == 0) {
fprintf(stderr,"median_compute_mean/fatal error: a1[%d] is null!\n", k);
exit(-1);
}
ww += 1./a1[k];
for(i = 0; i < isize; i++) mean_img[i] += (img[k][i] - a0[k]) / a1[k];
}
/* Normalization (i.e. division with the sum of the weights): */
for(i = 0; i < isize; i++) mean_img[i] /= ww;
return(0);
}
/**************************************************************************
* Compute the coefficients to normalized the input image relative to
* the model.
*
* Linear regression:
*
* Minimum of Sum ( z - a1 f - a0)^2
* is reached when gradient is nul, i.e., when:
* sum_fz = a1 sum_ff + a0 sum_f
* sum_z = a1 sum_f + a0 sum_1
*
* INPUT:
* model: model to be fitted to imgg
* imgg: image array to be processed
* nx, ny: size of the image
*
* OUTPUT:
* model: (central part is zeroed!)
* a0, a1: coefficients found for the fit
**************************************************************************/
static int median_compute_coeff(float *model, float *imgg, INT4 nx, INT4 ny,
float *a0, float *a1)
{
float *tmp, wback, wdata;
double sum_1, sum_f, sum_z, sum_fz, sum_ff, det;
int tmp_dim, ixc, iyc, ii, jj, iside;
register int i, j;
ixc = nx/2; iyc = ny/2;
/* Central pixels are generally bad, so I neutralize them for the fit:
* Warning: big scatter found for the pixels 62,64 and 66,64, so iside
* has to be >= 2:
*/
iside = 2;
tmp_dim = 2 * iside + 1;
tmp = (float *)malloc(tmp_dim * tmp_dim * sizeof(float));
for(j = -iside; j <= iside; j++) {
for(i = -iside; i <= iside; i++) {
ii = (ixc + i) + (iyc + j) * nx;
/* First save original data */
tmp[(i + iside) + (j + iside) * tmp_dim] = imgg[ii];
/* Then set it to zero: */
model[ii] = 0.;
imgg[ii] = 0.;
}
}
sum_1 = 0.;
sum_f = 0.;
sum_z = 0.;
sum_fz = 0.;
sum_ff = 0.;
for(j = 0; j < ny; j++) {
jj = j * nx;
for(i = 0; i < nx; i++) {
wback = model[i + jj];
wdata = imgg[i + jj];
sum_1 += 1.;
sum_f += wback;
sum_z += wdata;
sum_fz += wback * wdata;
sum_ff += SQUARE(wback);
}
}
/* Resolution with the determinant of the system:
* sum_fz = a1 sum_ff + a0 sum_f
* sum_z = a1 sum_f + a0 sum_1
*/
det = sum_ff * sum_1 - sum_f * sum_f;
*a1 = (sum_1 * sum_fz - sum_f * sum_z) / det;
*a0 = (sum_ff * sum_z - sum_f * sum_fz) / det;
#ifdef DEBUGG
printf("median_compute_coeff/ a1=%f a0=%f\n", *a1, *a0);
#endif
/* Restore data: */
for(j = -iside; j <= iside; j++) {
for(i = -iside; i <= iside; i++) {
ii = (ixc + i) + (iyc + j) * nx;
imgg[ii] = tmp[(i + iside) + (j + iside) * tmp_dim];
}
}
return(0);
}
/**************************************************************************
* median_compute_median
* to compute the median of all the images contained in img array
*
* INPUT:
* img: array of pointers with the addresses of the arrays
* nfiles: number of image files
* nx, ny: size of the images
*
* OUTPUT:
* median_img: median array
**************************************************************************/
static int median_compute_median(float *median_img, float **img,
INT4 nx, INT4 ny, int nfiles)
{
float *data, value;
int isize;
register int i, j, k;
data = (float *)malloc(nfiles * sizeof(float));
isize = nx * ny;
for(i = 0; i < isize; i++) {
j = 0;
for(k = 0; k < nfiles; k++) data[j++] = img[k][i];
JLP_MEDIAN(data, nfiles, &value);
median_img[i] = value;
}
free(data);
return(0);
}
| 2.53125 | 3 |
2024-11-18T21:15:35.831873+00:00 | 2015-03-09T19:40:49 | 8b2ae30d2e61d472304b2aa52244f0c10e8a041e | {
"blob_id": "8b2ae30d2e61d472304b2aa52244f0c10e8a041e",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-09T19:40:49",
"content_id": "16919c50eacc755f6bc46cf32c45291ed699b1cf",
"detected_licenses": [
"MIT"
],
"directory_id": "3af01a255c16da9305ce6a69a72385d1b99548de",
"extension": "c",
"filename": "macd.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6007,
"license": "MIT",
"license_type": "permissive",
"path": "/code/macd.c",
"provenance": "stackv2-0112.json.gz:1832",
"repo_name": "trevor5gs/AlgorithmicTradingParallel",
"revision_date": "2015-03-09T19:40:49",
"revision_id": "c50edd4ab1e239a67769658434e46d019d7d4c9b",
"snapshot_id": "1304d10cb13f4f80fd8834675fa37b4e133c5565",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/trevor5gs/AlgorithmicTradingParallel/c50edd4ab1e239a67769658434e46d019d7d4c9b/code/macd.c",
"visit_date": "2021-01-21T08:24:18.971047"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include "common.h"
#include "structs.h"
#include "macd.h"
void print_sma( stock_moving_average_p sma, int start, int num, string debug) {
for(int i=start; i<start+num; i++)
printf("%s Value[i] = %lf\n", debug, i, sma->ma[i].value);
printf("%s done", debug);
}
stock_moving_average_p calculate_moving_avg_from_sma( stock_moving_average_p sma, int period) {
double sum = 0;
int i = 0, j = 0;
int n = sma->size;
unsigned int num_points = sma->size - period + 1;
double alpha = ((double)2 / (double)(period + 1));
#ifdef DEBUG
printf("At line number %d in file %s\n", __LINE__, __FILE__);
#endif
if( num_points <= 0 ) {
return NULL;
}
stock_moving_average_p result = (stock_moving_average_p) emalloc(sizeof(stock_moving_average));
result->period = period;
result->ma = (moving_average_p) emalloc(sizeof(moving_average) * num_points);
strcpy(result->ticker, sma->ticker);
for( i = 0; i < period && i < n; i++) {
sum += sma->ma[i].value;
}
strcpy(result->ma[j].date, sma->ma[i-1].date);
result->ma[j++].value = sum / (double)period;
for( ; i < n; i++, j++ ) {
strcpy(result->ma[j].date, sma->ma[i].date);
result->ma[j].value = ((sma->ma[i].value - result->ma[j-1].value)
* alpha) + result->ma[j-1].value;
}
result->size = j;
#ifdef DEBUG
printf("At line number %d in file %s\n", __LINE__, __FILE__);
printf("Predicted size = %d\tActual Size = %d\n", num_points, j);
#endif
return result;
}
stock_moving_average_p calculate_moving_average( stock_p s, int period ) {
double sum = 0;
int i = 0, j = 0;
int n = s->size;
unsigned int num_points = s->size - period ;
double alpha = ((double)2 / (double)(period + 1));
#ifdef DEBUG
printf("At line number %d in file %s\n", __LINE__, __FILE__);
#endif
if( num_points <= 0 ) {
return NULL;
}
stock_moving_average_p result = (stock_moving_average_p) emalloc(sizeof(stock_moving_average));
result->period = period;
result->ma = (moving_average_p) emalloc(sizeof(moving_average) * num_points);
strcpy(result->ticker, s->ticker);
for( i = n - 1; i > (n-1-period); i--) {
sum += s->entries[i].close;
}
strcpy(result->ma[j].date, s->entries[i].date);
result->ma[j++].value = sum / (double)period;
for( ; i > 0; i--, j++ ) {
strcpy(result->ma[j].date, s->entries[i-1].date);
result->ma[j].value = ((s->entries[i-1].close - result->ma[j-1].value)
* alpha) + result->ma[j-1].value;
}
result->size = j;
#ifdef DEBUG
printf("At line number %d in file %s\n", __LINE__, __FILE__);
printf("Predicted size = %d\tActual Size = %d\n", num_points, j);
#endif
return result;
}
stock_moving_average_p subtract_sma( stock_moving_average_p sma1, stock_moving_average_p sma2 ) {
#ifdef DEBUG
printf("At line number %d in file %s\n", __LINE__, __FILE__);
#endif
if( strcmp(sma1->ticker, sma2->ticker) != 0 ) {
fprintf(stderr, "Incompatible tickers used in subtraction\n");
return NULL;
}
#ifdef DEBUG
printf("At line number %d in file %s\n", __LINE__, __FILE__);
#endif
stock_moving_average_p result_sma = (stock_moving_average_p) emalloc(sizeof(stock_moving_average));
int num_points = sma1->size<sma2->size ? sma1->size : sma2->size;
moving_average_p ma1 = sma1->ma;
moving_average_p ma2 = sma2->ma;
result_sma->period = abs( sma1->period - sma2->period );
result_sma->size = num_points;
#ifdef DEBUG
printf("At line number %d in file %s\n", __LINE__, __FILE__);
printf("%d\n", num_points);
#endif
result_sma->ma = (moving_average_p) emalloc(sizeof(moving_average) * num_points);
#ifdef DEBUG
printf("At line number %d in file %s\n", __LINE__, __FILE__);
#endif
strcpy(result_sma->ticker, sma1->ticker);
while( strcmp(ma1->date, ma2->date) > 0 ) {
ma1++;
}
while( strcmp(ma2->date, ma1->date) > 0 ) {
ma2++;
}
for( int i=0; i<num_points; i++) {
strcpy(result_sma->ma[i].date, sma1->ma[i].date);
result_sma->ma[i].value = sma1->ma[i].value - sma2->ma[i].value;
}
return result_sma;
}
void sma_to_file( string path, stock_moving_average_p sma, stock_p s) {
char filename[100];
int p = sma->period;
int n = s->size;
#ifdef DEBUG
printf("At line number %d in file %s\n", __LINE__, __FILE__);
#endif
if( sma == NULL )
return;
snprintf(filename, 100,"%s/%s.%d.ema", path, sma->ticker, sma->period);
FILE *outfile = fopen(filename, "w");
if( NULL == outfile ) {
fprintf(stderr, "Unable to open file for writing\n");
return;
}
if( s != NULL ) {
fprintf(outfile, "Date,StockValue,MovingAverage\n");
for( int i=sma->size - 1; i > 0 ; i--)
fprintf(outfile, "%s,%f,%f\n", sma->ma[i].date, s->entries[n-1-p-i].close,
sma->ma[i].value);
} else {
fprintf(outfile, "Date,MovingAverage\n");
for( int i=sma->size - 1; i > 0 ; i--)
fprintf(outfile, "%s,%f\n", sma->ma[i].date, s->entries[i+p].close);
for( int i=0; i < sma->size; i++)
fprintf(outfile, "%s,%f\n", sma->ma[i].date, sma->ma[i].value);
}
fclose(outfile);
#ifdef DEBUG
printf("At line number %d in file %s\n", __LINE__, __FILE__);
#endif
}
void sort_ascending_date( stock_moving_average_p sma ) {
if( strcmp(sma->ma[0].date, sma->ma[1].date) > 0 ) {
moving_average_p new_ma = (moving_average_p) emalloc( sizeof(moving_average) * sma->size);
int i=0, j=sma->size - 1;
for(; i<sma->size; i++, j--) {
strcpy(new_ma[j].date, sma->ma[i].date);
new_ma[j].value = sma->ma[i].value;
}
free(sma->ma);
sma->ma = new_ma;
}
}
| 2.640625 | 3 |
2024-11-18T21:15:35.884122+00:00 | 2021-10-12T14:59:02 | a8ca20af134ce4eabbaac6fd5290af59a0b4d847 | {
"blob_id": "a8ca20af134ce4eabbaac6fd5290af59a0b4d847",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-12T14:59:02",
"content_id": "2071e4da8d0f6f040009aec419038f2f58f48f2e",
"detected_licenses": [
"MIT"
],
"directory_id": "af9ecd36a89c6236640fa7333f3aef20cda420f1",
"extension": "c",
"filename": "queue.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 148581577,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3303,
"license": "MIT",
"license_type": "permissive",
"path": "/tool/queue.c",
"provenance": "stackv2-0112.json.gz:1961",
"repo_name": "poyichou/algorithm_note",
"revision_date": "2021-10-12T14:59:02",
"revision_id": "faf3bcecb594fe9e062bb9c177ae8c62c63b19b6",
"snapshot_id": "91970a13c3986fd75e838d84b7ee95a06ce1d113",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/poyichou/algorithm_note/faf3bcecb594fe9e062bb9c177ae8c62c63b19b6/tool/queue.c",
"visit_date": "2021-10-14T06:54:28.705915"
} | stackv2 | #include "queue.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
/**
* This queue is implemented with a linked list of queue_nodes.
*/
typedef struct queue_node {
void *data;
struct queue_node *next;
} queue_node;
struct queue {
/* queue_node pointers to the head and tail of the queue */
queue_node *head, *tail;
/* The number of elements in the queue */
ssize_t size;
/**
* The maximum number of elements the queue can hold.
* max_size is non-positive if the queue does not have a max size.
*/
ssize_t max_size;
/* Mutex and Condition Variable for thread-safety */
pthread_cond_t cv;
pthread_mutex_t m;
};
ssize_t queue_size(queue* this) {
ssize_t size;
pthread_mutex_lock(&this->m);
size = this->size;
pthread_mutex_unlock(&this->m);
return size;
}
queue *queue_create(ssize_t max_size) {
queue *result = malloc(sizeof(queue));
result->size = 0;
result->max_size = max_size;
result->head = NULL;
result->tail = NULL;
pthread_mutex_init(&result->m, NULL);
pthread_cond_init(&result->cv, NULL);
return result;
}
void queue_destroy(queue *this) {
if(this->head != NULL){
queue_node *node, *del;
node = this->head->next;
while(node != this->head){
del = node;
node = node->next;
//free(del->data);
free(del);
}
//free(this->head->data);
free(this->head);
}
free(this);
}
void queue_push(queue *this, void *data) {
pthread_mutex_lock(&this->m);
/*
* wrap pthread_cond_wait() in while loop instead of if-condition since
* pthread_cond_wait() might wake up resulted from certain wake-up signal on multi-cpu systems
* */
while(this->max_size > 0 && this->size >= this->max_size){
/*
* similar actions to pthread_cond_wait():
* while(1) {
* if (singaled) {
* break;
* } else {
* pthread_mutex_unlock(m);
* sleep();
* pthread_mutex_lock(m);
* }
* }
* or
* pthread_mutex_unlock(m);
* sleep_until_signaled();
* pthread_mutex_lock(m);
*
* */
pthread_cond_wait(&this->cv, &this->m);
if(this->max_size > 0 && this->size < this->max_size){
pthread_cond_signal(&this->cv);
}
}
if(this->tail == NULL && this->head == NULL){
this->tail = malloc(sizeof(queue_node));
this->tail->next = this->tail;
this->head = this->tail;
}else{
queue_node *new = malloc(sizeof(queue_node));
new->next = this->tail->next;
this->tail->next = new;
this->tail = this->tail->next;
}
this->tail->data = data;
this->size++;
if(this->size == 1){
/*
* wake an arbitrary thread up, see also pthread_cond_broadcast()
* */
pthread_cond_signal(&this->cv);
}
pthread_mutex_unlock(&this->m);
}
void *queue_pull(queue *this) {
pthread_mutex_lock(&this->m);
while(this->size < 1){
pthread_cond_wait(&this->cv, &this->m);
if(this->size >= 1){
pthread_cond_signal(&this->cv);
}
}
void *result = this->head->data;
queue_node *del = this->head;
if(this->head->next == this->head){//last one
this->head = NULL;
this->tail = this->head;
}else{
this->head = this->head->next;
this->tail->next = this->head;
}
free(del);
this->size--;
if(this->max_size > 0 && this->size == this->max_size - 1){
pthread_cond_signal(&this->cv);
}
pthread_mutex_unlock(&this->m);
return result;
}
| 3.234375 | 3 |
2024-11-18T21:15:37.634779+00:00 | 2023-09-02T14:55:31 | 35114fc4c54e5aadfb0596db8278436bb64bb56d | {
"blob_id": "35114fc4c54e5aadfb0596db8278436bb64bb56d",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-02T14:55:31",
"content_id": "3c1e9b35ae1ed7303a2358b06512f1b7f6d59f48",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "8838eb997879add5759b6dfb23f9a646464e53ca",
"extension": "h",
"filename": "siginfoq_stub.h",
"fork_events_count": 325,
"gha_created_at": "2015-03-29T15:27:48",
"gha_event_created_at": "2023-09-14T16:58:34",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 33078138,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 666,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/kernel/thread/signal/siginfoq_stub.h",
"provenance": "stackv2-0112.json.gz:3504",
"repo_name": "embox/embox",
"revision_date": "2023-09-02T14:55:31",
"revision_id": "98e3c06e33f3fdac10a29c069c20775568e0a6d1",
"snapshot_id": "d6aacec876978522f01cdc4b8de37a668c6f4c80",
"src_encoding": "UTF-8",
"star_events_count": 1087,
"url": "https://raw.githubusercontent.com/embox/embox/98e3c06e33f3fdac10a29c069c20775568e0a6d1/src/kernel/thread/signal/siginfoq_stub.h",
"visit_date": "2023-09-04T03:02:20.165042"
} | stackv2 | /**
* @file
* @brief Stubs for no signal support.
*
* @date 07.10.2013
* @author Eldar Abusalimov
*/
#ifndef KERNEL_THREAD_SIGRT_H_
#define KERNEL_THREAD_SIGRT_H_
#include <errno.h>
#include <signal.h>
struct siginfoq { }; /* stub */
static inline struct siginfoq *siginfoq_init(struct siginfoq *infoq) {
return infoq;
}
static inline int siginfoq_enqueue(struct siginfoq *infoq, int sig,
const siginfo_t *info) {
(void)infoq; (void)sig; (void)info;
return -ENOSYS;
}
static inline int siginfoq_dequeue(struct siginfoq *infoq, int sig, siginfo_t *info) {
(void)infoq; (void)sig; (void)info;
return -ENOSYS;
}
#endif /* KERNEL_THREAD_SIGRT_H_ */
| 2.234375 | 2 |
2024-11-18T21:15:39.104995+00:00 | 2019-02-19T14:29:04 | 25b51d1233cd7173fe17a281ed12008305605127 | {
"blob_id": "25b51d1233cd7173fe17a281ed12008305605127",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-19T14:29:04",
"content_id": "8d1676e2a679653f3e5c20a719a3dddfb0663231",
"detected_licenses": [],
"directory_id": "f9ca03b253a24ecd8f40ef824860ba81f88fd8a8",
"extension": "c",
"filename": "test_gauge.c",
"fork_events_count": 0,
"gha_created_at": "2019-02-19T14:20:39",
"gha_event_created_at": "2019-02-19T14:20:39",
"gha_language": null,
"gha_license_id": "BSD-3-Clause",
"github_id": 171486923,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1231,
"license": "",
"license_type": "permissive",
"path": "/tests/test_gauge.c",
"provenance": "stackv2-0112.json.gz:4019",
"repo_name": "anatolijd/statsite",
"revision_date": "2019-02-19T14:29:04",
"revision_id": "9fee488f8024187007faa30c0fa4e43083d8ea4d",
"snapshot_id": "54e9ca52922e4d47cf79bc9c1374ffe1e2267b23",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/anatolijd/statsite/9fee488f8024187007faa30c0fa4e43083d8ea4d/tests/test_gauge.c",
"visit_date": "2020-04-23T22:00:26.726355"
} | stackv2 | #include <check.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <math.h>
#include "gauge.h"
START_TEST(test_gauge_init)
{
gauge_t g;
int res = init_gauge(&g);
fail_unless(res == 0);
}
END_TEST
START_TEST(test_gauge_init_add)
{
gauge_t g;
int res = init_gauge(&g);
fail_unless(res == 0);
fail_unless(gauge_add_sample(&g, 100, false) == 0);
fail_unless(gauge_count(&g) == 1);
fail_unless(gauge_sum(&g) == 100);
fail_unless(gauge_value(&g) == 100);
fail_unless(gauge_mean(&g) == 100);
fail_unless(gauge_min(&g) == 100);
fail_unless(gauge_max(&g) == 100);
}
END_TEST
START_TEST(test_gauge_add_loop)
{
gauge_t g;
int res = init_gauge(&g);
fail_unless(res == 0);
fail_unless(gauge_add_sample(&g, 1, false) == 0);
for (int i=2; i<=100; i++)
fail_unless(gauge_add_sample(&g, i, true) == 0);
fail_unless(gauge_count(&g) == 100);
fail_unless(gauge_sum(&g) == 5050);
fail_unless(gauge_mean(&g) == 50.5);
fail_unless(gauge_value(&g) == 5050);
fail_unless(gauge_min(&g) == 2);
fail_unless(gauge_max(&g) == 100);
}
END_TEST
| 2.28125 | 2 |
2024-11-18T21:15:39.210781+00:00 | 2021-10-19T19:17:15 | 8e5514fbae377550a00e35ffed37208063f80979 | {
"blob_id": "8e5514fbae377550a00e35ffed37208063f80979",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-19T19:17:15",
"content_id": "d9acb7bf63ddd1f430b0574e1f98bfe1966c9778",
"detected_licenses": [
"MIT"
],
"directory_id": "e7b1c6f48537154a7e2ca62524114b6d74b7d7a5",
"extension": "h",
"filename": "ccw.h",
"fork_events_count": 4,
"gha_created_at": "2017-08-30T11:45:48",
"gha_event_created_at": "2020-01-22T20:41:29",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 101874751,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1058,
"license": "MIT",
"license_type": "permissive",
"path": "/include/lib/ccw.h",
"provenance": "stackv2-0112.json.gz:4153",
"repo_name": "openSUSE/s390-tools",
"revision_date": "2021-10-19T19:17:15",
"revision_id": "523b13c88f8cc8839d8415f2b1abf8bf65fe863b",
"snapshot_id": "abc4408446f00334c8fff5966f950d77ecab681e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/openSUSE/s390-tools/523b13c88f8cc8839d8415f2b1abf8bf65fe863b/include/lib/ccw.h",
"visit_date": "2023-08-24T11:28:47.545886"
} | stackv2 | /*
* ccw - Channel Command Word library (traditional I/O)
*
* Copyright 2017 IBM Corp.
*
* s390-tools is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIB_CCW_H
#define LIB_CCW_H
#include <stdbool.h>
#include "lib/zt_common.h"
/**
* ccw_devid - CCW device ID
*/
struct ccw_devid {
/** Channel Subsystem ID */
unsigned int cssid:8;
/** Subchannel set ID */
unsigned int ssid:8;
/** Device number */
unsigned int devno:16;
} __packed;
/**
* Initialize ccw_devid structure
*
* @param[in,out] devid Pointer to ccw_devid structure to be initialized
* @param[in] cssid Channel Subsystem ID
* @param[in] ssid Subchannel set ID
* @param[in] devno Device number
*/
static inline void ccw_devid_init(struct ccw_devid *devid,
unsigned int cssid, unsigned int ssid,
unsigned int devno)
{
devid->cssid = cssid;
devid->ssid = ssid;
devid->devno = devno;
}
bool ccw_parse_str(struct ccw_devid *devid, const char *id);
#endif
| 2.125 | 2 |
2024-11-18T21:15:39.419569+00:00 | 2017-04-29T20:57:47 | 785cfd97ed14882b077e0e1bb70e5b750b6671a6 | {
"blob_id": "785cfd97ed14882b077e0e1bb70e5b750b6671a6",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-29T20:57:47",
"content_id": "0994700e2c80868c2f27e231b2f4cb070f58d3f6",
"detected_licenses": [
"MIT"
],
"directory_id": "602f8b7e024ef374bac086fd6bf8130d2d2a1102",
"extension": "c",
"filename": "helpers.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4327,
"license": "MIT",
"license_type": "permissive",
"path": "/helpers.c",
"provenance": "stackv2-0112.json.gz:4538",
"repo_name": "jsavage/MOBOARD",
"revision_date": "2017-04-29T20:57:47",
"revision_id": "211d5062a41cd3f450b57efeaa270103d061e307",
"snapshot_id": "adced25651863ca2dc161d6026480e7bed5cd5fc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jsavage/MOBOARD/211d5062a41cd3f450b57efeaa270103d061e307/helpers.c",
"visit_date": "2021-05-10T14:48:50.517801"
} | stackv2 | /* Helper functions for the program */
#define PI (22.0/7.0)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "helpers.h"
double findSpeed(double dist, int time) {
dist = dist / 2025.372;
double t = ((double) time) / 60.0;
return dist / t;
}
double findDist(double speed, int time) {
return speed * time;
}
int findTime(double dist, double speed) {
return ceil(dist / speed);
}
double distance(vector_t *vector) {
return ceil(sqrt(pow(vector->x, 2) + pow(vector->y, 2)));
}
vector_t* unit_vec(vector_t *vector) {
vector_t *ans = malloc(sizeof(vector_t));
double mag = distance(vector);
ans->x = (vector->x) / mag;
ans->y = (vector->y) / mag;
return ans;
}
int cpa(ship_t *own_ship, contact_t *contact1, contact_t *contact2, int deltat) {
vector_t *ship_vec = malloc(sizeof(vector_t));
vector_t *contact_vec = malloc(sizeof(vector_t));
ship_t *return_ship = malloc(sizeof(ship_t));
double owncourseedit = own_ship->course + 90.0;
if (owncourseedit >= 360.0) { owncourseedit -= 360.0; }
ship_vec->x = (own_ship->speed / 5.0) * cos(owncourseedit * (PI / 180.0));
ship_vec->y = (own_ship->speed / 5.0) * sin(owncourseedit * (PI / 180.0));
double c1bearingedit = contact1->bearing + 90.0;
if (c1bearingedit >= 360.0) { c1bearingedit -= 360.0; }
double start_x = (contact1->range / 1000.0) * cos(c1bearingedit * (PI / 180.0));
double start_y = (contact1->range / 1000.0) * sin(c1bearingedit * (PI / 180.0));
double c2bearingedit = contact2->bearing + 90.0;
if (c2bearingedit >= 360.0) { c2bearingedit -= 360.0; }
double end_x = (contact2->range / 1000.0) * cos(c2bearingedit * (PI / 180.0));
double end_y = (contact2->range / 1000.0) * sin(c2bearingedit * (PI / 180.0));
contact_vec->x = end_x - start_x;
contact_vec->y = end_y - start_y;
return_ship = find_true(ship_vec, contact_vec, deltat);
printf("True speed: %lf\n", return_ship->speed);
printf("True course: %lf\n", return_ship->course);
double rel_speed = findSpeed(distance(contact_vec), deltat);
free(ship_vec);
free(contact_vec);
return 0;
}
int stationing(ship_t *own_ship, contact_t *contact1, contact_t *contact2,
int station_range, int station_bearing, int min_dist) {
//TODO
return 0;
}
int wind() {
//TODO
return 0;
}
ship_t* inputtoship(char *buffer) {
ship_t *own_ship = malloc(sizeof(ship_t));
printf("Ship course: ");
fgets(buffer, BUFF_SIZE, stdin);
own_ship->course = strtod(buffer, NULL);
printf("Ship speed: ");
fgets(buffer, BUFF_SIZE, stdin);
own_ship->speed = strtod(buffer, NULL);
return own_ship;
}
contact_t* inputtocontact(char* buffer) {
contact_t *contact = malloc(sizeof(contact_t));
printf("Time: ");
fgets(buffer, BUFF_SIZE, stdin);
contact->time = strtol(buffer, NULL, 10);
printf("Contact range: ");
fgets(buffer, BUFF_SIZE, stdin);
contact->range = strtod(buffer, NULL);
printf("Contact bearing: ");
fgets(buffer, BUFF_SIZE, stdin);
contact->bearing = strtod(buffer, NULL);
return contact;
}
ship_t* find_true(vector_t *own_ship, vector_t *contact, int deltat) {
ship_t *true_ship = malloc(sizeof(ship_t));
double rel_speed = findSpeed(distance(contact) * 1000.0, deltat);
printf("Relative Speed: %lf\n", rel_speed);
vector_t *relative = unit_vec(contact);
relative->x = relative->x * (rel_speed / 5);
relative->y = relative->y * (rel_speed / 5);
double true_x = own_ship->x + relative->x;
double true_y = own_ship->y + relative->y;
true_ship->speed = 5.0 * sqrt(pow(true_x, 2.0) + pow(true_y, 2.0));
double bearing_radians = atan(true_y / true_x);
double bearing_degrees = bearing_radians * (180.0 / PI);
double bdedited = bearing_degrees - 90.0;
if (bdedited < 0) { bdedited += 360.0; }
true_ship->course = bdedited;
return true_ship;
}
int timepassed(int time1, int time2) {
int t1hour = time1 / 100;
int t1min = time1 % 100;
time1 = (t1hour * 60) + t1min;
int t2hour = time2 / 100;
int t2min = time2 % 100;
time2 = (t2hour * 60) + t2min;
return time2 - time1;
}
| 2.890625 | 3 |
2024-11-18T21:15:39.655168+00:00 | 2014-09-05T09:11:07 | 6e4dc06c13dfac14ad278bd815aae0fc20f89ac9 | {
"blob_id": "6e4dc06c13dfac14ad278bd815aae0fc20f89ac9",
"branch_name": "refs/heads/master",
"committer_date": "2014-09-05T09:11:07",
"content_id": "af5098c32e0a248bc3c87885ff669666bbc332a4",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "7657bb5a0d28917a7834c05c58bd3199c9ea7461",
"extension": "c",
"filename": "pubapi.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2905278,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1839,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/bridge/sw/lib/pubapi/src/pubapi.c",
"provenance": "stackv2-0112.json.gz:4667",
"repo_name": "koanlogic/webthings",
"revision_date": "2014-09-05T09:11:07",
"revision_id": "4c495c5f0470db7be75e893e1782725ece484f13",
"snapshot_id": "deb60a41d38ff64a9ef2fb6eb2f2fa4bbb02ee68",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/koanlogic/webthings/4c495c5f0470db7be75e893e1782725ece484f13/bridge/sw/lib/pubapi/src/pubapi.c",
"visit_date": "2016-09-08T01:26:57.712737"
} | stackv2 | #include <u/libu.h>
#include <pubapi.h>
#include <svc.h>
#include "storage_drv.h"
struct pubapi_s
{
struct storage_drv *drv;
void *db;
};
int pubapi_last_update(pubapi_t *pa, time_t *ptimestamp)
{
char *value = NULL;
dbg_err_if(pa->drv->meta_get(pa->db, "last_update", &value));
dbg_err_if(value == NULL);
*ptimestamp = atoi(value);
u_free(value);
return 0;
err:
return ~0;
}
int pubapi_fetch_services(pubapi_t *pa, svc_cb_t fun, void *arg)
{
dbg_err_if(pa->drv->fetch_services(pa->db, fun, arg));
return 0;
err:
return ~0;
}
int pubapi_fetch_services_by_attr(pubapi_t *pa, svc_cb_t fun, void *arg,
const char *name, const char *sub_str)
{
dbg_err_if(pa->drv->fetch_services_by_attr(pa->db, fun, arg, name,
sub_str));
return 0;
err:
return ~0;
}
int pubapi_close(pubapi_t *pa)
{
dbg_err_if(pa == NULL);
u_free(pa);
return 0;
err:
return ~0;
}
int pubapi_connect(u_config_t *c, pubapi_t **ppa)
{
pubapi_t *pa = NULL;
u_config_t *db_conf;
const char *database, *db_type;
pa = u_zalloc(sizeof(pubapi_t));
dbg_err_if(pa == NULL);
database = u_config_get_subkey_value(c, "database");
crit_err_ifm(database == NULL, "database config key not found");
crit_err_ifm(u_config_get_subkey(c, database, &db_conf),
"database '%s' config key not found", database);
db_type = u_config_get_subkey_value(db_conf, "type");
crit_err_ifm(db_type == NULL, "db type key not found");
if(strcasecmp(db_type, "sqlite") == 0)
{
pa->drv = &drv_sqlite3;
} else
crit_err("unknown db type '%s'", db_type);
u_info("db type: %s", db_type);
dbg_err_if(pa->drv->connect(db_conf, &pa->db));
*ppa = pa;
return 0;
err:
pubapi_close(pa);
return ~0;
}
| 2.21875 | 2 |
2024-11-18T21:15:39.920670+00:00 | 2018-02-22T15:29:51 | 0776bb8c866495ff88c892acb43740f02a3f8b14 | {
"blob_id": "0776bb8c866495ff88c892acb43740f02a3f8b14",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-22T15:29:51",
"content_id": "ca05941bb852e688244c73161abb86cbe5b43db3",
"detected_licenses": [
"MIT"
],
"directory_id": "18df0cd27932dd42331fb66f38dd66e9871c3149",
"extension": "c",
"filename": "client.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4880,
"license": "MIT",
"license_type": "permissive",
"path": "/midterm/P4/client.c",
"provenance": "stackv2-0112.json.gz:5052",
"repo_name": "plChao/Intro-To-Network-Programming",
"revision_date": "2018-02-22T15:29:51",
"revision_id": "15b03a4f269cac671a174b9acb539b2e4e49b982",
"snapshot_id": "883b1fe4df4625e65fa26660d0cf512978c6c619",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/plChao/Intro-To-Network-Programming/15b03a4f269cac671a174b9acb539b2e4e49b982/midterm/P4/client.c",
"visit_date": "2020-09-27T17:25:17.383963"
} | stackv2 | #include "chat.h"
int main(int argc, char **argv)
{
if(argc < 3)
{
printf("Usage: ./client <Name> <myport> [port].\n");
exit(0);
}
char my_name[50];
strcpy(my_name, argv[1]);
int listenfd;
struct sockaddr_in server_addr;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[2]));
bind(listenfd, (SA *) &server_addr, sizeof(server_addr));
if(listen(listenfd, LISTENQ) == -1)
{
perror("listen error");
exit(-1);
}
int connfd;
struct sockaddr_in client_addr;
socklen_t client_len;
struct Friend con_cli[MAXCLIENT];
int i, j;
for(i = 0; i < MAXCLIENT; i++)
{
memset(con_cli[i].name, 0, 50);
con_cli[i].fd = -1;
con_cli[i].get_name = 0;
}
fd_set r_set, all_set;
int maxfd = listenfd;
FD_ZERO(&all_set);
FD_SET(listenfd, &all_set);
//connect myself
connfd = socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_port = htons(atoi(argv[2]));
inet_pton(AF_INET, "0.0.0.0", &server_addr.sin_addr);
if(connect(connfd, (SA *) &server_addr, sizeof(server_addr)) < 0)
{
perror("connect error");
exit(-1);
}
con_cli[0].fd = connfd;
con_cli[0].get_name = 1;
strcpy(con_cli[0].name, my_name);
FD_SET(connfd, &all_set);
if(connfd > maxfd) maxfd = connfd;
//connect to others
for(j = 0, i = 3; j < MAXCLIENT && i < argc; j++)
{
if(con_cli[j].fd >= 0) continue;
connfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[i++]));
inet_pton(AF_INET, "0.0.0.0", &server_addr.sin_addr);
if(connect(connfd, (SA *) &server_addr, sizeof(server_addr)) < 0)
{
perror("connect error");
exit(-1);
}
con_cli[j].fd = connfd;
FD_SET(connfd, &all_set);
if(connfd > maxfd) maxfd = connfd;
}
FD_SET(fileno(stdin), &all_set);
while(1)
{
r_set = all_set;
int num_of_ready;
if((num_of_ready = select(maxfd + 1, &r_set, NULL, NULL, NULL)) == -1)
{
perror("select error");
exit(-1);
}
//new connect
if(FD_ISSET(listenfd, &r_set))
{
///fprintf(stdout, "ddd\n");
client_len = sizeof(client_addr);
if((connfd = accept(listenfd, (SA *) &client_addr, &client_len)) == -1)
{
perror("Accept error");
exit(-1);
}
for(i = 0; i < MAXCLIENT; i++)
{
if(con_cli[i].fd < 0)
{
con_cli[i].fd = connfd;
char buf[100];
snprintf(buf, 100, "name %s\n", my_name);
write(connfd, buf, strlen(buf));
break;
}
}
if(i == MAXCLIENT)
fprintf(stdout, "too many client.\n");
FD_SET(connfd, &all_set);
if(connfd > maxfd) maxfd = connfd;
}
//recv msg
for(i = 0; i < MAXCLIENT; i++)
{
if(con_cli[i].fd < 0) continue;
int ter = 0;
if(FD_ISSET(con_cli[i].fd, &r_set))
{
char cmd[MAXLINE];
int n = read(con_cli[i].fd, cmd, MAXLINE);
if(n <= 0)
{
close(con_cli[i].fd);
FD_CLR(con_cli[i].fd, &all_set);
continue;
}
cmd[n] = '\0';
char tmp[100];
strcpy(tmp, cmd);
char *c = strtok(tmp, TOK_DEM);
if(strcmp(c, "name") == 0 && !con_cli[i].get_name)
{
char *name = strtok(NULL, TOK_DEM);
strcpy(con_cli[i].name, name);
con_cli[i].get_name = 1;
char buf[100];
snprintf(buf, 100, "name %s\n", my_name);
write(con_cli[i].fd, buf, strlen(buf));
}
else
{
if(strcmp(c, "name") != 0)
fputs(cmd, stdout);
}
}
}
//send msg
if(FD_ISSET(fileno(stdin), &r_set))
{
char input[MAXLINE];
if(fgets(input, MAXLINE, stdin) == NULL) break;
int ter = chat(my_name, con_cli, input);
if(ter == 1) exit(0);
}
}
return 0;
} | 2.515625 | 3 |
2024-11-18T21:15:39.987163+00:00 | 2016-05-10T05:09:16 | b960153e743e7289bde31a37d97a69b38cdac414 | {
"blob_id": "b960153e743e7289bde31a37d97a69b38cdac414",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-10T05:09:16",
"content_id": "eeecab48d5e875349fbacd687a2bf6077f5603e0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2c06da6b1b3c88923c47f96db290a3ec1b300f45",
"extension": "c",
"filename": "init.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 49739222,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1464,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/msp430-dxl/init.c",
"provenance": "stackv2-0112.json.gz:5183",
"repo_name": "ASL-Robot/msp430-dxl",
"revision_date": "2016-05-10T05:09:16",
"revision_id": "aef008f5d22a5f5dcf0440c143fff95f0c524a33",
"snapshot_id": "a0c6916256e7dcb53ce275537cd5d01700ff2195",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ASL-Robot/msp430-dxl/aef008f5d22a5f5dcf0440c143fff95f0c524a33/msp430-dxl/init.c",
"visit_date": "2021-01-13T00:42:24.298160"
} | stackv2 | /*
* author: Brian Ruiz
* date: December 19, 2015
* school: George Mason University
*/
#include <msp430.h>
#include "dynamixel.h"
#include "init.h"
void msp_init(void)
{
WDTCTL = WDTPW | WDTHOLD;
CSCTL0_H = CSKEY_H;
CSCTL1 = DCORSEL | DCOFSEL_4;
CSCTL3 = DIVA_0 | DIVS__8 | DIVM__2;
CSCTL0_H = 0;
/* configure pins for SPI */
P1SEL0 |= (BIT4 | BIT5 | BIT6 | BIT7); // P1.6 = UCB0MOSI
P1SEL1 &= ~(BIT4 | BIT5 | BIT6 | BIT7); // P1.7 = UCB0MISO
// P1.5 = UCB0STE
// P1.4 = UCB0CLK
/* configure pins for UART */
P4SEL0 |= (BIT2 | BIT3); // P4.2 = UCA0TX
P4SEL1 &= ~(BIT2 | BIT3); // P4.3 = UCA0RX
P4REN |= (BIT3);
P4OUT |= (BIT3);
P3DIR |= BIT2; // P3.2 = DIRECTION
P3OUT |= BIT2; // claim the bus
PM5CTL0 &= ~LOCKLPM5;
/* set up SPI */
UCB0CTLW0 = UCSWRST;
UCB0CTLW0 |= UCMSB | UCMODE_2 | UCSYNC; // active low enable slave
UCB0CTLW0 &= ~UCSWRST;
/* set up UART */
UCA0CTLW0 = UCSWRST;
UCA0CTLW0 |= UCSSEL__SMCLK; // 1 MHz baud
UCA0BRW = 2;
UCA0MCTLW = 0;
UCA0CTLW0 &= ~UCSWRST;
}
void dynamixel_init(void)
{
// set_id(0xFE, 0x12);
// joint_mode(0x12);
//set_return(0x12, 1);
// torque_enable(0x16);
// torque_enable(0x12);
//factory_reset(0x16, 2);
//factory_reset(0x12, 2);
// led_on(0xFE);
// __delay_cycles(100000);
// led_off(0xFE);
//set_id(0xFE, 0x12);
//joint_mode(0x12);
__no_operation();
}
| 2.109375 | 2 |
2024-11-18T21:15:40.183242+00:00 | 2015-01-13T18:03:04 | 4366754d096abf0d51cd3e47debd974a8cc3298b | {
"blob_id": "4366754d096abf0d51cd3e47debd974a8cc3298b",
"branch_name": "refs/heads/master",
"committer_date": "2015-01-13T18:03:04",
"content_id": "2ca0e8aecc798d0349624b1c80a2a01ba266d590",
"detected_licenses": [
"MIT"
],
"directory_id": "764b08ab5e2e0241f502f119c4a31ee56cfd88a0",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 637,
"license": "MIT",
"license_type": "permissive",
"path": "/objdump/src/main.c",
"provenance": "stackv2-0112.json.gz:5440",
"repo_name": "yongyecc/nm-objdump",
"revision_date": "2015-01-13T18:03:04",
"revision_id": "3a98316f29265e2f8b1275f0df2e0f74a066226a",
"snapshot_id": "23c3ad4862d5d42bd925986cb1e1630a6f2a252c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yongyecc/nm-objdump/3a98316f29265e2f8b1275f0df2e0f74a066226a/objdump/src/main.c",
"visit_date": "2021-12-04T05:52:51.345614"
} | stackv2 | /*
** objdump.c for objdump in /home/mesure_a/workspace/c/nm-objdump/objdump
**
** Made by arnaud mesureur
** Login <mesure_a@epitech.net>
**
** Started on Sun Mar 13 09:43:24 2011 arnaud mesureur
** Last update Sun Mar 13 22:39:16 2011 arnaud mesureur
*/
#include <stdio.h>
#include <stdlib.h>
#include "objdump.h"
int main(int argc, char **argv)
{
int status;
int i;
if (argc <= 2)
return (objdump(argc == 1 ? DEFAULT_BIN : argv[1]));
status = EXIT_SUCCESS;
i = 1;
while (argc-- > 1)
{
printf("\n%s:\n\n", argv[i]);
if (objdump(argv[i++]) == 1)
status = EXIT_FAILURE;
}
return (status);
}
| 2.46875 | 2 |
2024-11-18T21:15:40.598675+00:00 | 2014-05-16T03:01:22 | ca0caee5738e9b047675b8f8a019471df90404bd | {
"blob_id": "ca0caee5738e9b047675b8f8a019471df90404bd",
"branch_name": "refs/heads/master",
"committer_date": "2014-05-16T03:01:22",
"content_id": "f053469712cbd5c14c210c59024fee8eccfffe39",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5a4267fd7df20cd5f1189f71702a440d47ed4b87",
"extension": "h",
"filename": "sfpr_time.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4399,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/install/include/sfpr_time.h",
"provenance": "stackv2-0112.json.gz:5698",
"repo_name": "husthenry/easygx",
"revision_date": "2014-05-16T03:01:22",
"revision_id": "dc0b8150ed7163e3c13d82a00ab408954d471788",
"snapshot_id": "c30ec17fc9dc799d31c442202b487f30b98a83c7",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/husthenry/easygx/dc0b8150ed7163e3c13d82a00ab408954d471788/install/include/sfpr_time.h",
"visit_date": "2021-04-15T07:25:29.902498"
} | stackv2 |
/**
*\file sfpr_time.h
*\brief SFPR库的时间模块
*\author 刘晓强
*\version 0.1.0
*\date 2012-02-15
*/
#ifndef SFPR_TIME_H
#define SFPR_TIME_H
#ifdef __cplusplus
extern "C" {
#endif
#include <time.h>
#if defined VXWORKS
#include <timers.h>
#elif defined WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#include "sfpr_global.h"
/**************************************************************************************************/
/**
*\defgroup time 时间模块
*
**************************************************************************************************/
/**************************************************************************************************/
/**
*\defgroup time_base 基本结构和函数
*\ingroup time
**************************************************************************************************/
/**
*\ingroup time_base
*\brief 时间描述
*/
typedef struct sfpr_time_s{
time_t sec;/**< 秒*/
sfpr_long_t usec;/**< 微秒*/
}sfpr_time_t;
/**
*\ingroup time_base
*\brief 格式化时间描述
*/
typedef struct sfpr_tm_s{
sfpr_int_t year;/**< 年*/
sfpr_int_t month;/**< 月*/
sfpr_int_t mday;/**< 日*/
sfpr_int_t wday;/**< 一周的第几天*/
sfpr_int_t hour;/**< 小时*/
sfpr_int_t min;/**< 分*/
sfpr_int_t sec;/**< 秒*/
sfpr_int_t msec;/**< 毫秒*/
}sfpr_tm_t;
/**
*\ingroup time_base
*\brief 获取当前时间
*\param[out] time 时间指针。
*\return 是否成功
*\retval 0 成功
*\retval <0 失败
*/
int sfpr_time_now(sfpr_time_t *time);
/**
*\ingroup time_base
*\brief 把当前时间格式化,转为本地时间
*\param[in] time 时间指针。
*\param[out] tm 格式化时间指针。
*\return 是否成功
*\retval 0 成功
*\retval <0 失败
*/
int sfpr_time_localtime(sfpr_time_t *time,sfpr_tm_t *tm);
/**
*\ingroup time_base
*\brief 把当前时间格式化,转为UTC时间
*\param[in] time 时间指针。
*\param[out] tm 格式化时间指针。
*\return 是否成功
*\retval 0 成功
*\retval <0 失败
*/
int sfpr_time_get_utctime(sfpr_time_t *time,sfpr_tm_t *tm);
/**
*\ingroup time_base
*\brief 把格式化的时间转化为秒数
*\param[in] tm 格式化时间指针。
*\param[out] time 时间指针。
*\return 是否成功
*\retval 0 成功
*\retval <0 失败
*/
int sfpr_time_mktime(sfpr_tm_t *tm,sfpr_time_t *time);
/**
*\ingroup time_base
*\brief 设置系统时间
*\param[in] tm 格式化时间指针。
*\return 是否成功
*\retval 0 成功
*\retval <0 失败
*/
int sfpr_time_set(sfpr_tm_t *tm);
/**************************************************************************************************/
/**
*\defgroup time_bench 压力测试时间
*\ingroup time
**************************************************************************************************/
/**
*\ingroup time_bench
*\brief 压力测试时间描述
*/
typedef struct sfpr_bench_elapse_s{
sfpr_time_t start;/**< 开始时间*/
sfpr_time_t stop;/**< 结束时间*/
union{
sfpr_int_t _int;
sfpr_float_t _float;
}etime;/**< 流逝时间(毫秒)*/
union{
sfpr_uint32_t _uint32;
sfpr_float_t _float;
}bench;/**< 压力大小*/
sfpr_float_t op_per_ms;/**< 每毫秒操作数*/
sfpr_float_t ms_per_op;/**< 每个操作花费的时间(毫秒)*/
}sfpr_bench_elapse_t;
/**
*\ingroup time_bench
*\brief 开始压力测试
*\param[in] bench 压力测试时间结构指针。
*\return 是否成功
*\retval 0 成功
*\retval <0 失败
*/
sfpr_int_t sfpr_bench_start(sfpr_bench_elapse_t *bench);
/**
*\ingroup time_bench
*\brief 结束压力测试
*\param[in] bench 压力测试时间结构指针。
*\param[in] bench_count 当前压力大小。
*\return 是否成功
*\retval 0 成功
*\retval <0 失败
*/
sfpr_int_t sfpr_bench_stop(sfpr_bench_elapse_t *bench,sfpr_uint32_t bench_count);
/**
*\ingroup time_bench
*\brief 打印压力测试结果
*\param[in] bench 压力测试时间结构指针。
*\param[in] title 标题。
*\return 是否成功
*\retval 0 成功
*\retval <0 失败
*/
sfpr_int_t sfpr_bench_print(sfpr_bench_elapse_t *bench,char *title);
/**
*\ingroup time_base
*\brief 睡眠一段时间
*\param 睡眠的时间(毫秒)。
*\return 是否成功
*\retval 0 成功
*\retval <0 失败
*/
sfpr_int_t sfpr_time_msleep(int microseconds);
#ifdef __cplusplus
}
#endif
#endif
| 2.078125 | 2 |
2024-11-18T21:15:40.659411+00:00 | 2013-04-30T21:02:42 | 35e78f81b433f5d2aa54a22d7f17131f42041b88 | {
"blob_id": "35e78f81b433f5d2aa54a22d7f17131f42041b88",
"branch_name": "refs/heads/master",
"committer_date": "2013-04-30T21:02:42",
"content_id": "5206e339182be437120b6ec84272b272cd300f88",
"detected_licenses": [
"MIT"
],
"directory_id": "251abf3a137556878474a7e0a6a85c029248de0d",
"extension": "c",
"filename": "stringTools.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1141,
"license": "MIT",
"license_type": "permissive",
"path": "/src/stringTools.c",
"provenance": "stackv2-0112.json.gz:5828",
"repo_name": "davidsan/network-optimization",
"revision_date": "2013-04-30T21:02:42",
"revision_id": "e545e1e4c60dad371aa2f707e946b5c75519c257",
"snapshot_id": "a435244e879e6ae4ebb60dfb141300e44d5a536c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/davidsan/network-optimization/e545e1e4c60dad371aa2f707e946b5c75519c257/src/stringTools.c",
"visit_date": "2020-04-06T03:31:32.809986"
} | stackv2 | /**
* \file stringTools.c
* \brief Source des outils de manipulation des chaînes de caractères
* \author David San
*/
#include "stringTools.h"
int scanNbChain(char *string)
{
int res;
if (sscanf(string, "c NbChain: %d", &res) != 1) {
leverErreur("lecture NbChain (format incorrect)");
return -1;
}
return res;
}
int scanGamma(char *string)
{
int res;
if (sscanf(string, "c Gamma: %d", &res) != 1) {
leverErreur("lecture Gamma (format incorrect)");
return -1;
}
return res;
}
int scanNumero(char *string)
{
int res;
if (sscanf(string, "h %d ", &res) != 1) {
leverErreur("lecture numéro (format incorrect)");
return -1;
}
return res;
}
int scanNbNodes(char *string)
{
int res;
if (sscanf(string, "c NbNodes: %d", &res) != 1) {
leverErreur("lecture NbNodes (format incorrect)");
return -1;
}
return res;
}
int scanNbCables(char *string)
{
int res;
if (sscanf(string, "c NbCables: %d", &res) != 1) {
leverErreur("lecture NbCables (format incorrect)");
return -1;
}
return res;
}
int isComment(char *string)
{
return (string[0] == 'c');
}
| 2.6875 | 3 |
2024-11-18T21:15:40.811375+00:00 | 2020-05-08T00:32:18 | 7dd6540802be6f34bf31f297c96b5ccb97f67fb4 | {
"blob_id": "7dd6540802be6f34bf31f297c96b5ccb97f67fb4",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-08T00:32:18",
"content_id": "8e739a7d07368d0a0f370fac812a27e4b4a4402e",
"detected_licenses": [
"MIT"
],
"directory_id": "df0192933e300efd0a59f51d27295527d7d8865c",
"extension": "c",
"filename": "taflboard.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 261046306,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14291,
"license": "MIT",
"license_type": "permissive",
"path": "/src/taflboard.c",
"provenance": "stackv2-0112.json.gz:6086",
"repo_name": "ieuan-jones/tafl",
"revision_date": "2020-05-08T00:32:18",
"revision_id": "06d48291e08d59554d375bafb82251fe07ca1880",
"snapshot_id": "fef0ec15320d4f8cf7d4fbc7768bbdc0c58f99fd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ieuan-jones/tafl/06d48291e08d59554d375bafb82251fe07ca1880/src/taflboard.c",
"visit_date": "2022-06-14T05:34:05.828929"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "taflboard.h"
#include "taflutil.h"
uint8_t is_restricted_tile(uint8_t x, uint8_t y, uint8_t type) {
if(type == 3) return 0;
if(x == 0 && y == 0) return 1;
if(x == 0 && y == 10) return 1;
if(x == 10 && y == 0) return 1;
if(x == 10 && y == 10) return 1;
if(x == 5 && y == 5) return 1;
return 0;
}
uint8_t tile_has_takeable_piece(uint8_t x, uint8_t y, uint8_t type, struct State *state) {
// Does the tile have a piece that can be taken?
uint8_t checked_square = state->board[y][x];
if(checked_square != 0 && checked_square != 3 && type_to_side(checked_square) != type_to_side(type))
return 1;
return 0;
}
uint8_t tile_has_defender(uint8_t x, uint8_t y, uint8_t type, struct State *state) {
// Can tile can be used for taking?
uint8_t checked_square = type_to_side(state->board[y][x]);
if((checked_square != 0 && checked_square == type_to_side(type)) ||
is_restricted_tile(x, y, 1))
return 1;
return 0;
}
void add_piece(uint8_t x, uint8_t y, uint8_t type, struct State *state) {
state->board[y][x] = type;
switch (type) {
case 1:
state->white[state->white_count][0] = x;
state->white[state->white_count][1] = y;
state->white_count++;
break;
case 2:
state->black[state->black_count][0] = x;
state->black[state->black_count][1] = y;
state->black_count++;
break;
case 3:
state->king[0] = x;
state->king[1] = y;
break;
}
}
void remove_piece(uint8_t x, uint8_t y, uint8_t type, struct State *state) {
//printf("%d, %d, %d\n", x, y, type);
if(state->board[y][x] != type) printf("PIECE NOT ON BOARD!\n");
state->board[y][x] = 0;
int8_t index = -1;
switch (type) {
case 1:
for(int8_t i=0;i<state->white_count;i++) {
if(state->white[i][0] == x && state->white[i][1] == y) {
index = i;
break;
}
}
if(index != -1) {
state->white[index][0] = state->white[state->white_count-1][0];
state->white[index][1] = state->white[state->white_count-1][1];
state->white_count--;
}
break;
case 2:
for(int8_t i=0;i<state->black_count;i++) {
if(state->black[i][0] == x && state->black[i][1] == y) {
index = i;
break;
}
}
if(index != -1) {
state->black[index][0] = state->black[state->black_count-1][0];
state->black[index][1] = state->black[state->black_count-1][1];
state->black_count--;
}
break;
}
}
void move_piece(uint8_t from_x, uint8_t from_y, uint8_t to_x, uint8_t to_y, uint8_t type, struct State *state) {
state->board[from_y][from_x] = 0;
state->board[to_y][to_x] = type;
switch(type) {
case 1:
for(int8_t i=0;i<state->white_count;i++) {
if(state->white[i][0] == from_x && state->white[i][1] == from_y) {
state->white[i][0] = to_x;
state->white[i][1] = to_y;
}
}
break;
case 2:
for(int8_t i=0;i<state->black_count;i++) {
if(state->black[i][0] == from_x && state->black[i][1] == from_y) {
state->black[i][0] = to_x;
state->black[i][1] = to_y;
}
}
break;
case 3:
state->king[0] = to_x;
state->king[1] = to_y;
break;
}
}
uint8_t do_captures(uint8_t to_x, uint8_t to_y, uint8_t type, struct State *state) {
if(to_y > 1 && to_y < 9) {
if(tile_has_takeable_piece(to_x, to_y-1, type, state) && tile_has_defender(to_x, to_y-2, type, state)) {
remove_piece(to_x, to_y-1, opposite_side(type), state);
return 1;
}
if(tile_has_takeable_piece(to_x, to_y+1, type, state) && tile_has_defender(to_x, to_y+2, type, state)) {
remove_piece(to_x, to_y+1, opposite_side(type), state);
return 1;
}
}
if(to_x > 1 && to_x < 9) {
if(tile_has_takeable_piece(to_x-1, to_y, type, state) && tile_has_defender(to_x-2, to_y, type, state)) {
remove_piece(to_x-1, to_y, opposite_side(type), state);
return 1;
}
if(tile_has_takeable_piece(to_x+1, to_y, type, state) && tile_has_defender(to_x+2, to_y, type, state)) {
remove_piece(to_x+1, to_y, opposite_side(type), state);
return 1;
}
}
return 0;
}
int do_move(uint8_t piece, uint8_t move, struct MoveSet *moves, struct State *state) {
uint8_t from_x = 0;
uint8_t from_y = 0;
uint8_t type = 0;
uint8_t result = 0;
switch(state->turn) {
case 0:
if(piece < state->white_count) {
from_x = state->white[piece][0];
from_y = state->white[piece][1];
type = 1;
} else {
from_x = state->king[0];
from_y = state->king[1];
type = 3;
}
break;
case 1:
from_x = state->black[piece][0];
from_y = state->black[piece][1];
type = 2;
break;
}
move_piece(
from_x,
from_y,
moves->moves[piece][move][0],
moves->moves[piece][move][1],
type,
state
);
do_captures(
moves->moves[piece][move][0],
moves->moves[piece][move][1],
type,
state
);
result = state_of_game(state);
state->turn = 1-state->turn;
return result;
}
char state_of_game(struct State *state) {
// 0 - continue play
// 1 - draw
// 2 - white win
// 3 - black win
uint8_t k_x = state->king[0];
uint8_t k_y = state->king[1];
uint8_t w_pc = state->white_count;
if(state->black_count == 0) return 2;
// King escaped
if(k_x == 0 && k_y == 0) return 2;
if(k_x == 0 && k_y == 10) return 2;
if(k_x == 10 && k_y == 0) return 2;
if(k_x == 10 && k_y == 10) return 2;
// King surrounded
if(state->turn == 1 &&
((k_x > 0 && state->board[k_y][k_x-1] == 2) || (k_x == 6 && k_y == 5) || (w_pc == 0 && k_x == 0)) &&
((k_x < 10 && state->board[k_y][k_x+1] == 2) || (k_x == 4 && k_y == 5) || (w_pc == 0 && k_x == 10)) &&
((k_y > 0 && state->board[k_y-1][k_x] == 2) || (k_x == 5 && k_y == 6) || (w_pc == 0 && k_y == 0)) &&
((k_y < 10 && state->board[k_y+1][k_x] == 2) || (k_x == 5 && k_y == 4) || (w_pc == 0 && k_y == 10))) {
return 3;
}
if(state->turn == 1) {
// White surrounded
uint8_t broken = 0;
uint8_t first_colour = 0;
uint8_t last_colour = 0;
int8_t left = 0;
int8_t right = 0;
int8_t p_left = 0;
int8_t p_right = 0;
for(int8_t x=0;x<11;x++) {
first_colour = 0;
last_colour = 0;
p_left = left;
p_right = right;
left = -1;
right = -1;
for(int8_t y=0;y<11;y++) {
switch(type_to_side(state->board[y][x])) {
case 0:
break;
case 1:
if(first_colour == 0) return 0; // Outside white
last_colour = 1;
break;
case 2:
if(left == -1) {
if(abs(p_left-x) > 1) return 0;
left = x;
}
if(first_colour == 0) first_colour = 2;
right = x;
last_colour = 2;
break;
}
}
if(first_colour == 1 || last_colour == 1 ||
(x > 0 && left > -1 && abs(p_left-left) > 1) ||
(x > 0 && right > -1 && abs(p_right-right) > 1)) {
return 0;
}
}
for(int8_t y=0;y<11;y++) {
first_colour = 0;
last_colour = 0;
p_left = left;
p_right = right;
left = -1;
right = -1;
for(int8_t x=0;x<11;x++) {
switch(type_to_side(state->board[y][x])) {
case 0:
break;
case 1:
if(first_colour == 0) return 0; // Outside white
last_colour = 1;
break;
case 2:
if(left == -1) {
if(abs(p_left-x) > 1) return 0;
left = x;
}
if(first_colour == 0) first_colour = 2;
right = x;
last_colour = 2;
break;
}
}
if(first_colour == 1 || last_colour == 1 ||
(y > 0 && left > -1 && abs(p_left-left) > 1) ||
(y > 0 && right > -1 && abs(p_right-right) > 1)) {
return 0;
}
}
if(!broken) {
printf("Surrounded!");
return 3;
}
}
return 0;
}
uint8_t list_legal_moves_for_piece(uint8_t p_x, uint8_t p_y, uint8_t type, struct State *state, uint8_t moves[120][2]) {
uint8_t moves_found = 0;
for(int8_t x=p_x; x>=0; x--) {
if(x != p_x && state->board[p_y][x] != 0) {
break;
}
if(x != p_x && state->board[p_y][x] == 0 && !is_restricted_tile(x, p_y, type)) {
moves[moves_found][0] = x;
moves[moves_found][1] = p_y;
moves_found++;
}
}
for(int8_t x=p_x; x<11; x++) {
if(x != p_x && state->board[p_y][x] != 0) {
break;
}
if(x != p_x && state->board[p_y][x] == 0 && !is_restricted_tile(x, p_y, type)) {
moves[moves_found][0] = x;
moves[moves_found][1] = p_y;
moves_found++;
}
}
for(int8_t y=p_y; y>=0; y--) {
if(y != p_y && state->board[y][p_x] != 0) {
break;
}
if(y != p_y && state->board[y][p_x] == 0 && !is_restricted_tile(p_x, y, type)) {
moves[moves_found][0] = p_x;
moves[moves_found][1] = y;
moves_found++;
}
}
for(int8_t y=p_y; y<11; y++) {
if(y != p_y && state->board[y][p_x] != 0) {
break;
}
if(y != p_y && state->board[y][p_x] == 0 && !is_restricted_tile(p_x, y, type)) {
moves[moves_found][0] = p_x;
moves[moves_found][1] = y;
moves_found++;
}
}
return moves_found;
}
void list_legal_moves(uint8_t side, struct State *state, struct MoveSet *legal_moves) {
uint8_t pieces[BLACK_PIECE_COUNT][2];
uint8_t piece_count = 0;
short int moves_found = 0;
legal_moves->move_count = 0;
switch(side) {
case 1:
memcpy(&pieces, &state->white, sizeof state->white);
piece_count = state->white_count;
break;
case 2:
memcpy(&pieces, &state->black, sizeof state->black);
piece_count = state->black_count;
break;
}
for(int8_t i=0;i<piece_count;i++) {
moves_found = list_legal_moves_for_piece(pieces[i][0], pieces[i][1], side, state, legal_moves->moves[i]);
legal_moves->move_count += moves_found;
legal_moves->moves_per_piece[i] = moves_found;
}
if(side == 1) {
moves_found = list_legal_moves_for_piece(state->king[0], state->king[1], 3, state, legal_moves->moves[piece_count]);
legal_moves->move_count += moves_found;
legal_moves->moves_per_piece[piece_count] = moves_found;
}
/*if(side == 2) {
for(int8_t i=0;i<state->black_count;i++) {
if(side == 1) printf("%d, %d\n", state->black[i][0], state->black[i][1]);
for(int8_t j=0;j<legal_moves->moves_per_piece[i];j++)
printf("[%d,%d], ", legal_moves->moves[i][j][0], legal_moves->moves[i][j][1]);
printf("\n");
}
}*/
}
void initialise_state(struct State *state) {
state->white_count = 0;
state->black_count = 0;
state->turn = 0;
for(int8_t x=0; x<11; x++) {
for(int8_t y=0; y<11; y++) {
add_piece(x, y, 0, state);
}
}
add_piece(3, 0, 2, state);
add_piece(4, 0, 2, state);
add_piece(5, 0, 2, state);
add_piece(6, 0, 2, state);
add_piece(7, 0, 2, state);
add_piece(5, 1, 2, state);
add_piece(3, 10, 2, state);
add_piece(4, 10, 2, state);
add_piece(5, 10, 2, state);
add_piece(6, 10, 2, state);
add_piece(7, 10, 2, state);
add_piece(5, 9, 2, state);
add_piece(0, 3, 2, state);
add_piece(0, 4, 2, state);
add_piece(0, 5, 2, state);
add_piece(0, 6, 2, state);
add_piece(0, 7, 2, state);
add_piece(1, 5, 2, state);
add_piece(10, 3, 2, state);
add_piece(10, 4, 2, state);
add_piece(10, 5, 2, state);
add_piece(10, 6, 2, state);
add_piece(10, 7, 2, state);
add_piece(9, 5, 2, state);
add_piece(5, 3, 1, state);
add_piece(4, 4, 1, state);
add_piece(5, 4, 1, state);
add_piece(6, 4, 1, state);
add_piece(3, 5, 1, state);
add_piece(4, 5, 1, state);
add_piece(6, 5, 1, state);
add_piece(7, 5, 1, state);
add_piece(4, 6, 1, state);
add_piece(5, 6, 1, state);
add_piece(6, 6, 1, state);
add_piece(5, 7, 1, state);
add_piece(5, 5, 3, state);
}
void draw_board(struct State *state) {
for(int8_t y=0; y<11; y++) {
for(int8_t x=0; x<11; x++) {
if (state->board[y][x] == 0) printf(".");
else printf("%d", state->board[y][x]);
}
printf("\n");
}
for(int x=0; x<11; x++) printf("=");
printf("\n\n");
}
| 2.734375 | 3 |
2024-11-18T21:15:41.962672+00:00 | 2019-08-31T15:13:17 | f2774c4412de3df7c0e8ef8dbbfb0953058be3e6 | {
"blob_id": "f2774c4412de3df7c0e8ef8dbbfb0953058be3e6",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-31T15:13:17",
"content_id": "693bb574c53c2652b0b98d6b039ced7fcf0056f1",
"detected_licenses": [
"MIT"
],
"directory_id": "a0bc962999a3f89d15fe2fe0fe2fe414f3110bd1",
"extension": "c",
"filename": "server.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 194522118,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7054,
"license": "MIT",
"license_type": "permissive",
"path": "/LZL/聊天室B.cpp/server.c",
"provenance": "stackv2-0112.json.gz:6343",
"repo_name": "XiyouLinuxGroup-2019-Summer/TeamF",
"revision_date": "2019-08-31T15:13:17",
"revision_id": "7a661b172f7410583bd11335a3b049f9df8797a3",
"snapshot_id": "7981565eff2a0677bcffa35c3cb0a9a383d3ffd0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/XiyouLinuxGroup-2019-Summer/TeamF/7a661b172f7410583bd11335a3b049f9df8797a3/LZL/聊天室B.cpp/server.c",
"visit_date": "2020-06-13T03:42:03.370757"
} | stackv2 | #include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/epoll.h>
#include<errno.h>
#include<stdlib.h>
#include<pthread.h>
#include<signal.h>
#include<mysql/mysql.h>
#include"solve.h"
int fffffff;
int main()
{
List_Init(status_per,node_status_t);
MYSQL mysql;
mysql_init(&mysql); //初始化一个句柄
mysql_library_init(0,NULL,NULL);//初始化数据库
mysql_real_connect(&mysql,"127.0.0.1","root","lzl213260C","Login_Data",0,NULL,0);//连接数据库
mysql_set_character_set(&mysql,"utf8");//调整为中文字符
signal(SIGPIPE,SIG_IGN); //ctrl+c stop
int sock_fd,conn_fd;
int optval;
int flag_recv=USERNAME;
int name_num;
pid_t pid;
socklen_t cli_len;
struct sockaddr_in cli_addr,serv_addr;
size_t ret;
int connect_size=0; //目前连接数
pthread_t pth1;
recv_t recv_buf;
int epfd,nfds;
struct epoll_event ev,events[EVENTS_MAX_SIZE];
sock_fd=socket(AF_INET,SOCK_STREAM,0); //服务器套接字
if(sock_fd < 0)
{
perror("socket");
exit(1);
}
optval=1; //通用套接字 socket退出后可正常连接 待设置的套接字选项的值及其大小
if(setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,(void*)&optval,sizeof(int))<0)
{
perror("setsocket\n");
exit(1);
}
setsockopt(sock_fd,SOL_SOCKET,SO_KEEPALIVE,(void*)&optval,sizeof(int));
memset(&serv_addr,0,sizeof(struct sockaddr_in));
serv_addr.sin_family=AF_INET; //协议族 ipv4 tcp/ip
serv_addr.sin_port=htons(SERV_POT);//服务器端口
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY); //IP地址
if(bind(sock_fd,(struct sockaddr*)&serv_addr,sizeof(struct sockaddr_in))<0)
{
perror("bind\n");
exit(1);
}
if(listen(sock_fd,LISTENQ)<0)
{
perror("listen\n");
exit(1);
}
epfd=epoll_create(1);
ev.data.fd= sock_fd;
ev.events =EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLRDHUP ; //设置为监听读的状态
//使用默认的LT模式 // epoll 事件只触发一次
epoll_ctl(epfd,EPOLL_CTL_ADD,sock_fd,&ev);
connect_size++;
for(;;)
{
nfds = epoll_wait(epfd,events,EVENTS_MAX_SIZE,-1);//等待可写事件
for(int i=0;i<nfds;i++)
{
//printf(" The event type is %d\n",events[i].events);
connect_size++;
if(events[i].data.fd==sock_fd) //服务器套接字接收到一个连接请求
{
if(connect_size>MAX_CONTECT_SIZE)
{
perror("到达最大连接数!\n");
continue;
}
conn_fd=accept(events[i].data.fd,(struct sokcaddr*)&cli_addr,&cli_len);
//网络字节序转换成字符串输出
printf("%d accept a new client ! ip:%s\n",++fffffff,inet_ntoa(cli_addr.sin_addr));
if(conn_fd<=0)
{
perror("error in accept\n");
printf("%s\n",strerror(errno));
continue;
}
ev.data.fd= conn_fd;
ev.events =EPOLLIN | EPOLLONESHOT | EPOLLRDHUP;//|EPOLLOUT; //设置事件可写与可写
epoll_ctl(epfd,EPOLL_CTL_ADD,conn_fd,&ev); //新增服务器套接字
}
else if(events[i].events & (EPOLLRDHUP | EPOLLHUP | EPOLLERR))
{
//客户端被挂掉 值设置为24 不把事件类型设置为SO_REUSEADDR 会发送很多可读事件
//不清楚为什么 有点烦
epoll_ctl(epfd,EPOLL_CTL_DEL,events[i].data.fd,0);
close(events[i].data.fd);
}
else if(events[i].events & EPOLLIN ) //接收到可读 且不是服务器套接字 不用判断 上面已判断
{
if((ret=recv(events[i].data.fd,&recv_buf,sizeof(recv_buf),MSG_WAITALL))<0) //接收
//包的格式已经提前制定好
{
perror("recv\n");
continue;
}
if(!ret)//防止客户端异常退出时无法改变状态 客户端异常时会先发送一个大小为零的包
{ //对端关闭会发送一个可读事件 但包的大小为一
//这个处理限定了一个IP只能登录一个账号
list_status_t curps;
char buf_tmp[256];
List_ForEach(status_per,curps){
//printf("一次n");
if(curps->fdd==events[i].data.fd){
sprintf(buf_tmp,"update Data set status = '0' where Account = '%s'",curps->account);
//printf("%s\n",buf_tmp);
mysql_query(&mysql,buf_tmp); //改变登录状态
List_DelNode(curps); //不正常退出修改状态信息
break;
}
}
char buf[128];
printf("The client with IP %d is disconnected\n",events[i].data.fd);
sprintf(buf,"select *from Data where send_recv_fd = %d",events[i].data.fd);
mysql_query(&mysql,buf);
MYSQL_RES *result = mysql_store_result(&mysql);
MYSQL_ROW row=mysql_fetch_row(result);
mysql_free_result(result);
sprintf(buf,"update Data set status = \"0\" where send_recv_fd = \"%d\"",events[i].data.fd);
mysql_query(&mysql,buf);
mysql_free_result(result);
continue;
}
if(recv_buf.type==LOGIN)
{
list_status_t tmp=(list_status_t)malloc(sizeof(node_friend_t));
tmp->fdd=events[i].data.fd;//发送者套接字
//printf("套接字%d\n",events[i].data.fd);
strcpy(tmp->account,recv_buf.send_Account); //连接者账号 //用来在删除时找到账号修改状态
List_AddTail(status_per,tmp); //加入在线者链表
}
recv_buf.send_fd = events[i].data.fd; //发送者的套接字已经改变 应转换为accept后的套接字
recv_t *temp=(recv_t*)malloc(sizeof(recv_t)); //防止多线程访问一个结构体
*temp=recv_buf;
temp->epfd=epfd;
temp->conn_fd=events[i].data.fd;
//printf("进入线程\n");
pth1=pthread_create(&pth1,NULL,solve,temp);//开一个线程去判断任务类型从而执行 值传递
//solve((void*)temp);
}
}
}
close(sock_fd);
//还要关闭其他打开的套接字 别忘了
}
| 2.21875 | 2 |
2024-11-18T21:15:42.097478+00:00 | 2023-05-09T18:40:52 | a5d8f909cc3177f225dbc422510a6f83a35f31d9 | {
"blob_id": "a5d8f909cc3177f225dbc422510a6f83a35f31d9",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-09T18:40:52",
"content_id": "49f87f90d389ee23863c602148fc90196a4bfde1",
"detected_licenses": [
"MIT"
],
"directory_id": "a12b448f44beb4d521cb7e31677281f41df35f0b",
"extension": "c",
"filename": "warpAffine.c",
"fork_events_count": 168,
"gha_created_at": "2016-05-09T13:33:51",
"gha_event_created_at": "2023-09-08T11:47:06",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 58378976,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3229,
"license": "MIT",
"license_type": "permissive",
"path": "/benchmarks/framework_benchmarking/image_processing/warpAffine/warpAffine.c",
"provenance": "stackv2-0112.json.gz:6472",
"repo_name": "Tiramisu-Compiler/tiramisu",
"revision_date": "2023-05-09T18:40:52",
"revision_id": "f13e480f0ddb142cec371b7d7431a41d8ca885ec",
"snapshot_id": "d45f65dd9c35f643b3531ec79df1203c7ea3371d",
"src_encoding": "UTF-8",
"star_events_count": 906,
"url": "https://raw.githubusercontent.com/Tiramisu-Compiler/tiramisu/f13e480f0ddb142cec371b7d7431a41d8ca885ec/benchmarks/framework_benchmarking/image_processing/warpAffine/warpAffine.c",
"visit_date": "2023-08-25T12:21:26.889736"
} | stackv2 | #include "warpAffine.h"
#include <stdint.h>
#define mixf(x, y, a) ((x) + ((x) - (y)) * (a))
#define clamp(x, minval, maxval) ((x) < (minval) ? (minval) : (x) > (maxval) ? (maxval) : (x))
#ifdef __NVCC__
static void affine(const int src_rows, const int src_cols, const int src_step, const uint8_t *src,
const int dst_rows, const int dst_cols, const int dst_step, float *dst,
const float a00, const float a01, const float a10, const float a11, const float b00, const float b10) {
#else
static void affine(const int src_rows, const int src_cols, const int src_step, const uint8_t src[static const restrict src_rows][src_step],
const int dst_rows, const int dst_cols, const int dst_step, float dst[static const restrict dst_rows][dst_step],
const float a00, const float a01, const float a10, const float a11, const float b00, const float b10) {
#endif
#pragma scop
__pencil_assume(src_rows > 0);
__pencil_assume(src_cols > 0);
__pencil_assume(src_step >= src_cols);
__pencil_assume(dst_rows > 0);
__pencil_assume(dst_cols > 0);
__pencil_assume(dst_step >= dst_cols);
__pencil_kill(dst);
#pragma pencil independent
for (int n_r = 0; n_r < dst_rows; n_r++) {
#pragma pencil independent
for (int n_c = 0; n_c < dst_cols; n_c++) {
float o_r = a11 * n_r + a10 * n_c + b00;
float o_c = a01 * n_r + a00 * n_c + b10;
float r = o_r - floorf(o_r);
float c = o_c - floorf(o_c);
int coord_00_r = floorf(o_r);
int coord_00_c = floorf(o_c);
int coord_01_r = coord_00_r;
int coord_01_c = coord_00_c + 1;
int coord_10_r = coord_00_r + 1;
int coord_10_c = coord_00_c;
int coord_11_r = coord_00_r + 1;
int coord_11_c = coord_00_c + 1;
coord_00_r = clamp(coord_00_r, 0, src_rows - 1);
coord_00_c = clamp(coord_00_c, 0, src_cols - 1);
coord_01_r = clamp(coord_01_r, 0, src_rows - 1);
coord_01_c = clamp(coord_01_c, 0, src_cols - 1);
coord_10_r = clamp(coord_10_r, 0, src_rows - 1);
coord_10_c = clamp(coord_10_c, 0, src_cols - 1);
coord_11_r = clamp(coord_11_r, 0, src_rows - 1);
coord_11_c = clamp(coord_11_c, 0, src_cols - 1);
float A00 = src[coord_00_r][coord_00_c];
float A10 = src[coord_10_r][coord_10_c];
float A01 = src[coord_01_r][coord_01_c];
float A11 = src[coord_11_r][coord_11_c];
dst[n_r][n_c] = mixf(mixf(A00, A10, r), mixf(A01, A11, r), c);
}
}
__pencil_kill(src);
#pragma endscop
}
void pencil_affine_linear(const int src_rows, const int src_cols, const int src_step, const uint8_t src[],
const int dst_rows, const int dst_cols, const int dst_step, float dst[],
const float a00, const float a01, const float a10, const float a11, const float b00, const float b10) {
affine(src_rows, src_cols, src_step, src,
dst_rows, dst_cols, dst_step, dst,
a00, a01, a10, a11, b00, b10);
}
| 2.640625 | 3 |
2024-11-18T21:15:42.247914+00:00 | 2020-01-24T19:01:15 | a750238a3143923cc14fb29ed7bb2f37846f8e65 | {
"blob_id": "a750238a3143923cc14fb29ed7bb2f37846f8e65",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-24T19:01:15",
"content_id": "32a5abe3f7336d1a0f521830aa9e69094405e9ae",
"detected_licenses": [
"MIT"
],
"directory_id": "5d8decacd2defa666d4e1cab293e62e8ec24f7eb",
"extension": "h",
"filename": "types.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1696,
"license": "MIT",
"license_type": "permissive",
"path": "/MeOS/types.h",
"provenance": "stackv2-0112.json.gz:6731",
"repo_name": "michalismeng/Me-Operating-System",
"revision_date": "2020-01-24T19:01:15",
"revision_id": "e00e3963d843b04b578ee2c44f6b0773c1df5b68",
"snapshot_id": "6a7bc6f4cf919bce3b6b13583a5c787697632e63",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/michalismeng/Me-Operating-System/e00e3963d843b04b578ee2c44f6b0773c1df5b68/MeOS/types.h",
"visit_date": "2023-04-27T11:29:58.552820"
} | stackv2 | #ifndef TYPES_H
#define TYPES_H
#ifdef __cplusplus
extern "C" {
#else
#define bool uint8
#define true 1
#define false 0
#endif
typedef signed char int8;
typedef unsigned char uint8;
typedef signed short int16;
typedef unsigned short uint16;
typedef signed int int32;
typedef unsigned int uint32;
typedef signed long long int64;
typedef unsigned long long uint64;
typedef float float32;
typedef double float64;
typedef uint32 size_t;
typedef int32 ssize_t;
typedef uint32 error_t;
typedef uint8 BYTE;
typedef uint16 WORD;
typedef uint32 DWORD;
typedef uint64 QWORD;
typedef void VOID;
typedef uint32 virtual_addr;
typedef uint32 physical_addr;
#define CHK_BIT(x, bit) ( ( (x) & (bit) ) == (bit) )
#define KB *1024
#define MB KB*1024
#define GB MB*1024
#define PTR *
#define REF &
#define NULL 0
#define INVALID_FD -1
#define MAX_IO (size_t)-1 - 1
#define INVALID_IO (size_t)-1
#define cast(type, param) ((type)param)
typedef uint8* va_list;
#define sz(arg_type) ( sizeof(arg_type) % 4 != 0 ? sizeof(arg_type) + 4 - sizeof(arg_type) % 4 : sizeof(arg_type) )
//#define va_start2(pointer, last_arg) ( pointer = ( (va_list)&last_arg + sizeof(last_arg) ) )
#define va_start(pointer, last_arg) ( pointer = ( (va_list)&last_arg + sz(last_arg) ) )
#define va_end(pointer) ( pointer = (va_list) 0x0 )
//#define va_arg(pointer, arg_type) (uint8 sz = 4 - sizeof(arg_type) % 4, pointer += sz, *((arg_type *)(pointer - sz)); )
//#define sz2(arg_type) (4 - sizeof(arg_type) % 4)
#define va_arg(pointer, arg_type) ( *(arg_type*)( (pointer += sz(arg_type)) - sz(arg_type) ) )
// returns the current instruction pointer
extern uint32 get_eip(void);
#ifdef __cplusplus
}
#endif
#endif | 2.140625 | 2 |
2024-11-18T21:15:42.760746+00:00 | 2021-03-13T10:10:37 | 07cb6176da8923f5fc27e1b75973d6e7f25ee9e3 | {
"blob_id": "07cb6176da8923f5fc27e1b75973d6e7f25ee9e3",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-13T10:10:37",
"content_id": "cb18ad10aca437ec2adcfecdd258b88bd7b11ee5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cfb55b0c5cf5832533199fb59918c8bacc7a6f59",
"extension": "c",
"filename": "VIEWWIN.C",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 347318582,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 765,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/utils/VIEWWIN.C",
"provenance": "stackv2-0112.json.gz:6988",
"repo_name": "amos42/Game13h",
"revision_date": "2021-03-13T10:10:37",
"revision_id": "2d5d67a37dbd5adb515bfa58958d364461978974",
"snapshot_id": "08c9e8b515272ed8756903986e5ca573fd60daf4",
"src_encoding": "WINDOWS-1252",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/amos42/Game13h/2d5d67a37dbd5adb515bfa58958d364461978974/utils/VIEWWIN.C",
"visit_date": "2023-03-26T01:11:49.568093"
} | stackv2 | /*******************************************
WIN ÑÁ·©·i ¥¡µaº…”a.
********************************************/
#include <game13h.h>
main( int argc, char *argv[] )
{
int x, y;
int ch, number = 3;
if( argc < 2 ){
puts( "Usege : VIEWWIN <Window_file>" );
exit( 1 );
}
init_game13h();
load_user_window( argv[1] );
do{
x = (320 - number*16) / 2;
y = (200 - number*16) / 2;
draw_user_window( x, y, number, number );
ch = get_key();
bar( x, y, x + number*16, y + number*16, BLACK );
switch( ch ){
case UP : number ++; break;
case DOWN : number --; break;
}
if( number > 12 ) number = 12;
if( number < 3 ) number = 3;
} while( ch != ESC );
close_game13h();
}
| 2.359375 | 2 |
2024-11-18T21:15:43.144444+00:00 | 2022-08-25T16:31:12 | 33b41e3d765a07953def284c3bb6fb2061797e89 | {
"blob_id": "33b41e3d765a07953def284c3bb6fb2061797e89",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-25T16:33:04",
"content_id": "af5c364edcef9441549d22f97e19f3269e77bc5e",
"detected_licenses": [
"MIT"
],
"directory_id": "6ae5072ce81907f074364295ae12c567ddd90255",
"extension": "c",
"filename": "demo.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 69878898,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 416,
"license": "MIT",
"license_type": "permissive",
"path": "/pkgs/json-c/demo.c",
"provenance": "stackv2-0112.json.gz:7501",
"repo_name": "jwilk/fuzzing",
"revision_date": "2022-08-25T16:31:12",
"revision_id": "d2217c9ec07fa9755555c4d3ac6bf41e55f0e9ac",
"snapshot_id": "f3965c46324b6311b28c86acb7ed28155679e014",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/jwilk/fuzzing/d2217c9ec07fa9755555c4d3ac6bf41e55f0e9ac/pkgs/json-c/demo.c",
"visit_date": "2022-09-07T03:19:50.898492"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <json_object.h>
#include <json_tokener.h>
char input[99999];
int main(int argc, char **argv)
{
ssize_t n = read(0, input, sizeof input - 1);
if (n < 0)
abort();
struct json_object *o = json_tokener_parse((char*)input);
puts(json_object_to_json_string_ext(o, JSON_C_TO_STRING_PRETTY));
}
/* vim:set ts=4 sts=4 sw=4 et:*/
| 2.28125 | 2 |
2024-11-18T21:15:43.291014+00:00 | 2023-08-04T14:25:27 | ffd87bf2d9fee54b5b80bfc1ae0546d6fc8ef2d7 | {
"blob_id": "ffd87bf2d9fee54b5b80bfc1ae0546d6fc8ef2d7",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-04T14:25:27",
"content_id": "1ba4c885384efb00be1591f5bfb00f1b429055a4",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "e522359e0de8cc4b66901ffc585dba0da4fa5a0b",
"extension": "h",
"filename": "fmi1_import_variable_list.h",
"fork_events_count": 0,
"gha_created_at": "2019-06-13T06:28:27",
"gha_event_created_at": "2019-06-13T06:28:27",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 191704042,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4904,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/Import/include/FMI1/fmi1_import_variable_list.h",
"provenance": "stackv2-0112.json.gz:7631",
"repo_name": "fmi-tools/fmi-library",
"revision_date": "2023-08-04T14:25:27",
"revision_id": "0267cc0df741448e58449881ad8d3b7879a93d55",
"snapshot_id": "7b033a0a544732f6362d58531dbeaa6cd1ee7df5",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/fmi-tools/fmi-library/0267cc0df741448e58449881ad8d3b7879a93d55/src/Import/include/FMI1/fmi1_import_variable_list.h",
"visit_date": "2023-08-16T21:11:28.091532"
} | stackv2 | /*
Copyright (C) 2012 Modelon AB
This program is free software: you can redistribute it and/or modify
it under the terms of the BSD style license.
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
FMILIB_License.txt file for more details.
You should have received a copy of the FMILIB_License.txt file
along with this program. If not, contact Modelon AB <http://www.modelon.com>.
*/
/** \file fmi1_import_variable_list.h
* \brief Public interface to the FMI XML C-library. Handling of variable lists.
*/
#ifndef FMI1_IMPORT_VARIABLELIST_H_
#define FMI1_IMPORT_VARIABLELIST_H_
#include "fmi1_import_variable.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
\addtogroup fmi1_import
@{
\defgroup fmi1_import_varlist Handling of variable lists
@}
*/
/** \addtogroup fmi1_import_varlist
* \brief Variable lists are provided to handle sets of variables.
*
* Note that variable lists are allocated dynamically and must be freed when not needed any longer.
@{
*/
/* Allocate an empty list */
FMILIB_EXPORT fmi1_import_variable_list_t* fmi1_import_alloc_variable_list(fmi1_import_t* fmu, size_t size);
/** \brief Free a variable list. Note that variable lists are allocated dynamically and must be freed when not needed any longer
@param vl A variable list.
*/
FMILIB_EXPORT void fmi1_import_free_variable_list(fmi1_import_variable_list_t* vl);
/** \brief Make a copy of the list.
@param vl A variable list.
*/
FMILIB_EXPORT fmi1_import_variable_list_t* fmi1_import_clone_variable_list(fmi1_import_variable_list_t* vl);
/** \brief Get number of variables in a list */
FMILIB_EXPORT size_t fmi1_import_get_variable_list_size(fmi1_import_variable_list_t* vl);
/** \brief Get a pointer to the list of the value references for all the variables */
FMILIB_EXPORT const fmi1_value_reference_t* fmi1_import_get_value_reference_list(fmi1_import_variable_list_t* vl);
/** \brief Deprecated. Use fmi1_import_get_value_reference_list instead. */
FMILIB_EXPORT const fmi1_value_reference_t* fmi1_import_get_value_referece_list(fmi1_import_variable_list_t* vl);
/** \brief Get a single variable from the list*/
FMILIB_EXPORT fmi1_import_variable_t* fmi1_import_get_variable(fmi1_import_variable_list_t* vl, unsigned int index);
/** \name Operations on variable lists. Every operation creates a new list.
@{
*/
/** \brief Select sub-lists.
@param vl A variable list.
@param fromIndex Zero based start index, inclusive.
@param toIndex Zero based end index, inclusive.
@return A sublist. NULL is returned if toIndex is less than fromIndex or is larger than the list size or if memory allocation failed.
*/
FMILIB_EXPORT fmi1_import_variable_list_t* fmi1_import_get_sublist(fmi1_import_variable_list_t* vl, unsigned int fromIndex, unsigned int toIndex);
/** \brief Callback function typedef for the fmiFilterVariables.
The function should return 0 to prevent a variable from coming to the output list. */
typedef int (*fmi1_import_variable_filter_function_ft)(fmi1_import_variable_t*vl, void * data);
/** \brief Call the provided 'filter' function on every variable in the list and create a new list.
@param vl A variable list.
@param filter A filter function according to ::fmi1_import_variable_filter_function_ft.
@param context A parameter to be forwarded to the filter function.
@return A sub-list with the variables for which filter returned non-zero value. */
FMILIB_EXPORT fmi1_import_variable_list_t* fmi1_import_filter_variables(fmi1_import_variable_list_t* vl, fmi1_import_variable_filter_function_ft filter, void* context);
/** \brief Create a new variable list by concatenating two lists.
@param a A variable list.
@param b A variable list.
*/
FMILIB_EXPORT fmi1_import_variable_list_t* fmi1_import_join_var_list(fmi1_import_variable_list_t* a, fmi1_import_variable_list_t* b);
/** \brief Append a variable to the variable list.
@param vl A variable list.
@param v A variable.
*/
FMILIB_EXPORT fmi1_import_variable_list_t* fmi1_import_append_to_var_list(fmi1_import_variable_list_t* vl, fmi1_import_variable_t* v);
/** \brief Prepend a variable to the variable list.
@param vl A variable list.
@param v A variable.
*/
FMILIB_EXPORT fmi1_import_variable_list_t* fmi1_import_prepend_to_var_list(fmi1_import_variable_list_t* vl, fmi1_import_variable_t* v);
/** \brief Add a variable to a variable list.
@param vl A variable list.
@param v A variable.
*/
FMILIB_EXPORT jm_status_enu_t fmi1_import_var_list_push_back(fmi1_import_variable_list_t* vl, fmi1_import_variable_t* v);
/**
@}
*/
/**
@}
*/
#ifdef __cplusplus
}
#endif
#endif
| 2.046875 | 2 |
2024-11-18T21:15:43.346200+00:00 | 2019-01-06T05:11:09 | 929a8295dd8a08a4dc490ba9a61409e71984cc54 | {
"blob_id": "929a8295dd8a08a4dc490ba9a61409e71984cc54",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-06T05:11:09",
"content_id": "bab540cc3da7a8b6934ab542813b3a229daaf52a",
"detected_licenses": [
"Unlicense"
],
"directory_id": "69e9ef51126651f9482fd0b4925cb9710648bd69",
"extension": "c",
"filename": "3-15.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 163720090,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 221,
"license": "Unlicense",
"license_type": "permissive",
"path": "/C_Study_Example/Part3/Part3/3-15.c",
"provenance": "stackv2-0112.json.gz:7761",
"repo_name": "SekyuShin/C_Project",
"revision_date": "2019-01-06T05:11:09",
"revision_id": "90892c8374dad9eb02eadba04c3bd34379e38bfe",
"snapshot_id": "7249a0100d10c85808363148a10eaad45e697223",
"src_encoding": "UHC",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SekyuShin/C_Project/90892c8374dad9eb02eadba04c3bd34379e38bfe/C_Study_Example/Part3/Part3/3-15.c",
"visit_date": "2020-04-14T07:42:24.080377"
} | stackv2 | /* 3-15.c
#include<stdio.h>
int main(void)
{
FILE* stream = fopen("ftell.txt", "rb");
fseek(stream, 0, SEEK_END);
printf("ftell.txt 파일의 크기 : %d 바이트\n", ftell(stream));
fclose(stream);
return 0;
}
*/ | 2.828125 | 3 |
2024-11-18T21:15:43.410488+00:00 | 2018-08-28T04:40:22 | 43ff4f83f338456c4a4bd5d7b30aa647fd2a9ca6 | {
"blob_id": "43ff4f83f338456c4a4bd5d7b30aa647fd2a9ca6",
"branch_name": "refs/heads/systask",
"committer_date": "2018-08-28T04:40:22",
"content_id": "ca79c75f6a04648ffa9a81df1e4016099f5faaf3",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "20d485ba3ad23f10df0c6d92bc7d7dfb71287ddd",
"extension": "h",
"filename": "DD_SS.h",
"fork_events_count": 4,
"gha_created_at": "2016-08-23T04:30:50",
"gha_event_created_at": "2018-09-09T10:35:48",
"gha_language": "C",
"gha_license_id": null,
"github_id": 66333176,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 731,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Drivers/DevDriver/SS/Inc/DD_SS.h",
"provenance": "stackv2-0112.json.gz:7890",
"repo_name": "nitkcrbkn/stm32f_system",
"revision_date": "2018-08-28T04:40:22",
"revision_id": "0bc616c968bf2a192b5138c108b9501b82dfa9c6",
"snapshot_id": "9240ee87d550c774f386f37519004949ba1c3489",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/nitkcrbkn/stm32f_system/0bc616c968bf2a192b5138c108b9501b82dfa9c6/Drivers/DevDriver/SS/Inc/DD_SS.h",
"visit_date": "2020-09-21T19:55:37.184464"
} | stackv2 | /* ===Kisarazu RBKN Library===
*
* autor : Idutsu
* version : v0.10
* last update : 20180501
*
* **overview***
* SDの通信プロトコルを定める。
*
* ・I2Cのみのサポート
*/
#ifndef __SS_H
#define __SS_H
#include <stdint.h>
typedef struct{
uint8_t add; /*I2C アドレス格納変数*/
uint8_t data_size; /*データサイズ格納変数*/
uint8_t data[8]; /*データ格納配列*/
}DD_SSHand_t;
/*
* 指定バイト受信。
* [data[7:0](7:0)]*指定バイト分
*
*/
int DD_receive2SS(DD_SSHand_t *dmd);
/*
*SD handlerを表示。
*
*SD(Add:hex):[データサイズ],[受信データ]*データサイズ分
*/
void DD_SSHandPrint(DD_SSHand_t *dmd);
#endif
| 2.28125 | 2 |
2024-11-18T21:15:43.490412+00:00 | 2021-03-19T15:08:38 | d14c85f04afe20653cb8d7325113c6c1890b665a | {
"blob_id": "d14c85f04afe20653cb8d7325113c6c1890b665a",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-19T15:08:38",
"content_id": "6672972053d7d0fb84125b4647097916b861f9f5",
"detected_licenses": [
"MIT"
],
"directory_id": "b817afe3d3e278a7f9785dcd638b52ec3e59df7a",
"extension": "h",
"filename": "hashfunctions.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 332895998,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 524,
"license": "MIT",
"license_type": "permissive",
"path": "/src/hashfunctions.h",
"provenance": "stackv2-0112.json.gz:8019",
"repo_name": "Amayas29/E-Dictionnary",
"revision_date": "2021-03-19T15:08:38",
"revision_id": "fcca942f958ae1aaa3615053ad053e646bc58f43",
"snapshot_id": "60bea4a36eeaa49971979aae65a1553a5c19a9d7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Amayas29/E-Dictionnary/fcca942f958ae1aaa3615053ad053e646bc58f43/src/hashfunctions.h",
"visit_date": "2023-09-05T20:01:41.323845"
} | stackv2 | #ifndef __HASHFUNCTIONS__H__
#define __HASHFUNCTIONS__H__
/*
Premieres Fonction de hashage qui genere 2-3 collisions
A chaque fois on decale le resulat precedent de 2 positions
et on ajoute le code de la lettre lu (code(A) = 0, code(B) = 1 ...)
et on reccupere le modulo par rapport au nombre 171482
*/
int firstHashage(char *word);
/*
Une secondefonctions pour separer les derniers collisions de la fonction precedente
la sommes des code ASCII des lettres * leur positions
*/
int secondHashage(char *word);
#endif | 2.1875 | 2 |
2024-11-18T21:15:44.216786+00:00 | 2017-11-23T16:58:00 | c5cc50c1bc266d5004d6854700c3d4380f373808 | {
"blob_id": "c5cc50c1bc266d5004d6854700c3d4380f373808",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-23T16:58:00",
"content_id": "f3ce68a32832c0fada973b779c35661b3380a3f0",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "e0166b09db4700a0c2d46afb25bacc2dd6711371",
"extension": "c",
"filename": "tamanho.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 364,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/exemplos/04-VetoresEStrings/tamanho.c",
"provenance": "stackv2-0112.json.gz:8793",
"repo_name": "GuilhermeSCG/AEDS1-2017-2",
"revision_date": "2017-11-23T16:58:00",
"revision_id": "99676b2544d271769807bf445fa92e2abfdc2351",
"snapshot_id": "38adbf2d019acb5bec59d2c441a334dd316dd0eb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GuilhermeSCG/AEDS1-2017-2/99676b2544d271769807bf445fa92e2abfdc2351/exemplos/04-VetoresEStrings/tamanho.c",
"visit_date": "2020-03-25T08:42:05.485561"
} | stackv2 | #include <stdio.h>
int tamanho (char cadeia[]) {
int tam;
for (tam = 0; cadeia[tam] != '\0'; tam++)
;
return tam;
}
int main () {
char t_um[50] = "Eu sou o texto um.";
char t_dois[50] = "Eu sou o texto dois.";
printf ("Comprimento do texto um: %d\n", tamanho(t_um));
printf ("Comprimento do texto dois: %d\n", tamanho(t_dois));
return 0;
}
| 3.359375 | 3 |
2024-11-18T21:15:44.912846+00:00 | 2013-09-18T18:43:17 | 5c188919f4c11542934e7bdadf11aba1dfbdc87d | {
"blob_id": "5c188919f4c11542934e7bdadf11aba1dfbdc87d",
"branch_name": "refs/heads/master",
"committer_date": "2013-09-18T18:43:17",
"content_id": "88df3aff6a36a8f9016439405bfdc2cd76c76604",
"detected_licenses": [
"MIT"
],
"directory_id": "43b886e7e35bb34c4f2cb7f443c339a5efeb5dd4",
"extension": "h",
"filename": "linked_list.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1021,
"license": "MIT",
"license_type": "permissive",
"path": "/linked_list.h",
"provenance": "stackv2-0112.json.gz:8921",
"repo_name": "xim/tsoc",
"revision_date": "2013-09-18T18:43:17",
"revision_id": "8cd3d27372293bebfe1eb5b9d09915d8ba527268",
"snapshot_id": "c2dbe159cd1622f79daa45ac50e1214f575676e1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xim/tsoc/8cd3d27372293bebfe1eb5b9d09915d8ba527268/linked_list.h",
"visit_date": "2021-01-22T11:54:59.211717"
} | stackv2 | #ifndef LINKED_LIST_H
#define LINKED_LIST_H
typedef struct linked_list {
void * item;
struct linked_list * next;
} linked_list_t;
#define MALLOC_TYPE(TYPE) ((TYPE *)malloc(sizeof(TYPE)))
#define COPY_ITEM(TYPE, POINTER) (&(*MALLOC_TYPE(TYPE) = *POINTER))
#define GET_ITEM(LIST, TYPE) ((TYPE *)((LIST)->item))
#define GET_MEMBER(LIST, TYPE, ITEM) (GET_ITEM(LIST, TYPE)->ITEM)
#define SET_MEMBER(LIST, TYPE, ITEM, VALUE) (GET_MEMBER(LIST, TYPE, ITEM) = VALUE)
#define NEXT(LIST) (LIST = (LIST)->next)
#define PUSH_FRONT(LIST, ITEM) ({ \
linked_list_t * old_head = LIST; \
LIST = MALLOC_TYPE(linked_list_t); \
(LIST)->next = old_head; \
(LIST)->item = ITEM; \
})
#define PUSH_BEHIND(BEFORE, ITEM) ({ \
linked_list_t * self = MALLOC_TYPE(linked_list_t); \
self->next = BEFORE->next; \
self->item = ITEM; \
BEFORE->next = self; \
})
#define POP_HEAD(LIST) ({ \
linked_list_t * old_head = LIST; \
NEXT(LIST); \
free(old_head->item); \
free(old_head); \
})
#endif
| 2.546875 | 3 |
2024-11-18T21:15:45.451741+00:00 | 2016-12-30T08:32:36 | 2b1555c55330b0818179257c658ed8760316d5c4 | {
"blob_id": "2b1555c55330b0818179257c658ed8760316d5c4",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-30T08:32:36",
"content_id": "67ae3724f920375913b9e6c5fb68607287e45191",
"detected_licenses": [
"MIT"
],
"directory_id": "0dca20cb576868e8f4dda01d9f7b79e4692c3782",
"extension": "c",
"filename": "linked_list.c",
"fork_events_count": 0,
"gha_created_at": "2017-02-23T10:05:50",
"gha_event_created_at": "2017-02-23T10:05:50",
"gha_language": null,
"gha_license_id": null,
"github_id": 82913784,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3330,
"license": "MIT",
"license_type": "permissive",
"path": "/Codes/GUI/Core/src/linked_list.c",
"provenance": "stackv2-0112.json.gz:9565",
"repo_name": "wga1985/S-GUI",
"revision_date": "2016-12-30T08:32:36",
"revision_id": "f06de3d8a294c64758372be4a0c55604fe254a93",
"snapshot_id": "5e07b6bfeee63c8147adfd1acf642e7b56cd5e0b",
"src_encoding": "GB18030",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/wga1985/S-GUI/f06de3d8a294c64758372be4a0c55604fe254a93/Codes/GUI/Core/src/linked_list.c",
"visit_date": "2020-04-06T04:44:55.140081"
} | stackv2 | #include "linked_list.h"
#include "GUI.h"
#define MALLOC(x) GUI_Malloc(x)
#define FREE(x) GUI_Free(x);
/* 查找链表pl中节点pt的前驱 */
static LIST FindPrecious(LIST pl, LIST pt)
{
LIST p;
p = pl;
while (p->pNext != NULL && p->pNext != pt) {
p = p->pNext;
}
return p;
}
/* 删除pt指向的节点 */
void List_DeleteNode(LIST pl, LIST pt)
{
LIST p;
if (pl && pt) {
p = FindPrecious(pl, pt);
if (pl != pt) {
p->pNext = pt->pNext;
if (pt->DataLen) { /* 不是指针链表 */
FREE(pt->pData);
}
FREE(pt);
}
}
}
/* 将x指向的数据插入到pl指向的节点后 */
GUI_RESULT List_InsertNode(LIST pl, void * x, int len)
{
LIST l;
if (pl == NULL) {
return GUI_ERR;
}
l = MALLOC(sizeof(NODE));
if (l == NULL) {
return GUI_ERR;
}
if (len) { /* 申请空间 */
l->pData = MALLOC(len);
if (l->pData == NULL) {
FREE(l);
return GUI_ERR;
}
while (len--) { /* 复制内容 */
((char *)(l->pData))[len] = ((char *)x)[len];
}
} else { /* 指针链表 */
l->pData = x;
}
l->DataLen = len;
l->pNext = pl->pNext;
pl->pNext = l;
return GUI_OK;
}
/* 将一个节点插入到链表末尾 */
GUI_RESULT List_InsertEnd(LIST pl, void * x, int len)
{
if (pl == NULL) {
return GUI_ERR;
}
while (pl->pNext) {
pl = pl->pNext;
}
return List_InsertNode(pl, x, len);
}
/* 创建一个链表,这个链表有一个空表头 */
LIST List_Init(void)
{
LIST Front;
Front = MALLOC(sizeof(NODE));
Front->pData = NULL;
if (Front == NULL) {
return NULL;
}
Front->DataLen = 0;
Front->pNext = NULL;
return Front;
}
/* 删除链表 */
void List_Delete(LIST L)
{
LIST l;
while (L != NULL) {
l = L->pNext;
if (L->DataLen) { /* 不是指针链表 */
FREE(L->pData);
}
FREE(L);
L = l;
}
}
/* 获取链表长度 */
int List_GetSize(LIST pl)
{
int i = 0;
if (pl) {
for (; pl->pNext != NULL; ++i) {
pl = pl->pNext;
}
}
return i;
}
/* 得到第n个链节的地址 */
LIST List_GetNodePtr(LIST pl, int n)
{
int i;
if (n > List_GetSize(pl)) {
return NULL;
}
for (i = 0; i < n; ++i) {
pl = pl->pNext;
}
return pl;
}
/* 获取第n个链节的数据指针 */
void * List_GetNodeData(LIST pl, int n)
{
LIST p;
p = List_GetNodePtr(pl, n);
if (p != NULL) {
return p->pData;
} else {
return NULL;
}
}
/* 获取链表pl中pt指向的链节索引 */
int List_GetNodeIndex(LIST pl, LIST pt)
{
int i = 0;
if (pl) {
for (; pl->pNext != pt; ++i) {
pl = pl->pNext;
}
}
return i;
}
/* 查找字符串节点,仅当链表节点为字符串时可以使用,不区分大小写 */
int List_FindStr(LIST pl, char *pd)
{
int i = 1;
if (pl) {
while (pl->pNext != NULL) {
pl = pl->pNext;
if (GUI_Stricmp(pd, pl->pData) == 0) { /* 忽略大小写比较 */
return i;
}
++i;
}
}
return 0;
}
| 3.109375 | 3 |
2024-11-18T21:15:45.581429+00:00 | 2021-06-20T13:18:49 | b819d890e632b3094eb813f08ba9abb3d10aa3fc | {
"blob_id": "b819d890e632b3094eb813f08ba9abb3d10aa3fc",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-20T13:18:49",
"content_id": "a4dcee6f07150d2b0835082eb699cf177c96e419",
"detected_licenses": [
"MIT"
],
"directory_id": "4ebbe80c210a366811d3c5c87a13e9cc4e54bf96",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 378603392,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3624,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0112.json.gz:9694",
"repo_name": "marcotessarotto/dual_pivot_quicksort_comparison",
"revision_date": "2021-06-20T13:18:49",
"revision_id": "6b34c9beb1724542ae735311f2ce115e0ce18543",
"snapshot_id": "bec356ea17e8ecd547c359ffc39a81b4260483a3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marcotessarotto/dual_pivot_quicksort_comparison/6b34c9beb1724542ae735311f2ce115e0ce18543/main.c",
"visit_date": "2023-05-27T12:15:07.422997"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/resource.h>
#include "dual_pivot_quicksort.h"
#include "quicksort.h"
// some types of initialization
void init_array1_ordered_desc(int * a, int a_length) {
printf("initializing with ordered values, descending\n");
for (int i = 0; i < a_length; i++)
a[i] = a_length - i - 1;
}
void init_array2_rnd_values(int * a, int a_length, int seed) {
printf("initializing with pseudo-random values, seed=%d\n", seed);
srand(seed);
for (int i = 0; i < a_length; i++)
a[i] = rand();
}
void init_array3_ordered_ascending(int * a, int a_length) {
printf("initializing with ordered values, ascending\n");
for (int i = 0; i < a_length; i++)
a[i] = i;
}
// duplicate an array
void * memdup(const void * a, size_t size) {
void * result = malloc(size);
if (result == NULL)
return NULL;
memcpy(result, a, size);
return result;
}
// create an int array of 'length' elements and fill it with random values, using specified seed
int * rnd_int_array(int length, int seed) {
int * result = malloc(length * sizeof(int));
if (result == NULL)
return NULL;
srand(seed);
for (int i = 0; i < length; i++)
result[i] = rand();
return result;
}
typedef struct {
long * dt;
double average;
} test_results;
test_results do_tests(int * data, int data_length, void (* sort_function)(int *, int), int num_rep, int ** sort_result) {
test_results result;
int * work_array = NULL;
struct timespec ts1, ts2;
result.dt = malloc(sizeof(long) * num_rep);
if (result.dt == NULL)
exit(1);
// each sort test is repeated num_rep times
for (int i = 0; i < num_rep; i++) {
// at each iteration, recreate the array to be sorted, copying values from original test array
if (work_array != NULL)
free(work_array);
work_array = memdup(data, sizeof(int) * data_length);
if (work_array == NULL)
exit(1);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts1);
sort_function(work_array, data_length);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts2);
result.dt[i] = ((ts2.tv_sec - ts1.tv_sec) * 1000000000L + ts2.tv_nsec) - ts1.tv_nsec;
}
if (sort_result != NULL)
*sort_result = work_array;
else
free(work_array);
result.average = 0;
for (int i = 0; i < num_rep; i++) {
result.average = result.average + (result.dt[i] - result.average) / (i+1);
}
return result;
}
int main() {
int N = 1024*1024;
int NUMBER_OF_REPETITIONS = 10;
int RND_SEED = 10001;
int * test_array;
test_array = malloc(N * sizeof(int));
if (test_array == NULL)
exit(1);
//init_array1_ordered_desc(test_array, N);
init_array2_rnd_values(test_array, N, RND_SEED);
//init_array3_ordered_ascending(test_array, N);
int * work_array = NULL;
int * work_array2 = NULL;
test_results res1 = do_tests(test_array, N, dual_pivot_quick_sort, NUMBER_OF_REPETITIONS, &work_array);
test_results res2 = do_tests(test_array, N, quick_sort_hoare, NUMBER_OF_REPETITIONS, NULL);
test_results res3 = do_tests(test_array, N, quick_sort_lomuto, NUMBER_OF_REPETITIONS, &work_array2);
printf("average results:\n"
"number of iterations= %d\n"
"int array length= %d\n", NUMBER_OF_REPETITIONS, N);
printf("dual pivot quick sort : dt = %.2lf ns/iteration, %.3lf ms/iteration\n", res1.average, res1.average / 1000000);
printf("quick sort hoare partition scheme : dt = %.2lf ns/iteration, %.3lf ms/iteration\n", res2.average, res2.average / 1000000);
printf("quick sort lomuto partition scheme : dt = %.2lf ns/iteration, %.3lf ms/iteration\n", res3.average, res3.average / 1000000);
return 0;
}
| 3.21875 | 3 |
2024-11-18T21:15:45.679483+00:00 | 2020-05-14T03:26:13 | ad778841e5de121ddbe417dd272ad09bbffc955c | {
"blob_id": "ad778841e5de121ddbe417dd272ad09bbffc955c",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-29T19:37:48",
"content_id": "b623d3113a169c85ad317a053304e95bd25fd9d1",
"detected_licenses": [
"MIT"
],
"directory_id": "4054a250ae5db77119bfc5fd54de94675a3231ca",
"extension": "c",
"filename": "vccrypt_digital_signature_register_ed25519.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7363,
"license": "MIT",
"license_type": "permissive",
"path": "/src/digital_signature/vccrypt_digital_signature_register_ed25519.c",
"provenance": "stackv2-0112.json.gz:9823",
"repo_name": "hocktide/v-c-crypto",
"revision_date": "2020-05-14T03:26:13",
"revision_id": "4f3d5f21cc62f4a92c7987abdbcaee2d652781ca",
"snapshot_id": "21c937421534191e29d152f1e173e7e2dbd40bd0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hocktide/v-c-crypto/4f3d5f21cc62f4a92c7987abdbcaee2d652781ca/src/digital_signature/vccrypt_digital_signature_register_ed25519.c",
"visit_date": "2022-09-10T13:13:25.771967"
} | stackv2 | /**
* \file vccrypt_digital_signature_register_ed25519.c
*
* Register ed25519 and force a link dependency so that this algorithm can be
* used at runtime.
*
* \copyright 2017 Velo Payments, Inc. All rights reserved.
*/
#include <cbmc/model_assert.h>
#include <stdbool.h>
#include <string.h>
#include <vccrypt/digital_signature.h>
#include <vccrypt/hash.h>
#include <vpr/abstract_factory.h>
#include <vpr/allocator.h>
#include <vpr/parameters.h>
#include "ref/curve25519.h"
/* forward decls */
static int vccrypt_ed25519_init(
void* options, void* context);
static void vccrypt_ed25519_dispose(void* options, void* context);
static int vccrypt_ed25519_sign(
void* context, vccrypt_buffer_t* sign_buffer,
const vccrypt_buffer_t* priv, const uint8_t* data, size_t size);
static int vccrypt_ed25519_verify(
void* context, const vccrypt_buffer_t* signature,
const vccrypt_buffer_t* pub, const uint8_t* message, size_t size);
static int vccrypt_ed25519_keypair_create(
void* context, vccrypt_buffer_t* priv, vccrypt_buffer_t* pub);
/* static data for this instance */
static abstract_factory_registration_t ed25519_impl;
static vccrypt_digital_signature_options_t ed25519_options;
static bool ed25519_impl_registered = false;
/**
* Register ed25519 for use by the crypto library.
*/
void vccrypt_digital_signature_register_ed25519()
{
MODEL_ASSERT(!ed25519_impl_registered);
/* only register once */
if (ed25519_impl_registered)
{
return;
}
/* we need SHA-512 for ed25519 */
vccrypt_hash_register_SHA_2_512();
/* set up the options for ed25519 */
ed25519_options.hdr.dispose = 0; /* disposal handled by init */
ed25519_options.alloc_opts = 0; /* allocator handled by init */
ed25519_options.prng_opts = 0; /* prng options handled by init */
ed25519_options.hash_algorithm = VCCRYPT_HASH_ALGORITHM_SHA_2_512;
ed25519_options.signature_size =
VCCRYPT_DIGITAL_SIGNATURE_ED25519_SIGNATURE_SIZE;
ed25519_options.private_key_size =
VCCRYPT_DIGITAL_SIGNATURE_ED25519_PRIVATE_KEY_SIZE;
ed25519_options.public_key_size =
VCCRYPT_DIGITAL_SIGNATURE_ED25519_PUBLIC_KEY_SIZE;
ed25519_options.vccrypt_digital_signature_alg_init =
&vccrypt_ed25519_init;
ed25519_options.vccrypt_digital_signature_alg_dispose =
&vccrypt_ed25519_dispose;
ed25519_options.vccrypt_digital_signature_alg_sign =
&vccrypt_ed25519_sign;
ed25519_options.vccrypt_digital_signature_alg_verify =
&vccrypt_ed25519_verify;
ed25519_options.vccrypt_digital_signature_alg_keypair_create =
&vccrypt_ed25519_keypair_create;
/* set up this registration for the abstract factory. */
ed25519_impl.interface =
VCCRYPT_INTERFACE_SIGNATURE;
ed25519_impl.implementation =
VCCRYPT_DIGITAL_SIGNATURE_ALGORITHM_ED25519;
ed25519_impl.implementation_features =
VCCRYPT_DIGITAL_SIGNATURE_ALGORITHM_ED25519;
ed25519_impl.factory = 0;
ed25519_impl.context = &ed25519_options;
/* register this instance. */
abstract_factory_register(&ed25519_impl);
/* only register once */
ed25519_impl_registered = true;
}
/**
* Algorithm-specific initialization for digital signatures.
*
* \param options Opaque pointer to this options structure.
* \param context Opaque pointer to vccrypt_digital_signature_context_t
* structure.
*
* \returns 0 on success and non-zero on error.
*/
static int vccrypt_ed25519_init(
void* options, void* context)
{
vccrypt_digital_signature_options_t* opts =
(vccrypt_digital_signature_options_t*)options;
vccrypt_digital_signature_context_t* ctx =
(vccrypt_digital_signature_context_t*)context;
/* initialize the hash options with SHA-512 */
return vccrypt_hash_options_init(
&ctx->hash_opts, opts->alloc_opts, opts->hash_algorithm);
}
/**
* Algorithm-specific disposal for digital signatures.
*
* \param options Opaque pointer to this options structure.
* \param context Opaque pointer to vccrypt_digital_signature_context_t
* structure.
*/
static void vccrypt_ed25519_dispose(
void* UNUSED(options), void* context)
{
vccrypt_digital_signature_context_t* ctx =
(vccrypt_digital_signature_context_t*)context;
dispose((disposable_t*)&ctx->hash_opts);
}
/**
* Sign a message, given a private key, a message, and a message length.
*
* \param context An opaque pointer to the
* vccrypt_digital_signature_context_t structure.
* \param sign_buffer The buffer to receive the signature. Must be large
* enough for the given digital signature algorithm.
* \param priv The private key to use for the signature.
* \param message The input message.
* \param size The size of the message in bytes.
*
* \returns 0 on success and 1 on failure.
*/
static int vccrypt_ed25519_sign(
void* context, vccrypt_buffer_t* sign_buffer,
const vccrypt_buffer_t* priv, const uint8_t* data,
size_t size)
{
vccrypt_digital_signature_context_t* ctx =
(vccrypt_digital_signature_context_t*)context;
return ED25519_sign((uint8_t*)sign_buffer->data, data, size,
(const uint8_t*)priv->data, &ctx->hash_opts);
}
/**
* Verify a message, given a public key, a message, and a message length.
*
* \param context An opaque pointer to the
* vccrypt_digital_signature_context_t structure.
* \param signature The signature to verify.
* \param pub The public key to use for signature verification.
* \param message The input message.
* \param size The size of the message in bytes.
*
* \returns 0 if the message signature is valid, and no-zero on error.
*/
static int vccrypt_ed25519_verify(
void* context, const vccrypt_buffer_t* signature,
const vccrypt_buffer_t* pub, const uint8_t* message,
size_t size)
{
vccrypt_digital_signature_context_t* ctx =
(vccrypt_digital_signature_context_t*)context;
return ED25519_verify(message, size, (const uint8_t*)signature->data,
(const uint8_t*)pub->data, &ctx->hash_opts);
}
/**
* Create a keypair.
*
* The output buffers must be large enough to accept the resultant keys.
*
* \param context An opaque pointer to the
* vccrypt_digital_signature_context_t structure.
* \param priv The output buffer to receive the private key.
* \param pub The output buffer to receive the public key.
*/
static int vccrypt_ed25519_keypair_create(
void* context, vccrypt_buffer_t* priv, vccrypt_buffer_t* pub)
{
vccrypt_digital_signature_context_t* ctx =
(vccrypt_digital_signature_context_t*)context;
int retval = VCCRYPT_STATUS_SUCCESS;
/* create a PRNG context for use by the keypair algorithm. */
vccrypt_prng_context_t prng_ctx;
retval = vccrypt_prng_init(ctx->options->prng_opts, &prng_ctx);
if (VCCRYPT_STATUS_SUCCESS != retval)
{
return retval;
}
/* generate the keypair */
retval =
ED25519_keypair(
(uint8_t*)pub->data, (uint8_t*)priv->data, &prng_ctx,
&ctx->hash_opts);
/* dispose of the prng */
dispose((disposable_t*)&prng_ctx);
return retval;
}
| 2.25 | 2 |
2024-11-18T21:15:45.773031+00:00 | 2021-04-30T05:23:22 | 8eb1d86d3ec41cadabad7973abeda443cfbf38d2 | {
"blob_id": "8eb1d86d3ec41cadabad7973abeda443cfbf38d2",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-30T05:23:22",
"content_id": "f1554acb171ef419ba89546f92f1196d63f7a8c0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ecabd8fc1643ac2d239f22d840d0e9cc86e3c062",
"extension": "h",
"filename": "key.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 904,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/HARDWARE/KEY/key.h",
"provenance": "stackv2-0112.json.gz:9952",
"repo_name": "lw-lx/Data-recording-analyze",
"revision_date": "2021-04-30T05:23:22",
"revision_id": "d06dca8e41fdccf6eda12cae8913a81215e9b296",
"snapshot_id": "1623626c780c062193c0809b5babdbd6eb1e63b5",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lw-lx/Data-recording-analyze/d06dca8e41fdccf6eda12cae8913a81215e9b296/HARDWARE/KEY/key.h",
"visit_date": "2023-04-24T12:52:50.857792"
} | stackv2 | /*
* @Descripttion:
* @version: 1.0
* @Author: YLDS
* @Date: 2021-04-03 16:52:51
* @LastEditTime: 2021-04-03 17:09:59
*/
#ifndef _KEY_H
#define _KEY_H
#include "main.h"
//下面的方式是通过位带操作方式读取IO
//#define KEY0 PHin(3) //KEY0按键PH3
//#define KEY1 PHin(2) //KEY1按键PH2
//#define KEY2 PCin(13)//KEY2按键PC13
//#define WK_UP PAin(0) //WKUP按键PA0
//下面的方式是通过直接操作HAL库函数方式读取IO
#define KEY0 HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_4) //KEY0按键PE4
#define KEY1 HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_3) //KEY1按键PE3
#define KEY2 HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_2) //KEY2按键PE2
#define WK_UP HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0) //WKUP按键PA0
#define KEY0_PRES 1
#define KEY1_PRES 2
#define KEY2_PRES 3
#define WKUP_PRES 4
int KEY_Init(void);
u8 KEY_Scan(u8 mode);
#endif
| 2.125 | 2 |
2024-11-18T21:15:45.930967+00:00 | 2019-03-17T00:43:20 | c999f5bfb41a243582445f254d8c49c78851d28a | {
"blob_id": "c999f5bfb41a243582445f254d8c49c78851d28a",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-17T00:43:20",
"content_id": "55ad27c9e18e420230b90c097c2e666d2ffb3b02",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "020d7e51f35a3be40280f67e8c781b61cb9f7668",
"extension": "c",
"filename": "pam.c",
"fork_events_count": 1,
"gha_created_at": "2018-09-09T13:35:50",
"gha_event_created_at": "2019-03-17T00:43:21",
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 148028859,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1735,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/pam/pam.c",
"provenance": "stackv2-0112.json.gz:10210",
"repo_name": "moolen/glitchlock",
"revision_date": "2019-03-17T00:43:20",
"revision_id": "f2e4f823c7ce81e4c68021854b52d78a47181691",
"snapshot_id": "0687362d41018649a4d5a4bcb7252cda83a89622",
"src_encoding": "UTF-8",
"star_events_count": 19,
"url": "https://raw.githubusercontent.com/moolen/glitchlock/f2e4f823c7ce81e4c68021854b52d78a47181691/pam/pam.c",
"visit_date": "2020-03-28T09:19:21.319662"
} | stackv2 | #include <security/pam_appl.h>
#include <security/pam_misc.h>
#include <stdio.h>
#include <pwd.h>
const char* test_password = NULL;
const char* get_current_user() {
struct passwd *pw;
const char *user;
if ((pw = getpwuid(getuid())) == NULL)
return NULL;
if ((user = pw->pw_name) == NULL)
return NULL;
return user;
}
static int conv_callback(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr) {
if (num_msg == 0)
return 1;
if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
return 1;
}
for (int c = 0; c < num_msg; c++) {
if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
continue;
resp[c]->resp_retcode = 0;
if ((resp[c]->resp = strdup(test_password)) == NULL) {
return 1;
}
}
return 0;
}
int check_password(const char* user, const char* password) {
pam_handle_t *pam_handle=NULL;
int retval;
struct passwd *pw;
struct pam_conv conv = {
conv_callback,
NULL
};
test_password = password;
retval = pam_start("login", user, &conv, &pam_handle);
if (retval == PAM_SUCCESS)
retval = pam_authenticate(pam_handle, 0);
if (retval == PAM_SUCCESS)
retval = pam_acct_mgmt(pam_handle, 0);
if (pam_end(pam_handle,retval) != PAM_SUCCESS) {
pam_handle = NULL;
}
test_password = NULL;
return ( retval == PAM_SUCCESS ? 1:0 );
}
int check_current_user(const char* password) {
const char* user;
if ((user = get_current_user()) == NULL)
return 0;
return check_password(user, password);
}
| 2.53125 | 3 |
2024-11-18T21:15:46.110262+00:00 | 2015-08-08T16:35:36 | 10fbb9cd1f8b4352d157af803cca3ccbdeaf2027 | {
"blob_id": "10fbb9cd1f8b4352d157af803cca3ccbdeaf2027",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-08T16:35:36",
"content_id": "fbc352434c0bf0c2cb3400475031053631071ad2",
"detected_licenses": [
"MIT"
],
"directory_id": "393f87cc343d77693418b931519239571f737214",
"extension": "h",
"filename": "x86_64.h",
"fork_events_count": 0,
"gha_created_at": "2015-08-17T15:11:31",
"gha_event_created_at": "2015-08-17T15:11:31",
"gha_language": null,
"gha_license_id": null,
"github_id": 40904660,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6235,
"license": "MIT",
"license_type": "permissive",
"path": "/src/hotpatch/x86_64.h",
"provenance": "stackv2-0112.json.gz:10466",
"repo_name": "arigo/vmprof-python",
"revision_date": "2015-08-08T16:35:36",
"revision_id": "be8b2a890eafd260be8e3c67a67c1453f8c4d3ef",
"snapshot_id": "0a327eaaa3adc3fec5491006bd863ffa3701c8f0",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/arigo/vmprof-python/be8b2a890eafd260be8e3c67a67c1453f8c4d3ef/src/hotpatch/x86_64.h",
"visit_date": "2021-01-15T18:40:26.717431"
} | stackv2 | #if !defined(_x86_64_h_)
#define _x86_64_h_
#include <stdint.h>
#include "arch.h"
/*
* tramp_st2_entry - stage 2 trampoline entry
*
* This trampoline calls a handler function via the callee saved register %rbx.
* The handler function is stored in the field 'addr'.
*
* A default pre-filled (except addr, of course) version of this trampoline is
* provided so that the opcodes do not need to be filled in every time it is
* used. You only need to set the addr field of default_st2_tramp and you are
* ready to roll.
*
* This trampoline is the assembly code:
*
* push %rbx # save %rbx
* push %rbp # save previous stack frame's %rbp
* mov %rsp, %rbp # update %rbp to be current stack pointer
* andl 0xFFFFFFFFFFFFFFF0, %rsp # align stack pointer as per the ABI
* mov ADDR, %rbx # move address of handler into %rbx
* callq *%rbx # call handler
* pop %rbx # restore %rbx
* leave # restore %rbp, move stack pointer back
* ret # return
*/
static struct tramp_st2_entry {
unsigned char push_rbx;
unsigned char push_rbp;
unsigned char save_rsp[3];
unsigned char align_rsp[4];
unsigned char mov[2];
void *addr;
unsigned char call[2];
unsigned char leave;
unsigned char rbx_restore;
unsigned char ret;
} __attribute__((__packed__)) default_st2_tramp = {
.push_rbx = 0x53,
.push_rbp = 0x55,
.save_rsp = {0x48, 0x89, 0xe5},
.align_rsp = {0x48, 0x83, 0xe4, 0xf0},
.mov = {0x48, 0xbb},
.addr = 0,
.call = {0xff, 0xd3},
.rbx_restore = 0x5b,
.leave = 0xc9,
.ret = 0xc3,
};
/*
* inline_tramp_st2_entry - stage 2 inline trampoline entry
*
* This trampoline calls a handler function via the callee saved register %rbx,
* The handler function is stored in the field 'addr'.
*
* The major difference between this trampoline and the one above is that this
* trampoline is intended to be used as the target of an 'inline trampoline',
* that is code is redirected to this and the stack and registers may not be
* 'ready' for a function call.
*
* This trampoline provides space to regenerate the overwritten mov instruction
* and utmost care must be taken in order to recreate the overwritten
* instruction.
*
* This trampoline is hit with a jmp (NOT A CALL), and as such must take care
* to jmp back to resume execution.
*
* Like the above trampoline, this structure comes with a prefilled entry called
* default_inline_st2_tramp that has most of the fields prepopulated.
*
* To use this structure you must fill in:
* - mov_displacement - should be set to the 32bit displacement from the next
* instruction (i.e. frame) to freelist. This is used to recreate the
* overwritten instruction.
*
* - rdi_source_displacement - should be set to the 32bit displacement from
* the next instruction (i.e. push_rbx) to freelist. This is used to load
* freelist as the 1st argument to the handler.
*
* - addr - the address of the handler function to call
*
* - jmp_displacement - should be set to the 32bit displacement from the next
* instruction to the instruction after the stage 1 trampoline. This is
* used to resume execution after the handler has been hit.
*
*
* This structure represents the assembly code:
*
* mov SOURCE_REGISTER,-0x3f90d4a7(%rip) # update freelist
*
* # save caller saved registers here
*
* push %rax
* push %rcx
* push %rdx
* push %rsi
* push %rdi
* push %r8
* push %r9
* push %r10
* push %r11
* push %rbp
* mov %rsp,%rbp
* mov -0x3f90d4bf(%rip),%rdi # move freelist into rdi as arg1
* and $0xfffffffffffffff0,%rsp # align stack pointer
* mov $0x7ffff65e74e0,%rcx # put handler function into position
* callq *%rcx # call handler
*
* # restore caller saved registers here
*
* leaveq
* pop %r11
* pop %r10
* pop %r9
* pop %r8
* pop %rdi
* pop %rsi
* pop %rdx
* pop %rcx
* pop %rax
*
* jmpq 0x433972 <gc_sweep+754> # jump back
*/
static struct inline_tramp_st2_entry {
unsigned char rex;
unsigned char mov;
unsigned char src_reg;
uint32_t mov_displacement;
struct {
/*
* XXX xmm0-xmm7 are caller saved, too.
*/
unsigned char push_rax;
unsigned char push_rcx;
unsigned char push_rdx;
unsigned char push_rsi;
unsigned char push_rdi;
unsigned char push_r8[2];
unsigned char push_r9[2];
unsigned char push_r10[2];
unsigned char push_r11[2];
unsigned char push_rbp;
unsigned char mov_rsp_rbp[3];
unsigned char mov_rdi[3];
uint32_t rdi_source_displacement;
unsigned char align_rsp[4];
unsigned char mov[2];
void *addr;
unsigned char call[2];
unsigned char leave;
unsigned char pop_r11[2];
unsigned char pop_r10[2];
unsigned char pop_r9[2];
unsigned char pop_r8[2];
unsigned char pop_rdi;
unsigned char pop_rsi;
unsigned char pop_rdx;
unsigned char pop_rcx;
unsigned char pop_rax;
} __attribute__((__packed__)) frame;
unsigned char jmp;
uint32_t jmp_displacement;
} __attribute__((__packed__)) default_inline_st2_tramp = {
.rex = 0x48,
.mov = 0x89,
.src_reg = 0x05,
.mov_displacement = 0,
.frame = {
.push_rax = 0x50,
.push_rcx = 0x51,
.push_rdx = 0x52,
.push_rsi = 0x56,
.push_rdi = 0x57,
.push_r8 = {0x41, 0x50},
.push_r9 = {0x41, 0x51},
.push_r10 = {0x41, 0x52},
.push_r11 = {0x41, 0x53},
.push_rbp = 0x55,
.mov_rsp_rbp = {0x48, 0x89, 0xe5},
.mov_rdi = {0x48, 0x8b, 0x3d},
.rdi_source_displacement = 0,
.align_rsp = {0x48, 0x83, 0xe4, 0xf0},
.mov = {0x48, 0xb9},
.addr = 0,
.call = {0xff, 0xd1},
.leave = 0xc9,
.pop_r11 = {0x41, 0x5b},
.pop_r10 = {0x41, 0x5a},
.pop_r9 = {0x41, 0x59},
.pop_r8 = {0x41, 0x58},
.pop_rdi = 0x5f,
.pop_rsi = 0x5e,
.pop_rdx = 0x5a,
.pop_rcx = 0x59,
.pop_rax = 0x58,
},
.jmp = 0xe9,
.jmp_displacement = 0,
};
#endif
| 2.59375 | 3 |
2024-11-18T21:15:46.398710+00:00 | 2021-04-15T17:29:17 | 72532a72001a0647c45b0579ba3b984309da58d7 | {
"blob_id": "72532a72001a0647c45b0579ba3b984309da58d7",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-15T17:29:17",
"content_id": "48b423349977c9440766ca49c3ecc95ea220befc",
"detected_licenses": [
"MIT"
],
"directory_id": "fce54e076fffefa0bca376000c2e58225cc0744c",
"extension": "h",
"filename": "oa.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 354395114,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 725,
"license": "MIT",
"license_type": "permissive",
"path": "/src/oa.h",
"provenance": "stackv2-0112.json.gz:10723",
"repo_name": "llGuy/lGkn",
"revision_date": "2021-04-15T17:29:17",
"revision_id": "a4ae1bafa50b73b7dc497094287e0939c9c29afc",
"snapshot_id": "bf2c2fd2268b954caee7adf41518f5201fbc6a9f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/llGuy/lGkn/a4ae1bafa50b73b7dc497094287e0939c9c29afc/src/oa.h",
"visit_date": "2023-04-03T05:24:09.376424"
} | stackv2 | #ifndef OA_H
#define OA_H
#include "int.h"
typedef void *type_t;
typedef int8_t (*lessthan_pred_t)(type_t, type_t);
typedef struct {
type_t *array;
uint32_t size;
uint32_t max_size;
lessthan_pred_t lessthan;
} ordered_array_t;
int8_t def_lessthan_pred(type_t a, type_t b);
ordered_array_t create_ordered_array(
uint32_t max_size,
lessthan_pred_t less_than);
ordered_array_t place_ordered_array(
void *addr,
uint32_t max_size,
lessthan_pred_t pred);
void destroy_ordered_array(ordered_array_t *array);
void insert_ordered_array(type_t item, ordered_array_t *array);
type_t find_ordered_array(uint32_t i, ordered_array_t *array);
void remove_ordered_array(uint32_t i, ordered_array_t *array);
#endif
| 2.125 | 2 |
2024-11-18T21:15:46.507992+00:00 | 2023-05-11T09:40:44 | 752db73c049ab03b2db43f353d9ef398869c92ae | {
"blob_id": "752db73c049ab03b2db43f353d9ef398869c92ae",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-11T09:40:44",
"content_id": "ca9646fa3dd84aefaae2191b8fc11356e5bfa380",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e41d4656cc14e8dfbf3b0b520a4860eaae8989d4",
"extension": "h",
"filename": "motor_ctrl_timer.h",
"fork_events_count": 10,
"gha_created_at": "2019-09-08T09:59:49",
"gha_event_created_at": "2023-05-11T09:40:45",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 207093156,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2121,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/examples/peripherals/mcpwm/mcpwm_brushed_dc_control/components/motor_ctrl_timer/motor_ctrl_timer.h",
"provenance": "stackv2-0112.json.gz:10853",
"repo_name": "mongoose-os/esp-idf",
"revision_date": "2023-05-11T09:40:44",
"revision_id": "7b386c8b527afa8d51214c27c2355160d8af2c10",
"snapshot_id": "f72eeb62720dbddbcf6fca92d3659806112a93c5",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/mongoose-os/esp-idf/7b386c8b527afa8d51214c27c2355160d8af2c10/examples/peripherals/mcpwm/mcpwm_brushed_dc_control/components/motor_ctrl_timer/motor_ctrl_timer.h",
"visit_date": "2023-05-25T16:42:23.072381"
} | stackv2 | /* To set the control period for DC motor Timer
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "driver/timer.h"
typedef struct {
int (*get_pulse_callback)(void *);
void *callback_args;
int pulse_cnt;
} pulse_info_t;
typedef struct {
timer_group_t timer_group; /* Timer Group number */
timer_idx_t timer_idx; /* Timer ID */
unsigned int ctrl_period_ms; /* Motor control period, unit in ms */
QueueHandle_t timer_evt_que; /* The queue of timer events */
pulse_info_t pulse_info;
} motor_ctrl_timer_info_t;
/**
* @brief Initialize the motor control timer
*
* @param timer_info the secondary pointer of motor_ctrl_timer_info_t
* @param evt_que timer event queue
* @param ctrl_period_ms motor control period
* @param pulse_info quadrature encoder pulse information
* @return
* - ESP_OK: Motor control timer initialized successfully
* - ESP_FAIL: motor control timer failed to initialize because of other errors
*/
esp_err_t motor_ctrl_new_timer(motor_ctrl_timer_info_t **timer_info,
QueueHandle_t evt_que,
unsigned int ctrl_period_ms,
pulse_info_t pulse_info);
/**
* @brief Set timer alarm period
*
* @param period Timer alarm period
*/
void motor_ctrl_timer_set_period(unsigned int period);
/**
* @brief Start the timer
*/
void motor_ctrl_timer_start(void);
/**
* @brief Pause the timer and clear the counting value
*/
void motor_ctrl_timer_stop(void);
/**
* @brief Deinitialize the timer
*
* @param timer_info the secondary pointer of motor_ctrl_timer_info_t, the memory will be freed
*/
void motor_ctrl_timer_deinit(motor_ctrl_timer_info_t **timer_info);
#ifdef __cplusplus
}
#endif
| 2.703125 | 3 |
2024-11-18T21:15:47.420371+00:00 | 2021-05-05T09:16:47 | 6910c6a0c5f53ab6e8a080d7239e3b72d7faad66 | {
"blob_id": "6910c6a0c5f53ab6e8a080d7239e3b72d7faad66",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-05T09:16:47",
"content_id": "380e56887a63779dc5905087676bc6eeca76e159",
"detected_licenses": [
"MIT"
],
"directory_id": "fc18073fa0a8df83d9c41d2766d3eff764947c41",
"extension": "h",
"filename": "cstrings.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 321074403,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1043,
"license": "MIT",
"license_type": "permissive",
"path": "/C/PT/Lab2 Independent Compilation/Hw/cstrings.h",
"provenance": "stackv2-0112.json.gz:11242",
"repo_name": "RaulQX/School-Homework",
"revision_date": "2021-05-05T09:16:47",
"revision_id": "1cd0116bfb0fb4be80a98842d425a795293456c8",
"snapshot_id": "b1a551168118185d664d7eef93ad9eb5c534fb24",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RaulQX/School-Homework/1cd0116bfb0fb4be80a98842d425a795293456c8/C/PT/Lab2 Independent Compilation/Hw/cstrings.h",
"visit_date": "2023-04-23T16:00:59.322849"
} | stackv2 | typedef unsigned long size_t;
size_t mystrlen(char*s);
size_t mystrnlen(char*s, size_t maxlenght);
void * mymemchr(void *str, int character, size_t maxlenght);
int mymemcmp (const void* str1, const void* str2, size_t maxmem);
void *mymemcpy(void *string_to, const void *string_from, size_t maxmem);
void *mymemset(void *str, int character, size_t n);
char* mystrcat(char* string_to, char* string_from);
char* mystrncat(char* string_to, char* string_from, size_t n);
char *mystrchr (char* str, int c);
char *mystrrchr (char* str, int c);
int mystrcmp(char *str1, char* str2);
int mystrncmp(char *str1, char* str2, size_t n);
size_t mystrspn (char *str, char* characters);
size_t mystrcspn(char*str1, char* chars);
char *mystrstr(char*str, char*baby_str);
char* mystrpbrk(char*str, char*chars);
char *mystrdup(char*string_to);
char *mystrndup(char*string_to, size_t bytes);
char* mystrcpy(char*string_to, char*string_from);
char *mystrncpy(char *string_to, char*string_from, size_t n);
char *strtoupper(char *str);
char *strtolower(char *str); | 2.125 | 2 |
2024-11-18T21:15:48.845558+00:00 | 2019-05-26T13:58:23 | 143fd38f280189b4b2711f3fb7553333c8adc08a | {
"blob_id": "143fd38f280189b4b2711f3fb7553333c8adc08a",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-26T13:58:23",
"content_id": "b83d102b21a677ce9401479f5ee6ef36f90fd416",
"detected_licenses": [
"MIT",
"BSD-2-Clause"
],
"directory_id": "be7814890e8893395e41a83c051e4fff044d5198",
"extension": "c",
"filename": "cyg_devaccess_uart.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 5437116,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3895,
"license": "MIT,BSD-2-Clause",
"license_type": "permissive",
"path": "/examples/cyg_devaccess_uart.c",
"provenance": "stackv2-0112.json.gz:11885",
"repo_name": "hirokuma/libhknfcrw_c",
"revision_date": "2019-05-26T13:58:23",
"revision_id": "9b1bc588945cc34aee123c2957e3fa9d2a602f1d",
"snapshot_id": "ddd5999260495e5294af00095680bc49d416d9d8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hirokuma/libhknfcrw_c/9b1bc588945cc34aee123c2957e3fa9d2a602f1d/examples/cyg_devaccess_uart.c",
"visit_date": "2020-12-24T13:35:40.857496"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include "hk_devaccess.h"
// デバッグ設定
//#define DBG_WRITEDATA
//#define DBG_READDATA
//#define HKNFCRW_ENABLE_DEBUG
#ifdef HKNFCRW_ENABLE_DEBUG
#include <stdio.h>
#define LOGI printf
#define LOGE printf
#define LOGD printf
#else
#define LOGI(...)
#define LOGE(...)
#define LOGD(...)
#endif //HKNFCRW_ENABLE_DEBUG
//uart.sh も変更すること
static const char* NFCPCD_DEV = "/dev/com14";
// static const char* NFCPCD_DEV = "/dev/ttyUSB0";
static int s_fd = -1; ///< シリアルポートのファイルディスクリプタ
/**
* ポートオープン
*
* @retval true オープン成功
*/
bool hk_nfcrw_open(void)
{
if(s_fd != -1) {
LOGI("already opened");
return true;
}
//シリアルオープン
#ifndef __CYGWIN__
s_fd = open(NFCPCD_DEV, O_RDWR /*| O_NONBLOCK*/);
#else
s_fd = open(NFCPCD_DEV, O_RDWR); //cygwinだとnon-blockがうまく動かん
#endif
if(s_fd == -1) {
LOGE("open fail.");
return false;
}
//シリアル通信設定
struct termios ter;
memset(&ter, 0, sizeof(ter));
ter.c_iflag = IGNPAR;
//ter.c_oflag = 0;
ter.c_cflag = CLOCAL | CS8 | B115200 | CREAD;
//ter.c_lflag = 0;
//ter.c_cc[VMIN] = 0;
//ter.c_cc[VTIME] = 0;
tcsetattr(s_fd, TCSANOW, &ter);
return true;
}
/**
* ポートクローズ
*/
void hk_nfcrw_close(void)
{
close(s_fd);
s_fd = -1;
}
/**
* ポート送信
*
* @param[in] data 送信データ
* @param[in] len dataの長さ
* @return 送信したサイズ
*/
uint16_t hk_nfcrw_write(const uint8_t* data, uint16_t len)
{
//LOGD("[NfcPcd]_port_write");
#ifdef DBG_WRITEDATA
LOGD("write(%d):", len);
for(int i=0; i<len; i++) {
LOGD("[W]%02x ", data[i]);
}
#endif
errno = 0;
uint16_t ret_len = 0;
do {
ret_len = write(s_fd, data, len);
if(errno) {
LOGE("_port_write:%s", strerror(errno));
}
len -= ret_len;
data += ret_len;
} while(len);
fsync(s_fd);
return ret_len;
}
/**
* 受信
*
* @param[out] data 受信バッファ
* @param[in] len 受信サイズ
*
* @return 受信したサイズ
*
* @attention - len分のデータを受信するか失敗するまで処理がブロックされる。
*/
uint16_t hk_nfcrw_read(uint8_t* data, uint16_t len)
{
//LOGD("[NfcPcd]_port_read");
uint16_t ret_len = 0;
#ifndef __CYGWIN__
fd_set fds;
FD_ZERO(&fds);
FD_SET(s_fd, &fds);
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
do {
errno = 0;
int result = select(FD_SETSIZE, &fds, (fd_set *)0, (fd_set *)0, &tv);
if(result <= 0) {
LOGE("read err: result=%d ret_len=%d [%s]", result, ret_len, strerror(errno));
break;
}
else {
if(FD_ISSET(s_fd, &fds)) {
int nr;
ioctl(s_fd, FIONREAD, &nr);
//LOGD("ret : %d", ret);
if(ret_len + nr > len) {
nr = len - ret_len;
}
ssize_t sz = read(s_fd, data, nr);
ret_len += sz;
}
}
} while(ret_len < len);
#ifdef DBG_READDATA
LOGD("read(%d)", ret_len);
for(int i=0; i<ret_len; i++) {
LOGD("[R]%02x", data[i]);
}
#endif
#else //__CYGWIN__
#ifdef DBG_READDATA
LOGD("read(%d): ", len);
#endif
ret_len = len;
do {
size_t sz = read(s_fd, data, 1);
if(sz == 1) {
#ifdef DBG_READDATA
LOGD("[R]%02x ", *data);
#endif
len--;
data++;
}
} while(len);
#endif //__CYGWIN__
return ret_len;
}
/**
* ポート受信タイムアウト時間設定
*
* タイムアウト処理が可能な場合、受信タイムアウト時間を設定する。
* タイムアウトがない場合は、何も処理しないし、#hk_nfcrw_read()にも影響はない。
*
* @param[in] msec タイムアウト時間(ミリ秒)。0のときはタイムアウト解除。
*/
void hk_nfcrw_read_timeout(uint16_t msec)
{
}
| 2.53125 | 3 |
2024-11-18T21:15:49.010828+00:00 | 2013-12-09T17:23:28 | d567818c5c03790b6103f39640a71d1d43816d66 | {
"blob_id": "d567818c5c03790b6103f39640a71d1d43816d66",
"branch_name": "refs/heads/master",
"committer_date": "2013-12-09T17:23:28",
"content_id": "4ed0b1b132bc11398973955e79cb1100b2d56b42",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f69cd9a03e9db5fa565be4996b62f87cce26ab5e",
"extension": "h",
"filename": "fsm_tool_framework.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6893,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/fsm_tool_framework.h",
"provenance": "stackv2-0112.json.gz:12143",
"repo_name": "leonidc/FSM-tool",
"revision_date": "2013-12-09T17:23:28",
"revision_id": "3142ab1443cf711264e1db11c1419b4041879f79",
"snapshot_id": "65573400d889189aec633ff2383870e55a0972e3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/leonidc/FSM-tool/3142ab1443cf711264e1db11c1419b4041879f79/fsm_tool_framework.h",
"visit_date": "2021-01-16T20:48:45.080123"
} | stackv2 | /***************************************************************/
// File: FsmFramework.h
// Class/Module: C Fsm Framework
//
// Purpose:
// Description:
//
// Modification history:
// 9/1/2009 [LEONIDC] Created
//
//***************************************************************
#ifndef FSM_FRAMEWORK_H
#define FSM_FRAMEWORK_H
#ifndef WIN32
#include "ttypes.h"
#endif
#ifndef UNUSED_PARAM
#define UNUSED_PARAM(PARAM) ((void)(PARAM))
#endif
#define SET_EVENT(class_name , event) \
class_name##_##event##_t * ev = (class_name##_##event##_t *)(fsm->base.current_event); \
UNUSED_PARAM(ev);
#define NULL_EVENT 10001 // for condition state - state used only for check conditions
#define TIMER_EVENT 10002
// auxiliary timer
#define AUX_TIMER_EVENT 10006
#define AUX_TIMEOUT_ID 10007
#define NO_STATE 250
#define DEFAULT_PARAMS_D 0xffdf
#define TRACER_BUF_LEN_D 300
#ifdef WIN32
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned int tbool;
#endif
// Timer functions definition
typedef int (*real_tm_unsched) (void **timer_handler);
typedef int (*real_tm_sched ) (int timeout, void *data, void **timer_handler);
//------------------------------------------------------------------------
// enum defines 3 type of states derived from the Base class StateBase
//------------------------------------------------------------------------
typedef enum fsm_state_types
{
CONDITION,
SIMPLE,
COMPOSED
} fsm_state_types;
//------------------------------------------------------------------------
// enum defines indexes for all simultaneously scheduled timers for FSM
//------------------------------------------------------------------------
typedef enum fsm_timer_index
{
AUX_TMR,
SIMPLE_STATE_TMR,
COMPOSED_STATE_TMR,
LAST_INDEX_TMR
} fsm_timer_index;
//------------------------------------------------------------------------
// enum defines types of consume results
//------------------------------------------------------------------------
typedef enum fsm_consume_results
{
FSM_CONSUMED, // event consumed ok
FSM_NOT_CONSUMED, // event not handled by fsm : normal condition
FSM_CONSUME_ERROR // event erroneously consumed - example: stucked in condition state
} fsm_consume_results;
//**********************************************************************************************************
// TimerMngr
// Defines interfaces to Timer Manager
// User have to define module that interfaces with Real Timer manager of the system.
//
// Goals of TimerMngr : 1.FSM Automatically Scheduler timer upon entering state with timeout.
// 2.FSM framework also unschedule timer upon exit from state with timer.
// 3.User defined Auxiliary timer have to be explicitly scheduled and unscheduled.
//**********************************************************************************************************
typedef struct timer_params
{
unsigned short fsm_timer_id;
void *fsm;
tbool scheduled_status;
void *timer_ref;
} timer_params;
typedef struct timer_mngr
{
void *sched_func;
void *unsched_func;
timer_params client_data[LAST_INDEX_TMR];
} timer_mngr;
//------------------------------------------------------------------------
// Class EventBase - base class for events of real FSM
//------------------------------------------------------------------------
typedef struct fsm_event_base
{
int opcode;
const char *name;
} fsm_event_base;
//------------------------------------------------------------------------
// Specific type of FSM events - Timer event
//------------------------------------------------------------------------
typedef struct fsm_timer_event
{
int opcode;
const char *name;
unsigned short id;
} fsm_timer_event;
//##################################################
// Base struct for State . Defines default behavior
//##################################################
typedef struct fsm_state_base
{
const char *name;
unsigned short id;
fsm_state_types type;
struct fsm_state_base *composed; // points to its Composed state if parent state exist for this state
struct fsm_state_base *default_substate; // if state is Composed it has default substate
void *state_dispatcher;
void *entry_func;
void *exit_func;
} fsm_state_base;
typedef void (*fsm_user_trace) (char *buf, int len);
typedef void (*fsm_state_entry)(void *fsm);
typedef void (*fsm_state_exit) (void *fsm);
typedef fsm_state_base* (*fsm_state_dispatch) (void *fsm, unsigned short state_id);
//##################################################
// Base struct for FSM. Defines default behavior
// all user's FSMs include it
//##################################################
typedef struct fsm_base
{
unsigned short fsm_type; // type of FSM
fsm_state_base *curr_state; // points to current state static Class
fsm_state_base *prev_state; // points to the previous state
fsm_state_base *last_simple_state; // points to the last simple state (to get rid of all condition states between 2 real states)
int consumed_in_composed; // flag risen if last event was consumed in composed state
fsm_event_base *current_event;
int reaction_in_state;
fsm_consume_results consume_event_result; // result of consuming event by FSM
timer_mngr tmr_mngr; // integrated timer manager
int* state_timers; // pointer to the array of timers
fsm_user_trace user_trace;
unsigned char num_states; // number states in the state machine
fsm_state_base *target_state; // target State
int busy_flag; // to avoid recursive entry the FSMs
int err;
} fsm_base;
#ifndef WIN32
void fsm_trace(fsm_base *fsm, const char *format, ...)__attribute__((format(printf,2,3)));
#else
void fsm_trace(fsm_base *fsm, const char *format, ...);
#endif
int fsm_init(fsm_base *fsm, fsm_state_base *curr_state, uint8 num_states,
int *state_timer, fsm_user_trace user_trace,
void *timer_sched, void *timer_unsched);
int fsm_deinit(fsm_base *fsm);
int fsm_schedule_aux_timer(fsm_base *fsm, int timeout);
int fsm_unschedule_aux_timer(fsm_base *fsm);
void fsm_set_timer_value(fsm_base *fsm, int state, int timer_value);
int fsm_get_timer_value(fsm_base *fsm, int state);
void fsm_timer_trigger_operation(fsm_base *fsm, unsigned short id);
fsm_consume_results fsm_handle_event(fsm_base *fsm, fsm_event_base *ev);
fsm_state_base* fsm_state_handle_event(fsm_base *fsm, fsm_state_base *state,
fsm_event_base *ev);
#endif
| 2.171875 | 2 |
2024-11-18T21:15:49.671087+00:00 | 2015-09-01T16:38:20 | dc70da710c401888f9d03b67b2308b792ef27b95 | {
"blob_id": "dc70da710c401888f9d03b67b2308b792ef27b95",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-01T16:38:20",
"content_id": "8a7c2a2686c9dafe255314568663bcb971d75424",
"detected_licenses": [
"MIT"
],
"directory_id": "fd225388a38a3d0fed2b24718382f7c870be4474",
"extension": "h",
"filename": "common.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 41352937,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1704,
"license": "MIT",
"license_type": "permissive",
"path": "/common.h",
"provenance": "stackv2-0112.json.gz:13049",
"repo_name": "ttalvitie/radiosity",
"revision_date": "2015-09-01T16:38:20",
"revision_id": "d9e98e3106935fe40e927314f92704d851926f3c",
"snapshot_id": "bbfc4615eb779861088cb2b87a160140301770fc",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/ttalvitie/radiosity/d9e98e3106935fe40e927314f92704d851926f3c/common.h",
"visit_date": "2020-12-24T14:52:42.726861"
} | stackv2 | /// \file
#pragma once
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
static const float PI = 3.14159265358979323846f;
/// Simple error handler that outputs an error message given in the style of
/// printf() and aborts.
void fail(const char *format, ...);
/// Calls malloc, but if it fails, calls fail().
static inline void* checked_malloc(size_t size) {
void* ret = malloc(size);
if(!ret && size) fail("Could not allocate memory: call to malloc failed.");
return ret;
}
/// Calls malloc with value \p a * \p b, but if the product overflows or malloc
/// fails, calls fail().
static inline void* checked_malloc2(size_t a, size_t b) {
if(a != 0 && b > SIZE_MAX / a) {
fail("Could not allocate memory: size does not fit in size_t.");
}
return checked_malloc(a * b);
}
/// Calls malloc with value \p a * \p b * \p c, but if the product overflows or
/// malloc fails, calls fail().
static inline void* checked_malloc3(size_t a, size_t b, size_t c) {
if(a != 0 && b > SIZE_MAX / a) {
fail("Could not allocate memory: size does not fit in size_t.");
}
return checked_malloc2(a * b, c);
}
/// Calls realloc, but if it fails, calls fail().
static inline void* checked_realloc(void* ptr, size_t size) {
void* ret = realloc(ptr, size);
if(!ret && size) fail("Could not allocate memory: call to realloc failed.");
return ret;
}
/// Calls realloc with parameters (\p ptr, \p a * \p b), but if the product
/// overflows or realloc fails, calls fail().
static inline void* checked_realloc2(void* ptr, size_t a, size_t b) {
if(a != 0 && b > SIZE_MAX / a) {
fail("Could not allocate memory: size does not fit in size_t.");
}
return checked_realloc(ptr, a * b);
}
| 2.984375 | 3 |
2024-11-18T21:15:51.344918+00:00 | 2021-08-25T12:40:43 | e99d34fac7a64eab517bc0c9e829ca1391911f83 | {
"blob_id": "e99d34fac7a64eab517bc0c9e829ca1391911f83",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-25T12:40:43",
"content_id": "ad4065f4a4111f8aa1b5e01a358eb2fa53635595",
"detected_licenses": [
"MIT"
],
"directory_id": "068822c557cb27b73c9fc9bac7f5efe08955e0df",
"extension": "c",
"filename": "crack.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 307490236,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1746,
"license": "MIT",
"license_type": "permissive",
"path": "/hacker2/crack.c",
"provenance": "stackv2-0112.json.gz:13307",
"repo_name": "AlexandreSato/CC50",
"revision_date": "2021-08-25T12:40:43",
"revision_id": "d8438106611fe224c3334265ab30c72786588ebd",
"snapshot_id": "ffbb398bf5b8c7212002dbee48ab24bf77010342",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/AlexandreSato/CC50/d8438106611fe224c3334265ab30c72786588ebd/hacker2/crack.c",
"visit_date": "2023-07-25T16:28:45.401338"
} | stackv2 | /*Programa para quebrar senhas DES-BASED para o curso CC50 ministrado por @Gabriel Lima Guimarães e CS50 por @David J. Malan
Autor: Alexandre Nobuharu Sato em 10 de outubro de 2020 às 16h56min.*/
/* para executar:
alesato@ubuntusato: $ ./crack.c <hash>
Ex:
alesato@ubuntusato: $ ./crack.c 42r8gDz47ETXY
Senha: lemon */
#define _XOPEN_SOURCE
#include <crypt.h>
#include <string.h>
#include <cc50.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
if (argc != 2)
return 1;
char SALT[2];
SALT[0] = argv[1][0];
SALT[1] = argv[1][1];
printf ("SALT DES-BASED: %s\n", SALT);
/*Teste por brute-force, seis loops para seis caracteres lower case
limitados a isto devido minha capacidade computacional*/
for (int LETRA_0 = 97; LETRA_0 <= 122; LETRA_0++)
{
for (int LETRA_1 = 97; LETRA_1 <= 122; LETRA_1++)
{
for (int LETRA_2 = 97; LETRA_2 <= 122; LETRA_2++)
{
for (int LETRA_3 = 97; LETRA_3 <= 122; LETRA_3++)
{
for (int LETRA_4 = 97; LETRA_4 <= 122; LETRA_4++)
{
for (int LETRA_5 = 97; LETRA_5 <= 122; LETRA_5++)
{
char SENHA[6];
SENHA[0] = (char) LETRA_0;
SENHA[1] = (char) LETRA_1;
SENHA[2] = (char) LETRA_2;
SENHA[3] = (char) LETRA_3;
SENHA[4] = (char) LETRA_4;
SENHA[5] = (char) LETRA_5;
char *HASH_TEST = crypt ( SENHA, SALT );
/*É aqui que a mágica acontece, compara com
a senha gerada pelo brute force com o hash
do começo */
printf ("Senha em teste: %s Hash: %s\n", SENHA, HASH_TEST);
if ( !strcmp ( HASH_TEST, argv[1] ))
{
printf ("A senha é: %s\n", SENHA);
return 0;
}
}
}
}
}
}
}
}
| 2.8125 | 3 |
2024-11-18T21:15:51.425624+00:00 | 2023-07-29T09:54:42 | 48d71e162555ef6c23d4bd0d880670310a0a28d0 | {
"blob_id": "48d71e162555ef6c23d4bd0d880670310a0a28d0",
"branch_name": "refs/heads/mjit",
"committer_date": "2023-07-29T09:54:42",
"content_id": "a27ba4e52f938e4dedcfbc26b61ff586f6da9290",
"detected_licenses": [
"MIT"
],
"directory_id": "e37ea57c174698121d7fbfc6cda3eea999ac8c1d",
"extension": "c",
"filename": "ep-session-provider.c",
"fork_events_count": 0,
"gha_created_at": "2019-11-26T05:18:21",
"gha_event_created_at": "2023-07-29T09:54:43",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 224108521,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5048,
"license": "MIT",
"license_type": "permissive",
"path": "/src/native/eventpipe/ep-session-provider.c",
"provenance": "stackv2-0112.json.gz:13435",
"repo_name": "mikedn/runtime",
"revision_date": "2023-07-29T09:54:42",
"revision_id": "fcbcaaf345871e3200acaeddb53255ce25cac0f4",
"snapshot_id": "ec0c7f5dd2340f2b44e3f04bea5518fa6af0debb",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/mikedn/runtime/fcbcaaf345871e3200acaeddb53255ce25cac0f4/src/native/eventpipe/ep-session-provider.c",
"visit_date": "2023-08-16T17:33:16.116940"
} | stackv2 | #include "ep-rt-config.h"
#ifdef ENABLE_PERFTRACING
#if !defined(EP_INCLUDE_SOURCE_FILES) || defined(EP_FORCE_INCLUDE_SOURCE_FILES)
#define EP_IMPL_SESSION_PROVIDER_GETTER_SETTER
#include "ep-session-provider.h"
#include "ep-rt.h"
/*
* Forward declares of all static functions.
*/
static
void
session_provider_free_func (void *session_provider);
/*
* EventPipeSessionProvider.
*/
static
void
session_provider_free_func (void *session_provider)
{
ep_session_provider_free ((EventPipeSessionProvider *)session_provider);
}
EventPipeSessionProvider *
ep_session_provider_alloc (
const ep_char8_t *provider_name,
uint64_t keywords,
EventPipeEventLevel logging_level,
const ep_char8_t *filter_data)
{
EventPipeSessionProvider *instance = ep_rt_object_alloc (EventPipeSessionProvider);
ep_raise_error_if_nok (instance != NULL);
if (provider_name) {
instance->provider_name = ep_rt_utf8_string_dup (provider_name);
ep_raise_error_if_nok (instance->provider_name != NULL);
}
if (filter_data) {
instance->filter_data = ep_rt_utf8_string_dup (filter_data);
ep_raise_error_if_nok (instance->filter_data != NULL);
}
instance->keywords = keywords;
instance->logging_level = logging_level;
ep_on_exit:
return instance;
ep_on_error:
ep_session_provider_free (instance);
instance = NULL;
ep_exit_error_handler ();
}
void
ep_session_provider_free (EventPipeSessionProvider * session_provider)
{
ep_return_void_if_nok (session_provider != NULL);
ep_rt_utf8_string_free (session_provider->filter_data);
ep_rt_utf8_string_free (session_provider->provider_name);
ep_rt_object_free (session_provider);
}
/*
* EventPipeSessionProviderList.
*/
EventPipeSessionProviderList *
ep_session_provider_list_alloc (
const EventPipeProviderConfiguration *configs,
uint32_t configs_len)
{
ep_return_null_if_nok ((configs_len == 0) || (configs_len > 0 && configs != NULL));
EventPipeSessionProviderList *instance = ep_rt_object_alloc (EventPipeSessionProviderList);
ep_raise_error_if_nok (instance != NULL);
ep_rt_session_provider_list_alloc (&instance->providers);
ep_raise_error_if_nok (ep_rt_session_provider_list_is_valid (&instance->providers));
instance->catch_all_provider = NULL;
for (uint32_t i = 0; i < configs_len; ++i) {
const EventPipeProviderConfiguration *config = &configs [i];
EP_ASSERT (config != NULL);
// Enable all events if the provider name == '*', all keywords are on and the requested level == verbose.
if ((ep_rt_utf8_string_compare(ep_provider_get_wildcard_name_utf8 (), ep_provider_config_get_provider_name (config)) == 0) &&
(ep_provider_config_get_keywords (config) == 0xFFFFFFFFFFFFFFFF) &&
((ep_provider_config_get_logging_level (config) == EP_EVENT_LEVEL_VERBOSE) && (instance->catch_all_provider == NULL))) {
instance->catch_all_provider = ep_session_provider_alloc (NULL, 0xFFFFFFFFFFFFFFFF, EP_EVENT_LEVEL_VERBOSE, NULL );
ep_raise_error_if_nok (instance->catch_all_provider != NULL);
}
else {
EventPipeSessionProvider * session_provider = ep_session_provider_alloc (
ep_provider_config_get_provider_name (config),
ep_provider_config_get_keywords (config),
ep_provider_config_get_logging_level (config),
ep_provider_config_get_filter_data (config));
ep_raise_error_if_nok (ep_rt_session_provider_list_append (&instance->providers, session_provider));
}
}
ep_on_exit:
return instance;
ep_on_error:
ep_session_provider_list_free (instance);
instance = NULL;
ep_exit_error_handler ();
}
void
ep_session_provider_list_free (EventPipeSessionProviderList *session_provider_list)
{
ep_return_void_if_nok (session_provider_list != NULL);
ep_rt_session_provider_list_free (&session_provider_list->providers, session_provider_free_func);
ep_session_provider_free (session_provider_list->catch_all_provider);
ep_rt_object_free (session_provider_list);
}
void
ep_session_provider_list_clear (EventPipeSessionProviderList *session_provider_list)
{
EP_ASSERT (session_provider_list != NULL);
ep_rt_session_provider_list_clear (&session_provider_list->providers, session_provider_free_func);
}
bool
ep_session_provider_list_is_empty (const EventPipeSessionProviderList *session_provider_list)
{
EP_ASSERT (session_provider_list != NULL);
return (ep_rt_session_provider_list_is_empty (&session_provider_list->providers) && session_provider_list->catch_all_provider == NULL);
}
bool
ep_session_provider_list_add_session_provider (
EventPipeSessionProviderList *session_provider_list,
EventPipeSessionProvider *session_provider)
{
EP_ASSERT (session_provider_list != NULL);
EP_ASSERT (session_provider != NULL);
return ep_rt_session_provider_list_append (&session_provider_list->providers, session_provider);
}
#endif /* !defined(EP_INCLUDE_SOURCE_FILES) || defined(EP_FORCE_INCLUDE_SOURCE_FILES) */
#endif /* ENABLE_PERFTRACING */
#ifndef EP_INCLUDE_SOURCE_FILES
extern const char quiet_linker_empty_file_warning_eventpipe_session_provider;
const char quiet_linker_empty_file_warning_eventpipe_session_provider = 0;
#endif
| 2.046875 | 2 |
2024-11-18T21:15:51.577787+00:00 | 2016-12-28T19:57:10 | 70df54bd02d08b65eb5cdf14c389a8df671da169 | {
"blob_id": "70df54bd02d08b65eb5cdf14c389a8df671da169",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-28T19:57:10",
"content_id": "94ff517c35fa02718c3e12f8fccb17fe755b47cb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "59d379fea3acf47e9da81a6f718f475e652b7aa8",
"extension": "h",
"filename": "testHooks.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 49103687,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2088,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/simulator/testHooks.h",
"provenance": "stackv2-0112.json.gz:13564",
"repo_name": "MINDS-i/Drone-Tests",
"revision_date": "2016-12-28T19:57:10",
"revision_id": "212fa812ce0825fd059ddb9fcf95042a5c7f73cb",
"snapshot_id": "3c5f3b341ce32442f1db60d2783df4c86bf1ab33",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/MINDS-i/Drone-Tests/212fa812ce0825fd059ddb9fcf95042a5c7f73cb/simulator/testHooks.h",
"visit_date": "2020-04-12T07:25:06.597739"
} | stackv2 | #pragma once
#include <avr/io.h>
#include <avr/sleep.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include "testHooksCommon.h"
#include "Arduino.h"
/* Configure communication ports as writable IO registers */
#define DBGS _MMIO_BYTE(SIGNAL_IO_NUM)
#define DBGD _MMIO_BYTE(DATA_IO_NUM)
#define FIX_SUBLIME_TEXT_HIGHLIGHTING_BUG
/* Call with printf syntax to start a test of a given name */
#define beginTest(testName, ...) \
do { \
DBGS = NAME_START; \
printf(testName, ##__VA_ARGS__); \
DBGS = CLOCK_START; \
} while(0)
#define passTest() \
do { \
DBGS = TEST_PASS; \
} while(0)
#define failTest() \
do { \
DBGS = TEST_FAIL; \
} while(0)
#define benchFinish() \
do { \
DBGS = BENCH_FINISH; \
} while(0)
#define TEST_NAMED(test, name, ...) \
do { \
beginTest(name, ##__VA_ARGS__); \
if (test()) { \
passTest(); \
} else { \
failTest(); \
} \
} while(0)
#define TEST(testFunc) TEST_NAMED(testFunc, #testFunc)
#define BENCHMARK_NAMED(mark, name, ...) \
do { \
beginTest(name, ##__VA_ARGS__); \
mark(); \
benchFinish(); \
} while(0)
#define BENCHMARK(markFunc) BENCHMARK_NAMED(markFunc, #markFunc)
#define ASSERT(a) \
do { \
if(!a) { \
printf("%s was false", #a); \
return false; \
} \
} while(0)
#define CASSERT(a,b) \
do { \
if(!((a) == (b))) { \
printf("%s != %s", #a, #b); \
return false; \
} \
} while(0)
#define FPASSERT(a,b) \
do { \
const float ans = a; \
const float chk = b; \
if(!fuzzyCompare(ans,chk)) { \
printf("%s=%f != %f", #a, ans, chk); \
return false; \
} \
} while(0)
#define FPASSERTC(a,b,c) \
do { \
const float ans = a; \
const float chk = b; \
if(!fuzzyCompare(a,b,c)) { \
printf("%s=%f != %f", #a, ans, chk); \
return false; \
} \
} while(0)
| 2.21875 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.