language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "hash.h" #include "header.h" //********** Functions *********** int *procCigar(char *cigar, int *cigs){ char *num; int pos=0; cigs[0]=0; num=malloc(20*sizeof(char)); // printf("%s\n", cigar); for(int t=0; t<strlen(cigar); t++){ switch(*(cigar+t)) { case 'M': strncpy(num, cigar+pos, (t-pos)*sizeof(char)); num[t-pos]='\0'; // printf("%s %d %d\n", num, pos, t); pos=t+1; sscanf(num, "%d", &cigs[cigs[0]+1]); cigs[0]++; break; case 'D': case 'P': case 'H': case 'N': case 'S': strncpy(num, cigar+pos, (t-pos)*sizeof(char)); num[t-pos]='\0'; sscanf(num, "%d", &cigs[cigs[0]+1]); cigs[cigs[0]+1]*=-1; pos=t+1; cigs[0]++; break; case 'I': pos=t+1; break; default: strncat(num, cigar, 1); break; } } free(cigar); free(num); return(cigs); } void addRead2Frag(const char *qname, const char *chr, int start, int strand, int cigar, int totF, read_t *frags, int read){ if(read==1) { frags[totF].nreads=1; frags[totF].strand_1=cigar; } else { frags[totF].nreads=2; frags[totF].strand_2=cigar; } } //void addRead2Frag(const char *qname, const char *chr, int start, int strand, const char *cigar, int totF, read_t *frags, int read){ /*void addRead2Frag(const char *qname, const char *chr, int start, int strand, int cigar, int totF, read_t *frags, int read){ if(read==1){ frags[totF].qname = malloc((strlen(qname)+1) * sizeof(char)); strcpy(frags[totF].qname, qname); if(strlen(chr)>0) { frags[totF].chr_1 = malloc((strlen(chr)+1) * sizeof(char)); strcpy(frags[totF].chr_1, chr); } frags[totF].st_1=start; // frags[totF].cigar_1 = malloc((strlen(cigar)+1) * sizeof(char)); // strcpy(frags[totF].cigar_1, cigar); frags[totF].cigar_1 = cigar; frags[totF].strand_1=strand; frags[totF].nreads=1; } else { if(strlen(chr)>0) { frags[totF].chr_2 = malloc((strlen(chr)+1) * sizeof(char)); strcpy(frags[totF].chr_2, chr); } frags[totF].st_2=start; //frags[totF].cigar_2 = malloc((strlen(cigar)+1) * sizeof(char)); //strcpy(frags[totF].cigar_2, cigar); frags[totF].cigar_2 = cigar; frags[totF].strand_2 = strand; frags[totF].nreads=2; } } */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #define PORT 4444 const int NUM_INTERFACE = 2; struct control{ char interface[50], alias[50], mode[50]; }; struct lan{ char interface[50], rule[50], proto[50], srcip[50], srcmac[50], mask[50]; }; void show(struct control list[]){ printf("Interface Alias\t Filter Rule Mode\n"); for(int i = 1; i < NUM_INTERFACE; i++){ printf("%s\t", list[i].interface); printf("%s\t", list[i].alias); printf("%s\t", list[i].mode); printf("\n"); } } void show_rule(struct lan _lan){ printf("Rule updated!\n"); printf("Interface:\t%s\n", _lan.interface); printf("Rule:\t%s\n", _lan.rule); printf("Protocol:\t%s\n", _lan.proto); printf("Source IP:\t%s\n", _lan.srcip); printf("Source MAC:\t%s\n", _lan.srcmac); printf("Mac mask:\t%s\n", _lan.mask); } int true_ip(char ip[]){ char *p; int tmp; p = strtok(ip, "."); while(p!=NULL){ tmp = atoi(p); if(tmp < 0 || tmp >255) return 0; p = strtok(NULL, "."); } return 1; } int main(){ int clientSocket, ret; struct sockaddr_in serverAddr; char buffer[1024]; struct control list_control[5]; clientSocket = socket(AF_INET, SOCK_STREAM, 0); if(clientSocket < 0){ printf("[-]Error in connection.\n"); exit(1); } printf("[+]Client Socket is created.\n"); memset(&serverAddr, '\0', sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(PORT); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); /* char username[]="Dasan"; char password[]="123456"; char user[50], pass[50]; printf("Username: "); gets(user); printf("Password: "); gets(pass); while(strcmp(user, username)!=0||strcmp(pass, password)!=0) { printf("\nUsername or password incorrect\n"); printf("Username: "); gets(user); printf("Password: "); gets(pass); }*/ ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)); if(ret < 0){ printf("[-]Error in connection.\n"); exit(1); } printf("[+]Connected to Server.\n"); printf("LOGIN TO SERVER\n"); printf("User name: \t"); scanf("%s", &buffer[0]); send(clientSocket,buffer,50,0); printf("Password: \t"); scanf("%s", &buffer[0]); send(clientSocket,buffer,50,0); char sta[50]; recv(clientSocket,sta,50,0); while(strcmp(sta,"Wellcome Admin!")!=0) { memset(buffer, '\0', 50); printf("LOGIN TO SERVER\n"); printf("User name: \t"); scanf("%s", &buffer[0]); send(clientSocket,buffer,50,0); printf("Password: \t"); scanf("%s", &buffer[0]); send(clientSocket,buffer,50,0); recv(clientSocket,sta,50,0); } printf("=== WELLCOME ADMIN===\n"); for(int i = 1; i < NUM_INTERFACE; i++){ recv(clientSocket, list_control[i].interface, 50, 0); recv(clientSocket, list_control[i].alias, 50, 0); recv(clientSocket, list_control[i].mode, 50, 0); } show(list_control); while(1){ printf("Client: \t"); scanf("%s", &buffer[0]); send(clientSocket, buffer, 1024, 0); if(strcmp(buffer, ":exit") == 0){ close(clientSocket); printf("[-]Disconnected from server.\n"); exit(1); } if(strcmp(buffer, "set") == 0){ scanf("%s", &buffer[0]); send(clientSocket, buffer, 50, 0); scanf("%s", &buffer[0]); send(clientSocket, buffer, 50, 0); char status[50] = "False!"; recv(clientSocket, status, 50, 0); printf("%s\n", status); for(int i = 1; i < NUM_INTERFACE; i++){ recv(clientSocket, list_control[i].interface, 50, 0); recv(clientSocket, list_control[i].alias, 50, 0); recv(clientSocket, list_control[i].mode, 50, 0); } show(list_control); printf("Client set: %s\n", status); } else if(strcmp(buffer, "block") == 0){ scanf("%s", buffer); send(clientSocket, buffer, 1024, 0); if(strcmp(buffer, "ip") == 0){ char ip[50], status[50]; scanf("%s", ip); send(clientSocket, ip, 50, 0); recv(clientSocket, status, 50, 0); if(strcmp(status, "Wrong IP!") == 0){ printf("%s\n", status); continue; } char size[5]; recv(clientSocket, size, 10, 0); printf("%d\n", atoi(size)); printf("Black list IP:\n"); for(int i = 0; i < atoi(size); i++){ recv(clientSocket, ip, 50, 0); printf("%s\n", ip); } printf("%s\n", status); } if(strcmp(buffer, "rangeIP") == 0){ char ip[50], status[50]; scanf("%s", ip); send(clientSocket, ip, 50, 0); recv(clientSocket, status, 50, 0); char size[5]; recv(clientSocket, size, 10, 0); printf("%d\n", atoi(size)); printf("BlackList IP:\n"); for(int i = 0; i < atoi(size); i++){ recv(clientSocket, ip, 50, 0); printf("%s\n", ip); } printf("%s\n", status); } if(strcmp(buffer, "all")==0){ char status[50]; recv(clientSocket, status,50,0); printf("%s\n",status); } if(strcmp(buffer, "mac") == 0){ char mac[50], status[50]; scanf("%s", mac); send(clientSocket, mac, 50, 0); recv(clientSocket, status, 50, 0); char size[5]; recv(clientSocket, size, 10, 0); printf("%d\n", atoi(size)); printf("BlackList MAC:\n"); for(int i = 0; i < atoi(size); i++){ recv(clientSocket, mac, 50, 0); printf("%s\n", mac); } printf("%s\n", status); } } else if(strcmp(buffer, "allow") == 0){ scanf("%s", buffer); send(clientSocket, buffer, 1024, 0); if(strcmp(buffer, "ip") == 0){ char ip[50], status[50]; scanf("%s", ip); send(clientSocket, ip, 50, 0); recv(clientSocket, status, 50, 0); if(strcmp(status, "Wrong IP!") == 0){ printf("%s\n", status); continue; } char size[5]; recv(clientSocket, size, 10, 0); printf("%d\n", atoi(size)); printf("WhiteList IP:\n"); for(int i = 0; i < atoi(size); i++){ recv(clientSocket, ip, 50, 0); printf("%s\n", ip); } printf("%s\n", status); } if(strcmp(buffer, "rangeIP") == 0){ char ip[50], status[50]; scanf("%s", ip); send(clientSocket, ip, 50, 0); recv(clientSocket, status, 50, 0); if(strcmp(status, "Wrong IP!") == 0){ printf("%s\n", status); continue; } char size[5]; recv(clientSocket, size, 10, 0); printf("%d\n", atoi(size)); printf("WhiteList IP:\n"); for(int i = 0; i < atoi(size); i++){ recv(clientSocket, ip, 50, 0); printf("%s\n", ip); } printf("%s\n", status); } if(strcmp(buffer, "all")==0){ char status[50]; recv(clientSocket, status,50,0); printf("%s\n",status); } if(strcmp(buffer, "mac") == 0){ char mac[50], status[50]; scanf("%s", mac); send(clientSocket, mac, 50, 0); recv(clientSocket, status, 50, 0); char size[5]; recv(clientSocket, size, 10, 0); printf("%d\n", atoi(size)); printf("WhiteList MAC:\n"); for(int i = 0; i < atoi(size); i++){ recv(clientSocket, mac, 50, 0); printf("%s\n", mac); } printf("%s\n", status); } } else if(strcmp(buffer, "update") == 0){ scanf("%s", &buffer[0]); send(clientSocket, buffer, 50, 0); scanf("%s", &buffer[0]); send(clientSocket, buffer, 50, 0); char status[50] = "False!"; recv(clientSocket, status, 50, 0); if(strcmp(status, "Premiss Denied!") == 0) { printf("Server update: %s\n", status); continue; } for (int i = 0; i < 5; ++i) { recv(clientSocket, buffer, 1024, 0); printf("%s", buffer); scanf("%s", &buffer[0]); send(clientSocket, buffer, strlen(buffer), 0); } printf("Server update: %s\n", status); struct lan _lan; recv(clientSocket, _lan.interface, 50, 0); recv(clientSocket, _lan.rule, 50, 0); recv(clientSocket, _lan.proto, 50, 0); recv(clientSocket, _lan.srcip, 50, 0); recv(clientSocket, _lan.srcmac, 50, 0); recv(clientSocket, _lan.mask, 50, 0); show_rule(_lan); } else if(strcmp(buffer, "delete") == 0){ scanf("%s", &buffer[0]); send(clientSocket, buffer, strlen(buffer), 0); char status[50] = "False!"; recv(clientSocket, status, 50, 0); printf("Server delete: %s\n", status); } else{ recv(clientSocket, buffer, 1024, 0); printf("Server:\t%s\n", buffer); } } return 0; }
C
/* Demo code to toggle the Nth bit of given integer */ #include <stdio.h> int main() { //declaration of variable int num,num2; int toggle; char choice; do { unsigned mask = 1 << ((sizeof(int) << 3) - 1); unsigned mask2 = 1 << ((sizeof(int) << 3) - 1); //prompt the user to enter the number printf("Enter the number: "); //Read the number scanf("%d", &num); //Prompt the user to enter the bit position to be set printf("Enter the position of bit to be toggled: "); //Read the Bit position scanf("%d", &toggle); //print the binary of entered number before shifting printf("%d before user toggled %d bit\n", num, toggle); for ( ; mask; mask >>= 1) { num & mask ? putchar('1') : putchar('0'); } //store original number in another variable num2 = num; num2 ^= (1 << toggle); //print the binary of shifted number printf("\n%d become %d after user toggle %d bit\n", num,num2, toggle); for ( ; mask2; mask2 >>= 1) { num2 & mask2 ? putchar('1') : putchar('0'); } //Prompt the user to enter the choice to continue or not printf("\nDo you want to continue?\nPress Y/y(Yes) or any other key to exit:"); //read the choice scanf(" %c", &choice); } while ('Y' == choice || 'y' == choice); return 0; }
C
#include "lists.h" /** * add_dnodeint - new node at the beginning * @head: double pointer to head * @n: value * Return: pointer of node */ dlistint_t *add_dnodeint(dlistint_t **head, const int n) { dlistint_t *nNode; dlistint_t *tmp = *head; nNode = malloc(sizeof(dlistint_t)); if (!nNode) { dprintf(2, "Error: Can't malloc\n"); return (NULL); } nNode->n = n; nNode->prev = NULL; if (tmp == NULL) { *head = nNode; nNode->next = NULL; return (nNode); } nNode->next = tmp; tmp->prev = nNode; *head = nNode; return (nNode); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_NUM 51 int arr[MAX_NUM]; int main(int argc, char **argv) { int i, n, sum, avg, total, tests=0; while(scanf("%d", &n)!=EOF && n!=0) { sum = total = 0; for(i=0; i<n; i++) { scanf("%d", arr+i); sum += arr[i]; } avg = sum/n; for(i=0; i<n; i++) if(arr[i] > avg) total += (arr[i]-avg); printf("Set #%d\nThe minimum number of moves is %d.\n\n", ++tests, total); } }
C
//#include <stdio.h> //#include <stdlib.h> //#include <conio.h> //int main(void) //{ // char c; // while (1) // { // c=_getch(); // ʾҪзŵġ̨ϲʾϢ // printf("%c\n",c); // } // system("pause"); // return 0; //}
C
/* ** EPITECH PROJECT, 2019 ** MUL_my_defender_2018 ** File description: ** free_turrets */ #include <SFML/Graphics/CircleShape.h> #include <stdlib.h> #include "my_defender.h" void free_turret(turret_t *turret) { sfSprite_destroy(turret->sprite); sfTexture_destroy(turret->texture); sfCircleShape_destroy(turret->range_circle); sfClock_destroy(turret->clock); free(turret); } void free_turrets(turret_t *turrets) { while (turrets != NULL) { free_turret(turrets); turrets = turrets->next; } }
C
#include <stdio.h> #define SIZE 10 void quicksort(int *a, size_t n); int main() { int i; int a[SIZE] = { 4, 6, 10, 6, 90,8, 1 , 34,77, 40 }; for(i=0; i<SIZE; i++) { printf("%d ", a[i]); } printf("\n"); quicksort(a, SIZE); for(i=0; i<SIZE; i++) { printf("%d ", a[i]); } printf("\n"); return 0; } void quicksort(int *a, size_t n) { if (n <= 1) { return; } int i,j,k, mid, temp, pos; mid = a[n/2]; int correct = mid; i=0; j=n-1; printf("Before exchange: i=%d mid=%d j=%d\n", i,mid,j); while(i < j) { while(a[i] <= mid) { i++; } while(a[j] > mid) { j--; } if (i < j) { printf("\tExchanging %d and %d ... \n", a[i], a[j]); temp = a[i]; a[i] = a[j]; a[j] = temp; pos = j; for(k=0; k<SIZE; k++) { printf("%d ", a[k]); } printf("\n"); } } printf("%d is now at correct position %d. n=%d i=%d j=%d\n", correct, pos, n, i, j); for(k=0; k<SIZE; k++) { printf("%d ", a[k]); } printf("\n"); printf("Left quick sort with n = %d\n", pos-1); quicksort(a, pos-1); printf("Right quick sort starting at index %d with n = %d\n",pos+1, n-pos-1); quicksort(a+pos+1, n-pos-1); //quicksort(a+mid+1, n%2? mid : mid - 1); }
C
/* C program to find the inverse of a square matrix where the 2D matrix is given as 1D arrar*/ #include <stdio.h> #include <stdlib.h> void cofac(int A[],int i, int j, int tmp[], int n) { int p,q,l,k; p=0; q=0; for(k=0;k<n;k++) { for(l=0;l<n;l++) { if(k!=i && l!=j) { tmp[p*(n-1)+q]=A[n*k+l]; q++; if(q==n-1) { q=0; p++; } } } } } int det(int A[], int n) { int D=0; if(n==1) { return A[0]; } else { int *tmp=(int*)malloc(((n-1)*(n-1))*sizeof(int)); int sn=1; int i; for(i=0;i<n;i++) { cofac(A,0,i,tmp,n); D += sn * A[i] * det(tmp, n - 1); sn=-sn; } return D; } } void adj(int A[],int ad[], int n) { if(n==1) ad[0]=1; else { int sn=1; int i,j; int* temp=(int*)malloc(((n-1)*(n-1))*sizeof(int)); for(i=0;i<n;i++) { for(j=0;j<n;j++) { cofac(A,i,j,temp,n); if((i+j)%2==0) sn=1; else sn=-1; ad[j*n+i]=sn*(det(temp,n-1)); } } } } void inv(int A[],float invs[],int n) { int d=det(A,n); int i,j; int* ad=(int*)malloc((n*n)*sizeof(int)); adj(A,ad,n); for(i=0;i<n;i++) { for(j=0;j<n;j++) { invs[i*n+j]=ad[i*n+j]/(float)d; } } } int main() { int k; int i; printf("Enter the order of the Matrix : "); scanf("%d", &k); int* A=(int*)malloc((k*k)*sizeof(int)); float* invs=(float*)malloc((k*k)*sizeof(float)); printf("Enter the elements of %dX%d Matrix : \n", k, k); for (i = 0;i < k*k; i++) { scanf("%d", &A[i]); } inv(A,invs,k); for(i=0;i<k;i++) { for(int j=0;j<k;j++) printf("%d ",A[i*k+j]); } printf("%d",det(A,k)); for (i = 0;i < k*k; i++) { printf("%f ", invs[i]); } return 0; }
C
#include <stdio.h> #include <string.h> int main(int argc, char **argv) { char input[1024]; // read a line of standard input. use fgets() - use "man fgets" for reference // the "stream" to read from is standard input, 'stdin' // read 1023 characters into 'input'. fgets(input, 1023, stdin); // now use strtok() and some temporary pointers to print out each word // on a separate line. (use printf("%s\n",word_ptr); to print a word); char* string; printf("Input words are...\n"); printf("%s", strtok(input, " ")); while ((string = strtok(NULL, " ")) != NULL) { printf("\n%s", string); } return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { int num1; double result; scanf("%d",&num1); result=num1*num1*3.14; printf("%.2lf",result); }
C
#include "binary_trees.h" /** * binary_tree_balance - balance factor * @tree: pointer to root * Return: 0 if tree is NULL, otherwise balance factor */ int binary_tree_balance(const binary_tree_t *tree) { if (tree) return (binary_tree_height(tree->left) - binary_tree_height(tree->right)); return (0); } /** * binary_tree_height - returns height of binary tree recursively * @tree: root * Return: void **/ size_t binary_tree_height(const binary_tree_t *tree) { if (tree == NULL) return (0); else { /* compute the depth of each subtree */ int lDepth = binary_tree_height(tree->left); int rDepth = binary_tree_height(tree->right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); return (rDepth + 1); } }
C
#include "watchdog.h" void set_LED_RED(){ GPIOF->DATA |= LED_RED; } void clear_LED_RED(){ GPIOF->DATA &= ~LED_RED; } void set_LED_GREEN(){ GPIOF->DATA |= LED_GREEN; } void clear_LED_GREEN(){ GPIOF->DATA &= ~LED_GREEN; } void clear_LED(){ GPIOF->DATA &= ~(LED_GREEN | LED_RED); } void delay_miliseconds(unsigned int n){ for(unsigned volatile int i = 0; i < MILISECONDS_CONSTANT * n; i++); } void delay_seconds(unsigned int n){ for(unsigned volatile int i = 0; i < SECONDS_CONSTANT * n; i++); } void gpio_init(){ SYSCTL->RCGCGPIO = GPIO_PORTF; GPIOF->DIR = LED_RED | LED_GREEN; GPIOF->DEN = LED_RED | LED_GREEN; } void watchdog_init(){ SYSCTL->RCGCWD = W0; NVIC->ISER[0] = WDT0; } void enable_watchdog0_interrupt(){ WATCHDOG0->CTL |= INTEN; } void WDT0_Handler(){ clear_LED_GREEN(); set_LED_RED(); WATCHDOG0->ICR = 0; } int main(){ //generating random delay unsigned int delay_time = (unsigned int)(rand() % MILISECONDS_CONSTANT); //use SECONDS_CONSTANT for seconds delay watchdog_init(); gpio_init(); while(1){ if(!(GPIOF->DATA & LED_RED)){ set_LED_GREEN(); } WATCHDOG0->LOAD = WDT_LOADVALUE; //adjust the load value to trigger interrupt, keeping delay constant. If execution reaches here before delay, normal operation. enable_watchdog0_interrupt(); //triggers interrupt if value = 0 while delay is executed. delay_miliseconds(delay_time); //adjust the delay to trigger interrupt, keeping load value constant. Argument can be random or a constant value. } }
C
#include <stdio.h> #include "date.h" void main() { Date *date1 = create_date(12, 10, 2000); print_date(date1); Date *date2 = create_date(14, 8, 2000); print_date(date2); Person *pierrick = create_person("Dossin", "Pierrick", date2); print_person(pierrick); printf("%d %d\n", compare_date(date1, date2), compare_date(date1, date1)); Person *pierrickbis = dupliquer_person(pierrick); print_person(pierrickbis); List *list = create_list(date1); List *list2 = insert(date2, list); print_list(list2); }
C
/* Author: Marc Lee (Changhwan) duckid: clee3 Title: CIS415 project2 threadfxn for part2/3 This is my own work. */ #ifndef TFXN_C #define TFXN_C #include "threadfxn.h" void init() { pthread_mutex_init(&plock, NULL); pthread_mutex_init(&slock, NULL); } void* publisher(void* param) { /* wait for main thread's flag change. BUSY WAITING */ while (!flag) { sleep(1); } pthread_mutex_lock(&plock); thread_info* t_info = (thread_info *) param; int num = t_info->thread_num; printf("publisher thread %d reading from %s\n", num, t_info->str); pthread_mutex_unlock(&plock); free(t_info->str); return NULL; } void* subscriber(void* param) { /* wait for main thread's flag change. BUSY WAITING */ while(!flag) { sleep(1); } pthread_mutex_lock(&slock); thread_info* t_info = (thread_info *) param; int num = t_info->thread_num; printf("subscriber thread %d reading from %s\n", num, t_info->str); free(t_info->str); pthread_mutex_unlock(&slock); return NULL; } void* cleanup(void* param) { pthread_t tid = pthread_self(); printf("dequeue thread created!\n"); while (!done) { sleep(1); } printf("Current Cleanup Thread ID: %d\n", (int) tid); return NULL; } #endif
C
#ifndef _DICTIONARY_H_INCLUDE_ #define _DICTIONARY_H_INCLUDE_ #include<stdio.h> typedef struct LinkedListObj* LinkedList; typedef struct NodeObj* Node; Node newNode(int x); LinkedList newLinkedList(void); void freeLinkedList(LinkedList* pS); void addNode(Node N, LinkedList S); void printList(LinkedList S); void printLinkedList(FILE* out, LinkedList S); void insert(int number, LinkedList S); Node find(int number, LinkedList S); void delete(int n, LinkedList S); #endif
C
/* * biblioteca.h * * Created on: 19 de nov de 2018 * Author: amanda.oliveira */ #ifndef BIBLIOTECA_H_ #define BIBLIOTECA_H_ //Macros e constantes #define RANDOMICO rand() //Estruturas e novos tipos struct dados{ int codigo; struct dados *anterior; struct dados *proximo; }; typedef struct dados dados; //Prottipos void menu(); dados* inserirInicio(dados *lista); void imprimirLista(dados *lista, int contador); dados* inserirFimUltimo(dados *ultimo); dados* inserirFim(dados *lista); dados* excluirRegistro(int codigo, dados *lista); #endif /* BIBLIOTECA_H_ */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <stdarg.h> #include "rfifo.h" #include "julog.h" int runloop = 0; static rfifo fifo; #define RET_DATA_SIZE 10 #define MAX_CHUNK_NUM 6 static unsigned short frame_no = 0; static unsigned int cid = 0; #define RFIFO_FULL 1 int new_chunk_to_rfifo(rfifo *f ,unsigned int i) { char *pdata = NULL; int data_size = 0; int rc = 0; pdata = rfifo_acquire_chunk_buf(f); if (!pdata) return RFIFO_FULL; cid %= MAX_CHUNK_NUM; data_size = snprintf((char *)pdata, CHUNK_DATA_SIZE-1, "c%u data%u", cid, i); cid++; rc = rfifo_filled_chunk_buf(f, frame_no++, (unsigned int )data_size); #ifdef HAVE_DUMP_CHUNK rfifo_dump_chunk(&fifo, i); #endif /* HAVE_DUMP_CHUNK */ return rc; } void *thread_chunk_consumer(void *parg) { char *ret = (char *)malloc(RET_DATA_SIZE); pthread_t tid = pthread_self(); JULOG("thread consumer started %lu\n", tid); while (1) { int rc = 0; runloop++; char *r = rfifo_play_chunk(&fifo); if (r == NULL) { //#define HAVE_DEBUG_NO_NEW_CHUNK 1 #ifdef HAVE_DEBUG_NO_NEW_CHUNK JULOG("%d no new chunk, wait...\n", runloop); #endif usleep(15000); continue; } JULOG("%d cnt=%u rc = %d, data: %s\n", runloop, fifo.count, rc, r); rc = rfifo_played_chunk(&fifo); usleep(33000); } strncpy(ret, "123456789", RET_DATA_SIZE); JULOG("thread comsumer exit %lu\n", tid); pthread_exit((void *) ret); } void *thread_chunk_producer(void *parg) { unsigned int i = 1; unsigned int delay = 1; pthread_t tid = pthread_self(); JULOG("thread producer started %lu\n", tid); while (1) { int rc = 0; if (i % 50 == 0) { delay = 15000; } else { if (i % 85 == 0) delay = 1000000; else delay = 33000; } rc = new_chunk_to_rfifo(&fifo, ++i); while (rc == RFIFO_FULL) { usleep(10); continue; } usleep(delay); } JULOG("thread producer exit %lu\n", tid); pthread_exit(0); } int main(int argc, char **argv) { unsigned int num = MAX_CHUNK_NUM; char *r = NULL; int rc = 0; pthread_t tid[2]; rc = rfifo_init(&fifo, num); pthread_create(&tid[0], NULL, &thread_chunk_consumer, &num); pthread_create(&tid[1], NULL, &thread_chunk_producer, &num); pthread_join(tid[0], (void **)&r); pthread_join(tid[1], NULL); JULOG("r=[%s]\n", r); free(r); return rc; }
C
#include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #include <stdlib.h> static char *sort_location = "AllSorts"; void run(char *file, char *run, char *stat, char *k) { chdir(sort_location); char *args[] = {"make", file, NULL}; if (fork() == 0) { execvp(args[0], args); } else { wait(NULL); } char *clean = "clean"; args[1] = clean; if (fork() == 0) { execvp(args[0], args); } else { wait(NULL); } char *args2[] = {run, stat, k, NULL}; execvp(args2[0], args2); } int main(int argc, char *argv[]) { if (argc == 5) { char *type = NULL; char *comp = NULL; for (int i=1; i<=4; i++) { if (strcmp(argv[i], "--type") == 0) { type = argv[i+1]; } else if (strcmp(argv[i], "--comp") == 0) { comp = argv[i+1]; } } if (type == NULL || comp == NULL) { fprintf(stderr, "Bad arguments\n"); exit(1); } if (strcmp(type, "insert") == 0) { if (strcmp(comp, "<=") == 0) { run("InsertionSortle", "./InsertionSortle", NULL, NULL); } else if (strcmp(comp, ">=") == 0) { run("InsertionSortge", "./InsertionSortge", NULL, NULL); } } else if (strcmp(type, "merge") == 0) { if (strcmp(comp, "<=") == 0) { run("MergeSortle", "./MergeSortle", NULL, NULL); } else if (strcmp(comp, ">=") == 0) { run("MergeSortge", "./MergeSortge", NULL, NULL); } } else if (strcmp(type, "quick") == 0) { if (strcmp(comp, "<=") == 0) { run("QuickSortle", "./QuickSortle", NULL, NULL); } else if (strcmp(comp, ">=") == 0) { run("QuickSortge", "./QuickSortge", NULL, NULL); } } else if (strcmp(type, "dpquick") == 0) { if (strcmp(comp, "<=") == 0) { run("DPQuickle", "./DPQuickle", NULL, NULL); } else if (strcmp(comp, ">=") == 0) { run("DPQuickge", "./DPQuickge", NULL, NULL); } } else if (strcmp(type, "hybridmi") == 0) { if (strcmp(comp, "defined") == 0) { run("HybridSortMI", "./HybridSortMI", NULL, NULL); } } else if (strcmp(type, "hybridqi") == 0) { if (strcmp(comp, "defined") == 0) { run("HybridSortQI", "./HybridSortQI", NULL, NULL); } } else if (strcmp(type, "hybridmq") == 0) { if (strcmp(comp, "defined") == 0) { run("HybridSortMQ", "./HybridSortMQ", NULL, NULL); } } else if (strcmp(type, "hybridqm") == 0) { if (strcmp(comp, "defined") == 0) { run("HybridSortQM", "./HybridSortQM", NULL, NULL); } } } else if (argc == 8) { char *type = NULL; char *comp = NULL; char *stat = NULL; char *k = NULL; for (int i=1; i<=7; i++) { if (strcmp(argv[i], "--type") == 0) { type = argv[i+1]; } else if (strcmp(argv[i], "--comp") == 0) { comp = argv[i+1]; } else if (strcmp(argv[i], "--stat") == 0) { stat = argv[i+1]; k = argv[i+2]; } } if (type == NULL || comp == NULL) { fprintf(stderr, "Bad arguments\n"); exit(1); } if (strcmp(type, "insert") == 0) { if (strcmp(comp, "<=") == 0) { run("InsertionSortle", "./InsertionSortle", stat, k); } else if (strcmp(comp, ">=") == 0) { run("InsertionSortge", "./InsertionSortge", stat, k); } } else if (strcmp(type, "merge") == 0) { if (strcmp(comp, "<=") == 0) { run("MergeSortle", "./MergeSortle", stat, k); } else if (strcmp(comp, ">=") == 0) { run("MergeSortge", "./MergeSortge", stat, k); } } else if (strcmp(type, "quick") == 0) { if (strcmp(comp, "<=") == 0) { run("QuickSortle", "./QuickSortle", stat, k); } else if (strcmp(comp, ">=") == 0) { run("QuickSortge", "./QuickSortge", stat, k); } } else if (strcmp(type, "dpquick") == 0) { if (strcmp(comp, "<=") == 0) { run("DPQuickle", "./DPQuickle", stat, k); } else if (strcmp(comp, ">=") == 0) { run("DPQuickge", "./DPQuickge", stat, k); } } else if (strcmp(type, "hybridmi") == 0) { if (strcmp(comp, "defined") == 0) { run("HybridSortMI", "./HybridSortMI", stat, k); } } else if (strcmp(type, "hybridqi") == 0) { if (strcmp(comp, "defined") == 0) { run("HybridSortQI", "./HybridSortQI", stat, k); } } else if (strcmp(type, "hybridmq") == 0) { if (strcmp(comp, "defined") == 0) { run("HybridSortMQ", "./HybridSortMQ", stat, k); } } else if (strcmp(type, "hybridqm") == 0) { if (strcmp(comp, "defined") == 0) { run("HybridSortQM", "./HybridSortQM", stat, k); } } } else { fprintf(stderr, "4 or 7 arguments needed. Have %d\n", argc-1); exit(1); } return 0; }
C
#include <stdio.h> //standard input output #include <stddef.h> //the difference of pointer data type ptrdiff_t #include <limits.h> //INT_MIN limits #define MAXLEN 100 #define HELP "Options:\n"\ "1.Copy\n"\ "2.Concatenate\n"\ "3.Compare\n"\ //length of a string int FindStrLen(char *s) { int count = 0; for(; *s != '\0' ; s++) count++; return count; } //Check if the n is within the len of t, Can't copy/cmp/Concatenate more than the string t int CheckN(char *t, int n) { if(n > FindStrLen(t)) return 0; return 1; } //copying n characters from s to t void ncpy(char *s, char *t, int n) { for(int i = 0; i < n; i++) *s++ = *t++; return; } //copy n characters from s to t main func void strncpyM(char *s, char *t, int n) { if(!CheckN(t, n)) return; ncpy(s, t, n); return; } //Concatenate n characters in t to s at the end of the string void strncatM(char *s, char *t, int n) { if(!CheckN(t, n)) return; for(; *s != '\0'; s++); ncpy(s, t, n); return; } //Compare n characters from beginning in s and t int strncmpM(char *s, char *t, int n) { if(!CheckN(t, n)) return INT_MIN; if(!CheckN(s, n)) return INT_MIN; int i = 0; for(i = 0; i < n; i++) { ptrdiff_t diff = *s - *t; if(diff != 0) return diff; s++; t++; } return 0; } int main(void) { char s[MAXLEN]; char t[MAXLEN]; scanf("%s", s); scanf("%s", t); int n = 0, select = 0, res = INT_MIN; scanf("%i", &n); printf(HELP); if(n > 0) { scanf("%i", &select); switch (select) { case 1: strncpyM(s, t, n); break; case 2: strncatM(s, t, n); break; case 3: res = strncmpM(s, t, n); break; default : printf("wrong key\n"); } } if(select == 3) printf("%i\n", res); else printf("%s\n", s); return 0; }
C
#include <stdio.h> #include <stdlib.h> int binom_coeff(int n, int k) { /* if (k == 0) return 1; */ /* if (n == 0) return 0; */ /* return binom_coeff(n-1, k) + binom_coeff(n-1, k-1); */ int D[n+1][k+1]; for (int j = 0; j < k+1; j++) { D[0][j] = 0; } for (int i = 0; i < n+1; i++) { D[i][0] = 1; } for (int i = 1; i < n+1; i++) { for (int j = 1; j < k+1; j++) { D[i][j] = D[i-1][j] + D[i-1][j-1]; } } return D[n][k]; } int main(int argc, char** argv) { if (argc >= 3) { int n = atoi(argv[1]); int k = atoi(argv[2]); printf("%d\n", binom_coeff(n, k)); } }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char * argv[]) { printf("The number of args: %d\n", argc); printf("%s\n%s\n", argv[0], argv[1]); printf("As int: %d\n", atoi(argv[2])); return 0; }
C
// challeng simulating loops with goto // it's supposed to look like garbage #include <stdio.h> void print_first_row (int rows); void print_middle_rows (int num_rows); void print_middle_row (int row_num, int num_rows); void print_last_row (int num_rows); void print_char_n_times (char c, int n); int main (void) { printf("How many rows would you like? "); int rows; scanf("%d", &rows); print_first_row(rows); print_middle_rows(rows); print_last_row(rows); } void print_first_row (int rows) { print_char_n_times(' ', rows - 1); putchar('*'); putchar('\n'); } void print_middle_rows (int num_rows) { int count = 0; if (num_rows <= 2) goto end_loop; begin_loop: print_middle_row(count + 2, num_rows); ++count; if (count != (num_rows - 2)) goto begin_loop; end_loop:; } void print_middle_row (int row_num, int num_rows) { int first_spaces = num_rows - row_num, middle_spaces = 1 + 2 * (row_num - 2); print_char_n_times(' ', first_spaces); putchar('*'); print_char_n_times(' ', middle_spaces); putchar('*'); putchar('\n'); } void print_last_row (int rows) { if (rows > 1) { print_char_n_times('*', 2 * rows - 1); putchar('\n'); } } void print_char_n_times (char c, int n) { int count = 0; if (n <= 0) goto end_loop; begin_loop: putchar(c); ++count; if (count < n) goto begin_loop; end_loop:; // null statement with a label // above comment exists because I misread my own code several times }
C
#include "idobata_meeting.h" #define MESSAGE_BUFSIZE MESG_BUFSIZE+L_USERNAME+6 /* 発言メッセージサイズ */ static char Buffer[MESSAGE_BUFSIZE]; /* パケットの種類=type のパケットを作成する パケットのデータは 内部的なバッファ(Buffer)に作成される */ //各種のパケットを作成する関数 char *create_packet(u_int32_t type, char *message ){ switch(type){ case HELLO: snprintf( Buffer, MESSAGE_BUFSIZE, "HELO" ); break; case HERE: snprintf( Buffer, MESSAGE_BUFSIZE, "HERE" ); break; case JOIN: snprintf( Buffer, MESSAGE_BUFSIZE, "JOIN %s", message ); break; case POST: snprintf( Buffer, MESSAGE_BUFSIZE, "POST %s", message ); break; case MESSAGE: snprintf( Buffer, MESSAGE_BUFSIZE, "MESG %s", message ); break; case QUIT: snprintf( Buffer, MESSAGE_BUFSIZE, "QUIT" ); break; default: /* Undefined packet type */ break; } return Buffer; } //パケットのヘッダを解析する関数 u_int32_t analyze_header(char *header){ if( strncmp( header, "HELO", 4 )==0 ){ return(HELLO); } if( strncmp( header, "HERE", 4 )==0 ){ return(HERE); } if( strncmp( header, "JOIN", 4 )==0 ){ return(JOIN); } if( strncmp( header, "POST", 4 )==0 ){ return(POST); } if( strncmp( header, "MESG", 4 )==0 ){ return(MESSAGE); } if( strncmp( header, "QUIT", 4 )==0 ){ return(QUIT); } return 0; }
C
/***************************************************************************//** @file +Nombre del archivo (ej: template.h)+ @brief +Descripcion del archivo+ @author +Nombre del autor (ej: Salvador Allende)+ ******************************************************************************/ #ifndef _RANA_H_ #define _RANA_H_ /******************************************************************************* * INCLUDE HEADER FILES ******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdint.h> /******************************************************************************* * CONSTANT AND MACRO DEFINITIONS USING #DEFINE ******************************************************************************/ #define INIT_X 7 // Posicion de inicio de la rana #define INIT_Y 15 // Posicion de inicio de la rana /******************************************************************************* * ENUMERATIONS AND STRUCTURES AND TYPEDEFS ******************************************************************************/ typedef struct { int16_t pos_x; int16_t pos_y; uint8_t colision; uint8_t cant_vida; uint8_t nivel; }rana_t; // Estructura con atributos de la rana /******************************************************************************* * VARIABLE PROTOTYPES WITH GLOBAL SCOPE ******************************************************************************/ /******************************************************************************* * FUNCTION PROTOTYPES WITH GLOBAL SCOPE ******************************************************************************/ /** * @brief POSRANAINIT: inicializa la rana al comenzar la partida con todos sus atributos * @param init_pos estructura de la rana (jugador) * @param pasos cantidad de pixeles que ocupa un casillero del juego. 1: RaspberryPI; 30: Allegro. * @return devuelve la estructura de la rana inicializada */ rana_t pos_rana_init(rana_t init_pos, int pasos); /** * @brief RESETRANA: devuelve a la rana a la posicion de partida cuando pasa de nivel o colisiona * @param rana estructura de la rana * @param pasos pixeles correspondientes a cada output. 1: RaspberryPI; 30: Allegro. * @return devuelve la estructura de la rana con la nueva ubicacion */ rana_t reset_rana(rana_t rana, int pasos); /** * @brief MOVIMIENTORANA: mueve al jugador * @param tecla indica la direccion en la que se mueve la rana * @param posicion estructura de la rana * @param pasos pixeles correspondientes a cada output. 1: RaspberryPI; 30: Allegro. * @return devuelve la estructura de la rana con la nueva ubicacion */ rana_t movimiento_rana(char tecla, rana_t posicion, int pasos); /******************************************************************************* ******************************************************************************/ #endif // _RANA_H_
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <sys/ioctl.h> #include <linux/if.h> #include <errno.h> #define BUFLEN 4096 int if_link_status(const char *if_name) { int fd = 0; struct sockaddr_nl sa = {0}; fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (fd < 0) { printf("[Error] socket error!, errorcode:%d\n", errno); return -1; } sa.nl_family = AF_NETLINK; sa.nl_groups = RTNLGRP_LINK; /* 查询网卡状态 */ int ret = bind(fd, (struct sockaddr*)&sa, sizeof(sa)); if (ret) { printf("[Error] bind error!, errorcode: %d\n", errno); close(fd); return -1; } char buf[BUFLEN] = {0}; struct nlmsghdr* nh = NULL; struct ifinfomsg* ifinfo = NULL; struct rtattr* attr = NULL; int len = 0; while ((ret = read(fd, buf, sizeof(buf))) > 0) { for (nh = (struct nlmsghdr*)buf; NLMSG_OK(nh, ret); nh = NLMSG_NEXT(nh, ret)) { if (nh->nlmsg_type == NLMSG_DONE) break; else if (nh->nlmsg_type == NLMSG_ERROR) return -1; else if (nh->nlmsg_type != RTM_NEWLINK) continue; /* 读取网卡名字 */ ifinfo = NLMSG_DATA(nh); printf("[Note] if: %u link %s\n", ifinfo->ifi_index, (ifinfo->ifi_flags & IFF_LOWER_UP)? "up": "down" ); /* 读取网卡名称 */ attr = (struct rtattr*)(((char*)nh) + NLMSG_SPACE(sizeof(*ifinfo))); len = nh->nlmsg_len - NLMSG_SPACE(sizeof(*ifinfo)); for (; RTA_OK(attr, len); attr = RTA_NEXT(attr, len)) { if (attr->rta_type == IFLA_IFNAME) { printf("[Note] if_name: %s", (char*)RTA_DATA(attr)); break; } } printf("\n"); } } } int main(int argc, char** argv) { if_link_status(NULL); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_check_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mabouce <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/23 15:06:36 by mabouce #+# #+# */ /* Updated: 2019/03/07 15:20:27 by mabouce ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" void ft_set_db(t_struct *stru) { stru->db[0] = "sa"; stru->db[1] = "sb"; stru->db[2] = "ss"; stru->db[3] = "pa"; stru->db[4] = "pb"; stru->db[5] = "ra"; stru->db[6] = "rb"; stru->db[7] = "rr"; stru->db[8] = "rra"; stru->db[9] = "rrb"; stru->db[10] = "rrr"; } int ft_check_line(t_struct *stru) { stru->i = 0; ft_set_db(stru); while (stru->i < 11) { if (ft_strequ(stru->line, stru->db[stru->i]) == 1) return (1); stru->i++; } return (0); } int ft_check_flags(char *str, t_struct *stru) { int i; if (str[0] == '-') { i = 1; if (!str[i]) return (0); while (str[i]) { if (str[i] == 'l') stru->flag_light = 1; else if (str[i] == 'v') stru->flag_visu = 1; else if (str[i] == 'n') stru->flag_count_instru = 1; else return (0); i++; } return (1); } else return (0); } int ft_push_av(t_struct *stru) { int i; i = 1; while (stru->split[stru->j][i]) { if (stru->split[stru->j][i] < '0' || stru->split[stru->j][i] > '9') return (0); i++; } stru->lli = ft_atolli(stru->split[stru->j]); if (stru->lli > 2147483647 || stru->lli < -2147483648) return (0); ft_check_double(stru, stru->lli); if (!(ft_list_push_back(&stru->pile_a, (void *)stru->lli))) return (0); return (1); } int ft_check_av_and_fill(t_struct *stru) { stru->j = 0; while (stru->split[stru->j]) { if (ft_check_flags(stru->split[stru->j], stru) == 1) { stru->j++; continue; } if (stru->split[stru->j][0] < '0' || stru->split[stru->j][0] > '9') { if (stru->split[stru->j][0] == '+' || stru->split[stru->j][0] == '-') { if (stru->split[stru->j][1] < '0' || stru->split[stru->j][1] > '9') return (0); } else ft_error(stru, -2); } if (!(ft_push_av(stru))) return (0); stru->j++; } return (1); }
C
/* narnia1 */ #include <stdio.h> int main(){ int (*ret)(); if(getenv("EGG")==NULL){ printf("Give me something to execute at the env-variable EGG\n"); exit(1); } printf("Trying to execute EGG!\n"); ret = getenv("EGG"); ret(); return 0; }
C
#include<stdio.h> #define N 50 int main(void){ int i; char s[N][128]; for(i=0;i<N;i++){ scanf("%s",s[i]); if(s[i]=={"$$$$$"}){ break; } } for(i=0;i<N;i++){ printf("%s",s[i]); } }
C
/* * menu_framework.c * * Created: 27.09.2017 14:05:47 * Author: andrholt */ #include <stdlib.h> #include <string.h> #include <util/delay.h> #include <stddef.h> #include "OLED_driver.h" #include "menu_framework.h" #include "UART_driver.h" #include "game.h" int current_page = 1; menu* display_menu; static menu* current_menu; joystick_dir last_joy_dir = CENTER; int difficulty = EASY; int controller = USB; extern states current_state; void menu_setup(void){ menu* menu_front_page = create_menu("PingPongShow"); display_menu = menu_front_page; menu* play = create_menu("Start new game"); menu* highscore_menu = create_menu("Highscore"); menu* play_usb = create_menu("Control: USB"); menu* play_ps2 = create_menu("Control: PS2"); menu* usb_easy = create_menu("Easy"); menu* usb_medium = create_menu("Medium"); menu* usb_hard = create_menu("Hard"); menu* ps2_easy = create_menu("Easy"); menu* ps2_medium = create_menu("Medium"); menu* ps2_hard = create_menu("Hard"); menu* highscore_view = create_menu("View"); menu* highscore_reset = create_menu("Reset"); menu* reset_yes = create_menu("YES"); menu* reset_no = create_menu("NO"); create_submenu(menu_front_page, play); create_submenu(menu_front_page, highscore_menu); create_submenu(play, play_usb); create_submenu(play, play_ps2); create_submenu(play_usb, usb_easy); create_submenu(play_usb, usb_medium); create_submenu(play_usb, usb_hard); create_submenu(play_ps2, ps2_easy); create_submenu(play_ps2, ps2_medium); create_submenu(play_ps2, ps2_hard); create_submenu(highscore_menu, highscore_view); create_submenu(highscore_menu, highscore_reset); create_submenu(highscore_reset, reset_yes); create_submenu(highscore_reset, reset_no); oled_reset(); menu_display_setup(display_menu, current_page); oled_update(); current_menu = display_menu->child; } void menu_display_setup(menu* menu_node, int selector_pos){ int col = 0; int page = 0; oled_sram_reset(); menu* current = menu_node->child; oled_sram_string(menu_node->name, page, col); oled_sram_string("----------------", page+1, col); page = 2; col = 2; while(current != NULL){ oled_sram_string(current->name, page, col); current = current->next_sibling; page++; } oled_sram_char('*', selector_pos+1, 0); } menu* create_menu(char* new_name){ menu* new_menu = (menu*)malloc(sizeof(menu)); if(new_menu == NULL){ printf("Out of mem\n"); exit(1); } new_menu->name = new_name; new_menu->next_sibling = NULL; new_menu->prev_sibling = NULL; new_menu->parent = NULL; new_menu->child = NULL; new_menu->number_of_childs = 0; return new_menu; } menu* create_submenu(menu* parent_menu, menu* child_menu){ if (parent_menu->child == NULL){ parent_menu->child = child_menu; } else{ menu* current = parent_menu->child; while (current->next_sibling != NULL){ current = current->next_sibling; } current->next_sibling =child_menu; child_menu->prev_sibling =current; } parent_menu->number_of_childs++; child_menu->parent = parent_menu; return parent_menu; } menu* update_current_display_menu(menu* current_menu, int page, joystick_dir dir){ menu* current = current_menu->child; if(dir == RIGHT){ for(int i = 1; i < page; i++){ current = current->next_sibling; } }else{ current = current_menu->parent; } if(current != NULL){ return current; } return current_menu; } void print_selection_sign(int page){ oled_goto_column(0); oled_goto_page(page); oled_print_string("*"); } void menu_navigation(void){ int end_menu = 0; joystick_dir joy_dir = find_joystick_dir(); if(joy_dir != last_joy_dir){ switch(joy_dir){ case UP: if(current_page > 1){ current_menu = current_menu->prev_sibling; current_page--; } menu_display_setup(display_menu, current_page); oled_update(); break; case DOWN: if(current_page < display_menu->number_of_childs){ current_menu = current_menu ->next_sibling; current_page++; } menu_display_setup(display_menu, current_page); oled_update(); break; case RIGHT: if(current_menu->child != NULL){ display_menu = update_current_display_menu(display_menu, current_page, RIGHT); current_page = 1; menu_display_setup(display_menu, current_page); oled_update(); current_menu = current_menu->child; } else if(current_menu->parent->parent != NULL){ end_menu = 1; } break; case LEFT: if(current_menu->parent->parent != NULL){ display_menu = update_current_display_menu(display_menu, current_page, LEFT); current_page = 1; menu_display_setup(display_menu, current_page); oled_update(); current_menu = current_menu->parent->parent->child; } break; default: break; } } last_joy_dir = joy_dir; if(end_menu){ const char* menu_title = current_menu->name; if (!strcmp(menu_title,"Easy") && !strcmp(current_menu->parent->name, "Control: PS2")){ current_state = PLAY; controller = PS2; difficulty = EASY; }else if (!strcmp(current_menu->name, "Medium")&& !strcmp(current_menu->parent->name, "Control: PS2")){ current_state = PLAY; controller = PS2; difficulty = MEDIUM; }else if (!strcmp(current_menu->name, "Hard")&& !strcmp(current_menu->parent->name, "Control: PS2")){ current_state = PLAY; controller = PS2; difficulty = HARD; } else if (!strcmp(current_menu->name,"Easy") && !strcmp(current_menu->parent->name, "Control: USB")){ current_state = PLAY; controller = USB; difficulty = EASY; }else if (!strcmp(current_menu->name, "Medium")&& !strcmp(current_menu->parent->name, "Control: USB")){ current_state = PLAY; controller = USB; difficulty = MEDIUM; }else if (!strcmp(current_menu->name, "Hard")&& !strcmp(current_menu->parent->name, "Control: USB")){ current_state = PLAY; controller = USB; difficulty = HARD; } else if (!strcmp(current_menu->name,"View")){ current_state = HIGHSCORE; } else if (!strcmp(current_menu->name, "YES")){ oled_reset_highscore_list(); current_state = RESET_HIGHSCORE; } else if (!strcmp(current_menu->name, "NO")){ current_state = IDLE; } } }
C
#include <ell/ell.h> #include <stdbool.h> #include "adapter.h" typedef struct { const char* name; const char* signature; union { void *value; void **vector; } ref; // This is a pointer to the related property in adapter model } property_t ; static property_t vproperty[] = { { "Address", "s" , { .vector = (void**)&adapter.address } }, { "Name", "s" , { .vector = (void**)&adapter.name } }, { "Alias", "s" , { .vector = (void**)&adapter.alias } }, { "Powered", "b", { .value = (void*)&adapter.powered } }, { "Discoverable", "b", { .value = (void*)&adapter.discoverable } }, { NULL, NULL, { NULL} } }; static void print_property(int i) { if (!strcmp(vproperty[i].signature, "s")) { l_info(" %s: %s", vproperty[i].name, (char*)*vproperty[i].ref.vector); } else if (!strcmp(vproperty[i].signature, "b")) { if (*((bool*)vproperty[i].ref.value)) l_info(" %s: on", vproperty[i].name); else l_info(" %s: off", vproperty[i].name); } } int get_adapter_properties() { uint8_t i; for (i = 0 ; vproperty[i].name != NULL ; i++) { if (!strcmp(vproperty[i].signature, "s")) { if (!l_dbus_proxy_get_property(adapter.proxy, vproperty[i].name, vproperty[i].signature, &(*vproperty[i].ref.vector))) return -1; } else if (!strcmp(vproperty[i].signature, "b")) { if (!l_dbus_proxy_get_property(adapter.proxy, vproperty[i].name, vproperty[i].signature, vproperty[i].ref.value)) return -1; } } for (i = 0 ; vproperty[i].name != NULL ; i++) print_property(i); return 0; } int update_adapter_properties(struct l_dbus_message *msg, const char* name_property) { uint8_t i; for (i = 0; vproperty[i].name != NULL ; i++) { if (!strcmp(name_property, vproperty[i].name)) { if (!strcmp(vproperty[i].signature, "s")) { if (!l_dbus_message_get_arguments(msg, vproperty[i].signature, &(*vproperty[i].ref.vector))) return -1; } else if (!strcmp(vproperty[i].signature, "b")) { if (!l_dbus_message_get_arguments(msg, vproperty[i].signature, vproperty[i].ref.value )) return -1; } print_property(i); return 0; } } return 0; } static void cb_powered_on(struct l_dbus_proxy *proxy, struct l_dbus_message *result, void *user_data) { const char *msg, *txt; if (l_dbus_message_is_error(result)) { if (l_dbus_message_get_error(result, &msg, &txt)) l_error("%s: %s",msg, txt); } } static void cb_discoverable(struct l_dbus_proxy *proxy, struct l_dbus_message *result, void *user_data) { const char *msg, *txt; if (l_dbus_message_is_error(result)) { if (l_dbus_message_get_error(result, &msg, &txt)) l_error("%s: %s",msg, txt); } else { l_info("%s is visible", adapter.name); } } static void cb_name_changed(struct l_dbus_proxy *proxy, struct l_dbus_message *result, void *user_data) { const char *msg, *txt; if (l_dbus_message_is_error(result)) { if (l_dbus_message_get_error(result, &msg, &txt)) l_error("%s: %s",msg, txt); } else { l_info("Name changed"); } } bool power_adapter_on() { if (adapter.proxy) if (!l_dbus_proxy_set_property(adapter.proxy, cb_powered_on, NULL, NULL, "Powered", "b", true)) return false; return true; } bool power_adapter_off() { if (adapter.proxy) if (!l_dbus_proxy_set_property(adapter.proxy, cb_powered_on, NULL, NULL, "Powered", "b", false)) return false; return true; } bool make_visible() { if (adapter.proxy) if (!l_dbus_proxy_set_property(adapter.proxy, cb_discoverable, NULL, NULL, "Discoverable", "b", true)) return false; return true; } bool change_name(const char* new_name) { if (adapter.proxy) if (!l_dbus_proxy_set_property(adapter.proxy, cb_name_changed, NULL, NULL, "Alias", "s", new_name)) return false; return true; }
C
#include<stdio.h> int main() { int num,rev=0,rem,t; printf("Enter the number"); scanf("%d",&num); t=num; while(t>0) { rem=t%10; rev=(rev*10)+rem; t=t/10; } if(num==rev) { printf("%d is an palindrom number",num); } else { printf("%d is an Not palindrom number",num); } }
C
#include <u.h> #include <libc.h> #include <thread.h> #include <draw.h> #include <mouse.h> #include "dat.h" #include "fncs.h" Click click[128]; Click *next; int size; enum{ MIN, CIN, ROLL, }; Click* findpoint(Point xy) { int i; for(i=0;i<size;i++) if(ptinrect(xy, click[i].r)) return click+i; return nil; } void eventthread(void *arg) { Mouse m; Click c; Channel **chans = arg; Channel *min = chans[0]; Channel *cin = chans[1]; Channel *out = chans[2]; Channel *roll = chans[3]; free(chans); Alt alts[] = { {min, &m, CHANRCV}, {cin, &c, CHANRCV}, {roll, nil, CHANRCV}, {nil, nil, CHANEND}, }; for(;;) switch(alt(alts)){ case CIN: size++; assert(size < 128); click[size] = c; break; case MIN: if(m.buttons != 1) continue; next = findpoint(m.xy); if(next != nil) send(out, next); break; case ROLL: size = 0; break; } } void spawnevent(Channel *min, Channel *cin, Channel *out, Channel *rollback) { Channel **chans; size = 0; chans = emalloc(sizeof(Channel*)*4); chans[0] = min; chans[1] = cin; chans[2] = out; chans[3] = rollback; threadcreate(eventthread, chans, 8192); }
C
/** * @file * @brief POSIX dirent functions on Windows. * @author 王文佑 * @date 2016.06.30 * @copyright ZLib Licence * @see http://www.openfoundry.org/of/projects/2419 */ #ifndef _GEN_WINDIRENT_H_ #define _GEN_WINDIRENT_H_ #ifndef _WIN32 #error This module can be used on Windows only! #endif #ifdef __cplusplus extern "C" { #endif /** * DIR enumeration object. */ typedef struct DIR DIR; /** * File type */ enum { DT_BLK, ///< This is a block device. DT_CHR, ///< This is a character device. DT_DIR, ///< This is a directory. DT_FIFO, ///< This is a named pipe (FIFO). DT_LNK, ///< This is a symbolic link. DT_REG, ///< This is a regular file. DT_SOCK, ///< This is a UNIX domain socket. DT_UNKNOWN, ///< The file type could not be determined. }; /** * dirent. */ struct dirent { unsigned d_ino; ///< Not used! unsigned d_off; ///< Not used! unsigned short d_reclen; ///< Length of this record. unsigned char d_type; ///< File type; not supported by all file system types. char d_name[1024]; ///< Null-terminated file name. }; DIR* opendir(const char *name); int closedir(DIR *dir); struct dirent *readdir(DIR *dir); #ifdef __cplusplus } // extern "C" #endif #endif
C
/* file: es76.c */ /* comando head */ #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <stdlib.h> int main(int argc, char **argv) { char c, *filename; int lines = 0, fdin = 0, fdout = 1, i = 0, n = 10; for (i = 1; i < argc - 1; i++) { /* controllo -n X */ if (strcmp(argv[i], "-n") == 0) { n = atoi(argv[i + 1]); i++; /* mangia l'argomento */ continue; /* prossimo */ } if (strcmp(argv[i], "-f") == 0) { filename = (argv[i + 1]); fdin = open(filename, O_RDONLY); i++; /* mangia l'argomento */ if (fdin < 0) { printf("error: %s non found.\n", filename); return(1); } continue; /* prossimo */ } printf("error invalid option: %s\n", argv[i]); return(2); } while(read(fdin, &c, 1) > 0) { if (lines < n) { write(fdout, &c, 1); } if (c == '\n') { lines++; } } return(0); }
C
#include <stdio.h> #include <stdlib.h> #include "linerseq.h" /* 设计一个算法,将顺序表中的所有元素逆置 */ void swap(ElemType *a, ElemType *b){ ElemType temp = *a; *a = *b; *b = temp; } void reverse(SqList *L){ ElemType *pa = L->elem; ElemType *pa_last = L->elem+L->length-1; while (pa < pa_last) { swap(pa, pa_last); pa++; pa_last--; } } int main(void){ int a[] = {2, 4, 5, 7, 9, 11}; SqList la; init_linerseq(&la); cp_array_linerseq(&la, a, ARRAY_LEN(a)); print_linerseq(&la); reverse(&la); print_linerseq(&la); return 0; }
C
/*Programa para el manejo del Teclado Matricial * Objetivo: Ingresar una clave digital y verificar si es 5050 * Se requiere agregar los archivos "keypad.h" y "keypad.c" * Se requiere agregar los archivos "lcd.h" y "lcd.c" * El PORTC utilizando 6 pines del RC0 al RC5 para el LCD * El PORTB utilizando los 8 pines RB0 al RB7 para el Keypad */ #pragma config FOSC = INTRC_NOCLKOUT, WDTE = OFF, LVP = OFF #include <xc.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define _XTAL_FREQ 4000000 #define LCD_PORT PORTC //Define Datos LCD en PORTC #define LCD_TRIS TRISC //Define Control Datos LCD #define LCD_RS PORTCbits.RC5 //Define pin RS LCD #define LCD_EN PORTCbits.RC4 //Define pin EN LCD #include "lcd.h" //Agrega archivo de encabezado local LCD #define KB_PORT PORTB //Define el Puerto de datos para el PAD #define KB_TRIS TRISB //Define el Registro de configuracion PAD #include "keypad.h" //Agrega la libreria basica del PAD char val, key, num = 0, res; char clave[8]; void main(void) //Funcion principal { OSCCONbits.IRCF = 0b110; //Ajuste de Oscilador a 4Mhz ANSEL = 0; //Configura los pines AN0-AN7 en modo digital ANSELH = 0; //Configura los pines AN8-AN15 en modo digital TRISC = 0b00000000; //Configura los pines del PORTC como salida LCDSetup(LINES2); //Inicia el modulo LCD LCDPuts("CLAVE:"); //Envia la palabra Hola en primera linea LCDGoto(0x40); //Posicionar el cursos LCD en la segunda linea KBSetup(); //Inicializa el Keypad OPTION_REGbits.nRBPU = 0; //Habilita las pull-up del PORTB while(1) { val = KBScan(); //Hace una captura de PAD if(val != 0) //Si el velor no es nulo { key = KBGetchar(val); //Recupera la tecla presionada if(key == '#') //Si la tecla presionada es '#' { clave[num] = 0; //Fin de lista para la clave res = strcmp(clave, "5050"); //Si la clave es 5050 if(res == 0) { LCDGoto(0x40); //Posiciona el cursor en linea 2 LCDPuts("Correcto "); } else { LCDGoto(0x40); //Posiciona el cursor en linea 2 LCDPuts("Incorrecto"); } __delay_ms(3000); //Retardo de 3 Segundos LCDSet(CLEAR); //Limpia la pantalla LCDPuts("CLAVE:"); LCDGoto(0x40); num = 0; //Inicia el contador de digitos } else { LCDPutc(key); //Escribe el valor de la tecla en el LCD clave[num] = key; //Almacena el valor en la lista num++; //Incrementa el contador } __delay_ms(50); } __delay_ms(20); } }
C
int gcd(int a,int b){ int temp; if(a<b){/*交换两个数,使大数放在a上*/ temp = a; a = b; b = temp; } while(b! = 0){/*利用辗除法,直到b为0为止*/ temp = a%b; a = b; b = temp; } return a; } // greatest common divisor (GCD) or greatest common factor (GCF) or Highest common factor (HCF) int gcd(int x, int y) { if (x == 0) { return y; } while (y != 0) { if (x > y) { x = x - y; } else { y = y - x; } } return x; } // least common multiple int lcm(int x, int y) { return (x * y) / gcd(x, y); } /* Recursive Function: Greatest Common Divisor */ int gcdr(int a, int b) { if (a == 0) return b; return gcdr(b%a, a); } unsigned int gcd(unsigned int a, unsigned int b) { int r; while(b>0) { r=a%b; a=b; b=r; } return a; } unsigned int gcd(unsigned int a, unsigned int b) { while(b^=a^=b^=a%=b); return a; } unsigned int gcd(unsigned int a,unsigned int b) { return (b>0)?gcd(b,a%b):a; }
C
#include <stdio.h> #include <stdlib.h> struct Queue { int front,rear,size; unsigned capacity; int *arr; } struct Queue* createQueue(unsigned capacity) { struct Queue* queue=(struct Queue*)malloc(sizeof(struct Queue)); queue->capacity=capacity; queue->front=queue->size=0; queue->rear=capacity-1; queue->array=(int*)malloc(queue->capacity* sizeof(int)); return queue; } int isEmpty(strcut Queue* queue) { return (queue->size==0); } int isFull(struct Queue* queue) { return (queue->size==queue->capacity); } void enqueue(struct Queue* queue,int item) { int main(int argc,char* argv[]) { struct Queue* queue=createQueue(1000); int arr[argc],k=0; for(int i=1;i,argc;i++) { enqueue(queue,atoi(argv[i])); }
C
#include "ch.h" #include "hal.h" #include <chprintf.h> #include <usbcfg.h> #include <leds.h> #include <main.h> #include <camera/po8030.h> #include <process_image.h> static int target_position = 0; //angular position given in pixels with //mode 0: target found, mode 1: target not found static uint8_t mode = 1; #define WIDTH_SLOPE 8 #define MIN_WIDTH_PIXELS 30 #define MIN_HALFWIDTH_PX 15 #define MIN_OFFSET 3 #define MAX_PX_VALUE 32 #define OFFSET 11 //Offset if the number to substract from max_px_value to find the threshhold value #define BRIGHTNESS_DEFAULT 0 #define CONTRAST_DEFAULT 64 #define RED_GAIN_DEFAULT 0x5E #define GREEN_GAIN_DEFAULT 0x40 #define BLUE_GAIN_DEFAULT 0x5D #define INTEGRAL_DEFAULT 0x80 #define FRACTIONAL_DEFAULT 0x00 #define LINE_TO_READ_BEGIN 200 #define NB_LINES_TO_READ 2 #define FRAMES_FOR_DETECTION 4 #define MIN_TOLERANCE_FOR_ALIGNEMENT 5 // some functions have been taken from TP4 and modified for the purpose of our project, // so the names of the variables and functions may be pretty close //================================================================= /* * internal Functions */ //================================================================= /** * @brief update if the object has been seen ///// * */ void found_lost_target(uint8_t target_not_found); void calibrate_camera(uint8_t brightness, uint8_t contrast, uint8_t awb, uint8_t ae, uint8_t r_gain, uint8_t g_gain, uint8_t b_gain, uint16_t e_integral, uint8_t e_fractional){ po8030_set_brightness(brightness); po8030_set_contrast(contrast); po8030_set_awb(awb); po8030_set_ae(ae); po8030_set_rgb_gain(r_gain,g_gain, b_gain); po8030_set_exposure(e_integral, e_fractional); } void extract_data(uint8_t* data, uint16_t size, uint8_t *pc){ //Extracts red bits from buffer for(uint16_t i = 0; i<size;i++){ data[i]= *pc>>0b11; pc += 0b10; } } void update_target_detection(uint8_t *buffer){ uint16_t i = 0, begin = 0, end = 0; uint8_t stop = 0; uint8_t mean = 0; // attention si WIDTH grand --> 16_t static uint8_t target_not_found = 0; //searching = TRUE, aligned = FALSE; target_not_found = 0; //search for a begin //is the object cut by the camera on the left side? for(uint8_t j = 0; j < WIDTH_SLOPE; j++){ mean+=buffer[j]; } if (mean>(MAX_PX_VALUE-OFFSET-MIN_OFFSET)*WIDTH_SLOPE){ //the object is on the left side stop = 1; begin = 1; i=1; } while(stop == 0 && i < (IMAGE_BUFFER_SIZE - WIDTH_SLOPE)) { //the slope must at least be WIDTH_SLOPE wide and is compared //to the mean of the image if(buffer[i] < MAX_PX_VALUE-OFFSET-MIN_OFFSET && buffer[i+WIDTH_SLOPE] > MAX_PX_VALUE-OFFSET) { begin = i; stop = 1; } i++; } //if a begin was found, search for an end if (i < (IMAGE_BUFFER_SIZE - WIDTH_SLOPE) && begin) { stop = 0; while(stop == 0 && i < IMAGE_BUFFER_SIZE-WIDTH_SLOPE) { if(buffer[i+WIDTH_SLOPE] < MAX_PX_VALUE-OFFSET-MIN_OFFSET && buffer[i] > MAX_PX_VALUE-OFFSET) { end = i; stop = 1; } i++; } //is the object cut on the right side? mean = 0; for(uint16_t j = (IMAGE_BUFFER_SIZE - WIDTH_SLOPE - 1); j < IMAGE_BUFFER_SIZE - 1; j++){ mean+=buffer[j]; } if (mean>(MAX_PX_VALUE-OFFSET)*WIDTH_SLOPE && !end){ //the object is on the left side end = IMAGE_BUFFER_SIZE - 1; } if (!end) { target_not_found = 1; } } else//if no begin was found { target_not_found = 1; } //if a line too small has been detected, continues the search if(!target_not_found && (end-begin) < MIN_WIDTH_PIXELS){ target_not_found = 1; } found_lost_target(target_not_found); if(target_not_found){ begin = 0; end = 0; }else{ target_position = (begin + end - IMAGE_BUFFER_SIZE)/2; //gives the target position relativ to the center of the image. } } void found_lost_target(uint8_t target_not_found){ //counts the number of times the object was detected static uint8_t detection_counter = 0; //mode 0: target found, mode 1: target not found if(mode != target_not_found){ detection_counter++; } else { detection_counter = 0; } //go true if the number of detections was sufficient for the object to be detected //also stay true when the object has not been proven to be absent if(detection_counter>FRAMES_FOR_DETECTION){ //inverse mode detection_counter = 0; mode = (mode==FALSE); } } //================================================================= /* * Threads */ //================================================================= //semaphore static BSEMAPHORE_DECL(image_ready_sem, TRUE); static THD_WORKING_AREA(waCaptureImage, 256); static THD_FUNCTION(CaptureImage, arg) { chRegSetThreadName(__FUNCTION__); (void)arg; //Takes pixels 0 to IMAGE_BUFFER_SIZE of the line to read (minimum 2 lines because reasons) po8030_advanced_config(FORMAT_RGB565, 0, LINE_TO_READ_BEGIN, IMAGE_BUFFER_SIZE, NB_LINES_TO_READ, SUBSAMPLING_X1, SUBSAMPLING_X1); calibrate_camera(BRIGHTNESS_DEFAULT, CONTRAST_DEFAULT+0x30, FALSE, FALSE, RED_GAIN_DEFAULT, GREEN_GAIN_DEFAULT, BLUE_GAIN_DEFAULT, INTEGRAL_DEFAULT+0x8F, FRACTIONAL_DEFAULT); dcmi_enable_double_buffering(); dcmi_set_capture_mode(CAPTURE_ONE_SHOT); dcmi_prepare(); while(1){ //starts a capture dcmi_capture_start(); //waits for the capture to be done wait_image_ready(); //signals an image has been captured chBSemSignal(&image_ready_sem); } } static THD_WORKING_AREA(waProcessImage, 1024); static THD_FUNCTION(ProcessImage, arg) { chRegSetThreadName(__FUNCTION__); (void)arg; uint8_t *img_buff_ptr; uint8_t image[IMAGE_BUFFER_SIZE] = {0}; // bool send_to_computer = true; while(1){ //waits until an image has been captured chBSemWait(&image_ready_sem); //gets the pointer to the array filled with the last image in RGB565 img_buff_ptr = dcmi_get_last_image_ptr(); //Extracts red pixels extract_data(image, IMAGE_BUFFER_SIZE, img_buff_ptr); //search for a target in the image and gets its position in pixels update_target_detection(image); } } //================================================================= /* * Public Functions */ //================================================================= uint8_t target_found(void){ return (mode==FALSE); // return 0; } int get_angle_to_target(void){ return -target_position; } void process_image_start(void){ chThdCreateStatic(waProcessImage, sizeof(waProcessImage), NORMALPRIO, ProcessImage, NULL); chThdCreateStatic(waCaptureImage, sizeof(waCaptureImage), NORMALPRIO+10, CaptureImage, NULL); }
C
/* 1.Create a function for get on the bus. The number of new passengers should be passed as a parameter. 2.Create a function for getting off the bus. The number of passengers who are getting off should be passed as a parameter. 3.Each time these functions are called, they should print out the current capacity. First the passengers fill up all the seats, and then the standing places when they get on the bus. When they get off the bus, the standing places will be released first. EXAMPLE: An Ikarus 280 has 147 standing places and 36 seats this means it can carry 183 person. - We start with an empty bus. First there are 50 new passengers. So after the get on function called it should inform us: We have 50 passengers. There is 0 empty seats and 133 standing places left. - Then we call the get off function with 20 passengers. This time it should print out something like this: We have 30 passengers. There is 0 seats left and 153 standing places. - If too much passengers wants to get in, our function simply should inform us, that this is too much for this bus and pass without any further action. 4.Create a function which takes the whole bus array as a parameter and returns the name of the bus with the largest capacity. */ #include <stdio.h> #include "Bus.h" int main(int argc, const char * argv[]) { Bus bus1; Bus bus2; Bus bus3; strcpy(bus1.name, "bus1"); strcpy(bus2.name, "bus2"); strcpy(bus3.name, "bus3"); bus1.numberOfSeats = 36; bus1.numberOfStandingPlaces = 147; bus2.numberOfSeats = 30; bus2.numberOfStandingPlaces = 150; bus3.numberOfSeats = 40; bus3.numberOfStandingPlaces = 160; getOnTheBus(bus1, 50); getOffTheBus(bus1, 20); Bus buses[] = {bus1, bus2, bus3}; int sizeOfArray = sizeof(buses) / sizeof(buses[0]); printf("The bus with the largest capacity is: %s\n", busWithTheLargestCapacity(buses, sizeOfArray)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_face_s.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ckillian <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/04 14:19:18 by ckillian #+# #+# */ /* Updated: 2018/12/06 16:20:54 by ckillian ### ########.fr */ /* */ /* ************************************************************************** */ #include <string.h> #include "fillit.h" int ft_face_s_f4(t_sqr *square, char ltr, int (*f)(char *, char)) { int j; if ((square->i + 2 * square->sqr_size - 1) >= (square->sqr_size * (square->sqr_size - 1) - 1)) return (0); if (f(&(square->sqr[square->i]), ltr)) return (0); j = square->sqr_size - 1; if (f(&(square->sqr[square->i + j]), ltr)) return (0); if (f(&(square->sqr[square->i + j + 1]), ltr)) return (0); j += square->sqr_size; if (f(&(square->sqr[square->i + j]), ltr)) return (0); return (1); } int ft_face_s_f3(t_sqr *square, char ltr, int (*f)(char *, char)) { int j; if ((square->i + square->sqr_size + 2) >= (square->sqr_size * (square->sqr_size - 1) - 1)) return (0); if (f(&(square->sqr[square->i]), ltr) || f(&(square->sqr[square->i + 1]), ltr)) return (0); j = square->sqr_size + 1; if (f(&(square->sqr[square->i + j]), ltr) || f(&(square->sqr[square->i + j + 1]), ltr)) return (0); return (1); } int ft_face_s_f2(t_sqr *square, char ltr, int (*f)(char *, char)) { int j; if ((square->i + 2 * square->sqr_size + 1) >= (square->sqr_size * (square->sqr_size - 1) - 1)) return (0); if (f(&(square->sqr[square->i]), ltr)) return (0); j = square->sqr_size; if (f(&(square->sqr[square->i + j]), ltr)) return (0); if (f(&(square->sqr[square->i + j + 1]), ltr)) return (0); j += square->sqr_size; if (f(&(square->sqr[square->i + j + 1]), ltr)) return (0); return (1); } int ft_face_s_f1(t_sqr *square, char ltr, int (*f)(char *, char)) { int j; j = 0; if ((square->i + square->sqr_size) >= (square->sqr_size * (square->sqr_size - 1) - 1)) return (0); if (f(&(square->sqr[square->i]), ltr)) return (0); if (f(&(square->sqr[square->i + 1]), ltr)) return (0); j = square->sqr_size - 1; if (f(&(square->sqr[square->i + j]), ltr)) return (0); if (f(&(square->sqr[square->i + j + 1]), ltr)) return (0); return (1); } t_f *ft_face_s(unsigned short tetro) { if ((tetro & FACE_1) == FACE_1) return (ft_face_s_f1); if ((tetro & FACE_2) == FACE_2) return (ft_face_s_f2); if ((tetro & FACE_3) == FACE_3) return (ft_face_s_f3); if ((tetro & FACE_4) == FACE_4) return (ft_face_s_f4); return (NULL); }
C
#define F_CPU 16000000L #include <avr/io.h> #include <util/delay.h> void SPI_Init() { // making SCK, MOSI, SS' as outptut DDRB |= (1<<DDB2) | (1<<DDB3) | (1<<DDB5); // making MISO as input DDRB &= ~(1<<DDB4); // making SCK, MOSI, as low PORTB &= ~(1<<PORTB3) & ~(1<<PORTB5); // making SS' as high PORTB |= (1<<PORTB2); // Select MSB first or LSB first by DORD SPCR &= ~(1<<DORD); // Select this as Master SPCR |= (1<<MSTR); // Let the clock polarity be SCK is low when idle SPCR &= ~(1<<CPOL); // Sampled at Rising or Falling Edge // we choose rising edge SPCR &= ~(1<<CPHA); // Selecting a SCK frequnecy // we select Fosc/4 by 000 SPSR &= ~(1<<SPI2X); SPCR &= ~(1<<SPR1); SPCR &= ~(1<<SPR0); // dISBALE SPIE bit for interrupt on Serial Transfer Completion SPCR &= ~(1<<SPIE); // Enabling SPI SPCR |= (1<<SPE); } uint8_t SPITransferReceive(uint8_t data_) { SPDR = data_; // wait till serial transmission is complete by checking the SPI Interrupt Flag while((SPSR & (1<<SPIF)) == 0 ) {}; // return the recieved data - can use it or ignore it return SPDR; } int main(void) { SPI_Init(); PORTB &= ~(1<<PORTB2); SPITransferReceive('A'); while(1) { } }
C
/* * Copyright 2016 Christopher Zell <[email protected]>. * * 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. */ /* * Defines some util functions to serialize and deserialize values to * and from bytes. Uses little endian for serialization and deserialization. * * File: serialization.h * Author: Christopher Zell <[email protected]> * * Created on October 11, 2016, 9:10 AM */ #ifndef SERIALIZATION_H #define SERIALIZATION_H #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <string.h> /** * Serializes a int64_t value, as little endian, into the given buffer. * * @param buffer the buffer which should contain the value * @param value the value which should be written * @return the next free space in the buffer */ uint8_t* serialize_int64(uint8_t * buffer, int64_t value); /** * Serializes a int32_t value, as little endian, into the given buffer. * * @param buffer the buffer which should contain the value * @param value the value which should be written * @return the next free space in the buffer */ uint8_t* serialize_int32(uint8_t * buffer, int32_t value); /** * Serializes a int16_t value, as little endian, into the given buffer. * * @param buffer the buffer which should contain the value * @param value the value which should be written * @return the next free space in the buffer */ uint8_t* serialize_int16(uint8_t * buffer, int16_t value); /** * Serializes a int8_t value into the given buffer. * * @param buffer the buffer which should contain the value * @param value the value which should be written * @return the next free space in the buffer */ uint8_t* serialize_int8(uint8_t * buffer, int8_t value); /** * Deserializes an int64_t value from the given buffer. * * @param buffer the buffer which contains the value * @param value the pointer to the variable on which the value should be written * @return the next place in the buffer */ uint8_t* deserialize_int64(uint8_t * buffer, int64_t* value); /** * Deserializes an int32_t value from the given buffer. * * @param buffer the buffer which contains the value * @param value the pointer to the variable on which the value should be written * @return the next place in the buffer */ uint8_t* deserialize_int32(uint8_t * buffer, int32_t* value); /** * Deserializes an int16_t value from the given buffer. * * @param buffer the buffer which contains the value * @param value the pointer to the variable on which the value should be written * @return the next place in the buffer */ uint8_t* deserialize_int16(uint8_t * buffer, int16_t* value); /** * Deserializes an int8_t value from the given buffer. * * @param buffer the buffer which contains the value * @param value the pointer to the variable on which the value should be written * @return the next place in the buffer */ uint8_t* deserialize_int8(uint8_t * buffer, uint8_t* value); #ifdef __cplusplus } #endif #endif /* SERIALIZATION_H */
C
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> //ͳƶ1ĸ int Count_Byte1(const int* x) { int count = 0; int tmp = *x; while (tmp) { tmp = tmp & (tmp - 1); count++; } return count; } //вͬλĸ //ͬλ0ͬλ1Ȼͳ1ĸ int Count_Byte(const int* x, const int* y) { int count = 0; int tmp = (*x) ^ (*y); Count_Byte1(&tmp); } //ӡеλżλ void Print_Odd_Even(const int* x) { int num = *x; int i; printf("\n%dλżλ\n",num); printf("ӡλ"); for (i = 31; i > 0; i = i - 2) { printf("%d",(num >> i)&1); } printf("\n"); printf("ӡżλ"); for (i = 30; i >= 0; i = i - 2) { printf("%d", (num >> i) & 1); } printf("\n"); } // void swap(int* x, int* y) { *x = (*x) ^ (*y); *y = (*x) ^ (*y); *x = (*x) ^ (*y); } int main(void) { int a, b; printf("a,b:>\n"); scanf("%d%d",&a,&b); printf("ֵΪ\na=%d , b=%d\n",a,b); printf("\n%d%dλͬλ%dλ\n",a,b,Count_Byte(&a,&b)); Print_Odd_Even(&a); Print_Odd_Even(&b); swap(&a, &b); printf("\nabֵǣ\na=%d , b=%d",a,b); return 0; }
C
#include <stdio.h> #include "timing.c" #include <omp.h> int main(){ int** table = NULL; table = (int **)malloc(sizeof * table * 2000); for(int i = 0; i < 2000; i++){ table[i] = (int *)malloc(sizeof * table[i] * 250000); } for(int i = 0; i < 2000; i++) { for(int j = 0; j < 250000; j++) table[i][j] = i+j; } long sum = 0; double wc1 = 0, wc2 = 0, cpuT = 0; timing(&wc1, &cpuT); #pragma omp parallel for reduction (+:sum) num_threads(4) for (int i = 0; i < 2000; i += 2){ for (int j = 0; j < 500; j++) sum = sum + table[i][j*j]; } timing(&wc2, &cpuT); printf("\n Time: %f ms\n", (wc2 - wc1)*1000); printf("sum = %ld\n", sum); }
C
#include<stdio.h> struct student { char id[100], name[100]; double cgpa; }; int main() { struct student s[3]; int i; for(i=0;i<3;i++) { printf("Input ID, Name and Cgpa of student %d: ",i+1); scanf("%s%s%lf",s[i].id, s[i].name, &s[i].cgpa); } printf("\n"); for(i=0;i<3;i++) { printf("Printing information of student %d\n\n",i+1); printf("ID : %s\n",s[i].id); printf("Name : %s\n",s[i].name); printf("Cgpa : %lf\n",s[i].cgpa); printf("\n"); } return 0; }
C
#include <stdio.h> int main(void) { int a = 0; printf("%d\n", ++a); int x = 0, y = 0, z = 0; z = x++ + y; printf("%d\n", z); printf("%d\n", x); return 0; }
C
//Accepted #include<stdio.h> int main() { int a,b,ans1,ans2,min; while(scanf("%d %d",&a,&b) && (a!=-1 || b!=-1)) { if(a>b) { ans1=a-b; ans2=b+100-a; } else if(b>a) { ans1=b-a; ans2=a+100-b; } else if(a==b) { ans1=0; ans2=0; } min=(ans1<ans2) ? ans1:ans2; printf("%d\n",min); } return 0; }
C
#include<stdio.h> #include<string.h> #define maxsize 10 int stack[maxsize],top=-1; void push(char); char pop(); int isempty(); int isfull(); main() { char str[maxsize],rev[maxsize]; int len,i,j,k,r=0; printf("Enter the string : "); scanf("%s",str); len=strlen(str); for(i=0;i<len;i++) push(str[i]); for(j=top;j>=0;j--) rev[r++]=pop(); for(k=0;k<len;k++) { if(str[k]!=rev[k]) { printf("%s is not a palindrome\n",str); exit(0); } } printf("%s is a palindrome\n",str); } void push(char elem) { if(isfull()) printf("Stack is Full\n"); else stack[++top]=elem; } char pop() { if(isempty()) printf("Stack is Empty\n"); else return stack[top--]; } int isempty() { if(top==-1) return 1; else return 0; } int isfull() { if(top>=(maxsize-1)) return 1; else return 0; }
C
#include "main.h" #include "parse.h" //external handlers extern TIM_HandleTypeDef htim2; extern TIM_HandleTypeDef htim4; extern TIM_HandleTypeDef htim8; //it is required to calibrate all current senses at two points uint32_t Parse_Current(uint32_t raw, uint32_t channel, uint32_t active) { uint32_t calculated=0; //else value is so low current must be 0 if(raw>177 && active) { calculated = ((579*raw)/20)-5100; } //calculate in mA; .028954*raw-5.100056 for A return calculated; //this sort of corresponds to amps I think } uint32_t Parse_Voltage(uint32_t raw, uint32_t raw_ground) { //voltage should be raw*4 after voltage divider, but component is not working with tolerances, voltage divider is 130 and 82 which is 106/41, voltage is raw*3.3/(2^10), V to mV is *1000; //approximate value from raw->Vcc based on measured values is (95*raw/2)-1645; note that this formula is not taken from reality, it is probably approximating a logarithimic formula but datasheet doesn't give enough details; is low enough precision that overflow is not a problem to consider at all uint32_t calculated=((((95*raw)/2)-1645)+((raw_ground*825)/256))/4; //calculate current in mV //TODO: check that this function works properly for the second board assembled as well sometime return calculated; } //without the 1k ohm resistor this is totally useless, please do not use for anything uint32_t Parse_Temperature(uint32_t raw) { //uint32_t calculated=401-(raw*3791/5000); //calculate temperature in °C uint32_t calculated=raw; return calculated; } uint32_t Calculate_PWM_DC(uint32_t channel) { uint32_t DC=0; uint32_t T=0, off=0, on=0; if (!(PWM_In_EN>>channel)&1) { Set_Error(WARN_PWM_CHANNEL_UNINITIALIZED); return 0; } switch(channel) { case 0: T=HAL_TIM_ReadCapturedValue(&htim2, TIM_CHANNEL_2); off=HAL_TIM_ReadCapturedValue(&htim2, TIM_CHANNEL_1); DC=(((T-off)*100)/T); //note integer division always rounds down break; case 3: T=HAL_TIM_ReadCapturedValue(&htim4, TIM_CHANNEL_1); on=HAL_TIM_ReadCapturedValue(&htim4, TIM_CHANNEL_2); DC=((on*100)/T); break; case 4: T=HAL_TIM_ReadCapturedValue(&htim8, TIM_CHANNEL_1); on=HAL_TIM_ReadCapturedValue(&htim8, TIM_CHANNEL_2); DC=((on*100)/T); break; default: Set_Error(WARN_PWM_INVALID_CHANNEL); return 0; } return DC; //DC ranges from 0-100 } uint32_t Calculate_PWM_Freq(uint32_t channel) { uint32_t frequency=0; uint32_t T=0; if (!(PWM_In_EN>>channel)&1) { Set_Error(WARN_PWM_CHANNEL_UNINITIALIZED); return 0; } switch(channel) { case 0: T=HAL_TIM_ReadCapturedValue(&htim2, TIM_CHANNEL_2); break; case 3: T=HAL_TIM_ReadCapturedValue(&htim4, TIM_CHANNEL_1); break; case 4: T=HAL_TIM_ReadCapturedValue(&htim8, TIM_CHANNEL_1); break; default: Set_Error(WARN_PWM_INVALID_CHANNEL); return 0; } frequency = (((HAL_RCC_GetHCLKFreq()*10)/(T*(PWM_Prescalers[channel]+1)))+5)/10; //calculate frequency in .1 Hz, add .5 Hz, divide by 10 to get rounded value in Hz //if frequency is higher than 255 Hz, two bytes must be used to send the frequency, frequency will almost surely not be over 65kHz return frequency; }
C
#ifndef _OBJECTA_H #define _OBJECTA_H #include "Token.h" #include "Object.h" #ifndef _EXPRARRAY #define _EXPRARRAY typedef struct _ExprArray ExprArray; extern void delete_ExprArray(void* array); #endif typedef struct _ObjectArray ObjectArray; struct _ObjectArray { Object ** Objects; int size; int used; void (*addElementToArray)(ObjectArray* array,Object* element); void (*delete)(void* array); Object* (*getElementInArrayAt)(ObjectArray* array,size_t index); void* (*copy)(void * arr); }; void init_ObjectArray(ObjectArray* array); void addElementToObjectArray(ObjectArray* array,Object* element); void delete_ObjectArray(void* array); Object* getObjectinArrayAt(ObjectArray* array,size_t index); void initializeObjectElement(Object** arg, void* values); void* copyObjectArray(void * arr); #endif
C
#ifndef LEVELGENERATOR_H #define LEVELGENERATOR_H #include "enemyclass.h" #define MW 1500 //Tile map width #define MH 1500 //Tile map height #define TS 64 //Tile square size #define ROOMSIZE 15 //Width and height of tiles per room (ROOMSIZE x ROOMSIZE) extern int map[MW][MH]; //Defenition of the tile map extern int roomCount; //Current amount of rooms generated extern int roomMax; //Desired number of rooms to be generated extern int exitXpos, exitYpos; //Tile position of the door blocking the exit struct Level { int levelNum; //Increases by 1 for each new floor int keyRooms; //Intended number of key rooms int spawnedKeyRooms; //Created number of key rooms }; extern Level level; struct Key { int active; //0 = No key, 1 = key int xpos, ypos; //Key position in world space }; extern Key key[100]; struct PickupList { int active; int type; //0 = half heart, 1 = full heart, 2 = arrow int xpos, ypos; }; struct Room { // Structure for each room PickupList pickupList[2]; Enemy enemy[4]; bool occupied; //Marked true when a room is spawned bool examined; //Marked true when a room has been checked by CheckSurroundingRooms method bool visited; //Used to track player visted rooms for minimap int roomType; //0-14 room types int roomContents; //0 is normal room, 1 is starting room, 2 is key room, 3 is exit room int roomStructure; //0-7 defines internal wall structure and spawn points for collectables and enemies int northPath; //0 is no path(wall), 1 is empty path, 2 is already connected room path int eastPath; int southPath; int westPath; int enemyCount; //Number of alive enemies in a room }; extern Room floorGrid[100][100]; void StartGenerator(void); void DrawRoom(int, int, int); void StructureRoom(int xRoom, int yRoom); void ChooseItemType(int roomX, int roomY, int i); void SpawnRoom(int roomType, int roomX, int roomY); void CloseRooms(void); void ChooseRoom(void); void CheckSurroundingRooms(int roomX, int roomY); void SetRoomValues(int roomType, int roomX, int roomY); void InitMap(void); #endif
C
#ifndef MAIN_H #define MAIN_H #define _CRT_SECURE_NO_DEPRECATE #include <windows.h> #include <d3d9.h> #include <d3dx9.h> #include <stdio.h> #include <string.h> /////////////// // // /////////////// #define ERR -1 // ó ڵ -1. #define SCREEN_WIDTH 800 // ȭ ũ. #define SCREEN_HEIGHT 600 // ȭ ũ. #define CLASS_NAME "D3D Game Program" ///////////////// // ũ Լ // ///////////////// #define KEYUP(KeyCode) ((GetAsyncKeyState(KeyCode))? 0 : 1) #define KEYDOWN(KeyCode) ((GetAsyncKeyState(KeyCode))? 1 : 0) // ޸ #define SAFE_RELEASE(Object) if(Object) { Object->Release(); Object = NULL; } #define SAFE_DELETE(p) {if(p) {delete (p); (p)=NULL; }} #define SAFE_DELETE_ARRAY(p) {if(p) {delete[] (p); (p)=NULL; }} #endif
C
#include<stdio.h> #include<string.h> int main(){ int l; char S[130]; double ans,temp; int i,j; while(scanf("%d%s", &l, S) != EOF){ ans = 0; for(; l<=strlen(S); l++){ for(i=0; i <= strlen(S)-l; i++){ temp = 0; for(j = i; j < i+l; j++) if(S[j] == 'C' || S[j] == 'c' || S[j] == 'G' || S[j] == 'g') temp += (double)1/l; if(temp > ans) ans = temp; } } printf("%.3lf\n",ans); } return 0; }
C
#define _POSIX_C_SOURCE 200809L /* get flockfile */ #include <stdio.h> #include <stdarg.h> #include <stdint.h> #include "dmalloc_common.h" int is_logging = 0; void dmalloc_log_protect() { flockfile(stderr); /* prevent output corruption from concurrency */ is_logging = 1; /* prevent output corruption from reentrancy */ } void dmalloc_log_unprotect() { is_logging = 0; funlockfile(stderr); } void dmalloc_logf( const char* format, ... ) { va_list args; va_start(args, format); #ifdef LINUX vfprintf(stderr, format, args); #else malloc_printf(format, args); #endif va_end( args ); } void dmalloc_printf( const char* format, ... ) { if (!is_logging) { va_list args; va_start(args, format); #ifdef LINUX vfprintf(stderr, format, args); #else malloc_printf(format, args); #endif va_end( args ); } }
C
#include <stdio.h> #define MAXCHAR 1000 int isSpecialChar(char c); int main() { char str[MAXCHAR]; int index = 0; int c; int newIndex = 0; printf("\nFill the str array\n"); while (((c = getchar()) != EOF) && (c != '\n')) { str[index++] = c; } str[index] = '\0'; printf("\nThe entered array: %s\t and index: %d\n", str, index); index = index - 1; while (isSpecialChar(str[index])) { /* Do nothing*/ --index; } ++index; str[index] = '\0'; while (str[newIndex] != '\0') { ++newIndex; } printf("\nThe final array is: %s\t and newIndex: %d\n", str, newIndex); return 0; } int isSpecialChar(char c) { if ((c == ' ') || (c == '\t') || (c == '\n')) return 1; return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* aizen.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: azulbukh <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/23 20:27:23 by azulbukh #+# #+# */ /* Updated: 2018/10/23 20:41:09 by azulbukh ### ########.fr */ /* */ /* ************************************************************************** */ #include "doom.h" void list_remove(t_line **list, t_line *node) { t_line *tmp; if (list == NULL || *list == NULL || node == NULL) return ; if (*list == node) { ft_putstr("removed\n"); *list = (*list)->next; free(node); node = NULL; } else { tmp = *list; while (tmp->next && tmp->next != node) tmp = tmp->next; if (tmp->next) { tmp->next = node->next; free(node); node = NULL; } } } void list_destroy(t_line **list) { if (list == NULL) return ; while (*list != NULL) { list_remove(list, *list); } } void itoa_isnegative(int *n, int *negative) { if (*n < 0) { *n *= -1; *negative = 1; } } char *ft_itoa(int n) { int tmpn; int len; int negative; char *str; if (n == -2147483648) return (strdup("-2147483648")); tmpn = n; len = 2; negative = 0; itoa_isnegative(&n, &negative); while (tmpn /= 10) len++; len += negative; if ((str = (char*)malloc(sizeof(char) * len)) == NULL) return (NULL); str[--len] = '\0'; while (len--) { str[len] = n % 10 + '0'; n = n / 10; } if (negative) str[0] = '-'; return (str); } char *concat(char *s1, char *s2) { char *result; result = malloc(strlen(s1) + strlen(s2) + 1); strcpy(result, s1); strcat(result, s2); return (result); }
C
#ifndef __DISPLAY_H #define __DISPLAY_H /* Video types for mode in which machine is currently running. */ enum video_type { VIDEO_TYPE_NONE = 0x00, VIDEO_TYPE_COLOR = 0x20, VIDEO_TYPE_MONOCHROME = 0x30 }; /* Available VGA colors for a display. */ enum vga_color { VGA_COLOR_BLACK = 0, VGA_COLOR_BLUE = 1, VGA_COLOR_GREEN = 2, VGA_COLOR_CYAN = 3, VGA_COLOR_RED = 4, VGA_COLOR_MAGENTA = 5, VGA_COLOR_BROWN = 6, VGA_COLOR_LIGHT_GREY = 7, VGA_COLOR_DARK_GREY = 8, VGA_COLOR_LIGHT_BLUE = 9, VGA_COLOR_LIGHT_GREEN = 10, VGA_COLOR_LIGHT_CYAN = 11, VGA_COLOR_LIGHT_RED = 12, VGA_COLOR_LIGHT_MAGENTA = 13, VGA_COLOR_LIGHT_BROWN = 14, VGA_COLOR_WHITE = 15 }; #endif
C
#include "ds/buffered_string.h" void print_str_with_indexes(String* str) { printf("Indexs for str4: \n"); for (int i = 0; i < str->length; i++) printf("%4d", i); printf("\n"); for (int i = 0; i < str->length; i++) printf("%4c", str->buffer[i]); printf("\n"); for (int i = str->length * -1; i < 0; i++) printf("%4d", i); printf("\n"); } int main() { printf("Init...\n"); String* str = init_string(6); String* str2 = init_string(6); printf("Copy...\n"); copy_char_str(str, "Hello, World luke"); copy_str(str2, str); char buffer[MAX_CHARS_BUFFER]; copy_to_buffer(buffer, MAX_CHARS_BUFFER, str); printf("str buffer: %s\n", str->buffer); printf("str2 buffer: %s\n", str2->buffer); printf("char buffer: %s\n", buffer); printf("\nEquals & Not Equals...\n"); if (not_equals_char_str(str, "Hello, World")) printf("str != c_str\n"); copy_char_str(str2, "Hello, W"); if (not_equals_str(str, str2)) printf("str1 != str2\n"); printf("\nLess & Less Than\n"); String* str3 = init_str(); copy_char_str(str3, "Alabama"); if (less_than_char_str(str3, "Peter Dickney")) printf("str < c_str\n"); if (less_than_equal_char_str(str3, "Alabama")) printf("str <= c_str\n"); printf("\nGreater & Greater Than\n"); String* str4 = init_str(); copy_char_str(str4, "Peter Dickney"); if (greater_than_char_str(str4, "Zootic Animal")) printf("str > c_str\n"); if (greater_than_equal_char_str(str4, "Peter Dickney")) printf("str >= c_str\n"); printf("\nSubstring ops\n"); print_str_with_indexes(str4); int subscripts[] = { 44, 5, -4, -4, -6, 7, -1, -13 }; String* str5 = substring(str4, subscripts[0], subscripts[1]); String* str6 = substring(str4, subscripts[2], subscripts[3]); String* str7 = substring(str4,subscripts[4], subscripts[5]); String* str8 = substring(str4, subscripts[6], subscripts[7]); if (str5) { printf("substring(%d, %d) = %s\n", subscripts[0], subscripts[1], str5->buffer); free_string(str5); } if (str6) { printf("substring(%d, %d) = %s\n", subscripts[2], subscripts[3], str6->buffer); free_string(str6); } if (str7) { printf("substring(%d, %d) = %s\n", subscripts[4], subscripts[5], str7->buffer); free_string(str7); } if (str8) { printf("substring(%d, %d) = %s\n", subscripts[6], subscripts[7], str8->buffer); free_string(str8); } printf("substring_to_buffer()\n"); char buffer2[8]; substring_to_buffer(buffer2, 8, str4, 3, -3); printf("%s\n", buffer2); printf("get_c() and set_c()\n"); int indexs[] = { 0, 3, 5, -6, -8, -1 }; printf("\nget_c()\n"); printf("get_c(%d) = %c\n", indexs[0], get_c(str4, indexs[0])); printf("get_c(%d) = %c\n", indexs[1], get_c(str4, indexs[1])); printf("get_c(%d) = %c\n", indexs[2], get_c(str4, indexs[2])); printf("get_c(%d) = %c\n", indexs[3], get_c(str4, indexs[3])); printf("get_c(%d) = %c\n", indexs[4], get_c(str4, indexs[4])); printf("\nset_c()\n"); set_c(str4, indexs[0], 'd'); set_c(str4, indexs[1], 'h'); set_c(str4, indexs[2], 'y'); set_c(str4, indexs[3], 'l'); set_c(str4, indexs[4], 'f'); printf("\nget_c() after set_c()\n"); printf("get_c(%d) = %c\n", indexs[0], get_c(str4, indexs[0])); printf("get_c(%d) = %c\n", indexs[1], get_c(str4, indexs[1])); printf("get_c(%d) = %c\n", indexs[2], get_c(str4, indexs[2])); printf("get_c(%d) = %c\n", indexs[3], get_c(str4, indexs[3])); printf("get_c(%d) = %c\n\n", indexs[4], get_c(str4, indexs[4])); print_str_with_indexes(str4); printf("\nstrcat()\n"); String* str10 = init_string(14); copy_str(str10, str4); printf("strcat(%s, ", str4->buffer); strcat_append_char_str(str4, "Hello World"); printf("%s) = %s\n", str3->buffer, str4->buffer); char buffer3[30] = "Hello"; strcat_prepend_char_str(buffer3, 30, str4); printf("strcat_prepend() = %s\n", buffer3); printf("mul_str()\n"); String* mul = mul_str(str3, 3); printf("mul_str() = %s\n", mul->buffer); char buffer4[7]; mul_str_to_buffer(buffer4, 7, str3, 3); printf("mul_str_to_buffer() = %s\n", buffer4); free_string(str); free_string(str2); free_string(str3); free_string(str4); free_string(str10); free_string(mul); return 0; }
C
#include "queue.h" #include <stdlib.h> int isEmpty(Node *head) { return (head == NULL); } Node *newNode(TREENODE *d, int p) { Node *temp = (Node *)malloc(sizeof(Node)); temp->data = d; temp->priority = p; temp->next = NULL; return temp; } void enqueue(Node **head, TREENODE *d, int p) { // Create new Node Node *temp = newNode(d, p); // TH1. Hang doi ban dau rong // TH2. do uu tien cua phan tu moi them // lon hon do uu tien o dau hang doi // chen phan tu moi truoc dau cu if ((*head) == NULL || (*head)->priority >= p) { temp->next = *head; (*head) = temp; } // TH3. Duyet tim vi tri chen thich hop // Vi tri chen thich hop voi do uu tien <= cac phan tu truoc // va do uu tien > do uu tien phan tu dung sau else { Node *start = (*head); while (start->next != NULL && start->next->priority < p) { start = start->next; } temp->next = start->next; start->next = temp; } } Node *dequeue(Node **head) { Node *temp = *head; (*head) = (*head)->next; return temp; }
C
/* * Módulo: cliente.h * Data: 03/06/2016 * Descricao: ficheiro .h do TAD do cliente * Autores: Miguel Real e Tomas Martins */ #ifndef CLIENTE_H_ #define CLIENTE_H_ typedef struct _cliente * cliente; /*********************************************** criaCliente - Criacao da instancia da estrutura associada a uma cliente. Parametros: numContribuinte - numero contribuinte; numCidadao - numero cidadao; nome - nome Retorno: apontador para a instancia criada Pre-condicoes: numContribuinte > 0 && numCidadao > 0 && (nome != NULL) ***********************************************/ cliente criaCliente(int numContribuinte, int numCidadao, char * nome); /*********************************************** destroiCliente - Liberta a memoria ocupada pela estrutura associada a cliente. Parametros: c - cliente a destruir Pre-condicoes: c != NULL ***********************************************/ void destroiCliente(cliente c); /*********************************************** destroiGenCliente - Liberta a memoria ocupada pela estrutura associada a cliente. Parametros: c - cliente a destruir do tipo void * Pre-condicoes: c != NULL ***********************************************/ void destroiGenCliente(void * c); /*********************************************** nomeCliente - retorna o nome do cliente. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ char * nomeCliente(cliente c); /*********************************************** contribuinteCliente - retorna o numero de contribuinte do cliente. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ int contribuinteCliente(cliente c); /*********************************************** cidadaoCliente - retorna o numero de cidadao do cliente. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ int cidadaoCliente(cliente c); /*********************************************** contaCliente - retorna a conta do cliente. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ float contaCliente(cliente c); /*********************************************** entraTempo - guarda os tempo de entrda em minutos no cliente. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ void entraTempo(cliente c , int mEntrada); /*********************************************** adicionaTempo - Adiciona minutos ao tempo total de permanencia do cliente. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ void adicionaTempo(cliente c , int adTotal); /*********************************************** mTotais - Retorna os minutos de permanencia totais do cliente. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ int mTotais(cliente c); /*********************************************** adicionaConta - Retorna os minutos de permanencia totais do cliente. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ void adicionaConta(cliente c, float adConta); /*********************************************** mEntrada - Retorna os minutos de entrada do cliente. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ int mEntrada(cliente c); /*********************************************** setTrampolins- Torna 1 a variavel que indica se o cliente esta nos trampolins. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ void setTrampolins(cliente c); /*********************************************** removeTrampolins - Torna 0 a variavel que indica se o cliente esta nos trampolins. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ void removeTrampolins(cliente c); /*********************************************** isTrampolins - Retorna os a variavel que indica se o cliente esta nos trampolins. Parametros: c - cliente Pre-condicoes: c != NULL ***********************************************/ int isTrampolins(cliente c); #endif /* CLIENTE_H_ */
C
// swapping of two numbers using call by reference #include <stdio.h> void swap_two_no(int* , int*); void main(){ int first,second; printf("Enter the first number ="); scanf("%d",&first); printf("Enter the second number = "); scanf("%d", &second); printf("Before swapping the numbers are : first %d and second %d",first, second); swap_two_no(&first,&second); printf("\nAfter swapping the numbers are : first %d and second %d ", first,second); } void swap_two_no(int*first, int*second){ int temp; temp = *first; *first = *second; *second = temp; }
C
/* * arrayLength has to be within main; if a function is used we will have only the pointer/array head as reference * O(n) = O(N) */ #include <stdio.h> #include <stdlib.h> #define SIZE 10 void reverse(int *, int); int main(int argc, const char *argv) { int myArray[] = { 0, 1, 2, 3, 4}; int arrayLength = sizeof(myArray) / sizeof(int); int i; printf("original array = "); for(i = 0; i < arrayLength; i++) { printf("%d, ", myArray[i]); } printf("\n"); // printf("length = %d\n", arrayLength); reverse(myArray, arrayLength); printf("reversed array = "); for(i = 0; i < arrayLength; i++) { printf("%d, ", myArray[i]); } printf("\n"); return EXIT_SUCCESS; } void reverse(int array[SIZE], int length) { for(int i = 0; i < length / 2; i++) { int other = length - i - 1; int temp = array[i]; array[i] = array[other]; array[other] = temp; } }
C
#include <stdio.h> void ft_swap(int *a, int *b) { int a_temp; a_temp = *a; *a = *b; *b = a_temp; } /* int main() { int a = 5; int b = 10; ft_swap(&a, &b); printf("a = %d\nb = %d\n", a, b); return (0); } */
C
/* fichier : ipc.h * 18/06/2014 * Florian CAULET Johann NOVAK * [email protected] [email protected] * Fichier qui regroupe toutes les constantes (car c'est le fichier que tous les autres header incluent), les variables globales, les structures liées aux ipc, et les prototypes des fonctions du fichier ipc.c. */ #ifndef IPC_H #define IPC_H #include <pthread.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/types.h> #include <signal.h> /* Définition des constantes de flags des ipc */ #define IPC_FLAGS 0777 | IPC_CREAT | IPC_EXCL /* Définition des constantes des type des messages de l'ipc ipcSignaux */ /* ID du signal d'une poubelle pleine qui alerte le service de ramassage */ #define ID_SIGNAL_POUBELLE_PLEINE 1 /* ID du signal d'une poubelle à la mairie pour lui transférer l'ID du jetteur et le litre de déchets jetés */ #define ID_SIGNAL_POUBELLE_MAIRIE 2 /* Définition des constantes des poubelles */ /* Capacité maximale de stockage d'un conteneur normal */ #define CONTENEUR_NORMAL_CAPA_MAX 200 /* Capacité maximale de stockage d'un conteneur recyclable */ #define CONTENEUR_RECYCLABLE_CAPA_MAX 1000 /* Capacité de stockage maximal d'un sac poubelle */ #define SAC_POUBELLE_CAPA_MAX 30 /* Définition des constantes des camions poubelles */ /* Temps que met un camion poubelle à vider une poubelle */ #define CAMION_TEMPS_DE_VIDE 3 /* Temps que met un camion poubelle à se déplacer à une poubelle pleine (même temps pour repartir) */ #define CAMION_TEMPS_DE_DEPLACEMENT 7 /* Définition des constantes de l'utilisateur */ /* Intervalle de temps que l'utilisateur attend avant de consommer de nouveau */ #define UTILISATEUR_TEMPS_CONSOMMATION 2 /* Nombre maximal de membres dans une famille */ #define UTILISATEUR_MAX_MEMBRE_FAMILLE 13 /* Temps que prend l'utilisateur pour jeter une poubelle ou des déchets */ #define UTILISATEUR_TEMPS_DE_JETTE 1 /* Définition du type booléen */ #define false 0 #define true 1 typedef int bool; /* Structure MsgBuffer * Structure utilisée pour transmettre des messages via les ipc, grâce aux primitives * msgsnd et msgrcv. */ typedef struct msgBuffer { /* Type du message, sert de moyen de filtrage des messages */ long type; /* Tableau de pointeurs non typés. Permet de mettre autant d'argument que l'on veut dans le message */ void** arg; }MsgBuffer; /* Variables globales */ pthread_mutex_t mutex_stop; /* mutex de la condition pour stopper le programme */ pthread_cond_t cond_signalPoubelleNormale; /* moniteur d'attente pour le service de ramssage d'un signal d'une poubelle pleine */ pthread_cond_t cond_fin; /* moniteur d'attente du main de fin de programme */ static bool stop = false; /* Variable permettant la continuation du programme */ int* ipcID; /* ID de l'ipc permettant les messages entre entités */ int* ipcPoubelleCamion; /* ID de l'ipc permettant les messages entre poubelles et camions */ int* ipcSignaux; /* ID de l'ipc permettant les messages de plusieurs émetteur à un seul receveur */ int* ID; /* Variable permettant d'assigner un ID unique à toutes les entités de notre programme */ int* NB_UTILISATEUR; /* Nombre de famille d'utilisateurs */ int* NB_PBLN; /* Nombre de conteneurs normales */ int* NB_PBLC; /* Nombre de conteneurs carton */ int* NB_PBLP; /* Nombre de conteneurs plastique */ int* NB_PBLV; /* Nombre de conteneurs verre */ int* NB_BAC; /* Nombre de bacs individuels */ int* NB_CPBLN; /* Nombre de camions poubelle destinés aux conteneurs normaux */ int* NB_CPBLC; /* Nombre de camions poubelle destinés aux conteneurs cartons */ int* NB_CPBLP; /* Nombre de camions poubelle destinés aux conteneurs plastiques */ int* NB_CPBLV; /* Nombre de camions poubelle destinés aux conteneurs verres */ /* Prototypes des procédures et des fonctions de ipc.c */ /* Procédure creation_ipc * Cette procédure sert à créer les 3 ipc déclarées au dessus avec la primitive * msgget. * Paramètres : - char* name : Nom de l'éxécutable. */ void creation_ipc(char* name); /* Procédure creation_message1 * Cette procédure assigne les différentes valeurs en paramètre au message également passé en paramètres. Le 1 signifie qu'il n'y a qu'un seul paramètre non typé. * Paramètres : - MsgBuffer* m : Message dont les attributs vont être modifiés; * - long type : Type du message servant à être filtré parmi les autres; * - void* arg1 : Argument qui va être incorporé au message. */ void creation_message1(MsgBuffer* m, long type, void* arg1); /* Procédure creation_message2 * Cette procédure assigne les différentes valeurs en paramètre au message également passé en paramètres. Le 2 signifie qu'il y a deux paramètres non typés. * Paramètres : - MsgBuffer* m : Message dont les attributs vont être modifiés; * - long type : Type du message servant à être filtré parmi les autres; * - void* arg1 : Argument qui va être incorporé au message. * - void* arg2 : Argument qui va être incorporé au message. */ void creation_message2(MsgBuffer* m, long type, void* arg1, void* arg2); /* Procédure destruction_message * Cette procédure va détruire tous les arguments que comporte ce message. * Paramètres : - MsgBuffer* m : Message dont les arguments vont être détruits. */ void destruction_message(MsgBuffer* m); /* Procédure destruction_ipc * Cette procédure va détruire les 3 ipc de notre projet avec la primitive msgctl. */ void destruction_ipc(); #endif // IPC_H
C
/* Eloisa Silva de Morais - 1960881 Turma A 20) Um hotel cobra R$ 50,00 reais a diária e mais uma taxa de serviços. A taxa de serviços é de: • 15,30 por dia, se número de diárias <15 • 10,00 por dia, se número de diárias =15 • 8,50 por dia, se número de diárias >15 Faça um programa que lê a quantidade de dias que o hóspede ficou no hotel e imprime a taxa e total a pagar. */ #include <stdio.h> #include <locale.h> int main() { setlocale(LC_ALL, "Portuguese"); //Declaração das variáveis float taxaDeServico; //Armazena a taxa de serviço int nDiarias; //Guarda o numero de diárias digitado pelo usuário float totalDespesas; //Guarda o resultado do cálculo da despesa do hóspede //Interação com o usuário printf("Digite a quantidade de diárias: "); scanf("%d", &nDiarias); if (nDiarias < 15) { taxaDeServico = 15.3; } else if (nDiarias == 15) { taxaDeServico = 10; } else if (nDiarias > 15) { taxaDeServico = 8.5; } //Cálculo do total a pagar totalDespesas = nDiarias * taxaDeServico; //Exibe resultado printf("Após aplicação da taxa diária de serviços de %.2f, o total a ser pago pelo cliente é R$%.f.\n", taxaDeServico, totalDespesas); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <conio.h> // for _getche() #include <stdlib.h> // for system(), exit() #include <Windows.h> // for Sleep() #include <time.h> // for time() #define MaxWord 1000 #define MaxWLen 20 #define MaxMLen 50 #define MaxSLen 160 #define DelayTime 3000 // ޴ ð (: 1/1000) #define DictName "eng.dic" typedef struct { char word [MaxWLen]; char mean [MaxMLen]; char synonym [MaxWLen]; char antonym [MaxWLen]; char sentence[MaxSLen]; } EWord; int openWord (EWord *); int addWord (EWord *, int); void listWord (EWord *, int); void searchWord(EWord *, int); void memoryWord(EWord *, int); void saveWord (EWord *, int); int main(void) { EWord Dict[MaxWord] = { 0 }; // Main Dictionary char choice; // Input character int line = 0; // line counter int WCount = 0; // Total Number of EWord char *FBanner = "*************** ܾ v0.1 **************\n"; puts(FBanner); WCount = openWord(Dict); // ܾ do { system("cls"); // ȭ puts(FBanner); printf("*** ޴ ϳ ϼ.\n\n"); printf("1.Է(A), 2.˻(S), 3.(L), 4.ϱ(M), 5.(Q) : "); choice=_getch(); fflush(stdin); switch (choice) { case '1': case 'A': case 'a': printf("%c\n",choice); if (WCount < MaxWord) WCount = addWord(Dict, WCount); else { printf("\a\a** ܾ áϴ!"); Sleep(DelayTime); } break; case '2': case 'S': case 's': printf("%c\n",choice); if (WCount > 0) searchWord(Dict, WCount); else { printf("\a\a** ܾ ֽϴ!"); Sleep(DelayTime); } break; case '3': case 'L': case 'l': printf("%c\n",choice); if (WCount > 0){ listWord(Dict, WCount); } else { printf("\a\a** ܾ ֽϴ!"); Sleep(DelayTime); } break; case '4': case 'M': case 'm': printf("%c\n",choice); if (WCount > 0) memoryWord(Dict, WCount); else { printf("\a\a** ܾ ֽϴ!"); Sleep(DelayTime); } break; case '5': case 'Q': case 'q': printf("%c\n",choice); if (WCount > 0) { saveWord(Dict, WCount); printf("\n\n ** %d ܾ ܾ忡 ߽ϴ.\n", WCount); } else printf("\n\n ** ܾ忡 ܾ ϴ.\n"); printf("\n\a*** α׷ ϰڽϴ. ***\n"); Sleep(DelayTime); break; default: printf("\a߸ Էϼ̽ϴ.\n"); Sleep(DelayTime); break; } } while ((choice != 'q') && (choice != 'Q') && (choice != '5')); return 0; } int openWord(EWord *pDict) { FILE *file; int rCount = 0, line = 0; int choice; char temp[MaxSLen]; // read buffer if ((file = fopen(DictName, "rt")) == NULL) { printf("*** ܾ (eng.dic) ϴ.\n"); printf(" - ܾ α׷ ġ ־ մϴ.\n"); printf(" - ϼ - (1) ܾ (2) ϱ : "); while (1) { choice = _getche(); if (choice == '1') { printf("\nܾ ϴ.\n"); Sleep(2000); return rCount; // 0 } else if (choice == '2') { printf("\nα׷ մϴ!\n"); Sleep(2000); exit(0); } else continue; } } else { while (fgets(temp, sizeof(temp), file) != NULL) { temp[strlen(temp) - 1] = '\0'; switch (line) { case 0: strcpy(pDict[rCount].word, temp); line++; break; case 1: strcpy(pDict[rCount].mean, temp); line++; break; case 2: strcpy(pDict[rCount].synonym, temp); line++; break; case 3: strcpy(pDict[rCount].antonym, temp); line++; break; case 4: strcpy(pDict[rCount].sentence, temp); line = 0; rCount++; break; } } printf("\aܾ忡 %d ܾ о鿴ϴ.\n", rCount); Sleep(DelayTime); fclose(file); return rCount; } } void saveWord(EWord *pDict, int WNum) { FILE *file; int i; if ((file = fopen(DictName, "wt")) == NULL) { printf(" \a**ܾ !\n"); return; } for (i = 0; i < WNum; i++) { fprintf(file, "%s\n", pDict[i].word); fprintf(file, "%s\n", pDict[i].mean); fprintf(file, "%s\n", pDict[i].synonym); fprintf(file, "%s\n", pDict[i].antonym); fprintf(file, "%s\n", pDict[i].sentence); } fclose(file); } int addWord (EWord *eng,int num) { int i; char j=0; for(i=0;j!='Q'&&j!='q';num++){ printf("\nܾ ö Էϼ: "); fgets(eng[num].word, MaxWLen, stdin); printf("\nܾ Էϼ: "); fgets(eng[num].mean, MaxMLen, stdin); printf("\nܾ Ǿ Էϼ: "); fgets(eng[num].synonym, MaxWLen, stdin); printf("\nܾ Ǿ Էϼ: "); fgets(eng[num].antonym, MaxWLen, stdin); printf("\nܾ Էϼ: "); fgets(eng[num].sentence, MaxSLen, stdin); printf(" Q ð Է½ ƹŰ"); j=_getch(); } return num; } void listWord (EWord* eng, int num) { int i,j; EWord temp; for(i=0; i<num-1; i++){ for(j=i+1; j<num; j++){ if(strcmp(eng[i].word,eng[j].word)>0){ temp=eng[i]; eng[i]=eng[j]; eng[j]=temp; } } } for(i=0; i<num; i++){ printf("=====[%d]° ܾ=====\n",i+1); printf("- ܾ : %s", eng[i].word); printf("- ǹ : %s", eng[i].mean); printf("- Ǿ : %s", eng[i].synonym); printf("- Ǿ : %s", eng[i].antonym); printf("- : %s\n", eng[i].sentence); } system("PAUSE"); } void searchWord (EWord *eng, int num) { int i,j; char Sword[20]; // Ž ܾ 迭 printf(" ˰ ϴ ܾ Էϼ: "); fgets(Sword, sizeof(Sword), stdin); for(i=0;i<num; i++) if(strcmp(Sword,eng[i].word)==0) j=i; if(j>=0&&j<=num){ printf("- ܾ : %s", eng[j].word); printf("- ǹ : %s", eng[j].mean); printf("- Ǿ : %s", eng[j].synonym); printf("- Ǿ : %s", eng[j].antonym); printf("- : %s\n", eng[j].sentence); }else printf("Է ܾ ϴ.\n"); system("PAUSE"); } void memoryWord (EWord *eng, int num) { int a; char b; int i; srand(time(NULL)); a= rand() % num; for(i=0; a<num; i++) { printf("- ܾ : %s", eng[a].word); printf("ܾ ƹŰ .\n"); b=_getch(); printf("- ǹ : %s", eng[a].mean); system("PAUSE"); return; } }
C
#include "holberton.h" /** * _strlen - Computes length of a string * @s: The string in question * * Return: The length of said string * */ int _strlen(char *s) { int len = 0; while (*s) { len++; s++; } return (len); }
C
#include<stdio.h> #include<stdlib.h> struct twoints{ int a; int b; }; int main(){ struct twoints* p = (struct twoints*) malloc(100*sizeof(struct twoints)); (*(p+2)).a = 6; free(p); int a; a = 5; printf("%d",a); }
C
/* *Created by Deangeli Gomes Neves * * This software may be freely redistributed under the terms * of the MIT license. * */ #ifndef _COMMON_H_ #define _COMMON_H_ #include <stdlib.h> #include <stdio.h> //#include <malloc.h> #include <math.h> #include <string.h> #include <limits.h> #include <time.h> #include <stdint.h> // for integer typedefs #include <float.h> #include <ctype.h> #include <stddef.h> #include <dirent.h> /* Error messages */ #define MSG1 "Cannot allocate memory space" #define MSG2 "Cannot open file" /* Common data types to all programs */ typedef unsigned short ushort; #ifndef __cplusplus #ifndef _WIN32 #ifndef __cplusplus typedef enum boolean {false,true} bool; #endif #else typedef unsigned short ushort; #endif #endif typedef struct timeval timer; typedef unsigned char uchar; typedef struct _point{ float x, y, z; } Vector, Point; typedef struct _voxel { int x, y, z; } Voxel; /* Common definitions */ #define PI 3.1415926536 #define INTERIOR 0 #define EXTERIOR 1 #define BOTH 2 #define RED 0 #define GREEN 1 #define BLUE 2 #define WHITE 0 #define GRAY 1 #define BLACK 2 #define NIL -1 #define INCREASING 1 #define DECREASING 0 #define Epsilon 1E-05 #define CG 1 #define CO 2 #define AXIS_X 0 #define AXIS_Y 1 #define AXIS_Z 2 /* Common operations */ #ifndef MAX #define MAX(x,y) (((x) > (y))?(x):(y)) #endif #ifndef MIN #define MIN(x,y) (((x) < (y))?(x):(y)) #endif #ifndef ValidVoxel #define ValidVoxel(img, v) ((v.x >= 0) && (v.x < img->nx) && (v.y >= 0) && (v.y < img->ny) && (v.z >= 0) && (v.z < img->nz)) #endif #define ROUND(x) ((x < 0)?(int)(x-0.5):(int)(x+0.5)) #define SIGN(x) ((x >= 0)?1:-1) #define isAlmostZero(value) (fabs( (double)value) <= 0.000001) int AlmostZero(double x); /* Check if variable is almost zero*/ char *AllocCharArray(int n); /* It allocates 1D array of n characters */ uchar *AllocUCharArray(int n); /* It allocates 1D array of n characters */ ushort *AllocUShortArray(int n); /* It allocates 1D array of n characters */ int *AllocIntArray(int n); /* It allocates 1D array of n integers */ float *AllocFloatArray(int n); /* It allocates 1D array of n floats */ double *AllocDoubleArray(int n);/* It allocates 1D array of n doubles */ void Error(char *msg,char *func); /* It prints error message and exits the program. */ void Warning(char *msg,char *func); /* It prints warning message and leaves the routine. */ void Change(int *a, int *b); /* It changes content between a and b */ int NCFgets(char *s, int m, FILE *f); /* It skips # comments */ /** * Gera um número inteiro aleatório no intervalo [low,high]. http://www.ime.usp.br/~pf/algoritmos/aulas/random.html **/ int RandomInteger (int low, int high); double randomNormalized(); double randomNumber(double low,double high); double generateGaussianNoise(double mean, double standardDeviation); char *copyString(const char *str); char *splitStringAt(const char *phrase, const char *delimiter, long position); #endif
C
#include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <wait.h> #include <time.h> #include <string.h> #define CHILDS 2 #define ITERATIONS_TO_TEST 30 #define NUMBER_OF_VALUES 10 typedef struct{ int numbers[NUMBER_OF_VALUES]; int data_shared; } shared_data_struct; void enter_shared_data_struct(shared_data_struct* shared_data, int gate); void leave_shared_data_struct(shared_data_struct* shared_data, int gate); int main(){ int i,interactions=0; int shm_field; int data_size = sizeof(shared_data_struct); shm_unlink("/ex13_shm"); shm_field = shm_open("/ex13_shm", O_CREAT | O_EXCL | O_RDWR , S_IRUSR|S_IWUSR); if (shm_field == -1){ perror("Opening shared memory ERROR.\n"); exit(EXIT_FAILURE); } if (ftruncate (shm_field, data_size) == -1){ perror("Space in Shared Memory ERROR\n"); exit(EXIT_FAILURE); } shared_data_struct * shared_data = (shared_data_struct*)mmap(NULL, data_size, PROT_READ|PROT_WRITE,MAP_SHARED,shm_field,0); if(shared_data == MAP_FAILED){ perror("Error maping the object.\n"); exit(EXIT_FAILURE); } char name[7]; sem_t *semaphores[CHILDS+1]; for (i=1; i<=CHILDS+1; i++){ sprintf(name, "/ex13_%d", i); sem_unlink(name); if (i==1) semaphores[i-1] = sem_open(name,O_CREAT|O_EXCL, 0644, 1); if (i>1) semaphores[i-1] = sem_open(name,O_CREAT|O_EXCL, 0644, 0); if(semaphores[i-1] == SEM_FAILED){ perror("Error creating the semaphore!\n"); exit(EXIT_FAILURE); } } shared_data->data_shared=0; srand(time(NULL)); for(i = 0; i < CHILDS; i++){ pid_t pid = fork(); if(pid == -1){ perror("Error on fork system call.\n"); exit(EXIT_FAILURE); } if(pid == 0){ while(interactions<ITERATIONS_TO_TEST/2){ sem_wait(semaphores[0]); if (shared_data->data_shared < 10){ int action = rand() % 5; shared_data->numbers[shared_data->data_shared] = action; printf("Producer%d [%d] -> %d\n", i+1, shared_data->data_shared, shared_data-> numbers[shared_data->data_shared]); shared_data->data_shared++; interactions++; } if (shared_data->data_shared == 10){ sem_post(semaphores[1]); sem_wait(semaphores[2]); } sem_post(semaphores[0]); } if(munmap(shared_data, data_size) == -1){ perror("Munmap failed.\n"); exit(EXIT_FAILURE); } if(close(shm_field) == -1){ perror("Cant close object.\n"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } } int values[30]; while(interactions<ITERATIONS_TO_TEST){ sem_wait(semaphores[1]); for (i=0; i<NUMBER_OF_VALUES; i++){ values[interactions] = shared_data->numbers[i]; printf("Consumer [%d] -> %d\n", interactions, values[interactions]); interactions++; } shared_data->data_shared=0; sem_post(semaphores[2]); } int status; for(i = 0; i < CHILDS; i++){ wait(&status); } if(munmap(shared_data, data_size) == -1){ perror("Munmap failed.\n"); exit(EXIT_FAILURE); } if(close(shm_field) == -1){ perror("Cant close object.\n"); exit(EXIT_FAILURE); } if (shm_unlink("/ex13_shm") < 0){ perror("unlink failed\n"); exit(EXIT_FAILURE); } for (i=1; i<=CHILDS+1; i++){ sprintf(name, "/ex13_%d", i); sem_unlink(name); } shm_unlink("/ex13_shm"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_number.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: onapoli- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/05/29 15:56:59 by onapoli- #+# #+# */ /* Updated: 2020/08/18 12:05:33 by onapoli- ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static int print_n_count_sign(char **num_char, int *str_len, int sign) { if (!sign) return (0); *num_char += 1; *str_len -= 1; return (write(1, "-", 1)); } static int left_print(t_modifier *f_mod, char *num_char, int str_len, int sign) { int blank_precision; int blank_width; int prnt_cnt; blank_precision = f_mod->precision > (str_len - sign) ? f_mod->precision - str_len + sign : 0; blank_width = f_mod->width > (blank_precision + str_len) ? f_mod->width - blank_precision - str_len : 0; prnt_cnt = 0; if (*num_char == '-') prnt_cnt += print_n_count_sign(&num_char, &str_len, sign); prnt_cnt += ft_print_repeat(blank_precision, '0'); prnt_cnt += write(1, num_char, str_len); prnt_cnt += ft_print_repeat(blank_width, ' '); return (prnt_cnt); } static int right_print(t_modifier *f_mod, char *num_char, int str_len, int sign) { int blank_precision; int blank_width; int fill_char; int prnt_cnt; blank_precision = f_mod->precision > (str_len - sign) ? f_mod->precision - str_len + sign : 0; blank_width = f_mod->width > (blank_precision + str_len) ? f_mod->width - blank_precision - str_len : 0; fill_char = ' '; prnt_cnt = 0; if (f_mod->zero && !f_mod->dot) { fill_char = '0'; prnt_cnt += print_n_count_sign(&num_char, &str_len, sign); } prnt_cnt += ft_print_repeat(blank_width, fill_char); if (*num_char == '-') prnt_cnt += print_n_count_sign(&num_char, &str_len, sign); prnt_cnt += ft_print_repeat(blank_precision, '0'); prnt_cnt += write(1, num_char, str_len); return (prnt_cnt); } int ft_print_number(va_list ap, t_modifier *f_mod) { int num; char *num_char; int str_len; int sign; int prnt_cnt; num = va_arg(ap, int); num_char = ft_itoa(num); str_len = ft_strlen(num_char); if (f_mod->dot && !f_mod->precision && !num) str_len = 0; sign = *num_char == '-' ? 1 : 0; prnt_cnt = 0; if (f_mod->minus) prnt_cnt += left_print(f_mod, num_char, str_len, sign); else prnt_cnt += right_print(f_mod, num_char, str_len, sign); free(num_char); return (prnt_cnt); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct bch_control {unsigned int* a_pow_tab; } ; /* Variables and functions */ int GF_M (struct bch_control*) ; int a_log (struct bch_control*,unsigned int) ; size_t mod_s (struct bch_control*,int) ; int solve_linear_system (struct bch_control*,unsigned int*,unsigned int*,int) ; __attribute__((used)) static int find_affine4_roots(struct bch_control *bch, unsigned int a, unsigned int b, unsigned int c, unsigned int *roots) { int i, j, k; const int m = GF_M(bch); unsigned int mask = 0xff, t, rows[16] = {0,}; j = a_log(bch, b); k = a_log(bch, a); rows[0] = c; /* buid linear system to solve X^4+aX^2+bX+c = 0 */ for (i = 0; i < m; i++) { rows[i+1] = bch->a_pow_tab[4*i]^ (a ? bch->a_pow_tab[mod_s(bch, k)] : 0)^ (b ? bch->a_pow_tab[mod_s(bch, j)] : 0); j++; k += 2; } /* * transpose 16x16 matrix before passing it to linear solver * warning: this code assumes m < 16 */ for (j = 8; j != 0; j >>= 1, mask ^= (mask << j)) { for (k = 0; k < 16; k = (k+j+1) & ~j) { t = ((rows[k] >> j)^rows[k+j]) & mask; rows[k] ^= (t << j); rows[k+j] ^= t; } } return solve_linear_system(bch, rows, roots, 4); }
C
/* ** EPITECH PROJECT, 2020 ** B-CPE-200-RUN-2-1-matchstick-yann.joubert ** File description: ** change_map.c */ #include "my.h" #include "matchstick.h" sticks_s *change_map(sticks_s *stick) { int i = my_strlen(stick->map[stick->line]); int compt = 0; for (; stick->map[stick->line][i] != '|'; i--); for (; compt < stick->match; compt++) { stick->map[stick->line][i] = ' '; i--; } return (stick); }
C
/* ** EPITECH PROJECT, 2019 ** CPE_BSQ_2019 ** File description: ** check_number_first_ligne */ #include "my.h" char *recup_number(char *str); int check_number_first_ligne(char *str) { int y = my_strlen(recup_number(str)); for (int i = 0; str[i] != '\n' && str[i] >= '0' && str[i] <= '9'; i++) if (y == i) return (0); else return (84); }
C
#include <stdio.h> #include <stdint.h> #include <unistd.h> #include <string.h> #include <openssl/md5.h> void grant_shell() { printf("Welcome back superuser!\nHere's your shell:\n"); setuid(geteuid()); char *const args[] = {"/bin/sh", NULL}; execv(args[0], args); } uint8_t valid_hash[] = {193, 179, 147, 105, 178, 122, 16, 111, 31, 197, 119, 133, 91, 193, 217, 252}; //easy way of storing hash in source file (16 bytes represented as 16 uint8's) int verify(char *argv1) { char passwd[21]; //holds 20 characters plus a null byte strcpy(passwd, argv1); passwd[20] = '\0'; //set the last char to null, ensures the string ends! uint8_t hash[16]; //enough space for 16 byte hash MD5(passwd, strlen(passwd), (char *)hash); return !memcmp(hash, valid_hash, 16); } int main(int argc, char **argv) { if(argc != 2) { printf("Usage: %s passwd\n", *argv); return 1; } if(verify(argv[1])) { //if password is okay grant_shell(); } else { printf("You're not the superuser, you don't know the password!!\n"); } return 0; }
C
// 顺序结构模拟俄罗斯轮盘赌博 #include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> typedef struct line { int No; struct line *next; } line; // 初始化链表 void initLine(line **head, int n); // 输出链表 void display(line *head); int main() { line *head = NULL; srand((int)time(0)); int n, shootNum, round = 1; printf("输入赌徒人数:"); scanf("%d", &n); initLine(&head, n); line *lineNext = head; // 用于记录每轮开始的位置 // 仅当链表中只含有一个节点时,即头节点时,退出循环 while (head->next != head) { printf("第%d轮开始,从编号为%d的人开始,", round, lineNext->No); shootNum = rand()%n + 1; printf("枪在第%d次扣动扳机时会响\n", shootNum); line *temp = lineNext; // 遍历循环链表,找到将要删除节点的上一个节点 for (int i = 1; i < shootNum - 1; i++) { temp = temp->next; } // 将要删除节点从链表中删除,并释放其占用控件 printf("编号为%d的赌徒退出赌博,剩余赌徒编号依次为:\n", temp->next->No); line *del = temp->next; temp->next = temp->next->next; if (del == head) { head = head->next; } free(del); display(head); // 赋值新一轮开始的位置 lineNext = temp->next; round++; // 记录循环次数 } printf("最终胜利的赌徒编号是:%d\n", head->No); return EXIT_SUCCESS; } // 按照赌徒人数,初始化循环链表 void initLine(line **head, int n) { *head = (line*)malloc(sizeof(line)); (*head)->next = NULL; (*head)->No = 1; line *list = *head; for (int i = 1; i < n; i++) { line *body = (line*)malloc(sizeof(line)); body->next = NULL; body->No = i + 1; list->next = body; list = list->next; } list->next = *head; // 将链表成环 } // 输出链表中所有节点信息 void display(line *head) { line *temp = head; while (temp->next != head) { printf("%d", temp->No); temp = temp->next; } printf("%d\n", temp->No); }
C
#include <allegro5/allegro.h> #include "common.h" #ifndef ELEMENT_H #define ELEMENT_H // Element structure typedef struct { ALLEGRO_BITMAP *bitmap; // Alegro bitmap for drawing the element ALLEGRO_COLOR color; // Element color int height; // Element height int width; // Element width int y; // Element y position on the map int x; // Element x position on the map } Element; // Create a element with the given dimentions, positions and color Element createElement(int width, int height, int x, int y, ALLEGRO_COLOR color); // Check the element validity bool destroyElement(Element element); // Destroy the given element (destroy the bitmap) bool checkElement(const Element element); // Render the element with its proportions and position on the given display void renderElement(Element element, ALLEGRO_DISPLAY *display); // Move the element on the given course and step size void moveElement(Element *element, direction course, int step_size); // Check the colision between the element and the display bool checkElementDisplayColision(Element element); // Check the colision between two elements bool checkElementsColision(Element element_1, Element element_2); // Print the element formated info void printElement(const Element element); #endif
C
#include <stdlib.h> #include <stdio.h> #include "Affiche_Jeu.h" /* -------------------------------------------------------- */ void affiche_quadrillage(Plateau P) { int i; /* NB : En soi on pourrait combiner les deux vu qu'on a forcément ligne = colonne, mais au cas où on change les options */ /* Lignes verticales */ for (i = 1 ; i < P.nb_col ; i++) { MLV_draw_filled_rectangle(i * TAILLE_IMAGE / P.nb_col, 0, 5, TAILLE_IMAGE, MLV_COLOR_BLACK); } /* Lignes horizontales */ for (i = 1 ; i < P.nb_lig ; i++) { MLV_draw_filled_rectangle(0, i * TAILLE_IMAGE / P.nb_lig, TAILLE_IMAGE, 5, MLV_COLOR_BLACK); } } /* -------------------------------------------------------- */ void affiche_interface_jeu(Plateau P) { int longueur_plateau = TAILLE_IMAGE * 2 + TAILLE_SEPARATEUR_IMAGE; /* Ligne séparateur entre les 2 images, et entre les images et l'interface en as */ MLV_draw_filled_rectangle(TAILLE_IMAGE, 0, TAILLE_SEPARATEUR_IMAGE, TAILLE_IMAGE, COULEUR_SOUS_MENU); MLV_draw_filled_rectangle(0, TAILLE_IMAGE, longueur_plateau, TAILLE_SEPARATEUR_IMAGE, COULEUR_SOUS_MENU); /* 1ère case : Nombre de coups joués */ MLV_draw_text_box(0, TAILLE_IMAGE + TAILLE_SEPARATEUR_IMAGE, longueur_plateau / 4, TAILLE_INTERFACE - TAILLE_SEPARATEUR_IMAGE, "Coups joues : %d", 10, COULEUR_SOUS_MENU, MLV_COLOR_BLACK, MLV_COLOR_WHITE, MLV_TEXT_CENTER, MLV_HORIZONTAL_CENTER, MLV_VERTICAL_CENTER, P.coups_joues); /* 2ème case : Temps écoulé */ MLV_draw_text_box(longueur_plateau / 4, TAILLE_IMAGE + TAILLE_SEPARATEUR_IMAGE, longueur_plateau / 4, TAILLE_INTERFACE - TAILLE_SEPARATEUR_IMAGE, "Temps écoulé : %d", 10, COULEUR_SOUS_MENU, MLV_COLOR_BLACK, MLV_COLOR_WHITE, MLV_TEXT_CENTER, MLV_HORIZONTAL_CENTER, MLV_VERTICAL_CENTER, P.time / 1000); /* 3ème case : Retry */ MLV_draw_text_box(longueur_plateau * 2 / 4, TAILLE_IMAGE + TAILLE_SEPARATEUR_IMAGE, longueur_plateau / 4, TAILLE_INTERFACE - TAILLE_SEPARATEUR_IMAGE, "Recommencer", 10, COULEUR_SOUS_MENU, MLV_COLOR_WHITE, MLV_COLOR_BLACK, MLV_TEXT_CENTER, MLV_HORIZONTAL_CENTER, MLV_VERTICAL_CENTER); /* 4ème case : Quitter */ MLV_draw_text_box(longueur_plateau * 3 / 4, TAILLE_IMAGE + TAILLE_SEPARATEUR_IMAGE, longueur_plateau / 4, TAILLE_INTERFACE - TAILLE_SEPARATEUR_IMAGE, "Quitter", 10, COULEUR_SOUS_MENU, MLV_COLOR_WHITE, MLV_COLOR_BLACK, MLV_TEXT_CENTER, MLV_HORIZONTAL_CENTER, MLV_VERTICAL_CENTER); MLV_actualise_window(); } /* -------------------------------------------------------- */ void affiche_image(const MLV_Image *image, Plateau P) { int i, j; double taille_case_col = TAILLE_IMAGE / P.nb_col, taille_case_lig = TAILLE_IMAGE / P.nb_lig; /* Blocs du taquin */ for (i = 0 ; i < P.nb_lig ; i++) { for (j = 0 ; j < P.nb_col ; j++) { MLV_draw_partial_image(image, P.bloc[i][j].col * taille_case_col, P.bloc[i][j].lig * taille_case_lig, taille_case_col, taille_case_lig, j * taille_case_col, i * taille_case_lig); } } /* Case noire du taquin */ MLV_draw_filled_rectangle(P.case_vide.col * taille_case_col, P.case_vide.lig * taille_case_lig, taille_case_col, taille_case_lig, MLV_COLOR_BLACK); /* Image originale à droite */ MLV_draw_partial_image(image, 0, 0, TAILLE_IMAGE, TAILLE_IMAGE, TAILLE_IMAGE + TAILLE_SEPARATEUR_IMAGE, 0); MLV_draw_filled_rectangle(TAILLE_IMAGE * 2 + TAILLE_SEPARATEUR_IMAGE - taille_case_col, TAILLE_IMAGE - taille_case_lig, taille_case_col, taille_case_lig, MLV_COLOR_BLACK); /* On affiche le quadrillage et l'interface du jeu (les boutons en bas des images) */ affiche_quadrillage(P); affiche_interface_jeu(P); } /* -------------------------------------------------------- */ void affiche_victoire(Plateau P) { int longueur_plateau = (TAILLE_IMAGE * 2 + TAILLE_SEPARATEUR_IMAGE), temps = 20; /* Le while qui fait un timer = temps (en seconde) */ while (temps-- > 1) { MLV_draw_text_box(longueur_plateau * 5 / 12, TAILLE_IMAGE * 5 / 12, longueur_plateau * 2 / 12, TAILLE_IMAGE * 2 / 12, "VICTOIRE !\nFermeture automatique\nde la fenêtre dans %d sec", 10, MLV_COLOR_RED, MLV_COLOR_RED, MLV_COLOR_WHITE, MLV_TEXT_CENTER, MLV_HORIZONTAL_CENTER, MLV_VERTICAL_CENTER, temps); MLV_actualise_window(); MLV_wait_seconds(1); } MLV_free_window(); } /* -------------------------------------------------------- */ int recommencer(int x, int y) { /* On vérifie que les coordonnées (x, y) sont sur le bouton "Recommencer" */ return x > (TAILLE_IMAGE * 2 + TAILLE_SEPARATEUR_IMAGE) / 2 && x < (TAILLE_IMAGE * 2 + TAILLE_SEPARATEUR_IMAGE) * 3 / 4 && y > TAILLE_IMAGE + TAILLE_SEPARATEUR_IMAGE; } /* -------------------------------------------------------- */ int quitter(int x, int y) { /* On vérifie que les coordonnées (x, y) sont sur le bouton "Quitter" */ return x > (TAILLE_IMAGE * 2 + TAILLE_SEPARATEUR_IMAGE) * 3 / 4 && y > TAILLE_IMAGE + TAILLE_SEPARATEUR_IMAGE; } /* -------------------------------------------------------- */
C
#include "helpers.h" #include "../src/base.h" #include "../src/core/region.h" #include "../src/core/growable.h" struct list { int elem; struct list* next; }; static struct list* from_array(struct region* rgn, int* a, size_t n) { struct list* la = NULL; for (size_t i = 0; i < n; i++) { struct list* l = ALLOCATE(rgn, struct list); l->elem = a[n - i - 1]; l->next = la; la = l; } return la; } static struct list const* ith(struct list const* l, size_t i) { for (size_t j = 0; j < i; j++) { l = l->next; } return l; } static struct list* reverse(struct region* rgn, struct list const* l1) { struct list* l_rev = NULL; while (l1 != NULL) { struct list* l = ALLOCATE(rgn, struct list); l->elem = l1->elem; l->next = l_rev; l_rev = l; l1 = l1->next; } return l_rev; } TEST(rgn_list_reverse) { struct region rgn[1]; ax__init_region(rgn); int a[3] = { 1, 2, 3 }; struct list* l1 = from_array(rgn, a, 3); struct list* l2 = reverse(rgn, l1); CHECK_IEQ(ith(l2, 0)->elem, 3); CHECK_IEQ(ith(l2, 1)->elem, 2); CHECK_IEQ(ith(l2, 2)->elem, 1); CHECK_NULL(ith(l2, 3)); ax__free_region(rgn); } TEST(rgn_lots_of_small) { struct region rgn[1]; ax__init_region(rgn); for (size_t i = 0; i < 5000; i++) { (void) ALLOCATE(rgn, int); } ax__region_clear(rgn); for (size_t i = 0; i < 10000; i++) { (void) ALLOCATE(rgn, int); } ax__free_region(rgn); } TEST(rgn_big) { struct big { int stuff[2048]; }; struct region rgn[1]; ax__init_region(rgn); for (int i = 0; i < 5; i++) { (void) ALLOCATE(rgn, struct big); } ax__region_clear(rgn); for (int i = 0; i < 5; i++) { (void) ALLOCATE(rgn, struct big); } ax__free_region(rgn); } TEST(grow_structs) { struct growable g; ax__init_growable(&g, DEFAULT_CAPACITY); for (int i = 0; i < 100; i++) { PUSH(&g, &AX_DIM(i, i * 0.5)); } struct ax_dim* dims = g.data; for (int i = 0; i < 100; i++) { CHECK_DIMEQ(dims[i], AX_DIM(i, i * 0.5)); } ax__growable_clear(&g); CHECK_TRUE(ax__is_growable_empty(&g)); for (int i = 0; i < 50; i++) { PUSH(&g, &AX_DIM(i, i * 0.3)); } dims = g.data; for (int i = 0; i < 50; i++) { CHECK_DIMEQ(dims[i], AX_DIM(i, i * 0.3)); } ax__free_growable(&g); } TEST(grow_string) { struct growable g; ax__init_growable(&g, DEFAULT_CAPACITY); ax__growable_clear_str(&g); CHECK_STREQ((char*) g.data, ""); ax__growable_push_str(&g, "hello"); CHECK_STREQ((char*) g.data, "hello"); ax__growable_push_char(&g, ','); CHECK_STREQ((char*) g.data, "hello,"); ax__growable_push_str(&g, " world"); CHECK_STREQ((char*) g.data, "hello, world"); ax__free_growable(&g); }
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { /*Two pointer*/ if(!head || !n) return head; struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode)); dummy->next = head; struct ListNode* fast = dummy; struct ListNode* slow = dummy; struct ListNode* tmp = NULL; while(fast && fast->next){ while(n && fast){ fast = fast->next; n--; } if(fast && fast->next){ fast = fast->next; slow = slow->next; } } if(slow->next) tmp = slow->next->next; slow->next = tmp; return dummy->next; } /*Since the question gives that n is valid, not too many checks have to be put in place. Otherwise, this would be necessary.*/ public ListNode removeNthFromEnd(ListNode head, int n) { ListNode start = new ListNode(0); ListNode slow = start, fast = start; slow.next = head; //Move fast in front so that the gap between slow and fast becomes n for(int i=1; i<=n+1; i++) { fast = fast.next; } //Move fast to the end, maintaining the gap while(fast != null) { slow = slow.next; fast = fast.next; } //Skip the desired node slow.next = slow.next.next; return start.next; } /*2nd*/ struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { /*Two pointer*/ if(!head || !n) return head; struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode)); dummy->next = head; struct ListNode* fast = dummy; struct ListNode* slow = dummy; while((n+1)){ fast = fast->next; n--; } while(fast){ fast = fast->next; slow = slow->next; } slow->next = slow->next->next;; return dummy->next; }
C
// // htab_foreach.c // IJC2 // // Created by Radek Pistelak on 24.04.2015. // Copyright (c) 2015 Radek Pistelak. All rights reserved. // // Email: [email protected] // Compiler: Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn) // Last modified date: 28.4.2015 // #include <stdint.h> #include "htable.h" /** * @Synopsis Volani funkce pro kazdy prvek v tabulce. * @Param t Hash tabulka * @Param function Ukazatel na funkci ktera se bude volat */ void htab_foreach(htab_t* t, void (*function)(const char* key, unsigned int value)) { if (!t || !function) { return; } for (unsigned int i = 0; i < t->htab_size; i++) { // cela HT for (struct htab_listitem* item = &t->ptr[i]; ; item = item->next) { // jednotlive seznamy if (item->key) { function(item->key, item->data); } if (!item->next) break; } } } // End of file: htab_foreach.c
C
include <stdio.h> int Walk(int altar) { if (altar == 1) return 1; else if (altar == 2) return 2; else return Walk(altar - 1) + Walk(altar - 2); } int main(void) { int n; printf("How many steps(n = ?): "); scanf_s("%d", &n); printf("Totally has %d ways to get on the stairs.", Walk(n)); return 0; } //quest 1 #include <stdio.h> void Kakutani(int x) { int isOdd = x % 2; if (x == 1) { return; } else if (isOdd) { printf(" -> %d", 3 * x + 1); return Kakutani(3 * x + 1); } else { printf(" -> %d", x / 2); return Kakutani(x / 2); } } int main(void) { int x; printf("x = ?"); scanf_s("%d", &x); printf("%d", x); Kakutani(x); return 0; } //
C
#include <iostream> #include <utility> #include <tuple> #include <vector> #include <algorithm> const int jobCnt = 10; // Job start times const int startTimes[] = { 2, 3, 1, 4, 3, 2, 6, 7, 8, 9}; // Job end times const int endTimes[] = { 4, 4, 3, 5, 5, 5, 8, 9, 9, 10}; using namespace std; int main() { vector<pair<int,int>> jobs; for(int i=0; i<jobCnt; ++i) jobs.push_back(make_pair(startTimes[i], endTimes[i])); // step 1: sort sort(jobs.begin(), jobs.end(),[](pair<int,int> p1, pair<int,int> p2) { return p1.second < p2.second; }); // step 2: empty set A vector<int> A; // step 3: for(int i=0; i<jobCnt; ++i) { auto job = jobs[i]; bool isCompatible = true; for(auto jobIndex : A) { // test whether the actual job and the job from A are incompatible if(job.second >= jobs[jobIndex].first && job.first <= jobs[jobIndex].second) { isCompatible = false; break; } } if(isCompatible) A.push_back(i); } //step 4: print A cout << "Compatible: "; for(auto i : A) cout << "(" << jobs[i].first << "," << jobs[i].second << ") "; cout << endl; return 0; }
C
#include <pthread.h> #include <time.h> #include <string.h> #include <fcntl.h> #include <sys/select.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <netdb.h> #define nullptr NULL #define BUFFER_SIZE 4096 #define HTTP_VERSION "HTTP/1.1" #define CONNECTION_TYPE "Connection: close\r\n" // API -- gethostbyname() char* host_to_ip(const char* hostname){ struct hostent* host_entry = gethostbyname(hostname); // 14.215.177.39 --> unsigned int // inet_ntoa() unsigned int --> char* if(host_entry){ return inet_ntoa(*(struct in_addr*)*host_entry->h_addr_list); } return nullptr; } int http_create_socket(char* ip){ int sockfd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in sin = { 0 }; sin.sin_family = AF_INET; sin.sin_port = htons(80); sin.sin_addr.s_addr = inet_addr(ip); if(0 != connect(sockfd, (struct sockaddr*)&sin, sizeof(struct sockaddr_in))){ return -1; } fcntl(sockfd, F_SETFL, O_NONBLOCK); return sockfd; } // hostname: github.com // resource: /artintel char* http_send_request(const char* hostname, const char* resource){ char* ip = host_to_ip(hostname); int sockfd = http_create_socket(ip); char buffer[BUFFER_SIZE] = { 0 }; sprintf(buffer, "GET %s %s\r\n\ Host: %s\r\n\ %s\r\n\ \r\n", resource, HTTP_VERSION, hostname, CONNECTION_TYPE ); send(sockfd, buffer, strlen(buffer), 0); //recv() //select() fd_set fdread; FD_ZERO(&fdread); FD_SET(sockfd, &fdread); struct timeval tv; tv.tv_sec = 5; tv.tv_usec = 0; char* result = malloc(sizeof(int)); memset(result, 0, sizeof(int)); while(1){ int selection = select(sockfd + 1, &fdread, nullptr, nullptr, &tv); if(!selection || !FD_ISSET(sockfd, &fdread)){ break; } else { memset(buffer, 0, BUFFER_SIZE); int len = recv(sockfd, buffer, BUFFER_SIZE, 0); if(len == 0){ //disconnect break; } result = realloc(result, (strlen(result) + len+ 1) * sizeof(char)); strncat(result, buffer, len); } } return result; } int main(int argc, char* argv[]){ if( argc < 3 ) return -1; char* response = http_send_request(argv[1], argv[2]); printf("response: %s\n", response); free(response); }
C
#include <stdio.h> #include <stdlib.h> int isPrime (long q); int main () { const long multiple = 600851475143; long primeFactor = 1; int i; for (i = 2; i < multiple; i++) { if( multiple % i == 0 && isPrime(i) ) printf ("prime factor : %i\n",i); } /* for (i = 2; i < 25; i++) printf ("%i : %i\n", i, isPrime(i)); // */ } int isPrime (long q) { int i; for(i = 2; i < q; i++) if( q % i == 0 ) return 0; return 1; }
C
//This changes all letters to lowercase and last letters of word to upper case. //Run this like ./a.out "This is a test" --> thiS iS A tesT #include <unistd.h> #define TOLOWER(c) (c | ' ') #define TOUPPER(c) (c & '_') void ft_putchar(char c) { write(1, &c, 1); } int ft_isspace(char str) { if (str == ' ' || str == '\t') return (1); return (0); } void rstr_capitalizer(char *str) { int i = 0; while (str[i]) { while (str[i] && ft_isspace(str[i])) ft_putchar(str[i++]); if (!(ft_isspace(str[i + 1]))) ft_putchar(TOLOWER(str[i++])); while (str[i] && ((ft_isspace(str[i + 1]) || (str[i + 1] == '\0')))) ft_putchar(TOUPPER(str[i++])); } } int main(int argc, char **argv) { int i; i = 0; if (argc > 1) { *argv++; while (*argv) { rstr_capitalizer(*argv++); write(1, "\n", 1); } } return (0); }
C
#include <stdio.h> #include "mixed.h" int main() { sMixedNumber a, b, ans; mixed_set(&a, 0, 13, 24); mixed_set(&b, 0, 17, 24); mixed_print(a); mixed_print(b); mixed_add(&ans, a, b); mixed_print(ans); mixed_sub(&ans, a, b); mixed_print(ans); mixed_set(&a, 9, 9, 10); mixed_set(&b, 5, 5, 21); mixed_mul(&ans, a, b); mixed_print(ans); mixed_div(&ans, a, b); mixed_print(ans); return 0; }
C
#pragma once // STRING extern char* iniReadStr(char* Section, char* Key, const char* DefaultString); extern void iniWriteStr(char* Section, char* Key, const char* ValueString); // INT extern int iniReadInt(char* Section, char* Key, int DefaultInt); extern void iniWriteInt(char* Section, char* Key, int ValueInt, bool DecHex); // FLOAT extern float iniReadFloat(char* szSection, char* szKey, float DefaultFloat); extern void iniWriteFloat(char* szSection, char* szKey, float ValueFloat, int decimal); /// <summary> /// Searches for the given process name. /// </summary> /// <returns> /// Returns 1 if process is running, 606 if the system version cannot be determined, 607 if unsupported OS, /// 605 if the process list could not be enumerated or if some modules (i.e.: PSAPI.DLL, etc) failed to load. /// </returns> extern int isProcessRunning(const char *szToFind);
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fil_parse.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mmatiush <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/05/24 14:43:16 by mmatiush #+# #+# */ /* Updated: 2018/05/24 14:43:18 by mmatiush ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "filler.h" /* ** Read the first line from STDIN and parse board or piece dimensionsint. ** Skip all not integers, then parse first number using ft_atoi, ** then move the pointer to the end of the parsed aread and run ft_atoi ** once again to parse the second number. */ static void get_fil_object_size(int *x, int *y) { char *buff; char *buff_ptr; buff = NULL; get_next_line(STDIN_FILENO, &buff); buff_ptr = buff; if (buff_ptr) { while (!ft_isdigit(*buff)) buff++; *y = ft_atoi(buff); while (ft_isdigit(*buff)) buff++; *x = ft_atoi(buff); free(buff_ptr); } } /* ** Parse and drop the line with coloumn numbers. ** Then start parsing the board. The whle loop will break when GNL reaches ** a non numeric value, which will mean that we got to Piece dimensions. */ static int init_fil_board(t_fil_struct *fil) { char *buff; int i; buff = NULL; i = 0; if (!(fil->board = (char**)malloc(sizeof(char*) * (fil->b_y + 1)))) return (0); get_next_line(STDIN_FILENO, &buff); if (buff) { free(buff); } while (i < fil->b_y) { get_next_line(STDIN_FILENO, &buff); if (buff) { if (!(fil->board[i++] = ft_strdup(buff + 4))) return (0); free(buff); } } fil->board[i] = NULL; return (1); } static int init_fil_piece(t_fil_struct *fil) { char *buff; int i; buff = NULL; i = 0; if (!(fil->piece = (char**)malloc(sizeof(char*) * (fil->p_y + 1)))) return (0); while (i < fil->p_y) { get_next_line(STDIN_FILENO, &buff); if (buff) { if (!(fil->piece[i++] = ft_strdup(buff))) return (0); free(buff); } } fil->piece[i] = NULL; return (1); } int fill_out_fil_struct(t_fil_struct *fil) { get_fil_object_size(&fil->b_x, &fil->b_y); if (!(init_fil_board(fil))) return (0); get_fil_object_size(&fil->p_x, &fil->p_y); if (!(init_fil_piece(fil))) return (0); return (1); }
C
/* archivo 'aritReal.h' es almacenado en el directorio 'miIncludes' */ /* función que suma dos números. */ float suma(float a, float b); /* función que resta 'b' a 'a' */ float resta(float a, float b); /* función que multiplica dos números */ float multiplica(float a, float b); /*función que divide 'a' por 'b'*/ float divide(float a, float b);
C
#include "hongyulib.h" #include "ESF.h" /****************************************************************** * This is a c script for determine the ONSET and ENDSET of each record * * The ONSET is determined by using the stretched_ES_win * * Changes: * the one period window has been changed to be: * [peak_to_amp_threshold_in_front_of_peak, * peak_to_amp_threshold_at_back_of_peak] * * DATE: Keywords: * Reference: ******************************************************************/ int get_ONSET_ENDSET_for_each_record_stretched(new_RECORD* my_record, new_INPUT* my_input) { printf("---> get_ONSET_ENDSET_for_each_record Begin for stretched EW\n"); int npts_phase; int count; npts_phase = (int) (my_input->phase_len / my_input->delta ); int ista,i; int npts_peak; double AMP = 0; int npts_ONSET = 1; int npts_ENDSET = 1; double dt_ONSET = 0; double dt_ENDSET = 0; for(ista = 0; ista < my_input->sta_num;ista++) { if(my_record[ista].beyong_window_flag == -1 ) continue; // use max value as the phase peak // assumption is that the phase peak will always be the first peak // //printf( "--> on %d / %d \n", ista, my_input->sta_num ); AMP = 0; for(i = 0; i<npts_phase;i++) { if( my_record[ista].stretched_ES_win[i] >= AMP ) { AMP = fabs( my_record[ista].stretched_ES_win[i] ); npts_peak = i; } } if(npts_peak == 0) npts_peak = 100; if(npts_peak == npts_phase -1) npts_peak = npts_phase -100; // store phase peak time and npts my_record[ista].time_phase_peak = my_record[ista].phase_beg + npts_peak * my_input->delta; my_record[ista].npts_phase_peak = npts_peak; // set ONSET begtime with a noise level double amp_crit = 0.1; double noise_level = AMP * amp_crit; // go from peak forward to the onset time where value is smaller then noise level // instead of use stretched ES win, we should be using phase_win for( i = npts_peak; i> 1 ; i--) { //if(fabs( my_record[ista].stretched_ES_win[i] ) < fabs(noise_level) ) if(fabs( my_record[ista].stretched_ES_win[i] ) < fabs(noise_level) ) { npts_ONSET = i; break; } } // convert npts ONSET into dt dt_ONSET = my_record[ista].phase_beg + npts_ONSET * my_input->delta ; // npts_ENDSET is find the same way as npts_ONSET //npts_ENDSET = npts_peak + (npts_peak - npts_ONSET); for( i = npts_peak; i< npts_phase ; i++) { if(fabs( my_record[ista].stretched_ES_win[i] ) < fabs(noise_level) ) { npts_ENDSET = i; break; } } if( npts_ONSET == npts_ENDSET ) { npts_ONSET = npts_peak -20; npts_ENDSET = npts_peak -20; if(npts_ONSET < 0 ) npts_ONSET = 0; if(npts_ENDSET > npts_phase-1) npts_ENDSET = npts_phase -1; } int npts_peak_ONSET = npts_peak - npts_ONSET; dt_ENDSET = my_record[ista].phase_beg + ( npts_peak+ npts_peak_ONSET) * my_input->delta ; //printf(" dt_ENDSET %lf %d %d %lf \n", my_record[ista].phase_beg, npts_peak , npts_peak_ONSET, my_input->delta) ; // store ONSET into dt_obs_prem my_record[ista].dt_obs_prem = dt_ONSET; my_record[ista].ONSET = dt_ONSET; my_record[ista].ENDSET = dt_ENDSET; int d_npts; int npts_one_period = dt_ENDSET - dt_ONSET; // =========================================================== // get misfit measurement misfit // =========================================================== // ================================== // when we calculate the misfit, we want to use the un-masked long // window to do the calculation, thus, we need to reconstruct the // phase_win from original long_win double phase_win_from_long_orig[npts_phase]; read_phase_window_original_long_win(&my_record[ista],my_input, phase_win_from_long_orig); // ================================== double misfit_ES=0; double misfit_record=0; double misfit = 0; double misfit_diff = 0; misfit = 0; misfit_diff = 0; double ES_amp; double record_amp; int amp_loc; amplitudeloc(my_record[ista].stretched_ES_win, npts_phase, &amp_loc , &ES_amp,1); amplitudeloc(phase_win_from_long_orig , npts_phase, &amp_loc , &record_amp,1); if(ES_amp == 0 ) ES_amp = 1; if(record_amp == 0 ) record_amp = 1; for(count = npts_ONSET; count < npts_ENDSET; count++) { misfit_diff += fabs( my_record[ista].stretched_ES_win[count] / ES_amp - phase_win_from_long_orig[count] / record_amp); } d_npts = (npts_ENDSET - npts_ONSET); if(d_npts == 0) d_npts =1; misfit = misfit_diff / d_npts; my_record[ista].misfit = misfit; // =========================================================== // get misfit measurement misfit_pre // =========================================================== //for empirical wavelet and for records misfit_ES=0; misfit_record=0; misfit = 0; misfit_diff = 0; double misfit_pre_2T = 0; double misfit_pre_3T = 0; double misfit_pre_4T = 0; int npts_beg; npts_beg = 2*npts_ONSET - npts_ENDSET; if(npts_beg < 0 ) npts_beg = 0; int npts_end; npts_end = npts_ONSET; for(count = npts_beg; count < npts_end; count++) { misfit_diff += fabs( my_record[ista].stretched_ES_win[count] / ES_amp - phase_win_from_long_orig[count] / record_amp); } d_npts = npts_end - npts_beg; if(d_npts == 0) d_npts =1; misfit = misfit_diff / d_npts; my_record[ista].misfit_pre = misfit; // get misfit_pre2T npts_beg = npts_ONSET - 2*(npts_ENDSET - npts_ONSET); npts_end = npts_ONSET - 1*(npts_ENDSET - npts_ONSET); if( npts_beg < 0) npts_beg = 0; if( npts_end >= npts_phase) npts_end = npts_phase -1; misfit_diff = 0; for(count = npts_beg; count < npts_end; count++) { misfit_diff += fabs( my_record[ista].stretched_ES_win[count] / ES_amp - phase_win_from_long_orig[count] / record_amp); } d_npts = npts_end - npts_beg; if(d_npts == 0) d_npts =1; misfit = misfit_diff / d_npts; my_record[ista].misfit_pre2T = misfit; // get misfit_pre3T npts_beg = npts_ONSET - 3*(npts_ENDSET - npts_ONSET); npts_end = npts_ONSET - 2*(npts_ENDSET - npts_ONSET); if( npts_beg < 0) npts_beg = 0; if( npts_end >= npts_phase) npts_end = npts_phase -1; misfit_diff = 0; for(count = npts_beg; count < npts_end; count++) { misfit_diff += fabs( my_record[ista].stretched_ES_win[count] / ES_amp - phase_win_from_long_orig[count] / record_amp); } d_npts = npts_end - npts_beg; if(d_npts == 0) d_npts =1; misfit = misfit_diff / d_npts; my_record[ista].misfit_pre3T = misfit; //printf("misfit pre pre2T pre3T %lf %lf %lf \n", my_record[ista].misfit_pre, //my_record[ista].misfit_pre2T, //my_record[ista].misfit_pre3T); // =========================================================== // get misfit measurement misfit_bak // =========================================================== //for empirical wavelet and for records misfit_ES=0; misfit_record=0; misfit = 0; misfit_diff = 0; npts_beg = npts_ENDSET; npts_end = 2*npts_ENDSET - npts_ONSET; if( npts_end > npts_phase ) npts_end = npts_phase; for(count = npts_beg; count < npts_end; count++) { misfit_diff += fabs( my_record[ista].stretched_ES_win[count] / ES_amp - phase_win_from_long_orig[count] / record_amp); } d_npts = npts_end - npts_beg; if(d_npts == 0) d_npts =1; misfit = misfit_diff / d_npts; my_record[ista].misfit_bak = misfit; // get misfit_bak2T npts_beg = npts_ENDSET + 1*(npts_ENDSET - npts_ONSET); npts_end = npts_ENDSET + 2*(npts_ENDSET - npts_ONSET); if( npts_beg < 0) npts_beg = 0; if( npts_end >= npts_phase) npts_end = npts_phase -1; misfit_diff = 0; for(count = npts_beg; count < npts_end; count++) { misfit_diff += fabs( my_record[ista].stretched_ES_win[count] / ES_amp - phase_win_from_long_orig[count] / record_amp); } d_npts = npts_end - npts_beg; if(d_npts == 0) d_npts =1; misfit = misfit_diff / d_npts; my_record[ista].misfit_bak2T = misfit; // get misfit_bak3T npts_beg = npts_ENDSET + 2*(npts_ENDSET - npts_ONSET); npts_end = npts_ENDSET + 3*(npts_ENDSET - npts_ONSET); if( npts_beg < 0) npts_beg = 0; if( npts_end >= npts_phase) npts_end = npts_phase -1; misfit_diff = 0; for(count = npts_beg; count < npts_end; count++) { misfit_diff += fabs( my_record[ista].stretched_ES_win[count] / ES_amp - phase_win_from_long_orig[count] / record_amp); } d_npts = npts_end - npts_beg; if(d_npts == 0) d_npts =1; misfit = misfit_diff / d_npts; my_record[ista].misfit_bak3T = misfit; //printf("sta is %s ONSET time is %lf phase beg is %lf npts_onset is %d * my_input->delta = %lf \n",my_record[ista].name, dt_ONSET, my_record[ista].phase_beg, npts_ONSET, npts_ONSET * my_input->delta); double extra_time = 3; npts_ONSET = npts_ONSET - (int)(extra_time / my_input->delta); if(npts_ONSET < 0) npts_ONSET = 0; // update the SNR using new ES window double phase_signal=0; double noise_signal=0; int i; for(i=npts_ONSET;i<npts_ENDSET;i++) { phase_signal += fabs(my_record[ista].phase_win[i]); } int value_noise_npts = 0; for(i=0;i<my_record[ista].npts_noise;i++) { if( my_record[ista].noise_win[i] == 0) continue; value_noise_npts ++; noise_signal += fabs(my_record[ista].noise_win[i]); } if(value_noise_npts < 100) my_record[ista].noise_too_short_flag = 1; //printf("noise signal is %lf phase signa; is %lf npts noise phase %d %d\n", noise_signal, phase_signal, my_record[ista].npts_noise,my_record[ista].npts_phase); if( noise_signal == 0 || npts_ONSET == npts_ENDSET) { puts("ERROR: noise_signal is 0 SNR problem!"); my_record[ista].quality = -1; continue; } else { double SNR_sig = phase_signal / (npts_ENDSET - npts_ONSET); //double SNR_noi = noise_signal / (my_record[ista].noise_len/my_input->delta); double SNR_noi = noise_signal / value_noise_npts; double SNR = SNR_sig/SNR_noi; my_record[ista].SNR_sig = SNR_sig; my_record[ista].SNR_noi = SNR_noi; my_record[ista].SNR = SNR; } // =========================================================== // get misfit measurement misfit2 // =========================================================== //printf("==> get misfit2 \n"); misfit_diff = 0; misfit_ES = 0; for(count = npts_ONSET; count < npts_ENDSET; count++) { misfit_diff += fabs(my_record[ista].stretched_ES_win[count]/ ES_amp - phase_win_from_long_orig[count] / record_amp ); } //##my_record[ista].misfit2 = misfit; d_npts = (npts_ENDSET - npts_ONSET); if(d_npts == 0) d_npts =1; misfit = misfit_diff / d_npts; my_record[ista].misfit2 = misfit; // =========================================================== // get new CCC for misfit2 window // =========================================================== //1. get records window int new_npts = npts_ENDSET - npts_ONSET ; double record_y[new_npts]; double EW_y[new_npts]; //record_y = (double*)malloc(sizeof(double)*new_npts); //EW_y = (double*)malloc(sizeof(double)*new_npts); int iii = 0; for(count = npts_ONSET; count < npts_ENDSET; count++) { record_y[iii] = my_record[ista].phase_win[count]; EW_y[iii] = my_record[ista].stretched_ES_win[count]; iii++; } int ccc_flag = 1; int npts_shift = 0; double new_ccc; CCC(record_y,new_npts,EW_y, new_npts, &npts_shift, &new_ccc, ccc_flag); my_record[ista].CCC3 = new_ccc; // =========================================================== // get SNR3 which is the peak to trough SNR // =========================================================== //int get_SNR3_and_4_for_record(double* phase_win,int phase_npts, double* noise_win,int noise_npts, double* SNR3, double* SNR4) if( my_input->Reprocessing_Flag == 1 ) { double SNR3 = 0; double SNR4 = 0; int npts_noise = (int)(my_input->noise_len / my_input->delta); get_SNR3_and_4_for_record(my_record[ista].phase_win, npts_phase, my_record[ista].noise_win, npts_noise, &SNR3, &SNR4, my_input); my_record[ista].SNR3 = SNR3; my_record[ista].SNR4 = SNR4; } } return 0; }
C
#include <stdio.h> #include <unistd.h> #include <signal.h> #include <string.h> /* signal() */ void (*exit_func)(int); void sig_handler01(int signum) { printf("signal() : %d\n", signum); signal(SIGINT, exit_func); // or signal(SIGINT, SIG_DFL); } /* sigaction */ // volatile 키워드 : 읽기/쓰기를 위해 메모리 액세스 필요. static volatile int g_exit_flag = 0; static void sig_handler02(int signum) { printf("signal() : %d\n", signum); g_exit_flag = 1; } void sig_int(int signo) { printf("SIGNAL : SIGINT\n"); g_exit_flag++; if(g_exit_flag == 1) signal(SIGINT, SIG_DFL); } int main() { // 1. signal() 사용 // SIGINT 시그널에 대해 지정된 함수(exit_func)를 호출하도록 합니다. //exit_func = signal(SIGINT, sig_handler01); // 2. sigaction 사용 /* struct sigaction sig_act; memset(&sig_act, '\0', sizeof(struct sigaction)); // sizeof() 사용시, type을 지정 sig_act.sa_handler = &sig_handler02; if(sigaction(SIGINT, &sig_act, NULL) < 0) { perror("sigaction"); return 1; } struct sigaction intsig; printf("PID : %d\n", getpid()); // pid 값 출력 intsig.sa_handler = sig_int; // 시그널 핸들러 등록 sigemptyset(&intsig.sa_mask); // 시그널 마스크 초기화 intsig.sa_flags = 0; if(sigaction(SIGINT, &intsig, 0) == -1) { perror("sigaction"); return -1; } while(1) { // 프로그램이 바로 종료되지 않게 합니다. // 2. sigaction // siganl 발생 시, g_exit_flag 값이 변경되면 if(g_exit_flag >= 5) { printf("Change flag!!!\n"); break; } } */ printf("PID : %d\n", getpid()); // pid 값 출력 struct sigaction intsig; intsig.sa_handler = sig_int; // 시그널 핸들러 등록 sigemptyset(&intsig.sa_mask); // 시그널 마스크 초기화 sigfillset(&intsig.sa_mask); // 모든 시그널 등록 sigdelset(&intsig.sa_mask, SIGINT); // SIGINT 시그널 제외 intsig.sa_flags = 0; if(sigprocmask(SIG_BLOCK, &intsig.sa_mask, 0) < 0) { perror("sigmask"); return -1; } if(sigaction(SIGINT, &intsig, 0) < 0) { perror("sigaction"); return -1; } while(1) { } return 0; }
C
#include <stdio.h> int main(int argc, char *argv) { int a = 0; int b = 0; //右移后,最低8可以放的下,否则会出错, //换句话说, 必须是连续在一起的8bit数据才是有效的 __asm__ __volatile__( "mov r0, #0x1100 \n" "mov %0, r0 \n" :"=r"(a) : :"r0","r1" ); printf("%#x\n", a); return 0; }
C
/* C89 compatible atomics. Choice of public domain or MIT-0. See license statements at the end of this file. David Reid - [email protected] */ /* Introduction ============ This library aims to implement an equivalent to the C11 atomics library. It's intended to be used as a way to enable the use of atomics in a mostly consistent manner to modern C, while still enabling compatibility with older compilers. This is *not* a drop-in replacement for C11 atomics, but is very similar. Only limited testing has been done so use at your own risk. I'm happy to accept feedback and pull requests with bug fixes. When compiling with GCC and Clang, this library will translate to a one-to-one wrapper around the __atomic_* intrinsics provided by the compiler. When compiling with Visual C++ things are a bit more complicated because it does not have support for C11 style atomic intrinsics. This library will try to use the _Interlocked* intrinsics instead, and if unavailable will use inlined assembly (x86 only). Supported compilers are Visual Studio back to VC6, GCC and Clang. If you need support for a different compiler I'm happy to add support (pull requests appreciated). This library currently assumes the `int` data type is 32 bits. Differences With C11 -------------------- For practicality, this is not a drop-in replacement for C11's `stdatomic.h`. Below are the main differences between c89atomic and stdatomic. * All operations require an explicit size which is specified by the name of the function, and only 8-, 16-, 32- and 64-bit operations are supported. Objects of an arbitrary sizes are not supported. * Some extra APIs are included: - `c89atomic_compare_and_swap_*()` - `c89atomic_test_and_set_*()` - `c89atomic_clear_*()` * All APIs are namespaced with `c89`. * `c89atomic_*` data types are undecorated. Compare Exchange ---------------- This library implements a simple compare-and-swap function called `c89atomic_compare_and_swap_*()` which is slightly different to C11's `atomic_compare_exchange_*()`. This is named differently to distinguish between the two. `c89atomic_compare_and_swap_*()` returns the old value as the return value, whereas `atomic_compare_exchange_*()` will return it through a parameter and supports explicit memory orders for success and failure cases. With Visual Studio and versions of GCC earlier than 4.7, an implementation of `atomic_compare_exchange_*()` is included which is implemented in terms of `c89atomic_compare_and_swap_*()`, but there's subtle details to be aware of with this implementation. Note that the following only applies for Visual Studio and versions of GCC earlier than 4.7. Later versions of GCC and Clang use the `__atomic_compare_exchange_n()` intrinsic directly and are not subject to the following. Below is the 32-bit implementation of `c89atomic_compare_exchange_strong_explicit_32()` which is implemented the same for the weak versions and other sizes, and only for Visual Studio and old versions of GCC (prior to 4.7): ```c c89atomic_bool c89atomic_compare_exchange_strong_explicit_32(volatile c89atomic_uint32* dst, volatile c89atomic_uint32* expected, c89atomic_uint32 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder) { c89atomic_uint32 expectedValue; c89atomic_uint32 result; expectedValue = c89atomic_load_explicit_32(expected, c89atomic_memory_order_seq_cst); result = c89atomic_compare_and_swap_32(dst, expectedValue, desired); if (result == expectedValue) { return 1; } else { c89atomic_store_explicit_32(expected, result, failureOrder); return 0; } } ``` The call to `c89atomic_store_explicit_32()` is not atomic with respect to the main compare-and-swap operation which may cause problems when `expected` points to memory that is shared between threads. This only becomes an issue if `expected` can be accessed from multiple threads at the same time which for the most part will never happen because a compare-and-swap will almost always be used in a loop with a local variable being used for the expected value. If the above is a concern, you should consider reworking your code to use `c89atomic_compare_and_swap_*()` directly, which is atomic and more efficient. Alternatively you'll need to use a lock to synchronize access to `expected`, upgrade your compiler, or use a different library. Types and Functions ------------------- The following types and functions are implemented: +-----------------------------------------+-----------------------------------------------+ | C11 Atomics | C89 Atomics | +-----------------------------------------+-----------------------------------------------+ | #include <stdatomic.h> | #include "c89atomic.h" | +-----------------------------------------+-----------------------------------------------+ | memory_order | c89atomic_memory_order | | memory_order_relaxed | c89atomic_memory_order_relaxed | | memory_order_consume | c89atomic_memory_order_consume | | memory_order_acquire | c89atomic_memory_order_acquire | | memory_order_release | c89atomic_memory_order_release | | memory_order_acq_rel | c89atomic_memory_order_acq_rel | | memory_order_seq_cst | c89atomic_memory_order_seq_cst | +-----------------------------------------+-----------------------------------------------+ | atomic_flag | c89atomic_flag | | atomic_bool | c89atomic_bool | | atomic_int8 | c89atomic_int8 | | atomic_uint8 | c89atomic_uint8 | | atomic_int16 | c89atomic_int16 | | atomic_uint16 | c89atomic_uint16 | | atomic_int32 | c89atomic_int32 | | atomic_uint32 | c89atomic_uint32 | | atomic_int64 | c89atomic_int64 | | atomic_uint64 | c89atomic_uint64 | +-----------------------------------------+-----------------------------------------------+ | atomic_flag_test_and_set | c89atomic_flag_test_and_set | | atomic_flag_test_and_set_explicit | c89atomic_flag_test_and_set_explicit | | | c89atomic_test_and_set_8 | | | c89atomic_test_and_set_16 | | | c89atomic_test_and_set_32 | | | c89atomic_test_and_set_64 | | | c89atomic_test_and_set_explicit_8 | | | c89atomic_test_and_set_explicit_16 | | | c89atomic_test_and_set_explicit_32 | | | c89atomic_test_and_set_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_flag_clear | c89atomic_flag_clear | | atomic_flag_clear_explicit | c89atomic_flag_clear_explicit | | | c89atomic_clear_8 | | | c89atomic_clear_16 | | | c89atomic_clear_32 | | | c89atomic_clear_64 | | | c89atomic_clear_explicit_8 | | | c89atomic_clear_explicit_16 | | | c89atomic_clear_explicit_32 | | | c89atomic_clear_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_store | c89atomic_store_8 | | atomic_store_explicit | c89atomic_store_16 | | | c89atomic_store_32 | | | c89atomic_store_64 | | | c89atomic_store_explicit_8 | | | c89atomic_store_explicit_16 | | | c89atomic_store_explicit_32 | | | c89atomic_store_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_load | c89atomic_load_8 | | atomic_load_explicit | c89atomic_load_16 | | | c89atomic_load_32 | | | c89atomic_load_64 | | | c89atomic_load_explicit_8 | | | c89atomic_load_explicit_16 | | | c89atomic_load_explicit_32 | | | c89atomic_load_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_exchange | c89atomic_exchange_8 | | atomic_exchange_explicit | c89atomic_exchange_16 | | | c89atomic_exchange_32 | | | c89atomic_exchange_64 | | | c89atomic_exchange_explicit_8 | | | c89atomic_exchange_explicit_16 | | | c89atomic_exchange_explicit_32 | | | c89atomic_exchange_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_compare_exchange_weak | c89atomic_compare_exchange_weak_8 | | atomic_compare_exchange_weak_explicit | c89atomic_compare_exchange_weak_16 | | atomic_compare_exchange_strong | c89atomic_compare_exchange_weak_32 | | atomic_compare_exchange_strong_explicit | c89atomic_compare_exchange_weak_64 | | | c89atomic_compare_exchange_weak_explicit_8 | | | c89atomic_compare_exchange_weak_explicit_16 | | | c89atomic_compare_exchange_weak_explicit_32 | | | c89atomic_compare_exchange_weak_explicit_64 | | | c89atomic_compare_exchange_strong_8 | | | c89atomic_compare_exchange_strong_16 | | | c89atomic_compare_exchange_strong_32 | | | c89atomic_compare_exchange_strong_64 | | | c89atomic_compare_exchange_strong_explicit_8 | | | c89atomic_compare_exchange_strong_explicit_16 | | | c89atomic_compare_exchange_strong_explicit_32 | | | c89atomic_compare_exchange_strong_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_fetch_add | c89atomic_fetch_add_8 | | atomic_fetch_add_explicit | c89atomic_fetch_add_16 | | | c89atomic_fetch_add_32 | | | c89atomic_fetch_add_64 | | | c89atomic_fetch_add_explicit_8 | | | c89atomic_fetch_add_explicit_16 | | | c89atomic_fetch_add_explicit_32 | | | c89atomic_fetch_add_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_fetch_sub | c89atomic_fetch_sub_8 | | atomic_fetch_sub_explicit | c89atomic_fetch_sub_16 | | | c89atomic_fetch_sub_32 | | | c89atomic_fetch_sub_64 | | | c89atomic_fetch_sub_explicit_8 | | | c89atomic_fetch_sub_explicit_16 | | | c89atomic_fetch_sub_explicit_32 | | | c89atomic_fetch_sub_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_fetch_or | c89atomic_fetch_or_8 | | atomic_fetch_or_explicit | c89atomic_fetch_or_16 | | | c89atomic_fetch_or_32 | | | c89atomic_fetch_or_64 | | | c89atomic_fetch_or_explicit_8 | | | c89atomic_fetch_or_explicit_16 | | | c89atomic_fetch_or_explicit_32 | | | c89atomic_fetch_or_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_fetch_xor | c89atomic_fetch_xor_8 | | atomic_fetch_xor_explicit | c89atomic_fetch_xor_16 | | | c89atomic_fetch_xor_32 | | | c89atomic_fetch_xor_64 | | | c89atomic_fetch_xor_explicit_8 | | | c89atomic_fetch_xor_explicit_16 | | | c89atomic_fetch_xor_explicit_32 | | | c89atomic_fetch_xor_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_fetch_and | c89atomic_fetch_and_8 | | atomic_fetch_and_explicit | c89atomic_fetch_and_16 | | | c89atomic_fetch_and_32 | | | c89atomic_fetch_and_64 | | | c89atomic_fetch_and_explicit_8 | | | c89atomic_fetch_and_explicit_16 | | | c89atomic_fetch_and_explicit_32 | | | c89atomic_fetch_and_explicit_64 | +-----------------------------------------+-----------------------------------------------+ | atomic_thread_fence() | c89atomic_thread_fence | | atomic_signal_fence() | c89atomic_signal_fence | +-----------------------------------------+-----------------------------------------------+ | atomic_is_lock_free | c89atomic_is_lock_free_8 | | | c89atomic_is_lock_free_16 | | | c89atomic_is_lock_free_32 | | | c89atomic_is_lock_free_64 | +-----------------------------------------+-----------------------------------------------+ | (Not Defined) | c89atomic_compare_and_swap_8 | | | c89atomic_compare_and_swap_16 | | | c89atomic_compare_and_swap_32 | | | c89atomic_compare_and_swap_64 | | | c89atomic_compare_and_swap_ptr | | | c89atomic_compiler_fence | +-----------------------------------------+-----------------------------------------------+ */ #ifndef c89atomic_h #define c89atomic_h #if defined(__cplusplus) extern "C" { #endif typedef signed char c89atomic_int8; typedef unsigned char c89atomic_uint8; typedef signed short c89atomic_int16; typedef unsigned short c89atomic_uint16; typedef signed int c89atomic_int32; typedef unsigned int c89atomic_uint32; #if defined(_MSC_VER) typedef signed __int64 c89atomic_int64; typedef unsigned __int64 c89atomic_uint64; #else #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wlong-long" #if defined(__clang__) #pragma GCC diagnostic ignored "-Wc++11-long-long" #endif #endif typedef signed long long c89atomic_int64; typedef unsigned long long c89atomic_uint64; #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) #pragma GCC diagnostic pop #endif #endif typedef int c89atomic_memory_order; typedef unsigned char c89atomic_bool; /* Architecture Detection */ #if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT) #ifdef _WIN32 #ifdef _WIN64 #define C89ATOMIC_64BIT #else #define C89ATOMIC_32BIT #endif #endif #endif #if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT) #ifdef __GNUC__ #ifdef __LP64__ #define C89ATOMIC_64BIT #else #define C89ATOMIC_32BIT #endif #endif #endif #if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT) #include <stdint.h> #if INTPTR_MAX == INT64_MAX #define C89ATOMIC_64BIT #else #define C89ATOMIC_32BIT #endif #endif #if defined(__x86_64__) || defined(_M_X64) #define C89ATOMIC_X64 #elif defined(__i386) || defined(_M_IX86) #define C89ATOMIC_X86 #elif defined(__arm__) || defined(_M_ARM) #define C89ATOMIC_ARM #endif /* We want to encourage the compiler to inline. When adding support for a new compiler, make sure it's handled here. */ #if defined(_MSC_VER) #define C89ATOMIC_INLINE __forceinline #elif defined(__GNUC__) /* I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue I am using "__inline__" only when we're compiling in strict ANSI mode. */ #if defined(__STRICT_ANSI__) #define C89ATOMIC_INLINE __inline__ __attribute__((always_inline)) #else #define C89ATOMIC_INLINE inline __attribute__((always_inline)) #endif #elif defined(__WATCOMC__) || defined(__DMC__) #define C89ATOMIC_INLINE __inline #else #define C89ATOMIC_INLINE #endif /* Assume everything supports all standard sized atomics by default. We'll #undef these when not supported. */ #define C89ATOMIC_HAS_8 #define C89ATOMIC_HAS_16 #define C89ATOMIC_HAS_32 #define C89ATOMIC_HAS_64 #if (defined(_MSC_VER) /*&& !defined(__clang__)*/) || defined(__WATCOMC__) || defined(__DMC__) /* Visual C++. */ #define c89atomic_memory_order_relaxed 0 #define c89atomic_memory_order_consume 1 #define c89atomic_memory_order_acquire 2 #define c89atomic_memory_order_release 3 #define c89atomic_memory_order_acq_rel 4 #define c89atomic_memory_order_seq_cst 5 /* Visual Studio 2003 (_MSC_VER 1300) and earlier have no support for sized atomic operations. We'll need to use inlined assembly for these compilers. I've also had a report that 8-bit and 16-bit interlocked intrinsics were only added in Visual Studio 2010 (_MSC_VER 1600). We'll need to disable these on the 64-bit build because there's no way to implement them with inlined assembly since Microsoft has decided to drop support for it from their 64-bit compilers. To simplify the implementation, any older MSVC compilers targeting 32-bit will use inlined assembly for everything. I'm not going to use inlined assembly wholesale for all 32-bit builds regardless of the age of the compiler because I don't trust the compiler will optimize the inlined assembly properly. The inlined assembly path supports both MSVC, Digital Mars and OpenWatcom. OpenWatcom is a little bit too pedantic with it's warnings. A few notes: - The return value of these functions are defined by the AL/AX/EAX/EAX:EDX registers which means an explicit return statement is not actually necessary. This is helpful for performance reasons because it means we can avoid the cost of a declaring a local variable and moving the value in EAX into that variable, only to then return it. However, unfortunately OpenWatcom thinks this is a mistake and tries to be helpful by throwing a warning. To work around we're going to declare a "result" variable and incur this theoretical cost. Most likely the compiler will optimize this away and make it a non-issue. - Variables that are assigned within the inline assembly will not be detected as such, and OpenWatcom will throw a warning about the variable being used without being assigned. To work around this we just initialize our local variables to 0. */ #if _MSC_VER < 1600 && defined(C89ATOMIC_32BIT) /* 1600 = Visual Studio 2010 */ #define C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY #endif #if _MSC_VER < 1600 #undef C89ATOMIC_HAS_8 #undef C89ATOMIC_HAS_16 #endif /* We need <intrin.h>, but only if we're not using inlined assembly. */ #if !defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY) #include <intrin.h> #endif /* atomic_compare_and_swap */ #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY) #if defined(C89ATOMIC_HAS_8) static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_compare_and_swap_8(volatile c89atomic_uint8* dst, c89atomic_uint8 expected, c89atomic_uint8 desired) { c89atomic_uint8 result = 0; __asm { mov ecx, dst mov al, expected mov dl, desired lock cmpxchg [ecx], dl /* Writes to EAX which MSVC will treat as the return value. */ mov result, al } return result; } #endif #if defined(C89ATOMIC_HAS_16) static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_compare_and_swap_16(volatile c89atomic_uint16* dst, c89atomic_uint16 expected, c89atomic_uint16 desired) { c89atomic_uint16 result = 0; __asm { mov ecx, dst mov ax, expected mov dx, desired lock cmpxchg [ecx], dx /* Writes to EAX which MSVC will treat as the return value. */ mov result, ax } return result; } #endif #if defined(C89ATOMIC_HAS_32) static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_compare_and_swap_32(volatile c89atomic_uint32* dst, c89atomic_uint32 expected, c89atomic_uint32 desired) { c89atomic_uint32 result = 0; __asm { mov ecx, dst mov eax, expected mov edx, desired lock cmpxchg [ecx], edx /* Writes to EAX which MSVC will treat as the return value. */ mov result, eax } return result; } #endif #if defined(C89ATOMIC_HAS_64) static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_compare_and_swap_64(volatile c89atomic_uint64* dst, c89atomic_uint64 expected, c89atomic_uint64 desired) { c89atomic_uint32 resultEAX = 0; c89atomic_uint32 resultEDX = 0; __asm { mov esi, dst /* From Microsoft documentation: "... you don't need to preserve the EAX, EBX, ECX, EDX, ESI, or EDI registers." Choosing ESI since it's the next available one in their list. */ mov eax, dword ptr expected mov edx, dword ptr expected + 4 mov ebx, dword ptr desired mov ecx, dword ptr desired + 4 lock cmpxchg8b qword ptr [esi] /* Writes to EAX:EDX which MSVC will treat as the return value. */ mov resultEAX, eax mov resultEDX, edx } return ((c89atomic_uint64)resultEDX << 32) | resultEAX; } #endif #else #if defined(C89ATOMIC_HAS_8) #define c89atomic_compare_and_swap_8( dst, expected, desired) (c89atomic_uint8 )_InterlockedCompareExchange8((volatile char*)dst, (char)desired, (char)expected) #endif #if defined(C89ATOMIC_HAS_16) #define c89atomic_compare_and_swap_16(dst, expected, desired) (c89atomic_uint16)_InterlockedCompareExchange16((volatile short*)dst, (short)desired, (short)expected) #endif #if defined(C89ATOMIC_HAS_32) #define c89atomic_compare_and_swap_32(dst, expected, desired) (c89atomic_uint32)_InterlockedCompareExchange((volatile long*)dst, (long)desired, (long)expected) #endif #if defined(C89ATOMIC_HAS_64) #define c89atomic_compare_and_swap_64(dst, expected, desired) (c89atomic_uint64)_InterlockedCompareExchange64((volatile long long*)dst, (long long)desired, (long long)expected) #endif #endif /* atomic_exchange_explicit */ #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY) #if defined(C89ATOMIC_HAS_8) static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 result = 0; (void)order; __asm { mov ecx, dst mov al, src lock xchg [ecx], al mov result, al } return result; } #endif #if defined(C89ATOMIC_HAS_16) static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 result = 0; (void)order; __asm { mov ecx, dst mov ax, src lock xchg [ecx], ax mov result, ax } return result; } #endif #if defined(C89ATOMIC_HAS_32) static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 result = 0; (void)order; __asm { mov ecx, dst mov eax, src lock xchg [ecx], eax mov result, eax } return result; } #endif #else #if defined(C89ATOMIC_HAS_8) static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return (c89atomic_uint8)_InterlockedExchange8((volatile char*)dst, (char)src); } #endif #if defined(C89ATOMIC_HAS_16) static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return (c89atomic_uint16)_InterlockedExchange16((volatile short*)dst, (short)src); } #endif #if defined(C89ATOMIC_HAS_32) static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return (c89atomic_uint32)_InterlockedExchange((volatile long*)dst, (long)src); } #endif #if defined(C89ATOMIC_HAS_64) && defined(C89ATOMIC_64BIT) static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return (c89atomic_uint64)_InterlockedExchange64((volatile long long*)dst, (long long)src); } #else /* Implemented below. */ #endif #endif #if defined(C89ATOMIC_HAS_64) && !defined(C89ATOMIC_64BIT) /* atomic_exchange_explicit_64() must be implemented in terms of atomic_compare_and_swap() on 32-bit builds, no matter the version of Visual Studio. */ static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; do { oldValue = *dst; } while (c89atomic_compare_and_swap_64(dst, oldValue, src) != oldValue); (void)order; /* Always using the strongest memory order. */ return oldValue; } #endif /* atomic_fetch_add */ #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY) #if defined(C89ATOMIC_HAS_8) static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 result = 0; (void)order; __asm { mov ecx, dst mov al, src lock xadd [ecx], al mov result, al } return result; } #endif #if defined(C89ATOMIC_HAS_16) static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 result = 0; (void)order; __asm { mov ecx, dst mov ax, src lock xadd [ecx], ax mov result, ax } return result; } #endif #if defined(C89ATOMIC_HAS_32) static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 result = 0; (void)order; __asm { mov ecx, dst mov eax, src lock xadd [ecx], eax mov result, eax } return result; } #endif #else #if defined(C89ATOMIC_HAS_8) static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return (c89atomic_uint8)_InterlockedExchangeAdd8((volatile char*)dst, (char)src); } #endif #if defined(C89ATOMIC_HAS_16) static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return (c89atomic_uint16)_InterlockedExchangeAdd16((volatile short*)dst, (short)src); } #endif #if defined(C89ATOMIC_HAS_32) static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return (c89atomic_uint32)_InterlockedExchangeAdd((volatile long*)dst, (long)src); } #endif #if defined(C89ATOMIC_HAS_64) && defined(C89ATOMIC_64BIT) static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return (c89atomic_uint64)_InterlockedExchangeAdd64((volatile long long*)dst, (long long)src); } #else /* Implemented below. */ #endif #endif #if defined(C89ATOMIC_HAS_64) && !defined(C89ATOMIC_64BIT) /* 9atomic_fetch_add_explicit_64() must be implemented in terms of atomic_compare_and_swap() on 32-bit builds, no matter the version of Visual Studio. */ static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; c89atomic_uint64 newValue; do { oldValue = *dst; newValue = oldValue + src; } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif /* atomic_thread_fence */ #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY) static C89ATOMIC_INLINE void __stdcall c89atomic_thread_fence(c89atomic_memory_order order) { (void)order; __asm { lock add [esp], 0 } } #else /* Can't use MemoryBarrier() for this as it require Windows headers which we want to avoid in the header. */ #if defined(C89ATOMIC_X64) #define c89atomic_thread_fence(order) __faststorefence(), (void)order #else static C89ATOMIC_INLINE void c89atomic_thread_fence(c89atomic_memory_order order) { volatile c89atomic_uint32 barrier = 0; c89atomic_fetch_add_explicit_32(&barrier, 0, order); } #endif /* C89ATOMIC_X64 */ #endif /* I'm not sure how to implement a compiler barrier for old MSVC so I'm just making it a thread_fence() and hopefully the compiler will see the volatile and not do any reshuffling. If anybody has a better idea on this please let me know! Cannot use _ReadWriteBarrier() as it has been marked as deprecated. */ #define c89atomic_compiler_fence() c89atomic_thread_fence(c89atomic_memory_order_seq_cst) /* I'm not sure how to implement this for MSVC. For now just using thread_fence(). */ #define c89atomic_signal_fence(order) c89atomic_thread_fence(order) /* Atomic loads can be implemented in terms of a compare-and-swap. Need to implement as functions to silence warnings about `order` being unused. */ #if defined(C89ATOMIC_HAS_8) static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_load_explicit_8(volatile const c89atomic_uint8* ptr, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return c89atomic_compare_and_swap_8((c89atomic_uint8*)ptr, 0, 0); } #endif #if defined(C89ATOMIC_HAS_16) static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_load_explicit_16(volatile const c89atomic_uint16* ptr, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return c89atomic_compare_and_swap_16((c89atomic_uint16*)ptr, 0, 0); } #endif #if defined(C89ATOMIC_HAS_32) static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_load_explicit_32(volatile const c89atomic_uint32* ptr, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return c89atomic_compare_and_swap_32((c89atomic_uint32*)ptr, 0, 0); } #endif #if defined(C89ATOMIC_HAS_64) static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_load_explicit_64(volatile const c89atomic_uint64* ptr, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return c89atomic_compare_and_swap_64((c89atomic_uint64*)ptr, 0, 0); } #endif /* atomic_store() is the same as atomic_exchange() but returns void. */ #if defined(C89ATOMIC_HAS_8) #define c89atomic_store_explicit_8( dst, src, order) (void)c89atomic_exchange_explicit_8 (dst, src, order) #endif #if defined(C89ATOMIC_HAS_16) #define c89atomic_store_explicit_16(dst, src, order) (void)c89atomic_exchange_explicit_16(dst, src, order) #endif #if defined(C89ATOMIC_HAS_32) #define c89atomic_store_explicit_32(dst, src, order) (void)c89atomic_exchange_explicit_32(dst, src, order) #endif #if defined(C89ATOMIC_HAS_64) #define c89atomic_store_explicit_64(dst, src, order) (void)c89atomic_exchange_explicit_64(dst, src, order) #endif /* fetch_sub() */ #if defined(C89ATOMIC_HAS_8) static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 oldValue; c89atomic_uint8 newValue; do { oldValue = *dst; newValue = (c89atomic_uint8)(oldValue - src); } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_16) static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 oldValue; c89atomic_uint16 newValue; do { oldValue = *dst; newValue = (c89atomic_uint16)(oldValue - src); } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_32) static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 oldValue; c89atomic_uint32 newValue; do { oldValue = *dst; newValue = oldValue - src; } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_64) static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; c89atomic_uint64 newValue; do { oldValue = *dst; newValue = oldValue - src; } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif /* fetch_and() */ #if defined(C89ATOMIC_HAS_8) static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 oldValue; c89atomic_uint8 newValue; do { oldValue = *dst; newValue = (c89atomic_uint8)(oldValue & src); } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_16) static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 oldValue; c89atomic_uint16 newValue; do { oldValue = *dst; newValue = (c89atomic_uint16)(oldValue & src); } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_32) static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 oldValue; c89atomic_uint32 newValue; do { oldValue = *dst; newValue = oldValue & src; } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_64) static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; c89atomic_uint64 newValue; do { oldValue = *dst; newValue = oldValue & src; } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif /* fetch_xor() */ #if defined(C89ATOMIC_HAS_8) static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 oldValue; c89atomic_uint8 newValue; do { oldValue = *dst; newValue = (c89atomic_uint8)(oldValue ^ src); } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_16) static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 oldValue; c89atomic_uint16 newValue; do { oldValue = *dst; newValue = (c89atomic_uint16)(oldValue ^ src); } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_32) static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 oldValue; c89atomic_uint32 newValue; do { oldValue = *dst; newValue = oldValue ^ src; } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_64) static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; c89atomic_uint64 newValue; do { oldValue = *dst; newValue = oldValue ^ src; } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif /* fetch_or() */ #if defined(C89ATOMIC_HAS_8) static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 oldValue; c89atomic_uint8 newValue; do { oldValue = *dst; newValue = (c89atomic_uint8)(oldValue | src); } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_16) static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 oldValue; c89atomic_uint16 newValue; do { oldValue = *dst; newValue = (c89atomic_uint16)(oldValue | src); } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_32) static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 oldValue; c89atomic_uint32 newValue; do { oldValue = *dst; newValue = oldValue | src; } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #if defined(C89ATOMIC_HAS_64) static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; c89atomic_uint64 newValue; do { oldValue = *dst; newValue = oldValue | src; } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif /* test_and_set() */ #if defined(C89ATOMIC_HAS_8) #define c89atomic_test_and_set_explicit_8( dst, order) c89atomic_exchange_explicit_8 (dst, 1, order) #endif #if defined(C89ATOMIC_HAS_16) #define c89atomic_test_and_set_explicit_16(dst, order) c89atomic_exchange_explicit_16(dst, 1, order) #endif #if defined(C89ATOMIC_HAS_32) #define c89atomic_test_and_set_explicit_32(dst, order) c89atomic_exchange_explicit_32(dst, 1, order) #endif #if defined(C89ATOMIC_HAS_64) #define c89atomic_test_and_set_explicit_64(dst, order) c89atomic_exchange_explicit_64(dst, 1, order) #endif /* clear() */ #if defined(C89ATOMIC_HAS_8) #define c89atomic_clear_explicit_8( dst, order) c89atomic_store_explicit_8 (dst, 0, order) #endif #if defined(C89ATOMIC_HAS_16) #define c89atomic_clear_explicit_16(dst, order) c89atomic_store_explicit_16(dst, 0, order) #endif #if defined(C89ATOMIC_HAS_32) #define c89atomic_clear_explicit_32(dst, order) c89atomic_store_explicit_32(dst, 0, order) #endif #if defined(C89ATOMIC_HAS_64) #define c89atomic_clear_explicit_64(dst, order) c89atomic_store_explicit_64(dst, 0, order) #endif /* Prefer 8-bit flags, but fall back to 32-bit if we don't support 8-bit atomics (possible on 64-bit MSVC prior to Visual Studio 2010). */ #if defined(C89ATOMIC_HAS_8) typedef c89atomic_uint8 c89atomic_flag; #define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_bool)c89atomic_test_and_set_explicit_8(ptr, order) #define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_8(ptr, order) #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_8(ptr, order) #else typedef c89atomic_uint32 c89atomic_flag; #define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_bool)c89atomic_test_and_set_explicit_32(ptr, order) #define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_32(ptr, order) #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_32(ptr, order) #endif #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))) /* Modern GCC atomic built-ins. */ #define C89ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE #define C89ATOMIC_HAS_NATIVE_IS_LOCK_FREE #define c89atomic_memory_order_relaxed __ATOMIC_RELAXED #define c89atomic_memory_order_consume __ATOMIC_CONSUME #define c89atomic_memory_order_acquire __ATOMIC_ACQUIRE #define c89atomic_memory_order_release __ATOMIC_RELEASE #define c89atomic_memory_order_acq_rel __ATOMIC_ACQ_REL #define c89atomic_memory_order_seq_cst __ATOMIC_SEQ_CST #define c89atomic_compiler_fence() __asm__ __volatile__("":::"memory") #define c89atomic_thread_fence(order) __atomic_thread_fence(order) #define c89atomic_signal_fence(order) __atomic_signal_fence(order) #define c89atomic_is_lock_free_8(ptr) __atomic_is_lock_free(1, ptr) #define c89atomic_is_lock_free_16(ptr) __atomic_is_lock_free(2, ptr) #define c89atomic_is_lock_free_32(ptr) __atomic_is_lock_free(4, ptr) #define c89atomic_is_lock_free_64(ptr) __atomic_is_lock_free(8, ptr) #define c89atomic_test_and_set_explicit_8( dst, order) __atomic_exchange_n(dst, 1, order) #define c89atomic_test_and_set_explicit_16(dst, order) __atomic_exchange_n(dst, 1, order) #define c89atomic_test_and_set_explicit_32(dst, order) __atomic_exchange_n(dst, 1, order) #define c89atomic_test_and_set_explicit_64(dst, order) __atomic_exchange_n(dst, 1, order) #define c89atomic_clear_explicit_8( dst, order) __atomic_store_n(dst, 0, order) #define c89atomic_clear_explicit_16(dst, order) __atomic_store_n(dst, 0, order) #define c89atomic_clear_explicit_32(dst, order) __atomic_store_n(dst, 0, order) #define c89atomic_clear_explicit_64(dst, order) __atomic_store_n(dst, 0, order) #define c89atomic_store_explicit_8( dst, src, order) __atomic_store_n(dst, src, order) #define c89atomic_store_explicit_16(dst, src, order) __atomic_store_n(dst, src, order) #define c89atomic_store_explicit_32(dst, src, order) __atomic_store_n(dst, src, order) #define c89atomic_store_explicit_64(dst, src, order) __atomic_store_n(dst, src, order) #define c89atomic_load_explicit_8( dst, order) __atomic_load_n(dst, order) #define c89atomic_load_explicit_16(dst, order) __atomic_load_n(dst, order) #define c89atomic_load_explicit_32(dst, order) __atomic_load_n(dst, order) #define c89atomic_load_explicit_64(dst, order) __atomic_load_n(dst, order) #define c89atomic_exchange_explicit_8( dst, src, order) __atomic_exchange_n(dst, src, order) #define c89atomic_exchange_explicit_16(dst, src, order) __atomic_exchange_n(dst, src, order) #define c89atomic_exchange_explicit_32(dst, src, order) __atomic_exchange_n(dst, src, order) #define c89atomic_exchange_explicit_64(dst, src, order) __atomic_exchange_n(dst, src, order) #define c89atomic_compare_exchange_strong_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder) #define c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder) #define c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder) #define c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder) #define c89atomic_fetch_add_explicit_8( dst, src, order) __atomic_fetch_add(dst, src, order) #define c89atomic_fetch_add_explicit_16(dst, src, order) __atomic_fetch_add(dst, src, order) #define c89atomic_fetch_add_explicit_32(dst, src, order) __atomic_fetch_add(dst, src, order) #define c89atomic_fetch_add_explicit_64(dst, src, order) __atomic_fetch_add(dst, src, order) #define c89atomic_fetch_sub_explicit_8( dst, src, order) __atomic_fetch_sub(dst, src, order) #define c89atomic_fetch_sub_explicit_16(dst, src, order) __atomic_fetch_sub(dst, src, order) #define c89atomic_fetch_sub_explicit_32(dst, src, order) __atomic_fetch_sub(dst, src, order) #define c89atomic_fetch_sub_explicit_64(dst, src, order) __atomic_fetch_sub(dst, src, order) #define c89atomic_fetch_or_explicit_8( dst, src, order) __atomic_fetch_or(dst, src, order) #define c89atomic_fetch_or_explicit_16(dst, src, order) __atomic_fetch_or(dst, src, order) #define c89atomic_fetch_or_explicit_32(dst, src, order) __atomic_fetch_or(dst, src, order) #define c89atomic_fetch_or_explicit_64(dst, src, order) __atomic_fetch_or(dst, src, order) #define c89atomic_fetch_xor_explicit_8( dst, src, order) __atomic_fetch_xor(dst, src, order) #define c89atomic_fetch_xor_explicit_16(dst, src, order) __atomic_fetch_xor(dst, src, order) #define c89atomic_fetch_xor_explicit_32(dst, src, order) __atomic_fetch_xor(dst, src, order) #define c89atomic_fetch_xor_explicit_64(dst, src, order) __atomic_fetch_xor(dst, src, order) #define c89atomic_fetch_and_explicit_8( dst, src, order) __atomic_fetch_and(dst, src, order) #define c89atomic_fetch_and_explicit_16(dst, src, order) __atomic_fetch_and(dst, src, order) #define c89atomic_fetch_and_explicit_32(dst, src, order) __atomic_fetch_and(dst, src, order) #define c89atomic_fetch_and_explicit_64(dst, src, order) __atomic_fetch_and(dst, src, order) #define c89atomic_compare_and_swap_8 (dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) #define c89atomic_compare_and_swap_16(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) #define c89atomic_compare_and_swap_32(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) #define c89atomic_compare_and_swap_64(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) typedef c89atomic_uint8 c89atomic_flag; #define c89atomic_flag_test_and_set_explicit(dst, order) (c89atomic_bool)__atomic_test_and_set(dst, order) #define c89atomic_flag_clear_explicit(dst, order) __atomic_clear(dst, order) #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_8(ptr, order) #else /* GCC and compilers supporting GCC-style inlined assembly. */ #define c89atomic_memory_order_relaxed 1 #define c89atomic_memory_order_consume 2 #define c89atomic_memory_order_acquire 3 #define c89atomic_memory_order_release 4 #define c89atomic_memory_order_acq_rel 5 #define c89atomic_memory_order_seq_cst 6 #define c89atomic_compiler_fence() __asm__ __volatile__("":::"memory") #if defined(__GNUC__) /* Legacy GCC atomic built-ins. Everything is a full memory barrier. */ #define c89atomic_thread_fence(order) __sync_synchronize(), (void)order /* exchange() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { if (order > c89atomic_memory_order_acquire) { __sync_synchronize(); } return __sync_lock_test_and_set(dst, src); } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 oldValue; do { oldValue = *dst; } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 oldValue; do { oldValue = *dst; } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; do { oldValue = *dst; } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue); (void)order; return oldValue; } /* fetch_add() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_add(dst, src); } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_add(dst, src); } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_add(dst, src); } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_add(dst, src); } /* fetch_sub() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_sub(dst, src); } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_sub(dst, src); } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_sub(dst, src); } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_sub(dst, src); } /* fetch_or() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_or(dst, src); } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_or(dst, src); } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_or(dst, src); } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_or(dst, src); } /* fetch_xor() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_xor(dst, src); } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_xor(dst, src); } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_xor(dst, src); } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_xor(dst, src); } /* fetch_and() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_and(dst, src); } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_and(dst, src); } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_and(dst, src); } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { (void)order; return __sync_fetch_and_and(dst, src); } #define c89atomic_compare_and_swap_8( dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) #define c89atomic_compare_and_swap_16(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) #define c89atomic_compare_and_swap_32(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) #define c89atomic_compare_and_swap_64(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired) #else /* Non-GCC compilers supporting GCC-style inlined assembly. The inlined assembly below uses Gas syntax. */ /* It's actually kind of confusing as to the best way to implement a memory barrier on x86/64. From my quick research, it looks like there's a few options: - SFENCE/LFENCE/MFENCE - LOCK ADD - XCHG (with a memory operand, not two register operands) It looks like the SFENCE instruction was added in the Pentium III series, whereas the LFENCE and MFENCE instructions were added in the Pentium 4 series. It's not clear how this actually differs to a LOCK-prefixed instruction or an XCHG instruction with a memory operand. For simplicity and compatibility, I'm just using a LOCK-prefixed ADD instruction which adds 0 to the value pointed to by the ESP register. The use of the ESP register is that it should theoretically have a high likelyhood to be in cache. For now, just to keep things simple, this is always doing a full memory barrier which means the `order` parameter is ignored on x86/64. I want a thread fence to also act as a compiler fence, so therefore I'm forcing this to be inlined by implementing it as a define. */ #if defined(C89ATOMIC_X86) #define c89atomic_thread_fence(order) __asm__ __volatile__("lock; addl $0, (%%esp)" ::: "memory", "cc") #elif defined(C89ATOMIC_X64) #define c89atomic_thread_fence(order) __asm__ __volatile__("lock; addq $0, (%%rsp)" ::: "memory", "cc") #else #error Unsupported architecture. Please submit a feature request. #endif /* compare_and_swap() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_compare_and_swap_8(volatile c89atomic_uint8* dst, c89atomic_uint8 expected, c89atomic_uint8 desired) { c89atomic_uint8 result; #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64) __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc"); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_compare_and_swap_16(volatile c89atomic_uint16* dst, c89atomic_uint16 expected, c89atomic_uint16 desired) { c89atomic_uint16 result; #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64) __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc"); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_compare_and_swap_32(volatile c89atomic_uint32* dst, c89atomic_uint32 expected, c89atomic_uint32 desired) { c89atomic_uint32 result; #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64) __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc"); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_compare_and_swap_64(volatile c89atomic_uint64* dst, c89atomic_uint64 expected, c89atomic_uint64 desired) { volatile c89atomic_uint64 result; #if defined(C89ATOMIC_X86) /* We can't use the standard CMPXCHG here because x86 does not support it with 64-bit values. We need to instead use CMPXCHG8B which is a bit harder to use. The annoying part with this is the use of the -fPIC compiler switch which requires the EBX register never be modified. The problem is that CMPXCHG8B requires us to write our desired value to it. I'm resolving this by just pushing and popping the EBX register manually. */ c89atomic_uint32 resultEAX; c89atomic_uint32 resultEDX; __asm__ __volatile__("push %%ebx; xchg %5, %%ebx; lock; cmpxchg8b %0; pop %%ebx" : "+m"(*dst), "=a"(resultEAX), "=d"(resultEDX) : "a"(expected & 0xFFFFFFFF), "d"(expected >> 32), "r"(desired & 0xFFFFFFFF), "c"(desired >> 32) : "cc"); result = ((c89atomic_uint64)resultEDX << 32) | resultEAX; #elif defined(C89ATOMIC_X64) __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc"); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } /* exchange() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 result = 0; (void)order; #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64) __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src)); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 result = 0; (void)order; #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64) __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src)); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 result; (void)order; #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64) __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src)); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 result; (void)order; #if defined(C89ATOMIC_X86) do { result = *dst; } while (c89atomic_compare_and_swap_64(dst, result, src) != result); #elif defined(C89ATOMIC_X64) __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src)); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } /* fetch_add() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 result; (void)order; #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64) __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc"); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 result; (void)order; #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64) __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc"); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 result; (void)order; #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64) __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc"); #else #error Unsupported architecture. Please submit a feature request. #endif return result; } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { #if defined(C89ATOMIC_X86) c89atomic_uint64 oldValue; c89atomic_uint64 newValue; (void)order; do { oldValue = *dst; newValue = oldValue + src; } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); return oldValue; #elif defined(C89ATOMIC_X64) c89atomic_uint64 result; (void)order; __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc"); return result; #endif } /* fetch_sub() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 oldValue; c89atomic_uint8 newValue; do { oldValue = *dst; newValue = (c89atomic_uint8)(oldValue - src); } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 oldValue; c89atomic_uint16 newValue; do { oldValue = *dst; newValue = (c89atomic_uint16)(oldValue - src); } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 oldValue; c89atomic_uint32 newValue; do { oldValue = *dst; newValue = oldValue - src; } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; c89atomic_uint64 newValue; do { oldValue = *dst; newValue = oldValue - src; } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } /* fetch_and() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 oldValue; c89atomic_uint8 newValue; do { oldValue = *dst; newValue = (c89atomic_uint8)(oldValue & src); } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 oldValue; c89atomic_uint16 newValue; do { oldValue = *dst; newValue = (c89atomic_uint16)(oldValue & src); } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 oldValue; c89atomic_uint32 newValue; do { oldValue = *dst; newValue = oldValue & src; } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; c89atomic_uint64 newValue; do { oldValue = *dst; newValue = oldValue & src; } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } /* fetch_xor() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 oldValue; c89atomic_uint8 newValue; do { oldValue = *dst; newValue = (c89atomic_uint8)(oldValue ^ src); } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 oldValue; c89atomic_uint16 newValue; do { oldValue = *dst; newValue = (c89atomic_uint16)(oldValue ^ src); } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 oldValue; c89atomic_uint32 newValue; do { oldValue = *dst; newValue = oldValue ^ src; } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; c89atomic_uint64 newValue; do { oldValue = *dst; newValue = oldValue ^ src; } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } /* fetch_or() */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order) { c89atomic_uint8 oldValue; c89atomic_uint8 newValue; do { oldValue = *dst; newValue = (c89atomic_uint8)(oldValue | src); } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order) { c89atomic_uint16 oldValue; c89atomic_uint16 newValue; do { oldValue = *dst; newValue = (c89atomic_uint16)(oldValue | src); } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order) { c89atomic_uint32 oldValue; c89atomic_uint32 newValue; do { oldValue = *dst; newValue = oldValue | src; } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order) { c89atomic_uint64 oldValue; c89atomic_uint64 newValue; do { oldValue = *dst; newValue = oldValue | src; } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue); (void)order; return oldValue; } #endif #define c89atomic_signal_fence(order) c89atomic_thread_fence(order) /* Atomic loads can be implemented in terms of a compare-and-swap. Need to implement as functions to silence warnings about `order` being unused. */ static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_load_explicit_8(volatile const c89atomic_uint8* ptr, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return c89atomic_compare_and_swap_8((c89atomic_uint8*)ptr, 0, 0); } static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_load_explicit_16(volatile const c89atomic_uint16* ptr, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return c89atomic_compare_and_swap_16((c89atomic_uint16*)ptr, 0, 0); } static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_load_explicit_32(volatile const c89atomic_uint32* ptr, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return c89atomic_compare_and_swap_32((c89atomic_uint32*)ptr, 0, 0); } static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_load_explicit_64(volatile const c89atomic_uint64* ptr, c89atomic_memory_order order) { (void)order; /* Always using the strongest memory order. */ return c89atomic_compare_and_swap_64((c89atomic_uint64*)ptr, 0, 0); } #define c89atomic_store_explicit_8( dst, src, order) (void)c89atomic_exchange_explicit_8 (dst, src, order) #define c89atomic_store_explicit_16(dst, src, order) (void)c89atomic_exchange_explicit_16(dst, src, order) #define c89atomic_store_explicit_32(dst, src, order) (void)c89atomic_exchange_explicit_32(dst, src, order) #define c89atomic_store_explicit_64(dst, src, order) (void)c89atomic_exchange_explicit_64(dst, src, order) #define c89atomic_test_and_set_explicit_8( dst, order) c89atomic_exchange_explicit_8 (dst, 1, order) #define c89atomic_test_and_set_explicit_16(dst, order) c89atomic_exchange_explicit_16(dst, 1, order) #define c89atomic_test_and_set_explicit_32(dst, order) c89atomic_exchange_explicit_32(dst, 1, order) #define c89atomic_test_and_set_explicit_64(dst, order) c89atomic_exchange_explicit_64(dst, 1, order) #define c89atomic_clear_explicit_8( dst, order) c89atomic_store_explicit_8 (dst, 0, order) #define c89atomic_clear_explicit_16(dst, order) c89atomic_store_explicit_16(dst, 0, order) #define c89atomic_clear_explicit_32(dst, order) c89atomic_store_explicit_32(dst, 0, order) #define c89atomic_clear_explicit_64(dst, order) c89atomic_store_explicit_64(dst, 0, order) typedef c89atomic_uint8 c89atomic_flag; #define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_bool)c89atomic_test_and_set_explicit_8(ptr, order) #define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_8(ptr, order) #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_8(ptr, order) #endif /* compare_exchange() */ #if !defined(C89ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE) #if defined(C89ATOMIC_HAS_8) C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8* expected, c89atomic_uint8 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder) { c89atomic_uint8 expectedValue; c89atomic_uint8 result; (void)successOrder; (void)failureOrder; expectedValue = c89atomic_load_explicit_8(expected, c89atomic_memory_order_seq_cst); result = c89atomic_compare_and_swap_8(dst, expectedValue, desired); if (result == expectedValue) { return 1; } else { c89atomic_store_explicit_8(expected, result, failureOrder); return 0; } } #endif #if defined(C89ATOMIC_HAS_16) C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16* expected, c89atomic_uint16 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder) { c89atomic_uint16 expectedValue; c89atomic_uint16 result; (void)successOrder; (void)failureOrder; expectedValue = c89atomic_load_explicit_16(expected, c89atomic_memory_order_seq_cst); result = c89atomic_compare_and_swap_16(dst, expectedValue, desired); if (result == expectedValue) { return 1; } else { c89atomic_store_explicit_16(expected, result, failureOrder); return 0; } } #endif #if defined(C89ATOMIC_HAS_32) C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32* expected, c89atomic_uint32 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder) { c89atomic_uint32 expectedValue; c89atomic_uint32 result; (void)successOrder; (void)failureOrder; expectedValue = c89atomic_load_explicit_32(expected, c89atomic_memory_order_seq_cst); result = c89atomic_compare_and_swap_32(dst, expectedValue, desired); if (result == expectedValue) { return 1; } else { c89atomic_store_explicit_32(expected, result, failureOrder); return 0; } } #endif #if defined(C89ATOMIC_HAS_64) C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_64(volatile c89atomic_uint64* dst, volatile c89atomic_uint64* expected, c89atomic_uint64 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder) { c89atomic_uint64 expectedValue; c89atomic_uint64 result; (void)successOrder; (void)failureOrder; expectedValue = c89atomic_load_explicit_64(expected, c89atomic_memory_order_seq_cst); result = c89atomic_compare_and_swap_64(dst, expectedValue, desired); if (result == expectedValue) { return 1; } else { c89atomic_store_explicit_64(expected, result, failureOrder); return 0; } } #endif #define c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_8 (dst, expected, desired, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder) #endif /* C89ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE */ #if !defined(C89ATOMIC_HAS_NATIVE_IS_LOCK_FREE) static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_8(volatile void* ptr) { (void)ptr; return 1; } static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_16(volatile void* ptr) { (void)ptr; return 1; } static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_32(volatile void* ptr) { (void)ptr; return 1; } static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_64(volatile void* ptr) { (void)ptr; /* For 64-bit atomics, we can only safely say atomics are lock free on 64-bit architectures or x86. Otherwise we need to be conservative and assume not lock free. */ #if defined(C89ATOMIC_64BIT) return 1; #else #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64) return 1; #else return 0; #endif #endif } #endif /* C89ATOMIC_HAS_NATIVE_IS_LOCK_FREE */ /* Pointer versions of relevant operations. Note that some functions cannot be implemented as #defines because for some reason, some compilers complain with a warning if you don't use the return value. I'm not fully sure why this happens, but to work around this, those particular functions are just implemented as inlined functions. */ #if defined(C89ATOMIC_64BIT) static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_ptr(volatile void** ptr) { return c89atomic_is_lock_free_64((volatile c89atomic_uint64*)ptr); } static C89ATOMIC_INLINE void* c89atomic_load_explicit_ptr(volatile void** ptr, c89atomic_memory_order order) { return (void*)c89atomic_load_explicit_64((volatile c89atomic_uint64*)ptr, order); } static C89ATOMIC_INLINE void c89atomic_store_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order) { c89atomic_store_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)src, order); } static C89ATOMIC_INLINE void* c89atomic_exchange_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order) { return (void*)c89atomic_exchange_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)src, order); } static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, volatile void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder) { return c89atomic_compare_exchange_strong_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder); } static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, volatile void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder) { return c89atomic_compare_exchange_weak_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder); } static C89ATOMIC_INLINE void* c89atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired) { return (void*)c89atomic_compare_and_swap_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)expected, (c89atomic_uint64)desired); } #elif defined(C89ATOMIC_32BIT) static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_ptr(volatile void** ptr) { return c89atomic_is_lock_free_32((volatile c89atomic_uint32*)ptr); } static C89ATOMIC_INLINE void* c89atomic_load_explicit_ptr(volatile void** ptr, c89atomic_memory_order order) { return (void*)c89atomic_load_explicit_32((volatile c89atomic_uint32*)ptr, order); } static C89ATOMIC_INLINE void c89atomic_store_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order) { c89atomic_store_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)src, order); } static C89ATOMIC_INLINE void* c89atomic_exchange_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order) { return (void*)c89atomic_exchange_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)src, order); } static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder) { return c89atomic_compare_exchange_strong_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder); } static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, volatile void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder) { return c89atomic_compare_exchange_weak_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder); } static C89ATOMIC_INLINE void* c89atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired) { return (void*)c89atomic_compare_and_swap_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)expected, (c89atomic_uint32)desired); } #else #error Unsupported architecture. #endif /* Implicit Flags. */ #define c89atomic_flag_test_and_set(ptr) c89atomic_flag_test_and_set_explicit(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_flag_clear(ptr) c89atomic_flag_clear_explicit(ptr, c89atomic_memory_order_seq_cst) /* Implicit Pointer. */ #define c89atomic_store_ptr(dst, src) c89atomic_store_explicit_ptr((volatile void**)dst, (void*)src, c89atomic_memory_order_seq_cst) #define c89atomic_load_ptr(ptr) c89atomic_load_explicit_ptr((volatile void**)ptr, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_ptr(dst, src) c89atomic_exchange_explicit_ptr((volatile void**)dst, (void*)src, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_strong_ptr(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_ptr((volatile void**)dst, (volatile void**)expected, (void*)desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_weak_ptr(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_ptr((volatile void**)dst, (volatile void**)expected, (void*)desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) /* Implicit Unsigned Integer. */ #define c89atomic_test_and_set_8( ptr) c89atomic_test_and_set_explicit_8( ptr, c89atomic_memory_order_seq_cst) #define c89atomic_test_and_set_16(ptr) c89atomic_test_and_set_explicit_16(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_test_and_set_32(ptr) c89atomic_test_and_set_explicit_32(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_test_and_set_64(ptr) c89atomic_test_and_set_explicit_64(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_clear_8( ptr) c89atomic_clear_explicit_8( ptr, c89atomic_memory_order_seq_cst) #define c89atomic_clear_16(ptr) c89atomic_clear_explicit_16(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_clear_32(ptr) c89atomic_clear_explicit_32(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_clear_64(ptr) c89atomic_clear_explicit_64(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_store_8( dst, src) c89atomic_store_explicit_8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_store_16(dst, src) c89atomic_store_explicit_16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_store_32(dst, src) c89atomic_store_explicit_32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_store_64(dst, src) c89atomic_store_explicit_64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_load_8( ptr) c89atomic_load_explicit_8( ptr, c89atomic_memory_order_seq_cst) #define c89atomic_load_16(ptr) c89atomic_load_explicit_16(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_load_32(ptr) c89atomic_load_explicit_32(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_load_64(ptr) c89atomic_load_explicit_64(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_8( dst, src) c89atomic_exchange_explicit_8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_16(dst, src) c89atomic_exchange_explicit_16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_32(dst, src) c89atomic_exchange_explicit_32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_64(dst, src) c89atomic_exchange_explicit_64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_strong_8( dst, expected, desired) c89atomic_compare_exchange_strong_explicit_8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_strong_16(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_strong_32(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_strong_64(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_weak_8( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_weak_16( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_weak_32( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_weak_64( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_add_8( dst, src) c89atomic_fetch_add_explicit_8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_add_16(dst, src) c89atomic_fetch_add_explicit_16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_add_32(dst, src) c89atomic_fetch_add_explicit_32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_add_64(dst, src) c89atomic_fetch_add_explicit_64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_sub_8( dst, src) c89atomic_fetch_sub_explicit_8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_sub_16(dst, src) c89atomic_fetch_sub_explicit_16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_sub_32(dst, src) c89atomic_fetch_sub_explicit_32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_sub_64(dst, src) c89atomic_fetch_sub_explicit_64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_or_8( dst, src) c89atomic_fetch_or_explicit_8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_or_16(dst, src) c89atomic_fetch_or_explicit_16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_or_32(dst, src) c89atomic_fetch_or_explicit_32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_or_64(dst, src) c89atomic_fetch_or_explicit_64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_xor_8( dst, src) c89atomic_fetch_xor_explicit_8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_xor_16(dst, src) c89atomic_fetch_xor_explicit_16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_xor_32(dst, src) c89atomic_fetch_xor_explicit_32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_xor_64(dst, src) c89atomic_fetch_xor_explicit_64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_and_8( dst, src) c89atomic_fetch_and_explicit_8 (dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_and_16(dst, src) c89atomic_fetch_and_explicit_16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_and_32(dst, src) c89atomic_fetch_and_explicit_32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_and_64(dst, src) c89atomic_fetch_and_explicit_64(dst, src, c89atomic_memory_order_seq_cst) /* Explicit Signed Integer. */ #define c89atomic_test_and_set_explicit_i8( ptr, order) (c89atomic_int8 )c89atomic_test_and_set_explicit_8( (c89atomic_uint8* )ptr, order) #define c89atomic_test_and_set_explicit_i16(ptr, order) (c89atomic_int16)c89atomic_test_and_set_explicit_16((c89atomic_uint16*)ptr, order) #define c89atomic_test_and_set_explicit_i32(ptr, order) (c89atomic_int32)c89atomic_test_and_set_explicit_32((c89atomic_uint32*)ptr, order) #define c89atomic_test_and_set_explicit_i64(ptr, order) (c89atomic_int64)c89atomic_test_and_set_explicit_64((c89atomic_uint64*)ptr, order) #define c89atomic_clear_explicit_i8( ptr, order) c89atomic_clear_explicit_8( (c89atomic_uint8* )ptr, order) #define c89atomic_clear_explicit_i16(ptr, order) c89atomic_clear_explicit_16((c89atomic_uint16*)ptr, order) #define c89atomic_clear_explicit_i32(ptr, order) c89atomic_clear_explicit_32((c89atomic_uint32*)ptr, order) #define c89atomic_clear_explicit_i64(ptr, order) c89atomic_clear_explicit_64((c89atomic_uint64*)ptr, order) #define c89atomic_store_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_store_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order) #define c89atomic_store_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_store_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order) #define c89atomic_store_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_store_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order) #define c89atomic_store_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_store_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order) #define c89atomic_load_explicit_i8( ptr, order) (c89atomic_int8 )c89atomic_load_explicit_8( (c89atomic_uint8* )ptr, order) #define c89atomic_load_explicit_i16(ptr, order) (c89atomic_int16)c89atomic_load_explicit_16((c89atomic_uint16*)ptr, order) #define c89atomic_load_explicit_i32(ptr, order) (c89atomic_int32)c89atomic_load_explicit_32((c89atomic_uint32*)ptr, order) #define c89atomic_load_explicit_i64(ptr, order) (c89atomic_int64)c89atomic_load_explicit_64((c89atomic_uint64*)ptr, order) #define c89atomic_exchange_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_exchange_explicit_8 ((c89atomic_uint8* )dst, (c89atomic_uint8 )src, order) #define c89atomic_exchange_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_exchange_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order) #define c89atomic_exchange_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_exchange_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order) #define c89atomic_exchange_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_exchange_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order) #define c89atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8* )expected, (c89atomic_uint8 )desired, successOrder, failureOrder) #define c89atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16*)expected, (c89atomic_uint16)desired, successOrder, failureOrder) #define c89atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder) #define c89atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8* )expected, (c89atomic_uint8 )desired, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16*)expected, (c89atomic_uint16)desired, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder) #define c89atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder) #define c89atomic_fetch_add_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_add_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order) #define c89atomic_fetch_add_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_add_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order) #define c89atomic_fetch_add_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_add_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order) #define c89atomic_fetch_add_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_add_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order) #define c89atomic_fetch_sub_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_sub_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order) #define c89atomic_fetch_sub_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_sub_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order) #define c89atomic_fetch_sub_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_sub_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order) #define c89atomic_fetch_sub_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_sub_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order) #define c89atomic_fetch_or_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_or_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order) #define c89atomic_fetch_or_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_or_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order) #define c89atomic_fetch_or_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_or_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order) #define c89atomic_fetch_or_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_or_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order) #define c89atomic_fetch_xor_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_xor_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order) #define c89atomic_fetch_xor_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_xor_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order) #define c89atomic_fetch_xor_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_xor_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order) #define c89atomic_fetch_xor_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_xor_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order) #define c89atomic_fetch_and_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_and_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order) #define c89atomic_fetch_and_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_and_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order) #define c89atomic_fetch_and_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_and_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order) #define c89atomic_fetch_and_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_and_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order) /* Implicit Signed Integer. */ #define c89atomic_test_and_set_i8( ptr) c89atomic_test_and_set_explicit_i8( ptr, c89atomic_memory_order_seq_cst) #define c89atomic_test_and_set_i16(ptr) c89atomic_test_and_set_explicit_i16(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_test_and_set_i32(ptr) c89atomic_test_and_set_explicit_i32(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_test_and_set_i64(ptr) c89atomic_test_and_set_explicit_i64(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_clear_i8( ptr) c89atomic_clear_explicit_i8( ptr, c89atomic_memory_order_seq_cst) #define c89atomic_clear_i16(ptr) c89atomic_clear_explicit_i16(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_clear_i32(ptr) c89atomic_clear_explicit_i32(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_clear_i64(ptr) c89atomic_clear_explicit_i64(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_store_i8( dst, src) c89atomic_store_explicit_i8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_store_i16(dst, src) c89atomic_store_explicit_i16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_store_i32(dst, src) c89atomic_store_explicit_i32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_store_i64(dst, src) c89atomic_store_explicit_i64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_load_i8( ptr) c89atomic_load_explicit_i8( ptr, c89atomic_memory_order_seq_cst) #define c89atomic_load_i16(ptr) c89atomic_load_explicit_i16(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_load_i32(ptr) c89atomic_load_explicit_i32(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_load_i64(ptr) c89atomic_load_explicit_i64(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_i8( dst, src) c89atomic_exchange_explicit_i8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_i16(dst, src) c89atomic_exchange_explicit_i16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_i32(dst, src) c89atomic_exchange_explicit_i32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_i64(dst, src) c89atomic_exchange_explicit_i64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_strong_i8( dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_strong_i16(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_strong_i32(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_strong_i64(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_weak_i8( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_weak_i16(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_weak_i32(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_compare_exchange_weak_i64(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_add_i8( dst, src) c89atomic_fetch_add_explicit_i8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_add_i16(dst, src) c89atomic_fetch_add_explicit_i16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_add_i32(dst, src) c89atomic_fetch_add_explicit_i32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_add_i64(dst, src) c89atomic_fetch_add_explicit_i64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_sub_i8( dst, src) c89atomic_fetch_sub_explicit_i8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_sub_i16(dst, src) c89atomic_fetch_sub_explicit_i16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_sub_i32(dst, src) c89atomic_fetch_sub_explicit_i32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_sub_i64(dst, src) c89atomic_fetch_sub_explicit_i64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_or_i8( dst, src) c89atomic_fetch_or_explicit_i8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_or_i16(dst, src) c89atomic_fetch_or_explicit_i16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_or_i32(dst, src) c89atomic_fetch_or_explicit_i32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_or_i64(dst, src) c89atomic_fetch_or_explicit_i64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_xor_i8( dst, src) c89atomic_fetch_xor_explicit_i8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_xor_i16(dst, src) c89atomic_fetch_xor_explicit_i16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_xor_i32(dst, src) c89atomic_fetch_xor_explicit_i32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_xor_i64(dst, src) c89atomic_fetch_xor_explicit_i64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_and_i8( dst, src) c89atomic_fetch_and_explicit_i8( dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_and_i16(dst, src) c89atomic_fetch_and_explicit_i16(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_and_i32(dst, src) c89atomic_fetch_and_explicit_i32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_fetch_and_i64(dst, src) c89atomic_fetch_and_explicit_i64(dst, src, c89atomic_memory_order_seq_cst) /* Floating Point Explicit. Not all operations are supported. */ typedef union { c89atomic_uint32 i; float f; } c89atomic_if32; typedef union { c89atomic_uint64 i; double f; } c89atomic_if64; #define c89atomic_clear_explicit_f32(ptr, order) c89atomic_clear_explicit_32((c89atomic_uint32*)ptr, order) #define c89atomic_clear_explicit_f64(ptr, order) c89atomic_clear_explicit_64((c89atomic_uint64*)ptr, order) static C89ATOMIC_INLINE void c89atomic_store_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order) { c89atomic_if32 x; x.f = src; c89atomic_store_explicit_32((volatile c89atomic_uint32*)dst, x.i, order); } static C89ATOMIC_INLINE void c89atomic_store_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order) { c89atomic_if64 x; x.f = src; c89atomic_store_explicit_64((volatile c89atomic_uint64*)dst, x.i, order); } static C89ATOMIC_INLINE float c89atomic_load_explicit_f32(volatile float* ptr, c89atomic_memory_order order) { c89atomic_if32 r; r.i = c89atomic_load_explicit_32((volatile c89atomic_uint32*)ptr, order); return r.f; } static C89ATOMIC_INLINE double c89atomic_load_explicit_f64(volatile double* ptr, c89atomic_memory_order order) { c89atomic_if64 r; r.i = c89atomic_load_explicit_64((volatile c89atomic_uint64*)ptr, order); return r.f; } static C89ATOMIC_INLINE float c89atomic_exchange_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order) { c89atomic_if32 r; c89atomic_if32 x; x.f = src; r.i = c89atomic_exchange_explicit_32((volatile c89atomic_uint32*)dst, x.i, order); return r.f; } static C89ATOMIC_INLINE double c89atomic_exchange_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order) { c89atomic_if64 r; c89atomic_if64 x; x.f = src; r.i = c89atomic_exchange_explicit_64((volatile c89atomic_uint64*)dst, x.i, order); return r.f; } /* Float Point Implicit */ #define c89atomic_clear_f32(ptr) (float )c89atomic_clear_explicit_f32(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_clear_f64(ptr) (double)c89atomic_clear_explicit_f64(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_store_f32(dst, src) c89atomic_store_explicit_f32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_store_f64(dst, src) c89atomic_store_explicit_f64(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_load_f32(ptr) (float )c89atomic_load_explicit_f32(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_load_f64(ptr) (double)c89atomic_load_explicit_f64(ptr, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_f32(dst, src) (float )c89atomic_exchange_explicit_f32(dst, src, c89atomic_memory_order_seq_cst) #define c89atomic_exchange_f64(dst, src) (double)c89atomic_exchange_explicit_f64(dst, src, c89atomic_memory_order_seq_cst) /* Spinlock */ typedef c89atomic_flag c89atomic_spinlock; static C89ATOMIC_INLINE void c89atomic_spinlock_lock(volatile c89atomic_spinlock* pSpinlock) { for (;;) { if (c89atomic_flag_test_and_set_explicit(pSpinlock, c89atomic_memory_order_acquire) == 0) { break; } while (c89atoimc_flag_load_explicit(pSpinlock, c89atomic_memory_order_relaxed) == 1) { /* Do nothing. */ } } } static C89ATOMIC_INLINE void c89atomic_spinlock_unlock(volatile c89atomic_spinlock* pSpinlock) { c89atomic_flag_clear_explicit(pSpinlock, c89atomic_memory_order_release); } #if defined(__cplusplus) } #endif #endif /* c89atomic_h */ /* This software is available as a choice of the following licenses. Choose whichever you prefer. =============================================================================== ALTERNATIVE 1 - Public Domain (www.unlicense.org) =============================================================================== This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org/> =============================================================================== ALTERNATIVE 2 - MIT No Attribution =============================================================================== Copyright 2020 David Reid 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. 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. */
C
#include <cs50.h> #include <stdio.h> int mult(int n); int main (void) { printf("Dame un numero "); int x = get_int(); printf("Esto es lo que sale %i\n",mult(x)); } int mult(int n) { n = n * n; return n; }
C
# include<cs50.h> # include<stdio.h> # include<string.h> # include<ctype.h> #include<stdlib.h> int main( int argc, string argv[]) { // check input at command line argument if (argc != 2) { printf ("Valid Key is not entered\n"); return 1; } // check key to be positive int key = atoi (argv[1]); if (key < 0) { printf ("Key is not positive\n"); return 1; } // get plain text from user string plaintext = GetString(); //get lenght of plain text int len = strlen (plaintext); for(int j = 0; j < len; j++) // loop to convert each character of string { if (isalpha (plaintext[j])) // conversion only for character { //A -65 Z 90 a97 z122 int init = isupper (plaintext[j]) ? 65 : 97; // A = 65 && a = 97 int asc= plaintext[j] + key ; // A-Z or a-z range exceeds if (! ((asc> 64 && asc <91) || (asc> 96 && asc <123))) { asc = asc - init; // asc('Y'+2) = 91 - 65 = 26 asc = (asc) % 26 +init; //26 % 26 + 65 = 'A' } printf ("%c", asc ); // print alpha character } else { //print special character or numeric character printf ("%c", plaintext[j] ); } } printf ("\n"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_s_specifier.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mrahmani <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/05 16:35:54 by mrahmani #+# #+# */ /* Updated: 2021/01/05 16:57:43 by mrahmani ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_printf.h" int write_str(char *str, int precision) { int i; i = 0; if (precision == -1 || precision > ft_strlen(str)) precision = ft_strlen(str); while (str[i] != '\0' && i < precision) { ft_putchar(str[i]); i++; } return (i); } int write_flags(char c, char *str, int width, int precision) { int size; int length; int count; count = 0; size = 0; if (width == -1) return (0); else { length = ft_strlen(str); precision = precision > width ? width : precision; if (precision >= length && width > precision) size = width - length; else if (precision == -1 || width == precision) size = width - length; else if ((width > precision && length < width) || width > precision) size = width - precision; } while (size > 0) { count += write_char(c); size--; } return (count); } int output_s(t_format *parser, char *str, int precision, int width) { int count; count = 0; if (width < -1) { parser->flag = '-'; width = width * -1; } if (parser->flag == '-') { count += write_str(str, precision); count += write_flags(' ', str, width, precision); } else if (parser->flag == '0') { count += write_flags('0', str, width, precision); count += write_str(str, precision); } else if (parser->flag == ' ') { count += write_flags(' ', str, width, precision); count += write_str(str, precision); } return (count); } int output_s_specifier(va_list *parms_arry, t_format *parser) { char *arg; int precision; int width; if (parser->is_dynamic_wdith == 1) { width = va_arg(*parms_arry, int); if (width < 0) { width = width * -1; parser->flag = '-'; } } else width = parser->width; if (parser->is_dynamic_precision == 1) precision = va_arg(*parms_arry, int); else precision = parser->precision; arg = va_arg(*parms_arry, char *); if (arg == NULL) arg = "(null)"; precision = precision < -1 ? ft_strlen(arg) : precision; return (output_s(parser, arg, precision, width)); }
C
#include "head.h" #include "get_conf_value.c" #ifdef DEBUG #define DBGprint(...) printf(__VA_ARGS__) #else #define DBGprint(...) #endif #define BUFFER_SIZE 1024 #define FILE_SIZE 512 #define INS 3 static pthread_mutex_t mutex[INS + 1] = PTHREAD_MUTEX_INITIALIZER; struct mypara { const char *s; int num; }; int connect_socket(char *host, char *port) { int sockfd; struct sockaddr_in dest_addr; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { DBGprint("Socket Error"); return -1; } dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(atoi(port)); dest_addr.sin_addr.s_addr = inet_addr(host); if (connect(sockfd, (struct sockaddr * )&dest_addr, sizeof(dest_addr))) { DBGprint("Connect Error"); return -1; } return sockfd; } int socket_listen(char *port) { int sockfd; struct sockaddr_in sock_addr; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { DBGprint("Socket Error"); return -1; } sock_addr.sin_family = AF_INET; sock_addr.sin_port = atoi(port); sock_addr.sin_addr.s_addr = htonl(INADDR_ANY); if ((bind(sockfd, (struct sockaddr *)&sock_addr, sizeof(struct sockaddr))) < 0) { DBGprint("Bind Error"); return -1; } if (listen(sockfd, 20) < 0) { DBGprint("Listen Error"); return -1; } return sockfd; } void get_filename (int ack, char *filename) { switch (ack) { case 100: { sprintf(filename, "./shell/logfile/CPU.log"); } break; case 200: { sprintf(filename, "./shell/logfile/Mem.log"); } break; case 300: { sprintf(filename, "./shell/logfile/Disk.log"); } break; case 400: { sprintf(filename, "./shell/logfile/System.log"); } break; case 500: { sprintf(filename, "./shell/logfile/User.log"); } break; case 600: { sprintf(filename, "./shell/logfile/Process.log"); } break; default : { DBGprint("Ack Error!\n"); break; } } } void *func(void *argv) { struct mypara *para; para = (struct mypara *) argv; char **bashFileName = (char **)malloc(sizeof(char *) * (INS + 1)); for (int i = 0; i < 3; i++) { bashFileName[i] = (char *)malloc(sizeof(char) * 30); } int n = 0, m = 0, waittime; switch(para->num) { case 0 : { n = 2; waittime = 5; sprintf(bashFileName[m++], "bash ./shell/CPU.sh"); sprintf(bashFileName[m++], "bash ./shell/Memlog.sh"); }break; case 1 : { n = 3; waittime = 60; sprintf(bashFileName[m++], "bash ./shell/Disk.sh"); sprintf(bashFileName[m++], "bash ./shell/System.sh"); sprintf(bashFileName[m++], "bash ./shell/Users.sh"); }break; case 2 : { n = 1; waittime = 30; sprintf(bashFileName[m++], "bash ./shell/Process.sh"); }break; default : DBGprint("Para->num Error!\n"); break; } FILE *fp; while (1) { for (int i = 0; i < n; i++) { pthread_mutex_lock(&mutex[para->num]); fp = popen(bashFileName[i], "r"); pclose(fp); pthread_mutex_unlock(&mutex[para->num]); } sleep(waittime); } return NULL; } void *alarm_func(void *argv) { char bashFileName[50], filename[50]; sprintf(bashFileName, "bash ./shell/Alarm.sh"); sprintf(filename, "./shell/logfile/warning.log"); FILE *fp, *fd; while (1) { fp = popen(bashFileName, "r"); pclose(fp); sleep(5); fd = fopen(filename, "r"); char ch; if (fd != NULL) { int alarm_socket; char *master_host = (char *)malloc(sizeof(char) * 20); get_conf_value("./piheadlthd.conf", "master_host", master_host); char *alarm_port = (char *)malloc(sizeof(char) * 5); get_conf_value("./piheadlthd.conf", "client_port", alarm_port); if ((alarm_socket = connect_socket(master_host, alarm_port)) < 0) { DBGprint("Connect Error"); return NULL; } DBGprint("Alarm Connect Success!\n"); char buffer[BUFFER_SIZE]; bzero(buffer, sizeof(buffer)); while (!feof(fd)) { int num_fread = fread(buffer, 4, 1, fd); if (num_fread < 0) { DBGprint("Fread Alarm Error"); } int x = send(alarm_socket, buffer, num_fread, 0); bzero(buffer, sizeof(buffer)); } fclose(fd); if (remove(filename) != 0) { DBGprint("Remove Error"); } close(alarm_socket); DBGprint("Warning Send Success!\n"); } } return NULL; } int main() { pid_t id = fork(); if (id < 0) { perror("fork()"); } else if (id > 0) { exit(0); } int sock_client; struct sockaddr_in dest_addr; char *master_host = (char *)malloc(sizeof(char) * 20); get_conf_value("./piheadlthd.conf", "master_host", master_host); char *client_port = (char *)malloc(sizeof(char) * 5); get_conf_value("./piheadlthd.conf", "client_port", client_port); if ((sock_client = connect_socket(master_host, client_port)) < 0) { DBGprint("Connect Error"); return -1; } DBGprint("Connect Master Success!\n"); close(sock_client); pthread_t t[INS + 1]; struct mypara para[INS + 1]; for (int i = 0; i < 3; i++) { para[i].s = "Check"; para[i].num = i; if (pthread_create(&t[i], NULL, func, (void *)&para[i]) == -1) { DBGprint("Pthread Create Error!\n"); exit(1); } } pthread_t alarm_t; if (pthread_create(&alarm_t, NULL, alarm_func, NULL) == -1) { DBGprint("Alarm Pthread Create Error!\n"); exit(1); } char *connect_port = (char *)malloc(sizeof(char) * 5); get_conf_value("./piheadlthd.conf", "connect_port", connect_port); int sock_listen = socket_listen(connect_port); int ack, short_socket, short_socket_listen; char *short_port = (char *)malloc(sizeof(char) * 5); get_conf_value("./piheadlthd.conf", "short_port", short_port); short_socket_listen = socket_listen(short_port); while (1) { struct sockaddr_in master_addr; socklen_t len = sizeof(master_addr); if ((sock_client= accept(sock_listen, (struct sockaddr *)&master_addr, &len)) < 0) { DBGprint("Accept Error!"); break; } DBGprint("Master Connect Success!\n"); FILE *fp; char *filename = (char *)malloc(sizeof(char) * 100); while (recv(sock_client, &ack, 4, 0) > 0) { fp = NULL; get_filename(ack, filename); if (access(filename, 0) == 0) { ack += 1; send(sock_client, &ack, 4, 0); DBGprint("%s Can Send!\n", filename); } else { ack = 404; send(sock_client, &ack, 4, 0); DBGprint("%s Can Not Send!\n", filename); continue; } if ((short_socket = accept(short_socket_listen, (struct sockaddr *)&master_addr, &len)) < 0) { DBGprint("Accept Error!\n"); break; } pthread_mutex_lock(&mutex[para->num]); FILE *fp = fopen(filename, "r"); char buffer[BUFFER_SIZE]; if (NULL == fp) { DBGprint("File: %s Not Found!\n", filename); } else { bzero(buffer, sizeof(buffer)); while (!feof(fp)) { int num_fread = fread(buffer, sizeof(char), 1, fp); if (num_fread < 0) { DBGprint("Fread Error"); return -1; } send(short_socket, buffer, num_fread, 0); bzero(buffer, sizeof(buffer)); } fclose(fp); if (remove(filename) != 0) { DBGprint("Remove Error"); } close(short_socket); } pthread_mutex_unlock(&mutex[para->num]); DBGprint("Send File:\t%s Successful!\n", filename); } close(sock_client); } close(short_socket_listen); close(sock_listen); }