hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
be7ad00f4f6cf665715c15d87dad265f58240e6e
2,063
h
C
wsf_c/axis2c/include/axis2_addr_mod.h
michaelarnauts/wso-wsf-php
48d05363fe70ffd51b159b957bf00c4128d8d615
[ "Apache-2.0" ]
18
2015-04-14T13:16:09.000Z
2021-06-28T01:56:54.000Z
wsf_c/axis2c/include/axis2_addr_mod.h
notxarb/wsf-php
3664c4123e062a75f576e69477e8bf245aa181a6
[ "Apache-2.0" ]
12
2015-04-19T13:17:37.000Z
2018-08-31T14:04:20.000Z
wsf_c/axis2c/include/axis2_addr_mod.h
notxarb/wsf-php
3664c4123e062a75f576e69477e8bf245aa181a6
[ "Apache-2.0" ]
15
2015-05-28T14:56:00.000Z
2022-03-30T11:39:37.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef AXIS2_ADDR_MOD_H #define AXIS2_ADDR_MOD_H /** * @defgroup axis2_mod_addr WS-Addressing Module * @ingroup axis2 * @{ * @} */ /** * @defgroup axis2_addr_mod addressing module interface * @ingroup axis2_mod_addr * @{ */ /** * @file axis2_addr_mod.h */ #include <axis2_handler.h> #ifdef __cplusplus extern "C" { #endif #define ADDR_IN_HANDLER "AddressingInHandler" #define ADDR_OUT_HANDLER "AddressingOutHandler" /** * Creates Addressing in handler * @param env pointer to environment struct * @param name name of handler * @return returns reference to handler created */ AXIS2_EXTERN axis2_handler_t *AXIS2_CALL axis2_addr_in_handler_create( const axutil_env_t * env, axutil_string_t * name); /** * Creates Addressing out handler * @param env pointer to environment struct * @param name name of handler * @return returns reference to handler created */ AXIS2_EXTERN axis2_handler_t *AXIS2_CALL axis2_addr_out_handler_create( const axutil_env_t * env, axutil_string_t * name); /** @} */ #ifdef __cplusplus } #endif #endif /* AXIS2_ADDR_MOD_H */
26.448718
75
0.684925
80edace2298102f69d7be288504bef77d59e6883
253
h
C
libs/media/exr_reader.h
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
15
2017-10-18T05:08:16.000Z
2022-02-02T11:01:46.000Z
libs/media/exr_reader.h
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
null
null
null
libs/media/exr_reader.h
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
1
2018-11-10T03:12:57.000Z
2018-11-10T03:12:57.000Z
// SPDX-License-Identifier: MIT // Copyright contributors to the gecko project. #pragma once namespace media { //////////////////////////////////////// void register_exr_reader( void ); //////////////////////////////////////// } // namespace media
16.866667
47
0.501976
4180c1cf4d8c290585e16057de3c325dbd068b0e
1,163
c
C
src/helpers/signal.c
ryanhs/cweb
8ac2c4394f61ff81ded9517fea718547ec353b46
[ "MIT" ]
1
2018-01-24T02:49:24.000Z
2018-01-24T02:49:24.000Z
src/helpers/signal.c
ryanhs/cweb
8ac2c4394f61ff81ded9517fea718547ec353b46
[ "MIT" ]
null
null
null
src/helpers/signal.c
ryanhs/cweb
8ac2c4394f61ff81ded9517fea718547ec353b46
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #include <errno.h> #include <resolv.h> #include <signal.h> #include "../models/config.h" void signal_handler(int signal){ if(DEBUG); printf("signal received: \n - "); switch(signal){ case SIGINT: printf("SIGINT <- external interrupt, usually initiated by the user\n"); break; case SIGTERM: printf("SIGTERM <- termination request, sent to the program\n"); break; case SIGSEGV: printf("SIGSEGV <- invalid memory access (segmentation fault)\n"); break; case SIGILL: printf("SIGILL <- invalid program image, such as invalid instruction\n"); break; case SIGABRT: printf("SIGABRT <- abnormal termination condition, as is e.g. initiated by abort()\n"); break; case SIGFPE: printf("SIGFPE <- erroneous arithmetic operation such as divide by zero\n"); break; default: printf("unknown signal -> %d\n", signal); break; } abort(); } void handle_signal(){ signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); signal(SIGSEGV, signal_handler); signal(SIGILL, signal_handler); signal(SIGFPE, signal_handler); }
23.734694
90
0.688736
84b5459f6745720e710c53058805e690fcf18967
94
h
C
ekf/Header.h
mantoshkumar1/imm-filter
17b39a99f57987c6c6342c1e6ac14dc33fd4b7e6
[ "MIT" ]
2
2021-05-09T07:49:34.000Z
2021-05-26T09:16:49.000Z
ekf/Header.h
mantoshkumar1/imm-filter
17b39a99f57987c6c6342c1e6ac14dc33fd4b7e6
[ "MIT" ]
null
null
null
ekf/Header.h
mantoshkumar1/imm-filter
17b39a99f57987c6c6342c1e6ac14dc33fd4b7e6
[ "MIT" ]
1
2020-06-15T05:43:42.000Z
2020-06-15T05:43:42.000Z
#pragma once #ifndef _HEADER_H #define _HEADER_H int sum(int, int); #endif /* _HEADER_H */
18.8
22
0.702128
4a3b7ce0e46672c0b04d26e469a7b19d874e6b6f
755
h
C
game.h
rayank77b/snakeGame
569bfdfe5118fdb17e4dcf089820694b268e5c08
[ "MIT" ]
null
null
null
game.h
rayank77b/snakeGame
569bfdfe5118fdb17e4dcf089820694b268e5c08
[ "MIT" ]
null
null
null
game.h
rayank77b/snakeGame
569bfdfe5118fdb17e4dcf089820694b268e5c08
[ "MIT" ]
null
null
null
#ifndef GAME_H #define GAME_H #include <QGraphicsScene> #include <QGraphicsView> #include <QTimer> #include <QGraphicsTextItem> #include <QGraphicsPixmapItem> #include <QFont> #include <QRandomGenerator> #include "snake.h" #include "snakebody.h" #include "apple.h" #include "score.h" const int X_MAX = 1000; const int Y_MAX = 800; class Game : public QGraphicsView { Q_OBJECT private: unsigned int snake_grow = 3; int game_period_ms = 250; public: QGraphicsScene *scene; Snake *snake; Apple *apple; Score *score; QGraphicsTextItem *txtGameOver; QTimer *gameTimer; QRandomGenerator *generator; Game(QWidget * parent=0); public slots: void snakeCollision(); void appleEated(); }; #endif // GAME_H
17.159091
35
0.704636
7d240a3c4f423fedcadd58131216eaa081e4e354
5,626
c
C
src/libbpf_map.c
infrared-rb/mruby-libbpf
0a30f68c6b5b200bd4ce3ff11500f7b987d7e319
[ "MIT" ]
2
2021-09-14T02:21:40.000Z
2021-09-15T10:42:13.000Z
src/libbpf_map.c
infrared-rb/mruby-libbpf
0a30f68c6b5b200bd4ce3ff11500f7b987d7e319
[ "MIT" ]
null
null
null
src/libbpf_map.c
infrared-rb/mruby-libbpf
0a30f68c6b5b200bd4ce3ff11500f7b987d7e319
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mruby.h> #include <mruby/data.h> #include <mruby/class.h> #include <mruby/value.h> #include <mruby/error.h> #include <bpf/libbpf.h> #include <bpf/bpf.h> #include "mrb_libbpf.h" #define DONE mrb_gc_arena_restore(mrb, 0); typedef struct { int fd; int key_size; int value_size; enum bpf_map_type type; struct bpf_map *ptr; } mrb_libbpf_map_data; static const struct mrb_data_type mrb_libbpf_map_data_type = { "mrb_libbpf_map_data", mrb_free, }; mrb_value mrb_libbpf_map_generate(mrb_state *mrb, int key_size, int value_size, enum bpf_map_type type, struct bpf_map *ptr) { struct RClass *m = mrb_module_get(mrb, "BPF"); struct RClass *c = mrb_class_get_under(mrb, m, "Map"); mrb_value self = mrb_obj_new(mrb, c, 0, NULL); DATA_TYPE(self) = &mrb_libbpf_map_data_type; mrb_libbpf_map_data *data = mrb_malloc(mrb, sizeof(mrb_libbpf_map_data)); data->key_size = key_size; data->value_size = value_size; data->type = type; data->ptr = ptr; data->fd = bpf_map__fd(ptr); DATA_PTR(self) = data; return self; } const __u32 get_first = -2; #define MAX_SLOTS 15 struct hist { __u32 slots[MAX_SLOTS]; }; mrb_value mrb_libbpf_map__debug(mrb_state *mrb, mrb_value self) { if(DATA_PTR(self) == NULL) mrb_sys_fail(mrb, "Invalidly initialized map"); //struct bpf_map *hists = ((mrb_libbpf_map_data *)DATA_PTR(self))->ptr; int fd = ((mrb_libbpf_map_data *)DATA_PTR(self))->fd; __u32 lookup_key = -2, next_key; struct hist h; while (!bpf_map_get_next_key(fd, &lookup_key, &next_key)) { int err = bpf_map_lookup_elem(fd, &next_key, &h); if (err < 0) { fprintf(stderr, "failed to lookup hist: %d\n", err); mrb_sys_fail(mrb, "Error"); } printf("pid: %d\n", next_key); for(int i = 0; i < MAX_SLOTS; i++) printf("\tvalue: hist[%d] = %d\n", i, h.slots[i]); lookup_key = next_key; } return mrb_true_value(); } mrb_value mrb_libbpf_map_next_key(mrb_state *mrb, mrb_value self) { if(DATA_PTR(self) == NULL) mrb_sys_fail(mrb, "Invalidly initialized map"); int fd = ((mrb_libbpf_map_data *)DATA_PTR(self))->fd; int klen = ((mrb_libbpf_map_data *)DATA_PTR(self))->key_size; const char* key; char* nextkey; mrb_int keylen; mrb_get_args(mrb, "s!", &key, &keylen); if (key == NULL && keylen == 0) { key = (void *)(&get_first); keylen = klen; } if (keylen != (mrb_int)klen) { mrb_sys_fail(mrb, "keysize unmatch"); } nextkey = mrb_calloc(mrb, 1, keylen); if(bpf_map_get_next_key(fd, key, nextkey) == -1) return mrb_nil_value(); mrb_value s = mrb_str_new(mrb, nextkey, keylen); mrb_free(mrb, nextkey); return s; } mrb_value mrb_libbpf_map_lookup(mrb_state *mrb, mrb_value self) { if(DATA_PTR(self) == NULL) mrb_sys_fail(mrb, "Invalidly initialized map"); int fd = ((mrb_libbpf_map_data *)DATA_PTR(self))->fd; int klen = ((mrb_libbpf_map_data *)DATA_PTR(self))->key_size; int vlen = ((mrb_libbpf_map_data *)DATA_PTR(self))->value_size; const char* key; char* value = mrb_malloc(mrb, vlen); mrb_int keylen; mrb_get_args(mrb, "s", &key, &keylen); if (keylen != (mrb_int)klen) { mrb_sys_fail(mrb, "keysize unmatch"); } int err = bpf_map_lookup_elem(fd, key, value); if (err < 0) { // mrb_sys_fail(mrb, "no element found"); return mrb_nil_value(); } return mrb_str_new(mrb, value, vlen); } mrb_value mrb_libbpf_map_do_update(mrb_state *mrb, mrb_value self) { if(DATA_PTR(self) == NULL) mrb_sys_fail(mrb, "Invalidly initialized map"); int fd = ((mrb_libbpf_map_data *)DATA_PTR(self))->fd; int klen = ((mrb_libbpf_map_data *)DATA_PTR(self))->key_size; int vlen = ((mrb_libbpf_map_data *)DATA_PTR(self))->value_size; const char *key, *value; mrb_int keylen, valuelen; mrb_get_args(mrb, "ss", &key, &keylen, &value, &valuelen); if (keylen != (mrb_int)klen) { mrb_sys_fail(mrb, "keysize unmatch"); } if (valuelen != (mrb_int)vlen) { mrb_sys_fail(mrb, "valuesize unmatch"); } int err = bpf_map_update_elem(fd, key, value, 0); if (err < 0) { mrb_sys_fail(mrb, "failed to update elem"); } return mrb_str_new(mrb, value, vlen); } mrb_value mrb_libbpf_map_do_delete(mrb_state *mrb, mrb_value self) { if(DATA_PTR(self) == NULL) mrb_sys_fail(mrb, "Invalidly initialized map"); int fd = ((mrb_libbpf_map_data *)DATA_PTR(self))->fd; int klen = ((mrb_libbpf_map_data *)DATA_PTR(self))->key_size; const char* key; mrb_int keylen; mrb_get_args(mrb, "s", &key, &keylen); if (keylen != (mrb_int)klen) { mrb_sys_fail(mrb, "keysize unmatch"); } int err = bpf_map_delete_elem(fd, key); if (err < 0) { mrb_sys_fail(mrb, "failed to delete elem"); } return mrb_str_new(mrb, key, klen); } void mrb_libbpf_map_init(mrb_state *mrb, struct RClass *m) { struct RClass *c = mrb_define_class_under(mrb, m, "Map", mrb->object_class); MRB_SET_INSTANCE_TT(c, MRB_TT_DATA); mrb_define_method(mrb, c, "next_key", mrb_libbpf_map_next_key, MRB_ARGS_REQ(1)); mrb_define_method(mrb, c, "lookup", mrb_libbpf_map_lookup, MRB_ARGS_REQ(1)); mrb_define_method(mrb, c, "do_update", mrb_libbpf_map_do_update, MRB_ARGS_REQ(2)); mrb_define_method(mrb, c, "do_delete", mrb_libbpf_map_do_delete, MRB_ARGS_REQ(1)); mrb_define_method(mrb, c, "__debug", mrb_libbpf_map__debug, MRB_ARGS_NONE()); /* mrb_define_class_method(mrb, libbpf, "hi", mrb_libbpf_hi, MRB_ARGS_NONE()); */ DONE; }
27.31068
84
0.670103
a430265f93b1843dc3529e4c895b089044b3d965
1,194
h
C
SynqUploader/Classes/SQAssetExporter.h
kjartanvest/synquploader-ios
74efaf1699210648e2a76102b07b8f93432071a8
[ "MIT" ]
null
null
null
SynqUploader/Classes/SQAssetExporter.h
kjartanvest/synquploader-ios
74efaf1699210648e2a76102b07b8f93432071a8
[ "MIT" ]
null
null
null
SynqUploader/Classes/SQAssetExporter.h
kjartanvest/synquploader-ios
74efaf1699210648e2a76102b07b8f93432071a8
[ "MIT" ]
null
null
null
// // SQAssetExporter.h // Pods // // Created by Kjartan Vestvik on 15.11.2016. // // This class is used to export PHAsset videos to temporary files, // and to delete those temporary files // #import <Foundation/Foundation.h> @import Photos; #import "SQVideoUpload.h" @protocol SQAssetExporterDelegate; @interface SQAssetExporter : NSObject @property (weak, nonatomic) id<SQAssetExporterDelegate> delegate; /** * Export a SQVideoUpload object to a file * Set the path of the file in SQVideoUpload.filePath * * @param video The SQVideoUpload object containing a PHAsset object to export */ - (void) exportVideo:(SQVideoUpload *)video allowICloudDownload:(BOOL)iCloudDownload; /** * Delete the file at the location specified in SQVideoUpload.filePath * * @param video The SQVideoUpload object */ - (void) deleteExportedFileForVideo:(SQVideoUpload *)video; @end /** * This delegate protocol is implemented by SynqLib to get notified when a video * has finished exporting */ @protocol SQAssetExporterDelegate <NSObject> @required - (void) assetExporter:(SQAssetExporter *)exporter finishedExportingVideo:(SQVideoUpload *)video; // TODO: add error methods @end
22.528302
97
0.749581
6d160b3b88b832db85d0acda9a22080826b0c575
3,784
c
C
include/pcap.c
joncampbell123/hcxdumptool
f27b030c15bafc0789bc405b9061b7f8009fa8da
[ "MIT" ]
1
2018-08-10T17:16:24.000Z
2018-08-10T17:16:24.000Z
include/pcap.c
joncampbell123/hcxdumptool
f27b030c15bafc0789bc405b9061b7f8009fa8da
[ "MIT" ]
null
null
null
include/pcap.c
joncampbell123/hcxdumptool
f27b030c15bafc0789bc405b9061b7f8009fa8da
[ "MIT" ]
null
null
null
#define _GNU_SOURCE #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <fcntl.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <stddef.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/utsname.h> #include "pcap.h" /*===========================================================================*/ uint16_t addoption(uint8_t *shb, uint16_t optioncode, uint16_t optionlen, char *option) { uint16_t padding; option_header_t *optionhdr; optionhdr = (option_header_t*)shb; optionhdr->option_code = optioncode; optionhdr->option_length = optionlen; padding = 0; if((optionlen % 4)) { padding = 4 -(optionlen % 4); } memset(optionhdr->option_data, 0, optionlen +padding); memcpy(optionhdr->option_data, option, optionlen); return optionlen + padding +4; } /*===========================================================================*/ bool writeidb(int fd, uint8_t *macorig, char *interfacestr) { int idblen; int written; interface_description_block_t *idbhdr; total_length_t *totallenght; char vendor[6]; uint8_t idb[256]; memset(&idb, 0, 256); idblen = IDB_SIZE; idbhdr = (interface_description_block_t*)idb; idbhdr->block_type = IDBID; idbhdr->linktype = DLT_IEEE802_11_RADIO; idbhdr->reserved = 0; idbhdr->snaplen = PCAPNG_MAXSNAPLEN; idblen += addoption(idb +idblen, IF_NAME, strlen(interfacestr), interfacestr); memset(&vendor, 0, 6); memcpy(&vendor, macorig, 3); idblen += addoption(idb +idblen, IF_MACADDR, 6, vendor); totallenght = (total_length_t*)(idb +idblen); idblen += TOTAL_SIZE; idbhdr->total_length = idblen; totallenght->total_length = idblen; written = write(fd, &idb, idblen); if(written != idblen) { close(fd); return false; } return true; } /*===========================================================================*/ bool writeshb(int fd) { int shblen; int written; section_header_block_t *shbhdr; total_length_t *totallenght; struct utsname unameData; char sysinfo[256]; uint8_t shb[256]; memset(&shb, 0, 256); shblen = SHB_SIZE; shbhdr = (section_header_block_t*)shb; shbhdr->block_type = PCAPNGBLOCKTYPE; #ifdef BIG_ENDIAN_HOST shbhdr->byte_order_magic = PCAPNGMAGICNUMBERBE; #else shbhdr->byte_order_magic = PCAPNGMAGICNUMBER; #endif shbhdr->byte_order_magic = PCAPNGMAGICNUMBER; shbhdr->major_version = PCAPNG_MAJOR_VER; shbhdr->minor_version = PCAPNG_MINOR_VER; shbhdr->section_length = -1; if(uname(&unameData) == 0) { shblen += addoption(shb +shblen, SHB_HARDWARE, strlen(unameData.machine), unameData.machine); sprintf(sysinfo, "%s %s", unameData.sysname, unameData.release); shblen += addoption(shb +shblen, SHB_OS, strlen(sysinfo), sysinfo); sprintf(sysinfo, "hcxdumptool %s", VERSION); shblen += addoption(shb +shblen, SHB_USER_APPL, strlen(sysinfo), sysinfo); shblen += addoption(shb +shblen, SHB_EOC, 0, NULL); } totallenght = (total_length_t*)(shb +shblen); shblen += TOTAL_SIZE; shbhdr->total_length = shblen; totallenght->total_length = shblen; written = write(fd, &shb, shblen); if(written != shblen) { close(fd); return false; } return true; } /*===========================================================================*/ int hcxcreatepcapngdump(char *pcapngdumpname, uint8_t *macorig, char *interfacestr) { int c; int fd; struct stat statinfo; char newpcapngoutname[PATH_MAX +2]; c = 0; strcpy(newpcapngoutname, pcapngdumpname); while(stat(newpcapngoutname, &statinfo) == 0) { snprintf(newpcapngoutname, PATH_MAX, "%s-%d", pcapngdumpname, c); c++; } umask(0); fd = open(newpcapngoutname, O_WRONLY | O_CREAT, 0644); if(fd == -1) { return -1; } if(writeshb(fd) == false) { return -1; } if(writeidb(fd, macorig, interfacestr) == false) { return -1; } return fd; } /*===========================================================================*/
24.571429
94
0.656977
7a38d8dbf107bf934c8015dc25da2513d4bbd1ad
2,004
h
C
proto/rudder.h
denidoank/avalonsailing
8bc6d511e243ebd4fd90e7fb678ac7560226b5ca
[ "Apache-2.0" ]
null
null
null
proto/rudder.h
denidoank/avalonsailing
8bc6d511e243ebd4fd90e7fb678ac7560226b5ca
[ "Apache-2.0" ]
null
null
null
proto/rudder.h
denidoank/avalonsailing
8bc6d511e243ebd4fd90e7fb678ac7560226b5ca
[ "Apache-2.0" ]
null
null
null
#ifndef PROTO_RUDDER_H #define PROTO_RUDDER_H #include <math.h> #include <stdint.h> struct RudderProto { int64_t timestamp_ms; double rudder_l_deg; double rudder_r_deg; double sail_deg; }; #define INIT_RUDDERPROTO { 0, NAN, NAN, NAN } #define OFMT_RUDDERPROTO_STS(x) \ "ruddersts: timestamp_ms:%lld rudder_l_deg:%.1lf rudder_r_deg:%.1lf sail_deg:%.1lf\n" \ , (x).timestamp_ms, (x).rudder_l_deg, (x).rudder_r_deg, (x).sail_deg #define OFMT_RUDDERPROTO_CTL(x) \ "rudderctl: timestamp_ms:%lld rudder_l_deg:%.3lf rudder_r_deg:%.3lf sail_deg:%.1lf\n" \ , (x).timestamp_ms, (x).rudder_l_deg, (x).rudder_r_deg, (x).sail_deg #define IFMT_RUDDERPROTO_STS(x, n) \ "ruddersts: timestamp_ms:%lld rudder_l_deg:%lf rudder_r_deg:%lf sail_deg:%lf\n%n" \ , &(x)->timestamp_ms, &(x)->rudder_l_deg, &(x)->rudder_r_deg, &(x)->sail_deg, (n) #define IFMT_RUDDERPROTO_STS_ITEMS 4 #define IFMT_RUDDERPROTO_CTL(x, n) \ "rudderctl: timestamp_ms:%lld rudder_l_deg:%lf rudder_r_deg:%lf sail_deg:%lf\n%n" \ , &(x)->timestamp_ms, &(x)->rudder_l_deg, &(x)->rudder_r_deg, &(x)->sail_deg, (n) #define IFMT_RUDDERPROTO_CTL_ITEMS 4 // Variants that only touch one field #define OFMT_STATUS_LEFT(x) \ "status_left: timestamp_ms:%lld angle_deg:%.1lf\n", (x).timestamp_ms, (x).rudder_l_deg #define IFMT_STATUS_LEFT(x, n) \ "status_left: timestamp_ms:%lld angle_deg:%lf\n%n", &(x)->timestamp_ms, &(x)->rudder_l_deg, (n) // Variants that only set one field #define OFMT_STATUS_RIGHT(x) \ "status_right: timestamp_ms:%lld angle_deg:%.1lf\n", (x).timestamp_ms, (x).rudder_r_deg #define IFMT_STATUS_RIGHT(x, n) \ "status_right: timestamp_ms:%lld angle_deg:%lf\n%n", &(x)->timestamp_ms, &(x)->rudder_r_deg, (n) // Variants that only set one field #define OFMT_STATUS_SAIL(x) \ "status_sail: timestamp_ms:%lld angle_deg:%.1lf\n", (x).timestamp_ms, (x).sail_deg #define IFMT_STATUS_SAIL(x, n) \ "status_sail: timestamp_ms:%lld angle_deg:%lf\n%n", &(x)->timestamp_ms, &(x)->sail_deg, (n) #endif // PROTO_RUDDER_H
35.785714
98
0.721557
9e5772a1ec8312d1d092b80256c0f19f57f2b509
5,058
h
C
library/src/main/cpp/interface/FrameRendererWrapper.h
1463836/android-gpuimage-plus
ad00886e8947e69548814eb457e39985aebea103
[ "MIT" ]
null
null
null
library/src/main/cpp/interface/FrameRendererWrapper.h
1463836/android-gpuimage-plus
ad00886e8947e69548814eb457e39985aebea103
[ "MIT" ]
null
null
null
library/src/main/cpp/interface/FrameRendererWrapper.h
1463836/android-gpuimage-plus
ad00886e8947e69548814eb457e39985aebea103
[ "MIT" ]
null
null
null
/* * cgeFrameRendererWrapper.h * * Created on: 2015-11-26 * Author: Wang Yang * Mail: admin@wysaid.org */ #include <jni.h> /* Header for class org_wysaid_nativePort_CGEFrameRenderer */ #ifndef _Included_org_wysaid_nativePort_CGEFrameRenderer #define _Included_org_wysaid_nativePort_CGEFrameRenderer #ifdef __cplusplus extern "C" { #endif /* * Class: org_wysaid_nativePort_CGEFrameRenderer * Method: nativeCreate * Signature: ()Ljava/nio/ByteBuffer; */ JNIEXPORT jlong JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeCreateRenderer (JNIEnv *, jobject); /* * Class: org_wysaid_nativePort_CGEFrameRenderer * Method: nativeInit * Signature: (Ljava/nio/ByteBuffer;IIII)Z */ JNIEXPORT jboolean JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeInit (JNIEnv *, jobject, jlong, jint, jint, jint, jint); /* * Class: org_wysaid_nativePort_CGEFrameRenderer * Method: nativeUpdate * Signature: (Ljava/nio/ByteBuffer;I)V */ JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeUpdate (JNIEnv *, jobject, jlong, jint, jfloatArray); /* * Class: org_wysaid_nativePort_CGEFrameRenderer * Method: nativeRender * Signature: (Ljava/nio/ByteBuffer;IIII)V */ JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeRender (JNIEnv *, jobject, jlong, jint, jint, jint, jint); /* * Class: org_wysaid_nativePort_CGEFrameRenderer * Method: nativeSetSrcRotation * Signature: (Ljava/nio/ByteBuffer;F)V */ JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetSrcRotation (JNIEnv *, jobject, jlong, jfloat); /* * Class: org_wysaid_nativePort_CGEFrameRenderer * Method: nativeSetSrcFlipScale * Signature: (Ljava/nio/ByteBuffer;FF)V */ JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetSrcFlipScale (JNIEnv *, jobject, jlong, jfloat, jfloat); /* * Class: org_wysaid_nativePort_CGEFrameRenderer * Method: nativeSetRenderRotation * Signature: (Ljava/nio/ByteBuffer;F)V */ JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetRenderRotation (JNIEnv *, jobject, jlong, jfloat); /* * Class: org_wysaid_nativePort_CGEFrameRenderer * Method: nativeSetRenderFlipScale * Signature: (Ljava/nio/ByteBuffer;FF)V */ JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetRenderFlipScale (JNIEnv *, jobject, jlong, jfloat, jfloat); /* * Class: org_wysaid_nativePort_CGEFrameRenderer * Method: nativeSetFilterWithConfig * Signature: (Ljava/nio/ByteBuffer;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetFilterWithConfig (JNIEnv *, jobject, jlong, jstring); /* * Class: org_wysaid_nativePort_CGEFrameRenderer * Method: nativeSetFilterIntensity * Signature: (Ljava/nio/ByteBuffer;F)V */ JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetFilterIntensity (JNIEnv *, jobject, jlong, jfloat); JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSrcResize (JNIEnv *, jobject, jlong, jint, jint); JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetMaskTexture (JNIEnv *, jobject, jlong, jint, jfloat); JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetMaskTextureRatio (JNIEnv *, jobject, jlong, jfloat); JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeRelease (JNIEnv *, jobject, jlong); JNIEXPORT jint JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeQueryBufferTexture (JNIEnv *, jobject, jlong); JNIEXPORT jint JNICALL Java_org_wysaid_nativePort_CGEFrameRenderer_nativeQueryTargetTexture (JNIEnv *, jobject, jlong); JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetMaskRotation (JNIEnv *, jobject, jlong, jfloat); JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetMaskFlipScale (JNIEnv *, jobject, jlong, jfloat, jfloat); JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeRunProc (JNIEnv *, jobject, jlong); ///////////////// Render Utils ///////////////////////////// JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeDrawCache (JNIEnv *, jobject, jlong); JNIEXPORT jlong JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeGetImageHandler (JNIEnv *, jobject, jlong); JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeBindImageFBO (JNIEnv *, jobject, jlong); JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSwapBufferFBO (JNIEnv *, jobject, jlong); JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeProcessWithFilter (JNIEnv *, jobject, jlong, jlong); //// JNIEXPORT void JNICALL Java_org_wysaid_nativePort_FrameRenderer_nativeSetFilterWithAddr (JNIEnv *, jobject, jlong, jlong); #ifdef __cplusplus } #endif #endif
33.496689
91
0.772242
9ecb90aae82c86ec3c672b5dbbe55cb75d338b5c
4,506
h
C
src/external/protobuf/test_util_lite.h
TimothyRHuertas/turicreate
afa00bee56d168190c6f122e14c9fbc6656b4e97
[ "BSD-3-Clause" ]
1
2019-04-16T19:51:18.000Z
2019-04-16T19:51:18.000Z
src/external/protobuf/test_util_lite.h
tashby/turicreate
7f07ce795833d0c56c72b3a1fb9339bed6d178d1
[ "BSD-3-Clause" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
src/external/protobuf/test_util_lite.h
tashby/turicreate
7f07ce795833d0c56c72b3a1fb9339bed6d178d1
[ "BSD-3-Clause" ]
1
2020-10-21T17:46:28.000Z
2020-10-21T17:46:28.000Z
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #ifndef GOOGLE_PROTOBUF_TEST_UTIL_LITE_H__ #define GOOGLE_PROTOBUF_TEST_UTIL_LITE_H__ #include <protobuf/unittest_lite.pb.h> namespace google { namespace protobuf { namespace unittest = protobuf_unittest; namespace unittest_import = protobuf_unittest_import; class TestUtilLite { public: // Set every field in the message to a unique value. static void SetAllFields(unittest::TestAllTypesLite* message); static void SetAllExtensions(unittest::TestAllExtensionsLite* message); static void SetPackedFields(unittest::TestPackedTypesLite* message); static void SetPackedExtensions(unittest::TestPackedExtensionsLite* message); // Use the repeated versions of the set_*() accessors to modify all the // repeated fields of the message (which should already have been // initialized with Set*Fields()). Set*Fields() itself only tests // the add_*() accessors. static void ModifyRepeatedFields(unittest::TestAllTypesLite* message); static void ModifyRepeatedExtensions( unittest::TestAllExtensionsLite* message); static void ModifyPackedFields(unittest::TestPackedTypesLite* message); static void ModifyPackedExtensions( unittest::TestPackedExtensionsLite* message); // Check that all fields have the values that they should have after // Set*Fields() is called. static void ExpectAllFieldsSet(const unittest::TestAllTypesLite& message); static void ExpectAllExtensionsSet( const unittest::TestAllExtensionsLite& message); static void ExpectPackedFieldsSet( const unittest::TestPackedTypesLite& message); static void ExpectPackedExtensionsSet( const unittest::TestPackedExtensionsLite& message); // Expect that the message is modified as would be expected from // Modify*Fields(). static void ExpectRepeatedFieldsModified( const unittest::TestAllTypesLite& message); static void ExpectRepeatedExtensionsModified( const unittest::TestAllExtensionsLite& message); static void ExpectPackedFieldsModified( const unittest::TestPackedTypesLite& message); static void ExpectPackedExtensionsModified( const unittest::TestPackedExtensionsLite& message); // Check that all fields have their default values. static void ExpectClear(const unittest::TestAllTypesLite& message); static void ExpectExtensionsClear( const unittest::TestAllExtensionsLite& message); static void ExpectPackedClear(const unittest::TestPackedTypesLite& message); static void ExpectPackedExtensionsClear( const unittest::TestPackedExtensionsLite& message); private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TestUtilLite); }; } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_TEST_UTIL_LITE_H__
44.176471
79
0.780515
fa261d25945977a1dde65e9c0581250afbc05a22
429
h
C
soc/arm/atmel_sam0/samd20/dts_fixup.h
sathishkuttan/zephyr
9d5a63b9c1d3b7f7400f2848692d6e6a4be4c8af
[ "Apache-2.0" ]
35
2018-09-09T13:32:51.000Z
2022-02-13T03:38:55.000Z
soc/arm/atmel_sam0/samd20/dts_fixup.h
sathishkuttan/zephyr
9d5a63b9c1d3b7f7400f2848692d6e6a4be4c8af
[ "Apache-2.0" ]
null
null
null
soc/arm/atmel_sam0/samd20/dts_fixup.h
sathishkuttan/zephyr
9d5a63b9c1d3b7f7400f2848692d6e6a4be4c8af
[ "Apache-2.0" ]
13
2018-11-16T16:40:53.000Z
2021-12-28T09:18:58.000Z
/* SPDX-License-Identifier: Apache-2.0 */ /* SoC level DTS fixup file */ #define DT_FLASH_DEV_NAME DT_ATMEL_SAM0_NVMCTRL_41004000_LABEL #define CONFIG_WDT_0_NAME DT_ATMEL_SAM0_WATCHDOG_0_LABEL #define CONFIG_COUNTER_0_NAME DT_ATMEL_SAM0_TC32_0_LABEL #define CONFIG_I2C_0_NAME DT_ATMEL_SAM0_I2C_0_LABEL #define DT_NUM_IRQ_PRIO_BITS DT_ARM_V6M_NVIC_E000E100_ARM_NUM_IRQ_PRIORITY_BITS /* End of SoC Level DTS fixup file */
26.8125
79
0.846154
cfffb45bf7ddb1e4ede8ee7574a5c5a8d58bca03
47,366
c
C
Sources/Cfyaml/lib/fy-walk.c
RockyYara/PotentCodables
c3f5c13aae9de60d1834901ba641034daf86f058
[ "MIT" ]
32
2019-08-19T09:33:49.000Z
2022-02-10T20:07:59.000Z
Sources/Cfyaml/lib/fy-walk.c
RockyYara/PotentCodables
c3f5c13aae9de60d1834901ba641034daf86f058
[ "MIT" ]
8
2020-02-26T10:08:20.000Z
2022-02-04T01:18:47.000Z
Sources/Cfyaml/lib/fy-walk.c
RockyYara/PotentCodables
c3f5c13aae9de60d1834901ba641034daf86f058
[ "MIT" ]
9
2020-02-26T09:42:56.000Z
2022-02-24T21:05:03.000Z
/* * fy-walk.c - path walker * * Copyright (c) 2021 Pantelis Antoniou <pantelis.antoniou@konsulko.com> * * SPDX-License-Identifier: MIT */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include <ctype.h> #include <errno.h> #include <unistd.h> #include <libfyaml.h> #include "fy-parse.h" #include "fy-doc.h" #include "fy-walk.h" #include "fy-utils.h" #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) ((sizeof(x)/sizeof((x)[0]))) #endif /* NOTE that walk results do not take references and it is invalid to * use _any_ call that modifies the document structure */ struct fy_walk_result *fy_walk_result_alloc(void) { struct fy_walk_result *fwr = NULL; fwr = malloc(sizeof(*fwr)); if (!fwr) return NULL; memset(fwr, 0, sizeof(*fwr)); return fwr; } void fy_walk_result_free(struct fy_walk_result *fwr) { if (!fwr) return; free(fwr); } void fy_walk_result_list_free(struct fy_walk_result_list *results) { struct fy_walk_result *fwr; while ((fwr = fy_walk_result_list_pop(results)) != NULL) fy_walk_result_free(fwr); } int fy_walk_result_add(struct fy_walk_result_list *results, struct fy_node *fyn) { struct fy_walk_result *fwr; /* do not add if fyn is NULL, it's a NOP */ if (!fyn) return 0; /* do not add multiple times */ for (fwr = fy_walk_result_list_head(results); fwr; fwr = fy_walk_result_next(results, fwr)) { if (fwr->fyn == fyn) return 0; } fwr = fy_walk_result_alloc(); if (!fwr) return -1; fwr->fyn = fyn; fy_walk_result_list_add_tail(results, fwr); return 0; } int fy_walk_result_add_recursive(struct fy_walk_result_list *results, struct fy_node *fyn, bool leaf_only) { struct fy_node *fyni; struct fy_node_pair *fynp; int ret; if (!fyn) return 0; if (fy_node_is_scalar(fyn)) return fy_walk_result_add(results, fyn); if (!leaf_only) { ret = fy_walk_result_add(results, fyn); if (ret) return ret; } if (fy_node_is_sequence(fyn)) { for (fyni = fy_node_list_head(&fyn->sequence); fyni; fyni = fy_node_next(&fyn->sequence, fyni)) { ret = fy_walk_result_add_recursive(results, fyni, leaf_only); if (ret) return ret; } } else { for (fynp = fy_node_pair_list_head(&fyn->mapping); fynp; fynp = fy_node_pair_next(&fyn->mapping, fynp)) { ret = fy_walk_result_add_recursive(results, fynp->value, leaf_only); if (ret) return ret; } } return 0; } int fy_walk_result_list_move(struct fy_walk_result_list *to, struct fy_walk_result_list *from) { struct fy_walk_result *fwr; struct fy_node *fyn; int ret; while ((fwr = fy_walk_result_list_pop(from)) != NULL) { fyn = fwr->fyn; fy_walk_result_free(fwr); ret = fy_walk_result_add(to, fyn); if (ret) return ret; } return 0; } struct fy_path_expr *fy_path_expr_alloc(void) { struct fy_path_expr *expr = NULL; expr = malloc(sizeof(*expr)); if (!expr) return NULL; memset(expr, 0, sizeof(*expr)); fy_path_expr_list_init(&expr->children); return expr; } void fy_path_expr_free(struct fy_path_expr *expr) { struct fy_path_expr *exprn; if (!expr) return; while ((exprn = fy_path_expr_list_pop(&expr->children)) != NULL) fy_path_expr_free(exprn); fy_token_unref(expr->fyt); free(expr); } struct fy_path_expr *fy_path_expr_alloc_recycle(struct fy_path_parser *fypp) { struct fy_path_expr *expr; if (!fypp || fypp->suppress_recycling) return fy_path_expr_alloc(); expr = fy_path_expr_list_pop(&fypp->expr_recycle); if (expr) return expr; return fy_path_expr_alloc(); } void fy_path_expr_free_recycle(struct fy_path_parser *fypp, struct fy_path_expr *expr) { struct fy_path_expr *exprn; if (!fypp || fypp->suppress_recycling) { fy_path_expr_free(expr); return; } while ((exprn = fy_path_expr_list_pop(&expr->children)) != NULL) fy_path_expr_free_recycle(fypp, exprn); if (expr->fyt) { fy_token_unref(expr->fyt); expr->fyt = NULL; } fy_path_expr_list_add_tail(&fypp->expr_recycle, expr); } const char *path_expr_type_txt[] = { [fpet_none] = "none", /* */ [fpet_root] = "root", [fpet_this] = "this", [fpet_parent] = "parent", [fpet_every_child] = "every-child", [fpet_every_child_r] = "every-child-recursive", [fpet_filter_collection] = "assert-collection", [fpet_filter_scalar] = "assert-scalar", [fpet_filter_sequence] = "assert-sequence", [fpet_filter_mapping] = "assert-mapping", [fpet_seq_index] = "seq-index", [fpet_seq_slice] = "seq-slice", [fpet_alias] = "alias", [fpet_map_key] = "map-key", [fpet_multi] = "multi", [fpet_chain] = "chain", [fpet_logical_or] = "logical-or", [fpet_logical_and] = "logical-and", }; bool fy_token_type_is_component_start(enum fy_token_type type) { return type == FYTT_PE_ROOT || type == FYTT_PE_THIS || type == FYTT_PE_PARENT || type == FYTT_PE_MAP_KEY || type == FYTT_PE_SEQ_INDEX || type == FYTT_PE_SEQ_SLICE || type == FYTT_PE_EVERY_CHILD || type == FYTT_PE_EVERY_CHILD_R || type == FYTT_PE_ALIAS; } bool fy_token_type_next_slash_is_root(enum fy_token_type type) { return type == FYTT_NONE || type == FYTT_STREAM_START || type == FYTT_PE_BARBAR || type == FYTT_PE_AMPAMP || type == FYTT_PE_LPAREN; } bool fy_token_type_is_filter(enum fy_token_type type) { return type == FYTT_PE_SCALAR_FILTER || type == FYTT_PE_COLLECTION_FILTER || type == FYTT_PE_SEQ_FILTER || type == FYTT_PE_MAP_FILTER; } static struct fy_diag *fy_path_parser_reader_get_diag(struct fy_reader *fyr) { struct fy_path_parser *fypp = container_of(fyr, struct fy_path_parser, reader); return fypp->cfg.diag; } static const struct fy_reader_ops fy_path_parser_reader_ops = { .get_diag = fy_path_parser_reader_get_diag, }; void fy_path_parser_setup(struct fy_path_parser *fypp, const struct fy_path_parse_cfg *pcfg) { if (!fypp) return; memset(fypp, 0, sizeof(*fypp)); if (pcfg) fypp->cfg = *pcfg; fy_reader_setup(&fypp->reader, &fy_path_parser_reader_ops); fy_token_list_init(&fypp->queued_tokens); fypp->last_queued_token_type = FYTT_NONE; /* use the static stack at first, faster */ fypp->operators = fypp->operators_static; fypp->operands = fypp->operands_static; fypp->operator_alloc = ARRAY_SIZE(fypp->operators_static); fypp->operand_alloc = ARRAY_SIZE(fypp->operands_static); fy_path_expr_list_init(&fypp->expr_recycle); fypp->suppress_recycling = (fypp->cfg.flags & FYPPCF_DISABLE_RECYCLING) || getenv("FY_VALGRIND"); } void fy_path_parser_cleanup(struct fy_path_parser *fypp) { struct fy_path_expr *expr; struct fy_token *fyt; if (!fypp) return; while (fypp->operator_top > 0) { fyt = fypp->operators[--fypp->operator_top]; fypp->operators[fypp->operator_top] = NULL; fy_token_unref(fyt); } if (fypp->operators != fypp->operators_static) free(fypp->operators); fypp->operators = fypp->operators_static; fypp->operator_alloc = ARRAY_SIZE(fypp->operators_static); while (fypp->operand_top > 0) { expr = fypp->operands[--fypp->operand_top]; fypp->operands[fypp->operand_top] = NULL; fy_path_expr_free(expr); } if (fypp->operands != fypp->operands_static) free(fypp->operands); fypp->operands = fypp->operands_static; fypp->operand_alloc = ARRAY_SIZE(fypp->operands_static); fy_reader_cleanup(&fypp->reader); fy_token_list_unref_all(&fypp->queued_tokens); while ((expr = fy_path_expr_list_pop(&fypp->expr_recycle)) != NULL) fy_path_expr_free(expr); fypp->last_queued_token_type = FYTT_NONE; } int fy_path_parser_open(struct fy_path_parser *fypp, struct fy_input *fyi, const struct fy_reader_input_cfg *icfg) { if (!fypp) return -1; return fy_reader_input_open(&fypp->reader, fyi, icfg); } void fy_path_parser_close(struct fy_path_parser *fypp) { if (!fypp) return; fy_reader_input_done(&fypp->reader); } struct fy_token *fy_path_token_vqueue(struct fy_path_parser *fypp, enum fy_token_type type, va_list ap) { struct fy_token *fyt; fyt = fy_token_list_vqueue(&fypp->queued_tokens, type, ap); if (fyt) { fypp->token_activity_counter++; fypp->last_queued_token_type = type; } return fyt; } struct fy_token *fy_path_token_queue(struct fy_path_parser *fypp, enum fy_token_type type, ...) { va_list ap; struct fy_token *fyt; va_start(ap, type); fyt = fy_path_token_vqueue(fypp, type, ap); va_end(ap); return fyt; } int fy_path_fetch_seq_index_or_slice(struct fy_path_parser *fypp, int c) { struct fy_reader *fyr; struct fy_token *fyt; bool neg; int i, j, val, nval, digits, indices[2]; fyr = &fypp->reader; /* verify that the called context is correct */ assert(fy_is_num(c) || (c == '-' && fy_is_num(fy_reader_peek_at(fyr, 1)))); i = 0; indices[0] = indices[1] = -1; j = 0; while (j < 2) { neg = false; if (c == '-') { neg = true; i++; } digits = 0; val = 0; while (fy_is_num((c = fy_reader_peek_at(fyr, i)))) { nval = (val * 10) | (c - '0'); FYR_PARSE_ERROR_CHECK(fyr, 0, i, FYEM_SCAN, nval >= val && nval >= 0, err_out, "illegal sequence index (overflow)"); val = nval; i++; digits++; } FYR_PARSE_ERROR_CHECK(fyr, 0, i, FYEM_SCAN, (val == 0 && digits == 1) || (val > 0), err_out, "bad number"); if (neg) val = -val; indices[j] = val; /* continue only on slice : */ if (c == ':') { c = fy_reader_peek_at(fyr, i + 1); if (fy_is_num(c) || (c == '-' && fy_is_num(fy_reader_peek_at(fyr, i + 2)))) { i++; j++; continue; } } break; } if (j >= 1) fyt = fy_path_token_queue(fypp, FYTT_PE_SEQ_SLICE, fy_reader_fill_atom_a(fyr, i), indices[0], indices[1]); else fyt = fy_path_token_queue(fypp, FYTT_PE_SEQ_INDEX, fy_reader_fill_atom_a(fyr, i), indices[0]); fyr_error_check(fyr, fyt, err_out, "fy_path_token_queue() failed\n"); return 0; err_out: fypp->stream_error = true; return -1; } int fy_path_fetch_simple_map_key(struct fy_path_parser *fypp, int c) { struct fy_reader *fyr; struct fy_token *fyt; int i; fyr = &fypp->reader; /* verify that the called context is correct */ assert(fy_is_first_alpha(c)); i = 1; while (fy_is_alnum(fy_reader_peek_at(fyr, i))) i++; /* document is NULL, is a simple key */ fyt = fy_path_token_queue(fypp, FYTT_PE_MAP_KEY, fy_reader_fill_atom_a(fyr, i), NULL); fyr_error_check(fyr, fyt, err_out, "fy_path_token_queue() failed\n"); return 0; err_out: fypp->stream_error = true; return -1; } int fy_path_fetch_flow_map_key(struct fy_path_parser *fypp, int c) { struct fy_reader *fyr; struct fy_token *fyt; struct fy_document *fyd; struct fy_atom handle; struct fy_parser fyp_data, *fyp = &fyp_data; struct fy_parse_cfg cfg_data, *cfg = NULL; int rc; fyr = &fypp->reader; /* verify that the called context is correct */ assert(fy_is_path_flow_key_start(c)); fy_reader_fill_atom_start(fyr, &handle); cfg = &cfg_data; memset(cfg, 0, sizeof(*cfg)); cfg->flags = FYPCF_DEFAULT_PARSE; cfg->diag = fypp->cfg.diag; rc = fy_parse_setup(fyp, cfg); fyr_error_check(fyr, !rc, err_out, "fy_parse_setup() failed\n"); /* associate with reader and set flow mode */ fy_parser_set_reader(fyp, fyr); fy_parser_set_flow_only_mode(fyp, true); fyd = fy_parse_load_document(fyp); /* cleanup the parser no matter what */ fy_parse_cleanup(fyp); fyr_error_check(fyr, fyd, err_out, "fy_parse_load_document() failed\n"); fy_reader_fill_atom_end(fyr, &handle); /* document is NULL, is a simple key */ fyt = fy_path_token_queue(fypp, FYTT_PE_MAP_KEY, &handle, fyd); fyr_error_check(fyr, fyt, err_out, "fy_path_token_queue() failed\n"); return 0; err_out: fypp->stream_error = true; return -1; } int fy_path_fetch_tokens(struct fy_path_parser *fypp) { enum fy_token_type type; struct fy_token *fyt; struct fy_reader *fyr; int c, rc, simple_token_count; fyr = &fypp->reader; if (!fypp->stream_start_produced) { fyt = fy_path_token_queue(fypp, FYTT_STREAM_START, fy_reader_fill_atom_a(fyr, 0)); fyr_error_check(fyr, fyt, err_out, "fy_path_token_queue() failed\n"); fypp->stream_start_produced = true; return 0; } /* XXX scan to next token? */ c = fy_reader_peek(fyr); if (fy_is_z(c)) { if (c >= 0) fy_reader_advance(fyr, c); /* produce stream end continuously */ fyt = fy_path_token_queue(fypp, FYTT_STREAM_END, fy_reader_fill_atom_a(fyr, 0)); fyr_error_check(fyr, fyt, err_out, "fy_path_token_queue() failed\n"); return 0; } fyt = NULL; type = FYTT_NONE; simple_token_count = 0; switch (c) { case '/': type = FYTT_PE_SLASH; simple_token_count = 1; break; case '^': type = FYTT_PE_ROOT; simple_token_count = 1; break; case ':': type = FYTT_PE_SIBLING; simple_token_count = 1; break; case '$': type = FYTT_PE_SCALAR_FILTER; simple_token_count = 1; break; case '%': type = FYTT_PE_COLLECTION_FILTER; simple_token_count = 1; break; case '[': if (fy_reader_peek_at(fyr, 1) == ']') { type = FYTT_PE_SEQ_FILTER; simple_token_count = 2; } break; case '{': if (fy_reader_peek_at(fyr, 1) == '}') { type = FYTT_PE_MAP_FILTER; simple_token_count = 2; } break; case ',': type = FYTT_PE_COMMA; simple_token_count = 1; break; case '.': if (fy_reader_peek_at(fyr, 1) == '.') { type = FYTT_PE_PARENT; simple_token_count = 2; } else { type = FYTT_PE_THIS; simple_token_count = 1; } break; case '*': if (fy_reader_peek_at(fyr, 1) == '*') { type = FYTT_PE_EVERY_CHILD_R; simple_token_count = 2; } else if (!fy_is_first_alpha(fy_reader_peek_at(fyr, 1))) { type = FYTT_PE_EVERY_CHILD; simple_token_count = 1; } else { type = FYTT_PE_ALIAS; simple_token_count = 2; while (fy_is_alnum(fy_reader_peek_at(fyr, simple_token_count))) simple_token_count++; } break; case '|': if (fy_reader_peek_at(fyr, 1) == '|') { type = FYTT_PE_BARBAR; simple_token_count = 2; break; } break; case '&': if (fy_reader_peek_at(fyr, 1) == '&') { type = FYTT_PE_AMPAMP; simple_token_count = 2; break; } break; case '(': type = FYTT_PE_LPAREN; simple_token_count = 1; break; case ')': type = FYTT_PE_RPAREN; simple_token_count = 1; break; default: break; } /* simple tokens */ if (simple_token_count > 0) { fyt = fy_path_token_queue(fypp, type, fy_reader_fill_atom_a(fyr, simple_token_count)); fyr_error_check(fyr, fyt, err_out, "fy_path_token_queue() failed\n"); return 0; } if (fy_is_first_alpha(c)) return fy_path_fetch_simple_map_key(fypp, c); if (fy_is_path_flow_key_start(c)) return fy_path_fetch_flow_map_key(fypp, c); if (fy_is_num(c) || (c == '-' && fy_is_num(fy_reader_peek_at(fyr, 1)))) return fy_path_fetch_seq_index_or_slice(fypp, c); FYR_PARSE_ERROR(fyr, 0, 1, FYEM_SCAN, "bad path expression starts here"); err_out: fypp->stream_error = true; rc = -1; return rc; } struct fy_token *fy_path_scan_peek(struct fy_path_parser *fypp, struct fy_token *fyt_prev) { struct fy_token *fyt; struct fy_reader *fyr; int rc, last_token_activity_counter; fyr = &fypp->reader; /* nothing if stream end produced (and no stream end token in queue) */ if (!fyt_prev && fypp->stream_end_produced && fy_token_list_empty(&fypp->queued_tokens)) { fyt = fy_token_list_head(&fypp->queued_tokens); if (fyt && fyt->type == FYTT_STREAM_END) return fyt; return NULL; } for (;;) { if (!fyt_prev) fyt = fy_token_list_head(&fypp->queued_tokens); else fyt = fy_token_next(&fypp->queued_tokens, fyt_prev); if (fyt) break; /* on stream error we're done */ if (fypp->stream_error) return NULL; /* keep track of token activity, if it didn't change * after the fetch tokens call, the state machine is stuck */ last_token_activity_counter = fypp->token_activity_counter; /* fetch more then */ rc = fy_path_fetch_tokens(fypp); if (rc) { fy_error(fypp->cfg.diag, "fy_path_fetch_tokens() failed\n"); goto err_out; } if (last_token_activity_counter == fypp->token_activity_counter) { fy_error(fypp->cfg.diag, "out of tokens and failed to produce anymore"); goto err_out; } } switch (fyt->type) { case FYTT_STREAM_START: fypp->stream_start_produced = true; break; case FYTT_STREAM_END: fypp->stream_end_produced = true; rc = fy_reader_input_done(fyr); if (rc) { fy_error(fypp->cfg.diag, "fy_parse_input_done() failed"); goto err_out; } break; default: break; } return fyt; err_out: return NULL; } struct fy_token *fy_path_scan_remove(struct fy_path_parser *fypp, struct fy_token *fyt) { if (!fypp || !fyt) return NULL; fy_token_list_del(&fypp->queued_tokens, fyt); return fyt; } struct fy_token *fy_path_scan_remove_peek(struct fy_path_parser *fypp, struct fy_token *fyt) { fy_token_unref(fy_path_scan_remove(fypp, fyt)); return fy_path_scan_peek(fypp, NULL); } struct fy_token *fy_path_scan(struct fy_path_parser *fypp) { return fy_path_scan_remove(fypp, fy_path_scan_peek(fypp, NULL)); } void fy_path_expr_dump(struct fy_path_expr *expr, struct fy_diag *diag, enum fy_error_type errlevel, int level, const char *banner) { struct fy_path_expr *expr2; const char *text; size_t len; bool save_on_error; if (errlevel < diag->cfg.level) return; save_on_error = diag->on_error; diag->on_error = true; if (banner) fy_diag_diag(diag, errlevel, "%-*s%s", level*2, "", banner); text = fy_token_get_text(expr->fyt, &len); fy_diag_diag(diag, errlevel, "> %-*s%s%s%.*s", level*2, "", path_expr_type_txt[expr->type], len ? " " : "", (int)len, text); for (expr2 = fy_path_expr_list_head(&expr->children); expr2; expr2 = fy_path_expr_next(&expr->children, expr2)) fy_path_expr_dump(expr2, diag, errlevel, level + 1, NULL); diag->on_error = save_on_error; } enum fy_path_expr_type fy_map_token_to_path_expr_type(enum fy_token_type type) { switch (type) { case FYTT_PE_ROOT: return fpet_root; case FYTT_PE_THIS: return fpet_this; case FYTT_PE_PARENT: case FYTT_PE_SIBLING: /* sibling maps to a chain of fpet_parent */ return fpet_parent; case FYTT_PE_MAP_KEY: return fpet_map_key; case FYTT_PE_SEQ_INDEX: return fpet_seq_index; case FYTT_PE_SEQ_SLICE: return fpet_seq_slice; case FYTT_PE_EVERY_CHILD: return fpet_every_child; case FYTT_PE_EVERY_CHILD_R: return fpet_every_child_r; case FYTT_PE_ALIAS: return fpet_alias; case FYTT_PE_SCALAR_FILTER: return fpet_filter_scalar; case FYTT_PE_COLLECTION_FILTER: return fpet_filter_collection; case FYTT_PE_SEQ_FILTER: return fpet_filter_sequence; case FYTT_PE_MAP_FILTER: return fpet_filter_mapping; case FYTT_PE_COMMA: return fpet_multi; case FYTT_PE_SLASH: return fpet_chain; case FYTT_PE_BARBAR: return fpet_logical_or; case FYTT_PE_AMPAMP: return fpet_logical_and; default: /* note parentheses do not have an expression */ break; } return fpet_none; } bool fy_token_type_is_operand(enum fy_token_type type) { return type == FYTT_PE_ROOT || type == FYTT_PE_THIS || type == FYTT_PE_PARENT || type == FYTT_PE_MAP_KEY || type == FYTT_PE_SEQ_INDEX || type == FYTT_PE_SEQ_SLICE || type == FYTT_PE_EVERY_CHILD || type == FYTT_PE_EVERY_CHILD_R || type == FYTT_PE_ALIAS; } bool fy_token_type_is_operator(enum fy_token_type type) { return type == FYTT_PE_SLASH || type == FYTT_PE_SCALAR_FILTER || type == FYTT_PE_COLLECTION_FILTER || type == FYTT_PE_SEQ_FILTER || type == FYTT_PE_MAP_FILTER || type == FYTT_PE_SIBLING || type == FYTT_PE_COMMA || type == FYTT_PE_BARBAR || type == FYTT_PE_AMPAMP || type == FYTT_PE_LPAREN || type == FYTT_PE_RPAREN; } bool fy_token_type_is_operand_or_operator(enum fy_token_type type) { return fy_token_type_is_operand(type) || fy_token_type_is_operator(type); } int fy_token_type_operator_prec(enum fy_token_type type) { switch (type) { case FYTT_PE_SLASH: return 10; case FYTT_PE_SCALAR_FILTER: case FYTT_PE_COLLECTION_FILTER: case FYTT_PE_SEQ_FILTER: case FYTT_PE_MAP_FILTER: return 5; case FYTT_PE_SIBLING: return 20; case FYTT_PE_COMMA: return 15; case FYTT_PE_BARBAR: case FYTT_PE_AMPAMP: return 4; case FYTT_PE_LPAREN: case FYTT_PE_RPAREN: return 30; default: break; } return -1; } #if 0 static void dump_operator_stack(struct fy_path_parser *fypp) { struct fy_token *fyt; unsigned int i; if (!fypp->operator_top) return; i = fypp->operator_top; do { fyt = fypp->operators[--i]; fy_notice(fypp->cfg.diag, "! [%d] %.*s (%2d)\n", i, 20, fy_token_debug_text_a(fyt), fy_token_type_operator_prec(fyt->type)); } while (i > 0); } static void dump_operand_stack(struct fy_path_parser *fypp) { struct fy_path_expr *expr; unsigned int i; if (!fypp->operand_top) return; i = fypp->operand_top; do { expr = fypp->operands[--i]; fy_path_expr_dump(fypp, expr, 0, NULL); } while (i > 0); } #endif static int push_operand(struct fy_path_parser *fypp, struct fy_path_expr *expr) { struct fy_path_expr **exprs; unsigned int alloc; size_t size; /* grow the stack if required */ if (fypp->operand_top >= fypp->operand_alloc) { alloc = fypp->operand_alloc; size = alloc * sizeof(*exprs); if (fypp->operands == fypp->operands_static) { exprs = malloc(size * 2); if (exprs) memcpy(exprs, fypp->operands_static, size); } else exprs = realloc(fypp->operands, size * 2); if (!exprs) return -1; fypp->operand_alloc = alloc * 2; fypp->operands = exprs; } fypp->operands[fypp->operand_top++] = expr; return 0; } static struct fy_path_expr * peek_operand_at(struct fy_path_parser *fypp, unsigned int pos) { if (fypp->operand_top <= pos) return NULL; return fypp->operands[fypp->operand_top - 1 - pos]; } static struct fy_path_expr * peek_operand(struct fy_path_parser *fypp) { if (fypp->operand_top == 0) return NULL; return fypp->operands[fypp->operand_top - 1]; } static struct fy_path_expr * pop_operand(struct fy_path_parser *fypp) { struct fy_path_expr *expr; if (fypp->operand_top == 0) return NULL; expr = fypp->operands[--fypp->operand_top]; fypp->operands[fypp->operand_top] = NULL; return expr; } static struct fy_token * peek_operator(struct fy_path_parser *fypp) { if (fypp->operator_top == 0) return NULL; return fypp->operators[fypp->operator_top - 1]; } static int push_operator(struct fy_path_parser *fypp, struct fy_token *fyt) { struct fy_token **fyts; unsigned int alloc; size_t size; assert(fy_token_type_is_operator(fyt->type)); /* grow the stack if required */ if (fypp->operator_top >= fypp->operator_alloc) { alloc = fypp->operator_alloc; size = alloc * sizeof(*fyts); if (fypp->operators == fypp->operators_static) { fyts = malloc(size * 2); if (fyts) memcpy(fyts, fypp->operators_static, size); } else fyts = realloc(fypp->operators, size * 2); if (!fyts) return -1; fypp->operator_alloc = alloc * 2; fypp->operators = fyts; } fypp->operators[fypp->operator_top++] = fyt; return 0; } static struct fy_token * pop_operator(struct fy_path_parser *fypp) { struct fy_token *fyt; if (fypp->operator_top == 0) return NULL; fyt = fypp->operators[--fypp->operator_top]; fypp->operators[fypp->operator_top] = NULL; return fyt; } #define PREFIX 0 #define INFIX 1 #define SUFFIX 2 int fy_token_type_operator_placement(enum fy_token_type type) { switch (type) { case FYTT_PE_SLASH: /* SLASH is special at the start of the expression */ case FYTT_PE_COMMA: case FYTT_PE_BARBAR: case FYTT_PE_AMPAMP: return INFIX; case FYTT_PE_SCALAR_FILTER: case FYTT_PE_COLLECTION_FILTER: case FYTT_PE_SEQ_FILTER: case FYTT_PE_MAP_FILTER: return SUFFIX; case FYTT_PE_SIBLING: return PREFIX; default: break; } return -1; } const struct fy_mark *fy_path_expr_start_mark(struct fy_path_expr *expr) { struct fy_path_expr *exprn; if (!expr) return NULL; if (!fy_path_expr_type_is_parent(expr->type)) return fy_token_start_mark(expr->fyt); exprn = fy_path_expr_list_head(&expr->children); if (!exprn) return NULL; return fy_path_expr_start_mark(exprn); } const struct fy_mark *fy_path_expr_end_mark(struct fy_path_expr *expr) { struct fy_path_expr *exprn; if (!expr) return NULL; if (!fy_path_expr_type_is_parent(expr->type)) return fy_token_end_mark(expr->fyt); exprn = fy_path_expr_list_tail(&expr->children); if (!exprn) return NULL; return fy_path_expr_end_mark(exprn); } #if 0 static struct fy_token * expr_to_token_mark(struct fy_path_expr *expr, struct fy_input *fyi) { const struct fy_mark *ms, *me; struct fy_atom handle; ms = fy_path_expr_start_mark(expr); me = fy_path_expr_end_mark(expr); assert(ms); assert(me); memset(&handle, 0, sizeof(handle)); handle.start_mark = *ms; handle.end_mark = *me; handle.fyi = fyi; handle.style = FYAS_PLAIN; handle.chomp = FYAC_CLIP; return fy_token_create(FYTT_INPUT_MARKER, &handle); } #endif static bool expr_is_before_token(struct fy_path_expr *expr, struct fy_token *fyt) { const struct fy_mark *me, *mt; if (!expr || !fyt) return false; me = fy_path_expr_end_mark(expr); if (!me) return false; mt = fy_token_start_mark(fyt); if (!mt) return false; return me->input_pos <= mt->input_pos; } static bool expr_is_after_token(struct fy_path_expr *expr, struct fy_token *fyt) { const struct fy_mark *me, *mt; if (!expr || !fyt) return false; me = fy_path_expr_start_mark(expr); if (!me) return false; mt = fy_token_end_mark(fyt); if (!mt) return false; return me->input_pos >= mt->input_pos; } static int evaluate(struct fy_path_parser *fypp) { struct fy_reader *fyr; struct fy_token *fyt_top = NULL, *fyt_peek; #if 0 struct fy_token *fyt_markl, *fyt_markr; #endif struct fy_path_expr *exprl = NULL, *exprr = NULL, *chain = NULL, *expr = NULL; struct fy_path_expr *parent = NULL; enum fy_path_expr_type etype; int ret; fyr = &fypp->reader; fyt_top = pop_operator(fypp); fyr_error_check(fyr, fyt_top, err_out, "pop_operator() failed to find token operator to evaluate\n"); exprl = NULL; exprr = NULL; switch (fyt_top->type) { case FYTT_PE_SLASH: /* dump_operand_stack(fypp); */ /* dump_operator_stack(fypp); */ /* try to figure out if this slash is the root or a chain operator */ exprr = peek_operand(fypp); exprl = peek_operand_at(fypp, 1); fyt_peek = peek_operator(fypp); /* remove expressions that are before this */ if (fyt_peek && fy_token_type_next_slash_is_root(fyt_peek->type)) { if (exprr && expr_is_before_token(exprr, fyt_peek)) { /* fyr_notice(fyr, "exprr before token, removing from scan\n"); */ exprr = NULL; } if (exprl && expr_is_before_token(exprl, fyt_peek)) { /* fyr_notice(fyr, "exprl before token, removing from scan\n"); */ exprl = NULL; } } if (exprr && !exprl && expr_is_before_token(exprr, fyt_top)) { /* fyr_notice(fyr, "exprl == NULL && exprr before token, means it's at the left\n"); */ exprl = exprr; exprr = NULL; } if (exprl && !exprr && expr_is_after_token(exprl, fyt_top)) { /* fyr_notice(fyr, "exprr == NULL && exprl after token, means it's at the right\n"); */ exprl = exprr; exprr = NULL; } #if 0 fyt_markl = NULL; fyt_markr = NULL; if (exprr) { fyt_markr = expr_to_token_mark(exprr, fyt_top->handle.fyi); assert(fyt_markr); } if (exprl) { fyt_markl = expr_to_token_mark(exprl, fyt_top->handle.fyi); assert(fyt_markl); } FYR_TOKEN_DIAG(fyr, fyt_top, FYDF_NOTICE, FYEM_PARSE, "location of fyt_top"); if (fyt_peek) { FYR_TOKEN_DIAG(fyr, fyt_peek, FYDF_NOTICE, FYEM_PARSE, "location of fyt_peek"); } else fyr_notice(fyr, "fyt_peek=<NULL>\n"); if (fyt_markl) FYR_TOKEN_DIAG(fyr, fyt_markl, FYDF_NOTICE, FYEM_PARSE, "location of exprl"); if (fyt_markr) FYR_TOKEN_DIAG(fyr, fyt_markr, FYDF_NOTICE, FYEM_PARSE, "location of exprr"); fy_token_unref(fyt_markl); fy_token_unref(fyt_markr); #endif if (exprl && exprr) { // fyr_notice(fyr, "CHAIN operator\n"); etype = fpet_chain; goto do_infix; } if (exprl) { // fyr_notice(fyr, "COLLECTION operator\n"); etype = fpet_filter_collection; goto do_suffix; } if (exprr) { // fyr_notice(fyr, "ROOT operator (with arguments)\n"); etype = fpet_root; goto do_prefix; } // fyr_notice(fyr, "ROOT value (with no arguments)\n"); exprr = fy_path_expr_alloc_recycle(fypp); fyr_error_check(fyr, exprr, err_out, "fy_path_expr_alloc_recycle() failed\n"); exprr->type = fpet_root; exprr->fyt = fyt_top; fyt_top = NULL; ret = push_operand(fypp, exprr); fyr_error_check(fyr, !ret, err_out, "push_operand() failed\n"); exprr = NULL; break; case FYTT_PE_SIBLING: /* get mapping expression type */ etype = fy_map_token_to_path_expr_type(fyt_top->type); do_prefix: exprr = pop_operand(fypp); FYR_TOKEN_ERROR_CHECK(fyr, fyt_top, FYEM_PARSE, exprr, err_out, "sibling operator without argument"); if (fyt_top->type == FYTT_PE_SIBLING) { FYR_TOKEN_ERROR_CHECK(fyr, fyt_top, FYEM_PARSE, exprr->fyt && exprr->fyt->type == FYTT_PE_MAP_KEY, err_out, "sibling operator on non-map key"); } /* chaining */ chain = fy_path_expr_alloc_recycle(fypp); fyr_error_check(fyr, chain, err_out, "fy_path_expr_alloc_recycle() failed\n"); chain->type = fpet_chain; chain->fyt = NULL; exprl = fy_path_expr_alloc_recycle(fypp); fyr_error_check(fyr, exprl, err_out, "fy_path_expr_alloc_recycle() failed\n"); exprl->type = etype; exprl->fyt = fyt_top; fyt_top = NULL; fy_path_expr_list_add_tail(&chain->children, exprl); exprl = NULL; fy_path_expr_list_add_tail(&chain->children, exprr); exprr = NULL; ret = push_operand(fypp, chain); fyr_error_check(fyr, !ret, err_out, "push_operand() failed\n"); chain = NULL; break; case FYTT_PE_COMMA: case FYTT_PE_BARBAR: case FYTT_PE_AMPAMP: /* get mapping expression type */ etype = fy_map_token_to_path_expr_type(fyt_top->type); do_infix: /* verify we got one */ assert(etype != fpet_none); /* and that it's one with children */ assert(fy_path_expr_type_is_parent(etype)); exprr = pop_operand(fypp); FYR_TOKEN_ERROR_CHECK(fyr, fyt_top, FYEM_PARSE, exprr, err_out, "operator without operands (rhs)"); exprl = pop_operand(fypp); FYR_TOKEN_ERROR_CHECK(fyr, fyt_top, FYEM_PARSE, exprl, err_out, "operator without operands (lhs)"); /* optimize parent */ if (exprl->type != etype) { /* parent */ parent = fy_path_expr_alloc_recycle(fypp); fyr_error_check(fyr, parent, err_out, "fy_path_expr_alloc_recycle() failed\n"); parent->type = etype; parent->fyt = fyt_top; fyt_top = NULL; fy_path_expr_list_add_tail(&parent->children, exprl); exprl = NULL; } else { /* reuse lhs */ parent = exprl; exprl = NULL; } if (exprr->type != etype) { /* not the same type, append */ fy_path_expr_list_add_tail(&parent->children, exprr); exprr = NULL; } else { /* move the contents of the chain */ while ((expr = fy_path_expr_list_pop(&exprr->children)) != NULL) fy_path_expr_list_add_tail(&parent->children, expr); fy_path_expr_free_recycle(fypp, exprr); exprr = NULL; } ret = push_operand(fypp, parent); fyr_error_check(fyr, !ret, err_out, "push_operand() failed\n"); parent = NULL; fy_token_unref(fyt_top); fyt_top = NULL; break; case FYTT_PE_SCALAR_FILTER: case FYTT_PE_COLLECTION_FILTER: case FYTT_PE_SEQ_FILTER: case FYTT_PE_MAP_FILTER: etype = fy_map_token_to_path_expr_type(fyt_top->type); do_suffix: exprl = pop_operand(fypp); FYR_TOKEN_ERROR_CHECK(fyr, fyt_top, FYEM_PARSE, exprl, err_out, "filter operator without argument"); if (exprl->type != fpet_chain) { /* chaining */ chain = fy_path_expr_alloc_recycle(fypp); fyr_error_check(fyr, chain, err_out, "fy_path_expr_alloc_recycle() failed\n"); chain->type = fpet_chain; chain->fyt = NULL; fy_path_expr_list_add_tail(&chain->children, exprl); exprl = NULL; } else { chain = exprl; exprl = NULL; } exprr = fy_path_expr_alloc_recycle(fypp); fyr_error_check(fyr, exprr, err_out, "fy_path_expr_alloc_recycle() failed\n"); exprr->type = etype; exprr->fyt = fyt_top; fyt_top = NULL; fy_path_expr_list_add_tail(&chain->children, exprr); exprr = NULL; ret = push_operand(fypp, chain); fyr_error_check(fyr, !ret, err_out, "push_operand() failed\n"); chain = NULL; break; case FYTT_PE_LPAREN: FYR_TOKEN_ERROR(fyr, fyt_top, FYEM_PARSE, "Mismatched left parentheses"); goto err_out; case FYTT_PE_RPAREN: while ((fyt_peek = peek_operator(fypp)) != NULL) { if (fyt_peek->type == FYTT_PE_LPAREN) break; ret = evaluate(fypp); fyr_error_check(fyr, !ret, err_out, "evaluate() failed\n"); } FYR_TOKEN_ERROR_CHECK(fyr, fyt_top, FYEM_PARSE, fyt_peek, err_out, "Missing left parentheses"); FYR_TOKEN_ERROR_CHECK(fyr, fyt_peek, FYEM_PARSE, fyt_peek->type == FYTT_PE_LPAREN, err_out, "Mismatched right parentheses"); fy_token_unref(fyt_top); fyt_top = pop_operator(fypp); fy_token_unref(fyt_top); return 0; default: fyr_error(fyr, "Unknown token %s\n", fy_token_debug_text_a(fyt_top)); goto err_out; } return 0; err_out: fy_token_unref(fyt_top); fy_path_expr_free(exprl); fy_path_expr_free(exprr); fy_path_expr_free(chain); fy_path_expr_free(parent); // fy_notice(fypp->cfg.diag, "operator stack\n"); // dump_operator_stack(fypp); // fy_notice(fypp->cfg.diag, "operand stack\n"); // dump_operand_stack(fypp); return -1; } struct fy_path_expr * fy_path_parse_expression(struct fy_path_parser *fypp) { struct fy_reader *fyr; struct fy_token *fyt = NULL, *fyt_top = NULL; struct fy_path_expr *expr; int ret; /* the parser must be in the correct state */ if (!fypp || fypp->operator_top || fypp->operand_top) return NULL; fyr = &fypp->reader; /* find stream start */ fyt = fy_path_scan_peek(fypp, NULL); FYR_PARSE_ERROR_CHECK(fyr, 0, 1, FYEM_PARSE, fyt && fyt->type == FYTT_STREAM_START, err_out, "no tokens available or start without stream start"); /* remove stream start */ fy_token_unref(fy_path_scan_remove(fypp, fyt)); fyt = NULL; while ((fyt = fy_path_scan_peek(fypp, NULL)) != NULL) { if (fyt->type == FYTT_STREAM_END) break; // FYR_TOKEN_DIAG(fyr, fyt, FYET_NOTICE, FYEM_PARSE, "next token %s", fy_token_debug_text_a(fyt)); /* if it's an operand convert it to expression and push */ if (fy_token_type_is_operand(fyt->type)) { expr = fy_path_expr_alloc_recycle(fypp); fyr_error_check(fyr, expr, err_out, "fy_path_expr_alloc_recycle() failed\n"); expr->fyt = fy_path_scan_remove(fypp, fyt); expr->type = fy_map_token_to_path_expr_type(fyt->type); fyt = NULL; ret = push_operand(fypp, expr); fyr_error_check(fyr, !ret, err_out, "push_operand() failed\n"); expr = NULL; continue; } /* it's an operator */ for (;;) { /* get the top of the operator stack */ fyt_top = peek_operator(fypp); /* if operator stack is empty or the priority of the new operator is larger, push operator */ if (!fyt_top || fy_token_type_operator_prec(fyt->type) > fy_token_type_operator_prec(fyt_top->type) || fyt_top->type == FYTT_PE_LPAREN) { fyt = fy_path_scan_remove(fypp, fyt); ret = push_operator(fypp, fyt); fyt = NULL; fyr_error_check(fyr, !ret, err_out, "push_operator() failed\n"); break; } ret = evaluate(fypp); /* evaluate will print diagnostic on error */ if (ret) goto err_out; } } FYR_PARSE_ERROR_CHECK(fyr, 0, 1, FYEM_PARSE, fypp->stream_error || (fyt && fyt->type == FYTT_STREAM_END), err_out, "stream ended without STREAM_END"); while ((fyt_top = peek_operator(fypp)) != NULL) { ret = evaluate(fypp); /* evaluate will print diagnostic on error */ if (ret) goto err_out; } FYR_TOKEN_ERROR_CHECK(fyr, fyt, FYEM_PARSE, fypp->operand_top == 1, err_out, "invalid operand stack at end"); /* remove stream end */ fy_token_unref(fy_path_scan_remove(fypp, fyt)); fyt = NULL; /* and return the last operand */ return pop_operand(fypp); err_out: // fy_notice(fypp->cfg.diag, "operator stack\n"); // dump_operator_stack(fypp); // fy_notice(fypp->cfg.diag, "operand stack\n"); // dump_operand_stack(fypp); fypp->stream_error = true; return NULL; } static struct fy_node * fy_path_expr_execute_single_result(struct fy_diag *diag, struct fy_path_expr *expr, struct fy_node *fyn) { struct fy_token *fyt; struct fy_anchor *fya; const char *text; size_t len; assert(expr); switch (expr->type) { case fpet_root: return fyn->fyd->root; case fpet_this: return fyn; case fpet_parent: return fyn->parent; case fpet_alias: fyt = expr->fyt; assert(fyt); assert(fyt->type == FYTT_PE_ALIAS); text = fy_token_get_text(fyt, &len); if (!text || len < 1) break; if (*text == '*') { text++; len--; } fya = fy_document_lookup_anchor(fyn->fyd, text, len); if (!fya) break; return fya->fyn; case fpet_seq_index: fyt = expr->fyt; assert(fyt); assert(fyt->type == FYTT_PE_SEQ_INDEX); /* only on sequence */ if (!fy_node_is_sequence(fyn)) break; return fy_node_sequence_get_by_index(fyn, fyt->seq_index.index); case fpet_map_key: fyt = expr->fyt; assert(fyt); assert(fyt->type == FYTT_PE_MAP_KEY); if (!fyt->map_key.fyd) { /* simple key */ text = fy_token_get_text(fyt, &len); if (!text || len < 1) break; return fy_node_mapping_lookup_value_by_simple_key(fyn, text, len); } return fy_node_mapping_lookup_value_by_key(fyn, fyt->map_key.fyd->root); case fpet_filter_scalar: if (!(fy_node_is_scalar(fyn) || fy_node_is_alias(fyn))) break; return fyn; case fpet_filter_collection: if (!(fy_node_is_mapping(fyn) || fy_node_is_sequence(fyn))) break; return fyn; case fpet_filter_sequence: if (!fy_node_is_sequence(fyn)) break; return fyn; case fpet_filter_mapping: if (!fy_node_is_mapping(fyn)) break; return fyn; default: break; } return NULL; } /* returns true if the expression is chain or multi and contains only single * result expressions */ static bool expr_is_leaf_chain_or_multi(struct fy_path_expr *expr) { struct fy_path_expr *exprn; if (!expr || !fy_path_expr_type_is_parent(expr->type)) return false; for (exprn = fy_path_expr_list_head(&expr->children); exprn; exprn = fy_path_expr_next(&expr->children, exprn)) { if (!fy_path_expr_type_is_single_result(exprn->type)) return false; } /* all expressions single result */ return true; } int fy_path_expr_execute(struct fy_diag *diag, struct fy_path_expr *expr, struct fy_walk_result_list *results, struct fy_node *fyn) { struct fy_node *fynn, *fyni; struct fy_node_pair *fynp; struct fy_token *fyt; struct fy_path_expr *exprn; struct fy_walk_result *fwrn; struct fy_walk_result_list tresults, nresults; int start, end, count, i; /* error */ if (!expr || !results) return -1; /* no node, just return */ if (!fyn) return 0; /* single result case is common enough to optimize */ if (fy_path_expr_type_is_single_result(expr->type)) { fynn = fy_path_expr_execute_single_result(diag, expr, fyn); if (!fynn) return 0; return fy_walk_result_add(results, fynn); } /* handle the remaining multi result cases */ switch (expr->type) { case fpet_chain: /* check if it's a leaf chain (i.e. chain with single result expressions only) */ if (expr_is_leaf_chain_or_multi(expr)) { /* optimized single result chain */ for (exprn = fy_path_expr_list_head(&expr->children); exprn; exprn = fy_path_expr_next(&expr->children, exprn)) { assert(fy_path_expr_type_is_single_result(exprn->type)); fynn = fy_path_expr_execute_single_result(diag, exprn, fyn); if (!fynn) return 0; fyn = fynn; } return fy_walk_result_add(results, fyn); } /* start with tresults containing the current node */ fy_walk_result_list_init(&tresults); fy_walk_result_add(&tresults, fyn); /* iterate over each chain item */ for (exprn = fy_path_expr_list_head(&expr->children); exprn; exprn = fy_path_expr_next(&expr->children, exprn)) { /* nresults is the temp list collecting the results of each step */ fy_walk_result_list_init(&nresults); /* for every node in the tresults execute */ while ((fwrn = fy_walk_result_list_pop(&tresults)) != NULL) { fynn = fwrn->fyn; fy_walk_result_free(fwrn); fy_path_expr_execute(diag, exprn, &nresults, fynn); } /* move everything from nresults to tresults */ fy_walk_result_list_move(&tresults, &nresults); } /* move everything in tresuls to results */ fy_walk_result_list_move(results, &tresults); return 0; case fpet_multi: /* iterate over each chain item */ for (exprn = fy_path_expr_list_head(&expr->children); exprn; exprn = fy_path_expr_next(&expr->children, exprn)) { /* nresults is the temp list collecting the results of each step */ fy_walk_result_list_init(&nresults); fy_path_expr_execute(diag, exprn, &nresults, fyn); /* move everything in nresuls to results */ fy_walk_result_list_move(results, &nresults); } return 0; case fpet_every_child: /* every scalar/alias is a single result */ if (fy_node_is_scalar(fyn) || fy_node_is_alias(fyn)) { fy_walk_result_add(results, fyn); } else if (fy_node_is_sequence(fyn)) { for (fyni = fy_node_list_head(&fyn->sequence); fyni; fyni = fy_node_next(&fyn->sequence, fyni)) { fy_walk_result_add(results, fyni); } } else if (fy_node_is_mapping(fyn)) { for (fynp = fy_node_pair_list_head(&fyn->mapping); fynp; fynp = fy_node_pair_next(&fyn->mapping, fynp)) { fy_walk_result_add(results, fynp->value); } } else assert(0); return 0; case fpet_every_child_r: return fy_walk_result_add_recursive(results, fyn, false); case fpet_seq_slice: fyt = expr->fyt; assert(fyt); assert(fyt->type == FYTT_PE_SEQ_SLICE); /* only on sequence */ if (!fy_node_is_sequence(fyn)) return 0; start = fyt->seq_slice.start_index; end = fyt->seq_slice.end_index; count = fy_node_sequence_item_count(fyn); /* don't handle negative slices yet */ if (start < 0 || end < 1 || start >= end) return 0; if (count < end) end = count; for (i = start; i < end; i++) { fynn = fy_node_sequence_get_by_index(fyn, i); fy_walk_result_add(results, fynn); } return 0; case fpet_logical_or: /* iterate over each chain item */ for (exprn = fy_path_expr_list_head(&expr->children); exprn; exprn = fy_path_expr_next(&expr->children, exprn)) { /* nresults is the temp list collecting the results of each step */ fy_walk_result_list_init(&nresults); fy_path_expr_execute(diag, exprn, &nresults, fyn); /* the first non empty result ends */ if (!fy_walk_result_list_empty(&nresults)) { /* move everything in nresuls to results */ fy_walk_result_list_move(results, &nresults); break; } } return 0; case fpet_logical_and: /* last non null result */ fy_walk_result_list_init(&nresults); /* iterate over each chain item */ for (exprn = fy_path_expr_list_head(&expr->children); exprn; exprn = fy_path_expr_next(&expr->children, exprn)) { /* nresults is the temp list collecting the results of each step */ fy_walk_result_list_init(&tresults); fy_path_expr_execute(diag, exprn, &tresults, fyn); /* the first non empty result ends */ if (fy_walk_result_list_empty(&tresults)) break; /* free the previous results */ fy_walk_result_list_free(&nresults); /* move everything in tresuls to nresults */ fy_walk_result_list_move(&nresults, &tresults); } /* and move from nresults to results */ fy_walk_result_list_move(results, &nresults); return 0; default: break; } return -1; } int fy_path_exec_setup(struct fy_path_exec *fypx, const struct fy_path_exec_cfg *xcfg) { if (!fypx) return -1; memset(fypx, 0, sizeof(*fypx)); if (xcfg) fypx->cfg = *xcfg; fy_walk_result_list_init(&fypx->results); return 0; } void fy_path_exec_cleanup(struct fy_path_exec *fypx) { if (!fypx) return; fy_walk_result_list_free(&fypx->results); fypx->fyn_start = NULL; } /* publicly exported methods */ struct fy_path_parser *fy_path_parser_create(const struct fy_path_parse_cfg *pcfg) { struct fy_path_parser *fypp; fypp = malloc(sizeof(*fypp)); if (!fypp) return NULL; fy_path_parser_setup(fypp, pcfg); return fypp; } void fy_path_parser_destroy(struct fy_path_parser *fypp) { if (!fypp) return; fy_path_parser_cleanup(fypp); free(fypp); } int fy_path_parser_reset(struct fy_path_parser *fypp) { if (!fypp) return -1; fy_path_parser_cleanup(fypp); return 0; } struct fy_path_expr * fy_path_parse_expr_from_string(struct fy_path_parser *fypp, const char *str, size_t len) { struct fy_path_expr *expr = NULL; struct fy_input *fyi = NULL; int rc; if (!fypp || !str || !len) return NULL; fy_path_parser_reset(fypp); fyi = fy_input_from_data(str, len, NULL, false); if (!fyi) { fy_error(fypp->cfg.diag, "failed to create ypath input from %.*s\n", (int)len, str); goto err_out; } rc = fy_path_parser_open(fypp, fyi, NULL); if (rc) { fy_error(fypp->cfg.diag, "failed to open path parser input from %.*s\n", (int)len, str); goto err_out; } expr = fy_path_parse_expression(fypp); if (!expr) { fy_error(fypp->cfg.diag, "failed to parse path expression %.*s\n", (int)len, str); goto err_out; } fy_input_unref(fyi); return expr; err_out: fy_path_expr_free(expr); fy_input_unref(fyi); return NULL; } struct fy_path_expr * fy_path_expr_build_from_string(const struct fy_path_parse_cfg *pcfg, const char *str, size_t len) { struct fy_path_parser fypp_data, *fypp = &fypp_data; struct fy_path_expr *expr = NULL; if (!str) return NULL; fy_path_parser_setup(fypp, pcfg); expr = fy_path_parse_expr_from_string(fypp, str, len); fy_path_parser_cleanup(fypp); return expr; } struct fy_path_exec *fy_path_exec_create(const struct fy_path_exec_cfg *xcfg) { struct fy_path_exec *fypx; fypx = malloc(sizeof(*fypx)); if (!fypx) return NULL; fy_path_exec_setup(fypx, xcfg); return fypx; } void fy_path_exec_destroy(struct fy_path_exec *fypx) { if (!fypx) return; fy_path_exec_cleanup(fypx); free(fypx); } int fy_path_exec_reset(struct fy_path_exec *fypx) { if (!fypx) return -1; fy_path_exec_cleanup(fypx); return 0; } int fy_path_exec_execute(struct fy_path_exec *fypx, struct fy_path_expr *expr, struct fy_node *fyn_start) { int rc; if (!fypx || !expr || !fyn_start) return -1; fy_walk_result_list_free(&fypx->results); fypx->fyn_start = fyn_start; rc = fy_path_expr_execute(fypx->cfg.diag, expr, &fypx->results, fypx->fyn_start); if (rc) { fy_walk_result_list_free(&fypx->results); return rc; } return 0; } struct fy_node * fy_path_exec_results_iterate(struct fy_path_exec *fypx, void **prevp) { struct fy_walk_result *fwr; if (!fypx || !prevp) return NULL; if (!*prevp) fwr = fy_walk_result_list_head(&fypx->results); else fwr = fy_walk_result_next(&fypx->results, *prevp); *prevp = fwr; return fwr ? fwr->fyn : NULL; }
22.684866
131
0.697737
2cbdda2996da78770f434a78d3fef4166602d2fd
2,188
h
C
audio_app.h
crc32a/audio_app
3b645cf82032837c4856eca6936d258deedb8e54
[ "BSD-2-Clause" ]
null
null
null
audio_app.h
crc32a/audio_app
3b645cf82032837c4856eca6936d258deedb8e54
[ "BSD-2-Clause" ]
null
null
null
audio_app.h
crc32a/audio_app
3b645cf82032837c4856eca6936d258deedb8e54
[ "BSD-2-Clause" ]
null
null
null
#include<stdarg.h> #include<inttypes.h> #include"dft.h" #ifndef AUDIO_APP_H #define AUDIO_aPP_H typedef struct { char *from_file; char *to_file; char *tone_file; int ret; double amp; double freq; double phase; int sr; int64_t n; } thread_args; enum dtype { DTYPE_NONE, DTYPE_INT, DTYPE_FLOAT, DTYPE_DOUBLE, DTYPE_STR, DTYPE_I64 }; #endif int error_dialog(char *fmt, ...); void entry_to_variable(GtkEntry *e, void *var, enum dtype vtype); GtkWidget *get_widget(char *name); int dbgprintfimp(const char *fmt, va_list ap); int dbgprintf(const char *fmt, ...); int set_entry_text(GtkWidget *w, char *fmt, ...); int update_entrys(); int update_convert_entrys(); char *get_entry_text(char *buff, GtkWidget *entry); int init_globals(int argc, char **argv); gboolean error_dialog_idle(gpointer msg); gboolean stop_spinlock_idle(gpointer nop); int print_variables(); int is_toggled(GtkRadioButton *b); int get_filename_dialog(char *fname, char *dialog_title); int update_convert_labels(); int thread_args_init(thread_args **ta); int thread_args_destroy(thread_args *ta); // Signals void on_show_variables_button_clicked(GtkButton *b); void on_tone_save_button_clicked(GtkButton *b); void on_tone_amp_entry_changed(GtkEntry *e); void on_tone_freq_entry_changed(GtkEntry *e); void on_tone_phase_entry_changed(GtkEntry *e); void on_tone_sr_entry_changed(GtkEntry *e); void on_tone_secs_entry_changed(GtkEntry *e); void on_tone_combo_changed(GtkComboBoxText *c); void on_generate_tone_button_clicked(GtkButton *b); void on_wav2data_radio_toggled(GtkRadioButton *b); void on_data2wave_radio_toggled(GtkRadioButton *b); void on_convert_to_file_button_clicked(GtkButton *b); void on_convert_from_file_button_clicked(GtkButton *b); void on_convert_sample_rate_entry_changed(GtkEntry *e); void on_from_file_entry_changed(GtkEntry *e); void on_to_file_entry_changed(GtkEntry *e); void on_convert_file_button_clicked(GtkEntry *e); int start_spinlock(char *calling_func_name); int stop_spinlock(char *calling_func_name); // Thread workers void *save_to_wave(void *vargs); void *save_to_data(void *vargs); void *gensigcaller(void *); void *savetonecaller(void *);
31.257143
74
0.788848
c5a868ad4aba77acdab1c758a181bf50183d70e6
40
h
C
api/clilac.h
FigmentBoy/lilac
f3927d4725c9403a147d7fd38a57ac0da248fcfe
[ "MIT" ]
null
null
null
api/clilac.h
FigmentBoy/lilac
f3927d4725c9403a147d7fd38a57ac0da248fcfe
[ "MIT" ]
null
null
null
api/clilac.h
FigmentBoy/lilac
f3927d4725c9403a147d7fd38a57ac0da248fcfe
[ "MIT" ]
null
null
null
#pragma once #include "lilac/ctypes.h"
10
25
0.725
c5fcff4662afea36317803451f8f4f58017965c8
1,750
h
C
PathReconstruction/Widgets/DesignerPlugins/qSlicerPathReconstructionModuleWidgetsPlugin.h
tavaughan/SlicerPathReconstruction
5504e03ade1892e7c0186495c21e64ebf93d3cce
[ "MIT" ]
1
2019-04-18T15:00:05.000Z
2019-04-18T15:00:05.000Z
PathReconstruction/Widgets/DesignerPlugins/qSlicerPathReconstructionModuleWidgetsPlugin.h
tavaughan/SlicerPathReconstruction
5504e03ade1892e7c0186495c21e64ebf93d3cce
[ "MIT" ]
11
2018-03-24T16:06:06.000Z
2019-04-10T18:36:22.000Z
PathReconstruction/Widgets/DesignerPlugins/qSlicerPathReconstructionModuleWidgetsPlugin.h
tavaughan/SlicerPathReconstruction
5504e03ade1892e7c0186495c21e64ebf93d3cce
[ "MIT" ]
1
2018-04-02T14:00:33.000Z
2018-04-02T14:00:33.000Z
/*============================================================================== Copyright (c) Thomas Vaughan Laboratory for Percutaneous Surgery (PerkLab) Queen's University, Kingston, ON, Canada. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef __qSlicerPathReconstructionModuleWidgetsPlugin_h #define __qSlicerPathReconstructionModuleWidgetsPlugin_h #include "vtkSlicerConfigure.h" // For Slicer_HAVE_QT5 // Qt includes #ifdef Slicer_HAVE_QT5 #include <QtUiPlugin/QDesignerCustomWidgetCollectionInterface> #else #include <QDesignerCustomWidgetCollectionInterface> #endif #include "qSlicerPathReconstructionTableWidgetPlugin.h" // \class Group the plugins in one library class Q_SLICER_QTMODULES_PATHRECONSTRUCTION_WIDGETS_PLUGINS_EXPORT qSlicerPathReconstructionModuleWidgetsPlugin : public QObject , public QDesignerCustomWidgetCollectionInterface { Q_OBJECT #ifdef Slicer_HAVE_QT5 Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QDesignerCustomWidgetCollectionInterface") #endif Q_INTERFACES(QDesignerCustomWidgetCollectionInterface); public: QList<QDesignerCustomWidgetInterface*> customWidgets() const { QList<QDesignerCustomWidgetInterface *> plugins; plugins << new qSlicerPathReconstructionTableWidgetPlugin; return plugins; } }; #endif
33.018868
111
0.744
d079595cb7c96dce6f7877ce76650f87265299e5
2,896
h
C
eyefinder/CBlobPair.h
alexkuehn/sensbli
bad3fcb822b05766ac4e4d7c790ab4a2c83670ba
[ "BSD-3-Clause" ]
1
2016-06-13T11:52:17.000Z
2016-06-13T11:52:17.000Z
eyefinder/CBlobPair.h
alexkuehn/sensbli
bad3fcb822b05766ac4e4d7c790ab4a2c83670ba
[ "BSD-3-Clause" ]
null
null
null
eyefinder/CBlobPair.h
alexkuehn/sensbli
bad3fcb822b05766ac4e4d7c790ab4a2c83670ba
[ "BSD-3-Clause" ]
null
null
null
/* * cblobpair.h * This file is part of SENSBLI. * * Copyright (c) 2009 Alexander Kühn (prj@alexkuehn.de) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the project's author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef CBLOBPAIR_H_ #define CBLOBPAIR_H_ #include "../bloblib/Blob.h" #include "ovroi.h" class CBlobPair { friend class CBlinkSensorDebugger; public: CBlobPair(int index1, CBlob* blob1, int index2, CBlob* blob2, ovroi* actovroi); virtual ~CBlobPair(); void calculateProperties(); double getValidity( void ); int getIndex1( void ); int getIndex2( void ); protected: unsigned int index1; // index of first pair element unsigned int index2; // index of second pair element CBlob* blob1; // pointer to first pair element CBlob* blob2; // pointer to second pair element ovroi* centerroi; // pointer to valid center roi coordinates bool overallvalid; // overall validity of this pair double validity; // factor that describes validity double diffx1; double diffy1; double diffx2; double diffy2; double centerx1; double centery1; double centerx2; double centery2; double aspect1; double aspect2; double xdelta; double ydelta; double distance; double distangle; double normwidth1; double normwidth2; double basenormwidth1; double basenormwidth2; double aspectratio; double arearatio; }; #endif /* CBLOBPAIR_H_ */
32.539326
83
0.73308
d0ac7b8e2968ef24bd63c796f1e2cf23c38c370a
28,902
c
C
vpx_dsp/mips/avg_msa.c
prometheansacrifice/esy-vpx
3aae0f7164b9e43a0146b078a7c125d70835c419
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
vpx_dsp/mips/avg_msa.c
prometheansacrifice/esy-vpx
3aae0f7164b9e43a0146b078a7c125d70835c419
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
vpx_dsp/mips/avg_msa.c
prometheansacrifice/esy-vpx
3aae0f7164b9e43a0146b078a7c125d70835c419
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
/* * Copyright (c) 2015 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <stdlib.h> #include "./vpx_dsp_rtcd.h" #include "vpx_dsp/mips/macros_msa.h" uint32_t vpx_avg_8x8_msa(const uint8_t *src, int32_t src_stride) { uint32_t sum_out; v16u8 src0, src1, src2, src3, src4, src5, src6, src7; v8u16 sum0, sum1, sum2, sum3, sum4, sum5, sum6, sum7; v4u32 sum = { 0 }; LD_UB8(src, src_stride, src0, src1, src2, src3, src4, src5, src6, src7); HADD_UB4_UH(src0, src1, src2, src3, sum0, sum1, sum2, sum3); HADD_UB4_UH(src4, src5, src6, src7, sum4, sum5, sum6, sum7); ADD4(sum0, sum1, sum2, sum3, sum4, sum5, sum6, sum7, sum0, sum2, sum4, sum6); ADD2(sum0, sum2, sum4, sum6, sum0, sum4); sum0 += sum4; sum = __msa_hadd_u_w(sum0, sum0); sum0 = (v8u16)__msa_pckev_h((v8i16)sum, (v8i16)sum); sum = __msa_hadd_u_w(sum0, sum0); sum = (v4u32)__msa_srari_w((v4i32)sum, 6); sum_out = __msa_copy_u_w((v4i32)sum, 0); return sum_out; } uint32_t vpx_avg_4x4_msa(const uint8_t *src, int32_t src_stride) { uint32_t sum_out; uint32_t src0, src1, src2, src3; v16u8 vec = { 0 }; v8u16 sum0; v4u32 sum1; v2u64 sum2; LW4(src, src_stride, src0, src1, src2, src3); INSERT_W4_UB(src0, src1, src2, src3, vec); sum0 = __msa_hadd_u_h(vec, vec); sum1 = __msa_hadd_u_w(sum0, sum0); sum0 = (v8u16)__msa_pckev_h((v8i16)sum1, (v8i16)sum1); sum1 = __msa_hadd_u_w(sum0, sum0); sum2 = __msa_hadd_u_d(sum1, sum1); sum1 = (v4u32)__msa_srari_w((v4i32)sum2, 4); sum_out = __msa_copy_u_w((v4i32)sum1, 0); return sum_out; } void vpx_hadamard_8x8_msa(const int16_t *src, ptrdiff_t src_stride, int16_t *dst) { v8i16 src0, src1, src2, src3, src4, src5, src6, src7; v8i16 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; LD_SH8(src, src_stride, src0, src1, src2, src3, src4, src5, src6, src7); BUTTERFLY_8(src0, src2, src4, src6, src7, src5, src3, src1, tmp0, tmp2, tmp4, tmp6, tmp7, tmp5, tmp3, tmp1); BUTTERFLY_8(tmp0, tmp1, tmp4, tmp5, tmp7, tmp6, tmp3, tmp2, src0, src1, src4, src5, src7, src6, src3, src2); BUTTERFLY_8(src0, src1, src2, src3, src7, src6, src5, src4, tmp0, tmp7, tmp3, tmp4, tmp5, tmp1, tmp6, tmp2); TRANSPOSE8x8_SH_SH(tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, src0, src1, src2, src3, src4, src5, src6, src7); BUTTERFLY_8(src0, src2, src4, src6, src7, src5, src3, src1, tmp0, tmp2, tmp4, tmp6, tmp7, tmp5, tmp3, tmp1); BUTTERFLY_8(tmp0, tmp1, tmp4, tmp5, tmp7, tmp6, tmp3, tmp2, src0, src1, src4, src5, src7, src6, src3, src2); BUTTERFLY_8(src0, src1, src2, src3, src7, src6, src5, src4, tmp0, tmp7, tmp3, tmp4, tmp5, tmp1, tmp6, tmp2); TRANSPOSE8x8_SH_SH(tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, src0, src1, src2, src3, src4, src5, src6, src7); ST_SH8(src0, src1, src2, src3, src4, src5, src6, src7, dst, 8); } void vpx_hadamard_16x16_msa(const int16_t *src, ptrdiff_t src_stride, int16_t *dst) { v8i16 src0, src1, src2, src3, src4, src5, src6, src7, src8, src9, src10; v8i16 src11, src12, src13, src14, src15, tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; v8i16 tmp6, tmp7, tmp8, tmp9, tmp10, tmp11, tmp12, tmp13, tmp14, tmp15; v8i16 res0, res1, res2, res3, res4, res5, res6, res7; LD_SH2(src, 8, src0, src8); src += src_stride; LD_SH2(src, 8, src1, src9); src += src_stride; LD_SH2(src, 8, src2, src10); src += src_stride; LD_SH2(src, 8, src3, src11); src += src_stride; LD_SH2(src, 8, src4, src12); src += src_stride; LD_SH2(src, 8, src5, src13); src += src_stride; LD_SH2(src, 8, src6, src14); src += src_stride; LD_SH2(src, 8, src7, src15); src += src_stride; BUTTERFLY_8(src0, src2, src4, src6, src7, src5, src3, src1, tmp0, tmp2, tmp4, tmp6, tmp7, tmp5, tmp3, tmp1); BUTTERFLY_8(src8, src10, src12, src14, src15, src13, src11, src9, tmp8, tmp10, tmp12, tmp14, tmp15, tmp13, tmp11, tmp9); BUTTERFLY_8(tmp0, tmp1, tmp4, tmp5, tmp7, tmp6, tmp3, tmp2, src0, src1, src4, src5, src7, src6, src3, src2); BUTTERFLY_8(src0, src1, src2, src3, src7, src6, src5, src4, tmp0, tmp7, tmp3, tmp4, tmp5, tmp1, tmp6, tmp2); TRANSPOSE8x8_SH_SH(tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, src0, src1, src2, src3, src4, src5, src6, src7); BUTTERFLY_8(src0, src2, src4, src6, src7, src5, src3, src1, tmp0, tmp2, tmp4, tmp6, tmp7, tmp5, tmp3, tmp1); BUTTERFLY_8(tmp0, tmp1, tmp4, tmp5, tmp7, tmp6, tmp3, tmp2, src0, src1, src4, src5, src7, src6, src3, src2); BUTTERFLY_8(src0, src1, src2, src3, src7, src6, src5, src4, tmp0, tmp7, tmp3, tmp4, tmp5, tmp1, tmp6, tmp2); TRANSPOSE8x8_SH_SH(tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, src0, src1, src2, src11, src4, src5, src6, src7); ST_SH8(src0, src1, src2, src11, src4, src5, src6, src7, dst, 8); BUTTERFLY_8(tmp8, tmp9, tmp12, tmp13, tmp15, tmp14, tmp11, tmp10, src8, src9, src12, src13, src15, src14, src11, src10); BUTTERFLY_8(src8, src9, src10, src11, src15, src14, src13, src12, tmp8, tmp15, tmp11, tmp12, tmp13, tmp9, tmp14, tmp10); TRANSPOSE8x8_SH_SH(tmp8, tmp9, tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, src8, src9, src10, src11, src12, src13, src14, src15); BUTTERFLY_8(src8, src10, src12, src14, src15, src13, src11, src9, tmp8, tmp10, tmp12, tmp14, tmp15, tmp13, tmp11, tmp9); BUTTERFLY_8(tmp8, tmp9, tmp12, tmp13, tmp15, tmp14, tmp11, tmp10, src8, src9, src12, src13, src15, src14, src11, src10); BUTTERFLY_8(src8, src9, src10, src11, src15, src14, src13, src12, tmp8, tmp15, tmp11, tmp12, tmp13, tmp9, tmp14, tmp10); TRANSPOSE8x8_SH_SH(tmp8, tmp9, tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, res0, res1, res2, res3, res4, res5, res6, res7); LD_SH2(src, 8, src0, src8); src += src_stride; LD_SH2(src, 8, src1, src9); src += src_stride; LD_SH2(src, 8, src2, src10); src += src_stride; LD_SH2(src, 8, src3, src11); src += src_stride; ST_SH8(res0, res1, res2, res3, res4, res5, res6, res7, dst + 64, 8); LD_SH2(src, 8, src4, src12); src += src_stride; LD_SH2(src, 8, src5, src13); src += src_stride; LD_SH2(src, 8, src6, src14); src += src_stride; LD_SH2(src, 8, src7, src15); src += src_stride; BUTTERFLY_8(src0, src2, src4, src6, src7, src5, src3, src1, tmp0, tmp2, tmp4, tmp6, tmp7, tmp5, tmp3, tmp1); BUTTERFLY_8(src8, src10, src12, src14, src15, src13, src11, src9, tmp8, tmp10, tmp12, tmp14, tmp15, tmp13, tmp11, tmp9); BUTTERFLY_8(tmp0, tmp1, tmp4, tmp5, tmp7, tmp6, tmp3, tmp2, src0, src1, src4, src5, src7, src6, src3, src2); BUTTERFLY_8(src0, src1, src2, src3, src7, src6, src5, src4, tmp0, tmp7, tmp3, tmp4, tmp5, tmp1, tmp6, tmp2); TRANSPOSE8x8_SH_SH(tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, src0, src1, src2, src3, src4, src5, src6, src7); BUTTERFLY_8(src0, src2, src4, src6, src7, src5, src3, src1, tmp0, tmp2, tmp4, tmp6, tmp7, tmp5, tmp3, tmp1); BUTTERFLY_8(tmp0, tmp1, tmp4, tmp5, tmp7, tmp6, tmp3, tmp2, src0, src1, src4, src5, src7, src6, src3, src2); BUTTERFLY_8(src0, src1, src2, src3, src7, src6, src5, src4, tmp0, tmp7, tmp3, tmp4, tmp5, tmp1, tmp6, tmp2); TRANSPOSE8x8_SH_SH(tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, src0, src1, src2, src3, src4, src5, src6, src7); ST_SH8(src0, src1, src2, src3, src4, src5, src6, src7, dst + 2 * 64, 8); BUTTERFLY_8(tmp8, tmp9, tmp12, tmp13, tmp15, tmp14, tmp11, tmp10, src8, src9, src12, src13, src15, src14, src11, src10); BUTTERFLY_8(src8, src9, src10, src11, src15, src14, src13, src12, tmp8, tmp15, tmp11, tmp12, tmp13, tmp9, tmp14, tmp10); TRANSPOSE8x8_SH_SH(tmp8, tmp9, tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, src8, src9, src10, src11, src12, src13, src14, src15); BUTTERFLY_8(src8, src10, src12, src14, src15, src13, src11, src9, tmp8, tmp10, tmp12, tmp14, tmp15, tmp13, tmp11, tmp9); BUTTERFLY_8(tmp8, tmp9, tmp12, tmp13, tmp15, tmp14, tmp11, tmp10, src8, src9, src12, src13, src15, src14, src11, src10); BUTTERFLY_8(src8, src9, src10, src11, src15, src14, src13, src12, tmp8, tmp15, tmp11, tmp12, tmp13, tmp9, tmp14, tmp10); TRANSPOSE8x8_SH_SH(tmp8, tmp9, tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, res0, res1, res2, res3, res4, res5, res6, res7); ST_SH8(res0, res1, res2, res3, res4, res5, res6, res7, dst + 3 * 64, 8); LD_SH4(dst, 64, src0, src1, src2, src3); LD_SH4(dst + 8, 64, src4, src5, src6, src7); BUTTERFLY_8(src0, src2, src4, src6, src7, src5, src3, src1, tmp0, tmp2, tmp4, tmp6, tmp7, tmp5, tmp3, tmp1); SRA_4V(tmp0, tmp1, tmp2, tmp3, 1); SRA_4V(tmp4, tmp5, tmp6, tmp7, 1); BUTTERFLY_8(tmp0, tmp1, tmp4, tmp5, tmp7, tmp6, tmp3, tmp2, src0, src1, src4, src5, src7, src6, src3, src2); ST_SH4(src0, src1, src2, src3, dst, 64); ST_SH4(src4, src5, src6, src7, dst + 8, 64); dst += 16; LD_SH4(dst, 64, src0, src1, src2, src3); LD_SH4(dst + 8, 64, src4, src5, src6, src7); BUTTERFLY_8(src0, src2, src4, src6, src7, src5, src3, src1, tmp0, tmp2, tmp4, tmp6, tmp7, tmp5, tmp3, tmp1); SRA_4V(tmp0, tmp1, tmp2, tmp3, 1); SRA_4V(tmp4, tmp5, tmp6, tmp7, 1); BUTTERFLY_8(tmp0, tmp1, tmp4, tmp5, tmp7, tmp6, tmp3, tmp2, src0, src1, src4, src5, src7, src6, src3, src2); ST_SH4(src0, src1, src2, src3, dst, 64); ST_SH4(src4, src5, src6, src7, dst + 8, 64); dst += 16; LD_SH4(dst, 64, src0, src1, src2, src3); LD_SH4(dst + 8, 64, src4, src5, src6, src7); BUTTERFLY_8(src0, src2, src4, src6, src7, src5, src3, src1, tmp0, tmp2, tmp4, tmp6, tmp7, tmp5, tmp3, tmp1); SRA_4V(tmp0, tmp1, tmp2, tmp3, 1); SRA_4V(tmp4, tmp5, tmp6, tmp7, 1); BUTTERFLY_8(tmp0, tmp1, tmp4, tmp5, tmp7, tmp6, tmp3, tmp2, src0, src1, src4, src5, src7, src6, src3, src2); ST_SH4(src0, src1, src2, src3, dst, 64); ST_SH4(src4, src5, src6, src7, dst + 8, 64); dst += 16; LD_SH4(dst, 64, src0, src1, src2, src3); LD_SH4(dst + 8, 64, src4, src5, src6, src7); BUTTERFLY_8(src0, src2, src4, src6, src7, src5, src3, src1, tmp0, tmp2, tmp4, tmp6, tmp7, tmp5, tmp3, tmp1); SRA_4V(tmp0, tmp1, tmp2, tmp3, 1); SRA_4V(tmp4, tmp5, tmp6, tmp7, 1); BUTTERFLY_8(tmp0, tmp1, tmp4, tmp5, tmp7, tmp6, tmp3, tmp2, src0, src1, src4, src5, src7, src6, src3, src2); ST_SH4(src0, src1, src2, src3, dst, 64); ST_SH4(src4, src5, src6, src7, dst + 8, 64); } int vpx_satd_msa(const int16_t *data, int length) { int i, satd; v8i16 src0, src1, src2, src3, src4, src5, src6, src7; v8i16 src8, src9, src10, src11, src12, src13, src14, src15; v8i16 zero = { 0 }; v8u16 tmp0_h, tmp1_h, tmp2_h, tmp3_h, tmp4_h, tmp5_h, tmp6_h, tmp7_h; v4u32 tmp0_w = { 0 }; if (16 == length) { LD_SH2(data, 8, src0, src1); tmp0_h = (v8u16)__msa_asub_s_h(src0, zero); tmp1_h = (v8u16)__msa_asub_s_h(src1, zero); tmp0_w = __msa_hadd_u_w(tmp0_h, tmp0_h); tmp0_w += __msa_hadd_u_w(tmp1_h, tmp1_h); satd = HADD_UW_U32(tmp0_w); } else if (64 == length) { LD_SH8(data, 8, src0, src1, src2, src3, src4, src5, src6, src7); tmp0_h = (v8u16)__msa_asub_s_h(src0, zero); tmp1_h = (v8u16)__msa_asub_s_h(src1, zero); tmp2_h = (v8u16)__msa_asub_s_h(src2, zero); tmp3_h = (v8u16)__msa_asub_s_h(src3, zero); tmp4_h = (v8u16)__msa_asub_s_h(src4, zero); tmp5_h = (v8u16)__msa_asub_s_h(src5, zero); tmp6_h = (v8u16)__msa_asub_s_h(src6, zero); tmp7_h = (v8u16)__msa_asub_s_h(src7, zero); tmp0_w = __msa_hadd_u_w(tmp0_h, tmp0_h); tmp0_w += __msa_hadd_u_w(tmp1_h, tmp1_h); tmp0_w += __msa_hadd_u_w(tmp2_h, tmp2_h); tmp0_w += __msa_hadd_u_w(tmp3_h, tmp3_h); tmp0_w += __msa_hadd_u_w(tmp4_h, tmp4_h); tmp0_w += __msa_hadd_u_w(tmp5_h, tmp5_h); tmp0_w += __msa_hadd_u_w(tmp6_h, tmp6_h); tmp0_w += __msa_hadd_u_w(tmp7_h, tmp7_h); satd = HADD_UW_U32(tmp0_w); } else if (256 == length) { for (i = 0; i < 2; ++i) { LD_SH8(data, 8, src0, src1, src2, src3, src4, src5, src6, src7); data += 8 * 8; LD_SH8(data, 8, src8, src9, src10, src11, src12, src13, src14, src15); data += 8 * 8; tmp0_h = (v8u16)__msa_asub_s_h(src0, zero); tmp1_h = (v8u16)__msa_asub_s_h(src1, zero); tmp2_h = (v8u16)__msa_asub_s_h(src2, zero); tmp3_h = (v8u16)__msa_asub_s_h(src3, zero); tmp4_h = (v8u16)__msa_asub_s_h(src4, zero); tmp5_h = (v8u16)__msa_asub_s_h(src5, zero); tmp6_h = (v8u16)__msa_asub_s_h(src6, zero); tmp7_h = (v8u16)__msa_asub_s_h(src7, zero); tmp0_w += __msa_hadd_u_w(tmp0_h, tmp0_h); tmp0_w += __msa_hadd_u_w(tmp1_h, tmp1_h); tmp0_w += __msa_hadd_u_w(tmp2_h, tmp2_h); tmp0_w += __msa_hadd_u_w(tmp3_h, tmp3_h); tmp0_w += __msa_hadd_u_w(tmp4_h, tmp4_h); tmp0_w += __msa_hadd_u_w(tmp5_h, tmp5_h); tmp0_w += __msa_hadd_u_w(tmp6_h, tmp6_h); tmp0_w += __msa_hadd_u_w(tmp7_h, tmp7_h); tmp0_h = (v8u16)__msa_asub_s_h(src8, zero); tmp1_h = (v8u16)__msa_asub_s_h(src9, zero); tmp2_h = (v8u16)__msa_asub_s_h(src10, zero); tmp3_h = (v8u16)__msa_asub_s_h(src11, zero); tmp4_h = (v8u16)__msa_asub_s_h(src12, zero); tmp5_h = (v8u16)__msa_asub_s_h(src13, zero); tmp6_h = (v8u16)__msa_asub_s_h(src14, zero); tmp7_h = (v8u16)__msa_asub_s_h(src15, zero); tmp0_w += __msa_hadd_u_w(tmp0_h, tmp0_h); tmp0_w += __msa_hadd_u_w(tmp1_h, tmp1_h); tmp0_w += __msa_hadd_u_w(tmp2_h, tmp2_h); tmp0_w += __msa_hadd_u_w(tmp3_h, tmp3_h); tmp0_w += __msa_hadd_u_w(tmp4_h, tmp4_h); tmp0_w += __msa_hadd_u_w(tmp5_h, tmp5_h); tmp0_w += __msa_hadd_u_w(tmp6_h, tmp6_h); tmp0_w += __msa_hadd_u_w(tmp7_h, tmp7_h); } satd = HADD_UW_U32(tmp0_w); } else if (1024 == length) { for (i = 0; i < 8; ++i) { LD_SH8(data, 8, src0, src1, src2, src3, src4, src5, src6, src7); data += 8 * 8; LD_SH8(data, 8, src8, src9, src10, src11, src12, src13, src14, src15); data += 8 * 8; tmp0_h = (v8u16)__msa_asub_s_h(src0, zero); tmp1_h = (v8u16)__msa_asub_s_h(src1, zero); tmp2_h = (v8u16)__msa_asub_s_h(src2, zero); tmp3_h = (v8u16)__msa_asub_s_h(src3, zero); tmp4_h = (v8u16)__msa_asub_s_h(src4, zero); tmp5_h = (v8u16)__msa_asub_s_h(src5, zero); tmp6_h = (v8u16)__msa_asub_s_h(src6, zero); tmp7_h = (v8u16)__msa_asub_s_h(src7, zero); tmp0_w += __msa_hadd_u_w(tmp0_h, tmp0_h); tmp0_w += __msa_hadd_u_w(tmp1_h, tmp1_h); tmp0_w += __msa_hadd_u_w(tmp2_h, tmp2_h); tmp0_w += __msa_hadd_u_w(tmp3_h, tmp3_h); tmp0_w += __msa_hadd_u_w(tmp4_h, tmp4_h); tmp0_w += __msa_hadd_u_w(tmp5_h, tmp5_h); tmp0_w += __msa_hadd_u_w(tmp6_h, tmp6_h); tmp0_w += __msa_hadd_u_w(tmp7_h, tmp7_h); tmp0_h = (v8u16)__msa_asub_s_h(src8, zero); tmp1_h = (v8u16)__msa_asub_s_h(src9, zero); tmp2_h = (v8u16)__msa_asub_s_h(src10, zero); tmp3_h = (v8u16)__msa_asub_s_h(src11, zero); tmp4_h = (v8u16)__msa_asub_s_h(src12, zero); tmp5_h = (v8u16)__msa_asub_s_h(src13, zero); tmp6_h = (v8u16)__msa_asub_s_h(src14, zero); tmp7_h = (v8u16)__msa_asub_s_h(src15, zero); tmp0_w += __msa_hadd_u_w(tmp0_h, tmp0_h); tmp0_w += __msa_hadd_u_w(tmp1_h, tmp1_h); tmp0_w += __msa_hadd_u_w(tmp2_h, tmp2_h); tmp0_w += __msa_hadd_u_w(tmp3_h, tmp3_h); tmp0_w += __msa_hadd_u_w(tmp4_h, tmp4_h); tmp0_w += __msa_hadd_u_w(tmp5_h, tmp5_h); tmp0_w += __msa_hadd_u_w(tmp6_h, tmp6_h); tmp0_w += __msa_hadd_u_w(tmp7_h, tmp7_h); } satd = HADD_UW_U32(tmp0_w); } else { satd = 0; for (i = 0; i < length; ++i) { satd += abs(data[i]); } } return satd; } void vpx_int_pro_row_msa(int16_t hbuf[16], const uint8_t *ref, const int ref_stride, const int height) { int i; v16u8 ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7; v8i16 hbuf_r = { 0 }; v8i16 hbuf_l = { 0 }; v8i16 ref0_r, ref0_l, ref1_r, ref1_l, ref2_r, ref2_l, ref3_r, ref3_l; v8i16 ref4_r, ref4_l, ref5_r, ref5_l, ref6_r, ref6_l, ref7_r, ref7_l; if (16 == height) { for (i = 2; i--;) { LD_UB8(ref, ref_stride, ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7); ref += 8 * ref_stride; UNPCK_UB_SH(ref0, ref0_r, ref0_l); UNPCK_UB_SH(ref1, ref1_r, ref1_l); UNPCK_UB_SH(ref2, ref2_r, ref2_l); UNPCK_UB_SH(ref3, ref3_r, ref3_l); UNPCK_UB_SH(ref4, ref4_r, ref4_l); UNPCK_UB_SH(ref5, ref5_r, ref5_l); UNPCK_UB_SH(ref6, ref6_r, ref6_l); UNPCK_UB_SH(ref7, ref7_r, ref7_l); ADD4(hbuf_r, ref0_r, hbuf_l, ref0_l, hbuf_r, ref1_r, hbuf_l, ref1_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref2_r, hbuf_l, ref2_l, hbuf_r, ref3_r, hbuf_l, ref3_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref4_r, hbuf_l, ref4_l, hbuf_r, ref5_r, hbuf_l, ref5_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref6_r, hbuf_l, ref6_l, hbuf_r, ref7_r, hbuf_l, ref7_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); } SRA_2V(hbuf_r, hbuf_l, 3); ST_SH2(hbuf_r, hbuf_l, hbuf, 8); } else if (32 == height) { for (i = 2; i--;) { LD_UB8(ref, ref_stride, ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7); ref += 8 * ref_stride; UNPCK_UB_SH(ref0, ref0_r, ref0_l); UNPCK_UB_SH(ref1, ref1_r, ref1_l); UNPCK_UB_SH(ref2, ref2_r, ref2_l); UNPCK_UB_SH(ref3, ref3_r, ref3_l); UNPCK_UB_SH(ref4, ref4_r, ref4_l); UNPCK_UB_SH(ref5, ref5_r, ref5_l); UNPCK_UB_SH(ref6, ref6_r, ref6_l); UNPCK_UB_SH(ref7, ref7_r, ref7_l); ADD4(hbuf_r, ref0_r, hbuf_l, ref0_l, hbuf_r, ref1_r, hbuf_l, ref1_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref2_r, hbuf_l, ref2_l, hbuf_r, ref3_r, hbuf_l, ref3_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref4_r, hbuf_l, ref4_l, hbuf_r, ref5_r, hbuf_l, ref5_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref6_r, hbuf_l, ref6_l, hbuf_r, ref7_r, hbuf_l, ref7_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); LD_UB8(ref, ref_stride, ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7); ref += 8 * ref_stride; UNPCK_UB_SH(ref0, ref0_r, ref0_l); UNPCK_UB_SH(ref1, ref1_r, ref1_l); UNPCK_UB_SH(ref2, ref2_r, ref2_l); UNPCK_UB_SH(ref3, ref3_r, ref3_l); UNPCK_UB_SH(ref4, ref4_r, ref4_l); UNPCK_UB_SH(ref5, ref5_r, ref5_l); UNPCK_UB_SH(ref6, ref6_r, ref6_l); UNPCK_UB_SH(ref7, ref7_r, ref7_l); ADD4(hbuf_r, ref0_r, hbuf_l, ref0_l, hbuf_r, ref1_r, hbuf_l, ref1_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref2_r, hbuf_l, ref2_l, hbuf_r, ref3_r, hbuf_l, ref3_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref4_r, hbuf_l, ref4_l, hbuf_r, ref5_r, hbuf_l, ref5_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref6_r, hbuf_l, ref6_l, hbuf_r, ref7_r, hbuf_l, ref7_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); } SRA_2V(hbuf_r, hbuf_l, 4); ST_SH2(hbuf_r, hbuf_l, hbuf, 8); } else if (64 == height) { for (i = 4; i--;) { LD_UB8(ref, ref_stride, ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7); ref += 8 * ref_stride; UNPCK_UB_SH(ref0, ref0_r, ref0_l); UNPCK_UB_SH(ref1, ref1_r, ref1_l); UNPCK_UB_SH(ref2, ref2_r, ref2_l); UNPCK_UB_SH(ref3, ref3_r, ref3_l); UNPCK_UB_SH(ref4, ref4_r, ref4_l); UNPCK_UB_SH(ref5, ref5_r, ref5_l); UNPCK_UB_SH(ref6, ref6_r, ref6_l); UNPCK_UB_SH(ref7, ref7_r, ref7_l); ADD4(hbuf_r, ref0_r, hbuf_l, ref0_l, hbuf_r, ref1_r, hbuf_l, ref1_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref2_r, hbuf_l, ref2_l, hbuf_r, ref3_r, hbuf_l, ref3_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref4_r, hbuf_l, ref4_l, hbuf_r, ref5_r, hbuf_l, ref5_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref6_r, hbuf_l, ref6_l, hbuf_r, ref7_r, hbuf_l, ref7_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); LD_UB8(ref, ref_stride, ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7); ref += 8 * ref_stride; UNPCK_UB_SH(ref0, ref0_r, ref0_l); UNPCK_UB_SH(ref1, ref1_r, ref1_l); UNPCK_UB_SH(ref2, ref2_r, ref2_l); UNPCK_UB_SH(ref3, ref3_r, ref3_l); UNPCK_UB_SH(ref4, ref4_r, ref4_l); UNPCK_UB_SH(ref5, ref5_r, ref5_l); UNPCK_UB_SH(ref6, ref6_r, ref6_l); UNPCK_UB_SH(ref7, ref7_r, ref7_l); ADD4(hbuf_r, ref0_r, hbuf_l, ref0_l, hbuf_r, ref1_r, hbuf_l, ref1_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref2_r, hbuf_l, ref2_l, hbuf_r, ref3_r, hbuf_l, ref3_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref4_r, hbuf_l, ref4_l, hbuf_r, ref5_r, hbuf_l, ref5_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); ADD4(hbuf_r, ref6_r, hbuf_l, ref6_l, hbuf_r, ref7_r, hbuf_l, ref7_l, hbuf_r, hbuf_l, hbuf_r, hbuf_l); } SRA_2V(hbuf_r, hbuf_l, 5); ST_SH2(hbuf_r, hbuf_l, hbuf, 8); } else { const int norm_factor = height >> 1; int cnt; for (cnt = 0; cnt < 16; cnt++) { hbuf[cnt] = 0; } for (i = 0; i < height; ++i) { for (cnt = 0; cnt < 16; cnt++) { hbuf[cnt] += ref[cnt]; } ref += ref_stride; } for (cnt = 0; cnt < 16; cnt++) { hbuf[cnt] /= norm_factor; } } } int16_t vpx_int_pro_col_msa(const uint8_t *ref, const int width) { int16_t sum; v16u8 ref0, ref1, ref2, ref3; v8u16 ref0_h; if (16 == width) { ref0 = LD_UB(ref); ref0_h = __msa_hadd_u_h(ref0, ref0); sum = HADD_UH_U32(ref0_h); } else if (32 == width) { LD_UB2(ref, 16, ref0, ref1); ref0_h = __msa_hadd_u_h(ref0, ref0); ref0_h += __msa_hadd_u_h(ref1, ref1); sum = HADD_UH_U32(ref0_h); } else if (64 == width) { LD_UB4(ref, 16, ref0, ref1, ref2, ref3); ref0_h = __msa_hadd_u_h(ref0, ref0); ref0_h += __msa_hadd_u_h(ref1, ref1); ref0_h += __msa_hadd_u_h(ref2, ref2); ref0_h += __msa_hadd_u_h(ref3, ref3); sum = HADD_UH_U32(ref0_h); } else { int idx; sum = 0; for (idx = 0; idx < width; ++idx) { sum += ref[idx]; } } return sum; } int vpx_vector_var_msa(const int16_t *ref, const int16_t *src, const int bwl) { int sse, mean, var; v8i16 src0, src1, src2, src3, src4, src5, src6, src7, ref0, ref1, ref2; v8i16 ref3, ref4, ref5, ref6, ref7, src_l0_m, src_l1_m, src_l2_m, src_l3_m; v8i16 src_l4_m, src_l5_m, src_l6_m, src_l7_m; v4i32 res_l0_m, res_l1_m, res_l2_m, res_l3_m, res_l4_m, res_l5_m, res_l6_m; v4i32 res_l7_m, mean_v; v2i64 sse_v; if (2 == bwl) { LD_SH2(src, 8, src0, src1); LD_SH2(ref, 8, ref0, ref1); ILVRL_H2_SH(src0, ref0, src_l0_m, src_l1_m); ILVRL_H2_SH(src1, ref1, src_l2_m, src_l3_m); HSUB_UH2_SW(src_l0_m, src_l1_m, res_l0_m, res_l1_m); HSUB_UH2_SW(src_l2_m, src_l3_m, res_l2_m, res_l3_m); sse_v = __msa_dotp_s_d(res_l0_m, res_l0_m); sse_v = __msa_dpadd_s_d(sse_v, res_l1_m, res_l1_m); DPADD_SD2_SD(res_l2_m, res_l3_m, sse_v, sse_v); mean_v = res_l0_m + res_l1_m; mean_v += res_l2_m + res_l3_m; sse_v += __msa_splati_d(sse_v, 1); sse = __msa_copy_s_w((v4i32)sse_v, 0); mean = HADD_SW_S32(mean_v); } else if (3 == bwl) { LD_SH4(src, 8, src0, src1, src2, src3); LD_SH4(ref, 8, ref0, ref1, ref2, ref3); ILVRL_H2_SH(src0, ref0, src_l0_m, src_l1_m); ILVRL_H2_SH(src1, ref1, src_l2_m, src_l3_m); ILVRL_H2_SH(src2, ref2, src_l4_m, src_l5_m); ILVRL_H2_SH(src3, ref3, src_l6_m, src_l7_m); HSUB_UH2_SW(src_l0_m, src_l1_m, res_l0_m, res_l1_m); HSUB_UH2_SW(src_l2_m, src_l3_m, res_l2_m, res_l3_m); HSUB_UH2_SW(src_l4_m, src_l5_m, res_l4_m, res_l5_m); HSUB_UH2_SW(src_l6_m, src_l7_m, res_l6_m, res_l7_m); sse_v = __msa_dotp_s_d(res_l0_m, res_l0_m); sse_v = __msa_dpadd_s_d(sse_v, res_l1_m, res_l1_m); DPADD_SD2_SD(res_l2_m, res_l3_m, sse_v, sse_v); DPADD_SD2_SD(res_l4_m, res_l5_m, sse_v, sse_v); DPADD_SD2_SD(res_l6_m, res_l7_m, sse_v, sse_v); mean_v = res_l0_m + res_l1_m; mean_v += res_l2_m + res_l3_m; mean_v += res_l4_m + res_l5_m; mean_v += res_l6_m + res_l7_m; sse_v += __msa_splati_d(sse_v, 1); sse = __msa_copy_s_w((v4i32)sse_v, 0); mean = HADD_SW_S32(mean_v); } else if (4 == bwl) { LD_SH8(src, 8, src0, src1, src2, src3, src4, src5, src6, src7); LD_SH8(ref, 8, ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7); ILVRL_H2_SH(src0, ref0, src_l0_m, src_l1_m); ILVRL_H2_SH(src1, ref1, src_l2_m, src_l3_m); ILVRL_H2_SH(src2, ref2, src_l4_m, src_l5_m); ILVRL_H2_SH(src3, ref3, src_l6_m, src_l7_m); HSUB_UH2_SW(src_l0_m, src_l1_m, res_l0_m, res_l1_m); HSUB_UH2_SW(src_l2_m, src_l3_m, res_l2_m, res_l3_m); HSUB_UH2_SW(src_l4_m, src_l5_m, res_l4_m, res_l5_m); HSUB_UH2_SW(src_l6_m, src_l7_m, res_l6_m, res_l7_m); sse_v = __msa_dotp_s_d(res_l0_m, res_l0_m); sse_v = __msa_dpadd_s_d(sse_v, res_l1_m, res_l1_m); DPADD_SD2_SD(res_l2_m, res_l3_m, sse_v, sse_v); DPADD_SD2_SD(res_l4_m, res_l5_m, sse_v, sse_v); DPADD_SD2_SD(res_l6_m, res_l7_m, sse_v, sse_v); mean_v = res_l0_m + res_l1_m; mean_v += res_l2_m + res_l3_m; mean_v += res_l4_m + res_l5_m; mean_v += res_l6_m + res_l7_m; ILVRL_H2_SH(src4, ref4, src_l0_m, src_l1_m); ILVRL_H2_SH(src5, ref5, src_l2_m, src_l3_m); ILVRL_H2_SH(src6, ref6, src_l4_m, src_l5_m); ILVRL_H2_SH(src7, ref7, src_l6_m, src_l7_m); HSUB_UH2_SW(src_l0_m, src_l1_m, res_l0_m, res_l1_m); HSUB_UH2_SW(src_l2_m, src_l3_m, res_l2_m, res_l3_m); HSUB_UH2_SW(src_l4_m, src_l5_m, res_l4_m, res_l5_m); HSUB_UH2_SW(src_l6_m, src_l7_m, res_l6_m, res_l7_m); DPADD_SD2_SD(res_l0_m, res_l1_m, sse_v, sse_v); DPADD_SD2_SD(res_l2_m, res_l3_m, sse_v, sse_v); DPADD_SD2_SD(res_l4_m, res_l5_m, sse_v, sse_v); DPADD_SD2_SD(res_l6_m, res_l7_m, sse_v, sse_v); mean_v += res_l0_m + res_l1_m; mean_v += res_l2_m + res_l3_m; mean_v += res_l4_m + res_l5_m; mean_v += res_l6_m + res_l7_m; sse_v += __msa_splati_d(sse_v, 1); sse = __msa_copy_s_w((v4i32)sse_v, 0); mean = HADD_SW_S32(mean_v); } else { int i; const int width = 4 << bwl; sse = 0; mean = 0; for (i = 0; i < width; ++i) { const int diff = ref[i] - src[i]; mean += diff; sse += diff * diff; } } var = sse - ((mean * mean) >> (bwl + 2)); return var; } void vpx_minmax_8x8_msa(const uint8_t *s, int p, const uint8_t *d, int dp, int *min, int *max) { v16u8 s0, s1, s2, s3, s4, s5, s6, s7, d0, d1, d2, d3, d4, d5, d6, d7; v16u8 diff0, diff1, diff2, diff3, min0, min1, max0, max1; LD_UB8(s, p, s0, s1, s2, s3, s4, s5, s6, s7); LD_UB8(d, dp, d0, d1, d2, d3, d4, d5, d6, d7); PCKEV_D4_UB(s1, s0, s3, s2, s5, s4, s7, s6, s0, s1, s2, s3); PCKEV_D4_UB(d1, d0, d3, d2, d5, d4, d7, d6, d0, d1, d2, d3); diff0 = __msa_asub_u_b(s0, d0); diff1 = __msa_asub_u_b(s1, d1); diff2 = __msa_asub_u_b(s2, d2); diff3 = __msa_asub_u_b(s3, d3); min0 = __msa_min_u_b(diff0, diff1); min1 = __msa_min_u_b(diff2, diff3); min0 = __msa_min_u_b(min0, min1); max0 = __msa_max_u_b(diff0, diff1); max1 = __msa_max_u_b(diff2, diff3); max0 = __msa_max_u_b(max0, max1); min1 = (v16u8)__msa_sldi_b((v16i8)min1, (v16i8)min0, 8); min0 = __msa_min_u_b(min0, min1); max1 = (v16u8)__msa_sldi_b((v16i8)max1, (v16i8)max0, 8); max0 = __msa_max_u_b(max0, max1); min1 = (v16u8)__msa_sldi_b((v16i8)min1, (v16i8)min0, 4); min0 = __msa_min_u_b(min0, min1); max1 = (v16u8)__msa_sldi_b((v16i8)max1, (v16i8)max0, 4); max0 = __msa_max_u_b(max0, max1); min1 = (v16u8)__msa_sldi_b((v16i8)min1, (v16i8)min0, 2); min0 = __msa_min_u_b(min0, min1); max1 = (v16u8)__msa_sldi_b((v16i8)max1, (v16i8)max0, 2); max0 = __msa_max_u_b(max0, max1); min1 = (v16u8)__msa_sldi_b((v16i8)min1, (v16i8)min0, 1); min0 = __msa_min_u_b(min0, min1); max1 = (v16u8)__msa_sldi_b((v16i8)max1, (v16i8)max0, 1); max0 = __msa_max_u_b(max0, max1); *min = min0[0]; *max = max0[0]; }
39.646091
80
0.634558
4580717ade19f8f527a7ee294972f7a144c3ba22
11,714
c
C
runtime/musl-lkl/lkl/drivers/pinctrl/freescale/pinctrl-imx6ul.c
dme26/intravisor
9bf9c50aa14616bd9bd66eee47623e8b61514058
[ "MIT" ]
11
2022-02-05T12:12:43.000Z
2022-03-08T08:09:08.000Z
runtime/musl-lkl/lkl/drivers/pinctrl/freescale/pinctrl-imx6ul.c
dme26/intravisor
9bf9c50aa14616bd9bd66eee47623e8b61514058
[ "MIT" ]
null
null
null
runtime/musl-lkl/lkl/drivers/pinctrl/freescale/pinctrl-imx6ul.c
dme26/intravisor
9bf9c50aa14616bd9bd66eee47623e8b61514058
[ "MIT" ]
1
2022-02-22T20:32:22.000Z
2022-02-22T20:32:22.000Z
/* * Freescale imx6ul pinctrl driver * * Author: Anson Huang <Anson.Huang@freescale.com> * Copyright (C) 2015 Freescale Semiconductor, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/err.h> #include <linux/init.h> #include <linux/io.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/pinctrl/pinctrl.h> #include "pinctrl-imx.h" enum imx6ul_pads { MX6UL_PAD_RESERVE0 = 0, MX6UL_PAD_RESERVE1 = 1, MX6UL_PAD_RESERVE2 = 2, MX6UL_PAD_RESERVE3 = 3, MX6UL_PAD_RESERVE4 = 4, MX6UL_PAD_RESERVE5 = 5, MX6UL_PAD_RESERVE6 = 6, MX6UL_PAD_RESERVE7 = 7, MX6UL_PAD_RESERVE8 = 8, MX6UL_PAD_RESERVE9 = 9, MX6UL_PAD_RESERVE10 = 10, MX6UL_PAD_SNVS_TAMPER4 = 11, MX6UL_PAD_RESERVE12 = 12, MX6UL_PAD_RESERVE13 = 13, MX6UL_PAD_RESERVE14 = 14, MX6UL_PAD_RESERVE15 = 15, MX6UL_PAD_RESERVE16 = 16, MX6UL_PAD_JTAG_MOD = 17, MX6UL_PAD_JTAG_TMS = 18, MX6UL_PAD_JTAG_TDO = 19, MX6UL_PAD_JTAG_TDI = 20, MX6UL_PAD_JTAG_TCK = 21, MX6UL_PAD_JTAG_TRST_B = 22, MX6UL_PAD_GPIO1_IO00 = 23, MX6UL_PAD_GPIO1_IO01 = 24, MX6UL_PAD_GPIO1_IO02 = 25, MX6UL_PAD_GPIO1_IO03 = 26, MX6UL_PAD_GPIO1_IO04 = 27, MX6UL_PAD_GPIO1_IO05 = 28, MX6UL_PAD_GPIO1_IO06 = 29, MX6UL_PAD_GPIO1_IO07 = 30, MX6UL_PAD_GPIO1_IO08 = 31, MX6UL_PAD_GPIO1_IO09 = 32, MX6UL_PAD_UART1_TX_DATA = 33, MX6UL_PAD_UART1_RX_DATA = 34, MX6UL_PAD_UART1_CTS_B = 35, MX6UL_PAD_UART1_RTS_B = 36, MX6UL_PAD_UART2_TX_DATA = 37, MX6UL_PAD_UART2_RX_DATA = 38, MX6UL_PAD_UART2_CTS_B = 39, MX6UL_PAD_UART2_RTS_B = 40, MX6UL_PAD_UART3_TX_DATA = 41, MX6UL_PAD_UART3_RX_DATA = 42, MX6UL_PAD_UART3_CTS_B = 43, MX6UL_PAD_UART3_RTS_B = 44, MX6UL_PAD_UART4_TX_DATA = 45, MX6UL_PAD_UART4_RX_DATA = 46, MX6UL_PAD_UART5_TX_DATA = 47, MX6UL_PAD_UART5_RX_DATA = 48, MX6UL_PAD_ENET1_RX_DATA0 = 49, MX6UL_PAD_ENET1_RX_DATA1 = 50, MX6UL_PAD_ENET1_RX_EN = 51, MX6UL_PAD_ENET1_TX_DATA0 = 52, MX6UL_PAD_ENET1_TX_DATA1 = 53, MX6UL_PAD_ENET1_TX_EN = 54, MX6UL_PAD_ENET1_TX_CLK = 55, MX6UL_PAD_ENET1_RX_ER = 56, MX6UL_PAD_ENET2_RX_DATA0 = 57, MX6UL_PAD_ENET2_RX_DATA1 = 58, MX6UL_PAD_ENET2_RX_EN = 59, MX6UL_PAD_ENET2_TX_DATA0 = 60, MX6UL_PAD_ENET2_TX_DATA1 = 61, MX6UL_PAD_ENET2_TX_EN = 62, MX6UL_PAD_ENET2_TX_CLK = 63, MX6UL_PAD_ENET2_RX_ER = 64, MX6UL_PAD_LCD_CLK = 65, MX6UL_PAD_LCD_ENABLE = 66, MX6UL_PAD_LCD_HSYNC = 67, MX6UL_PAD_LCD_VSYNC = 68, MX6UL_PAD_LCD_RESET = 69, MX6UL_PAD_LCD_DATA00 = 70, MX6UL_PAD_LCD_DATA01 = 71, MX6UL_PAD_LCD_DATA02 = 72, MX6UL_PAD_LCD_DATA03 = 73, MX6UL_PAD_LCD_DATA04 = 74, MX6UL_PAD_LCD_DATA05 = 75, MX6UL_PAD_LCD_DATA06 = 76, MX6UL_PAD_LCD_DATA07 = 77, MX6UL_PAD_LCD_DATA08 = 78, MX6UL_PAD_LCD_DATA09 = 79, MX6UL_PAD_LCD_DATA10 = 80, MX6UL_PAD_LCD_DATA11 = 81, MX6UL_PAD_LCD_DATA12 = 82, MX6UL_PAD_LCD_DATA13 = 83, MX6UL_PAD_LCD_DATA14 = 84, MX6UL_PAD_LCD_DATA15 = 85, MX6UL_PAD_LCD_DATA16 = 86, MX6UL_PAD_LCD_DATA17 = 87, MX6UL_PAD_LCD_DATA18 = 88, MX6UL_PAD_LCD_DATA19 = 89, MX6UL_PAD_LCD_DATA20 = 90, MX6UL_PAD_LCD_DATA21 = 91, MX6UL_PAD_LCD_DATA22 = 92, MX6UL_PAD_LCD_DATA23 = 93, MX6UL_PAD_NAND_RE_B = 94, MX6UL_PAD_NAND_WE_B = 95, MX6UL_PAD_NAND_DATA00 = 96, MX6UL_PAD_NAND_DATA01 = 97, MX6UL_PAD_NAND_DATA02 = 98, MX6UL_PAD_NAND_DATA03 = 99, MX6UL_PAD_NAND_DATA04 = 100, MX6UL_PAD_NAND_DATA05 = 101, MX6UL_PAD_NAND_DATA06 = 102, MX6UL_PAD_NAND_DATA07 = 103, MX6UL_PAD_NAND_ALE = 104, MX6UL_PAD_NAND_WP_B = 105, MX6UL_PAD_NAND_READY_B = 106, MX6UL_PAD_NAND_CE0_B = 107, MX6UL_PAD_NAND_CE1_B = 108, MX6UL_PAD_NAND_CLE = 109, MX6UL_PAD_NAND_DQS = 110, MX6UL_PAD_SD1_CMD = 111, MX6UL_PAD_SD1_CLK = 112, MX6UL_PAD_SD1_DATA0 = 113, MX6UL_PAD_SD1_DATA1 = 114, MX6UL_PAD_SD1_DATA2 = 115, MX6UL_PAD_SD1_DATA3 = 116, MX6UL_PAD_CSI_MCLK = 117, MX6UL_PAD_CSI_PIXCLK = 118, MX6UL_PAD_CSI_VSYNC = 119, MX6UL_PAD_CSI_HSYNC = 120, MX6UL_PAD_CSI_DATA00 = 121, MX6UL_PAD_CSI_DATA01 = 122, MX6UL_PAD_CSI_DATA02 = 123, MX6UL_PAD_CSI_DATA03 = 124, MX6UL_PAD_CSI_DATA04 = 125, MX6UL_PAD_CSI_DATA05 = 126, MX6UL_PAD_CSI_DATA06 = 127, MX6UL_PAD_CSI_DATA07 = 128, }; enum imx6ull_lpsr_pads { MX6ULL_PAD_BOOT_MODE0 = 0, MX6ULL_PAD_BOOT_MODE1 = 1, MX6ULL_PAD_SNVS_TAMPER0 = 2, MX6ULL_PAD_SNVS_TAMPER1 = 3, MX6ULL_PAD_SNVS_TAMPER2 = 4, MX6ULL_PAD_SNVS_TAMPER3 = 5, MX6ULL_PAD_SNVS_TAMPER4 = 6, MX6ULL_PAD_SNVS_TAMPER5 = 7, MX6ULL_PAD_SNVS_TAMPER6 = 8, MX6ULL_PAD_SNVS_TAMPER7 = 9, MX6ULL_PAD_SNVS_TAMPER8 = 10, MX6ULL_PAD_SNVS_TAMPER9 = 11, }; /* Pad names for the pinmux subsystem */ static const struct pinctrl_pin_desc imx6ul_pinctrl_pads[] = { IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE0), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE1), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE2), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE3), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE4), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE5), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE6), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE7), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE8), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE9), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE10), IMX_PINCTRL_PIN(MX6UL_PAD_SNVS_TAMPER4), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE12), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE13), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE14), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE15), IMX_PINCTRL_PIN(MX6UL_PAD_RESERVE16), IMX_PINCTRL_PIN(MX6UL_PAD_JTAG_MOD), IMX_PINCTRL_PIN(MX6UL_PAD_JTAG_TMS), IMX_PINCTRL_PIN(MX6UL_PAD_JTAG_TDO), IMX_PINCTRL_PIN(MX6UL_PAD_JTAG_TDI), IMX_PINCTRL_PIN(MX6UL_PAD_JTAG_TCK), IMX_PINCTRL_PIN(MX6UL_PAD_JTAG_TRST_B), IMX_PINCTRL_PIN(MX6UL_PAD_GPIO1_IO00), IMX_PINCTRL_PIN(MX6UL_PAD_GPIO1_IO01), IMX_PINCTRL_PIN(MX6UL_PAD_GPIO1_IO02), IMX_PINCTRL_PIN(MX6UL_PAD_GPIO1_IO03), IMX_PINCTRL_PIN(MX6UL_PAD_GPIO1_IO04), IMX_PINCTRL_PIN(MX6UL_PAD_GPIO1_IO05), IMX_PINCTRL_PIN(MX6UL_PAD_GPIO1_IO06), IMX_PINCTRL_PIN(MX6UL_PAD_GPIO1_IO07), IMX_PINCTRL_PIN(MX6UL_PAD_GPIO1_IO08), IMX_PINCTRL_PIN(MX6UL_PAD_GPIO1_IO09), IMX_PINCTRL_PIN(MX6UL_PAD_UART1_TX_DATA), IMX_PINCTRL_PIN(MX6UL_PAD_UART1_RX_DATA), IMX_PINCTRL_PIN(MX6UL_PAD_UART1_CTS_B), IMX_PINCTRL_PIN(MX6UL_PAD_UART1_RTS_B), IMX_PINCTRL_PIN(MX6UL_PAD_UART2_TX_DATA), IMX_PINCTRL_PIN(MX6UL_PAD_UART2_RX_DATA), IMX_PINCTRL_PIN(MX6UL_PAD_UART2_CTS_B), IMX_PINCTRL_PIN(MX6UL_PAD_UART2_RTS_B), IMX_PINCTRL_PIN(MX6UL_PAD_UART3_TX_DATA), IMX_PINCTRL_PIN(MX6UL_PAD_UART3_RX_DATA), IMX_PINCTRL_PIN(MX6UL_PAD_UART3_CTS_B), IMX_PINCTRL_PIN(MX6UL_PAD_UART3_RTS_B), IMX_PINCTRL_PIN(MX6UL_PAD_UART4_TX_DATA), IMX_PINCTRL_PIN(MX6UL_PAD_UART4_RX_DATA), IMX_PINCTRL_PIN(MX6UL_PAD_UART5_TX_DATA), IMX_PINCTRL_PIN(MX6UL_PAD_UART5_RX_DATA), IMX_PINCTRL_PIN(MX6UL_PAD_ENET1_RX_DATA0), IMX_PINCTRL_PIN(MX6UL_PAD_ENET1_RX_DATA1), IMX_PINCTRL_PIN(MX6UL_PAD_ENET1_RX_EN), IMX_PINCTRL_PIN(MX6UL_PAD_ENET1_TX_DATA0), IMX_PINCTRL_PIN(MX6UL_PAD_ENET1_TX_DATA1), IMX_PINCTRL_PIN(MX6UL_PAD_ENET1_TX_EN), IMX_PINCTRL_PIN(MX6UL_PAD_ENET1_TX_CLK), IMX_PINCTRL_PIN(MX6UL_PAD_ENET1_RX_ER), IMX_PINCTRL_PIN(MX6UL_PAD_ENET2_RX_DATA0), IMX_PINCTRL_PIN(MX6UL_PAD_ENET2_RX_DATA1), IMX_PINCTRL_PIN(MX6UL_PAD_ENET2_RX_EN), IMX_PINCTRL_PIN(MX6UL_PAD_ENET2_TX_DATA0), IMX_PINCTRL_PIN(MX6UL_PAD_ENET2_TX_DATA1), IMX_PINCTRL_PIN(MX6UL_PAD_ENET2_TX_EN), IMX_PINCTRL_PIN(MX6UL_PAD_ENET2_TX_CLK), IMX_PINCTRL_PIN(MX6UL_PAD_ENET2_RX_ER), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_CLK), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_ENABLE), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_HSYNC), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_VSYNC), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_RESET), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA00), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA01), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA02), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA03), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA04), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA05), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA06), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA07), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA08), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA09), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA10), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA11), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA12), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA13), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA14), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA15), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA16), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA17), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA18), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA19), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA20), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA21), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA22), IMX_PINCTRL_PIN(MX6UL_PAD_LCD_DATA23), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_RE_B), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_WE_B), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_DATA00), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_DATA01), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_DATA02), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_DATA03), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_DATA04), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_DATA05), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_DATA06), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_DATA07), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_ALE), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_WP_B), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_READY_B), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_CE0_B), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_CE1_B), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_CLE), IMX_PINCTRL_PIN(MX6UL_PAD_NAND_DQS), IMX_PINCTRL_PIN(MX6UL_PAD_SD1_CMD), IMX_PINCTRL_PIN(MX6UL_PAD_SD1_CLK), IMX_PINCTRL_PIN(MX6UL_PAD_SD1_DATA0), IMX_PINCTRL_PIN(MX6UL_PAD_SD1_DATA1), IMX_PINCTRL_PIN(MX6UL_PAD_SD1_DATA2), IMX_PINCTRL_PIN(MX6UL_PAD_SD1_DATA3), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_MCLK), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_PIXCLK), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_VSYNC), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_HSYNC), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_DATA00), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_DATA01), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_DATA02), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_DATA03), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_DATA04), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_DATA05), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_DATA06), IMX_PINCTRL_PIN(MX6UL_PAD_CSI_DATA07), }; /* pad for i.MX6ULL lpsr pinmux */ static const struct pinctrl_pin_desc imx6ull_snvs_pinctrl_pads[] = { IMX_PINCTRL_PIN(MX6ULL_PAD_BOOT_MODE0), IMX_PINCTRL_PIN(MX6ULL_PAD_BOOT_MODE1), IMX_PINCTRL_PIN(MX6ULL_PAD_SNVS_TAMPER0), IMX_PINCTRL_PIN(MX6ULL_PAD_SNVS_TAMPER1), IMX_PINCTRL_PIN(MX6ULL_PAD_SNVS_TAMPER2), IMX_PINCTRL_PIN(MX6ULL_PAD_SNVS_TAMPER3), IMX_PINCTRL_PIN(MX6ULL_PAD_SNVS_TAMPER4), IMX_PINCTRL_PIN(MX6ULL_PAD_SNVS_TAMPER5), IMX_PINCTRL_PIN(MX6ULL_PAD_SNVS_TAMPER6), IMX_PINCTRL_PIN(MX6ULL_PAD_SNVS_TAMPER7), IMX_PINCTRL_PIN(MX6ULL_PAD_SNVS_TAMPER8), IMX_PINCTRL_PIN(MX6ULL_PAD_SNVS_TAMPER9), }; static const struct imx_pinctrl_soc_info imx6ul_pinctrl_info = { .pins = imx6ul_pinctrl_pads, .npins = ARRAY_SIZE(imx6ul_pinctrl_pads), .gpr_compatible = "fsl,imx6ul-iomuxc-gpr", }; static const struct imx_pinctrl_soc_info imx6ull_snvs_pinctrl_info = { .pins = imx6ull_snvs_pinctrl_pads, .npins = ARRAY_SIZE(imx6ull_snvs_pinctrl_pads), .flags = ZERO_OFFSET_VALID, }; static const struct of_device_id imx6ul_pinctrl_of_match[] = { { .compatible = "fsl,imx6ul-iomuxc", .data = &imx6ul_pinctrl_info, }, { .compatible = "fsl,imx6ull-iomuxc-snvs", .data = &imx6ull_snvs_pinctrl_info, }, { /* sentinel */ } }; static int imx6ul_pinctrl_probe(struct platform_device *pdev) { const struct imx_pinctrl_soc_info *pinctrl_info; pinctrl_info = of_device_get_match_data(&pdev->dev); if (!pinctrl_info) return -ENODEV; return imx_pinctrl_probe(pdev, pinctrl_info); } static struct platform_driver imx6ul_pinctrl_driver = { .driver = { .name = "imx6ul-pinctrl", .of_match_table = of_match_ptr(imx6ul_pinctrl_of_match), }, .probe = imx6ul_pinctrl_probe, }; static int __init imx6ul_pinctrl_init(void) { return platform_driver_register(&imx6ul_pinctrl_driver); } arch_initcall(imx6ul_pinctrl_init);
32.629526
82
0.82602
e70d4aced3370c5b6e046990b58b15a7075c9d7c
939
c
C
build_gnu/gcc/gcc/testsuite/gcc.dg/sms-1.c
jed-frey/e200-gcc
df1421b421a8ec8729d70791129f5283dee5f9ea
[ "BSD-3-Clause" ]
1
2017-05-31T21:42:12.000Z
2017-05-31T21:42:12.000Z
build_gnu/gcc/gcc/testsuite/gcc.dg/sms-1.c
jed-frey/e200-gcc
df1421b421a8ec8729d70791129f5283dee5f9ea
[ "BSD-3-Clause" ]
null
null
null
build_gnu/gcc/gcc/testsuite/gcc.dg/sms-1.c
jed-frey/e200-gcc
df1421b421a8ec8729d70791129f5283dee5f9ea
[ "BSD-3-Clause" ]
1
2019-12-17T22:04:07.000Z
2019-12-17T22:04:07.000Z
/* The same test as loop-3c.c. It failed on ia64 due to not handling of subreg in the lhs that is fixed. */ /* { dg-do run } */ /* { dg-options "-O2 -fmodulo-sched -fmodulo-sched-allow-regmoves -fdump-rtl-sms" } */ /* { dg-additional-options "-fno-extelim" { target { powerpc*-*-* && lp64 } } } */ #include <limits.h> extern void abort (void); void * a[255]; __attribute__ ((noinline)) void f (m) { int i; int sh = 0x100; i = m; do { a[sh >>= 1] = ((unsigned)i << 3) + (char*)a; i += 4; } while (i < INT_MAX/2 + 1 + 4 * 4); } int main () { a[0x10] = 0; a[0x08] = 0; f (INT_MAX/2 + INT_MAX/4 + 2); if (a[0x10] || a[0x08]) abort (); a[0x10] = 0; a[0x08] = 0; f (INT_MAX/2 + 1); if (! a[0x10] || a[0x08]) abort (); return 0; } /* { dg-final { scan-rtl-dump-times "SMS succeeded" 1 "sms" { target powerpc*-*-* spu-*-* } } } */ /* { dg-final { cleanup-rtl-dump "sms" } } */
19.978723
99
0.523962
ecff3c5bec7fc76ab9b60aa5b5094685c00f9e58
3,645
c
C
volatile_atomic.c
IbrahimQatato/Modern_C
f29cb585e061cf94dfc617e78d7ae297b66383c4
[ "MIT" ]
null
null
null
volatile_atomic.c
IbrahimQatato/Modern_C
f29cb585e061cf94dfc617e78d7ae297b66383c4
[ "MIT" ]
null
null
null
volatile_atomic.c
IbrahimQatato/Modern_C
f29cb585e061cf94dfc617e78d7ae297b66383c4
[ "MIT" ]
null
null
null
#include <stdatomic.h> /** ** @brief A simple accumulation in a loop ** ** Any decent optimizer should be able to figure out that the return ** value is @c 100 and that the only side effect is to store the ** value @c 10 into @c *count. **/ unsigned accu(unsigned*restrict count) { unsigned ret = 0; unsigned tmp = 0; (*count) = 0; while (tmp < 9) { tmp = (*count)++; ret += 2*tmp +1; } return ret; } /** ** @brief @c volatile qualification ** ** @c volatile forces all stores to be effected. So this has side ** effects of storing @f$0, \ldots, 10@f$ into @c *count. **/ unsigned accuv(unsigned volatile*restrict count) { unsigned ret = 0; unsigned tmp = 0; (*count) = 0; while (tmp < 9) { tmp = (*count)++; ret += 2*tmp +1; } return ret; } /** ** @brief @c _Atomic specification ** ** Here, because it is not @c volatile, none of the side effects ** would have to be made visible before returning. Only there is an ** ambiguous phrase in the C standard: ** ** <quote> ** Atomic read-modify-write operations shall always read the last ** value (in the modification order) stored before the write ** associated with the read-modify-write operation. ** </quote> ** ** This can be read that for read-modify-write operations the read ** and write operations *must* be effected. **/ unsigned accua(_Atomic(unsigned)*restrict count) { unsigned ret = 0; unsigned tmp = 0; (*count) = 0; while (tmp < 9) { tmp = (*count)++; ret += 2*tmp +1; } return ret; } unsigned accuav(_Atomic(unsigned) volatile*restrict count) { unsigned ret = 0; unsigned tmp = 0; (*count) = 0; while (tmp < 9) { tmp = (*count)++; ret += 2*tmp +1; } return ret; } unsigned accuar(_Atomic(unsigned)*restrict count) { unsigned ret = 0; unsigned tmp = 0; atomic_store_explicit(count, 0, memory_order_relaxed); while (tmp < 9) { tmp = atomic_fetch_add_explicit(count, 1u, memory_order_relaxed); ret += 2*tmp +1; } return ret; } unsigned accuavr(_Atomic(unsigned) volatile*restrict count) { unsigned ret = 0; unsigned tmp = 0; atomic_store_explicit(count, 0, memory_order_relaxed); while (tmp < 9) { tmp = atomic_fetch_add_explicit(count, 1u, memory_order_relaxed); ret += 2*tmp +1; } return ret; } unsigned accut(unsigned*restrict count) { unsigned ret = 0; unsigned tmp = 0; (*count) = 0; while (tmp < 10) { ret += 2*tmp +1; (*count) = ++tmp; } return ret; } unsigned accutv(unsigned volatile*restrict count) { unsigned ret = 0; unsigned tmp = 0; (*count) = 0; while (tmp < 10) { ret += 2*tmp +1; (*count) = ++tmp; } return ret; } unsigned accuta(_Atomic(unsigned)*restrict count) { unsigned ret = 0; unsigned tmp = 0; (*count) = 0; while (tmp < 10) { ret += 2*tmp +1; (*count) = ++tmp; } return ret; } unsigned accutav(_Atomic(unsigned) volatile*restrict count) { unsigned ret = 0; unsigned tmp = 0; (*count) = 0; while (tmp < 10) { ret += 2*tmp +1; (*count) = ++tmp; } return ret; } unsigned accutar(_Atomic(unsigned)*restrict count) { unsigned ret = 0; unsigned tmp = 0; atomic_store_explicit(count, 0, memory_order_relaxed); while (tmp < 10) { ret += 2*tmp +1; atomic_store_explicit(count, ++tmp, memory_order_relaxed); } return ret; } unsigned accutavr(_Atomic(unsigned) volatile*restrict count) { unsigned ret = 0; unsigned tmp = 0; atomic_store_explicit(count, 0, memory_order_relaxed); while (tmp < 10) { ret += 2*tmp +1; atomic_store_explicit(count, ++tmp, memory_order_relaxed); } return ret; }
22.361963
69
0.632647
a15f9abb6c4625bb666ca5a7f508531c4241cbf0
1,144
h
C
Adafruit_Arcada_Filesystem.h
Rexypoo/Adafruit_Arcada
0f1c2be75404d080c81be4f8797c69b52561b619
[ "BSD-3-Clause" ]
64
2019-04-22T01:54:27.000Z
2022-03-14T22:06:43.000Z
Adafruit_Arcada_Filesystem.h
Rexypoo/Adafruit_Arcada
0f1c2be75404d080c81be4f8797c69b52561b619
[ "BSD-3-Clause" ]
33
2019-05-23T23:46:10.000Z
2022-03-14T21:24:27.000Z
Adafruit_Arcada_Filesystem.h
Rexypoo/Adafruit_Arcada
0f1c2be75404d080c81be4f8797c69b52561b619
[ "BSD-3-Clause" ]
27
2019-06-06T12:13:17.000Z
2022-02-23T18:15:06.000Z
#if ARCADA_TFT_WIDTH > 200 #define FILECHOOSEMENU_TEXT_SIZE 2 #else #define FILECHOOSEMENU_TEXT_SIZE 1 #endif #define FILECHOOSEMENU_TEXT_HEIGHT (FILECHOOSEMENU_TEXT_SIZE * 8) #define FILECHOOSEMENU_TEXT_WIDTH (FILECHOOSEMENU_TEXT_SIZE * 6) #define FILECHOOSEMENU_MAX_FILENAME_SIZE 80 #define FILECHOOSEMENU_MAX_LINELENGTH \ (ARCADA_TFT_WIDTH / FILECHOOSEMENU_TEXT_WIDTH) #define FILECHOOSEMENU_MAX_LINES \ ((ARCADA_TFT_HEIGHT / FILECHOOSEMENU_TEXT_HEIGHT) - 2) #define FILECHOOSEMENU_FILE_XOFFSET (FILECHOOSEMENU_TEXT_WIDTH / 2) #define FILECHOOSEMENU_FILE_YOFFSET (2 * FILECHOOSEMENU_TEXT_HEIGHT) #define FILECHOOSEMENU_FILE_W ARCADA_TFT_WIDTH #define FILECHOOSEMENU_FILE_H \ (FILECHOOSEMENU_MAX_LINES * FILECHOOSEMENU_TEXT_HEIGHT) #define FILECHOOSEMENU_FILE_BGCOLOR RGBVAL16(0x00, 0x00, 0x20) #define FILECHOOSEMENU_JOYS_YOFFSET (12 * FILECHOOSEMENU_TEXT_HEIGHT) #define FILECHOOSEMENU_VBAR_XOFFSET (0 * FILECHOOSEMENU_TEXT_WIDTH) #define FILECHOOSEMENU_VBAR_YOFFSET (FILECHOOSEMENU_FILE_YOFFSET)
49.73913
80
0.757867
08ba47e6ab974c102f11ce66917a56d3874ec44d
855
c
C
ch.c
Daksh/CSE231-Assignment_2-Shell
53eeb4510bf050c9f017d5168c9c2305a92dfb7e
[ "MIT" ]
null
null
null
ch.c
Daksh/CSE231-Assignment_2-Shell
53eeb4510bf050c9f017d5168c9c2305a92dfb7e
[ "MIT" ]
null
null
null
ch.c
Daksh/CSE231-Assignment_2-Shell
53eeb4510bf050c9f017d5168c9c2305a92dfb7e
[ "MIT" ]
1
2021-11-14T12:41:24.000Z
2021-11-14T12:41:24.000Z
#include <unistd.h> struct command{ const char **argv; }; void spawn_proc (int in, int out, struct command *cmd) { if (!fork ()){ if (in != 0){ dup2 (in, 0); close (in); } if (out != 1){ dup2 (out, 1); close (out); } execvp (cmd->argv [0], (char * const *)cmd->argv); } } void fork_pipes (int n, struct command *cmd){ int i; int in, fd [2]; in = 0; for (i = 0; i < n - 1; ++i){ pipe (fd); spawn_proc (in, fd [1], cmd + i); close (fd [1]); in = fd [0]; } if (in != 0) dup2 (in, 0); execvp (cmd [i].argv [0], (char * const *)cmd [i].argv); } int main (){ const char *ls[] = { "ls", "-l", 0 }; const char *awk[] = { "awk", "{print $1}", 0 }; const char *sort[] = { "sort", 0 }; const char *uniq[] = { "uniq", 0 }; struct command cmd [] = { {ls}, {sort}, {uniq} }; fork_pipes (4, cmd); return 0; }
16.764706
57
0.497076
8335f3b23f9382c584400506dab790323d7a2f02
4,123
c
C
src/serialization.c
FadiBasheer/chat_assignment
7add5ca3336dba7be29c37308223bf904af1b016
[ "Apache-2.0" ]
null
null
null
src/serialization.c
FadiBasheer/chat_assignment
7add5ca3336dba7be29c37308223bf904af1b016
[ "Apache-2.0" ]
null
null
null
src/serialization.c
FadiBasheer/chat_assignment
7add5ca3336dba7be29c37308223bf904af1b016
[ "Apache-2.0" ]
null
null
null
#include <string.h> #include <stdio.h> #include <stdarg.h> #include <ctype.h> /* ** packi16() -- store a 16-bit int into a char buffer (like htons()) */ void packi16(unsigned char *buf, unsigned int i) { *buf++ = i >> 8; *buf++ = i; } /* ** pack() -- store data dictated by the format string in the buffer ** ** bits |signed unsigned float string ** -----+---------------------------------- ** 8 | c C ** 16 | h H f ** 32 | l L d ** 64 | q Q g ** - | s ** ** (16-bit unsigned length is automatically prepended to strings) */ unsigned int pack(unsigned char *buf, char *format, ...) { va_list ap; signed char c; // 8-bit unsigned char C; int h; // 16-bit unsigned int H; char *s; // strings unsigned int len; unsigned int size = 0; va_start(ap, format); for (; *format != '\0'; format++) { switch (*format) { case 'C': // 8-bit unsigned size += 1; C = (unsigned char) va_arg(ap, unsigned int); // promoted *buf++ = C; break; case 'H': // 16-bit unsigned size += 2; H = va_arg(ap, unsigned int); packi16(buf, H); buf += 2; break; case 's': // string s = va_arg(ap, char*); len = strlen(s); size += len + 2; packi16(buf, len); buf += 2; memcpy(buf, s, len); buf += len; break; } } va_end(ap); return size; } unsigned int unpacku16(unsigned char *buf) { return ((unsigned int) buf[0] << 8) | buf[1]; } /* ** unpack() -- unpack data dictated by the format string into the buffer ** ** bits |signed unsigned float string ** -----+---------------------------------- ** 8 | c C ** 16 | h H f ** 32 | l L d ** 64 | q Q g ** - | s ** ** (string is extracted based on its stored length, but 's' can be ** prepended with a max length) */ void unpack(unsigned char *buf, char *format, ...) { va_list ap; signed char *c; // 8-bit unsigned char *C; int *h; // 16-bit unsigned int *H; long int *l; // 32-bit unsigned long int *L; long long int *q; // 64-bit unsigned long long int *Q; float *f; // floats double *d; long double *g; unsigned long long int fhold; char *s; unsigned int len, maxstrlen = 0, count; va_start(ap, format); for (; *format != '\0'; format++) { switch (*format) { case 'c': // 8-bit c = va_arg(ap, signed char*); if (*buf <= 0x7f) { *c = *buf; } // re-sign else { *c = -1 - (unsigned char) (0xffu - *buf); } buf++; break; case 'C': // 8-bit unsigned C = va_arg(ap, unsigned char*); *C = *buf++; break; case 'H': // 16-bit unsigned H = va_arg(ap, unsigned int*); *H = unpacku16(buf); buf += 2; break; case 's': // string s = va_arg(ap, char*); len = unpacku16(buf); buf += 2; if (maxstrlen > 0 && len >= maxstrlen) count = maxstrlen - 1; else count = len; memcpy(s, buf, count); s[count] = '\0'; buf += len; break; default: if (isdigit(*format)) { // track max str len maxstrlen = maxstrlen * 10 + (*format - '0'); } } if (!isdigit(*format)) maxstrlen = 0; } va_end(ap); }
25.930818
77
0.400194
d3efa8d2300f939c5d27f0e0b371453be90b91f1
37,681
c
C
c6502.c
nanochess/c6502
a3cc677d65c94cea14914a819016ff95ace5c215
[ "BSD-2-Clause" ]
5
2018-06-12T16:04:02.000Z
2021-12-17T16:53:34.000Z
c6502.c
nanochess/c6502
a3cc677d65c94cea14914a819016ff95ace5c215
[ "BSD-2-Clause" ]
null
null
null
c6502.c
nanochess/c6502
a3cc677d65c94cea14914a819016ff95ace5c215
[ "BSD-2-Clause" ]
null
null
null
/* ** 6502 to IntyBASIC compiler ** ** by Oscar Toledo G. ** ** Creation date: Jul/03/2017. ** Revision date: Aug/09/2017. Avoids calculating unnecessary flags. */ #include <stdio.h> #include <stdlib.h> #define R(addr) rom[(addr) & 0x0fff] #define C(addr) checked[(addr) & 0x0fff] typedef unsigned char byte; byte rom[4096]; /* ** bit 1-0 = step of process where it passed (it means code) ** bit 2 = 1 = label ** bit 3 = recalculates n ** bit 4 = recalculates z ** bit 5 = recalculates c ** bit 6 = recalculates v */ byte checked[4096]; #define LABEL 0x04 #define REN 0x08 /* Recalculates N */ #define REZ 0x10 /* Recalculates Z */ #define REC 0x20 /* Recalculates C */ #define REV 0x40 /* Recalculates V */ #define USC 0x80 /* Uses C */ int decimal; FILE *output; int step; #define RA 1 #define RX 2 #define RY 3 #define RS 4 int has_nz; /* ** Avoid store instructions */ int avoid(int address) { while (1) { switch (R(address)) { case 0x84: case 0x94: case 0x85: case 0x95: case 0x86: case 0x96: address += 2; continue; case 0x99: case 0x8d: address += 3; continue; default: return address; } } } /* ** Analyze 6502 code */ void analyze(int address) { int calc; while ((C(address) & 3) != step) { if (C(address) & LABEL) { if (step == 2) fprintf(output, "L%04X:\n", address); } if (step == 2) { if ((C(address) & 3) == 0) { fprintf(output, "\tDATA $%02X\n", R(address)); address++; continue; } } C(address) = (C(address) & ~3) | step; switch (R(address)) { case 0x10: /* BPL rel */ address++; calc = R(address); if (calc >= 128) calc -= 256; calc += address + 1; if (step == 1) { C(calc) |= LABEL; analyze(calc); } else { fprintf(output, "\tIF n = 0 THEN GOTO L%04X\n", calc); } address++; break; case 0x30: /* BMI rel */ address++; calc = R(address); if (calc >= 128) calc -= 256; calc += address + 1; if (step == 1) { C(calc) |= LABEL; analyze(calc); } else { fprintf(output, "\tIF n THEN GOTO L%04X\n", calc); } address++; break; case 0x50: /* BVC rel */ address++; calc = R(address); if (calc >= 128) calc -= 256; calc += address + 1; if (step == 1) { C(calc) |= LABEL; analyze(calc); } else { fprintf(output, "\tIF v = 0 THEN GOTO L%04X\n", calc); } address++; break; case 0x60: /* RTS */ if (step == 1) { return; } else { fprintf(output, "\tRETURN\n"); } address++; break; case 0x90: /* BCC rel */ address++; calc = R(address); if (calc >= 128) calc -= 256; calc += address + 1; if (step == 1) { C(calc) |= LABEL; analyze(calc); } else { fprintf(output, "\tIF c = 0 THEN GOTO L%04X\n", calc); } address++; break; case 0xa0: /* LDY #imm */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ty = $%02X\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = y AND $80:z = y = 0\n"); } address++; break; case 0xb0: /* BCS rel */ address++; calc = R(address); if (calc >= 128) calc -= 256; calc += address + 1; if (step == 1) { C(calc) |= LABEL; analyze(calc); } else { fprintf(output, "\tIF c THEN GOTO L%04X\n", calc); } address++; break; case 0xc0: /* CPY #imm */ C(address) |= REZ | REN | REC; address++; if (step == 2) { fprintf(output, "\t#t = y - $%02X\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = #t AND $80:z = (#t AND 255) = 0\n"); fprintf(output, "\tc = (#t / 256) = 0\n"); } address++; break; case 0xd0: /* BNE rel */ address++; calc = R(address); if (calc >= 128) calc -= 256; calc += address + 1; if (step == 1) { C(calc) |= LABEL; analyze(calc); } else { fprintf(output, "\tIF z = 0 THEN GOTO L%04X\n", calc); } address++; break; case 0xe0: /* CPX #imm */ C(address) |= REZ | REN | REC; address++; if (step == 2) { fprintf(output, "\t#t = x - $%02X\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = #t AND $80:z = (#t AND 255) = 0\n"); fprintf(output, "\tc = (#t / 256) = 0\n"); } address++; break; case 0xf0: /* BEQ rel */ address++; calc = R(address); if (calc >= 128) calc -= 256; calc += address + 1; if (step == 1) { C(calc) |= LABEL; analyze(calc); } else { fprintf(output, "\tIF z THEN GOTO L%04X\n", calc); } address++; break; case 0x20: /* JSR abs */ address++; if (step == 1) { C(R(address) | R(address + 1) << 8) |= LABEL; analyze(R(address) | R(address + 1) << 8); } else { fprintf(output, "\tGOSUB L%04X\n", R(address) | R(address + 1) << 8); } address += 2; break; case 0xb1: /* LDA ind,Y */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = zp(zp($%02X) + y)\t' !!!\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0xa2: /* LDX #imm */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\tx = $%02X\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = x AND $80:z = x = 0\n"); } address++; break; case 0x24: /* BIT zpg */ C(address) |= REZ | REN | REV; address++; if (step == 2) { if ((C(avoid(address + 1)) & (REN)) != (REN)) fprintf(output, "\tn = zp($%02X) AND $80\n", R(address)); if ((C(avoid(address + 1)) & (REZ)) != (REZ)) fprintf(output, "\tz = (zp($%02X) AND a) = 0\n", R(address)); fprintf(output, "\tv = zp($%02X) AND $40\n", R(address)); } address++; break; case 0x84: /* STY zpg */ address++; if (step == 2) { fprintf(output, "\tzp($%02X) = y\n", R(address)); } address++; break; case 0x94: /* STY zpg,x */ address++; if (step == 2) { fprintf(output, "\tzp($%02X + x) = y\n", R(address)); } address++; break; case 0xa4: /* LDY zpg */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ty = zp($%02X)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = y AND $80:z = y = 0\n"); } address++; break; case 0xb4: /* LDY zpg,x */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ty = zp($%02X + x)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = y AND $80:z = y = 0\n"); } address++; break; case 0x05: /* ORA zpg */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = a OR zp($%02X)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0x15: /* ORA zpg,x */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = a OR zp($%02X + x)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0x25: /* AND zpg */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = a AND zp($%02X)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0x35: /* AND zpg,x */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = a AND zp($%02X + x)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0x45: /* EOR zpg */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = a XOR zp($%02X)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0x55: /* EOR zpg,x */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = a XOR zp($%02X + x)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0x65: /* ADC zpg */ C(address) |= REZ | REN | REC | USC; address++; if (step == 2) { fprintf(output, "\t#t = a + zp($%02X) + c\n", R(address)); fprintf(output, "\ta = #t\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); fprintf(output, "\tc = #t / 256\n"); } address++; break; case 0x75: /* ADC zpg,x */ C(address) |= REZ | REN | REC | USC; address++; if (step == 2) { fprintf(output, "\t#t = a + zp($%02X + x) + c\n", R(address)); fprintf(output, "\ta = #t\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); fprintf(output, "\tc = #t / 256\n"); } address++; break; case 0x85: /* STA zpg */ address++; if (step == 2) { fprintf(output, "\tzp($%02X) = a\n", R(address)); } address++; break; case 0x95: /* STA zpg,X */ address++; if (step == 2) fprintf(output, "\tzp(x + $%02X) = a\n", R(address)); address++; break; case 0xa5: /* LDA zpg */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = zp($%02X)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0xb5: /* LDA zpg,X */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = zp($%02X + x)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0xc5: /* CMP zpg */ C(address) |= REZ | REN | REC; address++; if (step == 2) { fprintf(output, "\t#t = a - zp($%02X)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = #t AND $80:z = (#t AND 255) = 0\n"); fprintf(output, "\tc = (#t / 256) = 0\n"); } address++; break; case 0xd5: /* CMP zpg,x */ C(address) |= REZ | REN | REC; address++; if (step == 2) { fprintf(output, "\t#t = a - zp($%02X + x)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = #t AND $80:z = (#t AND 255) = 0\n"); fprintf(output, "\tc = (#t / 256) = 0\n"); } address++; break; case 0xe5: /* SBC zpg */ C(address) |= REZ | REN | REC | USC; address++; if (step == 2) { fprintf(output, "\t#t = a + (zp($%02X) XOR $FF) + c\n", R(address)); fprintf(output, "\ta = #t\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); fprintf(output, "\tc = #t / 256\n"); } address++; break; case 0xf5: /* SBC zpg,x */ C(address) |= REZ | REN | REC | USC; address++; if (step == 2) { fprintf(output, "\t#t = a + (zp($%02X + x) XOR $FF) + c\n", R(address)); fprintf(output, "\ta = #t\n"); fprintf(output, "\tn = a AND $80:z = a = 0\n"); fprintf(output, "\tc = #t / 256\n"); } address++; break; case 0x06: /* ASL zpg */ C(address) |= REZ | REC; address++; if (step == 2) { if ((C(avoid(address + 1)) & (REC | USC)) != (REC)) fprintf(output, "\tc = zp($%02X) AND 128\n", R(address)); fprintf(output, "\tzp($%02X) = zp($%02X) * 2\n", R(address), R(address)); if ((C(avoid(address + 1)) & (REZ)) != (REZ)) fprintf(output, "\tz = zp($%02X) = 0\n", R(address)); } address++; break; case 0x26: /* ROL zpg */ C(address) |= REZ | REC | USC; address++; if (step == 2) { fprintf(output, "\t#t = c\n"); fprintf(output, "\tc = zp($%02X) AND $80\n", R(address)); fprintf(output, "\tzp($%02X) = zp($%02X) * 2\n", R(address), R(address)); if ((C(avoid(address + 1)) & (REZ)) != (REZ)) fprintf(output, "\tz = zp($%02X) = 0\n", R(address)); } address++; break; case 0x46: /* LSR zpg */ C(address) |= REZ | REC; address++; if (step == 2) { if ((C(avoid(address + 1)) & (REC | USC)) != (REC)) fprintf(output, "\tc = zp($%02X) AND 1\n", R(address)); fprintf(output, "\tzp($%02X) = zp($%02X) / 2\n", R(address), R(address)); if ((C(avoid(address + 1)) & (REZ)) != (REZ)) fprintf(output, "\tz = zp($%02X) = 0\n", R(address)); } address++; break; case 0x66: /* ROR zpg */ C(address) |= REZ | REC | USC; address++; if (step == 2) { fprintf(output, "\t#t = c\n"); fprintf(output, "\tc = zp($%02X) AND 1\n", R(address)); fprintf(output, "\tzp($%02X) = zp($%02X) / 2 + #t * 128\n", R(address), R(address)); if ((C(avoid(address + 1)) & (REZ)) != (REZ)) fprintf(output, "\tz = zp($%02X) = 0\n", R(address)); } address++; break; case 0x86: /* STX zpg */ address++; if (step == 2) { fprintf(output, "\tzp($%02X) = x\n", R(address)); } address++; break; case 0x96: /* STX zpg,y */ address++; if (step == 2) { fprintf(output, "\tzp($%02X + y) = x\n", R(address)); } address++; break; case 0xa6: /* LDX zpg */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\tx = zp($%02X)\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = x AND $80:z = x = 0\n"); } address++; break; case 0xc6: /* DEC zpg */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\tzp($%02X) = zp($%02X) - 1\n", R(address), R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = zp($%02X) AND $80:z = zp($%02X) = 0\n", R(address), R(address)); } address++; break; case 0xe6: /* INC zpg */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\tzp($%02X) = zp($%02X) + 1\n", R(address), R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = zp($%02X) AND $80:z = zp($%02X) = 0\n", R(address), R(address)); } address++; break; case 0xf6: /* INC zpg,x */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\tzp($%02X + x) = zp($%02X + x) + 1\n", R(address), R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = zp($%02X + x) AND $80:z = zp($%02X + x) = 0\n", R(address), R(address)); } address++; break; case 0x18: /* CLC */ C(address) |= REC; if (step == 2) fprintf(output, "\tc = 0\n"); address++; break; case 0x38: /* SEC */ C(address) |= REC; if (step == 2) fprintf(output, "\tc = 1\n"); address++; break; case 0x78: /* SEI */ if (step == 2) fprintf(output, "\t' SEI\n"); address++; break; case 0x88: /* DEY */ C(address) |= REZ | REN; if (step == 2) { fprintf(output, "\ty = y - 1\n"); fprintf(output, "\tn = y AND $80:z = y = 0\n"); } address++; break; case 0x98: /* TYA */ C(address) |= REZ | REN; if (step == 2) { fprintf(output, "\ta = y\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0xa8: /* TAY */ C(address) |= REZ | REN; if (step == 2) { fprintf(output, "\ty = a\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = y AND $80:z = y = 0\n"); } address++; break; case 0xc8: /* INY */ C(address) |= REZ | REN; if (step == 2) { fprintf(output, "\ty = y + 1\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = y AND $80:z = y = 0\n"); } address++; break; case 0xd8: /* CLD */ if (step == 2) fprintf(output, "\t' Entering binary mode\n"); decimal = 0; address++; break; case 0xe8: /* INX */ C(address) |= REZ | REN; if (step == 2) { fprintf(output, "\tx = x + 1\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = x AND $80:z = x = 0\n"); } address++; break; case 0xf8: /* SED */ if (step == 2) fprintf(output, "\t' Entering decimal mode\n"); decimal = 1; address++; break; case 0x09: /* ORA #imm */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = a OR $%02X\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0x29: /* AND #imm */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = a AND $%02X\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0x39: /* AND abs,y */ C(address) |= REZ | REN; address++; if (step == 2) { calc = R(address) | R(address + 1) << 8; C(calc) |= LABEL; fprintf(output, "\ta = a AND L%04X(y)\n", calc); if ((C(avoid(address + 2)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address += 2; break; case 0x49: /* EOR #imm */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = a XOR $%02X\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0x69: /* ADC #imm */ C(address) |= REZ | REN | REC | USC; address++; if (step == 2) { fprintf(output, "\t#t = a + $%02X + c\n", R(address)); fprintf(output, "\ta = #t\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); fprintf(output, "\tc = #t / 256\n"); } address++; break; case 0x79: /* ADC abs,y */ C(address) |= REZ | REN | REC | USC; address++; if (step == 2) { calc = R(address) | R(address + 1) << 8; C(calc) |= LABEL; fprintf(output, "\t#t = a + L%04X(y) + c\n", calc); fprintf(output, "\ta = #t\n"); if ((C(avoid(address + 2)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); fprintf(output, "\tc = #t / 256\n"); } address += 2; break; case 0x99: /* STA abs,y */ address++; if (step == 2) { calc = R(address) | R(address + 1) << 8; C(calc) |= LABEL; fprintf(output, "\tL%04X(y) = a\n", calc); } address += 2; break; case 0xa9: /* LDA #imm */ C(address) |= REZ | REN; address++; if (step == 2) { fprintf(output, "\ta = $%02X\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0xb9: /* LDA abs,y */ C(address) |= REZ | REN; address++; if (step == 2) { calc = R(address) | R(address + 1) << 8; C(calc) |= LABEL; fprintf(output, "\ta = L%04X(y)\n", calc); if ((C(avoid(address + 2)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address += 2; break; case 0xc9: /* CMP #imm */ C(address) |= REZ | REN | REC; address++; if (step == 2) { fprintf(output, "\t#t = a - $%02X\n", R(address)); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = #t AND $80:z = (#t AND 255) = 0\n"); fprintf(output, "\tc = (#t / 256) = 0\n"); } address++; break; case 0xe9: /* SBC #imm */ C(address) |= REZ | REN | REC | USC; address++; if (step == 2) { fprintf(output, "\t#t = a + ($%02X XOR $FF) + c\n", R(address)); fprintf(output, "\ta = #t\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); fprintf(output, "\tc = #t / 256\n"); } address++; break; case 0x0a: /* ASL */ C(address) |= REZ | REC; if (step == 2) { if ((C(avoid(address + 1)) & (REC | USC)) != (REC)) fprintf(output, "\tc = a AND 128\n"); fprintf(output, "\ta = a * 2\n"); if ((C(avoid(address + 1)) & (REZ)) != (REZ)) fprintf(output, "\tz = a = 0\n"); } address++; break; case 0x2a: /* ROL */ C(address) |= REZ | REC | USC; if (step == 2) { fprintf(output, "\t#t = c\n"); fprintf(output, "\tc = a AND 1\n"); fprintf(output, "\ta = a * 2 + #t\n"); if ((C(avoid(address + 1)) & (REZ)) != (REZ)) fprintf(output, "\tz = a = 0\n"); } address++; break; case 0x4a: /* LSR */ C(address) |= REZ | REC; if (step == 2) { if ((C(avoid(address + 1)) & (REC | USC)) != (REC)) fprintf(output, "\tc = a AND 1\n"); fprintf(output, "\ta = a / 2\n"); if ((C(avoid(address + 1)) & (REZ)) != (REZ)) fprintf(output, "\tz = a = 0\n"); } address++; break; case 0x8a: /* TXA */ C(address) |= REZ | REN; if (step == 2) { fprintf(output, "\ta = x\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address++; break; case 0x9a: /* TXS */ C(address) |= REZ | REN; if (step == 2) { fprintf(output, "\ts = x\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = x AND $80:z = x = 0\n"); } address++; break; case 0xaa: /* TAX */ C(address) |= REZ | REN; if (step == 2) { fprintf(output, "\tx = a\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = x AND $80:z = x = 0\n"); } address++; break; case 0xca: /* DEX */ C(address) |= REZ | REN; if (step == 2) { fprintf(output, "\tx = x - 1\n"); if ((C(avoid(address + 1)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = x AND $80:z = x = 0\n"); } address++; break; case 0xea: /* NOP */ if (step == 2) { fprintf(output, "\t' NOP\n"); } address++; break; case 0x4c: /* JMP abs */ address++; if (step == 1) { C(R(address) | R(address + 1) << 8) |= LABEL; analyze(R(address) | R(address + 1) << 8); return; } else { fprintf(output, "\tGOTO L%04X\n\n", R(address) | R(address + 1) << 8); } address += 2; break; case 0x7d: /* ADC abs,x */ C(address) |= REZ | REN | REC | USC; address++; if (step == 2) { calc = R(address) | R(address + 1) << 8; C(calc) |= LABEL; fprintf(output, "\t#t = a + L%04X(x) + c\n", calc); fprintf(output, "\ta = #t\n"); if ((C(avoid(address + 2)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); fprintf(output, "\tc = #t / 256\n"); } address += 2; break; case 0x8d: /* STA abs */ address++; if (step == 2) { calc = R(address) | R(address + 1) << 8; C(calc) |= LABEL; fprintf(output, "\tL%04X(0) = a\n", calc); } address += 2; break; case 0xad: /* LDA abs */ C(address) |= REZ | REN; address++; if (step == 2) { calc = R(address) | R(address + 1) << 8; C(calc) |= LABEL; fprintf(output, "\ta = L%04X(0)\n", calc); if ((C(avoid(address + 2)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address += 2; break; case 0xbd: /* LDA abs,x */ C(address) |= REZ | REN; address++; if (step == 2) { calc = R(address) | R(address + 1) << 8; C(calc) |= LABEL; fprintf(output, "\ta = L%04X(x)\n", calc); if ((C(avoid(address + 2)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = a AND $80:z = a = 0\n"); } address += 2; break; case 0xbe: /* LDX abs,y */ C(address) |= REZ | REN; address++; if (step == 2) { calc = R(address) | R(address + 1) << 8; C(calc) |= LABEL; fprintf(output, "\tx = L%04X(y)\n", calc); if ((C(avoid(address + 2)) & (REZ | REN)) != (REZ | REN)) fprintf(output, "\tn = x AND $80:z = x = 0\n"); } address += 2; break; default: fprintf(stderr, "Unhandled opcode $%02x at $%04x\n", R(address), address); return; } } } /* ** Main program */ int main(int argc, char *argv[]) { FILE *input; int start; fprintf(stderr, "6502 to IntyBASIC compiler. http://nanochess.org/\n\n"); if (argc != 3) { fprintf(stderr, "Usage:\n\n"); fprintf(stderr, " c6502 input.rom output.bas\n\n"); fprintf(stderr, "Only 4K ROM supported and it will generate\n"); fprintf(stderr, "non-working programs. Sorry :P\n\n"); exit(1); } input = fopen(argv[1], "rb"); if (input == NULL) { fprintf(stderr, "Failure to open input file: %s\n", argv[1]); exit(1); } output = fopen(argv[2], "w"); if (output == NULL) { fclose(input); fprintf(stderr, "Failure to open output file: %s\n", argv[2]); exit(1); } if (fread(rom, 1, sizeof(rom), input) != sizeof(rom)) { fclose(input); fprintf(stderr, "Input ROM size isn't 4 kilobytes\n"); exit(1); } fclose(input); start = rom[0x0ffc] | (rom[0x0ffd] << 8); fprintf(stderr, "Starting analysis at %04X\n...\n", start); step = 1; analyze(start); step = 2; analyze(start); fclose(output); exit(0); }
39.169439
119
0.333882
ebf5c7b771436d270623e50784690c239d518e4d
6,017
c
C
rcl/src/rcl/init_options.c
hku-systems/Coorp-ROS2-rcl
0ab865c4d6616bec9888cfddd261e9de006326c4
[ "Apache-2.0" ]
null
null
null
rcl/src/rcl/init_options.c
hku-systems/Coorp-ROS2-rcl
0ab865c4d6616bec9888cfddd261e9de006326c4
[ "Apache-2.0" ]
null
null
null
rcl/src/rcl/init_options.c
hku-systems/Coorp-ROS2-rcl
0ab865c4d6616bec9888cfddd261e9de006326c4
[ "Apache-2.0" ]
null
null
null
// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifdef __cplusplus extern "C" { #endif #include "rcl/init_options.h" #include "./common.h" #include "./init_options_impl.h" #include "rcutils/macros.h" #include "rcl/error_handling.h" #include "rmw/error_handling.h" #include "rcutils/logging_macros.h" rcl_init_options_t rcl_get_zero_initialized_init_options(void) { return (const rcl_init_options_t) { .impl = 0, }; // NOLINT(readability/braces): false positive } rcl_ret_t rcl_init_options_init(rcl_init_options_t * init_options, rcl_allocator_t allocator) { RCUTILS_CAN_SET_MSG_AND_RETURN_WITH_ERROR_OF(RCL_RET_INVALID_ARGUMENT); RCUTILS_CAN_SET_MSG_AND_RETURN_WITH_ERROR_OF(RCL_RET_ALREADY_INIT); RCUTILS_CAN_SET_MSG_AND_RETURN_WITH_ERROR_OF(RCL_RET_BAD_ALLOC); RCUTILS_CAN_SET_MSG_AND_RETURN_WITH_ERROR_OF(RCL_RET_ERROR); RCL_CHECK_ARGUMENT_FOR_NULL(init_options, RCL_RET_INVALID_ARGUMENT); if (NULL != init_options->impl) { RCL_SET_ERROR_MSG("given init_options (rcl_init_options_t) is already initialized"); return RCL_RET_ALREADY_INIT; } RCL_CHECK_ALLOCATOR(&allocator, return RCL_RET_INVALID_ARGUMENT); init_options->impl = allocator.allocate(sizeof(rcl_init_options_impl_t), allocator.state); RCL_CHECK_FOR_NULL_WITH_MSG( init_options->impl, "failed to allocate memory for init options impl", return RCL_RET_BAD_ALLOC); init_options->impl->allocator = allocator; init_options->impl->rmw_init_options = rmw_get_zero_initialized_init_options(); rmw_ret_t rmw_ret = rmw_init_options_init(&(init_options->impl->rmw_init_options), allocator); if (RMW_RET_OK != rmw_ret) { allocator.deallocate(init_options->impl, allocator.state); RCL_SET_ERROR_MSG(rmw_get_error_string().str); return rcl_convert_rmw_ret_to_rcl_ret(rmw_ret); } return RCL_RET_OK; } rcl_ret_t rcl_init_options_copy(const rcl_init_options_t * src, rcl_init_options_t * dst) { RCUTILS_CAN_SET_MSG_AND_RETURN_WITH_ERROR_OF(RCL_RET_INVALID_ARGUMENT); RCUTILS_CAN_SET_MSG_AND_RETURN_WITH_ERROR_OF(RCL_RET_ALREADY_INIT); RCUTILS_CAN_SET_MSG_AND_RETURN_WITH_ERROR_OF(RCL_RET_BAD_ALLOC); RCUTILS_CAN_SET_MSG_AND_RETURN_WITH_ERROR_OF(RCL_RET_ERROR); RCL_CHECK_ARGUMENT_FOR_NULL(src, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(src->impl, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(dst, RCL_RET_INVALID_ARGUMENT); if (NULL != dst->impl) { RCL_SET_ERROR_MSG("given dst (rcl_init_options_t) is already initialized"); return RCL_RET_ALREADY_INIT; } // initialize dst (since we know it's in a zero initialized state) rcl_ret_t ret = rcl_init_options_init(dst, src->impl->allocator); if (RCL_RET_OK != ret) { return ret; // error already set } // copy src information into dst dst->impl->allocator = src->impl->allocator; // first zero-initialize rmw init options rmw_ret_t rmw_ret = rmw_init_options_fini(&(dst->impl->rmw_init_options)); if (RMW_RET_OK != rmw_ret) { rmw_error_string_t error_string = rmw_get_error_string(); rmw_reset_error(); ret = rcl_init_options_fini(dst); if (RCL_RET_OK != ret) { RCUTILS_LOG_ERROR_NAMED( "rcl", "failed to finalize dst rcl_init_options while handling failure to " "finalize rmw_init_options, original ret '%d' and error: %s", rmw_ret, error_string.str); return ret; // error already set } RCL_SET_ERROR_MSG(error_string.str); return rcl_convert_rmw_ret_to_rcl_ret(rmw_ret); } // then copy dst->impl->rmw_init_options = rmw_get_zero_initialized_init_options(); rmw_ret = rmw_init_options_copy(&(src->impl->rmw_init_options), &(dst->impl->rmw_init_options)); if (RMW_RET_OK != rmw_ret) { rmw_error_string_t error_string = rmw_get_error_string(); rmw_reset_error(); ret = rcl_init_options_fini(dst); if (RCL_RET_OK != ret) { RCUTILS_LOG_ERROR_NAMED( "rcl", "failed to finalize dst rcl_init_options while handling failure to " "copy rmw_init_options, original ret '%d' and error: %s", rmw_ret, error_string.str); return ret; // error already set } RCL_SET_ERROR_MSG(error_string.str); return rcl_convert_rmw_ret_to_rcl_ret(rmw_ret); } return RCL_RET_OK; } rcl_ret_t rcl_init_options_fini(rcl_init_options_t * init_options) { RCL_CHECK_ARGUMENT_FOR_NULL(init_options, RCL_RET_INVALID_ARGUMENT); RCL_CHECK_ARGUMENT_FOR_NULL(init_options->impl, RCL_RET_INVALID_ARGUMENT); rcl_allocator_t allocator = init_options->impl->allocator; RCL_CHECK_ALLOCATOR(&allocator, return RCL_RET_INVALID_ARGUMENT); rmw_ret_t rmw_ret = rmw_init_options_fini(&(init_options->impl->rmw_init_options)); if (RMW_RET_OK != rmw_ret) { RCL_SET_ERROR_MSG(rmw_get_error_string().str); return rcl_convert_rmw_ret_to_rcl_ret(rmw_ret); } allocator.deallocate(init_options->impl, allocator.state); return RCL_RET_OK; } rmw_init_options_t * rcl_init_options_get_rmw_init_options(rcl_init_options_t * init_options) { RCL_CHECK_ARGUMENT_FOR_NULL(init_options, NULL); RCL_CHECK_ARGUMENT_FOR_NULL(init_options->impl, NULL); return &(init_options->impl->rmw_init_options); } const rcl_allocator_t * rcl_init_options_get_allocator(const rcl_init_options_t * init_options) { RCL_CHECK_ARGUMENT_FOR_NULL(init_options, NULL); RCL_CHECK_ARGUMENT_FOR_NULL(init_options->impl, NULL); return &(init_options->impl->allocator); } #ifdef __cplusplus } #endif
36.689024
97
0.772312
23545db254d5869fce0894a6f7611b8f9cb64388
2,150
h
C
catboost/private/libs/options/oblivious_tree_options.h
jochenater/catboost
de2786fbc633b0d6ea6a23b3862496c6151b95c2
[ "Apache-2.0" ]
6,989
2017-07-18T06:23:18.000Z
2022-03-31T15:58:36.000Z
catboost/private/libs/options/oblivious_tree_options.h
jochenater/catboost
de2786fbc633b0d6ea6a23b3862496c6151b95c2
[ "Apache-2.0" ]
1,978
2017-07-18T09:17:58.000Z
2022-03-31T14:28:43.000Z
catboost/private/libs/options/oblivious_tree_options.h
jochenater/catboost
de2786fbc633b0d6ea6a23b3862496c6151b95c2
[ "Apache-2.0" ]
1,228
2017-07-18T09:03:13.000Z
2022-03-29T05:57:40.000Z
#pragma once #include "option.h" #include "bootstrap_options.h" #include "feature_penalties_options.h" #include <util/system/types.h> namespace NJson { class TJsonValue; } namespace NCatboostOptions { class TObliviousTreeLearnerOptions { public: explicit TObliviousTreeLearnerOptions(ETaskType taskType); void Save(NJson::TJsonValue* options) const; void Load(const NJson::TJsonValue& options) ; bool operator==(const TObliviousTreeLearnerOptions& rhs) const; bool operator!=(const TObliviousTreeLearnerOptions& rhs) const; void Validate() const; TOption<ui32> MaxDepth; TOption<ui32> LeavesEstimationIterations; TOption<ELeavesEstimation> LeavesEstimationMethod; TOption<float> L2Reg; TOption<float> PairwiseNonDiagReg; TOption<float> RandomStrength; TOption<TBootstrapConfig> BootstrapConfig; TOption<float> Rsm; TOption<ELeavesEstimationStepBacktracking> LeavesEstimationBacktrackingType; TOption<EScoreFunction> ScoreFunction; TOption<EGrowPolicy> GrowPolicy; TOption<ui32> MaxLeaves; TOption<double> MinDataInLeaf; TOption<ui32> DevExclusiveFeaturesBundleMaxBuckets; TCpuOnlyOption<ESamplingFrequency> SamplingFrequency; TOption<float> ModelSizeReg; // changing this parameter can affect results due to numerical accuracy differences TCpuOnlyOption<ui32> DevScoreCalcObjBlockSize; TCpuOnlyOption<float> SparseFeaturesConflictFraction; TGpuOnlyOption<EObservationsToBootstrap> ObservationsToBootstrap; TGpuOnlyOption<bool> FoldSizeLossNormalization; TGpuOnlyOption<bool> AddRidgeToTargetFunctionFlag; TGpuOnlyOption<ui32> MaxCtrComplexityForBordersCaching; TGpuOnlyOption<float> MetaL2Exponent; TGpuOnlyOption<float> MetaL2Frequency; TCpuOnlyOption<TMap<ui32, int>> MonotoneConstraints; TCpuOnlyOption <bool> DevLeafwiseApproxes; TCpuOnlyOption<TFeaturePenaltiesOptions> FeaturePenalties; private: TOption<ETaskType> TaskType; }; }
33.59375
91
0.728837
d92ddbb8c1794a05c501b9e86a8937f35cd00cc7
35,221
h
C
netfpga_src/project/reference_emu/sw/embedded/src/sume_register_defines.h
NaaS/emu-live
1de49d99f159642127cce9152a81335f97255069
[ "Apache-2.0" ]
3
2018-03-08T22:11:31.000Z
2021-06-29T08:16:07.000Z
netfpga_src/project/reference_emu/sw/embedded/src/sume_register_defines.h
NaaS/emu-live
1de49d99f159642127cce9152a81335f97255069
[ "Apache-2.0" ]
null
null
null
netfpga_src/project/reference_emu/sw/embedded/src/sume_register_defines.h
NaaS/emu-live
1de49d99f159642127cce9152a81335f97255069
[ "Apache-2.0" ]
1
2018-04-06T14:53:01.000Z
2018-04-06T14:53:01.000Z
/******************************************************************* * Copyright (c) 2015 University of Cambridge * All rights reserved. * * This software was developed by Stanford University and the University of Cambridge Computer Laboratory * under National Science Foundation under Grant No. CNS-0855268, * the University of Cambridge Computer Laboratory under EPSRC INTERNET Project EP/H040536/1 and * by the University of Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-11-C-0249 ("MRC2"), * as part of the DARPA MRC research programme. * * Use of this source code is governed by the Apache 2.0 license; see LICENSE file /******************************************************************* * This is an automatically generated header definitions file *******************************************************************/ /******************************************************************* * Definitions for MICROBLAZE_AXI_IIC *******************************************************************/ #define SUME_MICROBLAZE_AXI_IIC_BASEADDR 0x40800000 #define SUME_MICROBLAZE_AXI_IIC_HIGHADDR 0x4080FFFF #define SUME_MICROBLAZE_AXI_IIC_SIZEADDR 0x10000 /******************************************************************* * Definitions for MICROBLAZE_UARTLITE *******************************************************************/ #define SUME_MICROBLAZE_UARTLITE_BASEADDR 0x40600000 #define SUME_MICROBLAZE_UARTLITE_HIGHADDR 0x4060FFFF #define SUME_MICROBLAZE_UARTLITE_SIZEADDR 0x10000 /******************************************************************* * Definitions for MICROBLAZE_DLMB_BRAM *******************************************************************/ #define SUME_MICROBLAZE_DLMB_BRAM_BASEADDR 0x00000000 #define SUME_MICROBLAZE_DLMB_BRAM_HIGHADDR 0x0000FFFF #define SUME_MICROBLAZE_DLMB_BRAM_SIZEADDR 0x10000 /******************************************************************* * Definitions for MICROBLAZE_ILMB_BRAM *******************************************************************/ #define SUME_MICROBLAZE_ILMB_BRAM_BASEADDR 0x00000000 #define SUME_MICROBLAZE_ILMB_BRAM_HIGHADDR 0x0000FFFF #define SUME_MICROBLAZE_ILMB_BRAM_SIZEADDR 0x10000 /******************************************************************* * Definitions for MICROBLAZE_AXI_INTC *******************************************************************/ #define SUME_MICROBLAZE_AXI_INTC_BASEADDR 0x41200000 #define SUME_MICROBLAZE_AXI_INTC_HIGHADDR 0x4120FFFF #define SUME_MICROBLAZE_AXI_INTC_SIZEADDR 0x10000 /******************************************************************* * Definitions for INPUT_ARBITER *******************************************************************/ #define SUME_INPUT_ARBITER_BASEADDR 0x44010000 #define SUME_INPUT_ARBITER_HIGHADDR 0x44010FFF #define SUME_INPUT_ARBITER_SIZEADDR 0x1000 #define SUME_INPUT_ARBITER_0_ID_OFFSET 0x0 #define SUME_INPUT_ARBITER_0_ID_DEFAULT 0x0000DA01 #define SUME_INPUT_ARBITER_0_ID_WIDTH 32 #define SUME_INPUT_ARBITER_0_VERSION_OFFSET 0x4 #define SUME_INPUT_ARBITER_0_VERSION_DEFAULT 0x1 #define SUME_INPUT_ARBITER_0_VERSION_WIDTH 32 #define SUME_INPUT_ARBITER_0_RESET_OFFSET 0x8 #define SUME_INPUT_ARBITER_0_RESET_DEFAULT 0x0 #define SUME_INPUT_ARBITER_0_RESET_WIDTH 16 #define SUME_INPUT_ARBITER_0_FLIP_OFFSET 0xC #define SUME_INPUT_ARBITER_0_FLIP_DEFAULT 0x0 #define SUME_INPUT_ARBITER_0_FLIP_WIDTH 32 #define SUME_INPUT_ARBITER_0_DEBUG_OFFSET 0x10 #define SUME_INPUT_ARBITER_0_DEBUG_DEFAULT 0x0 #define SUME_INPUT_ARBITER_0_DEBUG_WIDTH 32 #define SUME_INPUT_ARBITER_0_PKTIN_OFFSET 0x14 #define SUME_INPUT_ARBITER_0_PKTIN_DEFAULT 0x0 #define SUME_INPUT_ARBITER_0_PKTIN_WIDTH 32 #define SUME_INPUT_ARBITER_0_PKTOUT_OFFSET 0x18 #define SUME_INPUT_ARBITER_0_PKTOUT_DEFAULT 0x0 #define SUME_INPUT_ARBITER_0_PKTOUT_WIDTH 32 /******************************************************************* * Definitions for OUTPUT_QUEUES *******************************************************************/ #define SUME_OUTPUT_QUEUES_BASEADDR 0x44030000 #define SUME_OUTPUT_QUEUES_HIGHADDR 0x44030FFF #define SUME_OUTPUT_QUEUES_SIZEADDR 0x1000 #define SUME_OUTPUT_QUEUES_0_ID_OFFSET 0x0 #define SUME_OUTPUT_QUEUES_0_ID_DEFAULT 0x0000DA03 #define SUME_OUTPUT_QUEUES_0_ID_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_VERSION_OFFSET 0x4 #define SUME_OUTPUT_QUEUES_0_VERSION_DEFAULT 0x1 #define SUME_OUTPUT_QUEUES_0_VERSION_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_RESET_OFFSET 0x8 #define SUME_OUTPUT_QUEUES_0_RESET_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_RESET_WIDTH 16 #define SUME_OUTPUT_QUEUES_0_FLIP_OFFSET 0xC #define SUME_OUTPUT_QUEUES_0_FLIP_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_FLIP_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_DEBUG_OFFSET 0x10 #define SUME_OUTPUT_QUEUES_0_DEBUG_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_DEBUG_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTIN_OFFSET 0x14 #define SUME_OUTPUT_QUEUES_0_PKTIN_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTIN_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTOUT_OFFSET 0x18 #define SUME_OUTPUT_QUEUES_0_PKTOUT_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTOUT_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT0_OFFSET 0x1C #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT0_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT0_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT0_OFFSET 0x20 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT0_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT0_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT0_OFFSET 0x24 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT0_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT0_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT0_OFFSET 0x28 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT0_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT0_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT0_OFFSET 0x2C #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT0_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT0_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT0_OFFSET 0x30 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT0_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT0_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT0_OFFSET 0x34 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT0_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT0_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT1_OFFSET 0x38 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT1_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT1_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT1_OFFSET 0x3C #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT1_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT1_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT1_OFFSET 0x40 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT1_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT1_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT1_OFFSET 0x44 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT1_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT1_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT1_OFFSET 0x48 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT1_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT1_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT1_OFFSET 0x4C #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT1_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT1_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT1_OFFSET 0x50 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT1_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT1_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT2_OFFSET 0x54 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT2_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT2_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT2_OFFSET 0x58 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT2_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT2_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT2_OFFSET 0x5C #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT2_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT2_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT2_OFFSET 0x60 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT2_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT2_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT2_OFFSET 0x64 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT2_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT2_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT2_OFFSET 0x68 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT2_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT2_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT2_OFFSET 0x6C #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT2_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT2_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT3_OFFSET 0x70 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT3_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT3_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT3_OFFSET 0x74 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT3_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT3_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT3_OFFSET 0x78 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT3_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT3_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT3_OFFSET 0x7C #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT3_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT3_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT3_OFFSET 0x80 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT3_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT3_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT3_OFFSET 0x84 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT3_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT3_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT3_OFFSET 0x88 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT3_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT3_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT4_OFFSET 0x8C #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT4_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTSTOREDPORT4_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT4_OFFSET 0x90 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT4_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESSTOREDPORT4_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT4_OFFSET 0x94 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT4_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTREMOVEDPORT4_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT4_OFFSET 0x98 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT4_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESREMOVEDPORT4_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT4_OFFSET 0x9C #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT4_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTDROPPEDPORT4_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT4_OFFSET 0xA0 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT4_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_BYTESDROPPEDPORT4_WIDTH 32 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT4_OFFSET 0xA4 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT4_DEFAULT 0x0 #define SUME_OUTPUT_QUEUES_0_PKTINQUEUEPORT4_WIDTH 32 /******************************************************************* * Definitions for OUTPUT_PORT_LOOKUP *******************************************************************/ #define SUME_OUTPUT_PORT_LOOKUP_BASEADDR 0x44020000 #define SUME_OUTPUT_PORT_LOOKUP_HIGHADDR 0x44020FFF #define SUME_OUTPUT_PORT_LOOKUP_SIZEADDR 0x1000 #define SUME_OUTPUT_PORT_LOOKUP_0_ID_OFFSET 0x0 #define SUME_OUTPUT_PORT_LOOKUP_0_ID_DEFAULT 0x0000DA02 #define SUME_OUTPUT_PORT_LOOKUP_0_ID_WIDTH 32 #define SUME_OUTPUT_PORT_LOOKUP_0_VERSION_OFFSET 0x4 #define SUME_OUTPUT_PORT_LOOKUP_0_VERSION_DEFAULT 0x1 #define SUME_OUTPUT_PORT_LOOKUP_0_VERSION_WIDTH 32 #define SUME_OUTPUT_PORT_LOOKUP_0_RESET_OFFSET 0x8 #define SUME_OUTPUT_PORT_LOOKUP_0_RESET_DEFAULT 0x0 #define SUME_OUTPUT_PORT_LOOKUP_0_RESET_WIDTH 16 #define SUME_OUTPUT_PORT_LOOKUP_0_FLIP_OFFSET 0xC #define SUME_OUTPUT_PORT_LOOKUP_0_FLIP_DEFAULT 0x0 #define SUME_OUTPUT_PORT_LOOKUP_0_FLIP_WIDTH 32 #define SUME_OUTPUT_PORT_LOOKUP_0_DEBUG_OFFSET 0x10 #define SUME_OUTPUT_PORT_LOOKUP_0_DEBUG_DEFAULT 0x0 #define SUME_OUTPUT_PORT_LOOKUP_0_DEBUG_WIDTH 32 #define SUME_OUTPUT_PORT_LOOKUP_0_PKTIN_OFFSET 0x14 #define SUME_OUTPUT_PORT_LOOKUP_0_PKTIN_DEFAULT 0x0 #define SUME_OUTPUT_PORT_LOOKUP_0_PKTIN_WIDTH 32 #define SUME_OUTPUT_PORT_LOOKUP_0_PKTOUT_OFFSET 0x18 #define SUME_OUTPUT_PORT_LOOKUP_0_PKTOUT_DEFAULT 0x0 #define SUME_OUTPUT_PORT_LOOKUP_0_PKTOUT_WIDTH 32 /******************************************************************* * Definitions for NF_10G_INTERFACE0 *******************************************************************/ #define SUME_NF_10G_INTERFACE0_BASEADDR 0x44040000 #define SUME_NF_10G_INTERFACE0_HIGHADDR 0x44040FFF #define SUME_NF_10G_INTERFACE0_SIZEADDR 0x1000 #define SUME_NF_10G_INTERFACE_SHARED_0_ID_OFFSET 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_ID_DEFAULT 0x00001F10 #define SUME_NF_10G_INTERFACE_SHARED_0_ID_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_VERSION_OFFSET 0x4 #define SUME_NF_10G_INTERFACE_SHARED_0_VERSION_DEFAULT 0x1 #define SUME_NF_10G_INTERFACE_SHARED_0_VERSION_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_RESET_OFFSET 0x8 #define SUME_NF_10G_INTERFACE_SHARED_0_RESET_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_RESET_WIDTH 16 #define SUME_NF_10G_INTERFACE_SHARED_0_FLIP_OFFSET 0xC #define SUME_NF_10G_INTERFACE_SHARED_0_FLIP_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_FLIP_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_DEBUG_OFFSET 0x10 #define SUME_NF_10G_INTERFACE_SHARED_0_DEBUG_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_DEBUG_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_INTERFACEID_OFFSET 0x14 #define SUME_NF_10G_INTERFACE_SHARED_0_INTERFACEID_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_INTERFACEID_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PKTIN_OFFSET 0x18 #define SUME_NF_10G_INTERFACE_SHARED_0_PKTIN_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PKTIN_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PKTOUT_OFFSET 0x1C #define SUME_NF_10G_INTERFACE_SHARED_0_PKTOUT_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PKTOUT_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_MACSTATUSVECTOR_OFFSET 0x20 #define SUME_NF_10G_INTERFACE_SHARED_0_MACSTATUSVECTOR_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_MACSTATUSVECTOR_WIDTH 2 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUS_OFFSET 0x24 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUS_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUS_WIDTH 8 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR0_OFFSET 0x28 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR0_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR0_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR1_OFFSET 0x2C #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR1_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR1_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR2_OFFSET 0x30 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR2_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR2_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR3_OFFSET 0x34 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR3_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR3_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR4_OFFSET 0x38 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR4_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR4_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR5_OFFSET 0x3C #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR5_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR5_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR6_OFFSET 0x40 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR6_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR6_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR7_OFFSET 0x44 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR7_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR7_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR8_OFFSET 0x48 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR8_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR8_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR9_OFFSET 0x4C #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR9_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR9_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR10_OFFSET 0x50 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR10_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR10_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR11_OFFSET 0x54 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR11_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR11_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR12_OFFSET 0x58 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR12_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR12_WIDTH 32 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR13_OFFSET 0x5C #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR13_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_SHARED_0_PCSPMASTATUSVECTOR13_WIDTH 32 /******************************************************************* * Definitions for NF_10G_INTERFACE1 *******************************************************************/ #define SUME_NF_10G_INTERFACE1_BASEADDR 0x44050000 #define SUME_NF_10G_INTERFACE1_HIGHADDR 0x44050FFF #define SUME_NF_10G_INTERFACE1_SIZEADDR 0x1000 #define SUME_NF_10G_INTERFACE_1_ID_OFFSET 0x0 #define SUME_NF_10G_INTERFACE_1_ID_DEFAULT 0x00001F10 #define SUME_NF_10G_INTERFACE_1_ID_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_VERSION_OFFSET 0x4 #define SUME_NF_10G_INTERFACE_1_VERSION_DEFAULT 0x1 #define SUME_NF_10G_INTERFACE_1_VERSION_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_RESET_OFFSET 0x8 #define SUME_NF_10G_INTERFACE_1_RESET_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_RESET_WIDTH 16 #define SUME_NF_10G_INTERFACE_1_FLIP_OFFSET 0xC #define SUME_NF_10G_INTERFACE_1_FLIP_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_FLIP_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_DEBUG_OFFSET 0x10 #define SUME_NF_10G_INTERFACE_1_DEBUG_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_DEBUG_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_INTERFACEID_OFFSET 0x14 #define SUME_NF_10G_INTERFACE_1_INTERFACEID_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_INTERFACEID_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PKTIN_OFFSET 0x18 #define SUME_NF_10G_INTERFACE_1_PKTIN_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PKTIN_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PKTOUT_OFFSET 0x1C #define SUME_NF_10G_INTERFACE_1_PKTOUT_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PKTOUT_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_MACSTATUSVECTOR_OFFSET 0x20 #define SUME_NF_10G_INTERFACE_1_MACSTATUSVECTOR_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_MACSTATUSVECTOR_WIDTH 2 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUS_OFFSET 0x24 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUS_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUS_WIDTH 8 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR0_OFFSET 0x28 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR0_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR0_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR1_OFFSET 0x2C #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR1_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR1_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR2_OFFSET 0x30 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR2_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR2_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR3_OFFSET 0x34 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR3_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR3_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR4_OFFSET 0x38 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR4_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR4_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR5_OFFSET 0x3C #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR5_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR5_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR6_OFFSET 0x40 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR6_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR6_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR7_OFFSET 0x44 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR7_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR7_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR8_OFFSET 0x48 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR8_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR8_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR9_OFFSET 0x4C #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR9_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR9_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR10_OFFSET 0x50 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR10_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR10_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR11_OFFSET 0x54 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR11_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR11_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR12_OFFSET 0x58 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR12_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR12_WIDTH 32 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR13_OFFSET 0x5C #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR13_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_1_PCSPMASTATUSVECTOR13_WIDTH 32 /******************************************************************* * Definitions for NF_10G_INTERFACE2 *******************************************************************/ #define SUME_NF_10G_INTERFACE2_BASEADDR 0x44060000 #define SUME_NF_10G_INTERFACE2_HIGHADDR 0x44060FFF #define SUME_NF_10G_INTERFACE2_SIZEADDR 0x1000 #define SUME_NF_10G_INTERFACE_2_ID_OFFSET 0x0 #define SUME_NF_10G_INTERFACE_2_ID_DEFAULT 0x00001F10 #define SUME_NF_10G_INTERFACE_2_ID_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_VERSION_OFFSET 0x4 #define SUME_NF_10G_INTERFACE_2_VERSION_DEFAULT 0x1 #define SUME_NF_10G_INTERFACE_2_VERSION_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_RESET_OFFSET 0x8 #define SUME_NF_10G_INTERFACE_2_RESET_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_RESET_WIDTH 16 #define SUME_NF_10G_INTERFACE_2_FLIP_OFFSET 0xC #define SUME_NF_10G_INTERFACE_2_FLIP_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_FLIP_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_DEBUG_OFFSET 0x10 #define SUME_NF_10G_INTERFACE_2_DEBUG_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_DEBUG_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_INTERFACEID_OFFSET 0x14 #define SUME_NF_10G_INTERFACE_2_INTERFACEID_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_INTERFACEID_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PKTIN_OFFSET 0x18 #define SUME_NF_10G_INTERFACE_2_PKTIN_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PKTIN_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PKTOUT_OFFSET 0x1C #define SUME_NF_10G_INTERFACE_2_PKTOUT_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PKTOUT_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_MACSTATUSVECTOR_OFFSET 0x20 #define SUME_NF_10G_INTERFACE_2_MACSTATUSVECTOR_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_MACSTATUSVECTOR_WIDTH 2 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUS_OFFSET 0x24 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUS_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUS_WIDTH 8 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR0_OFFSET 0x28 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR0_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR0_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR1_OFFSET 0x2C #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR1_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR1_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR2_OFFSET 0x30 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR2_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR2_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR3_OFFSET 0x34 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR3_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR3_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR4_OFFSET 0x38 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR4_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR4_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR5_OFFSET 0x3C #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR5_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR5_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR6_OFFSET 0x40 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR6_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR6_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR7_OFFSET 0x44 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR7_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR7_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR8_OFFSET 0x48 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR8_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR8_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR9_OFFSET 0x4C #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR9_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR9_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR10_OFFSET 0x50 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR10_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR10_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR11_OFFSET 0x54 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR11_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR11_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR12_OFFSET 0x58 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR12_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR12_WIDTH 32 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR13_OFFSET 0x5C #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR13_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_2_PCSPMASTATUSVECTOR13_WIDTH 32 /******************************************************************* * Definitions for NF_10G_INTERFACE3 *******************************************************************/ #define SUME_NF_10G_INTERFACE3_BASEADDR 0x44070000 #define SUME_NF_10G_INTERFACE3_HIGHADDR 0x44070FFF #define SUME_NF_10G_INTERFACE3_SIZEADDR 0x1000 #define SUME_NF_10G_INTERFACE_3_ID_OFFSET 0x0 #define SUME_NF_10G_INTERFACE_3_ID_DEFAULT 0x00001F10 #define SUME_NF_10G_INTERFACE_3_ID_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_VERSION_OFFSET 0x4 #define SUME_NF_10G_INTERFACE_3_VERSION_DEFAULT 0x1 #define SUME_NF_10G_INTERFACE_3_VERSION_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_RESET_OFFSET 0x8 #define SUME_NF_10G_INTERFACE_3_RESET_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_RESET_WIDTH 16 #define SUME_NF_10G_INTERFACE_3_FLIP_OFFSET 0xC #define SUME_NF_10G_INTERFACE_3_FLIP_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_FLIP_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_DEBUG_OFFSET 0x10 #define SUME_NF_10G_INTERFACE_3_DEBUG_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_DEBUG_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_INTERFACEID_OFFSET 0x14 #define SUME_NF_10G_INTERFACE_3_INTERFACEID_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_INTERFACEID_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PKTIN_OFFSET 0x18 #define SUME_NF_10G_INTERFACE_3_PKTIN_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PKTIN_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PKTOUT_OFFSET 0x1C #define SUME_NF_10G_INTERFACE_3_PKTOUT_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PKTOUT_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_MACSTATUSVECTOR_OFFSET 0x20 #define SUME_NF_10G_INTERFACE_3_MACSTATUSVECTOR_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_MACSTATUSVECTOR_WIDTH 2 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUS_OFFSET 0x24 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUS_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUS_WIDTH 8 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR0_OFFSET 0x28 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR0_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR0_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR1_OFFSET 0x2C #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR1_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR1_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR2_OFFSET 0x30 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR2_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR2_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR3_OFFSET 0x34 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR3_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR3_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR4_OFFSET 0x38 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR4_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR4_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR5_OFFSET 0x3C #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR5_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR5_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR6_OFFSET 0x40 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR6_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR6_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR7_OFFSET 0x44 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR7_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR7_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR8_OFFSET 0x48 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR8_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR8_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR9_OFFSET 0x4C #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR9_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR9_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR10_OFFSET 0x50 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR10_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR10_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR11_OFFSET 0x54 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR11_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR11_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR12_OFFSET 0x58 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR12_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR12_WIDTH 32 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR13_OFFSET 0x5C #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR13_DEFAULT 0x0 #define SUME_NF_10G_INTERFACE_3_PCSPMASTATUSVECTOR13_WIDTH 32 /******************************************************************* * Definitions for NF_RIFFA_DMA *******************************************************************/ #define SUME_NF_RIFFA_DMA_BASEADDR 0x44080000 #define SUME_NF_RIFFA_DMA_HIGHADDR 0x44080FFF #define SUME_NF_RIFFA_DMA_SIZEADDR 0x1000 #define SUME_NF_RIFFA_DMA_0_ID_OFFSET 0x0 #define SUME_NF_RIFFA_DMA_0_ID_DEFAULT 0x00001FFA #define SUME_NF_RIFFA_DMA_0_ID_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_VERSION_OFFSET 0x4 #define SUME_NF_RIFFA_DMA_0_VERSION_DEFAULT 0x1 #define SUME_NF_RIFFA_DMA_0_VERSION_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_RESET_OFFSET 0x8 #define SUME_NF_RIFFA_DMA_0_RESET_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_RESET_WIDTH 16 #define SUME_NF_RIFFA_DMA_0_FLIP_OFFSET 0xC #define SUME_NF_RIFFA_DMA_0_FLIP_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_FLIP_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_DEBUG_OFFSET 0x10 #define SUME_NF_RIFFA_DMA_0_DEBUG_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_DEBUG_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_RQPKT_OFFSET 0x14 #define SUME_NF_RIFFA_DMA_0_RQPKT_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_RQPKT_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_RCPKT_OFFSET 0x18 #define SUME_NF_RIFFA_DMA_0_RCPKT_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_RCPKT_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_CQPKT_OFFSET 0x1C #define SUME_NF_RIFFA_DMA_0_CQPKT_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_CQPKT_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_CCPKT_OFFSET 0x20 #define SUME_NF_RIFFA_DMA_0_CCPKT_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_CCPKT_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_XGETXPKT_OFFSET 0x24 #define SUME_NF_RIFFA_DMA_0_XGETXPKT_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_XGETXPKT_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_XGERXPKT_OFFSET 0x28 #define SUME_NF_RIFFA_DMA_0_XGERXPKT_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_XGERXPKT_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIERQ_OFFSET 0x2C #define SUME_NF_RIFFA_DMA_0_PCIERQ_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIERQ_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEPHY_OFFSET 0x30 #define SUME_NF_RIFFA_DMA_0_PCIEPHY_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEPHY_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIECONFIG_OFFSET 0x34 #define SUME_NF_RIFFA_DMA_0_PCIECONFIG_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIECONFIG_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIECONFIG2_OFFSET 0x38 #define SUME_NF_RIFFA_DMA_0_PCIECONFIG2_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIECONFIG2_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEERROR_OFFSET 0x3C #define SUME_NF_RIFFA_DMA_0_PCIEERROR_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEERROR_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEMISC_OFFSET 0x40 #define SUME_NF_RIFFA_DMA_0_PCIEMISC_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEMISC_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIETPH_OFFSET 0x44 #define SUME_NF_RIFFA_DMA_0_PCIETPH_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIETPH_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEFC1_OFFSET 0x48 #define SUME_NF_RIFFA_DMA_0_PCIEFC1_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEFC1_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEFC2_OFFSET 0x4C #define SUME_NF_RIFFA_DMA_0_PCIEFC2_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEFC2_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEFC3_OFFSET 0x50 #define SUME_NF_RIFFA_DMA_0_PCIEFC3_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEFC3_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEINTERRUPT_OFFSET 0x54 #define SUME_NF_RIFFA_DMA_0_PCIEINTERRUPT_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEINTERRUPT_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEMSIDATA_OFFSET 0x58 #define SUME_NF_RIFFA_DMA_0_PCIEMSIDATA_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEMSIDATA_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEMSIINT_OFFSET 0x5C #define SUME_NF_RIFFA_DMA_0_PCIEMSIINT_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEMSIINT_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEMSIPENDINGSTATUS_OFFSET 0x60 #define SUME_NF_RIFFA_DMA_0_PCIEMSIPENDINGSTATUS_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEMSIPENDINGSTATUS_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEMSIPENDINGSTATUS2_OFFSET 0x64 #define SUME_NF_RIFFA_DMA_0_PCIEMSIPENDINGSTATUS2_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEMSIPENDINGSTATUS2_WIDTH 32 #define SUME_NF_RIFFA_DMA_0_PCIEINTERRUPT2_OFFSET 0x68 #define SUME_NF_RIFFA_DMA_0_PCIEINTERRUPT2_DEFAULT 0x0 #define SUME_NF_RIFFA_DMA_0_PCIEINTERRUPT2_WIDTH 32
53.608828
106
0.871469
03bfec8311ddd26bc022ec6ca9231e6e0a6a762a
9,863
c
C
src/565/basic.c
LanFly/tGFX
4d3464c1fc741cc5832254448d11f5b7fabd6810
[ "Apache-2.0" ]
4
2020-10-30T09:10:19.000Z
2022-03-16T13:54:55.000Z
src/565/basic.c
LanFly/tGFX
4d3464c1fc741cc5832254448d11f5b7fabd6810
[ "Apache-2.0" ]
null
null
null
src/565/basic.c
LanFly/tGFX
4d3464c1fc741cc5832254448d11f5b7fabd6810
[ "Apache-2.0" ]
2
2020-06-19T14:45:47.000Z
2022-03-16T13:12:53.000Z
#include <tGFX/565/basic.h> /** * draw a pixel in overflow hidden mode. */ #ifndef tGFX_USE_REAL_TIME void tGFX_draw_pixel(tGFX_Canvas *canvas, uint16_t x, uint16_t y, uint16_t color) { // overflow hidden. if (x >= canvas->width || y >= canvas->height) { return; } uint32_t pos = (canvas->width * y + x) * 2; canvas->buffer[pos] = color >> 8; canvas->buffer[pos + 1] = color; } #endif #ifndef tGFX_USE_REAL_TIME void tGFX_get_pixel_RGB(tGFX_Canvas *canvas, uint16_t x, uint16_t y, uint8_t *r, uint8_t *g, uint8_t *b) { uint16_t pixel; // overflow hidden. if (x >= canvas->width || y >= canvas->height) { *r = *g = *b = 0; return; } uint32_t pos = (canvas->width * y + x) * 2; uint8_t msb = canvas->buffer[pos]; uint8_t lsb = canvas->buffer[pos + 1]; pixel = (0x0000 | msb) << 8 | lsb; *r = (pixel >> 11) << 3; *g = (pixel >> 5 & 0x3F) << 2; *b = (pixel & 0x1F) << 3; } #endif /** * draw a line with bresenhams line algorithm. * copyright: https://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#C */ void tGFX_draw_line(tGFX_Canvas *canvas, uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2, uint16_t color) { int dx = abs(x2 - x1), sx = x1 < x2 ? 1 : -1; int dy = abs(y2 - y1), sy = y1 < y2 ? 1 : -1; int err = (dx > dy ? dx : -dy) / 2, e2; while (1) { tGFX_draw_pixel(canvas, x1, y1, color); if (x1 == x2 && y1 == y2) { break; } e2 = err; if (e2 > -dx) { err -= dy; x1 += sx; } if (e2 < dy) { err += dx; y1 += sy; } } } /** * draw a rectangle with tGFX_draw_line func. */ void tGFX_draw_rect(tGFX_Canvas *canvas, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t color) { tGFX_draw_line(canvas, x, y, x + w, y, color); tGFX_draw_line(canvas, x + w, y, x + w, y + h, color); tGFX_draw_line(canvas, x + w, y + h, x, y + h, color); tGFX_draw_line(canvas, x, y + h, x, y, color); } /** * draw a filled rectangle with tGFX_draw_line func. */ void tGFX_fill_rect(tGFX_Canvas *canvas, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t color) { for (uint16_t height = 0; height < h; height++) { tGFX_draw_line(canvas, x, y + height, x + w, y + height, color); } } /** * draw a arc in a multiple of a quarter with Midpoint circle algorithm. * copyright: https://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm#C */ void tGFX_draw_arc_quarter(tGFX_Canvas *canvas, uint16_t xc, uint16_t yc, uint16_t r, uint8_t angle, uint16_t color) { int f = 1 - r; int ddF_x = 0; int ddF_y = -2 * r; int x = 0; int y = r; if (angle & 0x01) { tGFX_draw_pixel(canvas, xc, yc - r, color); tGFX_draw_pixel(canvas, xc + r, yc, color); } if (angle & 0x02) { tGFX_draw_pixel(canvas, xc + r, yc, color); tGFX_draw_pixel(canvas, xc, yc + r, color); } if (angle & 0x04) { tGFX_draw_pixel(canvas, xc, yc + r, color); tGFX_draw_pixel(canvas, xc - r, yc, color); } if (angle & 0x08) { tGFX_draw_pixel(canvas, xc - r, yc, color); tGFX_draw_pixel(canvas, xc, yc - r, color); } while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x + 1; if (angle & 0x01) { tGFX_draw_pixel(canvas, xc + x, yc - y, color); tGFX_draw_pixel(canvas, xc + y, yc - x, color); } if (angle & 0x02) { tGFX_draw_pixel(canvas, xc + x, yc + y, color); tGFX_draw_pixel(canvas, xc + y, yc + x, color); } if (angle & 0x04) { tGFX_draw_pixel(canvas, xc - x, yc + y, color); tGFX_draw_pixel(canvas, xc - y, yc + x, color); } if (angle & 0x08) { tGFX_draw_pixel(canvas, xc - x, yc - y, color); tGFX_draw_pixel(canvas, xc - y, yc - x, color); } } } /** * draw a circle with Midpoint circle algorithm. * copyright: https://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm#C */ void tGFX_draw_circle(tGFX_Canvas *canvas, uint16_t xc, uint16_t yc, uint16_t r, uint16_t color) { int f = 1 - r; int ddF_x = 0; int ddF_y = -2 * r; int x = 0; int y = r; tGFX_draw_pixel(canvas, xc, yc + r, color); tGFX_draw_pixel(canvas, xc, yc - r, color); tGFX_draw_pixel(canvas, xc + r, yc, color); tGFX_draw_pixel(canvas, xc - r, yc, color); while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x + 1; tGFX_draw_pixel(canvas, xc + x, yc + y, color); tGFX_draw_pixel(canvas, xc - x, yc + y, color); tGFX_draw_pixel(canvas, xc + x, yc - y, color); tGFX_draw_pixel(canvas, xc - x, yc - y, color); tGFX_draw_pixel(canvas, xc + y, yc + x, color); tGFX_draw_pixel(canvas, xc - y, yc + x, color); tGFX_draw_pixel(canvas, xc + y, yc - x, color); tGFX_draw_pixel(canvas, xc - y, yc - x, color); } } /** * draw a ellipse with midpoint ellipse algorithm. * copyright: https://www.geeksforgeeks.org/midpoint-ellipse-drawing-algorithm/ */ void tGFX_draw_ellipse(tGFX_Canvas *canvas, uint16_t xc, uint16_t yc, uint16_t rx, uint16_t ry, uint16_t color) { float dx, dy, d1, d2, x, y; x = 0; y = ry; // Initial decision parameter of region 1 d1 = (ry * ry) - (rx * rx * ry) + (0.25 * rx * rx); dx = 2 * ry * ry * x; dy = 2 * rx * rx * y; // For region 1 while (dx < dy) { // Print points based on 4-way symmetry tGFX_draw_pixel(canvas, x + xc, y + yc, color); tGFX_draw_pixel(canvas, -x + xc, y + yc, color); tGFX_draw_pixel(canvas, x + xc, -y + yc, color); tGFX_draw_pixel(canvas, -x + xc, -y + yc, color); // Checking and updating value of // decision parameter based on algorithm if (d1 < 0) { x++; dx = dx + (2 * ry * ry); d1 = d1 + dx + (ry * ry); } else { x++; y--; dx = dx + (2 * ry * ry); dy = dy - (2 * rx * rx); d1 = d1 + dx - dy + (ry * ry); } } // Decision parameter of region 2 d2 = ((ry * ry) * ((x + 0.5) * (x + 0.5))) + ((rx * rx) * ((y - 1) * (y - 1))) - (rx * rx * ry * ry); // Plotting points of region 2 while (y >= 0) { // printing points based on 4-way symmetry tGFX_draw_pixel(canvas, x + xc, y + yc, color); tGFX_draw_pixel(canvas, -x + xc, y + yc, color); tGFX_draw_pixel(canvas, x + xc, -y + yc, color); tGFX_draw_pixel(canvas, -x + xc, -y + yc, color); // Checking and updating parameter // value based on algorithm if (d2 > 0) { y--; dy = dy - (2 * rx * rx); d2 = d2 + (rx * rx) - dy; } else { y--; x++; dx = dx + (2 * ry * ry); dy = dy - (2 * rx * rx); d2 = d2 + dx - dy + (rx * rx); } } } /** * draw a rounded reacangle with tGFX_draw_line func. */ void tGFX_draw_rect_radius(tGFX_Canvas *canvas, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t r, uint16_t color) { if (w > h && r * 2 > h) { r = h / 2; } else if (r * 2 > w) { r = w / 2; } tGFX_draw_line(canvas, x + r, y, x + w - r, y, color); tGFX_draw_line(canvas, x + w, y + r, x + w, y + h - r, color); tGFX_draw_line(canvas, x + w - r, y + h, x + r, y + h, color); tGFX_draw_line(canvas, x, y + h - r, x, y + r, color); tGFX_draw_arc_quarter(canvas, x + r, y + r, r, 0x08, color); tGFX_draw_arc_quarter(canvas, x + w - r, y + r, r, 0x01, color); tGFX_draw_arc_quarter(canvas, x + w - r, y + h - r, r, 0x02, color); tGFX_draw_arc_quarter(canvas, x + r, y + h - r, r, 0x04, color); } /** * draw a polygon with tGFX_draw_line func. * @param points {x1, y1, x2, y2, ..., xn, yn} */ void tGFX_draw_polygon(tGFX_Canvas *canvas, uint16_t *points, uint8_t edge, uint16_t color) { uint8_t count = 0; uint8_t pos = 0; while (count < edge - 1) { tGFX_draw_line(canvas, points[pos], points[pos + 1], points[pos + 2], points[pos + 3], color); count++; pos = count * 2; } tGFX_draw_line(canvas, points[pos], points[pos + 1], points[0], points[1], color); } /** * draw a bitmap in vertical order with tGFX_draw_pixel func. */ void tGFX_draw_bitmap_v(tGFX_Canvas *canvas, uint16_t x, uint16_t y, uint16_t w, uint16_t h, const uint8_t *bitmap, uint16_t color) { uint16_t cx, cy, bytes_per_col, byte; bytes_per_col = h / 8; for (cx = 0; cx < w; cx++) { for (cy = 0; cy < h; cy++) { byte = bitmap[cx * bytes_per_col + cy / 8]; if (byte >> (7 - cy % 8) & 0x01) { tGFX_draw_pixel(canvas, x + cx, y + cy, color); } } } } /** * draw a bitmap in horizontal order with tGFX_draw_pixel func. * @param w w must be a multiple of 8 */ void tGFX_draw_bitmap(tGFX_Canvas *canvas, uint16_t x, uint16_t y, uint16_t w, uint16_t h, const uint8_t *bitmap, uint16_t color) { uint16_t cx, cy, bytes_per_row, byte; bytes_per_row = w / 8; for (cy = 0; cy < h; cy++) { for (cx = 0; cx < w; cx++) { byte = bitmap[cy * bytes_per_row + cx / 8]; if (byte >> (7 - cx % 8) & 0x01) { tGFX_draw_pixel(canvas, x + cx, y + cy, color); } } } } /** * draw a image in horizontal order with tGFX_draw_pixel func. * @param buffer image data in horizontal order. One pixel takes two bytes with * 565 format. */ void tGFX_draw_image(tGFX_Canvas *canvas, uint16_t x, uint16_t y, uint16_t w, uint16_t h, const uint8_t *buffer) { uint16_t cx, cy, pixel; for (cy = 0; cy < h; cy++) { for (cx = 0; cx < w; cx++) { pixel = buffer[cy * w * 2 + cx * 2]; pixel = pixel << 8 | buffer[cy * w * 2 + cx * 2 + 1]; tGFX_draw_pixel(canvas, x + cx, y + cy, pixel); } } }
28.923754
80
0.557538
fcec931b6acffd85a732d596b2dfd3c5c7c71e21
4,735
h
C
components/cast_streaming/browser/test/cast_streaming_test_receiver.h
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
components/cast_streaming/browser/test/cast_streaming_test_receiver.h
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
components/cast_streaming/browser/test/cast_streaming_test_receiver.h
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_CAST_STREAMING_BROWSER_TEST_CAST_STREAMING_TEST_RECEIVER_H_ #define COMPONENTS_CAST_STREAMING_BROWSER_TEST_CAST_STREAMING_TEST_RECEIVER_H_ #include "base/callback.h" #include "components/cast/message_port/message_port.h" #include "components/cast_streaming/browser/cast_streaming_session.h" #include "media/mojo/common/mojo_decoder_buffer_converter.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace cast_streaming { // Cast Streaming Receiver implementation for testing. This class provides basic // functionality for starting a Cast Streaming Receiver and receiving audio and // video frames to a Cast Streaming Sender. Example usage: // // std::unique_ptr<cast_api_bindings::MessagePort> sender_message_port; // std::unique_ptr<cast_api_bindings::MessagePort> receiver_message_port; // cast_api_bindings::MessagePort::CreatePair(&sender_message_port, // &receiver_message_port); // // // Send |sender_message_port| to a Sender and start it. // // CastStreamingTestReceiver receiver; // receiver.Start(std::move(receiver_message_port)); // receiver.RunUntilStarted(); // // if (!receiver.RunUntilAudioFramesCountIsAtLeast(1u)) { // return; // } // // Handle receiver.audio_frames()[0] here. // // if (!receiver.RunUntilVideoFramesCountIsAtLeast(1u)) { // return; // } // // Handle receiver.video_frames()[0] here. // // receiver.Stop(); // receiver.RunUntilStopped(); class CastStreamingTestReceiver : public CastStreamingSession::Client { public: CastStreamingTestReceiver(); ~CastStreamingTestReceiver() final; CastStreamingTestReceiver(const CastStreamingTestReceiver&) = delete; CastStreamingTestReceiver& operator=(const CastStreamingTestReceiver&) = delete; // Uses |message_port| as the Receiverr-end of a Cast Streaming MessagePort to // start a Cast Streaming Session. void Start(std::unique_ptr<cast_api_bindings::MessagePort> message_port); void Stop(); // Helper methods running the Receiver until it is properly started or // stopped. Only one of the Run*() methods can be called at any given time. void RunUntilStarted(); void RunUntilStopped(); // Helper methods running the Receiver until |*frames_count| audio or video // frames have been received or until the Receiver has stopped. Returns true // if the session is still active. Only one of the Run*() methods can be // called at any given time. bool RunUntilAudioFramesCountIsAtLeast(size_t audio_frames_count); bool RunUntilVideoFramesCountIsAtLeast(size_t video_frames_count); bool is_active() { return is_active_; } absl::optional<media::AudioDecoderConfig> audio_config() { return audio_config_; } absl::optional<media::VideoDecoderConfig> video_config() { return video_config_; } const std::vector<scoped_refptr<media::DecoderBuffer>>& audio_buffers() { return audio_buffers_; } const std::vector<scoped_refptr<media::DecoderBuffer>>& video_buffers() { return video_buffers_; } private: // Callbacks for |audio_decoder_buffer_reader_| and // |video_decoder_buffer_reader_|, respectively. void OnAudioBufferRead(scoped_refptr<media::DecoderBuffer> buffer); void OnVideoBufferRead(scoped_refptr<media::DecoderBuffer> buffer); // CastStreamingSession::Client implementation. void OnSessionInitialization( absl::optional<CastStreamingSession::AudioStreamInfo> audio_stream_info, absl::optional<CastStreamingSession::VideoStreamInfo> video_stream_info) final; void OnAudioBufferReceived(media::mojom::DecoderBufferPtr buffer) final; void OnVideoBufferReceived(media::mojom::DecoderBufferPtr buffer) final; void OnSessionReinitialization( absl::optional<CastStreamingSession::AudioStreamInfo> audio_stream_info, absl::optional<CastStreamingSession::VideoStreamInfo> video_stream_info) final; void OnSessionEnded() final; CastStreamingSession receiver_session_; bool is_active_ = false; base::OnceClosure receiver_updated_closure_; absl::optional<media::AudioDecoderConfig> audio_config_; std::unique_ptr<media::MojoDecoderBufferReader> audio_decoder_buffer_reader_; std::vector<scoped_refptr<media::DecoderBuffer>> audio_buffers_; absl::optional<media::VideoDecoderConfig> video_config_; std::unique_ptr<media::MojoDecoderBufferReader> video_decoder_buffer_reader_; std::vector<scoped_refptr<media::DecoderBuffer>> video_buffers_; }; } // namespace cast_streaming #endif // COMPONENTS_CAST_STREAMING_BROWSER_TEST_CAST_STREAMING_TEST_RECEIVER_H_
40.127119
81
0.777825
d8453b96713d1348cb1f866b06e8e04415878452
176
h
C
Telegraph/TGDayPresentationPallete.h
miladajilian/MimMessenger
72aca46135eed311f5f2fd3b711446a61b526548
[ "MIT" ]
null
null
null
Telegraph/TGDayPresentationPallete.h
miladajilian/MimMessenger
72aca46135eed311f5f2fd3b711446a61b526548
[ "MIT" ]
null
null
null
Telegraph/TGDayPresentationPallete.h
miladajilian/MimMessenger
72aca46135eed311f5f2fd3b711446a61b526548
[ "MIT" ]
null
null
null
#import "TGDefaultPresentationPallete.h" @interface TGDayPresentationPallete : TGDefaultPresentationPallete + (instancetype)dayPalleteWithAccentColor:(UIColor *)color; @end
22
66
0.840909
88f187ba58a6f442d359dc4fca5fd58ab70c2c57
821
h
C
event_handles/Sewing2dPatternEventHandle.h
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
32
2016-12-13T05:49:12.000Z
2022-02-04T06:15:47.000Z
event_handles/Sewing2dPatternEventHandle.h
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
2
2019-07-30T02:01:16.000Z
2020-03-12T15:06:51.000Z
event_handles/Sewing2dPatternEventHandle.h
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
18
2017-11-16T13:37:06.000Z
2022-03-11T08:13:46.000Z
#pragma once #include <QPoint> #include <QCursor> #include <QString> #include "ldpMat\ldp_basic_mat.h" #include "Abstract2dEventHandle.h" class Viewer2d; class QMouseEvent; class QWheelEvent; class QKeyEvent; class ObjMesh; class Sewing2dPatternEventHandle : public Abstract2dEventHandle { public: Sewing2dPatternEventHandle(Viewer2d* v); ~Sewing2dPatternEventHandle(); virtual ProcessorType type()const { return ProcessorTypeSewingPattern; } virtual void mousePressEvent(QMouseEvent *); virtual void mouseReleaseEvent(QMouseEvent *); virtual void mouseDoubleClickEvent(QMouseEvent *); virtual void mouseMoveEvent(QMouseEvent*); virtual void wheelEvent(QWheelEvent*); virtual void keyPressEvent(QKeyEvent*); virtual void keyReleaseEvent(QKeyEvent*); virtual void handleEnter(); virtual void handleLeave(); };
29.321429
73
0.807552
f050da8e894e16777b757fde5cab41e0b990e358
7,089
h
C
iree/hal/local/arena.h
KareemErgawy-TomTom/iree
1a88333d43ab1d564cc9412c04815f7eaa20f6ee
[ "Apache-2.0" ]
null
null
null
iree/hal/local/arena.h
KareemErgawy-TomTom/iree
1a88333d43ab1d564cc9412c04815f7eaa20f6ee
[ "Apache-2.0" ]
null
null
null
iree/hal/local/arena.h
KareemErgawy-TomTom/iree
1a88333d43ab1d564cc9412c04815f7eaa20f6ee
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #ifndef IREE_HAL_LOCAL_ARENA_H_ #define IREE_HAL_LOCAL_ARENA_H_ #include <stddef.h> #include "iree/base/api.h" #include "iree/base/internal/atomic_slist.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus //===----------------------------------------------------------------------===// // iree_arena_block_pool_t //===----------------------------------------------------------------------===// struct iree_arena_block_t; // NOTE: this struct is at the *end* of allocated blocks such that we don't mess // with alignment - byte 0 of a block is always byte 0 of the allocation from // the system. We can do this as all blocks have the same size so computing the // footer offset from a pointer is easy. typedef struct iree_arena_block_t { struct iree_arena_block_t* next; } iree_arena_block_t; // An atomic approximately LIFO singly-linked list. IREE_TYPED_ATOMIC_SLIST_WRAPPER(iree_atomic_arena_block, iree_arena_block_t, offsetof(iree_arena_block_t, next)); // A simple atomic fixed-size block pool. // Blocks are allocated from the system as required and kept in the pool to // satisfy future requests. Blocks are all of a uniform size specified when the // pool is created. It's recommended that power-of-two sizes are used for the // blocks so that the underlying allocator is more likely to bucket them // appropriately. // // Thread-safe; multiple threads may acquire and release blocks from the pool. // The underlying allocator must also be thread-safe. typedef struct iree_arena_block_pool_t { // Block size, in bytes. All blocks in the available_slist will have this // byte size which includes the iree_arena_block_t footer. iree_host_size_t total_block_size; // Block size, in bytes, of the usable bytes within a block. iree_host_size_t usable_block_size; // Allocator used for allocating/freeing each allocation block. iree_allocator_t block_allocator; // Linked list of free blocks (LIFO). iree_atomic_arena_block_slist_t available_slist; } iree_arena_block_pool_t; // Initializes a new block pool in |out_block_pool|. // |block_allocator| will be used to allocate and free blocks for the pool. // Each block allocated will be |total_block_size| but have a slightly smaller // usable size due to the tracking overhead. Prefer powers of two. void iree_arena_block_pool_initialize(iree_host_size_t total_block_size, iree_allocator_t block_allocator, iree_arena_block_pool_t* out_block_pool); // Deinitializes a block pool and frees all allocations. // All blocks that were acquired from the pool must have already been released // back to it. void iree_arena_block_pool_deinitialize(iree_arena_block_pool_t* block_pool); // Trims the pool by freeing unused blocks back to the allocator. // Acquired blocks are not freed and remain valid. void iree_arena_block_pool_trim(iree_arena_block_pool_t* block_pool); // Acquires a single block from the pool and returns it in |out_block|. // The block may be either a new allocation with undefined contents or a reused // prior allocation with undefined contents. iree_status_t iree_arena_block_pool_acquire(iree_arena_block_pool_t* block_pool, iree_arena_block_t** out_block); // Releases one or more blocks back to the block pool. // Any blocks chained in |block_head| will also be released allowing for // low-overhead resets when the blocks are already tracked in linked lists. void iree_arena_block_pool_release(iree_arena_block_pool_t* block_pool, iree_arena_block_t* block_head, iree_arena_block_t* block_tail); //===----------------------------------------------------------------------===// // iree_arena_allocator_t //===----------------------------------------------------------------------===// typedef struct iree_arena_oversized_allocation_t { struct iree_arena_oversized_allocation_t* next; } iree_arena_oversized_allocation_t; // A lightweight bump-pointer arena allocator using a shared block pool. // As allocations are made from the arena and block capacity is exhausted new // blocks will be acquired from the pool. Upon being reset all blocks will be // released back to the pool for reuse by either the same arena in the future or // other arenas sharing the same pool. // // The size of each allocated block used by the arena is inherited from the // block pool. Allocations from the arena may exceed the block size but will // incur additional allocation overhead as the block pool is bypassed and the // system allocator is directly used to service the request. // // Thread-compatible; the shared block pool is thread-safe and may be used by // arenas on multiple threads but each arena must only be used by a single // thread. typedef struct iree_arena_allocator_t { // Fixed-size block pool used to acquire new blocks for the arena. iree_arena_block_pool_t* block_pool; // Total bytes allocated to the arena from the block pool or system allocator. iree_host_size_t total_allocation_size; // Total bytes allocated from the arena; the utilization of the arena can be // checked with `used_allocation_size / total_allocation_size`. iree_host_size_t used_allocation_size; // Linked list of oversized allocations made directly from the system // allocator used by the block pool. iree_arena_oversized_allocation_t* allocation_head; // Linked list of allocated blocks maintained so that reset can release them. iree_arena_block_t* block_head; iree_arena_block_t* block_tail; // The number of bytes remaining in the block pointed to by block_head. iree_host_size_t block_bytes_remaining; } iree_arena_allocator_t; // Initializes an arena that will use |block_pool| for allocating blocks as // needed. void iree_arena_initialize(iree_arena_block_pool_t* block_pool, iree_arena_allocator_t* out_arena); // Deinitializes the arena and returns allocated blocks to the parent pool. void iree_arena_deinitialize(iree_arena_allocator_t* arena); // Resets the entire arena and returns allocated blocks to the parent pool. void iree_arena_reset(iree_arena_allocator_t* arena); // Allocates |byte_length| contiguous bytes from the arena. // The returned bytes will have undefined contents and must be initialized by // the caller. iree_status_t iree_arena_allocate(iree_arena_allocator_t* arena, iree_host_size_t byte_length, void** out_ptr); // Returns an iree_allocator_t that allocates from the given |arena|. // Frees are ignored as arenas can only be reset as a whole. iree_allocator_t iree_arena_allocator(iree_arena_allocator_t* arena); #ifdef __cplusplus } // extern "C" #endif // __cplusplus #endif // IREE_HAL_LOCAL_ARENA_H_
46.032468
80
0.729299
bb35dad17faaecfb8d0207d19da3bef04bf29e69
3,033
h
C
WonderMake/Job/JobFuture.h
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
3
2020-03-27T15:25:19.000Z
2022-01-18T14:12:25.000Z
WonderMake/Job/JobFuture.h
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
null
null
null
WonderMake/Job/JobFuture.h
nicolasgustafsson/WonderMake
9661d5dab17cf98e06daf6ea77c5927db54d62f9
[ "MIT" ]
null
null
null
#pragma once #include "Job/JobOutput.h" #include "Job/JobPromise.h" #include "Scheduling/ScheduleSystem.h" #include "Typedefs.h" template<typename TOutput, typename TOutputError> class JobFuture { public: using SelfType = JobFuture<TOutput, TOutputError>; using FuturePromise = JobPromise<TOutput, TOutputError>; inline JobFuture(FuturePromise& aPromise, ScheduleSystem& aScheduleSystem) : myPromise(aPromise) , myScheduleSystem(aScheduleSystem) {} template<typename TCallable> requires FuturePromise::template IsInvocableFulfill<TCallable> inline void Then(TCallable&& aCallable) { using PolicySet = Policy::Set<>; myPromise.SetCallbackSuccess(JobCallbackImpl<TOutput>::template CreateCallback<PolicySet, TCallable>(myScheduleSystem, std::forward<TCallable>(aCallable))); } template<typename TCallable, typename TCargo> requires FuturePromise::template IsInvocableFulfill<TCallable, TCargo> inline void Then(TCargo&& aCargo, TCallable&& aCallable) { using PolicySet = typename TCargo::PolicySet; myPromise.SetCallbackSuccess(JobCallbackImpl<TOutput>::template CreateCallback<PolicySet, TCallable>(myScheduleSystem, std::forward<TCallable>(aCallable), std::forward<TCargo>(aCargo))); } template<typename TCallable> requires FuturePromise::template IsInvocableFail<TCallable> inline SelfType& Error(TCallable&& aCallable) { using PolicySet = Policy::Set<>; myPromise.SetCallbackFailure(JobCallbackImpl<TOutputError>::template CreateCallback<PolicySet, TCallable>(myScheduleSystem, std::forward<TCallable>(aCallable))); return *this; } template<typename TCallable, typename TCargo> requires FuturePromise::template IsInvocableFail<TCallable, TCargo> inline SelfType& Error(TCargo&& aCargo, TCallable&& aCallable) { using PolicySet = typename TCargo::PolicySet; myPromise.SetCallbackFailure(JobCallbackImpl<TOutputError>::template CreateCallback<PolicySet, TCallable>(myScheduleSystem, std::forward<TCallable>(aCallable), std::forward<TCargo>(aCargo))); return *this; } protected: template<typename TOutput> class JobCallbackImpl { static_assert(AlwaysFalse<TOutput>, "Invalid input."); }; template<typename... TArgs> class JobCallbackImpl<JobOutput<TArgs...>> { public: template<typename TPolicySet, typename TCallable, typename... TAdditionalArgs> requires std::is_invocable_v<TCallable, TAdditionalArgs..., TArgs...> inline static auto CreateCallback(ScheduleSystem& aScheduleSystem, TCallable&& aCallable, TAdditionalArgs&&... aAdditionalArgs) { return [&aScheduleSystem, callable = std::forward<TCallable>(aCallable), ...additionalArgs = std::forward<TAdditionalArgs>(aAdditionalArgs)](TArgs&&... aArgs) mutable { aScheduleSystem.Schedule<TPolicySet>([callable = std::move(callable), ...additionalArgs = std::move(additionalArgs), ...args = std::forward<TArgs>(aArgs)]() mutable { (void)callable(std::move(additionalArgs)..., std::move(args)...); }); }; } }; FuturePromise& myPromise; ScheduleSystem& myScheduleSystem; };
36.542169
193
0.770854
15cc4f745f0ee2ce835e1ac9576a7f7ef4be2cca
2,759
c
C
detector/pwm.c
shseok/smart-safety-system
2ada165a2ff5d65448fb3fe444134662c192d3ad
[ "MIT" ]
null
null
null
detector/pwm.c
shseok/smart-safety-system
2ada165a2ff5d65448fb3fe444134662c192d3ad
[ "MIT" ]
null
null
null
detector/pwm.c
shseok/smart-safety-system
2ada165a2ff5d65448fb3fe444134662c192d3ad
[ "MIT" ]
null
null
null
#include<sys/stat.h> #include<sys/types.h> #include<fcntl.h> #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #include"pwm.h" int PWMExport(int pwmnum){ char buffer[BUFFER_MAX]; int bytes_written; int fd; fd = open("/sys/class/pwm/pwmchip0/unexport", O_WRONLY); if(-1 == fd){ fprintf(stderr, "Failed to open in unexport!\n"); return -1; } bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pwmnum); write(fd, buffer, bytes_written); close(fd); sleep(1); fd = open("/sys/class/pwm/pwmchip0/export", O_WRONLY); if(-1 == fd){ fprintf(stderr, "Failed to open in export!\n"); return -1; } bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pwmnum); write(fd, buffer, bytes_written); close(fd); sleep(1); return 0; } int PWMEnable(int pwmnum){ static const char s_unenable_str[] = "0"; static const char s_enable_str[] = "1"; char path[DIRECTION_MAX]; int fd; snprintf(path, DIRECTION_MAX, "/sys/class/pwm/pwmchip0/pwm%d/enable", pwmnum); // agian to check fd = open(path, O_WRONLY); if(-1 == fd){ fprintf(stderr, "Failed to open in enable!\n"); return -1; } write(fd, s_unenable_str, strlen(s_unenable_str)); close(fd); fd = open(path, O_WRONLY); if(-1 == fd){ fprintf(stderr, "Failed to open in enable!\n"); return -1; } write(fd, s_enable_str, strlen(s_enable_str)); close(fd); return 0; } int PWMWritePeriod(int pwmnum, int value){ char s_values_str[VALUE_MAX]; char path[VALUE_MAX]; int fd, byte; snprintf(path, VALUE_MAX, "/sys/class/pwm/pwmchip0/pwm%d/period", pwmnum); //check again fd = open(path, O_WRONLY); if(-1 == fd){ fprintf(stderr, "Failed to open in period!\n"); return -1; } byte = snprintf(s_values_str, VALUE_MAX, "%d", value); //check again if(-1 == write(fd, s_values_str, byte)){ fprintf(stderr, "Failed to write value in period!\n"); close(fd); return -1; } close(fd); return 0; } int PWMWriteDutyCycle(int pwmnum, int value){ char path[VALUE_MAX]; char s_values_str[VALUE_MAX]; int fd, byte; snprintf(path, VALUE_MAX, "/sys/class/pwm/pwmchip0/pwm%d/duty_cycle", pwmnum); //check this again fd = open(path, O_WRONLY); if(-1 == fd){ fprintf(stderr, "Faided to open in duty_cycle!\n"); return -1; } byte = snprintf(s_values_str, VALUE_MAX, "%d", value); //check this again if(-1 == write(fd, s_values_str, byte)){ fprintf(stderr, "Failed to write value! in duty_cycle\n"); close(fd); return -1; } close(fd); return 0; }
24.415929
101
0.602392
afb1e23e4c13a6d39b42421cd9092cd1ff3459a0
4,600
c
C
src/math/sigmoid-f16-avx2-rr1-p3-rcp.c
xbwee1024/XNNPACK
c921972294e429c152f1cacf6dfe517b74470070
[ "BSD-3-Clause" ]
null
null
null
src/math/sigmoid-f16-avx2-rr1-p3-rcp.c
xbwee1024/XNNPACK
c921972294e429c152f1cacf6dfe517b74470070
[ "BSD-3-Clause" ]
null
null
null
src/math/sigmoid-f16-avx2-rr1-p3-rcp.c
xbwee1024/XNNPACK
c921972294e429c152f1cacf6dfe517b74470070
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2022 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <assert.h> #include <stddef.h> #include <immintrin.h> #include <xnnpack/math-stubs.h> void xnn_math_f16_sigmoid__avx2_rr1_p3_rcp( size_t n, const void* input, void* output) { assert(n % (8 * sizeof(uint16_t)) == 0); // Floating-point mask with only the sign bit set const __m256 vsign_mask = _mm256_set1_ps(-0.0f); // Large number such that ulp(magic bias) == 1 and magic bias === 127 mod 2**22. const __m256 vmagic_bias = _mm256_set1_ps(0x1.8000FEp23f); const __m256 vlog2e = _mm256_set1_ps(0x1.715476p0f); const __m256 vminus_ln2 = _mm256_set1_ps(-0x1.62E43p-1f); // Coefficient of polynomial approximation of // exp(t) ~ 1 + t * (c1 + t * (c2 + t * c3)) on [-log(2)/2, log(2)/2] const __m256 vc3 = _mm256_set1_ps(0x1.5249A6p-3f); const __m256 vc2 = _mm256_set1_ps(0x1.021D60p-1f); const __m256 vc1 = _mm256_set1_ps(0x1.000CD6p+0f); const __m256 vone = _mm256_set1_ps(1.0f); // The smallest x for which sigmoidh(x) is normalized. // This number is also the smallest x for which exph(x) is normalized. const __m256 vdenorm_cutoff = _mm256_set1_ps(-0x1.368000p+3f); const uint16_t* i = (const uint16_t*) input; uint16_t* o = (uint16_t*) output; for (; n != 0; n -= 8 * sizeof(uint16_t)) { const __m256 vx = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i*) i)); i += 8; // General structure of the algorithm: // // / exp(x) / (1 + exp(x)) if x <= 0 // f[x] := // \ 1 - f[-x] if x >= 0 // // First we compute f[z] := exp(z) / (1 + exp(z)) where z = -abs(x), then replace result with 1 - f[z] if x >= 0. const __m256 vz = _mm256_or_ps(vx, vsign_mask); // Compute reduced argument n := round(z / log(2)). // We do it by adding a large number (magic bias) to the product z * (1/log(2)), which cause rounding of the // result to an integer, then subtracing the large number back. The first addition is combined with multiplication // by log2e into a single FMA instruction. The trick with adding large number is valid only within certain bounds // (|x / log(2)| <= 2**9, i.e. |z| <= 0x1.630p+8 = 355.0), but that is acceptable, because inputs x outside // of [-9.703125, 8.3125] (i.e. z outside [9.703125, 0]) underflow or saturate sigmoidh(x). We fixup the result for // such inputs at the very end of the algorithm. __m256 vn = _mm256_fmadd_ps(vz, vlog2e, vmagic_bias); // Create a floating-point number s (scale) such that s == 2**n for inputs which don't cause underflow, i.e. // -9.703125 <= z <= 0.0, and -14 <= n <= 0 accordingly. const __m256 vs = _mm256_castsi256_ps(_mm256_slli_epi32(_mm256_castps_si256(vn), 23)); // Subtract the large number back to get the final n := round(z / log(2)) as a floating-point number. vn = _mm256_sub_ps(vn, vmagic_bias); // Compute reduced argument t := z - n * log(2). // Use Cody-Waite range reduction method (note two constants to represent log(2)) to improve accuracy. __m256 vt = _mm256_fmadd_ps(vn, vminus_ln2, vz); // Compute degree-3 polynomial approximation for exp(t) on [-log(2)/2, log(2)/2]. // P(t) = 1 + t * (c1 + t * (c2 + t * c3)) = 1 + t * p __m256 vp = _mm256_fmadd_ps(vc3, vt, vc2); vp = _mm256_fmadd_ps(vp, vt, vc1); // Reconstruct the exp(z) value: // e = s * (1 + t * (c1 + t * (c2 + t * c3))) // = s + (t * s) * (c1 + t * (c2 + t * c3)) // = s + (t * s) * p vt = _mm256_mul_ps(vt, vs); const __m256 ve = _mm256_fmadd_ps(vt, vp, vs); // Denominator of the sigmoid fraction: 1.0 + exp(z) const __m256 vd = _mm256_add_ps(ve, vone); // Compute approximate reciprocal of denominator. // Note: 1 < d <= 2, because z >= 0.0 and 0 < exp(-z) <= 1.0. // Thus the reciprocal of the denominator never overflows. const __m256 vr = _mm256_rcp_ps(vd); // Reconstruct sigmoid(z) = exp(z) / (1.0 + exp(z)) __m256 vf = _mm256_mul_ps(ve, vr); // For inputs below denormal cutoff, replace output with +0.0f. // Note that for NaN inputs, comparison result is false, and outputs are left unchanged. vf = _mm256_andnot_ps(_mm256_cmp_ps(vz, vdenorm_cutoff, _CMP_LT_OS), vf); // Reconstruct sigmoid(x) = x < 0 ? sigmoid(z) : 1.0 - sigmoid(z) vf = _mm256_blendv_ps(_mm256_sub_ps(vone, vf), vf, vx); _mm_storeu_si128((__m128i*) o, _mm256_cvtps_ph(vf, _MM_FROUND_NO_EXC)); o += 8; } }
43.396226
119
0.64087
6394bb1034679a8e2a05d2238b5fab8c1241555e
14,244
h
C
aws-cpp-sdk-iot/include/aws/iot/model/DescribeScheduledAuditResult.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-iot/include/aws/iot/model/DescribeScheduledAuditResult.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-iot/include/aws/iot/model/DescribeScheduledAuditResult.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/iot/IoT_EXPORTS.h> #include <aws/iot/model/AuditFrequency.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/iot/model/DayOfWeek.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace IoT { namespace Model { class AWS_IOT_API DescribeScheduledAuditResult { public: DescribeScheduledAuditResult(); DescribeScheduledAuditResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); DescribeScheduledAuditResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>How often the scheduled audit takes place, either one of <code>DAILY</code>, * <code>WEEKLY</code>, <code>BIWEEKLY</code>, or <code>MONTHLY</code>. The start * time of each audit is determined by the system.</p> */ inline const AuditFrequency& GetFrequency() const{ return m_frequency; } /** * <p>How often the scheduled audit takes place, either one of <code>DAILY</code>, * <code>WEEKLY</code>, <code>BIWEEKLY</code>, or <code>MONTHLY</code>. The start * time of each audit is determined by the system.</p> */ inline void SetFrequency(const AuditFrequency& value) { m_frequency = value; } /** * <p>How often the scheduled audit takes place, either one of <code>DAILY</code>, * <code>WEEKLY</code>, <code>BIWEEKLY</code>, or <code>MONTHLY</code>. The start * time of each audit is determined by the system.</p> */ inline void SetFrequency(AuditFrequency&& value) { m_frequency = std::move(value); } /** * <p>How often the scheduled audit takes place, either one of <code>DAILY</code>, * <code>WEEKLY</code>, <code>BIWEEKLY</code>, or <code>MONTHLY</code>. The start * time of each audit is determined by the system.</p> */ inline DescribeScheduledAuditResult& WithFrequency(const AuditFrequency& value) { SetFrequency(value); return *this;} /** * <p>How often the scheduled audit takes place, either one of <code>DAILY</code>, * <code>WEEKLY</code>, <code>BIWEEKLY</code>, or <code>MONTHLY</code>. The start * time of each audit is determined by the system.</p> */ inline DescribeScheduledAuditResult& WithFrequency(AuditFrequency&& value) { SetFrequency(std::move(value)); return *this;} /** * <p>The day of the month on which the scheduled audit takes place. This is will * be <code>1</code> through <code>31</code> or <code>LAST</code>. If days * <code>29</code>-<code>31</code> are specified, and the month does not have that * many days, the audit takes place on the <code>LAST</code> day of the month.</p> */ inline const Aws::String& GetDayOfMonth() const{ return m_dayOfMonth; } /** * <p>The day of the month on which the scheduled audit takes place. This is will * be <code>1</code> through <code>31</code> or <code>LAST</code>. If days * <code>29</code>-<code>31</code> are specified, and the month does not have that * many days, the audit takes place on the <code>LAST</code> day of the month.</p> */ inline void SetDayOfMonth(const Aws::String& value) { m_dayOfMonth = value; } /** * <p>The day of the month on which the scheduled audit takes place. This is will * be <code>1</code> through <code>31</code> or <code>LAST</code>. If days * <code>29</code>-<code>31</code> are specified, and the month does not have that * many days, the audit takes place on the <code>LAST</code> day of the month.</p> */ inline void SetDayOfMonth(Aws::String&& value) { m_dayOfMonth = std::move(value); } /** * <p>The day of the month on which the scheduled audit takes place. This is will * be <code>1</code> through <code>31</code> or <code>LAST</code>. If days * <code>29</code>-<code>31</code> are specified, and the month does not have that * many days, the audit takes place on the <code>LAST</code> day of the month.</p> */ inline void SetDayOfMonth(const char* value) { m_dayOfMonth.assign(value); } /** * <p>The day of the month on which the scheduled audit takes place. This is will * be <code>1</code> through <code>31</code> or <code>LAST</code>. If days * <code>29</code>-<code>31</code> are specified, and the month does not have that * many days, the audit takes place on the <code>LAST</code> day of the month.</p> */ inline DescribeScheduledAuditResult& WithDayOfMonth(const Aws::String& value) { SetDayOfMonth(value); return *this;} /** * <p>The day of the month on which the scheduled audit takes place. This is will * be <code>1</code> through <code>31</code> or <code>LAST</code>. If days * <code>29</code>-<code>31</code> are specified, and the month does not have that * many days, the audit takes place on the <code>LAST</code> day of the month.</p> */ inline DescribeScheduledAuditResult& WithDayOfMonth(Aws::String&& value) { SetDayOfMonth(std::move(value)); return *this;} /** * <p>The day of the month on which the scheduled audit takes place. This is will * be <code>1</code> through <code>31</code> or <code>LAST</code>. If days * <code>29</code>-<code>31</code> are specified, and the month does not have that * many days, the audit takes place on the <code>LAST</code> day of the month.</p> */ inline DescribeScheduledAuditResult& WithDayOfMonth(const char* value) { SetDayOfMonth(value); return *this;} /** * <p>The day of the week on which the scheduled audit takes place, either one of * <code>SUN</code>, <code>MON</code>, <code>TUE</code>, <code>WED</code>, * <code>THU</code>, <code>FRI</code>, or <code>SAT</code>.</p> */ inline const DayOfWeek& GetDayOfWeek() const{ return m_dayOfWeek; } /** * <p>The day of the week on which the scheduled audit takes place, either one of * <code>SUN</code>, <code>MON</code>, <code>TUE</code>, <code>WED</code>, * <code>THU</code>, <code>FRI</code>, or <code>SAT</code>.</p> */ inline void SetDayOfWeek(const DayOfWeek& value) { m_dayOfWeek = value; } /** * <p>The day of the week on which the scheduled audit takes place, either one of * <code>SUN</code>, <code>MON</code>, <code>TUE</code>, <code>WED</code>, * <code>THU</code>, <code>FRI</code>, or <code>SAT</code>.</p> */ inline void SetDayOfWeek(DayOfWeek&& value) { m_dayOfWeek = std::move(value); } /** * <p>The day of the week on which the scheduled audit takes place, either one of * <code>SUN</code>, <code>MON</code>, <code>TUE</code>, <code>WED</code>, * <code>THU</code>, <code>FRI</code>, or <code>SAT</code>.</p> */ inline DescribeScheduledAuditResult& WithDayOfWeek(const DayOfWeek& value) { SetDayOfWeek(value); return *this;} /** * <p>The day of the week on which the scheduled audit takes place, either one of * <code>SUN</code>, <code>MON</code>, <code>TUE</code>, <code>WED</code>, * <code>THU</code>, <code>FRI</code>, or <code>SAT</code>.</p> */ inline DescribeScheduledAuditResult& WithDayOfWeek(DayOfWeek&& value) { SetDayOfWeek(std::move(value)); return *this;} /** * <p>Which checks are performed during the scheduled audit. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the * list of all checks, including those that are enabled or use * <code>UpdateAccountAuditConfiguration</code> to select which checks are * enabled.)</p> */ inline const Aws::Vector<Aws::String>& GetTargetCheckNames() const{ return m_targetCheckNames; } /** * <p>Which checks are performed during the scheduled audit. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the * list of all checks, including those that are enabled or use * <code>UpdateAccountAuditConfiguration</code> to select which checks are * enabled.)</p> */ inline void SetTargetCheckNames(const Aws::Vector<Aws::String>& value) { m_targetCheckNames = value; } /** * <p>Which checks are performed during the scheduled audit. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the * list of all checks, including those that are enabled or use * <code>UpdateAccountAuditConfiguration</code> to select which checks are * enabled.)</p> */ inline void SetTargetCheckNames(Aws::Vector<Aws::String>&& value) { m_targetCheckNames = std::move(value); } /** * <p>Which checks are performed during the scheduled audit. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the * list of all checks, including those that are enabled or use * <code>UpdateAccountAuditConfiguration</code> to select which checks are * enabled.)</p> */ inline DescribeScheduledAuditResult& WithTargetCheckNames(const Aws::Vector<Aws::String>& value) { SetTargetCheckNames(value); return *this;} /** * <p>Which checks are performed during the scheduled audit. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the * list of all checks, including those that are enabled or use * <code>UpdateAccountAuditConfiguration</code> to select which checks are * enabled.)</p> */ inline DescribeScheduledAuditResult& WithTargetCheckNames(Aws::Vector<Aws::String>&& value) { SetTargetCheckNames(std::move(value)); return *this;} /** * <p>Which checks are performed during the scheduled audit. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the * list of all checks, including those that are enabled or use * <code>UpdateAccountAuditConfiguration</code> to select which checks are * enabled.)</p> */ inline DescribeScheduledAuditResult& AddTargetCheckNames(const Aws::String& value) { m_targetCheckNames.push_back(value); return *this; } /** * <p>Which checks are performed during the scheduled audit. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the * list of all checks, including those that are enabled or use * <code>UpdateAccountAuditConfiguration</code> to select which checks are * enabled.)</p> */ inline DescribeScheduledAuditResult& AddTargetCheckNames(Aws::String&& value) { m_targetCheckNames.push_back(std::move(value)); return *this; } /** * <p>Which checks are performed during the scheduled audit. Checks must be enabled * for your account. (Use <code>DescribeAccountAuditConfiguration</code> to see the * list of all checks, including those that are enabled or use * <code>UpdateAccountAuditConfiguration</code> to select which checks are * enabled.)</p> */ inline DescribeScheduledAuditResult& AddTargetCheckNames(const char* value) { m_targetCheckNames.push_back(value); return *this; } /** * <p>The name of the scheduled audit.</p> */ inline const Aws::String& GetScheduledAuditName() const{ return m_scheduledAuditName; } /** * <p>The name of the scheduled audit.</p> */ inline void SetScheduledAuditName(const Aws::String& value) { m_scheduledAuditName = value; } /** * <p>The name of the scheduled audit.</p> */ inline void SetScheduledAuditName(Aws::String&& value) { m_scheduledAuditName = std::move(value); } /** * <p>The name of the scheduled audit.</p> */ inline void SetScheduledAuditName(const char* value) { m_scheduledAuditName.assign(value); } /** * <p>The name of the scheduled audit.</p> */ inline DescribeScheduledAuditResult& WithScheduledAuditName(const Aws::String& value) { SetScheduledAuditName(value); return *this;} /** * <p>The name of the scheduled audit.</p> */ inline DescribeScheduledAuditResult& WithScheduledAuditName(Aws::String&& value) { SetScheduledAuditName(std::move(value)); return *this;} /** * <p>The name of the scheduled audit.</p> */ inline DescribeScheduledAuditResult& WithScheduledAuditName(const char* value) { SetScheduledAuditName(value); return *this;} /** * <p>The ARN of the scheduled audit.</p> */ inline const Aws::String& GetScheduledAuditArn() const{ return m_scheduledAuditArn; } /** * <p>The ARN of the scheduled audit.</p> */ inline void SetScheduledAuditArn(const Aws::String& value) { m_scheduledAuditArn = value; } /** * <p>The ARN of the scheduled audit.</p> */ inline void SetScheduledAuditArn(Aws::String&& value) { m_scheduledAuditArn = std::move(value); } /** * <p>The ARN of the scheduled audit.</p> */ inline void SetScheduledAuditArn(const char* value) { m_scheduledAuditArn.assign(value); } /** * <p>The ARN of the scheduled audit.</p> */ inline DescribeScheduledAuditResult& WithScheduledAuditArn(const Aws::String& value) { SetScheduledAuditArn(value); return *this;} /** * <p>The ARN of the scheduled audit.</p> */ inline DescribeScheduledAuditResult& WithScheduledAuditArn(Aws::String&& value) { SetScheduledAuditArn(std::move(value)); return *this;} /** * <p>The ARN of the scheduled audit.</p> */ inline DescribeScheduledAuditResult& WithScheduledAuditArn(const char* value) { SetScheduledAuditArn(value); return *this;} private: AuditFrequency m_frequency; Aws::String m_dayOfMonth; DayOfWeek m_dayOfWeek; Aws::Vector<Aws::String> m_targetCheckNames; Aws::String m_scheduledAuditName; Aws::String m_scheduledAuditArn; }; } // namespace Model } // namespace IoT } // namespace Aws
43.294833
151
0.675723
17cba59bad905567b0ab2c7eb5787f309131b495
502
h
C
include/Msnhnet/core/MsnhBlasNCHW8.h
zh794390558/Msnhnet
38f8a83146c487d0e2b6053c13ddc584f7969994
[ "MIT" ]
null
null
null
include/Msnhnet/core/MsnhBlasNCHW8.h
zh794390558/Msnhnet
38f8a83146c487d0e2b6053c13ddc584f7969994
[ "MIT" ]
null
null
null
include/Msnhnet/core/MsnhBlasNCHW8.h
zh794390558/Msnhnet
38f8a83146c487d0e2b6053c13ddc584f7969994
[ "MIT" ]
null
null
null
#ifndef MSNHBLASNCHW8_H #define MSNHBLASNCHW8_H #include <algorithm> #include "Msnhnet/config/MsnhnetCfg.h" #include "Msnhnet/core/MsnhSimd.h" namespace Msnhnet { #define NCHW8_PACK 8 class MsnhNet_API BlasNCHW8 { public: static void cpuNCHWToNCHW8(float *const &org, const int width, const int height, const int channel, const int batch, float * const &dst); static size_t getNCHW8Params(const int width, const int height, const int channel, int &outWidth, int& outChannel); }; } #endif
23.904762
141
0.760956
1735f2d7fc936b716320110ddab281380dba4896
920
h
C
platform/linux-generic/test/ring/ring_suites.h
bala-manoharan/odp-dpdk
130f424695749f1859eebd33ebce18ef9ce36438
[ "BSD-3-Clause" ]
null
null
null
platform/linux-generic/test/ring/ring_suites.h
bala-manoharan/odp-dpdk
130f424695749f1859eebd33ebce18ef9ce36438
[ "BSD-3-Clause" ]
null
null
null
platform/linux-generic/test/ring/ring_suites.h
bala-manoharan/odp-dpdk
130f424695749f1859eebd33ebce18ef9ce36438
[ "BSD-3-Clause" ]
1
2019-02-09T08:41:27.000Z
2019-02-09T08:41:27.000Z
/* Copyright (c) 2016-2018, Linaro Limited * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #define RING_SIZE 4096 #define PIECE_BULK 32 #define HALF_BULK (RING_SIZE >> 1) #define ILLEGAL_SIZE (RING_SIZE | 0x3) /* test suite start and stop */ int ring_test_basic_start(void); int ring_test_basic_end(void); /* basic test cases */ void ring_test_basic_create(void); void ring_test_basic_burst(void); void ring_test_basic_bulk(void); void ring_test_basic_watermark(void); /* test suite start and stop */ int ring_test_stress_start(void); int ring_test_stress_end(void); /* stress test cases */ void ring_test_stress_1_1_producer_consumer(void); void ring_test_stress_1_N_producer_consumer(void); void ring_test_stress_N_1_producer_consumer(void); void ring_test_stress_N_M_producer_consumer(void); void ring_test_stress_ring_list_dump(void); int ring_suites_main(int argc, char *argv[]);
26.285714
50
0.792391
1786a0f1cce1005e2bc0e91160d85580fd8ff9da
5,118
h
C
src/util/ranlcg.h
EPCCed/ffs
e1086fb0e294c7753ca3e523e53604c679e51c7f
[ "BSD-3-Clause" ]
4
2018-10-05T11:51:27.000Z
2022-02-22T17:54:13.000Z
src/util/ranlcg.h
EPCCed/ffs
e1086fb0e294c7753ca3e523e53604c679e51c7f
[ "BSD-3-Clause" ]
null
null
null
src/util/ranlcg.h
EPCCed/ffs
e1086fb0e294c7753ca3e523e53604c679e51c7f
[ "BSD-3-Clause" ]
1
2021-12-24T08:17:00.000Z
2021-12-24T08:17:00.000Z
/*************************************************************************//** * * \file ranlcg.h * * Linear Congrutial random number generator. * * Parallel Forward Flux Sampling * (c) 2012 The University of Edinburgh * Funded by United Kingdom EPSRC Grant EP/I030298/1 * *****************************************************************************/ #ifndef RANLCG_H #define RANLCG_H /** * \defgroup ranlcg_t Random Number Generator * \ingroup utilities * \{ * Random number generator utility. * * A linear congruential generator for uniform random numbers based * on one by L'Ecuyer and Simard. See, for example the testu01 * packages (v1.2.2) * http://www.iro.umontreal.ca/~simardr/testu01/tu01.html * * The interface consists of an opaque object \c ranlcg_t and the * following functions. A default set of parameters is supplied * when the object is created. However, the user may override * this choice by explicitly setting the parameters \c a, \c c, and \c m * which determine the evolution of the state via * * <tt> state -> a*(state + c) % m </tt> * * The default parameter values are from TestU01/param/LCGGood.par * in the testu01 package. */ /** * \brief Opaque random number generator object */ typedef struct ranlcg_type ranlcg_t; /** * * \def RANLCG_ADEFAULT32 * Parameter \c a value for 32-bit integer * \def RANLCG_CDEFAULT32 * Parameter \c c value for 32-bit integer * \def RANLCG_MDEFAULT32 * Parameter \c m value for 32-bit integer */ #define RANLCG_ADEFAULT32 1389796 #define RANLCG_CDEFAULT32 0 #define RANLCG_MDEFAULT32 2147483647 /** * * \def RANLCG_ADEFAULT64 * Parameter \c a value for 64-bit integer * \def RANLCG_CDEFAULT64 * Parameter \c c value for 64-bit integer * \def RANLCG_MDEFAULT64 * Parameter \c m value for 64-bit integer */ #define RANLCG_ADEFAULT64 561860773102413563 #define RANLCG_CDEFAULT64 0 #define RANLCG_MDEFAULT64 1152921504606846883 /** * \def RANLCG_ADEFAULT * Default parameter value for constant multiplier \c a. * \def RANLCG_CDEFAULT * Default parameter value for additive constant \c c. * \def RANLCG_MDEFAULT * Default parameter value for modulus \c m. */ #if LONG_MAX == 2147483647 #define RANLCG_ADEFAULT RANLCG_ADEFAULT32 #define RANLCG_CDEFAULT RANLCG_CDEFAULT32 #define RANLCG_MDEFAULT RANLCG_MDEFAULT32 #else #define RANLCG_ADEFAULT RANLCG_ADEFAULT64 #define RANLCG_CDEFAULT RANLCG_CDEFAULT64 #define RANLCG_MDEFAULT RANLCG_MDEFAULT64 #endif /** * \brief Create and return a new object with the specified state * * \param state the initial state to be set * \param pnew a pointer to the new object to be returned * * \retval 0 a success * \retval -1 a failure */ int ranlcg_create(long int state, ranlcg_t ** pnew); /** * \brief Create a 32-bit version * * \param seed the 32-bit integer seed * \param pobj a point to the new structure to be returned * * \retval 0 a success * \retval -1 a failure (a NULL pointer or invalid seed was * received) * * This uses the 32-bit parameter values and is intended for use * with ranlcg_reep_int32() (only). */ int ranlcg_create32(int seed, ranlcg_t ** pobj); /** * \brief Release a ranlcg_t object * * \param p a pointer to the object to be released * * \retval none */ void ranlcg_free(ranlcg_t * p); /** * \brief Return the next uniform deviate [0,1) in the sequence * * \param p the ranlcg_t object * \param reep a pointer to the value to be returned * * \retval 0 a success * \retval -1 a failure */ int ranlcg_reep(ranlcg_t * p, double * reep); /** * \brief Return next-in-sequence as 32-bit integer [0, INT_MAX - 1] * * This potentially reduces the state from (long int) to (int) * * \param p a pointer to the ranlcg_t object * \param ireep the random deviate to be returned * * \retval 0 a success * \retval -1 a failure */ int ranlcg_reep_int32(ranlcg_t * p, int * ireep); /** * \brief Reset the state of an existing ranlcg_t object * * \param p a pointer to the ranlcg_t object * \param newstate the new value of the state to be set * * \retval 0 a success * \retval -1 a failure */ int ranlcg_state_set(ranlcg_t * p, long int newstate); /** * \brief Reset parameters of existing ranlcg_t object s -> (a*s + c) % m * * \param p a pointer to the ranlcg_t object * \param a the new parameter \c a * \param c the new parameter \c c * \param m the new parameter \c m * * \retval 0 a success * \retval -1 a failure */ int ranlcg_param_set(ranlcg_t * p, long int a, long int c, long int m); /** * \brief Return the current state * * \param p a pointer to the ranlcg_t object * \param state a pointer to the state to be returned * * \retval 0 a success * \retval -1 a failure */ int ranlcg_state(const ranlcg_t * p, long int * state); /** * \} */ #endif
25.59
79
0.646932
9d7561709b8252409847d4bdbc2da675c6bf109a
1,242
h
C
Game/Map.h
raphaelhamzagic/CGS_ProjectZ
3664602fc1c428baac69d08219d692ec9e1d3c09
[ "MIT" ]
null
null
null
Game/Map.h
raphaelhamzagic/CGS_ProjectZ
3664602fc1c428baac69d08219d692ec9e1d3c09
[ "MIT" ]
null
null
null
Game/Map.h
raphaelhamzagic/CGS_ProjectZ
3664602fc1c428baac69d08219d692ec9e1d3c09
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include "PlaceableActor.h" namespace projectz { namespace game { class Point; class Map { int m_width; int m_height; char *m_pBlueprintMap; char *m_pGameplayMap; public: Map(); ~Map(); bool Load(std::string levelFileName, std::vector<PlaceableActor*> &actorsOut, Point &playerInitialPositionOut); bool Convert(const char *const pMapBlueprint, const char *const pMapGameplay, std::vector<PlaceableActor*> &actorsOut, Point& playerInitialPositionOut); void Draw(const int playerX, const int playerY); char GetRoomAtPosition(int x, int y); void GetSurroundingRoomsFromPosition(int x, int y, std::vector<char> &roomsOut); bool IsWall(int x, int y); bool IsWindow(int x, int y); bool IsEmpty(int x, int y); int GetWidth() const { return m_width; }; int GetHeight() const { return m_height; }; private: int GetIndexFromCoordinates(const Point &p); int GetIndexFromCoordinates(const int &x, const int &y); }; } }
28.883721
164
0.586151
1264189647024c61f23e6b10ed2280829dc83648
2,574
h
C
sdk-6.5.20/src/bcm/dnx/tunnel/tunnel_init_ipv6.h
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/bcm/dnx/tunnel/tunnel_init_ipv6.h
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/bcm/dnx/tunnel/tunnel_init_ipv6.h
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ /** \file tunnel_init_ipv6.h * Tunnel init functionality for DNX tunnel encapsaultion */ #ifndef _TUNNEL_INIT_IPV6_INCLUDED__ /* * { */ #define _TUNNEL_INIT_IPV6_INCLUDED__ #ifndef BCM_DNX_SUPPORT #error "This file is for use by DNX (JR2) family only!" #endif /* BCM_DNX_SUPPORT */ /* * Include files. * { */ #include <bcm/types.h> #include <bcm/tunnel.h> #include <shared/shrextend/shrextend_debug.h> /* * } */ /** * \brief * The function indicate if a tunnel is ipv6 * \param [in] unit - * The unit number. * \param [in] tunnel_type - tunnel type * \param [out] is_ipv6 - is ipv6 indication */ void dnx_tunnel_init_ipv6_is_ipv6_tunnel( int unit, bcm_tunnel_type_t tunnel_type, uint32 *is_ipv6); /** * \brief * Write to IP tunnel encapsulation out-LIF data entry table. * * \param [in] unit - Relevant unit. * \param [in] tunnel - A pointer to the struct that holds information for the IPv4 tunnel encapsulation entry, * see \ref bcm_tunnel_initiator_t. * \param [in] local_outlif - * Local-Out-LIF whose entry should be added to out-LIF table. * \param [in] next_local_outlif - next local out lif for * outlif entry * * \return * \retval Negative in case of an error * \retval Zero in case of NO ERROR * * \remark * * The entry is written to DBAL_TABLE_EEDB_DATA_ENTRY */ shr_error_e dnx_tunnel_initiator_ipv6_data_entry_table_set( int unit, bcm_tunnel_initiator_t * tunnel, uint32 next_local_outlif, uint32 *local_outlif); /** * \brief * read IP tunnel encapsulation out-LIF data entry table. * * \param [in] unit - Relevant unit. * \param [in] tunnel - A pointer to the struct that holds information for the IPv4 tunnel encapsulation entry, * see \ref bcm_tunnel_initiator_t. * \param [in] local_outlif - * Local-Out-LIF whose entry should be added to out-LIF table. * \param [in] local_next_outlif - next local out lif for * outlif entry * * \return * \retval Negative in case of an error * \retval Zero in case of NO ERROR * * \remark * * The entry is written to DBAL_TABLE_EEDB_DATA_ENTRY */ shr_error_e dnx_tunnel_initiator_ipv6_data_entry_table_get( int unit, bcm_tunnel_initiator_t * tunnel, uint32 local_outlif, uint32 *local_next_outlif); #endif /*_TUNNEL_INIT_IPV6_INCLUDED__ */
26.8125
134
0.699301
8fbc109f7e78e280523d2c0ec9be6112b0c31e51
74,270
c
C
src/afs/UKERNEL/afs_usrops.c
bagdxk/openafs
8f1eba056fd2d2792a7d2b61d5dbcdd799bc173d
[ "BSD-3-Clause" ]
54
2015-01-26T02:12:37.000Z
2022-02-09T07:00:34.000Z
src/afs/UKERNEL/afs_usrops.c
bagdxk/openafs
8f1eba056fd2d2792a7d2b61d5dbcdd799bc173d
[ "BSD-3-Clause" ]
5
2016-08-12T04:37:29.000Z
2020-12-10T16:46:06.000Z
src/afs/UKERNEL/afs_usrops.c
bagdxk/openafs
8f1eba056fd2d2792a7d2b61d5dbcdd799bc173d
[ "BSD-3-Clause" ]
38
2015-07-30T13:27:25.000Z
2022-01-27T06:45:13.000Z
/* * Copyright 2000, International Business Machines Corporation and others. * All Rights Reserved. * * This software has been released under the terms of the IBM Public * License. For details, see the LICENSE file in the top-level source * directory or online at http://www.openafs.org/dl/license10.html */ /* * User space client specific interface glue */ #include <afsconfig.h> #include "afs/param.h" #ifdef UKERNEL #include "afs/sysincludes.h" /* Standard vendor system headers */ #include <net/if.h> #include "afsincludes.h" /* Afs-based standard headers */ #include "afs_usrops.h" #include "afs/afs_stats.h" #include "afs/auth.h" #include "afs/cellconfig.h" #include "afs/vice.h" #include "afs/afsutil.h" #include "afs/afs_bypasscache.h" #include "rx/rx_globals.h" #include "afsd/afsd.h" #define VFS 1 #undef VIRTUE #undef VICE #ifndef AFS_CACHE_VNODE_PATH #error You must compile UKERNEL code with -DAFS_CACHE_VNODE_PATH #endif #define CACHEINFOFILE "cacheinfo" #define AFSLOGFILE "AFSLog" #define DCACHEFILE "CacheItems" #define VOLINFOFILE "VolumeItems" #define CELLINFOFILE "CellItems" #define MAXIPADDRS 64 #ifndef MIN #define MIN(A,B) ((A)<(B)?(A):(B)) #endif #ifndef MAX #define MAX(A,B) ((A)>(B)?(A):(B)) #endif extern int cacheDiskType; char afs_LclCellName[64]; static struct usr_vnode *afs_FileTable[MAX_OSI_FILES]; static int afs_FileFlags[MAX_OSI_FILES]; static off_t afs_FileOffsets[MAX_OSI_FILES]; #define MAX_CACHE_LOOPS 4 static struct usr_vfs afs_RootVfs; static struct usr_vnode *afs_RootVnode = NULL; static struct usr_vnode *afs_CurrentDir = NULL; static char afs_mountDir[1024]; /* AFS mount point */ static int afs_mountDirLen; /* strlen of AFS mount point */ struct afsconf_dir *afs_cdir; /* config dir */ int afs_bufferpages = 100; static usr_key_t afs_global_u_key; static struct usr_proc *afs_global_procp = NULL; static struct usr_ucred *afs_global_ucredp = NULL; struct usr_ucred afs_osi_cred, *afs_osi_credp; usr_mutex_t afs_global_lock; usr_thread_t afs_global_owner; usr_mutex_t rx_global_lock; usr_thread_t rx_global_owner; static usr_mutex_t osi_dummy_lock; static usr_mutex_t osi_waitq_lock; static usr_mutex_t osi_authenticate_lock; afs_lock_t afs_ftf; afs_lock_t osi_flplock; afs_lock_t osi_fsplock; /* * Mutex and condition variable used to implement sleep */ pthread_mutex_t usr_sleep_mutex; pthread_cond_t usr_sleep_cond; int call_syscall(long, long, long, long, long, long); int fork_syscall(long, long, long, long, long, long); /* * Hash table mapping addresses onto wait structures for * osi_Sleep/osi_Wakeup and osi_Wait/osi_Wakeup */ typedef struct osi_wait { caddr_t addr; usr_cond_t cond; int flag; struct osi_wait *next; struct osi_wait *prev; time_t expiration; struct osi_wait *timedNext; struct osi_wait *timedPrev; } osi_wait_t; /* * Head of the linked list of available waitq structures. */ static osi_wait_t *osi_waithash_avail; /* * List of timed waits, NSAPI does not provide a cond_timed * wait, so we need to keep track of the timed waits ourselves and * periodically check for expirations */ static osi_wait_t *osi_timedwait_head; static osi_wait_t *osi_timedwait_tail; static struct { osi_wait_t *head; osi_wait_t *tail; } osi_waithash_table[OSI_WAITHASH_SIZE]; /* * Never call afs_brelse */ int ufs_brelse(struct usr_vnode *vp, struct usr_buf *bp) { usr_assert(0); return 0; } /* * I am not sure what to do with these, they assert for now */ int iodone(struct usr_buf *bp) { usr_assert(0); return 0; } struct usr_file * getf(int fd) { usr_assert(0); return 0; } /* * Every user is a super user */ int afs_osi_suser(afs_ucred_t *credp) { return 1; } int afs_suser(afs_ucred_t *credp) { return 1; } /* * These are no-ops in user space */ /* * xflock should never fall through, the only files we know * about are AFS files */ int usr_flock(void) { usr_assert(0); return 0; } /* * ioctl should never fall through, the only files we know * about are AFS files */ int usr_ioctl(void) { usr_assert(0); return 0; } /* * We do not support the inode related system calls */ int afs_syscall_icreate(long a, long b, long c, long d, long e, long f) { usr_assert(0); return 0; } int afs_syscall_iincdec(int dev, int inode, int inode_p1, int amount) { usr_assert(0); return 0; } int afs_syscall_iopen(int dev, int inode, int usrmod) { usr_assert(0); return 0; } int afs_syscall_ireadwrite(void) { usr_assert(0); return 0; } /* * these routines are referenced in the vfsops structure, but * should never get called */ int vno_close(void) { usr_assert(0); return 0; } int vno_ioctl(void) { usr_assert(0); return 0; } int vno_rw(void) { usr_assert(0); return 0; } int vno_select(void) { usr_assert(0); return 0; } /* * uiomove copies data between kernel buffers and uio buffers */ int usr_uiomove(char *kbuf, int n, int rw, struct usr_uio *uio) { int nio; int len; char *ptr; struct iovec *iovp; nio = uio->uio_iovcnt; iovp = uio->uio_iov; if (nio <= 0) return EFAULT; /* * copy the data */ ptr = kbuf; while (nio > 0 && n > 0) { len = MIN(n, iovp->iov_len); if (rw == UIO_READ) { memcpy(iovp->iov_base, ptr, len); } else { memcpy(ptr, iovp->iov_base, len); } n -= len; ptr += len; uio->uio_resid -= len; uio->uio_offset += len; iovp->iov_base = (char *)(iovp->iov_base) + len; iovp->iov_len -= len; iovp++; nio--; } if (n > 0) return EFAULT; return 0; } /* * routines to manage user credentials */ struct usr_ucred * usr_crcopy(struct usr_ucred *credp) { struct usr_ucred *newcredp; newcredp = afs_osi_Alloc(sizeof(struct usr_ucred)); *newcredp = *credp; newcredp->cr_ref = 1; return newcredp; } struct usr_ucred * usr_crget(void) { struct usr_ucred *newcredp; newcredp = afs_osi_Alloc(sizeof(struct usr_ucred)); newcredp->cr_ref = 1; return newcredp; } int usr_crfree(struct usr_ucred *credp) { credp->cr_ref--; if (credp->cr_ref == 0) { afs_osi_Free((char *)credp, sizeof(struct usr_ucred)); } return 0; } int usr_crhold(struct usr_ucred *credp) { credp->cr_ref++; return 0; } void usr_vattr_null(struct usr_vattr *vap) { int n; char *cp; n = sizeof(struct usr_vattr); cp = (char *)vap; while (n--) { *cp++ = -1; } } /* * Initialize the thread specific data used to simulate the * kernel environment for each thread. The user structure * is stored in the thread specific data. */ void uafs_InitThread(void) { int st; struct usr_user *uptr; /* * initialize the thread specific user structure. Use malloc to * allocate the data block, so pthread_finish can free the buffer * when this thread terminates. */ uptr = malloc(sizeof(struct usr_user) + sizeof(struct usr_ucred)); usr_assert(uptr != NULL); uptr->u_error = 0; uptr->u_prio = 0; uptr->u_procp = afs_global_procp; uptr->u_cred = (struct usr_ucred *)(uptr + 1); *uptr->u_cred = *afs_global_ucredp; st = usr_setspecific(afs_global_u_key, (void *)uptr); usr_assert(st == 0); } /* * routine to get the user structure from the thread specific data. * this routine is used to implement the global 'u' structure. Initializes * the thread if needed. */ struct usr_user * get_user_struct(void) { struct usr_user *uptr; int st; st = usr_getspecific(afs_global_u_key, &uptr); usr_assert(st == 0); if (uptr == NULL) { uafs_InitThread(); st = usr_getspecific(afs_global_u_key, &uptr); usr_assert(st == 0); usr_assert(uptr != NULL); } return uptr; } /* * Hash an address for the waithash table */ #define WAITHASH(X) \ (((long)(X)^((long)(X)>>4)^((long)(X)<<4))&(OSI_WAITHASH_SIZE-1)) /* * Sleep on an event */ void afs_osi_Sleep(void *x) { int index; osi_wait_t *waitp; int glockOwner = ISAFS_GLOCK(); usr_mutex_lock(&osi_waitq_lock); if (glockOwner) { AFS_GUNLOCK(); } index = WAITHASH(x); if (osi_waithash_avail == NULL) { waitp = afs_osi_Alloc(sizeof(osi_wait_t)); usr_cond_init(&waitp->cond); } else { waitp = osi_waithash_avail; osi_waithash_avail = osi_waithash_avail->next; } waitp->addr = x; waitp->flag = 0; DLL_INSERT_TAIL(waitp, osi_waithash_table[index].head, osi_waithash_table[index].tail, next, prev); waitp->expiration = 0; waitp->timedNext = NULL; waitp->timedPrev = NULL; while (waitp->flag == 0) { usr_cond_wait(&waitp->cond, &osi_waitq_lock); } DLL_DELETE(waitp, osi_waithash_table[index].head, osi_waithash_table[index].tail, next, prev); waitp->next = osi_waithash_avail; osi_waithash_avail = waitp; usr_mutex_unlock(&osi_waitq_lock); if (glockOwner) { AFS_GLOCK(); } } int afs_osi_SleepSig(void *x) { afs_osi_Sleep(x); return 0; } int afs_osi_Wakeup(void *x) { int index; osi_wait_t *waitp; index = WAITHASH(x); usr_mutex_lock(&osi_waitq_lock); waitp = osi_waithash_table[index].head; while (waitp) { if (waitp->addr == x && waitp->flag == 0) { waitp->flag = 1; usr_cond_signal(&waitp->cond); } waitp = waitp->next; } usr_mutex_unlock(&osi_waitq_lock); return 0; } int afs_osi_TimedSleep(void *event, afs_int32 ams, int aintok) { return afs_osi_Wait(ams, event, aintok); } int afs_osi_Wait(afs_int32 msec, struct afs_osi_WaitHandle *handle, int intok) { int index; osi_wait_t *waitp; struct timespec tv; int ret; int glockOwner = ISAFS_GLOCK(); tv.tv_sec = msec / 1000; tv.tv_nsec = (msec % 1000) * 1000000; if (handle == NULL) { if (glockOwner) { AFS_GUNLOCK(); } usr_thread_sleep(&tv); ret = 0; if (glockOwner) { AFS_GLOCK(); } } else { usr_mutex_lock(&osi_waitq_lock); if (glockOwner) { AFS_GUNLOCK(); } index = WAITHASH((caddr_t) handle); if (osi_waithash_avail == NULL) { waitp = afs_osi_Alloc(sizeof(osi_wait_t)); usr_cond_init(&waitp->cond); } else { waitp = osi_waithash_avail; osi_waithash_avail = osi_waithash_avail->next; } waitp->addr = (caddr_t) handle; waitp->flag = 0; DLL_INSERT_TAIL(waitp, osi_waithash_table[index].head, osi_waithash_table[index].tail, next, prev); tv.tv_sec += time(NULL); waitp->expiration = tv.tv_sec + ((tv.tv_nsec == 0) ? 0 : 1); DLL_INSERT_TAIL(waitp, osi_timedwait_head, osi_timedwait_tail, timedNext, timedPrev); usr_cond_wait(&waitp->cond, &osi_waitq_lock); if (waitp->flag) { ret = 2; } else { ret = 0; } DLL_DELETE(waitp, osi_waithash_table[index].head, osi_waithash_table[index].tail, next, prev); DLL_DELETE(waitp, osi_timedwait_head, osi_timedwait_tail, timedNext, timedPrev); waitp->next = osi_waithash_avail; osi_waithash_avail = waitp; usr_mutex_unlock(&osi_waitq_lock); if (glockOwner) { AFS_GLOCK(); } } return ret; } void afs_osi_CancelWait(struct afs_osi_WaitHandle *handle) { afs_osi_Wakeup(handle); } /* * Netscape NSAPI doesn't have a cond_timed_wait, so we need * to explicitly signal cond_timed_waits when their timers expire */ int afs_osi_CheckTimedWaits(void) { time_t curTime; osi_wait_t *waitp; curTime = time(NULL); usr_mutex_lock(&osi_waitq_lock); waitp = osi_timedwait_head; while (waitp != NULL) { usr_assert(waitp->expiration != 0); if (waitp->expiration <= curTime) { waitp->flag = 1; usr_cond_signal(&waitp->cond); } waitp = waitp->timedNext; } usr_mutex_unlock(&osi_waitq_lock); return 0; } /* * 'dummy' vnode, for non-AFS files. We don't actually need most vnode * information for non-AFS files, so point all of them towards this vnode * to save memory. */ static struct usr_vnode dummy_vnode = { 0, /* v_flag */ 1024, /* v_count */ NULL, /* v_op */ NULL, /* v_vfsp */ 0, /* v_type */ 0, /* v_rdev */ NULL /* v_data */ }; /* * Allocate a slot in the file table if there is not one there already, * copy in the file name and kludge up the vnode and inode structures */ int lookupname(char *fnamep, int segflg, int followlink, struct usr_vnode **compvpp) { int code; /* * Assume relative pathnames refer to files in AFS */ if (*fnamep != '/' || uafs_afsPathName(fnamep) != NULL) { AFS_GLOCK(); code = uafs_LookupName(fnamep, afs_CurrentDir, compvpp, 0, 0); AFS_GUNLOCK(); return code; } /* For non-afs files, nobody really looks at the meaningful values in the * returned vnode, so we can return a 'fake' one. The vnode can be held, * released, etc. and some callers check for a NULL vnode anyway, so we * to return something. */ usr_mutex_lock(&osi_dummy_lock); VN_HOLD(&dummy_vnode); usr_mutex_unlock(&osi_dummy_lock); *compvpp = &dummy_vnode; return 0; } /* * open a file given its i-node number */ void * osi_UFSOpen(afs_dcache_id_t *ino) { int rc; struct osi_file *fp; struct stat st; AFS_ASSERT_GLOCK(); AFS_GUNLOCK(); fp = afs_osi_Alloc(sizeof(struct osi_file)); usr_assert(fp != NULL); usr_assert(ino->ufs); fp->fd = open(ino->ufs, O_RDWR | O_CREAT, 0); if (fp->fd < 0) { get_user_struct()->u_error = errno; afs_osi_Free((char *)fp, sizeof(struct osi_file)); AFS_GLOCK(); return NULL; } rc = fstat(fp->fd, &st); if (rc < 0) { get_user_struct()->u_error = errno; afs_osi_Free((void *)fp, sizeof(struct osi_file)); AFS_GLOCK(); return NULL; } fp->size = st.st_size; fp->offset = 0; fp->vnode = (struct usr_vnode *)fp; AFS_GLOCK(); return fp; } int osi_UFSClose(struct osi_file *fp) { int rc; AFS_ASSERT_GLOCK(); AFS_GUNLOCK(); rc = close(fp->fd); if (rc < 0) { get_user_struct()->u_error = errno; afs_osi_Free((void *)fp, sizeof(struct osi_file)); AFS_GLOCK(); return -1; } afs_osi_Free((void *)fp, sizeof(struct osi_file)); AFS_GLOCK(); return 0; } int osi_UFSTruncate(struct osi_file *fp, afs_int32 len) { int rc; AFS_ASSERT_GLOCK(); AFS_GUNLOCK(); rc = ftruncate(fp->fd, len); if (rc < 0) { get_user_struct()->u_error = errno; AFS_GLOCK(); return -1; } fp->size = len; AFS_GLOCK(); return 0; } int afs_osi_Read(struct osi_file *fp, int offset, void *buf, afs_int32 len) { int rc, ret; struct stat st; AFS_ASSERT_GLOCK(); AFS_GUNLOCK(); if (offset >= 0) { rc = lseek(fp->fd, offset, SEEK_SET); } else { rc = lseek(fp->fd, fp->offset, SEEK_SET); } if (rc < 0) { get_user_struct()->u_error = errno; AFS_GLOCK(); return -1; } fp->offset = rc; ret = read(fp->fd, buf, len); if (ret < 0) { get_user_struct()->u_error = errno; AFS_GLOCK(); return -1; } fp->offset += ret; rc = fstat(fp->fd, &st); if (rc < 0) { get_user_struct()->u_error = errno; AFS_GLOCK(); return -1; } fp->size = st.st_size; AFS_GLOCK(); return ret; } int afs_osi_Write(struct osi_file *fp, afs_int32 offset, void *buf, afs_int32 len) { int rc, ret; struct stat st; AFS_ASSERT_GLOCK(); AFS_GUNLOCK(); if (offset >= 0) { rc = lseek(fp->fd, offset, SEEK_SET); } else { rc = lseek(fp->fd, fp->offset, SEEK_SET); } if (rc < 0) { get_user_struct()->u_error = errno; AFS_GLOCK(); return -1; } fp->offset = rc; ret = write(fp->fd, buf, len); if (ret < 0) { get_user_struct()->u_error = errno; AFS_GLOCK(); return -1; } fp->offset += ret; rc = fstat(fp->fd, &st); if (rc < 0) { get_user_struct()->u_error = errno; AFS_GLOCK(); return -1; } fp->size = st.st_size; AFS_GLOCK(); return ret; } int afs_osi_Stat(struct osi_file *fp, struct osi_stat *stp) { int rc; struct stat st; AFS_GUNLOCK(); rc = fstat(fp->fd, &st); if (rc < 0) { get_user_struct()->u_error = errno; AFS_GLOCK(); return -1; } stp->size = st.st_size; stp->mtime = st.st_mtime; stp->atime = st.st_atime; AFS_GLOCK(); return 0; } /* * VOP_RDWR routine */ int afs_osi_VOP_RDWR(struct usr_vnode *vnodeP, struct usr_uio *uioP, int rw, int flags, struct usr_ucred *credP) { int rc; struct osi_file *fp = (struct osi_file *)vnodeP; /* * We don't support readv/writev. */ usr_assert(uioP->uio_iovcnt == 1); usr_assert(uioP->uio_resid == uioP->uio_iov[0].iov_len); if (rw == UIO_WRITE) { usr_assert(uioP->uio_fmode == FWRITE); rc = afs_osi_Write(fp, uioP->uio_offset, uioP->uio_iov[0].iov_base, uioP->uio_iov[0].iov_len); } else { usr_assert(uioP->uio_fmode == FREAD); rc = afs_osi_Read(fp, uioP->uio_offset, uioP->uio_iov[0].iov_base, uioP->uio_iov[0].iov_len); } if (rc < 0) { return get_user_struct()->u_error; } uioP->uio_resid -= rc; uioP->uio_offset += rc; uioP->uio_iov[0].iov_base = (char *)(uioP->uio_iov[0].iov_base) + rc; uioP->uio_iov[0].iov_len -= rc; return 0; } void * afs_osi_Alloc(size_t size) { return malloc(size); } void afs_osi_Free(void *ptr, size_t size) { free(ptr); } void afs_osi_FreeStr(char *ptr) { free(ptr); } void * osi_AllocLargeSpace(size_t size) { AFS_STATCNT(osi_AllocLargeSpace); return afs_osi_Alloc(size); } void osi_FreeLargeSpace(void *ptr) { AFS_STATCNT(osi_FreeLargeSpace); afs_osi_Free(ptr, 0); } void * osi_AllocSmallSpace(size_t size) { AFS_STATCNT(osi_AllocSmallSpace); return afs_osi_Alloc(size); } void osi_FreeSmallSpace(void *ptr) { AFS_STATCNT(osi_FreeSmallSpace); afs_osi_Free(ptr, 0); } void shutdown_osi(void) { AFS_STATCNT(shutdown_osi); return; } void shutdown_osinet(void) { AFS_STATCNT(shutdown_osinet); return; } void shutdown_osifile(void) { AFS_STATCNT(shutdown_osifile); return; } void afs_nfsclient_init(void) { } void shutdown_nfsclnt(void) { return; } void afs_osi_Invisible(void) { return; } void afs_osi_Visible(void) { return; } int osi_Active(struct vcache *avc) { AFS_STATCNT(osi_Active); if (avc->opens > 0) return (1); return 0; } int afs_osi_MapStrategy(int (*aproc) (struct usr_buf *), struct usr_buf *bp) { afs_int32 returnCode; returnCode = (*aproc) (bp); return returnCode; } void osi_FlushPages(struct vcache *avc, afs_ucred_t *credp) { ObtainSharedLock(&avc->lock, 555); if ((hcmp((avc->f.m.DataVersion), (avc->mapDV)) <= 0) || ((avc->execsOrWriters > 0) && afs_DirtyPages(avc))) { ReleaseSharedLock(&avc->lock); return; } UpgradeSToWLock(&avc->lock, 565); hset(avc->mapDV, avc->f.m.DataVersion); ReleaseWriteLock(&avc->lock); return; } void osi_FlushText_really(struct vcache *vp) { if (hcmp(vp->f.m.DataVersion, vp->flushDV) > 0) { hset(vp->flushDV, vp->f.m.DataVersion); } return; } int osi_SyncVM(struct vcache *avc) { return 0; } void osi_ReleaseVM(struct vcache *avc, int len, struct usr_ucred *credp) { return; } void osi_Init(void) { int i; int st; /* * Use the thread specific data to implement the user structure */ usr_keycreate(&afs_global_u_key, free); /* * Initialize the global ucred structure */ afs_global_ucredp = (struct usr_ucred *) afs_osi_Alloc(sizeof(struct usr_ucred)); usr_assert(afs_global_ucredp != NULL); afs_global_ucredp->cr_ref = 1; afs_set_cr_uid(afs_global_ucredp, geteuid()); afs_set_cr_gid(afs_global_ucredp, getegid()); afs_set_cr_ruid(afs_global_ucredp, getuid()); afs_set_cr_rgid(afs_global_ucredp, getgid()); afs_global_ucredp->cr_suid = afs_cr_ruid(afs_global_ucredp); afs_global_ucredp->cr_sgid = afs_cr_rgid(afs_global_ucredp); st = getgroups(NGROUPS, &afs_global_ucredp->cr_groups[0]); usr_assert(st >= 0); afs_global_ucredp->cr_ngroups = (unsigned long)st; for (i = st; i < NGROUPS; i++) { afs_global_ucredp->cr_groups[i] = NOGROUP; } /* * Initialize the global process structure */ afs_global_procp = (struct usr_proc *) afs_osi_Alloc(sizeof(struct usr_proc)); usr_assert(afs_global_procp != NULL); afs_global_procp->p_pid = osi_getpid(); afs_global_procp->p_ppid = (pid_t) 1; afs_global_procp->p_ucred = afs_global_ucredp; /* * Initialize the mutex and condition variable used to implement * time sleeps. */ pthread_mutex_init(&usr_sleep_mutex, NULL); pthread_cond_init(&usr_sleep_cond, NULL); /* * Initialize the hash table used for sleep/wakeup */ for (i = 0; i < OSI_WAITHASH_SIZE; i++) { DLL_INIT_LIST(osi_waithash_table[i].head, osi_waithash_table[i].tail); } DLL_INIT_LIST(osi_timedwait_head, osi_timedwait_tail); osi_waithash_avail = NULL; /* * Initialize the AFS file table */ for (i = 0; i < MAX_OSI_FILES; i++) { afs_FileTable[i] = NULL; } /* * Initialize the global locks */ usr_mutex_init(&afs_global_lock); usr_mutex_init(&rx_global_lock); usr_mutex_init(&osi_dummy_lock); usr_mutex_init(&osi_waitq_lock); usr_mutex_init(&osi_authenticate_lock); /* * Initialize the AFS OSI credentials */ afs_osi_cred = *afs_global_ucredp; afs_osi_credp = &afs_osi_cred; init_et_to_sys_error(); } /* * Set the UDP port number RX uses for UDP datagrams */ void uafs_SetRxPort(int port) { usr_assert(usr_rx_port == 0); usr_rx_port = port; } /* * uafs_Init is for backwards compatibility only! Do not use it; use * uafs_Setup, uafs_ParseArgs, and uafs_Run instead. */ void uafs_Init(char *rn, char *mountDirParam, char *confDirParam, char *cacheBaseDirParam, int cacheBlocksParam, int cacheFilesParam, int cacheStatEntriesParam, int dCacheSizeParam, int vCacheSizeParam, int chunkSizeParam, int closeSynchParam, int debugParam, int nDaemonsParam, int cacheFlagsParam, char *logFile) { int code; int argc = 0; char *argv[32]; int freeargc = 0; void *freeargv[32]; char buf[1024]; int i; code = uafs_Setup(mountDirParam); usr_assert(code == 0); argv[argc++] = rn; if (mountDirParam) { argv[argc++] = "-mountdir"; argv[argc++] = mountDirParam; } if (confDirParam) { argv[argc++] = "-confdir"; argv[argc++] = confDirParam; } if (cacheBaseDirParam) { argv[argc++] = "-cachedir"; argv[argc++] = cacheBaseDirParam; } if (cacheBlocksParam) { snprintf(buf, sizeof(buf), "%d", cacheBlocksParam); argv[argc++] = "-blocks"; argv[argc++] = freeargv[freeargc++] = strdup(buf); } if (cacheFilesParam) { snprintf(buf, sizeof(buf), "%d", cacheFilesParam); argv[argc++] = "-files"; argv[argc++] = freeargv[freeargc++] = strdup(buf); } if (cacheStatEntriesParam) { snprintf(buf, sizeof(buf), "%d", cacheStatEntriesParam); argv[argc++] = "-stat"; argv[argc++] = freeargv[freeargc++] = strdup(buf); } if (dCacheSizeParam) { snprintf(buf, sizeof(buf), "%d", dCacheSizeParam); argv[argc++] = "-dcache"; argv[argc++] = freeargv[freeargc++] = strdup(buf); } if (vCacheSizeParam) { snprintf(buf, sizeof(buf), "%d", vCacheSizeParam); argv[argc++] = "-volumes"; argv[argc++] = freeargv[freeargc++] = strdup(buf); } if (chunkSizeParam) { snprintf(buf, sizeof(buf), "%d", chunkSizeParam); argv[argc++] = "-chunksize"; argv[argc++] = freeargv[freeargc++] = strdup(buf); } if (closeSynchParam) { argv[argc++] = "-waitclose"; } if (debugParam) { argv[argc++] = "-debug"; } if (nDaemonsParam) { snprintf(buf, sizeof(buf), "%d", nDaemonsParam); argv[argc++] = "-daemons"; argv[argc++] = freeargv[freeargc++] = strdup(buf); } if (cacheFlagsParam) { if (cacheFlagsParam & AFSCALL_INIT_MEMCACHE) { argv[argc++] = "-memcache"; } } if (logFile) { argv[argc++] = "-logfile"; argv[argc++] = logFile; } argv[argc] = NULL; code = uafs_ParseArgs(argc, argv); usr_assert(code == 0); for (i = 0; i < freeargc; i++) { free(freeargv[i]); } code = uafs_Run(); usr_assert(code == 0); } /** * Calculate the cacheMountDir used for a specified dir. * * @param[in] dir Desired mount dir * @param[out] mountdir On success, contains the literal string that should * be used as the cache mount dir. * @param[in] size The number of bytes allocated in mountdir * * @post On success, mountdir begins with a slash, and does not contain two * slashes adjacent to each other * * @return operation status * @retval 0 success * @retval ENAMETOOLONG the specified dir is too long to fix in the given * mountdir buffer * @retval EINVAL the specified dir does not actually specify any meaningful * mount directory */ static int calcMountDir(const char *dir, char *mountdir, size_t size) { char buf[1024]; char lastchar; char *p; int len; if (dir && strlen(dir) > size-1) { return ENAMETOOLONG; } /* * Initialize the AFS mount point, default is '/afs'. * Strip duplicate/trailing slashes from mount point string. * afs_mountDirLen is set to strlen(afs_mountDir). */ if (!dir) { dir = "afs"; } sprintf(buf, "%s", dir); mountdir[0] = '/'; len = 1; for (lastchar = '/', p = &buf[0]; *p != '\0'; p++) { if (lastchar != '/' || *p != '/') { mountdir[len++] = lastchar = *p; } } if (lastchar == '/' && len > 1) len--; mountdir[len] = '\0'; if (len <= 1) { return EINVAL; } return 0; } void uafs_mount(void) { int rc; /* * Mount the AFS filesystem */ AFS_GLOCK(); rc = afs_mount(&afs_RootVfs, NULL, NULL); usr_assert(rc == 0); rc = afs_root(&afs_RootVfs, &afs_RootVnode); usr_assert(rc == 0); AFS_GUNLOCK(); /* * initialize the current directory to the AFS root */ afs_CurrentDir = afs_RootVnode; VN_HOLD(afs_CurrentDir); return; } void uafs_setMountDir(const char *dir) { if (dir) { int rc; char tmp_mountDir[1024]; rc = calcMountDir(dir, tmp_mountDir, sizeof(tmp_mountDir)); if (rc) { afs_warn("Invalid mount dir specification (error %d): %s\n", rc, dir); } else { if (strcmp(tmp_mountDir, afs_mountDir) != 0) { /* mount dir changed */ strcpy(afs_mountDir, tmp_mountDir); afs_mountDirLen = strlen(afs_mountDir); } } } } int uafs_statvfs(struct statvfs *buf) { int rc; AFS_GLOCK(); rc = afs_statvfs(&afs_RootVfs, buf); AFS_GUNLOCK(); if (rc) { errno = rc; return -1; } return 0; } void uafs_Shutdown(void) { int rc; printf("\n"); AFS_GLOCK(); if (afs_CurrentDir) { VN_RELE(afs_CurrentDir); } rc = afs_unmount(&afs_RootVfs); usr_assert(rc == 0); AFS_GUNLOCK(); printf("\n"); } /* * Donate the current thread to the RX server pool. */ void uafs_RxServerProc(void) { osi_socket sock; int threadID; struct rx_call *newcall = NULL; rxi_MorePackets(2); /* alloc more packets */ threadID = rxi_availProcs++; while (1) { sock = OSI_NULLSOCKET; rxi_ServerProc(threadID, newcall, &sock); if (sock == OSI_NULLSOCKET) { break; } newcall = NULL; threadID = -1; rxi_ListenerProc(sock, &threadID, &newcall); /* assert(threadID != -1); */ /* assert(newcall != NULL); */ } } struct syscallThreadArgs { long syscall; long afscall; long param1; long param2; long param3; long param4; }; void * syscallThread(void *argp) { int i; struct usr_ucred *crp; struct syscallThreadArgs *sysArgsP = (struct syscallThreadArgs *)argp; /* * AFS daemons run authenticated */ get_user_struct()->u_viceid = getuid(); crp = get_user_struct()->u_cred; afs_set_cr_uid(crp, getuid()); afs_set_cr_ruid(crp, getuid()); crp->cr_suid = getuid(); crp->cr_groups[0] = getgid(); crp->cr_ngroups = 1; for (i = 1; i < NGROUPS; i++) { crp->cr_groups[i] = NOGROUP; } call_syscall(sysArgsP->syscall, sysArgsP->afscall, sysArgsP->param1, sysArgsP->param2, sysArgsP->param3, sysArgsP->param4); afs_osi_Free(argp, -1); return 0; } int fork_syscall(long syscall, long afscall, long param1, long param2, long param3, long param4) { usr_thread_t tid; struct syscallThreadArgs *sysArgsP; sysArgsP = (struct syscallThreadArgs *) afs_osi_Alloc(sizeof(struct syscallThreadArgs)); usr_assert(sysArgsP != NULL); sysArgsP->syscall = syscall; sysArgsP->afscall = afscall; sysArgsP->param1 = param1; sysArgsP->param2 = param2; sysArgsP->param3 = param3; sysArgsP->param4 = param4; usr_thread_create(&tid, syscallThread, sysArgsP); usr_thread_detach(tid); return 0; } int call_syscall(long syscall, long afscall, long param1, long param2, long param3, long param4) { int code = 0; struct a { long syscall; long afscall; long parm1; long parm2; long parm3; long parm4; } a; a.syscall = syscall; a.afscall = afscall; a.parm1 = param1; a.parm2 = param2; a.parm3 = param3; a.parm4 = param4; get_user_struct()->u_error = 0; get_user_struct()->u_ap = (char *)&a; code = Afs_syscall(); return code; } int uafs_Setup(const char *mount) { int rc; static int inited = 0; if (inited) { return EEXIST; } inited = 1; rc = calcMountDir(mount, afs_mountDir, sizeof(afs_mountDir)); if (rc) { return rc; } afs_mountDirLen = strlen(afs_mountDir); /* initialize global vars and such */ osi_Init(); /* initialize cache manager foo */ afsd_init(); return 0; } int uafs_ParseArgs(int argc, char **argv) { return afsd_parse(argc, argv); } int uafs_Run(void) { return afsd_run(); } const char * uafs_MountDir(void) { return afsd_cacheMountDir; } int uafs_SetTokens(char *tbuffer, int tlen) { int rc; struct afs_ioctl iob; char outbuf[1024]; iob.in = tbuffer; iob.in_size = tlen; iob.out = &outbuf[0]; iob.out_size = sizeof(outbuf); rc = call_syscall(AFSCALL_PIOCTL, 0, _VICEIOCTL(3), (long)&iob, 0, 0); if (rc != 0) { errno = rc; return -1; } return 0; } int uafs_RPCStatsEnableProc(void) { int rc; struct afs_ioctl iob; afs_int32 flag; flag = AFSCALL_RXSTATS_ENABLE; iob.in = (char *)&flag; iob.in_size = sizeof(afs_int32); iob.out = NULL; iob.out_size = 0; rc = call_syscall(AFSCALL_PIOCTL, 0, _VICEIOCTL(53), (long)&iob, 0, 0); if (rc != 0) { errno = rc; return -1; } return rc; } int uafs_RPCStatsDisableProc(void) { int rc; struct afs_ioctl iob; afs_int32 flag; flag = AFSCALL_RXSTATS_DISABLE; iob.in = (char *)&flag; iob.in_size = sizeof(afs_int32); iob.out = NULL; iob.out_size = 0; rc = call_syscall(AFSCALL_PIOCTL, 0, _VICEIOCTL(53), (long)&iob, 0, 0); if (rc != 0) { errno = rc; return -1; } return rc; } int uafs_RPCStatsClearProc(void) { int rc; struct afs_ioctl iob; afs_int32 flag; flag = AFSCALL_RXSTATS_CLEAR; iob.in = (char *)&flag; iob.in_size = sizeof(afs_int32); iob.out = NULL; iob.out_size = 0; rc = call_syscall(AFSCALL_PIOCTL, 0, _VICEIOCTL(53), (long)&iob, 0, 0); if (rc != 0) { errno = rc; return -1; } return rc; } int uafs_RPCStatsEnablePeer(void) { int rc; struct afs_ioctl iob; afs_int32 flag; flag = AFSCALL_RXSTATS_ENABLE; iob.in = (char *)&flag; iob.in_size = sizeof(afs_int32); iob.out = NULL; iob.out_size = 0; rc = call_syscall(AFSCALL_PIOCTL, 0, _VICEIOCTL(54), (long)&iob, 0, 0); if (rc != 0) { errno = rc; return -1; } return rc; } int uafs_RPCStatsDisablePeer(void) { int rc; struct afs_ioctl iob; afs_int32 flag; flag = AFSCALL_RXSTATS_DISABLE; iob.in = (char *)&flag; iob.in_size = sizeof(afs_int32); iob.out = NULL; iob.out_size = 0; rc = call_syscall(AFSCALL_PIOCTL, 0, _VICEIOCTL(54), (long)&iob, 0, 0); if (rc != 0) { errno = rc; return -1; } return rc; } int uafs_RPCStatsClearPeer(void) { int rc; struct afs_ioctl iob; afs_int32 flag; flag = AFSCALL_RXSTATS_CLEAR; iob.in = (char *)&flag; iob.in_size = sizeof(afs_int32); iob.out = NULL; iob.out_size = 0; rc = call_syscall(AFSCALL_PIOCTL, 0, _VICEIOCTL(54), (long)&iob, 0, 0); if (rc != 0) { errno = rc; return -1; } return rc; } /* * Lookup the target of a symbolic link * Call VN_HOLD on the output vnode if successful. * Returns zero on success, error code on failure. * If provided, use a path for confirming we are not linked to ourself. * * Note: Caller must hold the AFS global lock. */ static int uafs_LookupLinkPath(struct usr_vnode *vp, struct usr_vnode *parentVp, char *ppathP, struct usr_vnode **vpp) { int code; int len; char *pathP; struct usr_vnode *linkVp; struct usr_uio uio; struct iovec iov[1]; AFS_ASSERT_GLOCK(); pathP = afs_osi_Alloc(MAX_OSI_PATH + 1); usr_assert(pathP != NULL); /* * set up the uio buffer */ iov[0].iov_base = pathP; iov[0].iov_len = MAX_OSI_PATH + 1; uio.uio_iov = &iov[0]; uio.uio_iovcnt = 1; uio.uio_offset = 0; uio.uio_segflg = 0; uio.uio_fmode = FREAD; uio.uio_resid = MAX_OSI_PATH + 1; /* * Read the link data */ code = afs_readlink(VTOAFS(vp), &uio, get_user_struct()->u_cred); if (code) { afs_osi_Free(pathP, MAX_OSI_PATH + 1); return code; } len = MAX_OSI_PATH + 1 - uio.uio_resid; pathP[len] = '\0'; /* are we linked to ourname or ./ourname? ELOOP */ if (ppathP) { if ((strcmp(pathP, ppathP) == 0) || ((pathP[0] == '.') && (pathP[1] == '/') && (strcmp(&(pathP[2]), ppathP) == 0))) { return ELOOP; } } /* * Find the target of the symbolic link */ code = uafs_LookupName(pathP, parentVp, &linkVp, 1, 0); if (code) { afs_osi_Free(pathP, MAX_OSI_PATH + 1); return code; } afs_osi_Free(pathP, MAX_OSI_PATH + 1); *vpp = linkVp; return 0; } /* * Lookup a file or directory given its path. * Call VN_HOLD on the output vnode if successful. * Returns zero on success, error code on failure. * * Note: Caller must hold the AFS global lock. */ int uafs_LookupName(char *path, struct usr_vnode *parentVp, struct usr_vnode **vpp, int follow, int no_eval_mtpt) { int code = 0; int linkCount; struct usr_vnode *vp; struct usr_vnode *nextVp; struct usr_vnode *linkVp; struct vcache *nextVc; char *tmpPath; char *pathP; char *nextPathP = NULL; AFS_ASSERT_GLOCK(); /* * Absolute paths must start with the AFS mount point. */ if (path[0] != '/') { vp = parentVp; } else { path = uafs_afsPathName(path); if (path == NULL) { return ENOENT; } vp = afs_RootVnode; } /* * Loop through the path looking for the new directory */ tmpPath = afs_osi_Alloc(strlen(path) + 1); usr_assert(tmpPath != NULL); strcpy(tmpPath, path); VN_HOLD(vp); pathP = tmpPath; while (pathP != NULL && *pathP != '\0') { usr_assert(*pathP != '/'); /* * terminate the current component and skip over slashes */ nextPathP = afs_strchr(pathP, '/'); if (nextPathP != NULL) { while (*nextPathP == '/') { *(nextPathP++) = '\0'; } } /* * Don't call afs_lookup on non-directories */ if (vp->v_type != VDIR) { VN_RELE(vp); afs_osi_Free(tmpPath, strlen(path) + 1); return ENOTDIR; } if (vp == afs_RootVnode && strcmp(pathP, "..") == 0) { /* * The AFS root is its own parent */ nextVp = afs_RootVnode; } else { /* * We need execute permission to search a directory */ code = afs_access(VTOAFS(vp), VEXEC, get_user_struct()->u_cred); if (code != 0) { VN_RELE(vp); afs_osi_Free(tmpPath, strlen(path) + 1); return code; } /* * lookup the next component in the path, we can release the * subdirectory since we hold the global lock */ nextVc = NULL; nextVp = NULL; if ((nextPathP != NULL && *nextPathP != '\0') || !no_eval_mtpt) code = afs_lookup(VTOAFS(vp), pathP, &nextVc, get_user_struct()->u_cred, 0); else code = afs_lookup(VTOAFS(vp), pathP, &nextVc, get_user_struct()->u_cred, AFS_LOOKUP_NOEVAL); if (nextVc) nextVp=AFSTOV(nextVc); if (code != 0) { VN_RELE(vp); afs_osi_Free(tmpPath, strlen(path) + 1); return code; } } /* * Follow symbolic links for parent directories and * for leaves when the follow flag is set. */ if ((nextPathP != NULL && *nextPathP != '\0') || follow) { linkCount = 0; while (nextVp->v_type == VLNK) { if (++linkCount > MAX_OSI_LINKS) { VN_RELE(vp); VN_RELE(nextVp); afs_osi_Free(tmpPath, strlen(path) + 1); return code; } code = uafs_LookupLinkPath(nextVp, vp, NULL, &linkVp); if (code) { VN_RELE(vp); VN_RELE(nextVp); afs_osi_Free(tmpPath, strlen(path) + 1); return code; } VN_RELE(nextVp); nextVp = linkVp; } } VN_RELE(vp); vp = nextVp; pathP = nextPathP; } /* * Special case, nextPathP is non-null if pathname ends in slash */ if (nextPathP != NULL && vp->v_type != VDIR) { VN_RELE(vp); afs_osi_Free(tmpPath, strlen(path) + 1); return ENOTDIR; } afs_osi_Free(tmpPath, strlen(path) + 1); *vpp = vp; return 0; } int uafs_LookupLink(struct usr_vnode *vp, struct usr_vnode *parentVp, struct usr_vnode **vpp) { return uafs_LookupLinkPath(vp, parentVp, NULL, vpp); } /* * Lookup the parent of a file or directory given its path * Call VN_HOLD on the output vnode if successful. * Returns zero on success, error code on failure. * * Note: Caller must hold the AFS global lock. */ int uafs_LookupParent(char *path, struct usr_vnode **vpp) { int len; int code; char *pathP; struct usr_vnode *parentP; AFS_ASSERT_GLOCK(); /* * Absolute path names must start with the AFS mount point. */ if (*path == '/') { pathP = uafs_afsPathName(path); if (pathP == NULL) { return ENOENT; } } /* * Find the length of the parent path */ len = strlen(path); while (len > 0 && path[len - 1] == '/') { len--; } if (len == 0) { return EINVAL; } while (len > 0 && path[len - 1] != '/') { len--; } if (len == 0) { return EINVAL; } pathP = afs_osi_Alloc(len); usr_assert(pathP != NULL); memcpy(pathP, path, len - 1); pathP[len - 1] = '\0'; /* * look up the parent */ code = uafs_LookupName(pathP, afs_CurrentDir, &parentP, 1, 0); afs_osi_Free(pathP, len); if (code != 0) { return code; } if (parentP->v_type != VDIR) { VN_RELE(parentP); return ENOTDIR; } *vpp = parentP; return 0; } /* * Return a pointer to the first character in the last component * of a pathname */ char * uafs_LastPath(char *path) { int len; len = strlen(path); while (len > 0 && path[len - 1] == '/') { len--; } while (len > 0 && path[len - 1] != '/') { len--; } if (len == 0) { return NULL; } return path + len; } /* * Set the working directory. */ int uafs_chdir(char *path) { int retval; AFS_GLOCK(); retval = uafs_chdir_r(path); AFS_GUNLOCK(); return retval; } int uafs_chdir_r(char *path) { int code; struct vnode *dirP; code = uafs_LookupName(path, afs_CurrentDir, &dirP, 1, 0); if (code != 0) { errno = code; return -1; } if (dirP->v_type != VDIR) { VN_RELE(dirP); errno = ENOTDIR; return -1; } VN_RELE(afs_CurrentDir); afs_CurrentDir = dirP; return 0; } /* * Create a directory. */ int uafs_mkdir(char *path, int mode) { int retval; AFS_GLOCK(); retval = uafs_mkdir_r(path, mode); AFS_GUNLOCK(); return retval; } int uafs_mkdir_r(char *path, int mode) { int code; char *nameP; struct vnode *parentP; struct vcache *dirP; struct usr_vattr attrs; if (uafs_IsRoot(path)) { return EACCES; } /* * Look up the parent directory. */ nameP = uafs_LastPath(path); if (nameP != NULL) { code = uafs_LookupParent(path, &parentP); if (code != 0) { errno = code; return -1; } } else { parentP = afs_CurrentDir; nameP = path; VN_HOLD(parentP); } /* * Make sure the directory has at least one character */ if (*nameP == '\0') { VN_RELE(parentP); errno = EINVAL; return -1; } /* * Create the directory */ usr_vattr_null(&attrs); attrs.va_type = VREG; attrs.va_mode = mode; attrs.va_uid = afs_cr_uid(get_user_struct()->u_cred); attrs.va_gid = afs_cr_gid(get_user_struct()->u_cred); dirP = NULL; code = afs_mkdir(VTOAFS(parentP), nameP, &attrs, &dirP, get_user_struct()->u_cred); VN_RELE(parentP); if (code != 0) { errno = code; return -1; } VN_RELE(AFSTOV(dirP)); return 0; } /* * Return 1 if path is the AFS root, otherwise return 0 */ int uafs_IsRoot(char *path) { while (*path == '/' && *(path + 1) == '/') { path++; } if (strncmp(path, afs_mountDir, afs_mountDirLen) != 0) { return 0; } path += afs_mountDirLen; while (*path == '/') { path++; } if (*path != '\0') { return 0; } return 1; } /* * Open a file * Note: file name may not end in a slash. */ int uafs_open(char *path, int flags, int mode) { int retval; AFS_GLOCK(); retval = uafs_open_r(path, flags, mode); AFS_GUNLOCK(); return retval; } int uafs_open_r(char *path, int flags, int mode) { int fd; int code; int openFlags; int fileMode; struct usr_vnode *fileP; struct usr_vnode *dirP; struct usr_vattr attrs; char *nameP; struct vcache* vc; if (uafs_IsRoot(path)) { fileP = afs_RootVnode; VN_HOLD(fileP); } else { /* * Look up the parent directory. */ nameP = uafs_LastPath(path); if (nameP != NULL) { code = uafs_LookupParent(path, &dirP); if (code != 0) { errno = code; return -1; } } else { dirP = afs_CurrentDir; nameP = path; VN_HOLD(dirP); } /* * Make sure the filename has at least one character */ if (*nameP == '\0') { VN_RELE(dirP); errno = EINVAL; return -1; } /* * Get the VNODE for this file */ if (flags & O_CREAT) { usr_vattr_null(&attrs); attrs.va_type = VREG; attrs.va_mode = mode; attrs.va_uid = afs_cr_uid(get_user_struct()->u_cred); attrs.va_gid = afs_cr_gid(get_user_struct()->u_cred); if (flags & O_TRUNC) { attrs.va_size = 0; } fileP = NULL; vc=VTOAFS(fileP); code = afs_create(VTOAFS(dirP), nameP, &attrs, (flags & O_EXCL) ? usr_EXCL : usr_NONEXCL, mode, &vc, get_user_struct()->u_cred); VN_RELE(dirP); if (code != 0) { errno = code; return -1; } fileP = AFSTOV(vc); } else { fileP = NULL; code = uafs_LookupName(nameP, dirP, &fileP, 1, 0); VN_RELE(dirP); if (code != 0) { errno = code; return -1; } /* * Check whether we have access to this file */ fileMode = 0; if (flags & (O_RDONLY | O_RDWR)) { fileMode |= VREAD; } if (flags & (O_WRONLY | O_RDWR)) { fileMode |= VWRITE; } if (!fileMode) fileMode = VREAD; /* since O_RDONLY is 0 */ code = afs_access(VTOAFS(fileP), fileMode, get_user_struct()->u_cred); if (code != 0) { VN_RELE(fileP); errno = code; return -1; } /* * Get the file attributes, all we need is the size */ code = afs_getattr(VTOAFS(fileP), &attrs, get_user_struct()->u_cred); if (code != 0) { VN_RELE(fileP); errno = code; return -1; } } } /* * Setup the open flags */ openFlags = 0; if (flags & O_TRUNC) { openFlags |= FTRUNC; } if (flags & O_APPEND) { openFlags |= FAPPEND; } if (flags & O_SYNC) { openFlags |= FSYNC; } if (flags & O_SYNC) { openFlags |= FSYNC; } if (flags & (O_RDONLY | O_RDWR)) { openFlags |= FREAD; } if (flags & (O_WRONLY | O_RDWR)) { openFlags |= FWRITE; } if ((openFlags & (FREAD | FWRITE)) == 0) { /* O_RDONLY is 0, so ... */ openFlags |= FREAD; } /* * Truncate if necessary */ if ((flags & O_TRUNC) && (attrs.va_size != 0)) { usr_vattr_null(&attrs); attrs.va_mask = ATTR_SIZE; attrs.va_size = 0; code = afs_setattr(VTOAFS(fileP), &attrs, get_user_struct()->u_cred); if (code != 0) { VN_RELE(fileP); errno = code; return -1; } } vc=VTOAFS(fileP); /* * do the open */ code = afs_open(&vc, openFlags, get_user_struct()->u_cred); if (code != 0) { VN_RELE(fileP); errno = code; return -1; } /* * Put the vnode pointer into the file table */ for (fd = 0; fd < MAX_OSI_FILES; fd++) { if (afs_FileTable[fd] == NULL) { afs_FileTable[fd] = fileP; afs_FileFlags[fd] = openFlags; if (flags & O_APPEND) { afs_FileOffsets[fd] = attrs.va_size; } else { afs_FileOffsets[fd] = 0; } break; } } if (fd == MAX_OSI_FILES) { VN_RELE(fileP); errno = ENFILE; return -1; } return fd; } /* * Create a file */ int uafs_creat(char *path, int mode) { int rc; rc = uafs_open(path, O_CREAT | O_WRONLY | O_TRUNC, mode); return rc; } int uafs_creat_r(char *path, int mode) { int rc; rc = uafs_open_r(path, O_CREAT | O_WRONLY | O_TRUNC, mode); return rc; } /* * Write to a file */ int uafs_write(int fd, char *buf, int len) { int retval; AFS_GLOCK(); retval = uafs_pwrite_r(fd, buf, len, afs_FileOffsets[fd]); AFS_GUNLOCK(); return retval; } int uafs_pwrite(int fd, char *buf, int len, off_t offset) { int retval; AFS_GLOCK(); retval = uafs_pwrite_r(fd, buf, len, offset); AFS_GUNLOCK(); return retval; } int uafs_pwrite_r(int fd, char *buf, int len, off_t offset) { int code; struct usr_uio uio; struct iovec iov[1]; struct usr_vnode *fileP; /* * Make sure this is an open file */ fileP = afs_FileTable[fd]; if (fileP == NULL) { errno = EBADF; return -1; } /* * set up the uio buffer */ iov[0].iov_base = buf; iov[0].iov_len = len; uio.uio_iov = &iov[0]; uio.uio_iovcnt = 1; uio.uio_offset = offset; uio.uio_segflg = 0; uio.uio_fmode = FWRITE; uio.uio_resid = len; /* * do the write */ code = afs_write(VTOAFS(fileP), &uio, afs_FileFlags[fd], get_user_struct()->u_cred, 0); if (code) { errno = code; return -1; } afs_FileOffsets[fd] = uio.uio_offset; return (len - uio.uio_resid); } /* * Read from a file */ int uafs_read(int fd, char *buf, int len) { int retval; AFS_GLOCK(); retval = uafs_pread_r(fd, buf, len, afs_FileOffsets[fd]); AFS_GUNLOCK(); return retval; } int uafs_pread_nocache(int fd, char *buf, int len, off_t offset) { int retval; AFS_GLOCK(); retval = uafs_pread_nocache_r(fd, buf, len, offset); AFS_GUNLOCK(); return retval; } int uafs_pread_nocache_r(int fd, char *buf, int len, off_t offset) { int code; struct iovec iov[1]; struct usr_vnode *fileP; struct nocache_read_request *bparms; struct usr_uio uio; /* * Make sure this is an open file */ fileP = afs_FileTable[fd]; if (fileP == NULL) { errno = EBADF; return -1; } /* these get freed in PrefetchNoCache, so... */ bparms = afs_osi_Alloc(sizeof(struct nocache_read_request)); code = afs_CreateReq(&bparms->areq, get_user_struct()->u_cred); if (code) { afs_DestroyReq(bparms->areq); afs_osi_Free(bparms, sizeof(struct nocache_read_request)); errno = code; return -1; } bparms->auio = &uio; bparms->offset = offset; bparms->length = len; /* * set up the uio buffer */ iov[0].iov_base = buf; iov[0].iov_len = len; uio.uio_iov = &iov[0]; uio.uio_iovcnt = 1; uio.uio_offset = offset; uio.uio_segflg = 0; uio.uio_fmode = FREAD; uio.uio_resid = len; /* * do the read */ code = afs_PrefetchNoCache(VTOAFS(fileP), get_user_struct()->u_cred, bparms); if (code) { errno = code; return -1; } afs_FileOffsets[fd] = uio.uio_offset; return (len - uio.uio_resid); } int uafs_pread(int fd, char *buf, int len, off_t offset) { int retval; AFS_GLOCK(); retval = uafs_pread_r(fd, buf, len, offset); AFS_GUNLOCK(); return retval; } int uafs_pread_r(int fd, char *buf, int len, off_t offset) { int code; struct usr_uio uio; struct iovec iov[1]; struct usr_vnode *fileP; /* * Make sure this is an open file */ fileP = afs_FileTable[fd]; if (fileP == NULL) { errno = EBADF; return -1; } /* * set up the uio buffer */ iov[0].iov_base = buf; iov[0].iov_len = len; uio.uio_iov = &iov[0]; uio.uio_iovcnt = 1; uio.uio_offset = offset; uio.uio_segflg = 0; uio.uio_fmode = FREAD; uio.uio_resid = len; /* * do the read */ code = afs_read(VTOAFS(fileP), &uio, get_user_struct()->u_cred, 0); if (code) { errno = code; return -1; } afs_FileOffsets[fd] = uio.uio_offset; return (len - uio.uio_resid); } /* * Copy the attributes of a file into a stat structure. * * NOTE: Caller must hold the global AFS lock. */ int uafs_GetAttr(struct usr_vnode *vp, struct stat *stats) { int code; struct usr_vattr attrs; AFS_ASSERT_GLOCK(); /* * Get the attributes */ code = afs_getattr(VTOAFS(vp), &attrs, get_user_struct()->u_cred); if (code != 0) { return code; } /* * Copy the attributes, zero fields that aren't set */ memset((void *)stats, 0, sizeof(struct stat)); stats->st_dev = -1; stats->st_ino = attrs.va_nodeid; stats->st_mode = attrs.va_mode; stats->st_nlink = attrs.va_nlink; stats->st_uid = attrs.va_uid; stats->st_gid = attrs.va_gid; stats->st_rdev = attrs.va_rdev; stats->st_size = attrs.va_size; stats->st_atime = attrs.va_atime.tv_sec; stats->st_mtime = attrs.va_mtime.tv_sec; stats->st_ctime = attrs.va_ctime.tv_sec; /* preserve dv if possible */ #if defined(HAVE_STRUCT_STAT_ST_CTIMESPEC) stats->st_atimespec.tv_nsec = attrs.va_atime.tv_usec * 1000; stats->st_mtimespec.tv_nsec = attrs.va_mtime.tv_usec * 1000; stats->st_ctimespec.tv_nsec = attrs.va_ctime.tv_usec * 1000; #elif defined(HAVE_STRUCT_STAT_ST_CTIMENSEC) stats->st_atimensec = attrs.va_atime.tv_usec * 1000; stats->st_mtimensec = attrs.va_mtime.tv_usec * 1000; stats->st_ctimensec = attrs.va_ctime.tv_usec * 1000; #endif stats->st_blksize = attrs.va_blocksize; stats->st_blocks = attrs.va_blocks; return 0; } /* * Get the attributes of a file, do follow links */ int uafs_stat(char *path, struct stat *buf) { int retval; AFS_GLOCK(); retval = uafs_stat_r(path, buf); AFS_GUNLOCK(); return retval; } int uafs_stat_r(char *path, struct stat *buf) { int code; struct vnode *vp; code = uafs_LookupName(path, afs_CurrentDir, &vp, 1, 0); if (code != 0) { errno = code; return -1; } code = uafs_GetAttr(vp, buf); VN_RELE(vp); if (code) { errno = code; return -1; } return 0; } /* * Get the attributes of a file, don't follow links */ int uafs_lstat(char *path, struct stat *buf) { int retval; AFS_GLOCK(); retval = uafs_lstat_r(path, buf); AFS_GUNLOCK(); return retval; } int uafs_lstat_r(char *path, struct stat *buf) { int code; struct vnode *vp; code = uafs_LookupName(path, afs_CurrentDir, &vp, 0, 0); if (code != 0) { errno = code; return -1; } code = uafs_GetAttr(vp, buf); VN_RELE(vp); if (code) { errno = code; return -1; } return 0; } /* * Get the attributes of an open file */ int uafs_fstat(int fd, struct stat *buf) { int retval; AFS_GLOCK(); retval = uafs_fstat_r(fd, buf); AFS_GUNLOCK(); return retval; } int uafs_fstat_r(int fd, struct stat *buf) { int code; struct vnode *vp; vp = afs_FileTable[fd]; if (vp == NULL) { errno = EBADF; return -1; } code = uafs_GetAttr(vp, buf); if (code) { errno = code; return -1; } return 0; } /* * change the permissions on a file */ int uafs_chmod(char *path, int mode) { int retval; AFS_GLOCK(); retval = uafs_chmod_r(path, mode); AFS_GUNLOCK(); return retval; } int uafs_chmod_r(char *path, int mode) { int code; struct vnode *vp; struct usr_vattr attrs; code = uafs_LookupName(path, afs_CurrentDir, &vp, 1, 0); if (code != 0) { errno = code; return -1; } usr_vattr_null(&attrs); attrs.va_mask = ATTR_MODE; attrs.va_mode = mode; code = afs_setattr(VTOAFS(vp), &attrs, get_user_struct()->u_cred); VN_RELE(vp); if (code != 0) { errno = code; return -1; } return 0; } /* * change the permissions on an open file */ int uafs_fchmod(int fd, int mode) { int retval; AFS_GLOCK(); retval = uafs_fchmod_r(fd, mode); AFS_GUNLOCK(); return retval; } int uafs_fchmod_r(int fd, int mode) { int code; struct vnode *vp; struct usr_vattr attrs; vp = afs_FileTable[fd]; if (vp == NULL) { errno = EBADF; return -1; } usr_vattr_null(&attrs); attrs.va_mask = ATTR_MODE; attrs.va_mode = mode; code = afs_setattr(VTOAFS(vp), &attrs, get_user_struct()->u_cred); if (code != 0) { errno = code; return -1; } return 0; } /* * truncate a file */ int uafs_truncate(char *path, int length) { int retval; AFS_GLOCK(); retval = uafs_truncate_r(path, length); AFS_GUNLOCK(); return retval; } int uafs_truncate_r(char *path, int length) { int code; struct vnode *vp; struct usr_vattr attrs; code = uafs_LookupName(path, afs_CurrentDir, &vp, 1, 0); if (code != 0) { errno = code; return -1; } usr_vattr_null(&attrs); attrs.va_mask = ATTR_SIZE; attrs.va_size = length; code = afs_setattr(VTOAFS(vp), &attrs, get_user_struct()->u_cred); VN_RELE(vp); if (code != 0) { errno = code; return -1; } return 0; } /* * truncate an open file */ int uafs_ftruncate(int fd, int length) { int retval; AFS_GLOCK(); retval = uafs_ftruncate_r(fd, length); AFS_GUNLOCK(); return retval; } int uafs_ftruncate_r(int fd, int length) { int code; struct vnode *vp; struct usr_vattr attrs; vp = afs_FileTable[fd]; if (vp == NULL) { errno = EBADF; return -1; } usr_vattr_null(&attrs); attrs.va_mask = ATTR_SIZE; attrs.va_size = length; code = afs_setattr(VTOAFS(vp), &attrs, get_user_struct()->u_cred); if (code != 0) { errno = code; return -1; } return 0; } /* * set the read/write file pointer of an open file */ int uafs_lseek(int fd, int offset, int whence) { int retval; AFS_GLOCK(); retval = uafs_lseek_r(fd, offset, whence); AFS_GUNLOCK(); return retval; } int uafs_lseek_r(int fd, int offset, int whence) { int code; int newpos; struct usr_vattr attrs; struct usr_vnode *vp; vp = afs_FileTable[fd]; if (vp == NULL) { errno = EBADF; return -1; } switch (whence) { case SEEK_CUR: newpos = afs_FileOffsets[fd] + offset; break; case SEEK_SET: newpos = offset; break; case SEEK_END: code = afs_getattr(VTOAFS(vp), &attrs, get_user_struct()->u_cred); if (code != 0) { errno = code; return -1; } newpos = attrs.va_size + offset; break; default: errno = EINVAL; return -1; } if (newpos < 0) { errno = EINVAL; return -1; } afs_FileOffsets[fd] = newpos; return newpos; } /* * sync a file */ int uafs_fsync(int fd) { int retval; AFS_GLOCK(); retval = uafs_fsync_r(fd); AFS_GUNLOCK(); return retval; } int uafs_fsync_r(int fd) { int code; struct usr_vnode *fileP; fileP = afs_FileTable[fd]; if (fileP == NULL) { errno = EBADF; return -1; } code = afs_fsync(VTOAFS(fileP), get_user_struct()->u_cred); if (code != 0) { errno = code; return -1; } return 0; } /* * Close a file */ int uafs_close(int fd) { int retval; AFS_GLOCK(); retval = uafs_close_r(fd); AFS_GUNLOCK(); return retval; } int uafs_close_r(int fd) { int code; struct usr_vnode *fileP; fileP = afs_FileTable[fd]; if (fileP == NULL) { errno = EBADF; return -1; } afs_FileTable[fd] = NULL; code = afs_close(VTOAFS(fileP), afs_FileFlags[fd], get_user_struct()->u_cred); VN_RELE(fileP); if (code != 0) { errno = code; return -1; } return 0; } /* * Create a hard link from the source to the target * Note: file names may not end in a slash. */ int uafs_link(char *existing, char *new) { int retval; AFS_GLOCK(); retval = uafs_link_r(existing, new); AFS_GUNLOCK(); return retval; } int uafs_link_r(char *existing, char *new) { int code; struct usr_vnode *existP; struct usr_vnode *dirP; char *nameP; if (uafs_IsRoot(new)) { return EACCES; } /* * Look up the existing node. */ code = uafs_LookupName(existing, afs_CurrentDir, &existP, 1, 0); if (code != 0) { errno = code; return -1; } /* * Look up the parent directory. */ nameP = uafs_LastPath(new); if (nameP != NULL) { code = uafs_LookupParent(new, &dirP); if (code != 0) { VN_RELE(existP); errno = code; return -1; } } else { dirP = afs_CurrentDir; nameP = new; VN_HOLD(dirP); } /* * Make sure the filename has at least one character */ if (*nameP == '\0') { VN_RELE(existP); VN_RELE(dirP); errno = EINVAL; return -1; } /* * Create the link */ code = afs_link(VTOAFS(existP), VTOAFS(dirP), nameP, get_user_struct()->u_cred); VN_RELE(existP); VN_RELE(dirP); if (code != 0) { errno = code; return -1; } return 0; } /* * Create a symbolic link from the source to the target * Note: file names may not end in a slash. */ int uafs_symlink(char *target, char *source) { int retval; AFS_GLOCK(); retval = uafs_symlink_r(target, source); AFS_GUNLOCK(); return retval; } int uafs_symlink_r(char *target, char *source) { int code; struct usr_vnode *dirP; struct usr_vattr attrs; char *nameP; if (uafs_IsRoot(source)) { return EACCES; } /* * Look up the parent directory. */ nameP = uafs_LastPath(source); if (nameP != NULL) { code = uafs_LookupParent(source, &dirP); if (code != 0) { errno = code; return -1; } } else { dirP = afs_CurrentDir; nameP = source; VN_HOLD(dirP); } /* * Make sure the filename has at least one character */ if (*nameP == '\0') { VN_RELE(dirP); errno = EINVAL; return -1; } /* * Create the link */ usr_vattr_null(&attrs); attrs.va_type = VLNK; attrs.va_mode = 0777; attrs.va_uid = afs_cr_uid(get_user_struct()->u_cred); attrs.va_gid = afs_cr_gid(get_user_struct()->u_cred); code = afs_symlink(VTOAFS(dirP), nameP, &attrs, target, NULL, get_user_struct()->u_cred); VN_RELE(dirP); if (code != 0) { errno = code; return -1; } return 0; } /* * Read a symbolic link into the buffer */ int uafs_readlink(char *path, char *buf, int len) { int retval; AFS_GLOCK(); retval = uafs_readlink_r(path, buf, len); AFS_GUNLOCK(); return retval; } int uafs_readlink_r(char *path, char *buf, int len) { int code; struct usr_vnode *vp; struct usr_uio uio; struct iovec iov[1]; code = uafs_LookupName(path, afs_CurrentDir, &vp, 0, 0); if (code != 0) { errno = code; return -1; } if (vp->v_type != VLNK) { VN_RELE(vp); errno = EINVAL; return -1; } /* * set up the uio buffer */ iov[0].iov_base = buf; iov[0].iov_len = len; uio.uio_iov = &iov[0]; uio.uio_iovcnt = 1; uio.uio_offset = 0; uio.uio_segflg = 0; uio.uio_fmode = FREAD; uio.uio_resid = len; /* * Read the the link */ code = afs_readlink(VTOAFS(vp), &uio, get_user_struct()->u_cred); VN_RELE(vp); if (code) { errno = code; return -1; } /* * return the number of bytes read */ return (len - uio.uio_resid); } /* * Remove a file (or directory) * Note: file name may not end in a slash. */ int uafs_unlink(char *path) { int retval; AFS_GLOCK(); retval = uafs_unlink_r(path); AFS_GUNLOCK(); return retval; } int uafs_unlink_r(char *path) { int code; struct usr_vnode *dirP; char *nameP; if (uafs_IsRoot(path)) { return EACCES; } /* * Look up the parent directory. */ nameP = uafs_LastPath(path); if (nameP != NULL) { code = uafs_LookupParent(path, &dirP); if (code != 0) { errno = code; return -1; } } else { dirP = afs_CurrentDir; nameP = path; VN_HOLD(dirP); } /* * Make sure the filename has at least one character */ if (*nameP == '\0') { VN_RELE(dirP); errno = EINVAL; return -1; } /* * Remove the file */ code = afs_remove(VTOAFS(dirP), nameP, get_user_struct()->u_cred); VN_RELE(dirP); if (code != 0) { errno = code; return -1; } return 0; } /* * Rename a file (or directory) */ int uafs_rename(char *old, char *new) { int retval; AFS_GLOCK(); retval = uafs_rename_r(old, new); AFS_GUNLOCK(); return retval; } int uafs_rename_r(char *old, char *new) { int code; char *onameP; char *nnameP; struct usr_vnode *odirP; struct usr_vnode *ndirP; if (uafs_IsRoot(new)) { return EACCES; } /* * Look up the parent directories. */ onameP = uafs_LastPath(old); if (onameP != NULL) { code = uafs_LookupParent(old, &odirP); if (code != 0) { errno = code; return -1; } } else { odirP = afs_CurrentDir; onameP = old; VN_HOLD(odirP); } nnameP = uafs_LastPath(new); if (nnameP != NULL) { code = uafs_LookupParent(new, &ndirP); if (code != 0) { errno = code; return -1; } } else { ndirP = afs_CurrentDir; nnameP = new; VN_HOLD(ndirP); } /* * Make sure the filename has at least one character */ if (*onameP == '\0' || *nnameP == '\0') { VN_RELE(odirP); VN_RELE(ndirP); errno = EINVAL; return -1; } /* * Rename the file */ code = afs_rename(VTOAFS(odirP), onameP, VTOAFS(ndirP), nnameP, get_user_struct()->u_cred); VN_RELE(odirP); VN_RELE(ndirP); if (code != 0) { errno = code; return -1; } return 0; } /* * Remove a or directory * Note: file name may not end in a slash. */ int uafs_rmdir(char *path) { int retval; AFS_GLOCK(); retval = uafs_rmdir_r(path); AFS_GUNLOCK(); return retval; } int uafs_rmdir_r(char *path) { int code; struct usr_vnode *dirP; char *nameP; if (uafs_IsRoot(path)) { return EACCES; } /* * Look up the parent directory. */ nameP = uafs_LastPath(path); if (nameP != NULL) { code = uafs_LookupParent(path, &dirP); if (code != 0) { errno = code; return -1; } } else { dirP = afs_CurrentDir; nameP = path; VN_HOLD(dirP); } /* * Make sure the directory name has at least one character */ if (*nameP == '\0') { VN_RELE(dirP); errno = EINVAL; return -1; } /* * Remove the directory */ code = afs_rmdir(VTOAFS(dirP), nameP, get_user_struct()->u_cred); VN_RELE(dirP); if (code != 0) { errno = code; return -1; } return 0; } /* * Flush a file from the AFS cache */ int uafs_FlushFile(char *path) { int code; struct afs_ioctl iob; iob.in = NULL; iob.in_size = 0; iob.out = NULL; iob.out_size = 0; code = call_syscall(AFSCALL_PIOCTL, (long)path, _VICEIOCTL(6), (long)&iob, 0, 0); if (code != 0) { errno = code; return -1; } return 0; } int uafs_FlushFile_r(char *path) { int retval; AFS_GUNLOCK(); retval = uafs_FlushFile(path); AFS_GLOCK(); return retval; } /* * open a directory */ usr_DIR * uafs_opendir(char *path) { usr_DIR *retval; AFS_GLOCK(); retval = uafs_opendir_r(path); AFS_GUNLOCK(); return retval; } usr_DIR * uafs_opendir_r(char *path) { usr_DIR *dirp; struct usr_vnode *fileP; int fd; /* * Open the directory for reading */ fd = uafs_open_r(path, O_RDONLY, 0); if (fd < 0) { return NULL; } fileP = afs_FileTable[fd]; if (fileP == NULL) { return NULL; } if (fileP->v_type != VDIR) { uafs_close_r(fd); errno = ENOTDIR; return NULL; } /* * Set up the directory structures */ dirp = afs_osi_Alloc(sizeof(usr_DIR) + USR_DIRSIZE + sizeof(struct usr_dirent)); usr_assert(dirp != NULL); dirp->dd_buf = (char *)(dirp + 1); dirp->dd_fd = fd; dirp->dd_loc = 0; dirp->dd_size = 0; errno = 0; return dirp; } /* * Read directory entries into a file system independent format. * This routine was developed to support AFS cache consistency testing. * You should use uafs_readdir instead. */ int uafs_getdents(int fd, struct min_direct *buf, int len) { int retval; AFS_GLOCK(); retval = uafs_getdents_r(fd, buf, len); AFS_GUNLOCK(); return retval; } int uafs_getdents_r(int fd, struct min_direct *buf, int len) { int code; struct usr_uio uio; struct usr_vnode *vp; struct iovec iov[1]; /* * Make sure this is an open file */ vp = afs_FileTable[fd]; if (vp == NULL) { AFS_GUNLOCK(); errno = EBADF; return -1; } /* * set up the uio buffer */ iov[0].iov_base = (char *)buf; iov[0].iov_len = len; uio.uio_iov = &iov[0]; uio.uio_iovcnt = 1; uio.uio_offset = afs_FileOffsets[fd]; uio.uio_segflg = 0; uio.uio_fmode = FREAD; uio.uio_resid = len; /* * read the next chunk from the directory */ code = afs_readdir(VTOAFS(vp), &uio, get_user_struct()->u_cred); if (code != 0) { errno = code; return -1; } afs_FileOffsets[fd] = uio.uio_offset; return (len - uio.uio_resid); } /* * read from a directory (names only) */ struct usr_dirent * uafs_readdir(usr_DIR * dirp) { struct usr_dirent *retval; AFS_GLOCK(); retval = uafs_readdir_r(dirp); AFS_GUNLOCK(); return retval; } struct usr_dirent * uafs_readdir_r(usr_DIR * dirp) { int code; int len; struct usr_uio uio; struct usr_vnode *vp; struct iovec iov[1]; struct usr_dirent *direntP; struct min_direct *directP; if (!dirp) { errno = EBADF; return NULL; } /* * Make sure this is an open file */ vp = afs_FileTable[dirp->dd_fd]; if (vp == NULL) { errno = EBADF; return NULL; } /* * If there are no entries in the stream buffer * then read another chunk */ directP = (struct min_direct *)(dirp->dd_buf + dirp->dd_loc); if (dirp->dd_size == 0 || directP->d_fileno == 0) { /* * set up the uio buffer */ iov[0].iov_base = dirp->dd_buf; iov[0].iov_len = USR_DIRSIZE; uio.uio_iov = &iov[0]; uio.uio_iovcnt = 1; uio.uio_offset = afs_FileOffsets[dirp->dd_fd]; uio.uio_segflg = 0; uio.uio_fmode = FREAD; uio.uio_resid = USR_DIRSIZE; /* * read the next chunk from the directory */ code = afs_readdir(VTOAFS(vp), &uio, get_user_struct()->u_cred); if (code != 0) { errno = code; return NULL; } afs_FileOffsets[dirp->dd_fd] = uio.uio_offset; dirp->dd_size = USR_DIRSIZE - iov[0].iov_len; dirp->dd_loc = 0; directP = (struct min_direct *)(dirp->dd_buf + dirp->dd_loc); } /* * Check for end of file */ if (dirp->dd_size == 0 || directP->d_fileno == 0) { errno = 0; return NULL; } len = ((sizeof(struct min_direct) + directP->d_namlen + 4) & (~3)); usr_assert(len <= dirp->dd_size); /* * Copy the next entry into the usr_dirent structure and advance */ direntP = (struct usr_dirent *)(dirp->dd_buf + USR_DIRSIZE); direntP->d_ino = directP->d_fileno; direntP->d_off = direntP->d_reclen; direntP->d_reclen = sizeof(struct usr_dirent) - MAXNAMLEN + directP->d_namlen + 1; memcpy(&direntP->d_name[0], (void *)(directP + 1), directP->d_namlen); direntP->d_name[directP->d_namlen] = '\0'; dirp->dd_loc += len; dirp->dd_size -= len; return direntP; } /* * Close a directory */ int uafs_closedir(usr_DIR * dirp) { int retval; AFS_GLOCK(); retval = uafs_closedir_r(dirp); AFS_GUNLOCK(); return retval; } int uafs_closedir_r(usr_DIR * dirp) { int fd; int rc; if (!dirp) { errno = EBADF; return -1; } fd = dirp->dd_fd; afs_osi_Free((char *)dirp, sizeof(usr_DIR) + USR_DIRSIZE + sizeof(struct usr_dirent)); rc = uafs_close_r(fd); return rc; } /* * Destroy AFS credentials from the kernel cache */ int uafs_unlog(void) { int code; usr_mutex_lock(&osi_authenticate_lock); code = ktc_ForgetAllTokens(); usr_mutex_unlock(&osi_authenticate_lock); return code; } int uafs_unlog_r(void) { int retval; AFS_GUNLOCK(); retval = uafs_unlog(); AFS_GLOCK(); return retval; } /* * Strip the AFS mount point from a pathname string. Return * NULL if the path is a relative pathname or if the path * doesn't start with the AFS mount point string. */ char * uafs_afsPathName(char *path) { char *p; char lastchar; int i; if (path[0] != '/') return NULL; lastchar = '/'; for (i = 1, p = path + 1; *p != '\0'; p++) { /* Ignore duplicate slashes */ if (*p == '/' && lastchar == '/') continue; /* Is this a subdirectory of the AFS mount point? */ if (afs_mountDir[i] == '\0' && *p == '/') { /* strip leading slashes */ while (*(++p) == '/'); return p; } /* Reject paths that are not within AFS */ if (*p != afs_mountDir[i]) return NULL; lastchar = *p; i++; } /* Is this the AFS mount point? */ if (afs_mountDir[i] == '\0') { usr_assert(*p == '\0'); return p; } return NULL; } /* * uafs_getcellstatus * get the cell status */ int uafs_getcellstatus(char *cell, afs_int32 * status) { int rc; struct afs_ioctl iob; iob.in = cell; iob.in_size = strlen(cell) + 1; iob.out = 0; iob.out_size = 0; rc = call_syscall(AFSCALL_PIOCTL, /*path */ 0, _VICEIOCTL(35), (long)&iob, 0, 0); if (rc < 0) { errno = rc; return -1; } *status = (intptr_t)iob.out; return 0; } /* * uafs_getvolquota * Get quota of volume associated with path */ int uafs_getvolquota(char *path, afs_int32 * BlocksInUse, afs_int32 * MaxQuota) { int rc; struct afs_ioctl iob; VolumeStatus status; iob.in = 0; iob.in_size = 0; iob.out = (char *)&status; iob.out_size = sizeof status; rc = call_syscall(AFSCALL_PIOCTL, (long)path, _VICEIOCTL(4), (long)&iob, 0, 0); if (rc != 0) { errno = rc; return -1; } *BlocksInUse = status.BlocksInUse; *MaxQuota = status.MaxQuota; return 0; } /* * uafs_setvolquota * Set quota of volume associated with path */ int uafs_setvolquota(char *path, afs_int32 MaxQuota) { int rc; struct afs_ioctl iob; VolumeStatus status = { 0 }; iob.in = (char *)&status; iob.in_size = sizeof status; iob.out = 0; iob.out_size = 0; status.MaxQuota = MaxQuota; status.MinQuota = -1; rc = call_syscall(AFSCALL_PIOCTL, (long)path, _VICEIOCTL(5), (long)&iob, 0, 0); if (rc != 0) { errno = rc; return -1; } return 0; } /* * uafs_statmountpoint * Determine whether a dir. is a mount point or not * return 1 if mount point, 0 if not */ int uafs_statmountpoint(char *path) { int retval; AFS_GLOCK(); retval = uafs_statmountpoint_r(path); AFS_GUNLOCK(); return retval; } int uafs_statmountpoint_r(char *path) { int code; struct vnode *vp; struct vcache *avc; int r; code = uafs_LookupName(path, afs_CurrentDir, &vp, 0, 1); if (code != 0) { errno = code; return -1; } avc = VTOAFS(vp); r = avc->mvstat; VN_RELE(vp); return r; } /* * uafs_getRights * Get a list of rights for the current user on path. */ int uafs_access(char *path, int flags) { int code; struct vnode *vp; int fileMode = 0; if (flags & R_OK) { fileMode |= VREAD; } if (flags & W_OK) { fileMode |= VWRITE; } if (flags & X_OK) { fileMode |= VEXEC; } AFS_GLOCK(); code = uafs_LookupName(path, afs_CurrentDir, &vp, 1, 0); if (code != 0) { errno = code; AFS_GUNLOCK(); return -1; } code = afs_access(VTOAFS(vp), fileMode, get_user_struct()->u_cred); VN_RELE(vp); if (code != 0) errno = code; AFS_GUNLOCK(); return code ? -1 : 0; } /* * uafs_getRights * Get a list of rights for the current user on path. */ int uafs_getRights(char *path) { int code; struct vnode *vp; int afs_rights; AFS_GLOCK(); code = uafs_LookupName(path, afs_CurrentDir, &vp, 1, 0); if (code != 0) { errno = code; AFS_GUNLOCK(); return -1; } afs_rights = PRSFS_READ | PRSFS_WRITE | PRSFS_INSERT | PRSFS_LOOKUP | PRSFS_DELETE | PRSFS_LOCK | PRSFS_ADMINISTER; afs_rights = afs_getRights(VTOAFS(vp), afs_rights, get_user_struct()->u_cred); AFS_GUNLOCK(); return afs_rights; } #endif /* UKERNEL */
19.346184
95
0.613828
e94ede7c3caaf153d34c995a42ffdcc543b70c99
373
h
C
modules/queue/include/node.h
gurylev-nikita/devtools-course-practice
bab6ba4e39f04940e27c9ac148505eb152c05d17
[ "CC-BY-4.0" ]
null
null
null
modules/queue/include/node.h
gurylev-nikita/devtools-course-practice
bab6ba4e39f04940e27c9ac148505eb152c05d17
[ "CC-BY-4.0" ]
3
2021-04-22T17:12:19.000Z
2021-05-14T12:16:25.000Z
modules/queue/include/node.h
taktaev-artyom/devtools-course-practice
7cf19defe061c07cfb3ebb71579456e807430a5d
[ "CC-BY-4.0" ]
null
null
null
// Copyright 2021 Tkachev Alexey #ifndef MODULES_QUEUE_INCLUDE_NODE_H_ #define MODULES_QUEUE_INCLUDE_NODE_H_ class Node { private: double data; Node* next; public: Node(); ~Node(); void setDada(const double& data_); void setNext(Node* next); double getData() const; Node* getNext() const; }; #endif // MODULES_QUEUE_INCLUDE_NODE_H_
16.217391
40
0.691689
f5ff08f1866de9e61271cb931a10edb8db803023
3,244
c
C
src/glue.c
tniessen/littlefs-disk-img-viewer
93d1660f2cc292a0f70a7dee8c10f28f4231e657
[ "MIT" ]
2
2021-11-05T19:25:46.000Z
2021-11-07T12:12:03.000Z
src/glue.c
tniessen/littlefs-disk-img-viewer
93d1660f2cc292a0f70a7dee8c10f28f4231e657
[ "MIT" ]
null
null
null
src/glue.c
tniessen/littlefs-disk-img-viewer
93d1660f2cc292a0f70a7dee8c10f28f4231e657
[ "MIT" ]
1
2021-12-12T06:50:19.000Z
2021-12-12T06:50:19.000Z
#include "littlefs/lfs.h" #include <stdint.h> #include <string.h> static int32_t asyncify_info[2]; static uint8_t asyncify_buffer[ASYNCIFY_BUFFER_SIZE]; int32_t* get_asyncify_info(void) { return asyncify_info; } void prepare_asyncify_unwind(void) { asyncify_info[0] = (intptr_t) asyncify_buffer; asyncify_info[1] = asyncify_info[0] + sizeof(asyncify_buffer); } void read_file_range(uint32_t offset, void* buf, uint32_t length) __attribute__((import_module("env"), import_name("readFileRange"))); static enum lfs_error bd_read(const struct lfs_config* c, lfs_block_t block, lfs_off_t off, void* buffer, lfs_size_t size) { read_file_range(block * c->block_size + off, buffer, size); return 0; } static uint8_t lfs_read_buffer[MAX_CACHE_SIZE]; static uint8_t lfs_prog_buffer[MAX_CACHE_SIZE]; static uint8_t lfs_lookahead_buffer[MAX_LOOKAHEAD_SIZE] __attribute__((aligned(4))); static struct lfs_config config = { .read = bd_read, .read_buffer = lfs_read_buffer, .lookahead_buffer = lfs_lookahead_buffer, .prog_buffer = lfs_prog_buffer }; struct lfs_config* configure(uint32_t read_size, uint32_t cache_size, uint32_t lookahead_size, uint32_t block_size, uint32_t block_count) { config.read_size = read_size; config.prog_size = read_size; config.cache_size = cache_size; config.lookahead_size = lookahead_size; config.block_size = block_size; config.block_count = block_count; return &config; } static lfs_t image; lfs_t* get_lfs_image(void) { return &image; } static char lfs_path_buffer[MAX_PATH_SIZE]; char* get_lfs_path_buffer(void) { return lfs_path_buffer; } size_t get_lfs_path_buffer_size(void) { return sizeof(lfs_path_buffer); } static lfs_dir_t lfs_dir; lfs_dir_t* get_lfs_dir(void) { return &lfs_dir; } static struct lfs_info lfs_info; struct lfs_info* get_lfs_info(void) { return &lfs_info; } uint8_t get_lfs_info_type(void) { return lfs_info.type; } lfs_size_t get_lfs_info_size(void) { return lfs_info.size; } char* get_lfs_info_name(void) { return lfs_info.name; } size_t get_lfs_info_name_length(void) { return strlen(lfs_info.name); } static uint8_t internal_file_buffer[MAX_CACHE_SIZE]; static struct lfs_file_config lfs_file_config = { .buffer = internal_file_buffer }; struct lfs_file_config* get_lfs_file_config(void) { return &lfs_file_config; } static lfs_file_t lfs_file; lfs_file_t* get_lfs_file(void) { return &lfs_file; } uint8_t file_read_buffer[FILE_READ_BUFFER_SIZE]; uint8_t* get_file_read_buffer(void) { return file_read_buffer; } int traverse_callback(void*, lfs_block_t) __attribute__((import_module("env"), import_name("traverseCallback"))); int do_lfs_traverse(void) { return lfs_fs_traverse(&image, traverse_callback, NULL); } uint16_t attr_sizes[256] __attribute__((aligned(2))); uint16_t* get_attr_sizes(void) { return attr_sizes; } int list_lfs_attr(void) { unsigned int count = 0; for (unsigned int i = 0; i <= 0xff; i++) { lfs_ssize_t sz = lfs_getattr(&image, lfs_path_buffer, (uint8_t) i, NULL, 0); if (sz >= 0) { count++; attr_sizes[i] = (uint16_t) sz; } else if (sz == LFS_ERR_NOATTR) { attr_sizes[i] = (uint16_t) -1; } else { return (int) sz; } } return count; }
25.147287
139
0.753083
64c4ba15110e70b3e6925b4d3a8044207c8ddf30
134
h
C
include/kernel/elf.h
OscarShiang/ARMMultiTasking
f34e511a50f9adb706e39e5f263f2021af6cfa91
[ "MIT" ]
2
2021-02-27T07:47:41.000Z
2021-02-27T07:47:44.000Z
include/kernel/elf.h
jserv/ARMMultiTasking
443cdae20e2ae5477897a1d7906d3f641507879f
[ "MIT" ]
null
null
null
include/kernel/elf.h
jserv/ARMMultiTasking
443cdae20e2ae5477897a1d7906d3f641507879f
[ "MIT" ]
1
2021-08-01T16:03:35.000Z
2021-08-01T16:03:35.000Z
#ifndef KERNEL_ELF_H #define KERNEL_ELF_H void (*load_elf(const char* filename, void* dest))(void); #endif /* ifdef KERNEL_ELF_H */
19.142857
57
0.738806
d41343447205b8483292e3d43d309597fc149bf0
1,100
h
C
boot/legacy/stage3/realmode_call.h
CyberFlameGO/tilck
4c32541874102e524374ab79d46b68af9d759390
[ "BSD-2-Clause" ]
1,059
2018-07-30T14:48:42.000Z
2022-03-30T19:54:49.000Z
boot/legacy/stage3/realmode_call.h
CyberFlameGO/tilck
4c32541874102e524374ab79d46b68af9d759390
[ "BSD-2-Clause" ]
15
2019-06-17T13:58:08.000Z
2021-10-16T18:19:25.000Z
boot/legacy/stage3/realmode_call.h
CyberFlameGO/tilck
4c32541874102e524374ab79d46b68af9d759390
[ "BSD-2-Clause" ]
47
2020-03-09T16:54:07.000Z
2022-03-12T08:53:56.000Z
/* SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <tilck/common/basic_defs.h> void realmode_call(void *func, u32 *eax_ref, u32 *ebx_ref, u32 *ecx_ref, u32 *edx_ref, u32 *esi_ref, u32 *edi_ref, u32 *flags_ref); void realmode_call_by_val(void *func, u32 a, u32 b, u32 c, u32 d, u32 si, u32 di); /* * Realmode functions * * Usage: realmode_call(&realmode_func_name, <registers>); */ extern u32 realmode_int_10h; extern u32 realmode_int_13h; extern u32 realmode_int_15h; extern u32 realmode_int_16h; void test_rm_call_working(void); struct VbeFarPtr { u16 off; u16 seg; } PACKED; static ALWAYS_INLINE void *get_flat_ptr(struct VbeFarPtr fp) { return (void *)((u32)fp.off + ((u32)fp.seg) * 16); } char bios_read_char(void); bool read_drive_params(u8 drive, u32 *sectors_per_track, u32 *heads_per_cylinder, u32 *cylinder_count); void read_sectors(u32 dest_paddr, u32 lba_sector, u32 sector_count);
21.568627
77
0.63
ac3b9f1c00cb28f7e49cb61f2a97a5524588edff
763
h
C
cases/adaptative_surfers/param/post/objects/surfer__us_4o0__surftimeprefactor_2o25/px/group/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/adaptative_surfers/param/post/objects/surfer__us_4o0__surftimeprefactor_2o25/px/group/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/adaptative_surfers/param/post/objects/surfer__us_4o0__surftimeprefactor_2o25/px/group/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
#ifndef C0P_PARAM_POST_OBJECTS_SURFER__US_4O0__SURFTIMEPREFACTOR_2O25_PX_GROUP_CHOICE_H #define C0P_PARAM_POST_OBJECTS_SURFER__US_4O0__SURFTIMEPREFACTOR_2O25_PX_GROUP_CHOICE_H #pragma once // THIS FILE SHOULD NOT BE EDITED DIRECTLY BY THE USERS. // THIS FILE WILL BE AUTOMATICALLY EDITED WHEN THE // CHOOSE COMMAND IS USED // choose your post #include "core/post/objects/object/post/group/all/core.h" #include "param/post/objects/surfer__us_4o0__surftimeprefactor_2o25/px/group/all/parameters.h" namespace c0p { template<typename TypeSurferUs4O0Surftimeprefactor2O25Step> using PostSurferUs4O0Surftimeprefactor2O25PxGroup = PostPostGroupAll<PostSurferUs4O0Surftimeprefactor2O25PxGroupAllParameters, TypeSurferUs4O0Surftimeprefactor2O25Step>; } #endif
40.157895
173
0.859764
ac805a0b4e6b801f6ef06d17482775e6148ac1ec
20,266
c
C
kernel/msm-4.14/drivers/video/fbdev/msm/mdss_hdcp_2x.c
clovadevice/clockplus2
c347c3e1bf20dbb93ab533c58c2ce11367aa80cd
[ "Apache-2.0" ]
null
null
null
kernel/msm-4.14/drivers/video/fbdev/msm/mdss_hdcp_2x.c
clovadevice/clockplus2
c347c3e1bf20dbb93ab533c58c2ce11367aa80cd
[ "Apache-2.0" ]
null
null
null
kernel/msm-4.14/drivers/video/fbdev/msm/mdss_hdcp_2x.c
clovadevice/clockplus2
c347c3e1bf20dbb93ab533c58c2ce11367aa80cd
[ "Apache-2.0" ]
1
2021-06-29T01:29:23.000Z
2021-06-29T01:29:23.000Z
/* Copyright (c) 2015-2019, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #define pr_fmt(fmt) "[mdss-hdcp-2x] %s: " fmt, __func__ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/cdev.h> #include <linux/sched.h> #include <linux/list.h> #include <linux/mutex.h> #include <linux/types.h> #include <linux/device.h> #include <linux/errno.h> #include <linux/kthread.h> #include "mdss_hdcp_2x.h" /* all message IDs */ #define INVALID_MESSAGE 0 #define AKE_INIT 2 #define AKE_SEND_CERT 3 #define AKE_NO_STORED_KM 4 #define AKE_STORED_KM 5 #define AKE_SEND_H_PRIME 7 #define AKE_SEND_PAIRING_INFO 8 #define LC_INIT 9 #define LC_SEND_L_PRIME 10 #define SKE_SEND_EKS 11 #define REP_SEND_RECV_ID_LIST 12 #define REP_SEND_ACK 15 #define REP_STREAM_MANAGE 16 #define REP_STREAM_READY 17 #define SKE_SEND_TYPE_ID 18 #define HDCP2P2_MAX_MESSAGES 19 #define REAUTH_REQ BIT(3) #define LINK_INTEGRITY_FAILURE BIT(4) #define HDCP_2X_EXECUTE(x) { \ kthread_queue_work(&hdcp->worker, &hdcp->wk_##x); \ } struct mdss_hdcp_2x_ctrl { struct hdcp2_app_data app_data; u32 timeout_left; u32 total_message_length; bool no_stored_km; bool feature_supported; bool authenticated; void *client_data; void *hdcp2_ctx; struct hdcp_transport_ops *client_ops; struct mutex wakeup_mutex; enum mdss_hdcp_2x_wakeup_cmd wakeup_cmd; bool repeater_flag; bool update_stream; int last_msg; atomic_t hdcp_off; enum mdss_hdcp_2x_device_type device_type; struct task_struct *thread; struct completion topo_wait; struct kthread_worker worker; struct kthread_work wk_init; struct kthread_work wk_msg_sent; struct kthread_work wk_msg_recvd; struct kthread_work wk_timeout; struct kthread_work wk_clean; struct kthread_work wk_stream; }; static const char *mdss_hdcp_2x_message_name(int msg_id) { switch (msg_id) { case INVALID_MESSAGE: return TO_STR(INVALID_MESSAGE); case AKE_INIT: return TO_STR(AKE_INIT); case AKE_SEND_CERT: return TO_STR(AKE_SEND_CERT); case AKE_NO_STORED_KM: return TO_STR(AKE_NO_STORED_KM); case AKE_STORED_KM: return TO_STR(AKE_STORED_KM); case AKE_SEND_H_PRIME: return TO_STR(AKE_SEND_H_PRIME); case AKE_SEND_PAIRING_INFO: return TO_STR(AKE_SEND_PAIRING_INFO); case LC_INIT: return TO_STR(LC_INIT); case LC_SEND_L_PRIME: return TO_STR(LC_SEND_L_PRIME); case SKE_SEND_EKS: return TO_STR(SKE_SEND_EKS); case REP_SEND_RECV_ID_LIST: return TO_STR(REP_SEND_RECV_ID_LIST); case REP_STREAM_MANAGE: return TO_STR(REP_STREAM_MANAGE); case REP_STREAM_READY: return TO_STR(REP_STREAM_READY); case SKE_SEND_TYPE_ID: return TO_STR(SKE_SEND_TYPE_ID); default: return "UNKNOWN"; } } static const struct mdss_hdcp_2x_msg_data hdcp_msg_lookup[HDCP2P2_MAX_MESSAGES] = { [AKE_INIT] = { 2, { {"rtx", 0x69000, 8}, {"TxCaps", 0x69008, 3} }, 0 }, [AKE_SEND_CERT] = { 3, { {"cert-rx", 0x6900B, 522}, {"rrx", 0x69215, 8}, {"RxCaps", 0x6921D, 3} }, 0 }, [AKE_NO_STORED_KM] = { 1, { {"Ekpub_km", 0x69220, 128} }, 0 }, [AKE_STORED_KM] = { 2, { {"Ekh_km", 0x692A0, 16}, {"m", 0x692B0, 16} }, 0 }, [AKE_SEND_H_PRIME] = { 1, { {"H'", 0x692C0, 32} }, BIT(1) }, [AKE_SEND_PAIRING_INFO] = { 1, { {"Ekh_km", 0x692E0, 16} }, BIT(2) }, [LC_INIT] = { 1, { {"rn", 0x692F0, 8} }, 0 }, [LC_SEND_L_PRIME] = { 1, { {"L'", 0x692F8, 32} }, 0 }, [SKE_SEND_EKS] = { 2, { {"Edkey_ks", 0x69318, 16}, {"riv", 0x69328, 8} }, 0 }, [SKE_SEND_TYPE_ID] = { 1, { {"type", 0x69494, 1} }, 0 }, [REP_SEND_RECV_ID_LIST] = { 4, { {"RxInfo", 0x69330, 2}, {"seq_num_V", 0x69332, 3}, {"V'", 0x69335, 16}, {"ridlist", 0x69345, 155} }, BIT(0) }, [REP_SEND_ACK] = { 1, { {"V", 0x693E0, 16} }, 0 }, [REP_STREAM_MANAGE] = { 3, { {"seq_num_M", 0x693F0, 3}, {"k", 0x693F3, 2}, {"streamID_Type", 0x693F5, 126} }, 0 }, [REP_STREAM_READY] = { 1, { {"M'", 0x69473, 32} }, 0 }, }; static void mdss_hdcp_2x_check_worker_status(struct mdss_hdcp_2x_ctrl *hdcp) { if (!list_empty(&hdcp->wk_init.node)) pr_debug("init work queued\n"); if (hdcp->worker.current_work == &hdcp->wk_init) pr_debug("init work executing\n"); if (!list_empty(&hdcp->wk_msg_sent.node)) pr_debug("msg_sent work queued\n"); if (hdcp->worker.current_work == &hdcp->wk_msg_sent) pr_debug("msg_sent work executing\n"); if (!list_empty(&hdcp->wk_msg_recvd.node)) pr_debug("msg_recvd work queued\n"); if (hdcp->worker.current_work == &hdcp->wk_msg_recvd) pr_debug("msg_recvd work executing\n"); if (!list_empty(&hdcp->wk_timeout.node)) pr_debug("timeout work queued\n"); if (hdcp->worker.current_work == &hdcp->wk_timeout) pr_debug("timeout work executing\n"); if (!list_empty(&hdcp->wk_clean.node)) pr_debug("clean work queued\n"); if (hdcp->worker.current_work == &hdcp->wk_clean) pr_debug("clean work executing\n"); if (!list_empty(&hdcp->wk_stream.node)) pr_debug("stream work queued\n"); if (hdcp->worker.current_work == &hdcp->wk_stream) pr_debug("stream work executing\n"); } static int mdss_hdcp_2x_get_next_message(struct mdss_hdcp_2x_ctrl *hdcp, struct hdcp_transport_wakeup_data *data) { switch (hdcp->last_msg) { case INVALID_MESSAGE: return AKE_INIT; case AKE_INIT: return AKE_SEND_CERT; case AKE_SEND_CERT: if (hdcp->no_stored_km) return AKE_NO_STORED_KM; else return AKE_STORED_KM; case AKE_STORED_KM: case AKE_NO_STORED_KM: return AKE_SEND_H_PRIME; case AKE_SEND_H_PRIME: if (hdcp->no_stored_km) return AKE_SEND_PAIRING_INFO; else return LC_INIT; case AKE_SEND_PAIRING_INFO: return LC_INIT; case LC_INIT: return LC_SEND_L_PRIME; case LC_SEND_L_PRIME: return SKE_SEND_EKS; case SKE_SEND_EKS: if (!hdcp->repeater_flag) return SKE_SEND_TYPE_ID; case SKE_SEND_TYPE_ID: case REP_STREAM_READY: case REP_SEND_ACK: if (!hdcp->repeater_flag) return INVALID_MESSAGE; if (data->cmd == HDCP_TRANSPORT_CMD_SEND_MESSAGE) return REP_STREAM_MANAGE; else return REP_SEND_RECV_ID_LIST; case REP_SEND_RECV_ID_LIST: return REP_SEND_ACK; case REP_STREAM_MANAGE: return REP_STREAM_READY; default: pr_err("Uknown message ID (%d)", hdcp->last_msg); return -EINVAL; } } static void mdss_hdcp_2x_wakeup_client(struct mdss_hdcp_2x_ctrl *hdcp, struct hdcp_transport_wakeup_data *data) { int rc = 0; if (hdcp && hdcp->client_ops && hdcp->client_ops->wakeup && data && (data->cmd != HDCP_TRANSPORT_CMD_INVALID)) { data->abort_mask = REAUTH_REQ | LINK_INTEGRITY_FAILURE; if (data->cmd == HDCP_TRANSPORT_CMD_SEND_MESSAGE || data->cmd == HDCP_TRANSPORT_CMD_RECV_MESSAGE || data->cmd == HDCP_TRANSPORT_CMD_LINK_POLL) { hdcp->last_msg = mdss_hdcp_2x_get_next_message(hdcp, data); if (hdcp->last_msg <= INVALID_MESSAGE) { hdcp->last_msg = INVALID_MESSAGE; return; } data->message_data = &hdcp_msg_lookup[hdcp->last_msg]; } rc = hdcp->client_ops->wakeup(data); if (rc) pr_err("error sending %s to hdcp client\n", hdcp_transport_cmd_to_str(data->cmd)); } } static inline void mdss_hdcp_2x_send_message(struct mdss_hdcp_2x_ctrl *hdcp) { char msg_name[50]; struct hdcp_transport_wakeup_data cdata = { HDCP_TRANSPORT_CMD_SEND_MESSAGE }; cdata.context = hdcp->client_data; cdata.timeout = hdcp->app_data.timeout; cdata.buf_len = hdcp->app_data.response.length; /* ignore the first byte as it contains the message id */ cdata.buf = hdcp->app_data.response.data + 1; snprintf(msg_name, sizeof(msg_name), "%s: ", mdss_hdcp_2x_message_name(hdcp->app_data.response.data[0])); print_hex_dump(KERN_DEBUG, msg_name, DUMP_PREFIX_NONE, 16, 1, cdata.buf, cdata.buf_len, false); mdss_hdcp_2x_wakeup_client(hdcp, &cdata); } static bool mdss_hdcp_2x_client_feature_supported(void *data) { struct mdss_hdcp_2x_ctrl *hdcp = data; return hdcp2_feature_supported(hdcp->hdcp2_ctx); } static int mdss_hdcp_2x_check_valid_state(struct mdss_hdcp_2x_ctrl *hdcp) { int rc = 0; if (!list_empty(&hdcp->worker.work_list)) mdss_hdcp_2x_check_worker_status(hdcp); if (hdcp->wakeup_cmd == HDCP_2X_CMD_START) { if (!list_empty(&hdcp->worker.work_list)) { rc = -EBUSY; goto exit; } } else { if (atomic_read(&hdcp->hdcp_off)) { pr_debug("hdcp2.2 session tearing down\n"); goto exit; } } exit: return rc; } static void mdss_hdcp_2x_clean(struct mdss_hdcp_2x_ctrl *hdcp) { struct hdcp_transport_wakeup_data cdata = { HDCP_TRANSPORT_CMD_INVALID }; hdcp->authenticated = false; hdcp2_app_comm(hdcp->hdcp2_ctx, HDCP2_CMD_STOP, &hdcp->app_data); cdata.context = hdcp->client_data; cdata.cmd = HDCP_TRANSPORT_CMD_STATUS_FAILED; if (!atomic_read(&hdcp->hdcp_off)) mdss_hdcp_2x_wakeup_client(hdcp, &cdata); atomic_set(&hdcp->hdcp_off, 1); } static void mdss_hdcp_2x_cleanup_work(struct kthread_work *work) { struct mdss_hdcp_2x_ctrl *hdcp = container_of(work, struct mdss_hdcp_2x_ctrl, wk_clean); mdss_hdcp_2x_clean(hdcp); } static void mdss_hdcp_2x_stream(struct mdss_hdcp_2x_ctrl *hdcp) { int rc = 0; if (atomic_read(&hdcp->hdcp_off)) { pr_debug("invalid state, hdcp off\n"); return; } if (!hdcp->repeater_flag) { pr_debug("invalid state, not a repeater\n"); return; } rc = hdcp2_app_comm(hdcp->hdcp2_ctx, HDCP2_CMD_QUERY_STREAM, &hdcp->app_data); if (rc) goto exit; if (!hdcp->app_data.response.data || !hdcp->app_data.request.data) { pr_err("invalid response/request buffers\n"); rc = -EINVAL; goto exit; } pr_debug("message received from TZ: %s\n", mdss_hdcp_2x_message_name(hdcp->app_data.response.data[0])); exit: if (!rc && !atomic_read(&hdcp->hdcp_off)) mdss_hdcp_2x_send_message(hdcp); } static void mdss_hdcp_2x_query_stream_work(struct kthread_work *work) { struct mdss_hdcp_2x_ctrl *hdcp = container_of(work, struct mdss_hdcp_2x_ctrl, wk_stream); mdss_hdcp_2x_stream(hdcp); } static void mdss_hdcp_2x_initialize_command(struct mdss_hdcp_2x_ctrl *hdcp, enum hdcp_transport_wakeup_cmd cmd, struct hdcp_transport_wakeup_data *cdata) { cdata->cmd = cmd; cdata->timeout = hdcp->timeout_left; cdata->buf = hdcp->app_data.request.data + 1; } static void mdss_hdcp_2x_msg_sent(struct mdss_hdcp_2x_ctrl *hdcp) { struct hdcp_transport_wakeup_data cdata = { HDCP_TRANSPORT_CMD_INVALID }; cdata.context = hdcp->client_data; switch (hdcp->app_data.response.data[0]) { case SKE_SEND_TYPE_ID: if (!hdcp2_app_comm(hdcp->hdcp2_ctx, HDCP2_CMD_SET_HW_KEY, &hdcp->app_data)) { hdcp->authenticated = true; cdata.cmd = HDCP_TRANSPORT_CMD_STATUS_SUCCESS; mdss_hdcp_2x_wakeup_client(hdcp, &cdata); } /* poll for link check */ mdss_hdcp_2x_initialize_command(hdcp, HDCP_TRANSPORT_CMD_LINK_POLL, &cdata); break; case SKE_SEND_EKS: if (hdcp->repeater_flag && !atomic_read(&hdcp->hdcp_off)) { /* poll for link check */ mdss_hdcp_2x_initialize_command(hdcp, HDCP_TRANSPORT_CMD_LINK_POLL, &cdata); } else { hdcp->app_data.response.data[0] = SKE_SEND_TYPE_ID; hdcp->app_data.response.length = 2; hdcp->app_data.timeout = 100; mdss_hdcp_2x_send_message(hdcp); } break; case REP_SEND_ACK: pr_debug("Repeater authentication successful\n"); if (hdcp->update_stream) { HDCP_2X_EXECUTE(stream); hdcp->update_stream = false; } else { mdss_hdcp_2x_initialize_command(hdcp, HDCP_TRANSPORT_CMD_LINK_POLL, &cdata); } break; default: cdata.cmd = HDCP_TRANSPORT_CMD_RECV_MESSAGE; cdata.timeout = hdcp->timeout_left; cdata.buf = hdcp->app_data.request.data + 1; } mdss_hdcp_2x_wakeup_client(hdcp, &cdata); } static void mdss_hdcp_2x_msg_sent_work(struct kthread_work *work) { struct mdss_hdcp_2x_ctrl *hdcp = container_of(work, struct mdss_hdcp_2x_ctrl, wk_msg_sent); if (hdcp->wakeup_cmd != HDCP_2X_CMD_MSG_SEND_SUCCESS) { pr_err("invalid wakeup command %d\n", hdcp->wakeup_cmd); return; } mdss_hdcp_2x_msg_sent(hdcp); } static void mdss_hdcp_2x_init(struct mdss_hdcp_2x_ctrl *hdcp) { int rc = 0; if (hdcp->wakeup_cmd != HDCP_2X_CMD_START) { pr_err("invalid wakeup command %d\n", hdcp->wakeup_cmd); return; } rc = hdcp2_app_comm(hdcp->hdcp2_ctx, HDCP2_CMD_START, &hdcp->app_data); if (rc) goto exit; pr_debug("message received from TZ: %s\n", mdss_hdcp_2x_message_name(hdcp->app_data.response.data[0])); mdss_hdcp_2x_send_message(hdcp); return; exit: HDCP_2X_EXECUTE(clean); } static void mdss_hdcp_2x_init_work(struct kthread_work *work) { struct mdss_hdcp_2x_ctrl *hdcp = container_of(work, struct mdss_hdcp_2x_ctrl, wk_init); mdss_hdcp_2x_init(hdcp); } static void mdss_hdcp_2x_timeout(struct mdss_hdcp_2x_ctrl *hdcp) { int rc = 0; int message_id; if (atomic_read(&hdcp->hdcp_off)) { pr_debug("invalid state, hdcp off\n"); return; } rc = hdcp2_app_comm(hdcp->hdcp2_ctx, HDCP2_CMD_TIMEOUT, &hdcp->app_data); if (rc) goto error; message_id = (int)hdcp->app_data.response.data[0]; if (message_id == LC_INIT && !atomic_read(&hdcp->hdcp_off)) mdss_hdcp_2x_send_message(hdcp); return; error: if (!atomic_read(&hdcp->hdcp_off)) HDCP_2X_EXECUTE(clean); } static void mdss_hdcp_2x_timeout_work(struct kthread_work *work) { struct mdss_hdcp_2x_ctrl *hdcp = container_of(work, struct mdss_hdcp_2x_ctrl, wk_timeout); mdss_hdcp_2x_timeout(hdcp); } static void mdss_hdcp_2x_msg_recvd(struct mdss_hdcp_2x_ctrl *hdcp) { int rc = 0; char *msg = NULL; char msg_name[50]; u32 message_id_bytes = 0; u32 request_length, out_msg; struct hdcp_transport_wakeup_data cdata = { HDCP_TRANSPORT_CMD_INVALID }; if (atomic_read(&hdcp->hdcp_off)) { pr_debug("invalid state, hdcp off\n"); return; } cdata.context = hdcp->client_data; request_length = hdcp->total_message_length; msg = hdcp->app_data.request.data; if (request_length == 0) { pr_err("invalid message length\n"); goto exit; } if (hdcp->device_type == HDCP_TXMTR_DP) { msg[0] = hdcp->last_msg; message_id_bytes = 1; } request_length += message_id_bytes; snprintf(msg_name, sizeof(msg_name), "%s: ", mdss_hdcp_2x_message_name((int)msg[0])); print_hex_dump(KERN_DEBUG, msg_name, DUMP_PREFIX_NONE, 16, 1, msg, request_length, false); pr_debug("message received from SINK: %s\n", mdss_hdcp_2x_message_name(msg[0])); hdcp->app_data.request.length = request_length; rc = hdcp2_app_comm(hdcp->hdcp2_ctx, HDCP2_CMD_PROCESS_MSG, &hdcp->app_data); if (rc) { pr_err("failed to process message from hdcp sink (%d)\n", rc); rc = -EINVAL; goto exit; } if (msg[0] == AKE_SEND_H_PRIME && hdcp->no_stored_km) { cdata.cmd = HDCP_TRANSPORT_CMD_RECV_MESSAGE; cdata.timeout = hdcp->app_data.timeout; cdata.buf = hdcp->app_data.request.data + 1; goto exit; } if (msg[0] == REP_STREAM_READY) { if (!hdcp->authenticated) { rc = hdcp2_app_comm(hdcp->hdcp2_ctx, HDCP2_CMD_SET_HW_KEY, &hdcp->app_data); if (!rc) { hdcp->authenticated = true; cdata.cmd = HDCP_TRANSPORT_CMD_STATUS_SUCCESS; mdss_hdcp_2x_wakeup_client(hdcp, &cdata); } else { pr_err("failed to enable encryption (%d)\n", rc); } } mdss_hdcp_2x_initialize_command(hdcp, HDCP_TRANSPORT_CMD_LINK_POLL, &cdata); goto exit; } out_msg = (u32)hdcp->app_data.response.data[0]; pr_debug("message received from TZ: %s\n", mdss_hdcp_2x_message_name(out_msg)); if (out_msg == AKE_NO_STORED_KM) hdcp->no_stored_km = 1; else hdcp->no_stored_km = 0; if (out_msg == SKE_SEND_EKS) { hdcp->repeater_flag = hdcp->app_data.repeater_flag; hdcp->update_stream = true; } if (!atomic_read(&hdcp->hdcp_off)) { pr_debug("creating client data for: %s\n", mdss_hdcp_2x_message_name(out_msg)); cdata.cmd = HDCP_TRANSPORT_CMD_SEND_MESSAGE; cdata.buf = hdcp->app_data.response.data + 1; cdata.buf_len = hdcp->app_data.response.length; cdata.timeout = hdcp->app_data.timeout; } exit: mdss_hdcp_2x_wakeup_client(hdcp, &cdata); if (rc && !atomic_read(&hdcp->hdcp_off)) HDCP_2X_EXECUTE(clean); } static void mdss_hdcp_2x_msg_recvd_work(struct kthread_work *work) { struct mdss_hdcp_2x_ctrl *hdcp = container_of(work, struct mdss_hdcp_2x_ctrl, wk_msg_recvd); mdss_hdcp_2x_msg_recvd(hdcp); } static int mdss_hdcp_2x_wakeup(struct mdss_hdcp_2x_wakeup_data *data) { struct mdss_hdcp_2x_ctrl *hdcp; int rc = 0; if (!data) return -EINVAL; hdcp = data->context; if (!hdcp) return -EINVAL; mutex_lock(&hdcp->wakeup_mutex); hdcp->wakeup_cmd = data->cmd; hdcp->timeout_left = data->timeout; hdcp->total_message_length = data->total_message_length; pr_debug("%s\n", mdss_hdcp_2x_cmd_to_str(hdcp->wakeup_cmd)); rc = mdss_hdcp_2x_check_valid_state(hdcp); if (rc) goto exit; if (!completion_done(&hdcp->topo_wait)) complete_all(&hdcp->topo_wait); switch (hdcp->wakeup_cmd) { case HDCP_2X_CMD_START: hdcp->no_stored_km = 0; hdcp->repeater_flag = false; hdcp->update_stream = false; hdcp->last_msg = INVALID_MESSAGE; hdcp->timeout_left = 0; atomic_set(&hdcp->hdcp_off, 0); HDCP_2X_EXECUTE(init); break; case HDCP_2X_CMD_STOP: atomic_set(&hdcp->hdcp_off, 1); HDCP_2X_EXECUTE(clean); break; case HDCP_2X_CMD_MSG_SEND_SUCCESS: HDCP_2X_EXECUTE(msg_sent); break; case HDCP_2X_CMD_MSG_SEND_FAILED: case HDCP_2X_CMD_MSG_RECV_FAILED: case HDCP_2X_CMD_LINK_FAILED: HDCP_2X_EXECUTE(clean); break; case HDCP_2X_CMD_MSG_RECV_SUCCESS: HDCP_2X_EXECUTE(msg_recvd); break; case HDCP_2X_CMD_MSG_RECV_TIMEOUT: HDCP_2X_EXECUTE(timeout); break; case HDCP_2X_CMD_QUERY_STREAM_TYPE: HDCP_2X_EXECUTE(stream); break; default: pr_err("invalid wakeup command %d\n", hdcp->wakeup_cmd); } exit: mutex_unlock(&hdcp->wakeup_mutex); return rc; } int mdss_hdcp_2x_register(struct mdss_hdcp_2x_register_data *data) { int rc = 0; struct mdss_hdcp_2x_ctrl *hdcp = NULL; if (!data) { pr_err("invalid hdcp init data\n"); return -EINVAL; } if (!data->ops) { pr_err("invalid input: txmtr context\n"); return -EINVAL; } if (!data->client_ops) { pr_err("invalid input: client_ops\n"); return -EINVAL; } if (!data->hdcp_data) { pr_err("invalid input: hdcp_data\n"); return -EINVAL; } /* populate ops to be called by client */ data->ops->feature_supported = mdss_hdcp_2x_client_feature_supported; data->ops->wakeup = mdss_hdcp_2x_wakeup; hdcp = kzalloc(sizeof(*hdcp), GFP_KERNEL); if (!hdcp) { rc = -ENOMEM; goto unlock; } hdcp->client_data = data->client_data; hdcp->client_ops = data->client_ops; hdcp->device_type = data->device_type; hdcp->hdcp2_ctx = hdcp2_init(hdcp->device_type); atomic_set(&hdcp->hdcp_off, 0); mutex_init(&hdcp->wakeup_mutex); kthread_init_worker(&hdcp->worker); kthread_init_work(&hdcp->wk_init, mdss_hdcp_2x_init_work); kthread_init_work(&hdcp->wk_msg_sent, mdss_hdcp_2x_msg_sent_work); kthread_init_work(&hdcp->wk_msg_recvd, mdss_hdcp_2x_msg_recvd_work); kthread_init_work(&hdcp->wk_timeout, mdss_hdcp_2x_timeout_work); kthread_init_work(&hdcp->wk_clean, mdss_hdcp_2x_cleanup_work); kthread_init_work(&hdcp->wk_stream, mdss_hdcp_2x_query_stream_work); init_completion(&hdcp->topo_wait); *data->hdcp_data = hdcp; hdcp->thread = kthread_run(kthread_worker_fn, &hdcp->worker, "hdcp_tz_lib"); if (IS_ERR(hdcp->thread)) { pr_err("unable to start lib thread\n"); rc = PTR_ERR(hdcp->thread); hdcp->thread = NULL; goto error; } return 0; error: kzfree(hdcp); hdcp = NULL; unlock: return rc; } void mdss_hdcp_2x_deregister(void *data) { struct mdss_hdcp_2x_ctrl *hdcp = data; if (!hdcp) return; kthread_stop(hdcp->thread); mutex_destroy(&hdcp->wakeup_mutex); hdcp2_deinit(hdcp->hdcp2_ctx); kzfree(hdcp); }
25.237858
76
0.72106
3a017b46cfade6b68f0b619573163d829371de46
5,075
c
C
smilelibtests/parsing/lexer/lexerposition_tests.c
seanofw/smile
3bc8807513cdb54053134fe2c79c5bf077aa026d
[ "Apache-2.0" ]
15
2016-05-27T14:30:28.000Z
2020-12-09T09:14:18.000Z
smilelibtests/parsing/lexer/lexerposition_tests.c
seanofw/smile
3bc8807513cdb54053134fe2c79c5bf077aa026d
[ "Apache-2.0" ]
null
null
null
smilelibtests/parsing/lexer/lexerposition_tests.c
seanofw/smile
3bc8807513cdb54053134fe2c79c5bf077aa026d
[ "Apache-2.0" ]
4
2016-01-17T03:52:21.000Z
2019-02-06T19:24:33.000Z
//--------------------------------------------------------------------------------------- // Smile Programming Language Interpreter (Unit Tests) // Copyright 2004-2019 Sean Werkema // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //--------------------------------------------------------------------------------------- #include "../../stdafx.h" #include <smile/parsing/lexer.h> TEST_SUITE(LexerPositionTests) //------------------------------------------------------------------------------------------------- // Setup helper. static Lexer SetupString(String source) { Lexer lexer; Smile_ResetEnvironment(); lexer = Lexer_Create(source, 0, String_Length(source), GetTestScriptName(), 1, 1, True); lexer->symbolTable = Smile_SymbolTable; return lexer; } static Lexer Setup(const char *string) { return SetupString(String_FromC(string)); } typedef struct PositionResultStruct { Int tokenKind; Int line; Int column; Int lineStart; Int length; } *PositionResult; static void VerifyPositions(Lexer lexer, PositionResult expectedResults, Int numExpectedResults) { Int i; for (i = 0; i < numExpectedResults; i++) { PositionResult expected = expectedResults + i; Int actualToken = Lexer_Next(lexer); LexerPosition actualPos = Token_GetPosition(lexer->token); ASSERT(actualToken == expected->tokenKind); ASSERT(actualPos->line == expected->line); ASSERT(actualPos->column == expected->column); ASSERT(actualPos->lineStart == expected->lineStart); ASSERT(actualPos->length == expected->length); } } //------------------------------------------------------------------------------------------------- // Whitespace and comment tests. START_TEST(CanMeasureWhitespaceAndNewlines) { Lexer lexer = Setup(" \t\a\b \r\n \r \n \n\r \f\v "); static struct PositionResultStruct expectedResults[] = { // token ln col st len { TOKEN_WHITESPACE, 1, 1, 0, 9 }, // \t\a\b { TOKEN_NEWLINE, 1, 10, 0, 2 }, // \r\n { TOKEN_WHITESPACE, 2, 1, 11, 3 }, { TOKEN_NEWLINE, 2, 4, 11, 1 }, // \r { TOKEN_WHITESPACE, 3, 1, 15, 3 }, { TOKEN_NEWLINE, 3, 4, 15, 1 }, // \n { TOKEN_WHITESPACE, 4, 1, 19, 3 }, { TOKEN_NEWLINE, 4, 4, 19, 2 }, // \n\r { TOKEN_WHITESPACE, 5, 1, 24, 8 }, // \f\v { TOKEN_EOI, 5, 9, 24, 0 }, }; VerifyPositions(lexer, expectedResults, sizeof(expectedResults) / sizeof(struct PositionResultStruct)); } END_TEST START_TEST(CanMeasureSingleLineComments) { Lexer lexer = Setup(" // floob\r\n//greep \r //spud \n//poit \n\r// narf "); static struct PositionResultStruct expectedResults[] = { // token ln col st len { TOKEN_WHITESPACE, 1, 1, 0, 3 }, { TOKEN_COMMENT_SINGLELINE, 1, 4, 0, 8 }, // floob { TOKEN_NEWLINE, 1, 12, 0, 2 }, // \r\n { TOKEN_COMMENT_SINGLELINE, 2, 1, 13, 10 }, // greep { TOKEN_NEWLINE, 2, 11, 13, 1 }, // \r { TOKEN_WHITESPACE, 3, 1, 24, 1 }, { TOKEN_COMMENT_SINGLELINE, 3, 2, 24, 8 }, // spud { TOKEN_NEWLINE, 3, 10, 24, 1 }, // \n { TOKEN_COMMENT_SINGLELINE, 4, 1, 34, 9 }, // poit { TOKEN_NEWLINE, 4, 10, 34, 2 }, // \n\r { TOKEN_COMMENT_SINGLELINE, 5, 1, 45, 8 }, // poit { TOKEN_EOI, 5, 9, 45, 0 }, }; VerifyPositions(lexer, expectedResults, sizeof(expectedResults) / sizeof(struct PositionResultStruct)); } END_TEST START_TEST(CanMeasureMultilineComments) { Lexer lexer = Setup(" /* floob\r\n//greep \r //spud \n//poit \n\r*/ narf "); static struct PositionResultStruct expectedResults[] = { // token ln col st len { TOKEN_WHITESPACE, 1, 1, 0, 3 }, { TOKEN_COMMENT_MULTILINE, 1, 4, 0, 44 }, { TOKEN_WHITESPACE, 5, 3, 45, 1 }, { TOKEN_ALPHANAME, 5, 4, 45, 4 }, { TOKEN_WHITESPACE, 5, 8, 45, 1 }, { TOKEN_EOI, 5, 9, 45, 0 }, }; VerifyPositions(lexer, expectedResults, sizeof(expectedResults) / sizeof(struct PositionResultStruct)); } END_TEST START_TEST(CanMeasureIncludes) { Lexer lexer = Setup(" #include \"stdio\" "); static struct PositionResultStruct expectedResults[] = { // token ln col st len { TOKEN_WHITESPACE, 1, 1, 0, 3 }, { TOKEN_LOANWORD_INCLUDE, 1, 4, 0, 8 }, { TOKEN_WHITESPACE, 1, 12, 0, 1 }, { TOKEN_DYNSTRING, 1, 13, 0, 7 }, { TOKEN_WHITESPACE, 1, 20, 0, 2 }, { TOKEN_EOI, 1, 22, 0, 0 }, }; VerifyPositions(lexer, expectedResults, sizeof(expectedResults) / sizeof(struct PositionResultStruct)); } END_TEST #include "lexerposition_tests.generated.inc"
31.918239
99
0.598621
8dad9835930e7dfcbe91ca50b7a06de79d3f28fd
146
h
C
src/c/date-layer.h
Spitemare/constructor
c0ddca4bc83747a56c4a200d0d7acd1cfccce466
[ "MIT" ]
4
2016-12-05T23:20:36.000Z
2016-12-06T11:08:58.000Z
src/c/date-layer.h
Spitemare/constructor
c0ddca4bc83747a56c4a200d0d7acd1cfccce466
[ "MIT" ]
1
2017-06-13T13:07:16.000Z
2017-06-19T20:25:11.000Z
src/c/date-layer.h
Spitemare/constructor
c0ddca4bc83747a56c4a200d0d7acd1cfccce466
[ "MIT" ]
null
null
null
#pragma once #include "fctx-layer.h" typedef FctxLayer DateLayer; DateLayer *date_layer_create(void); void date_layer_destroy(DateLayer *this);
18.25
41
0.80137
385fb3b9b73775f17ae0477f2039819da873d251
372
h
C
DoNotDisturbServer.framework/DNDSMutableBehaviorSettingsRecord.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
4
2021-10-06T12:15:26.000Z
2022-02-21T02:26:00.000Z
DoNotDisturbServer.framework/DNDSMutableBehaviorSettingsRecord.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
null
null
null
DoNotDisturbServer.framework/DNDSMutableBehaviorSettingsRecord.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
1
2021-10-08T07:40:53.000Z
2021-10-08T07:40:53.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/DoNotDisturbServer.framework/DoNotDisturbServer */ @interface DNDSMutableBehaviorSettingsRecord : DNDSBehaviorSettingsRecord @property (nonatomic, copy) NSNumber *interruptionBehaviorSetting; - (id)copyWithZone:(struct _NSZone { }*)arg1; - (void)setInterruptionBehaviorSetting:(id)arg1; @end
28.615385
91
0.814516
e1d24dfce8ea9347b4b9c617efed08477b1ce16e
3,000
c
C
src/gnu/diffutils/error.c
gspu/bitkeeper
994fb651a4045b221e33703fc3d665c3a34784e1
[ "Apache-2.0" ]
342
2016-05-10T14:59:07.000Z
2022-03-09T23:45:43.000Z
src/gnu/diffutils/error.c
rvs/bitkeeper
616740d0daad99530951e46ab48e577807cbbaf4
[ "Apache-2.0" ]
4
2016-05-16T20:14:27.000Z
2020-10-04T19:59:25.000Z
src/gnu/diffutils/error.c
rvs/bitkeeper
616740d0daad99530951e46ab48e577807cbbaf4
[ "Apache-2.0" ]
78
2016-05-10T15:53:30.000Z
2022-03-09T23:46:06.000Z
/* error.c -- error handler for noninteractive utilities Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Written by David MacKenzie. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #ifdef HAVE_VPRINTF #if __STDC__ #include <stdarg.h> #define VA_START(args, lastarg) va_start(args, lastarg) #else /* !__STDC__ */ #include <varargs.h> #define VA_START(args, lastarg) va_start(args) #endif /* !__STDC__ */ #else /* !HAVE_VPRINTF */ #ifdef HAVE_DOPRNT #define va_alist args #define va_dcl int args; #else /* !HAVE_DOPRNT */ #define va_alist a1, a2, a3, a4, a5, a6, a7, a8 #define va_dcl char *a1, *a2, *a3, *a4, *a5, *a6, *a7, *a8; #endif /* !HAVE_DOPRNT */ #endif /* !HAVE_VPRINTF */ #ifdef STDC_HEADERS #include <stdlib.h> #include <string.h> #else /* !STDC_HEADERS */ void exit (); #endif /* !STDC_HEADERS */ extern char *program_name; #ifndef HAVE_STRERROR static char * private_strerror (errnum) int errnum; { extern char *sys_errlist[]; extern int sys_nerr; if (errnum > 0 && errnum <= sys_nerr) return sys_errlist[errnum]; return "Unknown system error"; } #define strerror private_strerror #endif /* !HAVE_STRERROR */ /* Print the program name and error message MESSAGE, which is a printf-style format string with optional args. If ERRNUM is nonzero, print its corresponding system error message. Exit with status STATUS if it is nonzero. */ /* VARARGS */ void #if defined (HAVE_VPRINTF) && __STDC__ error (int status, int errnum, char *message, ...) #else /* !HAVE_VPRINTF or !__STDC__ */ error (status, errnum, message, va_alist) int status; int errnum; char *message; va_dcl #endif /* !HAVE_VPRINTF or !__STDC__ */ { #ifdef HAVE_VPRINTF va_list args; #endif /* HAVE_VPRINTF */ fflush (stdout); fprintf (stderr, "%s: ", program_name); #ifdef HAVE_VPRINTF VA_START (args, message); vfprintf (stderr, message, args); va_end (args); #else /* !HAVE_VPRINTF */ #ifdef HAVE_DOPRNT _doprnt (message, &args, stderr); #else /* !HAVE_DOPRNT */ fprintf (stderr, message, a1, a2, a3, a4, a5, a6, a7, a8); #endif /* !HAVE_DOPRNT */ #endif /* !HAVE_VPRINTF */ if (errnum) fprintf (stderr, ": %s", strerror (errnum)); putc ('\n', stderr); fflush (stderr); if (status) exit (status); }
26.785714
76
0.696333
b8c061cfbf5592bffce76f3de314c98727aa1dd4
5,351
h
C
include/system.h
matteo-veglio/libohiboard
a4675d77c2fdb16aec58d032eafd9c117d0dd05d
[ "MIT" ]
3
2015-10-06T20:53:41.000Z
2020-10-27T09:56:00.000Z
include/system.h
matteo-veglio/libohiboard
a4675d77c2fdb16aec58d032eafd9c117d0dd05d
[ "MIT" ]
44
2015-01-27T14:36:00.000Z
2022-03-23T17:49:04.000Z
include/system.h
matteo-veglio/libohiboard
a4675d77c2fdb16aec58d032eafd9c117d0dd05d
[ "MIT" ]
7
2016-04-08T10:44:05.000Z
2021-09-07T09:48:05.000Z
/* * This file is part of the libohiboard project. * * Copyright (C) 2012-2019 A. C. Open Hardware Ideas Lab * * Authors: * Marco Giammarini <m.giammarini@warcomeb.it> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * @file libohiboard/include/system.h * @author Marco Giammarini <m.giammarini@warcomeb.it> * @brief */ #ifndef __SYSTEM_H #define __SYSTEM_H #ifdef __cplusplus extern "C" { #endif #include "platforms.h" #include "errors.h" #include "types.h" #define LIBOHIBOARD_VERSION_MAJOR (0x2ul) #define LIBOHIBOARD_VERSION_MINOR (0x0ul) #define LIBOHIBOARD_VERSION_BUG (0x0ul) #define LIBOHIBOARD_VERSION ((LIBOHIBOARD_VERSION_MAJOR << 16)\ |(LIBOHIBOARD_VERSION_MINOR << 8 )\ |(LIBOHIBOARD_VERSION_BUG )) /** * */ System_Errors System_controlDevice (void); #if (LIBOHIBOARD_VERSION >= 0x20000u) // propostra pe poter determinmare systick period, ovvero via macros #define LIBOHIBOARD_SYSTEM_TICK_100_MICROSEC 10000ul #define LIBOHIBOARD_SYSTEM_TICK_1_MILLISEC 1000ul #define LIBOHIBOARD_SYSTEM_TICK_10_MILLISEC 100ul #ifndef LIBOHIBOARD_SYSTEM_TICK #define LIBOHIBOARD_SYSTEM_TICK LIBOHIBOARD_SYSTEM_TICK_1_MILLISEC #endif /** * Return the status of SysTick Timer. * * @return TRUE if SysTick is running, FALSE Otherwise. */ bool System_systickIsRunning (void); /** * Initialize and start the System Tick with interrupt enabled * Counter is in free running mode to generate periodic interrupts. * * @note This function is called automatically from @ref System_sysickInit * * @note This function, for Microchip PIC microcontroller uses physical 32bit timer. * * @param[in] ticks Specifies the ticks number between two interrupts. * @return ERRORS_NO_ERROR when function succeeded. * @return ERRORS_SYSTEM_TICK_INIT_FAILED when function failed. */ System_Errors System_systickConfig (uint32_t ticks); /** * This function configure the SysTick clock source, and configure the * timer to have 1ms time base. * * @note This function is called automatically from @ref Clock_init * * @note This function, for Microchip PIC microcontroller uses physical 32bit timer. * * @param[in] priority Tick interrupt priority * @return ERRORS_NO_ERROR when function succeeded. * @return ERRORS_SYSTEM_NO_CLOCK when function failed because the lock source is zero. */ System_Errors System_systickInit (uint32_t priority); /** * This function return the current tick value in millisecond * @return The current tick value */ uint32_t System_currentTick (void); /** * This function provides delay in milliseconds. * The delay is blocking. * @param[in] msec The delay time length in millisecond */ void System_delay (uint32_t msec); /** * This function provides delay in milliseconds from a given time tick previously taken. * The delay is blocking. * @param[in] msec The delay time length in millisecond */ void System_delayFrom (uint32_t from, uint32_t msec); #if !defined (LIBOHIBOARD_MICROCHIP_PIC) /** * Interrupt handler for SysTick interrupt. */ void SysTick_Handler (void); #endif /** * Suspend Tick increment. */ void System_suspendTick (void); /** * Resume Tick increment. */ void System_resumeTick (void); /*! * TODO */ void System_softwareBreakpoint (void); /** * Force to be ON the configuration of MCUDBG peripheral to force clock to MCU on low power states.\n * MCUDBG on is generally default behaviour when debugger session is active.\n * This can be reset only by MCU power cycle. */ void System_forceEnableDebug(void); /** * Force to be OFF the configuration of MCUDBG peripheral to force clock to MCU on low power states.\n * MCUDBG on is generally default behaviour when debugger session is active.\n * This can be reset only by MCU power cycle. */ void System_forceDisableDebug(void); /** * Resume the HAL version. * The format is 4-byte data divided as: * @li 1-byte (MSB) - NOT USED * @li 1-byte - Major Version * @li 1-byte - Minor Version * @li 1-byte (LSB) - Bug fix * * @return An uint32_t that represent the version number. */ uint32_t System_getHalVersion (void); #endif // LIBOHIBOARD_VERSION >= 0x20000 #ifdef __cplusplus } #endif #endif // __SYSTEM_H
29.727778
102
0.735003
b4d9611c34492891d6fa2e03e8684530568994c4
6,437
h
C
util/CircularFIFO.h
azonenberg/staticnet
5c61e9a2b15a2be512890b2562e7e087dd98083e
[ "BSD-3-Clause" ]
22
2021-09-08T15:21:25.000Z
2022-03-26T14:12:43.000Z
util/CircularFIFO.h
azonenberg/staticnet
5c61e9a2b15a2be512890b2562e7e087dd98083e
[ "BSD-3-Clause" ]
10
2021-09-30T13:04:04.000Z
2021-11-03T05:38:21.000Z
util/CircularFIFO.h
azonenberg/staticnet
5c61e9a2b15a2be512890b2562e7e087dd98083e
[ "BSD-3-Clause" ]
null
null
null
/*********************************************************************************************************************** * * * staticnet v0.1 * * * * Copyright (c) 2021 Andrew D. Zonenberg and contributors * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * * Redistributions of source code must retain the above copyright notice, this list of conditions, and the * * following disclaimer. * * * * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * * * * Neither the name of the author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * * THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * * ***********************************************************************************************************************/ /** @file @brief Declaration of CircularFIFO */ #ifndef CircularFIFO_h #define CircularFIFO_h #include <stdio.h> #include <stdlib.h> /** @brief A circular buffer for storing byte-stream data which supports arbitrary length reads, writes, and peeks. Pointers are 16 bit to reduce the memory footprint. One extra address is required to distinguish between empty and full positions so the maximum legal value for SIZE is 2^16 - 1. This class has no interlocks and is not thread/interrupt safe. */ template<uint16_t SIZE> class CircularFIFO { public: CircularFIFO() { Reset(); } /** @brief Clears the FIFO to an empty state */ void Reset() { m_readPtr = 0; m_writePtr = 0; } /** @brief Returns the number of bytes of data available to read */ uint16_t ReadSize() { return m_writePtr - m_readPtr; } /** @brief Returns the number of bytes of free buffer space */ uint16_t WriteSize() { return SIZE - ReadSize(); } /** @brief Pushes a buffer of data into the FIFO Writes are all-or-nothing. If len > WriteSize() this function returns false and the FIFO state is unmodified. */ bool Push(uint8_t* data, uint16_t len) { if(len > WriteSize()) return false; //TODO: optimized version using memcpy //(note that we need to handle wraparound) for(uint16_t i=0; i<len; i++) Push(data[i]); return true; } /** @brief Pushes a single byte of data into the FIFO Returns true if there was a free byte or false if not. */ bool Push(uint8_t c) { if(WriteSize() == 0) return false; m_data[m_writePtr] = c; m_writePtr = IncrementPointer(m_writePtr); return true; } /** @brief Pops a single byte of data from the FIFO */ uint8_t Pop() { if(ReadSize() == 0) return 0; uint8_t ret = m_data[m_readPtr]; m_readPtr = IncrementPointer(m_readPtr); return ret; } /** @brief Pops a block of data from the FIFO */ void Pop(uint16_t size) { //cap size if(size > ReadSize()) size = ReadSize(); //TODO: be efficient for(uint16_t i=0; i<size; i++) Pop(); } /** @brief Rotates the buffer such that the read pointer is now at zero and returns a pointer to the data */ uint8_t* Rewind() { //Figure out how many spaces we need to rewind the buffer by uint16_t nbytes = ReadSize(); //uint16_t nrotate = m_readPtr; //If we're already rewound, we're done already if(m_readPtr == 0) return m_data; //If empty, just reset pointers (no data to copy) else if(m_writePtr == m_readPtr) {} //Easy case: buffer hasn't wrapped past zero yet //Just move the data left in place else if(m_writePtr > m_readPtr) memmove(m_data, m_data + m_readPtr, nbytes); //Hard case: there's data where we want to go else { while(1) {} } //Done m_readPtr = 0; m_writePtr = nbytes; return m_data; } protected: /** @brief Increments a pointer mod our buffer size */ uint16_t IncrementPointer(uint16_t p) { return (p + 1) % SIZE; } uint16_t m_writePtr; uint16_t m_readPtr; uint8_t m_data[SIZE]; }; #endif
34.983696
120
0.504117
0d01f9abe196385a3807e990c968decd3f43bcb9
284
c
C
reftests/declaration-2477.c
nacaclanga/lang-c
9381ed248447d5fcc4a5ce40f8d75a26b5dbdcf1
[ "Apache-2.0", "MIT" ]
112
2017-10-23T13:58:15.000Z
2022-03-28T12:05:40.000Z
reftests/declaration-2477.c
nacaclanga/lang-c
9381ed248447d5fcc4a5ce40f8d75a26b5dbdcf1
[ "Apache-2.0", "MIT" ]
30
2018-03-24T14:02:01.000Z
2022-03-14T23:35:10.000Z
reftests/declaration-2477.c
nacaclanga/lang-c
9381ed248447d5fcc4a5ce40f8d75a26b5dbdcf1
[ "Apache-2.0", "MIT" ]
23
2018-11-27T22:39:37.000Z
2022-03-14T18:58:45.000Z
#pragma gnu struct foo S; /*=== Declaration DeclarationSpecifier TypeSpecifier StructType StructKind Struct Identifier "foo" InitDeclarator Declarator DeclaratorKind Identifier "S" ===*/
17.75
33
0.53169
89091b0062980f00665ede89b1c6ac347c1d3b65
5,327
h
C
isis/src/qisis/objs/TableMainWindow/TableMainWindow.h
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
null
null
null
isis/src/qisis/objs/TableMainWindow/TableMainWindow.h
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
null
null
null
isis/src/qisis/objs/TableMainWindow/TableMainWindow.h
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
1
2021-07-12T06:05:03.000Z
2021-07-12T06:05:03.000Z
#ifndef TableMainWindow_h #define TableMainWindow_h #include <QMainWindow> #include <QMenu> #include <QListWidgetItem> #include <QPointer> #include "MainWindow.h" class QTableWidget; namespace Isis { /** * @brief a subclass of the qisis mainwindow, tablemainwindow * handles all of the table tasks. * * @ingroup Visualization Tools * * @author ????-??-?? Stacy Alley * * @internal * @history 2008-06-12 Noah Hilt - Changed the save/load * functions to work with blank entries. * @history 2008-06-25 Noah Hilt - Fixed the delete rows method to search the * entire row for values, rather than just the first column. * @history 2008-10-17 Noah Hilt - Added an optional tooltip parameter to the * addToTable method. This tooltip will be displayed over the checkbox * that is to be added to the dock area. * @history 2008-11-25 Noah Hilt - Added an action to save the table to a file * that has been loaded or set with the save as action. This way the * user does not have to reselect the file to save the table to. * @history 2012-06-18 Steven Lambright - Gave the mac toolbar an object name for * saving and restoring state. Fixes #851." * @history 2013-02-21 Steven Lambright - Fixed a seg fault on destruction. This happened because * the item list was being saved off independently; the items would be * destroyed in the table widget but our copies of the pointers were not * yet cleared. This has been fixed by adding the method itemList() * instead of storing p_itemList. References #710. * @history 2016-08-28 Kelvin Rodriguez - writeSettings now const to match parent and eliminate * hidden virtual overload warnings in clang. Part of porting to * OS X 10.11 * @history 2017-10-06 Adam Goins - showTable() now calls syncColumns() after it calls * this->show() so that it hides the unselected columns appropriately. * Fixes #5141. */ class TableMainWindow : public MainWindow { Q_OBJECT public: TableMainWindow(QString title, QWidget *parent = 0); ~TableMainWindow(); void clear(); /** * Returns the table * * @return QTableWidget* */ QTableWidget *table() const { return p_table; }; QList<QListWidgetItem *> itemList() const; /** * * Returns the list widget * * @return QListWidget* */ QListWidget *listWidget() const { return p_listWidget; }; /** * * Returns the selected rows * * @return int */ int selectedRows() const { return p_selectedRows; }; /** * * Returns the current index * * @return int */ int currentIndex() const { return p_currentIndex; }; /** * * Returns the current row * * @return int */ int currentRow() const { return p_currentRow; }; void addToTable(bool setOn, const QString &heading, const QString &menuText = "", int insertAt = -1, Qt::Orientation o = Qt::Horizontal, QString toolTip = ""); void deleteColumn(int item); void setStatusMessage(QString message); void closeEvent(QCloseEvent *event); void hideEvent(QHideEvent *event); public slots: void showTable(); void syncColumns(); void syncRows(); void saveAsTable(); void saveTable(); void clearTable(); void deleteRows(); void clearRow(int row); void setCurrentRow(int row); void setCurrentIndex(int currentIndex); void setTrackListItems(bool track = false); bool trackListItems(); void loadTable(); void writeSettings() const; signals: /** * Signal emitted when a file has loaded * */ void fileLoaded(); protected: bool eventFilter(QObject *o, QEvent *e); void createTable(); void readItemSettings(QString heading, QListWidgetItem *item, bool defaultChecked); private: std::string p_appName; //!< The application name QWidget *p_parent; //!< The parent widget QString p_title; //!< The title string QDockWidget *p_dock; //!< The dock widget QAction *p_save; //!< Action to save the table to the current file QFile p_currentFile; //!< The current file QTableWidget *p_table; //!< The table QPointer<QListWidget> p_listWidget; //!< List widget int p_selectedRows; //!< Number of selected rows int p_currentIndex; //!< Current index int p_currentRow; //!< Current row int p_visibleColumns; //!< Number of visible columns QList<int>p_startColumn; //!< List of start columns QList<int>p_endColumn; //!< List of end columns bool p_trackItems; //!< Boolean to track items }; }; #endif
31.335294
99
0.581566
4737fefab6aaf03755b0147c27d5067e5324ee3f
2,730
h
C
CellTrackerLib/ftkTrackFeatures.h
tostathaina/farsight
7e9d6d15688735f34f7ca272e4e715acd11473ff
[ "Apache-2.0" ]
8
2016-07-22T11:24:19.000Z
2021-04-10T04:22:31.000Z
CellTrackerLib/ftkTrackFeatures.h
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
null
null
null
CellTrackerLib/ftkTrackFeatures.h
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
7
2016-07-21T07:39:17.000Z
2020-01-29T02:03:27.000Z
#ifndef __FTK_TRACK_FEATURES_H #define __FTK_TRACK_FEATURES_H #include <vector> #include <stdio.h> #include <math.h> #include "ftkLabelImageToFeatures.h" #include <ftkFeatures/ftkObject.h> //#include "ftkIntrinsicFeatures.h" #define MAX(a,b) (((a) > (b))?(a):(b)) namespace ftk { typedef struct { std::string name; std::string units; std::string description; } TrackPointFeatureInfoType; typedef struct { std::string name; std::string units; std::string description; } TimeFeatureInfoType; typedef struct { std::string name; std::string units; std::string description; } SubTrackFeatureInfoType; typedef struct{ double x,y,z; int id,t; float BoundingBox[6]; } TrackPoint; class TrackPointFeatures{ public: TrackPointFeatures(){ for(int counter=0; counter <DISPLACEMENT_VEC_Z+1; counter++) { scalars[counter] = 0.0; } } enum{DISTANCE_TO_1, DISTANCE, INST_SPEED, ANGLE_REL_TO_1, CHANGE_DISTANCE_TO_1, HAS_CONTACT_TO_2, DISPLACEMENT_VEC_X, DISPLACEMENT_VEC_Y, DISPLACEMENT_VEC_Z}; static const int M = DISPLACEMENT_VEC_Z+1; //This is the number of scalar track features float scalars[M]; int num; static TrackPointFeatureInfoType Info[M]; void Fprintf(FILE *fp = stdout); }; class TrackFeatures{ public: TrackFeatures() { for(int counter=0; counter< CONFINEMENT_RATIO+1; counter++) { scalars[counter] = 0.0; } } std::vector<ftk::IntrinsicFeatures> intrinsic_features;// figure out what makes some of the vectors empty. std::vector<ftk::TrackPointFeatures> tfeatures; enum{ AVG_SPEED, MAX_SPEED, MIN_SPEED, AVG_DIST_TO_1, AVG_ANGLE_REL_TO_1,CHANGE_DISTANCE_TO_1, CONTACT_TO_2, DISPLACEMENT_VEC_X,\ DISPLACEMENT_VEC_Y, DISPLACEMENT_VEC_Z, PATHLENGTH, TOTAL_DISTANCE, CONFINEMENT_RATIO}; static const int NF = CONFINEMENT_RATIO+1; float scalars[NF]; static TimeFeatureInfoType TimeInfo[NF]; void Fprintf(FILE* fp1 = stdout,FILE *fp2 = stdout); }; class SubTrackFeatures { public: SubTrackFeatures() { for(int counter=0; counter< COS_ANGLE_REL_PATH_DIR+1; counter++) { scalars[counter] = 0.0; } } enum{ DIS_X, DIS_Y, DIS_Z, LENGTH, COS_ANGLE_REL_TO_PREV, COS_ANGLE_REL_PATH_DIR}; static const int NF = COS_ANGLE_REL_PATH_DIR+1; float scalars[NF]; static SubTrackFeatureInfoType SubTrackInfo[NF]; int num; int t1,t2; }; class TrackingFeatureComputation { public: TrackingFeatureComputation() { } void ComputeSubTrackFeatures(std::vector< std::vector <ftk::TrackPoint> > * track_points); std::vector< std::vector<ftk::SubTrackFeatures> > GetSubTrackFeatures(void){return this->_sub_track_feats;}; private: std::vector< std::vector< ftk::SubTrackFeatures > > _sub_track_feats; }; } #endif
22.016129
159
0.73663
e4f530eafbb81cd30b3c6625120496d76736dcd4
2,077
h
C
Source/Core/Engine/game_engine.h
mlavik1/HikariOnline
47fb9457a1c5329859a4d41cb06442109bc507fa
[ "MIT" ]
null
null
null
Source/Core/Engine/game_engine.h
mlavik1/HikariOnline
47fb9457a1c5329859a4d41cb06442109bc507fa
[ "MIT" ]
null
null
null
Source/Core/Engine/game_engine.h
mlavik1/HikariOnline
47fb9457a1c5329859a4d41cb06442109bc507fa
[ "MIT" ]
null
null
null
#ifndef HIKARI_GAMEENGINE_H #define HIKARI_GAMEENGINE_H #include "OGRE/Ogre.h" #include "Core/Common/singleton.h" #include <vector> namespace Hikari { class GameEngine; class World; class TaskManager; class InputManager; class TickManager; class WindowManager; class NetworkManager; class PlayerManager; class GameWindow; class Client; #ifdef HIKARI_WORLDSERVER class WorldServer; #endif #ifdef HIKARI_GAMESERVER class GameServer; #endif class GameEngine { __DeclareSingleton(Hikari::GameEngine); private: Ogre::Root* mOgreRoot; GameWindow* mGameWindow; World* mWorld; TickManager* mTickManager; InputManager* mInputManager; WindowManager* mWindowManager; NetworkManager* mNetworkManager; PlayerManager* mPlayerManager; TaskManager* mTaskManager; float mLastTime = 0.0f; #ifdef HIKARI_CLIENT Client* mClient; #endif #ifdef HIKARI_WORLDSERVER WorldServer* mWorldServer; #endif #ifdef HIKARI_GAMESERVER GameServer* mGameServer; #endif protected: GameEngine(); public: ~GameEngine(); public: void Initialise(); void TickEngine(); inline Ogre::Root* GetOgreRoot() { return mOgreRoot; } inline World* GetWorld() { return mWorld; } inline GameWindow* GetGameWindow() { return mGameWindow; } inline TickManager* GetTickManager() { return mTickManager; } inline InputManager* GetInputManager() { return mInputManager; } inline WindowManager* GetWindowManager() { return mWindowManager; } inline NetworkManager* GetNetworkManager() { return mNetworkManager; } inline PlayerManager* GetPlayerManager() { return mPlayerManager; } inline TaskManager* GetTaskManager() { return mTaskManager; } #ifdef HIKARI_CLIENT inline Client* GetClient() { return mClient; } #endif #ifdef HIKARI_WORLDSERVER inline WorldServer* GetWorldServer() { return mWorldServer; } #endif #ifdef HIKARI_GAMESERVER inline GameServer* GetGameServer() { return mGameServer; } #endif }; extern GameEngine* GGameEngine; } #endif
15.160584
44
0.729899
fd2f42e439e0c2586858ed0991ee044d05b5f4cc
92
h
C
headers/Handler.h
PanPapag/An-efficient-searching-machine
b5a0d0be743925278855a9b70f4171b0344faffc
[ "MIT" ]
5
2018-12-26T10:59:57.000Z
2020-05-16T08:56:44.000Z
headers/Handler.h
PanPapag/An-efficient-searching-machine
b5a0d0be743925278855a9b70f4171b0344faffc
[ "MIT" ]
null
null
null
headers/Handler.h
PanPapag/An-efficient-searching-machine
b5a0d0be743925278855a9b70f4171b0344faffc
[ "MIT" ]
null
null
null
#ifndef __HANDLER__ #define __HANDLER__ void sig_handler(); #define _GNU_SOURCE ; #endif
10.222222
21
0.771739
b80fc2e8afa3352ec0c7de76af1d2892c9e2fd96
145
c
C
C/fib.c
nguyenphuminh/Fibonacci
e6a29547f6319aafdcefecca236627765d29f7d3
[ "MIT" ]
5
2021-04-30T13:13:59.000Z
2021-07-08T03:13:46.000Z
C/fib.c
nguyenphuminh/Fibonacci
e6a29547f6319aafdcefecca236627765d29f7d3
[ "MIT" ]
null
null
null
C/fib.c
nguyenphuminh/Fibonacci
e6a29547f6319aafdcefecca236627765d29f7d3
[ "MIT" ]
2
2021-05-02T11:40:50.000Z
2021-05-02T15:50:41.000Z
#include <stdio.h> int fib(int n) { if (n < 2) return n; return fib(n-1) + fib(n-2); } int main() { printf("%d",fib(5)); }
14.5
32
0.468966
0aa93adff90145a5043d1e6c1caa1746abeca919
36,032
h
C
Engine/Source/Runtime/Engine/Public/CanvasTypes.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/Engine/Public/CanvasTypes.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/Engine/Public/CanvasTypes.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================= Canvas.h: Unreal canvas definition. =============================================================================*/ #pragma once #include "Engine/EngineTypes.h" #include "IBreakIterator.h" #include "BatchedElements.h" #include "CanvasItem.h" #include "CanvasTypes.generated.h" class FMaterialRenderProxy; class FTexture; class FRenderTarget; class FHitProxyConsumer; class FRHICommandListImmediate; /** * General purpose data structure for grouping all parameters needed when sizing or wrapping a string */ USTRUCT() struct FTextSizingParameters { GENERATED_USTRUCT_BODY() /** a pixel value representing the horizontal screen location to begin rendering the string */ UPROPERTY() float DrawX; /** a pixel value representing the vertical screen location to begin rendering the string */ UPROPERTY() float DrawY; /** a pixel value representing the width of the area available for rendering the string */ UPROPERTY() float DrawXL; /** a pixel value representing the height of the area available for rendering the string */ UPROPERTY() float DrawYL; /** A value between 0.0 and 1.0, which represents how much the width/height should be scaled, where 1.0 represents 100% scaling. */ UPROPERTY() FVector2D Scaling; /** the font to use for sizing/wrapping the string */ UPROPERTY() const UFont* DrawFont; /** Horizontal spacing adjustment between characters and vertical spacing adjustment between wrapped lines */ UPROPERTY() FVector2D SpacingAdjust; FTextSizingParameters() : DrawX(0) , DrawY(0) , DrawXL(0) , DrawYL(0) , Scaling(ForceInit) , DrawFont(NULL) , SpacingAdjust(ForceInit) { } FTextSizingParameters( float inDrawX, float inDrawY, float inDrawXL, float inDrawYL, const UFont* inFont=NULL ) : DrawX(inDrawX), DrawY(inDrawY), DrawXL(inDrawXL), DrawYL(inDrawYL) , Scaling(1.f,1.f), DrawFont(inFont) , SpacingAdjust( 0.0f, 0.0f ) { } FTextSizingParameters( const UFont* inFont, float ScaleX, float ScaleY) : DrawX(0.f), DrawY(0.f), DrawXL(0.f), DrawYL(0.f) , Scaling(ScaleX,ScaleY), DrawFont(inFont) , SpacingAdjust( 0.0f, 0.0f ) { } }; /** * Used by UUIString::WrapString to track information about each line that is generated as the result of wrapping. */ USTRUCT() struct FWrappedStringElement { GENERATED_USTRUCT_BODY() /** the string associated with this line */ UPROPERTY() FString Value; /** the size (in pixels) that it will take to render this string */ UPROPERTY() FVector2D LineExtent; FWrappedStringElement() : LineExtent(ForceInit) { } /** Constructor */ FWrappedStringElement( const TCHAR* InValue, float Width, float Height ) : Value(InValue), LineExtent(Width,Height) {} }; class ENGINE_API FCanvasWordWrapper { public: /** Array of indices where the wrapped lines begin and end in the source string */ typedef TArray< TPair<int32, int32> > FWrappedLineData; private: struct FWrappingState { FWrappingState( const TCHAR* const InString, const int32 InStringLength, const FTextSizingParameters& InParameters, TArray<FWrappedStringElement>& InResults, FWrappedLineData* const InWrappedLineData) : String(InString) , StringLength(InStringLength) , Parameters(InParameters) , StartIndex(0) , Results(InResults) , WrappedLineData(InWrappedLineData) {} const TCHAR* const String; const int32 StringLength; const FTextSizingParameters& Parameters; int32 StartIndex; TArray<FWrappedStringElement>& Results; FWrappedLineData* const WrappedLineData; }; public: FCanvasWordWrapper(); /** * Used to generate multi-line/wrapped text. * * @param InString The unwrapped text. * @param InFontInfo The font used to render the text. * @param InWrapWidth The width available. * @param OutWrappedLineData An optional array to fill with the indices from the source string marking the begin and end points of the wrapped lines */ void Execute(const TCHAR* const InString, const FTextSizingParameters& InParameters, TArray<FWrappedStringElement>& OutStrings, FWrappedLineData* const OutWrappedLineData); private: /** * Processes the string using a word wrapping algorithm, resulting in up to a single line. * * @return True if a new line could be processed, false otherwise such as having reached the end of the string. */ bool ProcessLine(FWrappingState& WrappingState); /** * Stub method that should measure the substring of the range [StartIndex, EndIndex). * * @return True if the substring fits the desired width. */ bool DoesSubstringFit(FWrappingState& WrappingState, const int32 EndIndex); /** * Stub method that should measure the substring starting from StartIndex until the wrap width is found or no more indices remain. * * @return The index of the character that is at or after the desired width. */ int32 FindIndexAtOrAfterWrapWidth(FWrappingState& WrappingState); /** * Stub method for processing a single produced substring of the range [StartIndex, EndIndex) as a new line. */ void AddLine(FWrappingState& WrappingState, const int32 EndIndex); int32 FindFirstMandatoryBreakBetween(FWrappingState& WrappingState, const int32 WrapIndex); int32 FindLastBreakCandidateBetween(const int32 StartIndex, const int32 WrapIndex); int32 FindEndOfLastWholeGraphemeCluster(const int32 StartIndex, const int32 WrapIndex); private: TSharedPtr<IBreakIterator> GraphemeBreakIterator; TSharedPtr<IBreakIterator> LineBreakIterator; }; /** * Encapsulates the canvas state. */ class FCanvas { public: /** * Enum that describes what type of element we are currently batching. */ enum EElementType { ET_Line, ET_Triangle, ET_MAX }; /** * Enum for canvas features that are allowed **/ enum ECanvasAllowModes { // flushing and rendering Allow_Flush = 1<<0, // delete the render batches when rendering Allow_DeleteOnRender= 1<<1 }; /** * Constructor. */ ENGINE_API FCanvas(FRenderTarget* InRenderTarget,FHitProxyConsumer* InHitProxyConsumer, UWorld* InWorld, ERHIFeatureLevel::Type InFeatureLevel); /** * Constructor. For situations where a world is not available, but time information is */ ENGINE_API FCanvas(FRenderTarget* InRenderTarget, FHitProxyConsumer* InHitProxyConsumer, float InRealTime, float InWorldTime, float InWorldDeltaTime, ERHIFeatureLevel::Type InFeatureLevel); /** * Destructor. */ ENGINE_API ~FCanvas(); ENGINE_API static ESimpleElementBlendMode BlendToSimpleElementBlend(EBlendMode BlendMode); /** * Returns a FBatchedElements pointer to be used for adding vertices and primitives for rendering. * Adds a new render item to the sort element entry based on the current sort key. * * @param InElementType - Type of element we are going to draw. * @param InBatchedElementParameters - Parameters for this element * @param InTexture - New texture that will be set. * @param InBlendMode - New blendmode that will be set. * @param GlowInfo - info for optional glow effect when using depth field rendering * @return Returns a pointer to a FBatchedElements object. */ ENGINE_API FBatchedElements* GetBatchedElements(EElementType InElementType, FBatchedElementParameters* InBatchedElementParameters=NULL, const FTexture* Texture=NULL, ESimpleElementBlendMode BlendMode=SE_BLEND_MAX,const FDepthFieldGlowInfo& GlowInfo = FDepthFieldGlowInfo()); /** * Generates a new FCanvasTileRendererItem for the current sortkey and adds it to the sortelement list of items to render */ ENGINE_API void AddTileRenderItem(float X,float Y,float SizeX,float SizeY,float U,float V,float SizeU,float SizeV,const FMaterialRenderProxy* MaterialRenderProxy,FHitProxyId HitProxyId,bool bFreezeTime,FColor InColor); /** * Generates a new FCanvasTriangleRendererItem for the current sortkey and adds it to the sortelement list of items to render */ ENGINE_API void AddTriangleRenderItem(const FCanvasUVTri& Tri, const FMaterialRenderProxy* MaterialRenderProxy, FHitProxyId HitProxyId, bool bFreezeTime); /** * Sends a message to the rendering thread to draw the batched elements. * @param RHICmdList - command list to use * @param bForce - force the flush even if Allow_Flush is not enabled */ ENGINE_API void Flush_RenderThread(FRHICommandListImmediate& RHICmdList, bool bForce = false); /** * Sends a message to the rendering thread to draw the batched elements. * @param bForce - force the flush even if Allow_Flush is not enabled */ ENGINE_API void Flush_GameThread(bool bForce = false); /** * Pushes a transform onto the canvas's transform stack, multiplying it with the current top of the stack. * @param Transform - The transform to push onto the stack. */ ENGINE_API void PushRelativeTransform(const FMatrix& Transform); /** * Pushes a transform onto the canvas's transform stack. * @param Transform - The transform to push onto the stack. */ ENGINE_API void PushAbsoluteTransform(const FMatrix& Transform); /** * Removes the top transform from the canvas's transform stack. */ ENGINE_API void PopTransform(); /** * Replace the base (ie. TransformStack(0)) transform for the canvas with the given matrix * * @param Transform - The transform to use for the base */ ENGINE_API void SetBaseTransform(const FMatrix& Transform); /** * Generate a 2D projection for the canvas. Use this if you only want to transform in 2D on the XY plane * * @param ViewSizeX - Viewport width * @param ViewSizeY - Viewport height * @return Matrix for canvas projection */ ENGINE_API static FMatrix CalcBaseTransform2D(uint32 ViewSizeX, uint32 ViewSizeY); /** * Generate a 3D projection for the canvas. Use this if you want to transform in 3D * * @param ViewSizeX - Viewport width * @param ViewSizeY - Viewport height * @param fFOV - Field of view for the projection * @param NearPlane - Distance to the near clip plane * @return Matrix for canvas projection */ ENGINE_API static FMatrix CalcBaseTransform3D(uint32 ViewSizeX, uint32 ViewSizeY, float fFOV, float NearPlane); /** * Generate a view matrix for the canvas. Used for CalcBaseTransform3D * * @param ViewSizeX - Viewport width * @param ViewSizeY - Viewport height * @param fFOV - Field of view for the projection * @return Matrix for canvas view orientation */ ENGINE_API static FMatrix CalcViewMatrix(uint32 ViewSizeX, uint32 ViewSizeY, float fFOV); /** * Generate a projection matrix for the canvas. Used for CalcBaseTransform3D * * @param ViewSizeX - Viewport width * @param ViewSizeY - Viewport height * @param fFOV - Field of view for the projection * @param NearPlane - Distance to the near clip plane * @return Matrix for canvas projection */ ENGINE_API static FMatrix CalcProjectionMatrix(uint32 ViewSizeX, uint32 ViewSizeY, float fFOV, float NearPlane); /** * Get the current top-most transform entry without the canvas projection * @return matrix from transform stack. */ ENGINE_API FMatrix GetTransform() const { return TransformStack.Top().GetMatrix() * TransformStack[0].GetMatrix().InverseFast(); } /** * Get the bottom-most element of the transform stack. * @return matrix from transform stack. */ ENGINE_API const FMatrix& GetBottomTransform() const { return TransformStack[0].GetMatrix(); } /** * Get the current top-most transform entry * @return matrix from transform stack. */ ENGINE_API const FMatrix& GetFullTransform() const { return TransformStack.Top().GetMatrix(); } /** * Copy the conents of the TransformStack from an existing canvas * * @param Copy canvas to copy from **/ ENGINE_API void CopyTransformStack(const FCanvas& Copy); /** * Sets the render target which will be used for subsequent canvas primitives. */ ENGINE_API void SetRenderTarget_GameThread(FRenderTarget* NewRenderTarget); /** * Get the current render target for the canvas */ ENGINE_API FORCEINLINE FRenderTarget* GetRenderTarget() const { return RenderTarget; } /** * Sets a rect that should be used to offset rendering into the viewport render target * If not set the canvas will render to the full target * * @param ViewRect The rect to use */ ENGINE_API void SetRenderTargetRect( const FIntRect& ViewRect ); /** * Marks render target as dirty so that it will be resolved to texture */ void SetRenderTargetDirty(bool bDirty) { bRenderTargetDirty = bDirty; } /** * Sets the hit proxy which will be used for subsequent canvas primitives. */ ENGINE_API void SetHitProxy(HHitProxy* HitProxy); // HitProxy Accessors. FHitProxyId GetHitProxyId() const { return CurrentHitProxy ? CurrentHitProxy->Id : FHitProxyId(); } FHitProxyConsumer* GetHitProxyConsumer() const { return HitProxyConsumer; } bool IsHitTesting() const { return HitProxyConsumer != NULL; } /** * Push sort key onto the stack. Rendering is done with the current sort key stack entry. * * @param InSortKey - key value to push onto the stack */ void PushDepthSortKey(int32 InSortKey) { DepthSortKeyStack.Push(InSortKey); }; /** * Pop sort key off of the stack. * * @return top entry of the sort key stack */ int32 PopDepthSortKey() { int32 Result = 0; if( DepthSortKeyStack.Num() > 0 ) { Result = DepthSortKeyStack.Pop(); } else { // should always have one entry PushDepthSortKey(0); } return Result; }; /** * Return top sort key of the stack. * * @return top entry of the sort key stack */ int32 TopDepthSortKey() { checkSlow(DepthSortKeyStack.Num() > 0); return DepthSortKeyStack.Top(); } /** * Toggle allowed canvas modes * * @param InAllowedModes New modes to set */ void SetAllowedModes(uint32 InAllowedModes) { AllowedModes = InAllowedModes; } /** * Accessor for allowed canvas modes * * @return current allowed modes */ uint32 GetAllowedModes() const { return AllowedModes; } /** * Determine if the canvas has dirty batches that need to be rendered * * @return true if the canvas has any element to render */ bool HasBatchesToRender() const; /** * Access current feature level * * @return feature level that this canvas is rendering at */ ERHIFeatureLevel::Type GetFeatureLevel() const { return FeatureLevel; } /** * Access current shader platform * * @return shader platform that this canvas is rendering at */ EShaderPlatform GetShaderPlatform() const { return GShaderPlatformForFeatureLevel[FeatureLevel]; } // Get/Set if this Canvas allows its batched elements to switch vertical axis (e.g., rendering to back buffer should never flip) bool GetAllowSwitchVerticalAxis() const { return bAllowsToSwitchVerticalAxis; } void SetAllowSwitchVerticalAxis(bool bInAllowsToSwitchVerticalAxis) { bAllowsToSwitchVerticalAxis = bInAllowsToSwitchVerticalAxis; } public: float AlphaModulate; /** Entry for the transform stack which stores a matrix and its CRC for faster comparisons */ class FTransformEntry { public: FTransformEntry(const FMatrix& InMatrix) : Matrix(InMatrix) { MatrixCRC = FCrc::MemCrc_DEPRECATED(&Matrix,sizeof(FMatrix)); } FORCEINLINE void SetMatrix(const FMatrix& InMatrix) { Matrix = InMatrix; MatrixCRC = FCrc::MemCrc_DEPRECATED(&Matrix,sizeof(FMatrix)); } FORCEINLINE const FMatrix& GetMatrix() const { return Matrix; } FORCEINLINE uint32 GetMatrixCRC() const { return MatrixCRC; } private: FMatrix Matrix; uint32 MatrixCRC; }; /** returns the transform stack */ FORCEINLINE const TArray<FTransformEntry>& GetTransformStack() const { return TransformStack; } FORCEINLINE const FIntRect& GetViewRect() const { return ViewRect; } FORCEINLINE void SetScaledToRenderTarget(bool bScale = true) { bScaledToRenderTarget = bScale; } FORCEINLINE bool IsScaledToRenderTarget() const { return bScaledToRenderTarget; } FORCEINLINE void SetStereoRendering(bool bStereo = true) { bStereoRendering = bStereo; } FORCEINLINE bool IsStereoRendering() const { return bStereoRendering; } /** Depth used for orthographic stereo projection. Uses World Units.*/ FORCEINLINE void SetStereoDepth(int32 InDepth) { StereoDepth = InDepth; } FORCEINLINE int32 GetStereoDepth() const { return StereoDepth; } public: /** Private class for handling word wrapping behavior. */ TSharedPtr<FCanvasWordWrapper> WordWrapper; private: /** Stack of SortKeys. All rendering is done using the top most sort key */ TArray<int32> DepthSortKeyStack; /** Stack of matrices. Bottom most entry is the canvas projection */ TArray<FTransformEntry> TransformStack; /** View rect for the render target */ FIntRect ViewRect; /** Current render target used by the canvas */ FRenderTarget* RenderTarget; /** Current hit proxy consumer */ FHitProxyConsumer* HitProxyConsumer; /** Current hit proxy object */ TRefCountPtr<HHitProxy> CurrentHitProxy; /** Toggles for various canvas rendering functionality **/ uint32 AllowedModes; /** true if the render target has been rendered to since last calling SetRenderTarget() */ bool bRenderTargetDirty; /** Current real time in seconds */ float CurrentRealTime; /** Current world time in seconds */ float CurrentWorldTime; /** Current world time in seconds */ float CurrentDeltaWorldTime; /** true, if Canvas should be scaled to whole render target */ bool bScaledToRenderTarget; // True if canvas allows switching vertical axis; false will ignore any flip bool bAllowsToSwitchVerticalAxis; /** Feature level that we are currently rendering with */ ERHIFeatureLevel::Type FeatureLevel; /** true, if Canvas should be rendered in stereo */ bool bStereoRendering; /** Depth used for orthographic stereo projection. Uses World Units.*/ int32 StereoDepth; /** Cached render target size, depth and ortho-projection matrices for stereo rendering */ FMatrix CachedOrthoProjection[2]; int32 CachedRTWidth, CachedRTHeight, CachedDrawDepth; bool GetOrthoProjectionMatrices(float InDrawDepth, FMatrix OutOrthoProjection[2]); /** * Shared construction function */ void Construct(); public: /** * Access current real time */ float GetCurrentRealTime() const { return CurrentRealTime; } /** * Access current world time */ float GetCurrentWorldTime() const { return CurrentWorldTime; } /** * Access current delta time */ float GetCurrentDeltaWorldTime() const { return CurrentDeltaWorldTime; } /** * Draw a CanvasItem * * @param Item Item to draw */ ENGINE_API void DrawItem(FCanvasItem& Item); /** * Draw a CanvasItem at the given coordinates * * @param Item Item to draw * @param InPosition Position to draw item */ ENGINE_API void DrawItem(FCanvasItem& Item, const FVector2D& InPosition); /** * Draw a CanvasItem at the given coordinates * * @param Item Item to draw * @param X X Position to draw item * @param Y Y Position to draw item */ ENGINE_API void DrawItem(FCanvasItem& Item, float X, float Y); /** * Clear the canvas * * @param Color Color to clear with. */ ENGINE_API void Clear(const FLinearColor& Color); /** * Draw arbitrary aligned rectangle. * * @param X - X position to draw tile at * @param Y - Y position to draw tile at * @param SizeX - Width of tile * @param SizeY - Height of tile * @param U - Horizontal position of the upper left corner of the portion of the texture to be shown(texels) * @param V - Vertical position of the upper left corner of the portion of the texture to be shown(texels) * @param SizeU - The width of the portion of the texture to be drawn. This value is in texels. * @param SizeV - The height of the portion of the texture to be drawn. This value is in texels. * @param Color - tint applied to tile * @param Texture - Texture to draw * @param AlphaBlend - true to alphablend */ ENGINE_API void DrawTile( float X, float Y, float SizeX, float SizeY, float U, float V, float SizeU, float SizeV, const FLinearColor& Color, const FTexture* Texture = NULL, bool AlphaBlend = true ); /** * Draw an string centered on given location. * This function is being deprecated. a FCanvasTextItem should be used instead. * * @param StartX - X point * @param StartY - Y point * @param Text - Text to draw * @param Font - Font to use * @param Color - Color of the text * @param ShadowColor - Shadow color to draw underneath the text (ignored for distance field fonts) * @return total size in pixels of text drawn */ ENGINE_API int32 DrawShadowedString( float StartX, float StartY, const TCHAR* Text, const UFont* Font, const FLinearColor& Color, const FLinearColor& ShadowColor = FLinearColor::Black ); ENGINE_API int32 DrawShadowedText( float StartX, float StartY, const FText& Text, const UFont* Font, const FLinearColor& Color, const FLinearColor& ShadowColor = FLinearColor::Black ); ENGINE_API void WrapString( FTextSizingParameters& Parameters, const float InCurX, const TCHAR* const pText, TArray<FWrappedStringElement>& out_Lines, FCanvasWordWrapper::FWrappedLineData* const OutWrappedLineData = nullptr); ENGINE_API void DrawNGon(const FVector2D& Center, const FColor& Color, int32 NumSides, float Radius); /** * Contains all of the batched elements that need to be rendered at a certain depth sort key */ class FCanvasSortElement { public: /** * Init constructor */ FCanvasSortElement(int32 InDepthSortKey=0) : DepthSortKey(InDepthSortKey) {} /** * Equality is based on sort key * * @param Other - instance to compare against * @return true if equal */ bool operator==(const FCanvasSortElement& Other) const { return DepthSortKey == Other.DepthSortKey; } /** sort key for this set of render batch elements */ int32 DepthSortKey; /** list of batches that should be rendered at this sort key level */ TArray<class FCanvasBaseRenderItem*> RenderBatchArray; }; /** Batched canvas elements to be sorted for rendering. Sort order is back-to-front */ TArray<FCanvasSortElement> SortedElements; /** Map from sortkey to array index of SortedElements for faster lookup of existing entries */ TMap<int32,int32> SortedElementLookupMap; /** Store index of last Element off to avoid semi expensive Find() */ int32 LastElementIndex; /** * Get the sort element for the given sort key. Allocates a new entry if one does not exist * * @param DepthSortKey - the key used to find the sort element entry * @return sort element entry */ FCanvasSortElement& GetSortElement(int32 DepthSortKey); }; /** * Base interface for canvas items which can be batched for rendering */ class FCanvasBaseRenderItem { public: virtual ~FCanvasBaseRenderItem() {} /** * Renders the canvas item * * @param Canvas - canvas currently being rendered * @param RHICmdList - command list to use * @return true if anything rendered */ virtual bool Render_RenderThread(FRHICommandListImmediate& RHICmdList, const FCanvas* Canvas) = 0; /** * Renders the canvas item * * @param Canvas - canvas currently being rendered * @return true if anything rendered */ virtual bool Render_GameThread(const FCanvas* Canvas) = 0; /** * FCanvasBatchedElementRenderItem instance accessor * * @return FCanvasBatchedElementRenderItem instance */ virtual class FCanvasBatchedElementRenderItem* GetCanvasBatchedElementRenderItem() { return NULL; } /** * FCanvasTileRendererItem instance accessor * * @return FCanvasTileRendererItem instance */ virtual class FCanvasTileRendererItem* GetCanvasTileRendererItem() { return NULL; } /** * FCanvasTriangleRendererItem instance accessor * * @return FCanvasTriangleRendererItem instance */ virtual class FCanvasTriangleRendererItem* GetCanvasTriangleRendererItem() { return NULL; } }; /** * Info needed to render a batched element set */ class FCanvasBatchedElementRenderItem : public FCanvasBaseRenderItem { public: /** * Init constructor */ FCanvasBatchedElementRenderItem( FBatchedElementParameters* InBatchedElementParameters=NULL, const FTexture* InTexture=NULL, ESimpleElementBlendMode InBlendMode=SE_BLEND_MAX, FCanvas::EElementType InElementType=FCanvas::ET_MAX, const FCanvas::FTransformEntry& InTransform=FCanvas::FTransformEntry(FMatrix::Identity), const FDepthFieldGlowInfo& InGlowInfo=FDepthFieldGlowInfo() ) // this data is deleted after rendering has completed : Data(new FRenderData(InBatchedElementParameters, InTexture, InBlendMode, InElementType, InTransform, InGlowInfo)) {} /** * Destructor to delete data in case nothing rendered */ virtual ~FCanvasBatchedElementRenderItem() { delete Data; } /** * FCanvasBatchedElementRenderItem instance accessor * * @return this instance */ virtual class FCanvasBatchedElementRenderItem* GetCanvasBatchedElementRenderItem() override { return this; } /** * Renders the canvas item. * Iterates over all batched elements and draws them with their own transforms * * @param Canvas - canvas currently being rendered * @param RHICmdList - command list to use * @return true if anything rendered */ virtual bool Render_RenderThread(FRHICommandListImmediate& RHICmdList, const FCanvas* Canvas) override; /** * Renders the canvas item. * Iterates over all batched elements and draws them with their own transforms * * @param Canvas - canvas currently being rendered * @return true if anything rendered */ virtual bool Render_GameThread(const FCanvas* Canvas) override; /** * Determine if this is a matching set by comparing texture,blendmode,elementype,transform. All must match * * @param BatchedElementParameters - parameters for this batched element * @param InTexture - texture resource for the item being rendered * @param InBlendMode - current alpha blend mode * @param InElementType - type of item being rendered: triangle,line,etc * @param InTransform - the transform for the item being rendered * @param InGlowInfo - the depth field glow of the item being rendered * @return true if the parameters match this render item */ bool IsMatch(FBatchedElementParameters* BatchedElementParameters, const FTexture* InTexture, ESimpleElementBlendMode InBlendMode, FCanvas::EElementType InElementType, const FCanvas::FTransformEntry& InTransform, const FDepthFieldGlowInfo& InGlowInfo) { return( Data->BatchedElementParameters.GetReference() == BatchedElementParameters && Data->Texture == InTexture && Data->BlendMode == InBlendMode && Data->ElementType == InElementType && Data->Transform.GetMatrixCRC() == InTransform.GetMatrixCRC() && Data->GlowInfo == InGlowInfo ); } /** * Accessor for the batched elements. This can be used for adding triangles and primitives to the batched elements * * @return pointer to batched elements struct */ FORCEINLINE FBatchedElements* GetBatchedElements() { return &Data->BatchedElements; } private: class FRenderData { public: /** * Init constructor */ FRenderData( FBatchedElementParameters* InBatchedElementParameters=NULL, const FTexture* InTexture=NULL, ESimpleElementBlendMode InBlendMode=SE_BLEND_MAX, FCanvas::EElementType InElementType=FCanvas::ET_MAX, const FCanvas::FTransformEntry& InTransform=FCanvas::FTransformEntry(FMatrix::Identity), const FDepthFieldGlowInfo& InGlowInfo=FDepthFieldGlowInfo() ) : BatchedElementParameters(InBatchedElementParameters) , Texture(InTexture) , BlendMode(InBlendMode) , ElementType(InElementType) , Transform(InTransform) , GlowInfo(InGlowInfo) {} /** Current batched elements, destroyed once rendering completes. */ FBatchedElements BatchedElements; /** Batched element parameters */ TRefCountPtr<FBatchedElementParameters> BatchedElementParameters; /** Current texture being used for batching, set to NULL if it hasn't been used yet. */ const FTexture* Texture; /** Current blend mode being used for batching, set to BLEND_MAX if it hasn't been used yet. */ ESimpleElementBlendMode BlendMode; /** Current element type being used for batching, set to ET_MAX if it hasn't been used yet. */ FCanvas::EElementType ElementType; /** Transform used to render including projection */ FCanvas::FTransformEntry Transform; /** info for optional glow effect when using depth field rendering */ FDepthFieldGlowInfo GlowInfo; }; /** * Render data which is allocated when a new FCanvasBatchedElementRenderItem is added for rendering. * This data is only freed on the rendering thread once the item has finished rendering */ FRenderData* Data; }; /** * Info needed to render a single FTileRenderer */ class FCanvasTileRendererItem : public FCanvasBaseRenderItem { public: /** * Init constructor */ FCanvasTileRendererItem( const FMaterialRenderProxy* InMaterialRenderProxy=NULL, const FCanvas::FTransformEntry& InTransform=FCanvas::FTransformEntry(FMatrix::Identity), bool bInFreezeTime=false) // this data is deleted after rendering has completed : Data(new FRenderData(InMaterialRenderProxy,InTransform)) , bFreezeTime(bInFreezeTime) {} /** * Destructor to delete data in case nothing rendered */ virtual ~FCanvasTileRendererItem() { delete Data; } /** * FCanvasTileRendererItem instance accessor * * @return this instance */ virtual class FCanvasTileRendererItem* GetCanvasTileRendererItem() override { return this; } /** * Renders the canvas item. * Iterates over each tile to be rendered and draws it with its own transforms * * @param Canvas - canvas currently being rendered * @param RHICmdList - command list to use * @return true if anything rendered */ virtual bool Render_RenderThread(FRHICommandListImmediate& RHICmdList, const FCanvas* Canvas) override; /** * Renders the canvas item. * Iterates over each tile to be rendered and draws it with its own transforms * * @param Canvas - canvas currently being rendered * @return true if anything rendered */ virtual bool Render_GameThread(const FCanvas* Canvas) override; /** * Determine if this is a matching set by comparing material,transform. All must match * * @param IInMaterialRenderProxy - material proxy resource for the item being rendered * @param InTransform - the transform for the item being rendered * @return true if the parameters match this render item */ bool IsMatch( const FMaterialRenderProxy* InMaterialRenderProxy, const FCanvas::FTransformEntry& InTransform ) { return( Data->MaterialRenderProxy == InMaterialRenderProxy && Data->Transform.GetMatrixCRC() == InTransform.GetMatrixCRC() ); }; /** * Add a new tile to the render data. These tiles all use the same transform and material proxy * * @param X - tile X offset * @param Y - tile Y offset * @param SizeX - tile X size * @param SizeY - tile Y size * @param U - tile U offset * @param V - tile V offset * @param SizeU - tile U size * @param SizeV - tile V size * @param return number of tiles added */ FORCEINLINE int32 AddTile(float X,float Y,float SizeX,float SizeY,float U,float V,float SizeU,float SizeV,FHitProxyId HitProxyId,FColor InColor) { return Data->AddTile(X,Y,SizeX,SizeY,U,V,SizeU,SizeV,HitProxyId,InColor); }; private: class FRenderData { public: FRenderData( const FMaterialRenderProxy* InMaterialRenderProxy=NULL, const FCanvas::FTransformEntry& InTransform=FCanvas::FTransformEntry(FMatrix::Identity) ) : MaterialRenderProxy(InMaterialRenderProxy) , Transform(InTransform) {} const FMaterialRenderProxy* MaterialRenderProxy; FCanvas::FTransformEntry Transform; struct FTileInst { float X,Y; float SizeX,SizeY; float U,V; float SizeU,SizeV; FHitProxyId HitProxyId; FColor InColor; }; TArray<FTileInst> Tiles; FORCEINLINE int32 AddTile(float X, float Y, float SizeX, float SizeY, float U, float V, float SizeU, float SizeV, FHitProxyId HitProxyId, FColor InColor) { FTileInst NewTile = {X,Y,SizeX,SizeY,U,V,SizeU,SizeV,HitProxyId,InColor}; return Tiles.Add(NewTile); }; }; /** * Render data which is allocated when a new FCanvasTileRendererItem is added for rendering. * This data is only freed on the rendering thread once the item has finished rendering */ FRenderData* Data; const bool bFreezeTime; }; /** * Info needed to render a single FTriangleRenderer */ class FCanvasTriangleRendererItem : public FCanvasBaseRenderItem { public: /** * Init constructor */ FCanvasTriangleRendererItem( const FMaterialRenderProxy* InMaterialRenderProxy = NULL, const FCanvas::FTransformEntry& InTransform = FCanvas::FTransformEntry(FMatrix::Identity), bool bInFreezeTime = false) // this data is deleted after rendering has completed : Data(new FRenderData(InMaterialRenderProxy, InTransform)) , bFreezeTime(bInFreezeTime) {} /** * Destructor to delete data in case nothing rendered */ virtual ~FCanvasTriangleRendererItem() { delete Data; } /** * FCanvasTriangleRendererItem instance accessor * * @return this instance */ virtual class FCanvasTriangleRendererItem* GetCanvasTriangleRendererItem() override { return this; } /** * Renders the canvas item. * Iterates over each triangle to be rendered and draws it with its own transforms * * @param Canvas - canvas currently being rendered * @param RHICmdList - command list to use * @return true if anything rendered */ virtual bool Render_RenderThread(FRHICommandListImmediate& RHICmdList, const FCanvas* Canvas) override; /** * Renders the canvas item. * Iterates over each triangle to be rendered and draws it with its own transforms * * @param Canvas - canvas currently being rendered * @return true if anything rendered */ virtual bool Render_GameThread(const FCanvas* Canvas) override; /** * Determine if this is a matching set by comparing material,transform. All must match * * @param IInMaterialRenderProxy - material proxy resource for the item being rendered * @param InTransform - the transform for the item being rendered * @return true if the parameters match this render item */ bool IsMatch(const FMaterialRenderProxy* InMaterialRenderProxy, const FCanvas::FTransformEntry& InTransform) { return(Data->MaterialRenderProxy == InMaterialRenderProxy && Data->Transform.GetMatrixCRC() == InTransform.GetMatrixCRC()); }; /** * Add a new triangle to the render data. These triangles all use the same transform and material proxy * * @param return number of triangles added */ FORCEINLINE int32 AddTriangle(const FCanvasUVTri& Tri, FHitProxyId HitProxyId) { return Data->AddTriangle(Tri, HitProxyId); }; private: class FRenderData { public: FRenderData( const FMaterialRenderProxy* InMaterialRenderProxy = NULL, const FCanvas::FTransformEntry& InTransform = FCanvas::FTransformEntry(FMatrix::Identity)) : MaterialRenderProxy(InMaterialRenderProxy) , Transform(InTransform) {} const FMaterialRenderProxy* MaterialRenderProxy; FCanvas::FTransformEntry Transform; struct FTriangleInst { FCanvasUVTri Tri; FHitProxyId HitProxyId; }; TArray<FTriangleInst> Triangles; FORCEINLINE int32 AddTriangle(const FCanvasUVTri& Tri, FHitProxyId HitProxyId) { FTriangleInst NewTri = { Tri, HitProxyId }; return Triangles.Add(NewTri); }; }; /** * Render data which is allocated when a new FCanvasTriangleRendererItem is added for rendering. * This data is only freed on the rendering thread once the item has finished rendering */ FRenderData* Data; const bool bFreezeTime; }; /** * Render string using both a font and a material. The material should have a font exposed as a * parameter so that the correct font page can be set based on the character being drawn. * * @param Font - font containing texture pages of character glyphs * @param XL - out width * @param YL - out height * @param Text - string of text to be measured */ extern ENGINE_API void StringSize( const UFont* Font, int32& XL, int32& YL, const TCHAR* Text );
30.587436
275
0.744005
7479347904c9ff43cfacae9df695b2015da86801
780
h
C
SmartDeviceLink/private/SDLControlFramePayloadTransportEventUpdate.h
codelynx/sdl_ios
90317e17d408426547b4afed91620bc695a3279c
[ "BSD-3-Clause" ]
171
2015-01-13T14:17:29.000Z
2022-03-18T19:55:24.000Z
SmartDeviceLink/private/SDLControlFramePayloadTransportEventUpdate.h
codelynx/sdl_ios
90317e17d408426547b4afed91620bc695a3279c
[ "BSD-3-Clause" ]
1,524
2015-01-16T14:31:10.000Z
2022-03-30T14:37:02.000Z
SmartDeviceLink/private/SDLControlFramePayloadTransportEventUpdate.h
codelynx/sdl_ios
90317e17d408426547b4afed91620bc695a3279c
[ "BSD-3-Clause" ]
129
2015-01-15T19:27:18.000Z
2021-11-26T01:49:12.000Z
// // SDLControlFramePayloadTransportEventUpdate.h // SmartDeviceLink-iOS // // Created by Sho Amano on 2018/03/05. // Copyright © 2018 Xevo Inc. All rights reserved. // #import <Foundation/Foundation.h> #import "SDLControlFramePayloadType.h" NS_ASSUME_NONNULL_BEGIN @interface SDLControlFramePayloadTransportEventUpdate : NSObject <SDLControlFramePayloadType> /** A string representing IP address of Core's TCP transport. It can be either IPv4 or IPv6 address. */ @property (copy, nonatomic, readonly, nullable) NSString *tcpIpAddress; /** TCP port number that Core is listening on */ @property (assign, nonatomic, readonly) int32_t tcpPort; - (instancetype)initWithTcpIpAddress:(nullable NSString *)tcpIpAddress tcpPort:(int32_t)tcpPort; @end NS_ASSUME_NONNULL_END
27.857143
103
0.783333
dac88c1c84d9c5c59d8c40a622355bb19a00d497
3,234
h
C
OSE V2/OSE-Core/Logging.h
rexapex/OSE-V2-Game-Engine-
cbf8040d4b017275c073373f8438b227e691858d
[ "MIT" ]
1
2019-09-29T17:45:11.000Z
2019-09-29T17:45:11.000Z
OSE V2/OSE-Core/Logging.h
rexapex/OSE-V2-Game-Engine-
cbf8040d4b017275c073373f8438b227e691858d
[ "MIT" ]
10
2020-11-13T13:41:26.000Z
2020-11-16T18:46:57.000Z
OSE V2/OSE-Core/Logging.h
rexapex/OSE-Game-Engine
cbf8040d4b017275c073373f8438b227e691858d
[ "MIT" ]
null
null
null
#pragma once #include "OSE-Core/File System/FileSystemUtil.h" namespace ose { namespace logging { template <typename T> inline void LogToStream(std::ostream & stream, T t) { stream << t; } template <typename T, typename... Args> inline void LogToStream(std::ostream & stream, T t, Args... args) { stream << t << " "; LogToStream(stream, args...); } // Convenience method for output // Use \n instead of endl so the buffer isn't flushed with every log template <typename T, typename... Args> inline void Log(char const * filename, char const * line, char const * function, T t, Args... args) { #ifdef CONSOLE_LOGGING std::clog << "LOG : " << fs::GetRelativePath(filename, fs::GetParentPath(PROJECT_DIR)) << " : " << line << " : " << function << " : "; LogToStream(std::clog, t, args...); std::clog << "\n"; #endif // If debug build with console logging enabled, don't bother logging to file #if !defined(CONSOLE_LOGGING) || !defined(_DEBUG) // TODO - Log to file #endif } // Convenience method for output of error messages template <typename T, typename... Args> inline void LogError(char const * filename, char const * line, char const * function, T t, Args... args) { #ifdef CONSOLE_LOGGING std::cerr << "ERROR : " << fs::GetRelativePath(filename, fs::GetParentPath(PROJECT_DIR)) << " : " << line << " : " << function << " : "; LogToStream(std::cerr, t, args...); std::cerr << std::endl; #endif // If debug build with console logging enabled, don't bother logging to file #if !defined(CONSOLE_LOGGING) || !defined(_DEBUG) // TODO - Log to file #endif } // Convenience method for output in debug mode only template <typename T, typename... Args> inline void DebugLog(char const * filename, char const * line, char const * function, T t, Args... args) { #ifdef CONSOLE_LOGGING std::clog << "DEBUG : " << fs::GetRelativePath(filename, fs::GetParentPath(PROJECT_DIR)) << " : " << line << " : " << function << " : "; LogToStream(std::clog, t, args...); std::clog << std::endl; #endif // If debug build with console logging enabled, don't bother logging to file #if !defined(CONSOLE_LOGGING) || !defined(_DEBUG) // TODO - Log to file #endif } } } #ifndef PROJECT_DIR #error "PROJECT_DIR is not defined, add PROJECT_DIR=R"($(ProjectDir))"; as a preprocessor token" #endif #ifndef __FILE__ # define __FILE__ "#" #endif #ifndef __LINE__ # define __LINE__ "#" #endif #ifdef _MSC_VER # define __func__ __FUNCTION__ #endif #ifndef STR # define STR(x) #x #endif #ifndef TOSTR # define TOSTR(x) STR(x) #endif // Convenience method for output // Use \n instead of endl so the buffer isn't flushed with every log #define LOG(x, ...) ose::logging::Log(__FILE__, TOSTR(__LINE__), __func__, x, ##__VA_ARGS__) // Convenience method for output of error messages #define LOG_ERROR(x, ...) ose::logging::LogError(__FILE__, TOSTR(__LINE__), __func__, x, ##__VA_ARGS__) #ifdef _WIN32 # ifdef _DEBUG # define DEBUG_LOG(x, ...) ose::logging::DebugLog(__FILE__, TOSTR(__LINE__), __func__, x, ##__VA_ARGS__) # else # define DEBUG_LOG(x, ...) do {} while(0) # endif // _DEBUG #else # define DEBUG_LOG(x, ...) do {} while(0) #endif // _WIN32
30.224299
139
0.66543
74f4912bd650974c74cb56e7cb09cf79b57beead
1,504
h
C
ash/wm/desks/desk_name_view.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ash/wm/desks/desk_name_view.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
ash/wm/desks/desk_name_view.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_DESKS_DESK_NAME_VIEW_H_ #define ASH_WM_DESKS_DESK_NAME_VIEW_H_ #include "ash/ash_export.h" #include "ash/wm/desks/desks_textfield.h" #include "ui/base/metadata/metadata_header_macros.h" namespace ash { class DeskMiniView; // Defines a textfield styled to normally look like a label. Allows modifying // the name of its corresponding desk. // When Bento is enabled and the user creates a new desk, the accessible name // for `this` will be the default desk name. class ASH_EXPORT DeskNameView : public DesksTextfield { public: METADATA_HEADER(DeskNameView); explicit DeskNameView(DeskMiniView* mini_view); DeskNameView(const DeskNameView&) = delete; DeskNameView& operator=(const DeskNameView&) = delete; ~DeskNameView() override; // Commits an on-going desk name change (if any) by bluring the focus away // from any view on |widget|, where |widget| should be the desks bar widget. static void CommitChanges(views::Widget* widget); // DesksTextfield: void OnViewHighlighted() override; private: // The mini view that associated with this name view. DeskMiniView* const mini_view_; }; BEGIN_VIEW_BUILDER(/* no export */, DeskNameView, DesksTextfield) END_VIEW_BUILDER } // namespace ash DEFINE_VIEW_BUILDER(/* no export */, ash::DeskNameView) #endif // ASH_WM_DESKS_DESK_NAME_VIEW_H_
30.693878
78
0.765293
97c84ac436725b4fa889333f22f6316f43f03d2f
884
c
C
defines.c
hyphenrf/sea
3e4aa213a39d71a10e1de4162c3166212a626c37
[ "Unlicense" ]
null
null
null
defines.c
hyphenrf/sea
3e4aa213a39d71a10e1de4162c3166212a626c37
[ "Unlicense" ]
null
null
null
defines.c
hyphenrf/sea
3e4aa213a39d71a10e1de4162c3166212a626c37
[ "Unlicense" ]
null
null
null
#include <stdio.h> #include "defines.h" /* nonstandard includes are quoted instead of using angle * brackets. Those header files are expected to be found * in the working directory where the compilation happens * you may include headers in subdirs as well. */ int globalVariable = 10; // globals must be assigned at declaration // assigning is often referred to as initialization when done first time int main() { int declaredLocal; // only local variables can be declared empty declaredLocal = 5; printf("PI, imported from defines.h: %.2f\n\ globalVariable, accessed by all funcs: %d\n\ another way to assign vars is declare in a \n\ line then assign in another. Like declaredLocal: %d\n", PI, globalVariable, declaredLocal); int x = 5/2.0; // type int to float will discard any fractions printf("%.2f\n",(float) x); // (type) casting return 0; }
29.466667
91
0.717195
5ad29a25234c94af3e25075b60b078c3639cdd5e
208
h
C
src/util/util_time.h
miniupnp/sundog
eb48447d1791e8bbd9ce4afe872a541dc67fcca1
[ "MIT" ]
54
2017-01-31T08:14:04.000Z
2022-03-18T23:26:35.000Z
src/util/util_time.h
miniupnp/sundog
eb48447d1791e8bbd9ce4afe872a541dc67fcca1
[ "MIT" ]
9
2018-02-25T15:28:55.000Z
2021-10-15T14:29:44.000Z
src/util/util_time.h
miniupnp/sundog
eb48447d1791e8bbd9ce4afe872a541dc67fcca1
[ "MIT" ]
13
2017-01-29T12:38:26.000Z
2021-12-22T23:57:35.000Z
#ifndef H_UTIL_TIME #define H_UTIL_TIME #ifdef __cplusplus extern "C" { #endif /* Sleep for a specified number of milli-seconds */ unsigned int msleep(unsigned int ms); #ifdef __cplusplus } #endif #endif
13
51
0.75
e386a967d2887befdedfa485718a1a71d3db766f
196
h
C
killable.h
pallas/liboco
e67af0343f5e0bf76405313af736272b7e971f6a
[ "Zlib" ]
null
null
null
killable.h
pallas/liboco
e67af0343f5e0bf76405313af736272b7e971f6a
[ "Zlib" ]
null
null
null
killable.h
pallas/liboco
e67af0343f5e0bf76405313af736272b7e971f6a
[ "Zlib" ]
3
2021-03-04T06:27:00.000Z
2021-03-04T06:27:14.000Z
#ifndef KILLABLE_H #define KILLABLE_H class killable { public: killable(); void kill(); bool dead() const; protected: virtual void die(); private: bool dead_; }; #endif//KILLABLE_H
10.315789
21
0.683673
5a6eb20042c471b59cfdba91e1fa16c9c9226610
34,976
c
C
sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56780_a0/ina_2_4_13/bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_template_map.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56780_a0/ina_2_4_13/bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_template_map.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/libs/sdklt/bcmlrd/chip/bcm56780_a0/ina_2_4_13/bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_template_map.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/******************************************************************************* * * DO NOT EDIT THIS FILE! * This file is auto-generated by fltg from * INTERNAL/fltg/xgs/npl/bcm56780_a0/ina_2_4_13/bcm56780_a0_ina_2_4_13_DT_IFP_PRESEL_GRP_TEMPLATE.map.ltl for * bcm56780_a0 variant ina_2_4_13 * * Tool: $SDK/INTERNAL/fltg/bin/fltg * * Edits to this file will be lost when it is regenerated. * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #include <bcmlrd/bcmlrd_internal.h> #include <bcmlrd/chip/bcmlrd_id.h> #include <bcmlrd/chip/bcm56780_a0/ina_2_4_13/bcm56780_a0_ina_2_4_13_lrd_field_data.h> #include <bcmlrd/chip/bcm56780_a0/bcm56780_a0_lrd_ltm_intf.h> #include <bcmlrd/chip/bcm56780_a0/ina_2_4_13/bcm56780_a0_ina_2_4_13_lrd_ltm_intf.h> #include <bcmlrd/chip/bcm56780_a0/ina_2_4_13/bcm56780_a0_ina_2_4_13_lrd_xfrm_field_desc.h> #include <bcmdrd/chip/bcm56780_a0_enum.h> #include "bcmltd/chip/bcmltd_common_enumpool.h" #include "../bcm56780_a0_lrd_enumpool.h" #include "bcm56780_a0_ina_2_4_13_lrd_enumpool.h" #include <bcmltd/bcmltd_handler.h> /* DT_IFP_PRESEL_GRP_TEMPLATE field init */ static const bcmlrd_field_data_t bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_template_map_field_data_mmd[] = { { /* 0 DT_IFP_PRESEL_GRP_TEMPLATE_INDEX */ .flags = BCMLTD_FIELD_F_KEY, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u32_0x1, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u32_0x1, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u32_0x6, .depth = 0, .width = 3, .edata = NULL, }, { /* 1 ING_CMD_BUS_L2_IIF_OPAQUE_CTRL_ID */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 2 ING_CMD_BUS_L3_IIF_OPAQUE_CTRL_ID */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 3 ING_CMD_BUS_PROTOCOL_PKT_OPAQUE_CTRL_ID */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 4 ING_CMD_BUS_VFI_OPAQUE_CTRL_ID */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 5 ING_CMD_BUS_SVP_OPAQUE_CTRL_ID */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 6 ING_CMD_BUS_DEVICE_PORT_TYPE */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 7 ING_CMD_BUS_DEVICE_PORT_OPAQUE_CMD1 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 8 ING_CMD_BUS_HG3_FLAGS */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 9 ING_CMD_BUS_SYSTEM_OPCODE */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 10 ING_CMD_BUS_LOOPBACK_HDR_TYPE */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 11 ING_CMD_BUS_LOOPBACK_HDR_FLAGS */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 12 ING_CMD_BUS_L2L3_RESOLVED_HIT_STATUS */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 13 ING_CMD_BUS_PKT_STATUS */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 14 ING_CMD_BUS_FORWARDING_STATUS */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 15 ING_CMD_BUS_PKT_FLOW_0 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 16 ING_CMD_BUS_DESTINATION_TYPE */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 17 ING_CMD_BUS_FIXED_HVE_RESULT_SET_0 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 18 ING_CMD_BUS_FIXED_HVE_RESULT_SET_1 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 19 ING_CMD_BUS_FLEX_HVE_RESULT_SET_1 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 20 ING_CMD_BUS_NUM_OF_FWD_EXT_HEADERS */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x3, .depth = 0, .width = 2, .edata = NULL, }, { /* 21 ING_CMD_BUS_SPANNING_TREE_STATE */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x3, .depth = 0, .width = 2, .edata = NULL, }, { /* 22 ING_CMD_BUS_MY_STATION_1_HIT */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 23 ING_CMD_BUS_MY_STATION_HIT */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 24 ING_CMD_BUS_PKT_MISC_CTRL_0 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 25 ING_CMD_BUS_TUNNEL_PROCESSING_RESULTS_1 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 26 ING_CMD_BUS_LEARN_COMMANDS */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 27 ING_CMD_BUS_L2_SRC_MISC_CTRL_1 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 28 ING_CMD_BUS_L4_VALID */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 29 ING_CMD_BUS_L3_CHECK_L2_INTERFACE_MATCHED */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, { /* 30 INGRESS_PKT_OUTER_L2_HDR_VNTAG */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 31 INGRESS_PKT_SYS_HDR_LOOPBACK */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 32 INGRESS_PKT_OUTER_L3_L4_HDR_GRE_ROUT */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 33 INGRESS_PKT_INNER_L3_L4_HDR_TCP_FIRST_4BYTES */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 34 INGRESS_PKT_INNER_L3_L4_HDR_P_1588 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 35 INGRESS_PKT_OUTER_L3_L4_HDR_RARP */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 36 INGRESS_PKT_OUTER_L3_L4_HDR_AUTH_EXT_2 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 37 INGRESS_PKT_OUTER_L2_HDR_ITAG */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 38 INGRESS_PKT_OUTER_L3_L4_HDR_AUTH_EXT_1 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 39 INGRESS_PKT_OUTER_L3_L4_HDR_UNKNOWN_L3 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 40 INGRESS_PKT_OUTER_L3_L4_HDR_MPLS4 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 41 INGRESS_PKT_INNER_L3_L4_HDR_FRAG_EXT_1 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 42 INGRESS_PKT_INNER_L3_L4_HDR_ETHERTYPE */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 43 INGRESS_PKT_OUTER_L3_L4_HDR_MPLS5 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 44 INGRESS_PKT_INNER_L2_HDR_OTAG */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 45 INGRESS_PKT_OUTER_L3_L4_HDR_TCP_FIRST_4BYTES */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 46 INGRESS_PKT_INNER_L2_HDR_ETAG */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 47 INGRESS_PKT_INNER_L3_L4_HDR_IPV6 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 48 INGRESS_PKT_OUTER_L2_HDR_HG3_EXT_0 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 49 INGRESS_PKT_INNER_L3_L4_HDR_ESP_EXT */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 50 INGRESS_PKT_INNER_L3_L4_HDR_FRAG_EXT_2 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 51 INGRESS_PKT_INNER_L3_L4_HDR_UDP */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 52 INGRESS_PKT_OUTER_L3_L4_HDR_IGMP */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 53 INGRESS_PKT_INNER_L2_HDR_SNAP_OR_LLC */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 54 INGRESS_PKT_OUTER_L3_L4_HDR_ARP */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 55 INGRESS_PKT_INNER_L3_L4_HDR_IGMP */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 56 INGRESS_PKT_OUTER_L3_L4_HDR_MPLS3 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 57 INGRESS_PKT_INNER_L3_L4_HDR_ARP */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 58 INGRESS_PKT_OUTER_L3_L4_HDR_MPLS2 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 59 INGRESS_PKT_OUTER_L3_L4_HDR_MPLS0 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 60 INGRESS_PKT_INNER_L2_HDR_VNTAG */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 61 INGRESS_PKT_INNER_L3_L4_HDR_RARP */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 62 INGRESS_PKT_INNER_L3_L4_HDR_ICMP */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 63 INGRESS_PKT_OUTER_L3_L4_HDR_GPE */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 64 INGRESS_PKT_INNER_L2_HDR_ITAG */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 65 INGRESS_PKT_INNER_L3_L4_HDR_AUTH_EXT_1 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 66 INGRESS_PKT_OUTER_L3_L4_HDR_ESP_EXT */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 67 INGRESS_PKT_OUTER_L2_HDR_SNAP_OR_LLC */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 68 INGRESS_PKT_OUTER_L3_L4_HDR_P_1588 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 69 INGRESS_PKT_OUTER_L3_L4_HDR_FRAG_EXT_2 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 70 INGRESS_PKT_INNER_L2_HDR_L2 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 71 INGRESS_PKT_INNER_L3_L4_HDR_UNKNOWN_L4 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 72 INGRESS_PKT_OUTER_L3_L4_HDR_UNKNOWN_L4 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 73 INGRESS_PKT_OUTER_L3_L4_HDR_GRE_CHKSUM */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 74 INGRESS_PKT_OUTER_L3_L4_HDR_UNKNOWN_L5 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 75 INGRESS_PKT_OUTER_L2_HDR_L2 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 76 INGRESS_PKT_OUTER_L3_L4_HDR_VXLAN */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 77 INGRESS_PKT_OUTER_L2_HDR_OTAG */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 78 INGRESS_PKT_INNER_L3_L4_HDR_UNKNOWN_L3 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 79 INGRESS_PKT_OUTER_L3_L4_HDR_UDP */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 80 INGRESS_PKT_INNER_L3_L4_HDR_BFD */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 81 INGRESS_PKT_OUTER_L3_L4_HDR_MPLS1 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 82 INGRESS_PKT_SYS_HDR_EP_NIH */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 83 INGRESS_PKT_INNER_L3_L4_HDR_TCP_LAST_16BYTES */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 84 INGRESS_PKT_OUTER_L2_HDR_ETAG */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 85 INGRESS_PKT_OUTER_L2_HDR_HG3_BASE */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 86 INGRESS_PKT_INNER_L3_L4_HDR_IPV4 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 87 INGRESS_PKT_INNER_L3_L4_HDR_AUTH_EXT_2 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 88 INGRESS_PKT_OUTER_L3_L4_HDR_IFA_HEADER */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 89 INGRESS_PKT_OUTER_L3_L4_HDR_MPLS6 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 90 INGRESS_PKT_OUTER_L3_L4_HDR_FRAG_EXT_1 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 91 INGRESS_PKT_OUTER_L3_L4_HDR_IPV4 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 92 INGRESS_PKT_OUTER_L3_L4_HDR_ICMP */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 93 INGRESS_PKT_INNER_L3_L4_HDR_UNKNOWN_L5 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 94 INGRESS_PKT_OUTER_L3_L4_HDR_GRE */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 95 INGRESS_PKT_OUTER_L3_L4_HDR_IPV6 */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 96 INGRESS_PKT_OUTER_L3_L4_HDR_BFD */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 97 INGRESS_PKT_OUTER_L3_L4_HDR_MPLS_CW */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 98 INGRESS_PKT_OUTER_L3_L4_HDR_ETHERTYPE */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 99 INGRESS_PKT_OUTER_L3_L4_HDR_MPLS_ACH */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 100 INGRESS_PKT_OUTER_L3_L4_HDR_GRE_KEY */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 101 INGRESS_PKT_OUTER_L3_L4_HDR_GRE_SEQ */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 102 INGRESS_PKT_OUTER_L3_L4_HDR_TCP_LAST_16BYTES */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_is_true_0x1, .depth = 0, .width = 1, .edata = NULL, }, { /* 103 DROP_DECISION */ .flags = 0, .min = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .def = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0x0, .max = &bcm56780_a0_ina_2_4_13_lrd_ifd_u8_0xf, .depth = 0, .width = 4, .edata = NULL, }, }; const bcmlrd_map_field_data_t bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_template_map_field_data = { .fields = 104, .field = bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_template_map_field_data_mmd }; static const bcmlrd_map_table_attr_t bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_templatet_attr_entry[] = { { /* 0 */ .key = BCMLRD_MAP_TABLE_ATTRIBUTE_ENTRY_LIMIT, .value = 6, }, { /* 1 */ .key = BCMLRD_MAP_TABLE_ATTRIBUTE_INTERACTIVE, .value = FALSE, }, }; static const bcmlrd_map_attr_t bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_templatet_attr_group = { .attributes = 2, .attr = bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_templatet_attr_entry, }; static const bcmlrd_map_entry_t bcm56780_a0_ina_2_4_13_lrd_bcmimm_dt_ifp_presel_grp_template_entry[] = { { /* 0 */ .entry_type = BCMLRD_MAP_ENTRY_TABLE_HANDLER, .desc = { .field_id = 0, .field_idx = 0, .minbit = 0, .maxbit = 0, .entry_idx = 0, .reserved = 0 }, .u = { /* handler: bcm56780_a0_ina_2_4_13_lta_bcmimm_dt_ifp_presel_grp_template_cth_handler */ .handler_id = BCMLTD_TABLE_BCM56780_A0_INA_2_4_13_LTA_BCMIMM_DT_IFP_PRESEL_GRP_TEMPLATE_CTH_HANDLER_ID } }, }; static const bcmlrd_map_group_t bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_template_map_group[] = { { .dest = { .kind = BCMLRD_MAP_CUSTOM, .id = 0, }, .entries = 1, .entry = bcm56780_a0_ina_2_4_13_lrd_bcmimm_dt_ifp_presel_grp_template_entry }, }; const bcmlrd_map_t bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_template_map = { .src_id = BCM56780_A0_INA_2_4_13_DT_IFP_PRESEL_GRP_TEMPLATEt, .field_data = &bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_template_map_field_data, .groups = 1, .group = bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_template_map_group, .table_attr = &bcm56780_a0_ina_2_4_13_lrd_dt_ifp_presel_grp_templatet_attr_group, .entry_ops = BCMLRD_MAP_TABLE_ENTRY_OPERATION_LOOKUP | BCMLRD_MAP_TABLE_ENTRY_OPERATION_TRAVERSE | BCMLRD_MAP_TABLE_ENTRY_OPERATION_INSERT | BCMLRD_MAP_TABLE_ENTRY_OPERATION_UPDATE | BCMLRD_MAP_TABLE_ENTRY_OPERATION_DELETE };
34.223092
226
0.651733
0c5e24805b874cf860d3abba9deb72c1707e4811
2,895
h
C
src/include/gurt/atomic.h
wli5/daos
92d8839007749770fc5aa612d9ab7ab4cc293f45
[ "Apache-2.0" ]
1
2021-12-04T14:57:48.000Z
2021-12-04T14:57:48.000Z
src/include/gurt/atomic.h
wli5/daos
92d8839007749770fc5aa612d9ab7ab4cc293f45
[ "Apache-2.0" ]
1
2020-01-14T18:47:07.000Z
2020-01-14T18:47:07.000Z
src/include/gurt/atomic.h
wli5/daos
92d8839007749770fc5aa612d9ab7ab4cc293f45
[ "Apache-2.0" ]
null
null
null
/* * (C) Copyright 2017-2020 Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * GOVERNMENT LICENSE RIGHTS-OPEN SOURCE SOFTWARE * The Government's rights to use, modify, reproduce, release, perform, display, * or disclose this software are subject to the terms of the Apache License as * provided in Contract No. 8F-30005. * Any reproduction of computer software, computer software documentation, or * portions thereof marked with this legend must also reproduce the markings. */ /* * Atomic directives */ #ifndef __GURT_ATOMIC_H__ #define __GURT_ATOMIC_H__ #if HAVE_STDATOMIC #include <stdatomic.h> #ifdef __INTEL_COMPILER #define ATOMIC volatile #else #define ATOMIC _Atomic #endif /* stdatomic interface for compare_and_exchange doesn't quite align */ #define atomic_compare_exchange(ptr, oldvalue, newvalue) \ atomic_compare_exchange_weak_explicit(ptr, &oldvalue, newvalue, \ memory_order_relaxed, memory_order_relaxed) #define atomic_store_release(ptr, value) \ atomic_store_explicit(ptr, value, memory_order_release) #define atomic_store_relaxed(ptr, value) \ atomic_store_explicit(ptr, value, memory_order_relaxed) #define atomic_load_relaxed(ptr) atomic_load_explicit(ptr, memory_order_relaxed) #define atomic_fetch_sub_relaxed(ptr, value) \ atomic_fetch_sub_explicit(ptr, value, memory_order_relaxed) #define atomic_fetch_add_relaxed(ptr, value) \ atomic_fetch_add_explicit(ptr, value, memory_order_relaxed) #else #define atomic_fetch_sub __sync_fetch_and_sub #define atomic_fetch_add __sync_fetch_and_add #define atomic_fetch_sub_relaxed __sync_fetch_and_sub #define atomic_fetch_add_relaxed __sync_fetch_and_add #define atomic_compare_exchange __sync_bool_compare_and_swap #define atomic_store_release(ptr, value) \ do { \ __sync_synchronize(); \ *(ptr) = (value); \ } while (0) #define atomic_store_relaxed(ptr, value) atomic_store_release(ptr, value) /* There doesn't seem to be a great option here to mimic just * consume. Adding 0 should suffice for the load side. If * the compiler is smart, it could potentially avoid the * actual synchronization after the store as the store isn't * required. */ #define atomic_load_consume(ptr) atomic_fetch_add(ptr, 0) #define atomic_load_relaxed(ptr) atomic_fetch_add(ptr, 0) #define ATOMIC #endif #endif /* __GURT_ATOMIC_H__ */
34.879518
80
0.777547
8cdcd3ce3f7b6bcd51257c3bf540f7ab5b919cb6
131,163
c
C
render.c
kzwkt/foot
94f0b7283a4fba57788c753380afe1fc752351de
[ "MIT" ]
null
null
null
render.c
kzwkt/foot
94f0b7283a4fba57788c753380afe1fc752351de
[ "MIT" ]
null
null
null
render.c
kzwkt/foot
94f0b7283a4fba57788c753380afe1fc752351de
[ "MIT" ]
null
null
null
#include "render.h" #include <string.h> #include <wctype.h> #include <unistd.h> #include <signal.h> #include <sys/ioctl.h> #include <sys/time.h> #include <sys/timerfd.h> #include <sys/epoll.h> #include <pthread.h> #include "macros.h" #if HAS_INCLUDE(<pthread_np.h>) #include <pthread_np.h> #define pthread_setname_np(thread, name) (pthread_set_name_np(thread, name), 0) #elif defined(__NetBSD__) #define pthread_setname_np(thread, name) pthread_setname_np(thread, "%s", (void *)name) #endif #include <wayland-cursor.h> #include <xdg-shell.h> #include <presentation-time.h> #include <fcft/fcft.h> #define LOG_MODULE "render" #define LOG_ENABLE_DBG 0 #include "log.h" #include "box-drawing.h" #include "config.h" #include "grid.h" #include "hsl.h" #include "ime.h" #include "quirks.h" #include "selection.h" #include "shm.h" #include "sixel.h" #include "url-mode.h" #include "util.h" #include "xmalloc.h" #define TIME_SCROLL_DAMAGE 0 struct renderer { struct fdm *fdm; struct wayland *wayl; }; static struct { size_t total; size_t zero; /* commits presented in less than one frame interval */ size_t one; /* commits presented in one frame interval */ size_t two; /* commits presented in two or more frame intervals */ } presentation_statistics = {0}; static void fdm_hook_refresh_pending_terminals(struct fdm *fdm, void *data); struct renderer * render_init(struct fdm *fdm, struct wayland *wayl) { struct renderer *renderer = malloc(sizeof(*renderer)); if (unlikely(renderer == NULL)) { LOG_ERRNO("malloc() failed"); return NULL; } *renderer = (struct renderer) { .fdm = fdm, .wayl = wayl, }; if (!fdm_hook_add(fdm, &fdm_hook_refresh_pending_terminals, renderer, FDM_HOOK_PRIORITY_NORMAL)) { LOG_ERR("failed to register FDM hook"); free(renderer); return NULL; } return renderer; } void render_destroy(struct renderer *renderer) { if (renderer == NULL) return; fdm_hook_del(renderer->fdm, &fdm_hook_refresh_pending_terminals, FDM_HOOK_PRIORITY_NORMAL); free(renderer); } static void DESTRUCTOR log_presentation_statistics(void) { if (presentation_statistics.total == 0) return; const size_t total = presentation_statistics.total; LOG_INFO("presentation statistics: zero=%f%%, one=%f%%, two=%f%%", 100. * presentation_statistics.zero / total, 100. * presentation_statistics.one / total, 100. * presentation_statistics.two / total); } static void sync_output(void *data, struct wp_presentation_feedback *wp_presentation_feedback, struct wl_output *output) { } struct presentation_context { struct terminal *term; struct timeval input; struct timeval commit; }; static void presented(void *data, struct wp_presentation_feedback *wp_presentation_feedback, uint32_t tv_sec_hi, uint32_t tv_sec_lo, uint32_t tv_nsec, uint32_t refresh, uint32_t seq_hi, uint32_t seq_lo, uint32_t flags) { struct presentation_context *ctx = data; struct terminal *term = ctx->term; const struct timeval *input = &ctx->input; const struct timeval *commit = &ctx->commit; const struct timeval presented = { .tv_sec = (uint64_t)tv_sec_hi << 32 | tv_sec_lo, .tv_usec = tv_nsec / 1000, }; bool use_input = (input->tv_sec > 0 || input->tv_usec > 0) && timercmp(&presented, input, >); char msg[1024]; int chars = 0; if (use_input && timercmp(&presented, input, <)) return; else if (timercmp(&presented, commit, <)) return; LOG_DBG("commit: %lu s %lu µs, presented: %lu s %lu µs", commit->tv_sec, commit->tv_usec, presented.tv_sec, presented.tv_usec); if (use_input) { struct timeval diff; timersub(commit, input, &diff); chars += snprintf( &msg[chars], sizeof(msg) - chars, "input - %llu µs -> ", (unsigned long long)diff.tv_usec); } struct timeval diff; timersub(&presented, commit, &diff); chars += snprintf( &msg[chars], sizeof(msg) - chars, "commit - %llu µs -> ", (unsigned long long)diff.tv_usec); if (use_input) { xassert(timercmp(&presented, input, >)); timersub(&presented, input, &diff); } else { xassert(timercmp(&presented, commit, >)); timersub(&presented, commit, &diff); } chars += snprintf( &msg[chars], sizeof(msg) - chars, "presented (total: %llu µs)", (unsigned long long)diff.tv_usec); unsigned frame_count = 0; if (tll_length(term->window->on_outputs) > 0) { const struct monitor *mon = tll_front(term->window->on_outputs); frame_count = (diff.tv_sec * 1000000. + diff.tv_usec) / (1000000. / mon->refresh); } presentation_statistics.total++; if (frame_count >= 2) presentation_statistics.two++; else if (frame_count >= 1) presentation_statistics.one++; else presentation_statistics.zero++; #define _log_fmt "%s (more than %u frames)" if (frame_count >= 2) LOG_ERR(_log_fmt, msg, frame_count); else if (frame_count >= 1) LOG_WARN(_log_fmt, msg, frame_count); else LOG_INFO(_log_fmt, msg, frame_count); #undef _log_fmt wp_presentation_feedback_destroy(wp_presentation_feedback); free(ctx); } static void discarded(void *data, struct wp_presentation_feedback *wp_presentation_feedback) { struct presentation_context *ctx = data; wp_presentation_feedback_destroy(wp_presentation_feedback); free(ctx); } static const struct wp_presentation_feedback_listener presentation_feedback_listener = { .sync_output = &sync_output, .presented = &presented, .discarded = &discarded, }; static struct fcft_font * attrs_to_font(const struct terminal *term, const struct attributes *attrs) { int idx = attrs->italic << 1 | attrs->bold; return term->fonts[idx]; } static inline pixman_color_t color_hex_to_pixman_with_alpha(uint32_t color, uint16_t alpha) { return (pixman_color_t){ .red = ((color >> 16 & 0xff) | (color >> 8 & 0xff00)) * alpha / 0xffff, .green = ((color >> 8 & 0xff) | (color >> 0 & 0xff00)) * alpha / 0xffff, .blue = ((color >> 0 & 0xff) | (color << 8 & 0xff00)) * alpha / 0xffff, .alpha = alpha, }; } static inline pixman_color_t color_hex_to_pixman(uint32_t color) { /* Count on the compiler optimizing this */ return color_hex_to_pixman_with_alpha(color, 0xffff); } static inline uint32_t color_decrease_luminance(uint32_t color) { uint32_t alpha = color & 0xff000000; int hue, sat, lum; rgb_to_hsl(color, &hue, &sat, &lum); return alpha | hsl_to_rgb(hue, sat, lum / 1.5); } static inline uint32_t color_dim(const struct terminal *term, uint32_t color) { const struct config *conf = term->conf; const uint8_t custom_dim = conf->colors.use_custom.dim; if (likely(custom_dim == 0)) return color_decrease_luminance(color); for (size_t i = 0; i < 8; i++) { if (((custom_dim >> i) & 1) == 0) continue; if (term->colors.table[0 + i] == color) { /* “Regular” color, return the corresponding “dim” */ return conf->colors.dim[i]; } else if (term->colors.table[8 + i] == color) { /* “Bright” color, return the corresponding “regular” */ return term->colors.table[i]; } } return color_decrease_luminance(color); } static inline uint32_t color_brighten(const struct terminal *term, uint32_t color) { /* * First try to match the color against the base 8 colors. If we * find a match, return the corresponding bright color. */ if (term->conf->bold_in_bright.palette_based) { for (size_t i = 0; i < 8; i++) { if (term->colors.table[i] == color) return term->colors.table[i + 8]; } return color; } int hue, sat, lum; rgb_to_hsl(color, &hue, &sat, &lum); return hsl_to_rgb(hue, sat, min(100, lum * 1.3)); } static inline void color_dim_for_search(pixman_color_t *color) { color->red /= 2; color->green /= 2; color->blue /= 2; } static inline int font_baseline(const struct terminal *term) { return term->font_y_ofs + term->fonts[0]->ascent; } static void draw_unfocused_block(const struct terminal *term, pixman_image_t *pix, const pixman_color_t *color, int x, int y, int cell_cols) { const int scale = term->scale; const int width = min(min(scale, term->cell_width), term->cell_height); pixman_image_fill_rectangles( PIXMAN_OP_SRC, pix, color, 4, (pixman_rectangle16_t []){ {x, y, cell_cols * term->cell_width, width}, /* top */ {x, y, width, term->cell_height}, /* left */ {x + cell_cols * term->cell_width - width, y, width, term->cell_height}, /* right */ {x, y + term->cell_height - width, cell_cols * term->cell_width, width}, /* bottom */ }); } static void draw_beam_cursor(const struct terminal *term, pixman_image_t *pix, const struct fcft_font *font, const pixman_color_t *color, int x, int y) { int baseline = y + font_baseline(term) - term->fonts[0]->ascent; pixman_image_fill_rectangles( PIXMAN_OP_SRC, pix, color, 1, &(pixman_rectangle16_t){ x, baseline, term_pt_or_px_as_pixels(term, &term->conf->cursor.beam_thickness), term->fonts[0]->ascent + term->fonts[0]->descent}); } static void draw_underline_with_thickness( const struct terminal *term, pixman_image_t *pix, const struct fcft_font *font, const pixman_color_t *color, int x, int y, int cols, int thickness) { /* Make sure the line isn't positioned below the cell */ int y_ofs = font_baseline(term) - (term->conf->use_custom_underline_offset ? -term_pt_or_px_as_pixels(term, &term->conf->underline_offset) : font->underline.position); y_ofs = min(y_ofs, term->cell_height - thickness); pixman_image_fill_rectangles( PIXMAN_OP_SRC, pix, color, 1, &(pixman_rectangle16_t){ x, y + y_ofs, cols * term->cell_width, thickness}); } static void draw_underline_cursor(const struct terminal *term, pixman_image_t *pix, const struct fcft_font *font, const pixman_color_t *color, int x, int y, int cols) { int thickness = term->conf->cursor.underline_thickness.px >= 0 ? term_pt_or_px_as_pixels( term, &term->conf->cursor.underline_thickness) : font->underline.thickness; draw_underline_with_thickness( term, pix, font, color, x, y + font->underline.thickness, cols, thickness); } static void draw_underline(const struct terminal *term, pixman_image_t *pix, const struct fcft_font *font, const pixman_color_t *color, int x, int y, int cols) { draw_underline_with_thickness( term, pix, font, color, x, y, cols, font->underline.thickness); } static void draw_strikeout(const struct terminal *term, pixman_image_t *pix, const struct fcft_font *font, const pixman_color_t *color, int x, int y, int cols) { pixman_image_fill_rectangles( PIXMAN_OP_SRC, pix, color, 1, &(pixman_rectangle16_t){ x, y + font_baseline(term) - font->strikeout.position, cols * term->cell_width, font->strikeout.thickness}); } static void cursor_colors_for_cell(const struct terminal *term, const struct cell *cell, const pixman_color_t *fg, const pixman_color_t *bg, pixman_color_t *cursor_color, pixman_color_t *text_color) { bool is_selected = cell->attrs.selected; if (term->cursor_color.cursor >> 31) { *cursor_color = color_hex_to_pixman(term->cursor_color.cursor); *text_color = color_hex_to_pixman( term->cursor_color.text >> 31 ? term->cursor_color.text : term->colors.bg); if (cell->attrs.reverse ^ is_selected) { pixman_color_t swap = *cursor_color; *cursor_color = *text_color; *text_color = swap; } if (term->is_searching && !is_selected) { color_dim_for_search(cursor_color); color_dim_for_search(text_color); } } else { *cursor_color = *fg; *text_color = *bg; } } static void draw_cursor(const struct terminal *term, const struct cell *cell, const struct fcft_font *font, pixman_image_t *pix, pixman_color_t *fg, const pixman_color_t *bg, int x, int y, int cols) { pixman_color_t cursor_color; pixman_color_t text_color; cursor_colors_for_cell(term, cell, fg, bg, &cursor_color, &text_color); switch (term->cursor_style) { case CURSOR_BLOCK: if (unlikely(!term->kbd_focus)) draw_unfocused_block(term, pix, &cursor_color, x, y, cols); else if (likely(term->cursor_blink.state == CURSOR_BLINK_ON)) { *fg = text_color; pixman_image_fill_rectangles( PIXMAN_OP_SRC, pix, &cursor_color, 1, &(pixman_rectangle16_t){x, y, cols * term->cell_width, term->cell_height}); } break; case CURSOR_BEAM: if (likely(term->cursor_blink.state == CURSOR_BLINK_ON || !term->kbd_focus)) { draw_beam_cursor(term, pix, font, &cursor_color, x, y); } break; case CURSOR_UNDERLINE: if (likely(term->cursor_blink.state == CURSOR_BLINK_ON || !term->kbd_focus)) { draw_underline_cursor(term, pix, font, &cursor_color, x, y, cols); } break; } } static int render_cell(struct terminal *term, pixman_image_t *pix, struct row *row, int col, int row_no, bool has_cursor) { struct cell *cell = &row->cells[col]; if (cell->attrs.clean) return 0; cell->attrs.clean = 1; cell->attrs.confined = true; int width = term->cell_width; int height = term->cell_height; const int x = term->margins.left + col * width; const int y = term->margins.top + row_no * height; bool is_selected = cell->attrs.selected; uint32_t _fg = 0; uint32_t _bg = 0; uint16_t alpha = 0xffff; if (is_selected && term->colors.use_custom_selection) { _fg = term->colors.selection_fg; _bg = term->colors.selection_bg; } else { /* Use cell specific color, if set, otherwise the default colors (possible reversed) */ switch (cell->attrs.fg_src) { case COLOR_RGB: _fg = cell->attrs.fg; break; case COLOR_BASE16: case COLOR_BASE256: xassert(cell->attrs.fg < ALEN(term->colors.table)); _fg = term->colors.table[cell->attrs.fg]; break; case COLOR_DEFAULT: _fg = term->reverse ? term->colors.bg : term->colors.fg; break; } switch (cell->attrs.bg_src) { case COLOR_RGB: _bg = cell->attrs.bg; break; case COLOR_BASE16: case COLOR_BASE256: xassert(cell->attrs.bg < ALEN(term->colors.table)); _bg = term->colors.table[cell->attrs.bg]; break; case COLOR_DEFAULT: _bg = term->reverse ? term->colors.fg : term->colors.bg; break; } if (cell->attrs.reverse ^ is_selected) { uint32_t swap = _fg; _fg = _bg; _bg = swap; } else if (cell->attrs.bg_src == COLOR_DEFAULT) alpha = term->colors.alpha; } if (unlikely(is_selected && _fg == _bg)) { /* Invert bg when selected/highlighted text has same fg/bg */ _bg = ~_bg; alpha = 0xffff; } if (cell->attrs.dim) _fg = color_dim(term, _fg); if (term->conf->bold_in_bright.enabled && cell->attrs.bold) _fg = color_brighten(term, _fg); if (cell->attrs.blink && term->blink.state == BLINK_OFF) _fg = color_decrease_luminance(_fg); pixman_color_t fg = color_hex_to_pixman(_fg); pixman_color_t bg = color_hex_to_pixman_with_alpha(_bg, alpha); if (term->is_searching && !is_selected) { color_dim_for_search(&fg); color_dim_for_search(&bg); } struct fcft_font *font = attrs_to_font(term, &cell->attrs); const struct composed *composed = NULL; const struct fcft_grapheme *grapheme = NULL; const struct fcft_glyph *single = NULL; const struct fcft_glyph **glyphs = NULL; unsigned glyph_count = 0; wchar_t base = cell->wc; int cell_cols = 1; if (base != 0) { if (unlikely( /* Classic box drawings */ (base >= GLYPH_BOX_DRAWING_FIRST && base <= GLYPH_BOX_DRAWING_LAST) || /* Braille */ (base >= GLYPH_BRAILLE_FIRST && base <= GLYPH_BRAILLE_LAST) || /* * Unicode 13 "Symbols for Legacy Computing" * sub-ranges below. * * Note, the full range is U+1FB00 - U+1FBF9 */ (base >= GLYPH_LEGACY_FIRST && base <= GLYPH_LEGACY_LAST)) && likely(!term->conf->box_drawings_uses_font_glyphs)) { struct fcft_glyph ***arr; size_t count; size_t idx; if (base >= GLYPH_LEGACY_FIRST) { arr = &term->custom_glyphs.legacy; count = GLYPH_LEGACY_COUNT; idx = base - GLYPH_LEGACY_FIRST; } else if (base >= GLYPH_BRAILLE_FIRST) { arr = &term->custom_glyphs.braille; count = GLYPH_BRAILLE_COUNT; idx = base - GLYPH_BRAILLE_FIRST; } else { arr = &term->custom_glyphs.box_drawing; count = GLYPH_BOX_DRAWING_COUNT; idx = base - GLYPH_BOX_DRAWING_FIRST; } if (unlikely(*arr == NULL)) *arr = xcalloc(count, sizeof((*arr)[0])); if (likely((*arr)[idx] != NULL)) single = (*arr)[idx]; else { mtx_lock(&term->render.workers.lock); /* Other thread may have instantiated it while we * acquired the lock */ single = (*arr)[idx]; if (likely(single == NULL)) single = (*arr)[idx] = box_drawing(term, base); mtx_unlock(&term->render.workers.lock); } if (single != NULL) { glyph_count = 1; glyphs = &single; cell_cols = single->cols; } } else if (base >= CELL_COMB_CHARS_LO && base <= CELL_COMB_CHARS_HI) { composed = composed_lookup(term->composed, base - CELL_COMB_CHARS_LO); base = composed->chars[0]; if (term->conf->can_shape_grapheme && term->conf->tweak.grapheme_shaping) { grapheme = fcft_grapheme_rasterize( font, composed->count, composed->chars, 0, NULL, term->font_subpixel); } if (grapheme != NULL) { cell_cols = composed->width; composed = NULL; glyphs = grapheme->glyphs; glyph_count = grapheme->count; } } if (single == NULL && grapheme == NULL) { xassert(base != 0); single = fcft_glyph_rasterize(font, base, term->font_subpixel); if (single == NULL) { glyph_count = 0; cell_cols = 1; } else { glyph_count = 1; glyphs = &single; cell_cols = single->cols; } } } assert(glyph_count == 0 || glyphs != NULL); const int cols_left = term->cols - col; cell_cols = max(1, min(cell_cols, cols_left)); /* * Determine cells that will bleed into their right neighbor and remember * them for cleanup in the next frame. */ int render_width = cell_cols * width; if (term->conf->tweak.overflowing_glyphs && glyph_count > 0 && cols_left > cell_cols) { int glyph_width = 0, advance = 0; for (size_t i = 0; i < glyph_count; i++) { glyph_width = max(glyph_width, advance + glyphs[i]->x + glyphs[i]->width); advance += glyphs[i]->advance.x; } if (glyph_width > render_width) { render_width = min(glyph_width, render_width + width); for (int i = 0; i < cell_cols; i++) row->cells[col + i].attrs.confined = false; } } pixman_region32_t clip; pixman_region32_init_rect( &clip, x, y, render_width, term->cell_height); pixman_image_set_clip_region32(pix, &clip); pixman_region32_fini(&clip); /* Background */ pixman_image_fill_rectangles( PIXMAN_OP_SRC, pix, &bg, 1, &(pixman_rectangle16_t){x, y, cell_cols * width, height}); if (cell->attrs.blink && term->blink.fd < 0) { /* TODO: use a custom lock for this? */ mtx_lock(&term->render.workers.lock); term_arm_blink_timer(term); mtx_unlock(&term->render.workers.lock); } if (has_cursor && term->cursor_style == CURSOR_BLOCK && term->kbd_focus) draw_cursor(term, cell, font, pix, &fg, &bg, x, y, cell_cols); if (cell->wc == 0 || cell->wc >= CELL_SPACER || cell->wc == L'\t' || (unlikely(cell->attrs.conceal) && !is_selected)) { goto draw_cursor; } pixman_image_t *clr_pix = pixman_image_create_solid_fill(&fg); int pen_x = x; for (unsigned i = 0; i < glyph_count; i++) { const int letter_x_ofs = i == 0 ? term->font_x_ofs : 0; const struct fcft_glyph *glyph = glyphs[i]; if (glyph == NULL) continue; int g_x = glyph->x; int g_y = glyph->y; if (i > 0 && glyph->x >= 0) g_x -= term->cell_width; if (unlikely(pixman_image_get_format(glyph->pix) == PIXMAN_a8r8g8b8)) { /* Glyph surface is a pre-rendered image (typically a color emoji...) */ if (!(cell->attrs.blink && term->blink.state == BLINK_OFF)) { pixman_image_composite32( PIXMAN_OP_OVER, glyph->pix, NULL, pix, 0, 0, 0, 0, pen_x + letter_x_ofs + g_x, y + font_baseline(term) - g_y, glyph->width, glyph->height); } } else { pixman_image_composite32( PIXMAN_OP_OVER, clr_pix, glyph->pix, pix, 0, 0, 0, 0, pen_x + letter_x_ofs + g_x, y + font_baseline(term) - g_y, glyph->width, glyph->height); /* Combining characters */ if (composed != NULL) { assert(glyph_count == 1); for (size_t i = 1; i < composed->count; i++) { const struct fcft_glyph *g = fcft_glyph_rasterize( font, composed->chars[i], term->font_subpixel); if (g == NULL) continue; /* * Fonts _should_ assume the pen position is now * *after* the base glyph, and thus use negative * offsets for combining glyphs. * * Not all fonts behave like this however, and we * try to accommodate both variants. * * Since we haven't moved our pen position yet, we * add a full cell width to the offset (or two, in * case of double-width characters). * * If the font does *not* use negative offsets, * we'd normally use an offset of 0. However, to * somewhat deal with double-width glyphs we use * an offset of *one* cell. */ int x_ofs = g->x < 0 ? cell_cols * term->cell_width : (cell_cols - 1) * term->cell_width; pixman_image_composite32( PIXMAN_OP_OVER, clr_pix, g->pix, pix, 0, 0, 0, 0, /* Some fonts use a negative offset, while others use a * "normal" offset */ pen_x + x_ofs + g->x, y + font_baseline(term) - g->y, g->width, g->height); } } } pen_x += glyph->advance.x; } pixman_image_unref(clr_pix); /* Underline */ if (cell->attrs.underline) draw_underline(term, pix, font, &fg, x, y, cell_cols); if (cell->attrs.strikethrough) draw_strikeout(term, pix, font, &fg, x, y, cell_cols); if (unlikely(cell->attrs.url)) { pixman_color_t url_color = color_hex_to_pixman( term->conf->colors.use_custom.url ? term->conf->colors.url : term->colors.table[3] ); draw_underline(term, pix, font, &url_color, x, y, cell_cols); } draw_cursor: if (has_cursor && (term->cursor_style != CURSOR_BLOCK || !term->kbd_focus)) draw_cursor(term, cell, font, pix, &fg, &bg, x, y, cell_cols); pixman_image_set_clip_region32(pix, NULL); return cell_cols; } static void render_row(struct terminal *term, pixman_image_t *pix, struct row *row, int row_no, int cursor_col) { for (int col = term->cols - 1; col >= 0; col--) render_cell(term, pix, row, col, row_no, cursor_col == col); } static void render_urgency(struct terminal *term, struct buffer *buf) { uint32_t red = term->colors.table[1]; if (term->is_searching) red = color_decrease_luminance(red); pixman_color_t bg = color_hex_to_pixman(red); int width = min(min(term->margins.left, term->margins.right), min(term->margins.top, term->margins.bottom)); pixman_image_fill_rectangles( PIXMAN_OP_SRC, buf->pix[0], &bg, 4, (pixman_rectangle16_t[]){ /* Top */ {0, 0, term->width, width}, /* Bottom */ {0, term->height - width, term->width, width}, /* Left */ {0, width, width, term->height - 2 * width}, /* Right */ {term->width - width, width, width, term->height - 2 * width}, }); } static void render_margin(struct terminal *term, struct buffer *buf, int start_line, int end_line, bool apply_damage) { /* Fill area outside the cell grid with the default background color */ const int rmargin = term->width - term->margins.right; const int bmargin = term->height - term->margins.bottom; const int line_count = end_line - start_line; uint32_t _bg = !term->reverse ? term->colors.bg : term->colors.fg; pixman_color_t bg = color_hex_to_pixman_with_alpha(_bg, term->colors.alpha); if (term->is_searching) color_dim_for_search(&bg); pixman_image_fill_rectangles( PIXMAN_OP_SRC, buf->pix[0], &bg, 4, (pixman_rectangle16_t[]){ /* Top */ {0, 0, term->width, term->margins.top}, /* Bottom */ {0, bmargin, term->width, term->margins.bottom}, /* Left */ {0, term->margins.top + start_line * term->cell_height, term->margins.left, line_count * term->cell_height}, /* Right */ {rmargin, term->margins.top + start_line * term->cell_height, term->margins.right, line_count * term->cell_height}, }); if (term->render.urgency) render_urgency(term, buf); /* Ensure the updated regions are copied to the next frame's * buffer when we're double buffering */ pixman_region32_union_rect( &buf->dirty, &buf->dirty, 0, 0, term->width, term->margins.top); pixman_region32_union_rect( &buf->dirty, &buf->dirty, 0, bmargin, term->width, term->margins.bottom); pixman_region32_union_rect( &buf->dirty, &buf->dirty, 0, 0, term->margins.left, term->height); pixman_region32_union_rect( &buf->dirty, &buf->dirty, rmargin, 0, term->margins.right, term->height); if (apply_damage) { /* Top */ wl_surface_damage_buffer( term->window->surface, 0, 0, term->width, term->margins.top); /* Bottom */ wl_surface_damage_buffer( term->window->surface, 0, bmargin, term->width, term->margins.bottom); /* Left */ wl_surface_damage_buffer( term->window->surface, 0, term->margins.top + start_line * term->cell_height, term->margins.left, line_count * term->cell_height); /* Right */ wl_surface_damage_buffer( term->window->surface, rmargin, term->margins.top + start_line * term->cell_height, term->margins.right, line_count * term->cell_height); } } static void grid_render_scroll(struct terminal *term, struct buffer *buf, const struct damage *dmg) { int height = (dmg->region.end - dmg->region.start - dmg->lines) * term->cell_height; LOG_DBG( "damage: SCROLL: %d-%d by %d lines", dmg->region.start, dmg->region.end, dmg->lines); if (height <= 0) return; #if TIME_SCROLL_DAMAGE struct timespec start_time; clock_gettime(CLOCK_MONOTONIC, &start_time); #endif int dst_y = term->margins.top + (dmg->region.start + 0) * term->cell_height; int src_y = term->margins.top + (dmg->region.start + dmg->lines) * term->cell_height; /* * SHM scrolling can be *much* faster, but it depends on how many * lines we're scrolling, and how much repairing we need to do. * * In short, scrolling a *large* number of rows is faster with a * memmove, while scrolling a *small* number of lines is faster * with SHM scrolling. * * However, since we need to restore the scrolling regions when * SHM scrolling, we also need to take this into account. * * Finally, we also have to restore the window margins, and this * is a *huge* performance hit when scrolling a large number of * lines (in addition to the sloweness of SHM scrolling as * method). * * So, we need to figure out when to SHM scroll, and when to * memmove. * * For now, assume that the both methods perform roughly the same, * given an equal number of bytes to move/allocate, and use the * method that results in the least amount of bytes to touch. * * Since number of lines directly translates to bytes, we can * simply count lines. * * SHM scrolling needs to first "move" (punch hole + allocate) * dmg->lines number of lines, and then we need to restore * the bottom scroll region. * * If the total number of lines is less than half the screen - use * SHM. Otherwise use memmove. */ bool try_shm_scroll = shm_can_scroll(buf) && ( dmg->lines + dmg->region.start + (term->rows - dmg->region.end)) < term->rows / 2; bool did_shm_scroll = false; //try_shm_scroll = false; //try_shm_scroll = true; if (try_shm_scroll) { did_shm_scroll = shm_scroll( buf, dmg->lines * term->cell_height, term->margins.top, dmg->region.start * term->cell_height, term->margins.bottom, (term->rows - dmg->region.end) * term->cell_height); } if (did_shm_scroll) { /* Restore margins */ render_margin( term, buf, dmg->region.end - dmg->lines, term->rows, false); } else { /* Fallback for when we either cannot do SHM scrolling, or it failed */ uint8_t *raw = buf->data; memmove(raw + dst_y * buf->stride, raw + src_y * buf->stride, height * buf->stride); } #if TIME_SCROLL_DAMAGE struct timespec end_time; clock_gettime(CLOCK_MONOTONIC, &end_time); struct timespec memmove_time; timespec_sub(&end_time, &start_time, &memmove_time); LOG_INFO("scrolled %dKB (%d lines) using %s in %lds %ldns", height * buf->stride / 1024, dmg->lines, did_shm_scroll ? "SHM" : try_shm_scroll ? "memmove (SHM failed)" : "memmove", (long)memmove_time.tv_sec, memmove_time.tv_nsec); #endif wl_surface_damage_buffer( term->window->surface, term->margins.left, dst_y, term->width - term->margins.left - term->margins.right, height); } static void grid_render_scroll_reverse(struct terminal *term, struct buffer *buf, const struct damage *dmg) { int height = (dmg->region.end - dmg->region.start - dmg->lines) * term->cell_height; LOG_DBG( "damage: SCROLL REVERSE: %d-%d by %d lines", dmg->region.start, dmg->region.end, dmg->lines); if (height <= 0) return; #if TIME_SCROLL_DAMAGE struct timespec start_time; clock_gettime(CLOCK_MONOTONIC, &start_time); #endif int src_y = term->margins.top + (dmg->region.start + 0) * term->cell_height; int dst_y = term->margins.top + (dmg->region.start + dmg->lines) * term->cell_height; bool try_shm_scroll = shm_can_scroll(buf) && ( dmg->lines + dmg->region.start + (term->rows - dmg->region.end)) < term->rows / 2; bool did_shm_scroll = false; if (try_shm_scroll) { did_shm_scroll = shm_scroll( buf, -dmg->lines * term->cell_height, term->margins.top, dmg->region.start * term->cell_height, term->margins.bottom, (term->rows - dmg->region.end) * term->cell_height); } if (did_shm_scroll) { /* Restore margins */ render_margin( term, buf, dmg->region.start, dmg->region.start + dmg->lines, false); } else { /* Fallback for when we either cannot do SHM scrolling, or it failed */ uint8_t *raw = buf->data; memmove(raw + dst_y * buf->stride, raw + src_y * buf->stride, height * buf->stride); } #if TIME_SCROLL_DAMAGE struct timespec end_time; clock_gettime(CLOCK_MONOTONIC, &end_time); struct timespec memmove_time; timespec_sub(&end_time, &start_time, &memmove_time); LOG_INFO("scrolled REVERSE %dKB (%d lines) using %s in %lds %ldns", height * buf->stride / 1024, dmg->lines, did_shm_scroll ? "SHM" : try_shm_scroll ? "memmove (SHM failed)" : "memmove", (long)memmove_time.tv_sec, memmove_time.tv_nsec); #endif wl_surface_damage_buffer( term->window->surface, term->margins.left, dst_y, term->width - term->margins.left - term->margins.right, height); } static void render_sixel_chunk(struct terminal *term, pixman_image_t *pix, const struct sixel *sixel, int term_start_row, int img_start_row, int count) { /* Translate row/column to x/y pixel values */ const int x = term->margins.left + sixel->pos.col * term->cell_width; const int y = term->margins.top + term_start_row * term->cell_height; /* Width/height, in pixels - and don't touch the window margins */ const int width = max( 0, min(sixel->width, term->width - x - term->margins.right)); const int height = max( 0, min( min(count * term->cell_height, /* 'count' number of rows */ sixel->height - img_start_row * term->cell_height), /* What remains of the sixel */ term->height - y - term->margins.bottom)); /* Verify we're not stepping outside the grid */ xassert(x >= term->margins.left); xassert(y >= term->margins.top); xassert(width == 0 || x + width <= term->width - term->margins.right); xassert(height == 0 || y + height <= term->height - term->margins.bottom); //LOG_DBG("sixel chunk: %dx%d %dx%d", x, y, width, height); pixman_image_composite32( sixel->opaque ? PIXMAN_OP_SRC : PIXMAN_OP_OVER, sixel->pix, NULL, pix, 0, img_start_row * term->cell_height, 0, 0, x, y, width, height); wl_surface_damage_buffer(term->window->surface, x, y, width, height); } static void render_sixel(struct terminal *term, pixman_image_t *pix, const struct coord *cursor, const struct sixel *sixel) { const int view_end = (term->grid->view + term->rows - 1) & (term->grid->num_rows - 1); const bool last_row_needs_erase = sixel->height % term->cell_height != 0; const bool last_col_needs_erase = sixel->width % term->cell_width != 0; int chunk_img_start = -1; /* Image-relative start row of chunk */ int chunk_term_start = -1; /* Viewport relative start row of chunk */ int chunk_row_count = 0; /* Number of rows to emit */ #define maybe_emit_sixel_chunk_then_reset() \ if (chunk_row_count != 0) { \ render_sixel_chunk( \ term, pix, sixel, \ chunk_term_start, chunk_img_start, chunk_row_count); \ chunk_term_start = chunk_img_start = -1; \ chunk_row_count = 0; \ } /* * Iterate all sixel rows: * * - ignore rows that aren't visible on-screen * - ignore rows that aren't dirty (they have already been rendered) * - chunk consecutive dirty rows into a 'chunk' * - emit (render) chunk as soon as a row isn't visible, or is clean * - emit final chunk after we've iterated all rows * * The purpose of this is to reduce the amount of pixels that * needs to be composited and marked as damaged for the * compositor. * * Since we do CPU based composition, rendering is a slow and * heavy task for foot, and thus it is important to not re-render * things unnecessarily. */ for (int _abs_row_no = sixel->pos.row; _abs_row_no < sixel->pos.row + sixel->rows; _abs_row_no++) { const int abs_row_no = _abs_row_no & (term->grid->num_rows - 1); const int term_row_no = (abs_row_no - term->grid->view + term->grid->num_rows) & (term->grid->num_rows - 1); /* Check if row is in the visible viewport */ if (view_end >= term->grid->view) { /* Not wrapped */ if (!(abs_row_no >= term->grid->view && abs_row_no <= view_end)) { /* Not visible */ maybe_emit_sixel_chunk_then_reset(); continue; } } else { /* Wrapped */ if (!(abs_row_no >= term->grid->view || abs_row_no <= view_end)) { /* Not visible */ maybe_emit_sixel_chunk_then_reset(); continue; } } /* Is the row dirty? */ struct row *row = term->grid->rows[abs_row_no]; xassert(row != NULL); /* Should be visible */ if (!row->dirty) { maybe_emit_sixel_chunk_then_reset(); continue; } int cursor_col = cursor->row == term_row_no ? cursor->col : -1; /* * If image contains transparent parts, render all (dirty) * cells beneath it. * * If image is opaque, loop cells and set their 'clean' bit, * to prevent the grid rendered from overwriting the sixel * * If the last sixel row only partially covers the cell row, * 'erase' the cell by rendering them. * * In all cases, do *not* clear the ‘dirty’ bit on the row, to * ensure the regular renderer includes them in the damage * rect. */ if (!sixel->opaque) { /* TODO: multithreading */ int cursor_col = cursor->row == term_row_no ? cursor->col : -1; render_row(term, pix, row, term_row_no, cursor_col); } else { for (int col = sixel->pos.col; col < min(sixel->pos.col + sixel->cols, term->cols); col++) { struct cell *cell = &row->cells[col]; if (!cell->attrs.clean) { bool last_row = abs_row_no == sixel->pos.row + sixel->rows - 1; bool last_col = col == sixel->pos.col + sixel->cols - 1; if ((last_row_needs_erase && last_row) || (last_col_needs_erase && last_col)) { render_cell(term, pix, row, col, term_row_no, cursor_col == col); } else { cell->attrs.clean = 1; cell->attrs.confined = 1; } } } } if (chunk_term_start == -1) { xassert(chunk_img_start == -1); chunk_term_start = term_row_no; chunk_img_start = _abs_row_no - sixel->pos.row; chunk_row_count = 1; } else chunk_row_count++; } maybe_emit_sixel_chunk_then_reset(); #undef maybe_emit_sixel_chunk_then_reset } static void render_sixel_images(struct terminal *term, pixman_image_t *pix, const struct coord *cursor) { if (likely(tll_length(term->grid->sixel_images)) == 0) return; const int scrollback_end = (term->grid->offset + term->rows) & (term->grid->num_rows - 1); const int view_start = (term->grid->view - scrollback_end + term->grid->num_rows) & (term->grid->num_rows - 1); const int view_end = view_start + term->rows - 1; //LOG_DBG("SIXELS: %zu images, view=%d-%d", // tll_length(term->grid->sixel_images), view_start, view_end); tll_foreach(term->grid->sixel_images, it) { const struct sixel *six = &it->item; const int start = (six->pos.row - scrollback_end + term->grid->num_rows) & (term->grid->num_rows - 1); const int end = start + six->rows - 1; //LOG_DBG(" sixel: %d-%d", start, end); if (start > view_end) { /* Sixel starts after view ends, no need to try to render it */ continue; } else if (end < view_start) { /* Image ends before view starts. Since the image list is * sorted, we can safely stop here */ break; } render_sixel(term, pix, cursor, &it->item); } } #if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED static void render_ime_preedit_for_seat(struct terminal *term, struct seat *seat, struct buffer *buf) { if (likely(seat->ime.preedit.cells == NULL)) return; if (unlikely(term->is_searching)) return; /* Adjust cursor position to viewport */ struct coord cursor; cursor = term->grid->cursor.point; cursor.row += term->grid->offset; cursor.row -= term->grid->view; cursor.row &= term->grid->num_rows - 1; if (cursor.row < 0 || cursor.row >= term->rows) return; int cells_needed = seat->ime.preedit.count; if (seat->ime.preedit.cursor.start == cells_needed && seat->ime.preedit.cursor.end == cells_needed) { /* Cursor will be drawn *after* the pre-edit string, i.e. in * the cell *after*. This means we need to copy, and dirty, * one extra cell from the original grid, or we’ll leave * trailing “cursors” after us if the user deletes text while * pre-editing */ cells_needed++; } int row_idx = cursor.row; int col_idx = cursor.col; int ime_ofs = 0; /* Offset into pre-edit string to start rendering at */ int cells_left = term->cols - cursor.col; int cells_used = min(cells_needed, term->cols); /* Adjust start of pre-edit text to the left if string doesn't fit on row */ if (cells_left < cells_used) col_idx -= cells_used - cells_left; if (cells_needed > cells_used) { int start = seat->ime.preedit.cursor.start; int end = seat->ime.preedit.cursor.end; if (start == end) { /* Ensure *end* of pre-edit string is visible */ ime_ofs = cells_needed - cells_used; } else { /* Ensure the *beginning* of the cursor-area is visible */ ime_ofs = start; /* Display as much as possible of the pre-edit string */ if (cells_needed - ime_ofs < cells_used) ime_ofs = cells_needed - cells_used; } /* Make sure we don't start in the middle of a character */ while (ime_ofs < cells_needed && seat->ime.preedit.cells[ime_ofs].wc >= CELL_SPACER) { ime_ofs++; } } xassert(col_idx >= 0); xassert(col_idx < term->cols); struct row *row = grid_row_in_view(term->grid, row_idx); /* Don't start pre-edit text in the middle of a double-width character */ while (col_idx > 0 && row->cells[col_idx].wc >= CELL_SPACER) { cells_used++; col_idx--; } /* * Copy original content (render_cell() reads cell data directly * from grid), and mark all cells as dirty. This ensures they are * re-rendered when the pre-edit text is modified or removed. */ struct cell *real_cells = malloc(cells_used * sizeof(real_cells[0])); for (int i = 0; i < cells_used; i++) { xassert(col_idx + i < term->cols); real_cells[i] = row->cells[col_idx + i]; real_cells[i].attrs.clean = 0; } row->dirty = true; /* Render pre-edit text */ xassert(seat->ime.preedit.cells[ime_ofs].wc < CELL_SPACER); for (int i = 0, idx = ime_ofs; idx < seat->ime.preedit.count; i++, idx++) { const struct cell *cell = &seat->ime.preedit.cells[idx]; if (cell->wc >= CELL_SPACER) continue; int width = max(1, wcwidth(cell->wc)); if (col_idx + i + width > term->cols) break; row->cells[col_idx + i] = *cell; render_cell(term, buf->pix[0], row, col_idx + i, row_idx, false); } int start = seat->ime.preedit.cursor.start - ime_ofs; int end = seat->ime.preedit.cursor.end - ime_ofs; if (!seat->ime.preedit.cursor.hidden) { const struct cell *start_cell = &seat->ime.preedit.cells[0]; pixman_color_t fg = color_hex_to_pixman(term->colors.fg); pixman_color_t bg = color_hex_to_pixman(term->colors.bg); pixman_color_t cursor_color, text_color; cursor_colors_for_cell( term, start_cell, &fg, &bg, &cursor_color, &text_color); int x = term->margins.left + (col_idx + start) * term->cell_width; int y = term->margins.top + row_idx * term->cell_height; if (end == start) { /* Bar */ if (start >= 0) { struct fcft_font *font = attrs_to_font(term, &start_cell->attrs); draw_beam_cursor(term, buf->pix[0], font, &cursor_color, x, y); } term_ime_set_cursor_rect(term, x, y, 1, term->cell_height); } else if (end > start) { /* Hollow cursor */ if (start >= 0 && end <= term->cols) { int cols = end - start; draw_unfocused_block(term, buf->pix[0], &cursor_color, x, y, cols); } term_ime_set_cursor_rect( term, x, y, (end - start) * term->cell_width, term->cell_height); } } /* Restore original content (but do not render) */ for (int i = 0; i < cells_used; i++) row->cells[col_idx + i] = real_cells[i]; free(real_cells); wl_surface_damage_buffer( term->window->surface, term->margins.left, term->margins.top + row_idx * term->cell_height, term->width - term->margins.left - term->margins.right, 1 * term->cell_height); } #endif static void render_ime_preedit(struct terminal *term, struct buffer *buf) { #if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED tll_foreach(term->wl->seats, it) { if (it->item.kbd_focus == term) render_ime_preedit_for_seat(term, &it->item, buf); } #endif } int render_worker_thread(void *_ctx) { struct render_worker_context *ctx = _ctx; struct terminal *term = ctx->term; const int my_id = ctx->my_id; free(ctx); sigset_t mask; sigfillset(&mask); pthread_sigmask(SIG_SETMASK, &mask, NULL); char proc_title[16]; snprintf(proc_title, sizeof(proc_title), "foot:render:%d", my_id); if (pthread_setname_np(pthread_self(), proc_title) < 0) LOG_ERRNO("render worker %d: failed to set process title", my_id); sem_t *start = &term->render.workers.start; sem_t *done = &term->render.workers.done; mtx_t *lock = &term->render.workers.lock; while (true) { sem_wait(start); struct buffer *buf = term->render.workers.buf; bool frame_done = false; /* Translate offset-relative cursor row to view-relative */ struct coord cursor = {-1, -1}; if (!term->hide_cursor) { cursor = term->grid->cursor.point; cursor.row += term->grid->offset; cursor.row -= term->grid->view; cursor.row &= term->grid->num_rows - 1; } while (!frame_done) { mtx_lock(lock); xassert(tll_length(term->render.workers.queue) > 0); int row_no = tll_pop_front(term->render.workers.queue); mtx_unlock(lock); switch (row_no) { default: { xassert(buf != NULL); struct row *row = grid_row_in_view(term->grid, row_no); int cursor_col = cursor.row == row_no ? cursor.col : -1; render_row(term, buf->pix[my_id], row, row_no, cursor_col); break; } case -1: frame_done = true; sem_post(done); break; case -2: return 0; } } }; return -1; } struct csd_data get_csd_data(const struct terminal *term, enum csd_surface surf_idx) { xassert(term->window->csd_mode == CSD_YES); /* Only title bar is rendered in maximized mode */ const int border_width = !term->window->is_maximized ? term->conf->csd.border_width * term->scale : 0; const int title_height = term->window->is_fullscreen ? 0 : term->conf->csd.title_height * term->scale; const int button_width = !term->window->is_fullscreen ? term->conf->csd.button_width * term->scale : 0; const int button_close_width = term->width >= 1 * button_width ? button_width : 0; const int button_maximize_width = term->width >= 2 * button_width ? button_width : 0; const int button_minimize_width = term->width >= 3 * button_width ? button_width : 0; switch (surf_idx) { case CSD_SURF_TITLE: return (struct csd_data){ 0, -title_height, term->width, title_height}; case CSD_SURF_LEFT: return (struct csd_data){-border_width, -title_height, border_width, title_height + term->height}; case CSD_SURF_RIGHT: return (struct csd_data){ term->width, -title_height, border_width, title_height + term->height}; case CSD_SURF_TOP: return (struct csd_data){-border_width, -title_height - border_width, term->width + 2 * border_width, border_width}; case CSD_SURF_BOTTOM: return (struct csd_data){-border_width, term->height, term->width + 2 * border_width, border_width}; /* Positioned relative to CSD_SURF_TITLE */ case CSD_SURF_MINIMIZE: return (struct csd_data){term->width - 3 * button_width, 0, button_minimize_width, title_height}; case CSD_SURF_MAXIMIZE: return (struct csd_data){term->width - 2 * button_width, 0, button_maximize_width, title_height}; case CSD_SURF_CLOSE: return (struct csd_data){term->width - 1 * button_width, 0, button_close_width, title_height}; case CSD_SURF_COUNT: break; } BUG("Invalid csd_surface type"); return (struct csd_data){0}; } static void csd_commit(struct terminal *term, struct wl_surface *surf, struct buffer *buf) { xassert(buf->width % term->scale == 0); xassert(buf->height % term->scale == 0); wl_surface_attach(surf, buf->wl_buf, 0, 0); wl_surface_damage_buffer(surf, 0, 0, buf->width, buf->height); wl_surface_set_buffer_scale(surf, term->scale); wl_surface_commit(surf); } static void render_csd_part(struct terminal *term, struct wl_surface *surf, struct buffer *buf, int width, int height, pixman_color_t *color) { xassert(term->window->csd_mode == CSD_YES); pixman_image_fill_rectangles( PIXMAN_OP_SRC, buf->pix[0], color, 1, &(pixman_rectangle16_t){0, 0, buf->width, buf->height}); } static void render_osd(struct terminal *term, struct wl_surface *surf, struct wl_subsurface *sub_surf, struct fcft_font *font, struct buffer *buf, const wchar_t *text, uint32_t _fg, uint32_t _bg, unsigned x, unsigned y) { pixman_region32_t clip; pixman_region32_init_rect(&clip, 0, 0, buf->width, buf->height); pixman_image_set_clip_region32(buf->pix[0], &clip); pixman_region32_fini(&clip); uint16_t alpha = _bg >> 24 | (_bg >> 24 << 8); pixman_color_t bg = color_hex_to_pixman_with_alpha(_bg, alpha); pixman_image_fill_rectangles( PIXMAN_OP_SRC, buf->pix[0], &bg, 1, &(pixman_rectangle16_t){0, 0, buf->width, buf->height}); pixman_color_t fg = color_hex_to_pixman(_fg); const int x_ofs = term->font_x_ofs; const size_t len = wcslen(text); struct fcft_text_run *text_run = NULL; const struct fcft_glyph **glyphs = NULL; const struct fcft_glyph *_glyphs[len]; size_t glyph_count = 0; if (fcft_capabilities() & FCFT_CAPABILITY_TEXT_RUN_SHAPING) { text_run = fcft_text_run_rasterize(font, len, text, term->font_subpixel); if (text_run != NULL) { glyphs = text_run->glyphs; glyph_count = text_run->count; } } if (glyphs == NULL) { for (size_t i = 0; i < len; i++) { const struct fcft_glyph *glyph = fcft_glyph_rasterize( font, text[i], term->font_subpixel); if (glyph == NULL) continue; _glyphs[glyph_count++] = glyph; } glyphs = _glyphs; } pixman_image_t *src = pixman_image_create_solid_fill(&fg); for (size_t i = 0; i < glyph_count; i++) { const struct fcft_glyph *glyph = glyphs[i]; if (pixman_image_get_format(glyph->pix) == PIXMAN_a8r8g8b8) { pixman_image_composite32( PIXMAN_OP_OVER, glyph->pix, NULL, buf->pix[0], 0, 0, 0, 0, x + x_ofs + glyph->x, y + term->font_y_ofs + font->ascent - glyph->y, glyph->width, glyph->height); } else { pixman_image_composite32( PIXMAN_OP_OVER, src, glyph->pix, buf->pix[0], 0, 0, 0, 0, x + x_ofs + glyph->x, y + term->font_y_ofs + font->ascent - glyph->y, glyph->width, glyph->height); } x += glyph->advance.x; } fcft_text_run_destroy(text_run); pixman_image_unref(src); pixman_image_set_clip_region32(buf->pix[0], NULL); xassert(buf->width % term->scale == 0); xassert(buf->height % term->scale == 0); quirk_weston_subsurface_desync_on(sub_surf); wl_surface_attach(surf, buf->wl_buf, 0, 0); wl_surface_damage_buffer(surf, 0, 0, buf->width, buf->height); wl_surface_set_buffer_scale(surf, term->scale); struct wl_region *region = wl_compositor_create_region(term->wl->compositor); if (region != NULL) { wl_region_add(region, 0, 0, buf->width, buf->height); wl_surface_set_opaque_region(surf, region); wl_region_destroy(region); } wl_surface_commit(surf); quirk_weston_subsurface_desync_off(sub_surf); } static void render_csd_title(struct terminal *term, const struct csd_data *info, struct buffer *buf) { xassert(term->window->csd_mode == CSD_YES); struct wl_surf_subsurf *surf = &term->window->csd.surface[CSD_SURF_TITLE]; if (info->width == 0 || info->height == 0) return; xassert(info->width % term->scale == 0); xassert(info->height % term->scale == 0); uint32_t bg = term->conf->csd.color.title_set ? term->conf->csd.color.title : 0xffu << 24 | term->conf->colors.fg; uint32_t fg = term->conf->csd.color.buttons_set ? term->conf->csd.color.buttons : term->conf->colors.bg; if (!term->visual_focus) { bg = color_dim(term, bg); fg = color_dim(term, fg); } const wchar_t *title_text = L""; wchar_t *_title_text = NULL; int chars = mbstowcs(NULL, term->window_title, 0); if (chars >= 0) { _title_text = xmalloc((chars + 1) * sizeof(wchar_t)); mbstowcs(_title_text, term->window_title, chars + 1); title_text = _title_text; } struct wl_window *win = term->window; const int margin = win->csd.font->space_advance.x > 0 ? win->csd.font->space_advance.x : win->csd.font->max_advance.x; render_osd(term, surf->surf, surf->sub, win->csd.font, buf, title_text, fg, bg, margin, (buf->height - win->csd.font->height) / 2); csd_commit(term, surf->surf, buf); free(_title_text); } static void render_csd_border(struct terminal *term, enum csd_surface surf_idx, const struct csd_data *info, struct buffer *buf) { xassert(term->window->csd_mode == CSD_YES); xassert(surf_idx >= CSD_SURF_LEFT && surf_idx <= CSD_SURF_BOTTOM); struct wl_surface *surf = term->window->csd.surface[surf_idx].surf; if (info->width == 0 || info->height == 0) return; xassert(info->width % term->scale == 0); xassert(info->height % term->scale == 0); { pixman_color_t color = color_hex_to_pixman_with_alpha(0, 0); render_csd_part(term, surf, buf, info->width, info->height, &color); } /* * The “visible” border. */ int scale = term->scale; int bwidth = term->conf->csd.border_width * scale; int vwidth = term->conf->csd.border_width_visible * scale; /* Visible size */ xassert(bwidth >= vwidth); if (vwidth > 0) { const struct config *conf = term->conf; int x = 0, y = 0, w = 0, h = 0; switch (surf_idx) { case CSD_SURF_TOP: case CSD_SURF_BOTTOM: x = bwidth - vwidth; y = surf_idx == CSD_SURF_TOP ? info->height - vwidth : 0; w = info->width - 2 * x; h = vwidth; break; case CSD_SURF_LEFT: case CSD_SURF_RIGHT: x = surf_idx == CSD_SURF_LEFT ? bwidth - vwidth : 0; y = 0; w = vwidth; h = info->height; break; case CSD_SURF_TITLE: case CSD_SURF_MINIMIZE: case CSD_SURF_MAXIMIZE: case CSD_SURF_CLOSE: case CSD_SURF_COUNT: BUG("unexpected CSD surface type"); } xassert(x >= 0); xassert(y >= 0); xassert(w >= 0); xassert(h >= 0); xassert(x + w <= info->width); xassert(y + h <= info->height); uint32_t _color = conf->csd.color.border_set ? conf->csd.color.border : conf->csd.color.title_set ? conf->csd.color.title : 0xffu << 24 | term->conf->colors.fg; if (!term->visual_focus) _color = color_dim(term, _color); uint16_t alpha = _color >> 24 | (_color >> 24 << 8); pixman_color_t color = color_hex_to_pixman_with_alpha(_color, alpha); pixman_image_fill_rectangles( PIXMAN_OP_SRC, buf->pix[0], &color, 1, &(pixman_rectangle16_t){x, y, w, h}); } csd_commit(term, surf, buf); } static pixman_color_t get_csd_button_fg_color(const struct config *conf) { uint32_t _color = conf->colors.bg; uint16_t alpha = 0xffff; if (conf->csd.color.buttons_set) { _color = conf->csd.color.buttons; alpha = _color >> 24 | (_color >> 24 << 8); } return color_hex_to_pixman_with_alpha(_color, alpha); } static void render_csd_button_minimize(struct terminal *term, struct buffer *buf) { pixman_color_t color = get_csd_button_fg_color(term->conf); pixman_image_t *src = pixman_image_create_solid_fill(&color); const int max_height = buf->height / 2; const int max_width = buf->width / 2; int width = max_width; int height = max_width / 2; if (height > max_height) { height = max_height; width = height * 2; } xassert(width <= max_width); xassert(height <= max_height); int x_margin = (buf->width - width) / 2.; int y_margin = (buf->height - height) / 2.; pixman_triangle_t tri = { .p1 = { .x = pixman_int_to_fixed(x_margin), .y = pixman_int_to_fixed(y_margin), }, .p2 = { .x = pixman_int_to_fixed(x_margin + width), .y = pixman_int_to_fixed(y_margin), }, .p3 = { .x = pixman_int_to_fixed(buf->width / 2), .y = pixman_int_to_fixed(y_margin + height), }, }; pixman_composite_triangles( PIXMAN_OP_OVER, src, buf->pix[0], PIXMAN_a1, 0, 0, 0, 0, 1, &tri); pixman_image_unref(src); } static void render_csd_button_maximize_maximized( struct terminal *term, struct buffer *buf) { pixman_color_t color = get_csd_button_fg_color(term->conf); pixman_image_t *src = pixman_image_create_solid_fill(&color); const int max_height = buf->height / 3; const int max_width = buf->width / 3; int width = min(max_height, max_width); int thick = min(width / 2, 1 * term->scale); const int x_margin = (buf->width - width) / 2; const int y_margin = (buf->height - width) / 2; xassert(x_margin + width - thick >= 0); xassert(width - 2 * thick >= 0); xassert(y_margin + width - thick >= 0); pixman_image_fill_rectangles( PIXMAN_OP_SRC, buf->pix[0], &color, 4, (pixman_rectangle16_t[]){ {x_margin, y_margin, width, thick}, {x_margin, y_margin + thick, thick, width - 2 * thick}, {x_margin + width - thick, y_margin + thick, thick, width - 2 * thick}, {x_margin, y_margin + width - thick, width, thick}}); pixman_image_unref(src); } static void render_csd_button_maximize_window( struct terminal *term, struct buffer *buf) { pixman_color_t color = get_csd_button_fg_color(term->conf); pixman_image_t *src = pixman_image_create_solid_fill(&color); const int max_height = buf->height / 2; const int max_width = buf->width / 2; int width = max_width; int height = max_width / 2; if (height > max_height) { height = max_height; width = height * 2; } xassert(width <= max_width); xassert(height <= max_height); int x_margin = (buf->width - width) / 2.; int y_margin = (buf->height - height) / 2.; pixman_triangle_t tri = { .p1 = { .x = pixman_int_to_fixed(buf->width / 2), .y = pixman_int_to_fixed(y_margin), }, .p2 = { .x = pixman_int_to_fixed(x_margin), .y = pixman_int_to_fixed(y_margin + height), }, .p3 = { .x = pixman_int_to_fixed(x_margin + width), .y = pixman_int_to_fixed(y_margin + height), }, }; pixman_composite_triangles( PIXMAN_OP_OVER, src, buf->pix[0], PIXMAN_a1, 0, 0, 0, 0, 1, &tri); pixman_image_unref(src); } static void render_csd_button_maximize(struct terminal *term, struct buffer *buf) { if (term->window->is_maximized) render_csd_button_maximize_maximized(term, buf); else render_csd_button_maximize_window(term, buf); } static void render_csd_button_close(struct terminal *term, struct buffer *buf) { pixman_color_t color = get_csd_button_fg_color(term->conf); pixman_image_t *src = pixman_image_create_solid_fill(&color); const int max_height = buf->height / 3; const int max_width = buf->width / 3; int width = min(max_height, max_width); const int x_margin = (buf->width - width) / 2; const int y_margin = (buf->height - width) / 2; pixman_image_fill_rectangles( PIXMAN_OP_SRC, buf->pix[0], &color, 1, &(pixman_rectangle16_t){x_margin, y_margin, width, width}); pixman_image_unref(src); } static void render_csd_button(struct terminal *term, enum csd_surface surf_idx, const struct csd_data *info, struct buffer *buf) { xassert(term->window->csd_mode == CSD_YES); xassert(surf_idx >= CSD_SURF_MINIMIZE && surf_idx <= CSD_SURF_CLOSE); struct wl_surface *surf = term->window->csd.surface[surf_idx].surf; if (info->width == 0 || info->height == 0) return; xassert(info->width % term->scale == 0); xassert(info->height % term->scale == 0); uint32_t _color; uint16_t alpha = 0xffff; bool is_active = false; bool is_set = false; const uint32_t *conf_color = NULL; switch (surf_idx) { case CSD_SURF_MINIMIZE: _color = term->conf->colors.table[4]; /* blue */ is_set = term->conf->csd.color.minimize_set; conf_color = &term->conf->csd.color.minimize; is_active = term->active_surface == TERM_SURF_BUTTON_MINIMIZE; break; case CSD_SURF_MAXIMIZE: _color = term->conf->colors.table[2]; /* green */ is_set = term->conf->csd.color.maximize_set; conf_color = &term->conf->csd.color.maximize; is_active = term->active_surface == TERM_SURF_BUTTON_MAXIMIZE; break; case CSD_SURF_CLOSE: _color = term->conf->colors.table[1]; /* red */ is_set = term->conf->csd.color.close_set; conf_color = &term->conf->csd.color.close; is_active = term->active_surface == TERM_SURF_BUTTON_CLOSE; break; default: BUG("unhandled surface type: %u", (unsigned)surf_idx); break; } if (is_active) { if (is_set) { _color = *conf_color; alpha = _color >> 24 | (_color >> 24 << 8); } } else { _color = 0; alpha = 0; } if (!term->visual_focus) _color = color_dim(term, _color); pixman_color_t color = color_hex_to_pixman_with_alpha(_color, alpha); render_csd_part(term, surf, buf, info->width, info->height, &color); switch (surf_idx) { case CSD_SURF_MINIMIZE: render_csd_button_minimize(term, buf); break; case CSD_SURF_MAXIMIZE: render_csd_button_maximize(term, buf); break; case CSD_SURF_CLOSE: render_csd_button_close(term, buf); break; break; default: BUG("unhandled surface type: %u", (unsigned)surf_idx); break; } csd_commit(term, surf, buf); } static void render_csd(struct terminal *term) { xassert(term->window->csd_mode == CSD_YES); if (term->window->is_fullscreen) return; struct csd_data infos[CSD_SURF_COUNT]; int widths[CSD_SURF_COUNT]; int heights[CSD_SURF_COUNT]; for (size_t i = 0; i < CSD_SURF_COUNT; i++) { infos[i] = get_csd_data(term, i); const int x = infos[i].x; const int y = infos[i].y; const int width = infos[i].width; const int height = infos[i].height; struct wl_surface *surf = term->window->csd.surface[i].surf; struct wl_subsurface *sub = term->window->csd.surface[i].sub; xassert(surf != NULL); xassert(sub != NULL); if (width == 0 || height == 0) { widths[i] = heights[i] = 0; wl_subsurface_set_position(sub, 0, 0); wl_surface_attach(surf, NULL, 0, 0); wl_surface_commit(surf); continue; } widths[i] = width; heights[i] = height; wl_subsurface_set_position(sub, x / term->scale, y / term->scale); } struct buffer *bufs[CSD_SURF_COUNT]; shm_get_many(term->render.chains.csd, CSD_SURF_COUNT, widths, heights, bufs); for (size_t i = CSD_SURF_LEFT; i <= CSD_SURF_BOTTOM; i++) render_csd_border(term, i, &infos[i], bufs[i]); for (size_t i = CSD_SURF_MINIMIZE; i <= CSD_SURF_CLOSE; i++) render_csd_button(term, i, &infos[i], bufs[i]); render_csd_title(term, &infos[CSD_SURF_TITLE], bufs[CSD_SURF_TITLE]); } static void render_scrollback_position(struct terminal *term) { if (term->conf->scrollback.indicator.position == SCROLLBACK_INDICATOR_POSITION_NONE) return; struct wl_window *win = term->window; if (term->grid->view == term->grid->offset) { if (win->scrollback_indicator.surf != NULL) wayl_win_subsurface_destroy(&win->scrollback_indicator); return; } if (win->scrollback_indicator.surf == NULL) { if (!wayl_win_subsurface_new(win, &win->scrollback_indicator)) { LOG_ERR("failed to create scrollback indicator surface"); return; } } xassert(win->scrollback_indicator.surf != NULL); xassert(win->scrollback_indicator.sub != NULL); /* Find absolute row number of the scrollback start */ int scrollback_start = term->grid->offset + term->rows; int empty_rows = 0; while (term->grid->rows[scrollback_start & (term->grid->num_rows - 1)] == NULL) { scrollback_start++; empty_rows++; } /* Rebase viewport against scrollback start (so that 0 is at * the beginning of the scrollback) */ int rebased_view = term->grid->view - scrollback_start + term->grid->num_rows; rebased_view &= term->grid->num_rows - 1; /* How much of the scrollback is actually used? */ int populated_rows = term->grid->num_rows - empty_rows; xassert(populated_rows > 0); xassert(populated_rows <= term->grid->num_rows); /* * How far down in the scrollback we are. * * 0% -> at the beginning of the scrollback * 100% -> at the bottom, i.e. where new lines are inserted */ double percent = rebased_view + term->rows == populated_rows ? 1.0 : (double)rebased_view / (populated_rows - term->rows); wchar_t _text[64]; const wchar_t *text = _text; int cell_count = 0; /* *What* to render */ switch (term->conf->scrollback.indicator.format) { case SCROLLBACK_INDICATOR_FORMAT_PERCENTAGE: swprintf(_text, sizeof(_text) / sizeof(_text[0]), L"%u%%", (int)(100 * percent)); cell_count = 3; break; case SCROLLBACK_INDICATOR_FORMAT_LINENO: swprintf(_text, sizeof(_text) / sizeof(_text[0]), L"%d", rebased_view + 1); cell_count = 1 + (int)log10(term->grid->num_rows); break; case SCROLLBACK_INDICATOR_FORMAT_TEXT: text = term->conf->scrollback.indicator.text; cell_count = wcslen(text); break; } const int scale = term->scale; const int margin = 3 * scale; const int width = (2 * margin + cell_count * term->cell_width + scale - 1) / scale * scale; const int height = (2 * margin + term->cell_height + scale - 1) / scale * scale; /* *Where* to render - parent relative coordinates */ int surf_top = 0; switch (term->conf->scrollback.indicator.position) { case SCROLLBACK_INDICATOR_POSITION_NONE: BUG("Invalid scrollback indicator position type"); return; case SCROLLBACK_INDICATOR_POSITION_FIXED: surf_top = term->cell_height - margin; break; case SCROLLBACK_INDICATOR_POSITION_RELATIVE: { int lines = term->rows - 2; /* Avoid using first and last rows */ if (term->is_searching) { /* Make sure we don't collide with the scrollback search box */ lines--; } lines = max(lines, 0); int pixels = max(lines * term->cell_height - height + 2 * margin, 0); surf_top = term->cell_height - margin + (int)(percent * pixels); break; } } const int x = (term->width - margin - width) / scale * scale; const int y = (term->margins.top + surf_top) / scale * scale; if (y + height > term->height) { wl_surface_attach(win->scrollback_indicator.surf, NULL, 0, 0); wl_surface_commit(win->scrollback_indicator.surf); return; } struct buffer_chain *chain = term->render.chains.scrollback_indicator; struct buffer *buf = shm_get_buffer(chain, width, height); wl_subsurface_set_position( win->scrollback_indicator.sub, x / scale, y / scale); uint32_t fg = term->colors.table[0]; uint32_t bg = term->colors.table[8 + 4]; if (term->conf->colors.use_custom.scrollback_indicator) { fg = term->conf->colors.scrollback_indicator.fg; bg = term->conf->colors.scrollback_indicator.bg; } render_osd( term, win->scrollback_indicator.surf, win->scrollback_indicator.sub, term->fonts[0], buf, text, fg, 0xffu << 24 | bg, width - margin - wcslen(text) * term->cell_width, margin); } static void render_render_timer(struct terminal *term, struct timespec render_time) { struct wl_window *win = term->window; wchar_t text[256]; double usecs = render_time.tv_sec * 1000000 + render_time.tv_nsec / 1000.0; swprintf(text, sizeof(text) / sizeof(text[0]), L"%.2f µs", usecs); const int scale = term->scale; const int cell_count = wcslen(text); const int margin = 3 * scale; const int width = (2 * margin + cell_count * term->cell_width + scale - 1) / scale * scale; const int height = (2 * margin + term->cell_height + scale - 1) / scale * scale; struct buffer_chain *chain = term->render.chains.render_timer; struct buffer *buf = shm_get_buffer(chain, width, height); wl_subsurface_set_position( win->render_timer.sub, margin / term->scale, (term->margins.top + term->cell_height - margin) / term->scale); render_osd( term, win->render_timer.surf, win->render_timer.sub, term->fonts[0], buf, text, term->colors.table[0], 0xffu << 24 | term->colors.table[8 + 1], margin, margin); } static void frame_callback( void *data, struct wl_callback *wl_callback, uint32_t callback_data); static const struct wl_callback_listener frame_listener = { .done = &frame_callback, }; static void force_full_repaint(struct terminal *term, struct buffer *buf) { tll_free(term->grid->scroll_damage); render_margin(term, buf, 0, term->rows, true); term_damage_view(term); } static void reapply_old_damage(struct terminal *term, struct buffer *new, struct buffer *old) { static int counter = 0; static bool have_warned = false; if (!have_warned && ++counter > 5) { LOG_WARN("compositor is not releasing buffers immediately; " "expect lower rendering performance"); have_warned = true; } if (new->age > 1) { memcpy(new->data, old->data, new->height * new->stride); return; } /* * TODO: remove this frame’s damage from the region we copy from * the old frame. * * - this frame’s dirty region is only valid *after* we’ve applied * its scroll damage. * - last frame’s dirty region is only valid *before* we’ve * applied this frame’s scroll damage. * * Can we transform one of the regions? It’s not trivial, since * scroll damage isn’t just about counting lines; there may be * multiple damage records, each with different scrolling regions. */ pixman_region32_t dirty; pixman_region32_init(&dirty); bool full_repaint_needed = true; for (int r = 0; r < term->rows; r++) { const struct row *row = grid_row_in_view(term->grid, r); bool row_all_dirty = true; for (int c = 0; c < term->cols; c++) { if (row->cells[c].attrs.clean) { row_all_dirty = false; full_repaint_needed = false; break; } } if (row_all_dirty) { pixman_region32_union_rect( &dirty, &dirty, term->margins.left, term->margins.top + r * term->cell_height, term->width - term->margins.left - term->margins.right, term->cell_height); } } if (full_repaint_needed) { force_full_repaint(term, new); return; } for (size_t i = 0; i < old->scroll_damage_count; i++) { const struct damage *dmg = &old->scroll_damage[i]; switch (dmg->type) { case DAMAGE_SCROLL: if (term->grid->view == term->grid->offset) grid_render_scroll(term, new, dmg); break; case DAMAGE_SCROLL_REVERSE: if (term->grid->view == term->grid->offset) grid_render_scroll_reverse(term, new, dmg); break; case DAMAGE_SCROLL_IN_VIEW: grid_render_scroll(term, new, dmg); break; case DAMAGE_SCROLL_REVERSE_IN_VIEW: grid_render_scroll_reverse(term, new, dmg); break; } } if (tll_length(term->grid->scroll_damage) == 0) { pixman_region32_subtract(&dirty, &old->dirty, &dirty); pixman_image_set_clip_region32(new->pix[0], &dirty); } else pixman_image_set_clip_region32(new->pix[0], &old->dirty); pixman_image_composite32( PIXMAN_OP_SRC, old->pix[0], NULL, new->pix[0], 0, 0, 0, 0, 0, 0, term->width, term->height); pixman_image_set_clip_region32(new->pix[0], NULL); pixman_region32_fini(&dirty); } static void dirty_old_cursor(struct terminal *term) { if (term->render.last_cursor.row != NULL && !term->render.last_cursor.hidden) { struct row *row = term->render.last_cursor.row; struct cell *cell = &row->cells[term->render.last_cursor.col]; cell->attrs.clean = 0; row->dirty = true; } /* Remember current cursor position, for the next frame */ term->render.last_cursor.row = grid_row(term->grid, term->grid->cursor.point.row); term->render.last_cursor.col = term->grid->cursor.point.col; term->render.last_cursor.hidden = term->hide_cursor; } static void dirty_cursor(struct terminal *term) { if (term->hide_cursor) return; const struct coord *cursor = &term->grid->cursor.point; struct row *row = grid_row(term->grid, cursor->row); struct cell *cell = &row->cells[cursor->col]; cell->attrs.clean = 0; row->dirty = true; } static void grid_render(struct terminal *term) { if (term->shutdown.in_progress) return; struct timespec start_time, start_double_buffering = {0}, stop_double_buffering = {0}; if (term->conf->tweak.render_timer != RENDER_TIMER_NONE) clock_gettime(CLOCK_MONOTONIC, &start_time); xassert(term->width > 0); xassert(term->height > 0); struct buffer_chain *chain = term->render.chains.grid; struct buffer *buf = shm_get_buffer(chain, term->width, term->height); /* Dirty old and current cursor cell, to ensure they’re repainted */ dirty_old_cursor(term); dirty_cursor(term); if (term->render.last_buf == NULL || term->render.last_buf->width != buf->width || term->render.last_buf->height != buf->height || term->flash.active || term->render.was_flashing || term->is_searching != term->render.was_searching || term->render.margins) { force_full_repaint(term, buf); } else if (buf->age > 0) { LOG_DBG("buffer age: %u (%p)", buf->age, (void *)buf); xassert(term->render.last_buf != NULL); xassert(term->render.last_buf != buf); xassert(term->render.last_buf->width == buf->width); xassert(term->render.last_buf->height == buf->height); clock_gettime(CLOCK_MONOTONIC, &start_double_buffering); reapply_old_damage(term, buf, term->render.last_buf); clock_gettime(CLOCK_MONOTONIC, &stop_double_buffering); } if (term->render.last_buf != NULL) { shm_unref(term->render.last_buf); term->render.last_buf = NULL; } term->render.last_buf = buf; term->render.was_flashing = term->flash.active; term->render.was_searching = term->is_searching; shm_addref(buf); buf->age = 0; free(term->render.last_buf->scroll_damage); buf->scroll_damage_count = tll_length(term->grid->scroll_damage); buf->scroll_damage = xmalloc( buf->scroll_damage_count * sizeof(buf->scroll_damage[0])); { size_t i = 0; tll_foreach(term->grid->scroll_damage, it) { buf->scroll_damage[i++] = it->item; switch (it->item.type) { case DAMAGE_SCROLL: if (term->grid->view == term->grid->offset) grid_render_scroll(term, buf, &it->item); break; case DAMAGE_SCROLL_REVERSE: if (term->grid->view == term->grid->offset) grid_render_scroll_reverse(term, buf, &it->item); break; case DAMAGE_SCROLL_IN_VIEW: grid_render_scroll(term, buf, &it->item); break; case DAMAGE_SCROLL_REVERSE_IN_VIEW: grid_render_scroll_reverse(term, buf, &it->item); break; } tll_remove(term->grid->scroll_damage, it); } } /* * Ensure selected cells have their 'selected' bit set. This is * normally "automatically" true - the bit is set when the * selection is made. * * However, if the cell is updated (printed to) while the * selection is active, the 'selected' bit is cleared. Checking * for this and re-setting the bit in term_print() is too * expensive performance wise. * * Instead, we synchronize the selection bits here and now. This * makes the performance impact linear to the number of selected * cells rather than to the number of updated cells. * * (note that selection_dirty_cells() will not set the dirty flag * on cells where the 'selected' bit is already set) */ selection_dirty_cells(term); /* Translate offset-relative row to view-relative, unless cursor * is hidden, then we just set it to -1 */ struct coord cursor = {-1, -1}; if (!term->hide_cursor) { cursor = term->grid->cursor.point; cursor.row += term->grid->offset; cursor.row -= term->grid->view; cursor.row &= term->grid->num_rows - 1; } if (term->conf->tweak.overflowing_glyphs) { /* * Pre-pass to dirty cells affected by overflowing glyphs. * * Given any two pair of cells where the first cell is * overflowing into the second, *both* cells must be * re-rendered if any one of them is dirty. * * Thus, given a string of overflowing glyphs, with a single * dirty cell in the middle, we need to re-render the entire * string. */ for (int r = 0; r < term->rows; r++) { struct row *row = grid_row_in_view(term->grid, r); if (!row->dirty) continue; /* Loop row from left to right, looking for dirty cells */ for (struct cell *cell = &row->cells[0]; cell < &row->cells[term->cols]; cell++) { if (cell->attrs.clean) continue; /* * Cell is dirty, go back and dirty previous cells, if * they are overflowing. * * As soon as we see a non-overflowing cell we can * stop, since it isn’t affecting the string of * overflowing glyphs that follows it. * * As soon as we see a dirty cell, we can stop, since * that means we’ve already handled it (remember the * outer loop goes from left to right). */ for (struct cell *c = cell - 1; c >= &row->cells[0]; c--) { if (c->attrs.confined) break; if (!c->attrs.clean) break; c->attrs.clean = false; } /* * Now move forward, dirtying all cells until we hit a * non-overflowing cell. * * Note that the first non-overflowing cell must be * re-rendered as well, but any cell *after* that is * unaffected by the string of overflowing glyphs * we’re dealing with right now. * * For performance, this iterates the *outer* loop’s * cell pointer - no point in re-checking all these * glyphs again, in the outer loop. */ for (; cell < &row->cells[term->cols]; cell++) { cell->attrs.clean = false; if (cell->attrs.confined) break; } } } } render_sixel_images(term, buf->pix[0], &cursor); if (term->render.workers.count > 0) { mtx_lock(&term->render.workers.lock); term->render.workers.buf = buf; for (size_t i = 0; i < term->render.workers.count; i++) sem_post(&term->render.workers.start); xassert(tll_length(term->render.workers.queue) == 0); } int first_dirty_row = -1; for (int r = 0; r < term->rows; r++) { struct row *row = grid_row_in_view(term->grid, r); if (!row->dirty) { if (first_dirty_row >= 0) { int x = term->margins.left; int y = term->margins.top + first_dirty_row * term->cell_height; int width = term->width - term->margins.left - term->margins.right; int height = (r - first_dirty_row) * term->cell_height; wl_surface_damage_buffer( term->window->surface, x, y, width, height); pixman_region32_union_rect( &buf->dirty, &buf->dirty, 0, y, buf->width, height); } first_dirty_row = -1; continue; } if (first_dirty_row < 0) first_dirty_row = r; row->dirty = false; if (term->render.workers.count > 0) tll_push_back(term->render.workers.queue, r); else { int cursor_col = cursor.row == r ? cursor.col : -1; render_row(term, buf->pix[0], row, r, cursor_col); } } if (first_dirty_row >= 0) { int x = term->margins.left; int y = term->margins.top + first_dirty_row * term->cell_height; int width = term->width - term->margins.left - term->margins.right; int height = (term->rows - first_dirty_row) * term->cell_height; wl_surface_damage_buffer(term->window->surface, x, y, width, height); pixman_region32_union_rect(&buf->dirty, &buf->dirty, 0, y, buf->width, height); } /* Signal workers the frame is done */ if (term->render.workers.count > 0) { for (size_t i = 0; i < term->render.workers.count; i++) tll_push_back(term->render.workers.queue, -1); mtx_unlock(&term->render.workers.lock); for (size_t i = 0; i < term->render.workers.count; i++) sem_wait(&term->render.workers.done); term->render.workers.buf = NULL; } /* Render IME pre-edit text */ render_ime_preedit(term, buf); if (term->flash.active) { /* Note: alpha is pre-computed in each color component */ /* TODO: dim while searching */ pixman_image_fill_rectangles( PIXMAN_OP_OVER, buf->pix[0], &(pixman_color_t){.red=0x7fff, .green=0x7fff, .blue=0, .alpha=0x7fff}, 1, &(pixman_rectangle16_t){0, 0, term->width, term->height}); wl_surface_damage_buffer( term->window->surface, 0, 0, term->width, term->height); } render_scrollback_position(term); if (term->conf->tweak.render_timer != RENDER_TIMER_NONE) { struct timespec end_time; clock_gettime(CLOCK_MONOTONIC, &end_time); struct timespec render_time; timespec_sub(&end_time, &start_time, &render_time); struct timespec double_buffering_time; timespec_sub(&stop_double_buffering, &start_double_buffering, &double_buffering_time); switch (term->conf->tweak.render_timer) { case RENDER_TIMER_LOG: case RENDER_TIMER_BOTH: LOG_INFO("frame rendered in %lds %ldns " "(%lds %ldns double buffering)", (long)render_time.tv_sec, render_time.tv_nsec, (long)double_buffering_time.tv_sec, double_buffering_time.tv_nsec); break; case RENDER_TIMER_OSD: case RENDER_TIMER_NONE: break; } switch (term->conf->tweak.render_timer) { case RENDER_TIMER_OSD: case RENDER_TIMER_BOTH: render_render_timer(term, render_time); break; case RENDER_TIMER_LOG: case RENDER_TIMER_NONE: break; } } xassert(term->grid->offset >= 0 && term->grid->offset < term->grid->num_rows); xassert(term->grid->view >= 0 && term->grid->view < term->grid->num_rows); xassert(term->window->frame_callback == NULL); term->window->frame_callback = wl_surface_frame(term->window->surface); wl_callback_add_listener(term->window->frame_callback, &frame_listener, term); wl_surface_set_buffer_scale(term->window->surface, term->scale); if (term->wl->presentation != NULL && term->render.presentation_timings) { struct timespec commit_time; clock_gettime(term->wl->presentation_clock_id, &commit_time); struct wp_presentation_feedback *feedback = wp_presentation_feedback( term->wl->presentation, term->window->surface); if (feedback == NULL) { LOG_WARN("failed to create presentation feedback"); } else { struct presentation_context *ctx = xmalloc(sizeof(*ctx)); *ctx = (struct presentation_context){ .term = term, .input.tv_sec = term->render.input_time.tv_sec, .input.tv_usec = term->render.input_time.tv_nsec / 1000, .commit.tv_sec = commit_time.tv_sec, .commit.tv_usec = commit_time.tv_nsec / 1000, }; wp_presentation_feedback_add_listener( feedback, &presentation_feedback_listener, ctx); term->render.input_time.tv_sec = 0; term->render.input_time.tv_nsec = 0; } } if (term->conf->tweak.damage_whole_window) { wl_surface_damage_buffer( term->window->surface, 0, 0, INT32_MAX, INT32_MAX); } xassert(buf->width % term->scale == 0); xassert(buf->height % term->scale == 0); wl_surface_attach(term->window->surface, buf->wl_buf, 0, 0); wl_surface_commit(term->window->surface); } static void render_search_box(struct terminal *term) { xassert(term->window->search.sub != NULL); /* * We treat the search box pretty much like a row of cells. That * is, a glyph is either 1 or 2 (or more) “cells” wide. * * The search ‘length’, and ‘cursor’ (position) is in * *characters*, not cells. This means we need to translate from * character count to cell count when calculating the length of * the search box, where in the search string we should start * rendering etc. */ #if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED /* TODO: do we want to/need to handle multi-seat? */ struct seat *ime_seat = NULL; tll_foreach(term->wl->seats, it) { if (it->item.kbd_focus == term) { ime_seat = &it->item; break; } } size_t text_len = term->search.len; if (ime_seat != NULL && ime_seat->ime.preedit.text != NULL) text_len += wcslen(ime_seat->ime.preedit.text); wchar_t *text = xmalloc((text_len + 1) * sizeof(wchar_t)); text[0] = L'\0'; /* Copy everything up to the cursor */ wcsncpy(text, term->search.buf, term->search.cursor); text[term->search.cursor] = L'\0'; /* Insert pre-edit text at cursor */ if (ime_seat != NULL && ime_seat->ime.preedit.text != NULL) wcscat(text, ime_seat->ime.preedit.text); /* And finally everything after the cursor */ wcsncat(text, &term->search.buf[term->search.cursor], term->search.len - term->search.cursor); #else const wchar_t *text = term->search.buf; const size_t text_len = term->search.len; #endif /* Calculate the width of each character */ int widths[text_len + 1]; for (size_t i = 0; i < text_len; i++) widths[i] = max(0, wcwidth(text[i])); widths[text_len] = 0; const size_t total_cells = wcswidth(text, text_len); const size_t wanted_visible_cells = max(20, total_cells); xassert(term->scale >= 1); const int scale = term->scale; const size_t margin = 3 * scale; const size_t width = term->width - 2 * margin; const size_t visible_width = min( term->width - 2 * margin, (2 * margin + wanted_visible_cells * term->cell_width + scale - 1) / scale * scale); const size_t height = min( term->height - 2 * margin, (2 * margin + 1 * term->cell_height + scale - 1) / scale * scale); const size_t visible_cells = (visible_width - 2 * margin) / term->cell_width; size_t glyph_offset = term->render.search_glyph_offset; struct buffer_chain *chain = term->render.chains.search; struct buffer *buf = shm_get_buffer(chain, width, height); pixman_region32_t clip; pixman_region32_init_rect(&clip, 0, 0, width, height); pixman_image_set_clip_region32(buf->pix[0], &clip); pixman_region32_fini(&clip); #define WINDOW_X(x) (margin + x) #define WINDOW_Y(y) (term->height - margin - height + y) /* Background - yellow on empty/match, red on mismatch */ pixman_color_t color = color_hex_to_pixman( term->search.match_len == text_len ? term->colors.table[3] : term->colors.table[1]); pixman_image_fill_rectangles( PIXMAN_OP_SRC, buf->pix[0], &color, 1, &(pixman_rectangle16_t){width - visible_width, 0, visible_width, height}); pixman_color_t transparent = color_hex_to_pixman_with_alpha(0, 0); pixman_image_fill_rectangles( PIXMAN_OP_SRC, buf->pix[0], &transparent, 1, &(pixman_rectangle16_t){0, 0, width - visible_width, height}); struct fcft_font *font = term->fonts[0]; const int x_left = width - visible_width + margin; const int x_ofs = term->font_x_ofs; int x = x_left; int y = margin; pixman_color_t fg = color_hex_to_pixman(term->colors.table[0]); /* Move offset we start rendering at, to ensure the cursor is visible */ for (size_t i = 0, cell_idx = 0; i <= term->search.cursor; cell_idx += widths[i], i++) { if (i != term->search.cursor) continue; #if (FOOT_IME_ENABLED) && FOOT_IME_ENABLED if (ime_seat != NULL && ime_seat->ime.preedit.cells != NULL) { if (ime_seat->ime.preedit.cursor.start == ime_seat->ime.preedit.cursor.end) { /* All IME's I've seen so far keeps the cursor at * index 0, so ensure the *end* of the pre-edit string * is visible */ cell_idx += ime_seat->ime.preedit.count; } else { /* Try to predict in which direction we'll shift the text */ if (cell_idx + ime_seat->ime.preedit.cursor.start > glyph_offset) cell_idx += ime_seat->ime.preedit.cursor.end; else cell_idx += ime_seat->ime.preedit.cursor.start; } } #endif if (cell_idx < glyph_offset) { /* Shift to the *left*, making *this* character the * *first* visible one */ term->render.search_glyph_offset = glyph_offset = cell_idx; } else if (cell_idx > glyph_offset + visible_cells) { /* Shift to the *right*, making *this* character the * *last* visible one */ term->render.search_glyph_offset = glyph_offset = cell_idx - min(cell_idx, visible_cells); } /* Adjust offset if there is free space available */ if (total_cells - glyph_offset < visible_cells) { term->render.search_glyph_offset = glyph_offset = total_cells - min(total_cells, visible_cells); } break; } /* Ensure offset is at a character boundary */ for (size_t i = 0, cell_idx = 0; i <= text_len; cell_idx += widths[i], i++) { if (cell_idx >= glyph_offset) { term->render.search_glyph_offset = glyph_offset = cell_idx; break; } } /* * Render the search string, starting at ‘glyph_offset’. Note that * glyph_offset is in cells, not characters */ for (size_t i = 0, cell_idx = 0, width = widths[i], next_cell_idx = width; i < text_len; i++, cell_idx = next_cell_idx, width = widths[i], next_cell_idx += width) { /* Convert subsurface coordinates to window coordinates*/ /* Render cursor */ if (i == term->search.cursor) { #if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED bool have_preedit = ime_seat != NULL && ime_seat->ime.preedit.cells != NULL; bool hidden = ime_seat != NULL && ime_seat->ime.preedit.cursor.hidden; if (have_preedit && !hidden) { /* Cursor may be outside the visible area: * cell_idx-glyph_offset can be negative */ int cells_left = visible_cells - max( (ssize_t)(cell_idx - glyph_offset), 0); /* If cursor is outside the visible area, we need to * adjust our rectangle's position */ int start = ime_seat->ime.preedit.cursor.start + min((ssize_t)(cell_idx - glyph_offset), 0); int end = ime_seat->ime.preedit.cursor.end + min((ssize_t)(cell_idx - glyph_offset), 0); if (start == end) { int count = min(ime_seat->ime.preedit.count, cells_left); /* Underline the entire (visible part of) pre-edit text */ draw_underline(term, buf->pix[0], font, &fg, x, y, count); /* Bar-styled cursor, if in the visible area */ if (start >= 0 && start <= visible_cells) { draw_beam_cursor( term, buf->pix[0], font, &fg, x + start * term->cell_width, y); } term_ime_set_cursor_rect(term, WINDOW_X(x + start * term->cell_width), WINDOW_Y(y), 1, term->cell_height); } else { /* Underline everything before and after the cursor */ int count1 = min(start, cells_left); int count2 = max( min(ime_seat->ime.preedit.count - ime_seat->ime.preedit.cursor.end, cells_left - end), 0); draw_underline(term, buf->pix[0], font, &fg, x, y, count1); draw_underline(term, buf->pix[0], font, &fg, x + end * term->cell_width, y, count2); /* TODO: how do we handle a partially hidden rectangle? */ if (start >= 0 && end <= visible_cells) { draw_unfocused_block( term, buf->pix[0], &fg, x + start * term->cell_width, y, end - start); } term_ime_set_cursor_rect(term, WINDOW_X(x + start * term->cell_width), WINDOW_Y(y), term->cell_width * (end - start), term->cell_height); } } else if (!have_preedit) #endif { /* Cursor *should* be in the visible area */ xassert(cell_idx >= glyph_offset); xassert(cell_idx <= glyph_offset + visible_cells); draw_beam_cursor(term, buf->pix[0], font, &fg, x, y); term_ime_set_cursor_rect( term, WINDOW_X(x), WINDOW_Y(y), 1, term->cell_height); } } if (next_cell_idx >= glyph_offset && next_cell_idx - glyph_offset > visible_cells) { /* We're now beyond the visible area - nothing more to render */ break; } if (cell_idx < glyph_offset) { /* We haven't yet reached the visible part of the string */ cell_idx = next_cell_idx; continue; } const struct fcft_glyph *glyph = fcft_glyph_rasterize( font, text[i], term->font_subpixel); if (glyph == NULL) { cell_idx = next_cell_idx; continue; } if (unlikely(pixman_image_get_format(glyph->pix) == PIXMAN_a8r8g8b8)) { /* Glyph surface is a pre-rendered image (typically a color emoji...) */ pixman_image_composite32( PIXMAN_OP_OVER, glyph->pix, NULL, buf->pix[0], 0, 0, 0, 0, x + x_ofs + glyph->x, y + font_baseline(term) - glyph->y, glyph->width, glyph->height); } else { int combining_ofs = width == 0 ? (glyph->x < 0 ? width * term->cell_width : (width - 1) * term->cell_width) : 0; /* Not a zero-width character - no additional offset */ pixman_image_t *src = pixman_image_create_solid_fill(&fg); pixman_image_composite32( PIXMAN_OP_OVER, src, glyph->pix, buf->pix[0], 0, 0, 0, 0, x + x_ofs + combining_ofs + glyph->x, y + font_baseline(term) - glyph->y, glyph->width, glyph->height); pixman_image_unref(src); } x += width * term->cell_width; cell_idx = next_cell_idx; } #if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED if (ime_seat != NULL && ime_seat->ime.preedit.cells != NULL) /* Already rendered */; else #endif if (term->search.cursor >= term->search.len) { draw_beam_cursor(term, buf->pix[0], font, &fg, x, y); term_ime_set_cursor_rect( term, WINDOW_X(x), WINDOW_Y(y), 1, term->cell_height); } quirk_weston_subsurface_desync_on(term->window->search.sub); /* TODO: this is only necessary on a window resize */ wl_subsurface_set_position( term->window->search.sub, margin / scale, max(0, (int32_t)term->height - height - margin) / scale); xassert(buf->width % scale == 0); xassert(buf->height % scale == 0); wl_surface_attach(term->window->search.surf, buf->wl_buf, 0, 0); wl_surface_damage_buffer(term->window->search.surf, 0, 0, width, height); wl_surface_set_buffer_scale(term->window->search.surf, scale); struct wl_region *region = wl_compositor_create_region(term->wl->compositor); if (region != NULL) { wl_region_add(region, width - visible_width, 0, visible_width, height); wl_surface_set_opaque_region(term->window->search.surf, region); wl_region_destroy(region); } wl_surface_commit(term->window->search.surf); quirk_weston_subsurface_desync_off(term->window->search.sub); #if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED free(text); #endif #undef WINDOW_X #undef WINDOW_Y } static void render_urls(struct terminal *term) { struct wl_window *win = term->window; xassert(tll_length(win->urls) > 0); const int scale = term->scale; const int x_margin = 2 * scale; const int y_margin = 1 * scale; /* Calculate view start, counted from the *current* scrollback start */ const int scrollback_end = (term->grid->offset + term->rows) & (term->grid->num_rows - 1); const int view_start = (term->grid->view - scrollback_end + term->grid->num_rows) & (term->grid->num_rows - 1); const int view_end = view_start + term->rows - 1; const bool show_url = term->urls_show_uri_on_jump_label; /* * There can potentially be a lot of URLs. * * Since each URL is a separate sub-surface, and requires its own * SHM buffer, we may be allocating a lot of buffers. * * SHM buffers normally have their own, private SHM buffer * pool. Each pool is mmapped, and thus allocates *at least* * 4K. Since URL labels are typically small, we end up using an * excessive amount of both virtual and physical memory. * * For this reason, we instead use shm_get_many(), which uses a * single, shared pool for all buffers. * * To be able to use it, we need to have all the *all* the buffer * dimensions up front. * * Thus, the first iteration through the URLs do the heavy * lifting: builds the label contents and calculates both its * position and size. But instead of rendering the label * immediately, we store the calculated data, and then do a second * pass, where we first get all our buffers, and then render to * them. */ /* Positioning data + label contents */ struct { const struct wl_url *url; wchar_t *text; int x; int y; } info[tll_length(win->urls)]; /* For shm_get_many() */ int widths[tll_length(win->urls)]; int heights[tll_length(win->urls)]; size_t render_count = 0; tll_foreach(win->urls, it) { const struct url *url = it->item.url; const wchar_t *key = url->key; const size_t entered_key_len = wcslen(term->url_keys); if (key == NULL) { /* TODO: if we decide to use the .text field, we cannot * just skip the entire jump label like this */ continue; } struct wl_surface *surf = it->item.surf.surf; struct wl_subsurface *sub_surf = it->item.surf.sub; if (surf == NULL || sub_surf == NULL) continue; bool hide = false; const struct coord *pos = &url->start; const int _row = (pos->row - scrollback_end + term->grid->num_rows) & (term->grid->num_rows - 1); if (_row < view_start || _row > view_end) hide = true; if (wcslen(key) <= entered_key_len) hide = true; if (wcsncasecmp(term->url_keys, key, entered_key_len) != 0) hide = true; if (hide) { wl_surface_attach(surf, NULL, 0, 0); wl_surface_commit(surf); continue; } int col = pos->col; int row = pos->row - term->grid->view; while (row < 0) row += term->grid->num_rows; row &= (term->grid->num_rows - 1); /* Position label slightly above and to the left */ int x = col * term->cell_width - 15 * term->cell_width / 10; int y = row * term->cell_height - 5 * term->cell_height / 10; /* Don’t position it outside our window */ if (x < -term->margins.left) x = -term->margins.left; if (y < -term->margins.top) y = -term->margins.top; /* Maximum width of label, in pixels */ const int max_width = term->width - term->margins.left - term->margins.right - x; const int max_cols = max_width / term->cell_width; const size_t key_len = wcslen(key); size_t url_len = mbstowcs(NULL, url->url, 0); if (url_len == (size_t)-1) url_len = 0; wchar_t url_wchars[url_len + 1]; mbstowcs(url_wchars, url->url, url_len + 1); /* Format label, not yet subject to any size limitations */ size_t chars = key_len + (show_url ? (2 + url_len) : 0); wchar_t label[chars + 1]; label[chars] = L'\0'; if (show_url) swprintf(label, chars + 1, L"%ls: %ls", key, url_wchars); else wcsncpy(label, key, chars); /* Upper case the key characters */ for (size_t i = 0; i < wcslen(key); i++) label[i] = towupper(label[i]); /* Blank already entered key characters */ for (size_t i = 0; i < entered_key_len; i++) label[i] = L' '; /* * Don’t extend outside our window * * Truncate label so that it doesn’t extend outside our * window. * * Do it in a way such that we don’t cut the label in the * middle of a double-width character. */ int cols = 0; for (size_t i = 0; i <= wcslen(label); i++) { int _cols = wcswidth(label, i); if (_cols == (size_t)-1) continue; if (_cols >= max_cols) { if (i > 0) label[i - 1] = L'…'; label[i] = L'\0'; cols = max_cols; break; } cols = _cols; } if (cols == 0) continue; const int width = (2 * x_margin + cols * term->cell_width + scale - 1) / scale * scale; const int height = (2 * y_margin + term->cell_height + scale - 1) / scale * scale; info[render_count].url = &it->item; info[render_count].text = xwcsdup(label); info[render_count].x = x; info[render_count].y = y; widths[render_count] = width; heights[render_count] = height; render_count++; } struct buffer_chain *chain = term->render.chains.url; struct buffer *bufs[render_count]; shm_get_many(chain, render_count, widths, heights, bufs); uint32_t fg = term->conf->colors.use_custom.jump_label ? term->conf->colors.jump_label.fg : term->colors.table[0]; uint32_t bg = term->conf->colors.use_custom.jump_label ? term->conf->colors.jump_label.bg : term->colors.table[3]; for (size_t i = 0; i < render_count; i++) { struct wl_surface *surf = info[i].url->surf.surf; struct wl_subsurface *sub_surf = info[i].url->surf.sub; const wchar_t *label = info[i].text; const int x = info[i].x; const int y = info[i].y; xassert(surf != NULL); xassert(sub_surf != NULL); wl_subsurface_set_position( sub_surf, (term->margins.left + x) / term->scale, (term->margins.top + y) / term->scale); render_osd( term, surf, sub_surf, term->fonts[0], bufs[i], label, fg, 0xffu << 24 | bg, x_margin, y_margin); free(info[i].text); } } static void render_update_title(struct terminal *term) { static const size_t max_len = 2048; const char *title = term->window_title != NULL ? term->window_title : "foot"; char *copy = NULL; if (strlen(title) > max_len) { copy = xstrndup(title, max_len); title = copy; } xdg_toplevel_set_title(term->window->xdg_toplevel, title); free(copy); } static void frame_callback(void *data, struct wl_callback *wl_callback, uint32_t callback_data) { struct terminal *term = data; xassert(term->window->frame_callback == wl_callback); wl_callback_destroy(wl_callback); term->window->frame_callback = NULL; bool grid = term->render.pending.grid; bool csd = term->render.pending.csd; bool search = term->is_searching && term->render.pending.search; bool urls = urls_mode_is_active(term) > 0 && term->render.pending.urls; term->render.pending.grid = false; term->render.pending.csd = false; term->render.pending.search = false; term->render.pending.urls = false; struct grid *original_grid = term->grid; if (urls_mode_is_active(term)) { xassert(term->url_grid_snapshot != NULL); term->grid = term->url_grid_snapshot; } if (csd && term->window->csd_mode == CSD_YES) { quirk_weston_csd_on(term); render_csd(term); quirk_weston_csd_off(term); } if (search) render_search_box(term); if (urls) render_urls(term); if (grid && (!term->delayed_render_timer.is_armed | csd | search | urls)) grid_render(term); tll_foreach(term->wl->seats, it) { if (it->item.kbd_focus == term) ime_update_cursor_rect(&it->item); } term->grid = original_grid; } static void tiocswinsz(struct terminal *term) { if (term->ptmx >= 0) { if (ioctl(term->ptmx, (unsigned int)TIOCSWINSZ, &(struct winsize){ .ws_row = term->rows, .ws_col = term->cols, .ws_xpixel = term->cols * term->cell_width, .ws_ypixel = term->rows * term->cell_height}) < 0) { LOG_ERRNO("TIOCSWINSZ"); } } } static bool fdm_tiocswinsz(struct fdm *fdm, int fd, int events, void *data) { struct terminal *term = data; if (events & EPOLLIN) tiocswinsz(term); if (term->window->resize_timeout_fd >= 0) { fdm_del(fdm, term->window->resize_timeout_fd); term->window->resize_timeout_fd = -1; } return true; } static void send_dimensions_to_client(struct terminal *term) { struct wl_window *win = term->window; if (!win->is_resizing || term->conf->resize_delay_ms == 0) { /* Send new dimensions to client immediately */ tiocswinsz(term); /* And make sure to reset and deallocate a lingering timer */ if (win->resize_timeout_fd >= 0) { fdm_del(term->fdm, win->resize_timeout_fd); win->resize_timeout_fd = -1; } } else { /* Send new dimensions to client “in a while” */ assert(win->is_resizing && term->conf->resize_delay_ms > 0); int fd = win->resize_timeout_fd; uint16_t delay_ms = term->conf->resize_delay_ms; bool successfully_scheduled = false; if (fd < 0) { /* Lazy create timer fd */ fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK); if (fd < 0) LOG_ERRNO("failed to create TIOCSWINSZ timer"); else if (!fdm_add(term->fdm, fd, EPOLLIN, &fdm_tiocswinsz, term)) { close(fd); fd = -1; } win->resize_timeout_fd = fd; } if (fd >= 0) { /* Reset timeout */ const struct itimerspec timeout = { .it_value = {.tv_sec = 0, .tv_nsec = delay_ms * 1000000}, }; if (timerfd_settime(fd, 0, &timeout, NULL) < 0) { LOG_ERRNO("failed to arm TIOCSWINSZ timer"); fdm_del(term->fdm, fd); win->resize_timeout_fd = -1; } else successfully_scheduled = true; } if (!successfully_scheduled) tiocswinsz(term); } } /* Move to terminal.c? */ static bool maybe_resize(struct terminal *term, int width, int height, bool force) { if (term->shutdown.in_progress) return false; if (!term->window->is_configured) return false; if (term->cell_width == 0 && term->cell_height == 0) return false; int scale = -1; tll_foreach(term->window->on_outputs, it) { if (it->item->scale > scale) scale = it->item->scale; } if (scale < 0) { /* Haven't 'entered' an output yet? */ scale = term->scale; } width *= scale; height *= scale; if (width == 0 && height == 0) { /* * The compositor is letting us choose the size * * If we have a "last" used size - use that. Otherwise, use * the size from the user configuration. */ if (term->stashed_width != 0 && term->stashed_height != 0) { width = term->stashed_width; height = term->stashed_height; } else { switch (term->conf->size.type) { case CONF_SIZE_PX: width = term->conf->size.width; height = term->conf->size.height; if (term->window->csd_mode == CSD_YES) { /* Take CSD title bar into account */ xassert(!term->window->is_fullscreen); height -= term->conf->csd.title_height; } width *= scale; height *= scale; break; case CONF_SIZE_CELLS: width = term->conf->size.width * term->cell_width; height = term->conf->size.height * term->cell_height; width += 2 * term->conf->pad_x * scale; height += 2 * term->conf->pad_y * scale; /* * Ensure we can scale to logical size, and back to * pixels without truncating. */ if (width % scale) width += scale - width % scale; if (height % scale) height += scale - height % scale; xassert(width % scale == 0); xassert(height % scale == 0); break; } } } /* Don't shrink grid too much */ const int min_cols = 2; const int min_rows = 1; /* Minimum window size */ const int min_width = min_cols * term->cell_width; const int min_height = min_rows * term->cell_height; width = max(width, min_width); height = max(height, min_height); /* Padding */ const int max_pad_x = (width - min_width) / 2; const int max_pad_y = (height - min_height) / 2; const int pad_x = min(max_pad_x, scale * term->conf->pad_x); const int pad_y = min(max_pad_y, scale * term->conf->pad_y); if (!force && width == term->width && height == term->height && scale == term->scale) return false; /* Cancel an application initiated "Synchronized Update" */ term_disable_app_sync_updates(term); /* Drop out of URL mode */ urls_reset(term); term->width = width; term->height = height; term->scale = scale; const uint32_t scrollback_lines = term->render.scrollback_lines; /* Screen rows/cols before resize */ const int old_cols = term->cols; const int old_rows = term->rows; /* Screen rows/cols after resize */ const int new_cols = (term->width - 2 * pad_x) / term->cell_width; const int new_rows = (term->height - 2 * pad_y) / term->cell_height; /* Grid rows/cols after resize */ const int new_normal_grid_rows = 1 << (32 - __builtin_clz(new_rows + scrollback_lines - 1)); const int new_alt_grid_rows = 1 << (32 - __builtin_clz(new_rows)); xassert(new_cols >= 1); xassert(new_rows >= 1); /* Margins */ const int grid_width = new_cols * term->cell_width; const int grid_height = new_rows * term->cell_height; const int total_x_pad = term->width - grid_width; const int total_y_pad = term->height - grid_height; if (term->conf->center && !term->window->is_resizing) { term->margins.left = total_x_pad / 2; term->margins.top = total_y_pad / 2; } else { term->margins.left = pad_x; term->margins.top = pad_y; } term->margins.right = total_x_pad - term->margins.left; term->margins.bottom = total_y_pad - term->margins.top; xassert(term->margins.left >= pad_x); xassert(term->margins.right >= pad_x); xassert(term->margins.top >= pad_y); xassert(term->margins.bottom >= pad_y); if (new_cols == old_cols && new_rows == old_rows) { LOG_DBG("grid layout unaffected; skipping reflow"); goto damage_view; } if (term->grid == &term->alt) selection_cancel(term); struct coord *const tracking_points[] = { &term->selection.start, &term->selection.end, }; /* Resize grids */ grid_resize_and_reflow( &term->normal, new_normal_grid_rows, new_cols, old_rows, new_rows, term->selection.end.row >= 0 ? ALEN(tracking_points) : 0, tracking_points); grid_resize_without_reflow( &term->alt, new_alt_grid_rows, new_cols, old_rows, new_rows); /* Reset tab stops */ tll_free(term->tab_stops); for (int c = 0; c < new_cols; c += 8) tll_push_back(term->tab_stops, c); term->cols = new_cols; term->rows = new_rows; sixel_reflow(term); #if defined(_DEBUG) && LOG_ENABLE_DBG LOG_DBG("resize: %dx%d, grid: cols=%d, rows=%d " "(left-margin=%d, right-margin=%d, top-margin=%d, bottom-margin=%d)", term->width, term->height, term->cols, term->rows, term->margins.left, term->margins.right, term->margins.top, term->margins.bottom); #endif if (term->scroll_region.start >= term->rows) term->scroll_region.start = 0; if (term->scroll_region.end >= old_rows) term->scroll_region.end = term->rows; term->render.last_cursor.row = NULL; damage_view: /* Signal TIOCSWINSZ */ send_dimensions_to_client(term); if (!term->window->is_maximized && !term->window->is_fullscreen && !term->window->is_tiled) { /* Stash current size, to enable us to restore it when we're * being un-maximized/fullscreened/tiled */ term->stashed_width = term->width; term->stashed_height = term->height; } #if 0 /* TODO: doesn't include CSD title bar */ xdg_toplevel_set_min_size( term->window->xdg_toplevel, min_width / scale, min_height / scale); #endif { bool title_shown = !term->window->is_fullscreen && term->window->csd_mode == CSD_YES; int title_height = title_shown ? term->conf->csd.title_height : 0; xdg_surface_set_window_geometry( term->window->xdg_surface, 0, -title_height, term->width / term->scale, term->height / term->scale + title_height); } tll_free(term->normal.scroll_damage); tll_free(term->alt.scroll_damage); shm_unref(term->render.last_buf); term->render.last_buf = NULL; term_damage_view(term); render_refresh_csd(term); render_refresh_search(term); render_refresh(term); return true; } bool render_resize(struct terminal *term, int width, int height) { return maybe_resize(term, width, height, false); } bool render_resize_force(struct terminal *term, int width, int height) { return maybe_resize(term, width, height, true); } static void xcursor_callback( void *data, struct wl_callback *wl_callback, uint32_t callback_data); static const struct wl_callback_listener xcursor_listener = { .done = &xcursor_callback, }; static void render_xcursor_update(struct seat *seat) { /* If called from a frame callback, we may no longer have mouse focus */ if (!seat->mouse_focus) return; xassert(seat->pointer.xcursor != NULL); if (seat->pointer.xcursor == XCURSOR_HIDDEN) { /* Hide cursor */ wl_surface_attach(seat->pointer.surface, NULL, 0, 0); wl_surface_commit(seat->pointer.surface); return; } seat->pointer.cursor = wl_cursor_theme_get_cursor( seat->pointer.theme, seat->pointer.xcursor); if (seat->pointer.cursor == NULL) { LOG_ERR("failed to load xcursor pointer '%s'", seat->pointer.xcursor); return; } const int scale = seat->pointer.scale; struct wl_cursor_image *image = seat->pointer.cursor->images[0]; wl_surface_attach( seat->pointer.surface, wl_cursor_image_get_buffer(image), 0, 0); wl_pointer_set_cursor( seat->wl_pointer, seat->pointer.serial, seat->pointer.surface, image->hotspot_x / scale, image->hotspot_y / scale); wl_surface_damage_buffer( seat->pointer.surface, 0, 0, INT32_MAX, INT32_MAX); wl_surface_set_buffer_scale(seat->pointer.surface, scale); xassert(seat->pointer.xcursor_callback == NULL); seat->pointer.xcursor_callback = wl_surface_frame(seat->pointer.surface); wl_callback_add_listener(seat->pointer.xcursor_callback, &xcursor_listener, seat); wl_surface_commit(seat->pointer.surface); } static void xcursor_callback(void *data, struct wl_callback *wl_callback, uint32_t callback_data) { struct seat *seat = data; xassert(seat->pointer.xcursor_callback == wl_callback); wl_callback_destroy(wl_callback); seat->pointer.xcursor_callback = NULL; if (seat->pointer.xcursor_pending) { render_xcursor_update(seat); seat->pointer.xcursor_pending = false; } } static void fdm_hook_refresh_pending_terminals(struct fdm *fdm, void *data) { struct renderer *renderer = data; struct wayland *wayl = renderer->wayl; tll_foreach(renderer->wayl->terms, it) { struct terminal *term = it->item; if (unlikely(term->shutdown.in_progress || !term->window->is_configured)) continue; bool grid = term->render.refresh.grid; bool csd = term->render.refresh.csd; bool search = term->is_searching && term->render.refresh.search; bool urls = urls_mode_is_active(term) && term->render.refresh.urls; if (!(grid | csd | search | urls)) continue; if (term->render.app_sync_updates.enabled && !(csd | search | urls)) continue; term->render.refresh.grid = false; term->render.refresh.csd = false; term->render.refresh.search = false; term->render.refresh.urls = false; if (term->window->frame_callback == NULL) { struct grid *original_grid = term->grid; if (urls_mode_is_active(term)) { xassert(term->url_grid_snapshot != NULL); term->grid = term->url_grid_snapshot; } if (csd && term->window->csd_mode == CSD_YES) { quirk_weston_csd_on(term); render_csd(term); quirk_weston_csd_off(term); } if (search) render_search_box(term); if (urls) render_urls(term); if (grid | csd | search | urls) grid_render(term); tll_foreach(term->wl->seats, it) { if (it->item.kbd_focus == term) ime_update_cursor_rect(&it->item); } term->grid = original_grid; } else { /* Tells the frame callback to render again */ term->render.pending.grid |= grid; term->render.pending.csd |= csd; term->render.pending.search |= search; term->render.pending.urls |= urls; } } tll_foreach(wayl->seats, it) { if (it->item.pointer.xcursor_pending) { if (it->item.pointer.xcursor_callback == NULL) { render_xcursor_update(&it->item); it->item.pointer.xcursor_pending = false; } else { /* Frame callback will call render_xcursor_update() */ } } } } void render_refresh_title(struct terminal *term) { if (term->render.title.is_armed) return; struct timespec now; if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) return; struct timespec diff; timespec_sub(&now, &term->render.title.last_update, &diff); if (diff.tv_sec == 0 && diff.tv_nsec < 8333 * 1000) { const struct itimerspec timeout = { .it_value = {.tv_nsec = 8333 * 1000 - diff.tv_nsec}, }; timerfd_settime(term->render.title.timer_fd, 0, &timeout, NULL); } else { term->render.title.last_update = now; render_update_title(term); } render_refresh_csd(term); } void render_refresh(struct terminal *term) { term->render.refresh.grid = true; } void render_refresh_csd(struct terminal *term) { if (term->window->csd_mode == CSD_YES) term->render.refresh.csd = true; } void render_refresh_search(struct terminal *term) { if (term->is_searching) term->render.refresh.search = true; } void render_refresh_urls(struct terminal *term) { if (urls_mode_is_active(term)) term->render.refresh.urls = true; } bool render_xcursor_set(struct seat *seat, struct terminal *term, const char *xcursor) { if (seat->pointer.theme == NULL) return false; if (seat->mouse_focus == NULL) { seat->pointer.xcursor = NULL; return true; } if (seat->mouse_focus != term) { /* This terminal doesn't have mouse focus */ return true; } if (seat->pointer.xcursor == xcursor) return true; /* FDM hook takes care of actual rendering */ seat->pointer.xcursor_pending = true; seat->pointer.xcursor = xcursor; return true; }
32.83179
157
0.583366
493be861524693bad4f262221ccf625da67d162f
477
c
C
kernel/arch/x86_64/irq/main.c
killvxk/MiraiOS
d18b33cbab198e1253fc6474799a22d8431a5b86
[ "MIT" ]
null
null
null
kernel/arch/x86_64/irq/main.c
killvxk/MiraiOS
d18b33cbab198e1253fc6474799a22d8431a5b86
[ "MIT" ]
null
null
null
kernel/arch/x86_64/irq/main.c
killvxk/MiraiOS
d18b33cbab198e1253fc6474799a22d8431a5b86
[ "MIT" ]
2
2018-03-28T15:05:09.000Z
2018-07-19T03:37:16.000Z
#include <irq.h> #include <stdint.h> #include <mm/heap.h> #include <sched/spinlock.h> #include <arch/idt.h> #include "exception.h" extern void undefinedInterrupt(void); extern void dummyInterrupt(void); extern void initIrqStubs(void); void archInitInterrupts(void) { initIDT(); initExceptions(); initIrqStubs(); for (int i = 0xE0; i < 0x100; i++) { if (i >= 0xF0) { mapIdtEntry(undefinedInterrupt, i, 0); } else { mapIdtEntry(dummyInterrupt, i, 0); } } }
17.666667
41
0.679245
1bc229bea5a1b50aa7b59bdfaaaed891d10fe3be
4,815
c
C
mos/chips/apds9300/apds9300.c
zxpower/MansOS
1130f54357649eb25020951951d9a5963e755c66
[ "MIT" ]
10
2015-10-14T12:35:50.000Z
2022-02-20T12:24:36.000Z
mos/chips/apds9300/apds9300.c
zxpower/MansOS
1130f54357649eb25020951951d9a5963e755c66
[ "MIT" ]
13
2015-11-24T03:25:08.000Z
2017-02-08T09:15:45.000Z
mos/chips/apds9300/apds9300.c
zxpower/MansOS
1130f54357649eb25020951951d9a5963e755c66
[ "MIT" ]
7
2015-10-15T07:53:52.000Z
2020-12-15T00:15:49.000Z
/* * Copyright (c) 2008-2013 the MansOS team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "apds9300.h" #include <i2c.h> #include <print.h> #include <platform.h> #define APDS9300_I2C_ID I2C_BUS_SW #define ENABLE_APDS_INTERRUPTS 0 void apdsInit(void) { // init SDA and SCK pins (defined in config file) i2cInit(APDS9300_I2C_ID); #if ENABLE_APDS_INTERRUPTS // init INT pin pinAsInput(APDS_INT_PORT, APDS_INT_PIN); pinEnableInt(APDS_INT_PORT, APDS_INT_PIN); pinClearIntFlag(APDS_INT_PORT, APDS_INT_PIN); #endif } uint8_t apdsWriteByte(uint8_t cmd, uint8_t val) { uint8_t err = 0; Handle_t intHandle; ATOMIC_START(intHandle); i2cSoftStart(); err |= i2cSoftWriteByte(SLAVE_ADDRESS << 1); err <<= 1; err |= i2cSoftWriteByte(cmd); err <<= 1; err |= i2cSoftWriteByte(val); i2cSoftStop(); ATOMIC_END(intHandle); return err; } uint8_t apdsWriteWord(uint8_t cmd, uint16_t val) { uint8_t err = 0; Handle_t intHandle; ATOMIC_START(intHandle); i2cSoftStart(); err |= i2cSoftWriteByte(SLAVE_ADDRESS << 1); err <<= 1; err |= i2cSoftWriteByte(cmd | I2C_WORD); err <<= 1; err |= i2cSoftWriteByte(val & 0xff); err <<= 1; err |= i2cSoftWriteByte(val >> 8); i2cSoftStop(); ATOMIC_END(intHandle); return err; } uint8_t apdsReadByte(uint8_t cmd, uint8_t *value) { uint8_t err = 0; Handle_t intHandle; ATOMIC_START(intHandle); i2cSoftStart(); err |= i2cSoftWriteByte(SLAVE_ADDRESS << 1 ); err <<= 1; err |= i2cSoftWriteByte(cmd); err <<= 1; i2cSoftStop(); i2cSoftStart(); err |= i2cSoftWriteByte((SLAVE_ADDRESS << 1) | 0x1); uint8_t tempVal = i2cSoftReadByte(I2C_ACK); *value = tempVal; i2cSoftStop(); ATOMIC_END(intHandle); return err; } uint8_t apdsReadWord(uint8_t cmd, uint16_t *value) { uint8_t err = 0; Handle_t intHandle; ATOMIC_START(intHandle); i2cSoftStart(); err |= i2cSoftWriteByte(SLAVE_ADDRESS << 1); err <<= 1; err |= i2cSoftWriteByte(cmd | I2C_WORD); err <<= 1; i2cSoftStop(); i2cSoftStart(); err |= i2cSoftWriteByte((SLAVE_ADDRESS << 1) | 0x1); uint8_t tempValLo = i2cSoftReadByte(I2C_ACK); uint8_t tempValHi = i2cSoftReadByte(I2C_ACK); *value = tempValLo | (tempValHi << 8); i2cSoftStop(); ATOMIC_END(intHandle); return err; } bool apdsOn(void) { uint8_t err; if ((err = apdsCommand(CONTROL_REG, POWER_UP))) { DEBUG_PRINTF("apdsOn: err=0x%x\n", err); return false; } return true; } void apdsOff(void) { apdsCommand(CONTROL_REG, POWER_DOWN); } #if ENABLE_APDS_INTERRUPTS ISR(PORT2, apds_interrupt) { if (pinReadIntFlag(APDS_INT_PORT, APDS_INT_PIN)) { PRINTF("got apds interrupt!\n"); pinClearIntFlag(APDS_INT_PORT, APDS_INT_PIN); } else { PRINTF("got some other port1 interrupt!\n"); } } #endif uint8_t apdsData0Read(uint16_t *data) { uint8_t err = false; uint8_t datalow, datahigh; err |= apdsReadByte(COMMAND | DATA0LOW_REG, &datalow); err <<= 1; err |= apdsReadByte(COMMAND | DATA0HIGH_REG, &datahigh); *data = (datalow | (datahigh << 8)); return err; } uint8_t apdsData1Read(uint16_t *data) { uint8_t err = false; uint8_t datalow, datahigh; err |= apdsReadByte(COMMAND | DATA1LOW_REG, &datalow); err <<= 1; err |= apdsReadByte(COMMAND | DATA1HIGH_REG, &datahigh); *data = (datalow | (datahigh << 8)); return err; }
30.09375
78
0.686397
adaf5d86e8e37df5fa918dbd6c2d1545d51787ff
803
h
C
mainwindow.h
fikret0/fluxchess
6fb97f30028b5dd158406d64ee064700b267484d
[ "MIT" ]
4
2021-08-08T06:12:22.000Z
2021-08-21T17:33:12.000Z
mainwindow.h
fikret0/fluxchess
6fb97f30028b5dd158406d64ee064700b267484d
[ "MIT" ]
null
null
null
mainwindow.h
fikret0/fluxchess
6fb97f30028b5dd158406d64ee064700b267484d
[ "MIT" ]
null
null
null
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <string> using namespace std; #include "piece.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); void highlightBlock(string pos); void boardBlock_clicked(); void movePiece(string pos, string dest); bool canMove(string pos, string dest); Piece getPieceFromPos(string pos); void clearBoardColors(); vector<string> ignoreWhitePos(vector<string> positions); void exitGame(); void makeAIMove(); void changeMMDepth(); void delay(int millisecondsToWait); void toggleAnalyze(); ~MainWindow(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
21.131579
60
0.719801
adb46297691e5c70c03a75dcf015d3174456639c
4,507
h
C
libraries/pbes/include/mcrl2/pbes/join.h
tneele/mCRL2
8f2d730d650ffec15130d6419f69c50f81e5125c
[ "BSL-1.0" ]
null
null
null
libraries/pbes/include/mcrl2/pbes/join.h
tneele/mCRL2
8f2d730d650ffec15130d6419f69c50f81e5125c
[ "BSL-1.0" ]
null
null
null
libraries/pbes/include/mcrl2/pbes/join.h
tneele/mCRL2
8f2d730d650ffec15130d6419f69c50f81e5125c
[ "BSL-1.0" ]
null
null
null
// Author(s): Wieger Wesselink // Copyright: see the accompanying file COPYING or copy at // https://github.com/mCRL2org/mCRL2/blob/master/COPYING // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // /// \file mcrl2/pbes/join.h /// \brief add your file description here. #ifndef MCRL2_PBES_JOIN_H #define MCRL2_PBES_JOIN_H #include "mcrl2/pbes/pbes_expression.h" #include "mcrl2/utilities/detail/join.h" namespace mcrl2 { namespace pbes_system { /// \brief Returns or applied to the sequence of pbes expressions [first, last) /// \param first Start of a sequence of pbes expressions /// \param last End of a sequence of of pbes expressions /// \return Or applied to the sequence of pbes expressions [first, last) template <typename FwdIt> pbes_expression join_or(FwdIt first, FwdIt last) { return utilities::detail::join(first, last, [](const pbes_expression& x, const pbes_expression& y) { return or_(x, y); }, false_()); } /// \brief Returns and applied to the sequence of pbes expressions [first, last) /// \param first Start of a sequence of pbes expressions /// \param last End of a sequence of of pbes expressions /// \return And applied to the sequence of pbes expressions [first, last) template <typename FwdIt> pbes_expression join_and(FwdIt first, FwdIt last) { return utilities::detail::join(first, last, [](const pbes_expression& x, const pbes_expression& y) { return and_(x, y); }, true_()); } /// \brief Splits a disjunction into a sequence of operands /// Given a pbes expression of the form p1 || p2 || .... || pn, this will yield a /// set of the form { p1, p2, ..., pn }, assuming that pi does not have a || as main /// function symbol. /// \param expr A PBES expression /// \param split_data_expressions if true, both data and pbes disjunctions are /// split, otherwise only pbes disjunctions are split. /// \return A sequence of operands inline std::set<pbes_expression> split_or(const pbes_expression& expr, bool split_data_expressions = false) { using namespace accessors; std::set<pbes_expression> result; if (split_data_expressions) { utilities::detail::split(expr, std::insert_iterator<std::set<pbes_expression> >(result, result.begin()), is_universal_or, data_left, data_right); } else { utilities::detail::split(expr, std::insert_iterator<std::set<pbes_expression> >(result, result.begin()), is_pbes_or, left, right); } return result; } /// \brief Splits a conjunction into a sequence of operands /// Given a pbes expression of the form p1 && p2 && .... && pn, this will yield a /// set of the form { p1, p2, ..., pn }, assuming that pi does not have a && as main /// function symbol. /// \param expr A PBES expression /// \param split_data_expressions if true, both data and pbes conjunctions are /// split, otherwise only pbes conjunctions are split. /// \return A sequence of operands inline std::set<pbes_expression> split_and(const pbes_expression& expr, bool split_data_expressions = false) { using namespace accessors; std::set<pbes_expression> result; if (split_data_expressions) { utilities::detail::split(expr, std::insert_iterator<std::set<pbes_expression> >(result, result.begin()), is_universal_and, data_left, data_right); } else { utilities::detail::split(expr, std::insert_iterator<std::set<pbes_expression> >(result, result.begin()), is_pbes_and, left, right); } return result; } /// \brief Returns or applied to the sequence of pbes expressions [first, last) /// \param first Start of a sequence of pbes expressions /// \param last End of a sequence of pbes expressions /// \return Or applied to the sequence of pbes expressions [first, last) template <typename FwdIt> inline pbes_expression optimized_join_or(FwdIt first, FwdIt last) { return utilities::detail::join(first, last, data::optimized_or<pbes_expression>, false_()); } /// \brief Returns and applied to the sequence of pbes expressions [first, last) /// \param first Start of a sequence of pbes expressions /// \param last End of a sequence of pbes expressions /// \return And applied to the sequence of pbes expressions [first, last) template <typename FwdIt> inline pbes_expression optimized_join_and(FwdIt first, FwdIt last) { return utilities::detail::join(first, last, data::optimized_and<pbes_expression>, true_()); } } // namespace pbes_system } // namespace mcrl2 #endif // MCRL2_PBES_JOIN_H
37.87395
150
0.732194
ade95abe20773f58a5a6ed909de3e0e9cc9583f0
389
h
C
ZDToolKit/ZDTools/ZDInvocationWrapper.h
faimin/ZDUtility
d00c94805fdf0fe8ceaf8c12bfc7021f5d91f3a9
[ "MIT" ]
6
2020-06-24T01:16:58.000Z
2022-01-15T15:01:16.000Z
ZDToolKit/ZDTools/ZDInvocationWrapper.h
faimin/ZDUtility
d00c94805fdf0fe8ceaf8c12bfc7021f5d91f3a9
[ "MIT" ]
3
2020-07-20T03:15:44.000Z
2021-07-15T04:18:55.000Z
ZDToolKit/ZDTools/ZDInvocationWrapper.h
faimin/ZDUtility
d00c94805fdf0fe8ceaf8c12bfc7021f5d91f3a9
[ "MIT" ]
5
2017-11-21T10:12:30.000Z
2022-03-31T07:57:51.000Z
// // ZDInvocationWrapper.h // ZDToolKit // // Created by Zero.D.Saber on 2019/9/20. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface ZDInvocationWrapper<__covariant R : id> : NSObject + (R)zd_target:(id)target invokeSelectorWithArgs:(SEL)selector, ...; + (R)zd_target:(id)target invokeSelector:(SEL)selector args:(va_list)args; @end NS_ASSUME_NONNULL_END
18.52381
74
0.745501
2127be3efb4818326a55331e42677006c74841e9
1,629
c
C
ch1/sc10/exercises/ex1-22/solution.c
lair001/the-c-programming-language-solutions
f1cf2e1c2ce5e8ca9d06d52522554f0b7d10bbd2
[ "MIT" ]
1
2018-07-03T01:37:15.000Z
2018-07-03T01:37:15.000Z
ch1/sc10/exercises/ex1-22/solution.c
lair001/the-c-programming-language-solutions
f1cf2e1c2ce5e8ca9d06d52522554f0b7d10bbd2
[ "MIT" ]
null
null
null
ch1/sc10/exercises/ex1-22/solution.c
lair001/the-c-programming-language-solutions
f1cf2e1c2ce5e8ca9d06d52522554f0b7d10bbd2
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #define DEFAULT_TAB_SIZE 8 #define DEFAULT_MAX_LINE_LENGTH 72 /* not counting newline char */ int tabSize; int maxLineLength; int nextStoredWsIndex = 0; int currentLineLength = 0; int parseIntArg(char arg[], int defaultVal) { int i = 1, isInt = isdigit(arg[0]) ? 1 : 0; if (isInt) { while(isdigit(arg[i])) ++i; isInt = arg[i] == '\0' ? 1 : 0; } return isInt ? atoi(arg) : defaultVal; } void storeTab(char storedWs[]) { storedWs[nextStoredWsIndex] = '\t'; ++nextStoredWsIndex; currentLineLength = (currentLineLength / tabSize + 1) * tabSize; } void storeSpace(char storedWs[]) { storedWs[nextStoredWsIndex] = ' '; ++nextStoredWsIndex; ++currentLineLength; } void putStoredWs(char storedWs[]) { for (int i = 0; i < nextStoredWsIndex; ++i) putchar(storedWs[i]); nextStoredWsIndex = 0; } void putNewline(void) { putchar('\n'); currentLineLength = 0; nextStoredWsIndex = 0; } void putChar(int c, char storedWs[]) { if (c == '\t') storeTab(storedWs); else if (c == ' ') storeSpace(storedWs); else if (c == '\n') putNewline(); else { if (currentLineLength < maxLineLength) { putStoredWs(storedWs); putchar(c); ++currentLineLength; } else putNewline(); } } int main(int argc, char *argv[]) { int c; tabSize = argc < 2 ? DEFAULT_TAB_SIZE : parseIntArg(argv[1], DEFAULT_TAB_SIZE); maxLineLength = argc < 3 ? DEFAULT_MAX_LINE_LENGTH : parseIntArg(argv[2], DEFAULT_MAX_LINE_LENGTH); char storedWs[maxLineLength]; while((c = getchar()) != EOF) putChar(c, storedWs); putStoredWs(storedWs); return 0; }
20.111111
66
0.668508
5dc4ab85eb312ec210d2140be0656599a095ea1d
1,790
c
C
src/enclave_src/sgx/error_conversion.c
openeuler-mirror/secGear
8dfe9c7b3badebf2c2b509d174707be04ab6bcc6
[ "MulanPSL-1.0" ]
5
2021-01-05T01:13:01.000Z
2022-03-25T09:32:00.000Z
src/enclave_src/sgx/error_conversion.c
openeuler-mirror/secGear
8dfe9c7b3badebf2c2b509d174707be04ab6bcc6
[ "MulanPSL-1.0" ]
null
null
null
src/enclave_src/sgx/error_conversion.c
openeuler-mirror/secGear
8dfe9c7b3badebf2c2b509d174707be04ab6bcc6
[ "MulanPSL-1.0" ]
1
2022-03-25T09:55:45.000Z
2022-03-25T09:55:45.000Z
/* * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. * secGear is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR * PURPOSE. * See the Mulan PSL v2 for more details. */ #include "error_conversion.h" cc_enclave_result_t conversion_res_status(uint32_t enclave_res) { switch (enclave_res) { case SGX_SUCCESS: return CC_SUCCESS; case SGX_ERROR_INVALID_PARAMETER: return CC_ERROR_BAD_PARAMETERS; case SGX_ERROR_OUT_OF_MEMORY: return CC_ERROR_OUT_OF_MEMORY; case SGX_ERROR_FILE_BAD_STATUS: return CC_ERROR_BAD_STATE; case SGX_ERROR_FEATURE_NOT_SUPPORTED: return CC_ERROR_NOT_SUPPORTED; case SGX_ERROR_ENCLAVE_LOST: return CC_ERROR_ENCLAVE_LOST; case SGX_ERROR_BUSY: return CC_ERROR_BUSY; case SGX_ERROR_UNDEFINED_SYMBOL: return CC_ERROR_INVALID_ENCLAVE; case SGX_ERROR_INVALID_SIGNATURE: return CC_ERROR_SIGNATURE_INVALID; case SGX_ERROR_OCALL_NOT_ALLOWED: return CC_ERROR_OCALL_NOT_ALLOWED; case SGX_ERROR_INVALID_FUNCTION: return CC_ERROR_INVALID_CMD; case SGX_ERROR_OUT_OF_TCS: return CC_ERROR_OUT_OF_TCS; case SGX_ERROR_ENCLAVE_CRASHED: return CC_ERROR_ENCLAVE_DEAD; default: return CC_ERROR_UNEXPECTED; } }
37.291667
99
0.693855
426cb11ba5223fb2d8db0b5937a6b154c34a0c08
177
h
C
include/xor-detect-single.h
afrischk/cryptography
3692fa6da90eb877575a90356fbfa9b22b1b5b42
[ "MIT" ]
null
null
null
include/xor-detect-single.h
afrischk/cryptography
3692fa6da90eb877575a90356fbfa9b22b1b5b42
[ "MIT" ]
null
null
null
include/xor-detect-single.h
afrischk/cryptography
3692fa6da90eb877575a90356fbfa9b22b1b5b42
[ "MIT" ]
null
null
null
#ifndef XOR_DETECT_SINGLE_H #define XOR_DETECT_SINGLE_H #include "xor-crack.h" extern xor_crk_res_t *xor_detect_single(const char *file_path); #endif /*XOR_DETECT_SINGLE_H*/
19.666667
63
0.813559
5d53676abded0097eb39d3649b02deb5aa92747b
568
h
C
widgetitem.h
dayuanyuan1989/RemoteBinder
6c07896828187bbb890115fa1326f9db4fbd7b68
[ "MIT" ]
null
null
null
widgetitem.h
dayuanyuan1989/RemoteBinder
6c07896828187bbb890115fa1326f9db4fbd7b68
[ "MIT" ]
null
null
null
widgetitem.h
dayuanyuan1989/RemoteBinder
6c07896828187bbb890115fa1326f9db4fbd7b68
[ "MIT" ]
null
null
null
#ifndef WIDGETITEM_H #define WIDGETITEM_H #include <QWidget> #include <QImage> namespace Ui { class WidgetItem; } class ListWidget; class WidgetItem : public QWidget { Q_OBJECT public: explicit WidgetItem(QWidget *parent = 0); ~WidgetItem(); void SetIcon(const QImage&); void SetText(const QString&); void SetBackgroundColor(const QColor&); protected: virtual void resizeEvent(QResizeEvent *); private: private: Ui::WidgetItem *ui; friend class ListWidget; }; #endif // WIDGETITEM_H
14.947368
46
0.660211
71310d70de599f8c295e85331c6abf682aa4bbab
2,027
h
C
src/asm/WmeWrapper/WmeWrapper/WAdInventory.h
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
3
2021-03-28T00:11:48.000Z
2022-01-12T13:10:52.000Z
src/asm/WmeWrapper/WmeWrapper/WAdInventory.h
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
null
null
null
src/asm/WmeWrapper/WmeWrapper/WAdInventory.h
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
null
null
null
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt // http://dead-code.org/redir.php?target=wme #pragma once #include "WAdItem.h" namespace DeadCode { namespace WME { namespace Core { using namespace System; using namespace DeadCode::WME::Core; public ref class WAdInventory : public WObject { public: WAdInventory(){}; WAdInventory(WGame^ Game); WAdInventory(CAdInventory* Native); virtual ~WAdInventory(void); ////////////////////////////////////////////////////////////////////////// // Properties ////////////////////////////////////////////////////////////////////////// property WDynArray<CAdItem*, WAdItem>^ TakenItems { WDynArray<CAdItem*, WAdItem>^ get() { if(!Native) return nullptr; else return gcnew WDynArray<CAdItem*, WAdItem>(&Native->m_TakenItems); } } ////////////////////////////////////////////////////////////////////////// // Miscelaneous ////////////////////////////////////////////////////////////////////////// bool RemoveItem(String^ ItemName) { char* S = (char*)WUtils::GetString(ItemName); bool Ret = SUCCEEDED(Native->RemoveItem(S)); WUtils::FreeString(S); return Ret; } bool RemoveItem(WAdItem^ Item) { if(Item!=nullptr) return SUCCEEDED(Native->RemoveItem(Item->Native)); else return false; } bool WAdInventory::InsertItem(String^ ItemName, String^ InsertAfter) { char* SItemName = (char*)WUtils::GetString(ItemName); char* SInsertAfter = (char*)WUtils::GetString(InsertAfter); bool Ret = SUCCEEDED(Native->InsertItem(SItemName, SInsertAfter)); WUtils::FreeString(SItemName); WUtils::FreeString(SInsertAfter); return Ret; } bool InsertItem(String^ ItemName) { return InsertItem(ItemName, nullptr); } internal: property CAdInventory* Native { CAdInventory* get() { return (CAdInventory*)m_Native; }; } }; }}};
25.3375
79
0.564874
99c85e691ae688d03970ef2aef349e8ed3a7b1e7
4,908
h
C
cwp/include/tencentcloud/cwp/v20180228/model/ModifyWebPageProtectDirRequest.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
cwp/include/tencentcloud/cwp/v20180228/model/ModifyWebPageProtectDirRequest.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
cwp/include/tencentcloud/cwp/v20180228/model/ModifyWebPageProtectDirRequest.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_CWP_V20180228_MODEL_MODIFYWEBPAGEPROTECTDIRREQUEST_H_ #define TENCENTCLOUD_CWP_V20180228_MODEL_MODIFYWEBPAGEPROTECTDIRREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/cwp/v20180228/model/ProtectHostConfig.h> namespace TencentCloud { namespace Cwp { namespace V20180228 { namespace Model { /** * ModifyWebPageProtectDir请求参数结构体 */ class ModifyWebPageProtectDirRequest : public AbstractModel { public: ModifyWebPageProtectDirRequest(); ~ModifyWebPageProtectDirRequest() = default; std::string ToJsonString() const; /** * 获取网站防护目录地址 * @return ProtectDirAddr 网站防护目录地址 */ std::string GetProtectDirAddr() const; /** * 设置网站防护目录地址 * @param ProtectDirAddr 网站防护目录地址 */ void SetProtectDirAddr(const std::string& _protectDirAddr); /** * 判断参数 ProtectDirAddr 是否已赋值 * @return ProtectDirAddr 是否已赋值 */ bool ProtectDirAddrHasBeenSet() const; /** * 获取网站防护目录名称 * @return ProtectDirName 网站防护目录名称 */ std::string GetProtectDirName() const; /** * 设置网站防护目录名称 * @param ProtectDirName 网站防护目录名称 */ void SetProtectDirName(const std::string& _protectDirName); /** * 判断参数 ProtectDirName 是否已赋值 * @return ProtectDirName 是否已赋值 */ bool ProtectDirNameHasBeenSet() const; /** * 获取防护文件类型,分号分割 ; * @return ProtectFileType 防护文件类型,分号分割 ; */ std::string GetProtectFileType() const; /** * 设置防护文件类型,分号分割 ; * @param ProtectFileType 防护文件类型,分号分割 ; */ void SetProtectFileType(const std::string& _protectFileType); /** * 判断参数 ProtectFileType 是否已赋值 * @return ProtectFileType 是否已赋值 */ bool ProtectFileTypeHasBeenSet() const; /** * 获取防护机器列表信息 * @return HostConfig 防护机器列表信息 */ std::vector<ProtectHostConfig> GetHostConfig() const; /** * 设置防护机器列表信息 * @param HostConfig 防护机器列表信息 */ void SetHostConfig(const std::vector<ProtectHostConfig>& _hostConfig); /** * 判断参数 HostConfig 是否已赋值 * @return HostConfig 是否已赋值 */ bool HostConfigHasBeenSet() const; private: /** * 网站防护目录地址 */ std::string m_protectDirAddr; bool m_protectDirAddrHasBeenSet; /** * 网站防护目录名称 */ std::string m_protectDirName; bool m_protectDirNameHasBeenSet; /** * 防护文件类型,分号分割 ; */ std::string m_protectFileType; bool m_protectFileTypeHasBeenSet; /** * 防护机器列表信息 */ std::vector<ProtectHostConfig> m_hostConfig; bool m_hostConfigHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CWP_V20180228_MODEL_MODIFYWEBPAGEPROTECTDIRREQUEST_H_
32.503311
90
0.470049
3951f911c35942acdb0fcb9cc5310a1160ebbad5
1,120
c
C
public/freetds-1.00.23/src/odbc/unittests/timeout2.c
thepriyakadam/hrms
af7f44ac10691850487e2c412a666694680a0672
[ "Unlicense" ]
null
null
null
public/freetds-1.00.23/src/odbc/unittests/timeout2.c
thepriyakadam/hrms
af7f44ac10691850487e2c412a666694680a0672
[ "Unlicense" ]
null
null
null
public/freetds-1.00.23/src/odbc/unittests/timeout2.c
thepriyakadam/hrms
af7f44ac10691850487e2c412a666694680a0672
[ "Unlicense" ]
null
null
null
#include "common.h" #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <assert.h> #include "replacements.h" /* * Test timeout on prepare * It execute a query wait for timeout and then try to issue a new prepare/execute * This test a BUG where second prepare timeouts * * Test from Ou Liu, cf "Query Time Out", 2006-08-08 */ int main(int argc, char *argv[]) { int i; odbc_connect(); odbc_command("create table #timeout(i int)"); odbc_command("insert into #timeout values(1)"); for (i = 0; i < 2; ++i) { printf("Loop %d\n", i); CHKSetStmtAttr(SQL_ATTR_QUERY_TIMEOUT, (SQLPOINTER) 10, SQL_IS_UINTEGER, "S"); CHKPrepare(T("select * from #timeout"), SQL_NTS, "S"); CHKExecute("S"); do { while (CHKFetch("SNo") == SQL_SUCCESS) ; } while (CHKMoreResults("SNo") == SQL_SUCCESS); if (i == 0) { printf("Sleep 15 seconds to test if timeout occurs\n"); tds_sleep_s(15); } SQLFreeStmt(odbc_stmt, SQL_CLOSE); SQLFreeStmt(odbc_stmt, SQL_UNBIND); SQLFreeStmt(odbc_stmt, SQL_RESET_PARAMS); SQLCloseCursor(odbc_stmt); } odbc_disconnect(); ODBC_FREE(); return 0; }
18.983051
82
0.671429
fbcefb39e884f706e7a5c2d46dafb95ad81653ba
1,037
h
C
PrivateHeaders/CoreSimulator/SimPasteboardSyncPool.h
fr0l/FBSimulatorControl
db194033f6cf78626c40734eae47bdeeb4dd8f17
[ "BSD-3-Clause" ]
21
2018-05-20T15:41:35.000Z
2022-03-14T05:21:20.000Z
PrivateHeaders/CoreSimulator/SimPasteboardSyncPool.h
fr0l/FBSimulatorControl
db194033f6cf78626c40734eae47bdeeb4dd8f17
[ "BSD-3-Clause" ]
35
2018-05-22T08:47:45.000Z
2021-05-21T07:15:10.000Z
PrivateHeaders/CoreSimulator/SimPasteboardSyncPool.h
fr0l/FBSimulatorControl
db194033f6cf78626c40734eae47bdeeb4dd8f17
[ "BSD-3-Clause" ]
8
2018-05-23T22:43:31.000Z
2022-03-14T05:21:55.000Z
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import <objc/NSObject.h> #import <CoreSimulator/SimPasteboardSyncPoolProtocol-Protocol.h> @class NSMapTable, NSUUID; @protocol OS_dispatch_queue; @interface SimPasteboardSyncPool : NSObject <SimPasteboardSyncPoolProtocol> { NSMapTable *_pasteboards; NSObject<OS_dispatch_queue> *_processing_queue; NSUUID *_poolIdentifier; } @property (retain, nonatomic) NSUUID *poolIdentifier; @property (retain, nonatomic) NSObject<OS_dispatch_queue> *processing_queue; @property (retain, nonatomic) NSMapTable *pasteboards; - (void).cxx_destruct; - (void)unregisterAndRemoveAll; - (BOOL)removePasteboard:(id)arg1 withError:(id *)arg2; - (BOOL)addPasteboard:(id)arg1 withError:(id *)arg2; - (void)dealloc; - (id)init; @end
29.628571
78
0.763742
059b1afe7ee2975c45c0ea9953315dd359cf7828
3,783
c
C
FreeBSD/sys/dev/pms/RefTisa/tisa/sassata/common/tdhw.c
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
4
2016-08-22T22:02:55.000Z
2017-03-04T22:56:44.000Z
FreeBSD/sys/dev/pms/RefTisa/tisa/sassata/common/tdhw.c
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
21
2016-08-11T09:43:43.000Z
2017-01-29T12:52:56.000Z
FreeBSD/sys/dev/pms/RefTisa/tisa/sassata/common/tdhw.c
TigerBSD/TigerBSD
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
null
null
null
/******************************************************************************* ** *Copyright (c) 2014 PMC-Sierra, Inc. All rights reserved. * *Redistribution and use in source and binary forms, with or without modification, are permitted provided *that the following conditions are met: *1. Redistributions of source code must retain the above copyright notice, this list of conditions and the *following disclaimer. *2. Redistributions in binary form must reproduce the above copyright notice, *this list of conditions and the following disclaimer in the documentation and/or other materials provided *with the distribution. * *THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED *WARRANTIES,INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS *FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE *FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT *NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT *LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE ********************************************************************************/ /*******************************************************************************/ /** \file * * This file contains hardware related functions * */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <dev/pms/config.h> #include <dev/pms/freebsd/driver/common/osenv.h> #include <dev/pms/freebsd/driver/common/ostypes.h> #include <dev/pms/freebsd/driver/common/osdebug.h> #include <dev/pms/RefTisa/sallsdk/api/sa.h> #include <dev/pms/RefTisa/sallsdk/api/saapi.h> #include <dev/pms/RefTisa/sallsdk/api/saosapi.h> #include <dev/pms/RefTisa/tisa/api/titypes.h> #include <dev/pms/RefTisa/tisa/api/ostiapi.h> #include <dev/pms/RefTisa/tisa/api/tiapi.h> #include <dev/pms/RefTisa/tisa/api/tiglobal.h> #ifdef FDS_SM #include <dev/pms/RefTisa/sat/api/sm.h> #include <dev/pms/RefTisa/sat/api/smapi.h> #include <dev/pms/RefTisa/sat/api/tdsmapi.h> #endif #ifdef FDS_DM #include <dev/pms/RefTisa/discovery/api/dm.h> #include <dev/pms/RefTisa/discovery/api/dmapi.h> #include <dev/pms/RefTisa/discovery/api/tddmapi.h> #endif #include <dev/pms/RefTisa/tisa/sassata/sas/common/tdtypes.h> #include <dev/pms/freebsd/driver/common/osstring.h> #include <dev/pms/RefTisa/tisa/sassata/common/tdutil.h> #ifdef INITIATOR_DRIVER #include <dev/pms/RefTisa/tisa/sassata/sas/ini/itdtypes.h> #include <dev/pms/RefTisa/tisa/sassata/sas/ini/itddefs.h> #include <dev/pms/RefTisa/tisa/sassata/sas/ini/itdglobl.h> #endif #ifdef TARGET_DRIVER #include <dev/pms/RefTisa/tisa/sassata/sas/tgt/ttdglobl.h> #include <dev/pms/RefTisa/tisa/sassata/sas/tgt/ttdxchg.h> #include <dev/pms/RefTisa/tisa/sassata/sas/tgt/ttdtypes.h> #endif #include <dev/pms/RefTisa/tisa/sassata/common/tdsatypes.h> #include <dev/pms/RefTisa/tisa/sassata/common/tdproto.h> /***************************************************************************** *! \biref tdsaReadHardwareInfo * * Purpose: This function reads the hardware information. This includes, * PCI DeviceID, PCI VendorID, PCI Chip Revision, PCI Function * Number. * * \param tiRoot: Pointer to driver/port instance. * * \return: None * \note - just a place holder for now *****************************************************************************/ osGLOBAL void tdsaReadHardwareInfo( tiRoot_t *tiRoot ) { return; }
39.40625
106
0.673011
3983fb0c861d49db61b0b3de81775dc3d180899a
3,065
c
C
mqtt-cloud-agent.c
braunku/mqtt-cloud-agent
339e771097c5c821000f5f0a46fda06b767eeeaa
[ "MIT" ]
null
null
null
mqtt-cloud-agent.c
braunku/mqtt-cloud-agent
339e771097c5c821000f5f0a46fda06b767eeeaa
[ "MIT" ]
null
null
null
mqtt-cloud-agent.c
braunku/mqtt-cloud-agent
339e771097c5c821000f5f0a46fda06b767eeeaa
[ "MIT" ]
null
null
null
//-------------------------------------------------------------------------- // This program is free software : you can redistribute it and / or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. //-------------------------------------------------------------------------- // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the // GNU General Public License for more details. //-------------------------------------------------------------------------- // You should have received a copy of the GNU General Public License // along with this program.If not, see < https : //www.gnu.org/licenses/>. //-------------------------------------------------------------------------- /// \file mqtt-cloud-agent /// /// /// \version 0.0.0 (alpha) /// /// /// \brief simple cloud agent using an mqtt api /// /// /// \author Kurt Braun kurt.braun@gmail.com /// //-------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <mosquitto.h> #include "get_config.h" #include "mqtt.h" #include "logger.h" // main mosquitto object struct mosquitto *mosq; // = NULL; //struct prog_config this_config; int switch_state = 0; int mqtt_state = 0; int led_state = 0; int i = 0; int main(int argc, char *argv[]) { log_set_quiet(false); log_set_level(1); // get the config this_config = get_program_config(); usleep(1000); mosquitto_lib_init(); printf("\nCrabgrass Started.\n"); mosq = mosquitto_new(NULL, true, NULL); if (!mosq) { log_error("Can't initialize Mosquitto library\n"); exit(-1); } if (this_config.support_tls) { mosquitto_tls_set(mosq, this_config.rootca_path, NULL, this_config.cert_path, this_config.key_path, NULL); } int Connected = 0; // Establish a connection to the MQTT server. Do not use a keep-alive ping printf("Connecting...\n"); int mosqConnectResp = mosquitto_connect(mosq, this_config.mqtt_endpoint, this_config.mqtt_port, 0); if (mosqConnectResp) { log_error("Failed to connect to %s at port %d", this_config.mqtt_endpoint, this_config.mqtt_port); return -1; } else { if (!Connected) { printf("Connected to %s at port %d\n", this_config.mqtt_endpoint, this_config.mqtt_port); Connected = 1; } int mosqSubResp = mosquitto_subscribe(mosq, NULL, this_config.event_sub_topic, 0); //int mosqSubResp = mosquitto_subscribe(mosq, NULL, "#", 0); if (mosqSubResp) { log_error("Problem subscribing to %s", this_config.event_sub_topic); } else { printf("Subscribed to %s\n", this_config.event_sub_topic); // Specify the function to call when a new message is received mosquitto_message_callback_set(mosq, mqtt_callback); mqtt_state = 1; } } int initCycles = 0; sleep(2); while (1) { mosquitto_loop(mosq, -1, 1); } }
29.471154
108
0.61925
5ed94e8c0e251e6987d16ffd389ef31b769a1a83
937
h
C
core/time_controller.h
Arpan-2109/caroline
23aba9ac9a35697c02358aeb88ed121d3d97a99c
[ "MIT" ]
1
2017-07-27T15:08:19.000Z
2017-07-27T15:08:19.000Z
core/time_controller.h
Arpan-2109/caroline
23aba9ac9a35697c02358aeb88ed121d3d97a99c
[ "MIT" ]
null
null
null
core/time_controller.h
Arpan-2109/caroline
23aba9ac9a35697c02358aeb88ed121d3d97a99c
[ "MIT" ]
1
2020-10-01T08:46:10.000Z
2020-10-01T08:46:10.000Z
// Copyright (c) 2014 The Caroline authors. All rights reserved. // Use of this source file is governed by a MIT license that can be found in the // LICENSE file. /// @author Aleksandr Derbenev <alex@technoworks.ru> #ifndef CORE_TIME_CONTROLLER_H_ #define CORE_TIME_CONTROLLER_H_ #include <ctime> #include <cinttypes> #include <vector> namespace core { class ImageCaptureImpl; class TimeController { public: virtual ~TimeController(); // Running time in us. virtual uint64_t GetCurrentTime() const = 0; // Time from the UNIX epoch (01/01/1970 00:00:00 UTC) in seconds. virtual time_t GetGlobalTime() const; // Add Image Capture for tracking. virtual bool AddCapture(ImageCaptureImpl* capture) = 0; // Call Grab on all tracked captures. Increase current time if needed. virtual bool Grab(); protected: std::vector<ImageCaptureImpl*> captures_; }; } // namespace core #endif // CORE_TIME_CONTROLLER_H_
22.853659
80
0.738527
9f86492226260f1c4de66c8e4de72ccc4615eded
717
h
C
mp2/ls_router.h
zyhhhhhhh/networking
25679076a841e01696eb4675c9ff48912f352ada
[ "MIT" ]
null
null
null
mp2/ls_router.h
zyhhhhhhh/networking
25679076a841e01696eb4675c9ff48912f352ada
[ "MIT" ]
null
null
null
mp2/ls_router.h
zyhhhhhhh/networking
25679076a841e01696eb4675c9ff48912f352ada
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include <sys/socket.h> #include <arpa/inet.h> #include <pthread.h> #define SIZE_ADJARRAY 32640 #define LEN_6 6 #define LSP_MAX_LEN 2000 struct node { int dest; unsigned int cost; int prevdest; int next_hop; }; void initialize_adjarray(); unsigned int cost_to_target(int i, int j); void change_cost(int i, int j, unsigned int newCost); unsigned int set_LSP(char *buf, int target); void sendLSP(int source, char *LSP, unsigned int LSP_length); void parse_LSP(char *buf, uint16_t *node, uint16_t *neighbors, uint32_t *costs, int temp_p, uint32_t *num_seq, unsigned int buf_length); void dijkstra();
24.724138
136
0.716876
9f90f889b76a0cd81f9cd3143034e24d5005fcb1
550
h
C
YBL365/Class/Profile/Section3/GoodManage/DeliverManage/ChooseDelivery/View/YBLChooseGoodLogisticsCompanyCollectionView.h
740326093/-
160c85a4e5e4c1ecaae951782b98a2e831119108
[ "MIT" ]
313
2017-09-25T04:10:27.000Z
2022-01-31T22:18:51.000Z
YBL365/Class/Profile/Section3/GoodManage/DeliverManage/ChooseDelivery/View/YBLChooseGoodLogisticsCompanyCollectionView.h
740326093/-
160c85a4e5e4c1ecaae951782b98a2e831119108
[ "MIT" ]
17
2017-09-26T03:16:23.000Z
2020-12-07T16:01:49.000Z
YBL365/Class/Profile/Section3/GoodManage/DeliverManage/ChooseDelivery/View/YBLChooseGoodLogisticsCompanyCollectionView.h
740326093/-
160c85a4e5e4c1ecaae951782b98a2e831119108
[ "MIT" ]
158
2017-09-25T06:55:34.000Z
2021-04-12T07:16:57.000Z
// // YBLChooseGoodLogisticsCompanyCollectionView.h // YC168 // // Created by 乔同新 on 2017/4/15. // Copyright © 2017年 乔同新. All rights reserved. // #import <UIKit/UIKit.h> typedef void(^ChooseGoodLogisticsCompanyCollectionViewCellDidSelectBlock)(id model); @interface YBLChooseGoodLogisticsCompanyCollectionView : UICollectionView @property (nonatomic, strong) ChooseGoodLogisticsCompanyCollectionViewCellDidSelectBlock chooseGoodLogisticsCompanyCollectionViewCellDidSelectBlock; @property (nonatomic, strong) NSMutableArray *dataArray; @end
27.5
148
0.823636
19455e39562f5491ef2ea916454936c9c907963b
1,962
c
C
mtest.c
haifenghuang/pprint4c
7928762f1e8f0c440afa9533746502a8ef08c758
[ "MIT" ]
6
2019-12-07T14:31:20.000Z
2022-02-11T01:15:53.000Z
mtest.c
haifenghuang/pprint4c
7928762f1e8f0c440afa9533746502a8ef08c758
[ "MIT" ]
null
null
null
mtest.c
haifenghuang/pprint4c
7928762f1e8f0c440afa9533746502a8ef08c758
[ "MIT" ]
null
null
null
#include "pprint.h" struct person { int age; int height; struct like { char *type; char *name; } like; }; typedef enum enum_t { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3, } enum_t; typedef struct sub2_t { char *msg; } sub2_t; typedef struct sub_t { int sub_dat1; int sub_dat2; int sub_dat3; sub2_t *psub2a; sub2_t *psub2b; } sub_t; typedef struct data_t { int data_int; char c; char *str; void *addr; enum_t e; sub_t sub; char *text; sub_t *psub; } data_t; int main() { char out[10240]; char sub_out[10240]; struct person johndoe = { .age = 6, .like = { .type = "Software-Developing", .name = "C" } }; structInfo person_info[] = { { .data = &johndoe, .structName = "person", .level = 0 /* the first must be level 0 */ }, }; pprint_struct("johndoe", person_info, ARRAY_SIZE(person_info)); int hoge = 10; char *str = "abcd"; struct sub2_t sub2 = { .msg = "abcdefghijklmnopqrstuvwxyz" "abcdefghijklmnopqrstuvwxyz" "abcdefghijklmnopqrstuvwxyz", }; struct sub_t sub = { .sub_dat1 = 1, .sub_dat2 = 2, .sub_dat3 = 3, .psub2b = &sub2, }; struct data_t d = { .data_int = 1, .c = 'x', .str = str, .addr = &hoge, .e = A | C | D, .sub = { .sub_dat1 = 123, .sub_dat2 = -1, .sub_dat3 = 0xa, }, .text = "hogehoge", .psub = &sub, }; structInfo data_info[] = { { .data = &d, .structName = "data_t", .level = 0 /* the first must be level 0 */ }, { .data = &hoge, .func = pprint_int, .level = 1, }, { .data = &sub, .structName = "sub_t", .level = 1 }, { .data = &sub2, .structName = "sub2_t", .level = 2 }, }; pprint_struct("d", data_info, ARRAY_SIZE(data_info)); return 0; } /* vim: set ts=2 sw=2 expandtab: */
16.487395
65
0.512742
58b7dcf2a70246cc166b23223bf4e42578f668ba
2,650
c
C
Lab2_3/five_four_bit_adder/isim/five_four_bit_adder_top_isim_beh.exe.sim/work/m_12367177302823571314_2226691148.c
Riyuzakii/CS220
122e6876792316604788e0b79b2f7c641ff56b41
[ "MIT" ]
null
null
null
Lab2_3/five_four_bit_adder/isim/five_four_bit_adder_top_isim_beh.exe.sim/work/m_12367177302823571314_2226691148.c
Riyuzakii/CS220
122e6876792316604788e0b79b2f7c641ff56b41
[ "MIT" ]
null
null
null
Lab2_3/five_four_bit_adder/isim/five_four_bit_adder_top_isim_beh.exe.sim/work/m_12367177302823571314_2226691148.c
Riyuzakii/CS220
122e6876792316604788e0b79b2f7c641ff56b41
[ "MIT" ]
null
null
null
/**********************************************************************/ /* ____ ____ */ /* / /\/ / */ /* /___/ \ / */ /* \ \ \/ */ /* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */ /* / / All Right Reserved. */ /* /---/ /\ */ /* \ \ / \ */ /* \___\/\___\ */ /***********************************************************************/ /* This file is designed for use with ISim build 0xfbc00daa */ #define XSI_HIDE_SYMBOL_SPEC true #include "xsi.h" #include <memory.h> #ifdef __GNUC__ #include <stdlib.h> #else #include <malloc.h> #define alloca _alloca #endif static const char *ng0 = "/media/rharish/822A-B6CA/CS220Labs/Lab2_3/five_four_bit_adder/five_four_bit_adder_top.v"; static int ng1[] = {0, 0}; static void Initial_51_0(char *t0) { char *t1; char *t2; char *t3; LAB0: t1 = (t0 + 3320U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: xsi_set_current_line(51, ng0); LAB4: xsi_set_current_line(53, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 1608); xsi_vlogvar_assign_value(t3, t2, 0, 0, 4); xsi_set_current_line(54, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 1768); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(55, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 1928); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(56, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 2088); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(57, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 2248); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(58, ng0); t2 = ((char*)((ng1))); t3 = (t0 + 2408); xsi_vlogvar_assign_value(t3, t2, 0, 0, 1); xsi_set_current_line(61, ng0); t2 = (t0 + 3128); xsi_process_wait(t2, 100000LL); *((char **)t1) = &&LAB5; LAB1: return; LAB5: goto LAB1; } extern void work_m_12367177302823571314_2226691148_init() { static char *pe[] = {(void *)Initial_51_0}; xsi_register_didat("work_m_12367177302823571314_2226691148", "isim/five_four_bit_adder_top_isim_beh.exe.sim/work/m_12367177302823571314_2226691148.didat"); xsi_register_executes(pe); }
31.176471
156
0.466792
c9234598379a738b7aece9e4c5eaf89408fde4d5
3,283
h
C
code/library/Inventory/InventoryGui.h
jpike/noah_ark
491ab775f69457e20a930c0dd8049609dee9c677
[ "Unlicense" ]
null
null
null
code/library/Inventory/InventoryGui.h
jpike/noah_ark
491ab775f69457e20a930c0dd8049609dee9c677
[ "Unlicense" ]
61
2015-04-11T21:26:12.000Z
2021-10-02T13:34:43.000Z
code/library/Inventory/InventoryGui.h
jpike/noah_ark
491ab775f69457e20a930c0dd8049609dee9c677
[ "Unlicense" ]
null
null
null
#pragma once #include <memory> #include <string> #include <SFML/System.hpp> #include "Graphics/Color.h" #include "Graphics/Renderer.h" #include "Input/InputController.h" #include "Inventory/Inventory.h" #include "Inventory/InventoryAnimalsPage.h" #include "Inventory/InventoryBiblePage.h" #include "Inventory/InventoryFoodPage.h" #include "Math/Vector2.h" #include "States/SavedGameData.h" namespace INVENTORY { /// A GUI for displaying a player's inventory. /// The GUI is divided into 3 distinct tabs /// for different collections in the inventory: /// /// -------------------------- /// | Bible | Animals | Food | /// -------------------------- /// | Content for current | /// | tab is displayed here. | /// -------------------------- /// /// A user can press a certain key to bring up the main inventory screen, /// which fills the screen, except for the standard HUD stuff above /// (which will still be visible at the top of the screen). /// /// There are be 3 tabs in the main inventory screen that a user can /// switch between: Bible, Animals, and Food. /// /// The Bible tab shows text for verses in a pane on the left and /// a list of verse on the right. /// /// The Animals tab will show a grid of animal icon images, along with /// counts of how many of each animal type have been found. An animal /// can be selected to bring up more detailed information. /// /// The Food tab will show a grid of food icon images, along with /// counts of how many of each food type have been found. Hover-over-style /// tooltips will show slightly more information for each food icon. class InventoryGui { public: // INNER TYPES. /// The different types of tabs that may be displayed /// in the GUI. enum class TabType { /// The tab for displaying Bible verses. /// This is the first enum value since it is also /// the default tab that should appear when opening /// the GUI. BIBLE, /// The tab for displaying animals. ANIMALS, /// The tab for displaying food. FOOD }; // UPDATING. OBJECTS::Food::TypeId Update(const sf::Time& elapsed_time, const INPUT_CONTROL::InputController& input_controller); // RENDERING. void Render(const STATES::SavedGameData& saved_game_data, GRAPHICS::Renderer& renderer); private: // RENDERING. void RenderTab( const std::string& tab_text, const MATH::Vector2f& left_top_screen_position_in_pixels, const GRAPHICS::Color& background_color, GRAPHICS::Renderer& renderer) const; // MEMBER VARIABLES. /// The type of tab currently being displayed. TabType CurrentTab = TabType::BIBLE; /// The page of the inventory GUI displaying collected Bible verses. InventoryBiblePage BiblePage = {}; /// The page of the inventory GUI displaying collected animals. InventoryAnimalsPage AnimalsPage = {}; /// The page of the inventory GUI displaying collected food. InventoryFoodPage FoodPage = {}; }; }
36.88764
123
0.617423
c9faab19ac0920ca68e0c656098b0b382045517f
1,103
h
C
WeirdEngine/src/WeirdEngine/Header Files/Utilities/Vector4.h
jeramauni/Proyecto-3
2dbdba99ef2899e498dea3eb9a085417773686d7
[ "Apache-2.0" ]
null
null
null
WeirdEngine/src/WeirdEngine/Header Files/Utilities/Vector4.h
jeramauni/Proyecto-3
2dbdba99ef2899e498dea3eb9a085417773686d7
[ "Apache-2.0" ]
null
null
null
WeirdEngine/src/WeirdEngine/Header Files/Utilities/Vector4.h
jeramauni/Proyecto-3
2dbdba99ef2899e498dea3eb9a085417773686d7
[ "Apache-2.0" ]
null
null
null
#pragma once #ifndef VECTOR4_H #define VECTOR4_H #include <string> class Vector4 { public: float x; float y; float z; float w; public: Vector4(); Vector4(float x, float y, float z, float w); ~Vector4(); bool operator==(const Vector4& v) const; bool operator!=(const Vector4& v) const; Vector4& operator+=(const Vector4& v); Vector4& operator-=(const Vector4& v); Vector4& operator*=(const Vector4& v); Vector4& operator*=(float n); Vector4& operator/=(const Vector4& v); Vector4& operator/=(float n); Vector4& operator+=(float n); Vector4& operator-=(float n); Vector4& operator=(const Vector4& v); Vector4 operator+(const Vector4& v) const; Vector4 operator-(const Vector4& v) const; Vector4 operator*(const Vector4& v) const; Vector4 operator/(const Vector4& v) const; Vector4 operator*(float n) const; Vector4 operator/(float n) const; void normalize(); double magnitudeSquared() const; double magnitude() const; Vector4 normalized() const; double dot(const Vector4& v); Vector4& set(float x, float y, float w, float z); std::string toString() const; }; #endif
22.510204
50
0.706256
84a3ca04ec88f160de09179c5d23d0daa0f3a272
3,147
c
C
Linux/linux_socket/file_transfer/udp/client_udp.c
snailinshell/blog-sample-alipay-
5346ce2b0922cd2827d61636a3d10ef8823913c5
[ "Apache-2.0" ]
299
2019-01-16T02:34:35.000Z
2022-03-07T05:20:40.000Z
Linux/linux_socket/file_transfer/udp/client_udp.c
niuwenkui/blog-sample
f842ec1ac1318b331a067de08bb8328bbaeb6c7a
[ "Apache-2.0" ]
18
2019-10-08T07:20:52.000Z
2021-03-28T03:35:08.000Z
Linux/linux_socket/file_transfer/udp/client_udp.c
cwn132/blog-sample
5346ce2b0922cd2827d61636a3d10ef8823913c5
[ "Apache-2.0" ]
224
2019-01-13T02:51:52.000Z
2022-03-31T01:46:46.000Z
#include "head.h" pthread_spinlock_t lock; int rear, head, count; double use_time; struct msg *queue_buf[QUEUE_SIZE]; void thread(char *filename) { FILE *fp; char buf[BUFSIZ]; ssize_t n; time_t start_time, end_time; struct msg *m; if (!(fp = fopen(filename, "r"))) p_error("fopen"); time(&start_time); while (1) { if(rear == head) while(count >= QUEUE_SIZE); m = queue_buf[rear]; memset(&buf, 0, sizeof(buf)); n = fread(&buf, sizeof(char), sizeof(buf), fp); if (n == 0) { if (fp) { fclose(fp); fp = NULL; } time(&end_time); use_time = difftime(end_time, start_time); m->type = MSG_DONE; m->len = 0; m->data[0] = '\0'; rear = (rear + 1) % QUEUE_SIZE; pthread_spin_lock(&lock); count++; pthread_spin_unlock(&lock); break; } else { m->type = MSG_CONTENT; m->len = n; memcpy(m->data, &buf, m->len); rear = (rear + 1) % QUEUE_SIZE; pthread_spin_lock(&lock); count++; pthread_spin_unlock(&lock); } } pthread_exit(NULL); } int main(int argc, char *argv[]) { int cfd, i; struct sockaddr_in serv_addr; struct msg *send_msg; char buf[BUFSIZ], source_filename[BUFSIZ], target_filename[BUFSIZ]; pthread_t tid; if ((cfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) p_error("socket error"); send_msg = (struct msg*)malloc(MSG_SIZE); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(SERV_PORT); inet_pton(AF_INET, argv[1], &serv_addr.sin_addr.s_addr); printf("Client UDP service start..\n"); while (1) { // malloc struct msg for (i=0; i<QUEUE_SIZE; i++) queue_buf[i] = (struct msg*)malloc(MSG_SIZE); printf("please input source file name: "); scanf("%s", source_filename); printf("please input target file name: "); scanf("%s", target_filename); memset(send_msg, 0, sizeof(struct msg)); send_msg->type = MSG_FILENAME; send_msg->len = strlen(target_filename); memcpy(send_msg->data, &target_filename, send_msg->len); // send file name sendto(cfd, (void *)send_msg, sizeof(struct msg) + send_msg->len, 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); // create thread if ((i = pthread_create(&tid, NULL, (void *)thread, source_filename)) != 0) p_error("pthread_create"); // init spin lock if ((i = pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE)) != 0) p_error("pthread_spin_init"); // send file content while (1) { if (rear == head) while (count <= 0); struct msg *m = queue_buf[head]; sendto(cfd, (void*)m, sizeof(struct msg) + m->len, 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); if (m->type == MSG_DONE) { printf("[INFO] complete send file, consume %lfs.\n", use_time); break; } head = (head + 1) % QUEUE_SIZE; pthread_spin_lock(&lock); count--; pthread_spin_unlock(&lock); } //exit and continue loop: printf(">(input 'q' to quit, input 'c' to continue) "); scanf("%s", buf); if (strcmp("c", buf) == 0) continue; else if (strcmp("q", buf) == 0) { printf("[INFO] you will exit..\n"); close(cfd); break; } else goto loop; } return 0; }
22.640288
77
0.630124
d5ee906c11a5a60dd030edff385e21b241b57cab
2,232
h
C
OEBuildInfo.h
Flames-LLC/FlamesEMU
f92287f63ad2f974f52c6ce57c4b9af22a5a31aa
[ "MIT" ]
null
null
null
OEBuildInfo.h
Flames-LLC/FlamesEMU
f92287f63ad2f974f52c6ce57c4b9af22a5a31aa
[ "MIT" ]
null
null
null
OEBuildInfo.h
Flames-LLC/FlamesEMU
f92287f63ad2f974f52c6ce57c4b9af22a5a31aa
[ "MIT" ]
null
null
null
/* Copyright (c) 2016, OpenEmu Team Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the OpenEmu Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY OpenEmu Team ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL OpenEmu Team BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @import Foundation; NS_ASSUME_NONNULL_BEGIN /** A helper class for providing build-time information to Swift. * @note OEBuildVersion.h is generated by a build-time script. Importing that header in Swift's bridging header causes Swift files and Objective-C files that import OpenEmu-Swift.h to be recompiled because the file has changed. This class exists to expose build-time generated macros to Swift without triggering recompilation. */ @interface OEBuildInfo : NSObject /// The value of the BUILD_VERSION string generated at build-time. @property (class, readonly) NSString *buildVersion; /// The value of the LONG_BUILD_VERSION string generated at build-time. @property (class, readonly) NSString *longBuildVersion; @end NS_ASSUME_NONNULL_END
49.6
326
0.783602
70b148977a9e54322a010b6a557a83304f5e9784
203
h
C
Example/Pods/MWPhotoBrowser@guangmingzizai/Pod/Classes/MWInbilinNavigationBar.h
guangmingzizai/GMMultipleImagePicker
6e2257591b1e192140c3eb062685947c6d72aa95
[ "MIT" ]
null
null
null
Example/Pods/MWPhotoBrowser@guangmingzizai/Pod/Classes/MWInbilinNavigationBar.h
guangmingzizai/GMMultipleImagePicker
6e2257591b1e192140c3eb062685947c6d72aa95
[ "MIT" ]
null
null
null
Example/Pods/MWPhotoBrowser@guangmingzizai/Pod/Classes/MWInbilinNavigationBar.h
guangmingzizai/GMMultipleImagePicker
6e2257591b1e192140c3eb062685947c6d72aa95
[ "MIT" ]
3
2016-07-01T03:41:00.000Z
2018-08-20T09:33:22.000Z
// // MWInbilinNavigationBar.h // Pods // // Created by 柬斐 王 on 15/9/29. // // #import <UIKit/UIKit.h> @interface MWInbilinNavigationBar : UIView @property (nonatomic, copy) NSString *title; @end
12.6875
44
0.674877
7e113d43a50b8667a80a05e23c84698fdf959ce9
161
h
C
main/hog_key.h
ifritJP/bt-keyboard-remapper
19fb7c18570a222375f9e43f8cdc002ffc887f00
[ "MIT" ]
null
null
null
main/hog_key.h
ifritJP/bt-keyboard-remapper
19fb7c18570a222375f9e43f8cdc002ffc887f00
[ "MIT" ]
null
null
null
main/hog_key.h
ifritJP/bt-keyboard-remapper
19fb7c18570a222375f9e43f8cdc002ffc887f00
[ "MIT" ]
null
null
null
extern bool hog_isConnected( void ); extern void le_keyboard_setup(void); extern void hog_send_report( void ); extern void hog_send_passkey( uint32_t passkey );
32.2
49
0.807453
0101a7afd116d247bc8613c4fbf0983299e8147e
689
h
C
YJCategories/Foundation/NSDictionary/NSDictionary+YJXML.h
stackhou/YJCategories
4a0abb1f74ea7cfee594d2f6cda5aa4356eef96c
[ "MIT" ]
134
2017-12-17T11:09:49.000Z
2019-03-06T02:21:56.000Z
YJCategories/Foundation/NSDictionary/NSDictionary+YJXML.h
stackhou/YJCategories
4a0abb1f74ea7cfee594d2f6cda5aa4356eef96c
[ "MIT" ]
1
2017-07-04T13:43:06.000Z
2017-08-29T23:26:59.000Z
YJCategories/Foundation/NSDictionary/NSDictionary+YJXML.h
stackhou/YJCategories
4a0abb1f74ea7cfee594d2f6cda5aa4356eef96c
[ "MIT" ]
6
2017-12-18T06:42:10.000Z
2019-05-22T10:18:50.000Z
// // NSDictionary+YJXML.h // YJCategoriesGather // // Created by YJHou on 2017/3/2. // Copyright © 2017年 侯跃军 houmanager@Hotmail.com. All rights reserved. // #import <Foundation/Foundation.h> @interface NSDictionary (YJXML) /** 不带XML声明 不带根节点 */ - (NSString *)yj_xmlString; /** 默认 <?xml version=\"1.0\" encoding=\"utf-8\"?> 声明 自定义根节点 */ - (NSString*)yj_xmlStringDefaultDeclarationWithRootElement:(NSString *)rootElement; /** 将NSDictionary转换成XML字符串, 自定义根节点 自定义xml声明 */ - (NSString*)yj_xmlStringWithRootElement:(NSString *)rootElement declaration:(NSString *)declaration; /** 字典转 plistString*/ - (NSString *)yj_plistString; /** 转换为plistData类型 */ - (NSData *)yj_plistData; @end
23.758621
101
0.716981
4f4d246da054a138b3d647c782af56c149f5ea44
532
h
C
src/components/sip/headers/SipUnsupportedHeader.h
simonwillis/SIP-Processing
be0fb2e80a04d25a34bf393f038bcf54d3963ae7
[ "MIT" ]
null
null
null
src/components/sip/headers/SipUnsupportedHeader.h
simonwillis/SIP-Processing
be0fb2e80a04d25a34bf393f038bcf54d3963ae7
[ "MIT" ]
null
null
null
src/components/sip/headers/SipUnsupportedHeader.h
simonwillis/SIP-Processing
be0fb2e80a04d25a34bf393f038bcf54d3963ae7
[ "MIT" ]
1
2021-11-02T03:23:19.000Z
2021-11-02T03:23:19.000Z
// // Created by Simon Willis on 23/05/2016. // #ifndef CORE_SIPUNSUPPORTEDHEADER_H #define CORE_SIPUNSUPPORTEDHEADER_H #include "SipHeader.h" class SipUnsupportedHeader : public SipHeader { public: SipUnsupportedHeader(mapped_buffer_t headerValue) : SipHeader(headerValue) { } virtual const char *getFieldName() override { return "Unsupported"; } virtual SipHeaderType getType() override { return SipHeaderType::UNSUPPORTED; } }; #endif //CORE_SIPUNSUPPORTEDHEADER_H
16.625
53
0.704887
9eeff82d2777f31290d14a6a3597db98f17fd7cc
4,380
h
C
DataCollector/mozilla/xulrunner-sdk/include/AudioMixer.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
1
2016-04-20T08:35:44.000Z
2016-04-20T08:35:44.000Z
DataCollector/mozilla/xulrunner-sdk/include/AudioMixer.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
null
null
null
DataCollector/mozilla/xulrunner-sdk/include/AudioMixer.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef MOZILLA_AUDIOMIXER_H_ #define MOZILLA_AUDIOMIXER_H_ #include "AudioSampleFormat.h" #include "nsTArray.h" #include "mozilla/PodOperations.h" #include "mozilla/LinkedList.h" #include "AudioStream.h" namespace mozilla { struct MixerCallbackReceiver { virtual void MixerCallback(AudioDataValue* aMixedBuffer, AudioSampleFormat aFormat, uint32_t aChannels, uint32_t aFrames, uint32_t aSampleRate) = 0; }; /** * This class mixes multiple streams of audio together to output a single audio * stream. * * AudioMixer::Mix is to be called repeatedly with buffers that have the same * length, sample rate, sample format and channel count. * * When all the tracks have been mixed, calling FinishMixing will call back with * a buffer containing the mixed audio data. * * This class is not thread safe. */ class AudioMixer { public: AudioMixer() : mFrames(0), mChannels(0), mSampleRate(0) { } ~AudioMixer() { MixerCallback* cb; while ((cb = mCallbacks.popFirst())) { delete cb; } } void StartMixing() { mSampleRate = mChannels = mFrames = 0; } /* Get the data from the mixer. This is supposed to be called when all the * tracks have been mixed in. The caller should not hold onto the data. */ void FinishMixing() { MOZ_ASSERT(mChannels && mFrames && mSampleRate, "Mix not called for this cycle?"); for (MixerCallback* cb = mCallbacks.getFirst(); cb != nullptr; cb = cb->getNext()) { cb->mReceiver->MixerCallback(mMixedAudio.Elements(), AudioSampleTypeToFormat<AudioDataValue>::Format, mChannels, mFrames, mSampleRate); } PodZero(mMixedAudio.Elements(), mMixedAudio.Length()); mSampleRate = mChannels = mFrames = 0; } /* Add a buffer to the mix. aSamples is interleaved. */ void Mix(AudioDataValue* aSamples, uint32_t aChannels, uint32_t aFrames, uint32_t aSampleRate) { if (!mFrames && !mChannels) { mFrames = aFrames; mChannels = aChannels; mSampleRate = aSampleRate; EnsureCapacityAndSilence(); } MOZ_ASSERT(aFrames == mFrames); MOZ_ASSERT(aChannels == mChannels); MOZ_ASSERT(aSampleRate == mSampleRate); for (uint32_t i = 0; i < aFrames * aChannels; i++) { mMixedAudio[i] += aSamples[i]; } } void AddCallback(MixerCallbackReceiver* aReceiver) { mCallbacks.insertBack(new MixerCallback(aReceiver)); } bool FindCallback(MixerCallbackReceiver* aReceiver) { for (MixerCallback* cb = mCallbacks.getFirst(); cb != nullptr; cb = cb->getNext()) { if (cb->mReceiver == aReceiver) { return true; } } return false; } bool RemoveCallback(MixerCallbackReceiver* aReceiver) { for (MixerCallback* cb = mCallbacks.getFirst(); cb != nullptr; cb = cb->getNext()) { if (cb->mReceiver == aReceiver) { cb->remove(); delete cb; return true; } } return false; } private: void EnsureCapacityAndSilence() { if (mFrames * mChannels > mMixedAudio.Length()) { mMixedAudio.SetLength(mFrames* mChannels); } PodZero(mMixedAudio.Elements(), mMixedAudio.Length()); } class MixerCallback : public LinkedListElement<MixerCallback> { public: explicit MixerCallback(MixerCallbackReceiver* aReceiver) : mReceiver(aReceiver) { } MixerCallbackReceiver* mReceiver; }; /* Function that is called when the mixing is done. */ LinkedList<MixerCallback> mCallbacks; /* Number of frames for this mixing block. */ uint32_t mFrames; /* Number of channels for this mixing block. */ uint32_t mChannels; /* Sample rate the of the mixed data. */ uint32_t mSampleRate; /* Buffer containing the mixed audio data. */ nsTArray<AudioDataValue> mMixedAudio; }; } #endif // MOZILLA_AUDIOMIXER_H_
29.006623
86
0.633562